Example #1
0
    def build_flexi_jnts(self, follicles):
        """ 
        Args:
            None
        Returns (None)
        """
        follicle_prefix = '%s_flexiPlane_' % self.flexiPlaneNameField.getText()
        jntGRP_name = self.flexiPlaneNameField.getText() + '_flexiPlane_JNT_GRP'
        
        pm.group( em = True, name = jntGRP_name )
        
        for index,follicle in enumerate(follicles):
            jnt_name = self.format_string.format(PREFIX = self.flexiPlaneNameField.getText(),
                                                 INDEX = 'flexiPlane_jnt%03d' % (index+1),
                                                 SUFFIX = 'JNT')
            jnt_offset_name = jnt_name.replace('_JNT','Offset_GRP')
            tweek_ctrlCon_name = self.format_string.format(PREFIX = self.flexiPlaneNameField.getText(),
                                                 INDEX = 'flexiPlane_tweak%03d' % (index+1),
                                                 SUFFIX = 'CTRLCon_GRP')

            pm.joint( p = ( follicle.translateX.get(), 0, 0 ), n = jnt_name )
            pm.select(jnt_name, r=True)
            offSetGRP.add_offset_grps()
            
            pm.parent( jnt_offset_name, jntGRP_name )
            pm.select( clear = True )
            
            tweak_ctrl_con = pm.PyNode(tweek_ctrlCon_name)
            joint_offset = pm.PyNode(jnt_offset_name)
            
            pm.parentConstraint( tweek_ctrlCon_name, jnt_offset_name )
            
            pm.setAttr(jnt_name + '.rotateZ', -90)
            pm.makeIdentity( jnt_name, apply=True, translate=True, rotate=True )
Example #2
0
    def createFailedEdits(self):
        # Animate the zombieAttrs
        for transform in [x.getParent() for x in pm.ls(type='mesh')]:
            try:
                zombie = transform.attr('zombieAttr')
            except pm.MayaAttributeError:
                continue
            zombie.setKey(t=1, v=1)
            zombie.setKey(t=2, v=2)
            zombie.setKey(t=3, v=4)

        # want to create another successful edit, so we can tell just by number of edits
        # whether we got failed, successful, or both
        #   failed = 1
        #   successful = 2
        #   both = 3
        pm.setAttr(self.sphereRef1.namespace + ':pSphere1.rotate', (30,0,0))

        self.masterFile = pm.saveAs(os.path.join(self.temp, 'master.ma'), f=1)


        # deleting the attr should give some failed ref edits in the master...
        pm.openFile(self.sphereFile, f=1)
        pm.SCENE.pSphere1.zombieAttr.delete()
        pm.saveFile(f=1)

        pm.openFile(self.masterFile, f=1)
        self.sphereRef1 = pm.FileReference(namespace='sphere1')
        self.sphereRef2 = pm.FileReference(namespace='sphere2')
        self.cubeRef1 = pm.FileReference(namespace='cube1')
        self.coneRef1 = pm.FileReference(namespace='cone1')
Example #3
0
def stretchyBack( ikHandleTorso, jntList ):
    pymelLogger.debug('Starting: stretchyBack()...')     
    #Stretchy process
    # ArcLen to create curveInfo
    curveInfoNodeBack = pm.arclen( ikHandleTorso[2], ch=True )
    # add attr to curveinfo Node (normalizedScale)
    # this will have a value coming from a multiply divide node that will be 
    # dividing the current length by the initial length of the curve
    # this will be used later to scale the joints
    pm.addAttr(curveInfoNodeBack, longName='normalizedScale', attributeType='double')
    # get initial length of the curve
    iniLen = pm.getAttr( curveInfoNodeBack + '.arcLength' )
    
    # create a node multiplydivide, operation set to division
    MDCurveBack = pm.shadingNode( 'multiplyDivide', asUtility=True )
    pm.setAttr( MDCurveBack+'.operation', 2 ) # divide
    
    # Connect curve arcLength to input1X
    pm.connectAttr( curveInfoNodeBack + '.arcLength', MDCurveBack + '.input1X', force=True )
    # Set input2X to initial length of the curve
    pm.setAttr(MDCurveBack+'.input2X', iniLen)
    # connect outpux x from multiplydivide to normalized scale of the curve info
    pm.connectAttr(MDCurveBack + '.outputX', curveInfoNodeBack + '.normalizedScale', force=True)
    
    returnList = [curveInfoNodeBack,MDCurveBack]
    
    
    pymelLogger.debug('End: stretchyBack()...')   
    return returnList
Example #4
0
 def clean_outliner(self, *args):
     """ 
     Args:
         None
     Returns (None)
     """
     base_name = '%s_flexiPlane' % self.flexiPlaneNameField.getText()
     surface =  '%s_SURF' % base_name
     surfaceSkinJNT = '%s_surfSkin_JNT' % base_name
     fol_grp =  '%s_FOL_GRP' % base_name
     ctrl_grp =  '%s_CTRL_GRP' % base_name
     jnt_grp =  '%s_JNT_GRP' % base_name
     bShp_grp =  '%s_bShp_GRP' % base_name
     
     flexi_GRP = pm.group( em = True, name = base_name + '_GRP' )
     parts_GRP = pm.group( em = True, name = base_name + '_parts_GRP' )
     
     pm.parent( surface, parts_GRP )
     pm.parent( surfaceSkinJNT, parts_GRP )
     pm.parent( fol_grp, parts_GRP )
     pm.parent( ctrl_grp, flexi_GRP )
     pm.parent( jnt_grp, flexi_GRP )
     pm.parent( bShp_grp, parts_GRP )
     pm.parent( parts_GRP, flexi_GRP )
     
     pm.setAttr( surface + '.visibility', 0)
     pm.select( cl = True )
Example #5
0
 def getCurrentTranslator(self, nodeName):
     """
     get the current translator for this node, querying and setting the default if not yet set
     """
     try :
         # asString allows for enum attributes as well
         transName = pm.getAttr(nodeName + ".aiTranslator", asString=True)
     except :
         transName = None
     translators = self.getTranslators()
     if not transName or transName not in translators:
         # set default
         transName = getDefaultTranslator(nodeName)
         if transName is None:
             if not translators:
                 pm.warning("cannot find default translator for %s" % nodeName)
                 return
             transName = translators[0]
         try :
             pm.setAttr(nodeName + ".aiTranslator", transName)
         except:
             pm.warning("cannot set default translator for %s" % nodeName)
             import traceback
             traceback.print_exc()
     return transName
	def createIkAnimatedJoints(self):
		
		pm.select(cl = True)
		
		#Iterate jointPositionList and append to ikAnimatedJointsList joint at each position
		self.ikAnimatedJointsList = []
		
		for index in range(0, len(self.jointPositionList)):
			#create Joint
			
			#decide jointNames
			jointName = self.prefix + '_ik_animated_j_' + str(index + 1)
			if( index == 0 ): jointName = self.prefix + '_ik_animated_j_' + 'base'
			if( index + 1 == len(self.jointPositionList) ): jointName = self.prefix + '_ik_animated_j_' + 'tip'
			
			joint = pm.joint(a = True, p= self.jointPositionList[index] , co = True, n = jointName)
			#setJointPreferredAngle for correct ikHandle bending
			pm.setAttr(joint.preferredAngleX, -1.0)
			self.ikAnimatedJointsList.append(joint)
			
			
		pm.select(cl = True)
		
		
		#Create ikAnimatedJointsGrp and parent first ik animated joint
		self.ikAnimatedJointsGrp = pm.group(n = self.prefix + '_ik_animated_joints_grp')
		pm.select(cl = True)
		pm.parent(self.ikAnimatedJointsList[0] , self.ikAnimatedJointsGrp)
		pm.select(cl = True)
Example #7
0
def createIKSpline( jntList ):
    pymelLogger.debug('Starting: createIKSpline()...') 
    # Make IK Spline
    ikHandleTorso = pm.ikHandle( startJoint=jntList[0], endEffector=jntList[-1], solver = 'ikSplineSolver', numSpans = 4, name = jntList[-1]+'_'+Names.suffixes['ikhandle'])
    # we should probably rename the object created to know names ......    
    # CAREFULL // inherits Transform OFF, to avoid double transformation when grouped later on
    pm.setAttr(ikHandleTorso[2] + '.inheritsTransform', 0)
    
    # Duplicate last and first joint to use as Drivers of the spine Ik curve
    print jntList
    drvStart = pm.duplicate(jntList[0], parentOnly=True, name = Names.prefixes['driver']+'_'+ jntList[0] +'_'+Names.suffixes['start'])
    drvEnd = pm.duplicate(jntList[-1], parentOnly=True, name = Names.prefixes['driver']+'_'+ jntList[-1] +'_'+Names.suffixes['end'])
    pm.parent(drvEnd, w=1)
    
    # Make radius bigger
    pm.joint(drvStart, edit = True, radius = 1)
    pm.joint(drvEnd, edit = True, radius = 1)
    
    # Skin hip/shldr jnt's to back curve
    pm.skinCluster(drvStart,drvEnd,ikHandleTorso[2],dr=4)
    
    # return nedded elements
    rList = [ikHandleTorso, drvStart, drvEnd ]
    
    pymelLogger.debug('End: createIKSpline()...') 
    return rList
Example #8
0
    def rebuild_hierarchy(self):
        """ Rebuild the hierarchy by reading the hierarchy info file"""
        read_info = self.hierarchy_file_info

        # Rebuild the hierarchy
        for transform in read_info["hierarchy"]:
            # Split the names
            splitNames = transform.split("|")

            # Get the current transform name
            target = splitNames[-1]

            if not pm.objExists(target):
                # If does not exist create a empty group
                target = pm.createNode("transform", name=target)
            else:
                # Otherwise convert to pynode
                target = pm.PyNode(target)

            # Does it have parents?
            if len(splitNames) > 2:
                # Get the parent name
                parent = pm.PyNode("|".join(splitNames[:-1]))

                # Set the parent name
                target.setParent(parent)

            # Set the hierarchy
            pm.setAttr(target.scalePivot, read_info["pivots"][target.name()]["ScalePivot"])
            pm.setAttr(target.rotatePivot, read_info["pivots"][target.name()]["RotatePivot"])
Example #9
0
 def updateDynState(self, state):
     self.DynState = state
     if state != 1:
         pm.setAttr(self.nameEmitter + ".rate", 0)
     else:
         pm.setAttr(self.nameEmitter + ".rate", float(self.ui.simulationEmit_le.text()))
     self.updateDynExpressionCreation(self.partShape)
Example #10
0
def add(inputs, name, operation=1):
    '''
    creates a plusMinusAverage node with the given inputs
    returns the newly created node

    if inputs are attributes, a connection to the attribute is made
    if inputs are values, initial md values are set accordingly
    '''
    pma = pmc.createNode('plusMinusAverage', name=name)
    pma.operation.set(operation)

    val = 0.0
    connect=False

    for i in range(len(inputs)):
        if type(inputs[i]) == pmc.general.Attribute:
            val = inputs[i].get()
            connect=True
        else:
            val = inputs[i]
            connect=False

        if type(val) == pmc.datatypes.Vector:
            if connect:
                inputs[i].connect('%s.input3D[%s]' % (pma, i))
            else:
                pmc.setAttr('%s.input3D[%s]' % (pma, i), inputs[i])
        else:
            if connect:
                inputs[i].connect('%s.input1D[%s]' % (pma, i))
            else:
                pmc.setAttr('%s.input1D[%s]' % (pma, i), inputs[i])

    return pma
Example #11
0
    def buildIK(self, *args):
        """
            Build the IK
        """
        #Setup variables
        if self.normal == 1:
            self.normal = (1, 0, 0)
        if self.normal == 2:
            self.normal = (0, 1, 0)
        if self.normal == 3:
            self.normal = (0, 0, 1)   

        #Create IK control
        self.ikControl = pm.circle(nr=self.normal, r=self.radius, n='%s_ikCnt'%self.prefix)
        pm.select(self.ikControl[0], r=True)
        pm.mel.eval("DeleteHistory;")
        pm.delete( pm.parentConstraint(self.ikChain[2], self.ikControl[0], mo=0) )
        self.zero(self.ikControl[0])               

        #Create RP IK
        self.arm_ikHandle = pm.ikHandle(sj=self.ikChain[0], ee=self.ikChain[2], solver='ikRPsolver', name=(self.prefix + '_armIkHandle'))
        pm.setAttr(self.arm_ikHandle[0] + '.visibility', 0)

        #Parent IK Handle to the ikWrist_cnt
        pm.parent(self.arm_ikHandle[0], self.ikControl[0])

        # Creates: self.pv_cnt
        self.createPoleVector()
Example #12
0
 def reloadTextures(cls, *args, **kwargs):
   ''' reloads all texture files in a scene '''
   sel = pm.ls(typ='file')
   for tex in sel:
     path = pm.getAttr(tex+'.fileTextureName')
     if path != '':
       pm.setAttr(tex+'.fileTextureName',path)
Example #13
0
  def setTransformVisibility(cls, list, visibility, *args, **kwargs):
    ''' set visibility of any transforms in list'''
    for item in list:
      if item.nodeType() == 'transform':
        pm.setAttr(item+'.visibility', visibility)

    return list
Example #14
0
def bdSetLipAnimTarget(index,value):
    sceneBs = pm.ls(type='blendShape')
    print sceneBs
    for bs in sceneBs:
        aliases = sorted([alias[0] for alias in bs.listAliases()])
        if 'lip_anim_blend_0_' in aliases:
            pm.setAttr('%s.lip_anim_blend_%s_'%(bs,str(index)),value)
Example #15
0
def viewOutHide():
    
    transNodeList = []
    
    startTime = pm.playbackOptions(q=1, min=1)
    endTime = pm.playbackOptions(q=1, max=1)
    
    for x in range(int(startTime), int(endTime + 1)):
        pm.currentTime(x)
        transNodeList += viewObjectList(False)
    
    transNodeListS = set(transNodeList)

    allTransNodeList = set()
    
    for x in pm.ls(type='mesh'):
        allTransNodeList.add(x.getParent().name())

    hideList = allTransNodeList - transNodeListS
    
    for x in hideList:
        try:
            pm.setAttr(x + '.v', 0)
        except:
            pass

    pm.currentTime(startTime)
Example #16
0
def setAlpha(c):
    target = py.ls(sl=1)
    for i in range(0,len(target)):
        py.select(target[i])
        s = getShader()
        a = abs(1-(float(c) / 255.0))
        py.setAttr(s + ".transparency", (a,a,a))   
Example #17
0
def setRGBA(s,c):
    r = float(c[0]) / 255.0
    g = float(c[1]) / 255.0
    b = float(c[2]) / 255.0
    a = abs(1-(float(c[3]) / 255.0))
    py.setAttr(s + ".color", (r,g,b))
    py.setAttr(s + ".transparency", (a,a,a))
Example #18
0
def muggins_cache_set_version(m_deformer, version='vLatest'):
    """ Sets the cache version on a muggins cache deformer object
    Args:
        m_deformer (pm.nt.MugginsCacheDeformer): muggins cache to modify
        version (str): version number in format 'v#' or 'vLatest'
    Returns (None)
    """
    cache_path = m_deformer.cachePath.get()
    versions = get_version_number(cache_path)
    corrected_path = cache_path.replace(versions[0], version)
    
    if os.path.exists(os.path.dirname(corrected_path)) and corrected_path != cache_path:
        m_deformer.cachePath.set(corrected_path)
        pm.setAttr(m_deformer+".version", version)
        logger.info('MugginsCache %s set to version: %s in path %s'%(m_deformer.name(), version, corrected_path))
        return corrected_path
        
    elif corrected_path == cache_path:
        logger.info('MugginsCache %s already set to version: %s in path %s'%(m_deformer.name(), version, corrected_path))
        m_deformer.refreshCache.set(1)
        m_deformer.refreshCache.set(0)
        return True
    
    else:
        logger.info('MugginsCache %s does not have a version: %s in path %s'%(m_deformer.name(), version, corrected_path))
        return False
	def change_distance(self):
		intervValue = self.interv_int.value()
		value = self.distance_float.value()

		pm.setAttr(rigLight+'.translateZ', value)
		pm.xform(vis_mainGrp, s=[value, value, value])
		vis_mainGrp
Example #20
0
 def handleChanged(self, item, column):
     if item.checkState(column) == Qt.Checked:
         pm.setAttr('%s.enabled' % item.text(column), 1)
         sys.stdout.write('%s is Enabled\n' % item.text(column))
     if item.checkState(column) == Qt.Unchecked:
         pm.setAttr('%s.enabled' % item.text(column), 0)
         sys.stdout.write('%s is Disabled\n' % item.text(column))
Example #21
0
def rig_makeCtrlLabel(label):
	'''Creates a control that is displayed in customized choice of letters
	Args:
		label (string): the name of the desired control/visual display text
	Returns (pm.nt.Transform): returns the display control object
	Example Usage:
		rig_makeCtrlLabel("display")
	'''
	if not pm.objExists(label + "_CTRL"):
		txt_crv=pm.PyNode( pm.textCurves(ch=0,t=label,f="Courier")[0] )
		curves=[]
		i=1
		for crvShp in pm.ls(txt_crv.getChildren(ad=True), et="nurbsCurve"):
			crvTrm = crvShp.getParent()
			crvShp.getParent().setParent(w=True)
			pm.makeIdentity(crvShp.getParent(),apply=True,s=1,r=1,t=1,n=0)
			crvTrm.rename("display_%02d_CRV" % i)
			curves.append(crvTrm)
			i+=1
		displayCtrl=rig_combineCurves(curves,label+'_CTRL')
		pm.delete(txt_crv)
		displayCtrl.centerPivots()
		pm.move(displayCtrl, (0,0,0), rpr=True)
		pm.makeIdentity(displayCtrl,apply=True,s=1,r=1,t=1,n=0)
		displayGrp=pm.group(em=1,n=(label + "Offset_GRP"))
		displayCtrl.setParent(displayGrp)
		for displayCtrlShape in displayCtrl.listRelatives(shapes=True, fullPath=True):
			pm.setAttr(displayCtrlShape + ".overrideEnabled", 1)
			pm.setAttr(displayCtrlShape + ".overrideColor",17)
			
		rig_ctrlLock([displayCtrl], ["tx","ty","tz","rx","ry","rz","sx","sy","sz","v"], setKeyable=False, lock=True)
		return displayCtrl
	else:
		pm.error("That control already exists smarty pants!\n")
