Exemplo n.º 1
1
def CentreUVs():
	objSel = cmds.ls(sl=True)
	
	try:
		for item, x in enumerate(objSel):
			cmds.select('%s.map[*]' %objSel[item])
			mm.eval("PolySelectConvert 4;")
			mm.eval('TranslateToolWithSnapMarkingMenu')
			objPiv = cmds.getAttr('%s.uvPivot' %objSel[0])
			mm.eval('MarkingMenuPopDown')
			objCenterU = 0.5 - objPiv[0][0]
			objCenterV = 0.5 - objPiv[0][1]
			cmds.polyEditUV(u=objCenterU, v=objCenterV, r=1)
			cmds.select(objSel)
	except ValueError:
	
		objQuery = cmds.listRelatives(objSel[0], ap=True)
		cmds.select('%s.map[*]' %objQuery[0])
		mm.eval("PolySelectConvert 4;")
		mm.eval('TranslateToolWithSnapMarkingMenu')
		objPiv = cmds.getAttr('%s.uvPivot' %objQuery[0])
		mm.eval('MarkingMenuPopDown')
		objCenterU = 0.5 - objPiv[0][0]
		objCenterV = 0.5 - objPiv[0][1]
		cmds.polyEditUV(u=objCenterU, v=objCenterV, r=1)
		cmds.select(objQuery)
Exemplo n.º 2
0
def setToDefault(ctrl):
    """
	Set the attributes of the specified control to default values
	@param ctrl: The control to set default attribute values for
	@type ctrl: str
	"""
    # Check control
    if not mc.objExists(ctrl):
        raise Exception('Control "' + ctrl + '" does not exist!')

        # Define standard transform controls
    tAttr = ["tx", "ty", "tz"]
    rAttr = ["rx", "ry", "rz"]
    sAttr = ["sx", "sy", "sz"]

    # Get user defined attrs
    udAttr = mc.listAttr(ctrl, ud=True)

    # Reset to defaults
    for attr in tAttr:
        if mc.getAttr(ctrl + "." + attr, se=True):
            mc.setAttr(ctrl + "." + attr, 0.0)
    for attr in rAttr:
        if mc.getAttr(ctrl + "." + attr, se=True):
            mc.setAttr(ctrl + "." + attr, 0.0)
    for attr in sAttr:
        if mc.getAttr(ctrl + "." + attr, se=True):
            mc.setAttr(ctrl + "." + attr, 1.0)
    for attr in udAttr:
        dv = mc.addAttr(ctrl + "." + attr, q=True, dv=True)
        if mc.getAttr(ctrl + "." + attr, se=True):
            mc.setAttr(ctrl + "." + attr, dv)
Exemplo n.º 3
0
 def changeNumberOfJoints(self, *args):
     self.blueprint_UI_instance.deleteScriptJob()
     
     joints = self.getJoints()
     numJoints = len(joints)
     newNumJoints = cmds.intField(self.numberOfJointsField, q=True, value=True)
     
     startPos = cmds.xform(self.getTranslationControl(joints[0]), q=True, ws=True, t=True)
     endPos = cmds.xform(self.getTranslationControl(joints[numJoints-1]), q=True, ws=True, t=True)
     
     hookObject = self.findHookObjectForLock()
     
     rotationOrder = cmds.getAttr(joints[0] + ".rotateOrder")
     sao_local = cmds.getAttr(self.moduleNamespace+":module_grp.sao_local")
     sao_world = cmds.getAttr(self.moduleNamespace+":module_grp.sao_world")
     
     self.delete()
     
     newInstance = Spline(self.userSpecifiedName, hookObject, newNumJoints, startPos, endPos)
     newInstance.install()
     # We have to refer to the new instance stored in memory
     newJoints = newInstance.getJoints()
     
     cmds.setAttr(newJoints[0]+".rotateOrder", rotationOrder)
     
     cmds.setAttr(newInstance.moduleNamespace+":module_grp.sao_local", sao_local)
     cmds.setAttr(newInstance.moduleNamespace+":module_grp.sao_world", sao_world)
     
     self.blueprint_UI_instance.createScriptJob()
     
     cmds.select(newInstance.moduleNamespace+":module_transform", replace=True)
Exemplo n.º 4
0
    def switchFromUI(self, ctrl):
        """
        Switch a spaces nodes to the specified target from the spaces UI
        @param ctrl: Control whose spaces target will be switched
        @type ctrl: str
        """
        # Determine spaces node
        spacesNode = self.getSpacesNode(ctrl)
        tag = cmds.getAttr(spacesNode + '.nameTag')

        # Query Target
        # !!! optionMenu command no longer allows access to attrEnumOptionMenu !!!
        # target = cmds.optionMenu(tag+'_switchAEO',q=True,v=True)
        targetIndex = cmds.getAttr(cmds.attrEnumOptionMenu(tag + '_switchAEO', q=True, dtg=True))
        target = self.targetList(spacesNode)[targetIndex]

        # Check keyframe options
        key = cmds.checkBoxGrp(self.uiKeyCBG, q=True, v1=True)
        keyPrevious = cmds.checkBoxGrp(self.uiKeyPreviousCBG, q=True, v1=True)

        # Check offset options
        maintainPos = cmds.checkBoxGrp(self.uiMaintainPosCBG, q=True, v1=True)

        # Do switch
        self.switch(ctrl, target, key, keyPrevious, maintainPos)
Exemplo n.º 5
0
def setRotate_keepJointOrient( mtx, jnt ):
    jntP = cmds.listRelatives( jnt, p=1 )[0]
    joValue = cmds.getAttr( jnt+'.jo' )[0]
    joMEuler = om.MEulerRotation( math.radians( joValue[0] ), math.radians( joValue[1] ), math.radians( joValue[2] ) )
    joTransform = mpx.MPxTransformationMatrix( om.MMatrix() )
    joTransform.rotateBy( joMEuler )
    jo_im = joTransform.asMatrixInverse()
        
    jntP_wim_list = cmds.getAttr( jntP+'.wim' )
    jntP_wim = om.MMatrix()
    om.MScriptUtil.createMatrixFromList( jntP_wim_list, jntP_wim )
        
    cuMtx = mtx*jntP_wim*jo_im
        
    transform = mpx.MPxTransformationMatrix( cuMtx )
    rot = transform.eulerRotation().asVector()
    
    degrees = [math.degrees( rot.x ), math.degrees( rot.y ), math.degrees( rot.z )]
    
    for i in range( len( degrees ) ):
        if degrees[i] > 180:
            degrees[i] = degrees[i]-360
        elif degrees[i] < -180:
            degrees[i] = degrees[i]+360
    cmds.setAttr( jnt+'.r', *degrees )
Exemplo n.º 6
0
 def removeFloatVariable(self, nodeAttr, varslayout, index):
    # Remove variable
    children = cmds.columnLayout(varslayout, query=1, childArray=1)
    
    if len(children) <= index:
       return
    
    baseNameAttr = nodeAttr
    baseValueAttr = nodeAttr.replace("fparam_name", "fparam_value");
    
    for i in xrange(index+1, len(children)):
       rembtn, namefld, _, valfld = cmds.formLayout(children[i], query=1, childArray=1)
       
       indexStr = "[%d]" % (i - 1)
       nextIndexStr = "[%d]" % i
       
       nameAttr = baseNameAttr + indexStr
       valueAttr = baseValueAttr + indexStr
       
       cmds.setAttr(nameAttr, cmds.getAttr(baseNameAttr + nextIndexStr), type="string")
       cmds.setAttr(valueAttr, cmds.getAttr(baseValueAttr + nextIndexStr));
       
       self.setupVariableNameCallback(nameAttr, namefld)
       self.setupFloatVariableValueCallback(valueAttr, valfld)
       cmds.button(rembtn, edit=1, command=lambda *args: self.removeFloatVariable(nodeAttr, varslayout, i-1))
    
    cmds.deleteUI(children[index])
    
    cmds.removeMultiInstance("%s[%d]" % (baseNameAttr, len(children)-1), b=True)
    cmds.removeMultiInstance("%s[%d]" % (baseValueAttr, len(children)-1), b=True)
Exemplo n.º 7
0
def printCurvePoints():
    """
    Use: For printing to the console or write out to a file, the points of a new custom curve.
    This can be added to the curve Dictionary for quickly building more curves for all rigging tools using the curve Dictionary.
    @param toFile: if you would like to output the points to a text file in your home folder or not
    @type toFile: Boolean
    """
    curvePoints = []
    curSel = cmds.ls(sl = True)
    if not curSel:
        cmds.warning('Nothing selected for export.')
        pass
    else:
        for nurbsCurve in curSel:
            getDegree = cmds.getAttr(nurbsCurve + '.degree')
            getSpans = cmds.getAttr(nurbsCurve + '.spans')
            numPoints = int(getDegree) + int(getSpans)
            for x in range (numPoints):
                getWS = cmds.xform(nurbsCurve + '.cv[%s]' % x, query = True, t = True, ws = True)
                tempVar = []
                for p in getWS:
                    tempVar.append("{0:.2f}".format(p))
                curvePoints.append(tempVar)
                tempVar = []
            numKnots = numPoints + getDegree -1

        sys.stdout.write('cmds.curve(name = "' + str(curSel[0]) + '", d = ' + str(getDegree) + ', p = ' + str(curvePoints) + ')')
Exemplo n.º 8
0
    def reset(self, ctrl, key=0, keyPreviousFrame=0):
        """
        Reset spaces constraint offsets for the specified control
        @param ctrl: Control whose spaces target offset values will be rest
        @type ctrl: str
        @param key: Set keyframe after reset
        @type key: bool
        @param keyPreviousFrame: Set keyframe before reset. Only relevant when "key" is also True.
        @type keyPreviousFrame: bool
        """
        # Get spaces info
        spacesNode = self.getSpacesNode(ctrl)
        spacesNodeConstraint = self.getSpacesConstraint(ctrl)

        # Check spaces attribute
        if not cmds.objExists(spacesNode + '.spaces'):
            raise UserInputError('Object ' + spacesNode + 'does not contain a ".spaces" attribute!')
        targetIndex = cmds.getAttr(spacesNode + '.spaces')
        target = self.targetList(ctrl)[targetIndex]

        # Key previous frame
        if keyPreviousFrame: self.key(ctrl, [], cmds.currentTime(q=True) - 1, )

        # Reset Offset Values
        translateOffset = cmds.getAttr(spacesNode + '.defaultOffset[' + str(targetIndex) + '].dot')[0]
        rotateOffset = cmds.getAttr(spacesNode + '.defaultOffset[' + str(targetIndex) + '].dor')[0]
        cmds.setAttr(spacesNode + '.tot', translateOffset[0], translateOffset[1], translateOffset[2])
        cmds.setAttr(spacesNode + '.tor', rotateOffset[0], rotateOffset[1], rotateOffset[2])

        # Key current frame
        if key: self.key(ctrl)
Exemplo n.º 9
0
def copy_user_attr(selparentshapes, seltargetshapes, copyUV=True):
    listattrvalue = {}
    listdatatype = {}
    userattr = cmds.listAttr(selparentshapes, ud=True)
    if copyUV and cmds.nodeType(seltargetshapes) == 'mesh' and cmds.nodeType(selparentshapes) == 'mesh':
            cmds.transferAttributes(selparentshapes, seltargetshapes, transferUVs=1, transferColors=2, searchMethod=3, sampleSpace=5, flipUVs=False)
    if userattr:
        for attr in userattr:
            nodetype = cmds.nodeType(selparentshapes)
            checkrendershape = cmds.getAttr(selparentshapes + '.intermediateObject')
            if checkrendershape != 1 or nodetype != 'mesh':
                key = attr
                value = cmds.getAttr("%s.%s" % (selparentshapes, key))
                data = cmds.getAttr("%s.%s" % (selparentshapes, key), typ=True)
                listattrvalue[key] = value
                listdatatype[key] = data
    checkrendershape = cmds.getAttr(seltargetshapes + '.intermediateObject')
    if checkrendershape != 1:
        for key in listattrvalue:
            if not cmds.attributeQuery(key, node=seltargetshapes, ex=True):
                if listdatatype[key] == 'string':
                    cmds.addAttr(seltargetshapes, longName=key, dataType=listdatatype[key])
                    cmds.setAttr("%s.%s" % (seltargetshapes, key), listattrvalue[key], type=listdatatype[key])
                else:
                    cmds.addAttr(seltargetshapes, longName=key)
                    cmds.setAttr("%s.%s" % (seltargetshapes, key), listattrvalue[key])
            else:
                cmds.warning('Attribute ' + key + ' already on ' + seltargetshapes)
                if cmds.getAttr("%s.%s" % (seltargetshapes, key), se=True):
                    if listdatatype[key] == 'string':
                        cmds.setAttr("%s.%s" % (seltargetshapes, key), listattrvalue[key], type=listdatatype[key])
                    else:
                        cmds.setAttr("%s.%s" % (seltargetshapes, key), listattrvalue[key])
Exemplo n.º 10
0
	def apply( self, mapping, **kwargs ):
		'''
		construct a mel string to pass to eval - so it can be contained in a single undo...
		'''
		cmdQueue = api.CmdQueue()

		#gather options...
		additive = kwargs.get( self.kOPT_ADDITIVE,
							   self.kOPT_DEFAULTS[ self.kOPT_ADDITIVE ] )

		for clipObj, tgtObj in mapping.iteritems():
			try:
				attrDict = self[ clipObj ]
			except KeyError: continue

			for attr, value in attrDict.iteritems():
				attrpath = '%s.%s' % (tgtObj, attr)
				try:
					if not cmd.getAttr( attrpath, settable=True ): continue
				except TypeError: continue

				if additive: value += cmd.getAttr( attrpath )
				cmdQueue.append( 'setAttr -clamp %s %s;' % (attrpath, value) )

		cmdQueue()
Exemplo n.º 11
0
def getNodesOverload(poseObj, nodes, *args):

    # NOTE: poseObj already has an attr 'metaRig' which is filled
    # automatically in the main buildInternalPoseData() call
    metaNode = poseObj.metaRig
    currentSelection = cmds.ls(sl=True, l=True)
    filteredNodes = []

    if not issubclass(type(metaNode), r9Meta.MetaHIKControlSetNode):
        # see if we have a left or right controller selected and switch to the
        # appropriate subMetaSystem

        if cmds.getAttr('%s.mirrorSide' % currentSelection[0]) == 1:
            print '\nFinger : PoseOverload Handler : %s >> side: Left' % metaNode
            filteredNodes = metaNode.L_ArmSystem.L_FingerSystem.getChildren()
            [filteredNodes.append(node) for node in cmds.listRelatives(filteredNodes, type='joint', ad=True, f=True)]

        elif cmds.getAttr('%s.mirrorSide' % currentSelection[0]) == 2:
            print '\nFinger : PoseOverload Handler : %s >> side: Right' % metaNode
            filteredNodes = metaNode.R_ArmSystem.R_FingerSystem.getChildren()
            [filteredNodes.append(node) for node in cmds.listRelatives(filteredNodes, type='joint', ad=True, f=True)]
    else:
        if currentSelection[0] == metaNode.LeftWristEffector or currentSelection[0] == metaNode.LeftHand:
            [filteredNodes.append(node) for node in cmds.listRelatives(metaNode.LeftHand, type='joint', ad=True, f=True)]
        elif currentSelection[0] == metaNode.RightWristEffector or currentSelection[0] == metaNode.RightHand:
            [filteredNodes.append(node) for node in cmds.listRelatives(metaNode.RightHand, type='joint', ad=True, f=True)]

    # modify the actual PoseData object, changing the data to be matched on index
    # rather than using the standard name or metaMap matching
    poseObj.metaPose = False
    poseObj.matchMethod = 'index'

    return filteredNodes
def maya_move(angular_velocity, time_step):
            
    objects = cmds.ls(sl=True)
    if objects == []:
        print('* Please select at least an object.')
        return
        
    trajectory = cmds.ls('trajectory')
    
    for i, o in enumerate(objects):
        x = cmds.getAttr(o + '.translateX')
        y = cmds.getAttr(o + '.translateY')
        z = cmds.getAttr(o + '.translateZ')
    
        loc = [x, y, z]
        state = make_state(loc)
                
        state = simulate_circle(state, angular_velocity, time_step)
        
        old_loc = loc
        loc = get_location(state)
        
        cmds.select(o)
        cmds.move(loc[0], loc[1], loc[2])
        
        # draw trajectory for the first object
        if i == 0:
            if trajectory == []:
                cv = cmds.curve(point=[old_loc, loc], degree=1)                
                cmds.rename(cv, 'trajectory')
            else:
                cmds.curve('trajectory', point=[loc], degree=1, append=True)
        
    # keep all objects selected
    cmds.select(objects)
Exemplo n.º 13
0
 def create_ik_arm_stretch(self):
     """Creates the IK stretch setup."""
     arm_dist, start_loc, end_loc = self.c.distance_node(self.guides['upperArm'], self.guides['hand'])
     arm_dist = cmds.rename(arm_dist, '%s_%s_%s' % (self.side, 'arm', self.nc.distance))
     start_loc = cmds.rename(start_loc, '%s_%s_%s' % (self.side, 'armLengthStart', self.nc.locator))
     end_loc = cmds.rename(end_loc, '%s_%s_%s' % (self.side, 'armLengthEnd', self.nc.locator))
     cmds.parent(end_loc, self.controls['handik'])
     cmds.parent(arm_dist, self.top_grp)
     driver = '%sShape.distance' % arm_dist
     if self.side == 'R':
         mult = cmds.shadingNode('multiplyDivide', asUtility=True)
         mult = cmds.rename(mult, '%s_%s_stretch_negative_MDN' % (self.side, 'arm'))
         cmds.connectAttr('%sShape.distance' % arm_dist, '%s.input1X' % mult, f=True)
         cmds.setAttr('%s.input2X' % mult, -1)
         driver = '%s.outputX' % mult
     # END if
     upper_arm_len = cmds.getAttr('%s.tx' % self.ik_jnts[1])
     fore_arm_len = cmds.getAttr('%s.tx' % self.ik_jnts[2])
     sum_len = upper_arm_len + fore_arm_len
     cmds.setDrivenKeyframe('%s.translateX' % self.ik_jnts[1], cd=driver,
                            dv=sum_len, itt='linear', ott='linear')
     cmds.setDrivenKeyframe('%s.translateX' % self.ik_jnts[1], cd=driver,
                            dv=sum_len*2, v=upper_arm_len*2, itt='linear', ott='linear')
     cmds.setDrivenKeyframe('%s.translateX' % self.ik_jnts[2], cd=driver,
                            dv=sum_len, itt='linear', ott='linear')
     cmds.setDrivenKeyframe('%s.translateX' % self.ik_jnts[2], cd=driver,
                            dv=sum_len*2, v=fore_arm_len*2, itt='linear', ott='linear')
     cmds.setAttr('%s_translateX.postInfinity' % self.ik_jnts[1], 1)
     cmds.setAttr('%s_translateX.postInfinity' % self.ik_jnts[2], 1)
     # stretch the result joints
     curve = '%s_%s_%s' % (self.side, 'upperArm', self.nc.curve)
     self.stretch_result_joints(curve, 'upperArm', self.upper_arm_jnts)
     curve = '%s_%s_%s' % (self.side, 'foreArm', self.nc.curve)
     self.stretch_result_joints(curve, 'foreArm', self.fore_arm_jnts)
