def NormaltoColor(VecOriginlist, vTarNorArray, Intensity): oMeshArray = VecOriginlist[0] iVertArray = VecOriginlist[1] iFaceArray = VecOriginlist[2] vOriNorArray = VecOriginlist[3] oMeshlist = VecOriginlist[5] for y in range(oMeshlist.length()): mMesh = om.MFnMesh(oMeshlist[y]) IntenVec = om.MVector(Intensity, Intensity, Intensity) cVtxColorArray = om.MColorArray() CiVertArray = om.MIntArray() CiFaceArray = om.MIntArray() samemeshposit = [ i for i in range(oMeshArray.length()) if oMeshArray[i] == oMeshlist[y] ] for x in range(len(samemeshposit)): posit = samemeshposit[x] CiFaceArray.append(iFaceArray[posit]) CiVertArray.append(iVertArray[posit]) OriNor = vOriNorArray[posit] TarNor = vTarNorArray[posit] ResultNor = lerpVector(OriNor, TarNor, IntenVec) cVtxColor = om.MColor((ResultNor.x + 1) / 2, (ResultNor.y + 1) / 2, (ResultNor.z + 1) / 2, 1.0) cVtxColorArray.append(cVtxColor) mMesh.setFaceVertexColors(cVtxColorArray, CiFaceArray, CiVertArray)
def _CopyColorSetToMeshAsDisplayColor(self, srcMesh, colorSetName, dstMesh): """ Copies a color set named colorSetName from the MFnMesh srcMesh to the MFnMesh dstMesh. All existing color sets on dstMesh will be removed. """ testUsdExportColorSets._ClearColorSets(dstMesh) colorSetData = OpenMaya.MColorArray() unsetColor = OpenMaya.MColor(-999, -999, -999, -999) srcMesh.getFaceVertexColors(colorSetData, colorSetName, unsetColor) colorRep = srcMesh.getColorRepresentation(colorSetName) colorRepString = 'RGBA' if colorRep == OpenMaya.MFnMesh.kAlpha: colorRepString = 'A' elif colorRep == OpenMaya.MFnMesh.kRGB: colorRepString = 'RGB' isClamped = srcMesh.isColorClamped(colorSetName) cmds.polyColorSet(dstMesh.name(), create=True, colorSet='displayColor', representation=colorRepString, clamped=isClamped) dstMesh.setCurrentColorSetName('displayColor') # XXX: The Maya setFaceVertexColor() API seems to somehow still author # faceVertex colors we don't want it to, so after setting the ones we # intend, we also remove the ones we don't. removeFaces = OpenMaya.MIntArray() removeVertices = OpenMaya.MIntArray() itMeshFV = OpenMaya.MItMeshFaceVertex(srcMesh.object()) itMeshFV.reset() while not itMeshFV.isDone(): faceId = itMeshFV.faceId() vertId = itMeshFV.vertId() faceVertId = itMeshFV.faceVertId() next(itMeshFV) colorIndexPtr = OpenMaya.intPtr() srcMesh.getFaceVertexColorIndex(faceId, faceVertId, colorIndexPtr, colorSetName) colorSetValue = colorSetData[colorIndexPtr.value()] if colorSetValue == unsetColor: removeFaces.append(faceId) removeVertices.append(vertId) continue dstMesh.setFaceVertexColor(colorSetValue, faceId, vertId, None, colorRep) if removeFaces.length() > 0 and removeVertices.length() > 0: dstMesh.removeFaceVertexColors(removeFaces, removeVertices)
def deform(self, dataBlock, geoIter, mtx, multiIndex): """This method performs the deformation algorithm. The geometry iterator passed to this method is in local space and not world space. To convert points to world space use the matrix that is suppied. * dataBlock [MDataBlock] is the node's datablock. * geoIter [MItGeometry] is an iterator for the current geometry being deformed. * mtx [MMatrix] is the geometry's world space transformation matrix. * multiIndex [int] is the index corresponding to the requested output geometry. """ # pylint: disable=unused-argument envelope = dataBlock.inputValue( ompx.cvar.MPxGeometryFilter_envelope).asFloat() amplitude = dataBlock.inputValue(TestDeformer.inAmplitude).asFloat() displace = dataBlock.inputValue(TestDeformer.inDisplace).asFloat() inputArrayHandle = dataBlock.outputArrayValue( ompx.cvar.MPxGeometryFilter_input) inputArrayHandle.jumpToElement(multiIndex) inputElement = inputArrayHandle.outputValue() inMesh = inputElement.child( ompx.cvar.MPxGeometryFilter_inputGeom).asMesh() outMeshArrayHandle = dataBlock.outputArrayValue( ompx.cvar.MPxGeometryFilter_outputGeom) outMesh = outMeshArrayHandle.inputValue().asMesh() mMatrix = dataBlock.inputValue(TestDeformer.inMatrix).asMatrix() vTrans = om1.MVector(mMatrix(3, 0), mMatrix(3, 1), mMatrix(3, 2)) meshFn = om1.MFnMesh(inMesh) normalsArray = om1.MFloatVectorArray() meshFn.getVertexNormals(False, normalsArray, om1.MSpace.kObject) posArray = om1.MPointArray() colorsArray = om1.MColorArray() vertexArray = om1.MIntArray() while not geoIter.isDone(): index = geoIter.index() vertexArray.append(index) pntPos = geoIter.position() weight = self.weightValue(dataBlock, multiIndex, index) colorsArray.append(om1.MColor(1, 0, 0, 1)) if weight != 0: pntPos.x = pntPos.x + math.sin( index + displace - vTrans[0] ) * amplitude * normalsArray[index].x * weight * envelope pntPos.y = pntPos.y + math.sin( index + displace - vTrans[0] ) * amplitude * normalsArray[index].y * weight * envelope pntPos.z = pntPos.z + math.sin( index + displace - vTrans[0] ) * amplitude * normalsArray[index].z * weight * envelope posArray.append(pntPos) geoIter.next() meshFn.setObject(outMesh) meshFn.setVertexColors(colorsArray, vertexArray) geoIter.setAllPositions(posArray)
def main(): mesh_list = pm.ls(pm.pickWalk(d="down"), ni=1, type="mesh") if not mesh_list: return csv_path = r"C:\Users\timmyliang\Desktop\file_test\2020-12-1\head.csv" pm.progressWindow(title=u"设置顶点色", status=u"设置顶点色...", progress=0.0) with open(csv_path, "r") as f: reader = csv.DictReader(f) data_list = { int(row[" IDX"]): ( float(row[" COLOR.x"]), float(row[" COLOR.y"]), float(row[" COLOR.z"]), float(row[" COLOR.w"]), ) for row in reader } mesh = mesh_list[0] mfn = mesh.__apimfn__() itr = OpenMaya.MItMeshFaceVertex(mesh.__apimobject__()) face_list = OpenMaya.MIntArray() vertex_list = OpenMaya.MIntArray() colors = OpenMaya.MColorArray() index = -1 total = len(mesh.vtxFace) pm.progressWindow(title=u"设置顶点色", status=u"设置顶点色...", progress=0.0) while not itr.isDone(): index += 1 pm.progressWindow(e=1, progress=index / total * 100) vert_id = itr.vertId() face_id = itr.faceId() vertex_list.append(vert_id) face_list.append(face_id) color = data_list.get(vert_id) if not color: colors.append(OpenMaya.MColor(0, 0, 0)) itr.next() continue r, g, b,a = color colors.append(OpenMaya.MColor(r, g, b)) itr.next() mfn.setFaceVertexColors(colors, face_list, vertex_list) pm.progressWindow(ep=1)
def deform(self, data, geoIter, matrix, multiIndex): inMesh = data.inputValue(DeformerNode.inMesh).asMesh() meshFn = om.MFnMesh(inMesh) colors = om.MColorArray() colorSet = 'polyColorPerVertex1' meshFn.getColors(colors) envelope = ompx.cvar.MPxGeometryFilter_envelope envelopeHandle = data.inputValue(envelope) envelopeValue = envelopeHandle.asFloat() matrixData = data.inputValue(DeformerNode.deformSpace) matrixVal = matrixData.asMatrix() invMatrixVal = matrixVal.inverse() amplitudeData = data.inputValue(DeformerNode.amplitude) amplitudeValue = amplitudeData.asFloat() frequencyData = data.inputValue(DeformerNode.frequency) frequencyValue = frequencyData.asFloat() while not geoIter.isDone(): if envelopeValue > 0: i = geoIter.index() color = colors[i] point = geoIter.position() point *= invMatrixVal length = math.sqrt((point.x * point.x) + (point.z * point.z)) sinVal = math.sin(length) point.y = sinVal / length point.y *= envelopeValue point *= matrixVal #=============================================================== # point.x = color.r + pos.x # point.y = color.g + pos.y # point.z = color.b + pos.z #=============================================================== geoIter.setPosition(point) geoIter.next()
def RGB_identity_cube(name, density=20): """ Creates an RGB identity cube with given name and geometric density. Parameters ---------- name : unicode Cube name. density : int, optional Cube divisions count. Returns ------- unicode Cube. """ cube = cmds.polyCube(w=1, h=1, d=1, sx=density, sy=density, sz=density, ch=False)[0] set_attributes({ '{0}.translateX'.format(cube): .5, '{0}.translateY'.format(cube): .5, '{0}.translateZ'.format(cube): .5 }) cmds.setAttr('{0}.displayColors'.format(cube), True) vertex_colour_array = OpenMaya.MColorArray() vertex_index_array = OpenMaya.MIntArray() point_array = OpenMaya.MPointArray() fn_mesh = OpenMaya.MFnMesh(dag_path(shapes(cube)[0])) fn_mesh.getPoints(point_array, OpenMaya.MSpace.kWorld) for i in range(point_array.length()): vertex_colour_array.append(point_array[i][0], point_array[i][1], point_array[i][2]) vertex_index_array.append(i) fn_mesh.setVertexColors(vertex_colour_array, vertex_index_array, None) cmds.makeIdentity(cube, apply=True, t=True, r=True, s=True) cmds.xform(cube, a=True, rotatePivot=(0, 0, 0), scalePivot=(0, 0, 0)) return cmds.rename(cube, name)
def EmptyColor(VecOriginlist): oMeshArray = VecOriginlist[0] iVertArray = VecOriginlist[1] iFaceArray = VecOriginlist[2] oMeshlist = VecOriginlist[5] for y in range(oMeshlist.length()): mMesh = om.MFnMesh(oMeshlist[y]) cVtxColorArray = om.MColorArray() CiVertArray = om.MIntArray() CiFaceArray = om.MIntArray() samemeshposit = [ i for i in range(oMeshArray.length()) if oMeshArray[i] == oMeshlist[y] ] for x in range(len(samemeshposit)): posit = samemeshposit[x] CiFaceArray.append(iFaceArray[posit]) CiVertArray.append(iVertArray[posit]) mMesh.removeFaceVertexColors(CiFaceArray, CiVertArray)
def tagMesh(meshDagPath): """Tag the points on the supplied mesh with vertex colors to store Maya's point order""" # clear any extant vertex colors try: cmds.polyColorSet(meshDagPath.partialPathName(), e=True, delete=True, acs=True) except: pass # encode each point index in the red and green channels of each point's color value meshFn = om.MFnMesh(meshDagPath) vertexCount = om.MIntArray() vertexList = om.MIntArray() meshFn.getVertices(vertexCount, vertexList) vertexColors = om.MColorArray(meshFn.numVertices(), om.MColor(0.0,0.0,1.0,1.0)) for i in xrange(meshFn.numVertices()): col = om.MColor(tagIndexToColor(i)) vertexColors[i].r = col.r vertexColors[i].g = col.g meshFn.createColorSetWithName('blendShapeIndexMap') meshFn.setColors(vertexColors, 'blendShapeIndexMap') meshFn.assignColors(vertexList)
def apply_vert_colors(obj, colors, vert_indexes): """ Sets vert colors on the supplied mesh. Args: obj(string): Object to edit vert colors. colors(float[]): A list of rgb values. vert_indexes(int[]): A list of vertex indexes. This should match the length of colors. """ obj_shapes = cmds.listRelatives(obj, f=True, shapes=True) or [] old_pcolor = set( cmds.ls(cmds.listHistory(obj_shapes), type="polyColorPerVertex")) color_array = OpenMaya.MColorArray() int_array = OpenMaya.MIntArray() for rgb, vert_index in zip(colors, vert_indexes): color_array.append(OpenMaya.MColor(rgb[0], rgb[1], rgb[2])) int_array.append(vert_index) selection_list = OpenMaya.MSelectionList() dag_path = OpenMaya.MDagPath() selection_list.add(obj) selection_list.getDagPath(0, dag_path) mfn_mesh = OpenMaya.MFnMesh(dag_path) mfn_mesh.setVertexColors(color_array, int_array) # This creates polyColorPerVertex new_pcolor = set( cmds.ls(cmds.listHistory(obj_shapes), type="polyColorPerVertex")) dif_pcolor = list(new_pcolor.difference(old_pcolor)) if dif_pcolor: cmds.addAttr(dif_pcolor[0], ln=constants.POLY_COLOR_PER_VERT, dt="string") cmds.rename(dif_pcolor[0], constants.POLY_COLOR_PER_VERT)
def BuildVecOrigin(): dagPathMeshArray, oCompsArray, oMeshList = _getSelectedComponents() if not oCompsArray[0].isNull(): oMeshArray = om.MObjectArray() iVertArray = om.MIntArray() iFaceArray = om.MIntArray() vPosArray = om.MVectorArray() vNormalArray = om.MVectorArray() cVtxColorArray = om.MColorArray() for x in range(dagPathMeshArray.length()): dagPathMesh = dagPathMeshArray[x] oMesh = dagPathMesh.node() oComps = oCompsArray[x] itComponent = om.MItMeshFaceVertex( dagPathMesh, oComps) # iterate only on selected components while not itComponent.isDone(): iVertArray.append(itComponent.vertId()) iFaceArray.append(itComponent.faceId()) oMeshArray.append(oMesh) cVtxColor = om.MColor() itComponent.getColor(cVtxColor, om.MSpace.kObject) cVtxColorArray.append(cVtxColor) #get normals in each vertex pPos = itComponent.position(om.MSpace.kWorld) vPosArray.append(om.MVector(pPos.x, pPos.y, pPos.z)) oNormal = om.MVector() itComponent.getNormal(oNormal, om.MSpace.kObject) vNormalArray.append(oNormal) itComponent.next() return [ oMeshArray, iVertArray, iFaceArray, vNormalArray, vPosArray, oMeshList, cVtxColorArray ] else: print "nothing test" return [0, 0, 0, 0, 0]
def createVoxelMesh(self, voxelCenterPosition, uvArray, texNodeName, cubeWidth, voxelWeights, voxelBlendWeights): numVoxels = len(voxelCenterPosition) numVertices = 8 #number of vertices numPolygons = 6 #number of polygons numVerticesPerPolygon = 4 #number of vertices per polygon numNormalsPerVoxel = numVerticesPerPolygon * numPolygons #24 number of vertex normals numPolygonConnectsPerVoxel = numPolygons * numVerticesPerPolygon #24 number of polygon connects cubeHalfWidth = cubeWidth / 2.0 #initialize all the params in the MFnMesh.create() #vertexArray: point array, This should include all the vertices in the mesh and no eatras totalVertices = numVertices * numVoxels vertexArray = OpenMaya.MFloatPointArray() #polygonCounts array of vertex counts for each polygon #for the cube would have 6 faces, each of which had 4 verts, so the polygonCounts would be [4,4,4,4,4,4] totalPolygons = numPolygons * numVoxels polygonCounts = OpenMaya.MIntArray() #polygonConnects #array of vertex connections for each polygon polygonConnects = OpenMaya.MIntArray() #set shared Normals for these vertices vertexNormals = OpenMaya.MVectorArray() #vertexColorArray vertexColorArray = OpenMaya.MColorArray() #vertexColorIndexArray vertexIndexArray = OpenMaya.MIntArray() #PolygonIDArray faceList = OpenMaya.MIntArray() #vertexWeightArray vertexWeightArray = OpenMaya.MDoubleArray() #vertexBlendWeightArray vertexBlendWeightArray = OpenMaya.MDoubleArray() for i in range(numVoxels): pVoxelCenterPosition = voxelCenterPosition[i] #Update VertexArray for VoxelMesh vertexList = [ OpenMaya.MFloatPoint(pVoxelCenterPosition.x - cubeHalfWidth, pVoxelCenterPosition.y - cubeHalfWidth, pVoxelCenterPosition.z - cubeHalfWidth), #vertex 0 OpenMaya.MFloatPoint(pVoxelCenterPosition.x - cubeHalfWidth, pVoxelCenterPosition.y - cubeHalfWidth, pVoxelCenterPosition.z + cubeHalfWidth), #vertex 1 OpenMaya.MFloatPoint(pVoxelCenterPosition.x - cubeHalfWidth, pVoxelCenterPosition.y + cubeHalfWidth, pVoxelCenterPosition.z - cubeHalfWidth), #vertex 2 OpenMaya.MFloatPoint(pVoxelCenterPosition.x - cubeHalfWidth, pVoxelCenterPosition.y + cubeHalfWidth, pVoxelCenterPosition.z + cubeHalfWidth), #vertex 3 OpenMaya.MFloatPoint(pVoxelCenterPosition.x + cubeHalfWidth, pVoxelCenterPosition.y - cubeHalfWidth, pVoxelCenterPosition.z - cubeHalfWidth), #vertex 4 OpenMaya.MFloatPoint(pVoxelCenterPosition.x + cubeHalfWidth, pVoxelCenterPosition.y - cubeHalfWidth, pVoxelCenterPosition.z + cubeHalfWidth), #vertex 5 OpenMaya.MFloatPoint(pVoxelCenterPosition.x + cubeHalfWidth, pVoxelCenterPosition.y + cubeHalfWidth, pVoxelCenterPosition.z - cubeHalfWidth), #vertex 6 OpenMaya.MFloatPoint(pVoxelCenterPosition.x + cubeHalfWidth, pVoxelCenterPosition.y + cubeHalfWidth, pVoxelCenterPosition.z + cubeHalfWidth), #vertex 7 ] for j in range(numVertices): vertexArray.append(vertexList[j]) #here need to assign vertexWeight if self.skinCluster: for item in voxelWeights[i]: vertexWeightArray.append(item) vertexBlendWeightArray.append(voxelBlendWeights[i]) #print [item for sublist in voxelWeights[i] for item in sublist] #here need to assign vertex color if texNodeName: vertexColor = cmds.colorAtPoint(texNodeName, o='RGB', u=uvArray[i][0], v=uvArray[i][1]) mColor = OpenMaya.MColor(vertexColor[0], vertexColor[1], vertexColor[2]) vertexColorArray.append(mColor) vertexIndexArray.append(i * numVertices + j) #print vertexColor #Update polygonCounts for VoxelMesh for j in range(numPolygons): polygonCounts.append(numVerticesPerPolygon) faceList.append(i * numPolygons + j) #Update polygonConnects for VoxelMesh #Update vertexNormals for VoxelMesh polygonConnectsList = [ 0, 1, 3, 2, 1, 5, 7, 3, 4, 6, 7, 5, 2, 6, 4, 0, 0, 4, 5, 1, 2, 3, 7, 6 ] vertexNormalsList = [ OpenMaya.MVector(-1.0, 0.0, 0.0), #vertex normal on face (0,1,3,2) #0 OpenMaya.MVector(-1.0, 0.0, 0.0), #vertex normal on face (0,1,3,2) #1 OpenMaya.MVector(-1.0, 0.0, 0.0), #vertex normal on face (0,1,3,2) #7 OpenMaya.MVector(-1.0, 0.0, 0.0), #vertex normal on face (0,1,3,2) #3 OpenMaya.MVector(0.0, 0.0, 1.0), #vertex normal on face (1,5,7,3) #1 OpenMaya.MVector(0.0, 0.0, 1.0), #vertex normal on face (1,5,7,3) #5 OpenMaya.MVector(0.0, 0.0, 1.0), #vertex normal on face (1,5,7,3) #7 OpenMaya.MVector(0.0, 0.0, 1.0), #vertex normal on face (1,5,7,3) #3 OpenMaya.MVector(1.0, 0.0, 0.0), #vertex normal on face (4,6,7,5) #4 OpenMaya.MVector(1.0, 0.0, 0.0), #vertex normal on face (4,6,7,5) #6 OpenMaya.MVector(1.0, 0.0, 0.0), #vertex normal on face (4,6,7,5) #7 OpenMaya.MVector(1.0, 0.0, 0.0), #vertex normal on face (4,6,7,5) #5 OpenMaya.MVector(0.0, 0.0, -1.0), #vertex normal on face (2,6,4,0) #2 OpenMaya.MVector(0.0, 0.0, -1.0), #vertex normal on face (2,6,4,0) #6 OpenMaya.MVector(0.0, 0.0, -1.0), #vertex normal on face (2,6,4,0) #4 OpenMaya.MVector(0.0, 0.0, -1.0), #vertex normal on face (2,6,4,0) #0 OpenMaya.MVector(0.0, -1.0, 0.0), #vertex normal on face (0,4,5,1) #0 OpenMaya.MVector(0.0, -1.0, 0.0), #vertex normal on face (0,4,5,1) #4 OpenMaya.MVector(0.0, -1.0, 0.0), #vertex normal on face (0,4,5,1) #5 OpenMaya.MVector(0.0, -1.0, 0.0), #vertex normal on face (0,4,5,1) #1 OpenMaya.MVector(0.0, 1.0, 0.0), #vertex normal on face (2,3,7,6) #2 OpenMaya.MVector(0.0, 1.0, 0.0), #vertex normal on face (2,3,7,6) #3 OpenMaya.MVector(0.0, 1.0, 0.0), #vertex normal on face (2,3,7,6) #7 OpenMaya.MVector(0.0, 1.0, 0.0) #vertex normal on face (2,3,7,6) #6 ] for j in range(numNormalsPerVoxel): vertexNormals.append(vertexNormalsList[j]) polygonConnects.append(polygonConnectsList[j] + i * numVertices) mFnMesh = OpenMaya.MFnMesh() #shapeNode mMeshShape = mFnMesh.create(totalVertices, totalPolygons, vertexArray, polygonCounts, polygonConnects) mDagNode = OpenMaya.MFnDagNode(mMeshShape) mDagNode.setName('voxelGeom') #in case name existing: name = mDagNode.name() #print mDagNode.name() mDagPath = OpenMaya.MDagPath() mDagNode = OpenMaya.MFnDagNode(mDagNode.child(0)) #print mDagNode.name() mDagNode.getPath(mDagPath) mCubeMesh = OpenMaya.MFnMesh(mDagPath) ''' #assign Normal to the Cubes: #confused how to use setFaceVertexNormals #rewrite the function for setFaceVertexNormals based on setFaceVertexNormal #by query the facelist #support hard edge! for i in range (faceList.length()): for j in range (numVerticesPerPolygon): index = numVerticesPerPolygon * i + j mCubeMesh.setFaceVertexNormal(vertexNormals[index], i, polygonConnects[index]) ''' #''' #setVertexColor if texNodeName: mCubeMesh.createColorSetWithName('vertexColorSet') mCubeMesh.setIsColorClamped('vertexClorSet', True) mCubeMesh.setVertexColors(vertexColorArray, vertexIndexArray, None, OpenMaya.MFnMesh.kRGB) #''' #create skincluster and remap weightData and blendWeight Data if self.skinCluster: influenceObj = cmds.skinCluster(q=True, inf=True) voxelSkinCluster = cmds.skinCluster(influenceObj, name, tsb=2, nw=2) mSelectionlist = OpenMaya.MSelectionList() mSelectionlist.add(voxelSkinCluster[0]) mObj_voxelSkinCluster = OpenMaya.MObject() mSelectionlist.getDependNode(0, mObj_voxelSkinCluster) mfnSkinCluster = OpenMayaAnim.MFnSkinCluster(mObj_voxelSkinCluster) mDagPath, component = self.getSkinClusterData(mfnSkinCluster) influenceIndices = OpenMaya.MIntArray() for i in xrange(len(influenceObj)): influenceIndices.append(i) #print voxelWeights mfnSkinCluster.setWeights(mDagPath, component, influenceIndices, vertexWeightArray, False) mfnSkinCluster.setBlendWeights(mDagPath, component, vertexBlendWeightArray) #''' #--[retrive initialShadingGroup]--# mSelectionList = OpenMaya.MSelectionList() mSelectionList.add("initialShadingGroup") mObject_initShdGrp = OpenMaya.MObject() mSelectionList.getDependNode(0, mObject_initShdGrp) mFnDependencyNode_initialShadingGroup = OpenMaya.MFnDependencyNode( mObject_initShdGrp) #mFnDependencyNode_initialShadingGroup.setObject(mObject_initShdGrp) #name = mFnDependencyNode_initialShadingGroup.name() # Result: initialShadingGroup, so it ok so far fnSet = OpenMaya.MFnSet(mObject_initShdGrp) fnSet.addMember(mMeshShape)
def importPly(self, plyPath, importOptions): verbose = False if importOptions: if 'verbose' in importOptions and importOptions[ 'verbose'] == 'true': verbose = True plydata = ply.PlyData.read(str(plyPath)) #if verbose: # print( plydata ) # # Process vertices # vertexElement = plydata['vertex'] numVertices = vertexElement.count vertexAttributes = map(lambda x: x[0], vertexElement.dtype()) if verbose: print("Vertices : %d" % numVertices) print("Vertex Attributes : %s" % vertexAttributes) vertexProperties = vertexElement.properties (x, y, z) = (vertexElement[t] for t in ('x', 'y', 'z')) vertices = OpenMaya.MFloatPointArray(numVertices) for i in range(numVertices): vertices.set(i, float(x[i]), float(y[i]), float(z[i])) vertexNormalsPresent = ('nx' in vertexAttributes and 'ny' in vertexAttributes and 'nz' in vertexAttributes) if vertexNormalsPresent: if verbose: print("Vertex Normals present") (nx, ny, nz) = (vertexElement[t] for t in ('nx', 'ny', 'nz')) vertexNormals = OpenMaya.MVectorArray() vertexNormalsIndices = OpenMaya.MIntArray() vertexNormalsIndices.setLength(numVertices) for i in range(numVertices): vertexNormals.append( OpenMaya.MVector(float(nx[i]), float(ny[i]), float(nz[i]))) vertexNormalsIndices.set(i, i) vertexUVsPresent = ('u' in vertexAttributes and 'v' in vertexAttributes) if vertexUVsPresent: if verbose: print("Vertex UVs present") (u, v) = (vertexElement[t] for t in ('u', 'v')) uArray = OpenMaya.MFloatArray() uArray.setLength(numVertices) vArray = OpenMaya.MFloatArray() vArray.setLength(numVertices) for i in range(numVertices): uArray.set(float(u[i]), i) vArray.set(float(v[i]), i) vertexColorsPresent = ('r' in vertexAttributes and 'g' in vertexAttributes and 'b' in vertexAttributes) if vertexColorsPresent: if verbose: print("Vertex Colors present") (r, g, b) = (vertexElement[t] for t in ('r', 'g', 'b')) vertexColors = OpenMaya.MColorArray() vertexColorsIndices = OpenMaya.MIntArray() vertexColorsIndices.setLength(numVertices) for i in range(numVertices): vertexColors.append( OpenMaya.MColor(float(r[i]), float(g[i]), float(b[i]))) vertexColorsIndices.set(i, i) # # Process faces # faceElement = plydata['face'] numFaces = faceElement.count faceAttributes = map(lambda x: x[0], faceElement.dtype()) if verbose: print("Faces : %d" % numFaces) print("Face Attributes : %s" % faceAttributes) vertex_indices = faceElement['vertex_indices'] faceCounts = OpenMaya.MIntArray() faceCounts.setLength(numFaces) faceIndicesCount = 0 for i in range(numFaces): indices = vertex_indices[i] faceCounts.set(int(len(indices)), i) faceIndicesCount += int(len(indices)) faceIndicesArray = OpenMaya.MIntArray() faceIndicesArray.setLength(faceIndicesCount) n = 0 for i in range(numFaces): indices = vertex_indices[i] for j in range(len(indices)): faceIndicesArray.set(int(indices[j]), int(n)) n = n + 1 faceNormalsPresent = ('nx' in faceAttributes and 'ny' in faceAttributes and 'nz' in faceAttributes) if faceNormalsPresent: if verbose: print("Per Face Normals present") (nx, ny, nz) = (faceElement[t] for t in ('nx', 'ny', 'nz')) faceNormals = OpenMaya.MVectorArray() faceNormalsIndices = OpenMaya.MIntArray() faceNormalsVertexIndices = OpenMaya.MIntArray() faceNormalsIndices.setLength(faceIndicesCount) faceNormalsVertexIndices.setLength(faceIndicesCount) n = 0 for i in range(numFaces): indices = vertex_indices[i] for j in range(len(indices)): faceNormals.append( OpenMaya.MVector(float(nx[i]), float(ny[i]), float(nz[i]))) faceNormalsIndices.set(i, n) faceNormalsVertexIndices.set(int(indices[j]), int(n)) n = n + 1 normalsElement = None if 'normals' in plydata: normalsElement = plydata['normals'] facePerVertexNormalsPresent = ('normals_indices' in faceAttributes) and normalsElement if facePerVertexNormalsPresent: if verbose: print("Per Face Per Vertex Normals present") (nx, ny, nz) = (normalsElement[t] for t in ('nx', 'ny', 'nz')) normals_indices = faceElement['normals_indices'] faceNormals = OpenMaya.MVectorArray() faceNormalsIndices = OpenMaya.MIntArray() faceNormalsVertexIndices = OpenMaya.MIntArray() faceNormalsIndices.setLength(faceIndicesCount) faceNormalsVertexIndices.setLength(faceIndicesCount) n = 0 for i in range(numFaces): indices = normals_indices[i] for j in range(len(indices)): normalIndex = indices[j] faceNormals.append( OpenMaya.MVector(float(nx[normalIndex]), float(ny[normalIndex]), float(nz[normalIndex]))) faceNormalsIndices.set(i, n) faceNormalsVertexIndices.set(int(normalIndex), int(n)) n = n + 1 #if verbose: # print( "Face %d : Vertex %d : Normal %3.3f, %3.3f, %3.3f" % ( # i, j, float(nx[normalIndex]), float(ny[normalIndex]), float(nz[normalIndex]))) uvElement = None if 'uvs' in plydata: uvElement = plydata['uvs'] faceUVsPresent = ('uv_indices' in faceAttributes) and uvElement if faceUVsPresent: if verbose: print("Per Face Per Vertex UVs present") (u, v) = (uvElement[t] for t in ('u', 'v')) uv_indices = faceElement['uv_indices'] uArray = OpenMaya.MFloatArray() uArray.setLength(len(u)) vArray = OpenMaya.MFloatArray() vArray.setLength(len(v)) for i in range(len(u)): uArray.set(float(u[i]), i) vArray.set(float(v[i]), i) colorsElement = None if 'colors' in plydata: colorsElement = plydata['colors'] facePerVertexColorsPresent = ('colors_indices' in faceAttributes) and colorsElement if facePerVertexColorsPresent: if verbose: print("Per Face Per Vertex Colors present") (r, g, b) = (colorsElement[t] for t in ('r', 'g', 'b')) colors_indices = faceElement['colors_indices'] faceColors = OpenMaya.MColorArray() faceColorsIndices = OpenMaya.MIntArray() faceColorsVertexIndices = OpenMaya.MIntArray() faceColorsIndices.setLength(faceIndicesCount) faceColorsVertexIndices.setLength(faceIndicesCount) n = 0 for i in range(numFaces): indices = colors_indices[i] for j in range(len(indices)): colorIndex = indices[j] faceColors.append( OpenMaya.MColor(float(r[colorIndex]), float(g[colorIndex]), float(b[colorIndex]))) faceColorsIndices.set(i, n) faceColorsVertexIndices.set(int(colorIndex), int(n)) n = n + 1 # # Build Maya mesh # outputMesh = OpenMaya.MObject() meshFS = OpenMaya.MFnMesh() newMesh = meshFS.create(numVertices, numFaces, vertices, faceCounts, faceIndicesArray, outputMesh) if vertexNormalsPresent: meshFS.setVertexNormals(vertexNormals, vertexNormalsIndices) if vertexColorsPresent: meshFS.setVertexColors(vertexColors, vertexColorsIndices) if facePerVertexNormalsPresent: status = meshFS.setFaceVertexNormals(faceNormals, faceNormalsIndices, faceIndicesArray) if faceNormalsPresent: status = meshFS.setFaceVertexNormals(faceNormals, faceNormalsIndices, faceIndicesArray) if facePerVertexColorsPresent: meshFS.setFaceVertexColors(faceColors, faceColorsIndices, faceIndicesArray) if vertexUVsPresent: if verbose: print("Vertex UVs present") meshFS.setUVs(uArray, vArray) uvCounts = OpenMaya.MIntArray() uvCounts.setLength(numFaces) uvIds = OpenMaya.MIntArray() uvIds.setLength(faceIndicesCount) uvCountsIndex = 0 uvIndex = 0 for i in range(numFaces): numPolygonVertices = meshFS.polygonVertexCount(i) uvCounts.set(numPolygonVertices, int(uvCountsIndex)) uvCountsIndex = uvCountsIndex + 1 if numPolygonVertices == 0: continue indices = vertex_indices[i] for vertexIndex in range(numPolygonVertices): uvIds.set(int(indices[vertexIndex]), int(uvIndex)) uvIndex = uvIndex + 1 meshFS.assignUVs(uvCounts, uvIds) if faceUVsPresent: if verbose: print("Face UVs present") meshFS.setUVs(uArray, vArray) uvCounts = OpenMaya.MIntArray() uvCounts.setLength(numFaces) uvIds = OpenMaya.MIntArray() uvIds.setLength(faceIndicesCount) uvCountsIndex = 0 uvIndex = 0 for i in range(numFaces): numPolygonVertices = meshFS.polygonVertexCount(i) uvCounts.set(numPolygonVertices, int(uvCountsIndex)) uvCountsIndex = uvCountsIndex + 1 if numPolygonVertices == 0: continue indices = uv_indices[i] for vertexIndex in range(numPolygonVertices): uvIds.set(int(indices[vertexIndex]), int(uvIndex)) uvIndex = uvIndex + 1 meshFS.assignUVs(uvCounts, uvIds) meshFS.updateSurface() # Assign initial shading group initialSG = OpenMaya.MObject() slist = OpenMaya.MSelectionList() OpenMaya.MGlobal.getSelectionListByName("initialShadingGroup", slist) slist.getDependNode(0, initialSG) fnSG = OpenMaya.MFnSet(initialSG) if fnSG.restriction() == OpenMaya.MFnSet.kRenderableOnly: fnSG.addMember(newMesh)
def exportPly(self, mObject, mFnDagNode, dagPath, exportOptions): verbose = False triangulate = False if exportOptions: if 'verbose' in exportOptions and exportOptions[ 'verbose'] == 'true': verbose = True if 'triangulate' in exportOptions and exportOptions[ 'triangulate'] == 'true': triangulate = True dagNode = OpenMaya.MDagPath() mFnDagNode.getPath(dagNode) dagNode.extendToShape() meshNode = OpenMaya.MFnMesh(dagNode) dagPath = dagNode.fullPathName() if verbose: print("exportPly : %s" % dagPath) # Space to evaluate normals, point positions space = OpenMaya.MSpace.kWorld if exportOptions: if 'space' in exportOptions and exportOptions['space'] == 'object': if verbose: print("\tSpace : %s" % "object space") space = OpenMaya.MSpace.kObject else: if verbose: print("\tSpace : %s" % "world space") ''' polygonSets = OpenMaya.MObjectArray() polygonComponents = OpenMaya.MObjectArray() isInstanced = dagNode.isInstanced() print( "\tInstanced : %s" % isInstanced ) if dagNode.isInstanced(): instanceNum = dagNode.instanceNumber() print( "\tInstance Number : %s" % instanceNum ) meshNode.getConnectedSetsAndMembers(instanceNum, polygonSets, polygonComponents, True) print( "\tPolygon Sets : %s" % polygonSets.length() ) print( "\tPolygon Components : %s" % polygonComponents.length() ) ''' # Get Vertices numVertices = meshNode.numVertices() if verbose: print("\tVerts : %d" % numVertices) points = OpenMaya.MPointArray() meshNode.getPoints(points, space) numPoints = points.length() if verbose: print("\tPoints : %d" % numPoints) # Get UVs us = OpenMaya.MFloatArray() vs = OpenMaya.MFloatArray() meshNode.getUVs(us, vs) numUVs = us.length() if verbose: print("\tUVs : %d" % numUVs) # Get Normals normals = OpenMaya.MFloatVectorArray() meshNode.getNormals(normals, space) numNormals = normals.length() if verbose: print("\tNorms : %d" % numNormals) # Faces numFaces = meshNode.numPolygons() if verbose: print("\tFaces : %d" % numFaces) # Vertex Colors numColors = meshNode.numColors() vertexColors = None faceVertexColors = None if numColors > 0: vertexColors = OpenMaya.MColorArray() meshNode.getVertexColors(vertexColors) numVertexColors = vertexColors.length() if verbose: print("\tVertex Colors : %d" % numVertexColors) #for i in range(numVertexColors): # print( "Color %d : %3.3f, %3.3f, %3.3f" % ( # i, vertexColors[i].r, vertexColors[i].g, vertexColors[i].b)) faceVertexColors = OpenMaya.MColorArray() meshNode.getFaceVertexColors(faceVertexColors) numFaceVertexColors = faceVertexColors.length() if verbose: print("\tFace Vert Colors : %d" % numFaceVertexColors) #for i in range(numFaceVertexColors): # print( "Color %d : %3.3f, %3.3f, %3.3f" % ( # i, faceVertexColors[i].r, faceVertexColors[i].g, faceVertexColors[i].b)) # Per-Face data itMeshPoly = OpenMaya.MItMeshPolygon(mObject) # Check for triangulation hasValidTriangulation = itMeshPoly.hasValidTriangulation() if verbose: print("\tHas Triangulation : %s" % hasValidTriangulation) if hasValidTriangulation: triangleCount = OpenMaya.MIntArray() triangleIndices = OpenMaya.MIntArray() meshNode.getTriangles(triangleCount, triangleIndices) else: if triangulate: OpenMaya.MGlobal.displayWarning( "Shape %s has invalid triangulation, skipping" % dagPath) return None if verbose: t0 = timeit.default_timer() if triangulate and hasValidTriangulation: plyData = self.exportTriangulatedMesh(mObject, dagPath, meshNode, points, us, vs, normals, faceVertexColors, triangleCount, triangleIndices, exportOptions, verbose) else: plyData = self.exportMesh(mObject, dagPath, meshNode, points, us, vs, normals, faceVertexColors, exportOptions, verbose) if verbose: t1 = timeit.default_timer() elapsed = (t1 - t0) print("export elapsed : %s" % elapsed) return plyData
def testStaticMeshStaticColor(self): red_array = OpenMaya.MColorArray() red_array.append(1.0, 0.0, 0.0) blue_array = OpenMaya.MColorArray() blue_array.append(0.0, 0.0, 1.0) single_indices = OpenMaya.MIntArray(4, 0) mixed_colors = [[1.0, 1.0, 0.0, 1.0], [0.0, 1.0, 1.0, 0.75], [1.0, 0.0, 1.0, 0.5], [1.0, 1.0, 1.0, 0.25]] mixed_array = OpenMaya.MColorArray() for x in mixed_colors: mixed_array.append(x[0], x[1], x[2], x[3]) mixed_indices = OpenMaya.MIntArray() for i in range(4): mixed_indices.append(i) MayaCmds.polyPlane(sx=1, sy=1, name='poly') MayaCmds.select('polyShape') sel = OpenMaya.MSelectionList() OpenMaya.MGlobal.getActiveSelectionList(sel) obj = OpenMaya.MObject() sel.getDependNode(0, obj) fn = OpenMaya.MFnMesh(obj) fn.createColorSetWithName('reds') fn.createColorSetWithName('mixed') fn.setColors(red_array, 'reds', OpenMaya.MFnMesh.kRGB) fn.assignColors(single_indices, 'reds') fn.setColors(mixed_array, 'mixed', OpenMaya.MFnMesh.kRGBA) fn.assignColors(mixed_indices, 'mixed') fn.setCurrentColorSetName('mixed') MayaCmds.polyPlane(sx=1, sy=1, name='subd') MayaCmds.select('subdShape') sel = OpenMaya.MSelectionList() OpenMaya.MGlobal.getActiveSelectionList(sel) obj = OpenMaya.MObject() sel.getDependNode(0, obj) fn = OpenMaya.MFnMesh(obj) fn.createColorSetWithName('blues') fn.createColorSetWithName('mixed') fn.setColors(blue_array, 'blues', OpenMaya.MFnMesh.kRGB) fn.assignColors(single_indices, 'blues') fn.setColors(mixed_array, 'mixed', OpenMaya.MFnMesh.kRGBA) fn.assignColors(mixed_indices, 'mixed') fn.setCurrentColorSetName('blues') MayaCmds.addAttr(longName='SubDivisionMesh', attributeType='bool', defaultValue=True) self.__files.append(util.expandFileName('staticColorSets.abc')) MayaCmds.AbcExport(j='-root poly -root subd -wcs -file ' + self.__files[-1]) MayaCmds.AbcImport(self.__files[-1], mode='open') MayaCmds.select('polyShape') sel = OpenMaya.MSelectionList() OpenMaya.MGlobal.getActiveSelectionList(sel) obj = OpenMaya.MObject() sel.getDependNode(0, obj) fn = OpenMaya.MFnMesh(obj) self.failUnless(fn.currentColorSetName() == 'mixed') setNames = [] fn.getColorSetNames(setNames) self.failUnless(len(setNames) == 2) self.failUnless(setNames.count('mixed') == 1) self.failUnless(setNames.count('reds') == 1) colArray = OpenMaya.MColorArray() fn.getFaceVertexColors(colArray, 'reds') self.failUnless(colArray.length() == 4) for x in range(colArray.length()): self.failUnless(colArray[x].r == 1) self.failUnless(colArray[x].g == 0) self.failUnless(colArray[x].b == 0) fn.getFaceVertexColors(colArray, 'mixed') self.failUnless(colArray.length() == 4) for x in range(colArray.length()): self.failUnless(colArray[x].r == mixed_colors[x][0]) self.failUnless(colArray[x].g == mixed_colors[x][1]) self.failUnless(colArray[x].b == mixed_colors[x][2]) self.failUnless(colArray[x].a == mixed_colors[x][3]) MayaCmds.select('subdShape') self.failUnless(MayaCmds.getAttr('subdShape.SubDivisionMesh') == 1) sel = OpenMaya.MSelectionList() OpenMaya.MGlobal.getActiveSelectionList(sel) obj = OpenMaya.MObject() sel.getDependNode(0, obj) fn = OpenMaya.MFnMesh(obj) self.failUnless(fn.currentColorSetName() == 'blues') setNames = [] fn.getColorSetNames(setNames) self.failUnless(len(setNames) == 2) self.failUnless(setNames.count('mixed') == 1) self.failUnless(setNames.count('blues') == 1) colArray = OpenMaya.MColorArray() fn.getFaceVertexColors(colArray, 'blues') self.failUnless(colArray.length() == 4) for x in range(colArray.length()): self.failUnless(colArray[x].r == 0) self.failUnless(colArray[x].g == 0) self.failUnless(colArray[x].b == 1) fn.getFaceVertexColors(colArray, 'mixed') self.failUnless(colArray.length() == 4) for x in range(colArray.length()): self.failUnless(colArray[x].r == mixed_colors[x][0]) self.failUnless(colArray[x].g == mixed_colors[x][1]) self.failUnless(colArray[x].b == mixed_colors[x][2]) self.failUnless(colArray[x].a == mixed_colors[x][3])
def testStaticMeshAnimColor(self): MayaCmds.currentTime(1) MayaCmds.polyPlane(sx=1, sy=1, name='poly') MayaCmds.polyColorPerVertex(r=0.0,g=1.0,b=0.0, cdo=True) MayaCmds.setKeyframe(["polyColorPerVertex1"]) MayaCmds.currentTime(10) MayaCmds.polyColorPerVertex(r=0.0,g=0.0,b=1.0, cdo=True) MayaCmds.setKeyframe(["polyColorPerVertex1"]) MayaCmds.currentTime(1) MayaCmds.polyPlane(sx=1, sy=1, name='subd') MayaCmds.select('subdShape') MayaCmds.addAttr(longName='SubDivisionMesh', attributeType='bool', defaultValue=True) MayaCmds.polyColorPerVertex(r=1.0,g=1.0,b=0.0, cdo=True) MayaCmds.setKeyframe(["polyColorPerVertex2"]) MayaCmds.currentTime(10) MayaCmds.polyColorPerVertex(r=1.0,g=0.0,b=0.0, cdo=True) MayaCmds.setKeyframe(["polyColorPerVertex2"]) self.__files.append(util.expandFileName('animColorSets.abc')) MayaCmds.AbcExport(j='-fr 1 10 -root poly -root subd -wcs -file ' + self.__files[-1]) MayaCmds.AbcImport(self.__files[-1], mode='open') MayaCmds.select('polyShape') sel = OpenMaya.MSelectionList() OpenMaya.MGlobal.getActiveSelectionList(sel) obj = OpenMaya.MObject() sel.getDependNode(0, obj) fn = OpenMaya.MFnMesh(obj) MayaCmds.currentTime(1) colArray = OpenMaya.MColorArray() fn.getFaceVertexColors(colArray) self.failUnless(colArray.length() == 4) for x in range(colArray.length()): self.failUnlessAlmostEqual(colArray[x].r, 0) self.failUnlessAlmostEqual(colArray[x].g, 1) self.failUnlessAlmostEqual(colArray[x].b, 0) MayaCmds.currentTime(5) colArray = OpenMaya.MColorArray() fn.getFaceVertexColors(colArray) self.failUnless(colArray.length() == 4) for x in range(colArray.length()): self.failUnless(colArray[x].r == 0) self.failUnlessAlmostEqual(colArray[x].g, 0.555555582047) self.failUnlessAlmostEqual(colArray[x].b, 0.444444447756) MayaCmds.currentTime(10) colArray = OpenMaya.MColorArray() fn.getFaceVertexColors(colArray) self.failUnless(colArray.length() == 4) for x in range(colArray.length()): self.failUnlessAlmostEqual(colArray[x].r, 0) self.failUnlessAlmostEqual(colArray[x].g, 0) self.failUnlessAlmostEqual(colArray[x].b, 1) self.failUnless(MayaCmds.getAttr('subdShape.SubDivisionMesh') == 1) MayaCmds.select('subdShape') sel = OpenMaya.MSelectionList() OpenMaya.MGlobal.getActiveSelectionList(sel) obj = OpenMaya.MObject() sel.getDependNode(0, obj) fn = OpenMaya.MFnMesh(obj) MayaCmds.currentTime(1) colArray = OpenMaya.MColorArray() fn.getFaceVertexColors(colArray) self.failUnless(colArray.length() == 4) for x in range(colArray.length()): self.failUnlessAlmostEqual(colArray[x].r, 1) self.failUnlessAlmostEqual(colArray[x].g, 1) self.failUnlessAlmostEqual(colArray[x].b, 0) MayaCmds.currentTime(5) colArray = OpenMaya.MColorArray() fn.getFaceVertexColors(colArray) self.failUnless(colArray.length() == 4) for x in range(colArray.length()): self.failUnlessAlmostEqual(colArray[x].r, 1) self.failUnlessAlmostEqual(colArray[x].g, 0.555555582047) self.failUnlessAlmostEqual(colArray[x].b, 0) MayaCmds.currentTime(10) colArray = OpenMaya.MColorArray() fn.getFaceVertexColors(colArray) self.failUnless(colArray.length() == 4) for x in range(colArray.length()): self.failUnlessAlmostEqual(colArray[x].r, 1) self.failUnlessAlmostEqual(colArray[x].g, 0) self.failUnlessAlmostEqual(colArray[x].b, 0)
def createVoxelMesh(self, voxelCenterPosition, uvArray, texNodeName, cubeWidth, outputMeshData): numVoxels = len(voxelCenterPosition) numVertices = 8 #number of vertices numPolygons = 6 #number of polygons numVerticesPerPolygon = 4 #number of vertices per polygon numNormalsPerVoxel = numVerticesPerPolygon * numPolygons #24 number of vertex normals numPolygonConnectsPerVoxel = numPolygons * numVerticesPerPolygon #24 number of polygon connects cubeHalfWidth = cubeWidth / 2 #initialize all the params in the MFnMesh.create() #vertexArray: point array, This should include all the vertices in the mesh and no eatras totalVertices = numVertices * numVoxels vertexArray = OpenMaya.MFloatPointArray() #polygonCounts array of vertex counts for each polygon #for the cube would have 6 faces, each of which had 4 verts, so the polygonCounts would be [4,4,4,4,4,4] totalPolygons = numPolygons * numVoxels polygonCounts = OpenMaya.MIntArray() #polygonConnects #array of vertex connections for each polygon polygonConnects = OpenMaya.MIntArray() #set shared Normals for these vertices vertexNormals = OpenMaya.MVectorArray() #vertexColorArray vertexColorArray = OpenMaya.MColorArray() #vertexColorIndexArray vertexIndexArray = OpenMaya.MIntArray() #PolygonIDArray faceList = OpenMaya.MIntArray() for i in range(numVoxels): pVoxelCenterPosition = voxelCenterPosition[i] #Update VertexArray for VoxelMesh vertexList = [ OpenMaya.MFloatPoint(pVoxelCenterPosition.x - cubeHalfWidth, pVoxelCenterPosition.y - cubeHalfWidth, pVoxelCenterPosition.z - cubeHalfWidth), #vertex 0 OpenMaya.MFloatPoint(pVoxelCenterPosition.x - cubeHalfWidth, pVoxelCenterPosition.y - cubeHalfWidth, pVoxelCenterPosition.z + cubeHalfWidth), #vertex 1 OpenMaya.MFloatPoint(pVoxelCenterPosition.x - cubeHalfWidth, pVoxelCenterPosition.y + cubeHalfWidth, pVoxelCenterPosition.z - cubeHalfWidth), #vertex 2 OpenMaya.MFloatPoint(pVoxelCenterPosition.x - cubeHalfWidth, pVoxelCenterPosition.y + cubeHalfWidth, pVoxelCenterPosition.z + cubeHalfWidth), #vertex 3 OpenMaya.MFloatPoint(pVoxelCenterPosition.x + cubeHalfWidth, pVoxelCenterPosition.y - cubeHalfWidth, pVoxelCenterPosition.z - cubeHalfWidth), #vertex 4 OpenMaya.MFloatPoint(pVoxelCenterPosition.x + cubeHalfWidth, pVoxelCenterPosition.y - cubeHalfWidth, pVoxelCenterPosition.z + cubeHalfWidth), #vertex 5 OpenMaya.MFloatPoint(pVoxelCenterPosition.x + cubeHalfWidth, pVoxelCenterPosition.y + cubeHalfWidth, pVoxelCenterPosition.z - cubeHalfWidth), #vertex 6 OpenMaya.MFloatPoint(pVoxelCenterPosition.x + cubeHalfWidth, pVoxelCenterPosition.y + cubeHalfWidth, pVoxelCenterPosition.z + cubeHalfWidth), #vertex 7 ] for j in range(numVertices): vertexArray.append(vertexList[j]) #here need to assign vertex color if texNodeName: vertexColor = cmds.colorAtPoint(texNodeName, o='RGB', u=uvArray[i][0], v=uvArray[i][1]) mColor = OpenMaya.MColor(vertexColor[0], vertexColor[1], vertexColor[2], 1.0) vertexColorArray.append(mColor) vertexIndexArray.append(i * numVertices + j) #print vertexColor #Update polygonCounts for VoxelMesh for j in range(numPolygons): polygonCounts.append(numVerticesPerPolygon) faceList.append(i * numPolygons + j) #Update polygonConnects for VoxelMesh #Update vertexNormals for VoxelMesh polygonConnectsList = [ 0, 1, 3, 2, 1, 5, 7, 3, 4, 6, 7, 5, 2, 6, 4, 0, 0, 4, 5, 1, 2, 3, 7, 6 ] vertexNormalsList = [ OpenMaya.MVector(-1.0, 0.0, 0.0), #vertex normal on face (0,1,3,2) #0 OpenMaya.MVector(-1.0, 0.0, 0.0), #vertex normal on face (0,1,3,2) #1 OpenMaya.MVector(-1.0, 0.0, 0.0), #vertex normal on face (0,1,3,2) #7 OpenMaya.MVector(-1.0, 0.0, 0.0), #vertex normal on face (0,1,3,2) #3 OpenMaya.MVector(0.0, 0.0, 1.0), #vertex normal on face (1,5,7,3) #1 OpenMaya.MVector(0.0, 0.0, 1.0), #vertex normal on face (1,5,7,3) #5 OpenMaya.MVector(0.0, 0.0, 1.0), #vertex normal on face (1,5,7,3) #7 OpenMaya.MVector(0.0, 0.0, 1.0), #vertex normal on face (1,5,7,3) #3 OpenMaya.MVector(1.0, 0.0, 0.0), #vertex normal on face (4,6,7,5) #4 OpenMaya.MVector(1.0, 0.0, 0.0), #vertex normal on face (4,6,7,5) #6 OpenMaya.MVector(1.0, 0.0, 0.0), #vertex normal on face (4,6,7,5) #7 OpenMaya.MVector(1.0, 0.0, 0.0), #vertex normal on face (4,6,7,5) #5 OpenMaya.MVector(0.0, 0.0, -1.0), #vertex normal on face (2,6,4,0) #2 OpenMaya.MVector(0.0, 0.0, -1.0), #vertex normal on face (2,6,4,0) #6 OpenMaya.MVector(0.0, 0.0, -1.0), #vertex normal on face (2,6,4,0) #4 OpenMaya.MVector(0.0, 0.0, -1.0), #vertex normal on face (2,6,4,0) #0 OpenMaya.MVector(0.0, -1.0, 0.0), #vertex normal on face (0,4,5,1) #0 OpenMaya.MVector(0.0, -1.0, 0.0), #vertex normal on face (0,4,5,1) #4 OpenMaya.MVector(0.0, -1.0, 0.0), #vertex normal on face (0,4,5,1) #5 OpenMaya.MVector(0.0, -1.0, 0.0), #vertex normal on face (0,4,5,1) #1 OpenMaya.MVector(0.0, 1.0, 0.0), #vertex normal on face (2,3,7,6) #2 OpenMaya.MVector(0.0, 1.0, 0.0), #vertex normal on face (2,3,7,6) #3 OpenMaya.MVector(0.0, 1.0, 0.0), #vertex normal on face (2,3,7,6) #7 OpenMaya.MVector(0.0, 1.0, 0.0) #vertex normal on face (2,3,7,6) #6 ] for j in range(numNormalsPerVoxel): vertexNormals.append(vertexNormalsList[j]) polygonConnects.append(polygonConnectsList[j] + i * numVertices) #for j in range (numPolygonConnectsPerVoxel): mFnMesh = OpenMaya.MFnMesh() #shapeNode mMeshShape = mFnMesh.create(totalVertices, totalPolygons, vertexArray, polygonCounts, polygonConnects, outputMeshData) #mMeshShape --> kMeshGeom mCubeMesh = OpenMaya.MFnMesh(mMeshShape) ''' #assign Normal to the Cubes: #confused how to use setFaceVertexNormals #rewrite the function for setFaceVertexNormals based on setFaceVertexNormal #by query the facelist #support hard edge! for i in range (faceList.length()): for j in range (numVerticesPerPolygon): index = numVerticesPerPolygon * i + j mCubeMesh.setFaceVertexNormal(vertexNormals[index], i, polygonConnects[index]) ''' #''' #setVertexColor if texNodeName: mCubeMesh.createColorSetDataMesh('vertexColorSet') mCubeMesh.setVertexColors(vertexColorArray, vertexIndexArray, None, OpenMaya.MFnMesh.kRGBA) #''' return outputMeshData
def writeAscii(fileHandle, itDag): try: dom = minidom.Document() meshElement = dom.createElement("Mesh") dom.appendChild(meshElement) ### DEFAULT_COLOR = (1.0, 1.0, 1.0, 1.0) DEFAULT_UV = (0, 0) vertexDict = {} # {[idPoint, idNormal, idColor, idUV0, idUV1,], } pointsDict = {} # {(float, float, float, float): id} normalsDict = {} # {(float, float, float): id} tangentsDict = {} # {(float, float, float): id} binormalsDict = {} # {(float, float, float): id} colorsDict = {DEFAULT_COLOR: 0} # {(r, g, b, a): id} uvCoordsDict = {DEFAULT_UV: 0} # {(r, g, b, a): id} faceList = [] objectFaces = [] # [ [faceID1, faceID2], [], ] colorSetNames = cmds.polyColorSet(query=True, allColorSets=True) #export objects numExportedObjects = 0 while not itDag.isDone(): dagPath = getDagPath(itDag) dagFn = OpenMaya.MFnDagNode(dagPath) mesh = OpenMaya.MFnMesh(dagPath) print ">> writing: %s ..." % dagPath.fullPathName() ### collect face defintions ### itPolygon = OpenMaya.MItMeshPolygon(dagPath) points = OpenMaya.MPointArray() normals = OpenMaya.MVectorArray() tangents = OpenMaya.MVectorArray() binormals = OpenMaya.MVectorArray() colors = OpenMaya.MColorArray() uList = OpenMaya.MFloatArray() vList = OpenMaya.MFloatArray() uvSetNames = [] itPolygon.getUVSetNames(uvSetNames) facesInObject = [] while not itPolygon.isDone(): itPolygon.getPoints(points, OpenMaya.MSpace.kObject) itPolygon.getNormals(normals, OpenMaya.MSpace.kObject) if colorSetNames: itPolygon.getColors(colors, colorSetNames[0]) #print "got colors %s" % colors else: colors = None for uvSet in uvSetNames: try: itPolygon.getUVs(uList, vList, uvSet) except Exception, msg: print "failed to query uvSet '%s'" % uvSet uList = OpenMaya.MFloatArray() vList = OpenMaya.MFloatArray() #print "tangent=%s" % ([tangent.x,tangent.y,tangent.z]) # Flip z for left-handed coordinate system #tangents.append( [tangent.x, tangent.y, -(tangent.z)] ) #binormals.append( [binormal.x, binormal.y, -(binormal.z)] ) itFaceVertex.next() ### iterate over face vertices ### faceVerticeIndexes = [] i = 0 #for i in range( points.length() ): itFaceVertex = OpenMaya.MItMeshFaceVertex( dagPath, itPolygon.polygon()) while not itFaceVertex.isDone(): ### get tangents and binormals #uvSets = [] #itPolygon.getUVSetNames( uvSets ) ### get position p = points[i] tPoint = (p.x, p.y, p.z, 1.0) if pointsDict.has_key(tPoint): pointIndex = pointsDict[tPoint] else: pointIndex = len(pointsDict) pointsDict[tPoint] = pointIndex ### get tangent t = itFaceVertex.getTangent(OpenMaya.MSpace.kObject, uvSetNames[0]) tangent = (t.x, t.y, t.z) if tangentsDict.has_key(tangent): tangentIndex = tangentsDict[tangent] else: tangentIndex = len(tangentsDict) tangentsDict[tangent] = tangentIndex ### get binormal b = itFaceVertex.getBinormal(OpenMaya.MSpace.kObject, uvSetNames[0]) binormal = (b.x, b.y, b.z) if binormalsDict.has_key(binormal): binormalIndex = binormalsDict[binormal] else: binormalIndex = len(binormalsDict) binormalsDict[binormal] = binormalIndex ### get normal n = normals[i] tNormal = (n.x, n.y, n.z) if normalsDict.has_key(tNormal): normalIndex = normalsDict[tNormal] else: normalIndex = len(normalsDict) normalsDict[tNormal] = normalIndex ### get uvs if len(uList) > i and len(vList) > i: tUV = (float(uList[i]), float(vList[i])) if uvCoordsDict.has_key(tUV): uvCoordIndex = uvCoordsDict[tUV] else: uvCoordIndex = len(uvCoordsDict) uvCoordsDict[tUV] = uvCoordIndex else: uvCoordIndex = 0 ### export Colors ### if not colors: tColor = DEFAULT_COLOR else: c = colors[i] #tColor= ( clamp(int(c.r * 255), 0, 255), # clamp(int(c.g * 255), 0, 255), # clamp(int(c.b * 255), 0, 255), # clamp(int(c.a * 255), 0, 255)) # Fix default colors if c.r == -1 and c.g == -1 and c.b == -1 and c.a == -1: c.r = c.g = c.b = c.a = 1.0 tColor = (c.r, c.g, c.b, c.a) if colorsDict.has_key(tColor): colorIndex = colorsDict[tColor] else: colorIndex = len(colorsDict) colorsDict[tColor] = colorIndex ### write vertex definition vertexDef = (pointIndex, normalIndex, colorIndex, uvCoordIndex, tangentIndex, binormalIndex) if vertexDict.has_key(vertexDef): vertexIndex = vertexDict[vertexDef] else: vertexIndex = len(vertexDict) vertexDict[vertexDef] = vertexIndex faceVerticeIndexes.append("%s" % vertexIndex) ### next vertex i += 1 itFaceVertex.next() facesInObject.append(len(faceList)) faceList.append(" ".join(faceVerticeIndexes)) itPolygon.next() objectFaces.append(facesInObject) numExportedObjects += 1 itDag.next() ### write vertex def list ### attributesElement = dom.createElement("Attributes") meshElement.appendChild(attributesElement) for id, listName, vtype in [ ("POSITION", "Positions", "R32G32B32A32_Float"), ("NORMAL", "Normals", "R32G32B32_Float"), ("COLOR", "Colors", "R32G32B32A32_Float"), ("TEXCOORD", "UVCoords", "R32G32_Float"), ("TANGENT", "Tangents", "R32G32B32_Float"), ("BINORMAL", "Binormals", "R32G32B32_Float"), ]: attributeElement = dom.createElement("Attribute") attributeElement.setAttribute("id", id) attributeElement.setAttribute("type", vtype) attributeElement.setAttribute("list", listName) attributesElement.appendChild(attributeElement) ### write vertices ### verticesElement = dom.createElement("Vertices") meshElement.appendChild(verticesElement) t = dom.createTextNode(getDictAsList(vertexDict)) verticesElement.appendChild(t) ### write positions ### positionsElement = dom.createElement("Positions") meshElement.appendChild(positionsElement) t = dom.createTextNode(getDictAsList(pointsDict)) positionsElement.appendChild(t) ### write normals ### normalsElement = dom.createElement("Normals") meshElement.appendChild(normalsElement) t = dom.createTextNode(getDictAsList(normalsDict)) normalsElement.appendChild(t) ### write tangents ### tangentsElement = dom.createElement("Tangents") meshElement.appendChild(tangentsElement) t = dom.createTextNode(getDictAsList(tangentsDict)) tangentsElement.appendChild(t) ### write binormals ### binormalElement = dom.createElement("Binormals") meshElement.appendChild(binormalElement) t = dom.createTextNode(getDictAsList(binormalsDict)) binormalElement.appendChild(t) ### write colors ### colorsElement = dom.createElement("Colors") meshElement.appendChild(colorsElement) t = dom.createTextNode(getDictAsList(colorsDict)) colorsElement.appendChild(t) ### write UVCoords ### uvCoordsElement = dom.createElement("UVCoords") meshElement.appendChild(uvCoordsElement) t = dom.createTextNode(getDictAsList(uvCoordsDict)) uvCoordsElement.appendChild(t) ### write faces ### facesElement = dom.createElement("Faces") meshElement.appendChild(facesElement) t = dom.createTextNode(", \n".join(faceList)) facesElement.appendChild(t) ### write objects ### objectsElement = dom.createElement("Objects") meshElement.appendChild(objectsElement) tlist = [] for of in objectFaces: tlist.append(listToString(of)) t = dom.createTextNode(" ,\n".join(tlist)) objectsElement.appendChild(t) #fileHandle.write( "<!DOCTYPE StillMesh>\n") fileHandle.write(dom.toprettyxml(indent=" ")) return True
def importModelNode(model, path): # Import skeleton for binds, materials for meshes (_handles, paths) = importSkeletonNode(model.Skeleton()) _materials = [importMaterialNode(path, x) for x in model.Materials()] # Import the meshes meshTransform = OpenMaya.MFnTransform() meshNode = meshTransform.create() meshTransform.setName(os.path.splitext(os.path.basename(path))[0]) meshes = model.Meshes() progress = utilityCreateProgress("Importing model...", len(meshes)) for mesh in meshes: newMeshTransform = OpenMaya.MFnTransform() newMeshNode = newMeshTransform.create(meshNode) newMeshTransform.setName("CastMesh") # Triangle count / vertex count faceCount = mesh.FaceCount() vertexCount = mesh.VertexCount() faces = mesh.FaceBuffer() scriptUtil = OpenMaya.MScriptUtil() scriptUtil.createFromList([x for x in faces], len(faces)) faceBuffer = OpenMaya.MIntArray(scriptUtil.asIntPtr(), len(faces)) faceCountBuffer = OpenMaya.MIntArray(faceCount, 3) vertexPositions = mesh.VertexPositionBuffer() scriptUtil = OpenMaya.MScriptUtil() scriptUtil.createFromList([ x for y in (vertexPositions[i:i + 3] + tuple([1.0]) * (i < len(vertexPositions) - 2) for i in xrange(0, len(vertexPositions), 3)) for x in y ], vertexCount) vertexPositionBuffer = OpenMaya.MFloatPointArray( scriptUtil.asFloat4Ptr(), vertexCount) newMesh = OpenMaya.MFnMesh() newMesh.create(vertexCount, faceCount, vertexPositionBuffer, faceCountBuffer, faceBuffer, newMeshNode) scriptUtil = OpenMaya.MScriptUtil() scriptUtil.createFromList([x for x in xrange(vertexCount)], vertexCount) vertexIndexBuffer = OpenMaya.MIntArray(scriptUtil.asIntPtr(), vertexCount) # Each channel after position / faces is optional # meaning we should comletely ignore null buffers here # even though you *should* have them vertexNormals = mesh.VertexNormalBuffer() if vertexNormals is not None: scriptUtil = OpenMaya.MScriptUtil() scriptUtil.createFromList([x for x in vertexNormals], len(vertexNormals)) vertexNormalBuffer = OpenMaya.MVectorArray( scriptUtil.asFloat3Ptr(), len(vertexNormals) / 3) newMesh.setVertexNormals(vertexNormalBuffer, vertexIndexBuffer) vertexColors = mesh.VertexColorBuffer() if vertexColors is not None: scriptUtil = OpenMaya.MScriptUtil() scriptUtil.createFromList([ x for xs in [[(x >> i & 0xff) / 255.0 for i in (24, 16, 8, 0)] for x in vertexColors] for x in xs ], len(vertexColors) * 4) vertexColorBuffer = OpenMaya.MColorArray(scriptUtil.asFloat4Ptr(), len(vertexColors)) newMesh.setVertexColors(vertexColorBuffer, vertexIndexBuffer) uvLayerCount = mesh.UVLayerCount() scriptUtil = OpenMaya.MScriptUtil() scriptUtil.createFromList([x for x in xrange(len(faces))], len(faces)) faceIndexBuffer = OpenMaya.MIntArray(scriptUtil.asIntPtr(), len(faces)) # Set a material, or default meshMaterial = mesh.Material() try: if meshMaterial is not None: cmds.sets(newMesh.fullPathName(), forceElement=("%sSG" % meshMaterial.Name())) else: cmds.sets(newMesh.fullPathName(), forceElement="initialShadingGroup") except RuntimeError: pass for i in xrange(uvLayerCount): uvLayer = mesh.VertexUVLayerBuffer(i) scriptUtil = OpenMaya.MScriptUtil() scriptUtil.createFromList([ y for xs in [ uvLayer[faces[x] * 2:faces[x] * 2 + 1] for x in xrange(len(faces)) ] for y in xs ], len(faces)) uvUBuffer = OpenMaya.MFloatArray(scriptUtil.asFloatPtr(), len(faces)) scriptUtil = OpenMaya.MScriptUtil() scriptUtil.createFromList([ 1 - y for xs in [ uvLayer[faces[x] * 2 + 1:faces[x] * 2 + 2] for x in xrange(len(faces)) ] for y in xs ], len(faces)) uvVBuffer = OpenMaya.MFloatArray(scriptUtil.asFloatPtr(), len(faces)) if i > 0: newUVName = newMesh.createUVSetWithName(("map%d" % (i + 1))) else: newUVName = newMesh.currentUVSetName() newMesh.setCurrentUVSetName(newUVName) newMesh.setUVs(uvUBuffer, uvVBuffer, newUVName) newMesh.assignUVs(faceCountBuffer, faceIndexBuffer, newUVName) maximumInfluence = mesh.MaximumWeightInfluence() if maximumInfluence > 0 and sceneSettings["importSkin"]: weightBoneBuffer = mesh.VertexWeightBoneBuffer() weightValueBuffer = mesh.VertexWeightValueBuffer() weightedBones = list({paths[x] for x in weightBoneBuffer}) weightedBonesCount = len(weightedBones) skinCluster = utilityCreateSkinCluster(newMesh, weightedBones, maximumInfluence) weightedRemap = { paths.index(x): i for i, x in enumerate(weightedBones) } clusterAttrBase = skinCluster.name() + ".weightList[%d]" clusterAttrArray = (".weights[0:%d]" % (weightedBonesCount - 1)) weightedValueBuffer = [0.0] * (weightedBonesCount) for i in xrange(vertexCount): if weightedBonesCount == 1: clusterAttrPayload = clusterAttrBase % i + ".weights[0]" weightedValueBuffer[0] = 1.0 else: clusterAttrPayload = clusterAttrBase % i + clusterAttrArray for j in xrange(maximumInfluence): weightedValueBuffer[weightedRemap[weightBoneBuffer[ j + (i * maximumInfluence)]]] = weightValueBuffer[ j + (i * maximumInfluence)] cmds.setAttr(clusterAttrPayload, *weightedValueBuffer) weightedValueBuffer = [0.0] * (weightedBonesCount) utilityStepProgress(progress) utilityEndProgress(progress)
def _getMeshData(self): maya.cmds.select(self.maya_node) selList = OpenMaya.MSelectionList() OpenMaya.MGlobal.getActiveSelectionList(selList) meshPath = OpenMaya.MDagPath() selList.getDagPath(0, meshPath) meshIt = OpenMaya.MItMeshPolygon(meshPath) meshFn = OpenMaya.MFnMesh(meshPath) dagFn = OpenMaya.MFnDagNode(meshPath) boundingBox = dagFn.boundingBox() do_color = False if meshFn.numColorSets(): do_color = True indices = [] positions = [None] * meshFn.numVertices() normals = [None] * meshFn.numVertices() colors = [None] * meshFn.numVertices() uvs = [None] * meshFn.numVertices() ids = OpenMaya.MIntArray() points = OpenMaya.MPointArray() if do_color: vertexColorList = OpenMaya.MColorArray() meshFn.getFaceVertexColors(vertexColorList) normal = OpenMaya.MVector() face_verts = OpenMaya.MIntArray() polyNormals = OpenMaya.MFloatVectorArray() meshFn.getNormals(polyNormals) uv_util = OpenMaya.MScriptUtil() uv_util.createFromList([0, 0], 2) uv_ptr = uv_util.asFloat2Ptr() while not meshIt.isDone(): meshIt.getTriangles(points, ids) meshIt.getVertices(face_verts) face_vertices = list(face_verts) for point, vertex_index in zip(points, ids): indices.append(vertex_index) pos = (point.x, point.y, point.z) face_vert_id = face_vertices.index(vertex_index) norm_id = meshIt.normalIndex(face_vert_id) norm = polyNormals[norm_id] norm = (norm.x, norm.y, norm.z) meshIt.getUV(face_vert_id, uv_ptr, meshFn.currentUVSetName()) u = uv_util.getFloat2ArrayItem(uv_ptr, 0, 0) v = uv_util.getFloat2ArrayItem(uv_ptr, 0, 1) # flip V for openGL # This fails if the the UV is exactly on the border (e.g. (0.5,1)) # but we really don't know what udim it's in for that case. if ExportSettings.vflip: v = int(v) + (1 - (v % 1)) uv = (u, v) if not positions[vertex_index]: positions[vertex_index] = pos normals[vertex_index] = norm uvs[vertex_index] = uv elif not (positions[vertex_index] == pos and normals[vertex_index] == norm and uvs[vertex_index] == uv): positions.append(pos) normals.append(norm) uvs.append(uv) indices[-1] = len(positions) - 1 if do_color: color = vertexColorList[vertex_index] colors[vertex_index] = (color.r, color.g, color.b) meshIt.next() if not len(Buffer.instances): primary_buffer = Buffer('primary_buffer') else: primary_buffer = Buffer.instances[0] if len(positions) >= 0xffff: idx_component_type = ComponentTypes.UINT else: idx_component_type = ComponentTypes.USHORT self.indices_accessor = Accessor(indices, "SCALAR", idx_component_type, 34963, primary_buffer, name=self.name + '_idx') self.indices_accessor.min_ = [0] self.indices_accessor.max_ = [len(positions) - 1] self.position_accessor = Accessor(positions, "VEC3", ComponentTypes.FLOAT, 34962, primary_buffer, name=self.name + '_pos') self.position_accessor.max_ = list(boundingBox.max())[:3] self.position_accessor.min_ = list(boundingBox.min())[:3] self.normal_accessor = Accessor(normals, "VEC3", ComponentTypes.FLOAT, 34962, primary_buffer, name=self.name + '_norm') self.texcoord0_accessor = Accessor(uvs, "VEC2", ComponentTypes.FLOAT, 34962, primary_buffer, name=self.name + '_uv')
def deform(self, block, iter, mat, multiIndex): # ################################### # get attributes # ################################### # envelope envelope = block.inputValue( OpenMayaMPx.cvar.MPxDeformerNode_envelope).asFloat() if (envelope == 0.0): return # ================================== # aOrigMesh oOrig = block.inputValue(self.aOrigMesh).asMesh() if oOrig.isNull(): return fnOrig = om.MFnMesh(oOrig) # ================================== # input[multiIndex].inputGeometry hInput = block.outputArrayValue(self.input) hInput.jumpToElement(multiIndex) hInputGeom = hInput.outputValue().child(self.inputGeom) oInputGeom = hInputGeom.asMesh() fnCurrent = om.MFnMesh(oInputGeom) # ================================== # aDisplayColors displayColors = block.inputValue(self.aDisplayColors).asBool() if (displayColors): colorBase = block.inputValue(self.aColorBase).asFloatVector() colorStretch = block.inputValue(self.aColorStretch).asFloatVector() colorSquash = block.inputValue(self.aColorSquash).asFloatVector() # ================================== # aMeasureTypeHeat measureTypeHeat = block.inputValue(self.aMeasureTypeHeat).asShort() # aMultiplyHeat aSquashMultiplyHeat aStretchMultiplyHeat multHeat = block.inputValue(self.aMultiplyHeat).asFloat() squashMultHeat = block.inputValue(self.aSquashMultiplyHeat).asFloat() stretchMultHeat = block.inputValue(self.aStretchMultiplyHeat).asFloat() if (multHeat == 0.0 or squashMultHeat == 0.0 and stretchMultHeat == 0.0): return # aMaxHeat aSquashMaxHeat aStretchMaxHeat maxHeat = block.inputValue(self.aMaxHeat).asBool() squashMaxHeat = block.inputValue(self.aSquashMaxHeat).asFloat() * -1 stretchMaxHeat = block.inputValue(self.aStretchMaxHeat).asFloat() if (squashMaxHeat == 0.0 and stretchMaxHeat == 0.0): return # aGrowHeat aSquashGrowHeat aStretchGrowHeat growHeat = block.inputValue(self.aGrowHeat).asInt() squashGrowHeat = block.inputValue(self.aSquashGrowHeat).asInt() stretchGrowHeat = block.inputValue(self.aStretchGrowHeat).asInt() # aIterationsSmoothHeat iterationsSmoothHeat = block.inputValue( self.aIterationsSmoothHeat).asInt() # aStrengthSmoothHeat strengthSmoothHeat = block.inputValue( self.aStrengthSmoothHeat).asFloat() # ================================== # aDeformationType deformationType = block.inputValue(self.aDeformationType).asShort() if (deformationType == 0): return # aIterationsSmoothDeformation iterationsSmoothDeformation = block.inputValue( self.aIterationsSmoothDeformation).asInt() # aStrengthSmoothDeformation strengthSmoothDeformation = block.inputValue( self.aStrengthSmoothDeformation).asFloat() # aTangentSpace tangentSpace = False if (deformationType == 2): tangentSpace = block.inputValue(self.aTangentSpace).asShort() # ================================== # aStretchMesh aSquashMesh if (deformationType == 2): # aStretchMesh oStretch = block.inputValue(self.aStretchMesh).asMesh() if oStretch.isNull(): return fnStretch = om.MFnMesh(oStretch) stretchPoints = om.MPointArray() fnStretch.getPoints(stretchPoints) # aSquashMesh oSquash = block.inputValue(self.aSquashMesh).asMesh() if oSquash.isNull(): return fnSquash = om.MFnMesh(oSquash) squashPoints = om.MPointArray() fnSquash.getPoints(squashPoints) # orig points origPoints = om.MPointArray() fnOrig.getPoints(origPoints) # ################################### # Gather information TODO: STORE in node (refresh button) # ################################### d_util = om.MScriptUtil() doublePtr = d_util.asDoublePtr() # orig edge lengths itEdgeOrig = om.MItMeshEdge(oOrig) edgeLengthsOrig = [] lengthSum = 0.0 while not itEdgeOrig.isDone(): itEdgeOrig.getLength(doublePtr) eachLength = d_util.getDouble(doublePtr) lengthSum += eachLength edgeLengthsOrig.append(eachLength) itEdgeOrig.next() edgeLengthAvrg = lengthSum / itEdgeOrig.count() # orig face area itPolyOrig = om.MItMeshPolygon(oOrig) polyAreasOrig = [] while not itPolyOrig.isDone(): itPolyOrig.getArea(doublePtr) eachArea = d_util.getDouble(doublePtr) polyAreasOrig.append(eachArea) itPolyOrig.next() # connected edges and vertices (and faces) connectedEdges = [] connectedPoints = [] connectedFaces = [] itPointCurrent = om.MItMeshVertex(oOrig) iaConnectedObjects = om.MIntArray() while not itPointCurrent.isDone(): # edges itPointCurrent.getConnectedEdges(iaConnectedObjects) connectedEdges.append(list(iaConnectedObjects)) # vertices itPointCurrent.getConnectedVertices(iaConnectedObjects) connectedPoints.append(list(iaConnectedObjects)) # faces itPointCurrent.getConnectedFaces(iaConnectedObjects) connectedFaces.append(list(iaConnectedObjects)) # finish itPointCurrent.next() # ################################### # Gather information per call # ################################### d_util = om.MScriptUtil() doublePtr = d_util.asDoublePtr() # current polygon area if (measureTypeHeat == 0): itPolyCurrent = om.MItMeshPolygon(oInputGeom) polyAreasCurrent = [] while not itPolyCurrent.isDone(): itPolyCurrent.getArea(doublePtr) eachArea = d_util.getDouble(doublePtr) polyAreasCurrent.append(eachArea) itPolyCurrent.next() # current edge length elif (measureTypeHeat == 1): edgeLengthsCurrent = [] itEdgeCurrent = om.MItMeshEdge(oInputGeom) while not itEdgeCurrent.isDone(): itEdgeCurrent.getLength(doublePtr) edgeLengthsCurrent.append(d_util.getDouble(doublePtr)) itEdgeCurrent.next() # current normals if (deformationType == 1): currentNormals = om.MFloatVectorArray() fnCurrent.getVertexNormals(False, currentNormals, om.MSpace.kObject) # find relevant points paPoints = om.MPointArray() ptIndices = [] ptWeights = [] while not iter.isDone(): iterIndex = iter.index() pt = iter.position() # get painted weight wPt = self.weightValue(block, multiIndex, iterIndex) if (wPt == 0.0): iter.next() continue # only store points with weights paPoints.append(pt) ptIndices.append(iterIndex) ptWeights.append(wPt) iter.next() iter.reset() # ################################### # Heat Calculation # ################################### # input: relevant points, default lengths, current lengths, edgeLengthAvrg # output: arHeat # # eachHeat =-1.0 // origLength*0 // squashed # eachHeat = 0.0 // origLength*1 // default # eachHeat = 1.0 // origLength*2 // stretched arHeat = [] for x, eachId in enumerate(ptIndices): # measure difference between orig and current currentMeasure = 0.0 origMeasure = 0.0 # faces if (measureTypeHeat == 0): for eachFace in connectedFaces[eachId]: currentMeasure += polyAreasCurrent[eachFace] origMeasure += polyAreasOrig[eachFace] eachHeat = ((currentMeasure - origMeasure) / origMeasure) # edges elif (measureTypeHeat == 1): for eachEdge in connectedEdges[eachId]: currentMeasure += edgeLengthsCurrent[eachEdge] origMeasure += edgeLengthsOrig[eachEdge] # to have similar behavior as face area multiply eachHeat = ((currentMeasure - origMeasure) / origMeasure) * 2 # # stretch and squash specific modification if (eachHeat < 0.0): eachHeat *= squashMultHeat * multHeat if (eachHeat < squashMaxHeat and maxHeat): eachHeat = squashMaxHeat elif (eachHeat > 0.0): eachHeat *= stretchMultHeat * multHeat if (eachHeat > stretchMaxHeat and maxHeat): eachHeat = stretchMaxHeat # store arHeat.append(eachHeat) # ################################### # Heat Grow # ################################### squashGrowHeat += growHeat stretchGrowHeat += growHeat if (squashGrowHeat or stretchGrowHeat): # find iteration count growIterations = squashGrowHeat if (stretchGrowHeat > growIterations): growIterations = stretchGrowHeat for y in range(growIterations): arHeatNew = list(arHeat) # loop through effected points for x, eachId in enumerate(ptIndices): strongestSquash = arHeatNew[x] strongestStretch = arHeatNew[x] # loop over neighbors for eachNeighborId in connectedPoints[eachId]: if (eachNeighborId in ptIndices): eachNeighborHeat = arHeat[ptIndices.index( eachNeighborId)] if (eachNeighborHeat < strongestSquash): strongestSquash = eachNeighborHeat if (eachNeighborHeat > strongestStretch): strongestStretch = eachNeighborHeat # set proper value if (squashGrowHeat > y and stretchGrowHeat > y): newValue = 0.0 if (strongestSquash < 0.0): newValue = strongestSquash if (strongestStretch > 0.0): newValue += strongestStretch if (newValue): arHeatNew[x] = newValue elif (squashGrowHeat > y and strongestSquash < 0.0): if (arHeatNew[x] > 0.0): arHeatNew[x] += strongestSquash else: arHeatNew[x] = strongestSquash elif (stretchGrowHeat > y and strongestStretch > 0.0): if (arHeatNew[x] < 0.0): arHeatNew[x] += strongestStretch else: arHeatNew[x] = strongestStretch arHeat = arHeatNew # # ################################### # Heat Smooth # ################################### # input: arHeat # output: arHeat for y in range(iterationsSmoothHeat): arHeatNew = list(arHeat) for x, eachId in enumerate(ptIndices): neighborIds = connectedPoints[eachId] neighborAvrg = 0.0 validNeighbor = False for eachNeighborId in neighborIds: if (eachNeighborId in ptIndices): validNeighbor = True neighborAvrg += arHeat[ptIndices.index(eachNeighborId)] if (validNeighbor): neighborAvrg /= len(neighborIds) arHeatNew[x] = arHeatNew[x] * ( 1.0 - strengthSmoothHeat) + neighborAvrg * strengthSmoothHeat arHeat = arHeatNew # ################################### # Heat Display # ################################### # input: arHeat # result: vertexColors if (displayColors): colorList = om.MColorArray() indexList = om.MIntArray() for x, eachId in enumerate(ptIndices): # colorBase colorStretch colorSquash eachColor = om.MFloatVector(colorBase) if (arHeat[x] > 0.0): eachColor += (colorStretch - eachColor) * (arHeat[x]) elif (arHeat[x] < 0.0): eachColor += (colorSquash - eachColor) * (arHeat[x] * -1) colorList.append( om.MColor(eachColor.x, eachColor.y, eachColor.z, 1.0)) indexList.append(eachId) #fnCurrent.setVertexColor( om.MColor(eachColor.x, eachColor.y, eachColor.z), eachId )# (setting all at once is faster) fnCurrent.setVertexColors(colorList, indexList) # ################################### # Deformation Calculation # ################################### # input: heatArray # output: motionVectorArray arVectors = [] for x, eachId in enumerate(ptIndices): eachHeat = arHeat[x] vecMove = om.MVector() # skip calculation for 0.0 heat if (eachHeat == 0.0): arVectors.append(vecMove) continue # ################################### # Normal # ################################### if (deformationType == 1): # normal deformation vecMove += om.MVector( currentNormals[eachId]) * (eachHeat * -1) * edgeLengthAvrg # ################################### # BlendShape # ################################### if (deformationType == 2): if (eachHeat < 0.0): targetPt = squashPoints[eachId] vecMove += (targetPt - origPoints[eachId]) * (eachHeat * -1) elif (eachHeat > 0.0): targetPt = stretchPoints[eachId] vecMove += (targetPt - origPoints[eachId]) * (eachHeat) # tangent spaces if (tangentSpace): matTangentOrig = getTangentSpace(tangentSpace, fnOrig, eachId, connectedFaces[eachId]) matTangentCurrent = getTangentSpace( tangentSpace, fnCurrent, eachId, connectedFaces[eachId]) vecMove *= matTangentOrig.inverse() * matTangentCurrent # # save vector arVectors.append(vecMove) # ################################### # Deformation Smooth # ################################### # input: motionVectorArray # result: motionVectorArray for x in range(iterationsSmoothDeformation): arVectorsNew = list(arVectors) for x, eachId in enumerate(ptIndices): neighborIds = connectedPoints[eachId] neighborAvrg = om.MVector() validNeighbor = False for eachNeighborId in neighborIds: if (eachNeighborId in ptIndices): validNeighbor = True neighborAvrg += arVectors[ptIndices.index( eachNeighborId)] if (validNeighbor): neighborAvrg /= len(neighborIds) arVectorsNew[x] = arVectorsNew[x] * ( 1.0 - strengthSmoothDeformation ) + neighborAvrg * strengthSmoothDeformation arVectors = arVectorsNew # ################################### # Deformation # ################################### # input: motionVectorArray, weights # result: deformed mesh counter = 0 while not iter.isDone(): if (iter.index() in ptIndices): iter.setPosition(paPoints[counter] + arVectors[counter] * ptWeights[counter] * envelope) counter += 1 iter.next()
def _getMeshData(self): maya.cmds.select(self.maya_node) selList = OpenMaya.MSelectionList() OpenMaya.MGlobal.getActiveSelectionList(selList) meshPath = OpenMaya.MDagPath() selList.getDagPath(0, meshPath) meshIt = OpenMaya.MItMeshPolygon(meshPath) meshFn = OpenMaya.MFnMesh(meshPath) do_color = False if meshFn.numColorSets(): do_color = True print "doing color" indices = [] positions = [None] * meshFn.numVertices() normals = [None] * meshFn.numVertices() all_colors = [None] * meshFn.numVertices() uvs = [None] * meshFn.numVertices() ids = OpenMaya.MIntArray() tracker = {} points = OpenMaya.MPointArray() if do_color: vertexColorList = OpenMaya.MColorArray() meshFn.getFaceVertexColors(vertexColorList) #meshIt.hasUVs() normal = OpenMaya.MVector() face_verts = OpenMaya.MIntArray() polyNormals = OpenMaya.MFloatVectorArray() meshFn.getNormals(polyNormals) uv_util = OpenMaya.MScriptUtil() uv_util.createFromList([0, 0], 2) uv_ptr = uv_util.asFloat2Ptr() bbox = BoundingBox() while not meshIt.isDone(): meshIt.getTriangles(points, ids) #meshIt.getUVs(u_list, v_list) meshIt.getVertices(face_verts) for x in range(0, ids.length()): indices.append(ids[x]) pos = (points[x].x, points[x].y, points[x].z) local_vert_id = getFaceVertexIndex(face_verts, ids[x]) #print "local vert:", local_vert_id norm_id = meshIt.normalIndex(local_vert_id) #meshIt.getNormal(local_vert_id, normal) normal = polyNormals[norm_id] norm = (normal.x, normal.y, normal.z) #print norm meshIt.getUV(local_vert_id, uv_ptr, meshFn.currentUVSetName()) u = uv_util.getFloat2ArrayItem(uv_ptr, 0, 0) v = uv_util.getFloat2ArrayItem(uv_ptr, 0, 1) # flip V for openGL # This fails if the the UV is exactly on the border (e.g. (0.5,1)) # but we really don't know what udim it's in for that case. if ExportSettings.vflip: v = int(v) + (1 - (v % 1)) uv = (u, v) # using a string IDs + dictionary for quick # tracking of pos/norm/uv combo's that we've seen. comp_str = '{},{},{}:{},{},{}:{},{}'.format( pos[0], pos[1], pos[2], norm[0], norm[1], norm[2], uv[0], uv[1]) if not positions[ids[x]]: positions[ids[x]] = pos normals[ids[x]] = norm uvs[ids[x]] = uv tracker[comp_str] = ids[x] elif not (positions[ids[x]] == pos and normals[ids[x]] == norm and uvs[ids[x]] == uv): matched = False if (hasattr(tracker, comp_str)): matched = True indices[-1] = tracker[comp_str] break if not matched: positions.append(pos) normals.append(norm) uvs.append(uv) indices[-1] = len(positions) - 1 if do_color: color = vertexColorList[ids[x]] all_colors[ids[x]] = (color.r, color.g, color.b) if points[x].x > bbox.xmax: bbox.xmax = points[x].x elif points[x].y > bbox.ymax: bbox.ymax = points[x].y elif points[x].z > bbox.zmax: bbox.zmax = points[x].z elif points[x].x < bbox.xmin: bbox.xmin = points[x].x elif points[x].y < bbox.ymin: bbox.ymin = points[x].y elif points[x].z < bbox.zmin: bbox.zmin = points[x].z meshIt.next() if not len(Buffer.instances): primary_buffer = Buffer('primary_buffer') else: primary_buffer = Buffer.instances[0] if len(positions) >= 0xffff: idx_component_type = 5125 else: idx_component_type = 5123 self.indices_accessor = Accessor(indices, "SCALAR", idx_component_type, 34963, primary_buffer, name=self.name + '_idx') self.indices_accessor.min = [0] self.indices_accessor.max = [len(positions) - 1] self.position_accessor = Accessor(positions, "VEC3", 5126, 34962, primary_buffer, name=self.name + '_pos') self.position_accessor.max = [bbox.xmax, bbox.ymax, bbox.zmax] self.position_accessor.min = [bbox.xmin, bbox.ymin, bbox.zmin] self.normal_accessor = Accessor(normals, "VEC3", 5126, 34962, primary_buffer, name=self.name + '_norm') self.texcoord0_accessor = Accessor(uvs, "VEC2", 5126, 34962, primary_buffer, name=self.name + '_uv')
#Accelerator. mmAccelParams = collider_MfnMesh.autoUniformGridParams() #Get points. source_MfnMesh = OpenMaya.MFnMesh(source_mDagPath) source_Pnts = OpenMaya.MFloatPointArray() source_MfnMesh.getPoints(source_Pnts, OpenMaya.MSpace.kWorld) #Defining used variables. checkCollision = 0 maxDeformation = 0.0 dummyFloatArray = OpenMaya.MFloatArray() source_pntNormal = OpenMaya.MVector() #Get Vertex color. vertexColorList = OpenMaya.MColorArray() source_MfnMesh.getVertexColors(vertexColorList) collideColor = OpenMaya.MColor(1.0, 0.0, 0.0, 1.0) lenVertexList = vertexColorList.length() #Get Vert list. fnComponent = OpenMaya.MFnSingleIndexedComponent() fullComponent = fnComponent.create(OpenMaya.MFn.kMeshVertComponent) fnComponent.setCompleteData(lenVertexList) vertexIndexList = OpenMaya.MIntArray() fnComponent.getElements(vertexIndexList) # direct collision deformation: for k in xrange(source_Pnts.length()): source_MfnMesh.getVertexNormal(k, source_pntNormal, OpenMaya.MSpace.kWorld)
def deform(self, dataBlock, geoIterator, matrix, geometryIndex): input = OpenMayaMPx.cvar.MPxDeformerNode_input # attach a handle to input Array Attribute # prevent recomputation dataHandleInputArray = dataBlock.outputArrayValue(input) #jump to particular element dataHandleInputArray.jumpToElement(geometryIndex) #attach a handle to specific data block dataHandleInputElement = dataHandleInputArray.outputValue() #reach to the child inputGeom = OpenMayaMPx.cvar.MPxDeformerNode_inputGeom dataHandleInputGeom = dataHandleInputElement.child(inputGeom) inMesh = dataHandleInputGeom.asMesh() #envelope envolope = OpenMayaMPx.cvar.MPxDeformerNode_envelope dataHandleEnvelope = dataBlock.inputValue(envolope) envolopeValue = dataHandleEnvelope.asFloat() #amplitude dataHandleAmplitude = dataBlock.inputValue(rippleDeformer.amplitude) amplitudeValue = dataHandleAmplitude.asFloat() #displace dataHandleDisplace = dataBlock.inputValue(rippleDeformer.displacement) displaceValue = dataHandleDisplace.asFloat() #matrix dataHandleMatrix = dataBlock.inputValue(rippleDeformer.matrix) MatrixValue = dataHandleMatrix.asMatrix() #read translation from Matrix mTransMatrix = OpenMaya.MTransformationMatrix(MatrixValue) translationValue = mTransMatrix.getTranslation(OpenMaya.MSpace.kObject) #mEulerRot = OpenMaya.MVector() #mEulerRot = mTransMatrix.eulerRotation().asVector() mFloatVectorArray_Normal = OpenMaya.MFloatVectorArray() inMeshMfn = OpenMaya.MFnMesh(inMesh) inMeshMfn.getVertexNormals(False, mFloatVectorArray_Normal, OpenMaya.MSpace.kObject) #create colorSet inMeshMfn.createColorSetDataMesh('vertexColorSet') inMeshMfn.setIsColorClamped('vertexColorSet', True) mPointArray_meshVert = OpenMaya.MPointArray() mColorArray_meshVert = OpenMaya.MColorArray() mVertexArray_meshVert = OpenMaya.MIntArray() while (not geoIterator.isDone()): pointPosition = geoIterator.position() weight = self.weightValue(dataBlock, geometryIndex, geoIterator.index()) #inMeshMfn.setVertexColor(pointColor, geoIterator.index(),None,OpenMaya.MFnMesh.kRGBA) pointPosition.x = pointPosition.x + math.sin( geoIterator.index() + displaceValue + translationValue[0] ) * amplitudeValue * envolopeValue * mFloatVectorArray_Normal[ geoIterator.index()].x * weight pointPosition.y = pointPosition.y + math.sin( geoIterator.index() + displaceValue + translationValue[0] ) * amplitudeValue * envolopeValue * mFloatVectorArray_Normal[ geoIterator.index()].y * weight pointPosition.z = pointPosition.z + math.sin( geoIterator.index() + displaceValue + translationValue[0] ) * amplitudeValue * envolopeValue * mFloatVectorArray_Normal[ geoIterator.index()].z * weight mPointArray_meshVert.append(pointPosition) #paint vertex color Color_R = math.sin(geoIterator.index() + displaceValue) * amplitudeValue Color_G = math.cos(geoIterator.index() + displaceValue) * amplitudeValue Color_B = math.sin(geoIterator.index() - displaceValue) * amplitudeValue pointColor = OpenMaya.MColor(Color_R, Color_G, Color_B, 1.0) mColorArray_meshVert.append(pointColor) mVertexArray_meshVert.append(geoIterator.index()) geoIterator.next() #optimize performance geoIterator.setAllPositions(mPointArray_meshVert) inMeshMfn.setVertexColors(mColorArray_meshVert, mVertexArray_meshVert, None, OpenMaya.MFnMesh.kRGBA) #set current colorset #inMeshMfn.setCurrentColorSetDataMesh('vertexColorSet') if (not cmds.polyColorSet(ccs=True, q=True) == 'vertexColorSet'): cmds.polyColorSet(ccs=True, cs='vertexColorSet')