Example #22
0
 def createNoiseControl(self):
     # Create locator
     control = '%s%s'%(self.camera, self._CONTROL_SUFIX)
     pc.spaceLocator(n=control)
     # Create attribute for turning noise on/off
     pc.addAttr(ln='NOISE_SWITCH', k=False, at='enum', en='-:')
     pc.setAttr('%s.NOISE_SWITCH'%control, lock=True, cb=True)
     pc.addAttr(ln='Noise', k=False, at='enum', en='Off:On:')
     pc.setAttr('%s.Noise'%control, 1, cb=True)
     # Create translation noise attributes: frequency, amplitude (x, y, z), jitter and seed
     for noise_type in ['T', 'R']:
         nname = 'TRANSLATION' if noise_type == 'T' else 'ROTATION'
         pc.addAttr(ln='%s_NOISE'%nname, k=False, at='enum', en='-:')
         pc.setAttr('%s.%s_NOISE'%(control, nname), lock=True, cb=True)
         for axis in ['X', 'Y', 'Z']:
             pc.addAttr(ln='Frequency_%s%s'%(noise_type, axis), k=True, at='double', min=0)
             pc.addAttr(ln='Amplitude_%s%s'%(noise_type, axis), k=True, at='double', min=0)
         pc.addAttr(ln='Jitter_%s'%noise_type, k=True, at='double', min=0)
         pc.addAttr(ln='Seed_%s'%noise_type, k=False, at='short', dv=random.randint(0, 9999))
         pc.setAttr('%s.Seed_%s'%(control, noise_type), cb=True)
     # Create extra attributes for camera position offset
     pc.addAttr(ln='CAM_OFFSET', k=False, at='enum', en='-:')
     pc.setAttr('%s.CAM_OFFSET'%control, lock=True, cb=True)
     for axis in ['X', 'Y', 'Z']:
         pc.addAttr(ln='Offset_%s'%axis, k=True, at='double')
     return control
def sumAttr(sumCtrl=None,
            ctrlAttrA=None, ctrlAttrB=None,
            ctrlAttrResult=None,
            scaleA=None, scaleB=None):

    pmaNode = pm.shadingNode('plusMinusAverage',n='%s_Sum'%sumCtrl, asUtility=1)
    if scaleA:
        scaleA_node = pm.shadingNode('multiplyDivide',n='%s_ScaleA'%sumCtrl, asUtility=1)
        pm.setAttr('%s.input1X'%scaleA_node,scaleA)
        pm.connectAttr(ctrlAttrA,'%s.input2X'%scaleA_node,f=1)
        pm.connectAttr('%s.outputX'%scaleA_node,'%s.input1D[0]'%pmaNode,f=1)
    else:
        pm.connectAttr(ctrlAttrA,'%s.input1D[0]'%pmaNode,f=1)

    if scaleB:
        scaleB_node = pm.shadingNode('multiplyDivide',n='%s_ScaleB'%sumCtrl, asUtility=1)
        pm.setAttr('%s.input1X'%scaleB_node,scaleB)
        pm.connectAttr(ctrlAttrB,'%s.input2X'%scaleB_node,f=1)
        pm.connectAttr('%s.outputX'%scaleB_node,'%s.input1D[1]'%pmaNode,f=1)
    else:
        pm.connectAttr(ctrlAttrB,'%s.input1D[1]'%pmaNode,f=1)

    try:
        pm.addAttr(sumCtrl, ln=ctrlAttrResult.split('.')[1], k=1)
    except Exception, e:
        raise( e )
Example #24
0
def colorCtrl(containers):
	'''colors the control yellow. Ugly! rewrite!
	'''
	pm.select(containers["ctrl"], r=1)
	shape = pm.listRelatives(s)
	pm.setAttr((shape[0]+".overrideEnabled"),1)
	pm.setAttr((shape[0]+".overrideColor"),17)
def FTM_createRulerPlane( control, axisPlane, isMainDirX, transformParent, dummyRulerTransform ):
	obj = pm.polyPlane( axis=axisPlane, ch=True, w=1, h=1, sx=1, sy=1 )
	if isMainDirX == True:
		bDir = 'width'
		bSubDir = 'subdivisionsWidth'
		sDir = 'height'
		sSubDir = 'subdivisionsHeight'
	else:
		sDir = 'width'
		sSubDir = 'subdivisionsWidth'
		bDir = 'height'
		bSubDir = 'subdivisionsHeight'
	
	pm.connectAttr( control+'.controlSize2', obj[1]+'.'+bDir)
	pm.connectAttr( control+'.rulerDivisions2', obj[1]+'.'+bSubDir)
	pm.connectAttr( control+'.rulerSmallSize', obj[1]+'.'+sDir)

	shapeTransformDriver = dummyRulerTransform
	if shapeTransformDriver is None:
		shapeTransformDriver = obj[0]
	outShp = FTM_createTransformedGeometry(obj[0], 'outMesh', 'inMesh', shapeTransformDriver )

	#shps = pm.listRelatives(obj[0],s=True)
	pm.connectAttr( control+'.rulerDisplay', outShp+'.visibility')
	pm.setAttr(outShp+'.template', 1)

	if transformParent is None:
		pm.parent(obj[0], control)
		return obj[0]
	else:
		pm.parent(outShp,transformParent, add=True, s=True)
		pm.delete( obj[0] )
Example #26
0
 def reloadTextureList(cls, texList, *args, **kwargs):
   ''' reloads a list of texture nodes '''
   for item in texList:
     path = pm.getAttr(item+'.fileTextureName')
     if os.path.exists(path):
       pm.setAttr(item+'.fileTextureName',path)
   pm.refresh()
Example #27
0
def rigBook(containers):
	center = createJointChain(name='center')
	left = createJointChain(name='left')
	right = createJointChain(name='right')
	ctrl = containers["ctrl"]
	
	pm.addAttr(containers["ctrl"],
	ln="_",
	at="enum",
	en="______"
	)
	pm.setAttr(containers["ctrl"]+"._", e=1, keyable=1)
	
	for page in range(pages):
		pageName = 'page'+str(page)
		skin = createJointChain(pageName+"_")
		rigPage(skin, center, left, right, ctrl, pageName)
		paper = createPaper(pageName)
		pm.select(skin, r=1, hi=1)
		pm.select(paper, add=1, )
		pm.bindSkin(toAll = 1, colorJoints = 1)
		pm.select(cl=1)
		pm.parent(paper, containers["paper_grp"])
		pm.parent(skin[0], containers["pages_grp"])
		pm.select(cl=1)
		print "rigged: %s" % pageName
	
	pm.parent(center[0], containers["pageTargets_grp"])
	pm.parent(left[0], containers["pageTargets_grp"])
	pm.parent(right[0], containers["pageTargets_grp"])
def jointsOnCurve(crv=None, num=None, name=None):
    if not crv: return
    if not num: return
    if not name: return
    if num < 1: return

    param_increment = 1.0/float(num)
    param = 0
    curveShape = pm.PyNode(crv).getShape()
    prnt = []
    for i in range(num):
        pm.select(clear=1)
        # Create joint
        jnt = pm.joint(n=name+'_'+str(i).zfill(2))
        # Attach to curve
        poci = pm.createNode('pointOnCurveInfo')
        pm.connectAttr('%s.ws'%curveShape,'%s.inputCurve'%poci,f=1)
        pm.connectAttr('%s.position'%poci,'%s.translate'%jnt,f=1)
        pm.setAttr('%s.parameter'%poci,param)
        pm.setAttr('%s.turnOnPercentage'%poci,1)

        pm.disconnectAttr('%s.position'%poci,'%s.translate'%jnt)
        pm.delete(poci)

        if len(prnt):
            pm.parent(jnt,prnt[-1])

        prnt.append(jnt)
        param += param_increment
Example #29
0
 def repathTextures(cls, texList, newPath, *args, **kwargs):
   ''' repath the textures in a given list '''
   if texList:
     for tex in texList:
       oldPath = pm.getAttr(tex+'.fileTextureName')
       fixedPath = path.repath(oldPath , newPath)
       pm.setAttr(tex+'.fileTextureName', fixedPath)
Example #30
0
def makePolygonsWithAttr(listOfGeomAttDictTuples):
    """This function takes a list of tuples, each
    tuple containing first a point list, and second
    a dictionary of attributes where the keys are the
    names of the attributes and the values are the 
    corresponding values for each attribute, then the
    function creates a polygon from each point list and
    for that polygon, creates an attribute for each
    attribute in the attribute dictionary. The return value
    is a list of the names of all the created polygons."""
    # create an empty list to hold results
    curves = []
    for item in listOfGeomAttDictTuples:
        # each item consists of a point list, and
        # an attribute dictionary
        pointList, attDict = item[0], item[1]
        # this should return the name of the item
        curve = ptListToPolyline(pointList)
        for key in attDict:
            # ln and sn, are long name and short name respectively
            pm.addAttr(curve, ln=key, sn=key, dt="string")
            # attKey creates a handle that whould point direclty to
            # the attribute on that specific object
            attKey = '%s.%s' % (curve, key)
            # and here we set the attribute to the corresponding
            # value.
            pm.setAttr(attKey, attDict[key], typ="string")
        # finally add the name of the object to the list
        # of results.
        curves.append(curve)
    return curves
Example #31
0
    def blink(self):

        dupeLeft = pm.duplicate("l_low_up_CURV", n="l_blink_CURV")
        blendLeftEye = pm.blendShape("l_low_down_CURV",
                                     "l_low_up_CURV",
                                     dupeLeft,
                                     n="l_blinkHeight_BLD")

        dupeRight = pm.duplicate("r_low_up_CURV", n="r_blink_CURV")
        blendRightEye = pm.blendShape("r_low_down_CURV",
                                      "r_low_up_CURV",
                                      dupeRight,
                                      n="r_blinkHeight_BLD")

        lBlinkHeightAttr = pm.addAttr("l_eye_upMiddle_CTL",
                                      longName="blinkHeight",
                                      attributeType="float",
                                      min=0,
                                      max=1,
                                      defaultValue=0,
                                      keyable=True)
        rBlinkHeightAttr = pm.addAttr("r_eye_upMiddle_CTL",
                                      longName="blinkHeight",
                                      attributeType="float",
                                      min=0,
                                      max=1,
                                      defaultValue=0,
                                      keyable=True)

        pm.setAttr("l_blinkHeight_BLD.l_low_up_CURV", 1)
        pm.setAttr("r_blinkHeight_BLD.r_low_up_CURV", 1)

        pm.connectAttr("l_eye_upMiddle_CTL.blinkHeight",
                       "l_blinkHeight_BLD.l_low_up_CURV",
                       f=1)
        rev1 = pm.shadingNode("reverse",
                              asUtility=True,
                              n="l_blinkHeightBS_REV")
        pm.connectAttr("l_eye_upMiddle_CTL.blinkHeight", rev1 + ".inputX", f=1)
        pm.connectAttr(rev1 + ".outputX", "l_blinkHeight_BLD.l_low_down_CURV")

        pm.connectAttr("r_eye_upMiddle_CTL.blinkHeight",
                       "r_blinkHeight_BLD.r_low_up_CURV",
                       f=1)
        rev2 = pm.shadingNode("reverse",
                              asUtility=True,
                              n="r_blinkHeightBS_REV")
        pm.connectAttr("r_eye_upMiddle_CTL.blinkHeight", rev2 + ".inputX", f=1)
        pm.connectAttr(rev2 + ".outputX", "r_blinkHeight_BLD.r_low_down_CURV")

        dupeLeftup = pm.duplicate("l_up_CURV", n="l_up_blink_CURV")
        dupeLeftdown = pm.duplicate("l_down_CURV", n="l_down_blink_CURV")

        dupeRightup = pm.duplicate("r_up_CURV", n="r_up_blink_CURV")
        dupeRightdown = pm.duplicate("r_down_CURV", n="r_down_blink_CURV")

        pm.setAttr("l_eye_upMiddle_CTL.blinkHeight", 1)
        lupw = pm.wire("l_up_blink_CURV",
                       gw=False,
                       en=1.000000,
                       ce=0.000000,
                       li=0.000000,
                       wire="l_blink_CURV",
                       n="l_up_blink_WIR")
        pm.setAttr(lupw[0] + ".scale[0]", 0)
        pm.setAttr("l_eye_upMiddle_CTL.blinkHeight", 0)
        ldownw = pm.wire("l_down_blink_CURV",
                         gw=False,
                         en=1.000000,
                         ce=0.000000,
                         li=0.000000,
                         wire="l_blink_CURV",
                         n="l_down_blink_WIR")
        pm.setAttr(ldownw[0] + ".scale[0]", 0)
        blendLeftEyeUp = pm.blendShape("l_up_blink_CURV",
                                       "l_up_CURV",
                                       n="l_blink_up_BLD")
        blendLeftEyeDown = pm.blendShape("l_down_blink_CURV",
                                         "l_down_CURV",
                                         n="l_blink_down_BLD")

        pm.setAttr("r_eye_upMiddle_CTL.blinkHeight", 1)
        rupw = pm.wire("r_up_blink_CURV",
                       gw=False,
                       en=1.000000,
                       ce=0.000000,
                       li=0.000000,
                       wire="r_blink_CURV",
                       n="r_up_blink_WIR")
        pm.setAttr(rupw[0] + ".scale[0]", 0)
        pm.setAttr("r_eye_upMiddle_CTL.blinkHeight", 0)
        rdownw = pm.wire("r_down_blink_CURV",
                         gw=False,
                         en=1.000000,
                         ce=0.000000,
                         li=0.000000,
                         wire="r_blink_CURV",
                         n="r_down_blink_WIR")
        pm.setAttr(rdownw[0] + ".scale[0]", 0)
        blendRightEyeUp = pm.blendShape("r_up_blink_CURV",
                                        "r_up_CURV",
                                        n="r_blink_up_BLD")
        blendRightEyeDown = pm.blendShape("r_down_blink_CURV",
                                          "r_down_CURV",
                                          n="r_blink_down_BLD")

        lBlinkUpAttr = pm.addAttr("l_eye_upMiddle_CTL",
                                  longName="blink",
                                  attributeType="float",
                                  min=0,
                                  max=1,
                                  defaultValue=0,
                                  keyable=True)
        lBlinkDownAttr = pm.addAttr("l_eye_downMiddle_CTL",
                                    longName="blink",
                                    attributeType="float",
                                    min=0,
                                    max=1,
                                    defaultValue=0,
                                    keyable=True)
        rBlinkUpAttr = pm.addAttr("r_eye_upMiddle_CTL",
                                  longName="blink",
                                  attributeType="float",
                                  min=0,
                                  max=1,
                                  defaultValue=0,
                                  keyable=True)
        rBlinkDownAttr = pm.addAttr("r_eye_downMiddle_CTL",
                                    longName="blink",
                                    attributeType="float",
                                    min=0,
                                    max=1,
                                    defaultValue=0,
                                    keyable=True)

        pm.connectAttr("l_eye_upMiddle_CTL.blink",
                       "l_blink_up_BLD.l_up_blink_CURV",
                       f=1)
        pm.connectAttr("l_eye_downMiddle_CTL.blink",
                       "l_blink_down_BLD.l_down_blink_CURV",
                       f=1)
        pm.connectAttr("r_eye_upMiddle_CTL.blink",
                       "r_blink_up_BLD.r_up_blink_CURV",
                       f=1)
        pm.connectAttr("r_eye_downMiddle_CTL.blink",
                       "r_blink_down_BLD.r_down_blink_CURV",
                       f=1)

        pm.setAttr("l_eye_upMiddle_CTL.blinkHeight", 0.25)
        pm.setAttr("r_eye_upMiddle_CTL.blinkHeight", 0.25)
Example #32
0
def gear_ikfk2bone_op(out=[],
                      root=None,
                      eff=None,
                      upv=None,
                      fk0=None,
                      fk1=None,
                      fk2=None,
                      lengthA=5,
                      lengthB=3,
                      negate=False,
                      blend=0):
    """Apply a sn_ikfk2bone_op operator

    Arguments:
        out (list of dagNodes): The constrained outputs order must be respected
            (BoneA, BoneB,  Center, CenterN, Eff), set it to None if you don't
            want one of the output.
        root (dagNode): Object that will act as the root of the chain.
        eff (dagNode): Object that will act as the eff controler of the chain.
        upv (dagNode): Object that will act as the up vector of the chain.
        fk0 (dagNode): Object that will act as the first fk controler of the
            chain.
        fk1 (dagNode): Object that will act as the second fk controler of the
            chain.
        fk2 (dagNode): Object that will act as the fk effector controler of the
            chain.
        lengthA (float): Length of first bone.
        lengthB (float): Length of second bone.
        negate (bool):  Use with negative Scale.
        blend (float): Default blend value (0 for full ik, 1 for full fk).

    Returns:
        pyNode: The newly created operator.

    """
    node = pm.createNode("mgear_ikfk2Bone")

    # Inputs
    pm.setAttr(node + ".lengthA", lengthA)
    pm.setAttr(node + ".lengthB", lengthB)
    pm.setAttr(node + ".negate", negate)
    pm.setAttr(node + ".blend", blend)

    pm.connectAttr(root + ".worldMatrix", node + ".root")
    pm.connectAttr(eff + ".worldMatrix", node + ".ikref")
    pm.connectAttr(upv + ".worldMatrix", node + ".upv")
    pm.connectAttr(fk0 + ".worldMatrix", node + ".fk0")
    pm.connectAttr(fk1 + ".worldMatrix", node + ".fk1")
    pm.connectAttr(fk2 + ".worldMatrix", node + ".fk2")

    # Outputs
    if out[0] is not None:
        pm.connectAttr(out[0] + ".parentMatrix", node + ".inAparent")

        dm_node = pm.createNode("decomposeMatrix")
        pm.connectAttr(node + ".outA", dm_node + ".inputMatrix")
        pm.connectAttr(dm_node + ".outputTranslate", out[0] + ".translate")
        pm.connectAttr(dm_node + ".outputRotate", out[0] + ".rotate")
        pm.connectAttr(dm_node + ".outputScale", out[0] + ".scale")

    if out[1] is not None:
        pm.connectAttr(out[1] + ".parentMatrix", node + ".inBparent")

        dm_node = pm.createNode("decomposeMatrix")
        pm.connectAttr(node + ".outB", dm_node + ".inputMatrix")
        pm.connectAttr(dm_node + ".outputTranslate", out[1] + ".translate")
        pm.connectAttr(dm_node + ".outputRotate", out[1] + ".rotate")
        pm.connectAttr(dm_node + ".outputScale", out[1] + ".scale")

    if out[2] is not None:
        pm.connectAttr(out[2] + ".parentMatrix", node + ".inCenterparent")

        dm_node = pm.createNode("decomposeMatrix")
        pm.connectAttr(node + ".outCenter", dm_node + ".inputMatrix")
        pm.connectAttr(dm_node + ".outputTranslate", out[2] + ".translate")
        pm.connectAttr(dm_node + ".outputRotate", out[2] + ".rotate")
        # connectAttr(dm_node+".outputScale", out[2]+".scale") # the scaling
        # is not working with FK blended to 1.
        # The output is from the solver I need to review the c++ solver

    if out[3] is not None:
        pm.connectAttr(out[3] + ".parentMatrix", node + ".inEffparent")

        dm_node = pm.createNode("decomposeMatrix")
        pm.connectAttr(node + ".outEff", dm_node + ".inputMatrix")
        pm.connectAttr(dm_node + ".outputTranslate", out[3] + ".translate")
        pm.connectAttr(dm_node + ".outputRotate", out[3] + ".rotate")
        pm.connectAttr(dm_node + ".outputScale", out[3] + ".scale")

    return node
