def createPreferredAngleRepresentation(self,joint,scaleTarget, childOfOrientationControl=False): paRepresentationFile = os.environ['RIGGING_TOOL_ROOT'] + '/ControlObjects/Blueprint/preferredAngle_representation.ma' cmds.file(paRepresentationFile, i=True) container = cmds.rename('preferredAngle_representation_container', joint + '_preferredAngle_representation_container') utils.addNodeToContainer(self.containerName, container) for node in cmds.container(container, q=True, nodeList=True): cmds.rename(node, joint + '_' + node, ignoreShape=True) control = joint + '_preferredAngle_representation' controlName = utils.stripAllNamespaces(control)[1] cmds.container(self.containerName,edit=True, publishAndBind=[container + '.axis' , controlName + '_axis']) controlGroup = cmds.group(control, n=joint + '_preferredAngle_parentConstraintGrp',absolute=True) containedNodes = [controlGroup] cmds.parent(controlGroup, self.preferredAngleRepresentationGrp, absolute=True) containedNodes.append(cmds.parentConstraint(joint, controlGroup, maintainOffset=False)[0]) if childOfOrientationControl: rotateXGrp = cmds.group(control, n=control + '_rotateX_grp', absolute=True) orientationControl = self.getOrientationControl(joint) cmds.connectAttr(orientationControl + '.rotateX', rotateXGrp + '.rotateX') containedNodes.append(rotateXGrp) containedNodes.append(cmds.scaleConstraint(scaleTarget, controlGroup, maintainOffset=False)[0]) utils.addNodeToContainer(container, containedNodes) return control
def setupIconScale(self, animationModuleNamespace): clusterNodes = cmds.cluster(self.controlObject, n=self.controlObject + "_icon_scale_cluster", relative=True) cmds.container(animationModuleNamespace + ":module_container", edit=True, addNode=clusterNodes, ihb=True, includeNetwork=True) clusterHandle = clusterNodes[1] cmds.setAttr(clusterHandle + ".scalePivotX", 0) cmds.setAttr(clusterHandle + ".scalePivotY", 0) cmds.setAttr(clusterHandle + ".scalePivotZ", 0) cmds.connectAttr(animationModuleNamespace + ":module_grp.iconScale", clusterHandle + ".scaleX") cmds.connectAttr(animationModuleNamespace + ":module_grp.iconScale", clusterHandle + ".scaleY") cmds.connectAttr(animationModuleNamespace + ":module_grp.iconScale", clusterHandle + ".scaleZ") cmds.parent(clusterHandle, self.controlObject, absolute=True) cmds.setAttr(clusterHandle + ".visibility", 0)
def createSingleOrientationControlAtJoint(self,joint): controlFile = os.environ['RIGGING_TOOL_ROOT'] + '/ControlObjects/Blueprint/singleJointOrientation_control.ma' cmds.file(controlFile, i=True) container = cmds.rename('singleJointOrientation_control_container', joint + '_singleJointOrientation_control_container') utils.addNodeToContainer(self.containerName, container) for node in cmds.container(container, q=True, nodeList=True): cmds.rename(node, joint + '_' + node, ignoreShape=True) control = joint + '_singleJointOrientation_control' cmds.parent(control, self.moduleTransform, absolute=True) translationControl = self.getTranslationControl(joint) pointConstraint = cmds.pointConstraint(translationControl, control, maintainOffset=False, n=control + '_pointConstraint')[0] utils.addNodeToContainer(self.containerName, pointConstraint) jointOrient = cmds.xform(joint, q=True, worldSpace=True, rotation=True) cmds.xform(control, worldSpace=True, absolute=True, rotation=jointOrient) jointNameWithoutNamespace = utils.stripLeadingNamespace(joint)[1] attrName = jointNameWithoutNamespace + '_R' cmds.container(container, edit=True, publishAndBind=[control+'.rotate', attrName]) cmds.container(self.containerName, edit=True, publishAndBind=[container + '.' + attrName, attrName]) return control
def add_node_to_container(container, nodesIn, ihb=False, includeShapes=False, force=False): import types nodes = [] if type(nodesIn) is types.ListType: nodes = list(nodesIn) else: nodes = [nodesIn] conversion_nodes = [] for node in nodes: node_conversion_nodes = cmds.listConnections(node, source=True, destination=True) node_conversion_nodes = cmds.ls(node_conversion_nodes, type="unitConversion") conversion_nodes.extend(node_conversion_nodes) nodes.extend(conversion_nodes) cmds.container(container, edit=True, addNode=nodes, ihb=ihb, includeShapes=includeShapes, force=force)
def publishModuleContainerNamesToOuterContainers(self): if self.moduleContainer == None: return characterContainer = self.characterNamespaceOnly + ":character_container" blueprintContainer = self.blueprintNamespace + ":module_container" for publishedName in self.publishedNames: outerPublishedNames = cmds.container(blueprintContainer, q=True, publishName=True) if publishedName in outerPublishedNames: continue cmds.container(blueprintContainer, edit=True, publishAndBind=[ self.moduleContainer + "." + publishedName, publishedName ]) cmds.container(characterContainer, edit=True, publishAndBind=[ blueprintContainer + "." + publishedName, publishedName ])
def zeroTransform(node,sufix='__ZTR'): if len(mc.ls(sl=True)) == 2: #get the parent of the node parentNode=mc.listRelatives(node,p=1) zeroTransform=mc.createNode('transform',n=node.split('__')[0]+sufix) mc.parent(zeroTransform,node) mc.xform(zeroTransform,t=[0,0,0],ro=[0,0,0],s=[1,1,1],sh=[0,0,0]) mc.parent(zeroTransform,parentNode) if mc.listRelatives(node,p=1)!=None else mc.parent(zeroTransform,w=1) mc.parent(node,zeroTransform) #check if the node is in a container and add if so, the zero to it container=mc.container(q=1,fc=node) if container: mc.container(container,e=1,an=zeroTransform) return zeroTransform for obj in mc.ls(sl=1): zeroTransform(obj) else: print 'Porfavor selecciona primero un mesh y luego una curva para usar de control'
def create_trans_ctrl_at_joint(self,joint): pos_ctrl_file = os.environ["mlrig_tool"]+"/controlobjects/blueprint/translation_control.ma" cmds.file(pos_ctrl_file, i=True) container = cmds.rename("translation_control_container", joint+"_translation_control_container") utils.add_node_to_container(self.container_name, container) for node in cmds.container(container, q=True, nodeList=True): cmds.rename(node, joint+"_"+node, ignoreShape=True) control = joint+"_translation_control" cmds.parent(control, self.module_trans, absolute=True) joint_pos = cmds.xform(joint, q=True, worldSpace=True, translation=True) cmds.xform(control, worldSpace=True, absolute=True, translation=joint_pos) nice_name = utils.strip_leading_namespace(joint)[1] attr_name = nice_name+"_T" cmds.container(container, edit=True, publishAndBind=[control+".translate", attr_name]) cmds.container(self.container_name, edit=True, publishAndBind=[container+"."+attr_name, attr_name]) return control
def rigPost(self): # Store root group as container asset cmds.container( self.container, edit=True, f= True, addNode= self.rootGrp, includeNetwork=True, includeHierarchyBelow= True) #set blueprint to 1 in container and class self.storeVariable("rig", "bu", "short", 1) # load connections data and connect stuff up! self.rigVar = 1
def doIt( self, argList ): """Creates forest instances from a scene object.""" argsLen = argList.length() if argsLen >= 4: SpeedTreeForest = argList.asString(0) partCloudShape = argList.asString(1) tree = argList.asString(2) setIndex = argList.asInt(3) if argsLen == 5: instancerPrefix = argList.asString(4) else: instancerPrefix = partCloudShape[:-5] instancerName = instancerPrefix + '_Instancer' treeShape = '' partInstancer = '' SpeedTreeAsset = '' treePlug = mc.connectionInfo( SpeedTreeForest + '.forestObjects[' + str( setIndex ) + ']', sfd=1 ) if tree != '': if mc.nodeType( tree ) != None: treeShapes = mc.listRelatives( tree, s=1 ) if treeShapes != None and len( treeShapes ) > 0: treeShape = treeShapes[0] supportedTreeTypes = [ 'transform', 'mesh', 'nurbsSurface', 'nurbsCurve', 'subdiv' ] assignForestObject = False #remove existing object if there is one cons = mc.listConnections( partCloudShape ) if ( cons != None and len( cons ) > 0 and mc.objExists( cons[0] ) and mc.nodeType( cons[0] ) == 'instancer' and mc.nodeType( treeShape ) != 'particle' ): if treePlug != '': oldObj = mel.eval( "instancer -index 0 -q -obj " + cons[0] ) if oldObj != '': mc.particleInstancer( partCloudShape, n=cons[0], edit=True, obj=oldObj, rm=True ) partInstancer = mc.particleInstancer( partCloudShape, n=cons[0], edit=True, obj=tree, a=True ) assignForestObject = True elif mc.nodeType( tree ) in supportedTreeTypes and mc.nodeType( treeShape ) != 'particle': partInstancer = mc.particleInstancer( partCloudShape, n=instancerName, obj=tree, a=True, lod='geometry', p='position', r='rotationPP', sc='UserVector1PP' ) useBBs = mc.getAttr( SpeedTreeForest + ".bb" ) mc.setAttr( partInstancer + '.lod', useBBs ) assignForestObject = True if assignForestObject: if treePlug != '': mc.disconnectAttr( treePlug, SpeedTreeForest + '.forestObjects[' + str( setIndex ) + ']' ) mc.setAttr( treePlug.split( '.' )[0] + '.visibility', 1 ) mc.connectAttr( tree + '.message', SpeedTreeForest + '.forestObjects[' + str( setIndex ) + ']' ) #create asset if MayaVersion >= 2009: SpeedTreeAsset = mc.container( q=True, findContainer=[ partCloudShape ] ) if partInstancer != '' and SpeedTreeAsset != None and SpeedTreeAsset != '': mc.container( SpeedTreeAsset, edit=True, addNode=partInstancer, force=True )
def create_translation_control_at_joint(self, joint): pos_control_file = os.environ[ "RIGMAROLE"] + "/ControlObjects/Blueprint/translation_control.ma" cmds.file(pos_control_file, i=True) container = cmds.rename("translation_control_container", joint + "_translation_control_container") utils.add_node_to_container(self.container_name, container) for node in cmds.container(container, q=True, nodeList=True): cmds.rename(node, joint + "_" + node, ignoreShape=True) control = joint + "_translation_control" cmds.parent(control, self.module_transform, absolute=True) joint_pos = cmds.xform(joint, q=True, worldSpace=True, translation=True) cmds.xform(control, worldSpace=True, absolute=True, translation=joint_pos) nice_name = utils.strip_leading_namespace(joint)[1] attr_name = nice_name + "_T" cmds.container(container, edit=True, publishAndBind=[control + ".translate", attr_name]) cmds.container(self.container_name, edit=True, publishAndBind=[container + "." + attr_name, attr_name]) return control
def create_orientation_control(self, parent_joint, child_joint): self.delete_hierarchy_representation(parent_joint) nodes = self.create_stretchy_object( "/ControlObjects/Blueprint/orientation_control.ma", "orientation_control_container", "orientation_control", parent_joint, child_joint) orientation_container = nodes[0] orientation_control = nodes[1] constrained_grp = nodes[2] cmds.parent(constrained_grp, self.orientation_controls_grp, relative=True) parent_joint_without_namespace = utils.strip_all_namespaces( parent_joint)[1] attr_name = parent_joint_without_namespace + "_orientation" cmds.container( orientation_container, edit=True, publishAndBind=[orientation_control + ".rotateX", attr_name]) cmds.container(self.container_name, edit=True, publishAndBind=[ orientation_container + "." + attr_name, attr_name ]) return orientation_control
def install_custom(self, joints): cmds.select(clear=True) ikJoints=[] if not self.mirrored: index=0 for joint in self.jointInfo: ikJoints.append(cmds.joint(n=self.moduleNamespace+":IK_"+joint[0], p=joint[1], absolute=True)) cmds.setAttr(ikJoints[index]+".visibility",0) if index!=0: cmds.joint(ikJoints[index-1],edit=True, oj="xyz", sao="yup") index+=1 else: rootJointName=self.jointInfo[0][0] tempDuplicateNodes=cmds.duplicate(self.originalModule+":IK_"+rootJointName, renameChildren=True) cmds.delete(tempDuplicateNodes.pop()) mirrorXY=False mirrorYZ=False mirrorXZ=False if self.mirrorPlane=="XY": mirrorXY=True elif self.mirrorPlane=="YZ": mirrorYZ=True elif self.mirrorPlane=="XZ": mirrorXZ=True mirrorBehavior=False if self.rotationFunction=="behaviour": mirrorBehaviour=True mirrorJoints=cmds.mirrorJoint(tempDuplicateNodes[0], mirrorXY=mirrorXY, mirrorYZ=mirrorYZ, mirrorXZ=mirrorXZ, mirrorBehavior=mirrorBehavior) cmds.delete(tempDuplicateNodes) cmds.xform(mirrorJoints[0], worldSpace=True, absolute=True, translation=cmds.xform(self.moduleNamespace+":"+rootJointName, q=True, worldSpace=True, translation=True)) for i in range(3): jointName=self.jointInfo[i][0] newName=cmds.rename(mirrorJoints[i], self.moduleNamespace+":IK_"+jointName) ikJoints.append(newName) utils.addNodeToContainer(self.containerName, ikJoints) for joint in ikJoints: jointName=utils.stripAllNamespaces(joint)[1] cmds.container(self.containerName, edit=True, publishAndBind=[joint+".rotate", jointName+"_R"]) cmds.setAttr(ikJoints[0]+".preferredAngleY", -50.0) cmds.setAttr(ikJoints[1]+".preferredAngleY", 50.0) ikNodes=utils.RP_2segment_stretchy_IK(ikJoints[0], ikJoints[1], ikJoints[2], self.containerName) locators=(ikNodes[0], ikNodes[1], ikNodes[2]) distanceNodes=ikNodes[3] constraints=[] for i in range(3): constraints.append(cmds.pointConstraint(self.getTranslationControl(joints[i]), locators[i], maintainOffset=False)[0]) cmds.parent(locators[i],self.moduleNamespace+":module_grp", absolute=True) cmds.setAttr(locators[i]+".visibility",0) utils.addNodeToContainer(self.containerName, constraints) scaleTarget=self.getTranslationControl(joints[1]) paRepresentation=self.createPreferredAngleRepresentation(ikJoints[1], scaleTarget) cmds.setAttr(paRepresentation+".axis",lock=True) #107
def initialiseHook(self, rootTranslationControl): unhookedLocator = cmds.spaceLocator(name=self.moduleNamespace + ':unhookedTarget')[0] #i have made some changes here on my own to rename to parent constraint. the original version #is commented out. #cmds.pointConstraint(rootTranslationControl, unhookedLocator, offset=[0,0.001,0]) parentConstraint =cmds.pointConstraint(rootTranslationControl, unhookedLocator, offset=[0,0.001,0])[0] cmds.rename(parentConstraint, (self.moduleNamespace + ':' + parentConstraint)) cmds.setAttr(unhookedLocator + '.visibility', 0) if self.hookObject == None: self.hookObject = unhookedLocator rootPos = cmds.xform(rootTranslationControl, q=True, worldSpace=True, translation=True) targetPos = cmds.xform(self.hookObject, q=True, worldSpace=True, translation=True) cmds.select(clear=True) rootJointWithoutNamespace = 'hook_root_joint' rootJoint = cmds.joint(n=self.moduleNamespace + ':' + rootJointWithoutNamespace, p=rootPos) cmds.setAttr((rootJoint + '.visibility'), 0) targetJointWithoutNamespace = 'hook_target_joint' targetJoint = cmds.joint(n=self.moduleNamespace + ':' + targetJointWithoutNamespace, p=targetPos) cmds.setAttr((targetJoint + '.visibility'), 0) cmds.joint(rootJoint, edit=True, orientJoint='xyz', sao='yup') hookGroup = cmds.group([rootJoint, unhookedLocator], name=self.moduleNamespace + ':hook_grp', parent=self.moduleGrp) hookContainer = cmds.container(name=self.moduleNamespace + ':hook_container') utils.addNodeToContainer(hookContainer, hookGroup, ihb=True) utils.addNodeToContainer(self.containerName, hookContainer) for joint in [rootJoint, targetJoint]: jointName = utils.stripAllNamespaces(joint)[1] cmds.container(hookContainer, edit=True, publishAndBind=[joint+'.rotate', jointName+'_R']) ikNodes = utils.basic_stretchy_IK(rootJoint, targetJoint, hookContainer, lockMinimumLength=False) ikHandle = ikNodes['ikHandle'] rootLocator = ikNodes['rootLocator'] endLocator = ikNodes['endLocator'] poleVectorLocator = ikNodes['poleVectorObject'] rootPointConstraint = cmds.pointConstraint(rootTranslationControl, rootJoint, maintainOffset=False, n=(rootJoint + '_pointConstraint'))[0] targetPointConstraint = cmds.pointConstraint(self.hookObject, endLocator, maintainOffset=False, n=(self.moduleNamespace + ':hook_pointConstraint'))[0] utils.addNodeToContainer(hookContainer, [rootPointConstraint, targetPointConstraint]) for node in [ikHandle, rootLocator, endLocator, poleVectorLocator]: cmds.parent(node, hookGroup, absolute=True) cmds.setAttr((node + '.visibility'), 0) objectNodes = self.createStretchyObject('/ControlObjects/Blueprint/hook_representation.ma', 'hook_representation_container', 'hook_representation', rootJoint, targetJoint) constrainedGrp = objectNodes[2] cmds.parent(constrainedGrp, hookGroup, absolute=True) hookRepresentationContainer = objectNodes[0] cmds.container(self.containerName, edit=True, removeNode=hookRepresentationContainer) utils.addNodeToContainer(hookContainer, hookRepresentationContainer)
def rotationBakingToLayer(i): cmds.bakeResults( listObjects[i], t = (asT, aeT), sm=True, bol=True, at = "rotate" ) #+ cmds.select( listObjects[i], r=True ) if (cycleInfinity): cmds.setInfinity( pri="cycle", poi="cycle" ) else: cmds.setInfinity( pri="constant", poi="constant" ) cmds.delete( aimLoc, zeroLoc ) #+ cmds.container( "BakeResultsContainer", e=True, rc=True ) cmds.animLayer( "BakeResults", e=True, p = layerName ) cmds.rename( "BakeResults", layerComp ) resetRangeTime()
def install_custom(self, joints): self.setup_interpolation() moduleGrp = self.moduleNamespace+":module_grp" cmds.select(moduleGrp) cmds.addAttr(at="enum", enumName="y:z", longName="sao_local") cmds.addAttr(at="enum", enumName="+x:-x:+y:-y:+z:-z", longName="sao_world") for attr in ["sao_local", "sao_world"]: cmds.container(self.containerName, edit=True, publishAndBind=[moduleGrp+"."+attr, attr])
def install_custom(self,joints): self.setup_interpolation() moduleGrp = self.moduleNamespace + ':module_grp' cmds.select(moduleGrp) cmds.addAttr(at='enum', enumName='y:z', longName='sao_local') cmds.addAttr(at='enum', enumName='+x:-x:+y:-y:+z:-z', longName='sao_world') for attr in ['sao_local','sao_world']: cmds.container(self.containerName,edit=True,publishAndBind=[moduleGrp+'.'+attr,attr])
def createPart(self, *args): contained_nodes = [] # Collect info from the UI to build part userDefinedName = cmds.textField(self.UIElements["name_text"], q=True, text=True) numParts = cmds.intField(self.UIElements["num_text"], q=True, v=True) partRoot = Utils_Part.rigNodeRoot(numParts, userDefinedName) contained_nodes.append(partRoot) parts = Utils_Part.rigNode(userDefinedName, numParts, partRoot) partsLen = len(parts) for p in range(len(parts)): contained_nodes.append(parts[p]) if p < partsLen - 1: partList = (parts[p], parts[p + 1]) partJoint = Utils_Part.createPJoints(partList) for j in partJoint: contained_nodes.append(j) # Set drawing overide on joints cmds.setAttr(j + '.overrideEnabled', 1) cmds.setAttr(j + '.overrideDisplayType', 1) ikHandleName = partJoint[0].replace('pjnt', 'ikh') ikInfo = Utils_Part.scStretchyIk(partList, partJoint, ikHandleName) for i in ikInfo[0]: contained_nodes.append(i) # Connect ikHnadles, parts, and joints ptca = cmds.pointConstraint(partList[0], partJoint[0], mo=True) cmds.connectAttr(partJoint[0] + '.rotate', partList[0] + '.rotateAxis') #cmds.parent(partJoint[0], partList[0]) ptcb = cmds.pointConstraint(partList[1], ikInfo[0][0]) contained_nodes.append(ptca[0]) contained_nodes.append(ptcb[0]) # Cleanup nodes and add to a container. print contained_nodes containerName = (userDefinedName + '_container') con1 = cmds.container(n=containerName) for i in contained_nodes: print i cmds.container(containerName, edit=True, addNode=i, inc=True, ish=True, ihb=True, iha=True)
def publishNameToModuleContainer(self, attribute, attributeNiceName, publishToOuterContainers=True): if self.moduleContainer == None: return blueprintName = utils.stripLeadingNamespace(self.blueprintNamespace)[1].partition("__")[2] attributePrefix = blueprintName + "_" + self.moduleNamespace + "_" publishedName = attributePrefix + attributeNiceName if publishToOuterContainers: self.publishedNames.append(publishedName) cmds.container(self.moduleContainer, edit=True, publishAndBind=[attribute, publishedName])
def setupMesh(self, characterName, setupContainer): projectDirs = turbineUtils.setupDirs(self.characterName, create=False) meshDir = projectDirs[8] characterName = self.characterName #setupContainer = self.setupContainer """ Import the mesh if it exists """ meshName = (meshDir + characterName + ".ma") geoGrp = "Geometry" if cmds.file(meshName, q=True, ex=True): """ Create a group for the mesh """ cmds.file(meshName, i=True, gr=True, gn=geoGrp) cmds.select(geoGrp) """ Add an attribute to the geo group that toggles vis mode. """ enumNames = "normal:template:reference" try: cmds.setAttr("Geometry.overrideEnabled", 1) cmds.container(setupNode, edit=True, publishAndBind=[ "Geometry.overrideDisplayType", "GeoDisplay" ]) except: print 'attribute exists' else: print "mesh does not exist on disk" """ Get the mesh into a var """ if cmds.objExists(geoGrp): characterGeo = cmds.listRelatives(geoGrp, c=True, type="transform") """ Parent the geo to the geo grp """ #for geo in characterGeo: #cmds.parent(geo, geoGrp) """ Unlock the setup container """ cmds.lockNode(setupContainer, lock=False, lockUnpublished=False) """ Add the Geo grp to the setup container """ cmds.container(setupContainer, edit=True, addNode=geoGrp, inc=True, ihb=True, isd=True, includeNetwork=True, force=True) import System.skinning as skinning """ Skin the mesh """ cmds.select(characterGeo) doSkin = skinning.skinning_Tools() doSkin.attachWithSkinning() """ Apply skin weights if they exist """ cmds.select(characterGeo) doSkin.loadSkinWeights(characterName)
def publishNameToModuleContainer(self, attribute, attributeNiceName, publishToOuterContainers=True): if self.moduleContainer == None: return blueprintName = utils.stripLeadingNamespace(self.blueprintNamespace)[1].partition("__")[2] attributePrefix = blueprintName + "_" + self.moduleNamespace + "_" publishedName = attributePrefix + attributeNiceName if publishToOuterContainers: self.publishedNames.append(publishedName) cmds.container(self.moduleContainer, edit = True, publishAndBind=[attribute, publishedName])
def doSkin(self, geometry, gameJoints, geoNode, setupNode): # Set the namespace to the export namespace characterName = turbineUtils.getCharacterInfo()[0] exportName = turbineUtils.getCharacterInfo()[3] cmds.namespace(set=":") # Create a geometry container if cmds.objExists(geoNode): print "Geo node exists" else: geoGrp = cmds.group(n=geoNode, empty=True) cmds.lockNode(setupNode, lock=False, lockUnpublished=False) for geo in geometry: cmds.select(d=True) import maya.mel as mel cmds.select(gameJoints, geo) skinClust = cmds.skinCluster(gameJoints, geo, tsb=True, maximumInfluences=2, omi=True, rui=False, sm=0, normalizeWeights=1, n=geo + "_skinCluster") try: cmds.parent(geo, geoNode) except: pass try: cmds.container(setupNode, edit=True, addNode=geoGrp, inc=True, ihb=True, it=True, ish=True, isd=True) except: pass cmds.lockNode(setupNode, lock=True, lockUnpublished=True) # Set the namespace back to default cmds.namespace(set=":")
def createTransCB(*args): selectionList = cmds.ls(selection=True) if len(selectionList) > 0: cmds.container(type='dagContainer', includeHierarchyBelow=True, includeTransform=True, force=True, addNode=selectionList) else: cmds.container(type='dagContainer', includeHierarchyBelow=True, includeTransform=True, force=True, addNode=[node])
def __init__(self): selectedObjects = cmds.ls(sl=True, transforms=True) filteredGroups = [] for obj in selectedObjects: if obj.find("Group__") == 0: filteredGroups.append(obj) if len(filteredGroups) == 0: return groupContainer = "Group_container" modules = [] for group in filteredGroups: modules.extend(self.findChildModules(group)) moduleContainers = [groupContainer] for module in modules: moduleContainer = module + ":module_container" moduleContainers.append(moduleContainer) for container in moduleContainers: cmds.lockNode(container, lock=False, lockUnpublished=False) for group in filteredGroups: numChildren = len(cmds.listRelatives(group, children=True)) # Ungroup childeren from group if numChildren > 1: cmds.ungroup(group, absolute=True) # Remove attrs from container for attr in ["t", "r", "globalScale"]: cmds.container(groupContainer, edit=True, unbindAndUnpublish=group+"."+attr) parentGroup = cmds.listRelatives(group, parent=True) cmds.delete(group) # This will ensure that if a module is deleted, we do not leave an empty group if parentGroup != None: parentGroup = parentGroup[0] children = cmds. listRelatives(parentGroup, children=True) children = cmds.ls(children, transforms=True) if len(children) == 0: cmds.select(parentGroup, replace=True) UngroupSelected() # Lock containers for container in moduleContainers: if cmds.objExists(container): cmds.lockNode(container, lock=True, lockUnpublished=True)
def publishModuleContainerNamesToOuterContainers(self): if self.moduleContainer == None: return characterContainer = self.characterNamespaceOnly+":character_container" blueprintContainer = self.blueprintNamespace+":module_container" for publishedName in self.publishedNames: outerPublishedNames = cmds.container(blueprintContainer, q=True, publishName=True) if publishedName in outerPublishedNames: continue cmds.container(blueprintContainer, edit=True, publishAndBind=[self.moduleContainer+"."+publishedName, publishedName]) cmds.container(characterContainer, edit=True, publishAndBind=[blueprintContainer+"."+publishedName, publishedName])
def __init__(self): selectedObjects = cmds.ls(selection=True, transforms=True) filteredGroups = [] for obj in selectedObjects: if obj.find('Group__') == 0: filteredGroups.append(obj) if len(filteredGroups) == 0: return groupContainer = 'Group_container' modules = [] for group in filteredGroups: modules.extend(self.findChildModules(group)) moduleContainers = [groupContainer] for module in modules: moduleContainer = (module + ':module_container') moduleContainers.append(moduleContainer) for container in moduleContainers: cmds.lockNode(container, lock=False, lockUnpublished=False) for group in filteredGroups: numberOfChildren = len(cmds.listRelatives(group, children=True)) if numberOfChildren > 1: cmds.ungroup(group, absolute=True) for attr in ['t', 'r', 'globalScale']: cmds.container(groupContainer, edit=True,unbindAndUnpublish=(group + '.' + attr)) parentGroup = cmds.listRelatives(group,parent=True) cmds.delete(group) if parentGroup != None: parentGroup = parentGroup[0] children = cmds.listRelatives(parentGroup, children=True) children = cmds.ls(children, transforms=True) if len(children) == 0: cmds.select(parentGroup, replace=True) UngroupSelected() for container in moduleContainers: if cmds.objExists(container): cmds.lockNode(container, lock=True, lockUnpublished=True)
def findAllNamesPublishedToOuterContainers(self): if self.moduleContainer == None: return [] blueprintContainer = self.blueprintNamespace + ':module_container' modulePublishedNames = cmds.container(self.moduleContainer,q=True, publishName=True) blueprintPublishedNames = cmds.container(blueprintContainer,q=True,publishName=True) returnPublishedNames = [] for name in modulePublishedNames: if name in blueprintPublishedNames: returnPublishedNames.append(name) return returnPublishedNames
def blueprintModule(self, name ,module): """ Run blueprint method for module """ if Util.moduleExists(name): if self.checkMethod( name,"blueprint"): self.Modules[name].blueprint() if module != "Root": cmds.parent(self.Modules[name].rootGrp, self.Modules["root"].groups["modules"]) cmds.container( self.Modules["root"].container, edit=True, an= self.Modules[name].container) else: cmds.error("Blueprint already built for " + name) else: cmds.error("Module "+name+" not found in rig instance")
def createContainer(self, nodeList, name='myFile_udim'): if nodeList != []: containerName = self.uniqName(name) cmds.container(name=containerName, includeShapes=1, includeTransform=1, force=1, addNode=nodeList) for i in cmds.ls(nodeList, type='file'): cmds.container(containerName, e=1, publishAndBind=[ i + ".fileTextureName", "texture_%s" % (i.split('_')[-2]) ])
def mirrorLyt(self, *args): """ Requires the lyt to be mirrored and added to a namespace. """ asset_info = {} if len(cmds.ls(sl=True)) == 0: return sel = cmds.ls(sl=True)[0] if cmds.nodeType(sel) != 'dagContainer': return assetcontents = cmds.container(sel, q=True, nl=True) print sel print assetcontents # Find the Main_GRP for a in assetcontents: if 'Main_GRP' in a: maingrp = a print maingrp mmain = maingrp.replace('L_', 'R_') print mmain # Determine mirror namespace name tv = maingrp.partition(':')[0] mns = tv.replace('L_', 'R_') cmds.namespace(set=':') cmds.namespace(add=mns) cmds.namespace(set=mns) # Duplicate the Main_GRP nodedupe = cmds.duplicate(maingrp, ic=True, rc=True, un=True) mircon = cmds.container(n='FACE_LYT_01_AST') print mmain try: cmds.container(sel, edit=True, rn=mmain, force=True) except: pass cmds.container(mircon, edit=True, an=mmain, f=True) cmds.namespace(set=':') for n in nodedupe: cmds.container(mircon, edit=True, an=n, f=True) cmds.container(mircon, edit=True, an=n, f=True)
def __init__(self, name): # create update variable if module is reloaded get variables from # container self.name = name self.update = 0 self.blueprintVar = 0 self.rigVar = 0 self.connectVar = 0 self.registeredAttributes= [] self.inputs = {} self.outputs = {} self.connections = {} # create default hierarchy for module # if Module already exists use existing objects if Util.checkForExistingObject( (self.name + "_CNT"), "container" ): self.container = (self.name + "_CNT") else: self.container = cmds.container( n= (self.name + "_CNT")) Util.storeString(self.container, "type", "Module") if Util.checkForExistingObject( (self.name + "Root_GRP"), "transform" ): self.rootGrp = (self.name + "Root_GRP") else: self.rootGrp = cmds.group( n = (self.name + "Root_GRP"), em = True ) self.storeInput(self.rootGrp,"root") # class specific init self.initialize()
def k015_check_displink(): k_return=[] k_dxdis=[] k_container = cc.ls(type='container') k_dxs = [a for a in k_container if 'dx11Shader_ast' in a] for k_dx in k_dxs: k_dxfiles=cc.container(k_dx,q=1,nodeList=1) for k_dxfile in k_dxfiles: k_dxtex=cc.nodeType(k_dxfile) if k_dxtex=='displacementShader': k_dxdis.append(k_dxfile) k_lsdisa=cc.ls(type='displacementShader') k_lsdiss=list(set(k_lsdisa).difference(set(k_dxdis))) for k_lsdis in k_lsdiss: k_listdis=cc.listConnections(k_lsdis,type='shadingEngine',d=1) if k_listdis :pass else:k_return.append(k_lsdis) return k_return
def installTemplate(self, templateAndPath, *args): cmds.file(templateAndPath, i=True, namespace="TEMPLATE_1") self.resolveNamespaceClashes("TEMPLATE_1") groupContainer = "TEMPLATE_1:Group_container" if cmds.objExists(groupContainer): self.resolveGroupNameClashes("TEMPLATE_1") cmds.lockNode(groupContainer, lock=False, lockUnpublished=False) oldGroupContainer = "Group_container" if cmds.objExists(oldGroupContainer): cmds.lockNode(oldGroupContainer, lock=False, lockUnpublished=False) nodeList = cmds.container(groupContainer, q=True, nodeList=True) utils.addNodeToContainer(oldGroupContainer, nodeList, force=True) cmds.delete(groupContainer) else: cmds.rename(groupContainer, oldGroupContainer) cmds.lockNode("Group_container", lock=True, lockUnpublished=True) cmds.namespace(setNamespace=":") cmds.namespace(moveNamespace=("TEMPLATE_1",":"), force=True) cmds.namespace(removeNamespace="TEMPLATE_1")
def getLayoutAsset(): layoutasset = [] mirrorlayoutasset = [] # The ls command can be used to find all nodes of a certain type. #assetnodes = cmds.ls(type='container') # The ls command can also be specific to our selection by using the sl flag #assetnodes = cmds.ls(sl=True, type='container') """ In our case we may be selecting a joint and not the asset when we hit the rig arm button. We can find the arm asset using the container command. """ # Start by getting the selection sel = cmds.ls(sl=True)[0] print sel if cmds.nodeType(sel) == 'container': # If the asset is selected, we can check it is an arm if cmds.getAttr('%s.type' % sel) == 'Arm_': layoutasset.append(sel) # If we don't have the asset selected, we need to find it. # Use the nodeList flag to see if our selection is in an asset selast = cmds.container(q=True, fc=sel) # Verify selast isn't None. if selast != None: layoutasset.append(selast) # Now we can check if we have a mirrored layout if "mirror" in cmds.listAttr(layoutasset[0], ud=True): mirrorlayoutasset.append(cmds.getAttr('%s.mirror' % layoutasset[0])) print layoutasset print mirrorlayoutasset return(layoutasset, mirrorlayoutasset)
def getLayoutAsset(): layoutasset = [] mirrorlayoutasset = [] # The ls command can be used to find all nodes of a certain type. #assetnodes = cmds.ls(type='container') # The ls command can also be specific to our selection by using the sl flag #assetnodes = cmds.ls(sl=True, type='container') """ In our case we may be selecting a joint and not the asset when we hit the rig arm button. We can find the arm asset using the container command. """ # Start by getting the selection sel = cmds.ls(sl=True)[0] print sel if cmds.nodeType(sel) == 'container': # If the asset is selected, we can check it is an arm if cmds.getAttr('%s.type' % sel) == 'Arm_': layoutasset.append(sel) # If we don't have the asset selected, we need to find it. # Use the nodeList flag to see if our selection is in an asset selast = cmds.container(q=True, fc=sel) # Verify selast isn't None. if selast != None: layoutasset.append(selast) # Now we can check if we have a mirrored layout if "mirror" in cmds.listAttr(layoutasset[0], ud=True): mirrorlayoutasset.append(cmds.getAttr('%s.mirror' % layoutasset[0])) print layoutasset print mirrorlayoutasset return (layoutasset, mirrorlayoutasset)
def installTemplate(self, templateAndPath, *args): cmds.file(templateAndPath, i=True, namespace='TEMPLATE_1') self.resolveNamespaceClashes('TEMPLATE_1') groupContainer = 'TEMPLATE_1:Group_container' if cmds.objExists(groupContainer): self.resolveGroupNameClashes('TEMPLATE_1') cmds.lockNode(groupContainer, lock=False, lockUnpublished=False) oldGroupContainer ='Group_container' if cmds.objExists(oldGroupContainer): cmds.lockNode(oldGroupContainer, lock=False, lockUnpublished=False) nodeList = cmds.container(groupContainer, q=True, nodeList=True) utils.addNodeToContainer(oldGroupContainer, nodeList, force=True) cmds.delete(groupContainer) else: cmds.rename(groupContainer, oldGroupContainer) cmds.lockNode('Group_container', lock=True, lockUnpublished=True) cmds.namespace(setNamespace=':') cmds.namespace(moveNamespace=('TEMPLATE_1',':'), force=True) cmds.namespace(removeNamespace='TEMPLATE_1')
def getInstalledAnimModules(): modSets = [] characters = utils.findInstalledCharacters() for character in characters: characterContainer = character + ":character_container" blueprintInstances = utils.findInstalledBlueprintInstances(character) for blueprintInstance in blueprintInstances: moduleContainer = character+":"+blueprintInstance+":module_container" #print moduleContainer """ Do we have animation modules installed? """ blueprintJointsGrp = character+":"+blueprintInstance+":blueprint_joints_grp" if cmds.getAttr(blueprintJointsGrp+".controlModulesInstalled"): #print "This is the group holding the blueprint joints that the animation module is installed on """ #print blueprintJointsGrp nodes = cmds.container(moduleContainer, q=True, nl=True) for node in nodes: suffix = ":module_container" result = node.endswith(suffix) if result == True: tmpVar = node.rpartition(":module_container") tmpVar = tmpVar[0].rpartition(":") className = tmpVar[2] modSets.append([blueprintInstance, className]) print (blueprintInstance + " has this anim mod installed " + className) print modSets
def _characterCtrl(charName, mode=0): #Listo todos container del personaje seleccionado charControls = mc.ls('%s:*__STKR' % charName, '%s:*__CNTR' % charName) #recorro los controles y coloco un key for cntr in charControls: if mode == 0: mc.setKeyframe(cntr) if mode == 1: if mc.container(cntr, q=1, pap=1, ba=1): for node in mc.container(cntr, q=1, pap=1, ba=1): if node != '%s:C_facemask_main__ZTR' % charName: _ZeroKey(node) mc.setKeyframe(cntr)
def createBuildPack(attr_dict, name): container = cmds.container(type="dagContainer", ind=("history", "channels"), includeHierarchyBelow=1, includeTransform=1, n=name + "_BuildPack") options_dict = { "float": "cmds.addAttr('{}', ln='{}', at='double', dv=0)".format( container, "--REPLACE--"), "integer": "cmds.addAttr('{}', ln='{}', at='long', dv=0)".format( container, "--REPLACE--"), "boolean": "cmds.addAttr('{}', ln='{}', at='bool')".format( container, "--REPLACE--"), "string": "cmds.addAttr('{}', ln='{}', dt='string')".format( container, "--REPLACE--"), "enum": "cmds.addAttr('{}', ln='{}', at='enum', en='{}')".format( container, "--REPLACE--", "--ENUM--") } for attr in attr_dict: exec(options_dict[attr_dict[attr]].replace("--REPLACE--", attr)) return container
def create_stretchy_obj(self, obj_relative_filepath, obj_container_name, obj_name, parent_joint, child_joint): obj_file = os.environ["mlrig_tool"] + obj_relative_filepath cmds.file(obj_file, i=True) obj_container = cmds.rename(obj_container_name, parent_joint + "_" + obj_container_name) for node in cmds.container(obj_container, q=True, nodeList=True): cmds.rename(node, parent_joint + "_" + node, ignoreShape=True) obj = parent_joint + "_" + obj_name con_grp = cmds.group(empty=True, name=obj + "_parentConstraint_grp") cmds.parent(obj, con_grp, absolute=True) parent_con = cmds.parentConstraint(parent_joint, con_grp, maintainOffset=False)[0] cmds.connectAttr(child_joint + ".translateX", con_grp + ".scaleX") scale_con = cmds.scaleConstraint(self.module_trans, con_grp, skip=["x"], maintainOffset=0)[0] utils.add_node_to_container(obj_container, [con_grp, parent_con, scale_con], ihb=True) utils.add_node_to_container(self.container_name, obj_container) return (obj_container, obj, con_grp)
def create_stretchy_obj(self,obj_relative_filepath,obj_container_name,obj_name,parent_joint,child_joint): obj_file = os.environ["mlrig_tool"]+obj_relative_filepath cmds.file(obj_file, i=True) obj_container = cmds.rename(obj_container_name, parent_joint+"_"+obj_container_name) for node in cmds.container(obj_container, q=True, nodeList=True): cmds.rename(node, parent_joint+"_"+node, ignoreShape=True) obj = parent_joint+"_"+obj_name con_grp = cmds.group(empty=True, name=obj+"_parentConstraint_grp") cmds.parent(obj, con_grp, absolute=True) parent_con = cmds.parentConstraint(parent_joint, con_grp, maintainOffset=False)[0] cmds.connectAttr(child_joint+".translateX", con_grp+".scaleX") scale_con = cmds.scaleConstraint(self.module_trans, con_grp, skip=["x"], maintainOffset=0)[0] utils.add_node_to_container(obj_container, [con_grp, parent_con, scale_con], ihb=True) utils.add_node_to_container(self.container_name, obj_container) return(obj_container, obj, con_grp)
def setupIconScale(self,animationModuleNamespace): clusterNodes = cmds.cluster(self.controlObject, n=self.controlObject + '_icon_scale_cluster', relative=True) cmds.container(animationModuleNamespace + ':module_container',edit=True,addNode=clusterNodes, ihb=True, includeNetwork=True) clusterHandle = clusterNodes[1] cmds.setAttr(clusterHandle + '.scalePivotX',0) cmds.setAttr(clusterHandle + '.scalePivotY',0) cmds.setAttr(clusterHandle + '.scalePivotZ',0) cmds.connectAttr(animationModuleNamespace + ':module_grp.iconScale', clusterHandle + '.scaleX') cmds.connectAttr(animationModuleNamespace + ':module_grp.iconScale', clusterHandle + '.scaleY') cmds.connectAttr(animationModuleNamespace + ':module_grp.iconScale', clusterHandle + '.scaleZ') cmds.parent(clusterHandle,self.controlObject,absolute=True) cmds.setAttr(clusterHandle + '.visibility',0)
def setupMesh(self, characterName, setupContainer): projectDirs = turbineUtils.setupDirs(self.characterName, create=False) meshDir = projectDirs[8] characterName = self.characterName #setupContainer = self.setupContainer """ Import the mesh if it exists """ meshName = (meshDir + characterName + ".ma") geoGrp = "Geometry" if cmds.file(meshName, q=True, ex=True): """ Create a group for the mesh """ cmds.file(meshName, i=True, gr=True, gn=geoGrp) cmds.select(geoGrp) """ Add an attribute to the geo group that toggles vis mode. """ enumNames = "normal:template:reference" try: cmds.setAttr("Geometry.overrideEnabled", 1) cmds.container(setupNode, edit=True, publishAndBind=["Geometry.overrideDisplayType", "GeoDisplay"]) except: print 'attribute exists' else: print "mesh does not exist on disk" """ Get the mesh into a var """ if cmds.objExists(geoGrp): characterGeo = cmds.listRelatives(geoGrp, c=True, type="transform") """ Parent the geo to the geo grp """ #for geo in characterGeo: #cmds.parent(geo, geoGrp) """ Unlock the setup container """ cmds.lockNode(setupContainer, lock=False, lockUnpublished=False) """ Add the Geo grp to the setup container """ cmds.container(setupContainer, edit=True, addNode=geoGrp, inc=True, ihb=True, isd=True, includeNetwork=True, force=True) import System.skinning as skinning """ Skin the mesh """ cmds.select(characterGeo) doSkin = skinning.skinning_Tools() doSkin.attachWithSkinning() """ Apply skin weights if they exist """ cmds.select(characterGeo) doSkin.loadSkinWeights(characterName)
def createGroup(self, groupName): fullGroupName = ('Group__' + groupName) if cmds.objExists(fullGroupName): cmds.confirmDialog(title='Name Conflic', message=('Group \'' + groupName + '\'already exists'), button='Accept', defaultButton='Accept') return None groupTransform = cmds.rename(self.tempGroupTransform, fullGroupName) groupContainer = 'Group_container' if not cmds.objExists(groupContainer): cmds.container(name=groupContainer) containers = [groupContainer] for obj in self.objectsToGroup: if obj.find('Group__') == 0: continue objNamespace = utils.stripLeadingNamespace(obj)[0] containers.append(objNamespace + ':module_container') for c in containers: cmds.lockNode(c,lock=False, lockUnpublished=False) if len(self.objectsToGroup) != 0: tempGroup = cmds.group(self.objectsToGroup, absolute=True) groupParent = cmds.listRelatives(tempGroup, parent=True) if groupParent != None: cmds.parent(groupTransform, groupParent[0], absolute=True) cmds.parent(self.objectsToGroup, groupTransform, absolute=True) cmds.delete(tempGroup) self.addGroupToContainer(groupTransform) for c in containers: cmds.lockNode(c,lock=True, lockUnpublished=True) cmds.setToolTo('moveSuperContext') cmds.select(groupTransform, replace=True) return groupTransform
def publishAttr(attr, assetAttrName=None, bind=True): ''' Publish specified attribute to asset node. @param attr: Contained node attribute to publish to asset. Attribute should be in "node.attr" format. @type attr: str @param assetAttrName: Bound asset attribute name. If None, is generated from node and attribute name (node_attr) @type assetAttrName: str or None @param bind: Bind published asset attribute to specified attribute. @type bind: bool ''' # ========== # - Checks - # ========== # Attribute if not mc.objExists(attr): raise Exception( 'Attribute "' + attr + '" does not exist! Unable to publish attribute to asset...') # Asset Attribute Name if not assetAttrName: assetAttrName = attr.replace('.', '_') # ====================== # - Get Node and Asset - # ====================== node = mc.ls(attr, o=True) containerNode = assetFromNode(node) # ===================== # - Publish Attribute - # ===================== # Publish Attribute (Unbound) mc.container(containerNode, e=True, publishName=assetAttrName) # Bid to Attribute if bind: mc.container(containerNode, e=True, bindAttr=[attr, assetAttrName]) # ================= # - Return Result - # ================= return containerNode + '.' + assetAttrName
def createOrientationControl(self,parentJoint,childJoint): self.deleteHierarchyRepresentation(parentJoint) nodes = self.createStretchyObject('/ControlObjects/Blueprint/orientation_control.ma', 'orientation_control_container','orientation_control',parentJoint,childJoint) orientationContainer = nodes[0] orientationControl = nodes[1] constrainedGrp = nodes[2] cmds.parent(constrainedGrp,self.orientationControlsGrp, relative=True) parentJointWithoutNamespace = utils.stripAllNamespaces(parentJoint)[1] attrName = parentJointWithoutNamespace + '_orientation' cmds.container(orientationContainer, edit=True, publishAndBind=[orientationControl + '.rotateX', attrName]) cmds.container(orientationContainer, edit=True, publishAndBind=[orientationContainer + '.' + attrName, attrName]) return orientationControl
def deleteModule(self, module): """ Deletes module """ moduleContainer = self.Modules[module].container moduleList = cmds.container( (moduleContainer), query= True, nodeList= True ) cmds.delete(moduleList)
def createGroup(self, groupName): fullGroupName = "Group__" + groupName if cmds.objExists(fullGroupName): cmds.confirmDialog(title="Name Conflict", message="Group \"" + groupName + "\" already exists",button="Accept", defaultButton = "Accept") return None groupTransform = cmds.rename(self.tempGroupTransform, fullGroupName) groupContainer = "Group_container" if not cmds.objExists(groupContainer): cmds.container(name=groupContainer) containers = [groupContainer] for obj in self.objectsToGroup: if obj.find("Group__") == 0: continue objNamespace = utils.stripLeadingNamespace(obj)[0] containers.append(objNamespace+":module_container") for c in containers: cmds.lockNode(c, lock=False, lockUnpublished=False) if len(self.objectsToGroup) != 0: tempGroup = cmds.group(self.objectsToGroup, absolute=True) groupParent = cmds.listRelatives( tempGroup, parent=True) if groupParent != None: cmds.parent( groupTransform, groupParent[0], absolute=True) cmds.parent(self.objectsToGroup, groupTransform, absolute=True) cmds.delete(tempGroup) self.addGroupToContainer(groupTransform) for c in containers: cmds.lockNode(c, lock=True, lockUnpublished=True) cmds.setToolTo("moveSuperContext") cmds.select(groupTransform, replace=True) return groupTransform
def create(name, nodes=None, dagContainer=True): """ Create container. @param name: Container name @type name: str @param nodes: List of nodes to add to container @type nodes: list or None @param dagContainer: Create a DAG container or DG container @type dagContainer: bool """ # ========== # - Checks - # ========== # Asset Node if cmds.objExists(name): raise Exception('Object "' + name + '" already exist! Unable to create container...') # Nodes if nodes: for node in nodes: if not cmds.objExists(node): raise Exception( 'Object "' + node + '" does not exist! Unable to add to container...') # ========================== # - Create Asset Container - # ========================== # Create Node if not dagContainer: containerNode = cmds.container(n=name) else: containerNode = cmds.container(n=name, typ='dagContainer') # Add Nodes if nodes: cmds.container(containerNode, e=True, addNode=nodes, f=True) # ================= # - Return Result - # ================= return containerNode
def duplicateBlueprint( moduleName, newName): """ Will duplicate module and load all data from source module onto new module """ groupRoot = moduleName + "Root_GRP" newGroupRoot = newName + "Root_GRP" moduleContainer = moduleName + "_CNT" dupContainer = newName + "_CNT" # Duplicate container duplicated = cmds.duplicate(moduleContainer, name = dupContainer, rc= True) duplicated.remove( dupContainer ) for object in duplicated: StringReplace = object.replace(moduleName, newName) StringReplace = StringReplace[0:(len(StringReplace)-1)] cmds.rename(object, StringReplace) # parent module under new container parentContainer = cmds.container(moduleContainer, query= True, par= True) cmds.container(parentContainer, edit= True, an = dupContainer )
def addNodeToContainer(container, nodesIn, ihb=False , includeShapes=False, force=False): nodes = [] if type(nodesIn) is types.ListType: nodes = list(nodesIn) else: nodes = [nodesIn] conversionNodes = [] for node in nodes: node_conversionNodes = cmds.listConnections(node, source=True, destination=True) node_conversionNodes = cmds.ls(node_conversionNodes, type='unitConversion') conversionNodes.extend(node_conversionNodes) nodes.extend(conversionNodes) cmds.container(container, edit=True, addNode=nodes, ihb=ihb, includeShapes=includeShapes, force=force)
def createPart(self, *args): contained_nodes = [] # Collect info from the UI to build part userDefinedName = cmds.textField(self.UIElements["name_text"], q=True, text=True) numParts = cmds.intField(self.UIElements["num_text"], q=True, v=True) partRoot = Utils_Part.rigNodeRoot(numParts, userDefinedName) contained_nodes.append(partRoot) parts = Utils_Part.rigNode(userDefinedName, numParts, partRoot) partsLen = len(parts) for p in range(len(parts)): contained_nodes.append(parts[p]) if p < partsLen-1: partList = (parts[p], parts[p+1]) partJoint = Utils_Part.createPJoints(partList) for j in partJoint: contained_nodes.append(j) # Set drawing overide on joints cmds.setAttr(j + '.overrideEnabled', 1) cmds.setAttr(j + '.overrideDisplayType', 1) ikHandleName = partJoint[0].replace('pjnt', 'ikh') ikInfo = Utils_Part.scStretchyIk(partList, partJoint, ikHandleName) for i in ikInfo[0]: contained_nodes.append(i) # Connect ikHnadles, parts, and joints ptca =cmds.pointConstraint(partList[0], partJoint[0], mo=True) cmds.connectAttr(partJoint[0] + '.rotate', partList[0] +'.rotateAxis') #cmds.parent(partJoint[0], partList[0]) ptcb = cmds.pointConstraint(partList[1], ikInfo[0][0]) contained_nodes.append(ptca[0]) contained_nodes.append(ptcb[0]) # Cleanup nodes and add to a container. print contained_nodes containerName = (userDefinedName+'_container') con1 = cmds.container(n=containerName) for i in contained_nodes: print i cmds.container(containerName, edit=True, addNode=i, inc=True, ish=True, ihb=True, iha=True)
def install_init(self): cmds.namespace(setNamespace=self.blueprintNamespace) cmds.namespace(add=self.moduleNamespace) cmds.namespace(setNamespace=":") characterContainer = self.characterNamespaceOnly+":character_container" blueprintContainer = self.blueprintNamespace+":module_container" containers = [characterContainer, blueprintContainer] for c in containers: cmds.lockNode(c, lock=False, lockUnpublished=False) # Duplicate creation pose joints to create new instance. Stored in external method. self.joints = self.duplicateAndRenameCreationPose() moduleJointsGrp = self.joints[0] # Group everything for animation module and parent to "Hook_IN_Grp" moduleGrp = cmds.group(empty=True, name=self.blueprintNamespace+":"+self.moduleNamespace+":module_grp") hookIn = self.blueprintNamespace+":HOOK_IN" cmds.parent(moduleGrp, hookIn, relative=True) cmds.parent(moduleJointsGrp, moduleGrp, absolute=True) # Attr to define icon size. cmds.select(moduleGrp) cmds.addAttr(at="float", ln="iconScale", min=0.001, softMaxValue=10.0, defaultValue=1, k=True) cmds.setAttr(moduleGrp+".overrideEnabled", 1) cmds.setAttr(moduleGrp+".overrideColor", 6) utilityNodes = self.setupBlueprintWeightBasedBlending() self.setupModuleVisibility(moduleGrp) containedNodes = list(self.joints) containedNodes.append(moduleGrp) containedNodes.extend(utilityNodes) self.moduleContainer = cmds.container(n=self.moduleContainer) utils.addNodeToContainer(self.moduleContainer, containedNodes, ihb=True) utils.addNodeToContainer(blueprintContainer, self.moduleContainer) #151 index = 0 publishToOuterContainers=False for joint in self.joints: if index > 0: niceJointName = utils.stripAllNamespaces(joint)[1] self.publishNameToModuleContainer(joint+".rotate", niceJointName+"_R", publishToOuterContainers=False) publishToOuterContainers=False index += 1 self.publishNameToModuleContainer(moduleGrp+".lod", "Control_LOD") self.publishNameToModuleContainer(moduleGrp+".iconScale", "Icon_Scale") self.publishNameToModuleContainer(moduleGrp+".overrideColor", "Icon_Color") self.publishNameToModuleContainer(moduleGrp+".visibility", "Vis") self.publishNameToModuleContainer(moduleGrp+".visibility", "Vis", publishToOuterContainers=False) return (self.joints, moduleGrp, self.moduleContainer)
def openCloseContainer(): cntr=str(mc.ls(sl=1)[0]) if cntr: cntr=mc.container( q=1,findContainer=cntr) if mc.getAttr(cntr+'.blackBox')==False: mc.setAttr(cntr+'.blackBox',1) else: mc.setAttr(cntr+'.blackBox',0) else: print 'Selecciona algo'
def publishAttr(attr, assetAttrName=None, bind=True): """ Publish specified attribute to asset node. @param attr: Contained node attribute to publish to asset. Attribute should be in "node.attr" format. @type attr: str @param assetAttrName: Bound asset attribute name. If None, is generated from node and attribute name (node_attr) @type assetAttrName: str or None @param bind: Bind published asset attribute to specified attribute. @type bind: bool """ # ========== # - Checks - # ========== # Attribute if not cmds.objExists(attr): raise Exception('Attribute "' + attr + '" does not exist! Unable to publish attribute to asset...') # Asset Attribute Name if not assetAttrName: assetAttrName = attr.replace('.', '_') # ====================== # - Get Node and Asset - # ====================== node = cmds.ls(attr, o=True) containerNode = assetFromNode(node) # ===================== # - Publish Attribute - # ===================== # Publish Attribute (Unbound) cmds.container(containerNode, e=True, publishName=assetAttrName) # Bid to Attribute if bind: cmds.container(containerNode, e=True, bindAttr=[attr, assetAttrName]) # ================= # - Return Result - # ================= return containerNode + '.' + assetAttrName
def add_file_to_maya(self, file_path, shotgun_data): """ Load file into Maya as an assembly reference """ import pymel.core as pm import maya.cmds as cmds ## Make sure the scene assembly plugins are loaded utils.loadSceneAssemblyPlugins(TankError) # get the slashes right file_path = file_path.replace(os.path.sep, "/") (path, ext) = os.path.splitext(file_path) texture_extensions = [ ".png", ".jpg", ".jpeg", ".exr", ".cin", ".dpx", ".psd", ".tiff", ".tga" ] if ext in [".ma", ".mb"]: # maya file - load it as an assembly reference assemblyDefPath = 'assemblyDef'.join(file_path.split('maya')) assetName = '%s_ARef' % file_path.split('.')[0].split('/')[-1] if not cmds.objExists(assetName): cmds.container(type='assemblyReference', name=assetName) cmds.setAttr('%s.definition' % assetName, assemblyDefPath, type='string') else: cmds.warning( 'Asset %s already exists in scene, try using the sceneBreakdown tool to update instead....' % assetName) elif ext in texture_extensions: # create a file texture read node x = cmds.shadingNode('file', asTexture=True) cmds.setAttr("%s.fileTextureName" % x, file_path, type="string") else: self.parent.log_error( "Unsupported file extension for %s! Nothing will be loaded." % file_path)
def create(name, nodes=None, dagContainer=True): """ Create container. @param name: Container name @type name: str @param nodes: List of nodes to add to container @type nodes: list or None @param dagContainer: Create a DAG container or DG container @type dagContainer: bool """ # ========== # - Checks - # ========== # Asset Node if cmds.objExists(name): raise Exception('Object "' + name + '" already exist! Unable to create container...') # Nodes if nodes: for node in nodes: if not cmds.objExists(node): raise Exception('Object "' + node + '" does not exist! Unable to add to container...') # ========================== # - Create Asset Container - # ========================== # Create Node if not dagContainer: containerNode = cmds.container(n=name) else: containerNode = cmds.container(n=name, typ='dagContainer') # Add Nodes if nodes: cmds.container(containerNode, e=True, addNode=nodes, f=True) # ================= # - Return Result - # ================= return containerNode
def findAllNamesPublishedToOuterContainers(self): # Look at the top node container to find the names of all published attributes if self.moduleContainer == None: return [] blueprintContainer = self.blueprintNamespace + ":module_container" modulePublishedNames = cmds.container(self.moduleContainer, q=True, publishName=True) blueprintPublishedNames = cmds.container(blueprintContainer, q=True, publishName=True) returnPublishedNames = [] for name in modulePublishedNames: if name in blueprintPublishedNames: returnPublishedNames.append(name) return returnPublishedNames