def bulge_button( self, *args ): if( cmds.objExists( "ZBend" ) ): cmds.confirmDialog( title="Error", message="First delete the bulge history on the previously\ndeformed object before bulging another.", button="Okie Dokie" ) return 0 latestSelection = cmds.ls( selection=True ) if( len( latestSelection ) == 0 ): return 0 if( len( latestSelection ) == 1 ): self.relatives = cmds.listRelatives( children=True ) if( len(self.relatives) == 1 ): self.bbox = cmds.exactWorldBoundingBox( latestSelection ) cmds.nonLinear( type='bend', curvature=cmds.intSliderGrp( "x_bulge_slider", value=True, query=True ) ) cmds.rename( "XBend" ) cmds.move((self.bbox[0] + self.bbox[3])/2, self.bbox[1], (self.bbox[2] + self.bbox[5])/2, "XBend", rpr=True ) cmds.setAttr( "XBend.rotateZ", -90 ) cmds.select( latestSelection ) cmds.nonLinear( type='bend', curvature=cmds.intSliderGrp( "z_bulge_slider", value=True, query=True ) ) cmds.rename( "ZBend" ) cmds.move((self.bbox[0] + self.bbox[3])/2, self.bbox[1], (self.bbox[2] + self.bbox[5])/2, "ZBend", rpr=True ) cmds.setAttr( "ZBend.rotateZ", -90 ) cmds.setAttr( "ZBend.rotateX", 90 ) cmds.connectControl( "x_bulge_slider", "bend1.curvature" ) cmds.connectControl( "z_bulge_slider", "bend2.curvature" ) cmds.select( latestSelection )
def rename(geo): ''' Rename shape nodes based on the parent transform name @param geo: Transform to rename shapes for @type geo: str ''' # Get Shapes shapes = getShapes(geo) # Check Shapes if not shapes: return [] # Rename Shapes for i in range(len(shapes)): # Get Shape Type shapeType = mc.objectType(shapes[i]) # Temporarily rename shapes, so hash index (#) is accurate shapes[i] = mc.rename(shapes[i],geo+'ShapeTMP') # Rename Shape if shapeType == 'nurbsCurve': shapes[i] = mc.rename(shapes[i],geo+'CrvShape#') elif shapeType == 'nurbsSurface': shapes[i] = mc.rename(shapes[i],geo+'SrfShape#') elif shapeType == 'mesh': shapes[i] = mc.rename(shapes[i],geo+'MeshShape#') else: shapes[i] = mc.rename(shapes[i],geo+'Shape#') # Return Result return shapes
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 SetupAlembic(alembicFile, shaderFile): # reference alembic file filename = os.path.basename(alembicFile) newNodes = cmds.file(alembicFile, reference=True, namespace=filename, groupReference=True, groupName='NewReference', returnNewNodes=True) alembicRoot = None for node in newNodes: if node == '|NewReference': alembicRoot = pm.PyNode(node) cmds.rename('%s:grp' % filename) # reference shader file filename = os.path.basename(shaderFile) newNodes = cmds.file(shaderFile, reference=True, namespace=filename, groupReference=True, groupName='NewReference', returnNewNodes=True) shaderRoot = None for node in newNodes: if node == '|NewReference': shaderRoot = pm.PyNode(node) cmds.rename('%s:grp' % filename) # connecting shader to alembic Connect(alembicRoot, shaderRoot) alembicRoot.v.set(0)
def maya_move(angular_velocity, time_step): objects = cmds.ls(sl=True) if objects == []: print('* Please select at least an object.') return trajectory = cmds.ls('trajectory') for i, o in enumerate(objects): x = cmds.getAttr(o + '.translateX') y = cmds.getAttr(o + '.translateY') z = cmds.getAttr(o + '.translateZ') loc = [x, y, z] state = make_state(loc) state = simulate_circle(state, angular_velocity, time_step) old_loc = loc loc = get_location(state) cmds.select(o) cmds.move(loc[0], loc[1], loc[2]) # draw trajectory for the first object if i == 0: if trajectory == []: cv = cmds.curve(point=[old_loc, loc], degree=1) cmds.rename(cv, 'trajectory') else: cmds.curve('trajectory', point=[loc], degree=1, append=True) # keep all objects selected cmds.select(objects)
def create_ik_arm_stretch(self): """Creates the IK stretch setup.""" arm_dist, start_loc, end_loc = self.c.distance_node(self.guides['upperArm'], self.guides['hand']) arm_dist = cmds.rename(arm_dist, '%s_%s_%s' % (self.side, 'arm', self.nc.distance)) start_loc = cmds.rename(start_loc, '%s_%s_%s' % (self.side, 'armLengthStart', self.nc.locator)) end_loc = cmds.rename(end_loc, '%s_%s_%s' % (self.side, 'armLengthEnd', self.nc.locator)) cmds.parent(end_loc, self.controls['handik']) cmds.parent(arm_dist, self.top_grp) driver = '%sShape.distance' % arm_dist if self.side == 'R': mult = cmds.shadingNode('multiplyDivide', asUtility=True) mult = cmds.rename(mult, '%s_%s_stretch_negative_MDN' % (self.side, 'arm')) cmds.connectAttr('%sShape.distance' % arm_dist, '%s.input1X' % mult, f=True) cmds.setAttr('%s.input2X' % mult, -1) driver = '%s.outputX' % mult # END if upper_arm_len = cmds.getAttr('%s.tx' % self.ik_jnts[1]) fore_arm_len = cmds.getAttr('%s.tx' % self.ik_jnts[2]) sum_len = upper_arm_len + fore_arm_len cmds.setDrivenKeyframe('%s.translateX' % self.ik_jnts[1], cd=driver, dv=sum_len, itt='linear', ott='linear') cmds.setDrivenKeyframe('%s.translateX' % self.ik_jnts[1], cd=driver, dv=sum_len*2, v=upper_arm_len*2, itt='linear', ott='linear') cmds.setDrivenKeyframe('%s.translateX' % self.ik_jnts[2], cd=driver, dv=sum_len, itt='linear', ott='linear') cmds.setDrivenKeyframe('%s.translateX' % self.ik_jnts[2], cd=driver, dv=sum_len*2, v=fore_arm_len*2, itt='linear', ott='linear') cmds.setAttr('%s_translateX.postInfinity' % self.ik_jnts[1], 1) cmds.setAttr('%s_translateX.postInfinity' % self.ik_jnts[2], 1) # stretch the result joints curve = '%s_%s_%s' % (self.side, 'upperArm', self.nc.curve) self.stretch_result_joints(curve, 'upperArm', self.upper_arm_jnts) curve = '%s_%s_%s' % (self.side, 'foreArm', self.nc.curve) self.stretch_result_joints(curve, 'foreArm', self.fore_arm_jnts)
def duplicate_this(self, input_object, copy_name='cpy_'): ''' Desc: return a obj that is the copy of inputObject with a name defined in nameOfCopy Parameter: input_object = the object to be copied copy_name = the copy name Return: the obj copied from the original with the new name ''' if input_object: #cmds.select(input_object) copy_object = cmds.duplicate(input_object, smartTransform=True, name = copy_name, renameChildren = True) copy_object[0] = cmds.rename(copy_object[0], copy_name+input_object) #print('DEBUG copy object: ', copy_object) # Search all children of the current object for renaming hierarchy = cmds.listRelatives(copy_object, c=True) if hierarchy: for child in hierarchy: cmds.rename(child, copy_name+child[:-1]) KstOut.debug(KstMaya._debug, str(copy_object[0])+" duplicated from "+str(input_object)) return copy_object else: KstOut.debug(KstMaya._debug, ' inputObject empty, check selection, or array')
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 cleanClashingElements(self, origRenderElements, newRenderElements): for newElement in newRenderElements: if clashNameSpace in newElement: if not newElement.split(clashNameSpace)[-1] in origRenderElements: classingBaseName = newElement.split(clashNameSpace + "_")[-1] cmds.delete(classingBaseName) cmds.rename(newElement, classingBaseName)
def exportSelection(selection, filepath): # combine if selection is more than 1 mesh if len(selection) > 1: selection = modeling.combine() # get asset name base = os.path.basename(filepath) assetname = os.path.splitext(base)[0] # create groups cmds.select(clear=True) main_group = cmds.group(n=assetname, empty=True) geo_group = cmds.group(n=assetname+'_main', empty=True, p=main_group) lod0_group = cmds.group(n=assetname+'_lod0', empty=True, p=geo_group) col_group = cmds.group(n=assetname+'_collision', empty=True, p=main_group) # parent the geo to the lod0 group cmds.parent(selection, lod0_group) # create the collision collision = cmds.duplicate(selection) cmds.parent(collision, col_group) # rename meshes cmds.rename(selection, 'part_state0') cmds.rename(collision, 'part_state0_Mesh1') # select main group cmds.select(main_group, r=True) # set fbx settings mel.eval('FBXExportFileVersion "FBX201300"') #mel.eval('FBXConvertUnitString "m"') mel.eval('FBXExportSmoothingGroups -v true') mel.eval('FBXExportUpAxis "Y"') # export selection mel.eval('FBXExport -f "'+filepath+'" -s')
def bdReplaceSelected(self,*args): selectedObj = [] selectedObj = cmds.ls(selection = True,ap=True ) strSearch = str(self.inputSearch.text()) strReplace = str(self.inputReplace.text()) strPrefix = str(self.inputPrefixReplace.text()) strSufix = str(self.inputSufixReplace.text()) strNewNames = [] if strSearch != '': self.listPreview.clear() for obj in selectedObj: newName = strPrefix + obj.split('|')[-1].replace(strSearch,strReplace) + strSufix self.listPreview.addItem(newName) strNewNames.append(newName) else: if strPrefix != '' or strSufix != '': self.listPreview.clear() for obj in selectedObj: newName = strPrefix + obj.split('|')[-1] + strSufix self.listPreview.addItem(newName) strNewNames.append(newName) strNewNames = list(reversed(strNewNames)) strSelected = list(reversed(selectedObj)) for i in range(len(strNewNames)): print 'new name for %s is %s'%(strSelected[i],strNewNames[i]) cmds.rename(strSelected[i],strNewNames[i])
def Run(self): Hyperbola = mc.textFieldGrp(self.Hyperbola,q=1,tx=1) JntNumber = mc.intSliderGrp(self.JntNumber,q=1,v=1) setCV = mc.ls(sl=1) CvBase = mc.rename(setCV[0],Hyperbola+'_hyperbola_cv_base') CvTgt = mc.rename(setCV[1],Hyperbola+'_hyperbola_cv_Tgt') self.CurveInfo(Hyperbola,CvBase,CvTgt,JntNumber)
def __setup_final_meshes(self): #--- this method setups the final meshes if 'FINAL' in self.mesh: if cmds.objExists(self.mesh): self.final_mesh = self.mesh else: self.final_mesh = cmds.duplicate(self.mesh) cmds.parent(self.final_mesh, self.sf_final_meshes) final_name = cmds.rename(self.final_mesh, self.mesh) self.final_mesh = final_name else: if cmds.objExists(self.mesh + 'FINAL'): self.final_mesh = self.mesh + 'FINAL' else: self.final_mesh = cmds.duplicate(self.mesh) cmds.parent(self.final_mesh, self.sf_final_meshes) final_name = cmds.rename(self.final_mesh, self.mesh + 'FINAL') self.final_mesh = final_name if cmds.objExists(self.mesh + '_BSP'): #--- setup blendShape deformer self.final_bsp = self.mesh + '_BSP' cmds.setAttr(self.final_bsp + '.' + self.mesh, 1) cmds.setAttr(self.mesh + '.v', 0) else: if 'FINAL' in self.mesh: self.mesh = self.mesh.split('FINAL')[0] self.final_bsp = cmds.blendShape(self.mesh, self.final_mesh, name = self.mesh + '_BSP')[0] cmds.setAttr(self.final_bsp + '.' + self.mesh, 1) cmds.setAttr(self.mesh + '.v', 0)
def repair(self, instance): """Process all the shape nodes in the instance""" shapes = cmds.ls(instance, shapes=True, long=True) for shape in shapes: if not self._is_valid(shape): correct_shape_name = self._define_default_name(shape) cmds.rename(shape, correct_shape_name)
def doNameObject(obj,sceneUnique = False): """ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> DESCRIPTION: Names an object, when forceOverride is False, will select conflicting objects ARGUMENTS: obj(string) - the object we'd like to name forceOverride(bool)- whether to rename conflicts or not RETURNS: newName(string) on success >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> """ ### input check assert mc.objExists(obj) is True, "'%s' doesn't exist" %obj name = returnUniqueGeneratedName(obj,sceneUnique = sceneUnique) nameFactory = NameFactory(obj) if nameFactory.amIMe(name): guiFactory.warning("'%s' is already named correctly."%nameFactory.nameBase) return name else: objLong = mc.ls(obj,long=True) renameBuffer = mc.rename(objLong,name) shapes = mc.listRelatives(renameBuffer,shapes=True,fullPath=True) if shapes: for shape in shapes: name = returnUniqueGeneratedName(shape,sceneUnique = sceneUnique) mc.rename(shape,name) return renameBuffer
def on_btn_FixBsBsEnd_clicked(self, clicked=None): if clicked == None:return #- selectIndexes = self.listView_attributeList.selectedIndexes() if len(selectIndexes) == 0:return selectAttr = self.__AttributeModel.data(selectIndexes[0], QtCore.Qt.DisplayRole) if not uiTool.warning('BlendShape\'s shape on attribute "%s" will be changed,\nand it can\'t to undo, \ncontinue? ?'%selectAttr):return #- dup model openCloseDeformer(self.__baseModel, 0) midModel = mc.duplicate(self.__baseModel, n=nameTool.compileMayaObjectName('%s_mid'%self.__baseModel.split(':')[-1]))[0] openCloseDeformer(self.__baseModel, 1) #- add blendShape mc.blendShape(self.__sculpmodel, self.__baseModel, midModel, w=((0, 1), (1, -1))) mc.delete(midModel, ch=True) if mc.objExists(selectAttr): mc.blendShape(midModel, selectAttr, w=((0, 1))) mc.delete(selectAttr, ch=True) mc.delete(midModel) else: shape = mc.listRelatives(midModel, s=True, path=True)[0] weightID = self.__AttributeDT2.get(selectAttr, None) TGTattr = self.__IGTAttributeDT.get(weightID, None) mc.connectAttr('%s.worldMesh[0]'%shape, '%s.%s'%(self.__blendShape, TGTattr), f=True) mc.rename(midModel, selectAttr) mc.delete(self.__sculpmodel) mc.delete(self.__tempmodel)
def on_btn_FixSkinBsEnd_clicked(self, clicked=None): if clicked == None:return selectIndexes = self.listView_attributeList.selectedIndexes() if len(selectIndexes) == 0:return selectAttr = self.__AttributeModel.data(selectIndexes[0], QtCore.Qt.DisplayRole) if not uiTool.warning('BlendShape\'s shape on attribute "%s" will be changed,\nand it can\'t to undo, \ncontinue? ?'%selectAttr):return openCloseDeformer(self.__baseModel, 0, ('skinCluster')) newSculpModel = cvShapeInverterCmds.invert(self.__baseModel, self.__sculpmodel, self.progressBar) mc.delete(newSculpModel, ch=True) openCloseDeformer(self.__baseModel, 1, ('skinCluster')) if mc.objExists(selectAttr): mc.blendShape(newSculpModel, selectAttr, w=((0, 1))) mc.delete(selectAttr, ch=True) mc.delete(newSculpModel) else: shape = mc.listRelatives(newSculpModel, s=True, path=True)[0] weightID = self.__AttributeDT2.get(selectAttr, None) TGTattr = self.__IGTAttributeDT.get(weightID, None) mc.connectAttr('%s.worldMesh[0]'%shape, '%s.%s'%(self.__blendShape, TGTattr), f=True) mc.rename(newSculpModel, selectAttr) mc.delete(self.__sculpmodel) mc.delete(self.__tempmodel)
def doRenderRig(self) : path = str(self.ui.path_lineEdit.text()) texturePath = '%s/textures' % path renderRes = str(self.ui.renderRes_comboBox.currentText()) facialCore.path = texturePath facialCore.res = renderRes if mc.objExists(self.defaultHeadName) : # rename mc.rename(self.defaultHeadName, self.renderHeadName) # group group = mc.group(em = True, n = self.stillGroup) mc.parent(self.renderHeadName, group) # render node ltNode = facialCore.makeRenderFacial() # create lambert if not mc.objExists(self.renderNode) : vrayMtl = mc.shadingNode('VRayMtl', asShader = True, n = self.renderNode) # connect mc.connectAttr('%s.outColor' % ltNode, '%s.color' % vrayMtl, f = True) # assign mc.select(self.renderHeadName) mc.hyperShade(assign = vrayMtl) self.messageBox('Success', 'Set Render Node Complete') else : self.messageBox('Warning', '%s not Exists' % self.defaultHeadName)
def on_btn_FixBsEnd_clicked(self, clicked=None): if clicked == None:return #- selectIndexes = self.listView_attributeList.selectedIndexes() if len(selectIndexes) == 0:return selectAttr = self.__AttributeModel.data(selectIndexes[0], QtCore.Qt.DisplayRole) #- if not uiTool.warning('BlendShape\'s shape on attribute "%s" will be changed,\nand it can\'t to undo, \ncontinue? ?'%selectAttr):return if mc.objExists(selectAttr): mc.blendShape(self.__sculpmodel, selectAttr, w=((0, 1))) mc.delete(selectAttr, ch=True) mc.delete(self.__sculpmodel) else: shape = mc.listRelatives(self.__sculpmodel, s=True, path=True)[0] weightID = self.__AttributeDT2.get(selectAttr, None) TGTattr = self.__IGTAttributeDT.get(weightID, None) mc.connectAttr('%s.worldMesh[0]'%shape, '%s.%s'%(self.__blendShape, TGTattr), f=True) mc.rename(self.__sculpmodel, selectAttr) mc.delete(self.__tempmodel)
def _createNativeModel(self, name='Model', nativeObjects=[], referenced=False): name = 'Model' if not name else name # Create a "model" namespace and add the locator to it # TODO: Make this a context currentNamespace = cmds.namespaceInfo(currentNamespace=True) namespace = cmds.namespace(addNamespace=name) cmds.namespace(setNamespace=namespace) # Create the transform node then the shape node so the transform is properly named parent = cmds.createNode('transform', name='Model') #name = cmds.createNode('locator', name='{}Shape'.format(name), parent=parent) output = cross3d.SceneWrapper._asMOBject(parent) userProps = cross3d.UserProps(output) userProps['model'] = True if referenced: userProps['referenced'] = referenced # Create the Active_Resolution enum if it doesn't exist # cmds.addAttr(name, longName="Active_Resolution", attributeType="enum", enumName="Offloaded:") # userProps['Resolutions'] = OrderedDict(Offloaded='') cmds.namespace(setNamespace=currentNamespace) # Add each of nativeObjects to the model namespace if nativeObjects: for nativeObject in nativeObjects: nativeObject = cross3d.SceneWrapper._getTransformNode(nativeObject) objName = cross3d.SceneWrapper._mObjName(nativeObject) # cmds.parent(objName, cross3d.SceneWrapper._mObjName(nativeParent)) nameInfo = cross3d.SceneWrapper._namespace(nativeObject) newName = '{namespace}:{name}'.format(namespace=namespace, name=nameInfo['name']) cmds.rename(objName, newName) nativeObjects.append(output) return output
def import_file(self): """Import component file""" log.info("Importing file: %s" % self.file) temp_namespace = "temp" cmds.file(self.file, i=True, namespace=temp_namespace) # Collect component nodes nodes = self._collect_imported_nodes() for node in nodes: # Check for duplicates if node.count("|"): e = "Duplicate node detected %s in component %s" % (node, self.__class__.__name__) log.error(e) raise RuntimeError(e) # Rename clean_node = ":".join(node.split(":")[1:]) try: cmds.rename(node, clean_node) self.nodes.append(clean_node) except: pass cmds.namespace(removeNamespace=temp_namespace, mergeNamespaceWithRoot=True, force=True)
def renameSelected(self,*args): ui.saveRenameText() self.setInitialGroupIndex() self.setInitialItemIndex() itemIndex = self.initialItemIndex groupIndex = self.initialGroupIndex switchIndex = cmds.checkBox( 'switchIndexesCheckBox', query=True, v=True ) prefix = cmds.textField( 'prefixTextField', query=True, tx=True ) body = cmds.textField( 'bodyTextField', query=True, tx=True ) suffix = cmds.textField( 'suffixTextField', query=True, tx=True ) groupIndexString = self.getGroupIndex(groupIndex) #give items a temp name, to help lessen chance of new name already existing #won't prevent it with items that exist outside of the selection for index,item in enumerate(cmds.ls( sl=True )): splitName = item.split('|')[-1] cmds.rename( item, splitName+'XXX'+str(index) ) for item in cmds.ls( sl=True ): itemIndexString = self.getItemIndex(itemIndex) newName = prefix+groupIndexString+body+itemIndexString+suffix if switchIndex is True: newName = prefix+itemIndexString+body+groupIndexString+suffix cmds.rename( item, newName ) itemIndex = itemIndex+1
def execute(self, command): from maya import cmds parts = command.split() if len(parts) > 2: raise Exception( 'Input must be a node type and optional name:\n\n' ' multiplyDivide\n' ' multiplyDivide myMultiplyDivide\n' ) node_type = parts[0] node = None name = None if len(parts) == 2: name = parts[1] # Handle dg nodes shading_classifications = ( 'Utility', 'Shader', 'Texture', 'Rendering', 'PostProcess', 'Light' ) for cls in shading_classifications: if cmds.getClassification(node_type, satisfies=cls.lower()): node = cmds.shadingNode(node_type, **{'as' + cls: True}) # Handle dag nodes if not node: node = cmds.createNode(node_type) if name: cmds.rename(node, name)
def create_ik_setup(self): """Creates the IK setup.""" ik = cmds.ikHandle(sj=self.result_jnts[0], ee=self.result_jnts[-1], sol='ikSplineSolver', ns=1) cmds.rename(ik[1], '%s_%s_%s' % (self.side, 'neck', self.nc.effector)) curve = cmds.rename(ik[2], '%s_%s_%s' % (self.side, 'neck', self.nc.curve)) cmds.setAttr('%s.inheritsTransform' % curve, 0) ik = cmds.rename(ik[0], '%s_%s_%s' % (self.side, 'neck', self.nc.ikhandle)) cmds.select(self.additional_jnts, curve) cmds.skinCluster(tsb=True) cmds.parent(ik, self.top_grp) cmds.setAttr('%s.dTwistControlEnable' % ik, 1) cmds.setAttr('%s.dWorldUpType' % ik, 4) cmds.setAttr('%s.dWorldUpAxis' % ik, 4) cmds.setAttr('%s.dWorldUpVectorY' % ik, -1) cmds.setAttr('%s.dWorldUpVectorEndY' % ik, 1) cmds.setAttr('%s.dWorldUpVectorEndZ' % ik, -1) cmds.connectAttr('%s.worldMatrix[0]' % self.additional_jnts[0], '%s.dWorldUpMatrix' % ik, f=True) cmds.connectAttr('%s.worldMatrix[0]' % self.additional_jnts[1], '%s.dWorldUpMatrixEnd' % ik, f=True) self.head_grp = cmds.group(self.controls['head']) self.head_grp = cmds.rename(self.head_grp, '%s_head_CTL_%s' % (self.side, self.nc.group)) cmds.parent(self.head_grp, self.top_grp) self.c.move_pivot_to(self.guides['neckEnd'][0], self.guides['neckEnd'][1], self.guides['neckEnd'][2], self.head_grp) cmds.parentConstraint(self.controls['head'], self.additional_jnts[-1], mo=True, weight=1) cmds.orientConstraint(self.controls['head_rot'], self.result_jnts[-1], mo=True, weight=1)
def creatStereo(): camL = mc.ls(sl=1) if camL == []: mc.confirmDialog(title="Missing", message="Please select a camera!", button=["Ok"]) return cam = camL[0] camShape = mc.listRelatives(cam, s=1)[0] FL = mc.camera(cam, q=1, fl=1) NCP = mc.camera(cam, q=1, ncp=1) FCP = mc.camera(cam, q=1, fcp=1) cam3d = maya.app.stereo.stereoCameraRig.createStereoCameraRig() mc.parent(cam3d[0], cam) mc.setAttr(cam3d[0] + ".translate", 0, 0, 0, lock=1) mc.setAttr(cam3d[0] + ".rotate", 0, 0, 0, lock=1) mc.setAttr(cam3d[0] + ".scale", 1, 1, 1, lock=1) cam3dShape = mc.listRelatives(cam3d[0], s=1)[0] mc.connectControl("interaxialSleder", stereoShape + ".interaxialSeparation") mc.connectControl("zeroSleder", stereoShape + ".zeroParallax") mc.setAttr(cam3dShape + ".focalLength", FL) mc.setAttr(cam3dShape + ".nearClipPlane", NCP) mc.setAttr(cam3dShape + ".farClipPlane", FCP) mc.setAttr(cam3dShape + ".zeroParallaxPlane", 1) mc.setAttr(cam3dShape + ".safeViewingVolume", 1) for i in cam3d: mc.rename(i, cam + "_" + i) camListStereo = mc.ls(type="stereoRigTransform") if camListStereo == []: mc.floatSliderGrp(interaxialSleder, e=1, enable=False) mc.floatSliderGrp(zeroSleder, e=1, enable=False) else: stereoShape = mc.listRelatives(camListStereo[0], s=1)[0] mc.floatSliderGrp(interaxialSleder, e=1, enable=True) mc.floatSliderGrp(zeroSleder, e=1, enable=True) mc.connectControl(interaxialSleder, cam3dShape + ".interaxialSeparation") mc.connectControl(zeroSleder, cam3dShape + ".zeroParallax")
def ui_on_BTN_create_clicked(self, *args): cube = m.polyCube(ch=False)[0] xPosUI = self.ui_FLTFLDGRP_xPos.getValue()[0] xNegUI = self.ui_FLTFLDGRP_xNeg.getValue()[0] yPosUI = self.ui_FLTFLDGRP_yPos.getValue()[0] yNegUI = self.ui_FLTFLDGRP_yNeg.getValue()[0] zPosUI = self.ui_FLTFLDGRP_zPos.getValue()[0] zNegUI = self.ui_FLTFLDGRP_zNeg.getValue()[0] xPos = max(xPosUI, xNegUI) xNeg = min(xPosUI, xNegUI) yPos = max(yPosUI, yNegUI) yNeg = min(yPosUI, yNegUI) zPos = max(zPosUI, zNegUI) zNeg = min(zPosUI, zNegUI) m.move(xPos, cube + faceMapping['xPos'], worldSpaceDistance=True, x=True) m.move(xNeg, cube + faceMapping['xNeg'], worldSpaceDistance=True, x=True) m.move(yPos, cube + faceMapping['yPos'], worldSpaceDistance=True, y=True) m.move(yNeg, cube + faceMapping['yNeg'], worldSpaceDistance=True, y=True) m.move(zPos, cube + faceMapping['zPos'], worldSpaceDistance=True, z=True) m.move(zNeg, cube + faceMapping['zNeg'], worldSpaceDistance=True, z=True) m.xform(cube, cp=True) m.rename(cube, BBOX_NAME)
def create(baseCrv,curveList,inMeshList,prefix): ''' Create standard copyMeshToCurve setup based on the input arguments @param baseCrv: Base curve @type baseCrv: str @param curveList: List of curves to copy mesh to @type curveList: list @param inMeshList: List of meshes to copy to curves @type inMeshList: list @param prefix: Naming prefix @type prefix: str ''' # Create copyMeshToCurve node copyMeshToCurve = mc.createNode('copyMeshToCurve',n=prefix+'_copyMeshToCurve') # Connect base curve mc.connectAttr(baseCrv+'.worldSpace[0]',copyMeshToCurve+'.baseCurve',f=True) # Connect input curves connectInputCurves(copyMeshToCurve,curveList) # Connect input mesh connectInputMesh(copyMeshToCurve,inMeshList) # Create output mesh outMeshShape = mc.createNode('mesh',n=prefix+'_outMeshShape') outMesh = mc.listRelatives(outMeshShape,p=True)[0] mc.rename(outMesh,prefix+'_outMesh') # Connect out mesh mc.connectAttr(copyMeshToCurve+'.outputMesh',outMeshShape+'.inMesh',f=True) # Return Reult return copyMeshToCurve
def GetGroupName(self): #Check to see if the name is saved with the file if cmds.objExists("CMSettings"): ScenePrepClass.GroupName = cmds.getAttr("CMSettings.ModelName") if cmds.objExists(ScenePrepClass.GroupName): print "Group name from save" return 1 #Check to see if the model is already grouped then use that name# if self.SelectedObjectsAreGrouped() != "": if cmds.textField("NameTextField",query = True, text = True) != "": #Rename the group if a name has been provided cmds.rename(ScenePrepClass.GroupName, cmds.textField("NameTextField",query = True, text = True)) #Replace the name in cursel for x in range(len(ScenePrepClass.Cursel)): if ScenePrepClass.Cursel[x] == ScenePrepClass.GroupName: ScenePrepClass.Cursel[x] = cmds.textField("NameTextField",query = True, text = True) # ScenePrepClass.GroupName = cmds.textField("NameTextField",query = True, text = True) print "Group name from model" return 1 #otherwise check the textfield if cmds.textField("NameTextField",query = True, text = True) != "": ScenePrepClass.GroupName = cmds.textField("NameTextField",query = True, text = True) print "Group name from field" if ScenePrepClass.GroupName == "": cmds.confirmDialog(m = "Please enter a name for the model") return 0
def insertDots(self): # copy dot object # copy cutout object # run mesh difference # delete the layers # delete the groups # rename the cutout. for dot in self.dots: # Copy sphere object from the template object. newDot = cmds.duplicate(self.getTemplateObjectName(dot.templateName()))[0] for cutout in dot.cutouts: # Copy cutout object from the template object, and rotate it. newCutout = cmds.duplicate(self.getTemplateObjectName(cutout.shape))[0] cutoutDagPath = self.getDagPathFromPath(newCutout) mfnTransform = OpenMaya.MFnTransform(cutoutDagPath) mfnTransform.rotateBy(cutout.rotation, OpenMaya.MSpace.kTransform) # Mesh boolean combine, with 'difference' operator. boolOp = cmds.polyBoolOp(newDot, newCutout, op=2) # Update the dot copy name and remove history. newDot = boolOp[0] cmds.delete(newDot, constructionHistory=True) dotPath = "dot_{0}".format(dot.name()) cmds.rename(newDot, dotPath) # Move the new dot onto the final grid for printing. self.positionDot(dotPath, dot.vertexId)
def addPrefixToGroup(self,*args): ui.saveAddPrefixText() prefix = cmds.textField( 'prefixTextField', query=True, tx=True ) for group in cmds.ls( sl=True ): groupItems = cmds.listRelatives( group, children=True, pa=True ) for item in groupItems: cmds.rename( item, prefix+item )
def ProjectCustom_SetUI(): # vvv 2/3 # Completely Custom tool for current proj. sSideCamera = 'SIDE_CAM' if not cmds.objExists(sSideCamera): oSideCamera = cmds.camera() cmds.rename(oSideCamera[0], '%s'%sSideCamera) oSel = [str(s) for s in cmds.ls(sl = True, o = True)] # Creation of SideCam sSideCamera = 'SIDE_CAM' if not cmds.objExists(sSideCamera): oSideCamera = cmds.camera() cmds.rename(oSideCamera[0], '%s'%sSideCamera) # Scene Storage. StudioSetting.SceneInfoStorage() dSceneInfo = { 'CustomCamViews':0, 'CustomCamViewList':[]} # Node Structure Creation aGroup = [ 'lllllllllllllllll__CAMERAs__lllllllllllllllll', 'CardRig___', 'SideCam___', 'FaceCam___', 'RenderCam___', 'lllllllllllllllll__Main_Puppet__lllllllllllll', 'lllllllllllllllll__Sub_Puppet__llllllllllllll', 'lllllllllllllllll__Lights__llllllllllllllllll'] # Do not change the list order. Possible to add more. cmds.select(clear = True) iError = 0 # Parent Nodes for g in aGroup: if not cmds.objExists(g): if '___' in g: cmds.group( em = True, name = g, p = aGroup[0]) else: cmds.group( em = True, name = g) if g == aGroup[0]: cmds.addAttr(aGroup[0], shortName = 'notes', dataType = 'string') # Activate Notes Attributes to store json StudioSettings.SceneInfoStorage(aGroup[0], dSceneInfo) # Store dSceneInfo if 'lllll' in g: vColour = UIColourControl.keywordColour('MayaBG') vColour = UIColourControl.offsetRGBvalues(vColour, R = 0.3, G = 0.3, B = 0.3) for i, v in enumerate('RGB'): cmds.setAttr('%s.useOutlinerColor'%g, True) cmds.setAttr('%s.outlinerColor%s'%(g, v), vColour[i]) ## Logic to find available cameras. (find children for camera) dSceneInfo = StudioSettings.SceneInfoStorage(aGroup[0]) # Get dSceneInfo dSceneInfo['CustomCamViewList'] = [] for cam in aGroup[2:5]: # Using aGroup[2 to 4] if cmds.listRelatives(cam, c = True, ad = True, type = 'camera'): dSceneInfo['CustomCamViewList'].append(cam) dSceneInfo = StudioSettings.SceneInfoStorage(aGroup[0], dSceneInfo) # Store dSceneInfo (update) print dSceneInfo # Find Next Camera to Display if len(dSceneInfo['CustomCamViewList']) == 0: # If no camera is found. (not sorted under cam groups) iError = 1 # No camera found. aPrint = UIColourControl.inViewMessageColourPreset('Red', 'No Cameras found') iIndex = 0 elif dSceneInfo['CustomCamViews'] >= len(dSceneInfo['CustomCamViewList'])-1: iIndex = 0 else: iIndex = dSceneInfo['CustomCamViews'] + 1 if not iError: # If cameras are found... sCamera = dSceneInfo['CustomCamViewList'][iIndex] aCamera = cmds.listRelatives(sCamera, c = True, ad = True, type = 'camera') if sCamera == aGroup[4]: aPrint = UIColourControl.inViewMessageColourPreset('Green', 'RENDER cam') aVis = [1, 1, 0, 0, 1, None, None, 1] aCamKeyword = ['Left', 'render', 'legalCam'] elif sCamera == aGroup[3]: aPrint = UIColourControl.inViewMessageColourPreset('Blue', ' FACE cam ') aVis = [1, 0, 0, 1, 0, None, None, 0] aCamKeyword = ['Shape1', 'FACE'] elif sCamera == aGroup[2]: aPrint = UIColourControl.inViewMessageColourPreset('Gray', ' SIDE cam ') aVis = [1, 0, 1, 0, 1, None, None, 1] aCamKeyword = ['SIDE_CAM'] # Hide unnecessary Groups of camera. for i, v in enumerate(aVis): if not v == None: cmds.setAttr('%s.visibility'%aGroup[i], v) # Pick camera of the first match in the keyword. sCamera = None sTCamera = None # This is needed if keyword search fails. (Just to have something selected.) for c in aCamera: sCamera = c for k in aCamKeyword: if k in c: sTCamera = c break if sTCamera: sCamera = sCamera if sCamera: cmds.modelEditor('modelPanel4', e = True, camera = sCamera) cmds.modelEditor('modelPanel1', e = True, camera = 'ANIM_CAM', activeView = True) # Print Statement cmds.inViewMessage(amg = '<text style="color:#%s";>%s</text>'%(aPrint[0], aPrint[1]), pos = 'botCenter', fade = True, fts = 10, ft = 'arial',bkc = aPrint[2] ) # Store Scene Info. dSceneInfo['CustomCamViews'] = iIndex StudioSettings.SceneInfoStorage(aGroup[0], dSceneInfo) # Store dSceneInfo cmds.select(oSel, r = True)
def setupControl(self,*args): #Load variables name = cmds.textFieldGrp(self.nameField,q=True,text=True) control = cmds.textFieldButtonGrp(self.controlField,q=True,text=True) rivet = cmds.textFieldButtonGrp(self.rivetField,q=True,text=True) constObj = cmds.textFieldButtonGrp(self.jointField,q=True,text=True) #Load selection verts = cmds.ls(sl=True,fl=True) #Create Cluster clusterName,clusterHandle = cmds.cluster(rel=True,n=name+'_clstr') #Delete Rivet's aim constraint because it causes flipping if the rivets lofted nurbs plane flips. #Add parent constraint to object.(constObj) """ try: temp = cmds.listConnections(rivet) cmds.delete(temp[1]) except: # No constraint to delete on rivet pass """ #Rivet WS location rivetLocation = cmds.xform(rivet,q=True,ws=True,t=True) #Snap Cluster pivots to rivetLocation self.move(clusterHandle, rivetLocation,t=False,sp=True,rp=True) #Snap Controls pivots to rivetLocation self.move(control, rivetLocation,t=False,sp=True,rp=True) #Group Cluster clusterGrp = cmds.group(clusterHandle) clusterGrp = cmds.rename(clusterGrp, name + 'Cluster_' + clusterHandle) #Create over ride group or_grp = cmds.group(em=True,name=name+"OR1") or2_grp = cmds.group(em=True,name=name+"OR2") #Parent override group to rivet cmds.parent(or_grp,or2_grp) cmds.parent(or2_grp,rivet) #Freeze transforms on override group cmds.makeIdentity(or_grp,apply=True,t=True,r=True,s=True,n=True) #Zero Control zeroNode = cmds.group(em=True,n=name + "nullGrp") pos = cmds.xform( control, q=1, ws=True, t=1) cmds.xform( zeroNode, ws=True, t=[pos[0], pos[1], pos[2]]) rot = cmds.xform( control, q=1, ws=True, ro=1) cmds.xform( zeroNode, ws=True, ro=[rot[0], rot[1], rot[2]]) scale = cmds.xform( control, q=1, r=1, s=1) cmds.xform( zeroNode, ws=True, s=[scale[0], scale[1], scale[2]]) #Snap zeroNode pivot to control controlLocation = cmds.xform(control,q=True,ws=True,rp=True) self.move(zeroNode, controlLocation, t=False, sp=True, rp=True) #parent control to OverRide group cmds.parent(control, zeroNode, a=True) cmds.parent(zeroNode,or_grp) #Connect control t,r,s to cluster, then hide the cluster and rivet group cmds.connectAttr(control + ".translate", clusterHandle + ".translate") cmds.connectAttr(control + ".rotate", clusterHandle + ".rotate") cmds.connectAttr(control + ".scale", clusterHandle + ".scale") #Create utility node and negate double transform #by reversing the transformation of or_grp <---- Cause of double transforms mdNode = cmds.createNode("multiplyDivide") nodeName = name + "_MD" cmds.rename(mdNode,nodeName) mdNode = nodeName #Unparent control cmds.parent(zeroNode,w=True) #Set up the MD node cmds.setAttr( "%s.input2X"%mdNode, -1) cmds.setAttr( "%s.input2Y"%mdNode, -1) cmds.setAttr( "%s.input2Z"%mdNode, -1) #Connect the nodes # control ---> mdNode cmds.connectAttr("%s.translateX"%control,"%s.input1X"%mdNode,f=True) cmds.connectAttr("%s.translateY"%control,"%s.input1Y"%mdNode,f=True) cmds.connectAttr("%s.translateZ"%control,"%s.input1Z"%mdNode,f=True) #mdNode ---> or_grp cmds.connectAttr("%s.outputX"%mdNode,"%s.translateX"%or_grp,f=True) cmds.connectAttr("%s.outputY"%mdNode,"%s.translateY"%or_grp,f=True) cmds.connectAttr("%s.outputZ"%mdNode,"%s.translateZ"%or_grp,f=True) #Reparent control cmds.parent(zeroNode,or_grp) #Get mesh name # ex. "meshName.vtx[35]" mesh = verts[0].split('.')[0] #Get meshDeformer meshDeformer = None try: meshDeformer = mel.eval('findRelatedSkinCluster("%s");'%mesh) except: pass """ history = cmds.listHistory(mesh) for each in history: #print " History: " + each if("skinCluster" in str(each)): #Possible match for meshDeformer if("Group" not in str(each)): meshDeformer = each if("cMuscleSystem" in str(each)): if("Group" not in str(each)): meshDeformer = each """ #Reorder deformer nodes if meshDeformer: #Move cluster + meshDeformer to top of deformer stack cmds.reorderDeformers(clusterHandle,meshDeformer,mesh) #Move meshDeformer to top of deformer stack cmds.reorderDeformers(meshDeformer,clusterHandle,mesh) #Create final group topGrp = cmds.group(em=True,name=name+"_followCnt_grp") cmds.parent(clusterGrp,rivet,topGrp) #Orient constrain rivet to constrain object if constObj: cmds.orientConstraint(constObj,rivet,mo=True) #Hide cluster grp cmds.setAttr(clusterGrp + ".visibility",0) #Hide the rivet rivetShape = cmds.listRelatives(rivet,shapes=True) cmds.setAttr(rivetShape[0] + ".visibility",0) # Add cluster atttribute to control cmds.addAttr(control,ln='cluster',min=0.0,max=1.0,dv=1.0) cmds.setAttr('%s.cluster'%control,l=False,k=True) # Connect it to the deformer cmds.connectAttr('%s.cluster'%control,'%s.envelope'%clusterName,f=True) #Clear selection cmds.select(clear=True)
def createDriverCrv (self, upLidBaseCrv, upRigGrp, lowLidBaseCrv, lowRigGrp): '''Create a driver curve for each lid curve and connect it to the base curve with a wire deformer. Called by 'buildRig' function. Call functions: 'eyelidsCorners', 'eyeLidsLeftAndRight' (unused), 'eyelidsCrvCVs', 'eyelidsMatchTopology' ''' ## Upper eyelid ## upLidDriverCrvTEMP = cmds.duplicate (upLidBaseCrv) [0] cmds.delete (upLidDriverCrvTEMP, ch = 1) # delete history cmds.rebuildCurve (upLidDriverCrvTEMP, rpo = 1, end = 1, kr = 2, kcp = 0, kep = 1, kt = 0, s = 4, d = 7, tol = 0.01) # list the position of the EPs of the upper lid driver curve upLidEpPosTEMP = [] x = 0 while x < 5 : posEp = cmds.xform ((upLidDriverCrvTEMP + ".ep[%d]" % x), q = 1, ws = 1, t = 1) upLidEpPosTEMP.append (posEp) x += 1 cmds.delete (upLidDriverCrvTEMP) # Create the upLid 'guide' curve for corner placement and query CVs positions and indexes upLidGuideCrv = cmds.curve (d = 3, ep = (upLidEpPosTEMP[0], upLidEpPosTEMP[1], upLidEpPosTEMP[2], upLidEpPosTEMP[3], upLidEpPosTEMP[4])) ## Lower eyelid ## lowLidDriverCrvTEMP = cmds.duplicate (lowLidBaseCrv) [0] cmds.delete (lowLidDriverCrvTEMP, ch = 1) # delete history cmds.rebuildCurve (lowLidDriverCrvTEMP, rpo = 1, end = 1, kr = 2, kcp = 0, kep = 1, kt = 0, s = 4, d = 7, tol = 0.01) # list the position of the EPs of the lower lid driver curve lowLidEpPosTEMP = [] x = 0 while x < 5 : posEp = cmds.xform ((lowLidDriverCrvTEMP + ".ep[%d]" % x), q = 1, ws = 1, t = 1) lowLidEpPosTEMP.append (posEp) x += 1 cmds.delete (lowLidDriverCrvTEMP) # Create the lowLid 'guide' curve for corner placement and query CVs positions and indexes lowLidGuideCrv = cmds.curve (d = 3, ep = (lowLidEpPosTEMP[0], lowLidEpPosTEMP[1], lowLidEpPosTEMP[2], lowLidEpPosTEMP[3], lowLidEpPosTEMP[4])) ## # Find position of eye corners self.cornerAPos, self.cornerBPos = self.eyelidsCorners (upLidEpPosTEMP, upLidGuideCrv, lowLidEpPosTEMP, lowLidGuideCrv) # Define "CornerA" and "CornerB" as "leftCorner" and "rightCorner" # ADD FUNC WHEN OK - self.eyeLidsLeftAndRight (self.cornerAPos, self.cornerBPos) # List CVs positions of upLidGuideCrv and lowLidGuideCrv upLidCVsPos, lowLidCVsPos = self.eyelidsCrvCVs (upLidGuideCrv, lowLidGuideCrv) # List CVs positions in the right order (to match topology) upLidCVsOrdered, lowLidCVsOrdered = self.eyelidsMatchTopology (self.cornerAPos, self.cornerBPos, upLidCVsPos, lowLidCVsPos) ## # Create upper driver curve self.upLidDriverCrv = cmds.curve (d = 3, p = (upLidCVsOrdered[0], upLidCVsOrdered[1], upLidCVsOrdered[2], upLidCVsOrdered[3], upLidCVsOrdered[4], upLidCVsOrdered[5], upLidCVsOrdered[6])) upLidDriverCrvName = upLidBaseCrv.replace ("_BASE_", "_DRIVER_") self.upLidDriverCrv = cmds.rename (self.upLidDriverCrv, upLidDriverCrvName) cmds.parent (self.upLidDriverCrv, upRigGrp) cmds.delete (upLidGuideCrv) # Create lower driver curve lowCrvTEMP = cmds.curve (d = 3, p = (lowLidCVsOrdered[0], lowLidCVsOrdered[1], lowLidCVsOrdered[2], lowLidCVsOrdered[3], lowLidCVsOrdered[4], lowLidCVsOrdered[5], lowLidCVsOrdered[6])) lowLidDriverCrvName = lowLidBaseCrv.replace ("_BASE_", "_DRIVER_") self.lowLidDriverCrv = cmds.rename (lowCrvTEMP, lowLidDriverCrvName) cmds.parent (self.lowLidDriverCrv, lowRigGrp) cmds.delete (lowLidGuideCrv) ## cmds.select (cl = 1) wireNodeUpLidName = upLidBaseCrv.replace ("_BASE_curve", "_controlCurve_wire") wireUpLid = cmds.wire (upLidBaseCrv, n = wireNodeUpLidName, w = self.upLidDriverCrv, gw = 0, en = 1, ce = 0, li = 0) cmds.select (cl = 1) wireNodeLowLidName = lowLidBaseCrv.replace ("_BASE_curve", "_controlCurve_wire") wireUpLid = cmds.wire (lowLidBaseCrv, n = wireNodeLowLidName, w = self.lowLidDriverCrv, gw = 0, en = 1, ce = 0, li = 0)
def importAbcCache(cachePath='',cacheName='',namespace='',parent='',mode='import',debug=False): ''' Import Alembic cache from file @param cachePath: Alembic cache file path @type cachePath: str @param cacheName: Alembic cache name. If empty, use filename. @type cacheName: str @param namespace: Namespace for cache. @type namespace: str @param parent: Reparent the whole hierarchy under an existing node in the current scene. @type parent: str @param mode: Import mode. "import", "open" or "replace". @type mode: str @param debug: Turn on debug message printout. @type debug: bool ''' # ========== # - Checks - # ========== # Load Import Plugin loadAbcImportPlugin() # Check Cache Path if not os.path.isfile(cachePath): raise Exception('Cache path "'+cachePath+'" is not a valid file!') # Check Cache Name if not cacheName: cacheBase = os.path.basename(cachePath) cacheName = os.path.splitext(cacheBase)[-1] # Check Namespace if namespace: if mc.namespace(ex=namespace): NSind = 1 while(mc.namespace(ex=namespace+str(NSind))): NSind += 1 namespace = namespace+str(NSind) # ============== # - Load Cache - # ============== cacheNode = mc.AbcImport(cachePath,mode=mode,debug=debug) cacheNode = mc.rename(cacheNode,cacheName+'Cache') # Get Cache Nodes cacheList = mc.listConnections(cacheNode,s=False,d=True) # Get Cache Roots rootList = [] for cacheItem in cacheList: root = cacheItem while mc.listRelatives(root,p=True) != None: root = mc.listRelatives(root,p=True,pa=True)[0] if not rootList.count(root): rootList.append(root) # Add to Namespace if namespace: for root in rootList: glTools.utils.namespace.addHierarchyToNS(root,namespace) # Parent if parent: # Check Parent Transform if not mc.objExists(parent): parent = mc.group(em=True,n=parent) # Parent mc.parent(rootList,parent) # ================= # - Return Result - # ================= return cacheNode
def importGpuCache(cachePath,cacheName='',namespace=''): ''' Import GPU Alembic cache from file @param cachePath: Alembic cache file path @type cachePath: str @param cacheName: Alembic cache name. If empty, use filename. @type cacheName: str ''' # ========= # - Check - # ========= # Load Import Plugin loadAbcImportPlugin() # Check Cache Path if not os.path.isfile(cachePath): raise Exception('Cache path "'+cachePath+'" is not a valid file!') # Check Cache Name if not cacheName: cacheBase = os.path.basename(cachePath) cacheName = os.path.splitext(cacheBase)[-1] # Check Namespace if namespace: if mc.namespace(ex=namespace): NSind = 1 while(mc.namespace(ex=namespace+str(NSind))): NSind += 1 namespace = namespace+str(NSind) # ============== # - Load Cache - # ============== # Create Cache Node cacheNode = mc.createNode('gpuCache',name=cacheName+'Cache') cacheParent = mc.listRelatives(cacheNode,p=True,pa=True) cacheParent = mc.rename(cacheParent,cacheName) # Set Cache Path mc.setAttr(cacheNode+'.cacheFileName',cachePath,type='string') # =================== # - Apply Namespace - # =================== if namespace: # Create Namespace (if necessary) if not mc.namespace(ex=namespace): mc.namespace(add=namespace) # Apply Namespace cacheParent = mc.rename(cacheParent,namespace+':'+cacheParent) # Update cacheNode cacheNode = mc.listRelatives(cacheParent,s=True,pa=True)[0] # ================= # - Return Result - # ================= return cacheParent
def get_bb_pos(arg=None, shapes=False, mode='center', mark=False, asEuclid=False): """ Get points relative to a bounding box where z is forward :parameters: arg(str/list): Object(s) to check shapes(bool): Only check dag node shapes mode(varied): center bottom top left right front back mark(bool): whether to add a locator at the position for testing asEuclid(bool) - whether to return as Vector or not :returns boundingBox size(list) """ _str_func = 'get_bb_pos' #_arg = VALID.stringListArg(arg,False,_str_func) _sel = mc.ls(sl=True) bb_raw = get_bb_size(arg, shapes, mode='raw') _mode = mode.lower() if _mode == 'center': log.debug("|{0}| >> Center mode".format(_str_func)) _res = [((bb_raw[0] + bb_raw[3]) / 2), ((bb_raw[4] + bb_raw[1]) / 2), ((bb_raw[5] + bb_raw[2]) / 2)] elif _mode in ['bottom', 'y-']: log.debug("|{0}| >> Bottom mode".format(_str_func)) _res = [((bb_raw[0] + bb_raw[3]) / 2), bb_raw[1], ((bb_raw[5] + bb_raw[2]) / 2)] elif _mode in ['top', 'y+']: log.debug("|{0}| >> Top mode".format(_str_func)) _res = [((bb_raw[0] + bb_raw[3]) / 2), bb_raw[4], ((bb_raw[5] + bb_raw[2]) / 2)] elif _mode in ['front', 'z+']: log.debug("|{0}| >> Front mode".format(_str_func)) _res = [((bb_raw[0] + bb_raw[3]) / 2), ((bb_raw[4] + bb_raw[1]) / 2), bb_raw[5]] elif _mode in ['back', 'z-']: log.debug("|{0}| >> Back mode".format(_str_func)) _res = [((bb_raw[0] + bb_raw[3]) / 2), ((bb_raw[4] + bb_raw[1]) / 2), bb_raw[2]] elif _mode in ['left', 'x+']: log.debug("|{0}| >> Left mode".format(_str_func)) _res = [ bb_raw[3], ((bb_raw[4] + bb_raw[1]) / 2), ((bb_raw[5] + bb_raw[2]) / 2) ] elif _mode in ['right', 'x-']: log.debug("|{0}| >> Right mode".format(_str_func)) _res = [ bb_raw[0], ((bb_raw[4] + bb_raw[1]) / 2), ((bb_raw[5] + bb_raw[2]) / 2) ] else: raise ValueError, "|{0}| >> Unknown mode: {1}".format(_str_func, _mode) if mark: _size = get_bb_size(arg, shapes) _loc = mc.spaceLocator()[0] ATTR.set(_loc, 'scale', [v / 4 for v in _size]) mc.move(_res[0], _res[1], _res[2], _loc, ws=True) mc.rename(_loc, '{0}_loc'.format(_mode)) if _sel: mc.select(_sel) if asEuclid: log.debug("|{0}| >> asEuclid...".format(_str_func)) return EUCLID.Vector3(_res[0], _res[1], _res[2]) return _res
def attachToMeshFol(cls, srcObj, trgMeshShp, oriOpt, revGrpOpt, mPosOffOpt, mOriOffOpt): # Mesh uv is must exists. # Follicle ignore target mesh's transform value. So, Duplicate target mesh and freeze transform temporarily to get accurate u and v parameter. cmds.select(cls.trgObj, r=True) tak_cleanUpModel.cleanChBox() tmpMesh = cmds.duplicate(trgMeshShp) try: cmds.parent(tmpMesh, world=True) except: pass cmds.makeIdentity(tmpMesh, apply=True) tmpMeshShp = cmds.listRelatives(tmpMesh, s=True)[0] tmpSrcObj = cmds.duplicate(srcObj)[0] if not cmds.listRelatives(tmpSrcObj, p=True) is None: cmds.parent(tmpSrcObj, world=True) clPtOnMeshNode = cmds.createNode('closestPointOnMesh', n=srcObj + '_clPtOnMesh') cmds.connectAttr('%s.outMesh' % (tmpMeshShp), '%s.inMesh' % (clPtOnMeshNode), force=True) cmds.connectAttr('%s.translate' % (tmpSrcObj), '%s.inPosition' % (clPtOnMeshNode), force=True) parmUVal = cmds.getAttr('%s.parameterU' % (clPtOnMeshNode)) parmVVal = cmds.getAttr('%s.parameterV' % (clPtOnMeshNode)) cmds.delete(clPtOnMeshNode, tmpMesh, tmpSrcObj) # Create follicle and connect nodes. fol = cmds.createNode('follicle') folPrnt = cmds.listRelatives(fol, parent=True)[0] folPrnt = cmds.rename(folPrnt, srcObj + '_fol') fol = cmds.listRelatives(folPrnt, s=True)[0] cmds.connectAttr('{0}.worldMesh'.format(trgMeshShp), '{0}.inputMesh'.format(fol)) cmds.connectAttr('{0}.worldMatrix'.format(trgMeshShp), '{0}.inputWorldMatrix'.format(fol)) cmds.connectAttr('{0}.outTranslate'.format(fol), '{0}.translate'.format(folPrnt)) cmds.setAttr('{0}.parameterU'.format(fol), parmUVal) cmds.setAttr('{0}.parameterV'.format(fol), parmVVal) cmds.setAttr('%s.visibility' % (fol), False) anchorGrp = cmds.createNode('transform', n=srcObj + '_anchor') cmds.connectAttr('{0}.translate'.format(folPrnt), '{0}.translate'.format(anchorGrp)) if oriOpt: cmds.connectAttr('{0}.outRotate'.format(fol), '{0}.rotate'.format(folPrnt)) cmds.connectAttr('{0}.rotate'.format(folPrnt), '{0}.rotate'.format(anchorGrp)) # Get srcObj parent before parent to anchorGrp. srcPrnt = cmds.listRelatives(srcObj, p=True) # Parent srcObj to anchorGrp. cmds.parent(srcObj, anchorGrp) # If srcPrnt exists, reparent anchorGrp to srcObj's old parent. if srcPrnt: cmds.parent(anchorGrp, srcPrnt[0]) if not mPosOffOpt: cls.setZeroAttr(srcObj, 'pos') if not mOriOffOpt: cls.setZeroAttr(srcObj, 'ori') if cmds.objectType(srcObj) == "joint": cls.setZeroJntOri(srcObj) if revGrpOpt: cls.reverseGrp(srcObj) return folPrnt
def createIkSpineSet(self): IKH = ikHandleMaker(self.spineJointList[1], self.spineJointList[-1], 'ikSplineSolver') print IKH IKH = [u'ikHandle1', u'effector1', u'curve1'] handleName = cmds.rename(IKH[0], 'C_IK_spine1_HDL') effectorName = cmds.rename(IKH[1], 'C_IK_spine1_EFFECTOR') curveName = cmds.rename(IKH[2], 'C_IK_spine1_CRV') cmds.rebuildCurve(curveName, s=2, d=3) locatorName = curveToLocatorFix(curveName) print locatorName cmds.parent(curveName, w=True) for x in range(len(locatorName)): NUL = homeNul(locatorName[x]) self.locatorNulList.append(NUL) # Advanced Twist Controls Set upLoc = cmds.spaceLocator(n=self.upBody.replace('CON', 'aTwist_LOC')) POsnap(upLoc, self.spineJointList[-1]) cmds.parent(upLoc, self.upBodySubCon) #[u'C_IK_root_JNT', u'C_IK_spine1_JNT', u'C_IK_spine2_JNT', u'C_IK_spine3_JNT', u'C_IK_chest_JNT'] lowLoc = cmds.spaceLocator(n=self.lowBody.replace('CON', 'aTwist_LOC')) POsnap(lowLoc, self.spineJointList[1]) cmds.parent(lowLoc, self.lowBodySubCon) cmds.setAttr('%s.dTwistControlEnable' % handleName, 1) cmds.setAttr('%s.dWorldUpType' % handleName, 4) cmds.setAttr('%s.dWorldUpAxis' % handleName, 0) cmds.setAttr('%s.dWorldUpVectorX' % handleName, 0) cmds.setAttr('%s.dWorldUpVectorY' % handleName, 1) cmds.setAttr('%s.dWorldUpVectorZ' % handleName, 0) cmds.setAttr('%s.dWorldUpVectorEndX' % handleName, 0) cmds.setAttr('%s.dWorldUpVectorEndY' % handleName, 1) cmds.setAttr('%s.dWorldUpVectorEndZ' % handleName, 0) cmds.connectAttr('%s.worldMatrix' % lowLoc[0], '%s.dWorldUpMatrix' % handleName) cmds.connectAttr('%s.worldMatrix' % upLoc[0], '%s.dWorldUpMatrixEnd' % handleName) # cmds.orientConstraint(self.upBodySubCon, self.spineJointList[-1], mo=True) #print self.locatorNulList[u'C_IK_spine1_NUL', u'C_IK_spine2_NUL', u'C_IK_spine3_NUL', u'C_IK_spine4_NUL'] AP_low0 = attachPart(self.lowBodySubCon, self.locatorNulList[0], 'translate', 'rotate', 'scale', 'shear') AP_low1 = attachPart(self.lowBodySubCon, self.locatorNulList[1], 'translate', 'rotate', 'scale', 'shear') AP_up4 = attachPart(self.upBodySubCon, self.locatorNulList[3], 'translate', 'rotate', 'scale', 'shear') AP_up5 = attachPart(self.upBodySubCon, self.locatorNulList[4], 'translate', 'rotate', 'scale', 'shear') cmds.parentConstraint(self.hipCon, self.spineJointList[0], mo=True) #...... AP_lowBoy = attachPart(self.spineControllerList[0], self.lowBodyNul, 'translate', 'rotate', 'scale', 'shear') AP_upBoy = attachPart(self.spineControllerList[0], self.upBodyNul, 'translate', 'rotate', 'scale', 'shear') #... #noneScaleSpineGroup = cmds.group( handleName, curveName, self.locatorNulList[0], self.locatorNulList[1], self.locatorNulList[2], self.locatorNulList[3], # self.locatorNulList[4], self.locatorNulList[5], name='noneScaleSpine_GRP' ) """ cmds.parent( noneScaleSpineGroup, 'noneScale_GRP' ) cmds.parent( self.spineJointList[0], 'C_IK_spineJoint_GRP' ) cmds.parent( self.spineControllerNulList[0], 'C_move_CON' ) cmds.parent( self.lowBodyNul, 'C_IK_spineController_GRP' ) cmds.parent( self.upBodyNul, 'C_IK_spineController_GRP' ) cmds.parent( AP_low0, 'C_IK_spineAttach_GRP' ) cmds.parent( AP_low1, 'C_IK_spineAttach_GRP' ) cmds.parent( AP_low2, 'C_IK_spineAttach_GRP' ) cmds.parent( AP_up3, 'C_IK_spineAttach_GRP' ) cmds.parent( AP_up4, 'C_IK_spineAttach_GRP' ) cmds.parent( AP_up5, 'C_IK_spineAttach_GRP' ) cmds.parent( AP_lowBoy, 'C_IK_spineAttach_GRP' ) cmds.parent( AP_upBoy, 'C_IK_spineAttach_GRP' ) """ spineMiddleCon = controllerShape('C_IK_spineMiddle_CON', 'hexagon', 'yellow') print spineMiddleCon #POsnap( spineMiddleCon, self.locatorNulList[2] ) cmds.delete( cmds.parentConstraint(self.upBody, self.lowBody, spineMiddleCon)) spineMiddleConNul = homeNul(spineMiddleCon) cmds.parentConstraint(self.upBodySubCon, self.lowBodySubCon, spineMiddleConNul, mo=True) attachPart(spineMiddleCon, self.locatorNulList[2], 'translate', 'rotate', 'scale', 'shear')
def LumberyardCreateProxies(*args): ##This function creates the proxy objects and parents them to joints #create display layers for proxy's visibility to easily be toggled LumberyardCreateProxyLayer() #variable for the display layer layerPhys = g_nameOfDisplayLayer #make a list of all of the selected objects selectedObjects = cmds.ls(selection = True) #if nothing is selected throw a warning if (len(selectedObjects) == 0): cmds.warning('No joints selected. Select Joints and press the Add Joints button.') else: for selectedObject in selectedObjects: if cmds.objectType(selectedObject, isType = 'joint' ) == True: shapeOfProxy = proxyCreationSettings.shape #get the joint node's position in world space jointStartPosition = cmds.xform(selectedObject, query = True, worldSpace = True, translation = True) proxyPosition = jointStartPosition proxyWidth = float(proxyCreationSettings.width) proxyLength = proxyWidth if (g_centerString in proxyCreationSettings.objectOrient) == False: proxyPosition = CreateProxyPositionFromChildren(selectedObject) #find out the length of the average child joints distanceBetweenPoints = math.sqrt(math.pow((jointStartPosition[0] - proxyPosition[0]), 2) + math.pow((jointStartPosition[1] - proxyPosition[1]) ,2) + math.pow((jointStartPosition[2] - proxyPosition[2]), 2)) proxyLength = distanceBetweenPoints * 2 #create the proxy shape if (shapeOfProxy == g_shapeTypes[g_boxIndex]): proxyShape = cmds.polyCube(height = proxyLength, width = proxyWidth, depth = proxyWidth, createUVs = 1,constructionHistory = True) else: proxyRadius = proxyWidth/2 if (shapeOfProxy == g_shapeTypes[g_capsuleIndex]): if (proxyLength > proxyWidth): proxyShape = cmds.polyCylinder(radius = proxyRadius, height = proxyLength - (proxyRadius *2), roundCap = True, subdivisionsCaps = 3) else: proxyShape = cmds.polySphere(radius = proxyRadius * 2, subdivisionsAxis = 16, subdivisionsHeight = 16) else: proxyShape = cmds.polySphere(radius = proxyRadius * 2, subdivisionsAxis = 16, subdivisionsHeight = 16) #add object to the phys display layer cmds.editDisplayLayerMembers( layerPhys, proxyShape[0]) #add an attribute to easily find our created proxy cmds.addAttr(proxyShape, longName = 'lumberyardPhysProxy', defaultValue = 1) #add material to proxy if (proxyCreationSettings.proxyMaterialName != 'no material'): LumberyardAddMaterialToProxy(proxyShape) #add orientation to proxy LumberyardOrientProxy(proxyShape[0]) #move proxy into place cmds.move(proxyPosition[0], proxyPosition[1], proxyPosition[2], proxyShape, worldSpace = True) #orient the proxy so its aiming toward the parent joint. can we do this with vector math instead? aimConsProxy = cmds.aimConstraint(selectedObject, proxyShape) cmds.delete(aimConsProxy) orientConsProxy = cmds.orientConstraint(selectedObject, proxyShape, skip = 'none') cmds.delete(orientConsProxy) #if the orient pulldown defines this as a center, center its orient on the joint. if (g_centerString in proxyCreationSettings.objectOrient): cmds.move(jointStartPosition[0], jointStartPosition[1],jointStartPosition[2], proxyShape[0], worldSpace = True) else: cmds.move(jointStartPosition[0], jointStartPosition[1], jointStartPosition[2], proxyShape[0] + ".scalePivot", proxyShape[0] + ".rotatePivot", worldSpace = True) #parent it to the joint cmds.parent(proxyShape[0], selectedObject) #freeze the proxy. this will zero out its translate values relative to its parent joint cmds.makeIdentity(proxyShape[0], apply = True, scale = 1, rotate = 1, translate = 1, normal = 0) #delete construction history cmds.delete(proxyShape[0],constructionHistory=True) #rename the proxy with the proper name cmds.rename(proxyShape[0], selectedObject + g_physPostfix) else: cmds.warning(selectedObject + " is not a joint. No proxy created.")
def createIkSpineController(self): rootCon = fkControllerMaker('cross', 'yellow', [self.spineJointList[0]]) spine1Con = fkControllerMaker('cube', 'yellow', [self.spineJointList[1]]) chestCon = fkControllerMaker('cube', 'yellow', [self.spineJointList[-1]]) self.spineControllerList = rootCon[0][0], spine1Con[0][0], chestCon[0][ 0] self.spineControllerNulList = rootCon[1][0], spine1Con[1][0], chestCon[ 1][0] self.spineConstraintList = rootCon[2][0], spine1Con[2][0], chestCon[2][ 0] cmds.delete(self.spineConstraintList) """ for each in range( len(self.spineControllerNulList)-1 ): cmds.delete( cmds.aimConstraint( self.spineJointList[each+1], self.spineControllerNulList[each], aimVector=[0,1,0], upVector=[0,0,-1], worldUpType='vector', worldUpVector=[0,1,0] ) ) cmds.delete( cmds.aimConstraint( self.spineJointList[-2], self.spineControllerNulList[-1], aimVector=[0,-1,0], upVector=[0,0,-1], worldUpType='vector', worldUpVector=[0,1,0] ) ) """ self.hipCon = controllerShape('C_IK_hip_CON', 'cube', 'yellow') #print self.spineJointList[1] POsnap(self.hipCon, self.spineJointList[0]) hipConNul = homeNul(self.hipCon) """ cmds.delete( cmds.aimConstraint( self.spineJointList[2], hipConNul, aimVector=[0,1,0], upVector=[0,0,-1], worldUpType='vector', worldUpVector=[0,1,0] ) ) """ #cmds.parent( hipConNul, self.spineControllerList[1] ) # 'C_IK_hip_CON' pivot moving~~ lowBodyPos = cmds.xform(spine1Con[0], ws=True, t=True, q=True) cmds.move(lowBodyPos[0], lowBodyPos[1], lowBodyPos[2], '%s.rotatePivot' % self.hipCon) cmds.move(lowBodyPos[0], lowBodyPos[1], lowBodyPos[2], '%s.rotatePivot' % hipConNul) hipConCvN = cmds.getAttr('%s.spans' % self.hipCon) cmds.select('%s.cv[0:%s]' % (self.hipCon, hipConCvN)) cmds.scale(0.8, 0.8, 0.8, ocp=True) cmds.select(cl=True) # Add Sub Controller print self.spineControllerNulList self.lowBodySubCon = controllerShape('C_IK_lowBodySub_CON', 'cube', 'yellow') self.upBodySubCon = controllerShape('C_IK_upBodySub_CON', 'cube', 'yellow') lowBodySubConCvN = cmds.getAttr('%s.spans' % self.lowBodySubCon) cmds.select('%s.cv[0:%s]' % (self.lowBodySubCon, lowBodySubConCvN)) cmds.scale(0.8, 0.8, 0.8, ocp=True) cmds.select(cl=True) upBodySubConCvN = cmds.getAttr('%s.spans' % self.upBodySubCon) cmds.select('%s.cv[0:%s]' % (self.upBodySubCon, upBodySubConCvN)) cmds.scale(0.8, 0.8, 0.8, ocp=True) cmds.select(cl=True) self.lowBodySubConNul = homeNul(self.lowBodySubCon) self.upBodySubConNul = homeNul(self.upBodySubCon) POsnap(self.lowBodySubConNul, spine1Con[0][0]) POsnap(self.upBodySubConNul, chestCon[0][0]) cmds.parent(self.lowBodySubConNul, spine1Con[0][0]) cmds.parent(self.upBodySubConNul, chestCon[0][0]) cmds.parent(hipConNul, self.lowBodySubCon) #........................................................................................ #print self.spineControllerList#(u'C_IK_root_CON', u'C_IK_spine1_CON', u'C_IK_chest_CON') self.lowBody = cmds.rename(self.spineControllerList[1], 'C_IK_lowBody_CON') self.upBody = cmds.rename(self.spineControllerList[2], 'C_IK_upBody_CON') self.lowBodyNul = cmds.rename(self.spineControllerNulList[1], 'C_IK_lowBody_NUL') self.upBodyNul = cmds.rename(self.spineControllerNulList[2], 'C_IK_upBody_NUL')
def _buildSideSplashEmitter(name='', boatName='', splashParticleName=[], boatIntersectCurveShape='', sideAnimatable='', presetName=None): """ New builder for sideSplash nParticle Emitter Checks if the NPARTICLE_EMITTLERS_hrc exists or not too @param name: The name of the new emitter @param splashParticleName: List of the names of nParticleShape nodes to connect to the emitter @param boatIntersectCurveShape: The name of the intersection curve to emit from. @type name: String @type splashParticleName: List @type boatIntersectCurveShape: String """ if not cmds.objExists('nPARTICLE_EMITTERS_hrc'): cmds.group(n='nPARTICLE_EMITTERS_hrc', em=True) debug(None, method='_buildSideSplashEmitter', message='name: %s' % name, verbose=False) # Get base flat surface lineCurve = cmds.curve(name='%s_extrudeCurve' % name, degree=1, point=[(-0.01, 0, 0), (0.01, 0, 0)]) flatSurface = cmds.extrude(lineCurve, boatIntersectCurveShape, name='%s_flatSurface' % name, constructionHistory=True, range=False, polygon=0, useComponentPivot=1, fixedPath=True, useProfileNormal=True, extrudeType=2, reverseSurfaceIfPathReversed=True)[0] cmds.rebuildSurface(flatSurface, constructionHistory=True, replaceOriginal=True, rebuildType=0, endKnots=1, keepCorners=False, spansU=1, degreeU=1, spansV=100, degreeV=3) # Offset upwards curve from surface offsetUp = cmds.offsetCurve('%s.u[0.5]' % flatSurface, name='%s_offsetUp' % name, distance=0, constructionHistory=True, range=0, subdivisionDensity=1)[0] cmds.rebuildCurve(offsetUp, constructionHistory=False, replaceOriginal=True, end=1, keepRange=0, keepControlPoints=True, degree=1) cmds.setAttr('%s.translateY' % offsetUp, 0.01) # Offset from upwards curve with distance and translate down to get the 45 degree angle offset_distance = -0.01 offsetOut = cmds.offsetCurve(offsetUp, name='%s_offsetOut' % name, distance=offset_distance, constructionHistory=True, range=0, subdivisionDensity=1)[0] cmds.setAttr('%s.translateY' % offsetOut, offset_distance) # Finally, loft a non-flipping surface solution (45 degree angle of the boat) noFlipSurface = cmds.loft(offsetUp, offsetOut, degree=1, constructionHistory=True, range=0, polygon=0, sectionSpans=1)[0] noFlipSurface = cmds.rename(noFlipSurface, '%s_noFlipSurface' % name) ## Build the emitter emitter = cmds.emitter(noFlipSurface, name='%s_emitter' % name, type='surface') # Create closestPointOnSurface for acceleration expression where front more acceleration cPoS = cmds.createNode('closestPointOnSurface', name='%s_cPoS' % name) cmds.connectAttr('%s.worldSpace' % noFlipSurface, '%s.inputSurface' % cPoS) ## Build the emitter group if it doesn't already exist emitterGroup = '%s_hrc' % name if not cmds.objExists(emitterGroup): cmds.group(lineCurve, flatSurface, offsetUp, offsetOut, noFlipSurface, emitter[0], n=emitterGroup) debug(None, method='_buildSideSplashEmitter', message='emitterName: %s' % emitter[1], verbose=False) ## Check if a custom preset has been assigned via the func flags for the emitter, if not use the default preset... if presetName: pathToPreset = '%s/%s' % (CONST.EMITTERBASEPRESETPATH, presetName) debug(None, method='_buildSideSplashEmitter', message='pathToPreset: %s' % pathToPreset, verbose=False) mel.eval('applyPresetToNode "%s" "" "" "%s" 1;' % (emitter[1], pathToPreset)) ## Now parent it try: cmds.parent(emitterGroup, 'nPARTICLE_EMITTERS_hrc') except: pass ## Connect the emitter to the particles debug(None, method='_buildSideSplashEmitter', message='Connected %s: %s' % (splashParticleName, emitter[1]), verbose=False) for each in splashParticleName: _connect_NParticleShape_to_NParticleEmitter(particleShapeNode=each, emitter=emitter[1]) ## Now do the expression for the side emitter if 'IntersectCurveRight' in emitter[1]: direction = 'R' else: direction = 'L' expStringList = [ 'float $minSpeed = %s.minSpeed;\n' % sideAnimatable, 'float $maxSpeed = %s.maxSpeed;\n' % sideAnimatable, 'float $speed = %s:world_ctrl.speed;\n' % boatName, 'float $curve = smoothstep($minSpeed, $maxSpeed, $speed);\n', 'float $rateMuliplier = %s.rateMultiplier%s;\n' % (sideAnimatable, direction), 'float $splashMaxSpeed = %s.splashMaxSpeed%s;\n' % (sideAnimatable, direction), '\n', 'if (%s.useSpeed == 1)\n' % sideAnimatable, '{\n\t', '%s.rate = $rateMuliplier * $curve;\n' % emitter[1], '\n\t\t', 'float $emitterSpeed = $splashMaxSpeed * $curve;\n\t\t', 'if ($emitterSpeed == 0)\n\t\t', '{\n\t\t\t', '$emitterSpeed = 0.1;\n\t\t', '}\n\t\t', '%s.speed = $emitterSpeed;\n' % emitter[1], '}\n', 'else\n', '{\n\t', '%s.rate = $rateMuliplier;\n\t' % emitter[1], '%s.speed = $splashMaxSpeed;\n' % emitter[1], '}\n', ] ## Check if the expression already exists in the scene, if so delete it utils.checkExpressionExists('%s_sideSplashEmitter' % boatName) ## Build new expression cmds.expression(emitter[1], n='%s_sideSplashEmitter' % emitter[1], string=utils.processExpressionString(expStringList)) ## Connect some attributes if not cmds.isConnected('%s.normalSpeed%s' % (sideAnimatable, direction), '%s.normalSpeed' % emitter[1]): cmds.connectAttr('%s.normalSpeed%s' % (sideAnimatable, direction), '%s.normalSpeed' % emitter[1]) if not cmds.isConnected('%s.randomSpeed%s' % (sideAnimatable, direction), '%s.speedRandom' % emitter[1]): cmds.connectAttr('%s.randomSpeed%s' % (sideAnimatable, direction), '%s.speedRandom' % emitter[1]) return cPoS
def build(self): """ """ super(Limb, self).build() self._ikfkSystem = rigIkFk.IkFkLimb( (self._startJoint.getPartialPath(), self._middleJoint.getPartialPath(), self._endJoint.getPartialPath())) self._ikfkSystem.create() self._ikfkSystem.setGroup( cmds.rename( self._ikfkSystem.getGroup(), "{0}_{1}".format(self._name, self._ikfkSystem.getGroup()))) cmds.parent(self._ikfkSystem.getGroup(), self._rigGroup.getPartialPath()) cmds.setAttr("{0}.v".format(self._ikfkSystem.getGroup()), 0) ikJointList = self._ikfkSystem.getIkJoints() fkJointList = self._ikfkSystem.getFkJoints() #------------------------------------------------- #FK SYSTEM #------------------------------------------------- fkControls = list() parent = self._rigGroup for jnt in (fkJointList): # create new control. ctrl = rigControl.Control( name=jnt.replace("{0}_{1}".format(rigName.BIND, rigName.FK), rigName.CONTROL), position=cmds.xform(jnt, q=True, ws=True, t=True), parent=parent, shape="circle", color=rigName.SIDECOLOR[rigName.getSide(self._name)]) ctrl.create() ctrl.setMatrix(cmds.xform(jnt, q=True, ws=True, m=True)) # constrain the joints to the controls cmds.pointConstraint(ctrl.getPartialPath(), jnt) cmds.orientConstraint(ctrl.getPartialPath(), jnt) # name the ctrl as the new parent and append to control list parent = ctrl fkControls.append(ctrl) #------------------------------------------------- # IK SYSTEM #------------------------------------------------- # create ik controls. ikCtrl = rigControl.Control( "{0}_{1}".format(self._name, rigName.CONTROL), position=self._endJoint.getPosition(), parent=self._rigGroup.getPartialPath(), shape="circle", color=rigName.SIDECOLOR[rigName.getSide(self._name)]) ikCtrl.create() offsetJnt = rigJoint.Joint("{0}_offset".format(ikJointList[-1].replace( "_{0}_".format(rigName.BIND), "")), parent=ikCtrl) offsetJnt.create() offsetJnt.setMatrix( cmds.xform(ikJointList[-1], q=True, ws=True, m=True)) rigJoint.Joint.rotateToOrient([offsetJnt.getPartialPath()]) cmds.parent(self._ikfkSystem.getHandle(), offsetJnt.getPartialPath()) cmds.setAttr("{0}.v".format(offsetJnt.getPartialPath()), 0) # renaming handle and setting the name back system self._ikfkSystem.setHandle( cmds.rename(self._ikfkSystem.getHandle(), "{0}_{1}".format(self._name, rigName.HANDLE))) # turn off the visibility of my ik handle cmds.setAttr("{0}.v".format(self._ikfkSystem.getHandle()), 0) # orient constrain the last ik joint in the chain to my offset joint cmds.orientConstraint(offsetJnt.getPartialPath(), ikJointList[-1]) # parent the ik handle pvPos = self._ikfkSystem.getPolevectorPosition( (self._startJoint.getPartialPath(), self._middleJoint.getPartialPath(), self._endJoint.getPartialPath())) pvCtrl = rigControl.Control( "{0}_pv_{1}".format(self._name, rigName.CONTROL), position=pvPos, parent=self._rigGroup.getPartialPath(), shape="circle", color=rigName.SIDECOLOR[rigName.getSide(self._name)]) pvCtrl.create() cmds.poleVectorConstraint(pvCtrl.getPartialPath(), self._ikfkSystem.getHandle()) for origJnt, blendJnt in zip(self._ikfkSystem.getOriginalJoints(), self._ikfkSystem.getBlendJoints()): cmds.parentConstraint(blendJnt, origJnt) #------------------------------------------------- # Param for IK/FK switching. #------------------------------------------------- # Create parameter node to drive ik/fk switching. paramLocator = cmds.spaceLocator()[0] paramNode = cmds.listRelatives(paramLocator, c=True, shapes=True)[0] paramNode = cmds.rename(paramNode, "{0}_param".format(self._name)) # parent cmds.parent(paramNode, pvCtrl.getPartialPath(), r=True, s=True) cmds.delete(paramLocator) del (paramLocator) cmds.setAttr("{0}.v".format(paramNode), 0) # lock and hide attributes rigAttribute.lockAndHide(paramNode, ["lpx", "lpy", "lpz", "lsx", "lsy", "lsz"]) # add ik/fk attribute to the param node cmds.addAttr(paramNode, ln="ikfk", at="double", min=0, max=1, dv=0, keyable=True) paramAttrIKFK = "{0}.ikfk".format(paramNode) # Loop through and create instance of paramNode on all of the controls. for ctrl in fkControls + [ikCtrl]: cmds.parent(paramNode, ctrl.getPartialPath(), r=True, s=True, add=True) # connect ikfk paramNode attr to the ikfk system attribute cmds.connectAttr(paramAttrIKFK, "{0}.ikfk".format(self._ikfkSystem.getGroup()), f=True) # hide controls when they shouldn't visible during ikfk switching. # create a reverse node reverseNode = cmds.createNode("reverse", n="{0}_{1}".format( self._name, rigName.REVERSE)) cmds.connectAttr("{0}.ikfk".format(self._ikfkSystem.getGroup()), "{0}.inputX".format(reverseNode), f=True) # param node ikfk attribute to the fk control visibility for ctrl in fkControls: cmds.connectAttr(paramAttrIKFK, "{0}.v".format(ctrl.getShape()), f=True) # connect reverse node to the ik controls for ctrl in (ikCtrl, pvCtrl): cmds.connectAttr("{0}.outputX".format(reverseNode), "{0}.v".format(ctrl.getShape()), f=True) self._fkControls = fkControls
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 createControl(name="default", type="circle", axis="x", color="darkBlue", *args): """ creates control namemed by first arg, at origin. shape is determined by second arg: "cube", "octagon", "sphere", "diamond", "barbell", third arg can be 'x',, 'y', , 'z' and is the axis along which the control lies. The colors are: 'lightBlue', 'darkGreen', 'lightPurple', 'yellow', 'darkPurple', 'pink', 'blue', 'purple', 'lightGreen', 'black', 'orange', 'white', 'darkYellow', 'brown', 'lightYellow', 'darkBlue', 'royalBlue', 'darkBrown', 'lightRed', 'medBlue', 'lightBrown', 'darkRed', 'yellowGreen', 'medGreen', 'green', 'red' Arguments: name, type, axis, color """ colors = {} colors["red"] = 13 colors["blue"] = 6 colors["green"] = 14 colors["darkRed"] = 4 colors["lightRed"] = 31 colors["darkBlue"] = 5 colors["medBlue"] = 15 colors["lightBlue"] = 18 colors["royalBlue"] = 29 colors["darkGreen"] = 7 colors["medGreen"] = 27 colors["lightGreen"] = 19 colors["yellowGreen"] = 26 colors["yellow"] = 17 colors["darkYellow"] = 21 colors["lightYellow"] = 22 colors["purple"] = 30 colors["lightPurple"] = 9 colors["darkPurple"] = 8 colors["black"] = 1 colors["white"] = 16 colors["brown"] = 10 colors["darkBrown"] = 11 colors["lightBrown"] = 24 colors["pink"] = 20 colors["orange"] = 12 #deal with axis, x is default if axis == "x": rot = (0, 0, 0) elif axis == "y": rot = (0, 0, 90) elif axis == "z": rot = (0, 90, 0) else: cmds.warning( 'createControl: you entered an incorrect axis. Must be x, y or z') #-------------------------do this from dictionary, that way it's easier to control the flow to error or return if type == "circle": ctrl = cmds.circle(n=name, nr=(1, 0, 0)) elif type == "cube": ctrl = cmds.curve( n=name, d=1, p=[[-0.34095753069042323, -1.0031016006564133, 1.0031016006564133], [-0.34095753069042323, 1.0031016006564133, 1.0031016006564133], [0.34095753069042323, 1.0031016006564133, 1.0031016006564133], [0.34095753069042323, -1.0031016006564133, 1.0031016006564133], [-0.34095753069042323, -1.0031016006564133, 1.0031016006564133], [ -0.34095753069042323, -1.0031016006564133, -1.0031016006564133 ], [-0.34095753069042323, 1.0031016006564133, -1.0031016006564133], [-0.34095753069042323, 1.0031016006564133, 1.0031016006564133], [0.34095753069042323, 1.0031016006564133, 1.0031016006564133], [0.34095753069042323, 1.0031016006564133, -1.0031016006564133], [0.34095753069042323, -1.0031016006564133, -1.0031016006564133], [0.34095753069042323, -1.0031016006564133, 1.0031016006564133], [0.34095753069042323, 1.0031016006564133, 1.0031016006564133], [0.34095753069042323, 1.0031016006564133, -1.0031016006564133], [-0.34095753069042323, 1.0031016006564133, -1.0031016006564133], [ -0.34095753069042323, -1.0031016006564133, -1.0031016006564133 ], [0.34095753069042323, -1.0031016006564133, -1.0031016006564133]]) elif type == "octagon": ctrl = cmds.curve( n=name, d=1, p=[[ -7.4559598726027055e-17, 0.70710670948028576, 0.70710670948028564 ], [5.5511098291698525e-17, 0.99999988079071067, 0.0], [ -7.4559598726027055e-17, 0.70710670948028576, -0.70710670948028564 ], [ -3.8857805861880489e-16, 1.7256332301709633e-31, -0.99999988079071045 ], [ -7.0259651851158272e-16, -0.70710670948028576, -0.70710670948028564 ], [-8.326672684688675e-16, -1.0000000000000002, 0.0], [ -7.0259654498136232e-16, -0.70710676908493053, 0.70710676908493042 ], [ -3.8857805861880489e-16, 1.7256332301709633e-31, 0.99999994039535522 ], [ -7.4559598726027055e-17, 0.70710670948028576, 0.70710670948028564 ]]) elif type == "barbell": ctrl = cmds.curve(n=name, d=3, p=[[ 0.57752510285324732, 5.5507632834890673e-17, -0.90650843775588597 ], [ -2.9672778948456972e-16, 6.4094693518606145e-17, -1.661011590594498 ], [ -0.57752510285324554, 5.550763283489071e-17, -0.90650843775588663 ], [ -0.29814028408909887, 1.0540006765710255e-17, -0.67397322551417882 ], [ -0.14033645814277884, -1.3393164286098273e-33, -2.7549060854235934e-16 ], [ -0.29814028408909921, -1.0540006765710255e-17, 0.67397322551417838 ], [ -0.57752510285324621, -5.5507632834890697e-17, 0.90650843775588641 ], [ -6.6071759651022318e-16, -6.4094693518606133e-17, 1.6610115905944978 ], [ 0.57752510285324488, -5.550763283489074e-17, 0.90650843775588708 ], [ 0.29814028408909876, -1.0540006765710279e-17, 0.67397322551417937 ], [ 0.14033645814277884, -2.8148100723370156e-32, 8.7651446050535732e-16 ], [ 0.29814028408909921, 1.0540006765710236e-17, -0.6739732255141776 ]]) cmds.closeCurve(name, ch=False, ps=False, rpo=True, bki=True) elif type == "sphere": ctrl = cmds.curve(n=name, d=1, p=[[0.0, 1.0, 0.0], [-0.382683, 0.92388000000000003, 0.0], [-0.70710700000000004, 0.70710700000000004, 0.0], [-0.92388000000000003, 0.382683, 0.0], [-1.0, 0.0, 0.0], [-0.92388000000000003, -0.382683, 0.0], [-0.70710700000000004, -0.70710700000000004, 0.0], [-0.382683, -0.92388000000000003, 0.0], [0.0, -1.0, 0.0], [0.382683, -0.92388000000000003, 0.0], [0.70710700000000004, -0.70710700000000004, 0.0], [0.92388000000000003, -0.382683, 0.0], [1.0, 0.0, 0.0], [0.92388000000000003, 0.382683, 0.0], [0.70710700000000004, 0.70710700000000004, 0.0], [0.382683, 0.92388000000000003, 0.0], [0.0, 1.0, 0.0], [0.0, 0.92388000000000003, 0.382683], [0.0, 0.70710700000000004, 0.70710700000000004], [0.0, 0.382683, 0.92388000000000003], [0.0, 0.0, 1.0], [0.0, -0.382683, 0.92388000000000003], [0.0, -0.70710700000000004, 0.70710700000000004], [0.0, -0.92388000000000003, 0.382683], [0.0, -1.0, 0.0], [0.0, -0.92388000000000003, -0.382683], [0.0, -0.70710700000000004, -0.70710700000000004], [0.0, -0.382683, -0.92388000000000003], [0.0, 0.0, -1.0], [0.0, 0.382683, -0.92388000000000003], [0.0, 0.70710700000000004, -0.70710700000000004], [0.0, 0.92388000000000003, -0.382683], [0.0, 1.0, 0.0], [-0.382683, 0.92388000000000003, 0.0], [-0.70710700000000004, 0.70710700000000004, 0.0], [-0.92388000000000003, 0.382683, 0.0], [-1.0, 0.0, 0.0], [-0.92388000000000003, 0.0, 0.382683], [-0.70710700000000004, 0.0, 0.70710700000000004], [-0.382683, 0.0, 0.92388000000000003], [0.0, 0.0, 1.0], [0.382683, 0.0, 0.92388000000000003], [0.70710700000000004, 0.0, 0.70710700000000004], [0.92388000000000003, 0.0, 0.382683], [1.0, 0.0, 0.0], [0.92388000000000003, 0.0, -0.382683], [0.70710700000000004, 0.0, -0.70710700000000004], [0.382683, 0.0, -0.92388000000000003], [0.0, 0.0, -1.0], [-0.382683, 0.0, -0.92388000000000003], [-0.70710700000000004, 0.0, -0.70710700000000004], [-0.92388000000000003, 0.0, -0.382683], [-1.0, 0.0, 0.0]]) elif type == "diamond": ctrl = cmds.curve(n=name, d=1, p=[[ 3.1401849173675503e-16, 0.70710678118654768, 1.1102230246251565e-16 ], [ 4.9303806576313238e-32, 1.1102230246251568e-16, -0.70710678118654757 ], [ -3.1401849173675503e-16, -0.70710678118654768, -1.1102230246251565e-16 ], [ -4.9303806576313238e-32, -1.1102230246251568e-16, 0.70710678118654757 ], [ 3.1401849173675503e-16, 0.70710678118654768, 1.1102230246251565e-16 ]]) else: cmds.warning("createControl doesn't know shape - '%s'" % type) #rotate to axis cmds.select("{0}.cv[*]".format(ctrl)) cmds.rotate(rot[0], rot[1], rot[2], r=True) cmds.select(cl=True) shapes = cmds.listRelatives(ctrl, shapes=True) for shape in shapes: cmds.setAttr("%s.overrideEnabled" % shape, 1) cmds.setAttr("%s.overrideColor" % shape, colors[color]) cmds.rename(shape, "{0}Shape".format(ctrl)) print "ctrl shape is: {0}".format(shape) #return the name of the curve return (ctrl)
def createLoc(): head= 2 mc.spaceLocator(n = 'FootLeftLoc') mc.scale(0.3,0.3,0.3) mc.move(1,0,1) mc.color(rgb=(0,0,1)) mc.spaceLocator(n = 'ToeLeftLoc') mc.scale(0.2,0.2,0.2) mc.move(1,0,2) mc.color(rgb=(0,0,1)) mc.parent('ToeLeftLoc','FootLeftLoc') mc.spaceLocator(n = 'AnkleLeftLoc') mc.move(1,head*0.5,0) mc.scale(0.2,0.2,0.2) mc.color(rgb=(0.5,0,0)) mc.parent('FootLeftLoc','AnkleLeftLoc') mc.spaceLocator(n = 'KneeLeftLoc') mc.move(1,head*2,0) mc.scale(0.3,0.3,0.3) mc.color(rgb=(0.5,0.2,0)) mc.parent('AnkleLeftLoc' , 'KneeLeftLoc') mc.spaceLocator(n = 'ThighLeftLoc') mc.move(1,head*4,0) mc.scale(0.4,0.4,0.4) mc.color(rgb=(0.5,0.2,0.5)) mc.parent('KneeLeftLoc' ,'ThighLeftLoc') mc.spaceLocator(n = 'NeckLoc') mc.move(0,head*6.5,0) mc.scale(0.2,0.2,0.2) mc.color(rgb=(0,0.2,0.5)) mc.spaceLocator(n = 'RootLoc') mc.move(0,head*4,0) mc.scale(0.2,0.2,0.2) mc.color(rgb=(0,0.2,0.5)) mc.spaceLocator(n = 'Spine0Loc') mc.move(0,head*4.5,0) mc.scale(0.2,0.2,0.2) mc.color(rgb=(0,0.2,0.5)) mc.spaceLocator(n = 'Spine1Loc') mc.move(0,head*5.0,0) mc.scale(0.2,0.2,0.2) mc.color(rgb=(0,0.2,0.5)) mc.spaceLocator(n = 'Spine2Loc') mc.move(0,head*5.5,0) mc.scale(0.2,0.2,0.2) mc.color(rgb=(0,0.2,0.5)) mc.spaceLocator(n = 'Spine3Loc') mc.move(0,head*6,0) mc.scale(0.2,0.2,0.2) mc.color(rgb=(0,0.2,0.5)) mc.spaceLocator(n = 'ShoulderLeftLoc') mc.move(head,head*6.5,0) mc.scale(0.2,0.2,0.2) mc.color(rgb=(0,0.2,0.5)) mc.spaceLocator(n = 'ClavicleLoc') mc.move(head*0.3,head*6.6,0) mc.scale(0.2,0.2,0.2) mc.color(rgb=(0,0.2,0.5)) mc.spaceLocator(n = 'ElbowLeftLoc') mc.move(head*2.5,head*6.5,0) mc.scale(0.2,0.2,0.2) mc.color(rgb=(0,0.2,0.5)) mc.spaceLocator(n = 'WristLeftLoc') mc.move(head*3.7,head*6.5,0) mc.scale(0.2,0.2,0.2) mc.color(rgb=(0,0.2,0.5)) mc.spaceLocator(n = 'IndexLeftLoc3') mc.move(head*4.4,head*6.5,0) mc.scale(0.1,0.1,0.1) mc.color(rgb=(0,0.2,0.5)) mc.spaceLocator(n = 'IndexLeftLoc0') fingerEnd = mc.getAttr('IndexLeftLoc3.tx') wrist = mc.getAttr('WristLeftLoc.tx') halfhand = wrist+(fingerEnd - wrist)*0.5 mc.move(halfhand,head*6.5,0) mc.scale(0.05,0.05,0.05) mc.spaceLocator(n = 'IndexLeftLoc1') fingerEnd = mc.getAttr('IndexLeftLoc3.tx') middlefingerRoot = mc.getAttr('IndexLeftLoc0.tx') halfmiddleFinger = middlefingerRoot + (fingerEnd - middlefingerRoot)*0.5 mc.move(halfmiddleFinger,head*6.5,0) mc.scale(0.05,0.05,0.05) mc.spaceLocator(n = 'IndexLeftLoc2') fingerEnd = mc.getAttr('IndexLeftLoc3.tx') IndexLeftLoc1 = mc.getAttr('IndexLeftLoc1.tx') halfmiddleSecondFinger = IndexLeftLoc1 + (fingerEnd - IndexLeftLoc1)*0.5 mc.move(halfmiddleSecondFinger,head*6.5,0) mc.scale(0.05,0.05,0.05) mc.select('IndexLeftLoc0','IndexLeftLoc1','IndexLeftLoc2','IndexLeftLoc3') mc.move(0,0,0.2,r = True) mc.spaceLocator(n = 'HeadLoc') mc.move(0,head*7,0) mc.scale(0.5,0.5,0.5) mc.color(rgb=(0,0.2,0.5)) mc.spaceLocator(n = 'HeadEndLoc') mc.move(0,head*8,0) mc.scale(0.7,0.7,0.7) mc.color(rgb=(0,0,2)) #other fingers besides index for i in range(3): mc.select('IndexLeftLoc0','IndexLeftLoc1','IndexLeftLoc2','IndexLeftLoc3') mc.duplicate() mc.move(0,0,-0.2*(i+1),r = True) for j in range(4): mc.rename('IndexLeftLoc' + str(j+4),'MiddleLeftLoc' + str(j)) for j in range(4,8): mc.rename('IndexLeftLoc' + str(j+4),'RingLeftLoc' + str(j-4)) for j in range(8,12): mc.rename('IndexLeftLoc' + str(j+4),'PinkieLeftLoc' + str(j-8)) #thumb mc.select('IndexLeftLoc0','IndexLeftLoc1','IndexLeftLoc2') mc.duplicate() mc.move(0,0,0.2,r = True) for j in range(3): mc.rename('IndexLeftLoc' + str(j+4),'ThumbLeftLoc' + str(j)) for i in range(1,3): mc.parent('ThumbLeftLoc' + str(3-i),'ThumbLeftLoc' + str(2-i) ) for each in ('PinkieLeft','RingLeft','MiddleLeft','IndexLeft'): for i in range(1,4): mc.parent(each + 'Loc' + str(4-i),each + 'Loc' + str(3-i) ) mc.parent('WristLeftLoc' ,'ElbowLeftLoc') mc.parent('ElbowLeftLoc','ShoulderLeftLoc') for each in ('MiddleLeftLoc0','IndexLeftLoc0','ThumbLeftLoc0','RingLeftLoc0','PinkieLeftLoc0'): mc.parent(each,'WristLeftLoc')
def createParamTracker(selection = [],name = '',startVector = [1,0,0]): if not len(selection) == 2: om.MGlobal.displayError('Wrong Selection: select parent and driver.') else: parentObj = selection[0] drivingObj = selection[1] position = cmds.xform(drivingObj,q = True, ws = True,rp = True) rotation = cmds.xform(drivingObj,q = True, ws = True,rotation = True) paramTrackerGrp = cmds.group(empty = True,name = '%s_Grp'%name) cmds.move(position[0],position[1],position[2],paramTrackerGrp,ws = True) cmds.parentConstraint(parentObj,paramTrackerGrp,mo = True) null = cmds.group(name = '%s_Tracking_Null'%name,empty = True) nullGrp = cmds.group(n = '%s_Tracking_Grp'%name,empty = True) cmds.move(position[0],position[1],position[2],nullGrp,ws = True) #cmds.move(startVector[0],startVector[1],startVector[2],nullGrp,os = True) cmds.parent(null,nullGrp) cmds.parent(nullGrp, paramTrackerGrp) locator = cmds.spaceLocator(n = '%s_Tracking_Loc'%name)[0] cmds.parent(locator,nullGrp) pointOnSurfaceNode = cmds.createNode('closestPointOnSurface',name = '%s_POS'%name) plane = cmds.nurbsPlane(n = '%s_Tracking_Surface'%name,w = 2)[0] cmds.rotate(rotation[0],rotation[1],rotation[2],plane,ws = True) planeShape = cmds.listRelatives(plane,type = 'shape')[0] cmds.parent(null,paramTrackerGrp,r = True) cmds.parent(plane,paramTrackerGrp,r = True) cmds.move(startVector[0],startVector[1],startVector[2],null,os = True) cmds.parentConstraint(drivingObj,null,mo = True) cmds.connectAttr('%s.worldSpace[0]'%planeShape,'%s.inputSurface'%pointOnSurfaceNode) cmds.addAttr(locator,ln = 'uValue',at = 'double') cmds.setAttr('%s.uValue'%locator,e = True,keyable = True) cmds.addAttr(locator,ln = 'vValue',at = 'double') cmds.setAttr('%s.vValue'%locator,e = True,keyable = True) cmds.connectAttr('%s.parameterU'%pointOnSurfaceNode,'%s.uValue'%locator) cmds.connectAttr('%s.parameterV'%pointOnSurfaceNode,'%s.vValue'%locator) decomposeMatrix = cmds.createNode('decomposeMatrix',n = '%s_DM'%name) cmds.connectAttr('%s.worldMatrix[0]'%locator,'%s.inputMatrix'%decomposeMatrix) cmds.connectAttr('%s.outputTranslate'%decomposeMatrix,'%s.inPosition'%pointOnSurfaceNode) rivetNodes = cmds.kSurfaceRivetCmd(s = planeShape) cmds.rename(rivetNodes[0],'%s_Rivet'%name) cmds.rename(rivetNodes[1],'%s_Rivet_Loc'%name) rivetNodes[0] = '%s_Rivet'%name rivetNodes[1] = '%s_Rivet_Loc'%name closestPointOnSurface = cmds.createNode('closestPointOnSurface',n = '%s_CPS'%name) cmds.connectAttr('%s.outputTranslate'%decomposeMatrix, '%s.inPosition'%closestPointOnSurface) cmds.connectAttr('%s.worldSpace[0]'%planeShape,'%s.inputSurface'%closestPointOnSurface) cmds.connectAttr('%s.result.parameterU'%closestPointOnSurface,'%s.uValue'%rivetNodes[0]) cmds.connectAttr('%s.result.parameterV'%closestPointOnSurface,'%s.vValue'%rivetNodes[0])
def createTechPasses(): ''' Creates tech passes for rendering zdepth, xyz, normals, gi, spec, reflection, lighting, uv, top/down TODO : topdown not working well due to strange creation methods ''' # first we make the sampler node as we will use this twice samplerNodeName = 'util_sampler_node' if not cmds.objExists(samplerNodeName): samplerNode = cmds.shadingNode('samplerInfo', asUtility=True) samplerNode = cmds.rename(samplerNode, samplerNodeName) # now we make the xyz point render element layerToMake = 'XYZ_tex' if not cmds.objExists(layerToMake): renderElement = mel.eval('vrayAddRenderElement ExtraTexElement;') cmds.rename(renderElement, layerToMake) cmds.setAttr(layerToMake + '.vray_explicit_name_extratex', 'world_xyz', type='string') cmds.setAttr(layerToMake + '.vray_considerforaa_extratex', 0) cmds.connectAttr(samplerNode + '.pointWorld', 'XYZ_tex.vray_texture_extratex') # now we make the normals render element layerToMake = 'normals' if not cmds.objExists(layerToMake): renderElement = mel.eval('vrayAddRenderElement normalsChannel;') cmds.rename(renderElement, layerToMake) cmds.setAttr(layerToMake + '.vray_filtering_normals', 0) # uv render element layerToMake = 'uv' if not cmds.objExists(layerToMake): renderElement = mel.eval('vrayAddRenderElement ExtraTexElement;') cmds.rename(renderElement, layerToMake) cmds.setAttr(layerToMake + '.vray_explicit_name_extratex', 'uv', type='string') cmds.connectAttr( samplerNode + '.uvCoord.uCoord', layerToMake + '.vray_texture_extratex.vray_texture_extratexR') cmds.connectAttr( samplerNode + '.uvCoord.vCoord', layerToMake + '.vray_texture_extratex.vray_texture_extratexG') cmds.setAttr(layerToMake + '.vray_filtering_extratex', 0) # add zdepth unclamped and unfiltered layerToMake = 'zdepth' if not cmds.objExists(layerToMake): renderElement = mel.eval('vrayAddRenderElement zdepthChannel;') renderElement = cmds.rename(renderElement, layerToMake) cmds.setAttr(renderElement + '.vray_depthClamp', 0) cmds.setAttr(renderElement + '.vray_filtering_zdepth', 0) # add zdepth filtered layerToMake = 'zdepthAA' if not cmds.objExists(layerToMake): renderElement = mel.eval('vrayAddRenderElement zdepthChannel;') renderElement = cmds.rename(renderElement, layerToMake) cmds.setAttr(renderElement + '.vray_depthClamp', 0) cmds.setAttr(renderElement + '.vray_filtering_zdepth', 1) # add base render layers for recomp layerToMake = 'gi' if not cmds.objExists(layerToMake): renderElement = mel.eval('vrayAddRenderElement giChannel;') renderElement = cmds.rename(renderElement, layerToMake) cmds.setAttr(renderElement + '.vray_name_gi', layerToMake, type='string') layerToMake = 'lighting' if not cmds.objExists(layerToMake): renderElement = mel.eval('vrayAddRenderElement lightingChannel;') renderElement = cmds.rename(renderElement, layerToMake) layerToMake = 'reflection' if not cmds.objExists(layerToMake): renderElement = mel.eval('vrayAddRenderElement reflectChannel;') renderElement = cmds.rename(renderElement, layerToMake) layerToMake = 'specular' if not cmds.objExists(layerToMake): renderElement = mel.eval('vrayAddRenderElement specularChannel;') renderElement = cmds.rename(renderElement, layerToMake) # create top down layerToMake = 'topdown' if not cmds.objExists(layerToMake): renderElement = mel.eval('vrayAddRenderElement ExtraTexElement;') renderElement = cmds.rename(renderElement, layerToMake) cmds.setAttr(renderElement + '.vray_explicit_name_extratex', layerToMake, type='string') # now create the vray plugin with no placement on UV (0 = none, 1 = 2d, 2 = 3d) newNode = mel.eval( 'vrayCreateNodeFromDll ("topdown_tex", "texture", "TexFalloff", 2);' ) newNode = cmds.rename('topdown_tex', 'topdown_tex') cmds.setAttr(newNode + '.direction_type', 2) cmds.setAttr(newNode + '.color1', 1, 0, 0, type='double3') cmds.setAttr(newNode + '.color2', 0, 1, 0, type='double3') cmds.connectAttr(newNode + '.outColor', renderElement + '.vray_texture_extratex') # create AO layerToMake = 'ao' if not cmds.objExists(layerToMake): renderElement = mel.eval('vrayAddRenderElement ExtraTexElement;') renderElement = cmds.rename(renderElement, layerToMake) cmds.setAttr(renderElement + '.vray_explicit_name_extratex', layerToMake, type='string') newNode = cmds.shadingNode('VRayDirt', name='ao_tex', asTexture=True) cmds.connectAttr(newNode + '.outColor', renderElement + '.vray_texture_extratex') cmds.setAttr(newNode + '.invertNormal', 1) cmds.setAttr(newNode + '.ignoreForGi', 0) cmds.setAttr(newNode + '.blackColor', -0.5, -0.5, -0.5, type='double3') cmds.setAttr(newNode + '.falloff', 5)
def topNodeRename(renameDict=TOP_NODE_RENAME): """ Explicit top node renaming """ for origName, newName in renameDict.iteritems(): if cmds.objExists(origName): cmds.rename(origName, newName)
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 Light_Import_Fn(self): File_Path = QFileDialog.getOpenFileName(self, caption=u"保存文件到", directory=".", filter="json (*.json)") # 空数组处理 try: if type(File_Path) is tuple: File_Path = File_Path[0] if type(File_Path) is list: File_Path = File_Path[0] except: traceback.print_exc() return if not os.path.exists(File_Path): return Light_Json = {} with open(File_Path, 'r') as f: Light_Json = json.load(f) for lightName in Light_Json['LightData']: if cmds.objExists(lightName): continue lightNameData = Light_Json['LightData'][lightName] if lightNameData['Type'] == "pointLight": light = cmds.pointLight(n=lightName) elif lightNameData['Type'] == "spotLight": light = cmds.spotLight(n=lightName) cmds.setAttr(light + ".coneAngle", lightNameData['coneAngle']) cmds.setAttr(light + ".penumbraAngle", lightNameData['penumbraAngle']) cmds.setAttr(light + ".dropoff", lightNameData['dropoff']) elif lightNameData['Type'] == "areaLight": light = cmds.shadingNode('areaLight', asLight=1, n=lightNameData['Name']) elif lightNameData['Type'] == "directionalLight": light = cmds.directionalLight(n=lightName) elif lightNameData['Type'] == "aiSkyDomeLight": aiLight = mtoa.utils.createLocatorWithName("aiSkyDomeLight", lightName, asLight=True) cmds.rename(aiLight[0], lightNameData['Name']) elif lightNameData['Type'] == "aiAreaLight": aiLight = mtoa.utils.createLocatorWithName("aiAreaLight", lightName, asLight=True) cmds.rename(aiLight[0], lightNameData['Name']) R = lightNameData['color']['R'] G = lightNameData['color']['G'] B = lightNameData['color']['B'] cmds.setAttr(lightNameData['Name'] + ".color", R, G, B, type="double3") cmds.setAttr(lightNameData['Name'] + ".intensity", lightNameData['Intensity']) cmds.setAttr(lightNameData['Name'] + ".aiExposure", lightNameData['Exposure']) tx = lightNameData['Translate']['tx'] ty = lightNameData['Translate']['ty'] tz = lightNameData['Translate']['tz'] cmds.setAttr(lightName + ".tx", tx) cmds.setAttr(lightName + ".ty", ty) cmds.setAttr(lightName + ".tz", tz) rx = lightNameData['Rotate']['rx'] ry = lightNameData['Rotate']['ry'] rz = lightNameData['Rotate']['rz'] cmds.setAttr(lightName + ".rx", rx) cmds.setAttr(lightName + ".ry", ry) cmds.setAttr(lightName + ".rz", rz) sx = lightNameData['Scale']['sx'] sy = lightNameData['Scale']['sy'] sz = lightNameData['Scale']['sz'] cmds.setAttr(lightName + ".sx", sx) cmds.setAttr(lightName + ".sy", sy) cmds.setAttr(lightName + ".sz", sz) QMessageBox.warning(self, u"Success", u"Json Import Success!")
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 readWeights( self, fileName, reverseOrder ): # open the file for reading try: weightFile = open(fileName, 'rb') except: OpenMaya.MGlobal.displayError('A file error has occured for file \'' + fileName + '\'.') return(-1) weightData = weightFile.read() weightLines = weightData.split('\n') weightFile.close() normalization = 1 # variables for writing a range of influences weightString = '' inflStart = -1 inflEnd = -1 setCount = 0 writeData = 0 # -------------------------------------------------------------------------------- # the first line contains the joints and skin shape # -------------------------------------------------------------------------------- objects = weightLines[0] items = objects.split(' ') shape = items[len(items) - 1] # -------------------------------------------------------------------------------- # the second line contains the name of the skin cluster # -------------------------------------------------------------------------------- skinClusterName = weightLines[1] # -------------------------------------------------------------------------------- # the third line contains the values for the skin cluster # -------------------------------------------------------------------------------- objects = objects.split(' ') if reverseOrder == 1: objects = objects[::-1] objects.pop(0) objects.append(shape) # select the influences and the skin shape try: cmd.select(objects, r=True) except: weightFile.close() return() # check if the geometry is not already bound history = cmd.listHistory(shape, f=0, bf=1) for h in history: if cmd.nodeType(h) == 'skinCluster': OpenMaya.MGlobal.displayError(shape + ' is already connected to a skinCluster.') return(-1) # check for the version # up to Maya 2012 the bind method flag is not available version = mel.eval('getApplicationVersionAsFloat()') bindMethod = '-bm 0 ' if version < 2013: bindMethod = '-ih ' # create the new skinCluster newSkinCluster = mel.eval('newSkinCluster \"-tsb ' + bindMethod + weightLines[2] + '-omi true -rui false\"')[0] cmd.rename(newSkinCluster, skinClusterName) # get the current normalization and store it # it will get re-applied after applying all the weights normalization = cmd.getAttr(skinClusterName + '.nw') # turn off the normalization to correctly apply the stored skin weights cmd.setAttr((skinClusterName + '.nw'), 0) # pruning the skin weights to zero is much faster # than iterating through all components and setting them to 0 cmd.skinPercent(skinClusterName, shape, prw=100, nrm=0) # allocate memory for the number of components to set weights = eval(weightLines[len(weightLines) - 2]) # get the index of the last component stored in the weight list maxIndex = weights[0] cmd.select(skinClusterName, r=True) cmdString = ('setAttr -s ' + str(maxIndex + 1) + ' \".wl\"') OpenMaya.MGlobal.executeCommand(cmdString) # -------------------------------------------------------------------------------- # apply the weight data # -------------------------------------------------------------------------------- # timer for timing the read time without the smooth binding #start = cmd.timerX() for l in range(3, len(weightLines) - 1): weights = eval(weightLines[l]) weightsNext = '' # also get the next line for checking if the component changes # but only if it's not the end of the list if l < len(weightLines) - 2: weightsNext = eval(weightLines[l + 1]) else: weightsNext = weights writeData = 1 compIndex = weights[0] # -------------------------------------------------------------------------------- # construct the setAttr string # i.e. setAttr -s 4 ".wl[9].w[0:3]" 0.0003 0.006 0.496 0.496 # -------------------------------------------------------------------------------- # start a new range if inflStart == -1: inflEnd = inflStart = weights[2] else: # if the current component is the next in line if inflEnd == weights[2] - 1: inflEnd = weights[2] # if influences were dropped because of zero weight else: # fill the weight string inbetween with zeros for x in range(inflEnd + 1, weights[2]): weightString += '0 ' setCount += 1 inflEnd = weights[2] # add the weight to the weight string weightString += str(weights[3]) + ' ' # increase the number of weights to be set setCount += 1 # if the next line is for the next index set the weights if compIndex != weightsNext[0]: writeData = 1 if writeData == 1: # decide if a range or a single influence index is written rangeString = ':' + str(inflEnd) if inflEnd == inflStart: rangeString = '' cmdString = ('setAttr -s ' + str(setCount) + ' \".weightList[' + str(compIndex) + '].weights[' + str(inflStart) + rangeString + ']\" ' + weightString) OpenMaya.MGlobal.executeCommand(cmdString) # reset and start over inflStart = inflEnd = -1 writeData = 0 setCount = 0 weightString = '' cmd.setAttr((skinClusterName + '.nw'), normalization) #doneTime = cmd.timerX(startTime=start) #OpenMaya.MGlobal.displayInfo('%.02f seconds' % doneTime) return(1)
def Controllers(): charName = cmds.textFieldGrp(NameInput, q=True, text=True) lengthY = locXYZ[1][1] - locXYZ[0][1] lengthZ = abs(locXYZ[0][2]) + abs(locXYZ[1][2]) legY = locXYZ[0][1] - locXYZ[5][1] side = ['_L_', '_R_'] nb = [1, -1] for i in range(len(side)): cmds.ikHandle(n=charName + '_Leg' + side[i] + 'ikHandle', sj=charName + side[i] + 'thigh_Jnt_01', ee=charName + side[i] + 'ankie_Jnt_01') cmds.spaceLocator(n=charName + '_poleVector' + side[i] + 'leg', p=(nb[i] * locXYZ[4][0] - legY * 0.005, locXYZ[4][1] + legY * 0.05, locXYZ[4][2])) cmds.xform(centerPivots=1) # aims the pole vector of 1 at 2. cmds.poleVectorConstraint(charName + '_poleVector' + side[i] + 'leg', charName + '_Leg' + side[i] + 'ikHandle') cmds.move(nb[i] * lengthY * 0.75, -lengthY * 0.75, charName + '_poleVector' + side[i] + 'leg', moveXY=True) cmds.setAttr(charName + '_Leg' + side[i] + 'ikHandle.twist', nb[i] * 90) cmds.ParentConstraint(charName + 'controllerfoot', charName + '_poleVector' + side[i] + 'leg') cmds.parent(charName + '_poleVector' + side[i] + 'leg', charName + '_Leg' + side[i] + 'ikHandle', relative=True) cmds.ikHandle(n=charName + '_Foot' + side[i] + 'ball_ikHandle', sj=charName + side[i] + 'ankie' + '_Jnt_01', ee=charName + side[i] + 'ball' + '_Jnt_01') cmds.ikHandle(n=charName + '_Foot' + side[i] + 'toe_ikHandle', sj=charName + side[i] + 'ball' + '_Jnt_01', ee=charName + side[i] + 'toe' + '_Jnt_01') cmds.group(charName + '_Leg' + side[i] + 'ikHandle', n=charName + '_Foot' + side[i] + 'heelPeel') #change pivot position Xpos = cmds.getAttr(charName + '_Foot' + side[i] + 'ball_ikHandle.translateX') Ypos = cmds.getAttr(charName + '_Foot' + side[i] + 'ball_ikHandle.translateY') Zpos = cmds.getAttr(charName + '_Foot' + side[i] + 'ball_ikHandle.translateZ') cmds.move(Xpos, Ypos, Zpos, charName + '_Foot' + side[i] + 'heelPeel.scalePivot', charName + '_Foot' + side[i] + 'heelPeel.rotatePivot', absolute=True) cmds.group(charName + '_Foot' + side[i] + 'ball_ikHandle', charName + '_Foot' + side[i] + 'toe_ikHandle', n=charName + '_Foot' + side[i] + 'toeTap') cmds.move(Xpos, Ypos, Zpos, charName + '_Foot' + side[i] + 'toeTap.scalePivot', charName + '_Foot' + side[i] + 'toeTap.rotatePivot', absolute=True) cmds.group(charName + '_Foot' + side[i] + 'ball_ikHandle', charName + '_Foot' + side[i] + 'toeTap', n=charName + '_Foot' + side[i] + 'TipToe') cmds.group(n=charName + '_Foot' + side[i] + '1', em=True) cmds.parent(charName + '_Foot' + side[i] + 'heelPeel', charName + '_Foot' + side[i] + 'TipToe', charName + '_Foot' + side[i] + '1', relative=True) cmds.move(Xpos, Ypos, Zpos, charName + '_Foot' + side[i] + '1.scalePivot', charName + '_Foot' + side[i] + '1.rotatePivot', absolute=True) Xpos = cmds.getAttr(charName + '_Foot' + side[i] + 'ball_ikHandle.translateX') Ypos = cmds.getAttr(charName + '_Foot' + side[i] + 'ball_ikHandle.translateY') Zpos = cmds.getAttr(charName + '_Foot' + side[i] + 'ball_ikHandle.translateZ') CreateCtr(charName + '_Foot' + side[i] + 'Crl', charName + '_Foot' + side[i] + '1', (Xpos, Ypos, Zpos), (lengthY / 60 * 10, lengthY / 60 * 10, lengthY / 60 * 16), (0, 0, 0)) #left Arm for i in range(len(side)): cmds.ikHandle(n=charName + '_Arm' + str(side[i]) + 'ikHandle', sj=charName + str(side[i]) + 'shoulder' + '_Jnt_02', ee=charName + str(side[i]) + 'wrist' + '_Jnt_01') cmds.CreateNURBSCircle() cmds.rename('nurbsCircle1', charName + '_Elbow' + str(side[i]) + 'Crl') cmds.move(nb[i] * locXYZ[2][0], locXYZ[2][1], locXYZ[2][2] * 30) cmds.scale(2, 2, 3) cmds.rotate(90, 0, 0) cmds.move(nb[i] * locXYZ[2][0], locXYZ[2][1], locXYZ[2][2], charName + '_Elbow' + str(side[i]) + 'Crl.scalePivot', charName + '_Elbow' + str(side[i]) + 'Crl.rotatePivot', absolute=True) cmds.makeIdentity(apply=True) cmds.xform(centerPivots=1) cmds.poleVectorConstraint( charName + '_Elbow' + str(side[i]) + 'Crl', charName + '_Arm' + str(side[i]) + 'ikHandle') #left Arm controller CreateCtr(charName + '_Arm' + side[i] + 'Crl', charName + '_Arm' + side[i] + 'ikHandle', (nb[i] * locXYZ[3][0], locXYZ[3][1], locXYZ[3][2]), (lengthY / 60 * 5, lengthY / 60 * 5, lengthY / 60 * 8), (0, 0, nb[i] * 30)) #spline cmds.parent(charName + '_R_shoulder_Jnt_01', w=True) cmds.parent(charName + '_L_shoulder_Jnt_01', w=True) cmds.select(d=True) cmds.select(charName + '_spline_Jnt_03') cmds.DisconnectJoint(charName + '_spline_Jnt_03') cmds.rename(charName + '_spline_Jnt_03', charName + '_neck_Jnt_00') cmds.rename('joint1', charName + '_spline_Jnt_03') cmds.rename(charName + '_root' + '_Jnt_01', charName + '_spline_Jnt_00') cmds.parent(charName + '_R_hip_Jnt_01', w=True) cmds.parent(charName + '_L_hip_Jnt_01', w=True) cmds.select(d=True) cmds.joint(p=(locXYZ[0][0], locXYZ[0][1], locXYZ[0][2]), n=charName + '_root' + '_Jnt_01') cmds.parent(charName + '_L_hip_Jnt_01') cmds.select(charName + '_root' + '_Jnt_01') cmds.parent(charName + '_R_hip_Jnt_01') cmds.curve(n=charName + '_SplineIK_Crv_01', p=[(locXYZ[0][0], locXYZ[0][1], locXYZ[0][2]), (0.0, locXYZ[0][1] + lengthY * 0.43, locXYZ[0][2] + lengthZ * 0.43), (0.0, locXYZ[0][1] + lengthY * 0.8, locXYZ[0][2] + lengthZ * 0.18), (locXYZ[1][0], locXYZ[1][1], locXYZ[1][2])]) cmds.ikHandle(n=charName + 'SplineIK_01', sj=charName + '_spline_Jnt_00', ee=charName + '_spline_Jnt_03', curve=charName + '_SplineIK_Crv_01', sol='ikSplineSolver', createCurve=False, parentCurve=False) for i in range(4): cmds.select(charName + '_SplineIK_Crv_01' + '.cv[' + str(i) + ']') cmds.cluster(n='cluster_' + str(i + 1)) CreateCtr(charName + '_Spline_Ctrl_01', 'cluster_1Handle', (0, locXYZ[0][1] * 1.05, 0), (lengthY / 60 * 25, lengthY / 60 * 25, lengthY / 60 * 25), (0, 0, 0)) cmds.parentConstraint(charName + '_Spline_Ctrl_01', charName + '_root_Jnt_01', maintainOffset=True) CreateCtr(charName + '_Chest_Ctrl_01', 'cluster_4Handle', (0, locXYZ[1][1], 0), (lengthY / 60 * 25, lengthY / 60 * 25, lengthY / 60 * 25), (0, 0, 0)) for i in range(len(side)): cmds.parentConstraint(charName + '_Chest_Ctrl_01', charName + side[i] + 'shoulder_Jnt_01', maintainOffset=True) cmds.parent(charName + '_Arm' + side[i] + 'Crl_grp', charName + '_Chest_Ctrl_01') cmds.parent(charName + '_Elbow' + side[i] + 'Crl', charName + '_Chest_Ctrl_01') CreateCtr(charName + '_Chest_Ctrl_02', 'cluster_2Handle', (0, (locXYZ[0][1] + locXYZ[1][1]) / 2, 0), (lengthY / 60 * 20, lengthY / 60 * 20, lengthY / 60 * 20), (0, 0, 0)) cmds.parentConstraint(charName + '_Chest_Ctrl_01', charName + '_neck_Jnt_00', maintainOffset=True, w=1) cmds.parentConstraint(charName + '_Chest_Ctrl_01', 'cluster_3Handle', maintainOffset=True, weight=0.5) cmds.parentConstraint(charName + '_Chest_Ctrl_01', charName + '_Chest_Ctrl_02_grp', maintainOffset=True, weight=0.5) cmds.parentConstraint(charName + '_Spline_Ctrl_01', charName + '_Chest_Ctrl_02_grp', maintainOffset=True, weight=0.5) cmds.CreateNURBSCircle() cmds.rename('nurbsCircle1', charName + '_Hip_Ctrl_01') cmds.move(0, locXYZ[0][1], 0) cmds.scale(lengthY / 60 * 30, lengthY / 60 * 30, lengthY / 60 * 30) cmds.makeIdentity(apply=True) cmds.parentConstraint(charName + '_Hip_Ctrl_01', charName + '_Spline_Ctrl_01', maintainOffset=True, weight=0.5) cmds.parentConstraint(charName + '_Hip_Ctrl_01', charName + '_Chest_Ctrl_01', maintainOffset=True, weight=0.5) #clean for i in range(len(side)): cmds.parent(charName + side[i] + 'shoulder_Jnt_01', charName + '_Joints_01') cmds.parent(charName + '_Chest_Ctrl_0' + str(i + 1) + '_grp', charName + '_Controls_01') cmds.parent(charName + '_Foot' + side[i] + '1', charName + '_Controls_01') cmds.parent(charName + '_Foot' + side[i] + 'Crl_grp', charName + '_Controls_01') cmds.parent(charName + '_Arm' + side[i] + 'ikHandle', charName + '_ikHandle_01') cmds.parent('cluster_' + str(i + 1) + 'Handle', charName + '_ikHandle_01') cmds.parent('cluster_' + str(i + 3) + 'Handle', charName + '_ikHandle_01') cmds.parent(charName + 'SplineIK_01', charName + '_ikHandle_01') cmds.parent(charName + '_SplineIK_Crv_01', charName + '_ikHandle_01') cmds.parent(charName + '_neck_Jnt_00', charName + '_Joints_01') cmds.parent(charName + '_root_Jnt_01', charName + '_Joints_01') cmds.parent(charName + '_spline_Jnt_00', charName + '_Joints_01') cmds.parent(charName + '_Spline_Ctrl_01_grp', charName + '_Controls_01') cmds.parent(charName + '_Hip_Ctrl_01', charName + '_Controls_01')
def sqGenerateMuscleLocators(self, *args): muscleLoaded = True if not cmds.pluginInfo('MayaMuscle.mll', query=True, loaded=True): muscleLoaded = False try: cmds.loadPlugin('MayaMuscle.mll') muscleLoaded = True except: print "Error: Can not load the Maya Muscle plugin!" pass if muscleLoaded: minIndex = 0 minPosX = 1000000000000000 # just to avoid non centered characters minPosId = 0 vertexPairList = [] muscleLocatorList = [] for e, edgeName in enumerate(self.edgeList): tempCompList = cmds.polyListComponentConversion(edgeName, fromEdge=True, toVertex=True) tempExpList = cmds.filterExpand(tempCompList, selectionMask=31, expand=True) vertexPairList.append(tempExpList) edgePosA = cmds.xform(tempExpList[0], query=True, worldSpace=True, translation=True)[0] edgePosB = cmds.xform(tempExpList[1], query=True, worldSpace=True, translation=True)[0] if edgePosA < minPosX: minIndex = e minPosX = edgePosA minPosId = 0 if edgePosB < minPosX: minIndex = e minPosX = edgePosB minPosId = 1 usedIndexList = [] usedIndexList.append(minIndex) lastIndexUp = minIndex lastIndexDown = 0 upEdgeList = [] upEdgeList.append(self.edgeList[minIndex]) downEdgeList = [] for i in range(0, len(vertexPairList) - 1): if not i == minIndex: if vertexPairList[i][0] in vertexPairList[minIndex][ minPosId] or vertexPairList[i][ 1] in vertexPairList[minIndex][minPosId]: downEdgeList.append(self.edgeList[i]) usedIndexList.append(i) lastIndexDown = i for i in range(0, self.maxIter - 2): for j in range(0, len(vertexPairList)): if not j in usedIndexList: if vertexPairList[j][0] in vertexPairList[ lastIndexUp] or vertexPairList[j][ 1] in vertexPairList[lastIndexUp]: upEdgeList.append(self.edgeList[j]) usedIndexList.append(j) lastIndexUp = j break for j in range(0, len(vertexPairList)): if not j in usedIndexList: if vertexPairList[j][0] in vertexPairList[ lastIndexDown] or vertexPairList[j][ 1] in vertexPairList[lastIndexDown]: downEdgeList.append(self.edgeList[j]) usedIndexList.append(j) lastIndexDown = j break upMinusDown = len(upEdgeList) - len(downEdgeList) downMinusUp = len(downEdgeList) - len(upEdgeList) if upMinusDown > 1: for i in range(0, upMinusDown): if not len(upEdgeList) == (self.maxIter - 3): downEdgeList.append(upEdgeList[len(upEdgeList) - 1]) upEdgeList = upEdgeList[:-1] if downMinusUp > 1: for i in range(0, downMinusUp): if not len(upEdgeList) == (self.maxIter - 3): upEdgeList.append(downEdgeList[len(downEdgeList) - 1]) downEdgeList = downEdgeList[:-1] upEdgeList = upEdgeList[:self.maxIter - 1] downEdgeList = downEdgeList[:self.maxIter - 1] for k in range(0, self.maxIter - 2): cmds.select([upEdgeList[k], downEdgeList[k]]) # cmds.refresh() # cmds.pause(seconds=1) mel.eval("cMuscleSurfAttachSetup();") msa = cmds.rename("StickLips_" + str(k) + "_MSA") cmds.disconnectAttr(msa + "Shape.outRotate", msa + ".rotate") cmds.setAttr(msa + ".rotateX", 0) cmds.setAttr(msa + ".rotateY", 0) cmds.setAttr(msa + ".rotateZ", 0) muscleLocatorList.append(msa) cmds.parent(self.clusterList[k], msa, absolute=True)
def replace(self, *args): from maya import OpenMaya def getDagPath(target): dagPath = OpenMaya.MDagPath() selList = OpenMaya.MSelectionList() selList.add(target) selList.getDagPath(0, dagPath) return dagPath def getMObject(target): oNode = OpenMaya.MObject() selList = OpenMaya.MSelectionList() selList.add(target) selList.getDependNode(0, oNode) return oNode sourceName = cmds.textField(WinA_Global.fld_source, q=1, tx=1) targetName = cmds.textField(WinA_Global.fld_target, q=1, tx=1) isNamespace = cmds.checkBox(WinA_Global.chk_isNamespace, q=1, v=1) if not sourceName: return None if isNamespace: targets = cmds.ls() fnTargets = [] for target in targets: if target[:len(sourceName)] != sourceName: continue if cmds.attributeQuery('wm', node=target, ex=1): fnTarget = om.MFnDagNode(getDagPath(target)) else: fnTarget = om.MFnDependencyNode(getMObject(target)) fnTargets.append(fnTarget) for fnTarget in fnTargets: if type(fnTarget) == type(om.MFnDagNode()): cmds.rename(fnTarget.fullPathName(), targetName + fnTarget.name()[len(sourceName):]) else: cmds.rename(fnTarget.name(), targetName + fnTarget.name()[len(sourceName):]) else: targets = cmds.ls() fnTargets = [] for target in targets: if target.find(sourceName) == -1: continue if cmds.attributeQuery('wm', node=target, ex=1): fnTarget = om.MFnDagNode(getDagPath(target)) else: fnTarget = om.MFnDependencyNode(getMObject(target)) fnTargets.append(fnTarget) for fnTarget in fnTargets: if type(fnTarget) == type(om.MFnDagNode()): cmds.rename( fnTarget.fullPathName(), fnTarget.name().replace(sourceName, targetName)) else: cmds.rename( fnTarget.name(), fnTarget.name().replace(sourceName, targetName))
def doSDKs(SDKnodes, target, search, replace, i, iterExec, specialIter, SDKResults, BWNResults, mode, createDriverAttr, drAttrSearch, drAttrReplace): ''' This is the procedure that actually performs the SDK replication ''' # Declare search direction of connectionInfo command, based of tool mode. if mode: conInfoLambda = lambda node: mc.listConnections( '%s.input' % node[0], d=False, s=True, p=True, scn=True) else: conInfoLambda = lambda node: mc.listConnections( '%s.output' % node[0], d=True, s=False, p=True, scn=True) for node in SDKnodes: # Check what's connected to SDK nodes and see if the target nodes # have the same attributes as the source node, if no reults or # no matching attributes, continue. connections = conInfoLambda(node) if not connections or (not createDriverAttr and (not mc.attributeQuery( node[1].replace(drAttrSearch, drAttrReplace), node=target, ex=True) and not mc.attributeQuery( node[1].split('[')[0].replace(drAttrSearch, drAttrReplace), node=target, ex=True))): print 'CONTINUED', node # delete me continue # If createDriverAttr is set to True and the driver attribute # doesn't exist, try to create it on the new driver. elif (not mc.attributeQuery( node[1].replace(drAttrSearch, drAttrReplace), node=target, ex=True) and not mc.attributeQuery(node[1].split('[')[0].replace( drAttrSearch, drAttrReplace), node=target, ex=True)): if mode or not createDriverAttr: continue sourceDriver = mc.listConnections('%s.input' % node[0], d=False, s=True, p=False, scn=True)[0] createDriverAttrFunc(sourceDriver, target, node[1].split('[')[0], drAttrSearch, drAttrReplace) if isinstance(connections, str): connections = [connections] # Duplicate keyframe node and mirror if asked. newKeyNode = mc.duplicate(node[0])[0] if node[2]: if mc.objExists(node[0].replace(search, replace)): mc.delete(node[0].replace(search, replace)) newKeyNode = mc.rename(newKeyNode, node[0].replace(search, replace)) mirrorKeys(newKeyNode) # Go through all the connections. for curNode in connections: # If in driver mode, check to see if node connected to keyframe # is a blendWeighted node. origBW = '' if not mode: nodeType = mc.ls(curNode.split('.')[0], st=True)[1] if nodeType == 'blendWeighted': origBW = curNode connections2 = mc.listConnections('%s.output' % curNode.split('.')[0], d=True, s=False, p=True, scn=True) else: connections2 = [curNode] else: connections2 = [curNode] # Connect the duplicated keyframes # to their respective target connections. for curNode2 in connections2: if search or not mode: # regex search pattern section. curRegexer = re.search(search, curNode2) errorCheck = False print(replace, iterExec, curNode, curNode2, mode, newKeyNode, origBW) # delete me if hasattr(curRegexer, 'group'): repPattern = curRegexer.group(0) if repPattern: (errorCheck, newConn) = \ connectToConn(replace, iterExec, curNode, curNode2, repPattern, mode, newKeyNode, origBW) else: errorCheck = True else: errorCheck = True if errorCheck: if mode: print( '\nFailure to find a driver for node %s ' 'based on search criteria %s for driver node %s .' % (target, search, curNode2.split('.')[0])) mc.delete(newKeyNode) else: print( '\nFailure to find a driven for nodes %s ' 'based on search criteria %s for driven node %s .' % (target, search, curNode2.split('.')[0])) continue elif mode: mc.connectAttr(curNode2, '%s.input' % newKeyNode, f=True) newConn = curNode2 # Connect the new SDK's to the new driver attrs. if mode: mc.connectAttr('%s.output' % newKeyNode, '%s.%s' % (target, node[1]), f=True) else: mc.connectAttr( '%s.%s' % (target, node[1].replace(drAttrSearch, drAttrReplace)), '%s.input' % newKeyNode, f=True) SDKResults.append( 'Connected Driver node %s.%s.output to ' 'Driven node %s.%s .' % (newConn, '.'.join( curNode2.split('.')[1:]), target, node[1]))
def ikfkMechanics(module, extraName, jnts, mechSkelGrp, ctrlGrp, moduleType, rig): """ Create the mechanics for a IK/FK setup. [Args]: module (class) - The class of the body part module extraName (string) - The extra name for the setup jnts (list)(string) - A list of jnts to create the mechanics on mechSkelGrp (string) - The name of the mechanics skeleton group ctrlGrp (string) - The name of the control group moduleType (string) - The type of module ('arm', 'leg', etc) rig (class) - The rig class to use [Returns]: ikJnts (list)(string) - The names of the IK joints fkJnts (list)(string) - The names of the FK joints jnts (list)(string) - The names of the result joints ikCtrlGrp (string) - The name of the IK controls group fkCtrlGrp (string) - The name of the FK controls group """ jntSuffix = suffix['joint'] newJntChains = [] ## create duplicate chains for chain in ['IK', 'FK']: newJnts = utils.duplicateJntChain(chain, jnts, parent=mechSkelGrp.name) newJntChains.append(newJnts) ikJnts = newJntChains[0] fkJnts = newJntChains[1] for i, each in enumerate(jnts): newName = '{}_result{}'.format(each.rsplit('_', 1)[0], jntSuffix) jnts[i] = cmds.rename(each, newName) # utils.addJntToSkinJnt(jnts[i], rig=rig) ## settings control module.settingCtrl = ctrlFn.ctrl( name='{}{}Settings'.format(extraName, moduleType), guide='{}{}Settings{}'.format(module.moduleName, moduleType, suffix['locator']), deleteGuide=True, side=module.side, skipNum=True, parent=module.rig.settingCtrlsGrp.name, scaleOffset=rig.scaleOffset, rig=rig) if moduleType == 'arm': settingJnt = jnts[3] else: settingJnt = jnts[2] module.settingCtrl.makeSettingCtrl(ikfk=True, parent=settingJnt) ## parent constraints for jnt, ikJnt, fkJnt in zip(jnts, ikJnts, fkJnts): parConstr = cmds.parentConstraint(ikJnt, fkJnt, jnt) cmds.connectAttr(module.settingCtrl.ctrl.ikfkSwitch, '{}.{}W1'.format(parConstr[0], fkJnt)) swRev = utils.newNode('reverse', name='{}{}IKFKSw'.format(extraName, moduleType), side=module.side) swRev.connect('inputX', module.settingCtrl.ctrl.ikfkSwitch, mode='to') swRev.connect('outputX', '{}.{}W0'.format(parConstr[0], ikJnt), mode='from') ## control vis groups ikCtrlGrp = utils.newNode('group', name='{}{}IKCtrls'.format(extraName, moduleType), side=module.side, parent=ctrlGrp.name, skipNum=True) fkCtrlGrp = utils.newNode('group', name='{}{}FKCtrls'.format(extraName, moduleType), side=module.side, parent=ctrlGrp.name, skipNum=True) cmds.setDrivenKeyframe(ikCtrlGrp.name, at='visibility', cd=module.settingCtrl.ctrl.ikfkSwitch, dv=0.999, v=1) cmds.setDrivenKeyframe(ikCtrlGrp.name, at='visibility', cd=module.settingCtrl.ctrl.ikfkSwitch, dv=1, v=0) cmds.setDrivenKeyframe(fkCtrlGrp.name, at='visibility', cd=module.settingCtrl.ctrl.ikfkSwitch, dv=0.001, v=1) cmds.setDrivenKeyframe(fkCtrlGrp.name, at='visibility', cd=module.settingCtrl.ctrl.ikfkSwitch, dv=0, v=0) return ikJnts, fkJnts, jnts, ikCtrlGrp, fkCtrlGrp
charName + '_ikHandle_01') cmds.parent('cluster_' + str(i + 3) + 'Handle', charName + '_ikHandle_01') cmds.parent(charName + 'SplineIK_01', charName + '_ikHandle_01') cmds.parent(charName + '_SplineIK_Crv_01', charName + '_ikHandle_01') cmds.parent(charName + '_neck_Jnt_00', charName + '_Joints_01') cmds.parent(charName + '_root_Jnt_01', charName + '_Joints_01') cmds.parent(charName + '_spline_Jnt_00', charName + '_Joints_01') cmds.parent(charName + '_Spline_Ctrl_01_grp', charName + '_Controls_01') cmds.parent(charName + '_Hip_Ctrl_01', charName + '_Controls_01') def CreateCtr(nameCtr, ObjToParent, (posX, posY, posZ), (scaleX, scaleY, scaleZ), (rotateX, rotateY, rotateZ)): cmds.CreateNURBSCircle() cmds.rename('nurbsCircle1', nameCtr) cmds.move(posX, posY, posZ) cmds.scale(scaleX, scaleY, scaleZ) cmds.makeIdentity(apply=True) cmds.group(nameCtr, n=nameCtr + '_grp') cmds.rotate(rotateX, rotateY, rotateZ) cmds.parentConstraint(nameCtr, ObjToParent, mo=True) '''def ImportOBJ(): def importImage( fileName, fileType): cmds.file( fileName, i=True ); return 1 cmds.fileBrowserDialog( m=0, fc=ImportOBJ(), ft='OBJ', an='Import_Image', om='Import' ) '''
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 ribbonJoints(sj, ej, bendyName, module, extraName='', moduleType=None, par=None, endCtrl=False, basePar=None): """ Create a ribbon setup. [Args]: sj (string) - ej (string) - bendyName (string) - The name of the ribbon setup module (class) - The class of the body part module extraName (string) - The extra name of the ribbon setup moduleType (string) - The type of module par (string) - The name of the mechanics parent endCtrl (bool) - Toggles creating an end control basePar (string) - The name of the joints parent [Returns]: bendyEndCtrl (class) - The end control class or False """ if not basePar: basePar = sj moduleName = utils.setupBodyPartName(module.extraName, module.side) bendyName = '{}{}'.format(moduleType, bendyName) col = utils.getColors(module.side) distance = cmds.getAttr('{}.tx'.format(ej)) nPlane = cmds.nurbsPlane(p=(distance / 2, 0, 0), lr=0.1, w=distance, axis=[0, 1, 0], u=3, d=3) nPlane = cmds.rename( nPlane[0], '{}{}Bendy{}'.format(moduleName, bendyName, suffix['nurbsSurface'])) if par: cmds.parent(nPlane, par) utils.matchTransforms(nPlane, sj) ## ctrl if not cmds.objExists('{}{}Ctrls{}'.format(moduleName, moduleType, suffix['group'])): ctrlGrp = cmds.group( n='{}{}Ctrls{}'.format(moduleName, moduleType, suffix['group'])) cmds.parent(ctrlGrp, module.rig.ctrlsGrp.name) bendyCtrl = ctrlFn.ctrl(name='{}{}Bendy'.format(extraName, bendyName), side=module.side, offsetGrpNum=2, skipNum=True, rig=module.rig, scaleOffset=module.rig.scaleOffset, parent='{}{}Ctrls{}'.format( moduleName, moduleType, suffix['group'])) bendyCtrl.modifyShape(color=col['col3'], shape='starFour', scale=(0.3, 0.3, 0.3)) cmds.pointConstraint(sj, ej, bendyCtrl.offsetGrps[0].name) cmds.orientConstraint(sj, bendyCtrl.offsetGrps[0].name, sk='x') orientConstr = cmds.orientConstraint(basePar, ej, bendyCtrl.offsetGrps[1].name, sk=['y', 'z'], mo=1) cmds.setAttr('{}.interpType'.format(orientConstr[0]), 2) ## clusters cmds.select('{}.cv[0:1][0:3]'.format(nPlane)) baseClu = utils.newNode('cluster', name='{}{}BendyBase'.format(extraName, bendyName), side=module.side, parent=par) cmds.select('{}.cv[2:3][0:3]'.format(nPlane)) midClu = utils.newNode('cluster', name='{}{}BendyMid'.format(extraName, bendyName), side=module.side, parent=par) bendyCtrl.constrain(midClu.name) bendyCtrl.constrain(midClu.name, typ='scale') endCluGrpTrans = utils.newNode('group', name='{}{}BendyEndCluTrans'.format( extraName, bendyName), side=module.side, parent=par) utils.matchTransforms(endCluGrpTrans.name, ej) endCluGrpOrientYZ = utils.newNode('group', name='{}{}BendyEndCluOrient'.format( extraName, bendyName), side=module.side, parent=endCluGrpTrans.name) utils.matchTransforms(endCluGrpOrientYZ.name, endCluGrpTrans.name) endCluGrpOrientX = utils.newNode('group', name='{}{}BendyEndCluOrientX'.format( extraName, bendyName), side=module.side, parent=endCluGrpOrientYZ.name) utils.matchTransforms(endCluGrpOrientX.name, endCluGrpOrientYZ.name) cmds.select('{}.cv[4:5][0:3]'.format(nPlane)) endClu = utils.newNode('cluster', name='{}{}BendyEnd'.format(extraName, bendyName), side=module.side, parent=endCluGrpOrientX.name) cmds.parentConstraint(basePar, baseClu.name, mo=1) cmds.scaleConstraint(basePar, baseClu.name, mo=1) if not endCtrl: cmds.pointConstraint(ej, endCluGrpTrans.name, mo=1) cmds.orientConstraint(ej, endCluGrpOrientX.name, mo=1, sk=['y', 'z']) cmds.orientConstraint(sj, endCluGrpOrientYZ.name, mo=1, sk='x') bendyEndCtrl = False else: bendyEndCtrl = ctrlFn.ctrl( name='{}{}BendyEnd'.format(extraName, bendyName), side=module.side, skipNum=True, rig=module.rig, scaleOffset=module.rig.scaleOffset, parent='{}{}Ctrls{}'.format(moduleName, moduleType, suffix['group'])) bendyEndCtrl.modifyShape(color=col['col3'], shape='starFour', scale=(0.3, 0.3, 0.3)) cmds.parentConstraint(ej, bendyEndCtrl.offsetGrps[0].name) bendyEndCtrl.constrain(endCluGrpTrans.name) bendyEndCtrl.constrain(endCluGrpTrans.name, typ='scale') ## rivets rivJntPar = sj for i in [0.1, 0.3, 0.5, 0.7, 0.9]: rivJnt = createRivet('{}Bendy'.format(bendyName), extraName, module, nPlane, pv=0.5, pu=i, parent=par, rivJntPar=rivJntPar) rivJntPar = rivJnt return bendyEndCtrl