Example #33
0
def gear_curveslide2_op(outcrv,
                        incrv,
                        position=0,
                        maxstretch=1,
                        maxsquash=1,
                        softness=0):
    """Apply a sn_curveslide2_op operator

    Arguments:
        outcrv (NurbsCurve): Out Curve.
        incrv (NurbsCurve):  In Curve.
        position (float): Default position value (from 0 to 1).
        maxstretch (float): Default maxstretch value (from 1 to infinite).
        maxsquash (float): Default maxsquash value (from 0 to 1).
        softness (float): Default softness value (from 0 to 1).

    Returns:
        pyNode: The newly created operator.
    """
    pm.select(outcrv)
    node = pm.deformer(type="mgear_slideCurve2")[0]

    pm.connectAttr(incrv + ".local", node + ".master_crv")
    pm.connectAttr(incrv + ".worldMatrix", node + ".master_mat")

    pm.setAttr(node + ".master_length", pm.arclen(incrv))
    pm.setAttr(node + ".slave_length", pm.arclen(incrv))
    pm.setAttr(node + ".position", 0)
    pm.setAttr(node + ".maxstretch", 1)
    pm.setAttr(node + ".maxsquash", 1)
    pm.setAttr(node + ".softness", 0)

    return node
def shaderConnections(ddsFiles, obj, shader, path):
    for s in ddsFiles:
        if "_Albedo" in s and str(obj) in s:
            fileTexNode = pm.shadingNode('file', n='AlbedoFileTex', asTexture=True)
            pm.connectAttr(fileTexNode + '.outColor', shader + '.color')
            pm.setAttr('%s.fileTextureName' % fileTexNode, path[0] + "\\" + s, type='string')
        elif "_AmbientOcclusion" in s and str(obj) in s:
            fileTexNode = pm.shadingNode('file', n="AOFileTex", asTexture=True)
            pm.connectAttr(fileTexNode + ".outColor", shader + ".ambientColor")
            pm.setAttr("%s.fileTextureName" % fileTexNode, path[0] + "\\" + s, type="string")
        elif "_Emissive" in s and str(obj) in s:
            fileTexNode = pm.shadingNode("file", n="EmissiveFileTex", asTexture=True)
            pm.connectAttr(fileTexNode + ".outColor", shader + ".incandescence")
            pm.setAttr("%s.fileTextureName" % fileTexNode, path[0] + "\\" + s, type="string")
        elif "_Normals" in s and str(obj) in s:
            bumpNode = pm.shadingNode('bump2d', n='NormalsBumpNode', asUtility=True)
            fileTexNode = pm.shadingNode('file', n="NormalsFileTex", asTexture=True)
            pm.setAttr(bumpNode + ".bumpInterp", 1)
            pm.connectAttr(fileTexNode + ".outAlpha", bumpNode + ".bumpValue")
            pm.connectAttr(bumpNode + ".outNormal", shader + ".normalCamera")
            pm.setAttr('%s.fileTextureName' % fileTexNode, path[0] + "\\" + s, type='string')
        elif "_Metallic" in s and str(obj) in s:
            fileTexNode = pm.shadingNode("file", n='MetallicFileTex', asTexture=True)
            pm.connectAttr(fileTexNode + ".outColor", shader + ".reflectedColor")
            pm.setAttr("%s.fileTextureName" % fileTexNode, path[0] + "\\" + s, type="string")
        elif "_Roughness" in s and str(obj) in s:
            fileTexNode = pm.shadingNode("file", n="RoughnessFileTex", asTexture=True)
            pm.connectAttr(fileTexNode + ".outColor", shader + ".specularColor")
            pm.setAttr("%s.fileTextureName" % fileTexNode, path[0] + "\\" + s, type="string")
Example #35
0
	def importGrooming(self, palName, descName= None, version= None):
		"""
		"""
		self.clearPreview()

		if descName:
			descs = [descName]
		else:
			descs = xg.descriptions(palName)
		# copy groom dir from versionRepo if @version has given
		if version:
			# check exists
			groomDesc = {}
			hasMissing = False
			for desc in descs:
				if xg.getAttr('groom', palName, desc):
					groomSource = '/'.join([self.paletteVerDir(palName, version), desc, 'groom'])
					if os.path.exists(groomSource):
						groomDesc[desc] = groomSource
					else:
						hasMissing = True
						msg = '[XGen Hub] : palette [%s] description [%s] version [%s] NOT exists. -> %s'
						pm.warning(msg % (palName, desc, version, groomSource))
			# copy file if no missing
			if not hasMissing:
				for desc in groomDesc:
					src = groomDesc[desc]
					dst = '/'.join([self.paletteWipDir(palName), desc, 'groom'])
					if os.path.isdir(dst):
						try:
							dir_util.remove_tree(dst)
						except:
							pm.warning('[XGen Hub] : Dir may not remove. -> ' + dst)
					dir_util._path_created = {}
					dir_util.copy_tree(src, dst)
			else:
				pm.error('[XGen Hub] : Some data missing, Check ScriptEditor. grooming import stopped.')

				return None

		self.refresh()
		# IMPORT GROOMING
		# clear out autoExport path for preventing grooming auto export
		xg.setOptionVarString('igAutoExportFolder', '')
		for desc in descs:
			if xg.getAttr('groom', palName, desc):
				importPath = xg.expandFilepath('${DESC}/groom', desc)
				igDescr = xg.igDescription(desc)
				# import Attribute Map
				try:
					pm.waitCursor(state= True)
					pm.mel.iGroom(im= importPath, d= igDescr)
				finally:
					pm.waitCursor(state= False)
				# import Mask
				try:
					pm.waitCursor(state= True)
					pm.mel.iGroom(ik= importPath, d= igDescr)
				finally:
					pm.waitCursor(state= False)
				# import Region
				try:
					pm.waitCursor(state= True)
					pm.mel.iGroom(ir= importPath, d= igDescr)
				finally:
					pm.waitCursor(state= False)
		# restore default autoExport path
		xg.setOptionVarString('igAutoExportFolder', '${DESC}/groom')

		# IMPORT GROOM SETTINGS
		"""
		Currently only grab [density] setting,
		['length', 'width'] will messed up imported grooming's map attribute
		"""
		for desc in descs:
			igdesc = xg.getAttr('groom', palName, desc)
			jsonPath = xg.expandFilepath('${DESC}/groom', desc) + 'groomSettings.json'
			if igdesc and os.path.isfile(jsonPath):
				groomSettings = {}
				with open(jsonPath) as jsonFile:
					groomSettings = json.load(jsonFile)
				for key in groomSettings:
					# grab [density] setting only
					if key == 'density':
						pm.setAttr(igdesc + '.' + key, groomSettings[key])

		self.notifyMsg('Grooming Import Complete !', 0)

		return True
Example #36
0
	def importPalette(self, palName, version, binding= False, anim= False, asDelta= False, delta= []):
		"""
		** NOT SUPPORT NAMESPACE **
		XGen palette will imported without validator.
		[!!!] When importing [BAKED] palette, @binding set to False should be fine.
		"""
		xgenFileName = palName + '.xgen'
		xgenFile = str('/'.join([self.paletteVerDir(palName, version), xgenFileName]))
		if not os.path.isfile(xgenFile):
			self.notifyMsg('.xgen file is not exists.', 2)
			pm.error('[XGen Hub] : .xgen file is not exists. -> ' + xgenFile)
			return None
		if asDelta and not pm.sceneName():
			self.notifyMsg('Please save the scene.', 2)
			return None
		
		self.clearPreview()
		
		# check if palette exists in current scene
		if palName in xg.palettes():
			# delete current palette folder
			palDir = xg.expandFilepath(xg.getAttr('xgDataPath', palName), '')
			if os.path.isdir(palDir):
				try:
					dir_util.remove_tree(palDir)
				except:
					pm.warning('[XGen Hub] : Dir may not remove. -> ' + palDir)
			# delete current palette
			# this action might cry about 'None type object has no attr "previewer"'
			# when there is no xgen ui panel
			xg.deletePalette(palName)
		
		# IMPORT PALETTE
		palName = base.importPalette(xgenFile, delta, '')
		# update the palette with the current project
		xg.setAttr('xgProjectPath', str(pm.workspace(q= 1, rd= 1)), palName)
		dataPath = xg.paletteRootVar() + '/' + palName
		xg.setAttr('xgDataPath', dataPath, palName)
		# create imported palette folder
		paletteRoot = xg.expandFilepath(dataPath, '', True, True)
		# create all imported descriptions folder
		msxgApi.setupDescriptionFolder(paletteRoot, palName)
		# wrap into maya nodes
		palName = str(pm.mel.xgmWrapXGen(pal= palName, wp= binding, wlg= binding, gi= binding))
		# copy maps from source
		descNames = xg.descriptions(palName)
		msxgApi.setupImportedMap(xgenFile, palName, descNames, self.projPath)
		# bind grooming descriptions to geometry
		if binding:
			for desc in descNames:
				igdesc = xg.getAttr('groom', palName, desc)
				if igdesc:
					# get groom dag node
					igdesc = xg.igActivateDescription(desc)
					# bind groom to geo
					pm.mel.igBindFromXGen(desc)
					# set groom density and sampling method
					pm.setAttr(igdesc + '.density', 1)
					pm.setAttr(igdesc + '.interpStyle', 1)
					# set all groom visible on
					xg.igSetDescriptionVisibility(True)
					# sync primitives tab attritube map path with auto export path
					xg.igSyncMaps(desc)

			# import grooming as well
			self.importGrooming(palName)

		# import as anim, build hairSystem
		if anim:
			# build hairSystem
			self.linkHairSystem(palName)
			# check preset dir exists
			presetLocalDir = str(pm.internalVar(userPresetsDir= 1))
			presetRepo = self.nDynPresetPath(palName, version)
			if os.path.exists(presetRepo):
				# copy preset
				for prs in os.listdir(presetRepo):
					dstPath = presetLocalDir + prs
					prs = '/'.join([presetRepo, prs])
					shutil.copyfile(prs, dstPath)
				# load preset
				# [note] nucleus preset will not be loaded during current devlope
				presetMel = []
				for nodeType in ['hairSystem', 'nRigid']:
					presetDict = self.ioAttrPreset(nodeType, False)
					presetMel.extend(presetDict.values())
				# dump preset
				for prs in presetMel:
					if os.path.isfile(prs):
						os.remove(prs)
			else:
				pm.warning('[XGen Hub] : nDynamic attribute presets folder not found.')

		if asDelta:
			dataPath = xg.getAttr('xgDataPath', palName)
			dataPath = dataPath + ';' + self.paletteVerDir(palName, version, raw= True)
			xg.setAttr('xgDataPath', dataPath, palName)
			# save scenes
			pm.saveFile(f= 1)
			# set export delta
			pm.setAttr(palName + '.xgExportAsDelta', 1)

		pm.warning('[XGen Hub] : Collection Import Complete !')
		self.notifyMsg('Collection Import Complete !', 0)

		return palName
    def jointsSetup(self):
        self.all_locs = []
        self.all_joint = []
        for each in self.all_guide:
            _joint = pm.joint(n=each.name().replace('guide', 'jnt__'))
            _loc = pm.spaceLocator(n=each.name().replace('guide', 'loc__'))
            pm.PyNode(_loc).getShape().localScaleX.set(0.2)
            pm.PyNode(_loc).getShape().localScaleY.set(0.2)
            pm.PyNode(_loc).getShape().localScaleZ.set(0.2)
            adb.changeColor_func(_loc, 'index', 14)
            pm.parent(_joint, w=True)
            self.all_joint.append(_joint)
            self.all_locs.append(_loc)

        for joint, guide in zip(self.all_joint, self.all_guide):
            pm.matchTransform(joint, guide, pos=True)
            pm.parent(joint, guide)

        for loc, guide in zip(self.all_locs, self.all_guide):
            pm.matchTransform(loc, guide, pos=True)
            pm.parentConstraint(guide, loc)
        pm.select(None)

        ## SCALING
        scaling_grp = pm.group(em=True, n='scaling__grp__')
        pm.parent('l__arm_clav__guide__root__grp__',
                  'l__arm_elbow__guide__root__grp__',
                  'l__arm_hand__guide__root__grp__',
                  'l__leg_main__guide__root__grp__',
                  'r__arm_clav__guide__root__grp__',
                  'r__arm_elbow__guide__root__grp__',
                  'r__arm_hand__guide__root__grp__',
                  'r__leg_main__guide__root__grp__', 'spine_guide__curve',
                  scaling_grp)
        pm.PyNode(scaling_grp).setScale((0.05, 0.05, 0.05))
        pm.parent(w=True)
        pm.delete(scaling_grp)
        ## -----------------------------------------------

        ## SPINE SUITE
        pm.select(self.spine_curve, r=True)
        sel = pm.select(".cv[*]")
        cvs = pm.filterExpand(fullPath=True, sm=28)
        # Nombre de vertex sur la curve #
        nbCvs = len(cvs)
        oCollClusters = [pm.cluster(cvs[x]) for x in range(0, nbCvs)]

        self.all_spine_guide = []
        for clus in oCollClusters:
            clus[1].v.set(0)
            spine_guide = pm.sphere(n='m__spine__guide_01', r=0.05)[0]
            self.all_spine_guide.append(spine_guide)
            pm.matchTransform(spine_guide, clus, pos=True)

        for oClus, spine in zip(oCollClusters, self.all_spine_guide):
            pm.parentConstraint(spine, oClus)

        for spine_guide in self.all_spine_guide:
            pm.select(spine_guide)
            mc.FreezeTransformations()

        pm.PyNode(self.all_spine_guide[1]).v.set(0)
        pm.PyNode(self.all_spine_guide[-2]).v.set(0)

        cluster_grp = pm.group(oCollClusters, n='spine_cls__grp__', w=1)
        all_spine_guide_grp = pm.group(self.all_spine_guide,
                                       n='spine_guide__grp__',
                                       w=1)

        self.all_guide.extend(self.all_spine_guide)

        ## Hide loc
        self.locs_grp = pm.group(n='x__locs_pos__grp__')
        pm.parent(self.all_locs, self.locs_grp)
        pm.PyNode(self.locs_grp).v.set(0)

        ## associate shader
        spine_shader = pm.shadingNode('lambert',
                                      asShader=True,
                                      n='yellow_guide_shader')
        pm.setAttr(spine_shader + ".incandescence",
                   0,
                   0.42,
                   0.06,
                   type='double3')

        pm.select(pm.ls(type='nurbsSurface'))

        for spine_guide in pm.selected():
            pm.select(spine_guide)
            pm.hyperShade(assign=spine_shader)

        @changeColor('index', col=(14))
        def create_curve():

            _curve_arm_1 = pm.curve(p=[(2.2, 5, -0.05), (1.45, 5, -0.05)],
                                    k=[0, 1],
                                    d=1)
            _curve_arm_2 = pm.curve(p=[(1.45, 5, -0.05), (0.5, 5, 0)],
                                    k=[0, 1],
                                    d=1)

            _curve_arm_4 = pm.curve(p=[(-2.2, 5, -0.05), (-1.45, 5, -0.05)],
                                    k=[0, 1],
                                    d=1)
            _curve_arm_5 = pm.curve(p=[(-1.45, 5, -0.05), (-0.5, 5, 0)],
                                    k=[0, 1],
                                    d=1)

            r_leg_thigh_curve = pm.curve(p=[(-0.4, 3.2, 0.05),
                                            (-0.4, 1.75, 0.185)],
                                         k=[0, 1],
                                         d=1)
            l_leg_thigh_curve = pm.curve(p=[(0.4, 3.2, 0.05),
                                            (0.4, 1.75, 0.185)],
                                         k=[0, 1],
                                         d=1)

            r_leg_knee_curve = pm.curve(p=[(-0.4, 1.75, 0.185),
                                           (-0.4, 0.35, 0)],
                                        k=[0, 1],
                                        d=1)
            l_leg_knee_curve = pm.curve(p=[(0.4, 1.75, 0.185), (0.4, 0.35, 0)],
                                        k=[0, 1],
                                        d=1)

            all_curves = [
                _curve_arm_1, _curve_arm_2, _curve_arm_4, _curve_arm_5,
                r_leg_thigh_curve, l_leg_thigh_curve, r_leg_knee_curve,
                l_leg_knee_curve
            ]

            self.curves_grp = pm.group(em=True, n='x__curves__grp__', w=True)

            pm.select(self.all_joint, r=True)
            pm.select(all_curves, add=True)

            mc.SmoothBindSkin()

            pm.parent(_curve_arm_1, _curve_arm_2, _curve_arm_4, _curve_arm_5,
                      r_leg_thigh_curve, l_leg_thigh_curve, r_leg_knee_curve,
                      l_leg_knee_curve, self.spine_curve, cluster_grp,
                      self.curves_grp)

            return self.curves_grp

        create_curve()

        guide_scale_grp = pm.group(em=True, n='x__guide__grp__')
        pm.parent('l__arm_clav__guide__root__grp__',
                  'l__arm_elbow__guide__root__grp__',
                  'l__arm_hand__guide__root__grp__',
                  'l__leg_main__guide__root__grp__',
                  'r__arm_clav__guide__root__grp__',
                  'r__arm_elbow__guide__root__grp__',
                  'r__arm_hand__guide__root__grp__',
                  'r__leg_main__guide__root__grp__', 'spine_guide__grp__',
                  guide_scale_grp)

        return guide_scale_grp
