コード例 #1
0
def attrReset( ):
	'''
	This function will reset the attributes on the selected objects in the scene.

	'''
	selected = cmds.ls(sl=True)
	
	# selCB = cmds.channelBox( "mainChannelBox", q=True, sma=True)
	
	for sel in selected:
		# Gathering all the attributes from the object.
		selCB = cmds.listAttr(sel, k=True)
		# Duplicating list because removing from the list your are looping through causes problems.
		newAttrs = selCB[:]
		try:
			[selCB.remove(x) for x in newAttrs if x in cmds.listAttr( selected , k=True, l=True )]
		except TypeError:
			print( "None of the attributes are locked.")
		for attr in selCB:
			attrName = "%s.%s" %(sel,attr)
			print(attrName)

			# Check to see if keyable
			if( cmds.getAttr( attrName, k=True) ):
				# Get default value
				# cmds.attributeQuery( "sx", node="nurbsCircle1", listDefault=True )
					
				attrDV = cmds.attributeQuery( attr, node=sel, listDefault=True)[0]
				print( "Object: %s Setting to Default: %s" %(attrName, attrDV))
				cmds.setAttr( attrName, attrDV )
コード例 #2
0
 def addFloatVariable(self, nodeAttr, varslayout, name=None, value=None):
    n = cmds.columnLayout(varslayout, query=1, numberOfChildren=1)
    
    indexStr = "[%d]" % n
    nameAttr = nodeAttr + indexStr
    valueAttr = nodeAttr.replace("fparam_name", "fparam_value") + indexStr
    
    form = cmds.formLayout(numberOfDivisions=100, parent=varslayout)
    
    rembtn = cmds.button(label="-")
    namefld = cmds.textField(text=("fparam%d" % n if name is None else name))
    vallbl = cmds.text(label="=")
    valfld = cmds.floatField(value=(0.0 if value is None else value))
    
    cmds.setAttr(nameAttr, ("fparam%d" % n if name is None else name), type="string")
    cmds.setAttr(valueAttr, (0.0 if value is None else value))
    
    self.setupVariableNameCallback(nameAttr, namefld)
    self.setupFloatVariableValueCallback(valueAttr, valfld)
    
    cmds.button(rembtn, edit=1, command=lambda *args: self.removeFloatVariable(nodeAttr, varslayout, n))
    
    cmds.formLayout(form, edit=1,
                    attachForm=[(rembtn, "top", 0), (rembtn, "bottom", 0), (rembtn, "left", 0),
                                (namefld, "top", 0), (namefld, "bottom", 0),
                                (vallbl, "top", 0), (vallbl, "bottom", 0),
                                (valfld, "top", 0), (valfld, "bottom", 0)],
                    attachControl=[(namefld, "left", 5, rembtn),
                                   (vallbl, "left", 5, namefld),
                                   (valfld, "left", 5, vallbl)],
                    attachNone=[(rembtn, "right"),
                                (vallbl, "right")],
                    attachPosition=[(namefld, "right", 0, 30),
                                    (valfld, "right", 0, 100)])
コード例 #3
0
ファイル: stranditem.py プロジェクト: nate-w/cadnano2.5
 def updateColor(self, mID, colorname):
     """
     Update the color of the Maya's Mesh Node associated with a this
     StrandItem, this is done by creating a shadingNode for each color or
     connecting the Mesh Mode to an existing shadingNode if one exists
     for a given color.
     """
     m = Mom()
     meshName = "%s%s" % (m.helixMeshName, mID)
     color = QColor(colorname)
     colorval = "%d_%d_%d" % (color.red(), color.green(), color.blue())
     shaderName = "%s%d_%d_%d" % (m.helixShaderName, color.red(),
                                               color.green(),
                                               color.blue())
     if not cmds.objExists(shaderName):
         # Shader does not exist create one
         cmds.shadingNode('lambert', asShader=True, name=shaderName)
         cmds.sets(n="%sSG" % shaderName, r=True, nss=True, em=True)
         cmds.connectAttr("%s.outColor" % shaderName,
                          "%sSG.surfaceShader" % shaderName)
         cmds.setAttr("%s.color" % shaderName,
                      color.redF(), color.greenF(), color.blueF(),
                      type="double3")
         cmds.sets(meshName, forceElement="%sSG" % shaderName)
     else:
         #shader exist connect
         cmds.sets(meshName, forceElement="%sSG" % shaderName)
コード例 #4
0
ファイル: KstRig.py プロジェクト: Leopardob/Kistie
    def create_line_from_2_obj(self, obja, objb, crv_name='_curve_CRV'):
        '''
        Desc:
        Make a line between 2 objects

        Parameter:
        crv_name = name of curve
        pta = first object
        ptb = second object

        Return: Curve name
        '''

        # Define generic curve
        curve=cmds.curve(d=1, p=[(0,0,0),(0,0,0)], k=[0,1], n=crv_name)
        cmds.setAttr(curve+'.overrideEnabled',1)
        cmds.setAttr(curve+'.overrideColor', 13)

        # Making connection in worldSpace using decomposeMatrix
        dMa=cmds.createNode('decomposeMatrix', n='_DMAT')
        dMb=cmds.createNode('decomposeMatrix', n='_DMAT')

        # Connect control worldMatrix to decomposeMatrix.inputMatrix
        KstMaya.node_op(obja+'.worldMatrix','>>', dMa+'.inputMatrix')
        KstMaya.node_op(dMa+'.outputTranslate','>>',curve+'.controlPoints[0]')
        KstMaya.node_op(objb+'.worldMatrix','>>', dMb+'.inputMatrix')
        KstMaya.node_op(dMb+'.outputTranslate','>>',curve+'.controlPoints[1]')
        return curve
コード例 #5
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)
コード例 #6
0
ファイル: spaces.py プロジェクト: bennymuller/glTools
    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)
コード例 #7
0
ファイル: spaceSwitch.py プロジェクト: Italic-/maya-prefs
 def spaceSwitchToken(self, obj, args):
     
     objects, attr, switchTo     = args       
     enumTokens                  = animMod.getTokens(obj, attr)
     value                       = 0
     switchToNum                 = None
     
     for loopToken in enumTokens:
         splitValue = loopToken.split("=")
         
         if splitValue:
             if len(splitValue) > 1:
                 loopToken = splitValue[0]
                 value     = eval(splitValue[1])
         
         
         if switchTo == loopToken:
             switchToNum = value
             break
         
         value += 1
         
         
     if switchToNum != None:  
         cmds.setAttr("%s.%s"%(obj, attr), switchToNum)     
コード例 #8
0
ファイル: sgRigMesh.py プロジェクト: jonntd/mayadev-1
def createMeshInstersectPointObject( sourcePointObject, destPointObject, mesh ):
    
    meshShape = sgModelDag.getShape( mesh )
    
    dcmpSrc = cmds.createNode( 'decomposeMatrix' )
    dcmpDst = cmds.createNode( 'decomposeMatrix' )
    intersectNode = cmds.createNode( 'sgMeshIntersect' )
    
    cmds.connectAttr( sourcePointObject+'.wm', dcmpSrc+'.imat' )
    cmds.connectAttr( destPointObject  +'.wm', dcmpDst+'.imat' )
    
    cmds.connectAttr( mesh+'.wm', intersectNode+'.inputMeshMatrix' )
    cmds.connectAttr( meshShape+'.outMesh', intersectNode+'.inputMesh' )
    cmds.connectAttr( dcmpSrc+'.ot', intersectNode+'.pointSource' )
    cmds.connectAttr( dcmpDst+'.ot', intersectNode+'.pointDest' )

    trObj = cmds.createNode( 'transform' )
    cmds.setAttr( trObj+'.dh', 1 )
    
    crv = cmds.curve( p=[[0,0,0],[0,0,0]], d=1 )
    cmds.setAttr( crv+'.template', 1 )
    crvShape = cmds.listRelatives( crv, s=1 )[0]
    mmdcSource = cmds.createNode( 'sgMultMatrixDecompose' )
    mmdcDest   = cmds.createNode( 'sgMultMatrixDecompose' )
    cmds.connectAttr( sourcePointObject+'.wm', mmdcSource+'.i[0]' )
    cmds.connectAttr( destPointObject+'.wm',   mmdcDest+'.i[0]' )
    cmds.connectAttr( crv+'.wim', mmdcSource+'.i[1]' )
    cmds.connectAttr( crv+'.wim', mmdcDest+'.i[1]' )
    cmds.connectAttr( mmdcSource+'.ot', crvShape+'.controlPoints[0]' )
    cmds.connectAttr( mmdcDest+'.ot',   crvShape+'.controlPoints[1]' )
    
    cmds.connectAttr( trObj+'.pim', intersectNode+'.pim' )
    cmds.connectAttr( intersectNode+'.outPoint', trObj+'.t' )
    
    return trObj, crv
コード例 #9
0
ファイル: baseLimb.py プロジェクト: zethwillie/python_rigger
    def createLocators(self):
        #create list of loc names (self.name)
        for i in range(len(self.jointList)):
            self.locList.append("%s_%s_Loc"%(self.jointList[i],self.limbName))

        #check that these don't exist already
        if (cmds.objExists(self.locList[0])):
            cmds.error("these limb locators exists already!")
        else:

            #fill dictionary - assign values from list
            self.locPos = {}
            for j in range(len(self.locList)):
                self.locPos[self.locList[j]] = self.locPosValues[j]

            #create the locs
            for key in self.locPos.keys():
                thisLoc = cmds.spaceLocator(n=key)
                cmds.move(self.locPos[key][0], self.locPos[key][1], self.locPos[key][2], thisLoc)

            #parent them together (from list of loc names)
            for k in range((len(self.locList)-1),0,-1):
                cmds.parent(self.locList[k], self.locList[k-1])

######### make this true only for the arms. . . or figure out how to extract which rot this should be
            #rotate second joint to just get a preferred angle
            cmds.setAttr("%s.ry"%self.locList[1], -5)
コード例 #10
0
def __createFrustumNode( mainCam, parent, baseName ):
  """
  Private method to this module.
  Create a display frustum node under the given parent.
  Make the default connections between the master camera and the frustum  
  Remove some of the channel box attributes that we do not want to show
  up in the channel box. 
  """

  frustum = cmds.createNode( 'stereoRigFrustum', name=baseName, parent=parent )
  for attr in [ 'localPositionX', 'localPositionY', 'localPositionZ',
                'localScaleX', 'localScaleY', 'localScaleZ' ] :
    cmds.setAttr( frustum + '.' + attr, channelBox=False )

  for attr in ['displayNearClip', 'displayFarClip', 'displayFrustum',
               'zeroParallaxPlane',
               'zeroParallaxTransparency',
               'zeroParallaxColor',
               'safeViewingVolume',
               'safeVolumeTransparency',
               'safeVolumeColor',
               'safeStereo',
               'zeroParallax' ] :
    cmds.connectAttr( mainCam+'.'+attr, frustum+'.'+attr )
    
  return frustum
コード例 #11
0
ファイル: shape.py プロジェクト: eddiehoyle/link
    def set_color(self, position):
        """Change display color of shapes"""

        color = common.get_color_index(position)
        for shape in self.nodes:
            cmds.setAttr("%s.overrideEnabled" % shape, 1)
            cmds.setAttr("%s.overrideColor" % shape, color)
コード例 #12
0
def importPose(filePath):
    """Import the pose data stored in filePath"""
    # try to open the file
    newRootControl = cmds.ls(sl=True, type='transform')[0]
    newNodeAttr = newRootControl.rpartition('_root_')[0]
    try: f = open(filePath, 'r')
    except:
        cmds.confirmDialog(
            t='Error', b=['OK'],
            m='Unable to open file: %s'%filePath
        )
        raise
    # uncPickle the data
    pose = cPickle.load(f)
    # close the file
    f.close()
    # set the attributes to the stored pose
    errAttrs = []
    for attrValue in pose:
        try: 
            cmds.setAttr('%s%s'%(newNodeAttr, attrValue[0]), attrValue[1])
        except:
            try: errAttrs.append(attrValue[0])
            except: errAttrs.append(attrValue)
    # display error message if needed
    if len(errAttrs) > 0:
        importErrorWindow(errAttrs)
        sys.stderr.write('Not all attributes could be loaded.')
コード例 #13
0
ファイル: Red9_Audio.py プロジェクト: jeanim/Red9_StudioPack
 def stampCompiled(self, audioNodes):
     '''
     Used by the compiler - stamp the audioNodes from which this audio
     track was compiled from
     '''
     cmds.addAttr(self.audioNode, longName='compiledAudio', dt='string')
     cmds.setAttr('%s.compiledAudio' % self.audioNode, ','.join(audioNodes), type="string")
コード例 #14
0
    def _publish_gpu_for_item(self, item, output, work_template, primary_publish_path, sg_task, comment, thumbnail_path, progress_cb):
        """
        Export a gpu cache for the specified item and publish it  to Shotgun.
        """
        group_name = item["name"].strip("|")
        debug(app = None, method = '_publish_gpu_for_item', message = 'group_name: %s' % group_name, verbose = False)
        tank_type = output["tank_type"]
        publish_template = output["publish_template"]        
                
        # get the current scene path and extract fields from it using the work template:
        scene_path = os.path.abspath(cmds.file(query=True, sn= True))
        fields = work_template.get_fields(scene_path)
        publish_version = fields["version"]

        # update fields with the group name:
        fields["grp_name"] = group_name

        ## create the publish path by applying the fields with the publish template:
        publish_path = publish_template.apply_fields(fields)
        #'@asset_root/publish/gpu/{name}[_{grp_name}].v{version}.abc'
        gpuFileName = os.path.splitext(publish_path)[0].split('\\')[-1] 
        fileDir = '/'.join(publish_path.split('\\')[0:-1])
        debug(app = None, method = '_publish_gpu_for_item', message = 'gpuFileName: %s' % gpuFileName, verbose = False)
        
        ## Now fix the shaders
        shd.fixDGForGPU()
        
        if cmds.objExists('CORE_ARCHIVES_hrc'):
            cmds.setAttr('CORE_ARCHIVES_hrc.visiblity', 0)
        
        if cmds.objExists('ROOT_ARCHIVES_DNT_hrc'):
            cmds.setAttr('ROOT_ARCHIVES_DNT_hrc.visiblity', 0)
                                       
        ## build and execute the gpu cache export command for this item:
        try:
            print '====================='
            print 'Exporting gpu now to %s\%s' % (fileDir, gpuFileName)
            #PUT THE FILE EXPORT COMMAND HERE
            cmds.select(clear = True)
            for geo in cmds.listRelatives(group_name, children = True):
                if 'geo_hrc' in geo:
                    geoGroup = str(group_name)
                    debug(app = None, method = '_publish_gpu_for_item', message = 'geoGroup: %s' % geoGroup, verbose = False)
                
            cmds.select(geoGroup)
            
            debug(app = None, method = '_publish_gpu_for_item', message = 'geoGroup: %s' % geoGroup, verbose = False)
            debug(app = None, method = '_publish_gpu_for_item', message = "gpuCache -startTime 1 -endTime 1 -optimize -optimizationThreshold 40000 -directory \"%s\" -fileName %s %s;" % (fileDir, gpuFileName, geoGroup), verbose = False)
            
            mel.eval("gpuCache -startTime 1 -endTime 1 -optimize -optimizationThreshold 40000 -directory \"%s\" -fileName %s %s;" % (fileDir, gpuFileName, geoGroup))

            print 'Finished gpu export...'
            print '====================='
            
            if cmds.objExists('dgSHD'):            
                ## Now reconnect the FileIn nodes
                for key, var in filesDict.items():
                    cmds.connectAttr('%s.outColor' % key, '%s.color' % var)
        except Exception, e:
            raise TankError("Failed to export gpu cache file")
コード例 #15
0
ファイル: FootRig.py プロジェクト: jaredauty/Rigging
 def connectBind(self):
     #Create opposite node to blend
     blendOpposite = rc.create1MinusNode(
         "%s.%s" %(self.m_blendControl, self.m_blendAttr),
         "%s_IKFKBlendOpp_CTRL" %(self.m_name)
         )
     for i in range(len(self.m_bindJoints)):
         const1 = cmds.parentConstraint(
             self.m_ikJoints[i],
             self.m_bindJoints[i],
             st = ["x", "y", "z"]
             )[0]
         const2 = cmds.parentConstraint(
             self.m_fkJoints[i],
             self.m_bindJoints[i],
             st = ["x", "y", "z"]
             )[0]
         cmds.connectAttr(
             blendOpposite,
             "%s.blendParent2" %(self.m_bindJoints[i])
             )
         # Change to quarternion
         pairBlend = cmds.listConnections(
             "%s.constraintRotateX" %(const1),
             d=1
             )[0]
         cmds.setAttr("%s.rotInterpolation" %(pairBlend), 1)
コード例 #16
0
ファイル: ribbon.py プロジェクト: duncanrudd/rooftops
def build(numBindJoints=6, numSpans=None, name='', numSkinJoints=3, width=None):
    '''
    builds a nurbs ribbon
    If width is not specified, width will be set to numBindJoints
    If numSpans is not specified, it will be set to numBindJoints
    
    '''
    if not width:
        width = numBindJoints
    if not numSpans:
        numSpans = numBindJoints
    
    main_grp = cmds.group(empty=1, name=(name + '_grp'))
    plane = cmds.nurbsPlane(axis=(0, 1, 0), ch=0, lengthRatio=(1.0 / width), w=width, u=numSpans, name=(name + '_nurbsPlane'))[0]
    cmds.parent(plane, main_grp)
    
    # Creat Skin joints
    skinJoints = []
    skinJointPositions = common.pointsAlongVector( start=[width*.5, 0, 0], end=[width*-.5, 0, 0], divisions=(numSkinJoints-1) )
    for index in range(len(skinJointPositions)):
        cmds.select(main_grp)
        j = cmds.joint(position = skinJointPositions[index], name=(name + '_' + str(index) + '_jnt'))
        skinJoints.append(j)
        
    # Add skinning to ribbon
    cmds.skinCluster(skinJoints, plane, tsb=1, name=(plane + '_skinCluster'))
    cmds.setAttr(plane+'.inheritsTransform', 0)
    
    # Add follicles
    for index in range(numBindJoints):
        f = rivet.build( mesh=plane, paramU=(1.0 / (numBindJoints-1) * index), paramV=0.5, name=(name + '_' + str(index)))
        cmds.parent(f, main_grp)
        j = cmds.joint(name=(name + '_' + str(index) + '_bnd'))
コード例 #17
0
def addVrayObjectIds(shapes=None):
    """ Add a vray_objectID attribute to selected meshes

    :param shapes: Shapes to apply the attribute to. If shapes is None it will get
                   the shapes related to the current selection.
    """
    if shapes is None:
        shapes = mc.ls(sl=1, s=1, dag=1, lf=1, o=1, long=True)

    if shapes:
        # Can only add objectIds to mesh, nurbsSurface so lets filter it
        shapes = mc.ls(shapes, type=("mesh", "nurbsSurface"))

    if shapes:
        result = mc.promptDialog(
            title="Object ID value",
            message="Object ID:",
            button=["OK", "Cancel"],
            defaultButton="OK",
            cancelButton="Cancel",
            dismissString="Cancel",
        )

        if result == "OK":
            value = int(mc.promptDialog(query=True, text=True))

            for shape in shapes:
                mc.vray("addAttributesFromGroup", shape, "vray_objectID", 1)
                mc.setAttr("{0}.{1}".format(shape, "vrayObjectID"), value)
コード例 #18
0
def copyVtxAndPast( meshName, index, indices ):
    
    hists = cmds.listHistory( meshName )
    
    skinCluster = ''
    for hist in hists:
        if cmds.nodeType( hist ) == 'skinCluster':
            skinCluster = hist
    
    if not skinCluster: return None
    
    fnSkinCluster = om.MFnDependencyNode( getMObject( skinCluster ) )
    weightListPlug = fnSkinCluster.findPlug( 'weightList' )
    
    weightListPlugElement = weightListPlug.elementByLogicalIndex( index )
    plugWeights = weightListPlugElement.child( 0 )
    
    indicesAndValues = []
    for i in range( plugWeights.numElements() ):
        index = plugWeights[i].logicalIndex()
        value = plugWeights[i].asFloat()
        indicesAndValues.append( [index,value] )
    
    for vtxIndex in indices:
        weightListPlugElement = weightListPlug.elementByLogicalIndex( vtxIndex )
        plugWeights = weightListPlugElement.child( 0 )
        for i in range( plugWeights.numElements() ):
            cmds.removeMultiInstance( plugWeights[0].name() )
        for index, value in indicesAndValues:
            cmds.setAttr( plugWeights.name() + '[%d]' % index, value )
