def use_weight_set(): cmds.select(cmds.cluster(cmds.textScrollList('UI_cluster_list', q=True, si=True)[0], q=True, g=True)[0]) mel.eval("ConvertSelectionToVertices;") weights = cmds.percent (cmds.textScrollList('UI_cluster_list', q=True, si=True)[0], q=True, v=True) cmds.filterExpand( ex=True, sm=31 ) elements = cmds.ls(sl=True, fl=True) return elements, weights
def expandSelection(): '''Expands current component selection to its max bounds''' oldSize = len(cmds.filterExpand(sm=[28,29,31,32,33,34,35])) while(1): cmds.polySelectConstraint(pp=1,t=0x00100) newSize = len(cmds.filterExpand(sm=[28,29,31,32,33,34,35])) if oldSize == newSize: break oldSize = newSize
def getObjectVertices(ob, verts): ov = cmds.polyListComponentConversion(ob, tv=1) ov = cmds.filterExpand(ov, ex=1, fp=1, sm=31) verts = cmds.filterExpand(verts, ex=1, fp=1, sm=31) # print ov # print verts com = [] for v in verts: if v in ov: com.append(v) return com
def edgeLoopsToCurve(edgeList,form=2,degree=1): ''' Generate edge loop curves from the specified list of edges. @param edgeList: The list of mesh edges to generate edge loop curves from. @type edgeList: list @param form: NURBS curve form. 0 = Periodic, 1 = Open, 2 = Best Guess. @type form: str @param degree: NURBS curve degree. @type degree: str ''' # Filter/Check Edge List edgeList = mc.filterExpand(edgeList,ex=True,sm=32) if not edgeList: raise Exception('Invalid edge list!') # For Each Edge edgeCurveList = [] for edge in edgeList: # Get Mesh edgeId = glTools.utils.component.index(edge) meshShape = mc.ls(edge,o=True)[0] mesh = mc.listRelatives(meshShape,p=True)[0] prefix = mesh.split(':')[-1] # To Edge Loop mc.polySelect(mesh,edgeLoop=edgeId) # Edge Loop to Curve edgeCurve = mc.polyToCurve(ch=False,form=form,degree=degree)[0] # Append List edgeCurveList.append(edgeCurve) # Return Result return edgeCurveList
def edgeLoopWeights(edgeList): """ """ # Check Edge List if not edgeList: raise Exception('Invalid or empty edge list!') edgeList = cmds.filterExpand(edgeList, ex=True, sm=32) or [] if not edgeList: raise Exception('Invalid edge list! List of polygon edges required...') # Get Mesh from Edges mesh = list(set(cmds.ls(edgeList, o=True) or [])) if len(mesh) > 1: raise Exception('Edges from multiple mesh shapes were supplied! ' + str(mesh)) mesh = mesh[0] for edge in edgeList: # Get Edge ID edgeID = glTools.utils.component.index(edge) # Get Vertices from Edge edgeVerts = cmds.polyListComponentConversion(edge, fe=True, tv=True) # Get Average Vertex Weights cmds.select(edgeVerts) glTools.tools.copyPasteWeights.averageWeights() # Select Edge Loop Vertices cmds.polySelect(mesh, edgeLoop=edgeID) loopEdges = cmds.ls(sl=1, fl=1) loopVerts = cmds.polyListComponentConversion(loopEdges, fe=True, tv=True) cmds.select(loopVerts) glTools.tools.copyPasteWeights.pasteWeights() # Return Result return mesh
def addSymEdgeAttr(edge): ''' Add mesh symmetry edge attribute based on specified mesh edge. @param edge: Mesh edge that defined the center edge row of a symmetrical mesh @type edge: str ''' # Check Edge edge = mc.filterExpand(edge,ex=True,sm=32) or [] if not edge: raise Exception('No valid mesh edge selected!') if len(edge) > 1: print('Multiple mesh edges found! Using first edge only ("'+edge[0]+'").') edge = edge[0] # Get Edge Mesh mesh = mc.ls(edge,o=True) or [] if not mesh: raise Exception('Unable to determine mesh from edge!') if len(mesh) > 1: print('Multiple mesh objects found from edge!') mesh = mesh[0] # Get Edge ID edgeID = glTools.utils.component.index(edge) # Add Attribute symAttr = 'symmetryEdgeId' if not mc.objExists(mesh+'.'+symAttr): mc.addAttr(mesh,ln=symAttr,at='long',min=0,dv=edgeID) mc.setAttr(mesh+'.'+symAttr,edgeID) # Return Result return mesh+'.'+symAttr
def setObjectToShatterCmd(self, *args): ''' ''' if not (cmds.draggerContext(self._IScontextTool._mContext, exists = True)): iMinTime = cmds.playbackOptions(query = True, minTime = True) cmds.currentTime(iMinTime, edit = True) polySelection = cmds.filterExpand(selectionMask = 12) if polySelection: if len(polySelection) > 0: mBreakNode = cmds.listConnections(polySelection[0], sh = True, type = 'fxBreakGeometry') if not mBreakNode: cmds.button(self._ISaddBtn, edit = True, label = 'Please wait... checking mesh toplogy') self._IScontextTool.checkForNonManifoldMeshes(polySelection[0]) cmds.delete(polySelection[0], ch = True) self.resetIShatterGUI() self._IScontextTool._mVoroObject = polySelection[0] cmds.button(self._ISaddBtn, edit = True, label = polySelection[0]) cmds.button(self._ISdelBtn, edit = True, enable = True) cmds.button(self._ISprocessBtn, edit = True, enable = True) cmds.checkBox(self._ISborderEdgesCbx, edit = True, enable = True) cmds.checkBox(self._IShideObjectsCbx, edit = True, enable = True) else: cmds.confirmDialog(title = 'Oups... IShatter Error', message = 'You must select one mesh object first !', button = 'OK', defaultButton = 'Yes', cancelButton = 'No', dismissString = 'No')
def CreateObjects(objectlist,*args): selCVs = cmds.ls(sl=True) selCVs_pos = cmds.filterExpand(ex=True,sm=28) cmds.select(cl=True) ObjName = cmds.optionMenu(objectlist,query=True,value=True) for num in selCVs_pos: position = cmds.pointPosition(num,w=True) pos_x = position[0] pos_y = position[1] pos_z = position[2] if(ObjName == "Cube"): make_obj = cmds.nurbsCube(); cmds.setAttr(make_obj[0] + ".tx",pos_x) cmds.setAttr(make_obj[0] + ".ty",pos_y) cmds.setAttr(make_obj[0] + ".tz",pos_z) if(ObjName == "Circle"): make_obj = cmds.circle(); cmds.setAttr(make_obj[0] + ".tx",pos_x) cmds.setAttr(make_obj[0] + ".ty",pos_y) cmds.setAttr(make_obj[0] + ".tz",pos_z) if(ObjName == "Joint"): make_obj = cmds.joint() cmds.setAttr(make_obj + ".tx",pos_x) cmds.setAttr(make_obj + ".ty",pos_y) cmds.setAttr(make_obj + ".tz",pos_z)
def alignUVs(doU, minU, doV, inV): """ align selected uvs based on the one most on top, bottom, left, right """ # get the selected UVs from current selection selectedItems = cmds.filterExpand(ex=False, sm=35) # 35 means UVs uvMin = [] uvMax = [] # get the 3d bounding box of selection uvInfo = cmds.polyEvaluate(bc2=True) uvMin[0] = uvInfo[0] uvMin[1] = uvInfo[2] uvMax[0] = uvInfo[1] uvMax[1] = uvInfo[3] if doU: if minU: cmds.polyEditUV(r=False, u=uvMin[0]) else: cmds.polyEditUV(r=False, u=uvMax[0]) if doV: if minV: cmds.polyEditUV(r=False, v=uvMin[1]) else: cmds.polyEditUV(r=False, v=uvMax[1])
def GrpEdgstoVertx(): sel=mc.ls(sl=True) if sel: if (mc.filterExpand(sel[0], sm = 32)): if not len(sel)==1: seled = flatten(sel) seled1 = seled[:] edgGrps = [] comEdges = [] for i in range(len(seled1)): if len(seled) > 1: if seled1[i] in comEdges: continue mc.select(seled1[i], r = 1) mel.eval('polySelectEdges edgeLoopOrBorder') loopEdges = flatten(mc.ls(sl=1)) comEdges = list(set(seled).intersection(set(loopEdges))) #edgGrps.append(comEdges) print comEdges if comEdges not in edgGrps : edgGrps.append(comEdges) mc.select(cl=1) for each in comEdges: mc.select(each,add=True) mel.eval('polyToCurve -form 2 -degree 3') else: mel.eval('polyToCurve -form 2 -degree 3') mc.select(cl=1) else: mc.confirmDialog (title='Error' ,message= 'Please Select Edges', button=['OK'] ,defaultButton='Yes') else: mc.confirmDialog (title='Error' ,message= 'Nothing Selected..Please Select any Edges', button=['OK'] ,defaultButton='Yes')
def shrinkVertexSelection(vtxSel): ''' Shrink the specified vertex selection list. @param vtxSel: Vertex selection list to expand. @type vtxSel: list ''' # ========== # - Checks - # ========== # Check Vertex Selection vtxSel = mc.filterExpand(vtxSel,sm=31) if not vtxSel: raise Exception('Invalid vertex selection!') # ==================== # - Shrink Selection - # ==================== # Convert To Faces conSel = mc.polyListComponentConversion(vtxSel,fv=True,tf=True,internal=True) # Convert To Vertex newSel = mc.polyListComponentConversion(conSel,ff=True,fe=True,tv=True,internal=True) # ================= # - Return Result - # ================= return newSel
def averageCoord(surfaceSkin,influence,controlPointList=[]): ''' Get the averaged target surface coordinate of the specified influence for the given control points @param surfaceSkin: surfaceSkin node to get the coordinates for @type surfaceSkin: str @param influence: Influence surface to query @type influence: str @param controlPointList: List of control points to get the target coordinate for @type controlPointList: str ''' # Check controlPointList if not controlPointList: controlPointList = mc.filterExpand(sm=(28,31)) if not controlPointList: raise Exception('No components specified for average coordinate operation!!') # Get surfacSkin utility object ssUtil = glTools.surfaceSkin.utils.SurfaceSkinUtilities() # Get coord average uv = [0,0] controlPointCnt = len(controlPointList) # Iterate over control point list for controlPoint in controlPointList: # Get control point target coordinate cpUV = getCoord(surfaceSkin,influence,controlPoint) uv[0] += cpUV[0] uv[1] += cpUV[1] # Average coordinates uv[0] /= controlPointCnt uv[1] /= controlPointCnt # Return result return (uv[0],uv[1])
def buildRigFromSelection(): ''' Build basic groom surface scuplting rig based on the current selection. ''' # Get Selection sel = mc.ls(sl=1) iso = mc.filterExpand(sel,sm=45) if not iso: iso = [] # Adjust Selection sel = list(set(sel)-set(iso)) # Build Surface Rigs for surface in sel: # Check Surface if glTools.utils.surface.isSurface(surface): minU = mc.getAttr(surface+'.minValueU') maxU = mc.getAttr(surface+'.maxValueU') midU = minU + ((maxU-minU)*0.5) buildRig(surface,uValue=midU) # Build Isoparm Rigs for crv in iso: surface = mc.ls(crv,o=True)[0] uValue = float(crv.split('[')[-1].split(']')[0]) buildRig(surface,uValue)
def getNormals(self): # Current vertexFace for this face vfs = cmds.polyListComponentConversion( self.name, ff=1, tvf=1 ) vfs = cmds.filterExpand(vfs, expand=True, sm=70) # normals = [] ''' for vf in vfs: for vert in self.vertex: vtxFaces, normals = Vertex.getFaceNormals(self.nodeName) ''' for vert in self.vertex: # vtxFaces, normals = Vertex.getFaceNormals(vert.) for curVfs in vfs: check = False if( vert.normals.has_key(curVfs)): self.normals.append( vert.normals[curVfs] ) check = True # if( not check ): # self.normals.append([]) return vfs
def setTargetCoordSel(surfaceSkin): ''' Selection based wrapper for setTargetCoord @param surfaceSkin: surfaceSkin node to apply the coordinates to @type surfaceSkin: str ''' # Get surfacePoint selection surfacePoint = mc.filterExpand(sm=41)[0] # Get controlPoint controlPoints = mc.filterExpand(sm=31) if not controlPoints: controlPoints = mc.filterExpand(sm=28) if not controlPoints: raise Exception('No components selected to set target coordinates for!!') # Apply target coord for cp in controlPoints: setTargetCoord(surfaceSkin,cp,surfacePoint)
def doIt(self,argList): polygons = cmds.filterExpand(sm=12) if not polygons: print 'Please select a polygon.' return paths = cmds.fileDialog2(dialogStyle=2, fileMode = 3, okCaption = "Save", cancelCaption = "Cancel") if not paths: return for p in range(0, len(polygons)): polygon = polygons[p] related_cluster = mel.eval('findRelatedSkinCluster '+polygon) if related_cluster == '': print 'Please bind skin for this polygon.' + polygon continue path = paths[0] joints = cmds.skinPercent(related_cluster, polygon+'.vtx[0]', q = True, t = None); f = open(path+'/'+polygon+'.weights', 'w') vertices = cmds.getAttr(polygon+'.vrts', multiIndices = True); for i in range(0, len(vertices)): infs = cmds.skinPercent(related_cluster, polygon+'.vtx['+str(vertices[i])+']', q = True, v = True) pos = cmds.xform(polygon+'.vtx['+str(vertices[i])+']', q=1, ws=1, t=1) f.write('vp ' + str(pos[0])+' '+str(pos[1])+' '+str(pos[2]) + '\n') f.write('vinf'); for j in range(0, len(infs)): f.write(' ' + joints[j] + ' ' + str(infs[j])) f.write('\n') f.close() print 'Export Complete.'
def cache(s, meshes=None): """ Store joints influence on objects for quick checking later """ if meshes: # Cache Joints and Meshes for mesh in meshes: skin = mel.eval("findRelatedSkinCluster %s" % mesh) if skin: joints = cmds.skinPercent(skin, "%s.vtx[0]" % mesh, q=True, t=None) for vert in range(cmds.getAttr("%s.weightList" % skin, size=True)): for i, v in enumerate(cmds.skinPercent(skin, "%s.vtx[%s]" % (mesh, vert), q=True, v=True)): joint = joints[i] if 0.2 < v: # Sort by joints s.joints[joint] = s.joints.get(joint, []) s.joints[joint].append("%s.vtx[%s]" % (mesh, vert)) # Sort by meshes s.meshes[mesh] = s.meshes.get(mesh, {}) s.meshes[mesh][joint] = s.meshes[mesh].get(joint, {}) s.meshes[mesh][joint][vert] = v # Speed up Cache if s.joints: s.select.ignore = True for j in s.joints: cmds.select(s.joints[j], r=True) s.joints[j] = cmds.filterExpand(ex=False, sm=31) cmds.select(clear=True) else: s.meshes = {} s.joints = {} pass
def getFaceNormals( vertex ): # vertex normal name fvtx = cmds.polyListComponentConversion( vertex, fv=True, tvf=True ) allFvtx = cmds.filterExpand( fvtx, expand=True, sm=70 ) # Face index # vtxFaces = Vertex.getFaceVertexIndex(allFvtx) ''' # There could be duplicate tags, so the dictionary will over write data! tempNormals = {} for i, curFvtx in enumerate(allFvtx): normalCoords = cmds.polyNormalPerVertex( curFvtx, q=True, xyz=True ) curFace = vtxFaces[i] tempNormals[curFvtx] = normalCoords return tempNormals ''' # normals = [] normals = {} for i, curFvtx in enumerate(allFvtx): normalCoords = cmds.polyNormalPerVertex( curFvtx, q=True, xyz=True ) # curFace = vtxFaces[i] normals[curFvtx] = normalCoords # normals.append( normalCoords ) return allFvtx, normals
def MakeJntAndIKs(side): """ 选择两圈眼球上的线,生成骨骼和ik,side的值例如:R_In or R_Out ps: 选择骨骼链的子物体,打组,centerPivot,在原点生成一个骨点,用组约束骨点,正确命名,然后将IK组分别放到对应骨点下边。 """ lx_start=mc.xform('loc_eyeCenter01',q=1,ws=1,t=1) lx_mouthPnt= mc.filterExpand(sm=31) mc.select (cl=1) lx_Jnts=[] lx_IKs = [] for i in lx_mouthPnt : lx_end=mc.xform(i,q=1,ws=1,t=1) lx_stJnt=mc.joint (n=("Jnt_"+side+"_st"),p=(lx_start[0],lx_start[1],lx_start[2]),radius=0.1) lx_edJnt=mc.joint (n=("Jnt_"+side+"_ed"),p=(lx_end[0],lx_end[1],lx_end[2]),radius=0.1) lx_scik =mc.ikHandle (n=("scik_"+side+str(01)),sj=lx_stJnt,ee=lx_edJnt,sol="ikSCsolver") #mc.setAttr((str(lx_scik[0]) +".visibility") ,0) mc.select(cl=1) lx_Jnts.append(lx_stJnt) lx_IKs .append(lx_scik[0]) mc.select(lx_Jnts,r=1) mc.group(n=("grp_Jnts"+side)) mc.select(lx_IKs,r=1) mc.group(n=("grp_iks"+side)) mc.setAttr((str("grp_iks"+side) +".visibility") ,0) #3.选择眼皮曲线,执行脚本,生成 def MakeEyeLidJnts(cuvs):
def deformCharacterShapeSel(self, value): RN = mc.referenceQuery(self.core.skCharacter[int(value)-1], referenceNode=1) Nodes = mc.referenceQuery(RN, nodes=1) self.characterdeformShape = [] self.allCharacterRightdeformShape = [] for item in Nodes: if self.nodeTypeSelf(item) in self.shapeType: self.characterdeformShape.append(item) for each in self.characterdeformShape: itemP = mc.listRelatives(each, p=1)[0] itemPP = mc.listRelatives(itemP, p=1) if itemPP != None and mc.getAttr('%s.v'%itemP) != 0 and mc.getAttr('%s.v'%itemPP[0]) != 0: self.allCharacterRightdeformShape.append(each) self.allCharacterRightdeformShape.reverse() for item in self.allCharacterRightdeformShape: if mc.filterExpand( item, sm=(10,12)) == None: self.allCharacterRightdeformShape.remove(item) for item in self.allCharacterRightdeformShape: if item.endswith('Orig') == True: self.allCharacterRightdeformShape.remove(item) for item in self.allCharacterRightdeformShape: if item.endswith('Orig') == True: self.allCharacterRightdeformShape.remove(item) for item in self.allCharacterRightdeformShape: if item.endswith('Orig') == True: self.allCharacterRightdeformShape.remove(item) for item in self.allCharacterRightdeformShape: if item.endswith('Orig') == True: self.allCharacterRightdeformShape.remove(item) for item in self.allCharacterRightdeformShape: if item.endswith('Orig') == True: self.allCharacterRightdeformShape.remove(item) return self.allCharacterRightdeformShape
def storeSelection(self): #Handle Object Selection for item in cmds.ls(sl=1,tr=1,l=1): obj = ObjSelData(item) self.__setitem__(item, obj) #Handle Component Selection for item in cmds.ls(hl=1,l=1): obj = ObjSelData(item, hilite=True) obj.populateSubSelection() self.__setitem__(item, obj) #Handle Components whose mesh is hilited sel_comps = [] clean_set = set() for compType in ObjSelData._filterExpandMap.values(): sel_comps += cmds.filterExpand(ex=0,fp=1,sm=compType) or [] for item in sel_comps: shape = item.split('.')[0] parent = shape.rsplit('|',1)[0] clean_set.add(parent) for item in list(clean_set) : obj = ObjSelData(item, hilite=True) obj.populateSubSelection() self.__setitem__(item, obj)
def transUVHier(rig): args = cmds.ls(sl=True) if rig: #select the target if it is skinned meshes cmds.select(args[1], r=1) #select just the polys cmds.SelectHierarchy() polys = cmds.filterExpand(cmds.ls(sl=1), expand=1, sm=12) for poly in polys: #if the geo has a skinCluster then... melCommand = "findRelatedDeformer(\""+str(poly)+"\")" deformers = mel.eval(melCommand) #print 'for object: ' + poly print deformers if skinClusterDef(deformers): shapes = getShapes(poly) if len(shapes) > 0: if cmds.objExists(shapes[0]+'Orig'): cmds.setAttr(shapes[0]+'Orig.intermediateObject', 0) #transferUvHierarchy( args[0], args[1] ) if rig: for poly in polys: #if the geo has a skinCluster then... melCommand = "findRelatedDeformer(\""+str(poly)+"\")" deformers = mel.eval(melCommand) #print 'for object: ' + poly if skinClusterDef(deformers): shapes = getShapes(poly) cmds.delete(shapes[0]+'Orig', ch=1) cmds.setAttr(shapes[0]+'Orig.intermediateObject', 1)
def buildEdgeCurves(edges,name,color=None): ''' Build poly edge curves. Group, name and color resulting curves. @param edges: List of poly edges to extract as curves. @type edges: str @param name: Curve and group name prefix. @type name: str @param color: Color to apply to the edge curve (group). @type color: int or str or None ''' # Get Edges edges = mc.filterExpand(ex=True,sm=32) # Poly Edges if not edges: raise Exception('Invalid or empty edge list!') # Get Master Group masterGrp = buildMasterCurveGroup('edgeCurveGroup') # Get Curve Group curveGrp = buildCurveGroup(name,color) try: mc.parent(curveGrp,masterGrp) except: pass # Build Edge Curves crvList = [] for edge in edges: crv = mc.polyToCurve(edge,form=2,degree=1)[0] for at in 'trs': mc.setAttr(crv+'.'+at,l=True,cb=False) mc.parent(crv,curveGrp) # Return Result return curveGrp
def getMeshVertexData( mesh ): returnData = [] exportObject = 'bwExportObject' cmds.duplicate( mesh, n=exportObject ) cmds.polyTriangulate(exportObject) numOfFaces = cmds.polyEvaluate(exportObject, f=True ) for i in xrange(0, numOfFaces): faceSelect = exportObject + '.f[' + str(i) + ']' fVertices = [] fVertices = cmds.polyListComponentConversion(faceSelect, ff = True, tvf = True) fVertices = cmds.filterExpand(fVertices, sm = 70, ex = True) print fVertices for vertex in fVertices: faceDict = {} vName = cmds.polyListComponentConversion(vertex, fvf = True, tv = True) xyz = [] xyz = cmds.xform(vName, q = True, os = True, t = True) faceDict['x'] = round(xyz[0], 2) faceDict['y'] = round(xyz[1], 2) faceDict['z'] = round(xyz[2], 2) normal = [] normal = cmds.polyNormalPerVertex(vertex, q = True, xyz = True) faceDict['xN'] = round(normal[0], 2) faceDict['yN'] = round(normal[1], 2) faceDict['zN'] = round(normal[2], 2) # vuv = [] # vuv = cmds.polyListComponentConversion(vertex, fvf = True, tuv = True) # uvCoords = [] # uvCoords = cmds.polyEditUV(vuv[0], q = True, u = True, v = True) # faceDict['u'] = round(uvCoords[0], 2) # faceDict['v'] = round(uvCoords[0], 2) returnData.append(faceDict) cmds.delete(exportObject) return json.dumps(returnData)
def meshFaceConstraintList(faceList=[], transformList=[], orient=True, prefix=''): """ """ # ========== # - Checks - # ========== # Face List if not faceList: faceList = cmds.filterExpand(sm=34) if not faceList: raise Exception('No mesh face list specified for constraint!') # Transform List if not transformList: transformList = ['' for vtx in vtxList] # Vertex / Face list length if not len(faceList) == len(transformList): raise Exception('Face and Transform list length mis-match!') # ====================== # - Create Constraints - # ====================== constraintList = [] for i in range(len(faceList)): cmds.select(cl=True) itPrefix = prefix + '_' + str(i) constraintList.append(meshFaceConstraint(faceList[i], transformList[i], orient=orient, prefix=itPrefix)) # ================= # - Return Result - # ================= return constraintList
def alignVertices(minX, maxX, minY, maxY, minZ, maxZ): """ align vertices in 3d """ # get the selected vertices from current selection selectedItems = cmds.filterExpand(ex=False, sm=31) # 31 means vertices # get the 3d bounding box of selection bInfo = cmds.polyEvaluate(bc=True) xmin = bInfo[0][0] xmax = bInfo[0][1] ymin = bInfo[1][0] ymax = bInfo[1][1] zmin = bInfo[2][0] zmax = bInfo[2][1] if minX: cmds.move(xmin, moveX=True) if maxX: cmds.move(xmax, moveX=True) if minY: cmds.move(ymin, moveY=True) if maxY: cmds.move(ymax, moveY=True) if minZ: cmds.move(zmin, moveZ=True) if maxZ: cmds.move(zmax, moveZ=True)
def expandVertexSelection(vtxSel,useFace=False): ''' Expand the specified vertex selection list. @param vtxSel: Vertex selection list to expand. @type vtxSel: list @param useFace: Expand the selection using face connection instead of edge connection. @type useFace: bool ''' # ========== # - Checks - # ========== # Check Vertex Selection vtxSel = mc.filterExpand(vtxSel,sm=31) if not vtxSel: raise Exception('Invalid vertex selection!') # ==================== # - Expand Selection - # ==================== conSel = [] if useFace: # Convert To Faces conSel = mc.polyListComponentConversion(vtxSel,fv=True,tf=True,internal=False) else: # Convert To Faces conSel = mc.polyListComponentConversion(vtxSel,fv=True,te=True,internal=False) # Convert To Vertex newSel = mc.polyListComponentConversion(conSel,ff=True,fe=True,tv=True,internal=False) # ================= # - Return Result - # ================= return newSel
def meshVertexConstraintList(vtxList=[],transformList=[],orient=True,prefix=''): ''' ''' # ========== # - Checks - # ========== # Vertex List if not vtxList: vtxList = mc.filterExpand(sm=31) if not vtxList: raise Exception('No mesh vertex list specified for constraint!') # Transform List if not transformList: transformList = ['' for vtx in vtxList] # Vertex / Transform list length if not len(vtxList) == len(transformList): raise Exception('Vertex and Transform list length mis-match!') # ====================== # - Create Constraints - # ====================== constraintList = [] for i in range(len(vtxList)): mc.select(cl=True) itPrefix = prefix+'_'+str(i) constraintList.append(meshVertexConstraint(vtxList[i],transformList[i],orient=orient,prefix=itPrefix)) # ================= # - Return Result - # ================= return constraintList
def get(curves=[]): ''' filters transforms from the selection or the objects you throw at it ''' from maya.cmds import filterExpand # if nothing given get from the selection if not curves: curves = filterExpand(sm=9) # else check the given objects for transforms else: curves = filterExpand(curves, sm=9) if not curves: raise IOError, 'could not get curves!' return curves
def getCurrentCoords( vertex ): uv = cmds.polyListComponentConversion( vertex, fv=True, tuv=True ) if( uv ): uvAll = cmds.filterExpand( uv, expand=True, sm=35 ) uvCoords = cmds.polyEditUV( uvAll , q=True ) return uvCoords else: return []
def autoAverageWeights(): """ """ # Get Component Selection sel = cmds.filterExpand(ex=True, sm=[28, 31, 46]) if not sel: return # For Each Vertex for vtx in sel: # Select Vert cmds.select(vtx) # Expand Selection mel.eval('PolySelectTraverse 1') cmds.select(vtx, d=True) # Calculate Average Weights from Neighbours averageWeights() cmds.select(vtx) # Paste Average Weights pasteWeights()
def pickMesh(self): selection = cmds.ls(selection=True) mesh = cmds.filterExpand(selection, sm=12) if mesh == None: om.MGlobal.displayError("your selection is not a polygon mesh") return self.mesh = mesh self.ui.pickMesh.setText(mesh[0]) self.shape = cmds.listRelatives(mesh, shapes=True) for node in mesh: history = cmds.listHistory(node) or [] deformHistory = cmds.ls(history, type="geometryFilter", long=True) if not deformHistory == []: om.MGlobal.displayWarning( "mesh has deformer in history that might affect the displacement, don't forget to check them if the displacement isn't working as expected" )
def findDagKey(self): """find selected dag keys""" selected = [] for mask in self.COMPONENTS: # search by mask components if cmds.filterExpand(sm=mask, ex=False): selected.append(self.COMPONENTS[mask]) if len(selected) == 2: break else: objects = cmds.ls(sl=True, an=True, o=True) for node in objects: child = cmds.listRelatives(node, s=True, f=True) if not child: continue child = cmds.nodeType(child[0]) if child not in selected or self.preferences["same_dag"]: selected.append(child) if len(selected) == 2: break selected.sort() return selected
def exportBlendshape(self): ''' Export blendshape data. Select mesh with blendShape node. ''' sel = cmds.ls(sl=1, tr=1) if not sel: LOG.error( 'Selection cannot be empty. Please select a mesh to export blendShape node.' ) return meshes = cmds.filterExpand(sel, sm=12) if not meshes: LOG.error( 'Selection must contain a mesh. Please select a mesh to export blendShape node.' ) return elif len(meshes) > 1: LOG.error( 'More than 1 mesh is selected. Please select only one mesh to export blendShape node.' ) return meshNode = meshes[0] history = cmds.listHistory(meshNode) bShp = cmds.ls(meshNode, history, type='blendShape') if not bShp: LOG.error('No blendShape node found on {}'.format(meshNode)) return elif len(bShp) > 1: LOG.error( 'More than 1 blendShape node is found on {}. Please make sure selected mesh has 1 blendShape node.' .format(meshNode)) return bShp = bShp[0] filepath = self.data['lineedits']['browse'].text() if not app.isValidPath(filepath): LOG.error('Filepath is not valid. {0}'.format(filepath)) return blendshapes.exportBlendShapes(filepath, bShp, exportTarget=0)
def unfold(sel=None): tim = cm.timerX(st=1) lssl = cm.ls(sel, l=1) if not lssl: lssl = [x for x in cm.ls(tr=1, l=1, sl=1) if cm.listRelatives(x, s=1, type="mesh")] if not lssl: return for sel in lssl: # split first split_shells(sel) vtxs = cm.filterExpand(cm.ls(sel+".vtx[*]"), sm=31) # unfold in space for vtx in vtxs: uvbb = cm.polyEvaluate(vtx, bc2=1) # pos = uv_to_ws(uvbb[0][0], uvbb[1][1], flat="z") # cm.move(pos[0], pos[1], pos[2], vtx) cm.move(0, uvbb[1][1], uvbb[0][0], vtx) print ("Finidshed in: ", cm.timerX(st=1) - tim)
def GrpEdgstoVertx(): sel = mc.ls(sl=True) if sel: if (mc.filterExpand(sel[0], sm=32)): if not len(sel) == 1: seled = flatten(sel) seled1 = seled[:] edgGrps = [] comEdges = [] for i in range(len(seled1)): if len(seled) > 1: if seled1[i] in comEdges: continue mc.select(seled1[i], r=1) mel.eval('polySelectEdges edgeLoopOrBorder') loopEdges = flatten(mc.ls(sl=1)) comEdges = list( set(seled).intersection(set(loopEdges))) #edgGrps.append(comEdges) print comEdges if comEdges not in edgGrps: edgGrps.append(comEdges) mc.select(cl=1) for each in comEdges: mc.select(each, add=True) mel.eval('polyToCurve -form 2 -degree 3') else: mel.eval('polyToCurve -form 2 -degree 3') mc.select(cl=1) else: mc.confirmDialog(title='Error', message='Please Select Edges', button=['OK'], defaultButton='Yes') else: mc.confirmDialog(title='Error', message='Nothing Selected..Please Select any Edges', button=['OK'], defaultButton='Yes')
def getUVs(self): # Getting current uvset currUVSet = cmds.polyUVSet(self.name, q=True, currentUVSet=True)[0] for i, uvSet in enumerate(self.uvSets): self.uvs[uvSet] = [] # Setting uvSet temp cmds.polyUVSet(self.name, currentUVSet=True, uvSet=uvSet) # Get uv maps uvMaps = cmds.polyListComponentConversion(self.name, ff=1, tuv=1) if (uvMaps): uvMaps = cmds.filterExpand(uvMaps, expand=True, sm=35) # Check to make sure there are uv's on this face. for uvMap in uvMaps: # Get my uvValues uvCoords = cmds.polyEditUV(uvMap, q=True) self.uvs[uvSet].append(uvCoords) # Returning to orginal uvSet cmds.polyUVSet(self.name, currentUVSet=True, uvSet=currUVSet)
def sequential_rename(name_format): selection = cmds.ls(sl=True) polygons = cmds.filterExpand(selection, sm=12) arg_length = len(name_format) tokens = name_format.split('#') print tokens tokens_length = len(tokens[0]) + len(tokens[len(tokens) - 1]) num_length = arg_length - tokens_length i = 0 while i < len(polygons): zero_string = '' loop_number = i + 1 current_zeros = num_length - len(str(loop_number)) j = 0 while j < current_zeros: zero_string += '0' j += 1 current_number = zero_string + str(loop_number) current_name = tokens[0] + current_number + tokens[len(tokens) - 1] cmds.rename(polygons[i], current_name) i += 1
def locatorPPC(): """ sourceFile: doCreatePointOnPolyConstraintArgList.mel sourcePath: C:\Program Files\Autodesk\Maya2015\scripts\others [note 1] # mel.eval('doCreatePointOnPolyConstraintArgList 2 {"0", "0", "0", "1", "", "1", "0", "0", "0", "0"}') [note 1] # eval 上面指令,會在某些狀況出錯,像當目標為 rigidBody 時,會因為 pycmd 抓到 shapeName 而產生 [note 1] # " // Error: line 0: setAttr: No object matches name: " 這樣的錯誤 [note 1] # 因此將指令依照 sourceFile 拆解如下 """ def evalPPC(pycmd): # doCreatePointOnPolyConstraint cmd = '{string $constraint[]=`pointOnPolyConstraint -offset 0 0 0 -weight 1`' + pycmd + ';}' mel.eval(cmd) componentList = cmds.filterExpand(sm= [31, 32, 34]) if componentList: for component in componentList: cmds.spaceLocator(n= component + 'loc') grpName = cmds.group(n= component + 'grp') cmds.select(component, r= 1) cmds.select(grpName, add= 1) # [note 1] start # make cmd pycmd = ppc.assembleCmd() try: evalPPC(pycmd) except: cmds.warning('Error occurred during operation. This is Plan B trying.') wrongName = pycmd.split('"')[1][1:-2] shapeName = component.split('.')[0] transName = cmds.listRelatives(shapeName, p= 1)[0].split(':')[-1] pycmd = pycmd.replace(wrongName, transName) evalPPC(pycmd) # [note 1] end else: cmds.warning('select one or more vertex, edge or face')
def placeEyeCenter (self, *args): '''Place locator in the center of the eyeball. Called by 'UI' function. Call functions: None ''' selection = cmds.filterExpand (sm = 12) # self.eyeName = cmds.textField (self.txtfEye, q = 1, tx = 1) if selection == None : self.eyeLoc = None # self.eyeName = None cmds.inViewMessage(smg = "ERROR, Select Eyeball First!!!", pos = "midCenterTop", fade = True, \ fontSize=15) else : eyeball = selection [0] if not self.eyeName : self.eyeName = name = "DefaultEye" else : # name = self.eyeName name = eyeball eyeTemp = cmds.duplicate (eyeball) [0] cmds.xform (eyeTemp, cp = 1) self.eyeLoc = cmds.spaceLocator (n = (name + "_eyeCenter_locator")) [0] cnstrTemp = cmds.pointConstraint (eyeTemp, self.eyeLoc) cmds.delete (cnstrTemp) cmds.delete (eyeTemp) # lock locator cmds.setAttr (self.eyeLoc + ".overrideEnabled", 1) cmds.setAttr (self.eyeLoc + ".overrideDisplayType", 2) cmds.select (cl = 1) # Update UI cmds.textField (self.txtfLoc, e = 1, tx = self.eyeLoc) cmds.button (self.btnPlaceCenter, e = 1, en = 0) cmds.button (self.btnUndoPlaceCenter, e = 1, en = 1)
def batchImportSkinClusterWeights(): rigCharacterGroup = SEJointHelper.getSelectedRigCharacterGroup() if rigCharacterGroup == None: return fileResult = cmds.fileDialog2(fm=3) if fileResult != None: modelGroup = SERigObjectTypeHelper.getCharacterModelGroup( rigCharacterGroup) if modelGroup: cmds.select(modelGroup) shapeNames = cmds.filterExpand(sm=[12]) cmds.select(rigCharacterGroup) totalProgress = len(shapeNames) curProgress = 0 cmds.progressWindow(title='Batching import skincluster weights', progress=0, max=totalProgress, status='Importing skincluster weights for: ', isInterruptable=True) for shapeName in shapeNames: importSkinClusterWeights(fileResult[0], shapeName) cmds.progressWindow( edit=True, progress=curProgress, status=('Importing skincluster weights for: %s' % shapeName)) curProgress += 1 cmds.progressWindow(endProgress=True) print('Batching import skincluster weighhts finished for: ' + rigCharacterGroup) else: cmds.warning( 'Model group not found. Batching import skincluster weighhts failed for:' + rigCharacterGroup)
def Vertex_Inst(self): random.seed(1998) result = cmds.ls(orderedSelection=True) vertex_name = cmds.filterExpand(expand=True, selectionMask=25) inst_obj = result[0] instance_group_name = cmds.group(empty=True, name=inst_obj + '_instance_grp#') cmds.xform(instance_group_name, centerPivots=True) if cmds.objectType(inst_obj) == 'transform': for vertex in vertex_name: instance_result = cmds.instance(inst_obj, name=inst_obj + '_instance#') cmds.parent(instance_result, instance_group_name) self.rnd_rotation(instance_result) self.rnd_scaling(instance_result) x_ver, y_ver, z_ver = cmds.pointPosition(vertex) cmds.move(x_ver, y_ver, z_ver) else: print("Oops") cmds.hide(inst_obj)
def snap_to_vtx_avg(self, vtx_input=''): """ Snaps current locator to selected vertex list average position :param vtx_input: """ vtx_list = vtx_input if vtx_input else mc.filterExpand(mc.ls(sl=1), sm=31) axis_x = axis_y = axis_z = 0 for vtx in vtx_list: axis_x += mc.xform(vtx, q=1, t=1, ws=1)[0] axis_y += mc.xform(vtx, q=1, t=1, ws=1)[1] axis_z += mc.xform(vtx, q=1, t=1, ws=1)[2] x_avg = axis_x / len(vtx_list) y_avg = axis_y / len(vtx_list) z_avg = axis_z / len(vtx_list) mc.xform(self.loc, t=(x_avg, y_avg, z_avg), ws=1) self.loc_data['custom_sets']['vertex_avg'] = vtx_list self.commit_loc_data() self.update_template_data()
def batchExportSkinClusterWeights(): rigCharacterGroup = SEJointHelper.getSelectedRigCharacterGroup() if rigCharacterGroup == None: return fileResult = cmds.fileDialog2(fm=3) if fileResult != None: modelGroup = SERigObjectTypeHelper.getCharacterModelGroup( rigCharacterGroup) if modelGroup: cmds.select(modelGroup) shapeNames = cmds.filterExpand(sm=[12]) cmds.select(rigCharacterGroup) for shapeName in shapeNames: exportSkinClusterWeights(fileResult[0], shapeName) print('Batching export skincluster weighhts finished for: ' + rigCharacterGroup) else: cmds.warning( 'Model group not found. Batching export skincluster weighhts failed for:' + rigCharacterGroup)
def _make_primitive(self, primitive, divisions): selection = cmds.ls(selection=True, long=True) components = cmds.filterExpand(selection, sm=(31, 32, 34, 35), fullPath=True) component_objects = list( set(cmds.ls(components, objectsOnly=True, long=True))) # Only snap if the len of nodes is 1 and the selection is a component snap = len(component_objects) == 1 and components if snap: # Get the tool position before node creation since maya # selects new nodes tool_position = general.get_tool_pivot_position() if primitive == PRIMITIVE.SPHERE: node, _ = cmds.polySphere(subdivisionsAxis=divisions, subdivisionsHeight=divisions) elif primitive == PRIMITIVE.CUBE: node, _ = cmds.polyCube(subdivisionsWidth=divisions, subdivisionsHeight=divisions, subdivisionsDepth=divisions) elif primitive == PRIMITIVE.CYLINDER: node, _ = cmds.polyCylinder(subdivisionsAxis=divisions, subdivisionsHeight=1, subdivisionsCaps=1) elif primitive == PRIMITIVE.PLANE: node, _ = cmds.polyPlane(subdivisionsWidth=divisions, subdivisionsHeight=divisions) else: raise RuntimeError("Primative not supported") if snap: general.snap_to_mesh_face(component_objects[0], node, tool_position)
def getNormals(self): # Current vertexFace for this face vfs = cmds.polyListComponentConversion(self.name, ff=1, tvf=1) vfs = cmds.filterExpand(vfs, expand=True, sm=70) # normals = [] ''' for vf in vfs: for vert in self.vertex: vtxFaces, normals = Vertex.getFaceNormals(self.nodeName) ''' for vert in self.vertex: # vtxFaces, normals = Vertex.getFaceNormals(vert.) for curVfs in vfs: check = False if (vert.normals.has_key(curVfs)): self.normals.append(vert.normals[curVfs]) check = True # if( not check ): # self.normals.append([]) return vfs
def edgeLoopCurveFromUI(close=False): ''' Execute createAlongCurve() from UI ''' # Get mesh edge selection selection = mc.filterExpand(sm=32) if not selection: raise UserInputError('No current valid mesh edge selection!!') # Window window = 'edgeLoopCurveUI' if not mc.window(window, q=True, ex=1): raise UIError('EdgeLoopCurve UI does not exist!!') prefix = str(mc.textFieldGrp('edgeLoopCurvePrefixTFG', q=True, text=True)) rebuildCrv = mc.checkBoxGrp('edgeLoopCurveRebuildCBG', q=True, v1=True) spans = mc.intSliderGrp('edgeLoopCurveSpanISG', q=True, v=True) # Execute command glTools.utils.curve.edgeLoopCrv(selection, rebuild=rebuildCrv, rebuildSpans=spans, prefix=prefix) # Cleanup if close: mc.deleteUI(window)
def placeEyeCenter (self, *args): '''Place locator in the center of the eyeball. Called by 'UI' function. Call functions: None ''' selection = cmds.filterExpand (sm = 12) self.eyeName = cmds.textField (self.txtfEye, q = 1, tx = 1) if selection == None : self.eyeLoc = None self.eyeName = None cmds.error ("Please select the eyeball.\n") else : eyeball = selection [0] if not self.eyeName : self.eyeName = name = "DefaultEye" else : name = self.eyeName eyeTemp = cmds.duplicate (eyeball) [0] cmds.xform (eyeTemp, cp = 1) self.eyeLoc = cmds.spaceLocator (n = (name + "_eyeCenter_locator")) [0] cnstrTemp = cmds.pointConstraint (eyeTemp, self.eyeLoc) cmds.delete (cnstrTemp) cmds.delete (eyeTemp) # lock locator cmds.setAttr (self.eyeLoc + ".overrideEnabled", 1) cmds.setAttr (self.eyeLoc + ".overrideDisplayType", 2) cmds.select (cl = 1) # Update UI cmds.textField (self.txtfLoc, e = 1, tx = self.eyeLoc) cmds.button (self.btnPlaceCenter, e = 1, en = 0) cmds.button (self.btnUndoPlaceCenter, e = 1, en = 1)
def CleanUnusedInfluenses(skinCluster): cmds.select(clear=True) weightedInfls = cmds.skinCluster(skinCluster, q=True, wi=True) #print weightedInfls unusedList = [] for wi in weightedInfls: cmds.skinCluster(skinCluster, e=True, selectInfluenceVerts=wi) sel = cmds.ls(selection=True, flatten=True) onlyVertices = cmds.filterExpand(sel, sm=31) #print onlyVertices if not onlyVertices: #print wi + ' REMOVE' cmds.skinCluster(skinCluster, e=True, removeInfluence=wi) unusedList.append(wi) resultMessage = '' if len(unusedList) > 10: resultMessage = '{}... + {} joints'.format(unusedList[:10], len(unusedList) - 10) elif unusedList: resultMessage = unusedList print '\tFor {0} removed {1} joints {2}'.format(skinCluster, len(unusedList), resultMessage)
def checkTdStart(self): global td_control,offset_control,tsize_control; tsize=cmds.intField(tsize_control,q=True, v=True); td=cmds.floatField(td_control,q=True, v=True); offset=cmds.floatField(offset_control,q=True, v=True); cmds.ConvertSelectionToFaces(); cmds.ls(sl=True,long=True) or [] selected = cmds.filterExpand( sm=34 ); if selected is None or len(selected) <=0 : MessageBox("未选中对象!"); return; r=[]; texSize = tsize*tsize; for f in selected: fa = getFaceTexelDensity(f,texSize); if abs(fa-td)>offset: r.append(f); cmds.select(cl=True); cmds.select(r); MessageBox(" 选中 %d 个面" % len(r))
def setHigh(*args): print "Set high."; global high,high_uv global high_text; high=[]; selected = cmds.ls(sl=True,long=True) or [] count = len(selected) if count<=0: print "null select."; cmds.text(high_text,l="High not set",edit=True) return; elif count==1: print "Set high ",selected[0]; cmds.text(high_text,l=selected[0],edit=True) else: cmds.text(high_text,l=len+" selected.",edit=True) cmds.ConvertSelectionToVertices() for i in cmds.filterExpand( sm=31 ): high.append(cmds.xform(i,ws=True,q=True,t=True)) #get highuv high_uv = getUVs() return;
def getUV(*args): """takes a selection of one or two verts and returns one UV position. If just the surface is selected, it will return UV vals of (.5, .5)""" #get vertex sel = cmds.ls(sl=True) #------filter for vertices (or cvs?) vertices = cmds.filterExpand(sm=(31), fp=True, ex=True) print "verts = %s" % vertices try: if len(vertices) > 2: cmds.warning( "You've selected more than two verts. Two is the max number I can take" ) except: cmds.warning("Please select one or two vertices!") uvs = [] if vertices: #here deal with option to use one or average uv values of two selections (shouldn't be more than two)? for vert in vertices: #convert vertex to uvs thisUV = cmds.polyListComponentConversion(vert, fv=True, tuv=True)[0] uvs.append(thisUV) else: cmds.warning( "You haven't selected any verts! Select one or two to place a follicle" ) print "uvs = %s" % uvs #convert vertices to uvs and get their value if uvs: uvList = [] for uv in uvs: #grab first (cuz verts can be multiple uv's) thisUV = cmds.ls(uv)[0] #convert the uv index to u and v values uvVal = cmds.polyEditUV(uv, q=True) uvList.append(uvVal) U = [] V = [] sizeUV = len(uvList) #print uvList for uv in uvList: U.append(uv[0]) V.append(uv[1]) #print "U = %s"%U #print "V = %s"%V #DO THE AVERAGING HERE x = 0 y = 0 for a in U: x = x + a for b in V: y = y + b u = x / sizeUV v = y / sizeUV uvVal = [u, v] print uvVal cmds.select(vertices) print "THESE ARE THE OUTPUTS" print "vertex is: %s" % vertices[0] shapeName = vertices[0].rpartition(".vtx")[0] meshName = cmds.listRelatives(shapeName, p=True)[0] print meshName folName = cmds.textFieldGrp(widgets["nameTFG"], q=True, tx=True) print folName uValue = uvVal[0] print uValue vValue = uvVal[1] print vValue follicle(meshName, folName, uValue, vValue) else: pass
def findWindingOrder(face): # Converts faces into verts (the are return in the proper winding order vertex = cmds.polyListComponentConversion(face, tv=True) # if any of the verts of compressed into ranges the will be expanded. allVerts = cmds.filterExpand(vertex, sm=31, expand=True) return allVerts
def getNumOfVertex(face): vertex = cmds.polyListComponentConversion(face, tv=True) allVerts = cmds.filterExpand(vertex, sm=31, expand=True) return len(allVerts)
def _getVertex(self): verts = cmds.polyListComponentConversion(self.name, ff=1, tv=1) allVerts = cmds.filterExpand(verts, sm=31, expand=True) for vtx in allVerts: self.vertex.append(Vertex(vtx))
def getFaces(shape): faces = cmds.polyListComponentConversion(shape, tf=1) allFaces = cmds.filterExpand(faces, expand=True, sm=34) return allFaces
def getCurrentUVMaps(vertex): uv = cmds.polyListComponentConversion(vertex, fv=True, tuv=True) uvAll = cmds.filterExpand(uv, expand=True, sm=35) return uvAll
def group_selection(): #print '*-*-*-**-*-* run group_selection *-*-*-*-*-*-*-*' if cmds.selectMode(q=True, o=True): sel = cmds.ls(sl=True, l=True) all_sets = cmds.ls(type='objectSet') select_sets = [] select_members = [] #print 'all_set :', all_sets for node in all_sets: members = cmds.ls(cmds.sets(node, int=node), l=True) for s in sel: if s in members: select_sets.append(node) select_members += members #print 'get select set :', select_sets select_sets = list(set(select_sets)) select_members = list(set(select_members)) if select_sets: cmds.select(select_sets + select_members + sel, r=True, ne=True) if cmds.selectMode(q=True, co=True): sel_comp = cmds.ls(sl=True, type='float3') #print 'sel comp', sel_comp if not sel_comp: sel_comp = cmds.ls(sl=True, tr=True) #print 'sel comp', sel_comp if not sel_comp: return #現在のモードを取っておく if cmds.selectType(q=True, pv=True): sel_comp = cmds.polyListComponentConversion(sel_comp, tv=True) mode = 31 if cmds.selectType(q=True, pe=True): sel_comp = cmds.polyListComponentConversion(sel_comp, te=True) mode = 32 if cmds.selectType(q=True, pf=True): sel_comp = cmds.polyListComponentConversion(sel_comp, tf=True) mode = 34 if not sel_comp: return sel_comp = cmds.filterExpand(sel_comp, sm=mode) #cmds.selectMode(o=True) #object = cmds.ls(sl=True, l=True) #all_clusters = cmds.ls(type='clusterHandle') all_sets = cmds.ls(set=True) sel_sets = [] sel_members = [] sel_clusters = [] #セットの処理 for set_node in all_sets: if 'tweakSet' in set_node: continue if not cmds.nodeType(set_node) == 'objectSet': continue members = cmds.sets(set_node, int=set_node) members = cmds.filterExpand(members, sm=mode) if members is None: continue #print 'get members :', set_node, members for comp in sel_comp: if comp in members: #print 'get comp menber :', comp, set_node, members sel_sets.append(set_node) set_hists = cmds.listHistory(set_node) #print set_node, 'get set hist :', set_hists cls_nodes = cmds.ls(set_hists, type='cluster') #print 'get cls :', cls_nodes if cls_nodes: for cls in cls_nodes: cls_hist = cmds.listHistory(cls, lv=1) #print 'cls hist :', cls_hist cls_handle = cmds.ls(cls_hist, type='transform') cls_parent = cmds.listRelatives(cls_hist) #cls_handle = cmds.listRelatives(cls_hist, pa=True) #print 'history :', cls_handle #print 'parent :', cls_parent sel_clusters += cls_handle sel_members += members break #print 'all cls :', all_clusters #print 'all sets :', all_sets #cmds.selectMode(co=True) #print 'sel sets :',sel_sets #print 'sel comp :', sel_members cmds.select(cl=True) cmds.select(sel_sets, sel_members, sel_clusters, ne=True)
def set_reference(mode=''): c_ctx = cmds.currentCtx(q=True) #print c_ctx sel = cmds.ls(sl=True, l=True) #print 'set reference :', mode, sel current_ctx = cmds.currentCtx() if mode == 'object': #print 'set reference object mode :' cmds.selectMode(o=True) rot = cmds.xform(sel, q=True, ro=True, ws=True) pos = cmds.xform(sel, q=True, t=True, ws=True) rx = rot[0] / 180 * math.pi ry = rot[1] / 180 * math.pi rz = rot[2] / 180 * math.pi cmds.manipScaleContext('Scale', e=True, orientAxes=(rx, ry, rz)) cmds.manipRotateContext('Rotate', e=True, orientAxes=(rx, ry, rz)) cmds.manipMoveContext('Move', e=True, orientAxes=(rx, ry, rz)) cmds.setToolTo('scaleSuperContext') #マニプ表示がおかしくなるのでいったんコンテキスト設定してから戻す cmds.setToolTo('RotateSuperContext') cmds.setToolTo('moveSuperContext') cmds.setToolTo(current_ctx) else: if mode == 'vertex': manip_type = 'PointHandleTowards' comp = cmds.polyListComponentConversion(sel, tv=True) comp = cmds.filterExpand(comp, sm=31) sel_node = '" , "'.join(pre_sel) #print 'vertex ref :', sel_node, comp[0] if mode == 'edge': manip_type = 'AlignHandleWith' comp = cmds.polyListComponentConversion(sel, te=True) comp = cmds.filterExpand(comp, sm=32) sel_node = comp[0] if mode == 'face': manip_type = 'AlignHandleWith' comp = cmds.polyListComponentConversion(sel, tf=True) comp = cmds.filterExpand(comp, sm=34) sel_node = comp[0] if comp: mel.eval('manipScaleOrient 5;') mel.eval('{ string $Selection1[]; $Selection1[0] = "' + comp[0] + '"; manipScale' + manip_type + '($Selection1[0], {"' + sel_node + '"}, {}, "", 0);; };') mel.eval('manipRotateOrient 5;') mel.eval('{ string $Selection1[]; $Selection1[0] = "' + comp[0] + '"; manipRotate' + manip_type + '($Selection1[0], {"' + sel_node + '"}, {}, "", 0);; };') mel.eval('manipMoveOrient 5;') mel.eval('{ string $Selection1[]; $Selection1[0] = "' + comp[0] + '"; manipMove' + manip_type + '($Selection1[0], {"' + sel_node + '"}, {}, "", 0);; };') cmds.selectMode(co=True) if pre_ref_mode == 'vertex': cmds.selectType(pv=1, smu=0, smp=1, pf=0, pe=0, smf=0, sme=0, puv=0) if pre_ref_mode == 'edge': cmds.selectType(pv=0, smu=0, smp=0, pf=0, pe=1, smf=0, sme=1, puv=0) if pre_ref_mode == 'face': cmds.selectType(pv=0, smu=0, smp=0, pf=1, pe=0, smf=0, sme=1, puv=0) trans = cmds.xform(sel, q=True, t=True, ws=True) num = len(trans) / 3 x = y = z = 0 for i in range(0, len(trans), 3): x += trans[i] y += trans[i + 1] z += trans[i + 2] pos = [x / num, y / num, z / num] #sel_obj = [] #obj_list = list(set([vtx.split('.')[0] for vtx in pre_sel])) #if obj_list: #sel_obj = [cmds.listRelatives(s, p=True)[0] if cmds.nodeType(s)=='mesh' else s for s in obj_list] #print obj_list, pre_sel #cmds.hilite(obj_list, r=True) #cmds.hilite(pre_sel, r=True) #print 'set to pre mode :', pre_ref_mode #print 'set to mode pre :', pre_ref_mode if pre_ref_mode == 'object': cmds.selectMode(o=True) else: cmds.selectMode(co=True) if pre_obj_list: cmds.hilite(pre_obj_list, r=True) if pre_sel: cmds.select(pre_sel, r=True) else: cmds.select(cl=True) sb.after_pick_context(ctx=c_ctx) #移動マニプを選択の中心に移動する cmds.manipPivot(p=pos)