Example #38
0
    def eyeRimLocators(self):

        locUpl = pm.spaceLocator(n="l_eyeUpVec_LOC")
        locUpr = pm.spaceLocator(n="r_eyeUpVec_LOC")
        lcenter = pm.xform("eyeCentre_0", q=1, ws=1, t=1)
        pm.xform(locUpl, ws=1, t=lcenter)
        pm.move(locUpl, [0, 3, 0], r=1, os=1, wd=1)
        rcenter = pm.xform("eyeCentre_1", q=1, ws=1, t=1)
        pm.xform(locUpr, ws=1, t=rcenter)
        pm.move(locUpr, [0, 3, 0], r=1, os=1, wd=1)

        locGRP1 = []
        sel = pm.listRelatives("l_uplid_GRP", children=True, type="transform")
        for s in sel:
            x = pm.pickWalk(s, direction="down")
            loc = pm.spaceLocator()
            pm.rename(loc, loc + "_LOC")
            locGRP1.append(loc)
            pm.setAttr(loc + ".scale", .1, .1, .1)
            pos = pm.xform(x, q=1, ws=1, t=1)
            pm.xform(loc, ws=1, t=pos)
            par = pm.listRelatives(x, p=1)[0]
            pm.aimConstraint(loc,
                             par,
                             mo=1,
                             weight=1,
                             aimVector=(1, 0, 0),
                             upVector=(0, 1, 0),
                             worldUpType='object',
                             worldUpObject="l_eyeUpVec_LOC")
        pm.group(locGRP1, n="l_uplid_LOC_GRP")

        locGRP2 = []
        sel = pm.listRelatives("l_downlid_GRP",
                               children=True,
                               type="transform")
        for s in sel:
            x = pm.pickWalk(s, direction="down")
            loc = pm.spaceLocator()
            pm.rename(loc, loc + "_LOC")
            locGRP2.append(loc)
            pm.setAttr(loc + ".scale", .1, .1, .1)
            pos = pm.xform(x, q=1, ws=1, t=1)
            pm.xform(loc, ws=1, t=pos)
            par = pm.listRelatives(x, p=1)[0]
            pm.aimConstraint(loc,
                             par,
                             mo=1,
                             weight=1,
                             aimVector=(1, 0, 0),
                             upVector=(0, 1, 0),
                             worldUpType='object',
                             worldUpObject="l_eyeUpVec_LOC")
        pm.group(locGRP2, n="l_downlid_LOC_GRP")

        locGRP3 = []
        sel = pm.listRelatives("r_uplid_GRP", children=True, type="transform")
        for s in sel:
            x = pm.pickWalk(s, direction="down")
            loc = pm.spaceLocator()
            pm.rename(loc, loc + "_LOC")
            locGRP3.append(loc)
            pm.setAttr(loc + ".scale", .1, .1, .1)
            pos = pm.xform(x, q=1, ws=1, t=1)
            pm.xform(loc, ws=1, t=pos)
            par = pm.listRelatives(x, p=1)[0]
            pm.aimConstraint(loc,
                             par,
                             mo=1,
                             weight=1,
                             aimVector=(1, 0, 0),
                             upVector=(0, 1, 0),
                             worldUpType='object',
                             worldUpObject="r_eyeUpVec_LOC")
        pm.group(locGRP3, n="r_uplid_LOC_GRP")

        locGRP4 = []
        sel = pm.listRelatives("r_downlid_GRP",
                               children=True,
                               type="transform")
        for s in sel:
            x = pm.pickWalk(s, direction="down")
            loc = pm.spaceLocator()
            pm.rename(loc, loc + "_LOC")
            locGRP4.append(loc)
            pm.setAttr(loc + ".scale", .1, .1, .1)
            pos = pm.xform(x, q=1, ws=1, t=1)
            pm.xform(loc, ws=1, t=pos)
            par = pm.listRelatives(x, p=1)[0]
            pm.aimConstraint(loc,
                             par,
                             mo=1,
                             weight=1,
                             aimVector=(1, 0, 0),
                             upVector=(0, 1, 0),
                             worldUpType='object',
                             worldUpObject="r_eyeUpVec_LOC")
        pm.group(locGRP4, n="r_downlid_LOC_GRP")
Example #39
0
    def addObjects(self):
        """Add all the objects needed to create the component."""

        self.up_axis = pm.upAxis(q=True, axis=True)

        # Auto bend with position controls  -------------------
        if self.settings["autoBend"]:
            self.autoBendChain = primitive.add2DChain(
                self.root, self.getName("autoBend%s_jnt"),
                [self.guide.apos[0], self.guide.apos[-1]],
                self.guide.blades["blade"].z * -1, False, True)

            for j in self.autoBendChain:
                j.drawStyle.set(2)

        # Ik Controlers ------------------------------------
        if self.settings["IKWorldOri"]:
            t = datatypes.TransformationMatrix()
            t = transform.setMatrixPosition(t, self.guide.apos[0])
        else:
            t = transform.getTransformLookingAt(
                self.guide.apos[0], self.guide.apos[-1],
                self.guide.blades["blade"].z * -1, "yx", self.negate)
        self.ik_off = primitive.addTransform(self.root, self.getName("ik_off"),
                                             t)
        # handle Z up orientation offset
        if self.up_axis == "z" and self.settings["IKWorldOri"]:
            self.ik_off.rx.set(90)
            t = transform.getTransform(self.ik_off)

        self.ik0_npo = primitive.addTransform(self.ik_off,
                                              self.getName("ik0_npo"), t)

        self.ik0_ctl = self.addCtl(self.ik0_npo,
                                   "ik0_ctl",
                                   t,
                                   self.color_ik,
                                   "compas",
                                   w=self.size,
                                   tp=self.parentCtlTag)

        attribute.setKeyableAttributes(self.ik0_ctl, self.tr_params)
        attribute.setRotOrder(self.ik0_ctl, "ZXY")
        attribute.setInvertMirror(self.ik0_ctl, ["tx", "ry", "rz"])

        # hip base joint
        # TODO: add option in setting for on/off
        if True:
            self.hip_lvl = primitive.addTransform(self.ik0_ctl,
                                                  self.getName("hip_lvl"), t)
            self.jnt_pos.append([self.hip_lvl, "pelvis"])

        t = transform.setMatrixPosition(t, self.guide.apos[-1])
        if self.settings["autoBend"]:
            self.autoBend_npo = primitive.addTransform(
                self.root, self.getName("spinePosition_npo"), t)

            self.autoBend_ctl = self.addCtl(self.autoBend_npo,
                                            "spinePosition_ctl",
                                            t,
                                            self.color_ik,
                                            "square",
                                            w=self.size,
                                            d=.3 * self.size,
                                            tp=self.parentCtlTag)

            attribute.setKeyableAttributes(self.autoBend_ctl,
                                           ["tx", "ty", "tz", "ry"])

            attribute.setInvertMirror(self.autoBend_ctl, ["tx", "ry"])

            self.ik1_npo = primitive.addTransform(self.autoBendChain[0],
                                                  self.getName("ik1_npo"), t)

            self.ik1autoRot_lvl = primitive.addTransform(
                self.ik1_npo, self.getName("ik1autoRot_lvl"), t)

            self.ik1_ctl = self.addCtl(self.ik1autoRot_lvl,
                                       "ik1_ctl",
                                       t,
                                       self.color_ik,
                                       "compas",
                                       w=self.size,
                                       tp=self.autoBend_ctl)
        else:
            t = transform.setMatrixPosition(t, self.guide.apos[-1])
            self.ik1_npo = primitive.addTransform(self.root,
                                                  self.getName("ik1_npo"), t)

            self.ik1_ctl = self.addCtl(self.ik1_npo,
                                       "ik1_ctl",
                                       t,
                                       self.color_ik,
                                       "compas",
                                       w=self.size,
                                       tp=self.ik0_ctl)

        attribute.setKeyableAttributes(self.ik1_ctl, self.tr_params)
        attribute.setRotOrder(self.ik1_ctl, "ZXY")
        attribute.setInvertMirror(self.ik1_ctl, ["tx", "ry", "rz"])

        # Tangent controllers -------------------------------
        if self.settings["centralTangent"]:
            # vec_pos = vector.linearlyInterpolate(self.guide.apos[0],
            #                                      self.guide.apos[-1],
            #                                      .33)
            vec_pos = self.guide.pos["tan0"]
            t = transform.setMatrixPosition(t, vec_pos)

            self.tan0_npo = primitive.addTransform(self.ik0_ctl,
                                                   self.getName("tan0_npo"), t)

            self.tan0_off = primitive.addTransform(self.tan0_npo,
                                                   self.getName("tan0_off"), t)

            self.tan0_ctl = self.addCtl(self.tan0_off,
                                        "tan0_ctl",
                                        t,
                                        self.color_ik,
                                        "sphere",
                                        w=self.size * .1,
                                        tp=self.ik0_ctl)

            attribute.setKeyableAttributes(self.tan0_ctl, self.t_params)
            # vec_pos = vector.linearlyInterpolate(self.guide.apos[0],
            #                                      self.guide.apos[-1],
            #                                      .66)
            vec_pos = self.guide.pos["tan1"]
            t = transform.setMatrixPosition(t, vec_pos)

            self.tan1_npo = primitive.addTransform(self.ik1_ctl,
                                                   self.getName("tan1_npo"), t)

            self.tan1_off = primitive.addTransform(self.tan1_npo,
                                                   self.getName("tan1_off"), t)

            self.tan1_ctl = self.addCtl(self.tan1_off,
                                        "tan1_ctl",
                                        t,
                                        self.color_ik,
                                        "sphere",
                                        w=self.size * .1,
                                        tp=self.ik0_ctl)

            attribute.setKeyableAttributes(self.tan1_ctl, self.t_params)

            # Tangent mid control
            vec_pos = vector.linearlyInterpolate(self.guide.apos[0],
                                                 self.guide.apos[-1], .5)
            t = transform.setMatrixPosition(t, vec_pos)

            self.tan_npo = primitive.addTransform(self.tan0_npo,
                                                  self.getName("tan_npo"), t)

            self.tan_ctl = self.addCtl(self.tan_npo,
                                       "tan_ctl",
                                       t,
                                       self.color_fk,
                                       "sphere",
                                       w=self.size * .2,
                                       tp=self.ik1_ctl)

            attribute.setKeyableAttributes(self.tan_ctl, self.t_params)
            attribute.setInvertMirror(self.tan_ctl, ["tx"])

        else:
            # vec_pos = vector.linearlyInterpolate(self.guide.apos[0],
            #                                      self.guide.apos[-1],
            #                                      .33)
            vec_pos = self.guide.pos["tan0"]
            t = transform.setMatrixPosition(t, vec_pos)

            self.tan0_npo = primitive.addTransform(self.ik0_ctl,
                                                   self.getName("tan0_npo"), t)

            self.tan0_ctl = self.addCtl(self.tan0_npo,
                                        "tan0_ctl",
                                        t,
                                        self.color_ik,
                                        "sphere",
                                        w=self.size * .2,
                                        tp=self.ik0_ctl)

            attribute.setKeyableAttributes(self.tan0_ctl, self.t_params)

            # vec_pos = vector.linearlyInterpolate(self.guide.apos[0],
            #                                      self.guide.apos[-1],
            #                                      .66)
            vec_pos = self.guide.pos["tan1"]
            t = transform.setMatrixPosition(t, vec_pos)

            self.tan1_npo = primitive.addTransform(self.ik1_ctl,
                                                   self.getName("tan1_npo"), t)

            self.tan1_ctl = self.addCtl(self.tan1_npo,
                                        "tan1_ctl",
                                        t,
                                        self.color_ik,
                                        "sphere",
                                        w=self.size * .2,
                                        tp=self.ik1_ctl)

            attribute.setKeyableAttributes(self.tan1_ctl, self.t_params)

        attribute.setInvertMirror(self.tan0_ctl, ["tx"])
        attribute.setInvertMirror(self.tan1_ctl, ["tx"])

        # Curves -------------------------------------------
        self.mst_crv = curve.addCnsCurve(
            self.root, self.getName("mst_crv"),
            [self.ik0_ctl, self.tan0_ctl, self.tan1_ctl, self.ik1_ctl], 3)
        self.slv_crv = curve.addCurve(self.root, self.getName("slv_crv"),
                                      [datatypes.Vector()] * 10, False, 3)
        self.mst_crv.setAttr("visibility", False)
        self.slv_crv.setAttr("visibility", False)

        # Division -----------------------------------------
        # The user only define how many intermediate division he wants.
        # First and last divisions are an obligation.
        parentdiv = self.root
        parentctl = self.root
        self.div_cns = []
        self.fk_ctl = []
        self.fk_npo = []
        self.scl_transforms = []
        self.twister = []
        self.ref_twist = []

        t = transform.getTransformLookingAt(self.guide.apos[0],
                                            self.guide.apos[-1],
                                            self.guide.blades["blade"].z * -1,
                                            "yx", self.negate)

        parent_twistRef = primitive.addTransform(
            self.root, self.getName("reference"),
            transform.getTransform(self.root))

        self.jointList = []
        self.preiviousCtlTag = self.parentCtlTag
        # handle Z up orientation offset
        # parentctl = primitive.addTransform(
        #     parentctl,
        #     self.getName("fk0_off"),
        #     transform.getTransform(parentctl))
        # if self.up_axis == "z":
        #     parentctl.rx.set(90)

        for i in range(self.settings["division"]):

            # References
            div_cns = primitive.addTransform(parentdiv,
                                             self.getName("%s_cns" % i))
            pm.setAttr(div_cns + ".inheritsTransform", False)
            self.div_cns.append(div_cns)
            parentdiv = div_cns

            # Controlers (First and last one are fake)
            # if i in [0]:
            # TODO: add option setting to add or not the first and
            #  last controller for the fk
            if i in [0, self.settings["division"] - 1] and False:
                # if i in [0, self.settings["division"] - 1]:
                fk_ctl = primitive.addTransform(
                    parentctl, self.getName("%s_loc" % i),
                    transform.getTransform(parentctl))

                fk_npo = fk_ctl
                if i in [self.settings["division"] - 1]:
                    self.fk_ctl.append(fk_ctl)
            else:
                m = transform.getTransform(self.root)
                t = transform.getTransform(parentctl)
                m.inverse()

                fk_npo = primitive.addTransform(parentctl,
                                                self.getName("fk%s_npo" % (i)),
                                                t)

                fk_ctl = self.addCtl(fk_npo,
                                     "fk%s_ctl" % (i),
                                     transform.getTransform(parentctl),
                                     self.color_fk,
                                     "cube",
                                     w=self.size,
                                     h=self.size * .05,
                                     d=self.size,
                                     tp=self.preiviousCtlTag)

                attribute.setKeyableAttributes(self.fk_ctl)
                attribute.setRotOrder(fk_ctl, "ZXY")
                self.fk_ctl.append(fk_ctl)
                self.preiviousCtlTag = fk_ctl

            self.fk_npo.append(fk_npo)
            parentctl = fk_ctl
            scl_ref = primitive.addTransform(parentctl,
                                             self.getName("%s_scl_ref" % i),
                                             transform.getTransform(parentctl))

            self.scl_transforms.append(scl_ref)

            # Deformers (Shadow)
            # self.jnt_pos.append([scl_ref, i])
            self.jnt_pos.append([scl_ref, "spine_" + str(i + 1).zfill(2)])

            # Twist references (This objects will replace the spinlookup
            # slerp solver behavior)
            t = transform.getTransformLookingAt(
                self.guide.apos[0], self.guide.apos[-1],
                self.guide.blades["blade"].z * -1, "yx", self.negate)

            twister = primitive.addTransform(parent_twistRef,
                                             self.getName("%s_rot_ref" % i), t)

            ref_twist = primitive.addTransform(parent_twistRef,
                                               self.getName("%s_pos_ref" % i),
                                               t)

            ref_twist.setTranslation(datatypes.Vector(1.0, 0, 0),
                                     space="preTransform")

            self.twister.append(twister)
            self.ref_twist.append(ref_twist)

            # TODO: update this part with the optiona FK controls update
            for x in self.fk_ctl[:-1]:
                attribute.setInvertMirror(x, ["tx", "rz", "ry"])

        # Connections (Hooks) ------------------------------
        self.cnx0 = primitive.addTransform(self.root, self.getName("0_cnx"))
        self.cnx1 = primitive.addTransform(self.root, self.getName("1_cnx"))
Example #40
0
    def controlMyLids(self):

        filePath = r"E:\sgScripts\project\\" + charName + r"\guide\\" + charName + r"_eyelidCTLGuide.ma"
        cmds.file(filePath, i=True, dns=True)

        ctrl = []
        jnts = []
        guides = pm.ls("*_GUIDE")
        sides = ["0", "1"]

        for x in guides:
            oldName = x.split("_")
            newName = oldName[0] + "_" + oldName[1] + "_" + oldName[2] + "_CTL"
            ctl = controls.roundZ(curveScale=.2)
            pm.rename(ctl, newName)
            grp = pm.group(ctl, n=newName + "_fGRP")
            grp2 = pm.group(n=newName + "_offSet_fGRP")
            if x.startswith("l"):
                zero = pm.xform("eyeCentre_0", q=1, ws=1, t=1)
            else:
                zero = pm.xform("eyeCentre_1", q=1, ws=1, t=1)
            pm.xform(grp2, ws=1, t=zero)
            pm.parent(grp, grp2)
            ctrl.append(grp2)
            pos = pm.xform(x, q=1, ws=1, t=1)
            pm.xform(grp, ws=1, t=pos)
            jntName = oldName[0] + "_" + oldName[1] + "_" + oldName[2] + "_eJNT"
            jnt = pm.createNode("joint", n=jntName)
            jnts.append(jnt)
            con = pm.pointConstraint(ctl, jnt)
            pm.xform(jnt, ws=1, t=pos)

        eyelidControl = pm.group(ctrl, n="eylidControl_GRP")
        jntControl = pm.group(jnts, n="eyeLidJoints_GRP")
        pm.setAttr(jntControl + ".visibility", 0)

        pm.delete(guides)
        offGRPS = [
            "l_eye_upMiddle_CTL_offSet_fGRP",
            "l_eye_downMiddle_CTL_offSet_fGRP",
            "r_eye_upMiddle_CTL_offSet_fGRP",
            "r_eye_downMiddle_CTL_offSet_fGRP"
        ]
        middleCTLS = [
            "l_eye_upMiddle_CTL", "l_eye_downMiddle_CTL", "r_eye_upMiddle_CTL",
            "r_eye_downMiddle_CTL"
        ]
        for x in middleCTLS:
            oldNname = x.split("_")
            newName = oldNname[0] + "_" + oldNname[1] + "_" + oldNname[
                2] + "_" + "follow" + "_fGRP"
            follgrps = pm.group(empty=True, name=newName)

        follGRPS = [
            "l_eye_upMiddle_follow_fGRP", "l_eye_downMiddle_follow_fGRP",
            "r_eye_upMiddle_follow_fGRP", "r_eye_downMiddle_follow_fGRP"
        ]
        for x, y in zip(offGRPS, follGRPS):
            print(y + x)
            pm.parent(y, x)
        for x in follGRPS:
            pm.setAttr(x + ".tx", 0)
            pm.setAttr(x + ".ty", 0)
            pm.setAttr(x + ".tz", 0)

        midGRPS = [
            "l_eye_upMiddle_CTL_fGRP", "l_eye_downMiddle_CTL_fGRP",
            "r_eye_upMiddle_CTL_fGRP", "r_eye_downMiddle_CTL_fGRP"
        ]
        for x, y in zip(follGRPS, midGRPS):
            print(y + x)
            pm.parent(y, x)