Exemplo n.º 14
0
    def get_num_cvs(self, curve):
        '''
        Desc:
        Get cvs lenght from a curve

        Parameter:
        curve = curve to get cvs positin list from
        coords_space = the coordinat space, can be "world" (default), or "local"

        Return:
        list with positions
        '''

        # If curve is nod define or not correct release error
        if curve:
            # Get curve shape
            curve_shape = KstMaya.get_shape_node(curve)

            # Get degree
            degree = cmds.getAttr(curve_shape+".degree")

            # Get spans
            spans = cmds.getAttr(curve_shape+".spans")

            # Calulating ncvs with formula spans+degree
            ncvs = spans+degree

            # Return the list
            return ncvs
        else:
            cmds.warning("Curve %s,  is not defined, or is not a curve, double check!" % curve)
            return None
Exemplo n.º 15
0
def reset_pack():

    # pack is global
    global pack

    # IF pack exists
    if( len( pack ) ):

        # Loop through the pack
        for agent in pack:

            # Reset local position and heading to initial values
            cmds.setAttr( agent.animalName+".translateX", cmds.getAttr( agent.animalName+".initialPositionX" ) )
            cmds.setAttr( agent.animalName+".translateY", cmds.getAttr( agent.animalName+".initialPositionY" ) )
            cmds.setAttr( agent.animalName+".translateZ", cmds.getAttr( agent.animalName+".initialPositionZ" ) )
            cmds.setAttr( agent.animalName+".rotateY", cmds.getAttr( agent.animalName+".initialHeading" ) )
            cmds.setAttr( agent.animalName+".speed", cmds.getAttr( agent.animalName+".initialSpeed" ) )

            # Reset class specific variables
            agent.target = 0
            agent.wingAngle = 0

            # Reset awareness state
            agent.state = HuntingState.prowling

            # Reset state based attributes
            agent.set_speed_and_colour()
Exemplo n.º 16
0
 def __init__(self, name):
     Obj.__init__(self, name)
     self.resx = mc.getAttr('defaultResolution.width')
     self.resy = mc.getAttr('defaultResolution.height')
     self.aperture = mc.getAttr("%s.hfa" % self.name) * 25.4
     self.interaxial = mc.getAttr('%s.isep' % self.name)
     self.ZPS = mc.getAttr('%s.zp' % self.name)
Exemplo n.º 17
0
 def _mirror_setFollowValues(self):
     for target in self.__followTargets:
         if target.find( 'Collar' ) != -1:
             otherTarget = target.replace( 'Collar_L', 'Arm_L_PoleV' ).replace( 'Collar_R', 'Arm_R_PoleV' )
             mtxList = cmds.getAttr( otherTarget+'.wm' )
         elif target.find( 'Leg' ) != -1:
             poleVTarget = target.replace( 'Switch_CTL', 'PoleV_CTL' )
             poleVMtxList = cmds.getAttr( poleVTarget+'.wm' )
             mtxList = cmds.getAttr( target.replace( 'Switch', 'IK' )+'.wm' )
         else:
             mtxList = cmds.getAttr( target.replace( 'Switch', 'IK' )+'.wm' )
         
         index = self.__followTargets.index( target )
         udAttrs = cmds.listAttr( target, ud=1 )
         
         for attr in udAttrs:
             if attr.find( 'Follow' ) != -1:
                 cmds.setAttr( target+'.'+attr, self.__followValues[index].pop(0) )
                 
         if target.find( 'Switch' ) != -1: target = target.replace( 'Switch', 'IK' )
         elif target.find( 'Collar' ) != -1:
             target = target.replace( 'Collar_L', 'Arm_L_PoleV' ).replace( 'Collar_R', 'Arm_R_PoleV' )
         
         cmds.xform( target, ws=1, matrix = mtxList )
         if cmds.nodeType( target ) == 'joint':
             rigbase.setRotate_keepJointOrient( mtxList, target )
             
         if target.find( 'Leg' ) != -1:
             cmds.xform( poleVTarget, ws=1, matrix = poleVMtxList )
Exemplo n.º 18
0
    def goToObject(self, first, second, *args ):
        
        if cmds.nodeType( first ) == 'joint':
            
            jo = cmds.getAttr( first+'.jo' )[0]
            mpxTransform = mpx.MPxTransformationMatrix()
            rotVector = om.MVector( math.radians( jo[0] ), math.radians( jo[1] ), math.radians( jo[2] ) ) 
            mpxTransform.rotateTo( om.MEulerRotation( rotVector ) )
            joMtx = mpxTransform.asMatrix()
            
            fMtx = om.MMatrix()
            fPMtx = om.MMatrix()
            fMtxList = cmds.getAttr( first+'.wm' )
            fPMtxList = cmds.getAttr( first+'.pm' )
            sMtx = om.MMatrix()
            sMtxList = cmds.getAttr( second+'.wm' )
            
            om.MScriptUtil.createMatrixFromList( fMtxList, fMtx )
            om.MScriptUtil.createMatrixFromList( fPMtxList, fPMtx )
            om.MScriptUtil.createMatrixFromList( sMtxList, sMtx )
            
            sMtxPose = [ sMtx(3,0), sMtx(3,1), sMtx(3,2) ]
            
            rMtx = sMtx*(joMtx*fPMtx).inverse()
            rTransform = mpx.MPxTransformationMatrix( rMtx )
            rVector = rTransform.eulerRotation().asVector()
            
            rot = [ math.degrees( rVector.x ), math.degrees( rVector.y ), math.degrees( rVector.z ) ]

            cmds.setAttr( first+'.r', *rot )
            cmds.move( sMtxPose[0], sMtxPose[1], sMtxPose[2], first, ws=1 )

        else:
            rigbase.goToSamePosition( first, second )
Exemplo n.º 19
0
    def __init__( self, fullAttrName ):
        
        self.className = 'AnimCurveForBake'
        
        nodeName, attr = fullAttrName.split( '.' )
        attrType = cmds.attributeQuery( attr, node=nodeName, attributeType=1 )
        
        self.nodeType = ''
        if attrType == 'doubleLinear':
            self.nodeType = 'animCurveTL'
        elif attrType == 'doubleAngle':
            self.nodeType = 'animCurveTA'
        else:
            self.nodeType = 'animCurveTU'

        self.attrName     = fullAttrName
        self.times  = []
        self.values = []

        self.connectionExists = True
        if not cmds.listConnections( fullAttrName, s=1, d=0 ):
            node, attr = fullAttrName.split( '.' )
            parentAttrs = cmds.attributeQuery( attr, node=node, listParent=1 )
            if parentAttrs:
                if cmds.listConnections( node+'.'+parentAttrs[0] ):pass
                else:
                    self.connectionExists = False
                    self.times.append( 1 )
                    self.values.append( cmds.getAttr( fullAttrName ) )
            else:
                self.connectionExists = False
                self.times.append( 1 )
                self.values.append( cmds.getAttr( fullAttrName ) )
Exemplo n.º 20
0
 def _mirror_setFollowDefault(self):
     for target in self.__followTargets:
         if target.find( 'Collar' ) != -1:
             otherTarget = target.replace( 'Collar_L', 'Arm_L_PoleV' ).replace( 'Collar_R', 'Arm_R_PoleV' )
             mtxList = cmds.getAttr( otherTarget+'.wm' )
         elif target.find( 'Leg' ) != -1:
             poleVTarget = target.replace( 'Switch_CTL', 'PoleV_CTL' )
             poleVMtxList = cmds.getAttr( poleVTarget+'.wm' )
             mtxList = cmds.getAttr( target.replace( 'Switch', 'IK' ) +'.wm' )
         else:
             mtxList = cmds.getAttr( target.replace( 'Switch', 'IK' ) +'.wm' )
         
         udAttrs = cmds.listAttr( target, ud=1 )
         for attr in udAttrs:
             if attr.find( 'Follow' ) != -1:
                 case1 = target.find( 'Arm' ) != -1 and attr == 'collarFollow'
                 case2 = target.find( 'Leg' ) != -1 and attr == 'hipFollow'
                 case3 = attr == 'neckFollow'
                 if case1 or case2 or case3:
                     cmds.setAttr( target+'.'+attr, 10 )
                 else:
                     cmds.setAttr( target+'.'+attr, 0 )
                     
         if target.find( 'Switch' ) != -1: target = target.replace( 'Switch', 'IK' )
         elif target.find( 'Collar' ) != -1:
             target = target.replace( 'Collar_L', 'Arm_L_PoleV' ).replace( 'Collar_R', 'Arm_R_PoleV' )
         cmds.xform( target, ws=1, matrix = mtxList )
         if cmds.nodeType( target ) == 'joint':
             rigbase.setRotate_keepJointOrient(mtxList, target)
         
         if target.find( 'Leg' ) != -1:
             cmds.xform( poleVTarget, ws=1, matrix = poleVMtxList )
Exemplo n.º 21
0
Arquivo: goe.py Projeto: jonntd/Public
def setAttr(*args, **kwargs):
    """
    @type  args: *args
    @param args: specify nodes as you would do usually with maya cmds
    """
    assert args, "Please specify an existing node and attr."
    assert cmds.objExists(args[0]), "Please specify an existing node and attr."

    #--- vars
    check = False
    obj = args[0].split('.')[0]
    attr = args[0].split('.')[1]

    #--- unlock the attributes
    compound = cmds.attributeQuery(attr, node=obj, listChildren=True)
    if compound:
        for c in compound:
            if cmds.getAttr(obj + '.' + c, lock=True):
                attribute.lock_n_hide(obj, [c], True)
                check = True
    else:
        if cmds.getAttr(args[0], lock=True):
            attribute.lock_n_hide(obj, [attr], True)
            check = True

    #--- set attribute
    try:
        cmds.setAttr(args[0], args[1], args[2], args[3])
    except:
        cmds.setAttr(args[0], args[1])

    #--- lock the attribute
    if check:
        attribute.lock_n_hide(obj, [attr])
Exemplo n.º 22
0
	def getShaderInfo(self):
		# What material is connected to this shapeNode
		# shapeNode.ShaderMaterial
		# cmds.getAttr( "pCubeShape6.ShaderMaterial", asString=True )
		if( cmds.objExists( "%s.ShaderMaterial" %self.nodeName) ):
			# self.material = cmds.getAttr( "%s.ShaderMaterial" %self.nodeName, asString=True)
			self.material = cmds.getAttr( "%s.ShaderMaterial" %self.nodeName)
		else:
			self.material = ""
		'''
		# find the text file associated with the material.
		# What if they don't include a texture file?
		inputs = cmds.listConnections( source=True )
		files = cmds.ls( inputs, type="file" )
		fileNames = []
		for fn in files:
		    # setAttr -type "string" file1.fileTextureName "c.tga";
		    textureName = cmds.getAttr( "%s.fileTextureName" %fn )
		    fileNames.append( textureName )		
		'''
		
		# self.fileInfo = {}
				
		for i, uvSet in enumerate(self.sets):
			# cmds.uvLink( query=True, uvSet='pCubeShape2.uvSet[0].uvSetName' )
			files = cmds.uvLink( query=True, uvSet='%s.uvSet[%s].uvSetName' %(self.nodeName, i) )
			if(files):
				self.fileInfo[uvSet] = [cmds.getAttr( "%s.fileTextureName" %curFile) for curFile in files ]
