def getOverlapUVFaces(meshName): """Return overlapping faces""" faces = [] # find polygon mesh node selList = om.MSelectionList() selList.add(meshName) mesh = selList.getDependNode(0) if mesh.apiType() == om.MFn.kTransform: dagPath = selList.getDagPath(0) dagFn = om.MFnDagNode(dagPath) child = dagFn.child(0) if child.apiType() != om.MFn.kMesh: raise Exception("Can't find polygon mesh") mesh = child meshfn = om.MFnMesh(mesh) center, radius = createBoundingCircle(meshfn) for i in xrange(meshfn.numPolygons): rayb1, face1Orig, face1Vec = createRayGivenFace(meshfn, i) if not rayb1: continue cui = center[2 * i] cvi = center[2 * i + 1] ri = radius[i] # Exclude the degenerate face # if(area(face1Orig) < 0.000001) continue; # Loop through face j where j != i for j in range(i + 1, meshfn.numPolygons): cuj = center[2 * j] cvj = center[2 * j + 1] rj = radius[j] du = cuj - cui dv = cvj - cvi dsqr = du * du + dv * dv # Quick rejection if bounding circles don't overlap if (dsqr >= (ri + rj) * (ri + rj)): continue rayb2, face2Orig, face2Vec = createRayGivenFace(meshfn, j) if not rayb2: continue # Exclude the degenerate face # if(area(face2Orig) < 0.000001): continue; if checkCrossingEdges(face1Orig, face1Vec, face2Orig, face2Vec): face1 = '%s.f[%d]' % (meshfn.name(), i) face2 = '%s.f[%d]' % (meshfn.name(), j) if face1 not in faces: faces.append(face1) if face2 not in faces: faces.append(face2) return faces
def checkPolyCount(self): """ Check the poly count(Verts, Edges, Faces, Tris, UVs). Note: The default option of 'heads up->poly count' is 'Smooth Mesh Preview'. So the counts aren't the actual numbers of polygons which you see in maya scene. Select the option 'Cage' to make 'heads up' display the actual counts. Reference: http://help.autodesk.com/view/MAYAUL/2017/CHS/?guid=__files_GUID_0B85C721_C3C6_47D7_9D85_4F27B787ABB6_htm """ Verts = Edges = Faces = Tris = UVs = 0 dagIterator = OpenMaya.MItDag(OpenMaya.MItDag.kDepthFirst, OpenMaya.MFn.kMesh) while (not dagIterator.isDone()): dagObject = dagIterator.currentItem() instances = dagIterator.getPath().instanceNumber() + 1 meshFn = OpenMaya.MFnMesh(dagObject) Verts += meshFn.numVertices * instances Edges += meshFn.numEdges * instances Faces += meshFn.numPolygons * instances UVs += meshFn.numUVs() * instances Tris += sum(meshFn.getTriangles()[0]) * instances dagIterator.next() expected = int(self.suite['details']['check poly count'][0]) if expected and Verts > expected: self.data['report']['check poly count'][0] = str(Verts) expected = int(self.suite['details']['check poly count'][1]) if expected and Edges > expected: self.data['report']['check poly count'][1] = str(Edges) expected = int(self.suite['details']['check poly count'][2]) if expected and Faces > expected: self.data['report']['check poly count'][2] = str(Faces) expected = int(self.suite['details']['check poly count'][3]) if expected and Tris > expected: self.data['report']['check poly count'][3] = str(Tris) expected = int(self.suite['details']['check poly count'][4]) if expected and UVs > expected: self.data['report']['check poly count'][4] = str(UVs)
def getSelectedVertexIDs(cls): '''If a face or edge, converts to a vertex.''' # TODO: support conversion to CVs sel = om.MGlobal.getActiveSelectionList() dag, selectedComponents = sel.getComponent(0) vertexConversion = set() if selectedComponents.apiType() == om.MFn.kMeshVertComponent: return dag, selectedComponents elif selectedComponents.apiType() == om.MFn.kMeshEdgeComponent: edgeIter = om.MItMeshEdge(dag, selectedComponents) while not edgeIter.isDone(): vert1 = edgeIter.vertexId(0) vert2 = edgeIter.vertexId(1) vertexConversion.add(vert1) vertexConversion.add(vert2) edgeIter.next() elif selectedComponents.apiType() == om.MFn.kMeshPolygonComponent: faceIter = om.MItMeshPolygon(dag, selectedComponents) while not faceIter.isDone(): connectedVertices = faceIter.getVertices() vertexConversion.update(connectedVertices) faceIter.next() elif selectedComponents.apiType() == om.MFn.kInvalid: # no selected components. A transform might only be selected _dag = om.MDagPath(dag) _dag.extendToShape(0) # check what the shape's type is _shapeMObj = _dag.node() if _shapeMObj.hasFn(om.MFn.kMesh): meshMFnDagNode = om.MFnDagNode(_shapeMObj) meshMFn = om.MFnMesh(_shapeMObj) if not meshMFnDagNode.isIntermediateObject: vertexConversion.update(xrange(meshMFn.numVertices)) else: return newSel = om.MSelectionList() for vertId in vertexConversion: newSel.add(dag.fullPathName() + '.vtx[{0}]'.format(vertId)) dag, selectedComponents = newSel.getComponent(0) return dag, selectedComponents
def getContainerStacksUsingMayaAPI(): def _getPolyCountInContainer(containerNodeFn): containerData = _createtContainerNode() meshNodeFn = om.MFnMesh() containerData['container'] = containerNodeFn.name() for _ in (node for node in containerNodeFn.getMembers() if node.hasFn(om.MFn.kMesh)): meshNodeFn.setObject(_) if not meshNodeFn.isIntermediateObject: containerData['Verts'] += meshNodeFn.numVertices containerData['Edges'] += meshNodeFn.numEdges containerData['Faces'] += meshNodeFn.numPolygons containerData['UVs'] += meshNodeFn.numUVs() containerData['Tris'] += sum(meshNodeFn.getTriangles()[0]) return containerData def _getDagContainers(containerNodeFn): dagNodeFn = om.MFnDagNode() dagContainers = deque() dagContainers.append(containerNodeFn.name()) for _ in (node for node in containerNodeFn.getMembers() if node.hasFn(om.MFn.kDagContainer)): dagNodeFn.setObject(_) dagContainers.append(dagNodeFn.name()) return dagContainers containerNodeIterator = om.MItDependencyNodes(om.MFn.kContainer) containerNodeFn = om.MFnContainerNode() meshNodeFn = om.MFnMesh() containerStacks = [] dagContainersInContainers = [] while not containerNodeIterator.isDone(): stack = deque() containerNodeFn.setObject(containerNodeIterator.thisNode()) dagContainersInContainers.append(_getDagContainers(containerNodeFn)) stack.append(_getPolyCountInContainer(containerNodeFn)) parent = containerNodeFn.getParentContainer() while not parent.isNull(): containerNodeFn.setObject(parent) stack.append(_getPolyCountInContainer(containerNodeFn)) parent = containerNodeFn.getParentContainer() containerStacks.append(stack) containerNodeIterator.next() return containerStacks, dagContainersInContainers
def createVoxelMesh(self, pVoxelPositions, pVoxelWidth, pOutMeshData): ''' Create a mesh containing one cubic polygon for each voxel in the pVoxelPositions list. ''' numVoxels = len(pVoxelPositions) numVerticesPerVoxel = 8 # a cube has eight vertices. numPolygonsPerVoxel = 6 # a cube has six faces. numVerticesPerPolygon = 4 # four vertices are required to define a face of a cube. numPolygonConnectsPerVoxel = numPolygonsPerVoxel * numVerticesPerPolygon # 24 # Initialize the required arrays used to create the mesh in MFnMesh.create() totalVertices = numVoxels * numVerticesPerVoxel vertexArray = OpenMaya.MFloatPointArray() vertexArray.setLength(totalVertices) vertexIndexOffset = 0 totalPolygons = numVoxels * numPolygonsPerVoxel polygonCounts = OpenMaya.MIntArray() polygonCounts.setLength(totalPolygons) polygonCountsIndexOffset = 0 totalPolygonConnects = numVoxels * numPolygonConnectsPerVoxel polygonConnects = OpenMaya.MIntArray() polygonConnects.setLength(totalPolygonConnects) polygonConnectsIndexOffset = 0 # Populate the required arrays used in MFnMesh.create() for i in range(0, numVoxels): voxelPosition = pVoxelPositions[i] # Add a new cube to the arrays. self.createCube(voxelPosition, pVoxelWidth, vertexArray, vertexIndexOffset, numVerticesPerVoxel, polygonCounts, polygonCountsIndexOffset, numPolygonsPerVoxel, numVerticesPerPolygon, polygonConnects, polygonConnectsIndexOffset) # Increment the respective index offsets. vertexIndexOffset += numVerticesPerVoxel polygonCountsIndexOffset += numPolygonsPerVoxel polygonConnectsIndexOffset += numPolygonConnectsPerVoxel # Create the mesh now that the arrays have been populated. The mesh is stored in pOutMeshData meshFn = OpenMaya.MFnMesh() meshFn.create(vertexArray, polygonCounts, polygonConnects, parent=pOutMeshData)
def get_mesh_md5(_mesh): _mesh_md5 = {} selectionList = om.MSelectionList() selectionList.add(_mesh) _node = selectionList.getDependNode(0) _fnMesh = om.MFnMesh(_node) _verticesNum = _fnMesh.numVertices _p = om.MPoint(0, 0, 0) for _v in xrange(_verticesNum): _p += _fnMesh.getPoint(_v) _position = [correct_float(_p.x), correct_float(_p.y), correct_float(_p.z)] _md5 = get_md5(_position) # _mesh_md5[_mesh] = _md5 return _md5
def getNormals(self, _terrain, _curvePoints): # Initialise the array normalVectors = om.MVectorArray() numPoints = len(_curvePoints) normalVectors.setLength(numPoints) # Create a function set for the terrain terrainFn = om.MFnMesh(_terrain) # Iterate through the points and find the closest normal for i in range(numPoints): normal = om.MVector( terrainFn.getClosestNormal(_curvePoints[i], om.MSpace.kWorld)[0]) if (normal.length() != 1.0): normal.normalize() normalVectors[i] = normal return normalVectors
def getColor(segmantList, poly): MPoly = om.MGlobal.getSelectionListByName(poly) polyPath = MPoly.getDagPath(0) mesh = om.MFnMesh(polyPath) shape = mesh.name() shadingGrps = cmds.listConnections(shape, type='shadingEngine') #Get Connected shader name as string shader = cmds.ls(cmds.listConnections(shadingGrps), materials=1)[0] length = len(segmantList) imgObj = om1.MObject() sel = om1.MSelectionList() om1.MGlobal.getSelectionListByName(shader, sel) sel.getDependNode(0, imgObj) fnThisNode = om1.MFnDependencyNode(imgObj) attr = fnThisNode.attribute("color") outColours = om1.MVectorArray() outAlphas = om1.MDoubleArray() uColArray = om1.MDoubleArray() vColArray = om1.MDoubleArray() uColArray.setLength(1) vColArray.setLength(1) for segmant in segmantList: location = segmant.location vector = om.MVector(location[0], location[1], location[2]) point = om.MPoint(vector) try: u, v, w = mesh.getUVAtPoint(point, 4) uColArray.set(u, 0) vColArray.set(v, 0) omfx.MDynamicsUtil.evalDynamics2dTexture(imgObj, attr, uColArray, vColArray, outColours, outAlphas) except: print "Unable to sample current Shading Node" return segmantList color = outColours[0] segmant.color = [color.x, color.y, color.z] return segmantList
def closestPoint(driverMesh, drivenMesh, minDeltaLength, vertexIds, vertexWeights, multiplier=None, space=om.MSpace.kObject, closestVertex=False): """ move the drivenMesh vertex to the closestPoint or closestVertex on the driverMesh :param driverMesh: 'driverMeshName' :param drivenMesh: 'drivenMeshName' :param minDeltaLength: float :param vertexIds: [0, 1, ...] :param vertexWeights: [1.0, 0.5, ...] :param multiplier: float or detect if None :param space: om.MSpace.k___ :param closestVertex: bool :return: """ multiplier = getEditBlendshapeMultiplier(drivenMesh, multiplier) drivenIter = getMItMeshVertex(drivenMesh) selection = om.MSelectionList() selection.add(driverMesh) meshFn = om.MFnMesh(selection.getDagPath(0)) deltas = [] for vertexId, vertexWeight in izip(vertexIds, vertexWeights): drivenIter.setIndex(vertexId) startPosition = drivenIter.position(space) targetPosition, polygonId = meshFn.getClosestPoint( startPosition, space) if closestVertex: shortestDistance = None for polyVtxId in meshFn.getPolygonVertices(polygonId): polyVtxPosition = meshFn.getPoint(polyVtxId, space) distance = (polyVtxPosition - startPosition).length() if shortestDistance is None or distance < shortestDistance: shortestDistance = distance targetPosition = polyVtxPosition deltas.append( (targetPosition - startPosition) * vertexWeight * multiplier) # do the deformation mc.prMovePointsCmd(drivenMesh, space, minDeltaLength, vertexIds, *deltas)
def revert_to_base(base_tbl, current_tbl, sel_vtcs_idcs, val, dag_path, space): """ Revert selected vertices on the target mesh to the base position. :param base_tbl: positions of the points of the base mesh :type base_tbl: MPointArray :param current_tbl: positions of the points of the current mesh :type current_tbl: MPointArray :param sel_vtcs_idcs: indices of the selected points on the target mesh :type sel_vtcs_idcs: MIntArray :param val: percentage used for the revert to base function :type val: int :param dag_path: MDagPathArray of targets :type dag_path: MDagPathArray :param space: space in which operate the deformation (object or world) :type space: constant :return: """ # Create new table for destination position destination_table = om2.MPointArray() # Init MFnMesh tgt_mesh = om2.MFnMesh(dag_path) # Loop in MPointArray for i in range(base_tbl.__len__()): # If the current point is also in selection if i in sel_vtcs_idcs or sel_vtcs_idcs.__len__() == 0: # Modify new position destination_table.append(base_tbl[i] + ((current_tbl[i] - base_tbl[i]) * (val / 100.00))) # If the current point is not selected else: # Do nothing destination_table.append(current_tbl[i]) # Modify points position using the new coordinates tgt_mesh.setPoints(destination_table, space)
def bake_difference(base_tbl, tgt_tbl, current_tbl, sel_vtcs_idcs, dag_path, space): """ Bake the difference between 2 mesh on a list of vertices on a selection of meshes. :param base_tbl: positions of the points of the base mesh :type base_tbl: MPointArray :param tgt_tbl: positions of the points of the target mesh :type tgt_tbl: MPointArray :param current_tbl: positions of the points of the current mesh :type current_tbl: MPointArray :param sel_vtcs_idcs: indices of the selected points on the target mesh :type sel_vtcs_idcs: MIntArray :param dag_path: MDagPathArray of targets :type dag_path: MDagPathArray :param space: space in which operate the deformation (object or world) :type space: constant :return: """ # Create new table for destination position destination_table = om2.MPointArray() # Init MFnMesh tgt_mesh = om2.MFnMesh(dag_path) # Loop in MPointArray for i in range(base_tbl.__len__()): # If the current point is also in selection if i in sel_vtcs_idcs or sel_vtcs_idcs.__len__() == 0: # Modify new position destination_table.append(current_tbl[i] + (tgt_tbl[i] - base_tbl[i])) # If the current point is not selected else: # Do nothing destination_table.append(current_tbl[i]) # Modify points position using the new coordinates tgt_mesh.setPoints(destination_table, space)
def verifyLayerState(self, layer): if layer == 'composite': return else: obj = sxglobals.settings.shapeArray[ len(sxglobals.settings.shapeArray) - 1] selectionList = OM.MSelectionList() selectionList.add(obj) nodeDagPath = OM.MDagPath() nodeDagPath = selectionList.getDagPath(0) MFnMesh = OM.MFnMesh(nodeDagPath) layerColors = OM.MColorArray() layerColors = MFnMesh.getFaceVertexColors(colorSet=layer) # States: visibility, mask, adjustment state = [False, False, False] state[0] = (bool( maya.cmds.getAttr(str(obj) + '.' + str(layer) + 'Visibility'))) for k in range(len(layerColors)): if ((layerColors[k].a > 0) and (layerColors[k].a < sxglobals.settings.project['AlphaTolerance'])): state[2] = True elif ((layerColors[k].a >= sxglobals.settings.project['AlphaTolerance']) and (layerColors[k].a <= 1)): state[1] = True if not state[0]: hidden = 'H' else: hidden = ' ' if state[1]: mask = 'M' else: mask = ' ' if state[2]: adj = 'A' else: adj = ' ' layerName = sxglobals.settings.project['LayerData'][layer][6] itemString = hidden + mask + adj + ' ' + layerName return itemString
def cloneMeshs(meshPaths): cloneMeshPaths = [] cloneGroup = cmds.group(empty=True, world=True, name='ssdsResult') cloneGroupSL = om.MGlobal.getSelectionListByName(cloneGroup) cloneGroupFn = om.MFnTransform(cloneGroupSL.getDagPath(0)) for path in meshPaths: mesh = om.MFnMesh(path) meshName = om.MFnDagNode(mesh.parent(0)).name() cloneMeshName = 'ssds_' + meshName cmds.duplicate(mesh.name(), returnRootsOnly=True, name=cloneMeshName) cmds.parent(cloneMeshName, cloneGroup) cmds.setAttr(cloneMeshName + '.inheritsTransform', False) cloneMeshSL = om.MGlobal.getSelectionListByName(cloneMeshName) cloneMeshPath = cloneMeshSL.getDagPath(0) cloneMeshPath.extendToShape() cloneMeshPaths.append(cloneMeshPath) return cloneMeshPaths, cloneGroup
def createVertexStream(self, object, vertexBuffer, targetIndexing, sharedIndexing, sourceStreams): # get the descriptor from the vertex buffer. # It describes the format and layout of the stream. descriptor = vertexBuffer.descriptor() # we are expecting a float stream. if descriptor.dataType != omr.MGeometry.kFloat: return # we are expecting a float2 if descriptor.dimension != 2: return # we are expecting a texture channel if descriptor.semantic != omr.MGeometry.kTexture: return # get the mesh from the current path # if it is not a mesh we do nothing. mesh = om.MFnMesh(object) indices = targetIndexing.indices() vertexCount = len(indices) if vertexCount <= 0: return # fill the data. buffer = vertexBuffer.acquire(vertexCount, True) # writeOnly = True - we don't need the current buffer values inc = sizeof(c_float) address = buffer for i in range(0, vertexCount): # Here we are embedding some custom data into the stream. # The included effects (vertexBufferGeneratorGL.cgfx and # vertexBufferGeneratorDX11.fx) will alternate # red, green, and blue vertex colored triangles based on this input. c_float.from_address(address).value = 1.0 address += inc c_float.from_address(address).value = indices[i] # color index address += inc # commit the buffer to signal completion. vertexBuffer.commit(buffer)
def DeformationTransfer(): meshPaths = getSelectMesh() src_ref_mesh_path = meshPaths[0] src_def_mesh_path = meshPaths[1] trg_ref_mesh_path = meshPaths[2] trg_def_mesh_path = meshPaths[3] # set target reference model print "analysis target reference model" MatA = computeMatrixA(trg_ref_mesh_path) print "MatA : ", MatA.shape MatAt = MatA.transpose() print "MatAt : ", MatAt.shape LU = linalg.lu_factor(np.dot(MatAt, MatA)) # LU decompose # transfer to target model print "analysis transfer of source ref and def" matF = computeMatrixF( src_ref_mesh_path, src_def_mesh_path) # deformation gradient for source model print "matF : ", matF.shape # solve deformation transfer UtS = np.dot(MatAt, matF) print "UtS : ", UtS.shape trg_def_x = linalg.lu_solve(LU, UtS) print "trg_def_x : ", trg_def_x.shape # set result to target def model trg_def_mesh = om.MFnMesh(trg_def_mesh_path) for i in xrange(trg_def_mesh.numVertices): pos = trg_def_mesh.getPoint(i) pos[0] = trg_def_x[i][0] pos[1] = trg_def_x[i][1] pos[2] = trg_def_x[i][2] trg_def_mesh.setPoint(i, pos) print "done"
def distToClosestPoint(mySphere, myLocator): obj, dag = dagObjFromName(mySphere) meshFn = om2.MFnMesh(dag) point = locatorToPoint(myLocator) locpos = cmds.xform(myLocator, q=1, rp=1, ws=1) resultPoint = meshFn.getClosestPoint(point, om2.MSpace.kWorld)[0] resultPos = [resultPoint[0], resultPoint[1], resultPoint[2]] space = cmds.distanceDimension(sp=locpos, ep=resultPos) dis = cmds.getAttr("distanceDimension1" + ".distance") cmds.delete("distanceDimension1") if cmds.objExists("locator1"): cmds.delete("locator1") return dis
def get_uv_at_point(point, geo): """ Returns UV value at point on geo surface Open Maya 2 function :return (U, V): """ m_point = om2.MPoint(point[0], point[1], point[2]) m_sel_list = om2.MSelectionList() m_sel_list.add(geo) md_path = m_sel_list.getDagPath(0) fn_mesh = om2.MFnMesh(md_path) uv_value = fn_mesh.getUVAtPoint(m_point, om2.MSpace.kObject) return [uv_value[0], uv_value[1]]
def undo_last_action(self): """ Undo the last move stored. :return: """ if len(self.undo) > 0: undo = self.undo.pop(-1) else: print 'No undo action to undo.' return dag_path = self.create_MDagPath(undo['obj_path']) tgt_mesh = om2.MFnMesh(dag_path) tgt_mesh.setPoints(undo['points_pos'], om2.MSpace.kObject)
def compute(self, plug, data): if plug == self.aOutShape: thisObj = self.thisMObject() origHandle = data.inputValue(self.aOrigShape) deformedHandle = data.inputValue(self.aDeformedShape) outHandle = data.outputValue(self.aOutShape) colorRamp = om2.MRampAttribute(thisObj, self.aColorRamp) if self.isOrigDirty: self.isOrigDirty = False self.origEdgeLenArray = self.getEdgeLen(origHandle) if self.isDeformedDirty: self.isDeformedDirty = False self.deformedEdgeLenArray = self.getEdgeLen(deformedHandle) origEdges = self.origEdgeLenArray defmEdges = self.deformedEdgeLenArray if len(origEdges) == len(defmEdges): outHandle.copy(deformedHandle) outHandle.setMObject(deformedHandle.asMesh()) outMesh = outHandle.asMesh() meshFn = om2.MFnMesh(outMesh) numVerts = meshFn.numVertices vertColors = om2.MColorArray() vertColors.setLength(numVerts) for i in xrange(numVerts): delta = 0.5 delta += ((origEdges[i] - defmEdges[i]) / origEdges[i]) vertColor = colorRamp.getValueAtPosition(delta) vertColors[i] = vertColor if not self.setAndAssignColors(meshFn, vertColors): self.setVertexColors(meshFn, vertColors) else: print("Edge count doesn't match.") data.setClean(plug)
def create_colour_set(mesh, name, colours): """ :param str mesh: :param str name: :param list colours: """ dag = api.conversion.get_dag(mesh) dag.extendToShape() mesh_fn = OpenMaya.MFnMesh(dag) vertices = range(mesh_fn.numVertices) cmds.polyColorSet(mesh, create=True, colorSet=name, clamped=True, representation="RGB") mesh_fn.setVertexColors(colours, vertices)
def getSourceIndexing(self, object, sourceIndexing): # get the mesh from the object mesh = om.MFnMesh(object) (vertexCount, vertexList) = mesh.getVertices() vertCount = len(vertexList) vertices = sourceIndexing.indices() vertices.setLength(vertCount) for i in range(0, vertCount): vertices[i] = vertexList[i] # assign the source indexing sourceIndexing.setComponentType(omr.MComponentDataIndexing.kFaceVertex) return True
def draw_eye_guide_mesh_plane(points, t): # type: (Tuple[float, float, float], datatypes.MMatrix) -> om.MFnMesh mesh = om.MFnMesh() points = [x - t.getTranslation(space="world") for x in points] # points = [x - t.getTranslation(space="world") for x in points] mean_x = sum(p[0] for p in points) / len(points) mean_y = sum(p[1] for p in points) / len(points) mean_z = sum(p[2] for p in points) / len(points) mean = (mean_x, mean_y, mean_z) # Simple unitCube coordinates vertices = [om.MPoint(mean), ] polygonCounts = [] polygonConnects = [] for i, p in enumerate(points): vertices.append(om.MPoint(p)) # 0 if 1 < i: polygonCounts.append(3) polygonConnects.append(i) polygonConnects.append(i - 1) polygonConnects.append(0) if len(points) == (i + 1): polygonCounts.append(3) polygonConnects.append(i + 1) polygonConnects.append(i) polygonConnects.append(0) polygonCounts.append(3) polygonConnects.append(1) polygonConnects.append(i + 1) polygonConnects.append(0) mesh_obj = mesh.create(vertices, polygonCounts, polygonConnects) return mesh mesh_trans = om.MFnTransform(mesh_obj) n = pm.PyNode(mesh_trans.name()) v = t.getTranslation(space="world") n.setTranslation(v, om.MSpace.kWorld) return mesh
def setAllVertexPositions(self, geoObj, positions=[], worldSpace=True): """ Set all vertex of a mesh from a list """ mPoint = om2.MPointArray(positions) mSpace = None if worldSpace == True: mSpace = om.MSpace.kWorld else: mSpace = om.MSpace.kObject mSL = om2.MSelectionList() mSL.add(geoObj) mFnSet = om2.MFnMesh(mSL.getDagPath(0)) mFnSet.setPoints(mPoint, mSpace)
def meshIntersect(edgeVertsCoord=None, mesh2Intersect=None): '''see if a given edge(2 verts) interesects with mesh2Intersect ''' # see if given mesh or edgeVertsCoord intersects with target mesh or not mSelList = om.MSelectionList() mDagPath = om.MDagPath() targetMesh = "%s" % mesh2Intersect mSelList.add(targetMesh) targetDagP = mSelList.getDagPath(0) targetMfnSet = om.MFnMesh(targetDagP) edgeCount = len(edgeVertsCoord) hitCount = 0 for coord in edgeVertsCoord: rayStartPos = om.MFloatPoint(coord[0]) rayEndPos = om.MFloatPoint(coord[1]) rayVec = om.MFloatVector(rayEndPos - rayStartPos) rayLen = rayVec.length() infoList = targetMfnSet.closestIntersection(rayStartPos, rayVec, om.MSpace.kWorld, 999, False) hitPos = infoList[0] hitParem = infoList[1] hitLen = om.MVector(hitPos - rayStartPos).length() if hitParem == 0: # not even hit at all continue elif hitParem != 0: if hitLen <= rayLen: #print True return True # once a function does return, it ends the function else: # hit point is further than the length of the edge, not intersecting hitCount += 1 if hitCount == edgeCount: #print hitCount,edgeCount #print "inside geo or target too small" return False #print hitCount,edgeCount #print False return False
def colorsPerVertex(self): ## Going to be displaying false coloring, ## so skip getting internal colors. if self.mNormalsPerVertex: return 0 numColors = 0 path = self.currentPath() if path.hasFn(om.MFn.kMesh): fnMesh = om.MFnMesh(path.node()) numColorSets = fnMesh.numColorSets if numColorSets < 2: numColors = numColorSets else: numColors = 2 return numColors
def get_uv_info(): all_meshes = [mesh.longName() for mesh in get_all_meshes.get_all_meshes()] uv_dict = dict() for mesh_name in all_meshes: mesh_node = name_to_node(mesh_name) mesh = om.MFnMesh(mesh_node) U_array, V_array = mesh.getUVs() uv_counts, uvIds = mesh.getAssignedUVs() json_data = { "U_array": list(U_array), "V_array": list(V_array), "uv_counts": list(uv_counts), "uvIds": list(uvIds) } uv_dict[mesh_name] = json_data return uv_dict
def UvCoordToWorld(U, V, pShape): mfnMesh = om.MFnMesh( om.MGlobal.getSelectionListByName(pShape).getDagPath(0)) WSpoint = om.MPoint(0.0, 0.0, 0.0) for i in range(mfnMesh.numPolygons): try: WSpoint = mfnMesh.getPointAtUV(i, U, V, space=om.MSpace.kWorld, tolerance=0.0) break #point is in poly except BaseException: continue #point not found! return list(WSpoint)[:3]
def saveVColor(slotName, dagName, rootDic): # mesh_MPointArray = OpenMaya.MPointArray() # selection = OpenMaya.MGlobal.getActiveSelectionList() # meshDagPath = selection.getDagPath(0) dagpath = mdagpath_from_name(dagName) meshFn = OpenMaya.MFnMesh(dagpath) colors = [] try: colors = meshFn.getVertexColors() except RuntimeError: defaultColor = OpenMaya.MColor() meshFn.setVertexColors([defaultColor] * meshFn.numVertices, range(meshFn.numVertices)) colors = meshFn.getVertexColors() # write colors into file with open(rootDic + '/data/vcol/{0}.vcol'.format(slotName), 'w') as outfile: json.dump(serializeColor(colors), outfile)
def getBoundingBox(self, pMeshObj): ''' Calculate a bounding box around the mesh vertices. ''' # Create the bounding box object we will populate with the points of the mesh. boundingBox = OpenMaya.MBoundingBox() meshFn = OpenMaya.MFnMesh(pMeshObj) pointArray = OpenMaya.MPointArray() # Get the points of the mesh in its local coordinate space. pointArray = meshFn.getPoints(OpenMaya.MSpace.kTransform) for i in range(0, len(pointArray)): point = pointArray[i] boundingBox.expand(point) return boundingBox
def query_vertex_positions(transform): """ Queries all vertex positions from a given transform Using Maya Python API 2.0 """ # Create a selectionList and add our transform to it sel_list = om2.MSelectionList() sel_list.add(transform.name()) # Get the dag path of the first item in the selection list sel_obj = sel_list.getDagPath(0) # create a Mesh functionset from our dag object mfn_object = om2.MFnMesh(sel_obj) return mfn_object.getPoints()