コード例 #19
0
ファイル: volume_push_collider.py プロジェクト: jonntd/Public
    def _setup_wire_deformer(self, mesh, wire, wirebase, curve,
                             parent, complexity):
        """Setup the wire deformer. If complexity is 1 or higher call this
        function recursively to create a wire deformer on the nurbs surface.

        @param mesh(string): PolyMesh used to wire deform
        @param wire(string): Descriptive part of the name of the wire deformer
        @param wirebase(string): Descriptive part of the name of the base wire
        @param curve(string): Curve used for wireTool deformer
        @param parent(string): Parent node of the wire setup
        @param complexity(uint): complexity level value
        """
        w = wire
        wb = wirebase
        cmds.wire(mesh, w=curve, dds=[0, 10000], n=w, foc=False)
        cmds.rename(cmds.listConnections('%s.baseWire[0]' % w)[0], wb)
        if not cmds.listRelatives(curve, p=True) == [self.wire_grp]:
            cmds.parent(curve, wb, self.wire_grp)
        # end if
        wbs = cmds.listRelatives(wb, ad=True, type='shape')[0]
        cs = cmds.listRelatives(curve, ad=True, type='shape')[0]
        cmds.setAttr('%s.rotation' % w, 0)
        # connect to showHistory
        cmds.connectAttr('%s.showHistory' % self.mod_grp, '%s.ihi' % w)
        cmds.connectAttr('%s.showHistory' % self.mod_grp, '%s.ihi' % wb)
        cmds.connectAttr('%s.showHistory' % self.mod_grp, '%s.ihi' % wbs)
        cmds.connectAttr('%s.showHistory' % self.mod_grp, '%s.ihi' % cs)
        if complexity:
            cmds.duplicate(self.curve, n=self.nrbcurve)
            return self._setup_wire_deformer(self.surface, self.nrbwire,
                                             self.nrbwirebase, self.nrbcurve,
                                             self.parent, 0)
コード例 #20
0
ファイル: Main.py プロジェクト: McBainC/Portfolio
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()
コード例 #21
0
ファイル: setMirrorType.py プロジェクト: jonntd/mayadev-1
 def addAttr( target, **options ):
 
     items = options.items()
     
     attrName = ''
     channelBox = False
     keyable = False
     for key, value in items:
         if key in ['ln', 'longName']:
             attrName = value
         elif key in ['cb', 'channelBox']:
             channelBox = True
             options.pop( key )
         elif key in ['k', 'keyable']:
             keyable = True 
             options.pop( key )
     
     if cmds.attributeQuery( attrName, node=target, ex=1 ): return None
     
     cmds.addAttr( target, **options )
     
     if channelBox:
         cmds.setAttr( target+'.'+attrName, e=1, cb=1 )
     elif keyable:
         cmds.setAttr( target+'.'+attrName, e=1, k=1 )
コード例 #22
0
ファイル: jt_autorig.py プロジェクト: MaxIsJames/jt_tools
def create_base_rig(cog, rig_region_name):
    # create curve and scale it to the correct size
    base_curve, base_curve_group = jt_ctl_curve.create(None, 'star_30')
    cmds.select(base_curve)
    cmds.setAttr(base_curve + '.scale', 5,5,5)
    cmds.makeIdentity(apply=True, t=0, r=1, s=1, n=0)

    # unparent the curve from the default group it is given so its a child of the world
    base_curve = cmds.rename('base')
    cmds.parent(w=True)
    cmds.select(base_curve_group, r=True)
    cmds.delete()

    # add a string attribute to keep track of all the nodes that are used for easy de-rigging
    # NOTE: text is stored in the attr as a string formatted like a python dict with the key being
    # the name of the body region and the value being a list of the nodes involved this makes 
    # de-rigging nice and easy as you just need to find the entry in the dict and delete all the nodes

    cmds.select(base_curve)
    cmds.addAttr(ln='rig_nodes', dt='string')
    cmds.setAttr(base_curve + '.rig_nodes', '{}', type='string')

    # add base_curve to base curve attr list
    add_node_to_rig_nodes(base_curve, 'base', base_curve)

    # update ui base_curve_field
    cmds.textField('jt_autorig_base_name_select_text', e=True, tx=base_curve)
コード例 #23
0
ファイル: allCtlsCmd.py プロジェクト: jonntd/mayadev-1
 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 )
コード例 #24
0
def setupScene():
	'''
	Setup some scene attributes we want to be common to all Spinifex car scenes
	TODO:
	make width over height as float
	'''
		
	# Check if we haven't done this before
	if cmds.objExists('vraySettings.setupSceneHasBeenRun'):
		# Check that everything is setup correctly before continuing.
		dialogMessage = 'setupScene has already been run. Do you wish to continue? Some of your render settings will be reset.'
		result = cmds.confirmDialog( title='spckSetupScene', message=dialogMessage, button=['YES','NO'], defaultButton='NO', cancelButton='NO', dismissString='NO' )
		if result == 'NO' :
			print("Aborted. We\'ve done this before...\n")
			return
	else:
		# Check that everything is setup correctly before continuing.
		dialogMessage = 'Have you set up your workspace.mel?'
		result = cmds.confirmDialog( title='spckSetupScene', message=dialogMessage, button=['YES','NO'], defaultButton='YES', cancelButton='NO', dismissString='NO' )
		if result == 'NO' :
			print('Go setup your workspace and run again.\n')
			return
		
	# Units for working in metric and 30fps
	cmds.currentUnit (linear='cm')
	cmds.currentUnit (angle='deg')
	cmds.currentUnit (time='ntsc')

	# Load VRAY if not active
	cmds.loadPlugin ('vrayformaya', quiet=True)
	cmds.pluginInfo ('vrayformaya', edit=True, autoload=True)
	cmds.setAttr  ('defaultRenderGlobals.ren', 'vray', type='string')

	cmds.evalDeferred ( 'createBaseRenderSettings()' , lowestPriority=True )	
	print('Success.\n')
コード例 #25
0
ファイル: allCtlsCmd.py プロジェクト: jonntd/mayadev-1
 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 )
コード例 #26
0
ファイル: ui.py プロジェクト: jonntd/mayadev-1
 def followAttrVis(self, ctlNameList, attrName, onOff, *args ):
     if onOff == True:
         for ctlName in ctlNameList:
             cmds.setAttr( ctlName+'.'+attrName, e=1, k=1 )
     else:
         for ctlName in ctlNameList:
             cmds.setAttr( ctlName+'.'+attrName, e=1, k=0 )
コード例 #27
0
def main(selectedChannels=True, transformsOnly=False):
    '''
    Resets selected channels in the channel box to default, or if nothing's
    selected, resets all keyable channels to default.
    '''
    gChannelBoxName = mm.eval('$temp=$gChannelBoxName')
    
    sel = mc.ls(sl=True)
    if not sel:
        return
    
    chans = None
    if selectedChannels:
        chans = mc.channelBox(gChannelBoxName, query=True, sma=True)
    
    testList = ['translateX','translateY','translateZ','rotateX','rotateY','rotateZ','scaleX','scaleY','scaleZ',
                'tx','ty','yz','rx','ry','rz','sx','sy','sz']
    for obj in sel:
        attrs = chans
        if not chans:
            attrs = mc.listAttr(obj, keyable=True, unlocked=True)
        if transformsOnly:
            attrs = [x for x in attrs if x in testList]
        if attrs:
            for attr in attrs:
                try:
                    default = mc.attributeQuery(attr, listDefault=True, node=obj)[0]
                    mc.setAttr(obj+'.'+attr, default)
                except StandardError:
                    pass
                
    utl.deselectChannels()
コード例 #28
0
ファイル: allCtlsCmd.py プロジェクト: jonntd/mayadev-1
    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 )
コード例 #29
0
ファイル: KstRig.py プロジェクト: Leopardob/Kistie
    def modifiy_joint_chain_axis(joint_chain, orient_chain='xyz', up_axis_chain='yup'):
        '''
        Desc:
        Modify specified joint chain orientation

        Parameter:
        joint_chain = chain to affect
        orient_chain = axis to orient
        up_axis_chain = chain up axis

        Return:
        None
        '''
        for i in range(0, len(joint_chain)):
            KstOut.debug(KstRig._debug, 'Reorient current joint:' )
            KstOut.debug(KstRig._debug, 'joint: %s' % joint_chain[i])
            try:
                cmds.joint(joint_chain[i], e=True, zso=True, oj=orient_chain, sao=up_axis_chain, ch=True)
            except:
                print('Error on reorient, check the rotations')

            # If it's the last joint reset rotation axis
            if i == len(joint_chain)-1:
                rot_axis = ['X','Y','Z']
                for axis in rot_axis:
                    cmds.setAttr(joint_chain[i]+'.jointOrient'+axis, 0)
コード例 #30
0
ファイル: jt_autorig.py プロジェクト: MaxIsJames/jt_tools
def create_spine_rig(base_curve, rig_region_name, pelvis, cog, spine_1, spine_2, spine_3, spine_4, neck):

    # create group to contain all rigging nodes
    cmds.select(cl=True)
    spine_group = cmds.group(em=True, n=rig_region_name + '_group')
    cmds.select(spine_group, base_curve, r=True)
    cmds.parent()

    # add the arm group node to the base curve rig nodes attr
    add_node_to_rig_nodes(base_curve, rig_region_name, spine_group)

    cog_curve, cog_curve_group = jt_ctl_curve.create(cog, 'star_5', lock_unused=False)
    cmds.setAttr(cog_curve + '.scale', 3,3,3)
    cmds.select(cog_curve, r=True)
    cmds.makeIdentity(apply=True, t=0, r=0, s=1, n=0)

    cmds.select(cog_curve, cog, r=True)
    cmds.parentConstraint(mo=True, weight=1)
    cmds.scaleConstraint(mo=True, weight=1)

    cmds.select(cog_curve_group, base_curve, r=True)
    cmds.parent()

    pelvis_curve, pelvis_curve_group = jt_ctl_curve.create(pelvis, 'waist', True, True, True, True)
    spine_1_curve, spine_1_curve_group = jt_ctl_curve.create(spine_1, 'circle', True, True, True, True)
    spine_2_curve, spine_2_curve_group = jt_ctl_curve.create(spine_2, 'circle', True, True, True, True)
    spine_3_curve, spine_3_curve_group = jt_ctl_curve.create(spine_3, 'circle', True, True, True, True)
    spine_4_curve, spine_4_curve_group = jt_ctl_curve.create(spine_4, 'circle', True, True, True, True)
    neck_curve, neck_curve_group = jt_ctl_curve.create(neck, 'circle', True, True, True, True)

    # parent fk controlls to spine group
    cmds.select(cog_curve_group, pelvis_curve_group, spine_1_curve_group, spine_2_curve_group, spine_3_curve_group, spine_4_curve_group, neck_curve_group, spine_group, r=True)
    cmds.parent()
コード例 #31
0
def createTangentSegmentSetup(pre,
                              start,
                              end,
                              nxt,
                              oTan,
                              iTan,
                              aoTan,
                              aiTan,
                              isFirst=False,
                              isLast=False):
    """ Create a single twist spline tangent setup for a single segment

	With 4 CV's given, there are 3 segments between them.
	This creates a tangent setup for the middle segment.

	Arguments:
		pre (str): The previous CV for auto-tangent calculations
		start (str): The CV that will have its out-tangent connected
		end (str): The CV that will have its in-tangent connected
		nxt (str): The last CV for auto-tangent calculations
		oTan (str): The Out-Tangent object
		iTan (str): The In-Tangent object
		aoTan (str): The Auto-Out-Tangent object
		aiTan (str): The Auto-In-Tangent object
		isFirst (bool): Whether this segment is the first one in the spline
		isLast (bool): Whether this segment is the last one in the spline
	"""
    # connect all the in/out tangents
    ott = cmds.createNode(
        "twistTangent",
        name="twistTangentOut")  # TODO: make with name based on oTan
    cmds.connectAttr("{}.worldMatrix[0]".format(oTan),
                     "{}.inTangent".format(ott))
    cmds.connectAttr("{}.Auto".format(oTan), "{}.auto".format(ott))
    cmds.connectAttr("{}.Smooth".format(oTan), "{}.smooth".format(ott))
    cmds.connectAttr("{}.Weight".format(oTan), "{}.weight".format(ott))
    if not isFirst:
        cmds.connectAttr("{}.worldMatrix[0]".format(pre),
                         "{}.previousVertex".format(ott))
    else:
        cmds.setAttr("{}.Smooth".format(oTan), 0.0)

    cmds.connectAttr("{}.worldMatrix[0]".format(start),
                     "{}.currentVertex".format(ott))
    cmds.connectAttr("{}.worldMatrix[0]".format(end),
                     "{}.nextVertex".format(ott))
    cmds.setAttr("{}.Auto".format(oTan), 1.0)

    itt = cmds.createNode(
        "twistTangent",
        name="twistTangentIn")  # TODO: make with name based on iTan
    cmds.connectAttr("{}.worldMatrix[0]".format(iTan),
                     "{}.inTangent".format(itt))
    cmds.connectAttr("{}.Auto".format(iTan), "{}.auto".format(itt))
    cmds.connectAttr("{}.Smooth".format(iTan), "{}.smooth".format(itt))
    cmds.connectAttr("{}.Weight".format(iTan), "{}.weight".format(itt))
    if not isLast:
        cmds.connectAttr("{}.worldMatrix[0]".format(nxt),
                         "{}.previousVertex".format(itt))
    else:
        cmds.setAttr("{}.Smooth".format(iTan), 0.0)

    cmds.connectAttr("{}.worldMatrix[0]".format(end),
                     "{}.currentVertex".format(itt))
    cmds.connectAttr("{}.worldMatrix[0]".format(start),
                     "{}.nextVertex".format(itt))
    cmds.setAttr("{}.Auto".format(iTan), 1.0)

    cmds.connectAttr("{}.outLinearTarget".format(itt),
                     "{}.inLinearTarget".format(ott))
    cmds.connectAttr("{}.outLinearTarget".format(ott),
                     "{}.inLinearTarget".format(itt))

    cmds.connectAttr("{0}.out".format(ott), "{}.translate".format(aoTan))
    cmds.connectAttr("{}.parentInverseMatrix[0]".format(aoTan),
                     "{}.parentInverseMatrix".format(ott))

    cmds.connectAttr("{0}.out".format(itt), "{}.translate".format(aiTan))
    cmds.connectAttr("{}.parentInverseMatrix[0]".format(aiTan),
                     "{}.parentInverseMatrix".format(itt))