Example #41
0
 def changeAttrToBoundValue(self):
     # type: () -> None
     pm.setAttr(self.getChangeAttrName(), self.getValue())
Example #42
0
    def eyeRimJoints(self):

        eyeball = ["eyeCentre_0", "eyeCentre_1"]
        eyelids = [
            [inData["HEAD"] + eye for eye in inData["EYES"]["EYETOP_L_V"]],
            [inData["HEAD"] + eye for eye in inData["EYES"]["EYEBOT_L_V"]],
            [inData["HEAD"] + eye for eye in inData["EYES"]["EYETOP_R_V"]],
            [inData["HEAD"] + eye for eye in inData["EYES"]["EYEBOT_R_V"]]
        ]

        for lid in eyelids[0:2]:
            for v in lid:
                pm.select(cl=1)
                old = v.split("_")
                num = old[2].split(".")
                before = lid[0].split("_")
                after = before[2].split(".")
                jnt = pm.joint(n=after[1] + num[1] + "end_JNT")
                pos = pm.xform(v, q=1, ws=1, t=1)
                pm.xform(jnt, ws=1, t=pos)
                posC = pm.xform(eyeball[0], q=1, ws=1, t=1)
                pm.select(cl=1)
                jntC = pm.joint(n=after[1] + num[1] + "start_JNT")
                pm.xform(jntC, ws=1, t=posC)
                pm.parent(jnt, jntC)
                pm.setAttr(jnt + ".radius", .1)
                pm.setAttr(jntC + ".radius", .1)
                #orient joints
                pm.joint(jntC,
                         e=1,
                         oj='xyz',
                         secondaryAxisOrient='yup',
                         ch=1,
                         zso=1)

        for lid in eyelids[2:4]:
            for v in lid:
                pm.select(cl=1)
                old = v.split("_")
                num = old[2].split(".")
                before = lid[0].split("_")
                after = before[2].split(".")
                jnt = pm.joint(n=after[1] + num[1] + "end_JNT")
                pos = pm.xform(v, q=1, ws=1, t=1)
                pm.xform(jnt, ws=1, t=pos)
                posC = pm.xform(eyeball[1], q=1, ws=1, t=1)
                pm.select(cl=1)
                jntC = pm.joint(n=after[1] + num[1] + "start_JNT")
                pm.xform(jntC, ws=1, t=posC)
                pm.parent(jnt, jntC)
                pm.setAttr(jnt + ".radius", .1)
                pm.setAttr(jntC + ".radius", .1)
                #orient joints
                pm.joint(jntC,
                         e=1,
                         oj='xyz',
                         secondaryAxisOrient='yup',
                         ch=1,
                         zso=1)

        jnts1 = pm.ls("vtx_2541*start*", "vtx_2541*end*")
        for x in jnts1:
            oldName = x.split("_")
            newName = "l_uplid_" + oldName[2] + "_" + oldName[
                3] + "_" + oldName[4] + "_" + oldName[5]
            pm.rename(x, newName)
        jnts2 = pm.ls("l_uplid_*start_JNT")
        pm.group(jnts2, name="l_uplid_GRP")

        jnts3 = pm.ls("vtx_2381*star*", "vtx_2381*end*")
        for x in jnts3:
            oldName = x.split("_")
            newName = "l_downlid_" + oldName[2] + "_" + oldName[
                3] + "_" + oldName[4] + "_" + oldName[5]
            pm.rename(x, newName)
        jnts4 = pm.ls("l_downlid_*start_JNT")
        pm.group(jnts4, name="l_downlid_GRP")

        jnts5 = pm.ls("vtx_656*start*", "vtx_656*end*")
        for x in jnts5:
            oldName = x.split("_")
            newName = "r_uplid_" + oldName[2] + "_" + oldName[
                3] + "_" + oldName[4] + "_" + oldName[5]
            pm.rename(x, newName)
        jnts6 = pm.ls("r_uplid_*start_JNT")
        pm.group(jnts6, name="r_uplid_GRP")

        jnts7 = pm.ls("vtx_651*start*", "vtx_651*end*")
        for x in jnts7:
            oldName = x.split("_")
            newName = "r_downlid_" + oldName[2] + "_" + oldName[
                3] + "_" + oldName[4] + "_" + oldName[5]
            pm.rename(x, newName)
        jnts8 = pm.ls("r_downlid_*start_JNT")
        pm.group(jnts8, name="r_downlid_GRP")
Example #43
0
#Email:[email protected]
#Mobile: +91-7728050400(Whatsapp)

#You can set this as Hotkey as 0 or something very useful to zeroout t s r on ctrls
#change the prifix on line 11 accordingly like '*Ctrl' '*Ctl' '*etc'
#remove # from line 61 if you want to set scale to 1

import pymel.core as pm
try:
    sel = pm.ls(sl=1)
except:
    sel = pm.ls('*Ctrl', an=True)

for i in sel:
    try:
        pm.setAttr(i + '.translateX', 0)
    except:
        pass
    try:
        pm.setAttr(i + '.translateY', 0)
    except:
        pass

    try:
        pm.setAttr(i + '.translateZ', 0)
    except:
        pass
    try:
        pm.setAttr(i + '.rotateX', 0)
    except:
        pass
Example #44
0
    rsShader.diffuse_color.set(baseColor)

    if fileNode:

        fileNode.outColor >> rsShader.diffuse_color

    if shader.normalCamera.isConnected():

        bump2d = shader.normalCamera.listConnections()[0]
        oldNormalTex = bump2d.bumpValue.listConnections()[0]
        oldPlace2d = oldNormalTex.uvCoord.listConnections()[0]

        newPath = oldNormalTex.getAttr('fileTextureName')

        rsNormal = pm.rendering.shadingNode('RedshiftNormalMap',
                                            asTexture=True)

        pm.setAttr('.tex0', newPath, type='string')

        rsNormal.outDisplacementVector >> rsShader.bump_input
        oldPlace2d.outUV >> rsNormal.uvCoord

        pm.delete(oldNormalTex)
        pm.delete(bump2d)

    shaderSG = shader.outColor.listConnections()[0]
    rsShader.outColor >> shaderSG.surfaceShader

    pm.delete(shader)
	def setVrayRenderSettingsParameter(self, linearOnly = False, set_pre_render_mel_script = False):
		"""Set Vray Rendersettings. Never use this method directly."""
		
		#methodVars
		verbose = True
		vraySettingsNode = self.vrayRenderSettingsNode()
		
		
		#set Vray Rendersettings
		#------------------------------------------------------------------
		#------------------------------------------------------------------
		
		#Vray Common
		#------------------------------------------------------------------
		if not (linearOnly):
			
			#Image File Output
			pm.setAttr(vraySettingsNode.imageFormatStr, 'exr (multichannel)')
			pm.setAttr(vraySettingsNode.imgOpt_exr_compression, 3)
			pm.setAttr(vraySettingsNode.imgOpt_exr_autoDataWindow, 1)
			pm.setAttr(vraySettingsNode.imgOpt_exr_bitsPerChannel, 16)
			
			#Resolution
			pm.setAttr(vraySettingsNode.width, 1280)
			pm.setAttr(vraySettingsNode.height, 720)
			pm.setAttr(vraySettingsNode.aspectRatio, 1.777)
			pm.setAttr(vraySettingsNode.pixelAspect, 1)
			pm.setAttr(vraySettingsNode.sRGBOn, 1)
			pm.setAttr(vraySettingsNode.vfbOn, 1)
			if(set_pre_render_mel_script):
				pm.setAttr("defaultRenderGlobals.preRenderMel", PRE_RENDER_MEL_SCRIPT)
			
			if(verbose): print('Vray Common Parms set')
			
		
		#Vray
		#------------------------------------------------------------------
		if not (linearOnly):
			
			#Global options
			pm.setAttr(vraySettingsNode.globopt_render_viewport_subdivision, 1)
			pm.setAttr(vraySettingsNode.globopt_geom_displacement, 1)
			pm.setAttr(vraySettingsNode.globopt_light_doDefaultLights, 0)
			
			#Image Sampler
			pm.setAttr(vraySettingsNode.samplerType, 1)
			pm.setAttr(vraySettingsNode.aaFilterOn, 1)
			pm.setAttr(vraySettingsNode.aaFilterType, 1)
			pm.setAttr(vraySettingsNode.aaFilterSize, 1.5)
			pm.setAttr(vraySettingsNode.dmcMinSubdivs, 1)
			pm.setAttr(vraySettingsNode.dmcMaxSubdivs, 4)
			pm.setAttr(vraySettingsNode.dmcThreshold, 0.01)
			
			#Environment
			pm.setAttr(vraySettingsNode.cam_overrideEnvtex, 0)
			pm.setAttr(vraySettingsNode.cam_envtexGi, (0,0,0), type = 'double3')
			
		#Color mapping
		pm.setAttr(vraySettingsNode.cmap_type, 0)
		pm.setAttr(vraySettingsNode.cmap_gamma, 2.2)
		pm.setAttr(vraySettingsNode.cmap_affectBackground, 1)
		pm.setAttr(vraySettingsNode.cmap_subpixelMapping, 1)
		pm.setAttr(vraySettingsNode.cmap_adaptationOnly, 1)
		pm.setAttr(vraySettingsNode.cmap_linearworkflow, 1)
		pm.setAttr(vraySettingsNode.cmap_clampOutput, 1)
		pm.setAttr(vraySettingsNode.cmap_clampLevel, 5)
		pm.setAttr(vraySettingsNode.cmap_affectSwatches, 1)
		if(verbose): print('Vray Linear Light Parms set')
		
		if not (linearOnly):
			
			#Misc
			pm.setAttr(vraySettingsNode.bumpMultiplier, 1)
			pm.setAttr(vraySettingsNode.texFilterScaleMultiplier, 1)
			pm.setAttr(vraySettingsNode.photometricScale, 20)
			pm.setAttr(vraySettingsNode.allowNegativeShaderColors, 1)
			
			#Vray UI
			pm.setAttr(vraySettingsNode.ui_render_swatches, 1)
			
			if(verbose): print('Vray Parms set')
		
		
		#Indirect Illumination
		#------------------------------------------------------------------
		if not (linearOnly):
			
			#GI
			pm.setAttr(vraySettingsNode.giOn, 1)
			pm.setAttr(vraySettingsNode.saturation, 1)
			pm.setAttr(vraySettingsNode.contrast, 1)
			pm.setAttr(vraySettingsNode.contrastBase, 0.5)
			
			pm.setAttr(vraySettingsNode.primaryEngine, 2)
			pm.setAttr(vraySettingsNode.primaryMultiplier, 1)
			pm.setAttr(vraySettingsNode.giRayDistOn, 1)
			pm.setAttr(vraySettingsNode.dmc_subdivs, 32)
			pm.setAttr(vraySettingsNode.dmc_depth, 2)

			pm.setAttr(vraySettingsNode.secondaryEngine, 0)
			pm.setAttr(vraySettingsNode.secondaryMultiplier, 1)
			pm.setAttr(vraySettingsNode.aoOn, 0)
			
			#(Engine Specific Options) Irradiance Map
			pm.setAttr(vraySettingsNode.imap_currentPreset, 5)
			
			
			if(verbose): print('Global Illumination Parms set')
			
		
		#Settings
		#------------------------------------------------------------------
		if not (linearOnly):
			
			#DMC Sampler
			pm.setAttr(vraySettingsNode.dmcs_timeDependent, 0)
			pm.setAttr(vraySettingsNode.dmcs_adaptiveAmount, 0.85)
			pm.setAttr(vraySettingsNode.dmcs_adaptiveThreshold, 0.01)
			pm.setAttr(vraySettingsNode.dmcs_adaptiveMinSamples, 8)
			pm.setAttr(vraySettingsNode.dmcs_subdivsMult, 1)
			
			#Default Displacement and Subdivision
			pm.setAttr(vraySettingsNode.ddisplac_edgeLength, 2)
			pm.setAttr(vraySettingsNode.ddisplac_viewDependent, 1)
			pm.setAttr(vraySettingsNode.ddisplac_maxSubdivs, 6)
			pm.setAttr(vraySettingsNode.ddisplac_tightBounds, 1)
			pm.setAttr(vraySettingsNode.ddisplac_amount, 1)
			
			#System
			pm.setAttr(vraySettingsNode.sys_rayc_dynMemLimit, 40000)
			pm.setAttr(vraySettingsNode.sys_regsgen_xylocked, 1)
			pm.setAttr(vraySettingsNode.sys_regsgen_xc, 32)
			pm.setAttr(vraySettingsNode.sys_progress_increment, 1)
			pm.setAttr(vraySettingsNode.stamp_on, 1)
			
			if(verbose): print('Settings Parms set')
Example #46
0
def buildScaffoldChain(prefix, scaffoldChainDict):
    """
    Build a basic scaffold chain
    :param prefix: `string` scaffold chain prefix. eg."tail"
    :param scaffoldChainDict:`dict`
        dictionary that defines the chain structure.
        chain locator prefix: chain locator world position
        example: {"base": [0,0,0], "end":[3,-6,7]}
    :return: `PyNode` scaffold chain top group
    """
    # create scaffold top node
    scaffoldTop = pm.createNode("transform",
                                n="{0}_scaffold_grp".format(prefix))
    mayautils.disableChannels(scaffoldTop, "trs", "lh")
    scaffAttrs = [{
        "ln": SCAFFOLD_TOP_TAG,
        "dt": "string"
    }, {
        "ln": SCAFFOLD_META_PIV_TAG,
        "dt": "string"
    }, {
        "ln": "locatorSize",
        "at": "float",
        "dv": 1,
        "k": 1
    }, {
        "ln": "locators",
        "at": "message",
        "m": 1
    }, {
        "ln": "scaffoldType",
        "dt": "string"
    }]
    mayautils.addAttributes(scaffoldTop, scaffAttrs)
    pm.setAttr("{0}.{1}".format(scaffoldTop.name(), SCAFFOLD_TOP_TAG), prefix)

    # create group hierarchy
    jntGrp = pm.createNode("transform",
                           n="{0}_scaffold_jnt_grp".format(prefix))
    locGrp = pm.createNode("transform",
                           n="{0}_scaffold_loc_grp".format(prefix))
    crvGrp = pm.createNode("transform",
                           n="{0}_scaffold_curve_grp".format(prefix))
    pivGrp = pm.createNode("transform",
                           n="{0}_scaffold_piv_grp".format(prefix))
    pm.parent(jntGrp, locGrp, crvGrp, pivGrp, scaffoldTop)
    for grp in [jntGrp, locGrp, crvGrp, pivGrp]:
        mayautils.disableChannels(grp, "trsv", "lh")

    # create meta pivot ctrl
    # metaPiv = pm.spaceLocator(n="{0}_scaffold_piv".format(prefix))
    metaPiv = mayautils.createCtrl("{0}_scaffold_piv".format(prefix),
                                   "locator", 1.5, SCAFFOLD_PIV_COLOR)
    pm.xform(metaPiv, t=scaffoldChainDict.values()[0], ws=1)
    metaPiv.setParent(scaffoldTop)
    pm.connectAttr(metaPiv.message, "{0}.{1}".format(scaffoldTop.name(),
                                                     SCAFFOLD_META_PIV_TAG))

    # create scaffold joints and ctrls
    scaffLocators = []
    for i, locName in enumerate(scaffoldChainDict):
        locPos = scaffoldChainDict[locName]

        # create joints
        locJnt = pm.joint(n="{0}_{1}_scaffold_jnt".format(prefix, locName),
                          p=locPos)
        locJnt.v.set(0)
        locJnt.setParent(jntGrp)

        # create loc ctrls
        ctrlColor = SCAFFOLD_LOC_COLOR if i < len(
            scaffoldChainDict) - 1 else SCAFFOLD_END_LOC_COLOR
        locCtrl = mayautils.createCtrl(
            "{0}_{1}_scaffold_loc".format(prefix, locName), "hollowSphere",
            0.5, ctrlColor)
        mayautils.matchObject(locJnt, locCtrl, "t")
        locCtrlOff = mayautils.createParentTransform("off", locCtrl)
        locCtrlOff.setParent(locGrp)
        pm.pointConstraint(locCtrl, locJnt, n=locJnt.name() + "_pnt", mo=0)
        scaffLocators.append(locCtrl)
        locCtrl.message.connect(scaffoldTop.locators[i])

        # connect with scaffold top
        scaffoldTop.locatorSize.connect(locCtrl.sx)
        scaffoldTop.locatorSize.connect(locCtrl.sy)
        scaffoldTop.locatorSize.connect(locCtrl.sz)
        mayautils.disableChannels(locCtrl, "rsv")

        # # create pivot ctrls
        # if i < len(scaffoldChainDict) - 1:
        #     locPiv = mayautils.createCtrl("{0}_{1}_scaffold_piv".format(prefix, locName), "locator", 1.0, SCAFFOLD_PIV_COLOR, locJnt) #pm.createNode("locator", n="{0}_{1}_scaffold_piv".format(prefix, locName))
        #     locPiv.setParent(pivGrp)

    # build secondary axis controls
    for i in range(len(scaffLocators) - 1):
        locName = scaffLocators[i].name()
        followOff = pm.createNode("transform",
                                  n=locName + "_follow_off",
                                  p=scaffLocators[i])
        orientOff = pm.createNode("transform",
                                  n=locName + "_orient_off",
                                  p=followOff)
        upVectorOff = pm.createNode("transform",
                                    n=locName + "_upVector_off",
                                    p=orientOff)
        upVectorOff.dla.set(1)

        locAttrs = [
            {
                "ln": "upAxis",
                "at": "enum",
                "en": "y:-y:z:-z",
                "dv": 0,
                "k": 0
            },
            {
                "ln": "upAxisOffset",
                "at": "float",
                "dv": 0,
                "k": 0
            },
        ]
        mayautils.addAttributes(scaffLocators[i], locAttrs)
        scaffLocators[i].upAxisOffset.connect(orientOff.rotateX)
        followOffAim = pm.aimConstraint(scaffLocators[i + 1],
                                        followOff,
                                        n=followOff.name() + "_aim",
                                        mo=0)
        for dvValue, drvnKey in enumerate([(0, 1, 0), (0, -1, 0), (0, 0, 1),
                                           (0, 0, -1)]):
            pm.setDrivenKeyframe(followOffAim.upVectorX,
                                 dv=dvValue,
                                 v=drvnKey[0],
                                 cd=scaffLocators[i].upAxis)
            pm.setDrivenKeyframe(followOffAim.upVectorY,
                                 dv=dvValue,
                                 v=drvnKey[1],
                                 cd=scaffLocators[i].upAxis)
            pm.setDrivenKeyframe(followOffAim.upVectorZ,
                                 dv=dvValue,
                                 v=drvnKey[2],
                                 cd=scaffLocators[i].upAxis)

        pm.addAttr(scaffLocators[i], ln="upAxisObject", at="message")
        upVectorOff.message.connect(scaffLocators[i].upAxisObject)

    # create reference curve connecting locators
    crv = pm.curve(n="{0}_scaffold_crv".format(prefix),
                   d=1,
                   p=[scaffoldChainDict[x] for x in scaffoldChainDict])
    crv.setParent(crvGrp)
    pm.skinCluster(jntGrp.getChildren(), crv)

    # Todo lock hide useless channels
    pm.select(scaffoldTop)
    return scaffoldTop
