def ik_stretch(ikhnd): ''' ''' jts = cmds.ikHandle(ikhnd, q=True, jl=True) cu_s = cmds.ikHandle(ikhnd, q=True, c=True) cu = cmds.listRelatives(cu_s, p=1)[0] cmds.addAttr(ikhnd, longName='ik_stretch', k=1, defaultValue=1.0, minValue=0.0, maxValue=1.) dcu = cmds.duplicate(cu, n=cu + '_base_scale')[0] dcu_s = cmds.listRelatives(dcu, c=1)[0] cf = cmds.createNode('curveInfo') dcf = cmds.createNode('curveInfo') bl = cmds.createNode('blendTwoAttr') md = cmds.createNode('multiplyDivide') cmds.connectAttr(cu_s + '.worldSpace', cf + '.inputCurve') cmds.connectAttr(dcu_s + '.worldSpace', dcf + '.inputCurve') cmds.connectAttr(dcf + '.arcLength', bl + '.input[0]') cmds.connectAttr(cf + '.arcLength', bl + '.input[1]') cmds.connectAttr(ikhnd + '.ik_stretch', bl + '.attributesBlender') cmds.connectAttr(bl + '.output', md + '.input1X') cmds.setAttr(md + '.input2X', cmds.getAttr(cf + '.arcLength'), l=1) cmds.setAttr(md + '.operation', 2) cmds.setAttr(dcu + '.v', 0) for j in jts: cmds.connectAttr(md + '.outputX', j + '.sx') return dcu
def orderNextTo(objects, target): ''' places 'objects'/[objects] next to 'target' in hierarchy and ordering I found most of the time I use the get/setOrder stuff to relocate objs to another with parenting and if in world and hierarchy Nr and all that shit.. this does it inline ''' if not isinstance(objects, list): objects = [objects] handledObjs = [] targetParent = m.listRelatives(target, parent=True, fullPath=True) targetNr = getOrder(target) # handle each object on its own no matter how its parented for o in objects: oParent = m.listRelatives(o, parent=1, fullPath=1) if oParent != targetParent: if targetParent: o = m.parent(o, targetParent)[0] else: o = m.parent(o, world=1)[0] # else if in same hierarchy already decrease count if obj is before target elif getOrder(o) <= targetNr: targetNr -= 1 handledObjs.append(o) setOrder(handledObjs, targetNr + 1) m.select(handledObjs) return handledObjs
def unparent(shape): ''' Unparent shape nodes from a source parent @param shape: Shape or transform to unparent shapes from @type shape: str ''' # Checks if not mc.objExists(shape): raise Exception('Object "'+shape+'" does not exist!!') # Get 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] # Create shape holder shapeHolder = transform+'Shapes' if not mc.objExists(shapeHolder): shapeHolder = mc.createNode('transform',n=shapeHolder) targetXform = mc.xform(transform,q=True,ws=True,m=True) mc.xform(shapeHolder,ws=True,m=targetXform) # Unparent shapes for shape in shapes: mc.parent(shape,shapeHolder,s=True,r=True) # Return Result return shapeHolder
def copyCrvShape(): sel = mc.ls(sl = True) if len(sel)>1: crvShape = mc.listRelatives(sel[0] , s = True) crvDegree = mc.getAttr(crvShape[0]+'.degree') crvSpans = mc.getAttr(crvShape[0]+'.spans') crvCvs = crvDegree + crvSpans for j in range(0,crvCvs+1): pos = mc.xform(sel[0] + '.cv[ '+str(j)+ ']' , q = True , os = True , t = True ) for i in range(0,len(sel)): if i == 0: continue else : mc.xform(sel[i] + '.cv[ '+str(j)+ ']' , os = True , t = pos ) else : searchQuery = mc.textField('searchUI' ,q = True ,tx = True) raplaceQuery = mc.textField('replaceUI' ,q = True ,tx = True) newCrv = sel[0].replace(searchQuery,raplaceQuery) crvShape = mc.listRelatives(sel[0] , s = True) crvDegree = mc.getAttr(crvShape[0]+'.degree') crvSpans = mc.getAttr(crvShape[0]+'.spans') crvCvs = crvDegree + crvSpans for j in range(0,crvCvs+1): pos = mc.xform(sel[0] + '.cv[ '+str(j)+ ']' , q = True , ws = True , t = True ) mc.xform(newCrv + '.cv[ '+str(j)+ ']' , ws = True , t = (-pos[0],pos[1],pos[2]) )
def getShapes(geo,nonIntermediates=True,intermediates=True): ''' Return a list of shapes under a transform parent @param geo: Transform to list shapes for @type geo: str @param nonIntermediates: List non intermediate shapes @type nonIntermediates: bool @param intermediates: List intermediate shapes @type intermediates: bool ''' # Checks if not mc.objExists(geo): raise Exception('Object "'+geo+'" does not exist!!') if isShape(geo): geo = mc.listRelatives(geo,p=True,pa=True)[0] # Get Shapes shapes = [] if nonIntermediates: nonIntShapes = mc.listRelatives(geo,s=True,ni=True,pa=True) if nonIntShapes: shapes.extend(nonIntShapes) if intermediates: shapes.extend(listIntermediates(geo)) # Return Result return shapes
def filterSelection(self): """ from a raw list of items, returns 1 dict containing: {[meshes], [cameras], [locators], [lights]} """ # get current selection cmds.select(hi = True) selection = [str(item) for item in cmds.ls(sl = True)] # fill the items dict from the raw selection items = {} # meshes items['meshes'] = [cmds.listRelatives(node, p=True, fullPath=True)[0] \ for node in selection if cmds.nodeType(node) == "mesh"] # cameras items['cameras'] = [cmds.listRelatives(node, p=True, fullPath=True)[0] \ for node in selection if cmds.nodeType(node) == "camera"] # locators items['locators'] = [cmds.listRelatives(node, p=True, fullPath=True)[0] \ for node in selection if cmds.nodeType(node) == "locator"] # lights items['lights'] = [cmds.listRelatives(node, p=True, fullPath=True)[0] \ for node in selection if 'Light' in cmds.nodeType(node)] return items
def listIntermediates(geo): ''' Return a list of intermediate shapes under a transform parent @param geo: Transform to list intermediate shapes for @type geo: str ''' # Checks if not mc.objExists(geo): raise Exception('Object "'+geo+'" does not exist!!') if isShape(geo): geo = mc.listRelatives(geo,p=True,pa=True)[0] # Get Non Intermediate Shapes shapes = mc.listRelatives(geo,s=True,ni=True,pa=True) # Get All Shapes allShapes = mc.listRelatives(geo,s=True,pa=True) # Get Intermediate Shapes if not allShapes: return [] if not shapes: return allShapes intShapes = list(set(allShapes) - set(shapes)) # Return Result return intShapes
def _setup_wire_deformer(self, mesh, wire, wirebase, curve, parent, complexity): """Setup the wire deformer. If complexity is 1 or higher call this function recursively to create a wire deformer on the nurbs surface. @param mesh(string): PolyMesh used to wire deform @param wire(string): Descriptive part of the name of the wire deformer @param wirebase(string): Descriptive part of the name of the base wire @param curve(string): Curve used for wireTool deformer @param parent(string): Parent node of the wire setup @param complexity(uint): complexity level value """ w = wire wb = wirebase cmds.wire(mesh, w=curve, dds=[0, 10000], n=w, foc=False) cmds.rename(cmds.listConnections('%s.baseWire[0]' % w)[0], wb) if not cmds.listRelatives(curve, p=True) == [self.wire_grp]: cmds.parent(curve, wb, self.wire_grp) # end if wbs = cmds.listRelatives(wb, ad=True, type='shape')[0] cs = cmds.listRelatives(curve, ad=True, type='shape')[0] cmds.setAttr('%s.rotation' % w, 0) # connect to showHistory cmds.connectAttr('%s.showHistory' % self.mod_grp, '%s.ihi' % w) cmds.connectAttr('%s.showHistory' % self.mod_grp, '%s.ihi' % wb) cmds.connectAttr('%s.showHistory' % self.mod_grp, '%s.ihi' % wbs) cmds.connectAttr('%s.showHistory' % self.mod_grp, '%s.ihi' % cs) if complexity: cmds.duplicate(self.curve, n=self.nrbcurve) return self._setup_wire_deformer(self.surface, self.nrbwire, self.nrbwirebase, self.nrbcurve, self.parent, 0)
def select_node_by_type(nodeType): sel = cmds.ls(sl=True, l=True) sel_ad = cmds.listRelatives(sel, ad=True, f=True) + sel cmds.select(cl=True) for node in sel_ad: if cmds.nodeType(node) == nodeType: cmds.select((cmds.listRelatives(node, p=True)), add=True)
def copyBitSettings(): ''' Copies the bit shape settings (OpenGL stuff) from the second object to the first (in selection order). ''' selList = cmds.ls( selection=True, long=True ) depFn = OpenMaya.MFnDependencyNode() if len(selList) == 2: # First object is target. targetShape = cmds.listRelatives( selList[0], shapes=True, fullPath=True )[0] targetShapeMObj = NodeUtility.getDependNode( targetShape ) depFn.setObject( targetShapeMObj ) targetShapeType = depFn.typeName() # Second object is source. sourceShape = cmds.listRelatives( selList[1], shapes=True, fullPath=True )[0] sourceShapeMObj = NodeUtility.getDependNode( sourceShape ) depFn.setObject( sourceShapeMObj ) sourceShapeType = depFn.typeName() if targetShapeType == sourceShapeType: # The types match. Do the copy of attribute settings. for attr in cmds.listAttr( sourceShape, multi=True, keyable=True ): # Get the plugs. sourcePlug = NodeUtility.getPlug( sourceShape, attr ) targetPlug = NodeUtility.getPlug( targetShape, attr ) # Get the source plug value. sourcePlugValue = NodeUtility.getPlugValue( sourcePlug ) # Set the target's plug value. NodeUtility.setPlugValue( targetPlug, sourcePlugValue ) else: raise ValueError( '{0} and {1} do not match.'.format( selList[0], selList[1] ) )
def getNodesOverload(poseObj, nodes, *args): # NOTE: poseObj already has an attr 'metaRig' which is filled # automatically in the main buildInternalPoseData() call metaNode = poseObj.metaRig currentSelection = cmds.ls(sl=True, l=True) filteredNodes = [] if not issubclass(type(metaNode), r9Meta.MetaHIKControlSetNode): # see if we have a left or right controller selected and switch to the # appropriate subMetaSystem if cmds.getAttr('%s.mirrorSide' % currentSelection[0]) == 1: print '\nFinger : PoseOverload Handler : %s >> side: Left' % metaNode filteredNodes = metaNode.L_ArmSystem.L_FingerSystem.getChildren() [filteredNodes.append(node) for node in cmds.listRelatives(filteredNodes, type='joint', ad=True, f=True)] elif cmds.getAttr('%s.mirrorSide' % currentSelection[0]) == 2: print '\nFinger : PoseOverload Handler : %s >> side: Right' % metaNode filteredNodes = metaNode.R_ArmSystem.R_FingerSystem.getChildren() [filteredNodes.append(node) for node in cmds.listRelatives(filteredNodes, type='joint', ad=True, f=True)] else: if currentSelection[0] == metaNode.LeftWristEffector or currentSelection[0] == metaNode.LeftHand: [filteredNodes.append(node) for node in cmds.listRelatives(metaNode.LeftHand, type='joint', ad=True, f=True)] elif currentSelection[0] == metaNode.RightWristEffector or currentSelection[0] == metaNode.RightHand: [filteredNodes.append(node) for node in cmds.listRelatives(metaNode.RightHand, type='joint', ad=True, f=True)] # modify the actual PoseData object, changing the data to be matched on index # rather than using the standard name or metaMap matching poseObj.metaPose = False poseObj.matchMethod = 'index' return filteredNodes
def rename_objects(*args): objs = meshes = cmds.ls( selection=True ) txt = fix_string( cmds.textField('txt_input',q=True,text=True) ) alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l',] if len(objs) == 1: ob = objs[0] shape = cmds.listRelatives(ob, shapes=True)[0] t_name = txt + '_t' m_name = txt cmds.rename(shape, m_name) cmds.rename(ob , t_name) return True if len(objs) > 1: count = 0 for ob in objs: shape = cmds.listRelatives(ob, shapes=True)[0] t_name = txt + '_t_' + alphabet[count] m_name = txt + '_' + alphabet[count] cmds.rename(shape, m_name) cmds.rename(ob , t_name) count+=1 return True else: print'Nothing to do' return False
def performTranferV1(self): getMesh=cmds.ls(sl=1) if len(getMesh)<2: print "select a skinned mesh group and an unskinned target mesh group" return else: pass getMeshController=getMesh[0] getMeshTarget=getMesh[1] getChildrenController=cmds.listRelatives(getMeshController, c=1, typ="transform") if getChildrenController==None: getChildrenController=([getMeshController]) getChildrenTarget=cmds.listRelatives(getMeshTarget, c=1, typ="transform") if getChildrenTarget==None: getChildrenTarget=([getMeshTarget]) result = cmds.promptDialog( title='find XML', message="Enter path", text="C:\Users\\"+str(getFolderName)+"\Documents\maya\projects\default\scenes\\", button=['Continue','Cancel'], defaultButton='Continue', cancelButton='Cancel', dismissString='Cancel' ) if result == 'Continue': skinPath=cmds.promptDialog(q=1) if skinPath: pass else: print "nothing collected" self.callJointsWin(getChildrenController, getChildrenTarget, skinPath)
def insepectDuplicatesShapes(self): geometrys = mc.listRelatives(mc.ls(type=('mesh', 'nurbsSurface')), p=True, path=True) u_geometrys = [] for geo in geometrys: if len(mc.listRelatives(geo, s=True)) > 1: u_geometrys.append(geo) return u_geometrys
def write_hierarchy(guide): """ Simple hierarchy data structure :param position: Guide node :type position: Guide, str :returns: Guide **Example**: >>> write_hierarchy("C_spine_0_gde") """ try: guide = guide.joint except Exception: guide = str(guide) if not cmds.objExists(guide): raise NameError("'%s' is not a guide." % guide) data = {} all_guides = cmds.listRelatives(guide, allDescendents=True, type="joint") or [] all_guides.insert(0, guide) for guide in all_guides: children = [Guide.validate(c) for c in cmds.listRelatives(guide, children=True, type="joint") or []] guide = Guide.validate(guide) data[guide] = children return data
def createDistanceNodeBetweenPosInfoNodes (node1,node2): """ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> DESCRIPTION: Creates a distance node between two position info nodes ARGUMENTS: node1(string) node2(string) RETURNS: returnList[0] - distance object returnList[1] - shape node returnList[2] - shape node distance attribute >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> """ returnList =[] distShapeBuffer = mc.createNode ('distanceDimShape') distBuffer = (mc.listRelatives (distShapeBuffer,parent=True)) mc.connectAttr ((node1+'.position'),(distShapeBuffer+'.startPoint')) mc.connectAttr ((node2+'.position'),(distShapeBuffer+'.endPoint')) distanceObj = mc.rename (distBuffer, (node1+'_to_'+node2+'_distNode') ) newDistShapeBuffer = (mc.listRelatives (distanceObj,shapes=True)) returnList.append (distanceObj) returnList.append (newDistShapeBuffer[0]) returnList.append (newDistShapeBuffer[0]+'.distance') return returnList
def multObjShapeUpdate(): sel_objs = cmds.ls(sl=True,fl=True) if len(sel_objs)>0: files_to_import = cmds.fileDialog2(fileFilter = '*.obj', dialogStyle = 2, caption = 'import multiple object files', fileMode = 4,okc="Import") if len(files_to_import) == len(sel_objs): object_names = [file_to_import.split('/')[-1].split('.obj')[0] for file_to_import in files_to_import] if len(sel_objs) == len([x for x in object_names if x in sel_objs]): for file_to_import in files_to_import: object_name = file_to_import.split('/')[-1].split('.obj')[0] returnedNodes = cmds.file('%s' % file_to_import, i = True, type = "OBJ", rnn=True, ignoreVersion = True, options = "mo=0", loadReferenceDepth = "all" ) cmds.delete(cmds.ls(returnedNodes,type="objectSet")) geo = cmds.listRelatives(cmds.ls(returnedNodes,g=1)[0],p=1) cmds.rename( geo, "newShape_{0}".format(object_name)) new_shapes = [s for s in cmds.listRelatives(cmds.ls(g=1),p=1) if "newShape_" in s] cur_shapes = sel_objs for new in new_shapes: for cur in cur_shapes: if new.split("newShape_")[1] == cur: blendshapeNd = cmds.blendShape(new,cur)[0] cmds.setAttr("{0}.{1}".format(blendshapeNd,new),1) cmds.delete(cur_shapes,ch=True) cmds.delete(new_shapes) cmds.confirmDialog(m="---===All Shapes Updated!===---") else: cmds.confirmDialog(m="--==Not Matching The Name!==--") else: cmds.confirmDialog(m="--==Please Select The Same Number Of Objects!==--") else: cmds.confirmDialog(m="--==Please Select Something!==--")
def dump(self): eval_joints = ["root"] skeleton_def = [] while len(eval_joints) > 0: current_node = eval_joints[0] eval_joints = eval_joints[1:] joint_def = [":{0}".format(current_node)] if current_node[-3:] == "_rt": # Skip the right part of skeleton tree continue child_nodes = cmds.listRelatives(current_node) if current_node == "root": # Split root from pelvis eval_joints += child_nodes else: while child_nodes is not None: joint_def.append("{0}:{1}".format(current_node, child_nodes[0])) eval_joints += child_nodes[1:] current_node = child_nodes[0] child_nodes = cmds.listRelatives(current_node) skeleton_def.append(joint_def) self.display_script(skeleton_def)
def createDistanceNodeBetweenObjects (obj1,obj2): """ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> DESCRIPTION: Creates a distance node between objects ARGUMENTS: obj1(string) obj2(string) RETURNS: none >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> """ """ Creates a distance node between objects """ pos1 = returnWorldSpacePosition (obj1) pos2 = returnWorldSpacePosition (obj2) tmp = mc.distanceDimension( sp=pos1, ep=pos2 ) distBuffer = mc.listRelatives ( [tmp], p=True) distanceObj = mc.rename (distBuffer, (obj1+'_to_'+obj2+'_distMeas') ) #return the stupid locators it makes so we can connect our own stuff distanceStartPoint = (distanceObj+'Shape.startPoint') distanceEndPoint = (distanceObj+'Shape.endPoint') locAttr1connection = (mc.connectionInfo (distanceStartPoint,sourceFromDestination=True)) locAttr2connection = (mc.connectionInfo (distanceEndPoint,sourceFromDestination=True)) locAttr1Stripped = '.'.join(locAttr1connection.split('.')[0:-1]) locAttr2Stripped = '.'.join(locAttr2connection.split('.')[0:-1]) loc1Buffer = (mc.listRelatives (locAttr1Stripped,parent=True)) loc2Buffer = (mc.listRelatives (locAttr2Stripped,parent=True)) #distObj1 = mc.rename (loc1Buffer, (obj1+'_distLoc') ) #distObj2 = mc.rename (loc2Buffer, (obj2+'_distLoc') ) return distanceObj
def deformCharacterShapeSel(self, value): RN = mc.referenceQuery(self.core.skCharacter[int(value)-1], referenceNode=1) Nodes = mc.referenceQuery(RN, nodes=1) self.characterdeformShape = [] self.allCharacterRightdeformShape = [] for item in Nodes: if self.nodeTypeSelf(item) in self.shapeType: self.characterdeformShape.append(item) for each in self.characterdeformShape: itemP = mc.listRelatives(each, p=1)[0] itemPP = mc.listRelatives(itemP, p=1) if itemPP != None and mc.getAttr('%s.v'%itemP) != 0 and mc.getAttr('%s.v'%itemPP[0]) != 0: self.allCharacterRightdeformShape.append(each) self.allCharacterRightdeformShape.reverse() for item in self.allCharacterRightdeformShape: if mc.filterExpand( item, sm=(10,12)) == None: self.allCharacterRightdeformShape.remove(item) for item in self.allCharacterRightdeformShape: if item.endswith('Orig') == True: self.allCharacterRightdeformShape.remove(item) for item in self.allCharacterRightdeformShape: if item.endswith('Orig') == True: self.allCharacterRightdeformShape.remove(item) for item in self.allCharacterRightdeformShape: if item.endswith('Orig') == True: self.allCharacterRightdeformShape.remove(item) for item in self.allCharacterRightdeformShape: if item.endswith('Orig') == True: self.allCharacterRightdeformShape.remove(item) for item in self.allCharacterRightdeformShape: if item.endswith('Orig') == True: self.allCharacterRightdeformShape.remove(item) return self.allCharacterRightdeformShape
def loadSurfaceGroup(self, *args ): sels = cmds.ls( sl=1 ) if not sels: cmds.error( "Select Surface Group" ) children = cmds.listRelatives( sels[-1], c=1, ad=1 ) if not children: cmds.error( "Select Surface Group" ) surfaceGrp = '' for child in children: shapes = cmds.listRelatives( child, s=1 ) if not shapes: continue for shape in shapes: if cmds.nodeType( shape ) == 'nurbsSurface': surfaceGrp = sels[-1] break if surfaceGrp: break if not surfaceGrp: cmds.error( "Select Surface Group" ) cmds.textField( self._surfaceGroup, e=1, tx=surfaceGrp ) if not cmds.attributeQuery( 'sets', node=surfaceGrp, ex=1 ): fnc.addArrayMessageAttribute( surfaceGrp, 'sets' ) self.saveData()
def __check_scene(self): #--- this method checks the scene #--- check if something is selected sel = cmds.ls(selection = True) if sel: #--- check if selection is a mesh transform = None for i in sel: if cmds.nodeType(i) == 'transform': transform = i if cmds.listRelatives(transform, allDescendents = True, type = 'mesh'): mesh = cmds.listRelatives(transform, allDescendents = True, type = 'mesh')[0] if cmds.nodeType(mesh) == 'mesh': #--- store the mesh self.mesh = transform #--- get current frame self.currentFrame = cmds.currentTime(query = True) #--- get timestamp ts = str(time.time()) self.time_stamp = str(ts.split('.')[0] + ts.split('.')[1]) else: raise Exception('The selected object is not a mesh!') else: raise Exception('The selected object is not a mesh!') else: raise Exception('You have to select a mesh, dude!')
def _findRelativesByType(self, embeddedRoot, resList=['lo', 'md', 'hi', 'apos'], byType='shape', resExcludeList=[]): shapes = None searchResList = list(set(resList) - set(resExcludeList)) #print 'searchResList: %s'%searchResList if embeddedRoot != 'master': shapes = [] for res in searchResList: if cmds.objExists('%s|%s'%(embeddedRoot, res)): resShapes = cmds.listRelatives('%s|%s'%(embeddedRoot, res), ad=True, type=byType, f=True) if resShapes: shapes.extend(resShapes) if not shapes: shapes = None else: embeddedCodes = self._findEmbeddedAssets() index = embeddedCodes.index('master') embeddedCodes.pop(index) if cmds.objExists('|master'): children = cmds.listRelatives('|master') if children: shapes = [] for child in children: if child not in embeddedCodes: if child in searchResList: #print 'child:%s' % child if cmds.objExists('|master|%s'%child): childShapes = cmds.listRelatives('|master|%s'%child, ad=True, type=byType, f=True) if childShapes: shapes.extend(childShapes) if not shapes: shapes = None return shapes
def extractFaces( faceList, delete=False ): ''' extracts the given faces into a separate object - unlike the maya function, this is actually useful... the given faces are extracted to a separate object, and can be optionally deleted from the original mesh if desired, or just duplicated out. ''' newMeshes = [] #get a list of meshes present in the facelist cDict = componentListToDict( faceList ) for mesh, faces in cDict.iteritems(): #is the mesh a shape or a transform - if its a shape, get its transform if cmd.nodeType( mesh ) == 'mesh': mesh = cmd.listRelatives( mesh, pa=True, p=True )[ 0 ] dupeMesh = cmd.duplicate( mesh, renameChildren=True )[ 0 ] children = cmd.listRelatives( dupeMesh, pa=True, typ='transform' ) if children: cmd.delete( children ) #now delete all faces except those we want to keep cmd.select( [ '%s.f[%d]' % (dupeMesh, idx) for idx in range( numFaces( dupeMesh ) ) ] ) cmd.select( [ '%s.f[%d]' % (dupeMesh, idx) for idx in faces ], deselect=True ) cmd.delete() newMeshes.append( dupeMesh ) if delete: cmd.delete( faceList ) return newMeshes
def getCamera(self): _selection = cmds.ls(selection=True) # check selection length if len(_selection) == 0: # check panel for camera if selection is empty _panel = cmds.getPanel(withFocus=True) _typeOfPanel = mm.eval("getPanel -typeOf " + _panel) # check if modelpanel with camera is active if _typeOfPanel == "modelPanel": # get camera from modelpanel _cameraname = cmds.modelPanel(_panel, query=True, camera=True) _camerashape = cmds.listRelatives(_cameraname, shapes=True)[0] else: # no selection, no modelpanel active _cameraname = "Nul" _camerashape = "Nul" else: # selection is not emtpy _cameraname = _selection[0] _camerashape = cmds.listRelatives(_cameraname, shapes=True)[0] # check if selected shape is camera if cmds.nodeType(_camerashape) != "camera": # selection is not camera _cameraname = "Nul" _camerashape = "Nul" self.name = _cameraname self.shape = _camerashape
def setImageRes(self): """ Sets image width to resolution """ skyDomeLgtList = self.getSkyDomeLgtList() areaLgtList = self.getAreaLgtList() print '' print '-------------------------------------------------' for lgt in skyDomeLgtList: lgtName = mc.listRelatives(lgt,p=True) img = self.imgPath(lgt) if img == 'None': print '# '+ lgtName[0] + ' ===> no file image attached' else: xres = self.imgInfo(str(img)) mc.setAttr(lgt+'.resolution',int(xres)) print '# ' + lgtName[0] + ' ===> set resolution to [ ' + str(xres) + ' ]' for lgt in areaLgtList: lgtName = mc.listRelatives(lgt,p=True) img = self.imgPath(lgt) if img == 'None': print '# '+ lgtName[0] + ' ===> no file image attached' else: xres = self.imgInfo(str(img)) mc.setAttr(lgt+'.aiResolution',int(xres)) print '# ' + lgtName[0] + ' ===> set resolution to [ ' + str(xres) + ' ]' print '-------------------------------------------------' print ''
def transferUvHierarchy( fromTopGroup, toTopGroup): fromChildren = cmds.listRelatives( fromTopGroup, ad=True, type='mesh', fullPath=True)[1:] toChildren = cmds.listRelatives( toTopGroup, ad=True, type='mesh', fullPath=True)[1:] print fromChildren tmp = copy.copy(fromChildren) for fChild in tmp: split = fChild.split("|")[1:] #print split split[0] = toTopGroup tChild = "|" + "|".join( split) print fChild, tChild if tChild in toChildren: fromChildren.remove( fChild) toChildren.remove( tChild) cmds.select( fChild, r=True) tShapes = getShapes(tChild) print 'transfered \n%s \n | \n%s' % (fChild, tChild) tChildShapeOrig = tShapes[0]+'Orig' if (cmds.objectType(fChild) == 'transform' and cmds.objectType(tChild) == 'transform' and cmds.objectType(tChildShapeOrig) == 'mesh'): cmds.select( tChildShapeOrig, add=True) cmds.transferAttributes( transferPositions=0, transferNormals=0, transferUVs=2, transferColors=0, sampleSpace=4, sourceUvSpace="map1", targetUvSpace="map1", searchMethod=3, flipUVs=0, colorBorders=1) print toChildren print fromChildren
def BindSkeletons(source, dest, method='connect'): ''' From 2 given root joints search through each hierarchy for child joints, match them based on node name, then connect their trans/rots directly, or parentConstrain them. Again cmds for speed ''' sourceJoints = cmds.listRelatives(source, ad=True, f=True, type='joint') destJoints = cmds.listRelatives(dest, ad=True, f=True, type='joint') if cmds.nodeType(source) == 'joint': sourceJoints.append(source) if cmds.nodeType(dest) == 'joint': destJoints.append(dest) attrs = ['rotateX', 'rotateY', 'rotateZ', 'translateX', 'translateY', 'translateZ'] for sJnt, dJnt in MatchGivenHierarchys(sourceJoints, destJoints): if method == 'connect': for attr in attrs: try: cmds.connectAttr('%s.%s' % (sJnt, attr), '%s.%s' % (dJnt, attr), f=True) except: pass elif method == 'constrain': try: cmds.parentConstraint(sJnt, dJnt, mo=True) except: pass
def altFrame(*args): # cmds.nodeType(sel), object type # optimize, real slow pnl = cmds.getPanel(withFocus=True) typ = cmds.getPanel(typeOf=pnl) if typ == 'modelPanel': sel = cmds.ls(sl=True, fl=True) gs = ac.GraphSelection() locs = [] if sel: for item in sel: if cmds.objectType(item, i='transform') or cmds.objectType(item, i='joint'): loc = cn.locator(obj=item, ro='zxy', X=0.35, constrain=False, shape=False)[0] locs.append(loc) else: try: print cmds.listRelatives(item, parent=True)[0], '_______________' loc = cn.locator(obj=cmds.listRelatives(item, parent=True)[0], ro='zxy', X=0.35, constrain=False, shape=False) print loc, '_____________________' loc = loc[0] locs.append(loc) except: message('didnt frame object: ' + item) cmds.select(locs) mel.eval("fitPanel -selected;") cmds.delete(locs) gs.reselect() else: message('select an object') else: mel.eval("fitPanel -selected;")
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 Light_Export_Fn(self): File_Path = QFileDialog.getSaveFileName(self, caption=u"1", directory=".", filter="json (*.json)") # 空数组处理 try: if type(File_Path) is tuple: File_Path = File_Path[0] if type(File_Path) is list: File_Path = File_Path[0] except: traceback.print_exc() return Light_Json = {} Light_Json['Generate_Application'] = "Maya" Light_Json['LightData'] = {} lightList = cmds.ls(type='lightList')[0] lightList = cmds.listConnections(lightList + ".lights") for lightName in lightList: if cmds.getAttr(lightName + ".visibility") == 0: continue light = cmds.listRelatives(lightName, c=1)[0] Light_Json['LightData'][lightName] = {} Light_Json['LightData'][lightName]['Name'] = light Light_Json['LightData'][lightName]['Type'] = cmds.objectType(light) Light_Json['LightData'][lightName]['Intensity'] = cmds.getAttr( light + ".intensity") Light_Json['LightData'][lightName]['Exposure'] = cmds.getAttr( light + ".aiExposure") Light_Json['LightData'][lightName]['color'] = {} Light_Json['LightData'][lightName]['color']["R"] = cmds.getAttr( light + ".color")[0][0] Light_Json['LightData'][lightName]['color']["G"] = cmds.getAttr( light + ".color")[0][1] Light_Json['LightData'][lightName]['color']["B"] = cmds.getAttr( light + ".color")[0][2] Light_Json['LightData'][lightName]['Translate'] = {} Light_Json['LightData'][lightName]['Translate'][ 'tx'] = cmds.getAttr(lightName + ".tx") Light_Json['LightData'][lightName]['Translate'][ 'ty'] = cmds.getAttr(lightName + ".ty") Light_Json['LightData'][lightName]['Translate'][ 'tz'] = cmds.getAttr(lightName + ".tz") Light_Json['LightData'][lightName]['Rotate'] = {} Light_Json['LightData'][lightName]['Rotate']['rx'] = cmds.getAttr( lightName + ".rx") Light_Json['LightData'][lightName]['Rotate']['ry'] = cmds.getAttr( lightName + ".ry") Light_Json['LightData'][lightName]['Rotate']['rz'] = cmds.getAttr( lightName + ".rz") Light_Json['LightData'][lightName]['Scale'] = {} Light_Json['LightData'][lightName]['Scale']['sx'] = cmds.getAttr( lightName + ".sx") Light_Json['LightData'][lightName]['Scale']['sy'] = cmds.getAttr( lightName + ".sy") Light_Json['LightData'][lightName]['Scale']['sz'] = cmds.getAttr( lightName + ".sz") if cmds.objectType(light) == "spotLight": Light_Json['LightData'][lightName]['coneAngle'] = cmds.getAttr( light + ".coneAngle") Light_Json['LightData'][lightName][ 'penumbraAngle'] = cmds.getAttr(light + ".penumbraAngle") Light_Json['LightData'][lightName]['dropoff'] = cmds.getAttr( light + ".dropoff") try: with open(File_Path, 'w') as f: json.dump(Light_Json, f, indent=4) QMessageBox.warning(self, u"Success", u"Json Export Success!") except: QMessageBox.warning(self, u"Warning", u"Fail to export the Json file")
def om_get_skin_weight(self): self.node_weight_dict = {} self.node_vtx_dict = {} self.inf_id_list = list() self.influences_dict = {} self.all_influences = list() self.all_skin_clusters = {} self.mesh_node_list = list() self.show_dict = {} #選択セルに表示をフォーカスする辞書 self.node_skinFn_dict = {} for mesh_path_name, skin_vtx in self.dag_skin_id_dict.items(): skinFn = skin_vtx[0] #スキンFn vtxArry = skin_vtx[1] #バーテックスIDのリスト skinName = skin_vtx[2] #スキン名 meshPath = skin_vtx[3] #print skinName, vtxArry self.node_skinFn_dict[mesh_path_name] = skinFn #print mesh_path_name if cmds.nodeType(meshPath) == 'mesh': mesh_path_name = cmds.listRelatives(mesh_path_name, p=True, f=True)[0] # シェイプの取得 #meshPath = self.om_get_shape(mesh_path_name) #meshNode = meshPath.node() #print 'try to get skin weight :', mesh_path_name, skinFn, vtxArry #print 'try to get skin weight :', meshPath.fullPathName() # 指定の頂点をコンポーネントとして取得する singleIdComp = om2.MFnSingleIndexedComponent() vertexComp = singleIdComp.create(om2.MFn.kMeshVertComponent) singleIdComp.addElements(vtxArry) # インフルエンスの数のIntArray infDags = skinFn.influenceObjects() #インフルエンスを全取得 infIndices = om2.MIntArray(len(infDags), 0) for x in xrange(len(infDags)): infIndices[x] = int(skinFn.indexForInfluenceObject(infDags[x])) #print 'get influence id list :', infIndices # すべてのウエイトの値を取得 try: #print 'get weight :',meshPath , vertexComp , weights , infCountPtr weights = skinFn.getWeights(meshPath, vertexComp) except Exception as e: print 'get skin weight error :', e.message continue #print 'check weight data type :', type(weights) #print "getWeights :", weights weights = self.conv_weight_shape(len(infIndices), weights[0]) #print "getWeights :", weights #インフルエンス名をフルパスで取得 influence_list = [ infDags[x].fullPathName() for x in range(len(infIndices)) ] #print 'all ifluences :', influence_list self.node_vtx_dict[mesh_path_name] = vtxArry self.all_skin_clusters[mesh_path_name] = skinName self.mesh_node_list.append(mesh_path_name) self.inf_id_list.append(infIndices) self.node_weight_dict[mesh_path_name] = weights #全ての頂点のウエイト一覧 self.influences_dict[mesh_path_name] = influence_list self.all_influences += influence_list self.show_dict[mesh_path_name] = vtxArry #全てのインフルエンスをまとめる self.all_influences = sorted(list(set(self.all_influences)))
import maya.cmds as mc import pymel.core as pm sourceSkeleton = "og" # source skeleton root joint targetSkeleton = "new" # target skeleton root joint # count the joints in the hierarchies hierarchy1 = [] hierarchy2 = [] sourceSkeletonList = mc.listRelatives(sourceSkeleton, c=True, ad=True, typ='joint') targetSkeletonList = mc.listRelatives(targetSkeleton, c=True, ad=True, typ='joint') for bone in sourceSkeletonList: hierarchy1.append(bone) for bone in targetSkeletonList: hierarchy2.append(bone) jointCount1 = (len(hierarchy1)) jointCount2 = (len(hierarchy2)) if jointCount1 != jointCount2: mc.error("Oops -different number of joints in skeletons!")
def StretchyIkSetup(self, armSels): if hasattr(armSels, '__getitem__'): #declare variables for the various joints self.firstJointPos=cmds.xform(armSels[0], q=1, ws=1, t=1) self.secondJointPos=cmds.xform(armSels[1], q=1, ws=1, t=1) self.lastJointPos=cmds.xform(armSels[2], q=1, ws=1, t=1) self.lastJointRot=cmds.xform(armSels[2], q=1, ws=1, ro=1) self.secondJointPosLocal=cmds.xform(armSels[1], q=1, t=1) self.lastJointPosLocal=cmds.xform(armSels[2], q=1, t=1) #Create an IK handle on first and last Joints. self.tempIKName= str(armSels[0]) + "IK_Hndl" self.ikName=cmds.ikHandle(ee=armSels[2], sj=armSels[0], n=self.tempIKName) #Create locators for the first and last joint. self.jnt1Loc=cmds.spaceLocator(p=(0, 0, 0)) cmds.move(self.firstJointPos[0], self.firstJointPos[1], self.firstJointPos[2]) self.jnt2Loc=cmds.spaceLocator(p=(0, 0, 0)) cmds.move(self.lastJointPos[0], self.lastJointPos[1], self.lastJointPos[2]) self.jnt1LocShape=cmds.listRelatives(self.jnt1Loc, s=1) self.jnt2LocShape=cmds.listRelatives(self.jnt2Loc, s=1) #create a control for the IK handle, give it a stretchy attribute. self.ikCtrlTempName = str(armSels[0]) + "_IK_Ctrl" self.ikJointControl = cmds.circle(c=(0, 0, 0), n=self.ikCtrlTempName) cmds.addAttr(ln="Stretchy", at="float", keyable=True) self.ourControlGrp = cmds.group(n=(str(armSels[0]) + "_IK_Ctrl_Grp"), em=True) cmds.move(self.lastJointPos[0], self.lastJointPos[1], self.lastJointPos[2], self.ourControlGrp, ws=1) cmds.rotate(self.lastJointRot[0], self.lastJointRot[1], self.lastJointRot[2], self.ourControlGrp, ws=1) cmds.parent(self.ikCtrlTempName , self.ourControlGrp) cmds.move(0,0,0, self.ikJointControl, ls=True) cmds.rotate(0,0,0, self.ikJointControl) #create a "Distance between" Node for... well. getting the distance between the two nodes. self.distanceTest=str(cmds.shadingNode('distanceBetween', asUtility=1)) #create all of these nodes for all the different things we need to set up for the system. self.arm01DistanceNode=str(cmds.shadingNode('multiplyDivide', asUtility=1)) cmds.setAttr((self.arm01DistanceNode + ".input1X"), self.secondJointPosLocal[0]) self.arm02DistanceNode=str(cmds.shadingNode('multiplyDivide', asUtility=1)) cmds.setAttr((self.arm02DistanceNode + ".input1X"), self.lastJointPosLocal[0]) self.chainLengthPMA=str(cmds.shadingNode('plusMinusAverage', asUtility=1)) self.distanceScalar=str(cmds.shadingNode('multiplyDivide', asUtility=1)) cmds.setAttr((self.distanceScalar + ".operation"), 2) self.stretchCondition=str(cmds.shadingNode('condition', asUtility=1)) cmds.setAttr((self.stretchCondition + ".operation"), 2) self.colorBlendNode=str(cmds.shadingNode('blendColors', asUtility=1)) cmds.setAttr((self.colorBlendNode + ".color2R"), 1) self.arm01ScaleMD=str(cmds.shadingNode('multiplyDivide', asUtility=1)) self.arm02ScaleMD=str(cmds.shadingNode('multiplyDivide', asUtility=1)) #connect them attributes self.LinkConstraints(self.jnt1LocShape[0], "worldPosition[0]", self.distanceTest, "point1") self.LinkConstraints(self.jnt2LocShape[0], "worldPosition[0]", self.distanceTest, "point2") self.LinkConstraints(self.arm01DistanceNode, "outputX", self.chainLengthPMA, "input1D[0]") self.LinkConstraints(self.arm02DistanceNode, "outputX", self.chainLengthPMA, "input1D[1]") self.LinkConstraints(self.chainLengthPMA, "output1D", self.distanceScalar, "input2X") self.LinkConstraints(self.distanceTest, "distance", self.distanceScalar, "input1X") self.LinkConstraints(self.distanceTest, "distance", self.stretchCondition, "firstTerm") self.LinkConstraints(self.chainLengthPMA, "output1D", self.stretchCondition, "secondTerm") self.LinkConstraints(self.distanceScalar, "outputX", self.stretchCondition, "colorIfTrueR") self.LinkConstraints(self.stretchCondition, "outColorR", self.colorBlendNode, "color1R") self.LinkConstraints(self.arm01DistanceNode, "outputX", self.arm01ScaleMD, "input1X") self.LinkConstraints(self.arm02DistanceNode, "outputX", self.arm02ScaleMD, "input1X") self.LinkConstraints(self.colorBlendNode, "outputR", self.arm01ScaleMD, "input2X") self.LinkConstraints(self.colorBlendNode, "outputR", self.arm02ScaleMD, "input2X") self.LinkConstraints(self.arm01ScaleMD, "outputX", armSels[1], "translateX") self.LinkConstraints(self.arm02ScaleMD, "outputX", armSels[2], "translateX") self.LinkConstraints((str(armSels[0]) + "_IK_Ctrl"), "Stretchy", self.colorBlendNode, "blender") cmds.parentConstraint(self.ikCtrlTempName, self.tempIKName, mo=True ) cmds.parentConstraint(self.ikCtrlTempName, self.jnt2Loc, mo=True ) cmds.scaleConstraint(self.ikCtrlTempName, self.tempIKName, mo=True ) cmds.scaleConstraint(self.ikCtrlTempName, self.jnt2Loc, mo=True ) else: print("Generic Error Message") return
def IMPORTFILE(outputReference, listImportWidget, batchMode, home): py.scriptEditorInfo(suppressWarnings=1, e=1) validSelection = 0 animationSelection = True if (str(listImportWidget) != "none" and ("." not in str(listImportWidget) or "<" in str(listImportWidget))): #IF FILE NAME ISN'T PROVIDED BY OUTSIDE SOURCES, GET IT FROM LIBRARY try: selectedAnimation = listImportWidget.currentItem().text() except: animationSelection = False customFile = home + "CUSTOM.json" if (".json" not in home.split("/")[-1]) else home customFileCheck = py.file(customFile, q=1, ex=1) if (customFileCheck == 1): with open(customFile, 'r') as f: line = json.load(f) if (outputReference == "none" and animationSelection == True): outputReference = line['IMPORT FILE (PATH)'] + selectedAnimation #GET RIG PATH FROM CUSTOM (USE "LITE" PATH IF IN BATCH MODE) rigPath = line['RIG (FULL NAME)'] rigLitePath = rigPath.replace("CHAR_", "LITE_") if (py.file(rigLitePath, q=1, ex=1) == 1 and line['EXPORT AS .MA'] == 0 and batchMode == 1 and animationSelection == True): rigPath = rigLitePath inputNameSpace = "inputFile" outputNameSpace = "outputFile" i = 1 while (py.namespace(exists=outputNameSpace) == 1): outputNameSpace = outputNameSpace + str(i) i += 1 i = 1 while (py.namespace(exists=inputNameSpace) == 1): inputNameSpace = inputNameSpace + str(i) i += 1 #IF SELECTED, CHECK NAMESPACE IF CONTROLLER IS VALID selections = py.ls(sl=1) if (selections != [] and animationSelection == True): i = 0 while (i < len(selections)): RiGGiE = py.listAttr(selections[i], st=["RiGGiE"], r=1) if (isinstance(RiGGiE, list) == 1): selections = selections[i] try: filePath = py.referenceQuery(selections, filename=1) if (":" in selections): name = selections.split(":")[-1] else: name = selections if (len(selections) > len(name)): nameSpace = selections[0:(len(selections) - len(name))] else: nameSpace = "" if ("_" in nameSpace): correctedName = nameSpace.replace("_", "") py.file(filePath, referenceNode="nameSpace", namespace=correctedName, e=1) inputNameSpace = correctedName else: inputNameSpace = nameSpace except: inputNameSpace = "none" validSelection = 1 break if (i == len(selections) - 1): selections = [] py.headsUpMessage( '"No valid controllers selected..." - HiGGiE', t=2) print '"No valid controllers selected..." - HiGGiE' i += 1 #REFERENCE IN THE INPUT RIG (TARGET) AND output RIG (ANIMATED) if ((py.file(rigPath, q=1, ex=1) == 1 or inputNameSpace == "none") and py.file(outputReference, q=1, ex=1) == 1 and animationSelection == True): #try:#IF FAILS, THEN USER IS IMPORTING THE SAME FILE INTO ITSELF py.file(outputReference, namespace=outputNameSpace, prompt=0, mnp=1, iv=1, gr=1, r=1) referenceGroup = py.ls(sl=1)[0] py.setAttr(referenceGroup + ".v", 0) try: firstItem = py.listRelatives(referenceGroup, type="joint", c=1, s=0)[-1] except: firstItem = py.listRelatives(referenceGroup, type="joint", ad=1, s=0)[-1] nameSpaceBreakdown = firstItem.split(":")[:-1] officialOutputNameSpace = "" i = 0 while (i < len(nameSpaceBreakdown)): officialOutputNameSpace = officialOutputNameSpace + nameSpaceBreakdown[ i] + ":" i += 1 outputNameSpace = officialOutputNameSpace[:-1] #IMPORT INPUT RIG IF NO RIG IS SELECTED if (inputNameSpace != "none" and validSelection == 0): initialObjects = py.ls(type="transform", o=1) py.file(rigPath, namespace=inputNameSpace, prompt=0, mnp=1, iv=1, r=1) #FIND OFFICIAL NAMESPACE OF INPUT RIG if (selections == []): allObjects = py.ls(type="transform", o=1) allTransforms = list(set(allObjects) - set(initialObjects)) i = 0 while (i < len(allTransforms)): if ("_" in allTransforms[i]): if (allTransforms[i].split("_")[-1] == "CTRL"): rigController = allTransforms[i] break i += 1 if (":" in rigController): name = rigController.split(":")[-1] inputNameSpace = rigController[0:(len(rigController) - len(name))] else: inputNameSpace = "none" selections = rigController joints = py.ls(outputNameSpace + ":*", type="joint") if (joints != []): py.select(selections, r=1) animationTransfer.ANIMATIONTRANSFER(inputNameSpace, outputNameSpace, outputReference, home) else: py.headsUpMessage('"No joints found in animated file..." - HiGGiE', t=2) print '"No joints found in animated file..." - HiGGiE' #except: # py.headsUpMessage('"Can not reference the same file into itself." - HiGGiE', t=2); # print '"Can not reference the same file into itself." - HiGGiE'; elif (animationSelection == False): py.headsUpMessage( '"You must select a valid animation in the library." - HiGGiE', t=2) print '"You must select a valid animation in the library." - HiGGiE' else: py.headsUpMessage('"Import file(s) do not exist..." - HiGGiE', t=2) print '"Import file(s) do not exist..." - HiGGiE'
else: smdName = util.names.nodeName('softMod', baseName) vtxPlug = mesh mesh = mel.eval('plugNode("{0}")'.format(str(vtxPlug))) if vtxPlug != mesh: softModPos = cmds.xform(vtxPlug, ws=1, t=1, q=1) else: softModPos = cmds.xform(mesh, ws=1, rp=1, q=1) # Piv ctl softModCenterCtlGrp = cmds.createNode('transform', n=util.names.nodeName('transform', '{0}PivotGrp'.format(baseName))) softModCenterCtl = cmds.spaceLocator(n=util.names.nodeName('transform', '{0}Pivot'.format(baseName)))[0] cmds.parent(softModCenterCtl, softModCenterCtlGrp) locatorShape = cmds.listRelatives(softModCenterCtl, children=1, type='locator')[0] grpParent = softModCenterCtlGrp # Soft Mod ctl softModCtlGrp = cmds.createNode('transform', n=util.names.nodeName('transform', '{0}Grp'.format(baseName))) softModCtl = cmds.circle( n=util.names.nodeName('transform', '{0}'.format(baseName)))[0] cmds.parent(softModCtl, softModCtlGrp) cmds.parent(softModCtlGrp, softModCenterCtl) meshConnections = cmds.listConnections('{0}.inMesh'.format(mesh), s=1, d=0, plugs=1) if attachToMesh and meshConnections: # Create a transform constrained to the mesh rivetGrp = cmds.createNode('transform', n=util.names.addModifier(softModCenterCtlGrp, 'transform', addSuffix='Rivet'))
def deformer(mod=None, side=None, name=None, suffix=None, obj=None): """ Rename the given node and return its final name """ #--- check which one of the given obj is the transform node trn = list() non = list() if isinstance(obj, list): for i in obj: if cmds.nodeType(i) == 'transform': trn.append(i) else: if not cmds.nodeType(i) == 'shape': non.append(i) else: if cmds.nodeType(obj) == 'transform': trn.append(obj) else: if not cmds.nodeType(obj) == 'shape': non.append(obj) if trn: obj = trn[0] if non: non = non[0] obj_name = None #--- get the curve name based on the given specifications if mod: if side: if name: if suffix: #--- side_modName_suffix obj_name = (side + '_' + mod + name[0].upper() + name[1:] + '_' + suffix) else: #--- side_modName obj_name = side + '_' + mod + name[0].upper() + name[1:] else: if suffix: #--- side_modCrv_suffix obj_name = (side + '_' + mod + obj[0].upper() + obj[1:] + '_' + suffix) else: #--- side_modCrv obj_name = side + '_' + mod + obj[0].upper() + obj[1:] else: if name: if suffix: #--- modName_suffix obj_name = mod + name[0].upper() + name[1:] + '_' + suffix else: #--- modName obj_name = mod + name[0].upper() + name[1:] else: #--- modCrv obj_name = mod + obj[0].upper() + obj[1:] else: if side: if name: if suffix: #--- side_name_suffix obj_name = side + '_' + name + '_' + suffix else: #--- side_name obj_name = side + '_' + name else: if suffix: #--- side_obj_suffix obj_name = side + '_' + obj + '_' + suffix else: #--- side_obj obj_name = side + '_' + obj else: if name: if suffix: #--- name_suffix obj_name = name + '_' + suffix else: #--- name obj_name = name else: #--- obj obj_name = obj #--- rename the obj transform = cmds.rename(obj, obj_name) shape = list() if cmds.listRelatives(transform, children=True): shape = cmds.listRelatives(transform, allDescendents=True, type='shape')[0] #--- rename the nonTransform/nonShape obj result = list() if non: if cmds.objExists(non): non = cmds.rename(non, obj_name + non[0].upper() + non[1:]) result = [transform, shape, non] else: if shape: result = [transform, shape] else: result = transform else: result = [transform, shape] return result
def BtoT(): global jnt ben = many[j] tjo = mc.listRelatives(ben) twi = tjo[0] if '_L' in '{}'.format(ben): a = ben.split('_bend_L') for i in get: if a[0] in i: if '_L' in '{}'.format(i): if 'bend' not in '{}'.format(i): if 'twist' not in '{}'.format(i): jnt = i elif '_R' in '{}'.format(ben): a = ben.split('_bend_R') for i in get: if a[0] in i: if '_R' in '{}'.format(i): if 'bend' not in '{}'.format(i): if 'twist' not in '{}'.format(i): jnt = i else: a = ben.split('_bend') for i in get: if a[0] in i: if '_L' not in '{}'.format(i): if '_R' not in '{}'.format(i): if 'bend' not in '{}'.format(i): if 'twist' not in '{}'.format(i): jnt = i if bant >= 1: for i in baim: if jnt in i: roop() #create node aim = mc.createNode('aimConstraint', n='{}_afterSplitTwistDriver'.format(jnt)) mc.select('{}'.format(aim), r=True) mc.addAttr(ln='bend', nc=3, at='double3') mc.addAttr(ln='twist', nc=3, at='double3') for i in range(3): mc.addAttr(ln='bend{}'.format(xyz[i]), at='doubleAngle', p='bend', k=True) mc.addAttr(ln='twist{}'.format(xyz[i]), at='doubleAngle', p='twist', k=True) oc1 = mc.createNode('orientConstraint', n='{}_afterSplitTwist'.format(jnt)) oc2 = mc.createNode('orientConstraint', n='{}_rot'.format(jnt)) oc3 = mc.createNode('orientConstraint', n='{}_twistRot'.format(jnt)) pb1 = mc.createNode('pairBlend', n='{}_weightedTwist'.format(jnt)) mc.addAttr(ln='inRot2', nc=3, at='double3', w=False) for i in range(3): mc.addAttr(ln='inRot2{}'.format(xyz[0]), at='doubleAngle', p='inRot2', w=False) pb2 = mc.createNode('pairBlend', n='{}_rotSafeRot'.format(jnt)) pb3 = mc.createNode('pairBlend', n='{}_twistRotSafeRot'.format(jnt)) grp = mc.group('{}'.format(oc1),'{}'.format(oc2),'{}'.format(oc3), n='{}_BendTwist'.format(jnt)) mc.parent('{}'.format(aim), '{}'.format(jnt)) mc.parent('{}'.format(grp), '{}'.format(jnt)) mc.setAttr('{}.visibility'.format(grp), 0) #setAttr mc.setAttr('{}.target[0].targetTranslateX'.format(aim), 1) mc.setAttr('{}.worldUpType'.format(aim), 4) mc.setAttr('{}.interpType'.format(oc2), 2) mc.setAttr('{}.interpType'.format(oc3), 2) mc.setAttr('{}.rotateMode'.format(pb2), 2) mc.setAttr('{}.rotateMode'.format(pb3), 2) mc.setAttr('{}.rotInterpolation'.format(pb2), 1) mc.setAttr('{}.rotInterpolation'.format(pb3), 1) for i in range(3): mc.setAttr('{0}.translate{1}'.format(aim, xyz[i]), 0) #connectAttr mc.connectAttr('{}.constraintRotate'.format(aim), '{}.bend'.format(aim)) mc.connectAttr('{}.constraintRotate'.format(aim), '{}.constraintJointOrient'.format(oc1)) mc.connectAttr('{}.constraintRotate'.format(oc1), '{}.twist'.format(aim)) mc.connectAttr('{}.matrix'.format(aim), '{}.target[0].targetParentMatrix'.format(aim)) mc.connectAttr('{}.matrix'.format(aim), '{}.target[0].targetParentMatrix'.format(oc1)) mc.connectAttr('{}.bend'.format(aim), '{}.target[0].targetJointOrient'.format(oc2)) mc.connectAttr('{}.twist'.format(aim), '{}.inRotate1'.format(pb1)) mc.connectAttr('{}.inRot2'.format(pb1), '{}.inRotate2'.format(pb1)) mc.connectAttr('{}.outRotate'.format(pb1), '{}.target[0].targetRotate'.format(oc2)) mc.connectAttr('{}.constraintRotate'.format(oc2), '{}.inRotate2'.format(pb2)) mc.connectAttr('{}.constraintRotate'.format(oc2), '{}.constraintJointOrient'.format(oc3)) mc.connectAttr('{}.rotate'.format(jnt), '{}.target[0].targetRotate'.format(oc3)) mc.connectAttr('{}.constraintRotate'.format(oc3), '{}.inRotate2'.format(pb3)) mc.connectAttr('{}.twistWeight'.format(twi), '{}.weight'.format(pb1)) for i in range(3): mc.connectAttr('{0}.rotate{1}'.format(jnt, xyz[i]), '{0}.rotate{1}'.format(aim, xyz[i])) mc.connectAttr('{0}.translate{1}'.format(jnt, xyz[i]), '{0}.translate{1}'.format(ben, xyz[i])) mc.connectAttr('{0}.scale{1}'.format(jnt, xyz[i]), '{0}.scale{1}'.format(ben, xyz[i])) mc.connectAttr('{0}.shear{1}'.format(jnt, she[i]), '{0}.shear{1}'.format(ben, she[i])) mc.connectAttr('{0}.scale{1}'.format(ben, xyz[i]), '{0}.scale{1}'.format(twi, xyz[i])) mc.connectAttr('{0}.outRotate{1}'.format(pb2, xyz[i]), '{0}.rotate{1}'.format(ben, xyz[i])) mc.connectAttr('{0}.outRotate{1}'.format(pb3, xyz[i]), '{0}.rotate{1}'.format(twi, xyz[i])) roop()
def getParent(self, obj, *args, **kwargs): return mc.listRelatives(obj, p=1)
def checkObjectSetKey(self): ''' 驱动过的物体是否锁定并设置成了不可K帧。 ''' geoName = self.getGeoGroup() notGroup = ['hair_G' , 'arnold_loc*' , 'yeti_G' , 'cloth_G'] if not geoName: OpenMaya.MGlobal_displayWarning('not geo group') else: notGroup.append(geoName[0]) notTransList = [] for n in notGroup: if pm.objExists(n): for i in pm.ls(n , tr = True): notTransList += self.notCkeck(pm.PyNode(i)) jointSel = cmds.ls( type = 'joint') if jointSel: for jnt in jointSel: attr = cmds.listAttr(jnt , k = True) if attr: for a in attr: value = cmds.getAttr(jnt+'.'+a , k = True) if value: if jnt not in self.keyjointList: self.keyjointList.append(jnt) continue all = cmds.ls(dag= True , type = 'transform' ) if not all: OpenMaya.MGlobal_displayInfo('file not object') return conList = cmds.ls( type =['constraint','joint']) ctrlList = [ cmds.listRelatives(s , p = True)[0] for s in cmds.ls(type = ['nurbsCurve' ,'camera'])] transList = [t for t in all if t not in conList+ctrlList+notTransList] attrs = ['t' , 'r' , 's' ] for t in transList: attr = cmds.listAttr(t , k = True ,sn = True) if attr: for at in attr: if at not in self.setKeyDict.keys(): continue value1 = cmds.getAttr(t +'.'+ at , l = True) if not value1: value = cmds.getAttr(t +'.'+ at) if value != self.setKeyDict[at] : if t not in self.keyOverName: self.keyOverName.append(t) continue if cmds.listConnections(t +'.'+ at , s = True , d = False): if t not in self.keyOverName: self.keyOverName.append(t) for at in attrs: valueX = cmds.getAttr(t +'.'+ at +'x' , l = True) valueY = cmds.getAttr(t +'.'+ at +'y' , l = True) valueZ = cmds.getAttr(t +'.'+ at +'z' , l = True) if valueX == True and valueX == True and valueX == True: continue if cmds.listConnections(t +'.'+ at , s = True , d = False): if t not in self.keyOverName: self.keyOverName.append(t) continue return self.keyOverName+self.keyjointList
def sqGenerateCurves(self, *args): self.edgeList = cmds.ls(selection=True, flatten=True) if not self.edgeList == None and not self.edgeList == [] and not self.edgeList == "": self.baseCurve = cmds.polyToCurve(name="baseCurve", form=2, degree=1)[0] cmds.select(self.baseCurve + ".ep[*]") cmds.insertKnotCurve(cmds.ls(selection=True, flatten=True), constructionHistory=True, curveOnSurface=True, numberOfKnots=1, addKnots=False, insertBetween=True, replaceOriginal=True) pointListA, pointListB, sideA, sideB = self.sqGetPointLists() toDeleteList = [] p = 2 for k in range((sideA + 2), (sideB - 1)): if p % 2 == 0: toDeleteList.append(self.baseCurve + ".cv[" + str(k) + "]") toDeleteList.append(self.baseCurve + ".cv[" + str(k + len(pointListA) - 1) + "]") p = p + 1 q = 2 m = sideA - 2 if m >= 0: while m >= 0: if not m == sideA and not m == sideB: if q % 2 == 0: toDeleteList.append(self.baseCurve + ".cv[" + str(m) + "]") m = m - 1 q = q + 1 cmds.delete(toDeleteList) cmds.insertKnotCurve([ self.baseCurve + ".u[" + str(len(pointListA) - 1) + "]", self.baseCurve + ".ep[" + str(len(pointListA) - 1) + "]" ], constructionHistory=True, curveOnSurface=True, numberOfKnots=1, addKnots=False, insertBetween=True, replaceOriginal=True) pointListA, pointListB, sideA, sideB = self.sqGetPointLists() posListA, posListB = [], [] for i in range(0, len(pointListA) - 1): posListA.append( cmds.xform(pointListA[i], query=True, worldSpace=True, translation=True)) posListB.append( cmds.xform(pointListB[i], query=True, worldSpace=True, translation=True)) self.mainCurveA = cmds.curve(name="StickyLips_Main_A_Crv", degree=1, point=posListA) self.mainCurveB = cmds.curve(name="StickyLips_Main_B_Crv", degree=1, point=posListB) cmds.rename( cmds.listRelatives(self.mainCurveA, children=True, shapes=True)[0], self.mainCurveA + "Shape") cmds.rename( cmds.listRelatives(self.mainCurveB, children=True, shapes=True)[0], self.mainCurveB + "Shape") cmds.select(self.mainCurveA + ".cv[*]") self.curveLenght = len(cmds.ls(selection=True, flatten=True)) cmds.select(clear=True) self.sqCheckCurveDirection(self.mainCurveA) self.sqCheckCurveDirection(self.mainCurveB) self.baseCurveA = cmds.duplicate(self.mainCurveA, name=self.mainCurveA.replace( "_Main_", "_Base_"))[0] self.baseCurveB = cmds.duplicate(self.mainCurveB, name=self.mainCurveB.replace( "_Main_", "_Base_"))[0] cmds.delete(self.baseCurve) self.maxIter = len(posListA) cmds.group(self.mainCurveA, self.mainCurveB, self.baseCurveA, self.baseCurveB, name="StickyLips_StaticData_Grp") else: mel.eval("warning \"Please, select an closed edgeLoop.\";")
def cleanup(self, *args, **kwargs): root=self.root #blow away constraints const=mc.ls(type="constraint") if const: mc.delete(const) #kill display layers dispLayers=mc.ls(type="displayLayer") if dispLayers: mc.delete(dispLayers) #flatten geometry hierarchy if mc.objExists(self.geoGrp): geo=[] for obj in mc.listRelatives(self.geoGrp, ad=1): if mc.objectType(obj)=="mesh" and self.getParent(self.getParent(obj))!=self.geoGrp: geo.append(self.getParent(obj)[0]) geo=list(set(geo)) try: mc.parent(geo, self.geoGrp) except: print "Can't parent %s to %s"%(geo, self.geoGrp) pass #delete non mesh groups in geo group geoChildren=mc.listRelatives(self.geoGrp, c=1) for dag in geoChildren: meshes=None children=mc.listRelatives(dag, c=1) if children: for child in children: if mc.objectType(child)=="mesh": meshes=child if not meshes: mc.delete(dag) else: mc.group(em=1, n=self.geoGrp) mc.parent(mc.listRelatives(mc.ls(type="mesh"), p=1), self.geoGrp) #clean out root and move joints and geo into root if mc.objExists(root)!=1: mc.group(em=1, n=root) else: mc.parent(mc.listRelatives(root, c=1), w=1) mc.parent(self.geoGrp, root) mc.lockNode(self.jntGrp, l=0) mc.parent(self.jntGrp, root) safeList=mc.listRelatives(root, ad=1) safeList.append(root) killList=mc.ls(dag=1) for i in safeList: try: killList.remove(i) except: pass mc.delete(killList)
def _publish_camera(self, item, publish_template, fields, comment, sg_task, primary_publish_path, progress_cb, thumbnail_path): """ Publishes the selected camera """ errors = [] print "<publish> publish camera called" # set publish path and publish name based on publish template and item name respectively. fields['name'] = item['name'].replace(":", "_") secondary_publish_path = publish_template.apply_fields(fields) secondary_publish_name = fields.get( "name").upper() # we want an uppercase name if not secondary_publish_name: secondary_publish_name = os.path.basename(secondary_publish_path) print "<publish> using name for publish: %s" % secondary_publish_name # check if camera has already been published. if os.path.exists(secondary_publish_path): print "<publish> The published camera named '%s' already exists!" % secondary_publish_path errors.append("The published camera named '%s' already exists!" % secondary_publish_path) return errors # select the camera try: cmds.select(item['name'], visible=True, hierarchy=True, replace=True) print "<publish> selected %s" % item['name'] except ValueError as e: errors.append('Unable to select camera [%s]' % item['name']) return errors # find the animated frame range to use: start_frame, end_frame = self._find_scene_animation_range() # bake out camera if grouped if not cmds.listRelatives(item['name'], allParents=True) is None: dup_name = self._bake_camera(item, start_frame, end_frame) else: dup_name = item['name'] self._unlock_camera(dup_name) if not cmds.getAttr(''.join([dup_name, '.sx'])) == 1: cmds.setAttr(''.join([dup_name, '.sx']), 1) cmds.setAttr(''.join([dup_name, '.sy']), 1) cmds.setAttr(''.join([dup_name, '.sz']), 1) alembic_args_string = ''.join(["-root |", dup_name]) alembic_args = [alembic_args_string] if start_frame and end_frame: alembic_args.append("-fr %d %d" % (start_frame, end_frame)) # Set the output path: # Note: The AbcExport command expects forward slashes! alembic_args.append("-file %s" % secondary_publish_path.replace("\\", "/")) # build the export command. Note, use AbcExport -help in Maya for # more detailed Alembic export help abc_export_cmd = ("AbcExport -j \"%s\"" % " ".join(alembic_args)) # ...and execute it: progress_cb(30, "Exporting Alembic cache") try: self.parent.log_debug("Executing command: %s" % abc_export_cmd) mel.eval(abc_export_cmd) except Exception, e: raise TankError("Failed to export Alembic Cache: %s" % e)
def sqCreateStickyLipsCtrlAttr(self, *args): if not cmds.objExists(self.optionCtrl): cmds.circle(name=self.optionCtrl, constructionHistory=False) cmds.addAttr(self.optionCtrl, longName='stickyLips', attributeType='bool') cmds.setAttr(self.optionCtrl + '.stickyLips', edit=True, keyable=True) for i in range(0, self.maxIter): cmds.addAttr(self.optionCtrl, longName="stickyLipsWireLocator" + str(i), attributeType='float', keyable=False) for i in range(0, self.maxIter): for wireNode in self.wireNodeList: cmds.connectAttr( self.optionCtrl + ".stickyLipsWireLocator" + str(i), wireNode + ".wireLocatorEnvelope[" + str(i) + "]") slTextCurve = cmds.textCurves(ch=False, font="Arial|w400|h-08", text="StickyLips", name="StickyLips_Label_Txt")[0] if "Shape" in slTextCurve: slTextCurve = cmds.rename(slTextCurve, slTextCurve[:slTextCurve.find("Shape")]) t = 0 slCharTransformList = cmds.listRelatives(slTextCurve, children=True, type="transform") for charTransform in slCharTransformList: txValue = cmds.getAttr(charTransform + ".tx") sLTextShapeList = cmds.listRelatives(charTransform, allDescendents=True, type="nurbsCurve") for i, textShape in enumerate(sLTextShapeList): textShape = cmds.rename(textShape, "StickyLips_Txt_" + str(t) + "Shape") cmds.parent(textShape, slTextCurve, shape=True, relative=True) cmds.move(txValue, 0, 0, textShape + ".cv[:]", relative=True) t = t + 1 cmds.delete(charTransform) cmds.setAttr(slTextCurve + ".translateX", -0.1) cmds.setAttr(slTextCurve + ".translateY", 0.25) cmds.setAttr(slTextCurve + ".scaleX", 0.1) cmds.setAttr(slTextCurve + ".scaleY", 0.1) cmds.setAttr(slTextCurve + ".scaleZ", 0.1) cmds.setAttr(slTextCurve + ".template", 1) cmds.makeIdentity(slTextCurve, apply=True) sideNameList = ["L", "R"] for side in sideNameList: bg = cmds.circle(name=side + "_StickyLips_Bg", normal=(0, 0, 1), radius=1, degree=1, sections=4, constructionHistory=False)[0] cmds.setAttr(bg + ".rotateZ", 45) cmds.setAttr(bg + ".translateX", 0.5) cmds.makeIdentity(bg, apply=True) cmds.setAttr(bg + ".scaleX", 0.85) cmds.setAttr(bg + ".scaleY", 0.15) cmds.makeIdentity(bg, apply=True) cmds.setAttr(bg + ".template", 1) self.sliderCtrl = cmds.circle(name=side + "_StickyLips_Ctrl", normal=(0, 0, 1), radius=0.1, degree=3, constructionHistory=False)[0] attrToHideList = [ 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'v' ] for attr in attrToHideList: cmds.setAttr(self.sliderCtrl + "." + attr, edit=True, lock=True, keyable=False) cmds.transformLimits(self.sliderCtrl, translationX=(0, 1), enableTranslationX=(1, 1)) distPos = 1.0 / self.maxIter for i in range(0, self.maxIter): lPosA = (i * distPos) lPosB = (lPosA + distPos) rPosB = 1 - (i * distPos) rPosA = (rPosB - distPos) if i > 0: lPosA = lPosA - (distPos * 0.33) rPosA = rPosA - (distPos * 0.33) cmds.setDrivenKeyframe(self.optionCtrl, attribute="stickyLipsWireLocator" + str(i), currentDriver=sideNameList[0] + "_StickyLips_Ctrl.translateX", driverValue=lPosA, value=0, inTangentType="linear", outTangentType="linear") cmds.setDrivenKeyframe(self.optionCtrl, attribute="stickyLipsWireLocator" + str(i), currentDriver=sideNameList[0] + "_StickyLips_Ctrl.translateX", driverValue=lPosB, value=1, inTangentType="linear", outTangentType="linear") cmds.setDrivenKeyframe(self.optionCtrl, attribute="stickyLipsWireLocator" + str(i), currentDriver=sideNameList[1] + "_StickyLips_Ctrl.translateX", driverValue=rPosA, value=0, inTangentType="linear", outTangentType="linear") cmds.setDrivenKeyframe(self.optionCtrl, attribute="stickyLipsWireLocator" + str(i), currentDriver=sideNameList[1] + "_StickyLips_Ctrl.translateX", driverValue=rPosB, value=1, inTangentType="linear", outTangentType="linear") lSliderGrp = cmds.group(sideNameList[0] + "_StickyLips_Ctrl", sideNameList[0] + "_StickyLips_Bg", name=sideNameList[0] + "_StickyLips_Ctrl_Grp") rSliderGrp = cmds.group(sideNameList[1] + "_StickyLips_Ctrl", sideNameList[1] + "_StickyLips_Bg", name=sideNameList[1] + "_StickyLips_Ctrl_Grp") cmds.setAttr(rSliderGrp + ".rotateZ", 180) cmds.setAttr(rSliderGrp + ".translateY", -0.25) sliderGrp = cmds.group(lSliderGrp, rSliderGrp, slTextCurve, name="StickyLips_Ctrl_Grp")
def setPublishPose(rig, con): ###create pub group #query parent pnt = cmds.listRelatives(con, p=True)[0] pub_nul = '' #name sort if cmds.attributeQuery('publishPose', node='rig_GRP', ex=True) is False: cmds.addAttr(rig, k=True, ln='publishPose', at='double', min=0, max=1, dv=0) cmds.setAttr(rig + '.publishPose', 1) pub_nul = cmds.group(con, n=con.replace('_CON', 'PublishPose_NUL')) cmds.xform(pub_nul, os=True, rp=(0, 0, 0)) ###end create pub group ###set pub pose # loc = cmds.spaceLocator(n=con.replace('_CON', 'PubPose_LOC'))[0] pbd = cmds.createNode('pairBlend') cmds.setAttr(pbd + '.rotInterpolation', 1) prefix = con.split('_')[0] if 'IK_foot' in con: pos1 = cmds.xform(prefix + '_IK_leg_JNT', q=True, rp=True, ws=True) pos2 = cmds.xform(prefix + '_IK_lowLeg_JNT', q=True, rp=True, ws=True) pos3 = cmds.xform(prefix + '_IK_foot_JNT', q=True, rp=True, ws=True) dis1 = abs( math.sqrt( math.pow(pos1[0] - pos2[0], 2) + math.pow(pos1[1] - pos2[1], 2) + math.pow(pos1[2] - pos2[2], 2))) dis2 = abs( math.sqrt( math.pow(pos2[0] - pos3[0], 2) + math.pow(pos2[1] - pos3[1], 2) + math.pow(pos2[2] - pos3[2], 2))) distance = dis1 + dis2 cmds.delete(cmds.pointConstraint(prefix + '_IK_leg_JNT', loc, w=True)) if 'Vec' in con: cmds.move(0, distance * -0.5, 5, loc, r=True) pbd = cmds.listConnections( con.replace('_CON', 'Space_NUL') + '.t')[0] dcm1 = cmds.listConnections(pbd + '.inTranslate1')[0] dcm2 = cmds.listConnections(pbd + '.inTranslate2')[0] mmx1 = cmds.listConnections(dcm1 + '.inputMatrix')[0] mmx2 = cmds.listConnections(dcm2 + '.inputMatrix')[0] loc1 = cmds.listConnections(mmx1 + '.matrixIn[0]')[0] loc2 = cmds.listConnections(mmx2 + '.matrixIn[0]')[0] t1 = cmds.getAttr(loc1 + '.t')[0] cmds.delete(cmds.parentConstraint(loc, loc1, w=True)) t2 = cmds.getAttr(loc1 + '.t')[0] pbd = cmds.createNode('pairBlend') cmds.setAttr(pbd + '.inTranslate1', t1[0], t1[1], t1[2]) cmds.setAttr(pbd + '.inTranslate2', t2[0], t2[1], t2[2]) cmds.connectAttr(pbd + '.outTranslate', loc1 + '.t', f=True) cmds.connectAttr(rig + '.publishPose', pbd + '.weight', f=True) cmds.setAttr(loc1 + '.t', t1[0], t1[1], t1[2]) t1 = cmds.getAttr(loc2 + '.t')[0] cmds.delete(cmds.parentConstraint(loc, loc2, w=True)) t2 = cmds.getAttr(loc2 + '.t')[0] pbd = cmds.createNode('pairBlend') cmds.setAttr(pbd + '.inTranslate1', t1[0], t1[1], t1[2]) cmds.setAttr(pbd + '.inTranslate2', t2[0], t2[1], t2[2]) cmds.connectAttr(pbd + '.outTranslate', loc2 + '.t', f=True) cmds.connectAttr(rig + '.publishPose', pbd + '.weight', f=True) cmds.setAttr(loc2 + '.t', t1[0], t1[1], t1[2]) cmds.delete(cmds.parentConstraint(loc, con, w=True)) cmds.setAttr(con + '.t', 0, 0, 0) else: cmds.delete(cmds.pointConstraint(con, loc, w=True, skip=('x', 'z'))) t1 = cmds.getAttr(con + '.t')[0] cmds.delete(cmds.pointConstraint(loc, con, w=True)) t2 = cmds.getAttr(con + '.t')[0] pbd = cmds.createNode('pairBlend') cmds.setAttr(pbd + '.inTranslate1', t1[0], t1[1], t1[2]) cmds.setAttr(pbd + '.inTranslate2', t2[0], t2[1], t2[2]) cmds.connectAttr(pbd + '.outTranslate', pub_nul + '.t', f=True) cmds.connectAttr(rig + '.publishPose', pbd + '.weight', f=True) cmds.setAttr(con + '.t', t1[0], t1[1], t1[2]) if 'root' in con: pos0 = cmds.xform(con, q=True, rp=True, ws=True) pos1 = cmds.xform('L_IK_leg_JNT', q=True, rp=True, ws=True) pos2 = cmds.xform('L_IK_lowLeg_JNT', q=True, rp=True, ws=True) pos3 = cmds.xform('L_IK_foot_JNT', q=True, rp=True, ws=True) pos4 = cmds.xform('L_IK_ball_JNT', q=True, rp=True, ws=True) dis1 = abs( math.sqrt( math.pow(pos1[0] - pos1[0], 2) + math.pow(pos0[1] - pos1[1], 2) + math.pow(pos1[2] - pos1[2], 2))) dis2 = abs( math.sqrt( math.pow(pos1[0] - pos2[0], 2) + math.pow(pos1[1] - pos2[1], 2) + math.pow(pos1[2] - pos2[2], 2))) dis3 = abs( math.sqrt( math.pow(pos2[0] - pos3[0], 2) + math.pow(pos2[1] - pos3[1], 2) + math.pow(pos2[2] - pos3[2], 2))) dis4 = abs( math.sqrt( math.pow(pos3[0] - pos3[0], 2) + math.pow(pos3[1] - pos4[1], 2) + math.pow(pos3[2] - pos3[2], 2))) dis5 = abs( math.sqrt( math.pow(pos1[0] - pos3[0], 2) + math.pow(pos1[1] - pos3[1], 2) + math.pow(pos1[2] - pos3[2], 2))) distance = dis1 + dis2 + dis3 + dis4 * 0.95 cmds.setAttr(loc + '.t', 0, distance, 0) t1 = cmds.getAttr(con + '.t')[0] r1 = cmds.getAttr(con + '.r')[0] cmds.delete(cmds.parentConstraint(loc, con, w=True)) t2 = cmds.getAttr(con + '.t')[0] r2 = cmds.getAttr(con + '.r')[0] pbd = cmds.createNode('pairBlend') cmds.setAttr(pbd + '.inTranslate1', t1[0], t1[1], t1[2]) cmds.setAttr(pbd + '.inTranslate2', t2[0], t2[1], t2[2]) cmds.setAttr(pbd + '.inRotate1', r1[0], r1[1], r1[2]) cmds.setAttr(pbd + '.inRotate2', r2[0], r2[1], r2[2]) cmds.connectAttr(pbd + '.outTranslate', pub_nul + '.t', f=True) cmds.connectAttr(pbd + '.outRotate', pub_nul + '.r', f=True) cmds.connectAttr(rig + '.publishPose', pbd + '.weight', f=True) cmds.setAttr(con + '.t', t1[0], t1[1], t1[2]) cmds.setAttr(con + '.r', r1[0], r1[1], r1[2]) if 'Body' in con: pos1 = cmds.xform(con, q=True, rp=True, ws=True) pos2 = cmds.xform('root_CON', q=True, rp=True, ws=True) distance = abs( math.sqrt( math.pow(pos1[0] - pos2[0], 2) + math.pow(pos1[1] - pos2[1], 2) + math.pow(pos1[2] - pos2[2], 2))) cmds.delete( cmds.pointConstraint('root_CON', loc, w=True, offset=(0, distance, 0))) t1 = cmds.getAttr(con + '.t')[0] r1 = cmds.getAttr(con + '.r')[0] cmds.delete(cmds.parentConstraint(loc, con, w=True)) t2 = cmds.getAttr(con + '.t')[0] r2 = cmds.getAttr(con + '.r')[0] pbd = cmds.createNode('pairBlend') cmds.setAttr(pbd + '.inTranslate1', t1[0], t1[1], t1[2]) cmds.setAttr(pbd + '.inTranslate2', t2[0], t2[1], t2[2]) cmds.setAttr(pbd + '.inRotate1', r1[0], r1[1], r1[2]) cmds.setAttr(pbd + '.inRotate2', r2[0], r2[1], r2[2]) cmds.connectAttr(pbd + '.outTranslate', pub_nul + '.t', f=True) cmds.connectAttr(pbd + '.outRotate', pub_nul + '.r', f=True) cmds.connectAttr(rig + '.publishPose', pbd + '.weight', f=True) cmds.setAttr(con + '.t', t1[0], t1[1], t1[2]) cmds.setAttr(con + '.r', r1[0], r1[1], r1[2]) if 'hip' in con: pos1 = cmds.xform(con, q=True, rp=True, ws=True) pos2 = cmds.xform('root_CON', q=True, rp=True, ws=True) distance = abs( math.sqrt( math.pow(pos1[0] - pos2[0], 2) + math.pow(pos1[1] - pos2[1], 2) + math.pow(pos1[2] - pos2[2], 2))) cmds.delete( cmds.pointConstraint('root_CON', loc, w=True, offset=(0, distance * -1, 0))) t1 = cmds.getAttr(con + '.t')[0] r1 = cmds.getAttr(con + '.r')[0] cmds.delete(cmds.parentConstraint(loc, con, w=True)) t2 = cmds.getAttr(con + '.t')[0] r2 = cmds.getAttr(con + '.r')[0] pbd = cmds.createNode('pairBlend') cmds.setAttr(pbd + '.inTranslate1', t1[0], t1[1], t1[2]) cmds.setAttr(pbd + '.inTranslate2', t2[0], t2[1], t2[2]) cmds.setAttr(pbd + '.inRotate1', r1[0], r1[1], r1[2]) cmds.setAttr(pbd + '.inRotate2', r2[0], r2[1], r2[2]) cmds.connectAttr(pbd + '.outTranslate', pub_nul + '.t', f=True) cmds.connectAttr(pbd + '.outRotate', pub_nul + '.r', f=True) cmds.connectAttr(rig + '.publishPose', pbd + '.weight', f=True) cmds.setAttr(con + '.t', t1[0], t1[1], t1[2]) cmds.setAttr(con + '.r', r1[0], r1[1], r1[2]) if 'head' in con: r1 = cmds.getAttr(con + '.r')[0] cmds.delete(cmds.orientConstraint(loc, con, w=True)) r2 = cmds.getAttr(con + '.r')[0] pbd = cmds.createNode('pairBlend') cmds.setAttr(pbd + '.inRotate1', r1[0], r1[1], r1[2]) cmds.setAttr(pbd + '.inRotate2', r2[0], r2[1], r2[2]) cmds.connectAttr(pbd + '.outRotate', pub_nul + '.r', f=True) cmds.connectAttr(rig + '.publishPose', pbd + '.weight', f=True) cmds.setAttr(con + '.r', r1[0], r1[1], r1[2]) if 'FK_leg' in con: cmds.delete(cmds.orientConstraint(prefix + '_IK_leg_JNT', loc, w=True)) r1 = cmds.getAttr(con + '.r')[0] cmds.delete(cmds.orientConstraint(loc, con, w=True)) r2 = cmds.getAttr(con + '.r')[0] pbd = cmds.createNode('pairBlend') cmds.setAttr(pbd + '.inRotate1', r1[0], r1[1], r1[2]) cmds.setAttr(pbd + '.inRotate2', r2[0], r2[1], r2[2]) cmds.connectAttr(pbd + '.outRotate', pub_nul + '.r', f=True) cmds.connectAttr(rig + '.publishPose', pbd + '.weight', f=True) cmds.setAttr(con + '.r', r1[0], r1[1], r1[2]) if 'FK_lowLeg' in con: cmds.delete( cmds.orientConstraint(prefix + '_IK_lowLeg_JNT', loc, w=True)) r1 = cmds.getAttr(con + '.r')[0] cmds.delete(cmds.orientConstraint(loc, con, w=True)) r2 = cmds.getAttr(con + '.r')[0] pbd = cmds.createNode('pairBlend') cmds.setAttr(pbd + '.inRotate1', r1[0], r1[1], r1[2]) cmds.setAttr(pbd + '.inRotate2', r2[0], r2[1], r2[2]) cmds.connectAttr(pbd + '.outRotate', pub_nul + '.r', f=True) cmds.connectAttr(rig + '.publishPose', pbd + '.weight', f=True) cmds.setAttr(con + '.r', r1[0], r1[1], r1[2]) if 'FK_foot' in con: cmds.delete(cmds.orientConstraint(prefix + '_IK_foot_JNT', loc, w=True)) r1 = cmds.getAttr(con + '.r')[0] cmds.delete(cmds.orientConstraint(loc, con, w=True)) r2 = cmds.getAttr(con + '.r')[0] pbd = cmds.createNode('pairBlend') cmds.setAttr(pbd + '.inRotate1', r1[0], r1[1], r1[2]) cmds.setAttr(pbd + '.inRotate2', r2[0], r2[1], r2[2]) cmds.connectAttr(pbd + '.outRotate', pub_nul + '.r', f=True) cmds.connectAttr(rig + '.publishPose', pbd + '.weight', f=True) cmds.setAttr(con + '.r', r1[0], r1[1], r1[2]) if 'FK_upArm' in con: if 'L' in prefix: cmds.setAttr(loc + '.r', 0, 5, 0) r1 = cmds.getAttr(con + '.r')[0] cmds.delete(cmds.orientConstraint(loc, con, w=True)) r2 = cmds.getAttr(con + '.r')[0] pbd = cmds.createNode('pairBlend') cmds.setAttr(pbd + '.inRotate1', r1[0], r1[1], r1[2]) cmds.setAttr(pbd + '.inRotate2', r2[0], r2[1], r2[2]) cmds.connectAttr(pbd + '.outRotate', pub_nul + '.r', f=True) cmds.connectAttr(rig + '.publishPose', pbd + '.weight', f=True) cmds.setAttr(con + '.r', r1[0], r1[1], r1[2]) if 'R' in prefix: cmds.setAttr(loc + '.r', -180, -5, 0) r1 = cmds.getAttr(con + '.r')[0] cmds.delete(cmds.orientConstraint(loc, con, w=True)) r2 = cmds.getAttr(con + '.r')[0] pbd = cmds.createNode('pairBlend') cmds.setAttr(pbd + '.inRotate1', r1[0], r1[1], r1[2]) cmds.setAttr(pbd + '.inRotate2', r2[0], r2[1], r2[2]) cmds.connectAttr(pbd + '.outRotate', pub_nul + '.r', f=True) cmds.connectAttr(rig + '.publishPose', pbd + '.weight', f=True) cmds.setAttr(con + '.r', r1[0], r1[1], r1[2]) if 'FK_foreArm' in con: if 'L' in prefix: cmds.setAttr(loc + '.r', 0, -5, 0) r1 = cmds.getAttr(con + '.r')[0] cmds.delete(cmds.orientConstraint(loc, con, w=True)) r2 = cmds.getAttr(con + '.r')[0] pbd = cmds.createNode('pairBlend') cmds.setAttr(pbd + '.inRotate1', r1[0], r1[1], r1[2]) cmds.setAttr(pbd + '.inRotate2', r2[0], r2[1], r2[2]) cmds.connectAttr(pbd + '.outRotate', pub_nul + '.r', f=True) cmds.connectAttr(rig + '.publishPose', pbd + '.weight', f=True) cmds.setAttr(con + '.r', r1[0], r1[1], r1[2]) if 'R' in prefix: cmds.setAttr(loc + '.r', -180, 5, 0) r1 = cmds.getAttr(con + '.r')[0] cmds.delete(cmds.orientConstraint(loc, con, w=True)) r2 = cmds.getAttr(con + '.r')[0] pbd = cmds.createNode('pairBlend') cmds.setAttr(pbd + '.inRotate1', r1[0], r1[1], r1[2]) cmds.setAttr(pbd + '.inRotate2', r2[0], r2[1], r2[2]) cmds.connectAttr(pbd + '.outRotate', pub_nul + '.r', f=True) cmds.connectAttr(rig + '.publishPose', pbd + '.weight', f=True) cmds.setAttr(con + '.r', r1[0], r1[1], r1[2]) if 'FK_hand' in con: if 'L' in prefix: cmds.setAttr(loc + '.r', 0, -5, 0) r1 = cmds.getAttr(con + '.r')[0] cmds.delete(cmds.orientConstraint(loc, con, w=True)) r2 = cmds.getAttr(con + '.r')[0] pbd = cmds.createNode('pairBlend') cmds.setAttr(pbd + '.inRotate1', r1[0], r1[1], r1[2]) cmds.setAttr(pbd + '.inRotate2', r2[0], r2[1], r2[2]) cmds.connectAttr(pbd + '.outRotate', pub_nul + '.r', f=True) cmds.connectAttr(rig + '.publishPose', pbd + '.weight', f=True) cmds.setAttr(con + '.r', r1[0], r1[1], r1[2]) if 'R' in prefix: cmds.setAttr(loc + '.r', -180, 5, 0) r1 = cmds.getAttr(con + '.r')[0] cmds.delete(cmds.orientConstraint(loc, con, w=True)) r2 = cmds.getAttr(con + '.r')[0] pbd = cmds.createNode('pairBlend') cmds.setAttr(pbd + '.inRotate1', r1[0], r1[1], r1[2]) cmds.setAttr(pbd + '.inRotate2', r2[0], r2[1], r2[2]) cmds.connectAttr(pbd + '.outRotate', pub_nul + '.r', f=True) cmds.connectAttr(rig + '.publishPose', pbd + '.weight', f=True) cmds.setAttr(con + '.r', r1[0], r1[1], r1[2]) if 'IK_hand' in con: if 'Vec' in con: cmds.delete( cmds.parentConstraint(prefix + '_FK_foreArm_CON', loc, w=True)) pbd = cmds.listConnections( con.replace('_CON', 'Space_NUL') + '.t')[0] dcm1 = cmds.listConnections(pbd + '.inTranslate1')[0] dcm2 = cmds.listConnections(pbd + '.inTranslate2')[0] mmx1 = cmds.listConnections(dcm1 + '.inputMatrix')[0] mmx2 = cmds.listConnections(dcm2 + '.inputMatrix')[0] loc1 = cmds.listConnections(mmx1 + '.matrixIn[0]')[0] loc2 = cmds.listConnections(mmx2 + '.matrixIn[0]')[0] t1 = cmds.getAttr(loc1 + '.t')[0] cmds.delete(cmds.parentConstraint(loc, loc1, w=True)) cmds.move(0, 0, -2.5, loc1, r=True) t2 = cmds.getAttr(loc1 + '.t')[0] pbd = cmds.createNode('pairBlend') cmds.setAttr(pbd + '.inTranslate1', t1[0], t1[1], t1[2]) cmds.setAttr(pbd + '.inTranslate2', t2[0], t2[1], t2[2]) cmds.connectAttr(pbd + '.outTranslate', loc1 + '.t', f=True) cmds.connectAttr(rig + '.publishPose', pbd + '.weight', f=True) cmds.setAttr(loc1 + '.t', t1[0], t1[1], t1[2]) t1 = cmds.getAttr(loc2 + '.t')[0] cmds.delete(cmds.parentConstraint(loc, loc2, w=True)) cmds.move(0, 0, -2.5, loc2, r=True) t2 = cmds.getAttr(loc2 + '.t')[0] pbd = cmds.createNode('pairBlend') cmds.setAttr(pbd + '.inTranslate1', t1[0], t1[1], t1[2]) cmds.setAttr(pbd + '.inTranslate2', t2[0], t2[1], t2[2]) cmds.connectAttr(pbd + '.outTranslate', loc2 + '.t', f=True) cmds.connectAttr(rig + '.publishPose', pbd + '.weight', f=True) cmds.setAttr(loc2 + '.t', t1[0], t1[1], t1[2]) cmds.setAttr(con + '.t', 0, 0, 0) else: cmds.delete( cmds.parentConstraint(prefix + '_FK_hand_CON', loc, w=True)) t1 = cmds.getAttr(con + '.t')[0] cmds.delete(cmds.pointConstraint(loc, con, w=True)) t2 = cmds.getAttr(con + '.t')[0] pbd = cmds.createNode('pairBlend') cmds.setAttr(pbd + '.inTranslate1', t1[0], t1[1], t1[2]) cmds.setAttr(pbd + '.inTranslate2', t2[0], t2[1], t2[2]) cmds.connectAttr(pbd + '.outTranslate', pub_nul + '.t', f=True) cmds.connectAttr(rig + '.publishPose', pbd + '.weight', f=True) cmds.setAttr(con + '.t', t1[0], t1[1], t1[2]) if 'Sub' in con: r1 = cmds.getAttr(con + '.r')[0] cmds.delete(cmds.orientConstraint(loc, con, w=True)) r2 = cmds.getAttr(con + '.r')[0] pbd = cmds.createNode('pairBlend') cmds.setAttr(pbd + '.inRotate1', r1[0], r1[1], r1[2]) cmds.setAttr(pbd + '.inRotate2', r2[0], r2[1], r2[2]) cmds.connectAttr(pbd + '.outRotate', pub_nul + '.r', f=True) cmds.connectAttr(rig + '.publishPose', pbd + '.weight', f=True) cmds.setAttr(con + '.r', r1[0], r1[1], r1[2]) if 'thumb' in con: if 'L' in prefix: cmds.setAttr(loc + '.r', 80, -30, -30) r1 = cmds.getAttr(con + '.r')[0] cmds.delete(cmds.orientConstraint(loc, con, w=True)) r2 = cmds.getAttr(con + '.r')[0] pbd = cmds.createNode('pairBlend') cmds.setAttr(pbd + '.inRotate1', r1[0], r1[1], r1[2]) cmds.setAttr(pbd + '.inRotate2', r2[0], r2[1], r2[2]) cmds.connectAttr(pbd + '.outRotate', pub_nul + '.r', f=True) cmds.connectAttr(rig + '.publishPose', pbd + '.weight', f=True) cmds.setAttr(con + '.r', r1[0], r1[1], r1[2]) if 'R' in prefix: cmds.setAttr(loc + '.r', -100, 30, 30) r1 = cmds.getAttr(con + '.r')[0] cmds.delete(cmds.orientConstraint(loc, con, w=True)) r2 = cmds.getAttr(con + '.r')[0] pbd = cmds.createNode('pairBlend') cmds.setAttr(pbd + '.inRotate1', r1[0], r1[1], r1[2]) cmds.setAttr(pbd + '.inRotate2', r2[0], r2[1], r2[2]) cmds.connectAttr(pbd + '.outRotate', pub_nul + '.r', f=True) cmds.connectAttr(rig + '.publishPose', pbd + '.weight', f=True) cmds.setAttr(con + '.r', r1[0], r1[1], r1[2]) if 'index' in con: if 'L' in prefix: cmds.setAttr(loc + '.r', 0, -5, 0) r1 = cmds.getAttr(con + '.r')[0] cmds.delete(cmds.orientConstraint(loc, con, w=True)) r2 = cmds.getAttr(con + '.r')[0] pbd = cmds.createNode('pairBlend') cmds.setAttr(pbd + '.inRotate1', r1[0], r1[1], r1[2]) cmds.setAttr(pbd + '.inRotate2', r2[0], r2[1], r2[2]) cmds.connectAttr(pbd + '.outRotate', pub_nul + '.r', f=True) cmds.connectAttr(rig + '.publishPose', pbd + '.weight', f=True) cmds.setAttr(con + '.r', r1[0], r1[1], r1[2]) if 'R' in prefix: cmds.setAttr(loc + '.r', -180, 5, 0) r1 = cmds.getAttr(con + '.r')[0] cmds.delete(cmds.orientConstraint(loc, con, w=True)) r2 = cmds.getAttr(con + '.r')[0] pbd = cmds.createNode('pairBlend') cmds.setAttr(pbd + '.inRotate1', r1[0], r1[1], r1[2]) cmds.setAttr(pbd + '.inRotate2', r2[0], r2[1], r2[2]) cmds.connectAttr(pbd + '.outRotate', pub_nul + '.r', f=True) cmds.connectAttr(rig + '.publishPose', pbd + '.weight', f=True) cmds.setAttr(con + '.r', r1[0], r1[1], r1[2]) if 'middle' in con: if 'L' in prefix: cmds.setAttr(loc + '.r', 0, -5, 0) r1 = cmds.getAttr(con + '.r')[0] cmds.delete(cmds.orientConstraint(loc, con, w=True)) r2 = cmds.getAttr(con + '.r')[0] pbd = cmds.createNode('pairBlend') cmds.setAttr(pbd + '.inRotate1', r1[0], r1[1], r1[2]) cmds.setAttr(pbd + '.inRotate2', r2[0], r2[1], r2[2]) cmds.connectAttr(pbd + '.outRotate', pub_nul + '.r', f=True) cmds.connectAttr(rig + '.publishPose', pbd + '.weight', f=True) cmds.setAttr(con + '.r', r1[0], r1[1], r1[2]) if 'R' in prefix: cmds.setAttr(loc + '.r', -180, 5, 0) r1 = cmds.getAttr(con + '.r')[0] cmds.delete(cmds.orientConstraint(loc, con, w=True)) r2 = cmds.getAttr(con + '.r')[0] pbd = cmds.createNode('pairBlend') cmds.setAttr(pbd + '.inRotate1', r1[0], r1[1], r1[2]) cmds.setAttr(pbd + '.inRotate2', r2[0], r2[1], r2[2]) cmds.connectAttr(pbd + '.outRotate', pub_nul + '.r', f=True) cmds.connectAttr(rig + '.publishPose', pbd + '.weight', f=True) cmds.setAttr(con + '.r', r1[0], r1[1], r1[2]) if 'ring' in con: if 'L' in prefix: cmds.setAttr(loc + '.r', 0, -5, 0) r1 = cmds.getAttr(con + '.r')[0] cmds.delete(cmds.orientConstraint(loc, con, w=True)) r2 = cmds.getAttr(con + '.r')[0] pbd = cmds.createNode('pairBlend') cmds.setAttr(pbd + '.inRotate1', r1[0], r1[1], r1[2]) cmds.setAttr(pbd + '.inRotate2', r2[0], r2[1], r2[2]) cmds.connectAttr(pbd + '.outRotate', pub_nul + '.r', f=True) cmds.connectAttr(rig + '.publishPose', pbd + '.weight', f=True) cmds.setAttr(con + '.r', r1[0], r1[1], r1[2]) if 'R' in prefix: cmds.setAttr(loc + '.r', -180, 5, 0) r1 = cmds.getAttr(con + '.r')[0] cmds.delete(cmds.orientConstraint(loc, con, w=True)) r2 = cmds.getAttr(con + '.r')[0] pbd = cmds.createNode('pairBlend') cmds.setAttr(pbd + '.inRotate1', r1[0], r1[1], r1[2]) cmds.setAttr(pbd + '.inRotate2', r2[0], r2[1], r2[2]) cmds.connectAttr(pbd + '.outRotate', pub_nul + '.r', f=True) cmds.connectAttr(rig + '.publishPose', pbd + '.weight', f=True) cmds.setAttr(con + '.r', r1[0], r1[1], r1[2]) if 'pinky' in con: if 'L' in prefix: cmds.setAttr(loc + '.r', 0, -5, 0) r1 = cmds.getAttr(con + '.r')[0] cmds.delete(cmds.orientConstraint(loc, con, w=True)) r2 = cmds.getAttr(con + '.r')[0] pbd = cmds.createNode('pairBlend') cmds.setAttr(pbd + '.inRotate1', r1[0], r1[1], r1[2]) cmds.setAttr(pbd + '.inRotate2', r2[0], r2[1], r2[2]) cmds.connectAttr(pbd + '.outRotate', pub_nul + '.r', f=True) cmds.connectAttr(rig + '.publishPose', pbd + '.weight', f=True) cmds.setAttr(con + '.r', r1[0], r1[1], r1[2]) if 'R' in prefix: cmds.setAttr(loc + '.r', -180, 5, 0) r1 = cmds.getAttr(con + '.r')[0] cmds.delete(cmds.orientConstraint(loc, con, w=True)) r2 = cmds.getAttr(con + '.r')[0] pbd = cmds.createNode('pairBlend') cmds.setAttr(pbd + '.inRotate1', r1[0], r1[1], r1[2]) cmds.setAttr(pbd + '.inRotate2', r2[0], r2[1], r2[2]) cmds.connectAttr(pbd + '.outRotate', pub_nul + '.r', f=True) cmds.connectAttr(rig + '.publishPose', pbd + '.weight', f=True) cmds.setAttr(con + '.r', r1[0], r1[1], r1[2]) cmds.setAttr('rig_GRP.publishPose', 0) cmds.delete(loc) return
import maya.cmds as cmds sels = cmds.ls(sl=1) for i in range(len(sels) - 1): selP = cmds.listRelatives(sels[i], p=1, f=1) if selP: cmds.parent(selP[0], sels[i + 1]) else: cmds.parent(sels[i], sels[i + 1])
# -*- coding: utf-8 -*- from maya import cmds ctrlShape = cmds.createNode('locator') ctrlTransform = cmds.listRelatives(ctrlShape,p=True,f=True) if isinstance(ctrlTransform,list): ctrlTransform = ctrlTransform[0] jt = cmds.createNode('joint',n='followJoint') attrName = 'follow' if not cmds.attributeQuery(attrName,n=ctrlTransform,ex=True): cmds.addAttr(ctrlTransform,ln=attrName,at='double',min=0.0,max=1.0,dv=0.1) cmds.setAttr('%s.%s'%(ctrlTransform,attrName),e=True,k=True) exp = '{\n\t$tx1 = %s.translateX;\n'%ctrlTransform exp += '\t$ty1 = %s.translateY;\n'%ctrlTransform exp += '\t$tz1 = %s.translateZ;\n'%ctrlTransform exp += '\t$tx2 = %s.translateX;\n'%jt exp += '\t$ty2 = %s.translateY;\n'%jt exp += '\t$tz2 = %s.translateZ;\n'%jt exp += '\t\n\t$f = %s.follow;\n'%ctrlTransform exp += '\t$dx = $tx1;\n' exp += '\t$dy = $ty1;\n' exp += '\t$dz = $tz1;\n' exp += '\tif ($f > 0.0)\n\t{\n\t\t$dx = ($tx1-$tx2)*$f;\n' exp += '\t\t$dy = ($ty1-$ty2)*$f;\n' exp += '\t\t$dz = ($tz1-$tz2)*$f;\n' exp += '\t}\n\t%s.translateX += $dx;\n'%jt exp += '\t%s.translateY += $dy;\n'%jt exp += '\t%s.translateZ += $dz;\n'%jt exp += '}'
def etc_set(self): ### attribute # sup con vis for x in range(8): cmds.addAttr(TP.AA['PL'][x], ln='sub_con_vis', at='enum', en='off:on:') cmds.setAttr(TP.AA['PL'][x] + '.sub_con_vis', e=1, keyable=1) cmds.connectAttr(TP.AA['PL'][x] + '.sub_con_vis', TP.AA['CL'][x] + '.visibility') # FK / IK switch for x in range(2): switchCon = controllerShape(TP.conVis['key'][x][0] + '_CON', 'cross', 'yellow') switchNul = cmds.group(switchCon, n=TP.conVis['key'][x][0] + '_NUL') cmds.delete(cmds.pointConstraint(TP.conVis['key'][x][1], switchNul)) cmds.parent(switchNul, TP.conVis['key'][x][1]) cmds.move(5, 0, 0, ws=1, r=1) cmds.addAttr(switchCon, ln=TP.conVis['attr'][0], at='enum', en='off:on:') cmds.setAttr(switchCon + '.' + TP.conVis['attr'][0], e=1, keyable=1) cmds.addAttr(switchCon, ln=TP.conVis['attr'][1], at='enum', en='off:on:') cmds.setAttr(switchCon + '.' + TP.conVis['attr'][1], e=1, keyable=1) for x in range(2): top_list = TP.conVis['vis'][x] for y in top_list: for z in y: if len(y) == 1: cmds.connectAttr( TP.conVis['key'][x][0] + '_CON.' + TP.conVis['attr'][0], z + '.visibility') else: cmds.connectAttr( TP.conVis['key'][x][0] + '_CON.' + TP.conVis['attr'][1], z + '.visibility') cmds.setAttr(TP.conVis['key'][x][0] + '_CON.IK_con_vis', 1) ### Parent node cmds.group(p='noneTransform_GRP', em=1, n='locator_GRP') cmds.parent(TP.noneTrans_list, 'locator_GRP') cmds.parent(TP.attach_list, 'attach_GRP') cmds.parent(TP.auxillary_list, 'auxillary_GRP') cmds.parent(TP.neck_list, 'C_neck_GRP') cmds.parent(TP.spine_list, 'C_spine_GRP') cmds.parent(TP.L_foreLeg_list, 'L_foreLeg_GRP') cmds.parent(TP.R_foreLeg_list, 'R_foreLeg_GRP') cmds.parent(TP.L_hindLeg_list, 'L_hindLeg_GRP') cmds.parent(TP.R_hindLeg_list, 'R_hindLeg_GRP') cmds.parent(TP.tail_list, 'C_tail_GRP') cmds.delete(TP.delete_list) cmds.select(TP.noneTrans_list, r=1) cmds.select('templateJoint_GRP', tgl=1) cmds.select(TP.hide_list, tgl=1) cmds.select(TP.hide_list2, tgl=1) cmds.HideSelectedObjects() ### Rotate controler self.controlerRotate(TP.rotate_con_list_A, 0, 0, -90) self.controlerRotate(TP.rotate_con_list_B, -90, 0, 0) ### controler Color for x in TP.R_con_list: conShapeName = cmds.listRelatives(x, s=1)[0] cmds.setAttr(conShapeName + '.overrideEnabled', 1) cmds.setAttr(conShapeName + '.overrideColor', 13) for x in TP.switch_con_list: conShapeName = cmds.listRelatives(x, s=1)[0] cmds.setAttr(conShapeName + '.overrideEnabled', 1) cmds.setAttr(conShapeName + '.overrideColor', 14) ### controler Scale for x in TP.scale_con_list: scale_value = 2 CRV_shape_name = cmds.listRelatives(x, s=1)[0] CRV_span_num = cmds.getAttr(CRV_shape_name + '.spans') cmds.select(x + '.cv[0:%s]' % (CRV_span_num)) cmds.scale(scale_value, scale_value, scale_value, r=1) ### controler Parent for x in range(2): PL = TP.parent_list['PL'][x] for y in TP.parent_list['CL'][x]: cmds.parentConstraint(PL, y, mo=1) ### hindLeg Parent cmds.setAttr('L_rig_hip_JNT.inheritsTransform', 0) cmds.setAttr('R_rig_hip_JNT.inheritsTransform', 0) itemList = ['.sx', '.sy', '.sz'] for x in TP.targetjointList: for y in itemList: cmds.connectAttr('place_CON.globalScale', x + y)
def poleVector(pvGuide, jnt, module, extraName, limbType, moduleName, limbIK, arrow=False, parent=None): """ Create a polevector control for an ik handle. [Args]: pvGuide (string) - The name of the poleVector guide locator jnt (string) - The name of the joint to aim at module (class) - The limb module class extraName (string) - The extra name of the module limbType (string) - The name of the limb type moduleName (string) - The module name limbIK (class) - The ik class arrow (bool) - Toggles creating an arrow from the start of the joint chain instead """ col = utils.getColors(module.side) cmds.delete(cmds.aimConstraint(jnt, pvGuide)) if not arrow: module.pvCtrl = ctrlFn.ctrl(name='{}{}PV'.format(extraName, limbType), side=module.side, guide=pvGuide, skipNum=True, deleteGuide=True, parent=module.ikCtrlGrp.name, scaleOffset=module.rig.scaleOffset, rig=module.rig) module.pvCtrl.modifyShape(shape='3dArrow', color=col['col1'], rotation=(0, 180, 0), scale=(0.4, 0.4, 0.4)) module.pvCtrl.lockAttr(['r', 's']) module.pvCtrl.constrain(limbIK.hdl, typ='poleVector') module.pvCtrl.spaceSwitching( [module.rig.globalCtrl.ctrlEnd, module.ikCtrl.ctrlEnd]) pvCrv = cmds.curve(d=1, p=[ cmds.xform(module.pvCtrl.ctrl.name, q=1, ws=1, t=1), cmds.xform(jnt, q=1, ws=1, t=1) ]) cmds.setAttr('{}.it'.format(pvCrv), 0) cmds.parent(pvCrv, module.pvCtrl.offsetGrps[0].name, r=1) pvCrv = cmds.rename( pvCrv, '{}{}PVLine{}'.format(moduleName, limbType, suffix['nurbsCrv'])) cmds.setAttr('{}Shape.overrideEnabled'.format(pvCrv), 1) cmds.setAttr('{}Shape.overrideDisplayType'.format(pvCrv), 1) cmds.select(cl=1) cmds.select('{}.cv[1]'.format(pvCrv)) pvJntCluHdl = utils.newNode('cluster', name='{}{}PVJnt'.format( extraName, limbType), side=module.side, parent=jnt) cmds.select('{}.cv[0]'.format(pvCrv)) pvCtrlCluHdl = utils.newNode('cluster', name='{}{}PVCtrl'.format( extraName, limbType), side=module.side, parent=module.pvCtrl.ctrlEnd) utils.setColor(pvJntCluHdl.name, color=None) utils.setColor(pvCtrlCluHdl.name, color=None) else: ikStartJnt = cmds.listRelatives(jnt, p=1)[0] module.pvCtrl = ctrlFn.ctrl(name='{}{}PV'.format(extraName, limbType), side=module.side, guide=ikStartJnt, skipNum=True, parent=module.ikCtrlGrp.name, scaleOffset=module.rig.scaleOffset, rig=module.rig) module.pvCtrl.modifyShape(shape='pvArrow', color=col['col2'], scale=(0.4, 0.4, 0.4)) module.pvCtrl.lockAttr(['t', 's', 'rx']) cmds.delete(cmds.aimConstraint(pvGuide, module.pvCtrl.rootGrp.name)) if parent: cmds.parentConstraint(parent, module.pvCtrl.rootGrp.name, mo=1) cmds.parent(pvGuide, module.pvCtrl.ctrlEnd) cmds.poleVectorConstraint(pvGuide, limbIK.hdl) utils.setShapeColor(pvGuide, color=None)
def groundConstraint(mesh, obj): name = mesh + '_' + obj # 1 create a CPOM node and connect input # ############################################################ # create input position locator and closest point locator: pos = cmd.xform(obj, q=True, translation=True, ws=True) colLoc = cmd.spaceLocator(n=name + '_collisionLoc')[0] cmd.xform(colLoc, translation=pos, ws=True) ctrlLoc = cmd.spaceLocator(n=name + '_ctrlLoc', p=pos)[0] cmd.xform(ctrlLoc, cp=True) cmd.parent(colLoc, ctrlLoc) # closest point on mesh node: CPOM = cmd.shadingNode('closestPointOnMesh', asUtility=True, n=name + '_CPOM') # connect ground mesh to CPOM meshShape = cmd.listRelatives(mesh, shapes=True)[0] cmd.connectAttr(meshShape + '.worldMesh[0]', CPOM + '.inMesh') cmd.connectAttr(meshShape + '.worldMatrix[0]', CPOM + '.inputMatrix') # connect ctrl locator and collision locator to CPOM # decompose ctrlLoc if cmd.pluginInfo('decomposeMatrix', q=True, loaded=True) == False: cmd.loadPlugin('decomposeMatrix') colLocDM = cmd.shadingNode('decomposeMatrix', asUtility=True, n=colLoc + '_decomposeMatrix') cmd.connectAttr(colLoc + '.worldMatrix', colLocDM + '.inputMatrix') cmd.connectAttr(colLocDM + '.outputTranslate', CPOM + '.inPosition') # ############################################################ # 2, fix rotation: make obj rotates on surface: normal constraint ############################################################# # create vector product nodes: ax_x = cmd.shadingNode('vectorProduct', asUtility=True, n=name + 'ax_x') ax_z = cmd.shadingNode('vectorProduct', asUtility=True, n=name + 'ax_z') for node in [ax_x, ax_z]: cmd.setAttr(node + '.operation', 2) #cross product cmd.setAttr(node + '.normalizeOutput', 1) #normalize output # normal from CPOM --> vector product nodes cmd.setAttr(ax_z + '.input1X', 1) cmd.connectAttr(CPOM + '.result.normal', ax_z + '.input2') cmd.connectAttr(CPOM + '.result.normal', ax_x + '.input1') cmd.connectAttr(ax_z + '.output', ax_x + '.input2') # create a 4X4 matrix fourbyfour = cmd.shadingNode('fourByFourMatrix', asUtility=True, n=name + '_fourByFourMatrix') # connect translate/rotate output to matrix cmd.connectAttr(ax_x + '.outputX', fourbyfour + '.in00') cmd.connectAttr(ax_x + '.outputY', fourbyfour + '.in01') cmd.connectAttr(ax_x + '.outputZ', fourbyfour + '.in02') cmd.connectAttr(CPOM + '.result.normalX', fourbyfour + '.in10') cmd.connectAttr(CPOM + '.result.normalY', fourbyfour + '.in11') cmd.connectAttr(CPOM + '.result.normalZ', fourbyfour + '.in12') cmd.connectAttr(ax_z + '.outputX', fourbyfour + '.in20') cmd.connectAttr(ax_z + '.outputY', fourbyfour + '.in21') cmd.connectAttr(ax_z + '.outputZ', fourbyfour + '.in22') cmd.connectAttr(CPOM + '.result.positionX', fourbyfour + '.in30') cmd.connectAttr(CPOM + '.result.positionY', fourbyfour + '.in31') cmd.connectAttr(CPOM + '.result.positionZ', fourbyfour + '.in32') ############################################################# # 3, detect if collision is happening ############################################################# # create the difference matrix diffMatrix = cmd.shadingNode('multMatrix', asUtility=True, n=name + '_diffMatrix') # connect output from 4X4 and colLoc inverse worldMatrix to diffMatrix cmd.connectAttr(fourbyfour + '.output', diffMatrix + '.matrixIn[0]') cmd.connectAttr(colLoc + '.worldInverseMatrix[0]', diffMatrix + '.matrixIn[1]') # decompose diffMatrix and create a condition node diffMatrixDM = cmd.shadingNode('decomposeMatrix', asUtility=True, n=diffMatrix + '_decomposeMatrix') cmd.connectAttr(diffMatrix + '.matrixSum', diffMatrixDM + '.inputMatrix') # condition: if diffMatrixDM.ty<0, then collision not happen (true=happe, false = not happen) condition = cmd.shadingNode('condition', asUtility=True, n=name + '_condition') cmd.setAttr(condition + '.operation', 2) #greater than cmd.setAttr(condition + '.colorIfTrueR', 1) cmd.setAttr(condition + '.colorIfFalseR', 0) cmd.connectAttr(diffMatrixDM + '.outputTranslate.outputTranslateY', condition + '.firstTerm') # blending: collision happen----> collide weight =1, collision not happen---> collide weight =0: blend = cmd.shadingNode('pairBlend', asUtility=True, n=name + '_blend') cmd.connectAttr(condition + '.outColorR', blend + '.weight') # blend ctrl loc and collision loc: # decompose ctrlLoc ctrlLocDM = cmd.shadingNode('decomposeMatrix', asUtility=True, n=ctrlLoc + '_decomposeMatrix') cmd.connectAttr(ctrlLoc + '.worldMatrix', ctrlLocDM + '.inputMatrix') # decompose 4X4 fourbyfourDM = cmd.shadingNode('decomposeMatrix', asUtility=True, n=fourbyfour + '_decomposeMatrix') cmd.connectAttr(fourbyfour + '.output', fourbyfourDM + '.inputMatrix') # blend: cmd.connectAttr(ctrlLocDM + '.outputTranslate', blend + '.inTranslate1') cmd.connectAttr(ctrlLocDM + '.outputRotate', blend + '.inRotate1') cmd.connectAttr(fourbyfourDM + '.outputTranslate', blend + '.inTranslate2') cmd.connectAttr(fourbyfourDM + '.outputRotate', blend + '.inRotate2') ######################################################################## # 5. offset obj position(contact) ######################################################################## offsetMatrix = cmd.shadingNode('multMatrix', asUtility=True, n=name + 'offsetMatrix') cmd.connectAttr(diffMatrix + '.matrixSum', offsetMatrix + '.matrixIn[0]') cmd.connectAttr(ctrlLoc + '.worldMatrix[0]', offsetMatrix + '.matrixIn[1]') cmd.connectAttr(offsetMatrix + '.matrixSum', fourbyfourDM + '.inputMatrix', force=True) # 5. connect result to obj ######################################################################## objGrp = cmd.group(obj, n=obj + '_collision_Grp', r=True) cmd.connectAttr(blend + '.outTranslate', objGrp + '.translate') cmd.connectAttr(blend + '.outRotate', objGrp + '.rotate') return (ctrlLoc, colLoc, objGrp)
def bend_chain(crv, controller, bones_nbr): jnt_nbr = bones_nbr + 1 # get shape crv_shape = mc.listRelatives(crv, c=True, s=True)[0] # calculation of the number of cv crv_degree = mc.getAttr(crv_shape + '.degree') crv_span = mc.getAttr(crv_shape + '.spans') cv_nbr = crv_degree + crv_span # place curve pivot on first cv crv_info = mc.createNode('curveInfo', n=crv + '_curveInfo') mc.connectAttr(crv_shape + '.worldSpace', crv_info + '.inputCurve') cv_tx = mc.getAttr(crv_info + '.controlPoints[0].xValue') cv_ty = mc.getAttr(crv_info + '.controlPoints[0].yValue') cv_tz = mc.getAttr(crv_info + '.controlPoints[0].zValue') mc.xform(crv, piv=(cv_tx, cv_ty, cv_tz), ws=True) # Stretch creation mult = mc.shadingNode('multiplyDivide', asUtility=True, name='multiplyDivide_STRETCH_' + crv) mc.connectAttr('%s.arcLength' % crv_info, '%s.input1X' % mult) crv_length = mc.getAttr(crv_info + '.arcLength') mc.setAttr(mult + '.input2X', crv_length) mc.setAttr(mult + '.operation', 2) # Joint chain creation jnt_length = crv_length / bones_nbr first_jnt = mc.joint(p=(cv_tx, cv_ty, cv_tz), name='SK_' + crv + '_0') for i in range(1, jnt_nbr): i = str(i) current_jnt = mc.joint(p=(jnt_length, 0, 0), r=True, name='SK_' + crv + '_' + i) mc.connectAttr(mult + '.outputX', current_jnt + '.scaleX') # ikSpline creation ik = 'IKSPLINE_' + crv mc.ikHandle(curve=crv, ee='SK_' + crv + '_' + str(bones_nbr), sol='ikSplineSolver', sj=first_jnt, name=ik, ccv=0) jnt_rotation = mc.xform(first_jnt, q=True, ro=True) # Orig joint orig.orig([first_jnt], 'orig') # offset de l'ik orig.orig([ik], 'orig') for j in range(0, cv_nbr): # Creation des clusters :) cls_nbr = str(j) cv = (crv + '.cv[' + cls_nbr + ']') mc.select(cv) cluster = mc.cluster() mc.select(deselect=True) # Recuperation de la position des clusters cls_pos_x = mc.getAttr('%s.controlPoints[%s].xValue' % (crv_info, cls_nbr)) cls_pos_y = mc.getAttr('%s.controlPoints[%s].yValue' % (crv_info, cls_nbr)) cls_pos_z = mc.getAttr('%s.controlPoints[%s].zValue' % (crv_info, cls_nbr)) # Controllers creation ctrl = mc.duplicate(controller, name='%s_%s_ctrl' % (crv, cls_nbr)) ctrl = mc.rename(ctrl, '%s_%s_ctrl' % (crv, cls_nbr)) mc.xform(ctrl, t=(cls_pos_x, cls_pos_y, cls_pos_z), ws=True) mc.xform(ctrl, ro=jnt_rotation) # Controllers orig orig.orig([ctrl], 'orig') # Cluster hierarchy mc.parent(cluster, ctrl) mc.select('%s_*_ctrl_orig' % crv) mc.group(name='%s_ctrl_grp' % crv) mc.select(deselect=True)
def createLayeredSplineIK(jnts, name, rig=None, side='C', extraName='', parent=None, dyn=False): """ Create a layered spline IK. [Args]: jnts (list)(string) - The names of the joints to create the IK with name (string) - The name of the IK rig (class) - The rig class to use side (string) - The side of the IK extraName (string) - The extra name of the IK parent (string) - The name of the parent dyn (bool) - Toggles dynamics on the spline IK """ moduleName = utils.setupBodyPartName(extraName, side) col = utils.getColors(side) ## create base layer jnts tmpCrv = utils.createCrvFromObjs(jnts, crvName='tmpCrv') ctrlGrp = utils.newNode('group', name='{}{}Ctrls'.format(extraName, name), side=side, parent=rig.ctrlsGrp.name if rig else None, skipNum=True) mechGrp = utils.newNode('group', name='{}{}Mech'.format(extraName, name), side=side, parent=rig.mechGrp.name if rig else None, skipNum=True) baseJnts = utils.createJntsFromCrv(tmpCrv, numOfJnts=4, side=side, name='{}{}_baseLayer'.format( extraName, name)) if rig: cmds.parent(jnts[0], rig.skelGrp.name) cmds.parent(baseJnts[0], mechGrp.name) ## parent locs to base jnts ## base layer ctrls baseLayerLocs = [] baseLayerCtrls = [] baseCtrlParent = ctrlGrp.name for each in baseJnts: baseLoc = utils.newNode('locator', name='{}{}_baseLayer'.format(extraName, name), side=side) baseLoc.parent(each, relative=True) utils.setShapeColor(baseLoc.name, color=None) baseLayerLocs.append(baseLoc) baseCtrl = ctrlFn.ctrl(name='{}{}_baseLayer'.format(extraName, name), guide=each, side=side, parent=baseCtrlParent, rig=rig, scaleOffset=rig.scaleOffset) baseCtrl.constrain(each) baseCtrl.modifyShape(shape='cube', color=col['col2'], scale=(1, 1, 1)) baseLayerCtrls.append(baseCtrl) baseCtrlParent = baseCtrl.ctrlEnd baseSpaces = [rig.globalCtrl.ctrlEnd] if parent: baseSpaces.insert(0, parent) baseLayerCtrls[0].spaceSwitching(parents=baseSpaces, niceNames=None, constraint='parent', dv=0) ## mid layer crv FROM BASE JNTS midCrv = utils.createCrvFromObjs(baseJnts, crvName='{}_midLayer'.format(name), side=side, extraName=extraName) ## create mid jnts midJnts = utils.createJntsFromCrv(tmpCrv, numOfJnts=7, side=side, name='{}{}_midLayer'.format( extraName, name)) cmds.parent(midJnts[0], mechGrp.name) cmds.delete(tmpCrv) ## parent locs to mid jnts ## create mid ctrls - parent constrain root grp to mid jnts midLayerLocs = [] midLayerCtrls = [] midCtrlParent = ctrlGrp.name for each in midJnts: midCtrl = ctrlFn.ctrl(name='{}{}_midLayer'.format(extraName, name), guide=each, side=side, parent=midCtrlParent, rig=rig, scaleOffset=rig.scaleOffset) cmds.parentConstraint(each, midCtrl.rootGrp.name, mo=1) midCtrl.modifyShape(shape='sphere', color=col['col1'], scale=(0.4, 0.4, 0.4)) midLayerCtrls.append(midCtrl) midLoc = utils.newNode('locator', name='{}{}_midLayer'.format(extraName, name), side=side) utils.setShapeColor(midLoc.name, color=None) midLoc.parent(midCtrl.ctrlEnd, relative=True) midLayerLocs.append(midLoc) midCtrlParent = midCtrl.ctrlEnd ## ik spline mid crv to mid jnts midIKSpline = ikFn.ik(sj=midJnts[0], ej=midJnts[-1], name='{}{}_midLayerIK'.format(extraName, name), side=side) midIKSpline.createSplineIK(crv=midCrv, parent=mechGrp.name) midIKSpline.addStretch(operation='both', mode='length', globalScaleAttr=rig.scaleAttr if rig else None) midIKSpline.advancedTwist(baseLayerCtrls[0].ctrlEnd, endObj=baseLayerCtrls[-1].ctrlEnd, wuType=4) ## connect mid crv cvs to base locators for i, each in enumerate(baseLayerLocs): cmds.connectAttr('{}.wp'.format(each.name), '{}Shape.cv[{}]'.format(midCrv, i)) ## create skin crv FROM MID JNTS skinCrvIn = utils.createCrvFromObjs(midJnts, side=side, extraName=extraName, crvName='{}_skinLayer{}'.format( name, 'DynIn' if dyn else '')) skinCrvInShape = cmds.listRelatives(skinCrvIn, s=1)[0] if dyn: dynMechGrp = utils.newNode('group', name='{}Dynamics'.format(name), side=side, parent=mechGrp.name, skipNum=True) cmds.parent(skinCrvIn, dynMechGrp.name) skinCrv = utils.createCrvFromObjs(midJnts, crvName='{}_skinLayer'.format(name), side=side, extraName=extraName) ## create output curve dynOutCrv = utils.createCrvFromObjs( midJnts, side=side, extraName=extraName, crvName='{}_skinLayerDynOut'.format(name)) cmds.parent(dynOutCrv, dynMechGrp.name) dynOutCrvShape = cmds.listRelatives(dynOutCrv, s=1)[0] ## create follicle fol = utils.newNode('follicle', name='{}_skinLayerDyn'.format(name), side=side, parent=dynMechGrp.name) cmds.setAttr('{}.restPose'.format(fol.name), 1) cmds.setAttr('{}.startDirection'.format(fol.name), 1) cmds.setAttr('{}.degree'.format(fol.name), 3) ## create hair system hs = utils.newNode('hairSystem', name='{}_skinLayerDyn'.format(name), side=side, parent=dynMechGrp.name) ## create nucleus nuc = utils.newNode('nucleus', name='{}_skinLayerDyn'.format(name), side=side, parent=dynMechGrp.name) ## connect shit fol.connect('startPosition', '{}.local'.format(skinCrvInShape), mode='to') fol.connect('startPositionMatrix', '{}.wm'.format(skinCrvIn), mode='to') fol.connect('currentPosition', '{}.outputHair[0]'.format(hs.name), mode='to') fol.connect('outCurve', '{}.create'.format(dynOutCrvShape), mode='from') fol.connect('outHair', '{}.inputHair[0]'.format(hs.name), mode='from') hs.connect('currentState', '{}.inputActive[0]'.format(nuc.name), mode='from') hs.connect('startState', '{}.inputActiveStart[0]'.format(nuc.name), mode='from') hs.connect('nextState', '{}.outputObjects[0]'.format(nuc.name), mode='to') hs.connect('startFrame', '{}.startFrame'.format(nuc.name), mode='to') hs.connect('currentTime', 'time1.outTime', mode='to') nuc.connect('currentTime', 'time1.outTime', mode='to') ## blend shape curves blendNode = cmds.blendShape(skinCrvIn, dynOutCrv, skinCrv, n='{}_{}Dynamics{}'.format( side, name, suffix['blend']))[0] ## connect blend shape to attribute ##- create dyn control dynCtrl = ctrlFn.ctrl(name='{}Settings'.format(name), guide='{}_{}SettingsGuide{}'.format( side, name, suffix['locator']), rig=rig, deleteGuide=True, side=side, skipNum=True, parent=rig.settingCtrlsGrp.name) dynCtrl.makeSettingCtrl(ikfk=False, parent=jnts[0]) dynCtrl.addAttr('dynSwitch', nn='Dynamics Switch', minVal=0, maxVal=1, defaultVal=1) dynSwitchRev = utils.newNode('reverse', name='{}DynamicsSwitch'.format(name), side=side) cmds.connectAttr(dynCtrl.ctrl.dynSwitch, '{}.{}'.format(blendNode, dynOutCrv)) dynSwitchRev.connect('inputX', dynCtrl.ctrl.dynSwitch, mode='to') dynSwitchRev.connect('outputX', '{}.{}'.format(blendNode, skinCrvIn), mode='from') else: skinCrv = skinCrvIn ## ik spline skin crv to skin jnts skinIKSpline = ikFn.ik(sj=jnts[0], ej=jnts[-1], name='{}{}_skinLayerIK'.format(extraName, name), side=side) skinIKSpline.createSplineIK(crv=skinCrv, parent=mechGrp.name) skinIKSpline.addStretch(operation='both', mode='length', globalScaleAttr=rig.scaleAttr if rig else None) skinIKSpline.advancedTwist(midLayerCtrls[0].ctrlEnd, endObj=midLayerCtrls[-1].ctrlEnd, wuType=4) ## connect skin crv cvs to mid locators for i, each in enumerate(midLayerLocs): cmds.connectAttr('{}.wp'.format(each.name), '{}Shape.cv[{}]'.format(skinCrvIn, i))
def __makeTransform(dagNode): if cmds.objectType(dagNode, isAType='transform'): return dagNode xform = cmds.listRelatives(dagNode, path=True, parent=True)[0] return xform
def create(self, geo, worldSpace=False): meshes = cmds.listRelatives(geo, f=1, ni=1, s=1, type='mesh') if not meshes: cmds.warning('No Geometry Selected. Skipping.') return False nucleus = mel.eval('getActiveNucleusNode(false, true);') self.clothNodes = [] for mesh in meshes: conns = cmds.listConnections(mesh, sh=1, type='nBase') if not conns: meshTforms = mel.eval('listTransforms("{}")'.format(mesh)) tform = meshTforms[0] nCloth = utils.newNode('nCloth', name=self.name, side=self.side) mel.eval('hideParticleAttrs("{}")'.format(nCloth.name)) self.clothNodes.append(nCloth) nCloth.connect('currentTime', 'time1.outTime', mode='to') wrapPlugs = cmds.listConnections('{}.worldMesh'.format(mesh), d=1, p=1, sh=1, type='wrap') nCloth.connect('inputMesh', '{}.worldMesh'.format(mesh), mode='to') oldMeshName = mesh.rsplit('|')[-1] # newMeshName = '{}_{}InputMesh_{}'.format(mesh.split('_', 1)[0], self.name, # mesh.rsplit('_', 1)[-1]) newMeshName = utils.setupName('{}InputMesh'.format(self.name), suffix='_{}'.format( oldMeshName.rsplit('_')[-1]), side=oldMeshName.split('_')[0]) print newMeshName mesh = cmds.rename(mesh, newMeshName) outMesh = utils.newNode('mesh', name='{}OutputMesh'.format(self.name), side=self.side) outMesh.renameNode(oldMeshName) if not worldSpace: cmds.parent(outMesh.name, tform, s=1, r=1) cmds.delete(outMesh.transform) nCloth.setAttr('localSpaceOutput', True) shadCons = cmds.listConnections( '{}.instObjGroups[0]'.format(mesh), d=1, sh=1, type='shadingEngine') # if len(shadCons) > 0: if shadCons: cmds.hyperShade(outMesh.name, assign=shadCons[0]) else: cmds.sets(outMesh.name, add='initialShadingGroup') outMesh.setAttr('quadSplit', 0) nCloth.connect('outputMesh', '{}.inMesh'.format(outMesh.name), mode='from') mel.eval('addActiveToNSystem("{}", "{}")'.format( nCloth.name, nucleus)) nCloth.connect('startFrame', '{}.startFrame'.format(nucleus), mode='to') cmds.setAttr('{}.intermediateObject'.format(mesh), 1) clothTforms = mel.eval('listTransforms "{}"'.format( nCloth.name)) cmds.setAttr('{}.translate'.format(clothTforms[0]), l=True) cmds.setAttr('{}.rotate'.format(clothTforms[0]), l=True) cmds.setAttr('{}.scale'.format(clothTforms[0]), l=True) ## todo: add shit about thickness for collisions if wrapPlugs: mel.eval( 'if( !`exists transferWrapConns` ){ source "removeNCloth.mel"; } transferWrapConns( "' + wrapPlugs + '", "' + outMesh.name + '" );') return True
def SK_fingerEditPose(obj,attribute): selObj = obj attrName = attribute ctrlAttr = rig.connectionInfo(selObj+'.ctrl',sfd = True) midJnt = ctrlAttr.split('.')[0] rootJnt = rig.listRelatives(midJnt,p = True)[0] ikCon = rig.connectionInfo(rootJnt+'.scale',sfd = True).split('.')[0] controlName = ikCon.split('_')[0]+'_Switch' if not rig.objExists(controlName): scaleVal = rig.getAttr(ikCon+'.scaleVal') curveName = rig.rename(SK_b29(4),controlName) rig.setAttr(curveName+'.scale',0.1*scaleVal,0.1*scaleVal,0.1*scaleVal) rig.setAttr(curveName+'.rz',90) SK_freezeObj(curveName) SK_snapToObj(midJnt,curveName) rig.parent(curveName,midJnt) SK_hideLockAll(curveName) if not (rig.attributeQuery(attrName,node = controlName,ex = True)): rig.addAttr(controlName,ln = attrName,at = 'float',minValue = -1,maxValue = 1,dv = 1,k = True) ctrls = [ctrl.split('.')[0] for ctrl in rig.connectionInfo(midJnt+'.ctrl',dfs = True)] ctrls = [ctrl for ctrl in ctrls if not ('_End' in ctrl)] for ctrl in ctrls: attrs = rig.listAttr(ctrl,k = True) for attr in attrs: attrV = rig.getAttr(ctrl+'.'+attr) if(math.fabs(attrV) > 0.01): ctrlJnt = rig.listRelatives(ctrl,p = True)[0] attrJnt = attrName+'_'+attr if(rig.attributeQuery(attrJnt,node = ctrlJnt,ex = True)): rig.setAttr(ctrlJnt+'.'+attrJnt,attrV) else: rig.addAttr(ctrlJnt,ln = attrJnt,at = 'float',dv = attrV) lsConnectJnt = rig.listConnections(ctrlJnt+'.'+attr,s = True,d = False,scn = True,p = True) if lsConnectJnt: lsConnectJnt = lsConnectJnt[0] if 'plusMinusAverage' == rig.nodeType(lsConnectJnt.split('.')[0]): existsMPA = lsConnectJnt.split('.')[0] numMPA = len(rig.getAttr(existsMPA+'.input1D[*]')) existsMD = SK_MDNode(controlName) if existsMD: inMD,inMD1,outMD = existsMD rig.connectAttr(ctrlJnt+'.'+attrJnt,inMD) rig.connectAttr(controlName+'.'+attrName,inMD1) rig.connectAttr(outMD,existsMPA+'.input1D['+str(numMPA)+']') else: jntMD = rig.createNode('multiplyDivide',n = ctrl+'_MD',ss = True) rig.connectAttr(ctrlJnt+'.'+attrJnt,jntMD+'.input1X') rig.connectAttr(controlName+'.'+attrName,jntMD+'.input2X') rig.connectAttr(jntMD+'.outputX',existsMPA+'.input1D['+str(numMPA)+']') else: existsMD = SK_MDNode(controlName) jntMPA = rig.createNode('plusMinusAverage',n = ctrl+'_MPA',ss = True) if existsMD: inMD,inMD1,outMD = existsMD rig.connectAttr(ctrlJnt+'.'+attrJnt,inMD) rig.connectAttr(controlName+'.'+attrName,inMD1) rig.connectAttr(outMD,jntMPA+'.input1D[1]') else: jntMD = rig.createNode('multiplyDivide',n = ctrl+'_MD',ss = True) rig.connectAttr(ctrlJnt+'.'+attrJnt,jntMD+'.input1X') rig.connectAttr(controlName+'.'+attrName,jntMD+'.input2X') rig.connectAttr(jntMD+'.outputX',jntMPA+'.input1D[1]') rig.connectAttr(lsConnectJnt,jntMPA+'.input1D[0]') rig.connectAttr(jntMPA+'.output1D',ctrlJnt+'.'+attr,f = True) else: existsMD = SK_MDNode(controlName) jntMPA = rig.createNode('plusMinusAverage',n = ctrl+'_MPA',ss = True) if existsMD: inMD,inMD1,outMD = existsMD rig.connectAttr(ctrlJnt+'.'+attrJnt,inMD) rig.connectAttr(controlName+'.'+attrName,inMD1) rig.connectAttr(outMD,jntMPA+'.input1D[1]') else: jntMD = rig.createNode('multiplyDivide',n = ctrl+'_MD',ss = True) rig.connectAttr(ctrlJnt+'.'+attrJnt,jntMD+'.input1X') rig.connectAttr(controlName+'.'+attrName,jntMD+'.input2X') rig.connectAttr(jntMD+'.outputX',jntMPA+'.input1D[1]') # rig.connectAttr(lsConnectJnt,jntMPA+'.input1D[0]') if(rig.getAttr(ctrlJnt+'.'+attr,l = True)): rig.setAttr(ctrlJnt+'.'+attr,l = False) rig.connectAttr(jntMPA+'.output1D',ctrlJnt+'.'+attr,f = True) for ctrl in ctrls: attrs = rig.listAttr(ctrl,k = True) for attr in attrs: attrV = rig.getAttr(ctrl+'.'+attr) if(math.fabs(attrV) > 0.01): rig.setAttr(ctrl+'.'+attr,0)
mirrorX['mode'] = 'mirror' mirrorX['pivot'] = [0, 0, 0, 0, 0, 0, 1, 1, 1] mirrorX['namePrefix'] = ['r', 'l'] mirrorX['nameReplace'] = ['', ''] mirrorX['nameIncr'] = '' mirrorX['nameAdd'] = [] mirrorX['noneMirrorAxe'] = -1 #BUILD for lod in ['Hi', 'Low']: modelClass_duplicateAndBuild(('head' + lod + '_GRP'), [mirrorX]) #REORDER HIERARCHY #CLEAN HIERARCHY grps = mc.listRelatives("ALL_GRP", c=True) for i in range(0, len(grps)): childrens = mc.listRelatives(grps[i], c=True) if (childrens == None) or (len(childrens) == 0): mc.delete(grps[i]) #REORDER HIERARCHY mc.createNode("transform", n="all_GRP") mc.createNode("transform", n="hi_GRP", p="all_GRP") mc.createNode("transform", n="low_GRP", p="all_GRP") mc.parent(mc.ls("ALL_GRP|*Low_GRP"), "low_GRP") mc.parent(mc.ls("ALL_GRP|*_GRP"), "hi_GRP") mc.delete("ALL_GRP") #___________________________________________________________________________SAVE TO MODEL rwi.mayaScene_save( 'D:/mcantat_BDD/projects/flyAway/assets/howie/maya/scenes/howie_model.ma')
def colorControl(self, Nameof, Type, colorname): sels = cmds.ls(sl=True) SizeofSelection = len(sels) if SizeofSelection < 1: Cirr = cmds.circle(c=(0, 0, 0), name=(Nameof)) shapes = cmds.listRelatives(Cirr, children=True, shapes=True) for shape in shapes: cmds.setAttr('%s.overrideEnabled' % shape, True) cmds.setAttr('%s.overrideColor' % shape, colorname) #RENAME if Type == "Group": if SizeofSelection < 1: print("Set a default one") else: dups = cmds.duplicate(sels) dups = cmds.polyUnite(dups) cmds.delete(dups, constructionHistory=True) BoxLimits = cmds.xform(dups[0], query=True, boundingBox=True) cmds.delete(dups[0]) XDirect = ((BoxLimits[0]) + (BoxLimits[3])) / 2 YDirect = ((BoxLimits[1]) + (BoxLimits[4])) / 2 ZDirect = ((BoxLimits[2]) + (BoxLimits[5])) / 2 Cirr = cmds.circle(c=(XDirect, YDirect, ZDirect), name=("Group " + Nameof)) shapes = cmds.listRelatives(Cirr, children=True, shapes=True) for shape in shapes: cmds.setAttr('%s.overrideEnabled' % shape, True) cmds.setAttr('%s.overrideColor' % shape, colorname) if Type == "Single": if SizeofSelection < 1: print("Set a default one") else: for i in range(len(sels)): BoxLimits = cmds.xform(sels[i], query=True, worldSpace=True, boundingBox=True) XDirect = ((BoxLimits[0]) + (BoxLimits[3])) / 2 YDirect = ((BoxLimits[1]) + (BoxLimits[4])) / 2 ZDirect = ((BoxLimits[2]) + (BoxLimits[5])) / 2 Cirr = cmds.circle(c=(XDirect, YDirect, ZDirect), name=self.RenameContrl(sels[i], Nameof)) shapes = cmds.listRelatives(Cirr, children=True, shapes=True) for shape in shapes: cmds.setAttr('%s.overrideEnabled' % shape, True) cmds.setAttr('%s.overrideColor' % shape, colorname) else: print("no objects selected, will put one in at default")
def iterParents( obj ): parent = cmd.listRelatives( obj, p=True, pa=True ) while parent is not None: yield parent[ 0 ] parent = cmd.listRelatives( parent[ 0 ], p=True, pa=True )
def link(src_root, dst_root): srcs = collect_by_name(src_root, type='mesh') dsts = collect_by_name(dst_root, type='mesh') for name, src_node in sorted(srcs.iteritems()): dst_node = dsts.get(name) if not dst_node: continue # Only bother transferring attributes on meshes that have a connection # to an alembic node. This isn't a very strong connection, but it # seems to work for us. is_deformed = False for node in cmds.listHistory(src_node) or (): type_ = cmds.nodeType(node) if type_ == 'AlembicNode': is_deformed = True break if not is_deformed: continue print 'mesh {}: {} -> {}'.format(name, src_node, dst_node) src_transform = cmds.listRelatives(src_node, parent=True, path=True)[0] dst_transform = cmds.listRelatives(dst_node, parent=True, path=True)[0] transfer = cmds.transferAttributes( src_transform, dst_transform, afterReference=1, # To play nice with references. transferPositions=1, transferNormals=1, sampleSpace=4, # 4 == components )[0] print ' transferAttributes:', transfer srcs = collect_by_name(src_root, type='transform') dsts = collect_by_name(dst_root, type='transform') for name, src_node in sorted(srcs.iteritems()): dst_node = dsts.get(name) if not dst_node: continue print 'transform {}: {} -> {}'.format(name, src_node, dst_node) is_alembiced = False if True: for node in cmds.listConnections(src_node, skipConversionNodes=True, source=True, destination=False) or (): if cmds.nodeType(node) == 'AlembicNode': is_alembiced = True print ' is alembiced:', node break is_animated = False if True: for attr in ('tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz'): connections = cmds.listConnections('{}.{}'.format( src_node, attr), source=True, destination=False) if connections: is_animated = True print ' is animated: {} is connected'.format(attr) break is_transformed = False if True: for attr in ('tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz'): src_value = cmds.getAttr('{}.{}'.format(src_node, attr)) dst_value = cmds.getAttr('{}.{}'.format(dst_node, attr)) if src_value != dst_value: if abs(src_value - dst_value) > 1e-12: is_transformed = True print ' is transformed: src {} {} != dst {}'.format( attr, src_value, dst_value) else: print ' has minor transform: src {} {} != dst {}'.format( attr, src_value, dst_value) break is_group = False has_shapes = False if True: children = cmds.listRelatives(src_node) child_shapes = cmds.listRelatives(src_node, shapes=True) has_shapes = bool(child_shapes) is_group = bool(children and not has_shapes) if is_group: print ' is group: {} children with no shapes'.format( len(children)) elif has_shapes: print ' has shapes: {} children with {} shapes'.format( len(children), len(child_shapes)) # Kevin asked to never constrain things which have shapes. do_constraint = (is_alembiced or is_animated or is_transformed) and not has_shapes if do_constraint: # Bulk of transform is handled by a parent constraint... constraint = cmds.parentConstraint(src_node, dst_node, name='abc_link_parent_' + name)[0] print ' parentConstraint:', constraint constraint = cmds.scaleConstraint(src_node, dst_node, name='abc_link_scale_' + name)[0] print ' scaleConstraint:', constraint # We really do want to connect all the visibility regardless of animation. if name != 'hi': # ... and other attributed are done directly. for attr_name in ('visibility', ): cmds.connectAttr(src_node + '.' + attr_name, dst_node + '.' + attr_name, force=True) print ' {}: {} -> {}'.format(attr_name, src_node, dst_node)
def SetDisplayColor(Unuse=None): Value = int(re.search('\d+$', mc.iconTextRadioCollection("UI_ColorCollide", q=True, sl=True)).group()) for OBJ in mc.ls(sl=True): for shp in mc.listRelatives(OBJ, s=True, path=True) or []: mc.setAttr(OBJ + '.ove', 1) mc.setAttr(OBJ + '.ovc', Value)