コード例 #32
0
    def createGuide(self, *args):
        Base.StartClass.createGuide(self)
        # Custom GUIDE:
        cmds.setAttr(self.moduleGrp+".moduleNamespace", self.moduleGrp[:self.moduleGrp.rfind(":")], type='string')
        # create cvJointLoc and cvLocators:
        self.cvNeckLoc, shapeSizeCH = ctrls.cvJointLoc(ctrlName=self.guideName+"_neck", r=0.5)
        self.connectShapeSize(shapeSizeCH)
        self.cvHeadLoc, shapeSizeCH = ctrls.cvLocator(ctrlName=self.guideName+"_head", r=0.4)
        self.connectShapeSize(shapeSizeCH)
        self.cvJawLoc, shapeSizeCH  = ctrls.cvLocator(ctrlName=self.guideName+"_jaw", r=0.3)
        self.connectShapeSize(shapeSizeCH)
        self.cvChinLoc, shapeSizeCH = ctrls.cvLocator(ctrlName=self.guideName+"_chin", r=0.3)
        self.connectShapeSize(shapeSizeCH)
        self.cvLLipLoc, shapeSizeCH = ctrls.cvLocator(ctrlName=self.guideName+"_lLip", r=0.1)
        self.connectShapeSize(shapeSizeCH)
        self.cvRLipLoc, shapeSizeCH = ctrls.cvLocator(ctrlName=self.guideName+"_rLip", r=0.1)
        self.connectShapeSize(shapeSizeCH)
        # create jointGuides:
        self.jGuideNeck = cmds.joint(name=self.guideName+"_JGuideNeck", radius=0.001)
        self.jGuideHead = cmds.joint(name=self.guideName+"_JGuideHead", radius=0.001)
        self.jGuideJaw  = cmds.joint(name=self.guideName+"_JGuideJaw", radius=0.001)
        self.jGuideChin = cmds.joint(name=self.guideName+"_JGuideChin", radius=0.001)
        # set jointGuides as templates:
        cmds.setAttr(self.jGuideNeck+".template", 1)
        cmds.setAttr(self.jGuideHead+".template", 1)
        cmds.setAttr(self.jGuideJaw+".template", 1)
        cmds.setAttr(self.jGuideChin+".template", 1)
        cmds.parent(self.jGuideNeck, self.moduleGrp, relative=True)
        # create cvEnd:
        self.cvEndJoint, shapeSizeCH = ctrls.cvLocator(ctrlName=self.guideName+"_JointEnd", r=0.1)
        self.connectShapeSize(shapeSizeCH)
        cmds.parent(self.cvEndJoint, self.cvChinLoc)
        cmds.setAttr(self.cvEndJoint+".tz", ctrls.dpCheckLinearUnit(1.3))
        self.jGuideEnd = cmds.joint(name=self.guideName+"_JGuideEnd", radius=0.001)
        cmds.setAttr(self.jGuideEnd+".template", 1)
        cmds.parent(self.jGuideEnd, self.jGuideChin)
        # connect cvLocs in jointGuides:
        ctrls.directConnect(self.cvNeckLoc, self.jGuideNeck, ['tx', 'ty', 'tz', 'rx', 'ry', 'rz'])
        ctrls.directConnect(self.cvHeadLoc, self.jGuideHead, ['tx', 'ty', 'tz', 'rx', 'ry', 'rz'])
        ctrls.directConnect(self.cvJawLoc, self.jGuideJaw, ['tx', 'ty', 'tz', 'rx', 'ry', 'rz'])
        ctrls.directConnect(self.cvChinLoc, self.jGuideChin, ['tx', 'ty', 'tz', 'rx', 'ry', 'rz'])
        ctrls.directConnect(self.cvEndJoint, self.jGuideEnd, ['tx', 'ty', 'tz', 'rx', 'ry', 'rz'])
        # limit, lock and hide cvEnd:
        cmds.transformLimits(self.cvEndJoint, tz=(0.01, 1), etz=(True, False))
        ctrls.setLockHide([self.cvEndJoint], ['tx', 'ty', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz'])
        # transform cvLocs in order to put as a good head guide:
        cmds.setAttr(self.moduleGrp+".rotateX", -90)
        cmds.setAttr(self.moduleGrp+".rotateY", 90)
        cmds.setAttr(self.cvNeckLoc+".rotateZ", 90)
        cmds.makeIdentity(self.cvNeckLoc, rotate=True, apply=True)
        cmds.setAttr(self.cvHeadLoc+".translateY", 2)
        cmds.setAttr(self.cvJawLoc+".translateY", 2.7)
        cmds.setAttr(self.cvJawLoc+".translateZ", 0.7)
        cmds.setAttr(self.cvChinLoc+".translateY", 2.7)
        cmds.setAttr(self.cvChinLoc+".translateZ", 1.7)

        # lip cvLocs:
        cmds.setAttr(self.cvLLipLoc+".translateX", 0.6)
        cmds.setAttr(self.cvLLipLoc+".translateY", 2.6)
        cmds.setAttr(self.cvLLipLoc+".translateZ", 2.4)
        self.lipMD = cmds.createNode("multiplyDivide", name=self.guideName+"_lip_MD")
        cmds.connectAttr(self.cvLLipLoc+".translateX", self.lipMD+".input1X", force=True)
        cmds.connectAttr(self.cvLLipLoc+".translateY", self.lipMD+".input1Y", force=True)
        cmds.connectAttr(self.cvLLipLoc+".translateZ", self.lipMD+".input1Z", force=True)
        cmds.connectAttr(self.lipMD+".outputX", self.cvRLipLoc+".translateX", force=True)
        cmds.connectAttr(self.lipMD+".outputY", self.cvRLipLoc+".translateY", force=True)
        cmds.connectAttr(self.lipMD+".outputZ", self.cvRLipLoc+".translateZ", force=True)
        cmds.setAttr(self.lipMD+".input2X", -1)

      # make parents between cvLocs:
        cmds.parent(self.cvNeckLoc, self.moduleGrp)
        cmds.parent(self.cvHeadLoc, self.cvNeckLoc)
        cmds.parent(self.cvJawLoc, self.cvHeadLoc)
        cmds.parent(self.cvChinLoc, self.cvJawLoc)
        cmds.parent(self.cvLLipLoc, self.cvJawLoc)
        cmds.parent(self.cvRLipLoc, self.cvJawLoc)
コード例 #33
0
    def rigModule(self, *args):
        Base.StartClass.rigModule(self)
        # verify if the guide exists:
        if cmds.objExists(self.moduleGrp):
            try:
                hideJoints = cmds.checkBox('hideJointsCB', query=True, value=True)
            except:
                hideJoints = 1
            # declare lists to store names and attributes:
            self.worldRefList, self.headCtrlList = [], []
            self.aCtrls, self.aLCtrls, self.aRCtrls = [], [], []
            # start as no having mirror:
            sideList = [""]
            # analisys the mirror module:
            self.mirrorAxis = cmds.getAttr(self.moduleGrp+".mirrorAxis")
            if self.mirrorAxis != 'off':
                # get rigs names:
                self.mirrorNames = cmds.getAttr(self.moduleGrp+".mirrorName")
                # get first and last letters to use as side initials (prefix):
                sideList = [ self.mirrorNames[0]+'_', self.mirrorNames[len(self.mirrorNames)-1]+'_' ]
                for s, side in enumerate(sideList):
                    duplicated = cmds.duplicate(self.moduleGrp, name=side+self.userGuideName+'_Guide_Base')[0]
                    allGuideList = cmds.listRelatives(duplicated, allDescendents=True)
                    for item in allGuideList:
                        cmds.rename(item, side+self.userGuideName+"_"+item)
                    self.mirrorGrp = cmds.group(name="Guide_Base_Grp", empty=True)
                    cmds.parent(side+self.userGuideName+'_Guide_Base', self.mirrorGrp, absolute=True)
                    # re-rename grp:
                    cmds.rename(self.mirrorGrp, side+self.userGuideName+'_'+self.mirrorGrp)
                    # do a group mirror with negative scaling:
                    if s == 1:
                        for axis in self.mirrorAxis:
                            cmds.setAttr(side+self.userGuideName+'_'+self.mirrorGrp+'.scale'+axis, -1)
            else: # if not mirror:
                duplicated = cmds.duplicate(self.moduleGrp, name=self.userGuideName+'_Guide_Base')[0]
                allGuideList = cmds.listRelatives(duplicated, allDescendents=True)
                for item in allGuideList:
                    cmds.rename(item, self.userGuideName+"_"+item)
                self.mirrorGrp = cmds.group(self.userGuideName+'_Guide_Base', name="Guide_Base_Grp", relative=True)
                # re-rename grp:
                cmds.rename(self.mirrorGrp, self.userGuideName+'_'+self.mirrorGrp)
            # store the number of this guide by module type
            dpAR_count = utils.findModuleLastNumber(CLASS_NAME, "dpAR_type") + 1
            # run for all sides
            for s, side in enumerate(sideList):
                # redeclaring variables:
                self.base       = side+self.userGuideName+"_Guide_Base"
                self.cvNeckLoc  = side+self.userGuideName+"_Guide_neck"
                self.cvHeadLoc  = side+self.userGuideName+"_Guide_head"
                self.cvJawLoc   = side+self.userGuideName+"_Guide_jaw"
                self.cvChinLoc  = side+self.userGuideName+"_Guide_chin"
                self.cvLLipLoc  = side+self.userGuideName+"_Guide_lLip"
                self.cvRLipLoc  = side+self.userGuideName+"_Guide_rLip"
                self.cvEndJoint = side+self.userGuideName+"_Guide_JointEnd"
                
                # creating joints:
                self.neckJnt = cmds.joint(name=side+self.userGuideName+"_"+self.langDic[self.langName]['c_neck']+"_Jnt")
                self.headJxt = cmds.joint(name=side+self.userGuideName+"_"+self.langDic[self.langName]['c_head']+"_Jxt")
                cmds.select(clear=True)
                self.headJnt = cmds.joint(name=side+self.userGuideName+"_"+self.langDic[self.langName]['c_head']+"_Jnt", scaleCompensate=False)
                self.jawJnt  = cmds.joint(name=side+self.userGuideName+"_"+self.langDic[self.langName]['c_jaw']+"_Jnt", scaleCompensate=False)
                self.chinJnt = cmds.joint(name=side+self.userGuideName+"_"+self.langDic[self.langName]['c_chin']+"_Jnt", scaleCompensate=False)
                self.endJnt  = cmds.joint(name=side+self.userGuideName+"_JEnd", scaleCompensate=False)
                cmds.select(clear=True)
                self.lLipJnt = cmds.joint(name=side+self.userGuideName+"_"+self.langDic[self.langName]['p002_left']+"_"+self.langDic[self.langName]['c_lip']+"_Jnt", scaleCompensate=False)
                cmds.select(clear=True)
                self.rLipJnt = cmds.joint(name=side+self.userGuideName+"_"+self.langDic[self.langName]['p003_right']+"_"+self.langDic[self.langName]['c_lip']+"_Jnt", scaleCompensate=False)
                dpARJointList = [self.neckJnt, self.headJnt, self.jawJnt, self.chinJnt, self.lLipJnt, self.rLipJnt]
                for dpARJoint in dpARJointList:
                    cmds.addAttr(dpARJoint, longName='dpAR_joint', attributeType='float', keyable=False)
                # creating controls:
                self.neckCtrl = ctrls.cvNeck(ctrlName=side+self.userGuideName+"_"+self.langDic[self.langName]['c_neck']+"_Ctrl", r=self.ctrlRadius/2.0)
                self.headCtrl = ctrls.cvHead(ctrlName=side+self.userGuideName+"_"+self.langDic[self.langName]['c_head']+"_Ctrl", r=self.ctrlRadius/2.0)
                self.jawCtrl  = ctrls.cvJaw( ctrlName=side+self.userGuideName+"_"+self.langDic[self.langName]['c_jaw']+"_Ctrl",  r=self.ctrlRadius/2.0)
                self.chinCtrl = ctrls.cvChin(ctrlName=side+self.userGuideName+"_"+self.langDic[self.langName]['c_chin']+"_Ctrl", r=self.ctrlRadius/2.0)
                self.lLipCtrl = cmds.circle(name=self.langDic[self.langName]['p002_left']+"_"+side+self.userGuideName+"_"+self.langDic[self.langName]['c_lip']+"_Ctrl", ch=False, o=True, nr=(0, 0, 1), d=3, s=8, radius=(self.ctrlRadius * 0.25))[0]
                self.rLipCtrl = cmds.circle(name=self.langDic[self.langName]['p003_right']+"_"+side+self.userGuideName+"_"+self.langDic[self.langName]['c_lip']+"_Ctrl", ch=False, o=True, nr=(0, 0, 1), d=3, s=8, radius=(self.ctrlRadius * 0.25))[0]
                self.headCtrlList.append(self.headCtrl)
                self.aCtrls.append([self.neckCtrl, self.headCtrl, self.jawCtrl, self.chinCtrl])
                self.aLCtrls.append([self.lLipCtrl])
                self.aRCtrls.append([self.rLipCtrl])
                
                #Setup Axis Order
                if self.rigType == Base.RigType.quadruped:
                    cmds.setAttr(self.neckCtrl + ".rotateOrder", 1)
                    cmds.setAttr(self.headCtrl + ".rotateOrder", 1)
                    cmds.setAttr(self.jawCtrl + ".rotateOrder", 1)
                else:
                    cmds.setAttr(self.neckCtrl + ".rotateOrder", 3)
                    cmds.setAttr(self.headCtrl + ".rotateOrder", 3)
                    cmds.setAttr(self.jawCtrl + ".rotateOrder", 3)

                # creating the originedFrom attributes (in order to permit integrated parents in the future):
                utils.originedFrom(objName=self.neckCtrl, attrString=self.base+";"+self.cvNeckLoc)
                utils.originedFrom(objName=self.headCtrl, attrString=self.cvHeadLoc)
                utils.originedFrom(objName=self.jawCtrl, attrString=self.cvJawLoc)
                utils.originedFrom(objName=self.chinCtrl, attrString=self.cvChinLoc+";"+self.cvEndJoint)
                
                # edit the mirror shape to a good direction of controls:
                ctrlList = [ self.neckCtrl, self.headCtrl, self.jawCtrl, self.chinCtrl ]
                if s == 1:
                    for ctrl in ctrlList:
                        if self.mirrorAxis == 'X':
                            cmds.setAttr(ctrl+'.rotateY', 180)
                        elif self.mirrorAxis == 'Y':
                            cmds.setAttr(ctrl+'.rotateY', 180)
                        elif self.mirrorAxis == 'Z':
                            cmds.setAttr(ctrl+'.rotateX', 180)
                            cmds.setAttr(ctrl+'.rotateZ', 180)
                        elif self.mirrorAxis == 'XYZ':
                            cmds.setAttr(ctrl+'.rotateX', 180)
                            cmds.setAttr(ctrl+'.rotateZ', 180)
                    cmds.makeIdentity(ctrlList, apply=True, translate=False, rotate=True, scale=False)

                # temporary parentConstraints:
                tempDelNeck = cmds.parentConstraint(self.cvNeckLoc, self.neckCtrl, maintainOffset=False)
                tempDelHead = cmds.parentConstraint(self.cvHeadLoc, self.headCtrl, maintainOffset=False)
                tempDelJaw  = cmds.parentConstraint(self.cvJawLoc, self.jawCtrl, maintainOffset=False)
                tempDelChin = cmds.parentConstraint(self.cvChinLoc, self.chinCtrl, maintainOffset=False)
                tempDelLLip = cmds.parentConstraint(self.cvLLipLoc, self.lLipCtrl, maintainOffset=False)
                tempDelRLip = cmds.parentConstraint(self.cvRLipLoc, self.rLipCtrl, maintainOffset=False)
                cmds.delete(tempDelNeck, tempDelHead, tempDelJaw, tempDelChin, tempDelLLip, tempDelRLip)
                
                # zeroOut controls:
                self.zeroLipCtrlList = utils.zeroOut([self.lLipCtrl, self.rLipCtrl])
                self.lLipGrp = cmds.group(self.lLipCtrl, name=self.lLipCtrl+"_Grp")
                self.rLipGrp = cmds.group(self.rLipCtrl, name=self.rLipCtrl+"_Grp")
                self.zeroCtrlList = utils.zeroOut([self.neckCtrl, self.headCtrl, self.jawCtrl, self.chinCtrl, self.zeroLipCtrlList[0], self.zeroLipCtrlList[1]])

                # make joints be ride by controls:
                cmds.makeIdentity(self.neckJnt, self.headJxt, self.headJnt, self.jawJnt, self.chinJnt, self.endJnt, rotate=True, apply=True)
                cmds.parentConstraint(self.neckCtrl, self.neckJnt, maintainOffset=False, name=self.neckJnt+"_ParentConstraint")
                cmds.scaleConstraint(self.neckCtrl, self.neckJnt, maintainOffset=False, name=self.neckJnt+"_ScaleConstraint")
                cmds.delete(cmds.parentConstraint(self.headCtrl, self.headJxt, maintainOffset=False))
                cmds.parentConstraint(self.headCtrl, self.headJnt, maintainOffset=False, name=self.headJnt+"_ParentConstraint")
                cmds.parentConstraint(self.jawCtrl, self.jawJnt, maintainOffset=False, name=self.jawJnt+"_ParentConstraint")
                cmds.parentConstraint(self.chinCtrl, self.chinJnt, maintainOffset=False, name=self.chinJnt+"_ParentConstraint")
                cmds.parentConstraint(self.lLipCtrl, self.lLipJnt, maintainOffset=False, name=self.lLipJnt+"_ParentConstraint")
                cmds.parentConstraint(self.rLipCtrl, self.rLipJnt, maintainOffset=False, name=self.rLipJnt+"_ParentConstraint")
                cmds.scaleConstraint(self.headCtrl, self.headJnt, maintainOffset=False, name=self.headJnt+"_ScaleConstraint")
                cmds.scaleConstraint(self.jawCtrl, self.jawJnt, maintainOffset=False, name=self.jawJnt+"_ScaleConstraint")
                cmds.scaleConstraint(self.chinCtrl, self.chinJnt, maintainOffset=False, name=self.chinJnt+"_ScaleConstraint")
                cmds.scaleConstraint(self.lLipCtrl, self.lLipJnt, maintainOffset=False, name=self.lLipJnt+"_ScaleConstraint")
                cmds.scaleConstraint(self.rLipCtrl, self.rLipJnt, maintainOffset=False, name=self.rLipJnt+"_ScaleConstraint")
                cmds.delete(cmds.parentConstraint(self.cvEndJoint, self.endJnt, maintainOffset=False))
                cmds.setAttr(self.jawJnt+".segmentScaleCompensate", 0)
                cmds.setAttr(self.chinJnt+".segmentScaleCompensate", 0)

                # create interations between neck and head:
                self.grpNeck = cmds.group(self.zeroCtrlList[0], name=self.neckCtrl+"_Grp")
                self.grpHeadA = cmds.group(empty=True, name=self.headCtrl+"_A_Grp")
                self.grpHead = cmds.group(self.grpHeadA, name=self.headCtrl+"_Grp")
                # arrange pivots:
                self.neckPivot = cmds.xform(self.neckCtrl, query=True, worldSpace=True, translation=True)
                self.headPivot = cmds.xform(self.headCtrl, query=True, worldSpace=True, translation=True)
                cmds.xform(self.grpNeck, pivots=(self.neckPivot[0], self.neckPivot[1], self.neckPivot[2]))
                cmds.xform(self.grpHead, self.grpHeadA, pivots=(self.headPivot[0], self.headPivot[1], self.headPivot[2]))
                
                self.worldRef = cmds.group(empty=True, name=side+self.userGuideName+"_WorldRef")
                self.worldRefList.append(self.worldRef)
                cmds.delete(cmds.parentConstraint(self.neckCtrl, self.worldRef, maintainOffset=False))
                cmds.parentConstraint(self.neckCtrl, self.grpHeadA, maintainOffset=True, skipRotate=["x", "y", "z"], name=self.grpHeadA+"_ParentConstraint")
                orientConst = cmds.orientConstraint(self.neckCtrl, self.worldRef, self.grpHeadA, maintainOffset=False, name=self.grpHeadA+"_OrientConstraint")[0]
                cmds.scaleConstraint(self.neckCtrl, self.grpHeadA, maintainOffset=True, name=self.grpHeadA+"_ScaleConstraint")
                cmds.parent(self.zeroCtrlList[1], self.grpHeadA, absolute=True)

                # connect reverseNode:
                cmds.addAttr(self.headCtrl, longName=self.langDic[self.langName]['c_Follow'], attributeType='float', minValue=0, maxValue=1, keyable=True)
                cmds.connectAttr(self.headCtrl+'.'+self.langDic[self.langName]['c_Follow'], orientConst+"."+self.neckCtrl+"W0", force=True)
                self.headRevNode = cmds.createNode('reverse', name=side+self.userGuideName+"_Rev")
                cmds.connectAttr(self.headCtrl+'.'+self.langDic[self.langName]['c_Follow'], self.headRevNode+".inputX", force=True)
                cmds.connectAttr(self.headRevNode+'.outputX', orientConst+"."+self.worldRef+"W1", force=True)
                
                # mount controls hierarchy:
                cmds.parent(self.zeroCtrlList[3], self.jawCtrl, absolute=True)
                
                # jaw follow head or root ctrl (using worldRef)
                jawParentConst = cmds.parentConstraint(self.headCtrl, self.worldRef, self.zeroCtrlList[2], maintainOffset=True, name=self.zeroCtrlList[2]+"_ParentConstraint")[0]
                cmds.setAttr(jawParentConst+".interpType", 2) #Shortest, no flip cause problem with scrubing
                cmds.addAttr(self.jawCtrl, longName=self.langDic[self.langName]['c_Follow'], attributeType="float", minValue=0, maxValue=1, defaultValue=1, keyable=True)
                cmds.connectAttr(self.jawCtrl+"."+self.langDic[self.langName]['c_Follow'], jawParentConst+"."+self.headCtrl+"W0", force=True)
                jawFollowRev = cmds.createNode("reverse", name=self.jawCtrl+"_Rev")
                cmds.connectAttr(self.jawCtrl+"."+self.langDic[self.langName]['c_Follow'], jawFollowRev+".inputX", force=True)
                cmds.connectAttr(jawFollowRev+".outputX", jawParentConst+"."+self.worldRef+"W1", force=True)
                cmds.scaleConstraint(self.headCtrl, self.zeroCtrlList[2], maintainOffset=True, name=self.zeroCtrlList[2]+"_ScaleConstraint")[0]

                # setup jaw auto translation
                self.jawSdkGrp = cmds.group(self.jawCtrl, name=self.jawCtrl+"_SDK_Grp")
                cmds.addAttr(self.jawCtrl, longName=self.langDic[self.langName]['c_moveIntensity']+"Y", attributeType='float', keyable=True)
                cmds.addAttr(self.jawCtrl, longName=self.langDic[self.langName]['c_moveIntensity']+"Z", attributeType='float', keyable=True)
                cmds.addAttr(self.jawCtrl, longName=self.langDic[self.langName]['c_moveStartRotation'], attributeType='float', keyable=True)
                cmds.setAttr(self.jawCtrl+"."+self.langDic[self.langName]['c_moveIntensity']+"Y", keyable=False, channelBox=True)
                cmds.setAttr(self.jawCtrl+"."+self.langDic[self.langName]['c_moveIntensity']+"Z", keyable=False, channelBox=True)
                cmds.setAttr(self.jawCtrl+"."+self.langDic[self.langName]['c_moveStartRotation'], keyable=False, channelBox=True)
                cmds.setAttr(self.jawCtrl+"."+self.langDic[self.langName]['c_moveIntensity']+"Y", 1)
                cmds.setAttr(self.jawCtrl+"."+self.langDic[self.langName]['c_moveIntensity']+"Z", 2)
                cmds.setAttr(self.jawCtrl+"."+self.langDic[self.langName]['c_moveStartRotation'], 10)
                self.jawIntensityFixUnitMD = cmds.createNode('multiplyDivide', name="JawMoveIntensityFixUnit_MD")
                self.jawIntensityMD = cmds.createNode('multiplyDivide', name="JawMoveIntensity_MD")
                self.jawIntensityZMD = cmds.createNode('multiplyDivide', name="JawMoveIntensityZ_MD")
                self.jawStartIntensityMD = cmds.createNode('multiplyDivide', name="JawMoveIntensityStart_MD")
                self.jawIntensityPMA = cmds.createNode('plusMinusAverage', name="JawMoveIntensity_PMA")
                self.jawIntensityCnd = cmds.createNode('condition', name="JawMoveIntensity_Cnd")
                cmds.connectAttr(self.jawCtrl+".rotateX", self.jawIntensityMD+".input1Y", force=True)
                cmds.connectAttr(self.jawCtrl+"."+self.langDic[self.langName]['c_moveIntensity']+"Y", self.jawIntensityFixUnitMD+".input1Y", force=True)
                cmds.connectAttr(self.jawIntensityFixUnitMD+".outputY", self.jawIntensityMD+".input2Y", force=True)
                cmds.setAttr(self.jawIntensityFixUnitMD+".input2Y", -0.01)
                cmds.connectAttr(self.jawIntensityFixUnitMD+".outputY", self.jawStartIntensityMD+".input1X", force=True)
                cmds.connectAttr(self.jawCtrl+"."+self.langDic[self.langName]['c_moveStartRotation'], self.jawStartIntensityMD+".input2X", force=True)
                cmds.setAttr(self.jawIntensityPMA+".operation", 2)
                cmds.connectAttr(self.jawIntensityMD+".outputY", self.jawIntensityPMA+".input1D[0]", force=True)
                cmds.connectAttr(self.jawStartIntensityMD+".outputX", self.jawIntensityPMA+".input1D[1]", force=True)
                cmds.connectAttr(self.jawIntensityPMA+".output1D", self.jawIntensityCnd+".colorIfTrueG", force=True)
                cmds.connectAttr(self.jawCtrl+".rotateX", self.jawIntensityCnd+".firstTerm", force=True)
                cmds.connectAttr(self.jawCtrl+"."+self.langDic[self.langName]['c_moveStartRotation'], self.jawIntensityCnd+".secondTerm", force=True)
                cmds.setAttr(self.jawIntensityCnd+".operation", 2)
                cmds.setAttr(self.jawIntensityCnd+".colorIfFalseG", 0)
                cmds.connectAttr(self.jawIntensityCnd+".outColorG", self.jawSdkGrp+".translateY", force=True)
                cmds.connectAttr(self.jawIntensityCnd+".outColorG", self.jawIntensityZMD+".input1Z", force=True)
                cmds.connectAttr(self.jawCtrl+"."+self.langDic[self.langName]['c_moveIntensity']+"Z", self.jawIntensityFixUnitMD+".input1Z", force=True)
                cmds.setAttr(self.jawIntensityFixUnitMD+".input2Z", -0.1)
                cmds.connectAttr(self.jawIntensityFixUnitMD+".outputZ", self.jawIntensityZMD+".input2Z", force=True)
                cmds.connectAttr(self.jawIntensityZMD+".outputZ", self.jawSdkGrp+".translateZ", force=True)

                # create lip setup:
                # left side lip:
                lLipParentConst = cmds.parentConstraint(self.jawCtrl, self.headCtrl, self.lLipGrp, maintainOffset=True, name=self.lLipGrp+"_ParentConstraint")[0]
                cmds.setAttr(lLipParentConst+".interpType", 2)
                cmds.addAttr(self.lLipCtrl, longName=self.langDic[self.langName]['c_Follow'], attributeType='float', minValue=0, maxValue=1, defaultValue=0.5, keyable=True)
                cmds.connectAttr(self.lLipCtrl+'.'+self.langDic[self.langName]['c_Follow'], lLipParentConst+"."+self.jawCtrl+"W0", force=True)
                self.lLipRevNode = cmds.createNode('reverse', name=side+self.userGuideName+"_"+self.langDic[self.langName]['p002_left']+"_"+self.langDic[self.langName]['c_lip']+"_Rev")
                cmds.connectAttr(self.lLipCtrl+'.'+self.langDic[self.langName]['c_Follow'], self.lLipRevNode+".inputX", force=True)
                cmds.connectAttr(self.lLipRevNode+'.outputX', lLipParentConst+"."+self.headCtrl+"W1", force=True)
                cmds.scaleConstraint(self.headCtrl, self.lLipGrp, maintainOffset=True, name=self.lLipGrp+"_ScaleConstraint")[0]
                # right side lip:
                rLipParentConst = cmds.parentConstraint(self.jawCtrl, self.headCtrl, self.rLipGrp, maintainOffset=True, name=self.rLipGrp+"_ParentConstraint")[0]
                cmds.setAttr(rLipParentConst+".interpType", 2)
                cmds.addAttr(self.rLipCtrl, longName=self.langDic[self.langName]['c_Follow'], attributeType='float', minValue=0, maxValue=1, defaultValue=0.5, keyable=True)
                cmds.connectAttr(self.rLipCtrl+'.'+self.langDic[self.langName]['c_Follow'], rLipParentConst+"."+self.jawCtrl+"W0", force=True)
                self.rLipRevNode = cmds.createNode('reverse', name=side+self.userGuideName+"_"+self.langDic[self.langName]['p003_right']+"_"+self.langDic[self.langName]['c_lip']+"_Rev")
                cmds.connectAttr(self.rLipCtrl+'.'+self.langDic[self.langName]['c_Follow'], self.rLipRevNode+".inputX", force=True)
                cmds.connectAttr(self.rLipRevNode+'.outputX', rLipParentConst+"."+self.headCtrl+"W1", force=True)
                cmds.scaleConstraint(self.headCtrl, self.rLipGrp, maintainOffset=True, name=self.rLipGrp+"_ScaleConstraint")[0]
                
                # create a locator in order to avoid delete static group
                loc = cmds.spaceLocator(name=side+self.userGuideName+"_DO_NOT_DELETE")[0]
                cmds.parent(loc, self.worldRef, absolute=True)
                cmds.setAttr(loc+".visibility", 0)
                ctrls.setLockHide([loc], ['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'v'])
                
                # hiding visibility attributes:
                ctrls.setLockHide([self.headCtrl, self.neckCtrl, self.jawCtrl, self.chinCtrl], ['v'], l=False)
                
                # create a masterModuleGrp to be checked if this rig exists:
                self.toCtrlHookGrp     = cmds.group(self.grpNeck, self.grpHead, self.zeroCtrlList[2], self.zeroCtrlList[4], self.zeroCtrlList[5], name=side+self.userGuideName+"_Control_Grp")
                self.toScalableHookGrp = cmds.group(self.neckJnt, self.headJnt, self.lLipJnt, self.rLipJnt, name=side+self.userGuideName+"_Joint_Grp")
                self.toStaticHookGrp   = cmds.group(self.toCtrlHookGrp, self.toScalableHookGrp, self.grpHead, self.worldRef, name=side+self.userGuideName+"_Grp")
                cmds.addAttr(self.toStaticHookGrp, longName="dpAR_name", dataType="string")
                cmds.addAttr(self.toStaticHookGrp, longName="dpAR_type", dataType="string")
                cmds.setAttr(self.toStaticHookGrp+".dpAR_name", self.userGuideName, type="string")
                cmds.setAttr(self.toStaticHookGrp+".dpAR_type", CLASS_NAME, type="string")
                # add module type counter value
                cmds.addAttr(self.toStaticHookGrp, longName='dpAR_count', attributeType='long', keyable=False)
                cmds.setAttr(self.toStaticHookGrp+'.dpAR_count', dpAR_count)
                # add hook attributes to be read when rigging integrated modules:
                utils.addHook(objName=self.toCtrlHookGrp, hookType='ctrlHook')
                utils.addHook(objName=self.grpHead, hookType='rootHook')
                utils.addHook(objName=self.toScalableHookGrp, hookType='scalableHook')
                utils.addHook(objName=self.toStaticHookGrp, hookType='staticHook')

                #Ensure head Jxt matrix
                mHead = cmds.getAttr(self.headCtrl + ".worldMatrix")
                cmds.xform(self.headJxt, m=mHead, ws=True)

                if hideJoints:
                    cmds.setAttr(self.toScalableHookGrp+".visibility", 0)
                
                # delete duplicated group for side (mirror):
                cmds.delete(side+self.userGuideName+'_'+self.mirrorGrp)
            # finalize this rig:
            self.integratingInfo()
            cmds.select(clear=True)
        # delete UI (moduleLayout), GUIDE and moduleInstance namespace:
        self.deleteModule()
 def Position_Fn(self):
     if self.Check_Selection():
         Base_Curve = self.MainWindow.Cam_Item_Widget.Attr["Add_Crv_LE"]
         CamGrp = self.Add_CamGrp_LE.text()
         cmds.xform(CamGrp, cp=1)
         cmds.delete(cmds.parentConstraint(Base_Curve, CamGrp))
         Target_Curve = self.Add_Crv_LE.text()
         # Note 解除曲线的锁定
         cmds.setAttr("%s.tx" % Target_Curve, lock=False)
         cmds.setAttr("%s.ty" % Target_Curve, lock=False)
         cmds.setAttr("%s.tz" % Target_Curve, lock=False)
         cmds.setAttr("%s.rx" % Target_Curve, lock=False)
         cmds.setAttr("%s.ry" % Target_Curve, lock=False)
         cmds.setAttr("%s.rz" % Target_Curve, lock=False)
         cmds.delete(cmds.parentConstraint(Base_Curve, Target_Curve))
         cmds.headsUpMessage(u"位置匹配完成")
     else:
         cmds.warning(u"物体不存在或没有选择")
         cmds.headsUpMessage(u"物体不存在或没有选择")
コード例 #35
0
def convertToTwistSpline(pfx, crv, numJoints=10):
    """ Convert a given NURBS or Bezier curve to a TwistSpline

	Arguments:
		pfx (str): The user name of the spline. Will be formatted into the given naming convention
		crv (str): The transform or shape of a *bezier* spline
		numJoints (int): The number of joints to create that ride this spline
	"""
    # get nurbs curve shape
    crvShape, toDelete = _bezierConvert(crv)

    # Get the curve function set
    # There's no way to get the knots through pure MEL (nodes don't count)
    # So as long as I'm doing it this way, I'll do it all like this
    objects = OpenMaya.MSelectionList()
    OpenMaya.MGlobal.getSelectionListByName(crvShape, objects)
    meshDag = OpenMaya.MDagPath()
    objects.getDagPath(0, meshDag)
    curveFn = OpenMaya.MFnNurbsCurve(meshDag)

    # Get the curve data
    knots = OpenMaya.MDoubleArray()
    curveFn.getKnots(knots)
    params = list(knots)[1::3]
    numCVs = len(params)
    curveLen = curveFn.length()

    # Maya reports the wrong form of the curve through the API
    # So I've got to do it via mel
    #curveForm = curveFn.form()
    curveForm = cmds.getAttr("{0}.form".format(crvShape))
    isClosed = curveForm > 0  # 1->closed 2->periodic
    if isClosed:
        numCVs -= 1

    # Get the point data
    # I could do it with cmds if I wanted, but I would have to un-flatten the list
    # it's annoying either way
    #allPos = cmds.xform("{0}.cv[*]".format(crvShape), q=True, worldSpace=True, translation=True)
    allPos = OpenMaya.MPointArray()
    curveFn.getCVs(allPos)
    # Just testing a micro-optimization
    # 2 steps means not creating 3 MPoints per loop
    allPos = [allPos[i] for i in range(allPos.length())]
    allPos = [(p.x, p.y, p.z) for p in allPos]

    # Build the spline
    tempRet = makeTwistSpline(pfx,
                              numCVs,
                              numJoints=numJoints,
                              maxParam=curveLen / 3.0,
                              spread=1.0,
                              closed=isClosed)
    cvs, bfrs, oTans, iTans, jPars, joints, group, spline, master, riderCnst = tempRet

    # Set the positions
    for pos, cv in zip(allPos[::3], bfrs):
        cmds.xform(cv, ws=True, a=True, t=pos)

    # Pin all the controllers so no length preservation happens
    # That way we can get the rotations at each param
    for cv in cvs:
        cmds.setAttr("{0}.Pin".format(cv), 1)

    for pos, cv in zip(allPos[1::3], oTans):
        cmds.xform(cv, ws=True, a=True, t=pos)
        cmds.setAttr("{0}.Auto".format(cv), 0)

    for pos, cv in zip(allPos[2::3], iTans):
        cmds.xform(cv, ws=True, a=True, t=pos)
        cmds.setAttr("{0}.Auto".format(cv), 0)

    # Make sure there is a rider constraint so I can follow the twist all along the spline
    tmpCnst = cmds.createNode("riderConstraint")
    cmds.connectAttr("{}.outputSpline".format(spline),
                     "{}.inputSplines[0].spline".format(tmpCnst))

    # Get the rotations at each CV point
    newInd = 0
    rotations = []
    cmds.setAttr("{0}.normValue".format(tmpCnst), params[-1])
    for param in params:
        cmds.setAttr("{0}.params[{1}].param".format(tmpCnst, newInd), param)
        cmds.dgeval(
            tmpCnst)  # maybe a propagation bug somewhere in the constraint?
        rot = cmds.getAttr("{0}.outputs[{1}].rotate".format(tmpCnst, newInd))
        rotations.append(rot[0])
    cmds.delete(tmpCnst)

    # Update the rotations after I've got them all
    for rot, ctrl in zip(rotations, bfrs):
        cmds.setAttr("{0}.rotate".format(ctrl), *rot)

    # Un-pin everything but the first, so back to length preservation
    for cv in cvs[1:]:
        cmds.setAttr("{0}.Pin".format(cv), 0)

    # Re-set the tangent worldspace positions now that things have changed
    for pos, cv in zip(allPos[1::3], oTans):
        cmds.xform(cv, ws=True, a=True, t=pos)
        cmds.setAttr("{0}.Auto".format(cv), 0)

    for pos, cv in zip(allPos[2::3], iTans):
        cmds.xform(cv, ws=True, a=True, t=pos)
        cmds.setAttr("{0}.Auto".format(cv), 0)

    # Delete the extra joint group and the constraint if I had to make 'em
    if toDelete:
        cmds.delete(toDelete)

    # Lock the buffers
    for bfr in bfrs:
        for att in [x + y for x in 'trs' for y in 'xyz']:
            cmds.setAttr("{0}.{1}".format(bfr, att), lock=True)
コード例 #36
0
def buildTwistSpline(pfx, cvs, aoTans, aiTans, tws, maxParam, closed=False):
    """ Given all the controller objects, build a twist spline

	Arguments:
		pfx (str): The user name of the spline. Will be formatted into the given naming convention
		cvs ([str, ...]): A list of the CV objects
		aoTans ([str, ...]): A list of the auto-out-tangents
		aiTans ([str, ...]): A list of the auto-in-tangents
		tws ([str, ...]): A list of the twist controllers
		maxParam (float): The U-Value of the last CV
		closed (bool): Whether the spline forms a closed loop

	Returns:
		str: The spline transform node
		str: The spline shape node

	"""
    numCVs = len(cvs)  # Total number of CV nodes
    shift = 0 if closed else 1  # convenience variable so I don't have if's everywhere
    usedCVs = numCVs + 1 - shift  # Total number of CV's connected to the spline node

    # build the spline object and set the spline Params
    splineTfm = cmds.createNode("transform", name=SPLINE_FMT.format(pfx))
    spline = cmds.createNode("twistSpline",
                             parent=splineTfm,
                             name=SPLINE_FMT.format(pfx) + "Shape")

    # Don't connect a first in tangent
    for i, aiTan in enumerate(aiTans):
        cmds.connectAttr("{}.worldMatrix[0]".format(aiTan),
                         "{}.vertexData[{}].inTangent".format(spline, i + 1))

    # Don't connect a last out tangent
    for i, aoTan in enumerate(aoTans):
        cmds.connectAttr("{}.worldMatrix[0]".format(aoTan),
                         "{}.vertexData[{}].outTangent".format(spline, i))

    for u in range(usedCVs):
        i = u % numCVs
        cmds.connectAttr("{}.worldMatrix[0]".format(cvs[i]),
                         "{}.vertexData[{}].controlVertex".format(spline, u))
        cmds.connectAttr("{}.Pin".format(cvs[i]),
                         "{}.vertexData[{}].paramWeight".format(spline, u))
        if u != i:
            # The paramValue needs an offset if we're at the last connection of a closed spline
            adL = cmds.createNode("addDoubleLinear")
            cmds.setAttr("{0}.input2".format(adL), maxParam)
            cmds.connectAttr("{0}.PinParam".format(cvs[i]),
                             "{0}.input1".format(adL),
                             f=True)
            cmds.connectAttr("{0}.output".format(adL),
                             "{}.vertexData[{}].paramValue".format(spline, u),
                             f=True)
        else:
            cmds.connectAttr("{}.PinParam".format(cvs[i]),
                             "{}.vertexData[{}].paramValue".format(spline, u))
            cmds.setAttr("{}.PinParam".format(cvs[i]),
                         (u * maxParam) / (usedCVs - 1.0))

        cmds.connectAttr("{}.UseTwist".format(tws[i]),
                         "{}.vertexData[{}].twistWeight".format(spline, u))
        cmds.connectAttr("{}.rotateX".format(tws[i]),
                         "{}.vertexData[{}].twistValue".format(spline, u))

    cmds.setAttr("{}.Pin".format(cvs[0]), 1.0)
    cmds.setAttr("{}.UseTwist".format(tws[0]), 1.0)

    return splineTfm, spline
コード例 #37
0
def makeLinkLine(sourceNode, destNode, selectNode=None):
    """ Draw a line between two nodes. Clicking the line selects the target object

	Arguments:
		sourceNode (str): The start of the line
		destNode (str): The end of the line
		selectNode (str): The object that gets selected. Defaults to sourceNode

	Returns:
		str: The line's shape node

	"""
    if selectNode is None:
        selectNode = sourceNode

    lineTfm = cmds.curve(d=1, p=([0, 0, 0], [0, 0, 1]), k=(0, 1))
    lineShape = cmds.listRelatives(lineTfm, s=True, path=True)[0]
    cmds.parent(lineShape, selectNode, r=True, s=True, nc=True)
    cmds.delete(lineTfm)

    for idx, node in enumerate([destNode, sourceNode]):
        if node == selectNode:
            # If so, we can skip all the connections and just set the control point
            # to the local rotPivot, and leave it there
            rotPivot = cmds.xform(sourceNode,
                                  q=True,
                                  objectSpace=True,
                                  rotatePivot=True)
            cmds.setAttr(lineShape + ".controlPoints[{0}]".format(idx),
                         *rotPivot)
        else:
            worldMatrix = cmds.createNode('pointMatrixMult',
                                          name=node + "_linkCurveWorldMat")
            inverseMatrix = cmds.createNode('pointMatrixMult',
                                            name=selectNode +
                                            "_linkCurveWorldMat")
            rotPivot = cmds.xform(node,
                                  q=True,
                                  objectSpace=True,
                                  rotatePivot=True)

            cmds.connectAttr(node + ".worldMatrix",
                             worldMatrix + ".inMatrix",
                             f=True)
            cmds.setAttr(worldMatrix + '.inPoint', *rotPivot)
            cmds.connectAttr(selectNode + ".worldInverseMatrix",
                             inverseMatrix + ".inMatrix",
                             f=True)

            cmds.connectAttr(worldMatrix + ".output",
                             inverseMatrix + ".inPoint",
                             f=True)
            cmds.connectAttr(inverseMatrix + ".output",
                             lineShape + ".controlPoints[{0}]".format(idx),
                             f=True)

    cmds.setAttr(lineShape + ".overrideEnabled", 1)
    cmds.setAttr(lineShape + ".overrideColor", 3)
    cmds.rename(lineShape, sourceNode + "Shape")

    for node in [worldMatrix, inverseMatrix]:
        cmds.setAttr(node + ".isHistoricallyInteresting", False)

    return lineShape
コード例 #38
0
ファイル: arm_rig.py プロジェクト: AlisaGf/AutoRig
    def make_ik_joint_chain(self, side, shoulder, knee, elbow_end, wrist,
                            color):
        # make ik handle and control
        cmds.ikHandle(n='ik_arm_' + side,
                      sj=shoulder,
                      ee=elbow_end,
                      sol='ikRPsolver')
        ik_arm = 'ik_arm_' + side
        cmds.parent(ik_arm, 'IKs')
        c = custom_controls.create_custom_controls()
        arm_control = c.cube_curve('ANIM_arm_' + side)
        cmds.setAttr(arm_control + '.lineWidth', 2)
        self.l.override_colors(arm_control, color)
        cmds.xform(arm_control, cp=True)
        arm_control_grp = cmds.group(arm_control, n='grp_ANIM_arm_' + side)
        cmds.matchTransform(arm_control_grp, elbow_end, pos=True, rot=True)
        self.controls.append(arm_control_grp)
        cmds.parent(arm_control_grp, 'controls')
        cmds.parentConstraint(arm_control, 'ik_arm_' + side)

        #create a pole vector
        pv = self.l.create_pole_vector(side, shoulder, knee, elbow_end, 'arm',
                                       'ik_arm_' + side, color)
        orient_constraint_wrist = cmds.orientConstraint(arm_control, wrist)[0]
        cmds.setDrivenKeyframe(orient_constraint_wrist + '.' + wrist + '_Ctl' +
                               'W0',
                               cd=self.ik_fk_control + '.ikfk',
                               v=0,
                               dv=0)
        cmds.setDrivenKeyframe(orient_constraint_wrist + '.' + wrist + '_Ctl' +
                               'W0',
                               cd=self.ik_fk_control + '.ikfk',
                               v=1,
                               dv=1)

        cmds.setDrivenKeyframe(orient_constraint_wrist + '.ANIM_arm_' + side +
                               'W1',
                               cd=self.ik_fk_control + '.ikfk',
                               v=1,
                               dv=0)
        cmds.setDrivenKeyframe(orient_constraint_wrist + '.ANIM_arm_' + side +
                               'W1',
                               cd=self.ik_fk_control + '.ikfk',
                               v=0,
                               dv=1)

        #hide visiblity
        condition = cmds.shadingNode('condition',
                                     asUtility=True,
                                     n='condition_node' + arm_control)
        cmds.connectAttr(self.ik_fk_control + '.ikfk',
                         condition + '.firstTerm')
        cmds.connectAttr(condition + '.outColorR', arm_control + '.visibility')
        cmds.connectAttr(condition + '.outColorR', pv + '.visibility')

        cmds.setAttr(condition + '.colorIfTrueR', 1)
        cmds.setAttr(condition + '.colorIfFalseR', 0)

        #make a joint for stretching
        self.stretchy_joint = cmds.joint()
        cmds.setAttr(self.stretchy_joint + '.drawStyle', 2)
        cmds.matchTransform(self.stretchy_joint, arm_control)
        cmds.parent(self.stretchy_joint, arm_control)
コード例 #39
0
ファイル: SplitJoint.py プロジェクト: yazici/damgteam
    def splitJoints(self):
        firstJnt = self.fjName.text()
        wldPos1 = cmds.xform(firstJnt, q=1, ws=1, rp=1)

        secondJnt = self.sjName.text()
        wldPos2 = cmds.xform(secondJnt, q=1, ws=1, rp=1)

        splitCount = self.splitCountName.text()
        returnPosX = (wldPos2[0] - wldPos1[0]) / (int(splitCount) + 1)
        returnPosZ = (wldPos2[2] - wldPos1[2]) / (int(splitCount) + 1)
        returnPosY = (wldPos2[1] - wldPos1[1]) / (int(splitCount) + 1)

        offsetX = returnPosX + wldPos1[0]
        offsetY = returnPosY + wldPos1[1]
        offsetZ = returnPosZ + wldPos1[2]

        cmds.select(cl=True)

        for x in range(0, int(splitCount)):
            cmds.joint(n=firstJnt + '_split' + str(x + 1))
            cmds.setAttr(firstJnt + '_split' + str(x + 1) + '.translateX',
                         returnPosX)
            cmds.setAttr(firstJnt + '_split' + str(x + 1) + '.translateY',
                         returnPosY)
            cmds.setAttr(firstJnt + '_split' + str(x + 1) + '.translateZ',
                         returnPosZ)

        captureLast = firstJnt + '_split' + str(splitCount)

        # reparent
        cmds.setAttr(firstJnt + '_split1.translateX', offsetX)
        cmds.setAttr(firstJnt + '_split1.translateY', offsetY)
        cmds.setAttr(firstJnt + '_split1.translateZ', offsetZ)
        cmds.parent
        cmds.parent
        cmds.warning("CHAIN SPLIT")
コード例 #40
0
def mkTwistSplineControllers(pfx, numCVs, spread, closed=False):
    """ Make and position all the controller objects

	Arguments:
		pfx (str): The user name of the spline. Will be formatted into the given naming convention
		numCVs (int): The number of CVs to create for a spline
		spread (float): The distance between each controller (including tangents)
		closed (bool): Whether the spline forms a closed loop

	Returns:
		[str, ...]: All the CV's
		[str, ...]: All the CV Buffers
		[str, ...]: All the Out-Tangents
		[str, ...]: All the In-Tangents
		[str, ...]: All the Auto-Out-Tangents
		[str, ...]: All the Auto-In-Tangents
		[str, ...]: All the Twisters
		[str, ...]: All the Twister Buffers
		str: The base controller
	"""

    # Make bases for the controllers
    cvCtrl, outTanCtrl, inTanCtrl, twistCtrl, masterCtrl = _mkMasterControllers(
    )

    master = cmds.duplicate(masterCtrl, name=MASTER_FMT.format(pfx))[0]
    cmds.addAttr(master,
                 longName="Offset",
                 attributeType='double',
                 defaultValue=0.0)
    cmds.setAttr(master + '.Offset', edit=True, keyable=True)
    cmds.addAttr(master,
                 longName="Stretch",
                 attributeType='double',
                 defaultValue=1.0,
                 minValue=0.0001)
    cmds.setAttr(master + '.Stretch', edit=True, keyable=True)

    # make the requested number of CV's
    # don't hide the .rx attribute
    cvs, tws, cvBfrs, twBfrs = [], [], [], []
    controlsGrp = cmds.createNode("transform", name=CTRL_ORG_FMT.format(pfx))
    cmds.parentConstraint(master, controlsGrp, mo=True)
    cmds.scaleConstraint(master, controlsGrp, mo=True)

    for i in range(numCVs):
        cvBfr = cmds.createNode("transform",
                                name=BFR_CV_FMT.format(pfx, i + 1),
                                parent=controlsGrp)
        cv = cmds.duplicate(cvCtrl, name=CTRL_CV_FMT.format(pfx, i + 1))[0]
        twBfr = cmds.createNode("transform",
                                name=BFR_TWIST_FMT.format(pfx, i + 1),
                                parent=controlsGrp)
        tw = cmds.duplicate(twistCtrl, name=CTRL_TWIST_FMT.format(pfx,
                                                                  i + 1))[0]

        cmds.addAttr(cv,
                     longName="Pin",
                     attributeType='double',
                     defaultValue=0.0,
                     minValue=0.0,
                     maxValue=1.0)
        cmds.setAttr(cv + '.Pin', edit=True, keyable=True)
        cmds.addAttr(cv,
                     longName="PinParam",
                     attributeType='double',
                     defaultValue=0.0,
                     minValue=0.0)
        cmds.setAttr(cv + '.PinParam', edit=True, keyable=True)

        for h in [
                '.tx', '.ty', '.tz', '.ry', '.rz', '.sx', '.sy', '.sz', '.v'
        ]:
            cmds.setAttr(tw + h, lock=True, keyable=False, channelBox=False)
        cmds.addAttr(tw,
                     longName="UseTwist",
                     attributeType='double',
                     defaultValue=0.0,
                     minValue=0.0,
                     maxValue=1.0)
        cmds.setAttr(tw + '.UseTwist', edit=True, keyable=True)
        cv, = cmds.parent(cv, cvBfr)
        twBfr, = cmds.parent(twBfr, cv)
        tw, = cmds.parent(tw, twBfr)
        cmds.xform(cvBfr, translation=(spread * 3 * i, 0, 0))
        cvs.append(cv)
        tws.append(tw)
        cvBfrs.append(cvBfr)
        twBfrs.append(twBfr)

    # make the tangents and auto-tangents
    oTans, iTans, aoTans, aiTans = [], [], [], []

    segments = numCVs if closed else numCVs - 1
    for i in range(segments):
        # make oTan, and iTan
        otNum = i
        itNum = (i + 1) % numCVs

        oTan = cmds.duplicate(outTanCtrl,
                              name=CTRL_OUTTAN_FMT.format(pfx, otNum + 1))[0]
        iTan = cmds.duplicate(inTanCtrl,
                              name=CTRL_INTAN_FMT.format(pfx, itNum + 1))[0]
        for ndTan in [oTan, iTan]:
            cmds.addAttr(ndTan,
                         longName="Auto",
                         attributeType='double',
                         defaultValue=1.0,
                         minValue=0.0,
                         maxValue=1.0)
            cmds.setAttr(ndTan + '.Auto', edit=True, keyable=True)
            cmds.addAttr(ndTan,
                         longName="Smooth",
                         attributeType='double',
                         defaultValue=1.0,
                         minValue=0.0,
                         maxValue=1.0)
            cmds.setAttr(ndTan + '.Smooth', edit=True, keyable=True)
            cmds.addAttr(ndTan,
                         longName="Weight",
                         attributeType='double',
                         defaultValue=1.0,
                         minValue=0.0001,
                         maxValue=5.0)
            cmds.setAttr(ndTan + '.Weight', edit=True, keyable=True)

        cmds.xform(oTan, translation=(spread * (3 * otNum + 1), 0, 0))
        cmds.xform(iTan, translation=(spread * (3 * itNum - 1), 0, 0))

        aoTan = cmds.createNode("transform",
                                name=BFR_AOUTTAN_FMT.format(pfx, otNum + 1),
                                parent=cvs[otNum])
        aiTan = cmds.createNode("transform",
                                name=BFR_AINTAN_FMT.format(pfx, itNum + 1),
                                parent=cvs[itNum])

        cmds.xform(aoTan, translation=(spread * (3 * otNum + 1), 0, 0))
        cmds.xform(aiTan, translation=(spread * (3 * itNum - 1), 0, 0))
        oTan = cmds.parent(oTan, cvs[otNum])[0]
        iTan = cmds.parent(iTan, cvs[itNum])[0]

        oTans.append(oTan)
        iTans.append(iTan)
        aoTans.append(aoTan)
        aiTans.append(aiTan)

        for nd in [aiTan, aoTan]:
            cmds.setAttr(nd + ".overrideEnabled", 1)
            cmds.setAttr(nd + ".overrideDisplayType", 2)
            cmds.setAttr(nd + ".visibility", 0)

        makeLinkLine(aoTan, cvs[otNum], selectNode=oTan)
        makeLinkLine(aiTan, cvs[itNum], selectNode=iTan)

    cmds.delete((cvCtrl, outTanCtrl, inTanCtrl, twistCtrl, masterCtrl))
    return cvs, cvBfrs, oTans, iTans, aoTans, aiTans, tws, twBfrs, master
コード例 #41
0
ファイル: twist.py プロジェクト: fsanges/glTools-1
def build_hip(hip,
              pelvis,
              numJoints=4,
              hipAim='x',
              hipFront='y',
              pelvisAim='x',
              pelvisFront='y',
              enableCtrl=False,
              prefix=''):
    '''
	Build hip twist using custom hipConstraint node
	@param hip: Hip or upper leg joint 
	@type hip: str
	@param pelvis: Pelvis joint 
	@type pelvis: str
	@param numJoint: Number of twist joints to generate 
	@type numJoint: int
	@param hipAim: Axis along the length of the hip/leg joint 
	@type hipAim: list or tuple
	@param hipFront: Forward facing axis of the hip/leg joint 
	@type hipFront: list or tuple
	@param pelvisAim: Axis along the length of the pelvis joint 
	@type pelvisAim: list or tuple
	@param pelvisFront: Forward facing axis of the pelvis joint 
	@type pelvisFront: list or tuple
	@param enableCtrl: Enable the twist child joint as a control 
	@type enableCtrl: bool
	@param prefix: Naming prefix for created nodes
	@type prefix: str
	'''
    # ==========
    # - Checks -
    # ==========

    # Define Axis Dictionary
    axisDict = {
        'x': (1, 0, 0),
        'y': (0, 1, 0),
        'z': (0, 0, 1),
        '-x': (-1, 0, 0),
        '-y': (0, -1, 0),
        '-z': (0, 0, -1)
    }

    if not mc.objExists(hip):
        raise Exception('Hip joint "' + hip + '" does not exist!')
    if not mc.objExists(pelvis):
        raise Exception('Pelvis joint "' + pelvis + '" does not exist!')

    if not axisDict.has_key(hipAim):
        raise Exception('Invalid hip aim axis value! ("' + hipAim + '")')
    if not axisDict.has_key(hipFront):
        raise Exception('Invalid hip front axis value! ("' + hipFront + '")')
    if not axisDict.has_key(pelvisAim):
        raise Exception('Invalid pelvis aim axis value! ("' + pelvisAim + '")')
    if not axisDict.has_key(pelvisFront):
        raise Exception('Invalid pelvis front axis value! ("' + pelvisFront +
                        '")')

    if not prefix: prefix = glTools.utils.stringUtils.stripSuffix(hip)

    # Check Plugin
    if not mc.pluginInfo('twistConstraint', q=True, l=True):
        try:
            mc.loadPlugin('twistConstraint')
        except:
            raise Exception('Unable to load plugin "twistConstraint"!')

    # ======================
    # - Configure Modifier -
    # ======================

    twistCtrlScale = 0.2
    ctrlBuilder = glTools.tools.controlBuilder.ControlBuilder()

    # =======================
    # - Create Twist Joints -
    # =======================

    twistJoints = createTwistJoints(joint=hip,
                                    numTwistJoints=numJoints,
                                    offsetAxis=hipAim[-1],
                                    prefix=prefix)
    # Reverse twist joint list
    twistJoints.reverse()

    # Create Twist Driver Joint
    mc.select(cl=True)
    hipTwist = mc.joint(n=prefix + '_twistDrive_jnt')
    hipTwistGrp = glTools.utils.joint.group(hipTwist)
    mc.delete(mc.parentConstraint(hip, hipTwistGrp))
    mc.parent(hipTwistGrp, hip)
    glTools.utils.base.displayOverride(hipTwist,
                                       overrideEnable=1,
                                       overrideDisplay=2,
                                       overrideLOD=0)

    # Create Hip Twist Joints
    twistJointGrps = []
    twistFactor = 1.0 / (len(twistJoints) - 1)
    jntLen = glTools.utils.joint.length(hip)
    for i in range(len(twistJoints)):

        # Add Twist Control Attribute
        mc.addAttr(twistJoints[i],
                   ln='twist',
                   min=-1.0,
                   max=1.0,
                   dv=twistFactor * i)

        # Add Twist Joint Group
        twistJointGrp = glTools.utils.joint.group(twistJoints[i],
                                                  indexStr='Twist')
        twistJointGrps.append(twistJointGrp)

        # Tag Bind Joint
        glTools.rig.utils.tagBindJoint(twistJoints[i], True)

        # Create Joint Control
        if enableCtrl:
            glTools.rig.utils.tagCtrl(twistJoints[i], 'tertiary')
            ctrlBuilder.controlShape(transform=twistJoints[i],
                                     controlType='sphere',
                                     controlScale=twistCtrlScale)

        # Set Display Override
        if enableCtrl:
            glTools.utils.base.displayOverride(twistJoints[i],
                                               overrideEnable=1,
                                               overrideDisplay=0,
                                               overrideLOD=1)
        else:
            glTools.utils.base.displayOverride(twistJoints[i],
                                               overrideEnable=1,
                                               overrideDisplay=2,
                                               overrideLOD=0)

    # Create Twist Group
    twistGrp = mc.joint(n=prefix + '_twistJoint_grp')
    glTools.utils.base.displayOverride(twistGrp,
                                       overrideEnable=1,
                                       overrideLOD=1)
    glTools.utils.transform.match(twistGrp, hip)
    mc.setAttr(twistGrp + '.segmentScaleCompensate', 0)
    mc.setAttr(twistGrp + '.drawStyle', 2)  # None
    mc.setAttr(twistGrp + '.radius', 0)
    mc.parent(twistGrp, hip)
    mc.parent(twistJointGrps, twistGrp)

    # Connect Inverse Scale
    for twistJointGrp in twistJointGrps:
        mc.connectAttr(hip + '.scale', twistJointGrp + '.inverseScale', f=True)

    # ==========================
    # - Create Hip Twist Setup -
    # ==========================

    # Create hipConstraint node
    hipCon = mc.createNode('hipConstraint', n=prefix + '_hipConstraint')

    # Set and connect hipConstraint attributes
    mc.connectAttr(hip + '.worldMatrix[0]', hipCon + '.hip', f=True)
    mc.connectAttr(pelvis + '.worldMatrix[0]', hipCon + '.pelvis', f=True)
    mc.connectAttr(hipTwist + '.parentInverseMatrix[0]',
                   hipCon + '.parentInverseMatrix',
                   f=True)
    mc.connectAttr(hipTwist + '.rotateOrder', hipCon + '.rotateOrder', f=True)
    mc.connectAttr(hipTwist + '.jointOrient', hipCon + '.jointOrient', f=True)
    mc.setAttr(hipCon + '.hipAim', *axisDict[hipAim])
    mc.setAttr(hipCon + '.hipFront', *axisDict[hipFront])
    mc.setAttr(hipCon + '.pelvisAim', *axisDict[pelvisAim])
    mc.setAttr(hipCon + '.pelvisFront', *axisDict[pelvisFront])

    # Connect to hip twist joint
    mc.connectAttr(hipCon + '.outRotate', hipTwist + '.rotate', f=True)

    # Correct initial offset
    twistOffset = mc.getAttr(hipTwist + '.r' + hipAim[-1])
    mc.setAttr(hipTwist + '.jo' + hipAim[-1], twistOffset)

    # ========================
    # - Connect Twist Joints -
    # ========================

    twistMultNode = []
    for i in range(len(twistJoints)):

        alphaInd = glTools.utils.stringUtils.alphaIndex(i, upper=True)
        twistMult = mc.createNode('multDoubleLinear',
                                  n=prefix + '_twist' + alphaInd +
                                  '_multDoubleLinear')
        mc.connectAttr(hipTwist + '.r' + hipAim[-1],
                       twistMult + '.input1',
                       f=True)
        mc.connectAttr(twistJoints[i] + '.twist',
                       twistMult + '.input2',
                       f=True)
        mc.connectAttr(twistMult + '.output',
                       twistJointGrps[i] + '.r' + hipAim[-1],
                       f=True)
        twistMultNode.append(twistMult)

    # Reverse twist joint list
    twistJoints.reverse()

    # ======================
    # - Set Channel States -
    # ======================

    chStateUtil = glTools.utils.channelState.ChannelState()
    chStateUtil.setFlags([2, 2, 2, 2, 2, 2, 2, 2, 2, 1], objectList=[twistGrp])
    chStateUtil.setFlags([0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
                         objectList=twistJoints)
    chStateUtil.setFlags([2, 2, 2, 2, 2, 2, 2, 2, 2, 1],
                         objectList=twistJointGrps)
    chStateUtil.setFlags([2, 2, 2, 2, 2, 2, 2, 2, 2, 1],
                         objectList=[hipTwistGrp])
    chStateUtil.setFlags([2, 2, 2, 1, 1, 1, 2, 2, 2, 1], objectList=[hipTwist])

    # =================
    # - Return Result -
    # =================

    result = {}
    result['twistGrp'] = twistGrp
    result['twistJoints'] = twistJoints
    result['twistJointGrps'] = twistJointGrps
    result['twistDriveJoint'] = hipTwist
    result['twistConstraint'] = hipCon
    result['twistMultNodes'] = twistMultNode
    return result
コード例 #42
0
	def _createNode(self):
		''' Create transform node and add the attributes. '''
		self.node = cmds.createNode('transform',n=self.ctrlName+'_tireSpinNode')

		cmds.addAttr( longName='currentPosition', numberOfChildren=3, attributeType='compound' )
		cmds.addAttr( longName='cpx', attributeType='double', parent='currentPosition' )
		cmds.addAttr( longName='cpy', attributeType='double', parent='currentPosition' )
		cmds.addAttr( longName='cpz', attributeType='double', parent='currentPosition' )
		cmds.setAttr('%s.currentPosition'%self.node,k=True,l=False)
		
		cmds.addAttr( longName='previousPosition', numberOfChildren=3, attributeType='compound' )
		cmds.addAttr( longName='ppx', attributeType='double', parent='previousPosition' )
		cmds.addAttr( longName='ppy', attributeType='double', parent='previousPosition' )
		cmds.addAttr( longName='ppz', attributeType='double', parent='previousPosition' )
		cmds.setAttr('%s.previousPosition'%self.node,k=True,l=False)
		
		cmds.addAttr( longName='motionVector', numberOfChildren=3, attributeType='compound' )
		cmds.addAttr( longName='mvx', attributeType='double', parent='motionVector' )
		cmds.addAttr( longName='mvy', attributeType='double', parent='motionVector' )
		cmds.addAttr( longName='mvz', attributeType='double', parent='motionVector' )
		cmds.setAttr('%s.motionVector'%self.node,k=True,l=False)
		
		cmds.addAttr(self.node,ln='auto',attributeType='enum',enumName="off:on",dv=1)

		cmds.addAttr(self.node,ln='radius',dv=self.radius)
		cmds.setAttr('%s.radius'%self.node,k=True,l=False)
		
		cmds.addAttr(self.node,ln='driverDirectionAngle',dv=0.0)
		cmds.setAttr('%s.driverDirectionAngle'%self.node,k=True,l=False)
		
		cmds.addAttr(self.node,ln='rotationDirectionFactor',dv=0.0)
		cmds.setAttr('%s.rotationDirectionFactor'%self.node,k=True,l=False)
		
		cmds.addAttr(self.node,ln='distance',dv=0.0)
		cmds.setAttr('%s.distance'%self.node,k=True,l=False)
		
		
		#--- Output
		cmds.addAttr(self.node,ln='rotation',dv=0.0)
		cmds.setAttr('%s.rotation'%self.node,k=True,l=False)
コード例 #43
0
for obj in sel:
    cmds.xform(obj, os=True, r=False, ra=(0, 180, 23.5))

#to put select objs' pivots onto the closest point on a mesh that sort of tracks where you want them to be

import maya.cmds as cmds
mesh = "polyShape"
cpom = cmds.shadingNode("closestPointOnMesh", n="cpom", asUtility=True)
cmds.connectAttr("%s.mesh" % mesh, "%s.inputSurface" % cpos)

objs = cmds.ls(sl=True)

for obj in objs:
    #get position
    objPos = cmds.xform(obj, q=True, ws=True, rp=True)
    cmds.setAttr("%s.inPosition" % cpom, objPos[0], objPos[1], objPos[2])

    #get position on surface
    pos = cmds.getAttr("%s.position" % cpom)

    #change pivot
    cmds.xform(obj, ws=True, piv=pos[0])

#to connect a vis attr to the vis of the shape nodes

import maya.cmds as cmds

sel = cmds.ls(sl=True)

for ctrl in sel:
    thisShape = cmds.listRelatives(ctrl, s=True, c=True)
コード例 #44
0
ファイル: twist.py プロジェクト: fsanges/glTools-1
def build(sourceJoint,
          targetJoint,
          numJoints=4,
          aimAxis='x',
          upAxis='y',
          baseToTip=True,
          enableCtrl=False,
          prefix=''):
    '''
	Build twist joint setup using an aimConstraint to calculate rotation.
	@param sourceJoint: Twist base joint 
	@type sourceJoint: str
	@param targetJoint: Twist target or end joint
	@type targetJoint: str
	@param numJoint: Number of twist joints to generate 
	@type numJoint: int
	@param aimAxis: Axis along the length of the source joint 
	@type aimAxis: list or tuple
	@param upAxis: Upward facing axis of the source joint 
	@type upAxis: list or tuple
	@param baseToTip: Twist from the base to the tip 
	@type baseToTip: bool
	@param enableCtrl: Enable the twist child joint as a control 
	@type enableCtrl: bool
	@param prefix: Naming prefix for created nodes
	@type prefix: str
	'''
    # ==========
    # - Checks -
    # ==========

    # Define Axis Dictionary
    axisDict = {
        'x': (1, 0, 0),
        'y': (0, 1, 0),
        'z': (0, 0, 1),
        '-x': (-1, 0, 0),
        '-y': (0, -1, 0),
        '-z': (0, 0, -1)
    }

    if not mc.objExists(sourceJoint):
        raise Exception('Source joint "' + sourceJoint + '" does not exist!')
    if not mc.objExists(targetJoint):
        raise Exception('Target joint "' + targetJoint + '" does not exist!')

    if not axisDict.has_key(aimAxis):
        raise Exception('Invalid aim axis value! ("' + aimAxis + '")')
    if not axisDict.has_key(upAxis):
        raise Exception('Invalid up axis value! ("' + upAxis + '")')

    if not prefix: prefix = glTools.utils.stringUtils.stripSuffix(sourceJoint)

    # ======================
    # - Configure Modifier -
    # ======================

    twistCtrlScale = 0.2
    ctrlBuilder = glTools.tools.controlBuilder.ControlBuilder()

    # =======================
    # - Create Twist Joints -
    # =======================

    twistJoints = createTwistJoints(joint=sourceJoint,
                                    numTwistJoints=numJoints,
                                    offsetAxis=aimAxis[-1],
                                    prefix=prefix)

    # Check baseToTip - Reverse list order if false
    if not baseToTip: twistJoints.reverse()

    # Create Joint Groups/Attributes/Tags
    twistJointGrps = []
    twistFactor = 1.0 / (len(twistJoints) - 1)
    jntLen = glTools.utils.joint.length(sourceJoint)
    for i in range(len(twistJoints)):

        # Add Twist Control Attribute
        mc.addAttr(twistJoints[i],
                   ln='twist',
                   min=-1.0,
                   max=1.0,
                   dv=twistFactor * i)

        # Add Twist Joint Group
        twistJointGrp = glTools.utils.joint.group(twistJoints[i],
                                                  indexStr='Twist')
        twistJointGrps.append(twistJointGrp)

        # Tag Bind Joint
        glTools.rig.utils.tagBindJoint(twistJoints[i], True)

        # Create Joint Control
        if enableCtrl:
            glTools.rig.utils.tagCtrl(twistJoints[i], 'tertiary')
            ctrlBuilder.controlShape(transform=twistJoints[i],
                                     controlType='sphere',
                                     controlScale=twistCtrlScale)

        # Set Display Override
        if enableCtrl:
            glTools.utils.base.displayOverride(twistJoints[i],
                                               overrideEnable=1,
                                               overrideDisplay=0,
                                               overrideLOD=1)
        else:
            glTools.utils.base.displayOverride(twistJoints[i],
                                               overrideEnable=1,
                                               overrideDisplay=2,
                                               overrideLOD=0)

    # Create Twist Group
    twistGrp = mc.joint(n=prefix + '_twistJoint_grp')
    glTools.utils.base.displayOverride(twistGrp,
                                       overrideEnable=1,
                                       overrideDisplay=2,
                                       overrideLOD=1)
    glTools.utils.transform.match(twistGrp, sourceJoint)
    mc.setAttr(twistGrp + '.segmentScaleCompensate', 0)
    mc.setAttr(twistGrp + '.drawStyle', 2)  # None
    mc.setAttr(twistGrp + '.radius', 0)
    mc.parent(twistGrp, sourceJoint)
    mc.parent(twistJointGrps, twistGrp)

    # Connect Inverse Scale
    for twistJointGrp in twistJointGrps:
        mc.connectAttr(sourceJoint + '.scale',
                       twistJointGrp + '.inverseScale',
                       f=True)

    # ==========================
    # - Create Twist Aim Setup -
    # ==========================

    # Create Twist Aim Joint
    twistAimJnt = mc.duplicate(sourceJoint,
                               po=True,
                               n=prefix + '_twistAim_jnt')[0]
    # Remove user attributes
    glTools.utils.attribute.deleteUserAttrs(twistAimJnt)
    # Parent to source joint
    mc.parent(twistAimJnt, sourceJoint)
    # Display Overrides
    glTools.utils.base.displayOverride(twistAimJnt,
                                       overrideEnable=1,
                                       overrideDisplay=2,
                                       overrideLOD=0)

    # Create Twist Aim Locator
    twistAimLoc = mc.group(em=True, n=prefix + '_twistAim_loc')
    mc.delete(mc.pointConstraint(targetJoint, twistAimLoc, mo=False))
    mc.delete(mc.orientConstraint(sourceJoint, twistAimLoc, mo=False))
    mc.parent(twistAimLoc, targetJoint)
    # Display Overrides
    glTools.utils.base.displayOverride(twistAimLoc,
                                       overrideEnable=1,
                                       overrideDisplay=2,
                                       overrideLOD=0)

    # Create Twist Aim Constraint
    twistAimCon = mc.aimConstraint(targetJoint,
                                   twistAimJnt,
                                   aim=axisDict[aimAxis],
                                   u=axisDict[upAxis],
                                   wu=axisDict[upAxis],
                                   wuo=twistAimLoc,
                                   wut='objectrotation')[0]

    # ========================
    # - Connect Twist Joints -
    # ========================

    twistMultNode = []
    for i in range(len(twistJoints)):

        alphaInd = glTools.utils.stringUtils.alphaIndex(i, upper=True)
        twistMult = mc.createNode('multDoubleLinear',
                                  n=prefix + '_twist' + alphaInd +
                                  '_multDoubleLinear')
        mc.connectAttr(twistAimJnt + '.r' + aimAxis[-1],
                       twistMult + '.input1',
                       f=True)
        mc.connectAttr(twistJoints[i] + '.twist',
                       twistMult + '.input2',
                       f=True)
        mc.connectAttr(twistMult + '.output',
                       twistJointGrps[i] + '.r' + aimAxis[-1],
                       f=True)
        twistMultNode.append(twistMult)

    # ======================
    # - Set Channel States -
    # ======================

    chStateUtil = glTools.utils.channelState.ChannelState()
    chStateUtil.setFlags([2, 2, 2, 2, 2, 2, 2, 2, 2, 1], objectList=[twistGrp])
    chStateUtil.setFlags([0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
                         objectList=twistJoints)
    chStateUtil.setFlags([2, 2, 2, 2, 2, 2, 2, 2, 2, 1],
                         objectList=twistJointGrps)
    chStateUtil.setFlags([2, 2, 2, 1, 1, 1, 2, 2, 2, 1],
                         objectList=[twistAimJnt])
    chStateUtil.setFlags([2, 2, 2, 2, 2, 2, 2, 2, 2, 1],
                         objectList=[twistAimLoc])

    # =================
    # - Return Result -
    # =================

    result = {}
    result['twistGrp'] = twistGrp
    result['twistJoints'] = twistJoints
    result['twistJointGrps'] = twistJointGrps
    result['twistDriveJoint'] = twistAimJnt
    result['twistAimLocator'] = twistAimLoc
    result['twistConstraint'] = twistAimCon
    result['twistMultNodes'] = twistMultNode
    return result
コード例 #45
0
def set_render_settings(camera):
    """Set the render settings.

    Arguments:
        camera(unicode): QC Camera.
    """
    cmds.setAttr("{}.renderable".format(camera), True)
    cmds.setAttr("persp.renderable", False)
    cmds.setAttr("defaultRenderGlobals.startFrame", 1001)
    cmds.setAttr("defaultRenderGlobals.endFrame", 1360)
    cmds.setAttr("defaultRenderGlobals.outFormatControl", 0)
    cmds.setAttr("defaultRenderGlobals.animation", 1)
    cmds.setAttr("defaultResolution.width", 1280)
    cmds.setAttr("defaultResolution.height", 720)
コード例 #46
0
ファイル: twist.py プロジェクト: fsanges/glTools-1
def createTwistJoints(joint, numTwistJoints, offsetAxis='x', prefix=''):
    '''
	Generate twist joints for a specified rig joint.
	This function only creates the joints, it does not setup the twist control network.
	@param joint: Master rig joint that will drive the twist
	@type joint: str
	@param numTwistJoints: Number of twist joints to create
	@type numTwistJoints: int
	@param offsetAxis: Twist joint offset axis
	@type offsetAxis: str
	@param prefix: Naming prefix for twist joints
	@type prefix: str
	'''
    # ==========
    # - Checks -
    # ==========

    # Check joint
    if not mc.objExists(joint):
        raise Exception('Joint ' + joint + ' does not exist!')

    # Check prefix
    if not prefix: prefix = glTools.utils.stringUtils.stripSuffix(joint)

    # Offset Axis
    if not ['x', 'y', 'z'].count(offsetAxis):
        raise Exception('Invalid offset axis value! ("' + offsetAxis + '")')

    # =================
    # - Create Joints -
    # =================

    # Get joint length
    jointEnd = mc.listRelatives(joint, c=True)[0]
    jointLen = mc.getAttr(jointEnd + '.t' + offsetAxis)
    jointOffset = jointLen / (numTwistJoints - 1)

    # Create twist joints
    twistJoints = []
    for i in range(numTwistJoints):

        alphaInd = glTools.utils.stringUtils.alphaIndex(i, upper=True)

        # Duplicate joint
        twistJoint = mc.duplicate(joint,
                                  po=True,
                                  n=prefix + '_twist' + alphaInd + '_jnt')[0]
        # Remove user attributes
        glTools.utils.attribute.deleteUserAttrs(twistJoint)
        # Parent to joint
        mc.parent(twistJoint, joint)

        # Position joint
        mc.setAttr(twistJoint + '.t' + offsetAxis, jointOffset * i)

        # Append joint list
        twistJoints.append(twistJoint)

    # =================
    # - Return Result -
    # =================

    return twistJoints
コード例 #47
0
def modifyZdepth(zdshader):
	ncp=cm.floatFieldGrp('g_NCP',q=1,value1=1)
	fcp=cm.floatFieldGrp('g_FCP',q=1,value1=1)
	#inv=cm.checkBox('g_invert',q=1,v=1)
	cm.setAttr('%s.min_dis'%zdshader,ncp)
	cm.setAttr('%s.max_dis'%zdshader,fcp)
    def Batch_Position_Fn(self):

        ChildrenList = self.Item_Layout.children()
        for i,child in enumerate(ChildrenList):
            if i != 0:
                Base_Curve = self.Attr["Add_Crv_LE"]
                CamGrp = child.Attr["Add_CamGrp_LE"]
                if not cmds.objExists(Base_Curve): continue
                if not cmds.objExists(CamGrp): continue
                cmds.setAttr("%s.tx" % CamGrp,0)
                cmds.setAttr("%s.ty" % CamGrp,0)
                cmds.setAttr("%s.tz" % CamGrp,0)
                cmds.setAttr("%s.rx" % CamGrp,0)
                cmds.setAttr("%s.ry" % CamGrp,0)
                cmds.setAttr("%s.rz" % CamGrp,0)
                cmds.xform( CamGrp,cp=1 )
                cmds.delete(cmds.parentConstraint( Base_Curve,CamGrp ))
                Target_Curve = child.Attr["Add_Crv_LE"]
                if not cmds.objExists(Target_Curve): continue
                cmds.xform( Target_Curve,cp=1 )
                # Note 解除曲线的锁定
                cmds.setAttr("%s.tx" % Target_Curve,lock=False)
                cmds.setAttr("%s.ty" % Target_Curve,lock=False)
                cmds.setAttr("%s.tz" % Target_Curve,lock=False)
                cmds.setAttr("%s.rx" % Target_Curve,lock=False)
                cmds.setAttr("%s.ry" % Target_Curve,lock=False)
                cmds.setAttr("%s.rz" % Target_Curve,lock=False)
                cmds.delete(cmds.parentConstraint( Base_Curve,Target_Curve ))
                cmds.headsUpMessage(u"位置匹配完成")
コード例 #49
0
ファイル: baseClass.py プロジェクト: yazici/fromGod
def SK_mirrorRoateCons(obj):
    MorrirGrp = obj + '_Mirror_GRP'
    RX = MorrirGrp + '.rx'
    RY = MorrirGrp + '.ry'
    RZ = MorrirGrp + '.rz'
    DRX = rig.listConnections(RX, s=True, d=False, p=True)
    DRY = rig.listConnections(RY, s=True, d=False, p=True)
    DRZ = rig.listConnections(RZ, s=True, d=False, p=True)
    if DRX:
        rig.disconnectAttr(DRX[0], RX)
        rig.disconnectAttr(DRY[0], RY)
        rig.disconnectAttr(DRZ[0], RZ)

        OCT = obj + '_OCT'
        UpLoc = rig.spaceLocator(n=obj + '_Position_Up_Face_LOC')[0]
        AimLoc = rig.spaceLocator(n=obj + '_Position_Aim_Face_LOC')[0]
        LocGrp = rig.group(UpLoc, AimLoc, n=obj + '_Loc_GRP')
        Pos = rig.xform(obj, q=True, t=True, ws=True)
        rig.parent(LocGrp, obj)
        rig.xform(LocGrp, t=Pos, ws=True)
        rig.makeIdentity(LocGrp, apply=True, s=True, r=True, t=True)
        rig.setAttr(UpLoc + '.ty', 1)
        rig.setAttr(AimLoc + '.tz', 1)
        rig.parent(UpLoc, w=True)
        rig.parent(AimLoc, w=True)
        AimCons = rig.aimConstraint(AimLoc,
                                    MorrirGrp,
                                    aimVector=(0, 0, 1),
                                    upVector=(0, 1, 0),
                                    worldUpType='object',
                                    worldUpObject=UpLoc)
        rig.delete(AimCons, AimLoc, LocGrp, UpLoc)

        Ro = rig.xform(MorrirGrp, q=True, ro=True, wd=True)
        WsRo = rig.xform(MorrirGrp, q=True, ro=True, ws=True)
        rig.setAttr(MorrirGrp + '.X', Ro[0])
        rig.setAttr(MorrirGrp + '.Y', Ro[1])
        rig.setAttr(MorrirGrp + '.Z', Ro[2])
        rig.connectAttr(DRX[0], RX)
        rig.connectAttr(DRY[0], RY)
        rig.connectAttr(DRZ[0], RZ)
        rig.setAttr(OCT + '.offsetX', WsRo[0])
        rig.setAttr(OCT + '.offsetY', WsRo[1])
        rig.setAttr(OCT + '.offsetZ', WsRo[2])
        rig.xform(obj, ro=(0, 0, 0), wd=True)

    else:

        UpLoc = rig.spaceLocator(n=obj + '_Position_Up_Face_LOC')[0]
        AimLoc = rig.spaceLocator(n=obj + '_Position_Aim_Face_LOC')[0]
        LocGrp = rig.group(UpLoc, AimLoc, n=obj + '_Loc_GRP')
        Pos = rig.xform(obj, q=True, t=True, ws=True)
        rig.parent(LocGrp, obj)
        rig.xform(LocGrp, t=Pos, ws=True)
        rig.makeIdentity(LocGrp, apply=True, s=True, r=True, t=True)
        rig.setAttr(UpLoc + '.ty', 1)
        rig.setAttr(AimLoc + '.tz', 1)
        rig.parent(UpLoc, w=True)
        rig.parent(AimLoc, w=True)
        AimCons = rig.aimConstraint(AimLoc,
                                    MorrirGrp,
                                    aimVector=(0, 0, 1),
                                    upVector=(0, 1, 0),
                                    worldUpType='object',
                                    worldUpObject=UpLoc)
        rig.delete(AimCons, AimLoc, LocGrp, UpLoc)
        rig.xform(obj, ro=(0, 0, 0), wd=True)
コード例 #50
0
    def __init__(self, ctrlGrp, neckJnt, headJnt, headUpJnt, headLowJnt,
                 jawJnt, noseJnt, eyebrowJnt, upperTeethJnt, lowerTeethJnt,
                 tongue01Jnt, tongue02Jnt, tongue03Jnt, tongue04Jnt, earLFTJnt,
                 earRGTJnt, noseTipJnt, chinJnt, throatJnt, scale,
                 nostrilLFTJnt, cheekUpLFTJnt, cheekUpOutLFTJnt,
                 cheekDownLFTJnt, eyebrowInLFTJnt, eyebrowMidLFTJnt,
                 eyebrowOutLFTJnt, browInUpLFTJnt, browMidUpLFTJnt,
                 browOutUpLFTJnt, eyelidPinchInLFTJnt, browInDownLFTJnt,
                 browMidDownLFTJnt, browOutDownLFTJnt, eyelidPinchOutLFTJnt,
                 nostrilRGTJnt, cheekUpRGTJnt, cheekUpOutRGTJnt,
                 cheekDownRGTJnt, eyebrowInRGTJnt, eyebrowMidRGTJnt,
                 eyebrowOutRGTJnt, browInUpRGTJnt, browMidUpRGTJnt,
                 browOutUpRGTJnt, eyelidPinchInRGTJnt, browInDownRGTJnt,
                 browMidDownRGTJnt, browOutDownRGTJnt, eyelidPinchOutRGTJnt,
                 sideLFT, sideRGT, eyeballJntLFT, eyeballJntRGT,
                 prefixEyeballAim, positionEyeAimCtrl, objectFolMesh,
                 directionBrowIn, directionBrowMid, directionBrowOut,
                 directionBrowPinchIn, directionBrowPinchOut, headCtrlSSNode):

        # BUILD CONTROLLER
        ctrlFaceGroup = mc.group(em=1, n='faceCtrl_grp')

        main = mn.Build(
            ctrlGrp=ctrlGrp,
            objectFolMesh=objectFolMesh,
            neckJnt=neckJnt,
            headJnt=headJnt,
            noseJnt=noseJnt,
            headUpJnt=headUpJnt,
            headLowJnt=headLowJnt,
            eyebrowJnt=eyebrowJnt,
            jawJnt=jawJnt,
            upperTeethJnt=upperTeethJnt,
            lowerTeethJnt=lowerTeethJnt,
            tongue01Jnt=tongue01Jnt,
            tongue02Jnt=tongue02Jnt,
            tongue03Jnt=tongue03Jnt,
            tongue04Jnt=tongue04Jnt,
            noseTipJnt=noseTipJnt,
            chinJnt=chinJnt,
            throatJnt=throatJnt,
            scale=scale,
            eyeballJntLFT=eyeballJntLFT,
            eyeballJntRGT=eyeballJntRGT,
            prefixEyeballAim=prefixEyeballAim,
            positionEyeAimCtrl=positionEyeAimCtrl,
            headCtrlSSNode=headCtrlSSNode,
        )

        secLFT = sc.Build(objectFolMesh=objectFolMesh,
                          nostrilJnt=nostrilLFTJnt,
                          earJnt=earLFTJnt,
                          headCtrl=main.headCtrl,
                          headUpCtrl=main.headUpCtrl,
                          headLowCtrl=main.headLowCtrl,
                          cheekUpJnt=cheekUpLFTJnt,
                          cheekUpOutJnt=cheekUpOutLFTJnt,
                          cheekDownJnt=cheekDownLFTJnt,
                          eyebrowInJnt=eyebrowInLFTJnt,
                          eyebrowMidJnt=eyebrowMidLFTJnt,
                          eyebrowOutJnt=eyebrowOutLFTJnt,
                          browInUpJnt=browInUpLFTJnt,
                          browMidUpJnt=browMidUpLFTJnt,
                          browOutUpJnt=browOutUpLFTJnt,
                          eyelidPinchInJnt=eyelidPinchInLFTJnt,
                          browInDownJnt=browInDownLFTJnt,
                          browMidDownJnt=browMidDownLFTJnt,
                          browOutDownJnt=browOutDownLFTJnt,
                          eyelidPinchOutJnt=eyelidPinchOutLFTJnt,
                          sideRGT=sideRGT,
                          sideLFT=sideLFT,
                          scale=scale,
                          side=sideLFT,
                          directionBrowIn=directionBrowIn,
                          directionBrowMid=directionBrowMid,
                          directionBrowOut=directionBrowOut,
                          directionBrowPinchIn=directionBrowPinchIn,
                          directionBrowPinchOut=directionBrowPinchOut)

        secRGT = sc.Build(objectFolMesh=objectFolMesh,
                          nostrilJnt=nostrilRGTJnt,
                          earJnt=earRGTJnt,
                          cheekUpJnt=cheekUpRGTJnt,
                          cheekUpOutJnt=cheekUpOutRGTJnt,
                          headCtrl=main.headCtrl,
                          headUpCtrl=main.headUpCtrl,
                          headLowCtrl=main.headLowCtrl,
                          cheekDownJnt=cheekDownRGTJnt,
                          eyebrowInJnt=eyebrowInRGTJnt,
                          eyebrowMidJnt=eyebrowMidRGTJnt,
                          eyebrowOutJnt=eyebrowOutRGTJnt,
                          browInUpJnt=browInUpRGTJnt,
                          browMidUpJnt=browMidUpRGTJnt,
                          browOutUpJnt=browOutUpRGTJnt,
                          eyelidPinchInJnt=eyelidPinchInRGTJnt,
                          browInDownJnt=browInDownRGTJnt,
                          browMidDownJnt=browMidDownRGTJnt,
                          browOutDownJnt=browOutDownRGTJnt,
                          eyelidPinchOutJnt=eyelidPinchOutRGTJnt,
                          sideRGT=sideRGT,
                          sideLFT=sideLFT,
                          scale=scale,
                          side=sideRGT,
                          directionBrowIn=directionBrowIn,
                          directionBrowMid=directionBrowMid,
                          directionBrowOut=directionBrowOut,
                          directionBrowPinchIn=directionBrowPinchIn,
                          directionBrowPinchOut=directionBrowPinchOut)

        self.headUpCtrlGrpParent = main.headUpCtrlGrp
        self.headUpCtrl = main.headUpCtrl

        self.headLowCtrl = main.headLowCtrl
        self.jawCtrl = main.jawCtrl

        # CONSTRAINT CHEEK DOWN JNT
        prntConsLFT = mc.parentConstraint(main.headLowCtrl,
                                          main.jawCtrl,
                                          secLFT.cheekDownJntGrp,
                                          mo=1)[0]
        mc.setAttr(prntConsLFT + '.interpType', 2)

        prntConsRGT = mc.parentConstraint(main.headLowCtrl,
                                          main.jawCtrl,
                                          secRGT.cheekDownJntGrp,
                                          mo=1)[0]
        mc.setAttr(prntConsRGT + '.interpType', 2)

        mc.parent(secLFT.eyebrowCtrlGrp, secRGT.eyebrowCtrlGrp,
                  main.headUpCtrl)
        mc.parent(secLFT.earCtrlGrp, secRGT.earCtrlGrp, main.headCtrlGimbal)
        mc.parent(secLFT.follicleTransformAll, secRGT.follicleTransformAll,
                  main.follicleTransformAll, main.headCtrlGrp,
                  main.headCtrlGrp, ctrlFaceGroup)

        self.ctrlFaceGroup = ctrlFaceGroup
        # self.neckCtrlGrp = main.neckCtrlGrp
        self.eyeballAimMainCtrlGrp = main.eyeballAimMainCtrlGrp
        self.eyeballAimMainCtrl = main.eyeballAimMainCtrl
        self.headCtrlGrp = main.headCtrlGrp
コード例 #51
0
def readCoreData(pathToXML=''):
    '''
    Clean up the Scene, get the Dictionary and setup the scene.
    '''
    print 'MY PATHTOXML IS: %s' % pathToXML
    _cleanUp()
    print "Cleaned Up successfully"
    mentalCoreGlobalsDict, mentalCoreLensDataDict, mentalrayGlobalsDict, miDefaultOptionDict, layerDict, mentalCorePassesDict = _XML2Dictinary(
        pathToXML)
    #     print mentalCoreGlobalsDict
    #     print mentalCoreLensDataDict
    #     print mentalrayGlobalsDict
    #     print miDefaultOptionDict
    #     print layerDict
    #     print mentalCorePassesDict
    print "Dictionaries are here successfully"
    mentalCoreAvailibleDict = {
        0: 'Beauty',
        1: 'Colour',
        2: 'Diffuse',
        3: 'Diffuse Raw',
        4: 'Shadow',
        5: 'Shadow Raw',
        6: 'Diffuse Without Shadows',
        7: 'Diffuse Without Shadows Raw',
        8: 'Ambient',
        9: 'Ambient Raw',
        10: 'Indirect',
        11: 'Indirect Raw',
        12: 'Ambient Occlusion',
        13: 'Translucency',
        14: 'Subsurface',
        15: 'Subsurface Front',
        16: 'Subsurface Mid',
        17: 'Subsurface Back',
        18: 'Incandescence',
        19: 'Specular',
        20: 'Reflection',
        21: 'Refraction',
        38: 'Light Select',
        22: 'Bloom Source',
        37: 'Environment',
        23: 'Depth',
        23: 'Depth (Normalized)',
        24: 'Normal World',
        24: 'Normal World (Normalized)',
        25: 'Normal Camera',
        25: 'Normal Camera (Normalized)',
        26: 'Point World',
        27: 'Point Camera',
        28: 'Motion Vector',
        28: 'Motion Vector (Normalized)',
        29: 'Opacity',
        30: 'Facing Ratio',
        31: 'UV',
        32: 'Material ID',
        33: 'Object ID',
        34: 'Matte',
        35: 'Custom Colour',
        36: 'Custom Vector',
        39: 'Diagnostic Samples',
        40: 'Diagnostic Error',
        41: 'Diagnostic Time'
    }

    #########################################################################
    # 1- check if layer exist and if not create a new layer
    #########################################################################
    for eachKey, eachValue in layerDict.iteritems():
        if eachKey not in cmds.ls(
                type="renderLayer"
        ):  #Looking for Existing layers and adding to the scene
            cmds.createRenderLayer(name=eachKey)
        #########################################################################
        # 2- assign the each Asset under each layer
        #########################################################################
        if eachKey != "defaultRenderLayer":  #assigning each assets to each existing layer
            for eachOBJ in eachValue[1]:
                cmds.editRenderLayerMembers(eachKey, eachOBJ, noRecurse=True)

        #########################################################################
        # 3- check the passes in the scene and create one if doesn't exist
        #########################################################################
    for eachKey, eachValue in mentalCorePassesDict.iteritems():
        if eachValue[0] != "":
            mapi.create_pass(mentalCoreAvailibleDict[eachValue[0]], n=eachKey)

        #########################################################################
        # 4- set each passes setting in the scene
        #########################################################################
        for eachSettingKey, eachSettingValue in eachValue[2].iteritems():
            #             print "%s.%s %s Progressing" %(eachKey,eachSettingKey,eachSettingValue)
            #             print type(eachSettingValue)
            if eachSettingValue != "":
                if type(eachSettingValue) == int:
                    cmds.setAttr("%s.%s" % (eachKey, eachSettingKey),
                                 eachSettingValue)
                if type(eachSettingValue) == bool:
                    cmds.setAttr("%s.%s" % (eachKey, eachSettingKey),
                                 eachSettingValue)
                if type(eachSettingValue) == str:
                    cmds.setAttr("%s.%s" % (eachKey, eachSettingKey),
                                 eachSettingValue,
                                 type="string")
                if type(eachSettingValue) == tuple:
                    print "%s.%s %s Progressing" % (eachKey, eachSettingKey,
                                                    eachSettingValue)
                    print type(eachSettingValue)

        #########################################################################
        # 5- connect the passes to asses in the scene
        #########################################################################
        if eachValue[1] != "":
            mapi.link_to_pass(eachValue[1], eachKey, mapi.OBJECTS)

        #########################################################################
        # 6- check the associated passes and create new if doesn't exist
        #########################################################################
    for eachlayerKey, eachlayerValue in layerDict.iteritems():
        if eachlayerValue[0] != "":
            for eachAssociacted in eachlayerValue[0]:
                mapi.associate_pass(eachAssociacted, eachlayerKey)

        #########################################################################
        # 7- set the setting of imDefaultOption
        #########################################################################
    miDefaultName = "miDefaultOptions"
    for eachMIKey, eachIMValue in miDefaultOptionDict.iteritems():
        if eachIMValue != "":
            if type(eachIMValue) == int:
                cmds.setAttr("%s.%s" % (miDefaultName, eachMIKey), eachIMValue)
            if type(eachIMValue) == bool:
                cmds.setAttr("%s.%s" % (miDefaultName, eachMIKey), eachIMValue)
            if type(eachIMValue) == str:
                cmds.setAttr("%s.%s" % (miDefaultName, eachMIKey),
                             eachIMValue,
                             type="string")
            if type(eachIMValue) == tuple:
                print "%s.%s %s Progressing" % (miDefaultName, eachMIKey,
                                                eachIMValue)
                print type(eachIMValue)

        if eachIMValue == "":
            cmds.setAttr("%s.%s" % (miDefaultName, eachMIKey),
                         "",
                         type="string")

        #########################################################################
        # 8- set the setting of Mentalray Globals
        #########################################################################
    mentalrayName = "mentalrayGlobals"
    for eachMRKey, eachMRValue in mentalrayGlobalsDict.iteritems():
        if eachMRValue != "":
            if type(eachMRValue) == int:
                cmds.setAttr("%s.%s" % (mentalrayName, eachMRKey), eachMRValue)
            if type(eachMRValue) == bool:
                cmds.setAttr("%s.%s" % (mentalrayName, eachMRKey), eachMRValue)
            if type(eachMRValue) == str:
                cmds.setAttr("%s.%s" % (mentalrayName, eachMRKey),
                             eachMRValue,
                             type="string")
            if type(eachMRValue) == tuple:
                print "%s.%s %s Progressing" % (mentalrayName, eachMRKey,
                                                eachMRValue)
                print type(eachMRValue)
        if eachMRValue == "":
            cmds.setAttr("%s.%s" % (mentalrayName, eachMRKey),
                         "",
                         type="string")
        #########################################################################
        # 9- set the setting of MentalCore Globals
        #########################################################################
    mentalcoreGlobalsName = "mentalcoreGlobals"
    for eachMCGKey, eachMCGValue in mentalCoreGlobalsDict.iteritems():
        if eachMCGValue != "":
            if type(eachMCGValue) == int:
                cmds.setAttr("%s.%s" % (mentalcoreGlobalsName, eachMCGKey),
                             eachMCGValue)
            if type(eachMCGValue) == bool:
                cmds.setAttr("%s.%s" % (mentalcoreGlobalsName, eachMCGKey),
                             eachMCGValue)
            if type(eachMCGValue) == str:
                cmds.setAttr("%s.%s" % (mentalcoreGlobalsName, eachMCGKey),
                             eachMCGValue,
                             type="string")
            if type(eachMCGValue) == tuple:
                print "%s.%s %s Progressing" % (mentalcoreGlobalsName,
                                                eachMCGKey, eachMCGValue)
                print type(eachMCGValue)
        if eachMCGValue == "":
            cmds.setAttr("%s.%s" % (mentalcoreGlobalsName, eachMCGKey),
                         "",
                         type="string")

        #########################################################################
        # 10- set the setting of MentalCore Lens Data
        #########################################################################
    mentalcoreLensName = "mentalcoreLens"
    for eachMCLKey, eachMCLValue in mentalCoreLensDataDict.iteritems():
        if eachMCLValue != "":
            if type(eachMCLValue) == int:
                cmds.setAttr("%s.%s" % (mentalcoreLensName, eachMCLKey),
                             eachMCLValue)
            if type(eachMCLValue) == bool:
                cmds.setAttr("%s.%s" % (mentalcoreLensName, eachMCLKey),
                             eachMCLValue)
            if type(eachMCLValue) == str:
                cmds.setAttr("%s.%s" % (mentalcoreLensName, eachMCLKey),
                             eachMCLValue,
                             type="string")
            if type(eachMCLValue) == tuple:
                print "%s.%s %s Progressing" % (mentalcoreLensName, eachMCLKey,
                                                eachMCLValue)
                print type(eachMCLValue)
        if eachMCLValue == "":
            cmds.setAttr("%s.%s" % (mentalcoreLensName, eachMCLKey),
                         "",
                         type="string")
    return
コード例 #52
0
def modifyAoAndWn(awshader):
	sa=cm.intFieldGrp('g_samp', q=1,value1=1)
	br=cm.colorSliderGrp('g_brig',q=1,rgb=1)
	da=cm.colorSliderGrp('g_dark',q=1,rgb=1)
	sp=cm.floatFieldGrp('g_spre',q=1,value1=1)
	ma=cm.floatFieldGrp('g_maxD',q=1,value1=1)
	re=cm.checkBox('g_reflective',q=1,v=1)
	ou=cm.intSliderGrp('g_outputM',q=1,v=1)
	oi=cm.checkBox('g_OIA',q=1,v=1)
	fa=cm.floatFieldGrp('g_fallo',q=1,value1=1)
	idi=cm.intFieldGrp('g_idIncl',q=1,value1=1)
	idn=cm.intFieldGrp('g_idNonself',q=1,value1=1)
	cm.setAttr('%s.samples'%awshader, sa)
	cm.setAttr('%s.bright'%awshader, br[0],br[1],br[2], type='double3')
	cm.setAttr('%s.dark'%awshader, da[0],da[1],da[2], type='double3')
	cm.setAttr('%s.spread'%awshader, sp)
	cm.setAttr('%s.max_distance'%awshader, ma)
	cm.setAttr('%s.reflective'%awshader, re)
	cm.setAttr('%s.output_mode'%awshader, ou)
	cm.setAttr('%s.occlusion_in_alpha'%awshader, oi)
	cm.setAttr('%s.falloff'%awshader, fa)
	cm.setAttr('%s.id_inclexcl'%awshader, idi)
	cm.setAttr('%s.id_nonself'%awshader, idn)
コード例 #53
0
    def _stretchy(self):
        """Stretchy attribute and create connections to joints. """

        stretchy_attr = self.ik_controllers["hindleg"] + ".stretchy"
        dist_dict = {}

        stretchy_grp = mc.group(n='{}_{}_stretchy_{}_{}'.format(self.side, self.name, self.suffix, self.instance_num),
                                em=True, p=self.mod_dict["IKcontrol"])
        mc.hide(stretchy_grp)

        start_loc = mc.spaceLocator(n=self.joint_dict["hipSPRING"].replace('jnt', 'loc'))[0]
        end_loc = mc.spaceLocator(n=self.ik_controllers["footIkOffset"].replace('ctl', 'loc'))[0]

        hip_loc_static = mc.spaceLocator(n=self.joint_dict["hipFINAL"].replace('_jnt', 'Static_loc'))[0]
        knee_loc_static = mc.spaceLocator(n=self.joint_dict["kneeFINAL"].replace('_jnt', 'Static_loc'))[0]
        foot_loc_static = mc.spaceLocator(n=self.joint_dict["footFINAL"].replace('_bnd', 'Static_loc'))[0]
        ball_loc_static = mc.spaceLocator(n=self.joint_dict["ballFINAL"].replace('_bnd', 'Static_loc'))[0]

        mc.parentConstraint(self.ik_controllers["footIkOffset"], end_loc, n=end_loc.replace("loc", "prc"))
        mc.parentConstraint(self.joint_dict["hipSPRING"], start_loc, n=start_loc.replace("loc", "prc"))

        del_hip = mc.parentConstraint(self.joint_dict["hipSPRING"], hip_loc_static)
        del_knee = mc.parentConstraint(self.joint_dict["kneeSPRING"], knee_loc_static)
        del_foot = mc.parentConstraint(self.joint_dict["footSPRING"], foot_loc_static)
        del_ball = mc.parentConstraint(self.joint_dict["ballSPRING"], ball_loc_static)

        [mc.delete(x) for x in [del_hip, del_knee, del_foot, del_ball]]

        for i in [start_loc, end_loc, hip_loc_static, knee_loc_static, foot_loc_static, ball_loc_static]:
            mc.parent(i, stretchy_grp)

        dist_node = mc.createNode('distanceBetween')
        for i in ["hip", "knee", "foot"]:
            dist = mc.createNode('distanceBetween', n=self.joint_dict[i + "FINAL"].replace('_jnt', 'Static_dst'))
            dist_dict[i] = dist

        dist_pma = mc.createNode('plusMinusAverage', n=self.joint_dict["footFINAL"].replace('_bnd', 'Static_pma'))
        mult1 = mc.createNode('multiplyDivide', n=stretchy_grp.replace("_grp", "Distance_mult"))
        cond1 = mc.createNode('condition', n=mult1.replace('mult', 'cond'))
        cond2 = mc.createNode('condition',  n=cond1.replace('Distance', 'On'))

        mc.connectAttr('{}.worldMatrix'.format(start_loc), '{}.inMatrix1.'.format(dist_node))
        mc.connectAttr('{}.worldMatrix'.format(end_loc), '{}.inMatrix2.'.format(dist_node))
        mc.connectAttr('{}.worldMatrix'.format(hip_loc_static), '{}.inMatrix1.'.format(dist_dict["hip"]))
        mc.connectAttr('{}.worldMatrix'.format(knee_loc_static), '{}.inMatrix2.'.format(dist_dict["hip"]))
        mc.connectAttr('{}.worldMatrix'.format(knee_loc_static), '{}.inMatrix1.'.format(dist_dict["knee"]))
        mc.connectAttr('{}.worldMatrix'.format(foot_loc_static), '{}.inMatrix2.'.format(dist_dict["knee"]))
        mc.connectAttr('{}.worldMatrix'.format(foot_loc_static), '{}.inMatrix1.'.format(dist_dict["foot"]))
        mc.connectAttr('{}.worldMatrix'.format(ball_loc_static), '{}.inMatrix2.'.format(dist_dict["foot"]))

        mc.connectAttr('{}.distance'.format(dist_dict["hip"]), '{}.input1D[0]'.format(dist_pma))
        mc.connectAttr('{}.distance'.format(dist_dict["knee"]), '{}.input1D[1]'.format(dist_pma))
        mc.connectAttr('{}.distance'.format(dist_dict["foot"]), '{}.input1D[2]'.format(dist_pma))

        mc.setAttr('{}.operation'.format(mult1), 2)
        mc.connectAttr('{}.output1D'.format(dist_pma), '{}.input2.input2X.'.format(mult1))
        mc.connectAttr('{}.distance'.format(dist_node), '{}.input1.input1X.'.format(mult1))

        mc.setAttr('{}.operation'.format(cond1), 3)
        mc.connectAttr('{}.output.outputX'.format(mult1), '{}.firstTerm.'.format(cond1))
        mc.setAttr('{}.secondTerm.'.format(cond1), 1)
        mc.connectAttr('{}.output.outputX'.format(mult1), '{}.colorIfTrue.colorIfTrueR.'.format(cond1))

        mc.setAttr('{}.secondTerm'.format(cond2), 1)
        mc.connectAttr('{}.outColor.outColorR'.format(cond1), '{}.colorIfTrue.colorIfTrueR.'.format(cond2))
        mc.connectAttr(stretchy_attr, '{}.firstTerm.'.format(cond2))
        mc.connectAttr('{}.outColor.outColorR'.format(cond2), '{}.scale.scaleZ.'.format(self.joint_dict["hipIK"]))
        mc.connectAttr('{}.outColor.outColorR'.format(cond2), '{}.scale.scaleZ.'.format(self.joint_dict["kneeIK"]))
コード例 #54
0
def AnorldToRedshift():
    import maya.cmds as cmds
    StartShader = 'aiStandardSurface'
    EndShader = 'RedshiftMaterial'

    diff_color1 = '.baseColor'
    diff_color2 = '.diffuse_color'

    metalness1 = '.metalness'
    metalness2 = '.refl_metalness'

    spc_w_parm1 = '.specular'
    spc_w_parm2 = '.refl_weight'

    spc_color1 = '.specularColor'
    spc_color2 = '.refl_color'

    spc_Roughness1 = '.specularRoughness'
    spc_Roughness2 = '.refl_roughness'

    tran_color1 = '.opacity'
    tran_color2 = '.opacity_color'

    bump_color1 = '.normalCamera'
    bump_color2 = '.bump_input'

    ai_list = cmds.ls(sl=True, type=StartShader)

    del_mat_list = []
    del_Displace_Utility_list = []

    for node in ai_list:
        new_shader = cmds.shadingNode(EndShader,
                                      n='Rs' + '_' + str(node),
                                      asShader=True)
        old_shadingEngine = cmds.listConnections(node + '.outColor')
        for shading_node in old_shadingEngine:
            cmds.connectAttr(str(new_shader) + '.outColor',
                             str(shading_node) + '.surfaceShader',
                             force=True)
            Displace_Utility = cmds.listConnections(shading_node +
                                                    '.displacementShader')
            if (Displace_Utility[0] != None):
                new_Displace_Utility = cmds.shadingNode(
                    'RedshiftDisplacement',
                    n='new_RsDis_' + str(Displace_Utility[0]),
                    asShader=True)
                if (cmds.nodeType(
                        Displace_Utility[0]) == 'displacementShader'):
                    Displace_tex_file = cmds.listConnections(
                        Displace_Utility[0] + '.displacement')
                    cmds.setAttr(str(new_Displace_Utility) + '.scale', 0.1)
                    for Displace_tex_file_node in Displace_tex_file:
                        Displace_tex_file_node_type = cmds.nodeType(
                            Displace_tex_file_node)
                        if (Displace_tex_file_node_type == 'file'):
                            cmds.connectAttr(
                                str(Displace_tex_file_node) + '.outColor',
                                str(new_Displace_Utility) + '.texMap',
                                force=True)
                            cmds.connectAttr(
                                str(new_Displace_Utility) + '.out',
                                shading_node + '.displacementShader',
                                force=True)
                if (cmds.nodeType(Displace_Utility[0]) == 'file'):
                    cmds.setAttr(str(new_Displace_Utility) + '.scale', 0.1)
                    cmds.connectAttr(str(Displace_Utility[0]) + '.outColor',
                                     str(new_Displace_Utility) + '.texMap',
                                     force=True)
                    cmds.connectAttr(str(new_Displace_Utility) + '.out',
                                     shading_node + '.displacementShader',
                                     force=True)

                #del_Displace_Utility_list.append(Displace_Utility[0])

            #diffuse_color
            diff_c_file = cmds.listConnections(node + diff_color1)
            diff_c_file_type = cmds.nodeType(diff_c_file)
            if (diff_c_file != None and str(diff_c_file_type) == 'file'):
                cmds.connectAttr(str(diff_c_file[0]) + '.outColor',
                                 str(new_shader) + diff_color2,
                                 force=True)
            else:
                diff_c_number = cmds.getAttr(node + diff_color1)
                cmds.setAttr(new_shader + diff_color2,
                             diff_c_number[0][0],
                             diff_c_number[0][1],
                             diff_c_number[0][2],
                             type="double3")

            #metalness_weight
            metalness_w_file = cmds.listConnections(node + metalness1)
            metalness_w_file_type = cmds.nodeType(metalness_w_file)
            if (metalness_w_file != None
                    and str(metalness_w_file_type) == 'file'):
                cmds.setAttr(new_shader + '.refl_fresnel_mode', 2)
                cmds.connectAttr(str(metalness_w_file[0]) + '.outAlpha',
                                 str(new_shader) + metalness2,
                                 force=True)
            else:
                metalness_w_number = cmds.getAttr(node + metalness1)
                cmds.setAttr(new_shader + metalness2, metalness_w_number)

            #specular_weight
            spc_w_file = cmds.listConnections(node + spc_w_parm1)
            spc_w_file_type = cmds.nodeType(spc_w_file)
            if (spc_w_file != None and str(spc_w_file_type) == 'file'):
                cmds.connectAttr(str(spc_w_file[0]) + '.outAlpha',
                                 str(new_shader) + spc_w_parm2,
                                 force=True)
            else:
                spc_w_number = cmds.getAttr(node + spc_w_parm1)
                cmds.setAttr(new_shader + spc_w_parm2, spc_w_number)

            #specular_color
            spc_c_file = cmds.listConnections(node + spc_color1)
            spc_c_file_type = cmds.nodeType(spc_c_file)
            if (spc_c_file != None and str(spc_c_file_type) == 'file'):
                cmds.connectAttr(str(spc_c_file[0]) + '.outColor',
                                 str(new_shader) + spc_color2,
                                 force=True)
            else:
                spc_c_number = cmds.getAttr(node + spc_color1)
                cmds.setAttr(new_shader + spc_color2,
                             spc_c_number[0][0],
                             spc_c_number[0][1],
                             spc_c_number[0][2],
                             type="double3")

            #specularRoughness
            spcrou_w_file = cmds.listConnections(node + spc_Roughness1)
            spcrou_w_file_type = cmds.nodeType(spcrou_w_file)
            if (spcrou_w_file != None and str(spcrou_w_file_type) == 'file'):
                cmds.connectAttr(str(spcrou_w_file[0]) + '.outAlpha',
                                 str(new_shader) + spc_Roughness2,
                                 force=True)
            if (spcrou_w_file != None
                    and str(spcrou_w_file_type) == 'aiRange'):
                spcrou_w_file2 = cmds.listConnections(spcrou_w_file[0] +
                                                      '.input')
                cmds.connectAttr(str(spcrou_w_file2[0]) + '.outAlpha',
                                 str(new_shader) + spc_Roughness2,
                                 force=True)
            if (spcrou_w_file == None):
                spcrou_w_number = cmds.getAttr(node + spc_Roughness1)
                cmds.setAttr(new_shader + spc_Roughness2, spcrou_w_number)

            #opacity_color
            tran_c_file = cmds.listConnections(node + tran_color1)
            tran_c_file_type = cmds.nodeType(tran_c_file)
            if (tran_c_file != None and str(tran_c_file_type) == 'file'):
                cmds.connectAttr(str(tran_c_file[0]) + '.outColor',
                                 str(new_shader) + tran_color2,
                                 force=True)
            else:
                tran_c_number = cmds.getAttr(node + tran_color1)
                cmds.setAttr(new_shader + tran_color2,
                             int(tran_c_number[0][0]),
                             int(tran_c_number[0][1]),
                             int(tran_c_number[0][2]),
                             type="double3")

            #normal_bump
            ainormap = cmds.listConnections(node + bump_color1)
            if (ainormap != None):
                ainormap_type = cmds.nodeType(ainormap[0])
                if (ainormap_type == 'aiNormalMap'):
                    ainormap_file = cmds.listConnections(ainormap[0] +
                                                         '.input')
                    new_bump_node = cmds.shadingNode('RedshiftBumpMap',
                                                     n='new_Rsbump_' +
                                                     str(ainormap_file[0]),
                                                     asTexture=True)
                    cmds.setAttr(
                        str(ainormap_file[0]) + '.alphaIsLuminance', 1)
                    cmds.connectAttr(str(ainormap_file[0]) + '.outColor',
                                     str(new_bump_node) + '.input',
                                     force=True)
                    cmds.connectAttr(str(new_bump_node) + '.out',
                                     str(new_shader) + bump_color2,
                                     force=True)
                    cmds.delete(ainormap[0])
                if (ainormap_type == 'bump2d'):
                    ainormap_file = cmds.listConnections(ainormap[0] +
                                                         '.bumpValue')
                    new_bump_node = cmds.shadingNode('RedshiftBumpMap',
                                                     n='new_Rsbump_' +
                                                     str(ainormap_file[0]),
                                                     asTexture=True)
                    cmds.setAttr(
                        str(ainormap_file[0]) + '.alphaIsLuminance', 1)
                    cmds.connectAttr(str(ainormap_file[0]) + '.outColor',
                                     str(new_bump_node) + '.input',
                                     force=True)
                    cmds.connectAttr(str(new_bump_node) + '.out',
                                     str(new_shader) + bump_color2,
                                     force=True)
                    cmds.delete(ainormap[0])

            del_mat_list.append(node)

        for del_mat in set(del_mat_list):
            try:
                print 'delete ' + str(del_mat)
                cmds.delete(del_mat)
            except:
                continue
        for del_Displace_Utility in set(del_Displace_Utility_list):
            try:
                print 'delete ' + str(del_Displace_Utility)
                cmds.delete(del_Displace_Utility)
            except:
                continue
コード例 #55
0
    def testMeshNextToAssemblyAndImported(self):
        """
        Tests the colors between a mesh with (0.55, 0.55, 0.55)
        exporting that file and then re-importing it, and also referencing
        it back into the same scene.

        While this is a bit more than just "GL" testing, it's a useful place to
        centralize all this.  If we don't like that this is testing usdImport
        functionality, we can remove

        This will render as follows:


        blank    |  usdImport
                 |
        ---------+-----------
        modeled  |  ref'd
                 |

        """
        x = self._PlaneWithColor((0.55, 0.55, 0.55))
        cmds.loadPlugin('pxrUsd')
        cwd = os.path.abspath('.')
        usdFile = os.path.join(cwd, 'plane.usd')
        cmds.select(x)
        cmds.usdExport(file=usdFile,
                       selection=True,
                       shadingMode='displayColor')
        assembly = cmds.assembly(name='ref', type='pxrUsdReferenceAssembly')
        cmds.xform(assembly, translation=(30.48, 0, 0))
        cmds.setAttr('%s.filePath' % assembly, usdFile, type='string')
        cmds.setAttr('%s.primPath' % assembly, '/pPlane1', type='string')
        cmds.assembly(assembly, edit=True, active='Collapsed')

        x = cmds.usdImport(file=usdFile)
        cmds.xform(x, translation=(30.48, 30.48, 0))

        cmds.setAttr("hardwareRenderingGlobals.floatingPointRTEnable", 0)
        cmds.setAttr('defaultColorMgtGlobals.outputTransformEnabled', 0)
        self._Snapshot('default')
        cmds.setAttr("hardwareRenderingGlobals.floatingPointRTEnable", 1)
        cmds.setAttr('defaultColorMgtGlobals.outputTransformEnabled', 1)
        self._Snapshot('colorMgt')
コード例 #56
0
    def _turnOffInheritTransform(self, item):
        """Turn off inherit transform on node."""

        mc.setAttr(item + ".inheritsTransform", 0)
cmds.delete( 'hairSystem1OutputCurves', 'hairSystem1', 'nucleus1' )

# Create joints
cmds.joint( p=(0, 0, 0) )
cmds.duplicate()
cmds.duplicate()
cmds.duplicate()
cmds.duplicate()
cmds.duplicate()
cmds.parent( 'joint1', 'ribbenFollicle5008' )
cmds.parent( 'joint2', 'ribbenFollicle5025' )
cmds.parent( 'joint3', 'ribbenFollicle5041' )
cmds.parent( 'joint4', 'ribbenFollicle5058' )
cmds.parent( 'joint5', 'ribbenFollicle5074' )
cmds.parent( 'joint6', 'ribbenFollicle5091' )
cmds.setAttr( 'joint6.translateY' , 0 )
cmds.setAttr( 'joint1.translateY' , 0 )
cmds.setAttr( 'joint2.translateY' , 0 )
cmds.setAttr( 'joint3.translateY' , 0 )
cmds.setAttr( 'joint4.translateY' , 0 )
cmds.setAttr( 'joint5.translateY' , 0 )
cmds.select( clear=True )
cmds.joint( p=(0, 0, 0) )
cmds.setAttr( 'joint7.radius', 5 )
cmds.select( clear=True )
cmds.joint( p=(0, 0, 3) )
cmds.setAttr( 'joint8.radius', 5 )
cmds.select( clear=True )
cmds.joint( p=(0, 0, -3) )
cmds.setAttr( 'joint9.radius', 5 )
# Create set selection for Rig
コード例 #58
0
    def _createHockIkHierarchy(self):
        """Create IK hock control hierarchy. """

        ik_hock_ctl = mc.circle(n="{}_{}_hockIk_ctl_{}".format(self.side, self.name, self.instance_num), r=1)[0]
        ik_hock_grp = mc.group(ik_hock_ctl, n=ik_hock_ctl.replace("ctl", "grp"))
        ik_hock_zero = mc.group(ik_hock_grp, n=ik_hock_ctl.replace("ctl", "zero"))
        inverse_hock_grp = mc.group(n=ik_hock_ctl.replace("_ctl", "_Inverse_grp"), em=1)
        inverse_hock_zero = mc.group(inverse_hock_grp, n=ik_hock_ctl.replace("_ctl", "_Inverse_zero"))

        mc.setAttr(inverse_hock_grp + ".rotateOrder", 5)

        mc.connectAttr(self.ik_controllers["hindleg"] + ".ikFk", ik_hock_zero + ".v")

        mc.parent(inverse_hock_zero, ik_hock_ctl)
        mc.parent(ik_hock_zero, self.mod_dict["IKcontrol"])

        mc.xform(ik_hock_zero, ws=1, matrix=self.guides["foot"][2])

        par_del = mc.parentConstraint(self.ik_controllers["footIk"], inverse_hock_zero)
        mc.delete(par_del)

        mult = mc.createNode("multiplyDivide", n=inverse_hock_grp.replace("grp", "mdn"))
        mc.setAttr(mult + ".input2X", -1)
        mc.setAttr(mult + ".input2Y", -1)
        mc.setAttr(mult + ".input2Z", -1)

        mc.connectAttr(self.misc["hockslave1"] + ".r", mult + ".input1")
        mc.connectAttr(mult + ".output", inverse_hock_grp + ".r")

        hock_grp = mc.listRelatives(self.ik_controllers["footIkOffset"], ad=1)[1]
        rjc.constrain_object(hock_grp, ik_hock_zero, "parent", 1)

        rollIn_grp = mc.group(n=ik_hock_ctl.replace("ctl", "rollIn_org"), em=1)
        rollOut_grp = mc.group(n=ik_hock_ctl.replace("ctl", "rollOut_org"), em=1)

        rollHeel_ctl = mc.circle(n=ik_hock_ctl.replace("ctl", "rollHeel_ctl"), r=.4)[0]
        rollHeel_cth = mc.group(rollHeel_ctl, n=ik_hock_ctl.replace("ctl", "rollHeel_cth"))
        rollHeel_org = mc.group(rollHeel_cth, n=ik_hock_ctl.replace("ctl", "rollHeel_org"))

        rollToe_ctl = mc.circle(n=ik_hock_ctl.replace("ctl", "rollToe_ctl"), r=.4)[0]
        rollToe_cth = mc.group(rollToe_ctl, n=ik_hock_ctl.replace("ctl", "rollToe_cth"))
        rollToe_org = mc.group(rollToe_cth, n=ik_hock_ctl.replace("ctl", "rollToe_org"))

        ballIk_ctl = mc.circle(n=ik_hock_ctl.replace("hockIk_ctl", "ballIk_ctl"), r=.4)[0]
        ballIk_cth = mc.group(ballIk_ctl, n=ballIk_ctl.replace("ctl", "cth"))
        ballIk_org = mc.group(ballIk_cth, n=ballIk_ctl.replace("ctl", "org"))

        footIk_grp = mc.group(n=ik_hock_ctl.replace("ctl", "footHook_grp"), em=1)
        footIk_cth = mc.group(footIk_grp, n=footIk_grp.replace("grp", "cth"))
        footIk_org = mc.group(footIk_cth, n=footIk_grp.replace("grp", "org"))
        footIkRev_org = mc.group(footIk_org, n=footIk_grp.replace("_grp", "Inverse_org"))
        footIkAttr_org = mc.group(footIkRev_org, n=footIk_grp.replace("_grp", "Attr_org"))

        mc.xform(rollIn_grp, ws=1, t=self.guides["rollIn"][1])
        mc.xform(rollOut_grp, ws=1, t=self.guides["rollOut"][1])
        mc.xform(rollHeel_org, ws=1, t=self.guides["rollHeel"][1])
        mc.xform(rollToe_org, ws=1, t=self.guides["toeEnd"][1])
        mc.xform(ballIk_org, ws=1, t=self.guides["ball"][1])
        mc.xform(footIkAttr_org, ws=1, t=self.guides["ball"][1])
        mc.xform(footIk_org, ws=1, matrix=self.guides["foot"][2])

        mc.parent(rollIn_grp, inverse_hock_grp)
        mc.parent(rollOut_grp, rollIn_grp)
        mc.parent(rollHeel_org, rollOut_grp)
        mc.parent(rollToe_org, rollHeel_ctl)
        mc.parent(ballIk_org, rollToe_ctl)
        mc.parent(footIkAttr_org, ballIk_ctl)

        mc.connectAttr(self.misc["hockslave1"] + ".r", footIkRev_org + ".r")
        mc.parentConstraint(ballIk_cth, self.joint_dict["ball" + "IK"], n=ballIk_cth.replace("cth", "prc"), mo=1)

        par = mc.parentConstraint(ballIk_cth, self.joint_dict["ball" + "FK"], self.joint_dict["ball" + "FINAL"],
                                  n=self.joint_dict["ball" + "FK"].replace("jnt", "prc").replace("parentConstraint1",
                                                                                                 ""), mo=1)[0]
        mc.connectAttr(self.ik_controllers["hindleg"] + ".ikFk", par + "." + ballIk_cth + "W0")

        rev = mc.createNode("reverse", n=self.joint_dict["ball" + "FK"].replace("jnt", "rev"))
        mc.connectAttr(self.ik_controllers["hindleg"] + ".ikFk", rev + ".inputX")
        mc.connectAttr(rev + ".outputX", par + "." + self.joint_dict["ball" + "FK"] + "W1")

        self.misc["footHook"] = footIk_grp
        self.misc["footHookCth"] = footIk_cth
        self.misc["footHookAttr"] = footIkAttr_org
        self.misc["rollToe"] = rollToe_cth
        self.misc["rollHeel"] = rollHeel_cth
        self.misc["rollIn"] = rollIn_grp
        self.misc["rollOut"] = rollOut_grp
コード例 #59
0
    def build(self):
        '''
        '''
        super(Arm, self).build()
        # get the values from the user. Node attributes in the graph.
        clavicleCtrl = self.getAttributeByName('clavicleCtrl').getValue()
        swingCtrl = self.getAttributeByName('swingCtrl').getValue()
        MirrorSwing = self.getAttributeByName('MirrorSwing').getValue()
        paramNodeName = self.getAttributeByName("paramNode").getValue()

        swingNul, swingMirrorOrt, swingOrt, swingCtrl = control.create(
            name=swingCtrl,
            controlType="square",
            hierarchy=['nul', 'mirror_ort', 'ort'])
        clavicleNul, clavicleOrt, clavicleCtrl = control.create(
            name=clavicleCtrl, controlType="square", hierarchy=['nul', 'ort'])

        # position the clavicle in the correct location
        clavicleJointMatrix = mc.xform(self._clavicleJoint,
                                       q=True,
                                       ws=True,
                                       matrix=True)
        mc.xform(clavicleNul, ws=True, matrix=clavicleJointMatrix)

        # get the aim direction
        aimDistance = mc.getAttr("{}.t".format(self.jointList[1]))[0]
        aimAttr, aimVector = self._getDistanceVector(aimDistance)
        sidePos = mc.xform(self.jointList[1], q=True, ws=True, t=True)

        # set the Ort node to be mirrored from the other side
        if sidePos[0] < 0:
            mc.setAttr("{}.r{}".format(clavicleOrt, aimAttr.strip("-")), 180)
            mc.setAttr("{}.s{}".format(clavicleOrt, aimAttr.strip("-")), -1)

            # mirror the swing also if it is required by the build
            if MirrorSwing:
                mc.setAttr("{}.r{}".format(swingMirrorOrt, aimAttr.strip("-")),
                           180)
                mc.setAttr("{}.s{}".format(swingMirrorOrt, aimAttr.strip("-")),
                           -1)

        # move the shoulderSwing control to the correct location.
        shoulderCtrlMatrix = mc.xform(self._fkControls[0],
                                      q=True,
                                      ws=True,
                                      matrix=True)
        mc.xform(swingNul, ws=True, matrix=shoulderCtrlMatrix)

        # Hookup clavicle connect nul, the direct connection for the rotate allow keeps the auto
        # clav from causint a double rotation on the shoulder
        clavicleConnect = mc.duplicate(clavicleCtrl,
                                       po=1,
                                       n=clavicleCtrl + '_connect')[0]
        rigrepo.libs.control.untagAsControl(clavicleConnect)
        mc.parent(clavicleConnect, clavicleNul)
        mc.connectAttr(clavicleCtrl + '.r', clavicleConnect + '.r')
        mc.connectAttr(clavicleCtrl + '.s', clavicleConnect + '.s')

        # This allows the translates to come through with auto clav
        clavicleConnectTranslate = mc.duplicate(swingNul,
                                                po=1,
                                                n=clavicleCtrl +
                                                '_connect_trans')[0]
        mc.parent(clavicleConnectTranslate, clavicleCtrl)
        mc.pointConstraint(clavicleConnectTranslate, clavicleConnect)

        # getting rid of the point constraint for now. Not sure we need it.
        #mc.pointConstraint(clavicleCtrl, self._clavicleJoint)
        mc.orientConstraint(clavicleCtrl, self._clavicleJoint)

        # parent the shoulderSwing control to the clavicle control.
        mc.parent((self._fkControls[0], self._stretchTargetJointList[0]),
                  swingCtrl)
        ikJointList = self.ikfkSystem.getIkJointList()
        mc.parentConstraint(swingCtrl, ikJointList[0], mo=True)
        mc.parent(swingNul, clavicleConnect)

        # Connect to passed anchor
        #
        anchor = self.getAttributeByName('anchor').getValue()
        if mc.objExists(anchor):
            mc.parent(clavicleNul, anchor)
        else:
            # parent the clavicle to the group of this part.
            mc.parent(clavicleNul, self.name)
            mc.warning('Anchor object [ {} ] does not exist.'.format(anchor))

        # set the rotate order for the shoulder control
        #mc.setAttr("{}.rotateOrder".format(self._fkControls[0]), 0)
        # set the rotate order for the swing control
        #mc.setAttr("{}.rotateOrder".format(swingCtrl), 0)
        #self._fkControls.extend([clavicleCtrl,swingCtrl])

        # PSD driver - transform that picks up the auto clav and anim control rotation
        clavicleDriverPar = mc.duplicate(clavicleConnect,
                                         po=1,
                                         n=clavicleCtrl + '_driver_par')[0]
        clavicleDriver = mc.duplicate(clavicleConnect,
                                      po=1,
                                      n=clavicleCtrl + '_driver')[0]
        rigrepo.libs.control.untagAsControl(clavicleDriverPar)
        rigrepo.libs.control.untagAsControl(clavicleDriver)

        # make the node we can aim the wrist pv driver at for pv space switching to follow hand.
        clavicleDuplicate = mc.duplicate(clavicleNul,
                                         po=True,
                                         rr=True,
                                         name=clavicleNul.replace(
                                             "_nul", "_pvSpaceAim"))[0]
        self._pvSpaceAimNode = clavicleDuplicate

        # add the swing control to the string attribute for switching fk controls
        '''
コード例 #60
0
import maya.cmds as mc

#simple version up texture files
old_v = '009'
v = '010'

sel = mc.ls(sl = True)
for each in sel:
    x = mc.getAttr(each+'.fileTextureName')
    new_x = x.replace(old_v,v)
    mc.setAttr(each+'.fileTextureName',new_x,typ = 'string')
    
 
import maya.cmds as mc

def os_mergeGroups():
    sel = mc.ls(sl = True)
    for each in sel:
        c = mc.listRelatives(each,c = True, ad = True, type = 'transform')
        geoArr = []
        for child in c:
            if '_geo' in child:
                geoArr.append(child)
        
        print each+' : '+str(len(geoArr))
        if len(geoArr) == 1:
            mc.parent(geoArr[0], w=True)
        else:
            mc.polyUnite (each, ch = 0, mergeUVSets = 1, centerPivot = True, name = each)

os_mergeGroups()