Example #47
0
def createCrvShape(shapeName):
    crvShape = None
    if shapeName == 'circle':
        crvShape = pm.curve(d=3,
                            p=[(-0.5, 0.0, 0.0), (-0.5, 0.0, 0.130602),
                               (-0.391806, 0.0, 0.391806), (0.0, 0.0,
                                                            0.554097),
                               (0.391806, 0.0, 0.391806), (0.5, 0.0, 0.130602),
                               (0.5, 0.0, 0.0), (0.5, 0.0, -0.130602),
                               (0.391806, 0.0, -0.391806),
                               (0.0, 0.0, -0.554097),
                               (-0.391806, 0.0, -0.391806),
                               (-0.5, 0.0, -0.130602), (-0.5, 0.0, 0.0)],
                            k=[
                                2.0, 2.0, 2.0, 3.0, 4.0, 5.0, 6.0, 6.0, 6.0,
                                7.0, 8.0, 9.0, 10.0, 10.0, 10.0
                            ])

    elif shapeName == 'square':
        crvShape = pm.curve(d=1,
                            p=[(0.5, 0.0, 0.5), (-0.5, 0.0, 0.5),
                               (-0.5, 0.0, -0.5), (0.5, 0.0, -0.5),
                               (0.5, 0.0, 0.5)],
                            k=[0.0, 1.0, 2.0, 3.0, 4.0])

    elif shapeName == 'sphere':
        crvShape = pm.curve(d=3,
                            p=[
                                (-0.5, 0.0, -0.0), (-0.5, 0.130602, -0.0),
                                (-0.391806, 0.391806, -0.0),
                                (-0.130602, 0.5, -0.0), (0.0, 0.5, -0.0),
                                (0.0, 0.5, 0.130602), (0.0, 0.391806,
                                                       0.391806),
                                (0.0, 0.130602, 0.5), (0.0, -0.0, 0.5),
                                (0.130602, -0.0, 0.5),
                                (0.391806, -0.0, 0.391806),
                                (0.5, -0.0, 0.130602), (0.5, -0.0, 0.0),
                                (0.5, 0.130602, -0.0),
                                (0.391806, 0.391806, -0.0),
                                (0.130602, 0.5, -0.0), (0.0, 0.5, -0.0),
                                (0.0, 0.5, -0.130602),
                                (0.0, 0.391806, -0.391806),
                                (-0.0, 0.130602, -0.5), (-0.0, 0.0, -0.5),
                                (0.130602, 0.0, -0.5),
                                (0.391806, 0.0, -0.391806),
                                (0.5, 0.0, -0.130602), (0.5, -0.0, 0.0),
                                (0.5, -0.130602, 0.0),
                                (0.391806, -0.391806, 0.0),
                                (0.130602, -0.5, 0.0), (-0.0, -0.5, 0.0),
                                (-0.130602, -0.5, 0.0),
                                (-0.391806, -0.391806, 0.0),
                                (-0.5, -0.130602, 0.0), (-0.5, 0.0, -0.0),
                                (-0.5, 0.0, -0.130602),
                                (-0.391806, 0.0, -0.391806),
                                (-0.130602, 0.0, -0.5), (0.0, 0.0, -0.5),
                                (-0.0, -0.130602, -0.5),
                                (-0.0, -0.391806, -0.391806),
                                (-0.0, -0.5, -0.130602), (-0.0, -0.5, -0.0),
                                (-0.0, -0.5, 0.130602),
                                (-0.0, -0.391806, 0.391806),
                                (0.0, -0.130602, 0.5), (0.0, -0.0, 0.5),
                                (-0.130602, -0.0, 0.5),
                                (-0.391806, -0.0, 0.391806),
                                (-0.5, -0.0, 0.130602), (-0.5, 0.0, -0.0)
                            ],
                            k=[
                                8.0, 8.0, 8.0, 9.0, 10.0, 10.0, 10.0, 11.0,
                                12.0, 12.0, 12.0, 13.0, 14.0, 14.0, 14.0, 15.0,
                                16.0, 16.0, 16.0, 17.0, 18.0, 18.0, 18.0, 19.0,
                                20.0, 20.0, 20.0, 21.0, 22.0, 22.0, 22.0, 23.0,
                                24.0, 24.0, 24.0, 25.0, 26.0, 26.0, 26.0, 27.0,
                                28.0, 28.0, 28.0, 29.0, 30.0, 30.0, 30.0, 31.0,
                                32.0, 32.0, 32.0
                            ])

    elif shapeName == 'gear':
        transform = pm.createNode("transform", n="curve1")
        shapes = [
            pm.createNode("nurbsCurve", p=transform),
            pm.createNode("nurbsCurve", p=transform)
        ]
        pm.setAttr(shapes[0] + ".cc",
                   1,
                   32,
                   0,
                   False,
                   3, (0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0,
                       11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0,
                       20.0, 21.0, 22.0, 23.0, 24.0, 25.0, 26.0, 27.0, 28.0,
                       29.0, 30.0, 31.0, 32.0),
                   33,
                   33, (1.0011971810083387, 0.0, 0.11851736617223782),
                   (1.001197189472047, 0.0, -0.11851736720873104),
                   (0.7355889290488739, 0.0, -0.20071021702149838),
                   (0.6620637126011513, 0.0, -0.3782159567885748),
                   (0.7917582433205272, 0.0, -0.6241486124667979),
                   (0.6241494196778841, 0.0, -0.7917576310894893),
                   (0.37821666233952056, 0.0, -0.6620632132085538),
                   (0.20071060140046026, 0.0, -0.7355887728914914),
                   (0.1316864834477216, 0.0, -1.0011970883447325),
                   (-0.13168545312161806, 0.0, -1.0011970618798471),
                   (-0.2007098254073805, 0.0, -0.7355889461733963),
                   (-0.3782160036196437, 0.0, -0.6620636425135036),
                   (-0.6241485423791503, 0.0, -0.7917581964894583),
                   (-0.791757490914194, 0.0, -0.6241493260157462),
                   (-0.6620632600396227, 0.0, -0.378216592251873),
                   (-0.7355888665536292, 0.0, -0.20071046122516512),
                   (-1.0011971806904272, 0.0, -0.11851767009731831),
                   (-1.0011971306947773, 0.0, 0.11851705165536117),
                   (-0.7355889813761758, 0.0, 0.20070995395438632),
                   (-0.662063610535708, 0.0, 0.3782161643828788),
                   (-0.7917578867502331, 0.0, 0.6241485719267409),
                   (-0.6241489520030181, 0.0, 0.7917575380631745),
                   (-0.37821645207657784, 0.0, 0.6620633537017605),
                   (-0.2007103150767695, 0.0, 0.7355888374829058),
                   (-0.1185174830909543, 0.0, 1.0011972042649173),
                   (0.11851726490485413, 0.0, 1.0011972098215534),
                   (0.2007100914610428, 0.0, 0.7355888324796637),
                   (0.37821627265985613, 0.0, 0.6620634674533404),
                   (0.6241487941358845, 0.0, 0.7917577817777175),
                   (0.7917577018129599, 0.0, 0.6241488586587918),
                   (0.6620634005328294, 0.0, 0.37821638198893026),
                   (0.7355888200404718, 0.0, 0.20071022738773214),
                   (1.0011971810083387, 0.0, 0.11851736617223782),
                   type="nurbsCurve")
        pm.setAttr(shapes[1] + ".cc",
                   3,
                   10,
                   0,
                   False,
                   3, (2.0, 2.0, 2.0, 3.0, 4.0, 5.0, 6.0, 6.0, 6.0, 7.0, 8.0,
                       9.0, 10.0, 10.0, 10.0),
                   15,
                   13, (-0.5, 0.0, 0.0), (-0.5, 0.0, 0.130602),
                   (-0.391806, 0.0, 0.391806), (0.0, 0.0, 0.554097),
                   (0.391806, 0.0, 0.391806), (0.5, 0.0, 0.130602),
                   (0.5, 0.0, 0.0), (0.5, 0.0, -0.130602),
                   (0.391806, 0.0, -0.391806), (0.0, 0.0, -0.554097),
                   (-0.391806, 0.0, -0.391806), (-0.5, 0.0, -0.130602),
                   (-0.5, 0.0, 0.0),
                   type="nurbsCurve")
        crvShape = transform

    return crvShape
Example #48
0
    def doRig(self, bsDict=None):
        if not self.guideMoveall:
            self.doGuide()

        self.guideMoveall.visibility.set(0)

        if pm.objExists(self.name + 'Moveall'):
            pm.delete(self.name + 'Moveall')
        self.moveall = pm.group(em=True, n=self.name + 'Moveall')

        if pm.objExists('head_contrained'):
            constrained_grp = 'head_contrained'
        else:
            constrained_grp = pm.group(n='head_contrained', em=True)

        if bsDict:
            self.bsDict = bsDict

        size=0.8
        pm.select(cl=True)
        self.lcornerCntrl = controlTools.cntrlCrv(name='L_mouthCorner', obj=self.lcornerGuide, icone='trianguloMinusZ', size=.5)
        pm.addAttr (self.lcornerCntrl, ln="up", at="double")
        pm.addAttr (self.lcornerCntrl, ln="down", at="double")
        pm.addAttr (self.lcornerCntrl, ln="wide", at="double")
        pm.addAttr (self.lcornerCntrl, ln="narrow", at="double")
        pm.addAttr (self.lcornerCntrl, ln="upWide", at="double")
        pm.addAttr (self.lcornerCntrl, ln="upNarrow", at="double")
        pm.addAttr (self.lcornerCntrl, ln="downWide", at="double")
        pm.addAttr (self.lcornerCntrl, ln="downNarrow", at="double")

        attr = {self.lcornerCntrl: ["tz", "rx", "ry", "rz", "sx", "sy", "sz", "v"]}
        key = attr.keys ()
        for k in key:
            for item in attr[k]:
                pm.setAttr(k + "." + item, k=False, l=True)

        lClampX = pm.createNode("clamp", n="l_mouthX_clamp")
        lClampX.maxR.set(100)
        lClampX.minG.set(-100)
        lClampY = pm.createNode("clamp", n="l_mouthY_clamp")
        lClampY.maxR.set(100)
        lClampY.minG.set(-100)

        lMultX = pm.createNode("multiplyDivide", n="l_mouthX_md")
        lMultX.input2Y.set(-1)
        lMultY = pm.createNode("multiplyDivide", n="l_mouthY_md")
        lMultY.input2Y.set(-1)

        self.lcornerCntrl.translateX >> lClampX.inputR
        self.lcornerCntrl.translateX >> lClampX.inputG
        lClampX.outputR >> lMultX.input1X
        lClampX.outputG >> lMultX.input1Y
        self.lcornerCntrl.translateY >> lClampY.inputR
        self.lcornerCntrl.translateY >> lClampY.inputG
        lClampY.outputR >> lMultY.input1X
        lClampY.outputG >> lMultY.input1Y
        lMultX.outputX >> self.lcornerCntrl.wide
        lMultX.outputY >> self.lcornerCntrl.narrow
        lMultY.outputX >> self.lcornerCntrl.up
        lMultY.outputY >> self.lcornerCntrl.down
        
        multiUpWide = pm.createNode("multiplyDivide", n="MD_l_combo_up_wide")
        multiUpNarrow = pm.createNode("multiplyDivide", n="MD_l_combo_up_narrow")
        multiDownWide = pm.createNode("multiplyDivide", n="MD_l_combo_down_wide")
        multiDownNarrow = pm.createNode("multiplyDivide", n="MD_l_combo_down_narrow")

        self.lcornerCntrl.up >> multiUpWide.input1X
        self.lcornerCntrl.wide >> multiUpWide.input2X
        multiUpWide.outputX >> self.lcornerCntrl.upWide
        self.lcornerCntrl.up >> multiUpNarrow.input1X
        self.lcornerCntrl.narrow >> multiUpNarrow.input2X
        multiUpNarrow.outputX >> self.lcornerCntrl.upNarrow
        self.lcornerCntrl.down >> multiDownWide.input1X
        self.lcornerCntrl.wide >> multiDownWide.input2X
        multiDownWide.outputX >> self.lcornerCntrl.downWide
        self.lcornerCntrl.down >> multiDownNarrow.input1X
        self.lcornerCntrl.narrow >> multiDownNarrow.input2X
        multiDownNarrow.outputX >> self.lcornerCntrl.downNarrow

        self.rcornerCntrl = controlTools.cntrlCrv(name='R_mouthCorner', obj=self.rcornerGuide, icone='trianguloMinusZ', size=.5)
        self.rcornerCntrl.getParent().rotateY.set(180)

        pm.addAttr (self.rcornerCntrl, ln="up", at="double")
        pm.addAttr (self.rcornerCntrl, ln="down", at="double")
        pm.addAttr (self.rcornerCntrl, ln="wide", at="double")
        pm.addAttr (self.rcornerCntrl, ln="narrow", at="double")
        pm.addAttr (self.rcornerCntrl, ln="upWide", at="double")
        pm.addAttr (self.rcornerCntrl, ln="upNarrow", at="double")
        pm.addAttr (self.rcornerCntrl, ln="downWide", at="double")
        pm.addAttr (self.rcornerCntrl, ln="downNarrow", at="double")

        attrR = {self.rcornerCntrl: ["tz", "rx", "ry", "rz", "sx", "sy", "sz", "v"]}
        keyR = attrR.keys ()
        for kk in keyR:
            for cadaItem in attrR[kk]:
                pm.setAttr (kk + "." + cadaItem, k=False, l=True)

        rClampX = pm.createNode("clamp", n="l_mouthX_clamp")
        rClampX.maxR.set(100)
        rClampX.minG.set(-100)
        rClampY = pm.createNode("clamp", n="l_mouthY_clamp")
        rClampY.maxR.set(100)
        rClampY.minG.set(-100)
        rMultX = pm.createNode("multiplyDivide", n="r_mouthX_md")
        rMultX.input2Y.set(-1)
        rMultXNeg = pm.createNode("multiplyDivide", n="r_mouthX_md_neg")
        rMultY = pm.createNode("multiplyDivide", n="r_mouthY_md")
        rMultY.input2Y.set(-1)
        
        self.rcornerCntrl.translateX >> rClampX.inputR
        self.rcornerCntrl.translateX >> rClampX.inputG
        rClampX.outputR >> rMultX.input1X
        rClampX.outputG >> rMultX.input1Y
        rMultX.outputY >> rMultXNeg.input1X
        rMultX.outputX >> rMultXNeg.input1Y
        self.rcornerCntrl.translateY >> rClampY.inputR
        self.rcornerCntrl.translateY >> rClampY.inputG
        rClampY.outputR >> rMultY.input1X
        rClampY.outputG >> rMultY.input1Y
        rMultXNeg.outputY >> self.rcornerCntrl.wide
        rMultXNeg.outputX >> self.rcornerCntrl.narrow
        rMultY.outputX >> self.rcornerCntrl.up
        rMultY.outputY >> self.rcornerCntrl.down

        rMultiUpWide = pm.createNode("multiplyDivide", n="MD_r_combo_up_wide")
        rMultiUpNarrow = pm.createNode("multiplyDivide", n="MD_r_combo_up_narrow")
        rMultiDownWide = pm.createNode("multiplyDivide", n="MD_r_combo_down_wide")
        rMultiDwonWide = pm.createNode ("multiplyDivide", n="MD_r_combo_down_narrow")

        self.rcornerCntrl.up >> rMultiUpWide.input1X
        self.rcornerCntrl.wide >> rMultiUpWide.input2X
        rMultiUpWide.outputX >> self.rcornerCntrl.upWide
        self.rcornerCntrl.up >> rMultiUpNarrow.input1X
        self.rcornerCntrl.narrow >> rMultiUpNarrow.input2X
        rMultiUpNarrow.outputX >> self.rcornerCntrl.upNarrow
        self.rcornerCntrl.down >> rMultiDownWide.input1X
        self.rcornerCntrl.wide >> rMultiDownWide.input2X
        rMultiDownWide.outputX >> self.rcornerCntrl.downWide
        self.rcornerCntrl.down >> rMultiDwonWide.input1X
        self.rcornerCntrl.narrow >> rMultiDwonWide.input2X
        rMultiDwonWide.outputX >> self.rcornerCntrl.downNarrow

        pm.parent(self.lcornerCntrl.getParent(), self.rcornerCntrl.getParent(), self.moveall)
        pm.parent(self.moveall, constrained_grp)
Example #49
0
 def jointUnder(self, joint):
     jointUnder = pm.listRelatives(joint, c=1, type="joint")
     if not len(jointUnder):
         pm.setAttr(joint.jointOrient, (0, 0, 0))
         return None
     return jointUnder