Exemplo n.º 23
0
def returnClosestPointOnMeshInfo(targetObj, mesh):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Returns pertinent info of the closest point of a mesh to a target object -
    position, normal, parameterU,parameterV,closestFaceIndex,closestVertexIndex

    ARGUMENTS:
    targetObj(string)
    mesh(string)

    RETURNS:
    closestPointInfo(dict)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """

    """ make the closest point node """
    closestPointNode = mc.createNode ('closestPointOnMesh')
    controlSurface = mc.listRelatives(mesh,shapes=True)

    """ to account for target objects in heirarchies """
    attributes.doConnectAttr((targetObj+'.translate'),(closestPointNode+'.inPosition'))
    attributes.doConnectAttr((controlSurface[0]+'.worldMesh'),(closestPointNode+'.inMesh'))
    attributes.doConnectAttr((controlSurface[0]+'.matrix'),(closestPointNode+'.inputMatrix'))

    pointInfo = {}
    pointInfo['position']=attributes.doGetAttr(closestPointNode,'position')
    pointInfo['normal']=attributes.doGetAttr(closestPointNode,'normal')
    pointInfo['parameterU']=mc.getAttr(closestPointNode+'.parameterU')
    pointInfo['parameterV']=mc.getAttr(closestPointNode+'.parameterV')
    pointInfo['closestFaceIndex']=mc.getAttr(closestPointNode+'.closestFaceIndex')
    pointInfo['closestVertexIndex']=mc.getAttr(closestPointNode+'.closestVertexIndex')

    mc.delete(closestPointNode)
    return pointInfo
def check_transforms(objects):
    '''
    Check joints to insure they have no rotation values.
    '''
    
    invalid = []
    cmds.select(objects)
    new_objects = cmds.pickWalk(d='up')
    t_r_xform = ['t', 'r']
    scale_xform = 's'
    axis = ['x', 'y', 'z']
    

    for obj in new_objects:
        #check translates rotates and scales
        for trans in t_r_xform:
            #check each axis
            for ax in axis:
                trans_rot = cmds.getAttr('%s.%s%s' % (obj, trans, ax))
                
                if trans_rot != 0:
                    invalid.append(obj)
                    break
                
            for ax in axis:
                scale = cmds.getAttr('%s.%s%s' % (obj, scale_xform, ax))
                
                if scale != 1:
                    invalid.append(obj)
                    break
          
    return invalid
Exemplo n.º 25
0
def getComponent(textureNode, component='color'):

    if not 'dead_space' in cmds.getAttr(textureNode+'.fileTextureName'):
        cmds.warning('Cannot create component beacause this is not a  DS texture.')

    if not component in ('color', 'normal', 'specular'):
        cmds.warning("Please put one of the following component: 'color', 'normal', 'specular'")

    texturePath = cmds.getAttr(textureNode+'.fileTextureName')
    textureComponent = os.path.dirname(texturePath).split('/')[-1]

    if textureComponent == component:
        cmds.warning('You are trying to get the same component as the texture selected.')

    componentPath = os.path.dirname(texturePath).replace(textureComponent, component)
    if os.path.exists(componentPath):
        originalComp = COMPS[textureComponent]
        replaceComp = COMPS[component]
    else:
        cmds.warning('Cannot find component path.')
    componentTexturePath = componentPath+'/'+os.path.basename(texturePath).replace(originalComp, replaceComp)
    if os.path.isfile(componentTexturePath):
        return componentTexturePath
    else:
        #cmds.warning('Cannot find component texture file.')
        return None
Exemplo n.º 26
0
	def grow(self):
		scaleX = cmds.getAttr("%s.scaleX"%self.sphere)
		scaleZ = cmds.getAttr("%s.scaleZ"%self.sphere)
		newScaleX = scaleX * 1.5
		newScaleZ = scaleZ * 1.5
		cmds.setAttr("%s.scaleX"%self.sphere, newScaleX)
		cmds.setAttr("%s.scaleZ"%self.sphere, newScaleZ)
Exemplo n.º 27
0
def writeSetAttrCmd( trigger, connectIdxs=None ):
	cmdToks = []
	assert isinstance( trigger, Trigger )

	if connectIdxs is None:
		connectIdxs = [ idx for _,idx in trigger.connects() ]

	#make sure the zeroth connect isn't in the list and remove duplicates
	connectIdxs = removeDupes( connectIdxs )
	if 0 in connectIdxs:
		connectIdxs.remove( 0 )

	for connectIdx in connectIdxs:
		obj = trigger[connectIdx]
		attrs = cmd.listAttr( obj, k=True, s=True, v=True, m=True ) or []
		objTrigger = Trigger( obj )
		for a in attrs:
			attrPath = '%s.%s' % (obj, a)
			attrType = cmd.getAttr( attrPath, type=True )
			attrValue = cmd.getAttr( attrPath )
			if attrType.startswith( 'double' ):
				cmdToks.append( "setAttr %%%d.%s %0.5f;" % (connectIdx, a, attrValue) )
			else:
				cmdToks.append( "setAttr %%%d.%s %d;" % (connectIdx, a, attrValue) )

	return '\n'.join( cmdToks )
 def deformCharacterShapeSel(self, value):
     RN = mc.referenceQuery(self.core.skCharacter[int(value)-1], referenceNode=1)
     Nodes = mc.referenceQuery(RN, nodes=1)
     self.characterdeformShape = []
     self.allCharacterRightdeformShape = []
     for item in Nodes:
         if self.nodeTypeSelf(item) in self.shapeType:
             self.characterdeformShape.append(item)
     for each in self.characterdeformShape:
         itemP = mc.listRelatives(each, p=1)[0]
         itemPP = mc.listRelatives(itemP, p=1)
         if itemPP != None and mc.getAttr('%s.v'%itemP) != 0 and mc.getAttr('%s.v'%itemPP[0]) != 0:
             self.allCharacterRightdeformShape.append(each)
             self.allCharacterRightdeformShape.reverse()
     for item in self.allCharacterRightdeformShape:
         if mc.filterExpand( item, sm=(10,12)) == None:
             self.allCharacterRightdeformShape.remove(item)
     for item in self.allCharacterRightdeformShape:
         if item.endswith('Orig') == True:
             self.allCharacterRightdeformShape.remove(item)
     for item in self.allCharacterRightdeformShape:
         if item.endswith('Orig') == True:
             self.allCharacterRightdeformShape.remove(item)
     for item in self.allCharacterRightdeformShape:
         if item.endswith('Orig') == True:
             self.allCharacterRightdeformShape.remove(item)
     for item in self.allCharacterRightdeformShape:
         if item.endswith('Orig') == True:
             self.allCharacterRightdeformShape.remove(item)
     for item in self.allCharacterRightdeformShape:
         if item.endswith('Orig') == True:
             self.allCharacterRightdeformShape.remove(item)
     return self.allCharacterRightdeformShape
Exemplo n.º 29
0
def rebuildFromIsoparms(surface,spansU=0,spansV=0,degree=3,keepHistory=False):
	'''
	Build a new nurbs surface from an existing surfaces isoparms
	@param surface: Surface to build from
	@type surface: str
	@param direction: Surface direction to build from
	@type direction: str
	@param degree: Degree to build new surface to
	@type degree: int
	@param keepHistory: Keep loft surface history
	@type keepHistory: bool
	'''
	# Check surface
	if not mc.objExists(surface):
		raise Exception('Surface "'+surface+'" does not exist!!')
	if not isSurface(surface):
		raise Exception('Object "'+surface+'" is not a valid nurbs surface!!')
	
	# Initialize function pointers
	uMinPtr = OpenMaya.MScriptUtil().asDoublePtr()
	uMaxPtr = OpenMaya.MScriptUtil().asDoublePtr()
	vMinPtr = OpenMaya.MScriptUtil().asDoublePtr()
	vMaxPtr = OpenMaya.MScriptUtil().asDoublePtr()
	
	# Get surface details
	surfFn = getSurfaceFn(surface)
	surfFn.getKnotDomain(uMinPtr,uMaxPtr,vMinPtr,vMaxPtr)
	uMin = OpenMaya.MScriptUtil(uMinPtr).asDouble()
	uMax = OpenMaya.MScriptUtil(uMaxPtr).asDouble()
	vMin = OpenMaya.MScriptUtil(vMinPtr).asDouble()
	vMax = OpenMaya.MScriptUtil(vMaxPtr).asDouble()
	uDif = uMax - uMin
	vDif = vMax - vMin
	
	# Get surface form
	closeU = bool(mc.getAttr(surface+'.formU'))
	closeV = bool(mc.getAttr(surface+'.formV'))
	
	# Check spans
	if not spansU: spansU = surfFn.numKnotsInU()
	if not spansV: spansV = surfFn.numKnotsInV()
	
	# Get new knot values
	uList = []
	vList = []
	uInc = uDif/(spansU-int(not closeU))
	vInc = vDif/(spansV-int(not closeV))
	for u in range(spansU): uList.append(uMin+(uInc*u))
	for v in range(spansV): vList.append(vMin+(vInc*v))
	
	# Rebuild in U
	uLoft = mc.loft([surface+'.u['+str(i)+']' for i in uList],close=closeU,degree=degree)
	uSurface = uLoft[0]
	
	# Rebuld in V
	vLoft = mc.loft([uSurface+'.v['+str(i)+']' for i in vList],close=closeV,degree=degree)
	rebuildSurface = vLoft[0]
	
	# Return result
	return rebuildSurface
Exemplo n.º 30
0
def returnClosestUV (targetObject,surface):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Pass target object and surface into it and return the closest UV coordinates

    ARGUMENTS:
    targetObject(string)
    surface(string)

    RETURNS:
    UV(string)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    """ pass target object and surface into it and return the closest UV coordinates"""
    UVs = []
    """ make the node """
    tmpNode = mc.createNode ('closestPointOnSurface')
    """ to account for target objects in heirarchies """
    tmpObj = rigging.locMeObjectStandAlone(targetObject)
    mc.connectAttr ((tmpObj+'.translate'),(tmpNode+'.inPosition'))
    mc.connectAttr ((surface+'.worldSpace'),(tmpNode+'.inputSurface'))
    UVs.append (mc.getAttr (tmpNode+'.u'))
    UVs.append (mc.getAttr (tmpNode+'.v'))
    mc.delete (tmpNode)
    mc.delete (tmpObj)
    return UVs
Exemplo n.º 31
0
 def offset(self):
     '''
     simply get the offset
     '''
     return cmds.getAttr('%s.offset' % self.audioNode)
Exemplo n.º 32
0
def import_createShaveHairByObjectsAttr():
    selectedObj = cmds.ls(sl=True, l=True)
    objects = cmds.ls( selectedObj, l=True, exactType=('mesh', 'nurbsSurface', 'nurbsCurve') )
    temp = cmds.listRelatives( selectedObj, ad=True, f=True, type=('mesh', 'nurbsSurface', 'nurbsCurve') )
    if temp:
        temp = [c for c in temp if not cmds.getAttr( c+".intermediateObject") ]
        objects.extend( temp )
    objects = tuple( set(objects) )
    objects = [obj for obj in objects if cmds.attributeQuery( 'shaveData', node=obj, exists=True)  ]
    shaveDatas = {}
    for obj in objects:
        objAttr = json.loads( cmds.getAttr( obj+'.shaveData') )
        for shaveName, index, faceSet in objAttr['shaveData']:
            if not shaveDatas.has_key( shaveName ):
                shaveDatas[shaveName] = {'data':[]}
                
            if faceSet=='all':
                faceSet = [obj]
            else:
                faceSet = [obj+'.'+face for face in faceSet]            
            shaveDatas[shaveName]['data'].append( (index, faceSet) )
    if not shaveDatas:
        return
    
    shaveGrp =  '|shaveHairGroup'
    if not cmds.objExists( shaveGrp ):
        shaveGrp = cmds.group( name='shaveHairGroup', empty=True,  world=True)
           
    gMainProgressBar = mel.eval('$tmp = $gMainProgressBar')
    cmds.progressBar( gMainProgressBar, edit=True, beginProgress=True, isInterruptable=True,
                    status='Creating ShaveHair...', maxValue=len(shaveDatas.keys())  )
        
    newShaveHair = []
    for shaveName, shaveData in shaveDatas.iteritems():
        cmds.progressBar(gMainProgressBar, edit=True, step=1 )
        data = shaveData['data']    
        data.sort()
        setsObjects = []
        for objData in data:
            setsObjects.extend( objData[1] )
        cmds.select( setsObjects, r=True)
        
        presetFile = os.path.join( os.__file__.split( 'bin' )[0], 'presets/attrPresets/shaveHair/dirtyBlond.mel').replace('\\', '/')
        if not os.path.exists( presetFile):
            raise IOError( '%s is not exists!'%(presetFile) )
        mel.eval(
                 'shaveCreateHairFromPreset "%s";'%(presetFile)
                 )
        shaveShape = cmds.ls(sl=True, l=True)[0]
        shaveParent = cmds.parent( cmds.listRelatives(shaveShape, parent=True, f=True), shaveGrp )
        shaveShape = cmds.listRelatives( shaveParent, shapes=True, f=True)[0]
        
        
        newShaveHair.append( shaveShape )
        
        qm.delAttr( shaveShape, ['shaveHairName'])
        cmds.addAttr( shaveShape, ln='originalName', dt='string' )
        cmds.setAttr( shaveShape+'.originalName', shaveName, type='string' )
        
    cmds.progressBar(gMainProgressBar, edit=True, endProgress=True)
    
    return newShaveHair
Exemplo n.º 33
0
    def bakeRigBtn(self):
        bake_options = self.bakeOptions()
        selected_items = self.rigs_list.selectedItems()
        start_frame, end_frame = time_utils.get_maya_timeline_range_inner()
        if len(selected_items) == 0:
            _display_warning_ui(
                'at least one rig must be selected from Rigs list.')
            return
        try:
            cmds.refresh(suspend=True)
            mel.eval('paneLayout -e -manage false $gMainPane')
            ctx = tools_utils.tool_context(use_undo_chunk=True,
                                           restore_current_frame=True,
                                           use_dg_evaluation_mode=True,
                                           disable_viewport=False)
            with ctx:
                cmds.select(clear=True)
                for sel_item in selected_items:
                    children = self.getAllChildren(sel_item)
                    for j in children:
                        rigName = j.text(0)
                        object = cmds.getAttr(rigName + '.' +
                                              ATTRIBUTE_IDENTIFIER_NAME)
                        if FREEZE_RIG_SUFFIX_NAME in rigName:
                            self.full_bake_rdo_btn.setChecked(True)

                        if RIG_SUFFIX_NAME in rigName:
                            name = rigName.split(RIG_SUFFIX_NAME)[0]
                        if FREEZE_RIG_SUFFIX_NAME in rigName:
                            name = rigName.split(FREEZE_RIG_SUFFIX_NAME)[0]

                        if bake_options == 'full_bake':
                            # cmds.bakeResults(object, time=(start_frame, end_frame), simulation=True)
                            fastbake_lib.bake_attributes([object], [],
                                                         start_frame,
                                                         end_frame, False)
                        if bake_options == 'smart_bake':
                            nodes_list = cmds.listConnections(
                                name + SCREEN_Z_MASTER_NAME)
                            for node in nodes_list:
                                if 'screenX_condition' in node:
                                    x_node = node
                                if 'screenY_condition' in node:
                                    y_node = node
                            cmds.select(object)
                            attrs = ['tx', 'ty', 'tz']
                            # First key on objects existing key frames
                            for frame in self.getPreBakeFramesListFromNode(
                                    object):
                                oma.MAnimControl.setCurrentTime(
                                    om.MTime(frame))
                                cmds.setKeyframe(attribute=attrs)

                            # Key screen z depth attribute frames
                            keys_list = cmds.keyframe(rigName + '.' +
                                                      SCREEN_Z_DEPTH_ATTR_NAME,
                                                      query=True)
                            if keys_list:
                                for frame in keys_list:
                                    oma.MAnimControl.setCurrentTime(
                                        om.MTime(frame))
                                    cmds.setKeyframe(attribute=attrs)

                            # Check condition result node and set keyframe
                            for i in range(start_frame, end_frame + 1):
                                oma.MAnimControl.setCurrentTime(om.MTime(i))
                                x_changed = \
                                    cmds.getAttr(x_node + '.outColor')[0][0]
                                y_changed = \
                                    cmds.getAttr(y_node + '.outColor')[0][0]
                                if x_changed or y_changed:
                                    cmds.setKeyframe(attribute=attrs)
                            cmds.select(clear=True)
                self.deleteRigBtn()
                self.refreshRigsList()
        except (NameError, ValueError, TypeError) as e:
            LOG.warn(e)
        finally:
            mel.eval('paneLayout -e -manage true $gMainPane')
            cmds.refresh(suspend=False)
        return
Exemplo n.º 34
0
 def DetectAttrState(self, displayLayer, attribute):
     state = mc.getAttr(displayLayer + '.' + attribute)
     return state
Exemplo n.º 35
0
def bdRigLegBones(side):
    legBones = ['leg', 'knee', 'foot', 'toe', 'toe_end']
    for i in range(len(legBones)):
        legBones[i] = side + '_' + legBones[i] + '_ik_jnt'
    # START setup foot roll
    legIk = cmds.ikHandle(sol='ikRPsolver',
                          sticky='sticky',
                          startJoint=legBones[0],
                          endEffector=legBones[2],
                          name=side + '_leg_ikHandle')
    footIk = cmds.ikHandle(sol='ikSCsolver',
                           sticky='sticky',
                           startJoint=legBones[2],
                           endEffector=legBones[3],
                           name=side + '_foot_ikHandle')
    toeIk = cmds.ikHandle(sol='ikSCsolver',
                          sticky='sticky',
                          startJoint=legBones[3],
                          endEffector=legBones[4],
                          name=side + '_toe_ikHandle')
    # create the groups that will controll the foot animations ( roll, bend, etc etc)
    bdRigUtils.bdCreateOffsetLoc(legBones[2], side + '_foot_loc')
    bdRigUtils.bdCreateOffsetLoc(legBones[3], side + '_ball_loc')
    bdRigUtils.bdCreateOffsetLoc(legBones[4], side + '_toe_loc')
    bdRigUtils.bdCreateOffsetLoc(legBones[2], side + '_heel_loc')

    cmds.parent([
        side + '_ball_loc_grp', side + '_toe_loc_grp', side + '_heel_loc_grp'
    ], side + '_foot_loc')
    cmds.parent([legIk[0], footIk[0], toeIk[0]], side + '_foot_loc')
    cmds.parent([legIk[0]], side + '_ball_loc')
    cmds.parent([side + '_ball_loc_grp', footIk[0], toeIk[0]],
                side + '_toe_loc')
    cmds.parent([side + '_toe_loc_grp'], side + '_heel_loc')

    # add atributes on the footGrp - will be conected later to an anim controler
    attrList = ['Heel', 'Ball', 'Toe', 'kneeTwist']
    animCtrl = cmds.ls(side + '_foot_ik_anim')[0]
    bdRigUtils.bdAddSeparatorAttr(animCtrl, '______')
    bdRigUtils.bdAddAttribute(animCtrl, attrList, 'float')
    # connect the attributes
    cmds.connectAttr(animCtrl + '.' + attrList[0], side + '_heel_loc' + '.rz')
    cmds.connectAttr(animCtrl + '.' + attrList[1], side + '_ball_loc' + '.rz')
    cmds.connectAttr(animCtrl + '.' + attrList[2], side + '_toe_loc' + '.rz')
    # setup the controller
    bdRigLegCtrl(side)
    # END setup foot roll

    # START no flip knee knee
    reverse = 1
    if side == 'right':
        reverse = -1

    poleVectorLoc = cmds.spaceLocator()
    poleVectorLoc = cmds.rename(poleVectorLoc, side + 'poleVector')
    poleVectorLocGrp = cmds.group(poleVectorLoc, n=poleVectorLoc + '_GRP')

    thighPos = cmds.xform(legBones[0], q=True, ws=True, t=True)

    cmds.move(thighPos[0] + reverse * 5, thighPos[1], thighPos[2],
              poleVectorLocGrp)

    cmds.poleVectorConstraint(poleVectorLoc, legIk[0])

    shadingNodeADL = cmds.shadingNode('addDoubleLinear',
                                      asUtility=True,
                                      name=side + 'adl_twist')
    ikZval = cmds.getAttr(str(legIk[0]) + '.rotateZ')
    cmds.setAttr(shadingNodeADL + '.input2', reverse * 90)
    cmds.connectAttr(animCtrl + '.' + attrList[3], shadingNodeADL + '.input1')
    cmds.connectAttr(shadingNodeADL + '.output', legIk[0] + '.twist')
    thighRot = cmds.xform(legBones[0], q=True, ro=True, ws=True)
    startTwist = reverse * 90
    limit = 0.001
    increment = reverse * 0.01

    while True:
        cmds.select(cl=True)
        thighRot = cmds.xform(legBones[0], q=True, ro=True, os=True)
        print thighRot[0]
        if ((thighRot[0] > limit)):
            startTwist = startTwist - increment
            cmds.setAttr(shadingNodeADL + '.input2', startTwist)
        else:
            break
Exemplo n.º 36
0
def createBjt(topRjt):
    topBjt = rigbase.hierarchyCopyConnections(topRjt,
                                              typ='joint',
                                              replaceTarget='_RJT',
                                              replace='_BJT',
                                              t=0,
                                              r=0)

    bjts = cmds.listRelatives(topBjt, c=1, ad=1)
    bjts.append(topBjt)

    for bjt in bjts:
        rjt = bjt.replace('_BJT', '_RJT')
        #cmds.setAttr( bjt+'.r', 0,0,0 )
        #cmds.setAttr( bjt+'.jox', e=1, k=1 )
        #cmds.setAttr( bjt+'.joy', e=1, k=1 )
        #cmds.setAttr( bjt+'.joz', e=1, k=1 )
        #cmds.connectAttr( rjt+'.rx', bjt+'.rx' )
        #cmds.connectAttr( rjt+'.ry', bjt+'.ry' )
        #cmds.connectAttr( rjt+'.rz', bjt+'.rz' )

        conSameAttr = rigbase.connectSameAttr(rjt, bjt)
        conSameAttr.doIt('t', 'r', 's')

        if rjt.find('Leg_L_Lower4') != -1 or rjt.find('Leg_R_Lower4') != -1:
            conSameAttr.doIt('sh')

        cmds.setAttr(bjt + '.ssc', cmds.getAttr(rjt + '.ssc'))

        if cmds.attributeQuery('parameter', node=rjt, ex=1):
            rigbase.AttrEdit(bjt).addAttr(ln='parameter',
                                          min=-.001,
                                          max=1.001,
                                          dv=cmds.getAttr(rjt + '.parameter'),
                                          cb=1)
            cmds.connectAttr(bjt + '.parameter', rjt + '.parameter')

        bjtP = cmds.listRelatives(bjt, p=1)

        if not bjtP: continue

        try:
            cmds.connectAttr(bjtP[0] + '.scale', bjt + '.inverseScale')
        except:
            pass

    topRjtGrp = cmds.listRelatives(topRjt, p=1)[0]
    topBjtGrp = cmds.group(em=1, n='Root_BJT_GRP')

    rigbase.transformSetColor(topRjtGrp, 11)
    rigbase.transformSetColor(topBjtGrp, 29)

    bjtWorld = cmds.group(n='BJT_World')
    rigbase.addControlerShape(bjtWorld,
                              typ='circle',
                              normal=[0, 1, 0],
                              radius=5.5)
    rigbase.controlerSetColor(bjtWorld, 29)
    bjtWorldGrp = cmds.group(bjtWorld, n='BJT_World_GRP')
    cmds.connectAttr(topRjtGrp + '.t', topBjtGrp + '.t')
    cmds.connectAttr(topRjtGrp + '.r', topBjtGrp + '.r')
    cmds.parent(topBjt, topBjtGrp)

    rigbase.connectSameAttr('World_CTL_GRP',
                            'BJT_World_GRP').doIt('t', 'r', 's')
    rigbase.connectSameAttr('World_CTL', 'BJT_World').doIt('t', 'r', 's')
    #rigbase.AttrEdit( 'BJT_World' ).addAttr( ln='World_CTL', at='message' )
    #cmds.connectAttr( 'World_CTL.message', 'BJT_World.World_CTL' )

    RIG = cmds.group(em=1, n='RIG')
    cmds.parent('World_CTL_GRP', 'All_Init', RIG)
    SKIN = cmds.group(em=1, n='SKIN')
    cmds.parent('BJT_World_GRP', SKIN)

    cmds.setAttr(topRjt + '.v', 0)
Exemplo n.º 37
0
def alembic_import_hairAndShave( **kwargs):
    '''{'path':'Pipeline Cache/Alembic/alembic_import_hairAndShave( )ONLYSE',
'tip':'恢复shave和hair',
'icon':'$ICONDIR/alembic.png',
'html':'http://10.99.17.61/hq_maya/alembicPipeline',
'usage':"""
#根据选择物体的hairData和shaveData以及messenger物体的attributePresets和shaveHairInitialState属性来恢复hair和shave
#使用方法:    1.将保存了attributePresets和shaveHairInitialState属性的locator的名字赋给messenger
#        2.选择要恢复hair和shave的物体的组。
messenger = 'F2_HanJXN_SC03_AN_mb_INOF'
$fun( messenger=messenger)""",
}
'''
    selectedObj =  kwargs.get( 'objects', cmds.ls(sl=True, l=True))
    if not selectedObj:
        raise IOError( "Select objects to create hair and shave!")
    
    #得到属性的json对象
    hairAndShave = []
    messenger = kwargs.get( 'messenger', None)
    if messenger:
        if not cmds.objExists( messenger):
            raise IOError( '%s is not exists!'%(messenger) )
        if not cmds.attributeQuery( 'attributePresets', node=messenger, exists=True):
            raise IOError( '%s.attributePresets is not exists!'%(messenger) )
        
        if not cmds.attributeQuery( 'shaveHairInitialState', node=messenger, exists=True):
            shaveInitialState = None
        else:
            shaveInitialState = cmds.getAttr( messenger+'.shaveHairInitialState' )
            shaveInitialState = json.loads(shaveInitialState)
            #raise IOError( '%s.shaveHairInitialState is not exists!'%(messenger) )
        jsonPreset = cmds.getAttr(  messenger+'.attributePresets'  )
    else:
        jsonPreset = kwargs.get( 'jsonPreset', None)
    
    keyFromAttr = kwargs.get( 'keyFromAttr', 'originalName')   
    
        
    #创建hairSystem
    hairSystems = import_createHairSystemByCurveAttr()    
    if hairSystems:        
        hairAndShave.extend( hairSystems )   
    
    
    #检查shave插件
    loadedShave = False
    if not cmds.pluginInfo( 'shaveNode.mll', query=True, loaded=True):
        try: cmds.loadPlugin( 'shaveNode.mll' )
        except: pass    
    if cmds.pluginInfo( 'shaveNode.mll', query=True, loaded=True):
        loadedShave=True
    
    #创建shaveHair    
    if loadedShave:
        cmds.select( selectedObj, r=True)
        shaveHairs = import_createShaveHairByObjectsAttr()
        if shaveHairs:
            hairAndShave.extend( shaveHairs )    
    
    
    if hairAndShave:
        #载入shaveHair和hairSystem的预设,从json对象中
        qm.loadJsonAttrsPreset( objects=hairAndShave, jsonPreset=jsonPreset, keyFromAttr=keyFromAttr )
        
        #创建并载入hairSystem的brush节点,并从jsonPrest中载入预设
        if hairSystems:
            brushNodes = []
            for hair in hairSystems:
                if cmds.attributeQuery('brushNode', node=hair, exists=True):                   
                    
                    pfxHair = cmds.listConnections( hair+'.outputRenderHairs', s=False, shapes=True)
                    brushNode = cmds.listConnections( pfxHair[0]+'.brush', d=False, shapes=True)                    
                    if not brushNode:
                        cmds.select( hair, r=True)
                        mel.eval('assignBrushToHairSystem;')
                        brushNode = cmds.listConnections( pfxHair[0]+'.brush', d=False, shapes=True)              
                    
                    qm.delAttr( brushNode, ['originalName',] )
                    cmds.addAttr( brushNode[0], ln='originalName', dt='string' )
                    cmds.setAttr( brushNode[0]+'.originalName', cmds.getAttr( hair+'.brushNode' ),
                                  type='string')
                    brushNodes.append( brushNode[0] )
                    
            #Load brush attributes from jsonPreset
            if brushNodes:
                qm.loadJsonAttrsPreset( objects=brushNodes, jsonPreset=jsonPreset, keyFromAttr=keyFromAttr )
                    
        
        #Connect texture or shader to shaveHair
        for shave in hairAndShave:
            if cmds.attributeQuery( 'shaderData', node=shave, exists=True):
                shaderData = json.loads( cmds.getAttr( shave+'.shaderData')    )
                for fromAttr, toAttr in shaderData:
                    try:
                        cmds.connectAttr( fromAttr, shave+'.'+toAttr, f=True)
                    except:
                        pass

    #Initialize shaveHiar initial state
    if loadedShave and shaveInitialState and shaveHairs:
        gMainProgressBar = mel.eval('$tmp = $gMainProgressBar')
        cmds.progressBar( gMainProgressBar, edit=True, beginProgress=True, isInterruptable=True,
                status='Initialize state of shaveHair....', maxValue=len(shaveHairs)  )
        
         
        startFrame = shaveInitialState.get('frame', None)
        if not startFrame:
            raise IOError( "没有得到shavehair的初始状态所在的帧")
        cmds.currentTime( startFrame, e=True)
        #allShaveHair = cmds.ls( exactType='shaveHair', l=True )
        allShaveHair = shaveHairs
        shaveHairInitialData = {}
        for shave in allShaveHair:
            if cmds.attributeQuery( 'originalName', node=shave, exists=True):
                oriName = cmds.getAttr( shave+'.originalName' )
                shaveHairInitialData[oriName] = ([], shave)
        
        for shave, curveDataList in shaveInitialState.iteritems():
            cmds.progressBar(gMainProgressBar, edit=True, step=1 )
            if shaveHairInitialData.has_key(shave):
                for curveData in curveDataList:
                    newCurve = cmds.curve(degree=curveData[0], p=curveData[1:])
                    shaveHairInitialData[shave][0].append( newCurve )
        cmds.progressBar(gMainProgressBar, edit=True, endProgress=True)
        
        for shave, objects in shaveHairInitialData.iteritems():
            if objects[0]:
                cmds.select(objects[0], r=True)
                cmds.select(objects[1], add=True )
                cmds.shaveCombFromCurves()
            else:
                cmds.warning( "%s skiped!"%(shave)   )
            cmds.delete( objects[0] )
        
    return hairAndShave
Exemplo n.º 38
0
def alembic_output_createMatAttr(objects=None, invisible=False):
    '''{'path':'Pipeline Cache/Material/alembic_output_createMatAttr( )',
'icon':':/render_lambert.png',
'tip':'创建matInfo属性,保存材质信息',
'html':'http://10.99.17.61/hq_maya/alembicPipeline',
'usage':"""
#对选择的mesh, nurbsSurface物体创建matInfo属性,保存材质信息
#使用方法:选择要创建matInfo物体或组
$fun( )""",
}
'''
    startTime = time.time()
    #Function in there
    if objects==None:
        selectedObj = cmds.ls(sl=True, l=True)
    else:
        selectedObj = objects

    #cmds.select(all=True, ado=True, r=True)

    allMeshFullPath = cmds.listRelatives(selectedObj, type=['mesh','nurbsSurface'], noIntermediate=True, ad=True, f=True )
    #allMeshFullPath = cmds.ls(exactType=['mesh','nurbsSurface'], noIntermediate=False, l=True)
    allMeshFullPath = [child for child in allMeshFullPath if not cmds.getAttr( child+'.intermediateObject') ]
    
    if not invisible:
        toRemove = []
        for obj in allMeshFullPath:
            for papa in [obj.rsplit( '|', i)[0] for i in range(obj.count('|') ) ]:
                if not cmds.getAttr( papa+'.visibility'):                                               
                    toRemove.append( obj )
                    break
        allMeshFullPath = tuple( set(allMeshFullPath).difference(toRemove)  )

    
    seInfo = {}
    shadingEngines = cmds.ls( exactType='shadingEngine' )
    for se in shadingEngines:
        surShader = cmds.listConnections( se+'.surfaceShader', d=False)
        if not surShader:
            continue
        seInfo[se] = surShader[0]


    attrInfo = {}
    qm.delAttr( allMeshFullPath, ['matInfo','papa'] )
    papaPrefix =  socket.gethostbyname( socket.gethostname() ) +  str( time.time() )
    papaPrefix = papaPrefix.replace('.', '')
    for mesh in allMeshFullPath:
        #print mesh
        objMatInfo = {}
        mats = cmds.listConnections( mesh, c=True, s=False, type='shadingEngine')
        if not mats:
            continue

        for i in range( 0, len(mats), 2):
            if '.instObjGroups' not in mats[i] or  mats[i+1] not in seInfo.keys():
                continue
            
            surShader = seInfo[ mats[i+1] ]
            if not objMatInfo.has_key(surShader):
                objMatInfo[surShader] = []
            
            if mats[i].endswith('instObjGroups'):                
                objMatInfo[surShader] = 'All'
                break
            else:# '.instObjGroups.' in mats[i]:
                objAssigned = cmds.getAttr(mats[i]+'.objectGrpCompList')
                objMatInfo[surShader].extend( objAssigned )
        
        objMatInfo =objMatInfo if objMatInfo else None
        jsonStr = json.dumps( objMatInfo )
        cmds.addAttr(mesh, ln='matInfo', dt='string')#, h=True)
        cmds.setAttr( mesh+'.matInfo', jsonStr, type='string', l=True)
        #cmds.addAttr(mesh, ln='papa', dt='string')#, h=True)
        #papaName = papaPrefix +  mesh.split("|", 2)[1]
        #cmds.setAttr( mesh+'.papa', papaName, type='string', l=True)
    print time.time() - startTime
Exemplo n.º 39
0
def output_createHiarOutputCurve(hairSystemObjs = None, hasPfxHair=True, createMarked=False):
    if not hairSystemObjs:
        if not cmds.ls(sl=True):
            cmds.warning( 'Select a hairSystem node!' )
            return None
        hairSystemObjs = cmds.ls(sl=True, l=True, exactType='hairSystem')
    if not hairSystemObjs:
        hairSystemObjs = cmds.listRelatives(  cmds.ls(sl=True, l=True), shapes=True, type='hairSystem' )
    
    if not hairSystemObjs:
        return None
    
    
    if isinstance(hairSystemObjs, (str,unicode) ):
        hairSystemObjs = [hairSystemObjs]
    
    
    #hairSystemObjs, hasPfxHair, createMarked = cmds.ls(exactType='hairSystem', l=True), False, False
    resultCruveGrps = []
    allHairData = {}
    numFollicle = 0
    
    for hair in hairSystemObjs: 
        pfxHair = cmds.listConnections( hair+'.outputRenderHairs', s=False, shapes=True)
        if hasPfxHair and not pfxHair:
            continue
        
        
        allHairData[hair] = {}
        follicles = cmds.listConnections( hair+'.inputHair', d=False, shapes=True)
        if not follicles:
            continue
        
        #Connected attributes infomations to attributes of materials
        materialsInfo = []
        mayaShader = cmds.listConnections( hair, d=False, p=True, c=True, type='shadingDependNode', shapes=True)
        aiHairs = cmds.listConnections( hair, d=False, p=True, c=True, type='aiHair', shapes=True )
        if mayaShader:
            materialsInfo.extend(  
                                    [  (mayaShader[i+1],mayaShader[i].split('.', 1)[-1] ) for i in range(0, len(mayaShader), 2)     ]
                                    )
        if aiHairs:
            materialsInfo.extend(     
                                    [   (aiHairs[i+1],aiHairs[i].split('.', 1)[-1] ) for i in range(0, len(aiHairs), 2)     ]
                                    )
        if materialsInfo:
            
            qm.delAttr( hair, ['shaderData', 'brushAttrs'])
            cmds.addAttr( hair, ln='shaderData', dt='string')
            cmds.setAttr( hair+'.shaderData', json.dumps(materialsInfo), type='string' )
            
        
        
        if not createMarked:
            tempFollicles = []
            for fol in follicles:
                markedCurves = cmds.listConnections( fol+'.outCurve', s=False, shapes=True)
                if not markedCurves:
                    tempFollicles.append( fol )
                    continue
                
                if not [c for c in markedCurves if cmds.attributeQuery('hairData', node=c, exists=True)  ]:
                    tempFollicles.append( fol )
                    continue
                
            if not tempFollicles:
                continue
            follicles = tempFollicles
        
        allHairData[hair] = follicles 
        numFollicle = numFollicle+len( follicles )
        
    if not numFollicle:
        return []
    gMainProgressBar = mel.eval('$tmp = $gMainProgressBar')
    cmds.progressBar( gMainProgressBar, edit=True, beginProgress=True, isInterruptable=True,
                    status='Creating curve...', maxValue=numFollicle )
        
    curNum = 1
    folAttrs = {'clumpWidthMult':1,
                'densityMult':    1,
                'curlMult':    1,
                'clumpTwistOffset':    0,
                'colorBlend':    0,
                'colorR':   0,
                'colorG':   0,
                'colorB':   0,
                }
    
    for hair, follicles in allHairData.iteritems():
        outCurvesGrp = cmds.group( em=True, name='hairSystem_OutputCurves_#')
        for fol in follicles:
            if cmds.progressBar(gMainProgressBar, query=True, isCancelled=True ):
                break
            
            newCurve = cmds.createNode( "nurbsCurve")
            hairValue = {}
            hairValue['hairSystem'] = hair
            for attr, v in folAttrs.iteritems():
                curV = cmds.getAttr( fol+'.'+attr )
                if curV!=v:
                    hairValue[attr] = curV
            jsonStr = json.dumps( hairValue )
                
            cmds.addAttr( newCurve, ln='hairData', dt='string' )            
            cmds.setAttr( newCurve+'.hairData', jsonStr, type='string')
            
            curvePapa = cmds.listRelatives( newCurve, p=True, pa=True )[0]
            cmds.connectAttr( fol+'.outCurve', newCurve+'.create')
            if not cmds.listConnections( fol+'.currentPosition', d=False):
                hairSysAttr = cmds.listConnections( fol+'.outHair', p=True, s=False, shapes=True, type='hairSystem', exactType=True)[0]
                pIndex = re.match( r'.+\[(\d+)\]$', hairSysAttr).groups()[0]
                cmds.connectAttr( hair+'.outputHair[%s]'%(pIndex), fol+'.currentPosition')
                
            cmds.parent( curvePapa, outCurvesGrp, r=True  )                
            cmds.progressBar(gMainProgressBar, edit=True, step=1, status='Creating curve %s/%s'%(curNum, numFollicle) )
         
            curNum = curNum+1
        resultCruveGrps.append( outCurvesGrp )
        
    cmds.progressBar(gMainProgressBar, edit=True, endProgress=True)
    return resultCruveGrps
Exemplo n.º 40
0
def import_createHairSystemByCurveAttr():
    
    beforeHairSystem = set( cmds.ls( exactType='hairSystem', l=True) )
    selectedObj = cmds.ls(sl=True, l=True)
    curves = cmds.ls( selectedObj, l=True, exactType='nurbsCurve' )
    temp = cmds.listRelatives( selectedObj, ad=True, f=True, type='nurbsCurve')
    if temp:
        temp = [c for c in temp if not cmds.getAttr( c+".intermediateObject") ]
        curves.extend( temp )
    curves = tuple( set(curves) )
    curvesList = {}
    curves = [c for c in curves if cmds.attributeQuery( 'hairData', node=c, exists=True)]
    for c in curves:
        try:
            hairData = json.loads( cmds.getAttr(c+'.hairData') )
            hairName = hairData[ 'hairSystem']
            if not curvesList.has_key( hairName ):
                curvesList[hairName] = []
        except:
            print cmds.warning( '%s.hairData value loaded failed!'%(c)  )
            continue
        curvesList[hairName].append( c )
    
    numHairSystem = len(curvesList.keys())
    if not numHairSystem:
        return
    
    gMainProgressBar = mel.eval('$tmp = $gMainProgressBar')
    cmds.progressBar( gMainProgressBar, edit=True, beginProgress=True, isInterruptable=True,
                    status='Creating Hair System ...', maxValue=numHairSystem  )
    
    for hairName, curves in curvesList.iteritems():
        cmds.progressBar(gMainProgressBar, edit=True, step=1 )
        if not curves:
            continue
        cmds.select( curves, r=True)
        mel.eval( 'makeCurvesDynamic 2 { "0", "0", "0", "0", "1"}' )
        
    cmds.progressBar(gMainProgressBar, edit=True, endProgress=True)
    
        
    #Transfer attributes from curve to hairSystem and follicle attributes
    objs = cmds.ls(l=True, exactType='hairSystem')
    #folAttrs = ('clumpWidthMult',  'densityMult', 'curlMult', 'clumpTwistOffset', 'colorBlend', 'colorR', 'colorG', 'colorB')
    
    for hair in objs:
        fols = cmds.listConnections( hair+'.inputHair', d=False, shapes=True)
        c = cmds.listConnections( fols[0]+'.startPosition', d=False, shapes=True)[0]
        
        hairData = json.loads( cmds.getAttr( c+'.hairData') )
        hairSysName = hairData.get( 'hairSystem', None)
        if hairSysName and not cmds.attributeQuery('originalName', node=hair, exists=True):
            cmds.addAttr( hair, ln='originalName', dt='string' )
            cmds.setAttr( hair+'.originalName', hairSysName, type='string')
            
            cmds.setAttr( hair+'.active', False)
            cmds.setAttr( hair+'.simulationMethod', 1)
            
        for fol in fols:
            c = cmds.listConnections( fol+'.startPosition', d=False, shapes=True)[0]
            hairData = json.loads( cmds.getAttr( c+'.hairData') )
            hairData.pop( 'hairSystem', None)
            if hairData and not cmds.attributeQuery('oriAttrs', node=fol, exists=True):
                cmds.addAttr(fol, ln='oriAttrs', dt='string' )
                cmds.setAttr( fol+'.oriAttrs', json.dumps(hairData), type='string' )
                
    afterHairSystem = set(  cmds.ls(exactType='hairSystem', l=True)  )
    
    newHairSystems = tuple( afterHairSystem.difference( beforeHairSystem )    )
    
    hairSysGrp = cmds.group( newHairSystems, name='hairsystemGrp_#')
    newHairSystems = cmds.listRelatives(hairSysGrp, ad=True, type='hairSystem', f=True)
    pfxHairs = []
    for hair in newHairSystems:
        pfxHairs.extend( cmds.listConnections( hair+'.outputRenderHairs', s=False) )    
    cmds.group( pfxHairs, name='pfxHairGrp_#' ) 
    
    return newHairSystems
Exemplo n.º 41
0
def attach_to_surface(surface, dag, snap=False, scale=False):
    # nodes to attach dag to surface
    POSI = cmds.createNode('pointOnSurfaceInfo', name=dag + '_POSI')
    matrix_node = cmds.createNode('fourByFourMatrix', name=dag + '_4X4')
    foll = cmds.createNode('transform', name=dag + '_custom_foll')
    foll_MSC = cmds.createNode('millSimpleConstraint', name=foll + '_MSC')

    # find closest point on surface and it's UV values
    dag_pos = cmds.xform(dag, t=True, ws=True, q=True)
    pos, parU, parV = closest_point_on_surface(surface, dag_pos)

    cmds.xform(dag, t=(pos[0], pos[1], pos[2]), ws=True)

    # attach dag to surface
    cmds.connectAttr(surface + '.local', POSI + '.inputSurface')
    cmds.setAttr(POSI + '.parameterU', parU)
    cmds.setAttr(POSI + '.parameterV', parV)

    # create matrix from POSI node
    cmds.connectAttr(POSI + '.normalizedTangentVX', matrix_node + '.in00')
    cmds.connectAttr(POSI + '.normalizedTangentVY', matrix_node + '.in01')
    cmds.connectAttr(POSI + '.normalizedTangentVZ', matrix_node + '.in02')
    cmds.connectAttr(POSI + '.normalizedNormalX', matrix_node + '.in10')
    cmds.connectAttr(POSI + '.normalizedNormalY', matrix_node + '.in11')
    cmds.connectAttr(POSI + '.normalizedNormalZ', matrix_node + '.in12')
    cmds.connectAttr(POSI + '.normalizedTangentUX', matrix_node + '.in20')
    cmds.connectAttr(POSI + '.normalizedTangentUY', matrix_node + '.in21')
    cmds.connectAttr(POSI + '.normalizedTangentUZ', matrix_node + '.in22')
    cmds.connectAttr(POSI + '.positionX', matrix_node + '.in30')
    cmds.connectAttr(POSI + '.positionY', matrix_node + '.in31')
    cmds.connectAttr(POSI + '.positionZ', matrix_node + '.in32')

    cmds.connectAttr(matrix_node + '.output', foll_MSC + '.inMatrix')
    cmds.connectAttr(foll + '.parentInverseMatrix[0]',
                     foll_MSC + '.parentInverseMatrix')

    cmds.connectAttr(foll_MSC + '.outTranslate', foll + '.translate')
    cmds.connectAttr(foll_MSC + '.outRotate', foll + '.rotate')

    constraint.simple_constraint(foll, dag, snap=snap)

    if scale:
        POSI0 = cmds.createNode('pointOnSurfaceInfo',
                                name=dag + '_scale0_POSI')
        POSI1 = cmds.createNode('pointOnSurfaceInfo',
                                name=dag + '_scale1_POSI')
        dist = cmds.createNode('math_DistancePoints', name=dag + '_DIST')
        div = cmds.createNode('math_Divide', name=dag + '_DIV')

        cmds.connectAttr(surface + '.local', POSI0 + '.inputSurface')
        cmds.connectAttr(surface + '.local', POSI1 + '.inputSurface')
        cmds.setAttr(POSI0 + '.parameterU', 0)
        cmds.setAttr(POSI1 + '.parameterU', 1)
        cmds.setAttr(POSI0 + '.parameterV', parV)
        cmds.setAttr(POSI1 + '.parameterV', parV)

        cmds.connectAttr(POSI0 + '.position', dist + '.input1')
        cmds.connectAttr(POSI1 + '.position', dist + '.input2')

        init_distance = cmds.getAttr(dist + '.output')
        cmds.setAttr(div + '.input2', init_distance)
        cmds.connectAttr(dist + '.output', div + '.input1')

        cmds.connectAttr(div + '.output', foll + '.sz')

    return foll
Exemplo n.º 42
0
def output_createAttributeOnShaveHairSkin( **kwargs ):
    allHairs = kwargs.get('shaveHairs', None)
    #allHairs = cmds.ls(exactType='shaveHair', l=True)
    if not allHairs:
        return

    gMainProgressBar = mel.eval('$tmp = $gMainProgressBar')
    
    cmds.progressBar( gMainProgressBar, edit=True, beginProgress=True, isInterruptable=True,
                    status='Getting data of shaveData attribute...', maxValue=len(allHairs) )
    
    objsAttrsData = {}
    
    for shave in allHairs:
        if cmds.progressBar(gMainProgressBar, query=True, isCancelled=True ):
            break
        cmds.progressBar(gMainProgressBar, edit=True, step=1 )
        
        #Connected attributes infomations to attributes of materials
        materialsInfo = []
        mayaShader = cmds.listConnections( shave, d=False, p=True, c=True, type='shadingDependNode', shapes=True)
        aiHairs = cmds.listConnections( shave, d=False, p=True, c=True, type='THdependNode', shapes=True )
        if mayaShader:
            materialsInfo.extend(  
                                    [  (mayaShader[i+1],mayaShader[i].split('.', 1)[-1] ) for i in range(0, len(mayaShader), 2)     ]
                                    )
        if aiHairs:
            materialsInfo.extend(     
                                    [   (aiHairs[i+1],aiHairs[i].split('.', 1)[-1] ) for i in range(0, len(aiHairs), 2)     ]
                                    )
        if materialsInfo:
            qm.delAttr( shave, ['shaderData'])
            cmds.addAttr( shave, ln='shaderData', dt='string')
            cmds.setAttr( shave+'.shaderData', json.dumps(materialsInfo), type='string' )
            
        
        inputMesh = cmds.listConnections( shave+'.inputMesh', d=False, shapes=True )
        inputSurface = cmds.listConnections( shave+'.inputSurface', d=False, shapes=True )
        inputCurve = cmds.listConnections( shave+'.inputCurve', d=False, shapes=True )
        
        if inputMesh:            
            for i, v in enumerate( cmds.getAttr( shave+'.inputMesh', mi=True)  ):
                connectedInfo = cmds.listConnections( '%s.growthObjectsGroupID[%d]'%(shave, v), d=False, p=True, shapes=True)
                if connectedInfo:
                    groupAttr = connectedInfo[0].replace( '.objectGroupId','.objectGrpCompList')
                    faceList = cmds.getAttr( groupAttr)
                else:
                    faceList = 'all'
                
                meshObj = inputMesh[i]
                if not objsAttrsData.has_key(meshObj):
                    objsAttrsData[meshObj] = {'shaveData':[]}
                    
                objsAttrsData[meshObj]['shaveData'].append( (shave, v, faceList ) )
        
        if inputSurface:
            for i, v in enumerate(  cmds.getAttr( shave+'.inputSurface', mi=True)  ):
                surObj = inputSurface[i]
                if not objsAttrsData.has_key(surObj):
                    objsAttrsData[surObj] = {'shaveData':[]}                
                
                if not objsAttrsData.has_key(surObj):
                    objsAttrsData[surObj] = {'shaveData':[] }
                
                objsAttrsData[surObj]['shaveData'].append( (shave, v, 'all' ) )
                
        if inputCurve:
            for i, v in enumerate(  cmds.getAttr( shave+'.inputCurve', mi=True) ):
                curObj = inputCurve[i]
                if not objsAttrsData.has_key(curObj):
                    objsAttrsData[curObj] = {'shaveData':[]}                
                
                if not objsAttrsData.has_key(curObj):
                    objsAttrsData[curObj] = {'shaveData':[] }
                
                objsAttrsData[curObj]['shaveData'].append( (shave, v, 'all' ) )
    
    cmds.progressBar(gMainProgressBar, edit=True, status='Creating shaveData attribute...' )
    
    qm.delAttr( objsAttrsData.keys(), ['shaveData'] )
    cmds.addAttr( objsAttrsData.keys(), ln='shaveData', dt='string' )  
    for obj, v in  objsAttrsData.iteritems():                
        cmds.setAttr( obj+'.shaveData', json.dumps(v), type='string')
        
    cmds.progressBar(gMainProgressBar, edit=True, endProgress=True)
    
    
    
    #Create start position curves
    cmds.progressBar( gMainProgressBar, edit=True, beginProgress=True, isInterruptable=True,
                    status='Getting data of initialState attribute...', maxValue=len(allHairs) )
   
    #allHairs = cmds.ls(exactType='shaveHair', l=True)
    shaveCurveGroups = []
    shaveInitialState = {}
    startFrame = int( cmds.playbackOptions( q=True, min=True) )
    cmds.currentTime( startFrame, e=True)
    shaveInitialState['frame'] = startFrame
    
    for shave in allHairs:
        cmds.progressBar(gMainProgressBar, edit=True, step=1 )
        
        shaveInitialState[shave] = []        
        cmds.select( shave, r=True)
        cmds.shaveCreateCurvesFromGuides( )   
        curveGroup = cmds.ls(sl=True, l=True)[0]
        startCurves = cmds.listRelatives( curveGroup, ad=True, type='nurbsCurve', f=True )
        for curveShape in startCurves:
            cvPosList = []
            curveDegree = cmds.getAttr( curveShape+'.degree')
            cvPosList.append( curveDegree )
            numCV = cmds.getAttr( curveShape+'.spans') + curveDegree
            for cv in range( numCV ):
                cvPosList.append( cmds.pointPosition( '%s.cv[%d]'%(curveShape, cv)  ) 
                                  )
            shaveInitialState[shave].append( cvPosList )
        shaveCurveGroups.append( curveGroup )
    
    
    cmds.progressBar(gMainProgressBar, edit=True, status='Creating initialState attribute...' )   
       
    sceneName = cmds.file( q=True,  sceneName=True, shortName=True).replace('.', '_' )
    locatorName = sceneName + '_INFO'
    if not cmds.objExists( locatorName ):
        cmds.spaceLocator( name = locatorName )
    qm.delAttr( locatorName, ['shaveHairInitialState',])
    cmds.addAttr( locatorName, ln='shaveHairInitialState', dt='string', hidden=True )
    cmds.setAttr( locatorName+'.shaveHairInitialState', json.dumps(shaveInitialState),  type='string', l=True)    
    cmds.delete( shaveCurveGroups )
    
    cmds.progressBar(gMainProgressBar, edit=True, endProgress=True)
Exemplo n.º 43
0
    def setup(self):
        super(Foot,self).setup()

        #create an upvector for the foot joints
        self.footJntUpv = control.Control('{0}_upvGuide'.format(self.getName()), shape='cross')
        self.footJntUpv.create()
        cmds.parent( self.footJntUpv.getName(), self.masterGuide.getName())

        if self.getSide() == nameSpace.SIDES["left"]:
            #default positioning going in the order of self.jointList:
            self.jointPositions = [
                (0.25, 0.29, -0.06), #ankle
                (0.25, 0, 0.644), #ball
                (0.25, 0, 0.95), #tiptoe
                (0.25, 0, -0.215), #heel
                (0.065, 0, 0.5), #inpivot
                (0.46, 0, 0.5) ] #outp

            #move the masterguide
            self.masterGuide.setPosition( (2,0,0) )
            #move the upv
            self.footJntUpv.setPosition( (0.25,1,1) )

        elif self.getSide() == nameSpace.SIDES["right"]:
            #default positioning going in the order of self.jointList:
            self.jointPositions = [
                (-0.25, 0.29, -0.06), #ankle
                (-0.25, 0, 0.644), #ball
                (-0.25, 0, 0.95), #tiptoe
                (-0.25, 0, -0.215), #heel
                (-0.065, 0, 0.5), #inp
                (-0.46, 0, 0.5) ] #outp

            #move the masterguide
            self.masterGuide.setPosition( (-2,0,0) )
            #move the upv
            self.footJntUpv.setPosition( (-0.25,1,1) )

        #add aim and up attr to masterGuide
        self.aimAttr = attribute.switch(self.masterGuide.getName(),
                        "aim",0,
                        ["x","y","z","-x","-y","-z"],
                        [[1,0,0],[0,1,0],[0,0,1],[-1,0,0],[0,-1,0],[0,0,-1]])

        self.upAttr = attribute.switch(self.masterGuide.getName(),
                        "up",0,
                        ["x","y","z","-x","-y","-z"],
                        [[1,0,0],[0,1,0],[0,0,1],[-1,0,0],[0,-1,0],[0,0,-1]])
        #iterate through self.jointList
        #for each listItem in self.jointList
        parent = self.skeletonGroup

        for index,jnt in enumerate( self.jointList ):

            #create joint
            jnt.create()
            jnt.setPosition( self.jointPositions[index] )

            #if it's not the pivots
            if (index<4):
                # set parent
                jnt.setParent(parent)
                parent = jnt.getName()

                #if it's the heel, make it world
                if (index==3):
                    #no parent
                    cmds.select( jnt.getName() )
                    cmds.parent( w=True )
                    #and set joint orientations to zero
                    cmds.setAttr( "{0}.jointOrient".format( jnt.getName() )  )

            #if it is, parent them to the ankle
            else:
                jnt.setParent(parent)

            #create guides
            self.guides.append( self.createGuide(jnt.getName().replace(nameSpace.JOINT,nameSpace.GUIDE),
                             jnt.getName(),
                             jnt.getPosition(),
                             self.masterGuide.getName()) )
            #resize those guides.
            #cmds.select( self.guides[index].getName(),r=True )
            cmds.setAttr( "{0}.sx".format(self.guides[index].getName()), 0.15)
            cmds.setAttr( "{0}.sy".format(self.guides[index].getName()), 0.15)
            cmds.setAttr( "{0}.sz".format(self.guides[index].getName()), 0.15)


        aimConstraintList = list()

        for index,jnt in enumerate( self.jointList ):

            if ( index < 2):
                #all others are aimConstrained
                #aim constraint joint[jnt+1] to joint[jnt]
                aimCon = cmds.aimConstraint( self.guides[index+1].getName(),
                                            self.jointList[index].getName(),
                                            worldUpType='object',
                                            worldUpObject= self.footJntUpv.getName() )

                aimConstraintList.append( aimCon[0] )
                cmds.parent(aimConstraintList[index], self.guidesGroup)

        for cst in aimConstraintList:
            cmds.connectAttr(self.upAttr, "{0}.upVector".format(cst),f=True)
            cmds.connectAttr(self.aimAttr, "{0}.aimVector".format(cst),f=True)
            #cmds.setAttr("{0}.worldUpVector".format( cst ), self.upAttr )

        #so that the aim and up are not both x
        cmds.setAttr("{0}.up".format(self.masterGuide.getName()) ,1)
        self.strUpAttr = (cmds.getAttr ("{0}.up".format(self.masterGuide.getName()), asString = True))
        cmds.select(cl=True)
Exemplo n.º 44
0
 def get(self):
     """Set node's attribute value."""
     return cmds.getAttr(self.plug)
