def __init__(self): character = self.findSelectedCharacter() if character == None: return niceName = character.partition('__')[2] result = cmds.confirmDialog(title='Delete Character',message='Are you sure you want to delete the character \'' + niceName + '\'?\nCharacter deletion cannot be undone.',button=['Yes','Cancel'],defaultButton='Yes',cancelButton='Cancel',dismissString='Cancel') if result == 'Cancel': return characterContainer = character + ':character_container' cmds.lockNode(characterContainer, lock=False, lockUnpublished=False) cmds.delete(characterContainer) cmds.namespace(setNamespace=character) blueprintNamespaces = cmds.namespaceInfo(listOnlyNamespaces=True) for blueprintNamespace in blueprintNamespaces: cmds.namespace(setNamespace=':') cmds.namespace(setNamespace=blueprintNamespace) moduleNamespaces = cmds.namespaceInfo(listOnlyNamespaces=True) cmds.namespace(setNamespace=':') if moduleNamespaces != None: for moduleNamespace in moduleNamespaces: cmds.namespace(removeNamespace=moduleNamespace) cmds.namespace(removeNamespace=blueprintNamespace) cmds.namespace(removeNamespace=character)
def create(self, parent_transform, style): """Create shape""" self.parent = parent_transform # Add style curve_data = Style()[style] for curve in curve_data: temp = cmds.curve(name="temp_curve", d=1, p=curve['points'], k=curve['knot']) # Parent curve under transform shapes = cmds.listRelatives(temp, shapes=True) for shape_index, shape in enumerate(shapes): cmds.parent(shape, parent_transform, shape=True, r=True) # Rename shape to be tidy new_shape = cmds.rename(shape, "%s%s" % (self.name, shape_index)) self.nodes.append(new_shape) # Remove temp transform cmds.delete(temp) # Set colors self.set_color(name.get_position(self.parent)) # Match values self.scale_shapes(self.scale) self.rotate_shapes(self.rotate) # Clear selection cmds.select(cl=True)
def moveMirrorPosObj(obj,targetObj): """ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> DESCRIPTION: Attempts to mirror an objects position and rotation ARGUMENTS: obj(string) targetObj(string) RETURNS: Nothin >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> """ objTrans = mc.xform (targetObj, q=True, ws=True, sp=True) actualName = mc.spaceLocator () if objTrans[0] > 0: mc.xform (actualName[0],translation = [-objTrans[0],objTrans[1],objTrans[2]], ws=True) objTrans = mc.xform (actualName[0], q=True, ws=True, sp=True) mc.move (objTrans[0],objTrans[1],objTrans[2], [obj]) else: mc.xform (actualName[0],translation = [objTrans[0],objTrans[1],objTrans[2]], a=True) objTrans = mc.xform (actualName[0], q=True, ws=True, sp=True) mc.move (-objTrans[0],objTrans[1],objTrans[2], [obj]) mc.delete (actualName[0])
def singlePoly(self, arg=None): selObj=self.selection_grab() if selObj: pass else: print "select a polygon object" return if "." in selObj[0]: print "You need to select a polygon object to interogate.(check that you are not in component mode)" return else: pass cmds.select(cl=True) if cmds.objExists("PolyIssues")==True: cmds.delete("PolyIssues") cmds.sets(n="PolyIssues", co=5) cmds.select(selObj) errorFound=cmds.polyInfo(selObj, lf=True, nme=True, nmv=True ) cmds.select (errorFound) cmds.ConvertSelectionToVertices(errorFound) if errorFound>0: print "Polygon error found" cmds.sets( fe='PolyIssues') cmds.select('PolyIssues', r=True, ne=True) cmds.pickWalk(d='Up') errorFound=cmds.ls(sl=True) if (len(errorFound))==0: cmds.delete("PolyIssues")
def mirrorJoints(self, topJoint = '', prefix = ['l_', 'r_']): """ mirroring joint, top node needs to contain 'l_' as prefix """ lPrefix = prefix[0] rPrefix = prefix[1] cmds.select(cl = True) cmds.joint(n = 'temp_jnt') cmds.select(topJoint, r = True) cmds.select('temp_jnt', tgl = True) self.toggleSelect(topJoint, 'temp_jnt') cmds.parent() cmds.select(topJoint, r = True) cmds.mirrorJoint(mirrorYZ = True, mirrorBehavior = True, myz = True, searchReplace = prefix) rJoint = rPrefix + topJoint.split(lPrefix)[-1] cmds.select(topJoint, rJoint) cmds.parent(w = True) cmds.delete('temp_jnt') return rJoint
def create_herd(): # Global herd global herd global herd_target # Reset the old herd if it exists if( len( herd ) ): reset_herd() # Delete then recreate herd target cmds.delete( herd_target.targetName ) herd_target = Target( targetName = "Herd_target", x = -30.0, y = 0.0, z = -30.0 ) # IF the herd is empty if( len( herd ) == 0 ): # Fill the herd - flagging the first as the leader herd.append( Prey( animalName = "Prey_1", initialPosition = Vector3( x = 2.2, y = 0.0, z = 3.28 ), initialHeading = 0, initialSpeed = 0.5, leader = True ) ) herd.append( Prey( animalName = "Prey_2", initialPosition = Vector3( x = 0.0, y = 0.0, z = 0.0 ), initialHeading = 0, initialSpeed = 0.5, leader = False ) ) herd.append( Prey( animalName = "Prey_3", initialPosition = Vector3( x = 3.643, y = 0.0, z = -2.52 ), initialHeading = 0, initialSpeed = 0.5, leader = False ) ) herd.append( Prey( animalName = "Prey_4", initialPosition = Vector3( x = -5.054, y = 0.0, z = -4.208 ), initialHeading = 0, initialSpeed = 0.5, leader = False ) ) herd.append( Prey( animalName = "Prey_5", initialPosition = Vector3( x = 0.0, y = 0.0, z = -9.868 ), initialHeading = 0, initialSpeed = 0.5, leader = False ) ) herd.append( Prey( animalName = "Prey_6", initialPosition = Vector3( x = 5.252, y = 0.0, z = -5.856 ), initialHeading = 0, initialSpeed = 0.5, leader = False ) ) herd.append( Prey( animalName = "Prey_7", initialPosition = Vector3( x = -6.252, y = 0.0, z = 0.0 ), initialHeading = 0, initialSpeed = 0.5, leader = False ) ) herd.append( Prey( animalName = "Prey_8", initialPosition = Vector3( x = -2.132, y = 0.0, z = 2.649 ), initialHeading = 0, initialSpeed = 0.5, leader = False ) ) herd.append( Prey( animalName = "Prey_9", initialPosition = Vector3( x = 0.0, y = 0.0, z = -5.383 ), initialHeading = 0, initialSpeed = 0.5, leader = False ) ) herd.append( Prey( animalName = "Prey_10", initialPosition = Vector3( x = 12.128, y = 0.0, z = 0.0 ), initialHeading = 0, initialSpeed = 0.5, leader = False ) )
def confirmJoints(self): """ draw joints in locator position """ #- Getting Ball and Toe Location self.leftHipPos = cmds.xform('l_hip_Adjust_ctl', q = True, ws = True, t = True) self.leftKneePos = cmds.xform('l_knee_Adjust_ctl', q = True, ws = True, t = True) self.leftAnklePos = cmds.xform('l_ankle_Adjust_ctl', q = True, ws = True, t = True) self.leftBallPos = cmds.xform('l_ball_Adjust_ctl', q = True, ws = True, t = True) self.leftToePos = cmds.xform('l_toe_Adjust_ctl', q = True, ws = True, t = True) self.leftHeelPos = cmds.xform('l_heel_PivotPosition', q = True, ws = True, t = True) self.leftSideInPos = cmds.xform('l_sidein_PivotPosition', q = True, ws = True, t = True) self.leftSideOutPos = cmds.xform('l_sideout_PivotPosition', q = True, ws = True, t = True) #duplicate pivots cmds.duplicate('l_heel_PivotPosition', n = 'r_heel_PivotPosition', rr = True) cmds.xform('r_heel_PivotPosition', t = [-self.leftHeelPos[0], self.leftHeelPos[1], self.leftHeelPos[2]]) cmds.duplicate('l_sidein_PivotPosition', n = 'r_sidein_PivotPosition', rr = True) cmds.xform('r_sidein_PivotPosition', t = [-self.leftSideInPos[0], self.leftSideInPos[1], self.leftSideInPos[2]]) cmds.duplicate('l_sideout_PivotPosition', n = 'r_sideout_PivotPosition', rr = True) cmds.xform('r_sideout_PivotPosition', t = [-self.leftSideOutPos[0], self.leftSideOutPos[1], self.leftSideOutPos[2]]) cmds.select(cl = True) print 'leg Parts : ' , self.legParts for elem in self.legElement : jointPos = cmds.xform(self.left + elem + '_Adjust_ctl', t = True, q = True, ws = True) cmds.joint(n = '%s%s_jnt' %(self.left, elem), p = jointPos) #- orient joint cmds.joint(self.lHipJnt, e = True, oj = 'xzy', secondaryAxisOrient = 'yup', ch = True, zso = True) #- delete position locators cmds.delete(self.legParts)
def mirror_chain(self, side = None): #create one temporary joint at the origin tmp_jnt = cmds.joint(position = [0, 0, 0]) #parent the chain to that joint cmds.parent(self.ik_joint_names[0], tmp_jnt) #mirror the chain and rename the mirrored side if side == 'L': self.mirrored_ik_joint_names = cmds.mirrorJoint(self.ik_joint_names[0], mirrorYZ = 1, mirrorBehavior = 1, searchReplace = (side, 'R')) elif side == 'l': self.mirrored_ik_joint_names = cmds.mirrorJoint(self.ik_joint_names[0], mirrorYZ = 1, mirrorBehavior = 1, searchReplace = (side, 'r')) elif side == 'R': self.mirrored_ik_joint_names = cmds.mirrorJoint(self.ik_joint_names[0], mirrorYZ = 1, mirrorBehavior = 1, searchReplace = (side, 'L')) elif side == 'r': self.mirrored_ik_joint_names = cmds.mirrorJoint(self.ik_joint_names[0], mirrorYZ = 1, mirrorBehavior = 1, searchReplace = (side, 'l')) else: self.mirrored_ik_joint_names = cmds.mirrorJoint(self.ik_joint_names[0], mirrorYZ = 1, mirrorBehavior = 1) #unparent the chain and delete the temporary joint cmds.parent(self.ik_joint_names[0], self.mirrored_ik_joint_names[0], world = 1) cmds.delete(tmp_jnt) cmds.select(clear = 1) #rename the side of the mirrored effector correctly and store the ik and effector in a list mirrored_ik = self.mirrored_ik_joint_names[0][0] + self.ik_handle_names[-1][1:] mirrored_eff = cmds.rename(self.mirrored_ik_joint_names[-1], self.mirrored_ik_joint_names[0][0] + self.ik_handle_names[-1][1:]) self.mirrored_ik_handle_names = [mirrored_ik, mirrored_eff] self.mirrored_ik_joint_names.pop(-1)
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)
def isoparmCoord(surfaceSkin,influence,controlPoints,coord,direction='u'): ''' Set the target coordinates for the specified control points to lie along a given isoparm @param surfaceSkin: surfaceSkin node to apply the coordinates to @type surfaceSkin: str @param influence: surfaceSkin influence to get coordinate for @type influence: str @param controlPoints: List of control points to set the target coordinates for @type controlPoints: list @param coord: Coordinate value of the target isoparm @type coord: float @param direction: Direction of the isoparm @type direction: str ''' # Get surface curve crv = mc.duplicateCurve(influence+'.'+direction+'['+str(coord)+']',ch=False,rn=0,local=0,n=influence+'TEMP_CRV')[0] # Iterate through control point list for controlPoint in controlPoints: # Get component position pos = mc.pointPosition(controlPoint) # Get closest point on curve cCoord = glTools.utils.curve.closestPoint(crv,pos) # Apply Coord uvCoord = (0,0) if direction == 'u': uvCoord = (coord,cCoord) else: uvCoord = (cCoord,coord) applyCoord(surfaceSkin,influence,controlPoint,uvCoord) # Delete surface curve mc.delete(crv)
def mirror_chain(self, side = None): #create one temporary joint at the origin tmp_jnt = cmds.joint(position = [0, 0, 0]) #parent the chain to that joint cmds.parent(self.fk_joint_names[0], tmp_jnt) #mirror the chain and rename the mirrored side if side == 'L': self.mirrored_fk_joint_names = cmds.mirrorJoint(self.fk_joint_names[0], mirrorYZ = 1, mirrorBehavior = 1, searchReplace = (side, 'R')) elif side == 'l': self.mirrored_fk_joint_names = cmds.mirrorJoint(self.fk_joint_names[0], mirrorYZ = 1, mirrorBehavior = 1, searchReplace = (side, 'r')) elif side == 'R': self.mirrored_fk_joint_names = cmds.mirrorJoint(self.fk_joint_names[0], mirrorYZ = 1, mirrorBehavior = 1, searchReplace = (side, 'L')) elif side == 'r': self.mirrored_fk_joint_names = cmds.mirrorJoint(self.fk_joint_names[0], mirrorYZ = 1, mirrorBehavior = 1, searchReplace = (side, 'l')) else: self.mirrored_fk_joint_names = cmds.mirrorJoint(self.fk_joint_names[0], mirrorYZ = 1, mirrorBehavior = 1) #unparent the chain and delete the temporary joint cmds.parent(self.fk_joint_names[0], self.mirrored_fk_joint_names[0], world = 1) cmds.delete(tmp_jnt) cmds.select(clear = 1) return self.mirrored_fk_joint_names
def doRemoveABC(self) : title = 'Remove test abc' abcNodes = mc.ls(type = 'AlembicNode') if abcNodes : mc.delete(abcNodes) self.setStatus(title, True)
def cleanClashingElements(self, origRenderElements, newRenderElements): for newElement in newRenderElements: if clashNameSpace in newElement: if not newElement.split(clashNameSpace)[-1] in origRenderElements: classingBaseName = newElement.split(clashNameSpace + "_")[-1] cmds.delete(classingBaseName) cmds.rename(newElement, classingBaseName)
def returnClosestPointOnMeshInfoFromPos(pos, mesh): """ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> DESCRIPTION: Returns pertinent info of the closest point of a mesh to a position in space - position, normal, parameterU,parameterV,closestFaceIndex,closestVertexIndex ARGUMENTS: pos(string) mesh(string) RETURNS: closestPointInfo(dict) Keys: position normal parameterU parameterV closestFaceIndex closestVertexIndex >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> """ """ make the closest point node """ closestPointNode = mc.createNode ('closestPointOnMesh') controlSurface = mc.listRelatives(mesh,shapes=True) """ to account for target objects in heirarchies """ locBuffer = mc.spaceLocator() mc.move (pos[0],pos[1],pos[2], locBuffer[0]) pointInfo = returnClosestPointOnMeshInfo(locBuffer[0],mesh) mc.delete(locBuffer[0],closestPointNode) return pointInfo
def returnClosestPointOnMeshInfo(targetObj, mesh): """ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> DESCRIPTION: Returns pertinent info of the closest point of a mesh to a target object - position, normal, parameterU,parameterV,closestFaceIndex,closestVertexIndex ARGUMENTS: targetObj(string) mesh(string) RETURNS: closestPointInfo(dict) >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> """ """ make the closest point node """ closestPointNode = mc.createNode ('closestPointOnMesh') controlSurface = mc.listRelatives(mesh,shapes=True) """ to account for target objects in heirarchies """ attributes.doConnectAttr((targetObj+'.translate'),(closestPointNode+'.inPosition')) attributes.doConnectAttr((controlSurface[0]+'.worldMesh'),(closestPointNode+'.inMesh')) attributes.doConnectAttr((controlSurface[0]+'.matrix'),(closestPointNode+'.inputMatrix')) pointInfo = {} pointInfo['position']=attributes.doGetAttr(closestPointNode,'position') pointInfo['normal']=attributes.doGetAttr(closestPointNode,'normal') pointInfo['parameterU']=mc.getAttr(closestPointNode+'.parameterU') pointInfo['parameterV']=mc.getAttr(closestPointNode+'.parameterV') pointInfo['closestFaceIndex']=mc.getAttr(closestPointNode+'.closestFaceIndex') pointInfo['closestVertexIndex']=mc.getAttr(closestPointNode+'.closestVertexIndex') mc.delete(closestPointNode) return pointInfo
def addJoint(side='L'): if mc.objExists('%s_armPalm_bnd_0'%side):return # make joint and locators Joint = mc.createNode('joint', name='%s_armPalm_bnd_0'%side) JointGroup = mc.group(Joint, name='%s_armPalm_bndgrp_0'%side) FKloc = mc.spaceLocator(p=(0,0,0), name='%s_armPalmFK_loc_0'%side)[0] IKloc = mc.spaceLocator(p=(0,0,0), name='%s_armPalmIK_loc_0'%side)[0] # constraint constraintNode = mc.parentConstraint(FKloc, IKloc, JointGroup) # match position mc.delete(mc.parentConstraint('%s_armMiddleAIK_jnt_0'%side, FKloc)) mc.delete(mc.parentConstraint('%s_armMiddleAIK_jnt_0'%side, IKloc)) # parent locator mc.parent(FKloc, '%s_armWristFk_jnt_0'%side) mc.parent(IKloc, '%s_armMiddleAIK_jnt_0'%side) # make ikfk switch reverseNode = [x.split('.')[0] for x in mc.connectionInfo('%s_armFkIk_ctl_0.FKIKBlend'%side, dfs=True) if mc.nodeType(x.split('.')[0])=='reverse'][0] mc.connectAttr('%s.outputX'%reverseNode, '%s.%sW0'%(constraintNode[0], FKloc)) mc.connectAttr('%s_armFkIk_ctl_0.FKIKBlend'%side, '%s.%sW1'%(constraintNode[0], IKloc)) # add to bind set mc.sets(Joint, e=True, forceElement='bind_joints_set') # connect jointLayer mc.connectAttr('jointLayer.drawInfo', '%s.drawOverride'%Joint) # parent joint mc.parent(JointGroup, '%s_armBind_org_0'%side)
def returnClosestUV (targetObject,surface): """ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> DESCRIPTION: Pass target object and surface into it and return the closest UV coordinates ARGUMENTS: targetObject(string) surface(string) RETURNS: UV(string) >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> """ """ pass target object and surface into it and return the closest UV coordinates""" UVs = [] """ make the node """ tmpNode = mc.createNode ('closestPointOnSurface') """ to account for target objects in heirarchies """ tmpObj = rigging.locMeObjectStandAlone(targetObject) mc.connectAttr ((tmpObj+'.translate'),(tmpNode+'.inPosition')) mc.connectAttr ((surface+'.worldSpace'),(tmpNode+'.inputSurface')) UVs.append (mc.getAttr (tmpNode+'.u')) UVs.append (mc.getAttr (tmpNode+'.v')) mc.delete (tmpNode) mc.delete (tmpObj) return UVs
def _create_constraints(self, joints, side): """Creates the constraints between the hydraulics pieces. @param joints: the joints @param side: the side @type joints: list @type side: String """ name = joints[0].split('_start_%s' % self.nc.joint)[0] world_up_object = cmds.spaceLocator(n='%s_%s' % (name, self.nc.locator))[0] cmds.setAttr('%s.v' % world_up_object, 0) self.c.snap_a_to_b(world_up_object, joints[0]) ac1 = cmds.aimConstraint(joints[0], joints[-1], mo=False, weight=1, aimVector=(1, 0, 0), upVector=(0, 1, 0), worldUpType='object', worldUpObject=world_up_object)[0] ac2 = cmds.aimConstraint(joints[-1], joints[0], mo=False, weight=1, aimVector=(1, 0, 0), upVector=(0, 1, 0), worldUpType='object', worldUpObject=world_up_object)[0] cmds.delete(ac1, ac2) self._place_world_up_object(world_up_object, joints[0], joints[-1], side) ac1 = cmds.aimConstraint(joints[0], joints[-1], mo=False, weight=1, aimVector=(1, 0, 0), upVector=(0, 1, 0), worldUpType='object', worldUpObject=world_up_object)[0] ac2 = cmds.aimConstraint(joints[-1], joints[0], mo=False, weight=1, aimVector=(1, 0, 0), upVector=(0, 1, 0), worldUpType='object', worldUpObject=world_up_object)[0] if len(joints) == 3: cmds.aimConstraint(joints[-1], joints[1], mo=False, weight=1) cmds.pointConstraint(joints[0], joints[-1], joints[1], mo=False, weight=1) # END if return world_up_object
def removeLayTex(self, argsv): # get shapes of selection: args = cmds.ls(sl=1) shapesInSel = cmds.ls(dag=1,o=1,s=1,sl=1) shapeIndex = 0 for arg in args : # get shading groups from shapes: shadingGrps = cmds.listConnections(shapesInSel[shapeIndex],type='shadingEngine') # get the shaders: shaders = cmds.ls(cmds.listConnections(shadingGrps),materials=1) shader = shaders[0] #print cmds.listRelatives (p=True, arg) layeredTex = cmds.listConnections(shader, type='layeredTexture') layeredTex = layeredTex[0] if (not layeredTex == None): fileTex = cmds.listConnections(layeredTex, type='file') fileTex = fileTex[0] if (not fileTex == None): cmds.delete(layeredTex) print 'Connecting ' + shader + '.color to ' + fileTex + '.outColor' cmds.connectAttr(fileTex+'.outColor', shader+'.color', f=1) else: print ('Object ' + arg + ' does not have a file texture attached, skipping') else: print ('Object ' + arg + ' does not have a layered texture attached, skipping') shapeIndex += 1
def stabilizer (task): camera = Camera() point = cmds.ls (selection = True) if task == 'end': # turn off stab expression = str (cmds.expression ('stabilizator_expression', string = True, query = True)) camera.shape = expression[2:expression.find('#')] cmds.delete ('stabilizator_expression') camera.reset_camera () cmds.button ('button_stabilizer', edit = True, label = 'stabilize', backgroundColor = (0, 0.5, 0), command = 'fstab.stabilizer("start")') else: # start stab if cmds.objExists ('stabilizator_expression'): # stabilizator exists expression = str (cmds.expression ('stabilizator_expression', string = True, query = True)) camera.shape = expression[2:expression.find('#')] cmds.delete ('stabilizator_expression') cmds.select (camera.shape, replace = True) cmds.warning (('>>> STAB WAS TURNED ON. CHECK: ' + camera.shape + ' <<< FOR NONZERO OFFSET VALUES ::..')) else: if cmds.nodeType (point) != 'mesh' and cmds.nodeType (point) != 'transform' and len (point) == 0: # wrong selection cmds.warning ('..:: SELECT SOMETHING TO STABILIZE ::..') else: point = point[0] if point != camera.transform and point != camera.shape and camera.transform != 'empty': # stabilize cmds.setAttr( camera.shape + '.displayResolution', 0) cmds.setAttr( camera.shape + '.displayFilmGate', 0) expression = '//%s#' % camera.shape expression += '\npython "import maya.cmds as cmds";' expression += '\npython "fov_h = cmds.camera (\'%s\', query = True, horizontalFieldOfView = True)";' % camera.shape expression += '\npython "fov_v = cmds.camera (\'%s\', query = True, verticalFieldOfView = True)";' % camera.shape expression += '\npython "aperture_h = cmds.camera (\'%s\', query = True, horizontalFilmAperture = True)";' % camera.shape expression += '\npython "aperture_v = cmds.camera (\'%s\', query = True, verticalFilmAperture = True)";' % camera.shape expression += '\n$pos=`python "fstab.get_normalized_screen_position(\'%s\',\'%s\',fov_h, fov_v,aperture_h,aperture_v)"`;' % (point, camera.transform) expression += '\nsetAttr "%s.horizontalFilmOffset" ($pos[2]);' % camera.shape expression += '\nsetAttr "%s.verticalFilmOffset" ($pos[3]);' % camera.shape # create expression cmds.expression (name = 'stabilizator_expression', string = expression) # update GUI cmds.button ('button_stabilizer', edit = True, label ="deStabilize", backgroundColor = (1, 0, 0), command = 'fstab.stabilizer("end")') else: cmds.warning ('..:: CLICK IN THE PANE WITH THE CAMERA ::..')
def clean_up_scene (self, *args): delete_names = ['ikSystem', 'Turtle', 'xgen', 'xgm'] delete_types = ['mentalray', 'container'] delete_list = [] all_nodes = cmds.ls() # Append all the nodes that specified in deletion_names for node in all_nodes: for node_name in delete_names: if node.startswith(node_name): delete_list.append(node) for node_type in delete_types: if cmds.nodeType(node).startswith(node_type): delete_list.append(node) for node in delete_list: print node do_delete = cmds.confirmDialog( title='Confirm Deletion', message='Do you want to delete nodes listed in the console?', button=['Yes','No'], defaultButton='Yes', cancelButton='No', dismissString='No' ) if do_delete == 'Yes': # Delete node tha in delete_list for node in delete_list: try: cmds.lockNode(node, lock=False) cmds.delete(node) print node, 'Deleted' except: print node, 'Can not be deleted' pass else: print 'Operation canceled.'
def bt_moveObjToCamera(): #Check for hotkey and make if possible bt_checkCtrFHotkey() activePanel = cmds.getPanel(wf=1) if "model" in activePanel: activeCamera = cmds.modelEditor(activePanel,q=1,camera=1) else: cmds.error ('No active panel/camera to frame to') selected = cmds.ls(sl=1) locator = cmds.spaceLocator() cmds.select(activeCamera,add=1) cmds.parent(r=1) cmds.move(0,0,-5,locator,r=1,os=1) location = cmds.xform(q=1,t=1,ws=1) for object in selected: cmds.move(location[0],location[1],location[2],object,ws=1,a=1) #cmds.move(location[0],location[1],location[2],'pCube1',ws=1,a=1) cmds.delete(locator) cmds.select(selected,r=1)
def createJoints(prefix, lytObs, *args): print "CreateJoints" cmds.select(d=True) ik_joints = [] for item in lytObs: """ item[0] will be the joint item[1] will be the position item[2] will be the parent """ newJointName = item[0].replace("lyt_", prefix) cmds.select(d=True) if cmds.objExists(newJointName) == True: cmds.delete(newJointName) jnt = cmds.joint(p=item[1], n=newJointName ) ik_joints.append(jnt) lytLen = len(lytObs) for item in range(len(lytObs)): if item != 0: joint = lytObs[item][0].replace("lyt_", prefix) jointParent = lytObs[item][2].replace("lyt_", prefix) cmds.parent(joint, jointParent) for jnt in ik_joints: cmds.joint(jnt, e=True, oj='xyz', secondaryAxisOrient='yup', ch=True, zso=True) return ik_joints
def combine(self, objs=[], new_name="", keepHistory=0): ''' Combines the geometry and stores the names. This is useful for speeding up the rigs and seperating in a predictible way. @param objs: Mesh objects to combine @type objs: list @param new_name: New name for the combined mesh @type new_name: str @param keepHistory: Maintain history after function has completed @type keepHistory: bool ''' # Check input arguments if not objs: raise Exception('Input list "objs" is not a valid list!') for obj in objs: if not mc.objExists(obj): raise Exception('Object '+obj+' does not exist!') if mc.objExists(new_name): raise Exception('An object of name '+new_name+' already exists! Please choose another name!') # Combine multiple mesh objects to a single mesh new_obj = mc.polyUnite(objs, n=new_name) mc.addAttr( new_obj[0], ln='origNames', dt='string', multi=True) # Recond original names list on new mesh transform for i in range(len(objs)): mc.setAttr( new_obj[0]+'.origNames['+str(i)+']', objs[i], type='string') # Delete history if not keepHistory : mc.delete(new_obj[1]) mc.delete(objs) return new_obj[0]
def surfaceFromNodes(nodes, name='jntsSrf', upAxis=0, doubleEndPoints=False): """ Create a 2-degree nurbs surface from the position of a list of node (generally, the IK controls) @param nodes: controls that will dictate the CV positions @type nodes: list of strings @param name: the name of the surface @type name: str @param upAxis: the direction of the width of the surface @type upAxis: int representing x(0), y(1) or z(2) """ inPos = [0,0,0] outPos = [0,0,0] inPos[upAxis] = -1 outPos[upAxis] = 1 crv1 = curveFromNodes(nodes, doubleEndPoints=doubleEndPoints) crv2 = curveFromNodes(nodes, doubleEndPoints=doubleEndPoints) MC.xform(crv1, t=outPos) MC.xform(crv2, t=inPos) srf = MC.loft(crv1, crv2, u=1, c=0, ch=0, ar=1, d=1, ss=1, rn=0, po=0, rsn=True)[0] srf = MC.rename(srf, name) MC.delete(crv1, crv2) return srf
def _deleteTurtleNodes(*args): pluginName = 'Turtle' dn = cmds.pluginInfo(pluginName,q=True,dn=True) turtleNodes = cmds.ls(type=dn) cmds.lockNode(turtleNodes,l=False) cmds.delete(turtleNodes) return 0
def ShapeInverterCmdold(base=None, corrective=None, name=None): mc.undoInfo(openChunk=True) if not base or not corrective: sel = mc.ls(sl=True) base, corrective = sel shapes = mc.listRelatives(base, children=True, shapes=True) for s in shapes: if mc.getAttr("%s.intermediateObject" % s) and mc.listConnections("%s.worldMesh" % s, source=False): origMesh = s break deformed = mc.polyPlane(ch=False)[0] mc.connectAttr("%s.worldMesh" % origMesh, "%s.inMesh" % deformed) mc.setAttr("%s.intermediateObject" % origMesh, 0) mc.delete(deformed, ch=True) mc.setAttr("%s.intermediateObject" % origMesh, 1) if not name: name = "%s_inverted#" % corrective invertedShape = duplicateMesh(base, name=name) deformer = mc.deformer(invertedShape, type="ShapeInverter")[0] mc.ShapeInverterCmd(baseMesh=base, invertedShape=invertedShape, ShapeInverterdeformer=deformer, origMesh=deformed) # correctiveShape = duplicateMesh(base,name=corrective+"_corrective#") # mc.connectAttr('%s.outMesh' % getShape(correctiveShape), '%s.correctiveMesh' % deformer) # transferMesh(corrective,[correctiveShape]) mc.connectAttr("%s.outMesh" % getShape(corrective), "%s.correctiveMesh" % deformer) mc.setAttr("%s.activate" % deformer, True) mc.delete(deformed) bdingBx = mc.polyEvaluate(corrective, boundingBox=True) xDifVal = bdingBx[0][1] - bdingBx[0][0] # mc.move(xDifVal*1.10,correctiveShape,r=True,moveX=True) mc.move(xDifVal * 2.20, invertedShape, r=True, moveX=True) mc.undoInfo(closeChunk=True) return invertedShape # ,correctiveShape
def locatorOnly(self): sel = cmds.ls(sl=True) # Gives error if more than one object is selected. if len(sel) > 1: cmds.error("Too many objects selected!") # Creates and snaps a locator to object. elif len(sel): tObj = sel[0] tLoc = "{0}_tLoc".format(tObj) LScale = cmds.floatField(LocScale, q=True, v=True) if cmds.objExists(tLoc): cmds.delete(tLoc) cmds.spaceLocator(n="{0}_tLoc".format(tObj)) cmds.scale(LScale, LScale, LScale) cmds.parentConstraint(tObj, tLoc, mo=False) cmds.parentConstraint(tObj, tLoc, rm=True) print LScale # Gives error if no objects are selected. else: cmds.error("No objects selected!")
def transUVHier(rig): args = cmds.ls(sl=True) if rig: #select the target if it is skinned meshes cmds.select(args[1], r=1) #select just the polys cmds.SelectHierarchy() polys = cmds.filterExpand(cmds.ls(sl=1), expand=1, sm=12) for poly in polys: #if the geo has a skinCluster then... melCommand = "findRelatedDeformer(\""+str(poly)+"\")" deformers = mel.eval(melCommand) #print 'for object: ' + poly print deformers if skinClusterDef(deformers): shapes = getShapes(poly) if len(shapes) > 0: if cmds.objExists(shapes[0]+'Orig'): cmds.setAttr(shapes[0]+'Orig.intermediateObject', 0) #transferUvHierarchy( args[0], args[1] ) if rig: for poly in polys: #if the geo has a skinCluster then... melCommand = "findRelatedDeformer(\""+str(poly)+"\")" deformers = mel.eval(melCommand) #print 'for object: ' + poly if skinClusterDef(deformers): shapes = getShapes(poly) cmds.delete(shapes[0]+'Orig', ch=1) cmds.setAttr(shapes[0]+'Orig.intermediateObject', 1)
def orientJoint (objects = [], aim = [1,0,0], up = [0,0,1]): crossVector = getCrossVector(objects[0], objects[1], objects[-1]) for i in range(len(objects)-1): jointParents = cmds.listRelatives(objects[i], p=True) if jointParents: jointParent = jointParents[0] children = cmds.listRelatives(objects[i], c=True, type='transform') tempGrp = cmds.group(objects[i]) cmds.parent(children, tempGrp) cmds.parent(objects[i], world=True) cmds.delete(cmds.aimConstraint(objects[i+1], objects[i], aimVector=aim, upVector=up, worldUpType='vector', worldUpVector = crossVector)) cmds.parent(children, objects[i]) if jointParents: cmds.parent(objects[i], jointParent) cmds.delete(tempGrp) cmds.makeIdentity(objects[0], apply=True, r=True)
def createSpaceSwitching(self, grpHead, ctrlHead, jntIKShoulder, ctrlRootTrans, fkJnts, grpTorsoDNT, *args): # to delete: I might have constrained the head control when I should have used the grpHead # creates the head follow attributes locHeadNeck = "LOC_space_headNeck" locHeadShoulder = "LOC_space_headShoulder" locHeadBody = "LOC_space_headBody" locHeadRoot = "LOC_space_headRoot" headLocArray = [locHeadNeck, locHeadShoulder, locHeadBody, locHeadRoot] for i in range(len(headLocArray)): mc.spaceLocator(p=(0, 0, 0), name=headLocArray[i]) '''headLocArray.append(mc.spaceLocator(p=(0, 0, 0), name="LOC_space_headNeck")[0]) headLocArray.append(mc.spaceLocator(p=(0, 0, 0), name="LOC_space_headShoulder")[0]) headLocArray.append(mc.spaceLocator(p=(0, 0, 0), name="LOC_space_headBody")[0]) headLocArray.append(mc.spaceLocator(p=(0, 0, 0), name="LOC_space_headRoot")[0])''' # moves these to the head for i in range(len(headLocArray)): todelete = mc.pointConstraint(fkJnts[-1], headLocArray[i]) mc.delete(todelete) # parent the head space to their respective parts mc.parent(headLocArray[0], fkJnts[-1]) mc.parent(headLocArray[1], jntIKShoulder) mc.parent(headLocArray[2], grpTorsoDNT) mc.parent(headLocArray[3], ctrlRootTrans) headFollowOrntConstr = mc.orientConstraint(headLocArray, grpHead)[0] headFollowPntConstr = mc.pointConstraint(headLocArray, grpHead)[0] headFollowRot = 'rotationSpace' headFollowTrans = 'translationSpace' mc.addAttr(ctrlHead, longName=headFollowRot, at="enum", enumName="Neck:Shoulders:upperBody:Root", k=True) mc.addAttr(ctrlHead, longName=headFollowTrans, at="enum", enumName="Neck:Shoulders:upperBody:Root", k=True) # grab the last 4 attributes headSpaceFollowOrnt = mc.listAttr(headFollowOrntConstr)[-4:] headSpaceFollowPnt = mc.listAttr(headFollowPntConstr)[-4:] for i in range(len(headSpaceFollowOrnt)): # set the driven key to 1 and the undriven keys to 0 CRU.setDriverDrivenValues(ctrlHead, headFollowRot, headFollowOrntConstr, headSpaceFollowOrnt[i], i, 1) CRU.setDriverDrivenValues(ctrlHead, headFollowTrans, headFollowPntConstr, headSpaceFollowPnt[i], i, 1) for i2 in range(len(headSpaceFollowOrnt)): if i2 != i: # need to have the second to last value be i, not i2 CRU.setDriverDrivenValues(ctrlHead, headFollowRot, headFollowOrntConstr, headSpaceFollowOrnt[i2], i, 0) CRU.setDriverDrivenValues(ctrlHead, headFollowTrans, headFollowPntConstr, headSpaceFollowPnt[i2], i, 0) for i in range(len(headLocArray)): mc.setAttr("{0}.v".format(headLocArray[i]), False) return headLocArray, locHeadShoulder
def buildFKSpine(self): #find the number of spine bones from the skeleton settings spineJoints = self.getSpineJoints() fkControls = [] parent = None for joint in spineJoints: if joint == "spine_01": #add space switcher node to base of spine spaceSwitcherFollow = cmds.group(empty=True, name=joint + "_space_switcher_follow") constraint = cmds.parentConstraint(joint, spaceSwitcherFollow)[0] cmds.delete(constraint) spaceSwitcher = cmds.duplicate(spaceSwitcherFollow, name=joint + "_space_switcher")[0] cmds.parent(spaceSwitcher, spaceSwitcherFollow) #create an empty group in the same space as the joint group = cmds.group(empty=True, name=joint + "_anim_grp") constraint = cmds.parentConstraint(joint, group)[0] cmds.delete(constraint) #create an additional layer of group that has zeroed attrs offsetGroup = cmds.group(empty=True, name=joint + "_anim_offset_grp") constraint = cmds.parentConstraint(joint, offsetGroup)[0] cmds.delete(constraint) cmds.parent(offsetGroup, group) #create a control object in the same space as the joint control = utils.createControl("circle", 45, joint + "_anim") tempDupe = cmds.duplicate(control)[0] constraint = cmds.parentConstraint(joint, control)[0] cmds.delete(constraint) fkControls.append(control) #parent the control object to the group cmds.parent(control, offsetGroup) constraint = cmds.orientConstraint(tempDupe, control, skip=["x", "z"])[0] cmds.delete(constraint) cmds.makeIdentity(control, t=1, r=1, s=1, apply=True) #setup hierarchy if parent != None: cmds.parent(group, parent, absolute=True) else: cmds.parent(group, spaceSwitcher) cmds.parent(spaceSwitcherFollow, "body_anim") #set the parent to be the current spine control parent = control #clean up cmds.delete(tempDupe) for attr in [".v"]: cmds.setAttr(control + attr, lock=True, keyable=False) #set the control's color cmds.setAttr(control + ".overrideEnabled", 1) cmds.setAttr(control + ".overrideColor", 18) return fkControls
def cancel(self, *args): cmds.delete(self.sculptGeo) cmds.setAttr('%s.visibility' % self.skinGeo, True)
def createCorrective(self, mode, *args): '''# remove heads up display cmds.headsUpDisplay('sculptModeDisplay', remove = True)''' '''# off the isolate curPanel = cmds.paneLayout('viewPanes', q = True, pane1= True) cmds.isolateSelect(curPanel, state = False)''' # show skin geometry cmds.setAttr('%s.visibility' % self.skinGeo, True) self.vtxDeltaDic = {} sculptVtxFinVecDic = {} sculptVtxPointDic = {} inverseVtxPosDic = {} # get skin cluster cmds.select(self.skinGeo, r=True) mel.eval('string $selList[] = `ls -sl`;') mel.eval('string $source = $selList[0];') self.skinCluster = mel.eval('findRelatedSkinCluster($source);') # get number of vertex vtxNum = cmds.polyEvaluate(self.skinGeo, v=True) # progress window cmds.progressWindow(title='Creating Corrective Shape', maxValue=vtxNum, status='stand by', isInterruptable=True) # get the delta that between sculpted geometry and skin geometry for i in xrange(vtxNum): if cmds.progressWindow(q=True, isCancelled=True): break cmds.progressWindow(e=True, step=1, status='calculating delta...') sculptVtxPos = cmds.pointPosition('%s.vtx[%d]' % (self.sculptGeo, i), world=True) sculptVtxVec = OpenMaya.MVector(*sculptVtxPos) skinVtxPos = cmds.pointPosition('%s.vtx[%d]' % (self.skinGeo, i), world=True) skinVtxVec = OpenMaya.MVector(*skinVtxPos) delta = sculptVtxVec - skinVtxVec # if vertex didn't move, skip if delta.length() < 0.001: continue self.vtxDeltaDic[i] = delta cmds.progressWindow(e=True, progress=0, status='calculating delta...') # set envelop to 0 about all deformers without skin cluster of skin geometry allConnections = cmds.listHistory(self.skinGeo) for item in allConnections: if cmds.objectType(item) in self.deformerList: cmds.setAttr('%s.envelope' % item, 0) # reset progression window maxValue cmds.progressWindow(e=True, maxValue=len(self.vtxDeltaDic)) # get vertex position that skin cluster plus delta for i in self.vtxDeltaDic.keys(): if cmds.progressWindow(q=True, isCancelled=True): break cmds.progressWindow( e=True, step=1, status='calculating final sculpt vtx position...') skinVtxPos = cmds.pointPosition('%s.vtx[%d]' % (self.skinGeo, i), world=True) skinVtxVec = OpenMaya.MVector(*skinVtxPos) sculptVtxFinVecDic[i] = skinVtxVec + self.vtxDeltaDic[i] sculptVtxPointDic[i] = OpenMaya.MPoint(sculptVtxFinVecDic[i].x, sculptVtxFinVecDic[i].y, sculptVtxFinVecDic[i].z) cmds.progressWindow(e=True, progress=0, status='calculating final sculpt vtx position...') # get inversed vertex position for i in self.vtxDeltaDic.keys(): if cmds.progressWindow(q=True, isCancelled=True): break cmds.progressWindow(e=True, step=1, status='calculating inverse matrix...') # set matrix pallete matrixPallete = OpenMaya.MMatrix() matrixPalletInitList = [ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 ] OpenMaya.MScriptUtil.createMatrixFromList(matrixPalletInitList, matrixPallete) # get influences influenceList = cmds.skinCluster('%s.vtx[%d]' % (self.skinGeo, i), q=True, wi=True) # for each influence get the matrix and multiply inverse matrix for influence in influenceList: infBindMatrixList = cmds.getAttr('%s.bindPose' % influence) infWorldMatrixList = cmds.getAttr('%s.worldMatrix' % influence) infWeight = cmds.skinPercent(self.skinCluster, '%s.vtx[%d]' % (self.skinGeo, i), q=True, transform=influence, v=True) if infWeight == 0.0: continue infBindMatrix = OpenMaya.MMatrix() OpenMaya.MScriptUtil.createMatrixFromList( infBindMatrixList, infBindMatrix) infWorldMatrix = OpenMaya.MMatrix() OpenMaya.MScriptUtil.createMatrixFromList( infWorldMatrixList, infWorldMatrix) matrixPallete += (infBindMatrix.inverse() * infWorldMatrix) * infWeight inverseVtxPosDic[i] = sculptVtxPointDic[i] * matrixPallete.inverse( ) cmds.progressWindow(e=True, progress=0, status='calculating inverse matrix...') # on eidt mode, replace poseName to selTrg if mode == 'editMode': self.poseName = cmds.textScrollList('r_poseTexScrList', q=True, selectItem=True)[0] if mode != 'editMode': # get corrective geometry by duplicating skin geometry with skinCluster envelope 0 cmds.setAttr('%s.envelope' % self.skinCluster, 0) cmds.duplicate(self.skinGeo, n=self.poseName) # delete intermediate shape shapList = cmds.ls(self.poseName, dag=True, s=True) for shap in shapList: if cmds.getAttr('%s.intermediateObject' % (shap)): cmds.delete(shap) # set corrective shape's vertex position if mode != 'editMode': for i in self.vtxDeltaDic.keys(): if cmds.progressWindow(q=True, isCancelled=True): break cmds.progressWindow( e=True, step=1, status='calculating corrective vtx position...') cmds.xform('%s.vtx[%d]' % (self.poseName, i), ws=True, t=(inverseVtxPosDic[i].x, inverseVtxPosDic[i].y, inverseVtxPosDic[i].z)) elif mode == 'editMode': for i in self.vtxDeltaDic.keys(): if cmds.progressWindow(q=True, isCancelled=True): break cmds.progressWindow( e=True, step=1, status='calculating facial target vtx position...') # get vertex position that no assigned deformer cmds.setAttr('%s.envelope' % self.skinCluster, 0) skinVtxPos = cmds.pointPosition('%s.vtx[%d]' % (self.skinGeo, i), world=True) # get modified vertex vector modifiedVtxPos = [(inverseVtxPosDic[i].x - skinVtxPos[0]), (inverseVtxPosDic[i].y - skinVtxPos[1]), (inverseVtxPosDic[i].z - skinVtxPos[2])] # add modified vertex vector to original target vertex vector facialTrgVtxPos = cmds.pointPosition('%s.vtx[%d]' % (self.poseName, i), world=True) finalVtxPos = [(facialTrgVtxPos[0] + modifiedVtxPos[0]), (facialTrgVtxPos[1] + modifiedVtxPos[1]), (facialTrgVtxPos[2] + modifiedVtxPos[2])] # set final vertex position cmds.xform('%s.vtx[%d]' % (self.poseName, i), ws=True, t=finalVtxPos) cmds.progressWindow(endProgress=True) # all deformer's envelope set to 1 of skin geometry cmds.setAttr('%s.envelope' % self.skinCluster, 1) allConnections = cmds.listHistory(self.skinGeo) for item in allConnections: if cmds.objectType(item) in self.deformerList: cmds.setAttr('%s.envelope' % item, 1) # add corrective geometry to geo_grp if mode != 'editMode': corGeoGrpName = self.skinGeo + '_corrective_geo_grp' if cmds.objExists(corGeoGrpName): cmds.parent(self.poseName, corGeoGrpName) cmds.setAttr('%s.visibility' % self.poseName, False) else: cmds.createNode('transform', n=corGeoGrpName) cmds.parent(self.poseName, corGeoGrpName) cmds.setAttr('%s.visibility' % self.poseName, False) # delete sculpt geometry cmds.delete(self.sculptGeo) if mode != 'editMode': # add corrective to blend shape node if cmds.objExists(self.bsName): bsAttrList = cmds.aliasAttr(self.bsName, q=True) weightNumList = [] for bsAttr in bsAttrList: if 'weight' in bsAttr: reObj = re.search(r'\d+', bsAttr) weightNum = reObj.group() weightNumList.append(int(weightNum)) bsIndex = max(weightNumList) + 1 cmds.blendShape(self.bsName, edit=True, target=(self.skinGeo, bsIndex, self.poseName, 1.0)) cmds.setAttr('%s.%s' % (self.bsName, self.poseName), 1) # refresh pose list self.populatePoseList() else: cmds.blendShape(self.poseName, self.skinGeo, n=self.bsName, frontOfChain=True)[0] cmds.setAttr('%s.%s' % (self.bsName, self.poseName), 1) # refresh pose list self.populatePoseList() # get data for pose reader driverJoint = cmds.textFieldButtonGrp('jntTexButGrp', q=True, text=True) parentJoint = cmds.textFieldButtonGrp('prntJointTexBtnGrp', q=True, text=True) locatorJoint = cmds.textFieldButtonGrp('locJointTexBtnGrp', q=True, text=True) # pose reader self.poseReader(driverJoint, parentJoint, locatorJoint, self.poseName) # mirror mirOpt = cmds.checkBox('mirChkBox', q=True, v=True) if mirOpt: # create fliped opposite side geometry flipGeo = self.flipGeo() # add opposite corrective to the blend shape node bsAttrList = cmds.aliasAttr(self.bsName, q=True) weightNumList = [] for bsAttr in bsAttrList: if 'weight' in bsAttr: reObj = re.search(r'\d+', bsAttr) weightNum = reObj.group() weightNumList.append(int(weightNum)) bsIndex = max(weightNumList) + 1 cmds.blendShape(self.bsName, edit=True, target=(self.skinGeo, bsIndex, flipGeo, 1.0)) cmds.setAttr('%s.%s' % (self.bsName, flipGeo), 1) # refresh pose list self.populatePoseList() # get data for opposite side pose reader jntSearchTex = cmds.textFieldGrp('jntSrchTexFld', q=True, text=True) jntReplaceTex = cmds.textFieldGrp('jntRplcTexFld', q=True, text=True) oppoDriverJnt = re.sub(jntSearchTex, jntReplaceTex, driverJoint, 1) oppoParentJnt = re.sub(jntSearchTex, jntReplaceTex, parentJoint) oppolocatorJnt = re.sub(jntSearchTex, jntReplaceTex, locatorJoint, 1) # set opposite side pose srcRo = cmds.getAttr('%s.rotate' % (driverJoint))[0] srcRo = (srcRo[0], -srcRo[1], srcRo[2]) cmds.setAttr('%s.rotate' % (oppoDriverJnt), *srcRo) # create opposite side pose reader self.poseReader(oppoDriverJnt, oppoParentJnt, oppolocatorJnt, flipGeo) self.populatePoseList()
from sgMaya import sgCmds import maya.cmds as cmds import pymel.core sels = cmds.ls(sl=1) for sel in sels: pymelSel = pymel.core.ls(sel)[0] pymelSel.rotatePivot.set(0, 0, 0) pymelSel.scalePivot.set(0, 0, 0) pymelSel.rotatePivotTranslate.set(0, 0, 0) pymelSel.scalePivotTranslate.set(0, 0, 0) cmds.DeleteHistory() pivMtx = sgCmds.getPivotLocalMatrix(sel) worldMtx = sgCmds.listToMatrix(cmds.getAttr(sel + '.wm')) worldPivMtx = pivMtx * worldMtx tempTr = cmds.createNode('transform') cmds.xform(tempTr, ws=1, matrix=sgCmds.matrixToList(worldPivMtx)) sgCmds.setGeometryMatrixToTarget(sel, tempTr) cmds.delete(tempTr) cmds.select(sels) cmds.DeleteHistory()
def fix_invalid(cls, context): """Delete unknown nodes""" from maya import cmds for node in cls.get_invalid(context): cmds.delete(node)
def createEyeControls(self, eyeArray, ctrlHead, ctrlRootTrans, *args): # Create eye control eyeCtrlArray = [] eyeGrpArray = [] eyeRadBase = mc.listRelatives(eyeArray[-1], type="joint")[0] radiusBase = mc.getAttr("{0}.tz".format(eyeRadBase)) for i in range(len(eyeArray)): # takes the eye joints, creates a corresponding locator eyeName = str(eyeArray[i]).replace("JNT_BND_", "") ctrlEye = "CTRL_" + eyeName grpEye = "GRP_" + ctrlEye eyeCtrlArray.append(mc.spaceLocator(p=(0, 0, 0), name=ctrlEye)[0]) mc.setAttr('{0}.overrideEnabled'.format(eyeCtrlArray[i]), 1) if "_l_" in eyeCtrlArray[i]: mc.setAttr("{0}.overrideColor".format(eyeCtrlArray[i]), 14) elif "_r_" in eyeCtrlArray[i]: mc.setAttr("{0}.overrideColor".format(eyeCtrlArray[i]), 13) # groups them at the creation point eyeGrpArray.append(mc.group(ctrlEye, name=grpEye)) # moves the eye into posiiton mc.matchTransform(eyeGrpArray[i], eyeArray[i], pos=True, rot=True) mc.move(radiusBase * 20, eyeGrpArray[i], z=True, r=True, os=True) # Create the eyes control eyesCtrlName = "CTRL_eyes" eyesCtrl = mc.circle(nr=(0, 1, 0), r=radiusBase * 7.5, n=eyesCtrlName, degree=1, sections=4)[0] mc.setAttr("{0}.ry".format(eyesCtrl), 45) mc.makeIdentity(eyesCtrl, a=True) # freeze transform mc.setAttr("{0}.sx".format(eyesCtrl), 1.5) mc.makeIdentity(eyesCtrl, a=True) # freeze transform mc.setAttr("{0}.rx".format(eyesCtrl), 90) mc.makeIdentity(eyesCtrl, a=True) # freeze transform eyesGrp = mc.group(eyesCtrl, n="GRP_" + eyesCtrlName) todelete = mc.pointConstraint(eyeCtrlArray, eyesGrp) mc.delete(todelete) mc.parent(eyeGrpArray, eyesCtrl) mc.parent(eyesGrp, ctrlRootTrans) aimArray = [] for i in range(len(eyeArray)): aimArray.append( mc.aimConstraint(eyeCtrlArray[i], eyeArray[i], aim=[0, 0, 1])) # create the eye follow settings eyesFollowLocArray = [] locFollowHead = "LOC_follow_eyesHead" locFollowRoot = "LOC_follow_eyesRoot" eyesFollowLocArray.append( mc.spaceLocator(p=(0, 0, 0), name=locFollowHead)[0]) eyesFollowLocArray.append( mc.spaceLocator(p=(0, 0, 0), name=locFollowRoot)[0]) # moves the locators into position for i in range(len(eyesFollowLocArray)): todelete = mc.parentConstraint(eyesCtrl, eyesFollowLocArray[i], mo=False) mc.delete(todelete) mc.parent(eyesFollowLocArray[0], ctrlHead) mc.parent(eyesFollowLocArray[-1], ctrlRootTrans) eyesCtrlPrntConst = mc.parentConstraint(eyesFollowLocArray[0], eyesFollowLocArray[1], eyesGrp)[0] eyesFollow = 'eyesFollow' mc.addAttr(eyesCtrl, longName=eyesFollow, at="enum", enumName="head:root", k=True) # The last two attributes would be the relevant head and eye controls eyesFollowVals = mc.listAttr(eyesCtrlPrntConst)[-2:] CRU.setDriverDrivenValues(eyesCtrl, eyesFollow, eyesCtrlPrntConst, eyesFollowVals[0], 0, 1) CRU.setDriverDrivenValues(eyesCtrl, eyesFollow, eyesCtrlPrntConst, eyesFollowVals[0], 1, 0) CRU.setDriverDrivenValues(eyesCtrl, eyesFollow, eyesCtrlPrntConst, eyesFollowVals[1], 0, 0) CRU.setDriverDrivenValues(eyesCtrl, eyesFollow, eyesCtrlPrntConst, eyesFollowVals[1], 1, 1) for i in range(len(eyesFollowLocArray)): # hide the eye locators mc.setAttr("{0}.v".format(eyesFollowLocArray[i]), False) return eyeCtrlArray, eyesCtrl, eyeGrpArray, eyesGrp
def _flattenGlobalCtrlShape(self, ctrlObject): ctrlShapes = cmds.listRelatives(ctrlObject, s = 1, type = 'nurbsCurve') cluster = cmds.cluster(ctrlShapes)[1] # Get cluster handle, [0]: cluster name cmds.setAttr(cluster + '.rz', 90) cmds.delete(ctrlShapes, ch = 1)
def align(self, sourceObjs, targetObj, frames=None, translate=True, rotate=True, showProgress=False, selectSorceObjs=False): if not sourceObjs or not targetObj: return cmds.refresh(suspend=True) currFrame = cmds.currentTime(query=True) constraints = [] setValues = [] modes = [] status = "aTools - Aligning nodes..." if translate: modes.append({"mode": "translate", "constrain": "pointConstraint"}) if rotate: modes.append({"mode": "rotate", "constrain": "orientConstraint"}) if showProgress: utilMod.startProgressBar(status) if not frames: getCurves = animMod.getAnimCurves() animCurves = getCurves[0] getFrom = getCurves[1] if animCurves: keysSel = animMod.getTarget("keysSel", animCurves, getFrom) frames = utilMod.mergeLists(keysSel) if frames == []: frames = [currFrame] else: frames = [currFrame] if showProgress: totalSteps = len(sourceObjs + frames) firstStep = 0 thisStep = 0 estimatedTime = None startChrono = None #get values for thisStep, loopSourceObj in enumerate(sourceObjs): if showProgress: startChrono = utilMod.chronoStart(startChrono, firstStep, thisStep, totalSteps, estimatedTime, status) setValues.append({"modes": [], "values": [], "skips": []}) for loopMode in modes: mode = loopMode["mode"] constrainType = loopMode["constrain"] allAttrs = cmds.listAttr(loopSourceObj, settable=True, keyable=True) skip = [ loopXyz for loopXyz in ["x", "y", "z"] if "%s%s" % (mode, loopXyz.upper()) not in allAttrs ] contrainFn = eval("cmds.%s" % constrainType) with G.aToolsBar.createAToolsNode: constraints.append( contrainFn(targetObj, loopSourceObj, skip=skip)[0]) setValues[-1]["modes"].append(mode) setValues[-1]["values"].append([ cmds.getAttr("%s.%s" % (loopSourceObj, mode), time=loopKey)[0] for loopKey in frames ]) setValues[-1]["skips"].append(skip) if showProgress: estimatedTime = utilMod.chronoEnd(startChrono, firstStep, thisStep, totalSteps) #del constraints for loopConstrain in constraints: cmds.delete(loopConstrain) for n, loopKey in enumerate(frames): if showProgress: thisStep = thisStep + n + 1 startChrono = utilMod.chronoStart(startChrono, firstStep, thisStep, totalSteps, estimatedTime, status) for nn, loopSourceObj in enumerate(sourceObjs): loopSetValue = setValues[nn] values = loopSetValue["values"] skips = loopSetValue["skips"] for nnn, loopMode in enumerate(modes): mode = loopMode["mode"] xyz = [ loopXyz for loopXyz in ["x", "y", "z"] if loopXyz not in skips[nnn] ] for nnnn, loopXyz in enumerate(xyz): attr = "%s%s" % (mode, loopXyz.upper()) value = values[nnn][n][nnnn] if len(frames) > 1: cmds.setKeyframe(loopSourceObj, attribute=attr, time=(loopKey, loopKey), value=value) if currFrame == loopKey: cmds.setAttr("%s.%s" % (loopSourceObj, attr), value) #euler filter if n == len(frames) - 1 and rotate: animCurves = utilMod.mergeLists([ cmds.keyframe(loopSourceObj, query=True, name=True) for loopSourceObj in sourceObjs ]) animMod.eulerFilterCurve(animCurves) if showProgress: estimatedTime = utilMod.chronoEnd(startChrono, firstStep, thisStep, totalSteps) if showProgress: utilMod.setProgressBar(endProgress=True) if selectSorceObjs: cmds.select(sourceObjs) cmds.refresh(suspend=False)
def autoTranfer(self, arg): self.listSel = mc.ls(selection=True) if not mc.objExists('ARLoc_Grp'): mc.group(em=True, name='ARLoc_Grp') self.bakeLoc = [] self.delPar = [] self.delScale = [] self.selList = [] for self.sel in self.listSel: self.locName = self.sel + "_loc" self.loc = mc.spaceLocator(p=(0, 0, 0), name=self.locName) self.parentLoc = mc.parentConstraint(self.sel, self.loc, maintainOffset=False) self.scaleLoc = mc.scaleConstraint(self.sel, self.loc, maintainOffset=False) # self.bakeLoc.append(self.loc[0]) #because loc is list self.delPar.append(self.parentLoc[0]) #because delPar is list self.selList.append(self.sel) #mc.bakeResults(self.loc,simulation=True,time = (self.timeSliderMin,self.timeSliderMax)) #mc.delete(self.parentLoc) #mc.cutKey(self.sel, option='keys') #self.parentCon = mc.parentConstraint(self.loc,self.sel,maintainOffset = True) #self.scaleCon = mc.scaleConstraint(self.loc,self.sel,maintainOffset = True) #mc.parent(self.loc,'ARLoc_Grp') #mc.cutKey(self.loc,time=((self.timeSliderMin+1), (self.timeSliderMax-1)), option='keys') print self.delPar self.animNodes = mc.ls(type='animCurve') self.firstKey = mc.findKeyframe(self.animNodes, which='first') self.lastKey = mc.findKeyframe(self.animNodes, which='last') if self.firstKey < 101: self.firstKey = 101 # isolate viewport for faster baking mayaTools.isolateObj(True) # bake locator mc.bakeResults(self.bakeLoc, simulation=True, time=(self.firstKey, self.lastKey)) # restore viewport back mayaTools.isolateObj(False) mc.delete(self.delPar) mc.delete(self.delScale) mc.cutKey(self.selList, option='keys') #return for self.sel in self.listSel: self.locName = self.sel + "_loc" #mc.cutKey(self.sel, option='keys') self.parentCon = mc.parentConstraint(self.locName, self.sel, maintainOffset=False) #True self.scaleCon = mc.scaleConstraint(self.locName, self.sel, maintainOffset=False) mc.parent(self.locName, 'ARLoc_Grp') for shotSq in mc.sequenceManager(listShots=True): self.currentShotStart = mc.shot(shotSq, q=True, st=True) self.currentShotEnd = mc.shot(shotSq, q=True, et=True) mc.cutKey(self.locName, time=((self.currentShotStart + 1), (self.currentShotEnd - 1)), option='keys')
Cas_IO.Cas_printWarning("No targets are valid for skin binding") Cas_MCW_restoreMisc(undoState,texState) return #print "original = %s" % source #cmds.select (source) #cmds.select (target) # Bind joints to the target objects #delete history on target objects #print source #print target #return cmds.delete(target,ch=1) # now go through each target objects and do bind and copy weight progressRatio = 20.0 / len(target) for node in target: try: cmds.skinCluster(rootjoint,node,mi = 4,omi = 0,) except Exception , msg: warningCount += 1 print "Failed to bind object %s. %s " % (node,msg) cmds.select(source) cmds.select(node,add=1) try: cmds.copySkinWeights(sm=1,noMirror=1,sa = "closestPoint" , ia = ("name", "oneToOne"))
def _adjustMainCtrlShape(self, ctrl, scale, offset): ctrlShapes = cmds.listRelatives(ctrl.ControlObject, s = 1, type = 'nurbsCurve') cluster = cmds.cluster(ctrlShapes)[1] # Get cluster handle, [0]: cluster name cmds.setAttr(cluster + '.ry', 90) cmds.delete(ctrlShapes, ch = 1) cmds.move(scale*offset, ctrl.ControlGroup, moveY = True, relative = True)
def buildRotLimit( baseName ): print('rotLimit__________________ START') grpMain = baseName + '_rotLimit_GRP' grpWorld = baseName + '_toWorld_GRP' grpParent = baseName + '_toCnsParent_GRP' grpChild = baseName + '_toCnsChildren_GRP' limitAreaOrig = baseName + '_limitArea_ORIG' limitArea = baseName + '_limitArea_SURF' grpAim = baseName + '_outValueAim_GRP' valueLocMax = baseName + '_max_LOC' valueLocMin = baseName + '_min_LOC' curveBuildExt = baseName + '_ext_CRV' curveBuildInt = baseName + '_int_CRV' folMax = baseName + '_max_FOL' folMin = baseName + '_min_FOL' arrow = baseName + '_arrow_SURF' posDir = baseName + '_posDir_CRV' arrowOrig = baseName + '_arrow_ORIG' expName = baseName + '_limiteAreaRot_EXP' print('rotLimit__________________ CREATE HIERARCHY') elemsName = [ grpMain , grpWorld , grpParent , grpChild , limitAreaOrig , grpAim , arrowOrig , valueLocMax , valueLocMin ] elemsType = [ 'transform' , 'transform' , 'transform' , 'transform' , 'transform' , 'transform' , 'transform' , 'locator' , 'locator' ] elemsFather = [ '' , grpMain , grpMain , grpMain , grpParent , grpParent , grpChild , grpAim , grpAim ] utilsMaya.createDagNodes( elemsType , elemsName , elemsFather ) print('rotLimit__________________ CREATE CURVES') mc.circle( n = curveBuildExt, c = (0,0,0), nr = (0,1,0), sw = 360, r = 1, d = 3, ut = 0, tol = 0.01, s = 8, ch = 1 ) mc.circle( n = curveBuildInt, c = (0,0,0), nr = (0,1,0), sw = 360, r = 1, d = 3, ut = 0, tol = 0.01, s = 8, ch = 1 ) mc.parent( curveBuildExt , grpWorld ) mc.parent( curveBuildInt , grpWorld ) print('rotLimit__________________ CREATE LIMITE AREA') mc.loft( curveBuildExt, curveBuildInt, n = limitArea, ch = 1, u = 1, c = 0, ar = 1, d = 3, ss = 1, rn = 0, po = 0, rsn = True ) mc.parent( limitArea, limitAreaOrig ) print('rotLimit__________________ CREATE ARROW') curvesTmp = [ 'buildRotLimitTMP1_CRV' , 'buildRotLimitTMP2_CRV' ] mc.curve( n = curvesTmp[0], d = 1, p = ( ( 0, 0, 0 ) , ( 0.25, 0, 0.13 ) ) , k = (0,1) ) mc.curve( n = curvesTmp[1], d = 1, p = ( ( 0, 0, 0 ) , ( 0.25, 0, -0.13 ) ) , k = (0,1) ) mc.loft( curvesTmp[0], curvesTmp[1], n = arrow, ch = 1, u = 1, c = 0, ar = 1, d = 3, ss = 1, rn = 0, po = 0, rsn = True ) mc.delete( curvesTmp ) mc.parent( arrow, arrowOrig ) mc.setAttr( arrow + '.tx' , 1 ) print('rotLimit__________________ CREATE FOLLICLE') utilsMaya.buildFollicle( limitArea , n = folMax , u = 1 , v = 0 ) utilsMaya.buildFollicle( limitArea , n = folMin , u = 0 , v = 0 ) mc.parent( folMax , grpWorld ) mc.parent( folMin , grpWorld ) print('rotLimit__________________ CREATE POSDIR') mc.curve( n = posDir , d = 1 , p = ( (0.016,0,0.050) , (-0.016,0,0.050) , (-0.016,0,0.016) , (-0.050,0,0.016) , ( -0.050,0,-0.016 ) , ( -0.016,0,-0.016 ) , ( -0.016,0,-0.050 ) , ( 0.016,0,-0.050 ) , ( 0.016,0,-0.016 ) , ( 0.050,0,-0.016 ) , ( 0.050,0,0.016 ) , ( 0.016,0,0.016 ) , ( 0.016,0,0.050 ) , ( 0.016,0,0.050 ) ) , k = ( 0,1,2,3,4,5,6,7,8,9,10,11,12,13 ) ) mc.setAttr( posDir + '.tx' , -0.5 ) mc.parent( posDir , folMax ) print('rotLimit__________________ LIMITE AREA ATTR') attrToHide = [ 'translateX' , 'translateY' , 'translateZ' , 'rotateX' , 'rotateZ' , 'scaleX' , 'scaleY' , 'scaleZ' , 'visibility' ] for attr in attrToHide: mc.setAttr( limitArea + '.' + attr , cb = False , l = True , k = False ) attrNames = [ 'areaSize' , 'EXTRA_ATTR', 'overrideMode', 'max' , 'min' , 'LIMIT_OUT' , 'maxOut' , 'minOut' , 'VISU' , 'extShape' , 'intShape' , 'arrowSize' ] attrTypes = [ 'float1Pos' , 'separator' , 'intOnOff' , 'float1' , 'float1' , 'separator' , 'floatRead' , 'floatRead' , 'separator' , 'float1Pos' , 'float1Pos' , 'float1Pos' ] attrValues = [ 0 , None , 0 , 0 , 0 , None , 0 , 0 , None , 1.1 , 0.9 , 1 ] objs = [ limitArea for i in range( 0 , len(attrNames) ) ] utilsMaya.addSpecialAttrs( objs , attrNames , attrTypes , attrValues = attrValues ) print('rotLimit__________________ MAKE CONNECTIONS') mc.connectAttr( valueLocMax + '.rotateY' , limitArea + '.maxOut' ) mc.connectAttr( valueLocMin + '.rotateY' , limitArea + '.minOut' ) mc.connectAttr( limitArea + '.extShape' , curveBuildExt + '.scaleX' ) mc.connectAttr( limitArea + '.extShape' , curveBuildExt + '.scaleY' ) mc.connectAttr( limitArea + '.extShape' , curveBuildExt + '.scaleZ' ) mc.connectAttr( limitArea + '.intShape' , curveBuildInt + '.scaleX' ) mc.connectAttr( limitArea + '.intShape' , curveBuildInt + '.scaleY' ) mc.connectAttr( limitArea + '.intShape' , curveBuildInt + '.scaleZ' ) mc.connectAttr( limitArea + '.extShape' , arrowOrig + '.scaleX' ) mc.connectAttr( limitArea + '.extShape' , arrowOrig + '.scaleY' ) mc.connectAttr( limitArea + '.extShape' , arrowOrig + '.scaleZ' ) mc.connectAttr( limitArea + '.arrowSize' , arrow + '.scaleX' ) mc.connectAttr( limitArea + '.arrowSize' , arrow + '.scaleY' ) mc.connectAttr( limitArea + '.arrowSize' , arrow + '.scaleZ' ) print('rotLimit__________________ MAKE EXRPESSIONS') curveBuildExtShape = mc.listRelatives( curveBuildExt, s = True, c = True ) curveBuildExtMakeNode = mc.listConnections( curveBuildExtShape[0] + '.create' , s = True , d = False , ) curveBuildIntShape = mc.listRelatives( curveBuildInt, s = True, c = True ) curveBuildIntMakeNode = mc.listConnections( curveBuildIntShape[0] + '.create' , s = True , d = False , ) exp = '' exp += '\n' + 'float $limitAreaRotCompensateOffset = -90;' exp += '\n' + '//_____________________________________________________________INS' exp += '\n' + 'int $overrideMode = {0}.overrideMode;'.format( limitArea ) exp += '\n' + 'float $max = {0}.max; '.format( limitArea ) exp += '\n' + 'float $min = {0}.min; '.format( limitArea ) exp += '\n' + 'float $limitAreaRot = {0}.rotateY; '.format( limitArea ) exp += '\n' + 'float $limitAreaSize = {0}.areaSize;'.format( limitArea ) exp += '\n' + '//_____________________________________________________________COMPUTE' exp += '\n' + '' exp += '\n' + 'float $limitAreaRotCompensate = $limitAreaSize / 2 * -1 + $limitAreaRotCompensateOffset;' exp += '\n' + 'float $limitAreaFatherRot = 0;' exp += '\n' + '' exp += '\n' + 'if( $overrideMode == 1 )' exp += '\n' + '{ ' exp += '\n' + ' $limitAreaSize = abs( $max - $min ); ' exp += '\n' + ' $limitAreaRotCompensate = $min + $limitAreaRotCompensateOffset; ' exp += '\n' + ' $limitAreaFatherRot = $limitAreaRot * -1; ' exp += '\n' + '}' exp += '\n' + '//_____________________________________________________________OUTS' exp += '\n' + '{0}.sweep = clamp( 0.01 , 99999999 , $limitAreaSize);'.format( curveBuildExtMakeNode[0] ) exp += '\n' + '{0}.sweep = clamp( 0.01 , 99999999 , $limitAreaSize);'.format( curveBuildIntMakeNode[0] ) exp += '\n' + '{0}.rotateY = $limitAreaRotCompensate;'.format( curveBuildExt ) exp += '\n' + '{0}.rotateY = $limitAreaRotCompensate;'.format( curveBuildInt ) exp += '\n' + '{0}.rotateY = $limitAreaFatherRot;'.format( limitAreaOrig ) utilsMaya.buildSimpleExpression( expName , exp ) print('rotLimit__________________ MAKE CONSTRAINTS') mc.aimConstraint( folMax , valueLocMax , mo = True , aimVector = (0,0,-1), upVector = (0,1,0), worldUpType = "vector", worldUpVector = (0,1,0) ) mc.aimConstraint( folMin , valueLocMin , mo = True , aimVector = (0,0,1), upVector = (0,1,0), worldUpType = "vector", worldUpVector = (0,1,0) ) print('rotLimit__________________ SET DEFAUT VALUE') mc.setAttr( limitArea + '.areaSize' , 360 ) mc.setAttr( limitArea + '.rotateY' , 0 ) mc.setAttr( limitArea + '.max' , 180 ) mc.setAttr( limitArea + '.min' , -180 ) print('rotLimit__________________ CLEAN') mc.setAttr( grpWorld + '.visibility' , 0 ) mc.setAttr( grpAim + '.visibility' , 0 ) mc.setAttr( arrow + '.overrideEnabled' , 1 ) mc.setAttr( arrow + '.overrideDisplayType' , 2 ) mc.setAttr( posDir + '.overrideEnabled' , 1 ) mc.setAttr( posDir + '.overrideDisplayType' , 2 ) print('rotLimit__________________ END') return [ grpMain , grpParent , grpChild ]
#这是一个定位骨骼控制器的小插件 #先选骨骼,再加选控制器的组,执行代码即可定位控制器 import maya.cmds as mc selected = mc.ls(sl=1) mc.delete(mc.parentConstraint(selected[0], selected[1], mo=False))
def create_softmod(name, face): # create plane for follicle plane = cmds.polyPlane(name=name + '_foll_GEO') cmds.setAttr(plane[1] + '.sw', 1) cmds.setAttr(plane[1] + '.sh', 1) cmds.setAttr(plane[0] + '.s', .01, .01, .01) cmds.delete(plane[0], ch=True) cmds.makeIdentity(plane[0], apply=True) # move plane to face vertices = component.face_to_vertex([face]) pos_vtx_list = [] for each in vertices: pos = cmds.xform(each, t=True, ws=True, q=True) pos = (pos[0], pos[1], pos[2]) pos_vtx_list.append(pos) mtx = math.plane_matrix(vertices) cmds.xform(plane[0], matrix=mtx) # create follicle plane_geo = cmds.listRelatives(plane[0], s=True)[0] transform = cmds.createNode('transform', name=name + '_foll') foll = cmds.createNode('follicle', name=name + '_follShape', parent=transform) cmds.connectAttr(foll + ".outTranslate", transform + ".t", force=True) cmds.connectAttr(foll + ".outRotate", transform + ".r", force=True) cmds.setAttr(foll + ".visibility", False) cmds.connectAttr(plane_geo + '.outMesh', foll + '.inputMesh') cmds.connectAttr(plane_geo + '.worldMatrix[0]', foll + '.inputWorldMatrix') cmds.setAttr(foll + '.parameterU', 0.5) cmds.setAttr(foll + '.parameterV', 0.5) # copy skin weights to plane geo = face.split('.')[0] try: skin.copy_skincluster(geo, [plane_geo]) except: constraint.simple_constraint(geo, plane[0], snap=False) # create controls soft_mod_ctrl = ctrls.diamond_shape(name + '_SOFT_CTRL') soft_mod_ctrl_pivot = ctrls.sphere_shape(name + '_SOFT_PIV_CTRL') soft_mod_ctrl_pivot_zero = cmds.createNode('transform', name=soft_mod_ctrl_pivot + '_ZERO') cmds.setAttr(soft_mod_ctrl + '.s', 0.4, 0.4, 0.4) cmds.makeIdentity(soft_mod_ctrl, apply=True) cmds.addAttr(soft_mod_ctrl, ln='falloff', at='double', min=0, keyable=True) cmds.addAttr(soft_mod_ctrl, ln='falloffMode', at='enum', en='volume:surface', keyable=True) cmds.parent(soft_mod_ctrl, soft_mod_ctrl_pivot) cmds.parent(soft_mod_ctrl_pivot, soft_mod_ctrl_pivot_zero) constraint.simple_constraint(transform, soft_mod_ctrl_pivot_zero, snap=True) # create soft mod sm = cluster.create(geo, name + '_softMod', soft=True) constraint.simple_constraint(soft_mod_ctrl_pivot, sm[0], snap=True) constraint.simple_constraint(soft_mod_ctrl, sm[1], snap=True) cmds.connectAttr(soft_mod_ctrl + '.falloff', sm[1] + '.falloff') cmds.connectAttr(soft_mod_ctrl + '.falloffMode', sm[1] + '.falloffMode')
#randomCubes.py import maya.cmds as cmds import random random.seed(1234) cubeList = cmds.ls('myCube*') if len(cubeList) > 0: cmds.delete(cubeList) result = cmds.polyCube(w=1, h=1, d=1, name='myCube#') transformName = result[0] instanceGroupName = cmds.group(empty=True, name=transformName + '_instance_grp#') for i in range(0, 50): instanceResult = cmds.instance(transformName, name=transformName + '_instnace#') cmds.parent(instanceResult, instanceGroupName) # print 'instanceResult:' + str( instnaceResult ) x = random.uniform(-10, 10) y = random.uniform(0, 20) z = random.uniform(-10, 10) cmds.move(x, y, z, instanceResult)
def buildCoreComponents(self): #builds the master, the root, and the core rig groups #MASTER CONTROL masterControl = utils.createControl("circle", 150, "master_anim") constraint = cmds.pointConstraint("root", masterControl)[0] cmds.delete(constraint) cmds.makeIdentity(masterControl, apply = True) cmds.setAttr(masterControl + ".overrideEnabled", 1) cmds.setAttr(masterControl + ".overrideColor", 18) spaceSwitchFollow = cmds.group(empty = True, name = masterControl + "_space_switcher_follow") constraint = cmds.parentConstraint("root", spaceSwitchFollow)[0] cmds.delete(constraint) spaceSwitcher = cmds.group(empty = True, name = masterControl + "_space_switcher") constraint = cmds.parentConstraint("root", spaceSwitcher)[0] cmds.delete(constraint) cmds.parent(spaceSwitcher, spaceSwitchFollow) cmds.parent(masterControl, spaceSwitcher) cmds.makeIdentity(masterControl, apply = True) #OFFSET CONTROL offsetControl = utils.createControl("square", 140, "offset_anim") constraint = cmds.pointConstraint("root", offsetControl)[0] cmds.delete(constraint) cmds.parent(offsetControl, masterControl) cmds.makeIdentity(offsetControl, apply = True) cmds.setAttr(offsetControl + ".overrideEnabled", 1) cmds.setAttr(offsetControl + ".overrideColor", 17) #ROOT ANIM rootControl = utils.createControl("sphere", 10, "root_anim") constraint = cmds.parentConstraint("driver_root", rootControl)[0] cmds.delete(constraint) cmds.parent(rootControl, masterControl) cmds.makeIdentity(rootControl, apply = True) cmds.parentConstraint(rootControl, "driver_root") cmds.setAttr(rootControl + ".overrideEnabled", 1) cmds.setAttr(rootControl + ".overrideColor", 30) for attr in [".sx", ".sy", ".sz", ".v"]: cmds.setAttr(masterControl + attr, lock = True, keyable = False) cmds.setAttr(offsetControl + attr, lock = True, keyable = False) cmds.setAttr(rootControl + attr, lock = True, keyable = False) #Create the group that will hold all of the control rig components rigGrp = cmds.group(empty = True, name = "ctrl_rig") cmds.parent(rigGrp, "offset_anim") #finish grouping everything under 1 character grp controlRigGrp = cmds.group(empty = True, name = "rig_grp") cmds.parent(["driver_root", "master_anim_space_switcher_follow"], controlRigGrp) cmds.parent("Rig_Settings", controlRigGrp) if cmds.objExists("Proxy_Geo_Skin_Grp"): cmds.parent("Proxy_Geo_Skin_Grp", controlRigGrp) returnNodes = [rigGrp, offsetControl] return returnNodes
def parent(shape, parent, deleteShapeTransform=False, force=False): ''' Parent shape nodes to a destination parent @param shape: Shape or transform to parent @type shape: str @param parent: Destination parent transform @type parent: str @param deleteShapeTransform: Delete shape transform parent, only if transform has no descendants. @type deleteShapeTransform: bool ''' # Checks if not mc.objExists(shape): raise Exception('Object "' + shape + '" does not exist!!') if not mc.objExists(parent): raise Exception('Object "' + parent + '" does not exist!!') # Get shapes shapes = [] if mc.ls(shape, type='transform'): transform = shape shapes = mc.listRelatives(shape, s=True, pa=True) else: transform = mc.listRelatives(shape, p=True, pa=True)[0] shapes = [shape] # Match parent transform mc.parent(transform, parent) mc.makeIdentity(transform, apply=True, t=True, r=True, s=True) mc.parent(transform, w=True) # Parent shapes for i in range(len(shapes)): # Parent Shape to Target Transform shapeList = mc.parent(shapes[i], parent, s=True, r=True) shapes[i] = shapeList[0] # Get Shape Type shapeType = mc.objectType(shapes[i]) # Temporarily rename shapes, so hash index (#) is accurate shapes[i] = mc.rename(shapes[i], parent + 'ShapeTMP') # Rename Shapes if shapeType == 'nurbsCurve': shapes[i] = mc.rename(shapes[i], parent + 'CrvShape#') elif shapeType == 'nurbsSurface': shapes[i] = mc.rename(shapes[i], parent + 'SrfShape#') elif shapeType == 'mesh': shapes[i] = mc.rename(shapes[i], parent + 'MeshShape#') else: shapes[i] = mc.rename(shapes[i], parent + 'Shape#') # Delete Old Shape Transform if deleteShapeTransform: # Check remaining descendants if mc.listRelatives(transform, ad=True): if not force: print( 'Unable to delete transform "' + transform + '"! Object has remaining descendants. Use force=True to force deletion.' ) deleteShapeTransform = False else: print( 'Transform "' + transform + '" has remaining descendants, deleting anyway! (force=True)' ) # Check outgoing connections if mc.listConnections(transform, s=False, d=True): if not force: print( 'Unable to delete transform "' + transform + '"! Object has outgoing connections. Use force=True to force deletion.' ) deleteShapeTransform = False else: print( 'Transform "' + transform + '" has outgoing conections, deleting anyway! (force=True)') # Delete Transform if deleteShapeTransform: mc.delete(transform) # Return Result return shapes
def createDriverCrv (self, upLidBaseCrv, upRigGrp, lowLidBaseCrv, lowRigGrp): '''Create a driver curve for each lid curve and connect it to the base curve with a wire deformer. Called by 'buildRig' function. Call functions: 'eyelidsCorners', 'eyeLidsLeftAndRight' (unused), 'eyelidsCrvCVs', 'eyelidsMatchTopology' ''' ## Upper eyelid ## upLidDriverCrvTEMP = cmds.duplicate (upLidBaseCrv) [0] cmds.delete (upLidDriverCrvTEMP, ch = 1) # delete history cmds.rebuildCurve (upLidDriverCrvTEMP, rpo = 1, end = 1, kr = 2, kcp = 0, kep = 1, kt = 0, s = 4, d = 7, tol = 0.01) # list the position of the EPs of the upper lid driver curve upLidEpPosTEMP = [] x = 0 while x < 5 : posEp = cmds.xform ((upLidDriverCrvTEMP + ".ep[%d]" % x), q = 1, ws = 1, t = 1) upLidEpPosTEMP.append (posEp) x += 1 cmds.delete (upLidDriverCrvTEMP) # Create the upLid 'guide' curve for corner placement and query CVs positions and indexes upLidGuideCrv = cmds.curve (d = 3, ep = (upLidEpPosTEMP[0], upLidEpPosTEMP[1], upLidEpPosTEMP[2], upLidEpPosTEMP[3], upLidEpPosTEMP[4])) ## Lower eyelid ## lowLidDriverCrvTEMP = cmds.duplicate (lowLidBaseCrv) [0] cmds.delete (lowLidDriverCrvTEMP, ch = 1) # delete history cmds.rebuildCurve (lowLidDriverCrvTEMP, rpo = 1, end = 1, kr = 2, kcp = 0, kep = 1, kt = 0, s = 4, d = 7, tol = 0.01) # list the position of the EPs of the lower lid driver curve lowLidEpPosTEMP = [] x = 0 while x < 5 : posEp = cmds.xform ((lowLidDriverCrvTEMP + ".ep[%d]" % x), q = 1, ws = 1, t = 1) lowLidEpPosTEMP.append (posEp) x += 1 cmds.delete (lowLidDriverCrvTEMP) # Create the lowLid 'guide' curve for corner placement and query CVs positions and indexes lowLidGuideCrv = cmds.curve (d = 3, ep = (lowLidEpPosTEMP[0], lowLidEpPosTEMP[1], lowLidEpPosTEMP[2], lowLidEpPosTEMP[3], lowLidEpPosTEMP[4])) ## # Find position of eye corners self.cornerAPos, self.cornerBPos = self.eyelidsCorners (upLidEpPosTEMP, upLidGuideCrv, lowLidEpPosTEMP, lowLidGuideCrv) # Define "CornerA" and "CornerB" as "leftCorner" and "rightCorner" # ADD FUNC WHEN OK - self.eyeLidsLeftAndRight (self.cornerAPos, self.cornerBPos) # List CVs positions of upLidGuideCrv and lowLidGuideCrv upLidCVsPos, lowLidCVsPos = self.eyelidsCrvCVs (upLidGuideCrv, lowLidGuideCrv) # List CVs positions in the right order (to match topology) upLidCVsOrdered, lowLidCVsOrdered = self.eyelidsMatchTopology (self.cornerAPos, self.cornerBPos, upLidCVsPos, lowLidCVsPos) ## # Create upper driver curve self.upLidDriverCrv = cmds.curve (d = 3, p = (upLidCVsOrdered[0], upLidCVsOrdered[1], upLidCVsOrdered[2], upLidCVsOrdered[3], upLidCVsOrdered[4], upLidCVsOrdered[5], upLidCVsOrdered[6])) upLidDriverCrvName = upLidBaseCrv.replace ("_BASE_", "_DRIVER_") self.upLidDriverCrv = cmds.rename (self.upLidDriverCrv, upLidDriverCrvName) cmds.parent (self.upLidDriverCrv, upRigGrp) cmds.delete (upLidGuideCrv) # Create lower driver curve lowCrvTEMP = cmds.curve (d = 3, p = (lowLidCVsOrdered[0], lowLidCVsOrdered[1], lowLidCVsOrdered[2], lowLidCVsOrdered[3], lowLidCVsOrdered[4], lowLidCVsOrdered[5], lowLidCVsOrdered[6])) lowLidDriverCrvName = lowLidBaseCrv.replace ("_BASE_", "_DRIVER_") self.lowLidDriverCrv = cmds.rename (lowCrvTEMP, lowLidDriverCrvName) cmds.parent (self.lowLidDriverCrv, lowRigGrp) cmds.delete (lowLidGuideCrv) ## cmds.select (cl = 1) wireNodeUpLidName = upLidBaseCrv.replace ("_BASE_curve", "_controlCurve_wire") wireUpLid = cmds.wire (upLidBaseCrv, n = wireNodeUpLidName, w = self.upLidDriverCrv, gw = 0, en = 1, ce = 0, li = 0) cmds.select (cl = 1) wireNodeLowLidName = lowLidBaseCrv.replace ("_BASE_curve", "_controlCurve_wire") wireUpLid = cmds.wire (lowLidBaseCrv, n = wireNodeLowLidName, w = self.lowLidDriverCrv, gw = 0, en = 1, ce = 0, li = 0)
import maya.cmds as cmds import math #Set turret attributes: numberOfRows = 7 height = 1.5 width = 2.0 depth = width #Make turret shape: turret = cmds.polyCube(name="turret", h=height, w=width, d=depth) cmds.move(0, height / 2, 0) cmds.select(turret[0] + '.f[1]') cmds.scale(0.1, 0.1, 0, xz=True) cmds.select(turret[0] + '.f[3]', r=True) cmds.delete() cmds.select(turret[0]) #Add rows to turret: for rowNumber in range(1, numberOfRows): cmds.polyCut(rx=90, pcy=rowNumber * height / numberOfRows) #Add tiles to turret: for i in range(2): for rowNumber in range(numberOfRows): for tileNumber in range(1, numberOfRows - rowNumber): #Create lists of all faces in turret: list1 = [] list2 = [] numberOfFaces = cmds.polyEvaluate('turret', f=True)
def createScrew(self): name = 's' + str(self.num_s) cmds.polyHelix(n=name, sa=3, h=11.2, c=12, w=2.3, sco=16, r=.25) cmds.delete( name + '.f[0]', name + '.f[3]', name + '.f[6]', name + '.f[9]', name + '.f[12]', name + '.f[15]', name + '.f[18]', name + '.f[21]', name + '.f[24]', name + '.f[27]', name + '.f[30]', name + '.f[33]', name + '.f[36]', name + '.f[39]', name + '.f[42]', name + '.f[45]', name + '.f[48]', name + '.f[51]', name + '.f[54]', name + '.f[57]', name + '.f[60]', name + '.f[63]', name + '.f[66]', name + '.f[69]', name + '.f[72]', name + '.f[75]', name + '.f[78]', name + '.f[81]', name + '.f[84]', name + '.f[87]', name + '.f[90]', name + '.f[93]', name + '.f[96]', name + '.f[99]', name + '.f[102]', name + '.f[105]', name + '.f[108]', name + '.f[111]', name + '.f[114]', name + '.f[117]', name + '.f[120]', name + '.f[123]', name + '.f[126]', name + '.f[129]', name + '.f[132]', name + '.f[135]', name + '.f[138]', name + '.f[141]', name + '.f[144]', name + '.f[147]', name + '.f[150]', name + '.f[153]', name + '.f[156]', name + '.f[159]', name + '.f[162]', name + '.f[165]', name + '.f[168]', name + '.f[171]', name + '.f[174]', name + '.f[177]', name + '.f[180]', name + '.f[183]', name + '.f[186]', name + '.f[189]', name + '.f[192]', name + '.f[195]', name + '.f[198]', name + '.f[201]', name + '.f[204]', name + '.f[207]', name + '.f[210]', name + '.f[213]', name + '.f[216]', name + '.f[219]', name + '.f[222]', name + '.f[225]', name + '.f[228]', name + '.f[231]', name + '.f[234]', name + '.f[237]', name + '.f[240]', name + '.f[243]', name + '.f[246]', name + '.f[249]', name + '.f[252]', name + '.f[255]', name + '.f[258]', name + '.f[261]', name + '.f[264]', name + '.f[267]', name + '.f[270]', name + '.f[273]', name + '.f[276]', name + '.f[279]', name + '.f[282]', name + '.f[285]', name + '.f[288]', name + '.f[291]', name + '.f[294]', name + '.f[297]', name + '.f[300]', name + '.f[303]', name + '.f[306]', name + '.f[309]', name + '.f[312]', name + '.f[315]', name + '.f[318]', name + '.f[321]', name + '.f[324]', name + '.f[327]', name + '.f[330]', name + '.f[333]', name + '.f[336]', name + '.f[339]', name + '.f[342]', name + '.f[345]', name + '.f[348]', name + '.f[351]', name + '.f[354]', name + '.f[357]', name + '.f[360]', name + '.f[363]', name + '.f[366]', name + '.f[369]', name + '.f[372]', name + '.f[375]', name + '.f[378]', name + '.f[381]', name + '.f[384]', name + '.f[387]', name + '.f[390]', name + '.f[393]', name + '.f[396]', name + '.f[399]', name + '.f[402]', name + '.f[405]', name + '.f[408]', name + '.f[411]', name + '.f[414]', name + '.f[417]', name + '.f[420]', name + '.f[423]', name + '.f[426]', name + '.f[429]', name + '.f[432]', name + '.f[435]', name + '.f[438]', name + '.f[441]', name + '.f[444]', name + '.f[447]', name + '.f[450]', name + '.f[453]', name + '.f[456]', name + '.f[459]', name + '.f[462]', name + '.f[465]', name + '.f[468]', name + '.f[471]', name + '.f[474]', name + '.f[477]', name + '.f[480]', name + '.f[483]', name + '.f[486]', name + '.f[489]', name + '.f[492]', name + '.f[495]', name + '.f[498]', name + '.f[501]', name + '.f[504]', name + '.f[507]', name + '.f[510]', name + '.f[513]', name + '.f[516]', name + '.f[519]', name + '.f[522]', name + '.f[525]', name + '.f[528]', name + '.f[531]', name + '.f[534]', name + '.f[537]', name + '.f[540]', name + '.f[543]', name + '.f[546]', name + '.f[549]', name + '.f[552]', name + '.f[555]', name + '.f[558]', name + '.f[561]', name + '.f[564]', name + '.f[567]', name + '.f[570]', name + '.f[573]', name + '.f[576:577]') cmds.polyAppend(s=1, tx=1, a=[959, 912]) cmds.polyAppend(s=1, tx=1, a=[387, 434]) cmds.polyBridgeEdge(name + '.e[390]', name + '.e[393]', name + '.e[396]', name + '.e[399]', name + '.e[402]', name + '.e[405]', name + '.e[408]', name + '.e[411]', name + '.e[414]', name + '.e[417]', name + '.e[420]', name + '.e[423]', name + '.e[426]', name + '.e[429]', name + '.e[432]', name + '.e[435]', name + '.e[437:438]', name + '.e[440:441]', name + '.e[443:444]', name + '.e[446:447]', name + '.e[449:450]', name + '.e[452:453]', name + '.e[455:456]', name + '.e[458:459]', name + '.e[461:462]', name + '.e[464:465]', name + '.e[467:468]', name + '.e[470:471]', name + '.e[473:474]', name + '.e[476:477]', name + '.e[479:480]', name + '.e[482:483]', name + '.e[485:486]', name + '.e[488:489]', name + '.e[491:492]', name + '.e[494:495]', name + '.e[497:498]', name + '.e[500:501]', name + '.e[503:504]', name + '.e[506:507]', name + '.e[509:510]', name + '.e[512:513]', name + '.e[515:516]', name + '.e[518:519]', name + '.e[521:522]', name + '.e[524:525]', name + '.e[527:528]', name + '.e[530:531]', name + '.e[533:534]', name + '.e[536:537]', name + '.e[539:540]', name + '.e[542:543]', name + '.e[545:546]', name + '.e[548:549]', name + '.e[551:552]', name + '.e[554:555]', name + '.e[557:558]', name + '.e[560:561]', name + '.e[563:564]', name + '.e[566:567]', name + '.e[569:570]', name + '.e[572:573]', name + '.e[575:576]', name + '.e[578:579]', name + '.e[581:582]', name + '.e[584:585]', name + '.e[587:588]', name + '.e[590:591]', name + '.e[593:594]', name + '.e[596:597]', name + '.e[599:600]', name + '.e[602:603]', name + '.e[605:606]', name + '.e[608:609]', name + '.e[611:612]', name + '.e[614:615]', name + '.e[617:618]', name + '.e[620:621]', name + '.e[623:624]', name + '.e[626:627]', name + '.e[629:630]', name + '.e[632:633]', name + '.e[635:636]', name + '.e[638:639]', name + '.e[641:642]', name + '.e[644:645]', name + '.e[647:648]', name + '.e[650:651]', name + '.e[653:654]', name + '.e[656:657]', name + '.e[659:660]', name + '.e[662:663]', name + '.e[665:666]', name + '.e[668:669]', name + '.e[671:672]', name + '.e[674:675]', name + '.e[677:678]', name + '.e[680:681]', name + '.e[683:684]', name + '.e[686:687]', name + '.e[689:690]', name + '.e[692:693]', name + '.e[695:696]', name + '.e[698:699]', name + '.e[701:702]', name + '.e[704:705]', name + '.e[707:708]', name + '.e[710:711]', name + '.e[713:714]', name + '.e[716:717]', name + '.e[719:720]', name + '.e[722:723]', name + '.e[725:726]', name + '.e[728:729]', name + '.e[731:732]', name + '.e[734:735]', name + '.e[737:738]', name + '.e[740:741]', name + '.e[743:744]', name + '.e[746:747]', name + '.e[749:750]', name + '.e[752:753]', name + '.e[755:756]', name + '.e[758:759]', name + '.e[761:762]', name + '.e[764:765]', name + '.e[767:768]', name + '.e[770:771]', name + '.e[773:774]', name + '.e[776:777]', name + '.e[779:780]', name + '.e[782:783]', name + '.e[785:786]', name + '.e[788:789]', name + '.e[791:792]', name + '.e[794:795]', name + '.e[797:798]', name + '.e[800:801]', name + '.e[803:804]', name + '.e[806:807]', name + '.e[809:810]', name + '.e[812:813]', name + '.e[815:816]', name + '.e[818:819]', name + '.e[821:822]', name + '.e[824:825]', name + '.e[827:828]', name + '.e[830:831]', name + '.e[833:834]', name + '.e[836:837]', name + '.e[839:840]', name + '.e[842:843]', name + '.e[845:846]', name + '.e[848:849]', name + '.e[851:852]', name + '.e[854:855]', name + '.e[857:858]', name + '.e[860:861]', name + '.e[863:864]', name + '.e[866:867]', name + '.e[869:870]', name + '.e[872:873]', name + '.e[875:876]', name + '.e[878:879]', name + '.e[881:882]', name + '.e[884:885]', name + '.e[887:888]', name + '.e[890:891]', name + '.e[893:894]', name + '.e[896:897]', name + '.e[899:900]', name + '.e[902:903]', name + '.e[905:906]', name + '.e[908:909]', name + '.e[911]', name + '.e[914]', name + '.e[917]', name + '.e[920]', name + '.e[923]', name + '.e[926]', name + '.e[929]', name + '.e[932]', name + '.e[935]', name + '.e[938]', name + '.e[941]', name + '.e[944]', name + '.e[947]', name + '.e[950]', name + '.e[953]', name + '.e[956]', sma=30, dv=0) self.num_s += 1 return name
def createCrvCtrls (self, eyePrefix, parentCtrl, ctrlJnts): '''Creates controller curve for each controller joint. Called by 'buildRig' function. Call functions: None ''' # Organize rig hierarchy hierarchySecondGrp = cmds.group (n = (eyePrefix + "_Eyelids_CTRL_GRP"), em = 1) hierarchyMainGrp = "Eyelids_CTRL_GRP" if parentCtrl != None : ctrlChildren = cmds.listRelatives (parentCtrl, children = 1) if hierarchyMainGrp in ctrlChildren : cmds.parent (hierarchySecondGrp, (parentCtrl + "|" + hierarchyMainGrp)) else : cmds.group (n = hierarchyMainGrp, em = 1, p = parentCtrl) cmds.parent (hierarchySecondGrp, (parentCtrl + "|" + hierarchyMainGrp)) else : if cmds.objExists ("|" + hierarchyMainGrp) : cmds.parent (hierarchySecondGrp, ("|" + hierarchyMainGrp)) else : cmds.group (n = hierarchyMainGrp, em = 1) cmds.parent (hierarchySecondGrp, ("|" + hierarchyMainGrp)) # Creates the controller object cmds.select (cl = 1) TEMP_CTRL1 = cmds.circle (r = 0.15) [0] TEMP_CTRL2 = cmds.duplicate () [0] cmds.setAttr (TEMP_CTRL2 + ".rotateY", 90) TEMP_CTRL3 = cmds.duplicate () [0] cmds.setAttr (TEMP_CTRL3 + ".rotateX", 90) cmds.parent (TEMP_CTRL2, TEMP_CTRL3, TEMP_CTRL1) cmds.makeIdentity (apply = 1, t = 1, r = 1, s = 1, n = 0, pn = 1) cmds.pickWalk (d = "down") cmds.select (TEMP_CTRL1, tgl = 1) cmds.parent (r = 1, s = 1) cmds.delete (TEMP_CTRL2, TEMP_CTRL3) cmds.select (cl = 1) # Place the controllers and constrain the joints self.ctrlList = [] ctrlOffsetGrpList = [] for jnt in ctrlJnts: ctrlName = jnt [:-9] ctrlName = "CTRL_" + ctrlName ctrl = cmds.duplicate (TEMP_CTRL1, n = ctrlName) [0] self.ctrlList.append (ctrl) pointC_TEMP = cmds.pointConstraint (jnt, ctrl) cmds.delete (pointC_TEMP) origName = "ORIG_" + ctrlName origGrp = cmds.group (n = origName, em = 1) parentC_TEMP = cmds.parentConstraint (ctrl, origGrp) cmds.delete (parentC_TEMP) if ctrl.find ("_Secondary") != -1 : # If controller is 'secondary' offsetGrpName = origName.replace ("ORIG_", "OFFSET_") offsetGrp = cmds.duplicate (origGrp, n = offsetGrpName) cmds.parent (ctrl, offsetGrp) cmds.parent (offsetGrp, origGrp) ctrlOffsetGrpList.extend (offsetGrp) else: cmds.parent (ctrl, origGrp) cmds.parent (origGrp, hierarchySecondGrp) cmds.parentConstraint (ctrl, jnt) cmds.delete (TEMP_CTRL1) cmds.select (cl = 1) # Constraints between main controllers and secondary ones # self.ctrlList = same order as 'ctrlJnts' list # [ctrl_CornerA, ctrl_upLidSecA, ctrl_upLidMain, ctrl_upLidSecB, ctrl_CornerB, ctrl_lowLidSecB, ctrl_lowLidMain, ctrl_lowLidSecA] # Index: 0 1 2 3 4 5 6 7 # ctrlOffsetGrpList = [OFFSET_Up_secondaryA, OFFSET_Up_secondaryB, OFFSET_Low_secondaryB, OFFSET_Low_secondaryA] # Index: 0 1 2 3 cmds.parentConstraint (self.ctrlList[0], ctrlOffsetGrpList[0], mo = 1) cmds.parentConstraint (self.ctrlList[2], ctrlOffsetGrpList[0], mo = 1) cmds.parentConstraint (self.ctrlList[2], ctrlOffsetGrpList[1], mo = 1) cmds.parentConstraint (self.ctrlList[4], ctrlOffsetGrpList[1], mo = 1) cmds.parentConstraint (self.ctrlList[4], ctrlOffsetGrpList[2], mo = 1) cmds.parentConstraint (self.ctrlList[6], ctrlOffsetGrpList[2], mo = 1) cmds.parentConstraint (self.ctrlList[6], ctrlOffsetGrpList[3], mo = 1) cmds.parentConstraint (self.ctrlList[0], ctrlOffsetGrpList[3], mo = 1) # Secondary controllers visibility (drove by main controllers) cmds.select (cl = 1) cmds.select (self.ctrlList[2], self.ctrlList[6]) cmds.addAttr (ln = "SecondaryControls", at = "bool", k = 0) cmds.setAttr ((self.ctrlList[2] + ".SecondaryControls"), 1, channelBox = 1) cmds.setAttr ((self.ctrlList[6] + ".SecondaryControls"), 1, channelBox = 1) # Upper lid cmds.connectAttr ((self.ctrlList[2] + ".SecondaryControls"), (self.ctrlList[1] + ".visibility"), f = 1) cmds.connectAttr ((self.ctrlList[2] + ".SecondaryControls"), (self.ctrlList[3] + ".visibility"), f = 1) # Lower lid cmds.connectAttr ((self.ctrlList[6] + ".SecondaryControls"), (self.ctrlList[5] + ".visibility"), f = 1) cmds.connectAttr ((self.ctrlList[6] + ".SecondaryControls"), (self.ctrlList[7] + ".visibility"), f = 1) # Lock and hide unused channels for ctrl in self.ctrlList : cmds.setAttr ((ctrl + ".sx"), lock = 1, keyable = 0, channelBox = 0) cmds.setAttr ((ctrl + ".sy"), lock = 1, keyable = 0, channelBox = 0) cmds.setAttr ((ctrl + ".sz"), lock = 1, keyable = 0, channelBox = 0) cmds.setAttr ((ctrl + ".v"), lock = 1, keyable = 0, channelBox = 0)
def jpmBuildQuadrapedRig( armsFKIK, armsStretchy, armsSingle, armsRadius, arms4Joint, armsChicken, armsFingers, legsFKIK, legsStretchy, legsSingle ): ################## ##sorting ################## grps = [] geos = [] crvs = [] left = [] right = [] leftThumb = [] leftIndex = [] leftMiddle = [] leftRing = [] leftPinky = [] leftUlna = [] leftRadius = [] leftChickenArms = [] rightThumb = [] rightIndex = [] rightMiddle = [] rightRing = [] rightPinky = [] rightUlna = [] rightRadius = [] rightChickenArms = [] stabilize = [] places = cmds.ls( "*_PLACE_*", tr=True, fl=True ) for thisPlace in places: isFound = thisPlace.find("GRP") if str(isFound) != "-1": grps.append( thisPlace ) isFound = thisPlace.find("GEO") if str(isFound) != "-1": geos.append( thisPlace ) isFound = thisPlace.find("CRV") if str(isFound) != "-1": crvs.append( thisPlace ) isFound = thisPlace.find("left") if str(isFound) != "-1": left.append( thisPlace ) isFound = thisPlace.find("right") if str(isFound) != "-1": right.append( thisPlace ) isFound = thisPlace.find("stabilize") if str(isFound) != "-1": stabilize.append( thisPlace ) ##Left Hand for thisPlace in left: isFound = thisPlace.find("thumb") if str(isFound) != "-1": leftThumb.append( thisPlace ) isFound = thisPlace.find("index") if str(isFound) != "-1": leftIndex.append( thisPlace ) isFound = thisPlace.find("middle") if str(isFound) != "-1": leftMiddle.append( thisPlace ) isFound = thisPlace.find("ring") if str(isFound) != "-1": leftRing.append( thisPlace ) isFound = thisPlace.find("pinky") if str(isFound) != "-1": leftPinky.append( thisPlace ) isFound = thisPlace.find("ulna") if str(isFound) != "-1": leftUlna.append( thisPlace ) isFound = thisPlace.find("radius") if str(isFound) != "-1": leftRadius.append( thisPlace ) isFound = thisPlace.find("chickenArm") if str(isFound) != "-1": leftChickenArms.append( thisPlace ) ##Right Hand for thisPlace in right: isFound = thisPlace.find("thumb") if str(isFound) != "-1": rightThumb.append( thisPlace ) isFound = thisPlace.find("index") if str(isFound) != "-1": rightIndex.append( thisPlace ) isFound = thisPlace.find("middle") if str(isFound) != "-1": rightMiddle.append( thisPlace ) isFound = thisPlace.find("ring") if str(isFound) != "-1": rightRing.append( thisPlace ) isFound = thisPlace.find("pinky") if str(isFound) != "-1": rightPinky.append( thisPlace ) isFound = thisPlace.find("ulna") if str(isFound) != "-1": rightUlna.append( thisPlace ) isFound = thisPlace.find("radius") if str(isFound) != "-1": rightRadius.append( thisPlace ) isFound = thisPlace.find("chickenArm") if str(isFound) != "-1": rightChickenArms.append( thisPlace ) ################## ##Make Limb Skeletons ################## ##Define Anchor/Place points ##leg anchors[] == hip-place, knee-place, ankle-place, ball-place, toe-place, heel-place leftLegAnchors = [ "left_hip_PLACE_GEO", "left_knee_PLACE_GEO", "left_ankle_PLACE_GEO", "left_ball_PLACE_GEO", "left_toe_PLACE_GEO", "left_heel_PLACE_GEO" ] rightLegAnchors = [ "right_hip_PLACE_GEO", "right_knee_PLACE_GEO", "right_ankle_PLACE_GEO", "right_ball_PLACE_GEO", "right_toe_PLACE_GEO", "right_heel_PLACE_GEO" ] ##arm anchors[] == clavicle-place, shoulder-place, elbow-place, wrist-place, hands[finger][joint] leftHand = [ leftThumb, leftIndex, leftMiddle, leftRing, leftPinky ] leftArmAnchors = [ "left_clavicle_PLACE_GEO", "left_shoulder_PLACE_GEO", "left_elbow_PLACE_GEO", "left_wrist_PLACE_GEO", leftHand, leftUlna, leftRadius ] rightHand = [ rightThumb, rightIndex, rightMiddle, rightRing, rightPinky ] rightArmAnchors = [ "right_clavicle_PLACE_GEO", "right_shoulder_PLACE_GEO", "right_elbow_PLACE_GEO", "right_wrist_PLACE_GEO", rightHand, rightUlna, rightRadius ] ##spine anchors[] == waist-place, upperBody-place spineAnchors = [ "waist_PLACE_GEO", "upperBody_PLACE_GEO" ] leftLegJoints = limbs.createLimbJoints( "left", "leg", leftLegAnchors ) rightLegJoints = limbs.createLimbJoints( "right", "leg", rightLegAnchors ) leftArmJoints = limbs.createLimbJoints( "left", "arm", leftArmAnchors ) rightArmJoints = limbs.createLimbJoints( "right", "arm", rightArmAnchors ) shoulderGirdle = helper.makeObj( "SHOULDER_GIRDLE_GRP", "transform", "upperBody_PLACE_GEO", 0,0,0 ) spineJoints = limbs.createLimbJoints( "", "spine", spineAnchors ) cmds.parent( leftLegJoints[0], spineJoints[0] ) cmds.parent( rightLegJoints[0], spineJoints[0] ) cmds.parent( leftArmJoints[0], spineJoints[-1][-1] ) cmds.parent( rightArmJoints[0], spineJoints[-1][-1] ) ################## ##Joint Cleanup ################## cmds.select( "*_JNT" ) mm.eval( "jsOrientJoint 1" ) #cmds.joint( e=True, oj="yxz", sao="xdown", zso=True ) ################## ##Default Rig ################## transCtrl, pivotCtrl = ctrls.jpmCreateDefaultRig() ################## ##Make Limb Controls ################## leftLegControls = limbs.createLimbControls( "left", "leg", leftLegAnchors, leftLegJoints ) rightLegControls = limbs.createLimbControls( "right", "leg", rightLegAnchors, rightLegJoints ) leftArmControls = limbs.createLimbControls( "left", "arm", leftArmAnchors, leftArmJoints ) rightArmControls = limbs.createLimbControls( "right", "arm", rightArmAnchors, rightArmJoints ) shoulderGirdle = helper.makeObj( "SHOULDER_GIRDLE_GRP", "transform", "upperBody_PLACE_GEO", 0,0,0 ) cmds.parent( leftArmControls, shoulderGirdle ) cmds.parent( rightArmControls, shoulderGirdle ) cmds.parent( shoulderGirdle, pivotCtrl ) ##Hands Parent Stuff leftWristCon = cmds.parentConstraint( leftArmControls[0], leftArmControls[1], mo=True ) cmds.parentConstraint( pivotCtrl, leftArmControls[1], mo=True ) rightWristCon = cmds.parentConstraint( rightArmControls[0], rightArmControls[1], mo=True ) cmds.parentConstraint( pivotCtrl, rightArmControls[1], mo=True ) cmds.addAttr( transCtrl, ln="handsParent", at="float", min=0, max=1, dv=1 ) cmds.setAttr( (transCtrl + ".handsParent"), e=True, keyable=True ) cmds.connectAttr( (transCtrl + ".handsParent"), (leftWristCon[0] + ".w0") ) cmds.connectAttr( (transCtrl + ".handsParent"), (rightWristCon[0] + ".w0") ) revNode = cmds.shadingNode( "reverse", asUtility=True, n="hands_REV" ) cmds.connectAttr( (transCtrl + ".handsParent"), (revNode + ".inputX") ) cmds.connectAttr( (revNode + ".outputX"), (leftWristCon[0] + ".w1") ) cmds.connectAttr( (revNode + ".outputX"), (rightWristCon[0] + ".w1") ) spineControls = limbs.createLimbControls( "", "spine", spineAnchors, spineJoints ) ################## ##Pole Vectors ################## ################## ##Head CTRLs ################## headGrp = helper.makeObj( "neck_GRP", "transform", "neck_PLACE_GEO", 0,0,0 ) neckCtrl = helper.makeObj( "neck", "straightCompass", "neck_PLACE_GEO", 0,0,0 ) headCtrl = helper.makeObj( "head", "cubeTwo", "head_PLACE_GEO", 0,0,0 ) cmds.parent( headCtrl, neckCtrl ) cmds.parent( neckCtrl, headGrp ) ################## ##Do Mouth ################## cmds.select( cl=True ) cmds.select(crvs) clsCrvs.jpmACCurve(2, 2, 1) ################## #Cleanup ################## skelGrp = helper.makeObj( "SKELETON", "transform", "origin", 0,0,0 ) defGrp = helper.makeObj( "DEFORMERS", "transform", "origin", 0,0,0 ) cmds.parent( skelGrp, "WORLD" ) cmds.parent( defGrp, "WORLD" ) cmds.select( "*_PLACE_GEO" ) cmds.delete()
def eyelidsCorners (self, upLidEpCrvPos, upLidCrv, lowLidEpCrvPos, lowLidCrv): '''Define eye corners position (for example if upper lid and lower lid curves are not 'closed'). Called by 'createDriverCrv' function. Call functions: None ''' cornerUp1 = upLidEpCrvPos [0] cornerUp2 = upLidEpCrvPos [4] cornerLow1 = lowLidEpCrvPos [0] cornerLow2 = lowLidEpCrvPos [4] # distance formula is: d = sqrt((Ax-Bx)**2 + (Ay-By)**2 + (Az-Bz)**2) distTEMP1 = math.sqrt( (cornerUp1[0] - cornerLow1[0])**2 + (cornerUp1[1] - cornerLow1[1])**2 + (cornerUp1[2] - cornerLow1[2])**2 ) distTEMP2 = math.sqrt( (cornerUp1[0] - cornerLow2[0])**2 + (cornerUp1[1] - cornerLow2[1])**2 + (cornerUp1[2] - cornerLow2[2])**2 ) # If cornerUp1 is closer to cornerLow2 than cornerLow1, # then the center of the distance between cornerUp1 and cornerLow2 # will be the "CornerA" and "CornerB" will be defined by # the other two points. if distTEMP1 > distTEMP2 : # CornerA cmds.select (cl = 1) cmds.select (upLidCrv + ".ep[0]") cmds.select (lowLidCrv + ".ep[4]", tgl = 1) clusterTEMP1 = cmds.cluster (en = 1) [1] locTEMP1 = cmds.spaceLocator () [0] cmds.pointConstraint (clusterTEMP1, locTEMP1, mo = 0, w = 1) self.cornerAPos = cmds.xform (locTEMP1, q = 1, ws = 1, t = 1) cmds.delete (clusterTEMP1) cmds.delete (locTEMP1) # CornerB cmds.select (cl = 1) cmds.select (upLidCrv + ".ep[4]") cmds.select (lowLidCrv + ".ep[0]", tgl = 1) clusterTEMP2 = cmds.cluster (en = 1) [1] locTEMP2 = cmds.spaceLocator () [0] cmds.pointConstraint (clusterTEMP2, locTEMP2, mo = 0, w = 1) self.cornerBPos = cmds.xform (locTEMP2, q = 1, ws = 1, t = 1) cmds.delete (clusterTEMP2) cmds.delete (locTEMP2) else: # CornerA cmds.select (cl = 1) cmds.select (upLidCrv + ".ep[0]") cmds.select (lowLidCrv + ".ep[0]", tgl = 1) clusterTEMP1 = cmds.cluster (en = 1) [1] locTEMP1 = cmds.spaceLocator () [0] cmds.pointConstraint (clusterTEMP1, locTEMP1, mo = 0, w = 1) self.cornerAPos = cmds.xform (locTEMP1, q = 1, ws = 1, t = 1) cmds.delete (clusterTEMP1) cmds.delete (locTEMP1) # CornerB cmds.select (cl = 1) cmds.select (upLidCrv + ".ep[4]") cmds.select (lowLidCrv + ".ep[4]", tgl = 1) clusterTEMP2 = cmds.cluster (en = 1) [1] locTEMP2 = cmds.spaceLocator () [0] cmds.pointConstraint (clusterTEMP2, locTEMP2, mo = 0, w = 1) self.cornerBPos = cmds.xform (locTEMP2, q = 1, ws = 1, t = 1) cmds.delete (clusterTEMP2) cmds.delete (locTEMP2) return self.cornerAPos, self.cornerBPos
def process_group(self, group, parent): temp_group = cmds.duplicate(group, parentOnly=True, inputConnections=True)[0] empty_group = cmds.group(empty=True) cmds.parent(temp_group, empty_group, absolute=True) scale_axis = ".scaleX" if self.mirror_plane == "XZ": scale_axis = ".scaleY" elif self.mirror_plane == "XY": scale_axis = ".scaleZ" cmds.setAttr(empty_group + scale_axis, -1) instance = group_selected.GroupSelected() group_suffix = group.partition("__")[2] new_group = instance.create_group_at_specified( group_suffix + "_mirror", temp_group, parent) cmds.lockNode("Group_container", lock=False, lockUnpublished=False) cmds.delete(empty_group) for module_link in ((group, new_group), (new_group, group)): attribute_value = module_link[1] + "__" if self.mirror_plane == "YZ": attribute_value += "X" elif self.mirror_plane == "XZ": attribute_value += "Y" elif self.mirror_plane == "XY": attribute_value += "Z" cmds.select(module_link[0]) cmds.addAttr(dt="string", longName="mirrorLinks", k=False) cmds.setAttr(module_link[0] + "." + "mirrorLinks", attribute_value, type="string") cmds.select(clear=True) children = cmds.listRelatives(group, children=True) children = cmds.ls(children, transforms=True) for child in children: if child.find("Group__") == 0: self.process_group(child, new_group) else: child_namespaces = utils.strip_all_namespaces(child) if child_namespaces != None and child_namespaces[ 1] == "module_transform": for module in self.module_info: if child_namespaces[0] == module[0]: module_container = module[1] + ":module_container" cmds.lockNode(module_container, lock=False, lockUnpublished=False) module_transform = module[1] + ":module_transform" cmds.parent(module_transform, new_group, absolute=True) cmds.lockNode(module_container, lock=True, lockUnpublished=True)
def Position_Fn(self): self.Check_Selection() cmds.delete(cmds.parentConstraint(adv, Ziva_Rig[i]))
def saveTemplateToModule(moduleNull): """ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> DESCRIPTION: * Save the new positional information from the template objects * Collect all names of objects for a delete list * If anything in the module doesn't belong there, un parent it, report it * like a template object parented to another obect ARGUMENTS: moduleNull(string) RETURNS: limbJoints(list) >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> """ #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> #>>> Variables #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> #>>> Get our base info """ module null data """ moduleNullData = attributes.returnUserAttrsToDict(moduleNull) """ part name """ partName = NameFactory.returnUniqueGeneratedName(moduleNull, ignore='cgmType') partType = moduleNullData.get('cgmModuleType') direction = moduleNullData.get('cgmDirection') """ template null """ templateNull = moduleNullData.get('templateNull') templateNullData = attributes.returnUserAttrsToDict(templateNull) """ template object nulls """ templatePosObjectsInfoNull = returnInfoTypeNull(moduleNull, 'templatePosObjects') templatePosObjectsInfoData = attributes.returnUserAttrsToDict( templatePosObjectsInfoNull) templateControlObjectsNull = returnInfoTypeNull(moduleNull, 'templateControlObjects') templateControlObjectsData = attributes.returnUserAttrsToDict( templateControlObjectsNull) """ rig null """ rigNull = moduleNullData.get('rigNull') """ Start objects stuff """ templateStarterDataInfoNull = returnInfoTypeNull(moduleNull, 'templateStarterData') templateControlObjectsDataNull = returnInfoTypeNull( moduleNull, 'templateControlObjectsData') """ AutonameStuff """ divider = NameFactory.returnCGMDivider() moduleRootBuffer = returnInfoNullObjects(moduleNull, 'templatePosObjects', types='templateRoot') moduleRoot = moduleRootBuffer[0] templateObjects = [] coreNamesArray = [] #>>>TemplateInfo for key in templatePosObjectsInfoData.keys(): if (mc.attributeQuery(key, node=templatePosObjectsInfoNull, msg=True)) == True: templateObjects.append(templatePosObjectsInfoData[key]) coreNamesArray.append(key) posTemplateObjects = [] """ Get the positional template objects""" for obj in templateObjects: bufferList = obj.split(divider) if (typesDictionary.get('templateObject')) in bufferList: posTemplateObjects.append(obj) """ get our control template objects """ controlTemplateObjects = [] for key in templateControlObjectsData.keys(): if (mc.attributeQuery(key, node=templateControlObjectsNull, msg=True)) == True: controlTemplateObjects.append(templateControlObjectsData[key]) """put objects in order of closeness to root""" posTemplateObjects = distance.returnDistanceSortedList( moduleRoot, posTemplateObjects) controlTemplateObjects = distance.returnDistanceSortedList( moduleRoot, controlTemplateObjects) curve = (templatePosObjectsInfoData['curve']) #>>> get our orientation helpers helperObjects = [] for obj in posTemplateObjects: helperObjects.append( attributes.returnMessageObject(obj, 'orientHelper')) masterOrient = (attributes.returnMessageObject(moduleRoot, 'orientHelper')) print('%s%s' % (moduleNull, ' data acquired...')) #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> #>>> Save Data #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> #>>> Get the data """ pos objects """ storageData = [] for obj in posTemplateObjects: storageData.append(mc.xform(obj, q=True, ws=True, sp=True)) """ orientation helpers """ for obj in helperObjects: storageData.append(mc.xform(obj, q=True, os=True, ro=True)) storageData.append(mc.xform(masterOrient, q=True, os=True, ro=True)) print storageData """ template control objects data""" tempateControlObjectsStorageData = [] for obj in controlTemplateObjects: print obj tempateControlObjectsStorageData.append( mc.xform(obj, q=True, ws=True, t=True)) tempateControlObjectsStorageData.append( mc.xform(obj, q=True, os=True, ro=True)) rootScale = (mc.xform(moduleRoot, q=True, relative=True, scale=True)) objScaleBuffer = (mc.xform(obj, q=True, relative=True, scale=True)) objScale = [] cnt = 0 for scale in objScaleBuffer: objScale.append(scale * rootScale[cnt]) cnt += 1 tempateControlObjectsStorageData.append(objScale) print tempateControlObjectsStorageData #>>> Store the data to the initial objects pos """ Get the attributes to store to""" initialObjectsTemplateDataBuffer = attributes.returnUserAttrsToList( templateStarterDataInfoNull) initialObjectsPosData = lists.removeMatchedIndexEntries( initialObjectsTemplateDataBuffer, 'cgm') """ store it""" cnt = 0 for set in initialObjectsPosData: attrBuffer = set[0] xBuffer = (templateStarterDataInfoNull + '.' + attrBuffer + 'X') yBuffer = (templateStarterDataInfoNull + '.' + attrBuffer + 'Y') zBuffer = (templateStarterDataInfoNull + '.' + attrBuffer + 'Z') dataSet = storageData[cnt] mc.setAttr(xBuffer, dataSet[0]) mc.setAttr(yBuffer, dataSet[1]) mc.setAttr(zBuffer, dataSet[2]) cnt += 1 #>>> Store the data to the initial objects pos """ Get the attributes to store to""" templateControlObjectsDataNullBuffer = attributes.returnUserAttrsToList( templateControlObjectsDataNull) templateControlObjectsData = lists.removeMatchedIndexEntries( templateControlObjectsDataNullBuffer, 'cgm') """ store it""" cnt = 0 for set in templateControlObjectsData: attrBuffer = set[0] xBuffer = (templateControlObjectsDataNull + '.' + attrBuffer + 'X') yBuffer = (templateControlObjectsDataNull + '.' + attrBuffer + 'Y') zBuffer = (templateControlObjectsDataNull + '.' + attrBuffer + 'Z') dataSet = tempateControlObjectsStorageData[cnt] mc.setAttr(xBuffer, dataSet[0]) mc.setAttr(yBuffer, dataSet[1]) mc.setAttr(zBuffer, dataSet[2]) cnt += 1 #>>>>>>need to add locking>>>>>>>>>>>>>>>>>>>>>>>>>>>> print('%s%s' % (moduleNull, ' template object positional/rotational/scale data stored...')) #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> #>>> Save skin joints to skin joints null #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> #>>> Delete stuff #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> """ Gather our objects""" toDeleteList = search.returnObjectsOwnedByModuleNull(templateNull) print toDeleteList for obj in toDeleteList: if mc.objExists(obj) == True: print('%s%s' % (obj, ' deleted...')) mc.delete(obj) #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> #>>> Change Tag #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> mc.setAttr((moduleNull + '.templateState'), 0) mc.setAttr((moduleNull + '.skeletonState'), 1) #add locking print('%s%s' % (moduleNull, ' done')) return 'done'
def execute(self, tasks, work_template, progress_cb, **kwargs): """ Main hook entry point :tasks: List of tasks to be pre-published. Each task is be a dictionary containing the following keys: { item: Dictionary This is the item returned by the scan hook { name: String description: String type: String other_params: Dictionary } output: Dictionary This is the output as defined in the configuration - the primary output will always be named 'primary' { name: String publish_template: template tank_type: String } } :work_template: template This is the template defined in the config that represents the current work file :progress_cb: Function A progress callback to log progress during pre-publish. Call: progress_cb(percentage, msg) to report progress to the UI :returns: A list of any tasks that were found which have problems that need to be reported in the UI. Each item in the list should be a dictionary containing the following keys: { task: Dictionary This is the task that was passed into the hook and should not be modified { item:... output:... } errors: List A list of error messages (strings) to report } """ results = [] ## Get rid of stupid empty reference nodes... [(cmds.lockNode(ref, lock=False), cmds.delete(ref)) for ref in cmds.ls(type='reference')] # validate tasks: for task in tasks: debug(app=None, method='lighingPrePublish.execute', message='task: %s' % task, verbose=False) item = task["item"] debug(app=None, method='lighingPrePublish.execute', message='item: %s' % item, verbose=False) output = task["output"] errors = [] # report progress: progress_cb(0, "Validating", task) if item["type"] == "light_grp": errors.extend(self._validate_item_for_publish(item)) debug(app=None, method='lighingPrePublish.execute', message='light_grp validated', verbose=False) elif item["type"] == "cam_grp": errors.extend(self._validate_item_for_publish(item)) debug(app=None, method='lighingPrePublish.execute', message='cam_grp validated', verbose=False) elif item["type"] == "mesh_grp": errors.extend(self._validate_item_for_publish(item)) debug(app=None, method='lighingPrePublish.execute', message='mesh_grp validated', verbose=False) elif item["type"] == "fx_grp": errors.extend(self._validate_item_for_publish(item)) debug(app=None, method='lighingPrePublish.execute', message='fx_grp validated', verbose=False) # elif item["type"] == "renderPreview": # debug(app = None, method = 'lighingPrePublish.execute', message = 'renderPreview validated', verbose = False) # pass elif item["type"] == "renderFinal": debug(app=None, method='lighingPrePublish.execute', message='renderFinal validated', verbose=False) pass elif item["type"] == "xml_grp": debug(app=None, method='lighingPrePublish.execute', message='xml_grp validated', verbose=False) pass else: # don't know how to publish this output types! errors.append( "Don't know how to publish this item! \nPlease contact your supervisor..." % output["name"]) # if there is anything to report then add to result if len(errors) > 0: # add result: results.append({"task": task, "errors": errors}) progress_cb(100) debug(app=None, method='lighingPrePublish.execute', message='Returning Results....', verbose=False) return results
def go(obj = None, target = None, position = True, rotation = True, rotateAxis = False,rotateOrder = False, scalePivot = False, pivot = 'rp', space = 'w', mode = 'xform'): """ Core snap functionality. We're moving an object by it's rp to move it around. The scale pivot may be snapped as well :parameters: obj(str): Object to modify target(str): Object to snap to sourceObject(str): object to copy from :returns success(bool) """ _str_func = 'go' try:obj = obj.mNode except:pass _obj = VALID.mNodeString(obj) _target = VALID.mNodeString(target) _pivot = VALID.kw_fromDict(pivot, SHARED._d_pivotArgs, noneValid=False,calledFrom= __name__ + _str_func + ">> validate pivot") _space = VALID.kw_fromDict(space,SHARED._d_spaceArgs,noneValid=False,calledFrom= __name__ + _str_func + ">> validate space") #_mode = VALID.kw_fromDict(mode,_d_pos_modes,noneValid=False,calledFrom= __name__ + _str_func + ">> validate mode") _mode = mode log.debug("|{0}| >> obj: {1} | target:{2} | pivot: {5} | space: {3} | mode: {4}".format(_str_func,_obj,_target,_space,_mode,_pivot)) log.debug("|{0}| >> position: {1} | rotation:{2} | rotateAxis: {3} | rotateOrder: {4}".format(_str_func,position,rotation,rotateAxis,rotateOrder)) kws = {'ws':False,'os':False} if _space == 'world': kws['ws']=True else:kws['os']=True #cgmGEN.walk_dat(kws) if position: kws_move = copy.copy(kws) if _pivot == 'sp': kws_move['spr'] = True else: kws_move['rpr'] = True if _pivot == 'closestPoint': log.debug("|{0}|...closestPoint...".format(_str_func)) _targetType = SEARCH.get_mayaType(_target) p = DIST.get_by_dist(_obj,_target,resMode='pointOnSurface') POS.set(_obj,p) else: log.debug("|{0}|...postion...".format(_str_func)) pos = POS.get(target,_pivot,_space,_mode) #log.debug(pos) #cgmGEN.print_dict(kws,'move kws','snap.go') mc.move (pos[0],pos[1],pos[2], _obj, **kws_move) #log.debug(POS.get(_obj)) if rotateAxis: log.debug("|{0}|...rotateAxis...".format(_str_func)) mc.xform(obj,ra = mc.xform(_target, q=True, ra=True, **kws), p=True, **kws) if rotateOrder: log.debug("|{0}|...rotateOrder...".format(_str_func)) mc.xform(obj,roo = mc.xform(_target, q=True, roo=True), p=True) if rotation: log.debug("|{0}|...rotation...".format(_str_func)) _t_ro = ATTR.get_enumValueString(_target,'rotateOrder') _obj_ro = ATTR.get_enumValueString(obj,'rotateOrder') if _t_ro != _obj_ro: #Creating a loc to get our target space rotateOrder into new space log.debug("|{0}|...rotateOrders don't match...".format(_str_func)) _loc = mc.spaceLocator(n='tmp_roTranslation')[0] ATTR.set(_loc,'rotateOrder',_t_ro) rot = mc.xform (_target, q=True, ro=True, **kws ) mc.xform(_loc, ro = rot, **kws) mc.xform(_loc, roo = _obj_ro, p=True) rot = mc.xform (_loc, q=True, ro=True, **kws ) mc.delete(_loc) else: rot = mc.xform (_target, q=True, ro=True, **kws ) mc.xform(_obj, ro = rot, **kws) if scalePivot: log.debug("|{0}|...scalePivot...".format(_str_func)) mc.xform(obj,sp = mc.xform(_target, q=True, sp=True,**kws), p=True, **kws) return pos = infoDict['position'] mc.move (pos[0],pos[1],pos[2], _target, ws=True) mc.xform(_target, roo=infoDict['rotateOrder'],p=True) mc.xform(_target, ro=infoDict['rotation'], ws = True) mc.xform(_target, ra=infoDict['rotateAxis'],p=True) #mTarget = r9Meta.getMObject(target) mc.xform(_target, rp=infoDict['position'], ws = True, p=True) mc.xform(_target, sp=infoDict['scalePivot'], ws = True, p=True)
def build(startJoint, endJoint, controlShape='circle', endCtrl=False, ctrlRotate=[0, 0, 0], ctrlOrient=True, ctrlScale=1.0, ctrlLod='primary', prefix=''): ''' ''' # ========== # - Checks - # ========== if not prefix: prefix = 'fkChain' if not mc.objExists(startJoint): raise Exception('Start Joint "' + startJoint + '" does nto exist!') if not mc.objExists(endJoint): raise Exception('End Joint "' + endJoint + '" does nto exist!') # ==================== # - Configure Module - # ==================== # ========================== # - Build Module Structure - # ========================== # Create control group ctrl_grp = mc.group(em=True, n=prefix + '_ctrl_grp', w=True) # Create rig group rig_grp = mc.group(em=True, n=prefix + '_rig_grp', w=True) # Create skel group skel_grp = mc.group(em=True, n=prefix + '_skel_grp', w=True) # Create module group module = mc.group(em=True, n=prefix + '_module') mc.parent([ctrl_grp, rig_grp, skel_grp], module) # - Uniform Scale - mc.addAttr(module, ln='uniformScale', min=0.001, dv=1.0) mc.connectAttr(module + '.uniformScale', ctrl_grp + '.scaleX') mc.connectAttr(module + '.uniformScale', ctrl_grp + '.scaleY') mc.connectAttr(module + '.uniformScale', ctrl_grp + '.scaleZ') mc.connectAttr(module + '.uniformScale', skel_grp + '.scaleX') mc.connectAttr(module + '.uniformScale', skel_grp + '.scaleY') mc.connectAttr(module + '.uniformScale', skel_grp + '.scaleZ') # =================== # - Create Controls - # =================== # Get joint list jointList = glTools.utils.joint.getJointList(startJoint, endJoint) # Get joint length jntLen = 0.0 for jnt in jointList: cJntLen = glTools.utils.joint.length(jnt) if cJntLen > jntLen: jntLen = cJntLen # Build joint controls jointGrps = [] jointShape = [] for joint in jointList[:-1]: # Add control shape jntShape = glTools.tools.controlBuilder.controlShape(joint, controlShape, rotate=ctrlRotate, orient=ctrlOrient, scale=jntLen * ctrlScale) # Add joint buffer jntGrp = glTools.utils.joint.group(joint) # Tag Control glTools.rig.utils.tagCtrl(joint, ctrlLod) # Append arrays jointGrps.append(jntGrp) jointShape.extend(jntShape) # End Control if endCtrl: # Add control shape jntShape = glTools.tools.controlBuilder.controlShape(jointList[-1], controlShape, rotate=ctrlRotate, scale=jntLen * ctrlScale) # Add joint buffer jntGrp = glTools.utils.joint.group(jointList[-1]) # Tag Control glTools.rig.utils.tagCtrl(jointList[-1], ctrlLod) # Append arrays jointGrps.append(jntGrp) jointShape.extend(jntShape) # ======================= # - Create Attach Joint - # ======================= mc.select(cl=True) # Attach joint attachJoint = mc.joint(n=prefix + '_attachA_jnt') attachJointGrp = glTools.utils.joint.group(attachJoint) mc.delete(mc.pointConstraint(startJoint, attachJointGrp)) # Attach joint display mc.setAttr(attachJoint + '.overrideEnabled', 1) mc.setAttr(attachJoint + '.overrideLevelOfDetail', 1) # Parent attach joint mc.parent(jointGrps[0], attachJoint) mc.parent(attachJointGrp, skel_grp) # ====================== # - Set Channel States - # ====================== chStateUtil = glTools.utils.channelState.ChannelState() chStateUtil.setFlags([0, 0, 0, 0, 0, 0, 0, 0, 0, 1], objectList=jointList[:-1]) if endCtrl: chStateUtil.setFlags([0, 0, 0, 0, 0, 0, 0, 0, 0, 1], objectList=[jointList[-1]]) else: chStateUtil.setFlags([2, 2, 2, 2, 2, 2, 2, 2, 2, 1], objectList=[jointList[-1]]) chStateUtil.setFlags([2, 2, 2, 2, 2, 2, 2, 2, 2, 1], objectList=jointGrps) chStateUtil.setFlags([2, 2, 2, 2, 2, 2, 2, 2, 2, 1], objectList=[attachJointGrp]) chStateUtil.setFlags([1, 1, 1, 1, 1, 1, 1, 1, 1, 1], objectList=[attachJoint]) chStateUtil.setFlags([2, 2, 2, 2, 2, 2, 2, 2, 2, 1], objectList=[module, ctrl_grp, rig_grp, skel_grp]) # ================= # - Return Result - # ================= # Define control list ctrlList = jointList[:-1] if endCtrl: ctrlList.append(jointList[-1]) return [module, attachJoint]