Example #50
0
    def matrixConstraint(self, child, channels='trsh', mo=True):
        """
        Use the matrixConstraint for faster rigs.
        If you set the channels to 'trsh' it will act just as a parentConstraint.
        If you set the channels to 't' it will act just as a pointConstraint.
        If you set the channels to 's' it will act just as a scaleConstraint.
        If you set the channels to 'r' it will act just as a orientConstraint.

        t:translate, s:scale, r:rotate, s:shear

        there is no blending or multiple targets concept and the driven object MUST have the
        rotate order set to the default xyz or it will not work.

        :param Transform driven: the driven object

        @param channels: (str)  specify if the result should be connected to
                                translate, rotate or/and scale by passing a string with
                                the channels to connect.
                                Example: 'trsh' will connect them all, 'tr' will skip scale and shear

        @param mo:  (bool)  Maintain offset, like in the constrains a difference matrix will be
                            held for retaining the driven original position.
                            1 will multiply the offset before the transformations, 2 after.
                            by multiplying it after, the effect will be suitable for a
                            pointConstraint like behavior.

        Return the decompose Matrix Node
        """
        parent_transform = self.transform[0]

        if isinstance(child, list):
            child = child[0]
        elif isinstance(child, basestring):
            child = child
        elif isinstance(child, unicode):
            child = pm.PyNode(child)

        def getDagPath(node=None):
            sel = om.MSelectionList()
            sel.add(str(node))
            d = om.MDagPath()
            sel.getDagPath(0, d)
            return d

        def getLocalOffset():
            parentWorldMatrix = getDagPath(
                str(parent_transform)).inclusiveMatrix()
            childWorldMatrix = getDagPath(child).inclusiveMatrix()
            return childWorldMatrix * parentWorldMatrix.inverse()

        mult_matrix = pm.createNode('multMatrix',
                                    n='{}_multM'.format(parent_transform))
        dec_matrix = pm.createNode('decomposeMatrix',
                                   n='{}_dectM'.format(parent_transform))

        if mo is True:
            localOffset = getLocalOffset()

            # matrix Mult Node CONNECTIONS
            pm.setAttr("{}.matrixIn[0]".format(mult_matrix),
                       [localOffset(i, j) for i in range(4) for j in range(4)],
                       type="matrix")
            pm.PyNode(parent_transform).worldMatrix >> mult_matrix.matrixIn[1]
            mult_matrix.matrixSum >> dec_matrix.inputMatrix
            pm.PyNode(child).parentInverseMatrix >> mult_matrix.matrixIn[2]

        else:
            pm.PyNode(parent_transform).worldMatrix >> mult_matrix.matrixIn[0]
            mult_matrix.matrixSum >> dec_matrix.inputMatrix
            pm.PyNode(child).parentInverseMatrix >> mult_matrix.matrixIn[1]

        # CHANNELS CONNECTIONS
        axes = 'XYZ'
        for channel in channels:
            if channel == 't':
                for axe in axes:
                    pm.PyNode('{}.outputTranslate{}'.format(
                        dec_matrix, axe)) >> pm.PyNode('{}.translate{}'.format(
                            child, axe))
            if channel == 'r':
                for axe in axes:
                    pm.PyNode('{}.outputRotate{}'.format(
                        dec_matrix, axe)) >> pm.PyNode('{}.rotate{}'.format(
                            child, axe))
                pm.PyNode(child).rotateOrder >> pm.PyNode(
                    dec_matrix).inputRotateOrder
                try:
                    pm.PyNode(child).jointOrientX.set(0)
                    pm.PyNode(child).jointOrientY.set(0)
                    pm.PyNode(child).jointOrientZ.set(0)
                except AttributeError:
                    pass
            if channel == 's':
                for axe in axes:
                    pm.PyNode('{}.outputScale{}'.format(
                        dec_matrix, axe)) >> pm.PyNode('{}.scale{}'.format(
                            child, axe))
            if channel == 'h':
                dec_matrix.outputShearX >> pm.PyNode(child).shearXY
                dec_matrix.outputShearY >> pm.PyNode(child).shearXZ
                dec_matrix.outputShearZ >> pm.PyNode(child).shearYZ

        return dec_matrix
Example #51
0
def postSpring(dist = 5, hostUI = False,  hostUI2 = False, invertX=False ):

    """
    Create the dynamic spring rig. This spring system use the mgear_spring node. And transfer the position spring
    to rotation spring using an aim constraint.

    Note:
        The selected chain of object should be align with the X axis.

    Args:
        dist (float): The distance of the position spring.
        hostUI (dagNode): The spring active and intensity channel host.
        hostUI2 (dagNode): The daping and stiffness channel host for each object in the chain.
        invertX (bool): reverse the direction of the x axis.

    """
    oSel = pm.selected()

    if not hostUI2:
            hostUI2 = oSel[0]

    aSpring_active = att.addAttribute(hostUI2, "spring_active_%s"%oSel[0].name(), "double", 1.0, "___spring_active_______%s"%oSel[0].name(), "spring_active_%s"%oSel[0].name(), 0, 1)
    aSpring_intensity = att.addAttribute(hostUI2, "spring_intensity_%s"%oSel[0].name(), "double", 1.0, "___spring_intensity_______%s"%oSel[0].name(), "spring_intensity_%s"%oSel[0].name(), 0, 1)

    if invertX:
        dist = dist *-1
        #aim constraint
        aimAxis = "-xy"
    else:
        #aim constraint
        aimAxis = "xy"

    for obj in oSel:

        oParent = obj.getParent()



        oNpo = pm.PyNode(pm.createNode("transform", n= obj.name() + "_npo", p=oParent, ss=True))
        oNpo.setTransformation(obj.getMatrix())
        pm.parent(obj, oNpo)

        oSpring_cns = pm.PyNode(pm.createNode("transform", n= obj.name() + "_spr_cns", p=oNpo, ss=True))
        oSpring_cns.setTransformation(obj.getMatrix())
        pm.parent(obj, oSpring_cns)


        oSpringLvl = pm.PyNode(pm.createNode("transform", n= obj.name() + "_spr_lvl", p=oNpo, ss=True))
        oM = obj.getTransformation()
        oM.addTranslation([dist, 0,0], "object")
        oSpringLvl.setTransformation(oM.asMatrix())

        oSpringDriver = pm.PyNode(pm.createNode("transform", n= obj.name() + "_spr", p=oSpringLvl, ss=True))


        try:
                defSet = pm.PyNode("rig_PLOT_grp")
                pm.sets(defSet, add=oSpring_cns)
        except:
            defSet   =  pm.sets(name="rig_PLOT_grp")
            pm.sets(defSet, remove=obj)
            pm.sets(defSet, add=oSpring_cns)

        #adding attributes:
        if not hostUI:
            hostUI = obj


        aSpring_damping = att.addAttribute(hostUI, "spring_damping_%s"%obj.name(), "double", .5, "damping_%s"%obj.name(), "damping_%s"%obj.name(), 0, 1)
        aSpring_stiffness_ = att.addAttribute(hostUI, "spring_stiffness_%s"%obj.name(), "double", .5, "stiffness_%s"%obj.name(), "stiffness_%s"%obj.name(), 0, 1)




        cns = aop.aimCns(oSpring_cns, oSpringDriver, aimAxis, 2, [0,1,0], oNpo, False)

        #change from fcurves to spring
        pb_node = pm.createNode("pairBlend")

        pm.connectAttr(cns+".constraintRotateX", pb_node+".inRotateX2")
        pm.connectAttr(cns+".constraintRotateY", pb_node+".inRotateY2")
        pm.connectAttr(cns+".constraintRotateZ", pb_node+".inRotateZ2")
        pm.setAttr(pb_node+".translateXMode", 2)
        pm.setAttr(pb_node+".translateYMode", 2)
        pm.setAttr(pb_node+".translateZMode", 2)


        pm.connectAttr( pb_node+".outRotateX", oSpring_cns+".rotateX", f=True)
        pm.connectAttr( pb_node+".outRotateY", oSpring_cns+".rotateY", f=True)
        pm.connectAttr( pb_node+".outRotateZ", oSpring_cns+".rotateZ", f=True)
        pm.setKeyframe( oSpring_cns, at="rotateX")
        pm.setKeyframe( oSpring_cns, at="rotateY")
        pm.setKeyframe( oSpring_cns, at="rotateZ")

        #add sprint op
        springOP = aop.gear_spring_op(oSpringDriver)

        #connecting attributes
        pm.connectAttr(aSpring_active, pb_node+".weight")
        pm.connectAttr(aSpring_intensity, springOP+".intensity")
        pm.connectAttr(aSpring_damping, springOP+".damping")
        pm.connectAttr(aSpring_stiffness_, springOP+".stiffness")
Example #52
0
def set_renderer(render_engine_name):
    """ 
        Args:   render_engine_name = 'arnold' / 'redshift' / 'vray' / 'mayaSoftware' / 'mayaHardware' / 'mayaHardware2' / 'mayaVector' / mentalray

        eg:     mayaRendering.set_renderer('vray')
    """
    if render_engine_name == 'arnold':
        pm.setAttr("defaultRenderGlobals.currentRenderer",
                   str(render_engine_name))
    elif render_engine_name == 'redshift':
        pm.setAttr("defaultRenderGlobals.currentRenderer",
                   str(render_engine_name))
    elif render_engine_name == 'vray':
        pm.setAttr("defaultRenderGlobals.currentRenderer",
                   str(render_engine_name))
    elif render_engine_name == 'mayaSoftware':
        pm.setAttr("defaultRenderGlobals.currentRenderer",
                   str(render_engine_name))
    elif render_engine_name == 'mayaHardware':
        pm.setAttr("defaultRenderGlobals.currentRenderer",
                   str(render_engine_name))
    elif render_engine_name == 'mayaHardware2':
        pm.setAttr("defaultRenderGlobals.currentRenderer",
                   str(render_engine_name))
    elif render_engine_name == 'mayaVector':
        pm.setAttr("defaultRenderGlobals.currentRenderer",
                   str(render_engine_name))
    elif render_engine_name == 'mentalray':
        pm.setAttr("defaultRenderGlobals.currentRenderer",
                   str(render_engine_name))
Example #53
0
    def connectRef2(self,
                    refArray,
                    cns_obj,
                    in_attr,
                    init_ref=False,
                    skipTranslate=False,
                    init_refNames=False):
        """Connect the cns_obj to a multiple object using parentConstraint.

        Args:
            refArray (string): List of driver objects divided by ",".
            cns_obj (dagNode): The driven object.
            in_attr (attr): The attribute to connect the switch
            init_ref (list of dagNode): Set the initial default ref connections
            skipTranslate (bool): if True will skip the translation connections
            init_refNames (list of str, optional): Set initial default names
                for the initial default connections

        """
        if refArray:
            if init_refNames:
                # we only can perform name validation if the init_refnames are
                # provided in a separated list. This check ensures backwards
                # copatibility
                ref_names = self.get_valid_ref_list(refArray.split(","))
            else:
                ref_names = refArray.split(",")
            if len(ref_names) == 1 and not init_refNames:
                ref = self.rig.findRelative(ref_names[0])
                pm.parent(cns_obj, ref)
            else:
                if init_refNames:
                    ref_names = ref_names + init_refNames
                ref = []
                for ref_name in ref_names:
                    rrn = self.rig.findRelative(ref_name)
                    rgn = self.rig.findRelative("return the global ctl")
                    if rrn != rgn:
                        ref.append(self.rig.findRelative(ref_name))
                if init_ref:
                    ref = init_ref + ref
                ref.append(cns_obj)
                if skipTranslate:
                    cns_node = pm.parentConstraint(
                        *ref,
                        maintainOffset=True,
                        skipTranslate=["x", "y", "z"])
                else:
                    cns_node = pm.parentConstraint(*ref, maintainOffset=True)
                cns_attr = pm.parentConstraint(cns_node,
                                               query=True,
                                               weightAliasList=True)

                for i, attr in enumerate(cns_attr):
                    node_name = pm.createNode("condition")
                    pm.connectAttr(in_attr, node_name + ".firstTerm")
                    pm.setAttr(node_name + ".secondTerm", i)
                    pm.setAttr(node_name + ".operation", 0)
                    pm.setAttr(node_name + ".colorIfTrueR", 1)
                    pm.setAttr(node_name + ".colorIfFalseR", 0)
                    pm.connectAttr(node_name + ".outColorR", attr)
Example #54
0
def apply(preset, mode):
    '''
    &&& Do I optionally bookend the ranged switches?  Probably.
    Args:
        preset: Dict of { <pynode control>: '<space name or "# Activate">', ... }
        mode: str of [frame, all, range, selected]
    '''
    '''
    Tests
    All the combinations:
        Fk to Ik, ends are keyed
            opposite
        Fk to Ik, ends are not keyed
            opposite
        
    '''

    print(preset)

    leads = set()

    spaces = {}

    for ctrl, action in preset.items():
        leads.add(fossil.node.leadController(ctrl))
        if action != ACTIVATE_KEY:
            spaces[ctrl] = action

    if mode == 'frame':
        start = int(currentTime(q=True))
        end = int(currentTime(q=True))

    elif mode == 'range':
        start, end = pdil.time.playbackRange()

    elif mode == 'selected':
        if not pdil.time.rangeIsSelected():
            start, end = pdil.time.playbackRange()
        else:
            start, end = pdil.time.selectedTime()

    elif mode == 'all':

        #pairs = { obj: obj.getOtherMotionType() for obj in currentLeads }
        source = [obj.getOtherMotionType() for obj in leads]

        #targetLeads = [other for obj, other in pairs.items() if other]

        relevantControls = []
        relevantControls += source
        for leadControl in source:
            relevantControls += [
                obj for name, obj in leadControl.subControl.items()
            ]

        start, end = pdil.anim.findKeyTimes(relevantControls, None, None)
    print(start, end, '- - - -  - - ', leads)
    pdil.tool.fossil.kinematicSwitch.animStateSwitch(leads, start, end, spaces)

    return

    if mode == 'frame':
        # Single frame is easy, just do the work and get out
        for ctrl, targetSpace in preset.items():
            mainCtrl = fossil.rig.getMainController(ctrl)
            switcher = fossil.controllerShape.getSwitcherPlug(ctrl)

            # Ensure we're in ik or fk prior to switching spaces
            if switcher:
                if shouldBeFk(mainCtrl, switcher):
                    fossil.kinematicSwitch.activateFk(mainCtrl)
                elif shouldBeIk(mainCtrl, switcher):
                    # &&& This appears to key always, is this ok?
                    getIkSwitchCommand(mainCtrl)()
                    setAttr(
                        switcher, 1
                    )  # 7/9/2020 the switch command needs burping so actively set it

            # Finally space switch
            if targetSpace != ACTIVATE_KEY:
                fossil.space.switchToSpace(ctrl, targetSpace)

        return

    else:
        if mode == 'all':
            keyRange = (None, None)
        elif mode == 'range':
            keyRange = (playbackOptions(q=True, min=True),
                        playbackOptions(q=True, max=True))
        elif mode == 'selected':
            if not pdil.time.rangeIsSelected():
                keyRange = [currentTime()] * 2
            else:
                keyRange = pdil.time.selectedTime()

        presetLog.debug('Range {} {}'.format(keyRange[0], keyRange[-1]))
        '''
        This is a complex optimization.  The naive switcher ran over the timeline for _each_ control.
        Walking the timeline is the slowest operation (probably because all other nodes update) so a 10 control
        profile took 10x longer than a 1 control profile.
        
        Solution: collect all the times all events occur at, walk the timeline ONCE and switch as needed.
        Technically this is actually done twice, once to do the kinematic switch, and again to for the space.
        Future improvement will try to do it as one.
        
        kinematicSwitches[ <switch command> ] = [ <list of times to run at> ]
        '''

        kinematicSwitches = {}
        allTimes = set()

        for ctrl, targetSpace in preset.items():
            if isinstance(ctrl, basestring):
                continue

            mainCtrl = fossil.rig.getMainController(ctrl)
            switcher = fossil.controllerShape.getSwitcherPlug(ctrl)
            print(mainCtrl, switcher)
            # Implicit to ensure we're in the mode that the space is in.
            if switcher:
                otherMotionTimes = getLimbKeyTimes(
                    mainCtrl.getOtherMotionType(), keyRange[0], keyRange[1])
                targetTimes = getLimbKeyTimes(mainCtrl, keyRange[0],
                                              keyRange[1])
                presetLog.debug(
                    'other times count: {}   target times count: {}'.format(
                        len(otherMotionTimes), len(targetTimes)))
                # Neither is keyed, perform basic switch
                if not otherMotionTimes and not targetTimes:
                    presetLog.debug('No keys on either, just switch')
                    if shouldBeFk(mainCtrl, switcher):
                        fossil.kinematicSwitch.activateFk(mainCtrl)

                    elif shouldBeIk(mainCtrl, switcher):
                        getIkSwitchCommand(mainCtrl)()

                    continue

                # Bizarre case, no keys on the source space but some on dest space
                # Just switch at the ends and clean out the middle
                if not otherMotionTimes and targetTimes:
                    presetLog.debug('Only target')
                    #otherMain = mainCtrl.getOtherMotionType()
                    controls = [mainCtrl] + [
                        ctrl for name, ctrl in mainCtrl.subControl.items()
                    ]
                    if shouldBeFk(mainCtrl, switcher):
                        cutKey(controls, iub=True, t=keyRange, cl=True)
                        #fossil.kinematicSwitch.activateFk( mainCtrl )
                        kinematicSwitches[partial(toFk, controls,
                                                  switcher)] = keyRange

                    elif shouldBeIk(mainCtrl, switcher):
                        cutKey(controls, iub=True, t=keyRange, cl=True)
                        kinematicSwitches[getIkSwitchCommand(
                            mainCtrl)] = keyRange
                        #getIkSwitchCommand(mainCtrl)()

                    allTimes.update(keyRange)
                    # Does cleanTargetKeys() need to happen here?  I don't think so,
                    continue

                if shouldBeFk(mainCtrl, switcher):
                    targetMotion = 0
                    presetLog.debug('Switch to FK {}: {} - {}'.format(
                        mainCtrl, otherMotionTimes[0], otherMotionTimes[-1]))
                    fkCtrls = [mainCtrl] + [
                        ctrl for name, ctrl in mainCtrl.subControl.items()
                    ]

                    kinematicSwitches[partial(toFk, fkCtrls,
                                              switcher)] = otherMotionTimes
                    allTimes.update(otherMotionTimes)

                elif shouldBeIk(mainCtrl, switcher):
                    targetMotion = 1
                    presetLog.debug('Switch to IK {} {} - {}'.format(
                        mainCtrl, otherMotionTimes[0], otherMotionTimes[-1]))
                    kinematicSwitches[getIkSwitchCommand(
                        mainCtrl)] = otherMotionTimes
                    allTimes.update(otherMotionTimes)

                if otherMotionTimes:
                    keySwitcher(switcher, otherMotionTimes)
                    cleanTargetKeys(mainCtrl, switcher, otherMotionTimes,
                                    targetMotion)

        with pdil.time.preserveCurrentTime():
            # First timeline runthrough - ensure the kinematic state is correct.
            with pdil.ui.NoUpdate():
                presetLog.debug('KINEMATIC TIMES {}'.format(sorted(allTimes)))
                for i in sorted(allTimes):
                    currentTime(i)
                    for cmd, vals in kinematicSwitches.items():
                        if i in vals:
                            cmd()

            # Just like with kinematics, gather all the frames a space switch is needed.
            spaceSwitches = {}

            allSpaceTimes = set()
            for ctrl, targetSpace in preset.items():
                if not isinstance(ctrl,
                                  basestring) and targetSpace != ACTIVATE_KEY:

                    # If the space is unkeyed, just switch it, other wise store it
                    times = getSpaceTimes(ctrl, keyRange)
                    if not times:
                        fossil.space.switchToSpace(ctrl, targetSpace)
                    else:
                        allSpaceTimes.update(times)

                        presetLog.debug('Switch Ctrl {}'.format(ctrl))
                        enumVal = ctrl.space.getEnums()[targetSpace]
                        spaceSwitches[partial(performSpaceSwitch, ctrl,
                                              targetSpace, enumVal)] = times

            # Finally, walk the timeline a second time switching spaces as needed.
            with pdil.ui.NoUpdate():
                for i in sorted(allSpaceTimes):
                    currentTime(i)
                    for cmd, vals in spaceSwitches.items():
                        if i in vals:
                            cmd()