def CreateJoints():
    charName = cmds.textFieldGrp(NameInput, q=True, text=True)
    if charName == "":
        print("Write your character name")
    else:
        #Create directory
        listDirectory = [['_Joints_', '_Controls_', '_ikHandle_'],
                         '_GlobalControl_', '_Geo_']
        cmds.group(em=True, n=charName + '_Main_01')
        for i in range(len(listDirectory) - 1):
            cmds.group(em=True, n=charName + listDirectory[i + 1] + '01')
            cmds.parent(charName + listDirectory[i + 1] + '01',
                        charName + '_Main_01')
        for i in range(len(listDirectory[0])):
            cmds.group(em=True, n=charName + listDirectory[0][i] + '01')
            cmds.parent(charName + listDirectory[0][i] + '01',
                        charName + listDirectory[1] + '01')
        cmds.select(d=True)
        global locXYZ
        locXYZ = [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0],
                  [0, 0, 0]]
        for i in range(len(list)):
            locXYZ[i][0] = cmds.getAttr('Loc_' + list[i] + '.translateX')
            print('translateX calcule done')
            locXYZ[i][1] = cmds.getAttr('Loc_' + list[i] + '.translateY')
            print('translateY calcule done')
            locXYZ[i][2] = cmds.getAttr('Loc_' + list[i] + '.translateZ')
            print('translateZ calcule done')
        #total length between root and neck
        lengthY = locXYZ[1][1] - locXYZ[0][1]
        lengthZ = abs(locXYZ[0][2]) + abs(locXYZ[1][2])
        #length between root and toe
        legY = locXYZ[0][1] - locXYZ[5][1]
        lengthY = locXYZ[1][1] - locXYZ[0][1]
        lengthZ = abs(locXYZ[0][2]) + abs(locXYZ[1][2])
        #length between root and toe
        legY = locXYZ[0][1] - locXYZ[5][1]
        cmds.joint(p=(locXYZ[0][0], locXYZ[0][1], locXYZ[0][2]),
                   n=charName + '_root' + '_Jnt_01')

        def PlaceJoint(OrientThisJoint, x, y, z, jointName, o):
            cmds.joint(p=(x, y, z), n=jointName)
            cmds.joint(OrientThisJoint,
                       e=True,
                       zso=True,
                       oj='xyz',
                       sao=o + 'up')

        #place spline-head joint
        PlaceJoint(charName + '_root' + '_Jnt_01', 0,
                   locXYZ[0][1] + lengthY * 0.43,
                   locXYZ[0][2] + lengthZ * 0.43,
                   charName + '_spline' + '_Jnt_01', 'x')
        PlaceJoint(charName + '_spline' + '_Jnt_01', 0,
                   locXYZ[0][1] + lengthY * 0.8, locXYZ[0][2] + lengthZ * 0.18,
                   charName + '_spline' + '_Jnt_02', 'x')
        PlaceJoint(charName + '_spline' + '_Jnt_02', locXYZ[1][0],
                   locXYZ[1][1], locXYZ[1][2],
                   charName + '_spline' + '_Jnt_03', 'x')
        PlaceJoint(charName + '_spline' + '_Jnt_03', locXYZ[1][0],
                   locXYZ[1][1] + lengthY * 0.1, locXYZ[1][2] + lengthY * 0.05,
                   charName + '_neck' + '_Jnt_01', 'x')
        PlaceJoint(charName + '_neck' + '_Jnt_01',
                   (locXYZ[1][0] + locXYZ[1][0]) / 2,
                   locXYZ[1][1] + lengthY / 4,
                   (locXYZ[1][2] + locXYZ[0][2] + lengthY * 0.15) / 2,
                   charName + '_jaw' + '_Jnt_01', 'x')
        PlaceJoint(charName + '_jaw' + '_Jnt_01',
                   (locXYZ[1][0] + locXYZ[1][0]) / 4,
                   locXYZ[1][1] + lengthY / 2.8,
                   (locXYZ[1][2] + locXYZ[0][2] + lengthY * 0.15) / 2,
                   charName + '_eye' + '_Jnt_01', 'x')
        PlaceJoint(charName + '_eye' + '_Jnt_01', 0,
                   locXYZ[1][1] + lengthY / 1.8, locXYZ[0][2] + lengthY * 0.03,
                   charName + '_head' + '_Jnt_01', 'x')
        cmds.joint(charName + '_head' + '_Jnt_01',
                   e=True,
                   oj='none',
                   ch=True,
                   zso=True)

        #place arm joint
        cmds.select(d=True)
        cmds.joint(charName + '_spline' + '_Jnt_03',
                   p=(locXYZ[0][0] + lengthY * 0.1, locXYZ[1][1],
                      locXYZ[0][2] + lengthZ * 0.1),
                   n=charName + '_L' + '_shoulder' + '_Jnt_01')
        PlaceJoint(charName + '_L' + '_shoulder' + '_Jnt_01',
                   locXYZ[0][0] + lengthY * 0.24,
                   locXYZ[1][1] - lengthY * 0.05, locXYZ[0][2] - lengthZ * 0.2,
                   charName + '_L' + '_shoulder' + '_Jnt_02', 'y')
        PlaceJoint(
            charName + '_L' + '_shoulder' + '_Jnt_02',
            (locXYZ[0][0] + lengthY * 0.24 + locXYZ[2][0] - lengthZ * 0.1) / 2,
            (locXYZ[1][1] - lengthY * 0.05 + locXYZ[2][1] + lengthZ * 0.1) / 2,
            (locXYZ[0][2] - lengthZ * 0.2 + locXYZ[2][2]) / 2,
            charName + '_L' + '_arm' + '_Jnt_01', 'y')
        PlaceJoint(charName + '_L' + '_arm' + '_Jnt_01',
                   locXYZ[2][0] - lengthZ * 0.1, locXYZ[2][1] + lengthZ * 0.1,
                   locXYZ[2][2], charName + '_L' + '_arm' + '_Jnt_02', 'y')
        PlaceJoint(charName + '_L' + '_arm' + '_Jnt_02',
                   locXYZ[2][0] + lengthZ * 0.1, locXYZ[2][1] - lengthZ * 0.1,
                   locXYZ[2][2], charName + '_L' + '_arm' + '_Jnt_03', 'y')
        PlaceJoint(charName + '_L' + '_arm' + '_Jnt_03',
                   (locXYZ[2][0] + lengthZ * 0.1 + locXYZ[3][0]) / 2,
                   (locXYZ[2][1] - lengthZ * 0.1 + locXYZ[3][1]) / 2,
                   (locXYZ[2][2] + locXYZ[3][2]) / 2,
                   charName + '_L' + '_arm' + '_Jnt_04', 'y')
        PlaceJoint(charName + '_L' + '_arm' + '_Jnt_04', locXYZ[3][0],
                   locXYZ[3][1], locXYZ[3][2],
                   charName + '_L' + '_wrist' + '_Jnt_01', 'y')
        PlaceJoint(charName + '_L' + '_wrist' + '_Jnt_01', locXYZ[3][0],
                   locXYZ[3][1] + lengthY * -0.20, locXYZ[3][2],
                   charName + '_L' + '_hand' + '_Jnt_01', 'y')
        cmds.joint(charName + '_L' + '_hand' + '_Jnt_01',
                   e=True,
                   oj='none',
                   ch=True,
                   zso=True)

        #place leg joint
        cmds.select(d=True)
        cmds.joint(charName + '_root' + '_Jnt_01',
                   p=(locXYZ[0][0] + lengthY * 0.08, locXYZ[0][1],
                      locXYZ[0][2] - lengthZ / 3.9),
                   n=charName + '_L' + '_hip' + '_Jnt_01')
        PlaceJoint(charName + '_L' + '_hip' + '_Jnt_01',
                   locXYZ[0][0] + lengthY * 0.21, locXYZ[0][1] + legY * 0.03,
                   locXYZ[0][2] - lengthZ / 1.86,
                   charName + '_L' + '_thigh' + '_Jnt_01', 'x')
        PlaceJoint(charName + '_L' + '_thigh' + '_Jnt_01',
                   locXYZ[4][0] - legY * 0.005, locXYZ[4][1] + legY * 0.05,
                   locXYZ[4][2], charName + '_L' + '_knee' + '_Jnt_01', 'x')
        PlaceJoint(charName + '_L' + '_knee' + '_Jnt_01',
                   locXYZ[4][0] + legY * 0.005, locXYZ[4][1] - legY * 0.05,
                   locXYZ[4][2] - legY * 0.03,
                   charName + '_L' + '_knee' + '_Jnt_02', 'x')
        PlaceJoint(
            charName + '_L' + '_knee' + '_Jnt_02',
            locXYZ[5][0] - locXYZ[4][0] * 0.3,
            locXYZ[5][1] + locXYZ[4][1] * 0.17,
            locXYZ[4][2] - legY * 0.03 - (locXYZ[5][2] - locXYZ[4][2]) / 6,
            charName + '_L' + '_ankie' + '_Jnt_01', 'x')
        PlaceJoint(charName + '_L' + '_ankie' + '_Jnt_01',
                   (locXYZ[5][0] - locXYZ[4][0] * 0.3 + locXYZ[5][0]) / 2,
                   locXYZ[5][1], locXYZ[4][2] + locXYZ[5][2] / 1.9,
                   charName + '_L' + '_ball' + '_Jnt_01', 'x')
        PlaceJoint(charName + '_L' + '_ball' + '_Jnt_01', locXYZ[5][0],
                   locXYZ[5][1], locXYZ[5][2],
                   charName + '_L' + '_toe' + '_Jnt_01', 'x')
        cmds.joint(charName + '_L' + '_toe' + '_Jnt_01',
                   e=True,
                   oj='none',
                   ch=True,
                   zso=True)
    def Light_Export_Fn(self):
        File_Path = QFileDialog.getSaveFileName(self,
                                                caption=u"1",
                                                directory=".",
                                                filter="json (*.json)")
        # 空数组处理
        try:
            if type(File_Path) is tuple:
                File_Path = File_Path[0]
            if type(File_Path) is list:
                File_Path = File_Path[0]
        except:
            traceback.print_exc()
            return

        if not os.path.exists(File_Path):
            return

        Light_Json = {}
        Light_Json['Generate_Application'] = "Maya"
        Light_Json['LightData'] = {}

        lightList = cmds.ls(type='lightList')[0]
        lightList = cmds.listConnections(lightList + ".lights")
        for lightName in lightList:
            if cmds.getAttr(lightName + ".visibility") == 0:
                continue
            light = cmds.listRelatives(lightName, c=1)[0]
            Light_Json['LightData'][lightName] = {}
            Light_Json['LightData'][lightName]['Name'] = light
            Light_Json['LightData'][lightName]['Type'] = cmds.objectType(light)
            Light_Json['LightData'][lightName]['Intensity'] = cmds.getAttr(
                light + ".intensity")
            Light_Json['LightData'][lightName]['Exposure'] = cmds.getAttr(
                light + ".aiExposure")
            Light_Json['LightData'][lightName]['color'] = {}
            Light_Json['LightData'][lightName]['color']["R"] = cmds.getAttr(
                light + ".color")[0][0]
            Light_Json['LightData'][lightName]['color']["G"] = cmds.getAttr(
                light + ".color")[0][1]
            Light_Json['LightData'][lightName]['color']["B"] = cmds.getAttr(
                light + ".color")[0][2]
            Light_Json['LightData'][lightName]['Translate'] = {}
            Light_Json['LightData'][lightName]['Translate'][
                'tx'] = cmds.getAttr(lightName + ".tx")
            Light_Json['LightData'][lightName]['Translate'][
                'ty'] = cmds.getAttr(lightName + ".ty")
            Light_Json['LightData'][lightName]['Translate'][
                'tz'] = cmds.getAttr(lightName + ".tz")
            Light_Json['LightData'][lightName]['Rotate'] = {}
            Light_Json['LightData'][lightName]['Rotate']['rx'] = cmds.getAttr(
                lightName + ".rx")
            Light_Json['LightData'][lightName]['Rotate']['ry'] = cmds.getAttr(
                lightName + ".ry")
            Light_Json['LightData'][lightName]['Rotate']['rz'] = cmds.getAttr(
                lightName + ".rz")
            Light_Json['LightData'][lightName]['Scale'] = {}
            Light_Json['LightData'][lightName]['Scale']['sx'] = cmds.getAttr(
                lightName + ".sx")
            Light_Json['LightData'][lightName]['Scale']['sy'] = cmds.getAttr(
                lightName + ".sy")
            Light_Json['LightData'][lightName]['Scale']['sz'] = cmds.getAttr(
                lightName + ".sz")
            if cmds.objectType(light) == "spotLight":
                Light_Json['LightData'][lightName]['coneAngle'] = cmds.getAttr(
                    light + ".coneAngle")
                Light_Json['LightData'][lightName][
                    'penumbraAngle'] = cmds.getAttr(light + ".penumbraAngle")
                Light_Json['LightData'][lightName]['dropoff'] = cmds.getAttr(
                    light + ".dropoff")

        try:
            with open(File_Path, 'w') as f:
                json.dump(Light_Json, f, indent=4)
        except:
            if path != "":
                QMessageBox.warning(self, u"Warning", u"空路径读取失败")
