def f3DNoise( NObject, FMin, FMax ): # Set Local Variables NObjName = '%s' % NObject.name() min = FMin max = FMax # Select the Objects Vertices pm.selectMode( co=True ) pm.selectType( pv=True ) pm.polySelectConstraint( type=0x0001, mode=3 ) pm.select() # List the Objects Vertices ObjectVerts = pm.ls( selection=True, fl=True ) RandomVerts = list(ObjectVerts) random.shuffle(RandomVerts) pm.select( cl=True ) # For Every Vertex on the Object, Set its Vertex Color to a random value weighted by the sum of its location for v in range(len(ObjectVerts)): loc = pm.xform( RandomVerts[v], query=True, translation=True, worldSpace=True ) locValue = math.sqrt(abs(random.choice(loc))) RValue = random.uniform( min, max ) FValue = (locValue * RValue)/2 pm.polyColorPerVertex( ObjectVerts[v], colorRGB=( FValue, FValue, FValue ), alpha=1.0) # Release the Selection Constraints pm.polySelectConstraint( mode=0 ) pm.selectMode( o=True ) # Select the Object Again pm.select( NObjName )
def checkOverlappingVertices2(self): """ Find overlapping vertices.""" self.data['report']['check overlapping vertices'] = [] if len(self.data['geometries']): shapes = [eval('pm.' + s) for s in self.data['geometries'].keys()] with pm.uitypes.MainProgressBar(minValue=0, maxValue=len(shapes), interruptable=False) as bar: bar.setStatus('Check Overlapping Vertices.') for shape in shapes: bar.step(1) verts = set(shape.vtx) while verts: vert = verts.pop() position = vert.getPosition() pm.select(shape, r=True) pm.polySelectConstraint(disable=True, m=3, t=1, d=1, db=(0.0, 0.01), dp=position) _overlappingVerts = pm.ls(sl=True) verts.difference_update(set(_overlappingVerts)) _overlappingVerts = [ v.name() for v in _overlappingVerts ] pm.polySelectConstraint(disable=True) not len(_overlappingVerts) > 1 or self.data['report'][ 'check overlapping vertices'].append( _overlappingVerts)
def checkOverlappingVertices(*args, **kwargs): result = {} print kwargs progressDelegate = kwargs.setdefault('progress delegate', None) shapes = pm.ls(type='mesh') print progressDelegate progressDelegate is None or progressDelegate.setMaximum(len(shapes)) progress = 0 for shape in shapes: verts = set(shape.vtx) progress += 1 progressDelegate is None or progressDelegate.setProgress( progress, 'check overlapping vertices') while verts: vert = verts.pop() position = vert.getPosition() pm.select(shape, r=True) pm.polySelectConstraint(disable=True, m=3, t=1, d=1, db=(0.0, 0.01), dp=position) _overlappingVerts = pm.ls(sl=True) verts.difference_update(set(_overlappingVerts)) _overlappingVerts = [v.name() for v in _overlappingVerts] pm.polySelectConstraint(disable=True) not len(_overlappingVerts) > 1 or result.setdefault( shape.name(), []).append( reduce(lambda x, y: x + ', ' + y, _overlappingVerts)) return result
def PerlinNoiseFiller( NObject, FMin, FMax ): # Set Local Variables NObjName = '%s' % NObject.name() Divisions = 15 Vmin = FMin Vmax = FMax # Select the Objects Vertices pm.selectMode( co=True ) pm.selectType( pv=True ) pm.polySelectConstraint( type=0x0001, mode=3 ) pm.select() # List the Objects Vertices ObjectVerts = pm.ls( selection=True, fl=True ) pm.select( cl=True ) # For Every Vertex on the Object, Set its Vertex Color to a random value weighted by the sum of its location for v in range(len(ObjectVerts)): loc = pm.xform( ObjectVerts[v], query=True, translation=True, worldSpace=True ) RawValue = PerlinNoise((loc[0]*200),(loc[1]*300),(loc[2]*250), Divisions) ModValue = math.fabs(math.cos(RawValue/10.0)) FValue = max(min(ModValue, Vmax), Vmin) pm.polyColorPerVertex( ObjectVerts[v], colorRGB=( FValue, FValue, FValue ), alpha=1.0) # Release the Selection Constraints pm.polySelectConstraint( mode=0 ) pm.selectMode( o=True ) # Select the Object Again pm.select( NObjName )
def prepSelection(sel): verts = pm.filterExpand(sel, selectionMask=31) if verts: pm.polySelectConstraint(pp=3, type=0x0001) verts = pm.ls(sl=True, fl=True) return verts edge = pm.filterExpand(sel, selectionMask=32) if edge: verts = pm.polyListComponentConversion(edge, fromEdge=True, toVertex=True) return verts
def main(): lowAngle = 30 highAngle = 150 sels = pm.selected() for sel in sels: selEdge = pm.polyEvaluate(e=True) edge = selEdge - 1 pm.select(sel + '.e[0:' + str(edge) + ']', add=True) pm.polySelectConstraint(a=1, m=3, t=0x8000, ab=(lowAngle, highAngle)) pm.polySelectConstraint(m=0)
def selHardEdges(*args): meshList = pm.ls(type='surfaceShape') if not meshList: return [] # Find Triangles pm.select(meshList) pm.polySelectConstraint(mode=3, type=0x8000, sm=1) pm.polySelectConstraint(disable=True) hard = pm.filterExpand(ex=True, sm=32) or [] pm.select(hard) return 'select'
def noHoles(*args): meshList = pm.ls(type='surfaceShape') if not meshList: return [] # Find Triangles pm.select(meshList) pm.polySelectConstraint(mode=3, type=0x0008, h=1) pm.polySelectConstraint(disable=True) holes = pm.filterExpand(ex=True, sm=34) or [] pm.select(cl=True) if holes: return True
def checkLaminaFaces(*args, **kwargs): result = {} shapes = pm.ls(type='mesh') pm.select(shapes, r=True) pm.polySelectConstraint(disable=True, m=3, t=8, tp=2) laminas = pm.ls(sl=True) pm.polySelectConstraint(disable=True) pm.select(cl=True) for l in laminas: k = l.name().rpartition('.')[0] result.setdefault(k, []).append(l.name()) return result
def checkNGons(*args, **kwargs): result = {} shapes = pm.ls(type='mesh') pm.select(shapes, r=True) pm.polySelectConstraint(disable=True, m=3, t=8, sz=3) ngons = pm.ls(sl=True) pm.polySelectConstraint(disable=True) pm.select(cl=True) for n in ngons: k = n.name().rpartition('.')[0] result.setdefault(k, []).append(n.name()) return result
def vtxFromPnt(mesh, minDist = 0, maxDist = 1, pntCenter = [], selectVtx = False): ''' Returns the nearest verts from a pnt on the mesh. ''' pm.select( cl = True) pm.select(mesh) pm.polySelectConstraint(m = 3, t = 1, d = 1, db = [minDist, maxDist], dp = pntCenter) pm.polySelectConstraint(dis = True) vtx = pm.cmds.ls(sl = True, fl = True) if not selectVtx: pm.select( cl = True) return vtx
def bevelOnHardEdges(*args, **kwargs): duplications = [] resultPolyBevelNodes = [] meshTransformNodes = [i for i in pm.ls(sl=True) if isinstance(i, pm.nt.DagNode) and hasattr(i, 'getShape') and isinstance(i.getShape(), pm.nt.Mesh)] with utils.MayaUndoChuck('bevelOnHardEdges'): for meshTransform in meshTransformNodes: dup = pm.duplicate(meshTransform, st=True, rr=True)[0] duplications.append(dup) pm.move(25.0, 0.0, 0.0, dup, r=True) if pm.mel.eval('exists doMenuComponentSelection'): try: pm.mel.eval('doMenuComponentSelection("{0}", "edge")'.format(dup.name())) except pm.MelError: pass else: utils.switchSelectionModeToEdge(dup) pm.select(dup.e, r=True) pm.polySelectConstraint(disable=True, m=2, t=0x8000, sm=1) hardEdges = pm.ls(sl=True) not len(hardEdges) or resultPolyBevelNodes.append( pm.polyBevel3( hardEdges, fraction=kwargs['fraction'], offsetAsFraction=kwargs['offsetAsFraction'], autoFit=kwargs['autoFit'], depth=kwargs['depth'], mitering=kwargs['mitering'], miterAlong=kwargs['miterAlong'], chamfer=kwargs['chamfer'], segments=kwargs['segments'], worldSpace=kwargs['worldSpace'], smoothingAngle=kwargs['smoothingAngle'], subdivideNgons=kwargs['subdivideNgons'], mergeVertices=kwargs['mergeVertices'], mergeVertexTolerance=kwargs['mergeVertexTolerance'], miteringAngle=kwargs['miteringAngle'], angleTolerance=kwargs['angleTolerance'], forceParallel=kwargs['forceParallel'], ch=kwargs['ch'] ) ) pm.polySelectConstraint(disable=True) pm.select(duplications, r=True) return resultPolyBevelNodes
def SetMiddleGrey( NObject ): NObjName = '%s' % NObject.name() # Select the Objects Vertices pm.selectMode( co=True ) pm.selectType( pv=True ) pm.polySelectConstraint( type=0x0001, mode=3 ) pm.select() # List the Objects Vertices ObjectVerts = pm.ls( selection=True, fl=True ) pm.select( cl=True ) # For Every Vertex on the Object, Set its Vertex Color to 0.5 Grey for v in range(len(ObjectVerts)): pm.polyColorPerVertex( ObjectVerts[v], colorRGB=(0.5,0.5,0.5), alpha=1.0) # Release the Selection Constraints pm.polySelectConstraint( mode=0 ) pm.selectMode( o=True ) # Select the Object Again pm.select( NObjName )
def combineClean(instanceGroup, meshName, duplicateFaces=False): print("Combining mesh") mesh = pm.polyUnite(instanceGroup, name=meshName, constructionHistory=False) #print( "Merging %i" % len( mesh[ 0 ].vtx ) + " verticies" ) pm.polyMergeVertex(mesh[0].vtx, distance=0.1) #print( "Reduced to %i" % mesh[ 0 ].numVertices() + " verticies" ) if duplicateFaces: print("Cleaning up faces") pm.select(mesh[0]) pm.selectType(polymeshFace=True) pm.polySelectConstraint(mode=3, type=0x0008, topology=2) # Don't ask me how I did this mel.eval( 'polyCleanupArgList 3 { "0","2","0","0","0","0","0","0","0","1e-005","0","1e-005","1","0.3","0","-1","1" };' ) pm.delete() pm.polySelectConstraint(mode=0, topology=0) pm.selectType(polymeshFace=False) pm.selectMode(object=True) print("Faces reduced") if pm.PyNode(instanceGroup).exists(): pm.delete(instanceGroup) pm.delete(constructionHistory=True) pm.select(clear=True) print("Cleaning up complete") return mesh
def spawnEnemy( minSpawn, maxSpawn): colorRGBV = [1,1,0] rMax = maxSpawn rMin = minSpawn spawnMin = rMin + .01 spawnMax = rMax - .01 locX = random.uniform(spawnMin, spawnMax) locY = random.uniform(spawnMin, spawnMax) moveVectorX = random.uniform(-1.0,1.0) moveVectorY = random.uniform(-1.0,1.0) mayaObj = pm.polyCube( name="Enemy", w=1, h=1, d=1, cuv=0, ax=(0,1,0), sx=1, sy=1, sz=1 ) moveObj(mayaObj[0], locX, 0, locY) pm.selectType( pv=True ) pm.polySelectConstraint( type=0x0001, mode=3 ) pm.select() pVs = pm.ls( selection=True, fl=True ) pm.select( cl=True ) for v in range(len(pVs)): pm.polyColorPerVertex( pVs[v], colorRGB=colorRGBV, alpha=1.0, cdo=True, notUndoable=True ) return [mayaObj, moveVectorX, moveVectorY]
def combineClean( instanceGroup, meshName, duplicateFaces = False ): print( "Combining mesh" ) mesh = pm.polyUnite( instanceGroup, name = meshName, constructionHistory = False ) #print( "Merging %i" % len( mesh[ 0 ].vtx ) + " verticies" ) pm.polyMergeVertex( mesh[ 0 ].vtx, distance = 0.1 ) #print( "Reduced to %i" % mesh[ 0 ].numVertices() + " verticies" ) if duplicateFaces: print( "Cleaning up faces" ) pm.select( mesh[ 0 ] ) pm.selectType( polymeshFace = True ) pm.polySelectConstraint( mode = 3, type = 0x0008, topology = 2 ) # Don't ask me how I did this mel.eval('polyCleanupArgList 3 { "0","2","0","0","0","0","0","0","0","1e-005","0","1e-005","1","0.3","0","-1","1" };') pm.delete() pm.polySelectConstraint( mode = 0, topology = 0 ) pm.selectType( polymeshFace = False ) pm.selectMode( object = True ) print( "Faces reduced" ) if pm.PyNode( instanceGroup ).exists(): pm.delete( instanceGroup ) pm.delete( constructionHistory = True ) pm.select( clear = True ) print( "Cleaning up complete" ) return mesh
def checkNGons(self): """ Find n-gons(faces with more than 4 sides). This function refers to maya script, polyCleanupArgList.mel. """ self.data['report']['check n-gons'] = [] if len(self.data['geometries']): shapes = [eval('pm.' + s) for s in self.data['geometries'].keys()] with pm.uitypes.MainProgressBar(minValue=0, maxValue=2, interruptable=False) as bar: bar.setStatus('Check N-gons.') bar.step(1) pm.select(shapes, r=True) pm.polySelectConstraint(disable=True, m=3, t=8, sz=3) ngons = pm.ls(sl=True) pm.polySelectConstraint(disable=True) pm.select(cl=True) bar.step(1) self.data['report']['check n-gons'] = [n.name() for n in ngons ] if ngons else []
def SimpleNoise( NObject, FMin, FMax ): # Set Local Variables NObjName = '%s' % NObject.name() min = FMin max = FMax # Select the Objects Vertices pm.selectMode( co=True ) pm.selectType( pv=True ) pm.polySelectConstraint( type=0x0001, mode=3 ) pm.select() # List the Objects Vertices ObjectVerts = pm.ls( selection=True, fl=True ) pm.select( cl=True ) # For Every Vertex on the Object, Set its Vertex Color to 0.5 Grey for v in range(len(ObjectVerts)): FValue = random.uniform( min, max ) pm.polyColorPerVertex( ObjectVerts[v], colorRGB=( FValue, FValue, FValue ), alpha=1.0) # Release the Selection Constraints pm.polySelectConstraint( mode=0 ) pm.selectMode( o=True ) # Select the Object Again pm.select( NObjName )
def OpenEdge(*args): global selection global display5 global opedge NameList_Oe = [] cmds.select(selection) # 选择约束开放边 pm.polySelectConstraint(where=1, type=0x8000, mode=3) opedge = cmds.ls(sl=True) print opedge cmds.ConvertSelectionToShell() NameList = cmds.ls(sl=True) # 重置约束 cmd = r'resetPolySelectConstraint' result = mm.eval(cmd) cmds.select(clear=1) cmds.hilite(replace=True) for i in NameList: NameList_Oe.append(i.split('.')[0].encode('utf8')) if len(NameList_Oe) != 0: display5 = 1 return NameList_Oe
def checkLaminaFaces(self): """ Find Lamina faces(faces sharing all edges). This function refers to maya script, polyCleanupArgList.mel. """ self.data['report']['check lamina faces'] = [] if len(self.data['geometries']): shapes = [eval('pm.' + s) for s in self.data['geometries'].keys()] with pm.uitypes.MainProgressBar(minValue=0, maxValue=2, interruptable=False) as bar: bar.setStatus('Check Lamina Faces.') bar.step(1) pm.select(shapes, r=True) pm.polySelectConstraint(disable=True, m=3, t=8, tp=2) laminas = pm.ls(sl=True) pm.polySelectConstraint(disable=True) pm.select(cl=True) bar.step(1) self.data['report']['check lamina faces'] = [ l.name() for l in laminas ] if laminas else []
def uvmp_split_edges_at_UVs(*args, **kwargs): ''' automaticaly split edges wherever there is a uv border ''' sel = pm.ls(sl=True) if sel and pm.nodeType(sel[0]) == 'transform': polyObject = sel[0] pm.polyOptions(displayBorder=True, ao=True, sb=3) # get the open border uvs pm.select(polyObject.map, replace=True) pm.polySelectConstraint(t=0x0010, sh=0, bo=1, m=2) pm.polySelectConstraint(sh=0, bo=0, m=0) borderUVs = pm.ls(sl=True) borderEdges = pm.polyListComponentConversion(borderUVs, toEdge=True, internal=True) borderEdges = pm.filterExpand(borderEdges, sm=32, ex=True) for edge in borderEdges: if len(pm.PyNode(edge).connectedFaces()) < 2: print edge borderEdges.remove(edge) else: edgeUVs = pm.polyListComponentConversion(edge, toUV=True) edgeUVs = pm.filterExpand(edgeUVs, sm=35, ex=True) if not len(edgeUVs) > 2: borderEdges.remove(edge) print borderEdges pm.select(borderEdges, replace=True) pm.mel.eval('DetachEdgeComponent;') pm.delete(sel, constructionHistory=True) pm.select(sel, replace=True) else: lcUtility.Utility.lc_print('Please select an object', mode='warning')
def nonQuad(*args): meshList = pm.ls(type='surfaceShape') if not meshList: return [] # Find Triangles pm.select(meshList) pm.polySelectConstraint(mode=3, type=0x0008, size=1) pm.polySelectConstraint(disable=True) tris = pm.filterExpand(ex=True, sm=34) or [] # Find N-Gons pm.select(meshList) pm.polySelectConstraint(mode=3, type=0x0008, size=3) pm.polySelectConstraint(disable=True) ngon = pm.filterExpand(ex=True, sm=34) or [] pm.select(cl=True) if tris or ngon: return True
def unfold_by_uvs(sel=None): lssl = pm.ls(sel) if not lssl: lssl = [x for x in pm.selected() if x.getShape().type() == "mesh"] for sel in lssl: # split first uvs = sel.map pm.select(uvs) bord_uvs = pm.polySelectConstraint( t=0x0010, uv=0, bo=1, m=2, returnSelection=1) pm.polySplitVertex(bord_uvs, ch=0) # unfold in space for vtx in sel.vtx: uvbb = pm.polyEvaluate(vtx, bc2=1) pm.move(vtx, uv_to_ws(uvbb[0][0], uvbb[1][1], flat="z"))
def checkOverlappingVertices(self): """ Find overlapping vertices. Steps: 1. Find vertices on zero length edges(whose length is less than 0.01). 2. Find vertices on zero area faces(whose area is less than 0.01). """ self.data['report']['check overlapping vertices'] = [] if len(self.data['geometries']): overlappingVertices = set() shapes = [eval('pm.' + s) for s in self.data['geometries'].keys()] # Find vertices on zero length edges. pm.select(shapes, r=True) pm.polySelectConstraint(disable=True, m=3, t=0x8000, l=True, lb=(0.0, 0.01)) zeroEdges = pm.ls(sl=True) pm.polySelectConstraint(disable=True) pm.select(cl=True) overlappingVertices.update( set(pm.polyListComponentConversion(zeroEdges, toVertex=True))) # Find vertices on zero area faces. pm.select(shapes, r=True) pm.polySelectConstraint(disable=True, m=3, t=8, ga=True, gab=(0.0, 0.01)) zeroFaces = pm.ls(sl=True) pm.polySelectConstraint(disable=True) pm.select(cl=True) overlappingVertices.update( set(pm.polyListComponentConversion(zeroFaces, toVertex=True))) self.data['report']['check overlapping vertices'] = [ v.name() for v in overlappingVertices ]
def main(): sel_list = pm.ls(pm.pickWalk(d="down"), ni=1, type="mesh") if not sel_list: QtWidgets.QMessageBox.warning(None, u"警告", u"请选择一个模型") return sel = sel_list[0] # # NOTE(timmyliang) 获取法线贴图过滤出里外 # pm.mel.renderWindowRender("redoPreviousRender", "renderView") # texture_path = posixpath.join( # pm.workspace(q=1, rd=1), "turtle", "bakedTextures", "dilation.png" # ) # img = QtGui.QImage(texture_path) pm.undoInfo(ock=1) # TODO check overlap first num_list, total = sel.getUvShellsIds() shell_dict = {num: i for i, num in enumerate(num_list)} border_dict = defaultdict(dict) uv_dict = {} pm.progressWindow(title=u"获取 uv border", status=u"获取模型 uv border...", progress=0.0) for i, uv in shell_dict.items(): pm.progressWindow(e=1, progress=i / total * 100) # NOTES(timmyliang) 如果 uv 不在 0,1 象限则跳过 x,y = sel.getUV(uv) if not 0 < x < 1 or not 0 < y < 1: continue pm.select(sel.map[uv]) pm.polySelectConstraint(uv=1, bo=0, m=2) uv_list = pm.polySelectConstraint(t=0x0010, uv= 0, bo=1, m=2, rs=1) uv_list = [_uv.currentItemIndex() for _uv in pm.ls(uv_list, fl=1)] pos_list = {uv: sel.getUV(uv) for uv in uv_list} x = sum([pos[0] for pos in pos_list.values()]) / len(pos_list) y = sum([pos[1] for pos in pos_list.values()]) / len(pos_list) uv_dict.update(pos_list) borders = pm.polyListComponentConversion(fuv=1, te=1, bo=1) borders = pm.ls(borders, fl=1) for uv in uv_list: edges = pm.polyListComponentConversion(sel.map[uv], fuv=1, te=1) edges = [e for e in pm.ls(edges, fl=1) if e in borders] uvs = pm.polyListComponentConversion(edges, fe=1, tuv=1) uvs = [_uv.currentItemIndex() for _uv in pm.ls(uvs, fl=1)] uvs = [_uv for _uv in uvs if _uv != uv and _uv in uv_list] border_dict[uv] = {"uvs": uvs, "center": (x, y)} pm.progressWindow(ep=1) pm.polySelectConstraint(uv=0,bo=0, rs=1) distant = 0.01 for uv, data in border_dict.items(): uvs = data.get("uvs",[]) if len(uvs) <= 1: continue uv1, uv2 = uvs x, y = data.get("center") center = dt.Vector(x, y) pos = dt.Vector(*uv_dict[uv]) pos1 = dt.Vector(*uv_dict[uv1]) pos2 = dt.Vector(*uv_dict[uv2]) vec1 = pos - pos1 vec2 = pos2 - pos x,y = get_pt(pos,pos1,pos2,vec1,vec2,distant) pt = dt.Vector(x,y) vec = pos - pt line = pos - center # NOTE reverse if vec.dot(line) > 0: x,y = get_pt(pos,pos1,pos2,vec1,vec2,distant,True) sel.setUV(uv, x, y) face_list = pm.polyUVOverlap( sel.faces,oc=True ) pm.undoInfo(cck=1)
def main(): sel_list = pm.ls(pm.pickWalk(d="down"), ni=1, type="mesh") if not sel_list: QtWidgets.QMessageBox.warning(None, u"警告", u"请选择一个模型") return sel = sel_list[0] # pm.undoInfo(ock=1) num_list, total = sel.getUvShellsIds() shell_dict = {num: i for i, num in enumerate(num_list)} border_dict = defaultdict(dict) uv_dict = {} for i, uv in shell_dict.items(): pm.select(sel.map[uv]) pm.polySelectConstraint(uv=1, bo=0, m=2) uv_list = pm.ls(pm.polySelectConstraint(uv=0, rs=1), fl=1) face_list = pm.polyListComponentConversion(fuv=1, tf=1) border_list = pm.ls(pm.polyListComponentConversion(fuv=1, te=1, bo=1), fl=1) _border_list = [e.index() for e in border_list] edge_dict = { edge: { face.getUVIndex(j): face.getUV(j) for j in range(face.polygonVertexCount()) } for face in pm.ls(face_list, fl=1) for edge in face.getEdges() if edge in _border_list } border_dict = {} border_uvs = pm.polyListComponentConversion(border_list, fe=1, tuv=1) border_uvs = [uv for uv in pm.ls(border_uvs, fl=1) if uv in uv_list] for uv in border_uvs: edges = pm.polyListComponentConversion(uv, fuv=1, te=1) edges = [e for e in pm.ls(edges, fl=1) if e in border_list] uvs = pm.polyListComponentConversion(edges, fe=1, tuv=1) uvs = [ _uv for _uv in pm.ls(uvs, fl=1) if _uv != uv and _uv in border_uvs ] border_dict[uv] = uvs print(border_dict) break # print(json.dumps(edge_dict)) return # TODO 遍历 polygon 找 UV 对应关系 dag_path = sel.__apimdagpath__() itr = OpenMaya.MItMeshPolygon(dag_path) util = OpenMaya.MScriptUtil() edge_dict = defaultdict(list) while not itr.isDone(): face_idx = itr.index() uv = {} for i in range(itr.polygonVertexCount()): idx_ptr = util.asIntPtr() u_ptr = util.asFloatPtr() v_ptr = util.asFloatPtr() itr.getUVIndex(i, idx_ptr, u_ptr, v_ptr) idx = util.getInt(idx_ptr) u = util.getFloat(u_ptr) v = util.getFloat(v_ptr) uv[idx] = (u, v) edges = OpenMaya.MIntArray() itr.getEdges(edges) for i in range(edges.length()): edge = edges[i] edge_dict[edge].append({"uv": uv, "face_idx": face_idx}) itr.next() edge_list = [] for edge_idx, data in edge_dict.items(): print(len(data)) if len(data) == 1: edge_list.append(edge_idx) print(edge_list) # print(json.dumps(edge_dict)) return pm.progressWindow(title=u"获取 uv border", status=u"获取模型 uv border...", progress=0.0) for i, uv in shell_dict.items(): pm.progressWindow(e=1, progress=i / total * 100) # NOTES(timmyliang) 如果 uv 不在 0,1 象限则跳过 x, y = sel.getUV(uv) if not 0 < x < 1 or not 0 < y < 1: continue pm.select(sel.map[uv]) pm.polySelectConstraint(uv=1, bo=0, m=2) uv_list = pm.polySelectConstraint(t=0x0010, uv=0, bo=1, m=2, rs=1) uv_list = [_uv.currentItemIndex() for _uv in pm.ls(uv_list, fl=1)] pos_list = {uv: sel.getUV(uv) for uv in uv_list} x = sum([pos[0] for pos in pos_list.values()]) / len(pos_list) y = sum([pos[1] for pos in pos_list.values()]) / len(pos_list) uv_dict.update(pos_list) borders = pm.polyListComponentConversion(fuv=1, te=1, bo=1) borders = pm.ls(borders, fl=1) for uv in uv_list: edges = pm.polyListComponentConversion(sel.map[uv], fuv=1, te=1) edges = [e for e in pm.ls(edges, fl=1) if e in borders] uvs = pm.polyListComponentConversion(edges, fe=1, tuv=1) uvs = [_uv.currentItemIndex() for _uv in pm.ls(uvs, fl=1)] uvs = [_uv for _uv in uvs if _uv != uv and _uv in uv_list] border_dict[uv] = {"uvs": uvs, "center": (x, y)} pm.progressWindow(ep=1) pm.polySelectConstraint(uv=0, bo=0, rs=1) distant = 0.01 for uv, data in border_dict.items(): uvs = data.get("uvs", []) if len(uvs) <= 1: continue uv1, uv2 = uvs x, y = data.get("center") center = dt.Vector(x, y) pos = dt.Vector(*uv_dict[uv]) pos1 = dt.Vector(*uv_dict[uv1]) pos2 = dt.Vector(*uv_dict[uv2]) vec1 = pos - pos1 vec2 = pos2 - pos x, y = get_pt(pos, pos1, pos2, vec1, vec2, distant) pt = dt.Vector(x, y) vec = pos - pt line = pos - center # NOTE reverse if vec.dot(line) > 0: x, y = get_pt(pos, pos1, pos2, vec1, vec2, distant, True) sel.setUV(uv, x, y) face_list = pm.polyUVOverlap(sel.faces, oc=True) pm.undoInfo(cck=1)
def grabShell(cls, *args, **kwargs): ''' from a selection of UV's selects the shell ''' pm.polySelectConstraint(type=0x0010, shell=True, border=False, mode=2) #select the uv shell pm.polySelectConstraint(shell=False, border=False, mode=0) #reset the selection constraint
def CopySkinPolyToNurbs(source=None, dest=None, searchTolerance=0.005): if source == None or dest == None: source, dest = pm.ls(sl=True) # find shapes and skin nodes sourceShape = source.getShape() sourceSkin = FindDeformers(sourceShape, 'skinCluster') if not sourceSkin: pm.error("source object doesn't have a skin deformer") sourceSkin = sourceSkin[0] destShape = dest.getShape() destSkin = FindDeformers(destShape, 'skinCluster') if not destSkin: pm.error("target object doesn't have a skin deformer") destSkin = destSkin[0] # find joints affection the skin sourceJnts = pm.skinCluster(sourceSkin, q=True, influence=True) destJnts = pm.skinCluster(destSkin, q=True, influence=True) if sourceJnts != destJnts: pm.error("SkinClusters must have the same joint.") Us = destShape.numCVsInU() Vs = destShape.numCVsInV() numVtxs = pm.polyEvaluate(sourceShape, v=True) # unlock all joint for jnt in destJnts: jnt.liw.set(0) #=============================== pm.select(cl=True) for U in range(Us): for V in range(Vs): pm.select(destShape.cv[U][V], add=True) pos = destShape.getCV(U, V, space='world') # find vertex by position pm.select(source.vtx[0:numVtxs - 1]) pm.polySelectConstraint(mode=2, type=1, dist=1, distbound=(0, searchTolerance), distpoint=pos) vtx = pm.ls(sl=True)[0] pm.polySelectConstraint(dist=0) # find wieghts from found vertex wtList = [] rawWts = pm.skinPercent(sourceSkin, vtx, q=True, value=True) # find joints affection the vertex jntList = [] for i in range(len(rawWts)): if rawWts[i] > 0.0: jntList.append(sourceJnts[i]) wtList.append(rawWts[i]) # set weights to nurbs point opt = [] for j in range(len(jntList)): tmp = [] tmp.append(str(jntList[j])) tmp.append(wtList[j]) opt.append(tmp) pm.skinPercent(str(destSkin), destShape.cv[U][V], transformValue=(opt))
def CopySkinPolyToNurbs( source=None , dest=None, searchTolerance=0.005 ): if source==None or dest==None : source, dest = pm.ls(sl=True) # find shapes and skin nodes sourceShape = source.getShape() sourceSkin = FindDeformers( sourceShape , 'skinCluster' ) if not sourceSkin: pm.error("source object doesn't have a skin deformer") sourceSkin = sourceSkin[0] destShape = dest.getShape() destSkin = FindDeformers( destShape , 'skinCluster' ) if not destSkin: pm.error("target object doesn't have a skin deformer") destSkin = destSkin[0] # find joints affection the skin sourceJnts = pm.skinCluster(sourceSkin, q=True, influence=True) destJnts = pm.skinCluster(destSkin, q=True, influence=True) if sourceJnts != destJnts: pm.error("SkinClusters must have the same joint.") Us = destShape.numCVsInU() Vs = destShape.numCVsInV() numVtxs= pm.polyEvaluate( sourceShape, v=True ) # unlock all joint for jnt in destJnts: jnt.liw.set(0) #=============================== pm.select(cl=True) for U in range(Us): for V in range(Vs): pm.select( destShape.cv[U][V], add=True ) pos = destShape.getCV( U, V, space='world' ) # find vertex by position pm.select( source.vtx[0:numVtxs-1]) pm.polySelectConstraint( mode=2, type=1, dist=1, distbound=(0,searchTolerance), distpoint=pos ) vtx = pm.ls(sl=True)[0] pm.polySelectConstraint( dist=0 ) # find wieghts from found vertex wtList = [] rawWts = pm.skinPercent( sourceSkin, vtx, q=True, value=True ) # find joints affection the vertex jntList = [] for i in range(len(rawWts)): if rawWts[i] > 0.0: jntList.append(sourceJnts[i]) wtList.append(rawWts[i]) # set weights to nurbs point opt = [] for j in range(len(jntList)): tmp= [] tmp.append( str(jntList[j]) ) tmp.append( wtList[j] ) opt.append( tmp ) pm.skinPercent( str(destSkin), destShape.cv[U][V] , transformValue=( opt ) )
def bevelHardEdges(obj, offset = 0.5, segments = 1): if obj_is_poly(obj): pm.select(obj) pm.polySelectConstraint( m=3, t=0x8000, sm=1 ) # to get hard edges pm.polyBevel(offset = offset, segments = segments,autoFit = True, offsetAsFraction = True, fillNgons = True)
def run(): RawMovementVector = IntVector2( 0, 0 ) numEnemies = 15 playSpaceMinMaxX = 50 playSpaceMinMaxY = 50 enemyList = [] # Init SDL if sdl2.SDL_Init(sdl2.SDL_INIT_TIMER|sdl2.SDL_INIT_GAMECONTROLLER|sdl2.SDL_INIT_EVENTS) != 0: print(sdl2.SDL_GetError()) return -1 # Init Controller controller = sdl2.SDL_GameController() for i in range(sdl2.SDL_NumJoysticks()): if sdl2.SDL_IsGameController(i): controller = sdl2.SDL_GameControllerOpen(i) # Create SDL Window ctrlWindow = sdl2.SDL_CreateWindow( b"Control", sdl2.SDL_WINDOWPOS_UNDEFINED, sdl2.SDL_WINDOWPOS_UNDEFINED, 200, 150, sdl2.SDL_WINDOW_INPUT_FOCUS|sdl2.SDL_WINDOW_HIDDEN ) if not ctrlWindow: print(sdl2.GetError()) return -1 # Init Player player = pm.polyCube( name="Player", w=1, h=1, d=1, cuv=0, ax=(0,1,0), sx=1, sy=1, sz=1 ) if player is None: print "ERROR! Player not created!" return -1 else: pm.selectType( pv=True ) pm.polySelectConstraint( type=0x0001, mode=3 ) pm.select() pVs = pm.ls( selection=True, fl=True ) pm.select( cl=True ) for v in range(len(pVs)): pm.polyColorPerVertex( pVs[v], colorRGB=(1.0,0.0,0.0), alpha=1.0, cdo=True, notUndoable=True ) pSpeed = 40.0 for i in range(numEnemies): thisE = spawnEnemy(-(playSpaceMinMaxX), playSpaceMinMaxX) enemyList.append(thisE) print enemyList # Start Ticks lastTime = 0 cTime = sdl2.SDL_GetTicks() activeEnemies = numEnemies playerScale = 1.0 # Start Game Loop running = True while running: # See if Yout Won achieved #print activeEnemies if activeEnemies < 1: sdl2.SDL_DestroyWindow(ctrlWindow) sdl2.SDL_Quit() pm.select( all=True ) pm.delete() return "You Won!" #Calculate Delta Time lastTime = cTime cTime = sdl2.SDL_GetTicks() dTime = cTime - lastTime if dTime > 16: dTime = 16 deltaM = float(dTime)/float(1000) ButtonPressed = False # Process Input evnt = sdl2.SDL_Event() while sdl2.SDL_PollEvent(ctypes.byref(evnt)) != 0: if evnt.type == sdl2.SDL_QUIT: running = False break elif evnt.type == sdl2.SDL_CONTROLLERAXISMOTION: if evnt.caxis.axis == sdl2.SDL_CONTROLLER_AXIS_LEFTX: RawMovementVector.x = evnt.caxis.value break elif evnt.caxis.axis == sdl2.SDL_CONTROLLER_AXIS_LEFTY: RawMovementVector.y = evnt.caxis.value break elif evnt.type == sdl2.SDL_CONTROLLERBUTTONDOWN: if evnt.cbutton.button == sdl2.SDL_CONTROLLER_BUTTON_A: ButtonPressed = True break elif evnt.type == sdl2.SDL_CONTROLLERBUTTONUP: if evnt.cbutton.button == sdl2.SDL_CONTROLLER_BUTTON_A: ButtonPressed = False break elif evnt.type == sdl2.SDL_KEYDOWN: if evnt.key.keysym.sym == sdl2.SDLK_ESCAPE: sdl2.SDL_DestroyWindow(ctrlWindow) sdl2.SDL_Quit() break #print RawMovementVector.x, RawMovementVector.y, ButtonPressed # Remap Raw Movement to -1 to 1 in float Movement = RemapMovement( RawMovementVector.x, RawMovementVector.y ) #print Movement.x, Movement.y pMoveX = Movement.x * (deltaM*pSpeed) pMoveY = Movement.y * (deltaM*pSpeed) moveObj( player[0], pMoveX, 0.0, pMoveY) for i in range(len(enemyList)): testList = enemyList testList[i] = updateEnemy( testList[i], playSpaceMinMaxX, playSpaceMinMaxY, deltaM ) if detectCollision( player[0], testList[i][0][0] ) == True: vis = pm.getAttr( testList[i][0][0]+'.visibility' ) if vis == True: pm.hide( enemyList[i][0][0] ) activeEnemies = activeEnemies - 1 playerScale = playerScale + 0.5 pm.xform( player[0], scale=[playerScale, playerScale, playerScale] ) # redraw viewport pm.refresh( cv=True ) sdl2.SDL_DestroyWindow(ctrlWindow) sdl2.SDL_Quit() return 0
# Leif Peterson 2016 # # This code deletes random interior edges and cleans up winged vertices, while maintaing corners import pymel.core as pm import random # create a list of all selected objects SelectedObjects = pm.ls( selection=True, o=True ) # for each object delete its interior edges randomly for Object in range(len(SelectedObjects)): # select only border edges pm.selectType( pe=True ) pm.hilite( SelectedObjects[Object] ) pm.polySelectConstraint( mode=3, type=0x8000, where=1 ) pm.select() borderEdges = pm.ls( selection=True, fl=True ) # select all edges pm.polySelectConstraint( where=0 ) pm.select() allEdges = pm.ls( selection=True, fl=True ) # initilize the inside edges list insideEdges = [] # remove border edges for edge in range(len(borderEdges)): allEdges.remove( borderEdges[edge] )
def prepSel(self, sel): sel = pm.polyListComponentConversion(sel, tv=True) pm.select(sel) pm.polySelectConstraint(pp=3, type=0x0001) verts = pm.ls(sl=True, fl=True) return verts
def softMod_to_cluster(self): # sels = pm.ls(sl=1) # if sels: for sel in sels : l = pm.spaceLocator() pm.select(sel,tgl=1) pm.mel.eval('align -atl -x Mid -y Mid -z Mid') pm.select(l,r=1) pos_locator = pm.xform(q=1,ws=1,t=1) softMod_handle = sel.translate.connections(p=0,d=1)[0].constraintTranslateX.connections(p=0,d=1)[0] print softMod_handle # get handle shape softMod_handle_shape = pm.PyNode(softMod_handle).getShape() if softMod_handle_shape: print softMod_handle_shape softMod_handle = softMod_handle_shape.getParent() softMods = softMod_handle_shape.softModTransforms.connections(p=0,s=1) if softMods: softMod = softMods[0] if softMod : deform_sets = softMod.message.connections(p=0,s=1) #TODO radius*0.5 self.Radius = softMod.falloffRadius.get() #pvt = softMod.falloffCenter.get() print deform_sets if deform_sets: deform_set = deform_sets[0] geometrys = deform_set.memberWireframeColor.connections(p=0,s=1) print geometrys pm.select(geometrys[0],r=1) pm.polySelectConstraint(m=3,t=1,d=1,db=(0,self.Radius),dp=pos_locator) vtxs = pm.ls(sl=1,fl=1) pm.polySelectConstraint(m=0) # mags = [] pos_0_list = [] pos_1_list = [] pm.move(1,0,0,softMod_handle,r=1,ws=1) for vtx in vtxs: pos = pm.xform(vtx,q=1,ws=1,t=1) pos_0_list.append( pos ) pm.move(-1,0,0,softMod_handle,r=1,ws=1) for vtx in vtxs: pos = pm.xform(vtx,q=1,ws=1,t=1) pos_1_list.append( pos ) for (p0,p1) in zip(pos_0_list,pos_1_list): print 'p0:',p0 print 'p1:',p1 length = self.get_length(p0,p1) print 'length:',length mags.append(length) pm.mel.eval('newCluster \" -envelope 1\"') cluster_handle = pm.ls(sl=1)[0] cluster_shape = pm.ls(sl=1,dag=1,lf=1)[0] # Get cluster self.Cluster = cluster = cluster_shape.clusterTransforms.connections(p=0,d=1)[0] print 'cluster:',cluster cluster.relative.set(1) cluster_shape.originX.set(0) cluster_shape.originY.set(0) cluster_shape.originZ.set(0) pm.select(cluster_handle,r=1) pm.move(pos_locator,r=1) pm.move(cluster_handle.scalePivot,pos_locator) pm.move(cluster_handle.rotatePivot,pos_locator) cluster_handle.tx.set(0) cluster_handle.ty.set(0) cluster_handle.tz.set(0) cluster_shape.originX.set(pos_locator[0]) cluster_shape.originY.set(pos_locator[1]) cluster_shape.originZ.set(pos_locator[2]) pm.move(cluster_handle.scalePivot,pos_locator) pm.move(cluster_handle.rotatePivot,pos_locator) #select $vtxs; #sets -add $deformSet; pm.select(vtxs,r=1) pm.sets(deform_set,add=1) #$posSoftMod=`xform -q -ws -piv $softModHandle`; #move -r -ws 1 0 0 $softModHandle; print 'softMod_handle:',softMod_handle pos_softMod = pm.xform(softMod_handle,q=1,ws=1,piv=1) #pm.move(1,0,0,softMod_handle,r=1,ws=1) print '\na' min = pm.datatypes.min(mags) max = pm.datatypes.max(mags) print 'min:',min print 'max:',max for (vtx,m) in zip(vtxs,mags): try: mag = pm.datatypes.smoothstep(min,max,m) except: mag = 1 #print 'mags[i]:],',mags[i] #mag = 0.1 #print 'mag: ',mag pm.select(vtx,r=1) # set vtx weight pm.percent(cluster,v=mag) pm.select(sel,r=1) pm.select(cluster_handle,add=1) pm.parentConstraint(mo=1,weight=1) sel_parent = sel.getParent() print type(sel_parent) sel_parent = pm.PyNode( sel_parent ).getParent() sel_parent = pm.PyNode( sel_parent ).getParent() sel_parent = pm.PyNode( sel_parent ).getParent() sel_parent = pm.PyNode( sel_parent ).getParent() print 'sel_parent:',sel_parent pm.select(cluster_handle,r=1) pm.select( cluster_handle,sel_parent ) pm.parent() try: pm.delete(softMod_handle) except: pm.error('can not delete softMod handle') pm.delete(l)