Example #55
0
START_FRAME = 1
GLOBAL_SCALE = 1

geo = [
    g for g in pm.ls(an=1, ap=1, et='transform')
    if pm.listRelatives(g, s=1)[0].type() == 'mesh'
]
joints = pm.ls(an=1, ap=1, et='joint')

# do we need to conform functions to always take lists of joints
# or do the looping outside of the function and only pass single joints
if True:
    for j in joints:
        break_ts_anim(j)
        if not len(j.listRelatives(p=True)):
            pm.setAttr(j + '.tx', 0)
            pm.setAttr(j + '.ty', 0)
            pm.setAttr(j + '.tz', 0)
        pm.setAttr(j + ".radius", 0.5)

# export weights
if True:
    for g in geo:
        export_deformer_weights(g, WORKING_DIR)

        # don't use single shader, use incandescence option

        #shader = [x for x in pm.ls(type="shadingEngine") if x.name() == 'initialShadingGroup'][0]
        #pm.sets(shader, forceElement=g)

        #lambert_to_flat(g)
Example #56
0
    def addJoint(self,
                 obj,
                 name,
                 newActiveJnt=None,
                 UniScale=False,
                 segComp=0,
                 gearMulMatrix=True):
        """Add joint as child of the active joint or under driver object.

        Args:
            obj (dagNode): The input driver object for the joint.
            name (str): The joint name.
            newActiveJnt (bool or dagNode): If a joint is pass, this joint will
                be the active joint and parent of the newly created joint.
            UniScale (bool): Connects the joint scale with the Z axis for a
                unifor scalin, if set Falsewill connect with each axis
                separated.
            segComp (bool): Set True or False the segment compensation in the
                joint..
            gearMulMatrix (bool): Use the custom gear_multiply matrix node, if
                False will use Maya's default mulMatrix node.

        Returns:
            dagNode: The newly created joint.

        """

        if self.options["joint_rig"]:
            if newActiveJnt:
                self.active_jnt = newActiveJnt

            jnt = primitive.addJoint(self.active_jnt,
                                     self.getName(str(name) + "_jnt"),
                                     transform.getTransform(obj))
            # TODO: Set the joint to have always positive scaling
            # jnt.scale.set([1, 1, 1])

            # Disconnect inversScale for better preformance
            if isinstance(self.active_jnt, pm.nodetypes.Joint):
                try:
                    pm.disconnectAttr(self.active_jnt.scale, jnt.inverseScale)

                except RuntimeError:
                    # This handle the situation where we have in between joints
                    # transformation due a negative scaling
                    pm.ungroup(jnt.getParent())
            # All new jnts are the active by default
            self.active_jnt = jnt

            if gearMulMatrix:
                mulmat_node = applyop.gear_mulmatrix_op(
                    obj + ".worldMatrix", jnt + ".parentInverseMatrix")
                dm_node = node.createDecomposeMatrixNode(mulmat_node +
                                                         ".output")
                m = mulmat_node.attr('output').get()
            else:
                mulmat_node = node.createMultMatrixNode(
                    obj + ".worldMatrix", jnt + ".parentInverseMatrix")
                dm_node = node.createDecomposeMatrixNode(mulmat_node +
                                                         ".matrixSum")
                m = mulmat_node.attr('matrixSum').get()
            pm.connectAttr(dm_node + ".outputTranslate", jnt + ".t")
            pm.connectAttr(dm_node + ".outputRotate", jnt + ".r")
            # TODO: fix squash stretch solver to scale the joint uniform
            # the next line cheat the uniform scaling only fo X or Y axis
            # oriented joints
            if UniScale:
                pm.connectAttr(dm_node + ".outputScaleZ", jnt + ".sx")
                pm.connectAttr(dm_node + ".outputScaleZ", jnt + ".sy")
                pm.connectAttr(dm_node + ".outputScaleZ", jnt + ".sz")
            else:
                pm.connectAttr(dm_node + ".outputScale", jnt + ".s")
                pm.connectAttr(dm_node + ".outputShear", jnt + ".shear")

            # Segment scale compensate Off to avoid issues with the global
            # scale
            jnt.setAttr("segmentScaleCompensate", segComp)

            jnt.setAttr("jointOrient", 0, 0, 0)

            # setting the joint orient compensation in order to have clean
            # rotation channels
            jnt.attr("jointOrientX").set(jnt.attr("rx").get())
            jnt.attr("jointOrientY").set(jnt.attr("ry").get())
            jnt.attr("jointOrientZ").set(jnt.attr("rz").get())

            im = m.inverse()

            if gearMulMatrix:
                mul_nod = applyop.gear_mulmatrix_op(mulmat_node.attr('output'),
                                                    im, jnt, 'r')
                dm_node2 = mul_nod.output.listConnections()[0]
            else:
                mul_nod = node.createMultMatrixNode(
                    mulmat_node.attr('matrixSum'), im, jnt, 'r')
                dm_node2 = mul_nod.matrixSum.listConnections()[0]

            if jnt.attr("sz").get() < 0:
                # if negative scaling we have to negate some axis for rotation
                neg_rot_node = pm.createNode("multiplyDivide")
                pm.setAttr(neg_rot_node + ".operation", 1)
                pm.connectAttr(dm_node2.outputRotate,
                               neg_rot_node + ".input1",
                               f=True)
                for v, axis in zip([-1, -1, 1], "XYZ"):
                    pm.setAttr(neg_rot_node + ".input2" + axis, v)
                pm.connectAttr(neg_rot_node + ".output", jnt + ".r", f=True)

            # set not keyable
            attribute.setNotKeyableAttributes(jnt)

        else:
            jnt = primitive.addJoint(obj, self.getName(str(name) + "_jnt"),
                                     transform.getTransform(obj))
            pm.connectAttr(self.rig.jntVis_att, jnt.attr("visibility"))
            attribute.lockAttribute(jnt)

        self.addToGroup(jnt, "deformers")

        # This is a workaround due the evaluation problem with compound attr
        # TODO: This workaround, should be removed onces the evaluation issue
        # is fixed
        # github issue: Shifter: Joint connection: Maya evaluation Bug #210
        dm = jnt.r.listConnections(p=True, type="decomposeMatrix")
        if dm:
            at = dm[0]
            dm_node = at.node()
            pm.disconnectAttr(at, jnt.r)
            pm.connectAttr(dm_node.outputRotateX, jnt.rx)
            pm.connectAttr(dm_node.outputRotateY, jnt.ry)
            pm.connectAttr(dm_node.outputRotateZ, jnt.rz)

        dm = jnt.t.listConnections(p=True, type="decomposeMatrix")
        if dm:
            at = dm[0]
            dm_node = at.node()
            pm.disconnectAttr(at, jnt.t)
            pm.connectAttr(dm_node.outputTranslateX, jnt.tx)
            pm.connectAttr(dm_node.outputTranslateY, jnt.ty)
            pm.connectAttr(dm_node.outputTranslateZ, jnt.tz)

        dm = jnt.s.listConnections(p=True, type="decomposeMatrix")
        if dm:
            at = dm[0]
            dm_node = at.node()
            pm.disconnectAttr(at, jnt.s)
            pm.connectAttr(dm_node.outputScaleX, jnt.sx)
            pm.connectAttr(dm_node.outputScaleY, jnt.sy)
            pm.connectAttr(dm_node.outputScaleZ, jnt.sz)

        return jnt
Example #57
0
def createPairBlend(inputA=None,
                    inputB=None,
                    blender=.5,
                    rotInterpolation=0,
                    output=None,
                    trans=True,
                    rot=True):
    """Create and connect a PairBlend node.

    Arguments:
        inputA (dagNode): The transfomr input 1
        inputB (dagNode): The transfomr input 2
        blender (float or attr): Float in 0 to 1 range or attribute
            string name.
        rotInterpolation (int): Rotation interpolation option. 0=Euler.
            1=Quaternion.
        output (dagNode): The output node with the blend transfomr
            applied.
        trans (bool): If true connects translation.
        rot (bool): If true connects rotation.

    Returns:
        pyNode: the newly created node.

    Example:
        .. code-block:: python

            blend_node = nod.createPairBlend(self.legBonesFK[i],
                                             self.legBonesIK[i],
                                             self.blend_att,
                                             1)
            pm.connectAttr(blend_node + ".outRotate", x+".rotate")
            pm.connectAttr(blend_node + ".outTranslate", x+".translate")

    """
    node = pm.createNode("pairBlend")
    node.attr("rotInterpolation").set(rotInterpolation)

    if inputA:
        if trans:
            pm.connectAttr(inputA + ".translate", node + ".inTranslate1")
        if rot:
            pm.connectAttr(inputA + ".rotate", node + ".inRotate1")

    if inputB:
        if trans:
            pm.connectAttr(inputB + ".translate", node + ".inTranslate2")
        if rot:
            pm.connectAttr(inputB + ".rotate", node + ".inRotate2")

    if (isinstance(blender, str) or isinstance(blender, unicode)
            or isinstance(blender, pm.Attribute)):
        pm.connectAttr(blender, node + ".weight")
    else:
        pm.setAttr(node + ".weight", blender)

    if output:
        if rot:
            pm.connectAttr(node + ".outRotate", output + ".rotate")
        if trans:
            pm.connectAttr(node + ".outTranslate", output + ".translate")

    return node
    def maya_sim_setup(self):

        pm.confirmDialog(
            title='Confirm',
            message='Are you sure you want to create a new scene?',
            button=['Yes', 'No'],
            defaultButton='Yes',
            cancelButton='No',
            dismissString='No')

        print 'setting up maya Sim scene'

        #referencing latest cloth setup
        assets = su.getLatestShotAssets(self, 'cloth')
        clothFile = assets[0]['path']['local_path_windows']
        print clothFile
        #setup reference plate
        tk = self.parent.tank

        ctx = self.parent.context
        maya_work = tk.templates['shot_work_area']

        fields = ctx.as_template_fields(maya_work)
        assets = ['grandpa', 'start_null']

        cmds.file(newFile=True, force=True)
        pm.importFile(clothFile)
        #loading alembic plugin
        pm.loadPlugin('AbcImport.mll')

        for asset in assets:
            fields['Asset'] = asset

            cache_alembic = tk.templates['cache_alembic']
            abcFile = cache_alembic.apply_fields(fields)

            ncache = tk.templates['maya_nCache']
            ncachePath = ncache.apply_fields(fields)

            if asset == 'grandpa':
                abcNodes = "shoes l_eye r_eye topTeeth bottomTeeth body"
            else:
                abcNodes = "start_null"

            #import alembic
            print abcFile
            pm.AbcImport(abcFile,
                         mode="import",
                         ct=abcNodes,
                         ftr=True,
                         crt=True,
                         sts=True)

        #query time data
        startTime = cmds.playbackOptions(q=True, animationStartTime=True)
        endTime = cmds.playbackOptions(q=True, animationEndTime=True)

        pm.currentTime(startTime)
        pm.currentTime(startTime + 1)
        pm.currentTime(startTime)

        pm.PyNode('nucleus*').startFrame.set(startTime)

        #find all nCloth objects
        clothObjects = pm.ls(type='nCloth')

        #create simulation cache for all nCloth nodes in the scene
        print('caching theses nCloth objects: ' + str(clothObjects))
        cacheFiles = pm.cacheFile(cnd=clothObjects,
                                  st=startTime,
                                  et=endTime,
                                  dir=ncachePath,
                                  dtf=True,
                                  fm='OneFile',
                                  r=True,
                                  ws=True)

        #apply created cache to simulated objects
        cacheShapes = pm.ls('outputCloth*')
        i = 0
        for shape in cacheShapes:
            switch = mel.eval('createHistorySwitch(\"' + str(shape) +
                              '\",false)')
            cacheNode = pm.cacheFile(f=cacheFiles[i],
                                     cnm=str(shape),
                                     ia='%s.inp[0]' % switch,
                                     attachFile=True,
                                     dir=ncachePath)
            pm.setAttr('%s.playFromCache' % switch, 1)
            i += 1
Example #59
0
def mentalraySetupSoftblast():
    # sampling
    pm.setAttr("miDefaultOptions.maxRefractionRays", 0)
    pm.setAttr("miDefaultOptions.maxRayDepth", 6)
    # motionblur
    pm.setAttr("miDefaultOptions.motionBlur", 2)
    pm.setAttr("miDefaultOptions.motionBlurShadowMaps", True)
    # shadow
    pm.setAttr("miDefaultOptions.maxShadowRayDepth", 3)
    pm.setAttr("miDefaultOptions.shadowMethod", 1)
    pm.setAttr("miDefaultOptions.shadowMaps", 1)
Example #60
0
def RigFKIK(jnts=None,
            side='L',
            mode='arm',
            footRotate=None,
            rigHandOrFoot=False,
            ctrlSize=1.0,
            mirrorMode=False,
            poleVectorTransform=None):

    if not jnts:
        jnts = pm.ls(sl=True)
    else:
        jnts = pm.ls(jnts)

    if mode == 'arm':
        limbName = 'hand'
        secondLimb = 'elbow'
        optionCrv = HandCrv
    elif mode == 'leg':
        limbName = 'foot'
        secondLimb = 'knee'
        optionCrv = FootCrv
    else:
        pm.error(
            'ehm_tools...rigFKIK: mode argument must be either "arm" or "leg"!'
        )

    uparmJnt = jnts[0]

    handJnt = jnts[2]

    # FK
    FKjnt = pm.duplicate(uparmJnt)[0]
    FKjnts = GetAllChildren(FKjnt)
    SearchReplaceNames('jnt', 'FK_jnt', FKjnts)
    FKjnts[0].rename(FKjnts[0].name()[:-1])
    FKshapes = RigFK(jnts=FKjnts[:2], side=side)
    FKshapes.append(RigFK(jnts=FKjnts[2:-1], stretch=False, side=side))
    NoJointInViewport(FKjnts)

    # IK
    IKjnt = pm.duplicate(uparmJnt)[0]
    IKjnts = GetAllChildren(IKjnt)
    SearchReplaceNames('jnt', 'IK_jnt', IKjnts)
    IKjnts[0].rename(IKjnts[0].name()[:-1])
    IKjnts = pm.ls(IKjnts, jnts[-3:])
    IKstuff = RigIK(jnts=IKjnts,
                    side=side,
                    mode=mode,
                    mirrorMode=mirrorMode,
                    poleVectorTransform=poleVectorTransform,
                    footRotate=footRotate,
                    rigHandOrFoot=rigHandOrFoot,
                    ctrlSize=1.0)
    IKjnts[0].v.set(False)
    pm.setAttr(IKjnts[0].v, lock=True)

    # Fingers Ctrl which is FKIK control as well
    fingersCtrl = optionCrv(name='%s_fingers_ctrl' % side)

    # find color of the ctrls
    color = 'y'
    if side == 'L':
        color = 'r'
    elif side == 'R':
        color = 'b'

    Colorize(shapes=fingersCtrl.getShape(), color=color)
    fingerCtrlZO = ZeroGrp(fingersCtrl)
    pm.addAttr(fingersCtrl, ln="FKIK", at="double", min=0, max=1, dv=0, k=True)
    fingerCtrlZO[0].translate.set(pm.xform(IKstuff[0], q=True, t=True,
                                           ws=True))

    if side == 'L' and mode == 'leg':
        fingersCtrl.translateX.set(ctrlSize)
    elif side == 'R':
        fingersCtrl.translateX.set(-ctrlSize)
        ReverseShape(fingersCtrl, 'x')
    pm.parentConstraint(handJnt, fingerCtrlZO[0], mo=True)

    # blend FK IK joints
    for j in range(4):
        for att in ('rotate', 'scale'):
            BlendAttrs(IKjnts[j].attr(att), FKjnts[j].attr(att),
                       jnts[j].attr(att), fingersCtrl.FKIK)

    BlendAttrs(0, 1, FKjnts[0].v, fingersCtrl.FKIK)
    BlendAttrs(1, 0, IKstuff[0].v, fingersCtrl.FKIK)
    BlendAttrs(1, 0, IKstuff[1].v, fingersCtrl.FKIK)

    LockHideAttr(objs=(FKjnts, IKstuff[0], IKstuff[1]), attrs='v')

    # clean up
    FKIKgrp = pm.group(jnts[0],
                       IKstuff[-1],
                       FKjnts[0],
                       fingerCtrlZO[0],
                       name='%s_%s_grp' % (side, mode))

    return (FKjnts, IKjnts, IKstuff, fingersCtrl, FKIKgrp)