Exemplo n.º 47
0
 def customTextUpdate(self, attr):
     self.textAttribute = attr
     existingText = cmds.getAttr(attr)
     if existingText:
         self.textField.setText(existingText)
def Controllers():
    charName = cmds.textFieldGrp(NameInput, q=True, text=True)
    lengthY = locXYZ[1][1] - locXYZ[0][1]
    lengthZ = abs(locXYZ[0][2]) + abs(locXYZ[1][2])
    legY = locXYZ[0][1] - locXYZ[5][1]
    side = ['_L_', '_R_']
    nb = [1, -1]
    for i in range(len(side)):
        cmds.ikHandle(n=charName + 'Leg' + side[i] + 'ikHandle',
                      sj=charName + side[i] + 'thigh_Jnt_01',
                      ee=charName + side[i] + 'ankie_Jnt_01')
        cmds.spaceLocator(n=charName + 'poleVector' + side[i] + 'leg',
                          p=(nb[i] * locXYZ[4][0] - legY * 0.005,
                             locXYZ[4][1] + legY * 0.05, locXYZ[4][2]))
        cmds.xform(centerPivots=1)
        # aims the pole vector of 1 at 2.
        cmds.poleVectorConstraint(charName + 'poleVector' + side[i] + 'leg',
                                  charName + 'Leg' + side[i] + 'ikHandle')
        cmds.move(nb[i] * lengthY * 0.75,
                  -lengthY * 0.75,
                  charName + 'poleVector' + side[i] + 'leg',
                  moveXY=True)
        cmds.setAttr(charName + 'Leg' + side[i] + 'ikHandle.twist', nb[i] * 90)
        cmds.ParentConstraint('controllerfoot',
                              charName + 'poleVector' + side[i] + 'leg')
        cmds.parent(charName + 'poleVector' + side[i] + 'leg',
                    charName + 'Leg' + side[i] + 'ikHandle',
                    relative=True)
        cmds.ikHandle(n='Foot' + side[i] + 'ball_ikHandle',
                      sj=charName + side[i] + 'ankie' + '_Jnt_01',
                      ee=charName + side[i] + 'ball' + '_Jnt_01')
        cmds.ikHandle(n='Foot' + side[i] + 'toe_ikHandle',
                      sj=charName + side[i] + 'ball' + '_Jnt_01',
                      ee=charName + side[i] + 'toe' + '_Jnt_01')
        cmds.group(charName + 'Leg' + side[i] + 'ikHandle',
                   n=charName + 'Foot' + side[i] + 'heelPeel')
        #change pivot position
        Xpos = cmds.getAttr('Foot' + side[i] + 'ball_ikHandle.translateX')
        Ypos = cmds.getAttr('Foot' + side[i] + 'ball_ikHandle.translateY')
        Zpos = cmds.getAttr('Foot' + side[i] + 'ball_ikHandle.translateZ')
        cmds.move(Xpos,
                  Ypos,
                  Zpos,
                  'Foot' + side[i] + 'heelPeel.scalePivot',
                  'Foot' + side[i] + 'heelPeel.rotatePivot',
                  absolute=True)
        cmds.group('Foot' + side[i] + 'ball_ikHandle',
                   'Foot' + side[i] + 'toe_ikHandle',
                   n='Foot' + side[i] + 'toeTap')
        cmds.move(Xpos,
                  Ypos,
                  Zpos,
                  'Foot' + side[i] + 'toeTap.scalePivot',
                  'Foot' + side[i] + 'toeTap.rotatePivot',
                  absolute=True)
        cmds.group('Foot' + side[i] + 'ball_ikHandle',
                   'Foot' + side[i] + 'toeTap',
                   n='Foot' + side[i] + 'TipToe')
        cmds.group(n='Foot' + side[i] + '1', em=True)
        cmds.parent(charName + 'Foot' + side[i] + 'heelPeel',
                    'Foot' + side[i] + 'TipToe',
                    'Foot' + side[i] + '1',
                    relative=True)
        cmds.move(Xpos,
                  Ypos,
                  Zpos,
                  'Foot' + side[i] + '1.scalePivot',
                  'Foot' + side[i] + '1.rotatePivot',
                  absolute=True)
        Xpos = cmds.getAttr('Foot' + side[i] + 'ball_ikHandle.translateX')
        Ypos = cmds.getAttr('Foot' + side[i] + 'ball_ikHandle.translateY')
        Zpos = cmds.getAttr('Foot' + side[i] + 'ball_ikHandle.translateZ')
        CreateCtr('Foot' + side[i] + 'Crl', 'Foot' + side[i] + '1',
                  (Xpos, Ypos, Zpos),
                  (lengthY / 60 * 10, lengthY / 60 * 10, lengthY / 60 * 16),
                  (0, 0, 0))
    #left Arm
    for i in range(len(side)):
        cmds.ikHandle(n='Arm' + str(side[i]) + 'ikHandle',
                      sj=charName + str(side[i]) + 'shoulder' + '_Jnt_02',
                      ee=charName + str(side[i]) + 'wrist' + '_Jnt_01')
        cmds.CreateNURBSCircle()
        cmds.rename('nurbsCircle1', 'Elbow' + str(side[i]) + 'Crl')
        cmds.move(nb[i] * locXYZ[2][0], locXYZ[2][1], locXYZ[2][2] * 30)
        cmds.scale(2, 2, 3)
        cmds.rotate(90, 0, 0)
        cmds.move(nb[i] * locXYZ[2][0],
                  locXYZ[2][1],
                  locXYZ[2][2],
                  'Elbow' + str(side[i]) + 'Crl.scalePivot',
                  'Elbow' + str(side[i]) + 'Crl.rotatePivot',
                  absolute=True)
        cmds.makeIdentity(apply=True)
        cmds.xform(centerPivots=1)
        cmds.poleVectorConstraint('Elbow' + str(side[i]) + 'Crl',
                                  'Arm' + str(side[i]) + 'ikHandle')
        #left Arm controller
        CreateCtr('Arm' + side[i] + 'Crl', 'Arm' + side[i] + 'ikHandle',
                  (nb[i] * locXYZ[3][0], locXYZ[3][1], locXYZ[3][2]),
                  (lengthY / 60 * 5, lengthY / 60 * 5, lengthY / 60 * 8),
                  (0, 0, nb[i] * 30))
    #spline
    cmds.parent(charName + '_R_shoulder_Jnt_01', w=True)
    cmds.parent(charName + '_L_shoulder_Jnt_01', w=True)
    cmds.select(d=True)
    cmds.select(charName + '_spline_Jnt_03')
    cmds.DisconnectJoint(charName + '_spline_Jnt_03')
    cmds.rename(charName + '_spline_Jnt_03', charName + '_neck_Jnt_00')
    cmds.rename('joint1', charName + '_spline_Jnt_03')
    cmds.rename(charName + '_root' + '_Jnt_01', charName + '_spline_Jnt_00')
    cmds.parent(charName + '_R_hip_Jnt_01', w=True)
    cmds.parent(charName + '_L_hip_Jnt_01', w=True)
    cmds.select(d=True)
    cmds.joint(p=(locXYZ[0][0], locXYZ[0][1], locXYZ[0][2]),
               n=charName + '_root' + '_Jnt_01')
    cmds.parent(charName + '_L_hip_Jnt_01')
    cmds.select(charName + '_root' + '_Jnt_01')
    cmds.parent(charName + '_R_hip_Jnt_01')
    cmds.curve(n=charName + '_SplineIK_Crv_01',
               p=[(locXYZ[0][0], locXYZ[0][1], locXYZ[0][2]),
                  (0.0, locXYZ[0][1] + lengthY * 0.43,
                   locXYZ[0][2] + lengthZ * 0.43),
                  (0.0, locXYZ[0][1] + lengthY * 0.8,
                   locXYZ[0][2] + lengthZ * 0.18),
                  (locXYZ[1][0], locXYZ[1][1], locXYZ[1][2])])
    cmds.ikHandle(n=charName + 'SplineIK_01',
                  sj=charName + '_spline_Jnt_00',
                  ee=charName + '_spline_Jnt_03',
                  curve=charName + '_SplineIK_Crv_01',
                  sol='ikSplineSolver',
                  createCurve=False,
                  parentCurve=False)
    for i in range(4):
        cmds.select(charName + '_SplineIK_Crv_01' + '.cv[' + str(i) + ']')
        cmds.cluster(n='cluster_' + str(i + 1))
    CreateCtr(charName + '_Spline_Ctrl_01', 'cluster_1Handle',
              (0, locXYZ[0][1] * 1.05, 0),
              (lengthY / 60 * 25, lengthY / 60 * 25, lengthY / 60 * 25),
              (0, 0, 0))
    cmds.parentConstraint(charName + '_Spline_Ctrl_01',
                          charName + '_root_Jnt_01',
                          maintainOffset=True)
    CreateCtr(charName + '_Chest_Ctrl_01', 'cluster_4Handle',
              (0, locXYZ[1][1], 0),
              (lengthY / 60 * 25, lengthY / 60 * 25, lengthY / 60 * 25),
              (0, 0, 0))
    for i in range(len(side)):
        cmds.parentConstraint(charName + '_Chest_Ctrl_01',
                              charName + side[i] + 'shoulder_Jnt_01',
                              maintainOffset=True)
        cmds.parent('Arm' + side[i] + 'Crl_grp', charName + '_Chest_Ctrl_01')
        cmds.parent('Elbow' + side[i] + 'Crl', charName + '_Chest_Ctrl_01')
    CreateCtr(charName + '_Chest_Ctrl_02', 'cluster_2Handle',
              (0, (locXYZ[0][1] + locXYZ[1][1]) / 2, 0),
              (lengthY / 60 * 20, lengthY / 60 * 20, lengthY / 60 * 20),
              (0, 0, 0))
    cmds.parentConstraint(charName + '_Chest_Ctrl_01',
                          charName + '_neck_Jnt_00',
                          maintainOffset=True,
                          w=1)
    cmds.parentConstraint(charName + '_Chest_Ctrl_01',
                          'cluster_3Handle',
                          maintainOffset=True,
                          weight=0.5)
    cmds.parentConstraint(charName + '_Chest_Ctrl_01',
                          charName + '_Chest_Ctrl_02_grp',
                          maintainOffset=True,
                          weight=0.5)
    cmds.parentConstraint(charName + '_Spline_Ctrl_01',
                          charName + '_Chest_Ctrl_02_grp',
                          maintainOffset=True,
                          weight=0.5)
    cmds.CreateNURBSCircle()
    cmds.rename('nurbsCircle1', charName + '_Hip_Ctrl_01')
    cmds.move(0, locXYZ[0][1], 0)
    cmds.scale(lengthY / 60 * 30, lengthY / 60 * 30, lengthY / 60 * 30)
    cmds.makeIdentity(apply=True)
    cmds.parentConstraint(charName + '_Hip_Ctrl_01',
                          charName + '_Spline_Ctrl_01',
                          maintainOffset=True,
                          weight=0.5)
    cmds.parentConstraint(charName + '_Hip_Ctrl_01',
                          charName + '_Chest_Ctrl_01',
                          maintainOffset=True,
                          weight=0.5)
    #clean
    for i in range(len(side)):
        cmds.parent(charName + side[i] + 'shoulder_Jnt_01',
                    charName + '_Joints_01')
        cmds.parent(charName + '_Chest_Ctrl_0' + str(i + 1) + '_grp',
                    charName + '_Controls_01')
        cmds.parent('Foot' + side[i] + '1', charName + '_Controls_01')
        cmds.parent('Foot' + side[i] + 'Crl_grp', charName + '_Controls_01')
        cmds.parent('Arm' + side[i] + 'ikHandle', charName + '_ikHandle_01')
        cmds.parent('cluster_' + str(i + 1) + 'Handle',
                    charName + '_ikHandle_01')
        cmds.parent('cluster_' + str(i + 3) + 'Handle',
                    charName + '_ikHandle_01')
    cmds.parent(charName + 'SplineIK_01', charName + '_ikHandle_01')
    cmds.parent(charName + '_SplineIK_Crv_01', charName + '_ikHandle_01')
    cmds.parent(charName + '_neck_Jnt_00', charName + '_Joints_01')
    cmds.parent(charName + '_root_Jnt_01', charName + '_Joints_01')
    cmds.parent(charName + '_spline_Jnt_00', charName + '_Joints_01')
    cmds.parent(charName + '_Spline_Ctrl_01_grp', charName + '_Controls_01')
    cmds.parent(charName + '_Hip_Ctrl_01', charName + '_Controls_01')
Exemplo n.º 49
0
    def save(self, dirName=None, assetName=None, dataType=None):
        #--- this method saves the data
        attr = attribute.Attribute()
        sel = cmds.ls('*_GCTL', type='transform')
        data = list()
        shape = list()
        locator = list()
        if dataType == 'guides':
            #--- save the guides
            for i in sel:
                list_attr = cmds.listAttr(i, keyable=True, visible=True)
                value_list = []
                for attrs in list_attr:
                    value = attr.getAttr(node=i, attribute=attrs)
                    result = (str(i) + '.' + str(attrs), str(value))
                    value_list.append(result)
                data.append(value_list)
            self.write_data(dirName=dirName,
                            folder='data',
                            fileName=assetName,
                            obj=data)
            print 'GuideData saved!'

        elif dataType == 'weights':
            #--- get the skinClusters, meshes and shapes
            w = skinweight.Weights()
            skins = w.get_skin_weights()
            folder = os.path.join('data', dirName)
            #--- create a new character folder if it does not exist
            self.new_data_folder(folder=folder, dirName=assetName)
            for mesh, shape, skin in zip(skins[0], skins[1], skins[2]):
                data_path = os.path.join(self.root, 'data', dirName, assetName)
                file_name = mesh + '.xml'
                cmds.deformerWeights(file_name,
                                     path=data_path,
                                     shape=shape,
                                     export=True,
                                     deformer=skin)
            print 'WeightData saved'

        elif dataType == 'locators':
            #--- save all the information provided by the custom locators
            sel = cmds.ls('*_*CTLShape')
            for i in sel:
                obj_type = cmds.nodeType(i)
                if obj_type == 'eLocator':
                    attrs = cmds.listAttr(i, locked=True, unlocked=True)
                    for attr in attrs:
                        if not 'localScale' in attr:
                            if (attr == 'size' or attr == 'shape'
                                    or attr == 'orientation' or attr == 'width'
                                    or attr == 'localPositionX'
                                    or attr == 'localPositionY'
                                    or attr == 'localPositionZ'):
                                value = cmds.getAttr(i + '.' + attr)
                                result = [i, attr, value]
                                locator.append(result)
                else:
                    raise Exception('There is no eLocator shape of this node!')
            self.write_data(dirName=dirName,
                            folder='data',
                            fileName=assetName,
                            obj=locator)
            print 'LocatorData saved!'

        elif dataType == 'shapes':
            #--- save all curve shape information
            for i in sel:
                shape_type = cmds.listRelatives(i,
                                                allDescendents=True,
                                                shapes=True)
                obj_type = cmds.objectType(shape_type)
                if obj_type == 'nurbsCurve' or obj_type == 'nurbsSurface':
                    curve = cmds.ls(i + '.cv[*]', flatten=True)
                    for cv in curve:
                        pos = cmds.xform(cv,
                                         query=True,
                                         translation=True,
                                         worldSpace=True)
                        result = [i, pos]
                        shape.append(result)
                elif obj_type == 'mesh':
                    vertices = cmds.ls(i + '.vtx[*]', flatten=True)
                    for vtx in vertices:
                        pos = cmds.xform(vtx,
                                         query=True,
                                         translation=True,
                                         worldSpace=True)
                        result = [i, pos]
                        shape.append(result)
                else:
                    raise Exception('There is no component mode of this node!')
            self.write_data(dirName=dirName,
                            folder='data',
                            fileName=assetName,
                            obj=shape)
            print 'ShapeData saved!'
Exemplo n.º 50
0
def capture(camera=None,
            width=None,
            height=None,
            filename=None,
            start_frame=None,
            end_frame=None,
            frame=None,
            format='qt',
            compression='H.264',
            quality=100,
            off_screen=False,
            viewer=True,
            show_ornaments=True,
            sound=None,
            isolate=None,
            maintain_aspect_ratio=True,
            overwrite=False,
            frame_padding=4,
            raw_frame_numbers=False,
            camera_options=None,
            display_options=None,
            viewport_options=None,
            viewport2_options=None,
            complete_filename=None):
    """Playblast in an independent panel

    Arguments:
        camera (str, optional): Name of camera, defaults to "persp"
        width (int, optional): Width of output in pixels
        height (int, optional): Height of output in pixels
        filename (str, optional): Name of output file. If
            none is specified, no files are saved.
        start_frame (float, optional): Defaults to current start frame.
        end_frame (float, optional): Defaults to current end frame.
        frame (float or tuple, optional): A single frame or list of frames.
            Use this to capture a single frame or an arbitrary sequence of
            frames.
        format (str, optional): Name of format, defaults to "qt".
        compression (str, optional): Name of compression, defaults to "H.264"
        off_screen (bool, optional): Whether or not to playblast off screen
        viewer (bool, optional): Display results in native player
        show_ornaments (bool, optional): Whether or not model view ornaments
            (e.g. axis icon, grid and HUD) should be displayed.
        sound (str, optional):  Specify the sound node to be used during
            playblast. When None (default) no sound will be used.
        isolate (list): List of nodes to isolate upon capturing
        maintain_aspect_ratio (bool, optional): Modify height in order to
            maintain aspect ratio.
        overwrite (bool, optional): Whether or not to overwrite if file
            already exists. If disabled and file exists and error will be
            raised.
        frame_padding (bool, optional): Number of zeros used to pad file name
            for image sequences.
        raw_frame_numbers (bool, optional): Whether or not to use the exact
            frame numbers from the scene or capture to a sequence starting at
            zero. Defaults to False. When set to True `viewer` can't be used
            and will be forced to False.
        camera_options (dict, optional): Supplied camera options,
            using `CameraOptions`
        display_options (dict, optional): Supplied display
            options, using `DisplayOptions`
        viewport_options (dict, optional): Supplied viewport
            options, using `ViewportOptions`
        viewport2_options (dict, optional): Supplied display
            options, using `Viewport2Options`
        complete_filename (str, optional): Exact name of output file. Use this
            to override the output of `filename` so it excludes frame padding.

    Example:
        >>> # Launch default capture
        >>> capture()
        >>> # Launch capture with custom viewport settings
        >>> capture('persp', 800, 600,
        ...         viewport_options={
        ...             "displayAppearance": "wireframe",
        ...             "grid": False,
        ...             "polymeshes": True,
        ...         },
        ...         camera_options={
        ...             "displayResolution": True
        ...         }
        ... )


    """

    camera = camera or "persp"

    # Ensure camera exists
    if not cmds.objExists(camera):
        raise RuntimeError("Camera does not exist: {0}".format(camera))

    width = width or cmds.getAttr("defaultResolution.width")
    height = height or cmds.getAttr("defaultResolution.height")
    if maintain_aspect_ratio:
        ratio = cmds.getAttr("defaultResolution.deviceAspectRatio")
        height = round(width / ratio)

    if start_frame is None:
        start_frame = cmds.playbackOptions(minTime=True, query=True)
    if end_frame is None:
        end_frame = cmds.playbackOptions(maxTime=True, query=True)

    # We need to wrap `completeFilename`, otherwise even when None is provided
    # it will use filename as the exact name. Only when lacking as argument
    # does it function correctly.
    playblast_kwargs = dict()
    if complete_filename:
        playblast_kwargs['completeFilename'] = complete_filename
    if frame is not None:
        playblast_kwargs['frame'] = frame
    if sound is not None:
        playblast_kwargs['sound'] = sound

    # (#21) Bugfix: `maya.cmds.playblast` suffers from undo bug where it
    # always sets the currentTime to frame 1. By setting currentTime before
    # the playblast call it'll undo correctly.
    cmds.currentTime(cmds.currentTime(q=1))

    padding = 10  # Extend panel to accommodate for OS window manager
    with _independent_panel(width=width + padding,
                            height=height + padding,
                            off_screen=off_screen) as panel:
        cmds.setFocus(panel)

        with contextlib.nested(
                _disabled_inview_messages(), _maintain_camera(panel, camera),
                _applied_viewport_options(viewport_options, panel),
                _applied_camera_options(camera_options, panel),
                _applied_display_options(display_options),
                _applied_viewport2_options(viewport2_options),
                _isolated_nodes(isolate, panel), _maintained_time()):

            output = cmds.playblast(compression=compression,
                                    format=format,
                                    percent=100,
                                    quality=quality,
                                    viewer=viewer,
                                    startTime=start_frame,
                                    endTime=end_frame,
                                    offScreen=off_screen,
                                    showOrnaments=show_ornaments,
                                    forceOverwrite=overwrite,
                                    filename=filename,
                                    widthHeight=[width, height],
                                    rawFrameNumbers=raw_frame_numbers,
                                    framePadding=frame_padding,
                                    **playblast_kwargs)

        return output
Exemplo n.º 51
0
def flexi_loft(add_ik=0, bind=0, loft=0, cluster=0, stretchy=0, name=""):
    raw_curves = mc.ls(sl=1)
    curves = []
    ik_handle_list = []
    ik_spline_crv_list = []
    joint_list = []
    joint_chain_dict = {}
    grp_list = []

    # Creating brand new, clean curves out of selection
    for j, n in enumerate(raw_curves, 1):
        new_curve = mc.duplicate(n, n="{}_Loft_Crv{}".format(name, j))
        try:
            mc.parent(new_curve, w=1)
        except:
            pass
        mc.makeIdentity(new_curve, apply=True, t=1, r=1, s=1, n=0)
        mc.delete(new_curve, ch=1)
        mc.xform(new_curve, cp=1)
        curves.append(new_curve[0])

    # Joint chain and ikSpline section
    for n, n in enumerate(curves):
        crv_joint_list = joint_on_curve_cvs(path_crv=n)
        parent_in_order(sel=crv_joint_list)
        mc.joint(crv_joint_list, e=1, oj="xyz", secondaryAxisOrient="yup")
        joint_chain_dict.update({n: crv_joint_list})
        joint_list.append(crv_joint_list[0])
        mc.select(cl=1)

        if add_ik == 1:
            # Creating ikSpline - rename curve - append to grouping lists
            ik_handle_data = mc.ikHandle(sj=crv_joint_list[0],
                                         ee=crv_joint_list[-1],
                                         sol="ikSplineSolver",
                                         n=n + "_ikHandle")
            ik_crv = mc.rename(ik_handle_data[2],
                               "{}_ikSpline_Crv{}".format(name, n + 1))
            ik_handle_list.append(ik_handle_data[0])
            ik_spline_crv_list.append(ik_crv)

            if stretchy == 1:
                make_stretchy_spline(crv_joint_list, ik_crv, new_curve[0])

            if n == 0:
                # If it is the first loop - create groups - else - parent new items
                ik_grp = mc.group(ik_handle_data[0], n=name + "_ikHandle_Grp")
                spline_grp = mc.group(ik_crv, n=name + "_ikSpline_Crv_Grp")
                grp_list.append(ik_grp)
                grp_list.append(spline_grp)
            else:
                mc.parent(ik_handle_data[0], ik_grp)
                mc.parent(ik_crv, spline_grp)

        if bind == 1:
            mc.skinCluster(crv_joint_list, n)

    if loft == 1:
        loft_data = mc.loft(curves,
                            ch=1,
                            u=1,
                            c=0,
                            ar=0,
                            d=3,
                            ss=10,
                            rn=0,
                            po=1,
                            rsn=1)
        loft_srf = mc.rename(loft_data[0], name + "_LoftSrf_Geo")
        loft_grp = mc.group(loft_srf, n=name + "_LoftSrf_Geo_Grp")
        grp_list.append(loft_grp)

    if cluster == 1 and add_ik == 1:
        # Creates clusters holding the same cv on each ikSpline curve
        # Calculating the number of Cv's for loop
        curve_deg = mc.getAttr(ik_spline_crv_list[0] + ".degree")
        curve_spa = mc.getAttr(ik_spline_crv_list[0] + ".spans")
        # CV's = degrees + spans
        cv_count = curve_deg + curve_spa
        cls_list = []

        for n in range(cv_count):
            mc.select(cl=1)
            for j in ik_spline_crv_list:
                mc.select("{}.cv[{}]".format(j, n), add=1)
            cluster = mc.cluster(n="{}_Csl{}".format(name, n))
            cls_list.append(cluster[1])

        cluster_grp = mc.group(cls_list, n=name + "_Cls_Grp")
        grp_list.append(cluster_grp)

    else:
        mc.warning("addIk is off")

    curves_grp = mc.group(curves, n="{}_Loft_Crv_Grp".format(name))
    joint_grp = mc.group(joint_list, n=name + "_Jnt_Grp")
    grp_list.append(curves_grp)
    grp_list.append(joint_grp)
    sys_grp = mc.group(grp_list, n=name + "_Sys_Grp")

    return sys_grp
Exemplo n.º 52
0
    def testImportScope(self):
        cmds.usdImport(file=self.USD_FILE, primPath='/')
        dagObjects = cmds.ls(long=True, dag=True)

        self.assertIn('|A', dagObjects)
        self.assertEqual(cmds.nodeType('|A'), 'transform')
        self.assertFalse(cmds.getAttr('|A.tx', lock=True))

        self.assertIn('|A|A_1', dagObjects)
        self.assertEqual(cmds.nodeType('|A|A_1'), 'transform')
        self.assertEqual(cmds.getAttr('|A|A_1.USD_typeName'), 'Scope')
        self.assertTrue(cmds.getAttr('|A|A_1.tx', lock=True))

        self.assertIn('|A|A_1|A_1_I', dagObjects)
        self.assertEqual(cmds.nodeType('|A|A_1|A_1_I'), 'transform')
        self.assertFalse(cmds.getAttr('|A|A_1|A_1_I.tx', lock=True))

        self.assertIn('|A|A_1|A_1_II', dagObjects)
        self.assertEqual(cmds.nodeType('|A|A_1|A_1_II'), 'transform')
        self.assertFalse(cmds.getAttr('|A|A_1|A_1_II.tx', lock=True))

        self.assertIn('|A|A_1|A_1_III', dagObjects)
        self.assertEqual(cmds.nodeType('|A|A_1|A_1_III'), 'transform')
        self.assertEqual(cmds.getAttr('|A|A_1|A_1_III.USD_typeName'), 'Scope')
        self.assertTrue(cmds.getAttr('|A|A_1|A_1_III.tx', lock=True))

        self.assertIn('|A|A_2', dagObjects)
        self.assertEqual(cmds.nodeType('|A|A_2'), 'transform')
        self.assertEqual(cmds.getAttr('|A|A_2.USD_typeName'), 'Scope')
        self.assertTrue(cmds.getAttr('|A|A_2.tx', lock=True))

        self.assertIn('|B', dagObjects)
        self.assertEqual(cmds.nodeType('|B'), 'transform')
        self.assertEqual(cmds.getAttr('|B.USD_typeName'), 'Scope')
        self.assertTrue(cmds.getAttr('|B.tx', lock=True))

        self.assertIn('|B|B_1', dagObjects)
        self.assertEqual(cmds.nodeType('|B|B_1'), 'transform')
        self.assertFalse(cmds.getAttr('|B|B_1.tx', lock=True))
Exemplo n.º 53
0
 def __getattr__(self, name):
     return mc.getAttr('%s.%s' % (mc.ls(self.__dict__['__UUID'])[0], name))
Exemplo n.º 54
0
	def getAllMeshs(self):
		meshsList=[]
		allmeshs=cmds.ls(type='mesh')
		if allmeshs:
			[meshsList.append(mesh) for mesh in allmeshs if not cmds.getAttr('%s.intermediateObject'%mesh)]
		return meshsList
Exemplo n.º 55
0
def getColorBalanceAttributes():
    texture = getCurrentSelectedTexture()

    for value in values:
        dic[value] = mc.getAttr('%s.%s' % (texture[0], value))
    return dic
Exemplo n.º 56
0
def validateSkeleton(root, *args, **kwargs):
    '''
	Go through skeleton hierarchy and check for these things:
		- Joint Labels:
			- Side not set to None
			- Type not set to None
		- Joint Orient XYZ set to zero
		- Translate YX set to zero
		- Rotate XYZ set to zero
		- Segment Scale Compensate set to off
		- If Inverse Scale is disconnected
		- Has message attributes for metadata relationships
		- Duplicates

	:return:
	'''
    debugList = []

    print '\n\n'
    # Logger
    log = Validator('Skeleton Validator')
    log.setLevel(logging.DEBUG)

    if nodeType(root) != 'joint':
        log.fatal('Must provide a root joint.')
        return

    else:
        children = cmds.listRelatives(root, ad=True, type='joint')
        if not children:
            log.fatal('Skeleton has no hierarchy.')
            return
        else:
            children.insert(0, root)
            log.info('Length of Skeleton: {}'.format(len(children)))
            print ''

            for item in sorted(children):

                joint = Joint(str(item))
                debug = False

                if not joint.isValid():
                    log.fatal('{} : does not exist in scene.'.format(joint))
                else:
                    if item != root:
                        if joint.otherType.lower() not in ['leaf', 'bind']:

                            # Translate
                            for axis in ['y', 'z']:
                                attrName = 'translate{}'.format(axis.upper())
                                value = getattr(joint, attrName)

                                if value != 0:
                                    log.debug('{} : {} : {}'.format(
                                        joint, attrName, value))
                                    debug = True

                            # Joint Orient
                            value = [
                                0.0 if 'e-' in str(x) else x
                                for x in joint.jointOrient
                            ]
                            zeroCount = 3 - value.count(0.0)

                            if zeroCount >= 2:
                                log.debug(
                                    '{} : has {} of 3 Joint Orients'.format(
                                        joint, zeroCount))
                                debug = True

                    # Rotate / Scale
                    for attr in ['rotate', 'scale']:
                        for axis in ['x', 'y', 'z']:
                            attrName = '{}{}'.format(attr, axis.upper())
                            value = getattr(joint, attrName)

                            if attr == 'rotate':
                                if value != 0:
                                    log.debug('{} : {} : {}'.format(
                                        joint, attrName, value))
                                    debug = True
                            else:
                                if value != 1:
                                    log.debug('{} : {} : {}'.format(
                                        joint, attrName, value))
                                    debug = True

                    # Labels
                    if joint.type == 'none':
                        log.debug('{} : is missing Type Label'.format(joint))
                        debug = True

                    elif joint.type == 'other':
                        if not joint.otherType:
                            log.debug('{} : is missing OtherType Label'.format(
                                joint))
                            debug = True

                    if joint.side == 'none':
                        log.debug('{} : is missing Side Label'.format(joint))
                        debug = True

                    # Segment Scale
                    if cmds.getAttr('{}.{}'.format(
                            joint, MayaAttr.segmentScaleCompensate)):
                        log.debug('{} : has Segment Scale'.format(joint))
                        debug = True

                # Debug
                if debug:
                    if joint not in debugList:
                        debugList.append(joint)
                        print ''

        cmds.select(debugList)
        print '\n\n# Skeleton Validator : Validator Finished. View Script Editor for details. #',
        return debugList
Exemplo n.º 57
0
 def path(self):
     if self.isLoaded and self.audioNode:
         return cmds.getAttr('%s.filename' % self.audioNode)
     else:
         return self.__path
Exemplo n.º 58
0
def transfer_weight(skinMesh,
                    transferedMesh,
                    transferWeight=True,
                    returnInfluences=False,
                    logTransfer=True):
    '''
    スキンウェイトの転送関数
    転送先がバインドされていないオブジェクトの場合は転送元のバインド情報を元に自動バインド
    ・引数
    skinMesh→転送元メッシュ(1個,リスト形式でも可)
    transferedMesh(リスト形式,複数可、リストじゃなくても大丈夫)
    transferWeight→ウェイトを転送するかどうか。省略可能、デフォルトはTrue
    logTransfer→ログ表示するかどうか
    returnInfluences→バインドされているインフルエンス情報を戻り値として返すかどうか。省略可能、デフォルトはFalse
    '''

    massege01 = lang.Lang(
        en=
        ': It does not perform the transfer of weight because it is not a skin mesh.',
        ja=u': スキンメッシュではないのでウェイトの転送を行いません').output()
    massege02 = lang.Lang(en='Transfer the weight:', ja=u'ウェイトを転送:').output()
    massege03 = lang.Lang(en='Transfer bind influences:',
                          ja=u'バインド状態を転送:').output()

    if isinstance(skinMesh, list):  # 転送元がリストだった場合、最初のメッシュのみ取り出す
        skinMesh = skinMesh[0]  # リストを渡されたときのための保険

    # ノードの中からスキンクラスタを取得してくる#inMesh直上がSkinClusterとは限らないので修正
    srcSkinCluster = cmds.ls(cmds.listHistory(skinMesh), type='skinCluster')
    # srcSkinCluster = cmds.listConnections(skinMesh+'.inMesh', s=True, d=False)
    if not srcSkinCluster:
        if logTransfer:
            print skinMesh + massege01
        return False  # スキンクラスタがなかったら関数抜ける
    # スキンクラスタのパラメータ色々を取得しておく
    srcSkinCluster = srcSkinCluster[0]
    skinningMethod = cmds.getAttr(srcSkinCluster + ' .skm')
    dropoffRate = cmds.getAttr(srcSkinCluster + ' .dr')
    maintainMaxInfluences = cmds.getAttr(srcSkinCluster + ' .mmi')
    maxInfluences = cmds.getAttr(srcSkinCluster + ' .mi')
    bindMethod = cmds.getAttr(srcSkinCluster + ' .bm')
    normalizeWeights = cmds.getAttr(srcSkinCluster + ' .nw')
    influences = cmds.skinCluster(srcSkinCluster, q=True,
                                  inf=True)  # qフラグは照会モード、ちなみにeは編集モード

    # リストタイプじゃなかったらリストに変換する
    if not isinstance(transferedMesh, list):
        temp = transferedMesh
        transferedMesh = []
        transferedMesh.append(temp)

    for dst in transferedMesh:
        #子供のノード退避用ダミーペアレントを用意
        dummy = general.TemporaryReparent().main(mode='create')
        general.TemporaryReparent().main(dst, dummyParent=dummy, mode='cut')

        shapes = cmds.listRelatives(dst, s=True, pa=True, type='mesh')
        if not shapes:  # もしメッシュがなかったら
            continue  # 処理を中断して次のオブジェクトへ
        # スキンクラスタの有無を取得
        dstSkinCluster = cmds.ls(cmds.listHistory(shapes[0]),
                                 type='skinCluster')
        # スキンクラスタがない場合はあらかじめ取得しておいた情報をもとにバインドする
        if not dstSkinCluster:
            # バインド
            dstSkinCluster = cmds.skinCluster(
                dst,
                influences,
                omi=maintainMaxInfluences,
                mi=maxInfluences,
                dr=dropoffRate,
                sm=skinningMethod,
                nw=normalizeWeights,
                tsb=True,
            )
            if logTransfer:
                print massege03 + '[' + skinMesh + '] >>> [' + dst + ']'
        dstSkinCluster = dstSkinCluster[0]

        if transferWeight:
            cmds.copySkinWeights(
                ss=srcSkinCluster,
                ds=dstSkinCluster,
                surfaceAssociation='closestPoint',
                influenceAssociation=['name', 'closestJoint', 'oneToOne'],
                normalize=True,
                noMirror=True)
            if logTransfer:
                print massege02 + '[' + skinMesh + '] >>> [' + dst + ']'
        #親子付けを戻す
        general.TemporaryReparent().main(dst, dummyParent=dummy, mode='parent')
        #ダミーペアレントを削除
        general.TemporaryReparent().main(dummyParent=dummy, mode='delete')
    if returnInfluences:
        return influences
    else:
        return True
Exemplo n.º 59
0
    def combineAudio(self, filepath):
        '''
        Combine audio tracks into a single wav file. This by-passes
        the issues with Maya not playblasting multiple audio tracks.

        :param filepath: filepath to store the combined audioTrack
        TODO: Deal with offset start and end data + silence
        '''
        status = True
        failed = []
        if not len(self.audioNodes) > 1:
            raise ValueError(
                'We need more than 1 audio node in order to compile')

        for audio in cmds.ls(type='audio'):
            audioNode = AudioNode(audio)
            if audioNode.path == filepath:
                if audioNode.isCompiled:
                    log.info('Deleting currently compiled Audio Track : %s' %
                             audioNode.path)
                    if audioNode in self.audioNodes:
                        self.audioNodes.remove(audioNode)
                    audioNode.delete()
                    break
                else:
                    raise IOError(
                        'Combined Audio path is already imported into Maya')

        frmrange = self.getOverallRange()
        neg_adjustment = 0
        if frmrange[0] < 0:
            neg_adjustment = frmrange[0]

        duration = ((frmrange[1] + abs(neg_adjustment)) /
                    r9General.getCurrentFPS()) * 1000
        log.info('Audio BaseTrack duration = %f' % duration)
        baseTrack = audio_segment.AudioSegment.silent(duration)

        for audio in self.audioNodes:
            if not os.path.exists(audio.path):
                log.warning('Audio file not found!  : "%s" == %s' %
                            (audio.audioNode, audio.path))
                status = False
                failed.append(audio)
                continue
            # deal with any trimming of the audio node in Maya
            sourceStart = cmds.getAttr(audio.audioNode + '.sourceStart')
            sourceEnd = cmds.getAttr(audio.audioNode + '.sourceEnd')
            sound = audio_segment.AudioSegment.from_wav(
                audio.path)[(sourceStart / r9General.getCurrentFPS()) *
                            1000:(sourceEnd / r9General.getCurrentFPS()) *
                            1000]
            # sound = audio_segment.AudioSegment.from_wav(audio.path)
            if sound.sample_width not in [1, 2, 4]:
                log.warning(
                    '24bit Audio is NOT supported in Python audioop lib!  : "%s" == %i'
                    % (audio.audioNode, sound.sample_width))
                status = False
                failed.append(audio)
                continue
            insertFrame = (audio.startFrame + abs(neg_adjustment))
            log.info('inserting sound : %s at %f adjusted to %f' %
                     (audio.audioNode, audio.startFrame, insertFrame))
            baseTrack = baseTrack.overlay(
                sound,
                position=(insertFrame / r9General.getCurrentFPS()) * 1000)

        baseTrack.export(filepath, format="wav")
        compiled = AudioNode(filepath=filepath)
        compiled.importAndActivate()
        compiled.stampCompiled(self.mayaNodes)
        compiled.startFrame = neg_adjustment

        if not status:
            raise StandardError(
                'combine completed with errors: see script Editor for details')
Exemplo n.º 60
0
    def hand_system(self):
        """
        """
        meta_jnts_children_pos = []
        if self.meta_jnt_index == "" or self.meta_jnt_middle == "" or self.meta_jnt_ring == "" or self.meta_jnt_pinky == "":
            print "#### ---- One or more than one meta_jnts joint not provided. Module skipped!!! ---- ####"
        else:

            for i, key in enumerate(self.meta_jnts_relatives):
                tmp_relatives = cmds.listRelatives(
                    self.meta_jnts_relatives[key]['jnt_name'], children=True)
                tmp_joints = []
                for obj in tmp_relatives:
                    if cmds.nodeType(obj) == "joint":
                        tmp_joints.append(obj)
                        meta_jnts_children_pos.append(
                            cmds.xform(obj,
                                       worldSpace=True,
                                       query=True,
                                       translation=True))
                self.meta_jnts_relatives[key]['list_children'] = tmp_joints

            crv = cmds.curve(point=meta_jnts_children_pos, degree=3)
            cup_driver_crv = cmds.rename(
                crv, "{}_{}_nucklesDriver_CRV".format(self.side, self.name))

            # query the cup_driver_crv's CVs
            degs = cmds.getAttr("{}.degree".format(cup_driver_crv))
            spans = cmds.getAttr("{}.spans".format(cup_driver_crv))
            cvs = degs + spans

            locator_drivers = []
            cup_joints = []
            # creating the joints driver
            for i, key in enumerate(self.meta_jnts_relatives):
                # creating the spaceLocator which will drive the aiming of the
                driver_loc = cmds.spaceLocator(
                    name="{}_{}_{}_LOC".format(self.side, self.name, key))
                locator_drivers.append(driver_loc[0])
                transforms_utils.align_objs(
                    self.meta_jnts_relatives[key]["list_children"][0],
                    driver_loc)

                # attach the spaceLocator to curve
                point = OM.MPoint(meta_jnts_children_pos[i][0],
                                  meta_jnts_children_pos[i][1],
                                  meta_jnts_children_pos[i][2])
                parameter = curves_utils.get_param_at_point(
                    cup_driver_crv + "Shape", point)
                motion_path_node = cmds.createNode("motionPath",
                                                   name="{}_{}_{}_MPT".format(
                                                       self.side, self.name,
                                                       key))
                cmds.setAttr("{}.uValue".format(motion_path_node), parameter)
                cmds.connectAttr(
                    "{}Shape.worldSpace[0]".format(cup_driver_crv),
                    "{}.geometryPath".format(motion_path_node),
                    force=True)
                cmds.connectAttr("{}.xCoordinate".format(motion_path_node),
                                 "{}.translateX".format(driver_loc[0]),
                                 force=True)
                cmds.connectAttr("{}.yCoordinate".format(motion_path_node),
                                 "{}.translateY".format(driver_loc[0]),
                                 force=True)
                cmds.connectAttr("{}.zCoordinate".format(motion_path_node),
                                 "{}.translateZ".format(driver_loc[0]),
                                 force=True)

                # do aiming between the driver locator and the meta_jnt joint
                cmds.aimConstraint(driver_loc[0],
                                   self.meta_jnts_relatives[key]["jnt_name"],
                                   maintainOffset=True,
                                   worldUpType="objectrotation",
                                   worldUpVector=[0, 1, 0],
                                   worldUpObject=driver_loc[0])
                # scale fix
                for axis in ["X", "Y", "Z"]:
                    cmds.connectAttr(
                        "{}.scale{}".format(self.root_trf, axis),
                        "{}.scale{}".format(
                            self.meta_jnts_relatives[key]["jnt_name"], axis),
                        force=True)

                if i == 0:
                    joint_cup_end = cmds.createNode(
                        "joint",
                        name="{}_{}_jointCup_endDriver_JNT".format(
                            self.side, self.name))
                    cup_joints.append(joint_cup_end)
                    transforms_utils.align_objs(
                        self.meta_jnts_relatives[key]["list_children"][0],
                        joint_cup_end)
                    cmds.makeIdentity(joint_cup_end,
                                      apply=True,
                                      translate=True,
                                      rotate=True,
                                      scale=True,
                                      normal=False,
                                      preserveNormals=True)
                    self.end_cup_ctrl = controller.Control(
                        "{}_{}_endCup".format(self.side, self.name), 5.0,
                        'cube', joint_cup_end, joint_cup_end, "", ['s', 'v'],
                        '', True, True, False)
                    cmds.parentConstraint(self.end_cup_ctrl.get_control(),
                                          joint_cup_end,
                                          maintainOffset=True)
                if i == (cvs - 1):
                    joint_cup_start = cmds.createNode(
                        "joint",
                        name="{}_{}_jointCup_startDriver_JNT".format(
                            self.side, self.name))
                    cup_joints.append(joint_cup_start)
                    transforms_utils.align_objs(
                        self.meta_jnts_relatives[key]["list_children"][0],
                        joint_cup_start)
                    cmds.makeIdentity(joint_cup_start,
                                      apply=True,
                                      translate=True,
                                      rotate=True,
                                      scale=True,
                                      normal=False,
                                      preserveNormals=True)
                    self.start_cup_ctrl = controller.Control(
                        "{}_{}_startCup".format(self.side, self.name), 5.0,
                        'cube', joint_cup_start, joint_cup_start, "",
                        ['s', 'v'], '', True, True, False)
                    cmds.parentConstraint(self.start_cup_ctrl.get_control(),
                                          joint_cup_start,
                                          maintainOffset=True)

            # clean things up
            drivers_loc_grp = cmds.group(
                empty=True,
                name="{}_{}_metaJointDriverLocs_GRP".format(
                    self.side, self.name))
            cmds.parent(locator_drivers, drivers_loc_grp)
            cup_joints_grp = cmds.group(
                empty=True,
                name="{}_{}_cupDriverJoints_GRP".format(self.side, self.name))
            cmds.parent(cup_joints, cup_joints_grp)
            drivers_grp = cmds.group(empty=True,
                                     name="{}_{}_driversSystem_GRP".format(
                                         self.side, self.name))
            cmds.parent([cup_driver_crv, drivers_loc_grp, cup_joints_grp],
                        drivers_grp)

            # make skinCluster for drive the crv
            cmds.skinCluster(cup_joints, cup_driver_crv)

            for i in range(0, len(locator_drivers)):
                if i == (len(locator_drivers) - 1):
                    cmds.aimConstraint(locator_drivers[i - 1],
                                       locator_drivers[i],
                                       maintainOffset=True,
                                       worldUpType="objectrotation",
                                       worldUpVector=[0, 1, 0],
                                       worldUpObject=self.root_trf)
                else:
                    cmds.aimConstraint(locator_drivers[i + 1],
                                       locator_drivers[i],
                                       maintainOffset=True,
                                       worldUpType="objectrotation",
                                       worldUpVector=[0, 1, 0],
                                       worldUpObject=self.root_trf)

            self.module_main_grp([drivers_grp])

            # cleaning up teh scene
            if cmds.objExists(self.controls_grp):
                cmds.parentConstraint(self.root_trf,
                                      self.controls_grp,
                                      maintainOffset=False)
                for axis in ["X", "Y", "Z"]:
                    cmds.connectAttr("{}.scale{}".format(self.root_trf, axis),
                                     "{}.scale{}".format(
                                         self.controls_grp, axis),
                                     force=True)
                cmds.parent([
                    self.end_cup_ctrl.get_offset_grp(),
                    self.start_cup_ctrl.get_offset_grp()
                ], self.controls_grp)
            else:
                cmds.group(empty=True, name=self.controls_grp)
                cmds.parentConstraint(self.root_trf,
                                      self.controls_grp,
                                      maintainOffset=False)
                for axis in ["X", "Y", "Z"]:
                    cmds.connectAttr("{}.scale{}".format(self.root_trf, axis),
                                     "{}.scale{}".format(
                                         self.controls_grp, axis),
                                     force=True)
                cmds.parent([
                    self.end_cup_ctrl.get_offset_grp(),
                    self.start_cup_ctrl.get_offset_grp()
                ], self.controls_grp)