Python maya.OpenMaya.MFnMesh() Examples

The following are 17 code examples of maya.OpenMaya.MFnMesh(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module maya.OpenMaya , or try the search function .
Example #1
Source File: mesh_utils.py    From spore with MIT License 6 votes vote down vote up
def get_mesh_fn(target):
    """ get mesh function set for the given target
    :param target: dag path of the mesh
    :return MFnMesh """

    if isinstance(target, str) or isinstance(target, unicode):
        slls = om.MSelectionList()
        slls.add(target)
        ground_path = om.MDagPath()
        slls.getDagPath(0, ground_path)
        ground_path.extendToShapeDirectlyBelow(0)
        ground_node = ground_path.node()
    elif isinstance(target, om.MObject):
        ground_node = target
        ground_path = target
    elif isinstance(target, om.MDagPath):
        ground_node = target.node()
        ground_path = target
    else:
        raise TypeError('Must be of type str, MObject or MDagPath, is type: {}'.format(type(target)))

    if ground_node.hasFn(om.MFn.kMesh):
        return om.MFnMesh(ground_path)
    else:
        raise TypeError('Target must be of type kMesh') 
Example #2
Source File: mesh.py    From maya-skinning-tools with GNU General Public License v3.0 6 votes vote down vote up
def getNormals(dag):
    """
    Get the average normal in world space of each vertex on the provided mesh.
    The reason why OpenMaya.MItMeshVertex function has to be used is that the
    MFnMesh class returns incorrect normal results.

    :param OpenMaya.MDagPath dag:
    :return: Normals
    :rtype: list
    """
    # variables
    normals = []

    iter = OpenMaya.MItMeshVertex(dag)
    while not iter.isDone():
        # get normal data
        normal = OpenMaya.MVector()
        iter.getNormal(normal, OpenMaya.MSpace.kWorld)
        normals.append(normal)

        iter.next()

    return normals 
Example #3
Source File: rig.py    From fossil with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def intersect(mesh, point, ray):
    fnMesh = OpenMaya.MFnMesh( core.capi.asMObject(mesh.getShape()).object() )

    p = spaceLocator()
    p.t.set(point)
    p.setParent( mesh )
    
    objSpacePos = p.t.get()

    p.setTranslation( ray, space='world' )

    objSpaceRay = p.t.get() - objSpacePos
    
    point = OpenMaya.MFloatPoint(objSpacePos)
    ray = OpenMaya.MFloatVector(objSpaceRay)
    res = fnMesh.allIntersections(point, ray, OpenMaya.MSpace.kObject, 50, False )

    # -> (hitPoints, hitRayParams, hitFaces, hitTriangles, hitBary1s, hitBary2s)

    if not len(res[0]):
        hits = []
    
    else:
        hits = []
        for hit in res[0]:
            p.t.set( hit.x, hit.y, hit.z)
            hits.append( p.getTranslation(space='world') )
    
    delete(p)
    
    return hits 
Example #4
Source File: geo_cache.py    From spore with MIT License 5 votes vote down vote up
def create_uv_lookup(self):
        """ create a dict with an entry for every vertex and a list of
        neighbouring faces as well as a kd tree tro look up close face ids """

        self.logger.debug('Create UV lookup for the current GeoCache')

        util = om.MScriptUtil()
        connected_faces = om.MIntArray()

        mesh_fn = om.MFnMesh(self.mesh)
        num_verts = mesh_fn.numVertices()
        points = np.zeros(shape=(num_verts, 2))

        vert_iter = om.MItMeshVertex(self.mesh)
        while not vert_iter.isDone():

            index = vert_iter.index()
            vert_iter.getConnectedFaces(connected_faces)
            self.neighbor_lookup[index] = [connected_faces[i] for i in xrange(connected_faces.length())]

            util.createFromDouble(0.0, 0.0)
            uv_ptr = util.asFloat2Ptr()
            vert_iter.getUV(uv_ptr)
            u_coord = util.getFloat2ArrayItem(uv_ptr, 0, 0)
            v_coord = util.getFloat2ArrayItem(uv_ptr, 0, 1)
            points[index] = (u_coord, v_coord)

            vert_iter.next()

        self.uv_kd_tree = kd_tree(points) 
Example #5
Source File: maya_PasteFromExternal.py    From OD_CopyPasteExternal with Apache License 2.0 5 votes vote down vote up
def fn_createObject_openMaya():
    global importedObj

    cmds.select( all = True, hierarchy = True)
    currentObjs = cmds.ls(selection = True )

    newMesh = om.MFnMesh()

    mergeVertices = True
    pointTolerance = 0.0001

    for p in range(0, len(importedObj.polys), 1):
        polylist = []
        vCount = len(importedObj.polys[p])
        polylist = om.MPointArray()
        polylist.setLength(vCount)
        for i in range(vCount):
            polylist.set(importedObj.omVertices[int(importedObj.polys[p][i])], i)

        newMesh.addPolygon(polylist, mergeVertices, pointTolerance)


    if len(importedObj.weightMap) > 0:
        for v in range(0, importedObj.vertexCount , 1):
            c = importedObj.weightMap[v]
            vColor = om.MColor(c,c,c,c )
            newMesh.setVertexColor(vColor,v)

    newMesh.updateSurface()

    cmds.select( all = True, hierarchy = True)
    cmds.select(currentObjs, deselect = True)
    newObjs = cmds.ls(selection = True, transforms = True )
    cmds.select(newObjs, replace = True)
    cmds.sets( newObjs, e=True,forceElement='initialShadingGroup')
    cmds.rename (newObjs, importObjectName) 
Example #6
Source File: currentUVSet.py    From medic with MIT License 5 votes vote down vote up
def test(self, node):
        mesh = None
        try:
            mesh = OpenMaya.MFnMesh(node.object())
        except:
            return None

        if mesh.currentUVSetName() != CurrentUVSet.__DefaultSetName:
            return medic.PyReport(node)

        return None 
Example #7
Source File: mesh.py    From maya-skinning-tools with GNU General Public License v3.0 5 votes vote down vote up
def getPoints(dag):
    """
    Get the position in world space of each vertex on the provided mesh.

    :param OpenMaya.MDagPath dag:
    :return: Points
    :rtype: list
    """
    points = OpenMaya.MPointArray()
    mesh = OpenMaya.MFnMesh(dag)
    mesh.getPoints(points, OpenMaya.MSpace.kWorld)

    return [OpenMaya.MVector(points[i]) for i in range(points.length())] 
Example #8
Source File: meshNavigation.py    From mgear_core with MIT License 5 votes vote down vote up
def getClosestPolygonFromTransform(geo, loc):
    """Get closest polygon from transform

    Arguments:
        geo (dagNode): Mesh object
        loc (matrix): location transform

    Returns:
        Closest Polygon

    """
    if isinstance(loc, pm.nodetypes.Transform):
        pos = loc.getTranslation(space='world')
    else:
        pos = datatypes.Vector(loc[0], loc[1], loc[2])

    nodeDagPath = OpenMaya.MObject()
    try:
        selectionList = OpenMaya.MSelectionList()
        selectionList.add(geo.name())
        nodeDagPath = OpenMaya.MDagPath()
        selectionList.getDagPath(0, nodeDagPath)
    except Exception as e:
        raise RuntimeError("OpenMaya.MDagPath() failed "
                           "on {}. \n {}".format(geo.name(), e))

    mfnMesh = OpenMaya.MFnMesh(nodeDagPath)

    pointA = OpenMaya.MPoint(pos.x, pos.y, pos.z)
    pointB = OpenMaya.MPoint()
    space = OpenMaya.MSpace.kWorld

    util = OpenMaya.MScriptUtil()
    util.createFromInt(0)
    idPointer = util.asIntPtr()

    mfnMesh.getClosestPoint(pointA, pointB, space, idPointer)
    idx = OpenMaya.MScriptUtil(idPointer).asInt()

    return geo.f[idx], pos 
Example #9
Source File: utils.py    From maya-retarget-blendshape with GNU General Public License v3.0 5 votes vote down vote up
def asMFnMesh(dag):
    """
    OpenMaya.MDagPath -> OpenMaya.MfnMesh

    :param OpenMaya.MDagPath dag:
    :rtype: OpenMaya.MfnMesh
    """
    
    return OpenMaya.MFnMesh(dag) 
Example #10
Source File: node_utils.py    From spore with MIT License 5 votes vote down vote up
def get_meshfn_from_dagpath(dagpath):
    """ return a functionset for a specified dagpath
    :param dagpath : input dagpath """

    m_dagpath = get_dagpath_from_name(dagpath)
    return om.MFnMesh(m_dagpath) 
Example #11
Source File: ViewportPainter.py    From mViewportDrawOpenGL with MIT License 4 votes vote down vote up
def getMouseIntersect(self):

        sourcePnt = OpenMaya.MPoint(0,0,0)
        rayDir = OpenMaya.MVector(0,0,0)
        maximumDistance = 9999999999
        viewHeight = self.view3D.portHeight()
        
        hitNormal = OpenMaya.MVector()
        
        intersectedObject = None
        intersectedPoint = OpenMaya.MFloatPoint()
        intersectedFace = 0

        hitFace = OpenMaya.MScriptUtil()
        hitFace.createFromInt(0)
        hitFacePtr = hitFace.asIntPtr()

        hitDistance = OpenMaya.MScriptUtil(0.0)
        hitDistancePtr = hitDistance.asFloatPtr()

        self.view3D.viewToWorld(int(self.userMouseEvents.M_posX), int(viewHeight - self.userMouseEvents.M_posY), sourcePnt, rayDir)

        
        direction = OpenMaya.MFloatVector(rayDir.x, rayDir.y, rayDir.z).normal()

        iter = OpenMaya.MItDependencyNodes(OpenMaya.MFn.kMesh)

        while not iter.isDone():

            node =iter.thisNode()
            dagPath = OpenMaya.MDagPath.getAPathTo(node)

            hitPoint = OpenMaya.MFloatPoint()
            source = OpenMaya.MFloatPoint(sourcePnt.x, sourcePnt.y, sourcePnt.z)
            direction = OpenMaya.MFloatVector(direction.x,direction.y,direction.z)

            if dagPath.isVisible():
                mesh = OpenMaya.MFnMesh(dagPath)
                intersected = mesh.closestIntersection(source, direction, None, None, False, OpenMaya.MSpace.kWorld, 9999999999, True, None, hitPoint, hitDistancePtr, hitFacePtr, None, None, None, 0.0001)
                
                if intersected:
                    intersectionDistance = hitDistance.getFloat(hitDistancePtr)
                    if intersectionDistance < maximumDistance:
                        maximumDistance = intersectionDistance
                        intersectedPoint = hitPoint
                        intersectedFace =  OpenMaya.MScriptUtil(hitFacePtr).asInt()
                        mesh.getClosestNormal(OpenMaya.MPoint(intersectedPoint),hitNormal,OpenMaya.MSpace.kWorld)
                        intersectedObject = dagPath.fullPathName()

            iter.next()

        if intersectedPoint.x + intersectedPoint.y + intersectedPoint.z == 0:
            return None, None, None
        else:
            return intersectedPoint, intersectedFace, intersectedObject 
Example #12
Source File: oyCenterOfMass.py    From anima with MIT License 4 votes vote down vote up
def compute(self, plug, dataBlock):
        
        if plug == oyCenterOfMass.aCOMPos:
            
            # get the mesh vertices for time from start to end
            
            # get the meshes
            arrayDataHandle = dataBlock.inputArrayValue( oyCenterOfMass.aObjectList )
            numOfConnections = arrayDataHandle.elementCount()
            
            inputDataHandle = OpenMaya.MDataHandle()
            inputGeometryDataHandle = OpenMaya.MDataHandle()
            
            mesh = OpenMaya.MObject()
            meshList = OpenMaya.MObjectArray()
            
            for i in range(numOfConnections):
                arrayDataHandle.jumpToElement(i)
                
                inputDataHandle = arrayDataHandle.inputValue()
                inputGeometryDataHandle = inputDataHandle.child( oyCenterOfMass.aObjectList )
                
                mesh = inputGeometryDataHandle.asMesh()
                
                if mesh.hasFn( OpenMaya.MFn.kMesh ):
                    meshList.append( mesh )
            
            
            numOfMesh = meshList.length()
            
            # return if no mesh
            if numOfMesh == 0:
                return OpenMaya.MStatus.kSuccess
            
            # read the mesh vertices in to one big array
            verticesOfOneMesh = OpenMaya.MPointArray()
            allVertices = OpenMaya.MPointArray()
            
            meshFn = OpenMaya.MFnMesh()
            
            for i in range(numOfMesh):
                meshFn.getPoints ( verticesOfOneMesh, OpenMaya.MSpace.kWorld )
                
                for j in range(verticesOfOneMesh.length()):
                    allVertices.append( verticesOfOneMesh[j] )
                
            
            
            
            
            
            
            
            # set the time
            
            return OpenMaya.MStatus.kSuccess
        else:
            return OpenMaya.kUnknownParameter 
Example #13
Source File: randomizeUVDeformer.py    From anima with MIT License 4 votes vote down vote up
def deform(self, data_block, geometry_iterator, local_to_world_matrix, geometry_index):
        """do deformation
        """
        envelope_attribute = OpenMayaMPx.cvar.MPxDeformerNode_envelope
        envelope_value = data_block.inputValue(envelope_attribute).asFloat()

        input_geometry_object = \
            self.get_deformer_input_geometry(data_block, geometry_index)

        # Obtain the list of normals for each vertex in the mesh.
        mesh_fn = OpenMaya.MFnMesh(input_geometry_object)

        uv_shell_array = OpenMaya.MIntArray()
        u_array = OpenMaya.MFloatArray()
        v_array = OpenMaya.MFloatArray()
        script_util = OpenMaya.MScriptUtil(0)
        shells_ptr = script_util.asUintPtr()

        mesh_fn.getUvShellsIds(uv_shell_array, shells_ptr)
        mesh_fn.getUVs(u_array, v_array)

        max_offset_attr_handle = \
            data_block.inputValue(RandomizeDeformer.aMaxOffset)
        max_offset = max_offset_attr_handle.asInt()

        # compute and write the new uvs
        for uv_id in xrange(len(u_array)):
            shell_id = uv_shell_array[uv_id]
            offset_u = shell_id % max_offset
            u_array[uv_id] += offset_u

        mesh_fn.setUVs(u_array, v_array)

        uv_shell_array.clear()
        u_array.clear()
        v_array.clear()

        # # Iterate over the vertices to move them.
        # while not geometry_iterator.isDone():
        #     # Obtain the vertex normal of the geometry.
        #     # This normal is the vertex's averaged normal value if that
        #     # vertex is shared among several polygons.
        #     vertex_index = geometry_iterator.index()
        #     normal = OpenMaya.MVector(normals[vertex_index])
        #  Cast the MFloatVector into a simple vector.
        #
        #     # Increment the point along the vertex normal.
        #     point = geometry_iterator.position()
        #     newPoint = \
        #         point + (normal * vertexIncrement * meshInflation * envelopeValue)
        #
        #     # Clamp the new point within the bounding box.
        #     self.clampPointInBoundingBox(newPoint, boundingBox)
        #
        #     # Set the position of the current vertex to the new point.
        #     geometry_iterator.setPosition(newPoint)
        #
        #     # Jump to the next vertex.
        #     geometry_iterator.next() 
Example #14
Source File: flatten.py    From cmt with MIT License 4 votes vote down vote up
def flatten(mesh=None, uvset=None):
    """Creates a mesh from the UV layout of another mesh.

    I use this to generate flattened versions of meshes from Marvelous Designer to easily use Quad
    Draw to create clean meshes and then Transfer Attributes vertex positions through UVs.

    :param mesh: Mesh to sample.
    :param uvset: UV set name
    """
    if mesh is None:
        mesh = cmds.ls(sl=True)
        if not mesh:
            raise RuntimeError("No mesh selected.")
        mesh = mesh[0]
    o_mesh = shortcuts.get_mobject(shortcuts.get_shape(mesh))
    fn_mesh = OpenMaya.MFnMesh(o_mesh)
    if uvset is None:
        uvset = fn_mesh.currentUVSetName()

    vertex_count = fn_mesh.numUVs(uvset)
    polygon_count = fn_mesh.numPolygons()
    u_array = OpenMaya.MFloatArray()
    v_array = OpenMaya.MFloatArray()
    fn_mesh.getUVs(u_array, v_array, uvset)
    vertex_array = OpenMaya.MPointArray(u_array.length())
    for i in range(u_array.length()):
        vertex_array.set(i, u_array[i], 0, -v_array[i])
    polygon_counts = OpenMaya.MIntArray(polygon_count)

    it_poly = OpenMaya.MItMeshPolygon(o_mesh)
    polygon_connects = OpenMaya.MIntArray(fn_mesh.numFaceVertices())
    face_vertex_index = 0
    while not it_poly.isDone():
        face_index = it_poly.index()
        polygon_counts[face_index] = it_poly.polygonVertexCount()

        for i in range(polygon_counts[face_index]):
            int_ptr = shortcuts.get_int_ptr()
            it_poly.getUVIndex(i, int_ptr)
            uv_index = shortcuts.ptr_to_int(int_ptr)
            polygon_connects[face_vertex_index] = uv_index
            face_vertex_index += 1
        it_poly.next()

    new_mesh = OpenMaya.MFnMesh()
    new_mesh.create(
        vertex_count,
        polygon_count,
        vertex_array,
        polygon_counts,
        polygon_connects,
        u_array,
        v_array,
    )
    new_mesh.assignUVs(polygon_counts, polygon_connects) 
Example #15
Source File: pushDeformer.py    From AdvancedPythonForMaya with GNU General Public License v3.0 4 votes vote down vote up
def deform(self, data, geoIterator, matrix, geometryIndex):

        # Get the push value
        pushHandle = data.inputValue(self.push)
        push = pushHandle.asFloat()

        # get the envelope value
        envelopeHandle = data.inputValue(envelopeAttr)
        envelope = envelopeHandle.asFloat()

        # Get the input geometry
        mesh = self.getInputMesh(data, geometryIndex)

        # Create an empty array(list) of Float Vectors to store our normals in
        normals = om.MFloatVectorArray()
        # Then make the meshFn to interact with the mesh
        meshFn = om.MFnMesh(mesh)
        # And we use this to get and store the normals from the mesh onto the normals array we created above
        # Remember to pay attention to the pluralization of normals
        meshFn.getVertexNormals(
            True, # If True, the normals are angleWeighted which is what we want
            normals, # We tell it what to store the data in, in this case our array above,
            om.MSpace.kTransform # Finally we tell it what space we want the normals in, in this case the local object space
        )

        # Now we can iterate through the geometry vertices and do our deformation
        while not geoIterator.isDone():
            # Get the index of our current point
            index = geoIterator.index()
            # Look up the normals for this point from our array
            normal = om.MVector(normals[index])
            # Get the position of the point
            position = geoIterator.position()
            # Then calculate the offset
            # we do this by multiplying the magnitude of the normal vector by the intensity of the push and envelope
            offset = (normal * push * envelope)

            # We then query the painted weight for this area
            weight = self.weightValue(data, geometryIndex, index)
            offset = (offset * weight)

            # Finally we can set the position
            geoIterator.setPosition(position+offset)
            # And always remember to go on to the next item in the list
            geoIterator.next() 
Example #16
Source File: greenCageDeformer.py    From maya_greenCageDeformer with MIT License 4 votes vote down vote up
def __init__(self, meshData, baseInfo=None):
        self._meshData = meshData
        fn = MFnMesh(meshData)

        # 頂点座標リストを生成。各要素は API 2.0 の MVector とする。
        pntArr = MFloatPointArray()
        fn.getPoints(pntArr)
        nVrts = pntArr.length()
        if baseInfo and baseInfo[0] != nVrts:
            # ベースケージと頂点数が合わない場合は無効とする。
            self._vertices = None
            return
        vertices = _NONE_LIST * nVrts
        for i in xrange(nVrts):
            p = pntArr[i]
            vertices[i] = api2_MVector(p.x, p.y, p.z)
        #_pprt(vertices)
        self._vertices = vertices

        # ベースケージの場合はトライアングル情報を構築する。
        # トライアングルリストを生成。各要素は3頂点のインデクスリストとする。
        if baseInfo:
            triangles = baseInfo[1]
            self._triRestEdges = baseInfo[2]
            self._triRestAreas = baseInfo[3]
        else:
            triCounts = MIntArray()
            triVrts = MIntArray()
            fn.getTriangles(triCounts, triVrts)
            nPlys = triCounts.length()
            #print(triCounts.length(), triVrts.length())
            triangles = []
            vi = 0
            for i in xrange(nPlys):
                for j in range(triCounts[i]):
                    triangles.append([triVrts[k] for k in range(vi, vi + 3)])
                    vi += 3
            #_pprt(triangles)
        self._triangles = triangles

        # トライアングルのエッジベクトルを計算。
        self._triEdges = [(vertices[tri[1]] - vertices[tri[0]], vertices[tri[2]] - vertices[tri[1]]) for tri in triangles]

        # トライアングルの法線ベクトルを計算。
        self._triNrms = [(u ^ v).normalize() for u, v in self._triEdges]

        # ベースケージの場合はトライアングルの面積を計算。変形ケージでは不要。
        if not baseInfo:
            self._triAreas = [(u ^ v).length() * .5 for u, v in self._triEdges] 
Example #17
Source File: geo_cache.py    From spore with MIT License 4 votes vote down vote up
def validate_cache(self):
        """ check if the current cache is valid """

        points = om.MPointArray()
        mesh_fn = om.MFnMesh(self.mesh)
        mesh_fn.getPoints(points)

        if points.length() != self.poly_verts.length():
            self.logger.debug('Validate GeoCache succeded')
            return False

        for i in xrange(points.length()):
            if points[i] != self.poly_verts[i]:
                self.logger.debug('Validate GeoCache failed')
                return False

        return True


        """
        index = 0
        tri_points = om.MPointArray()
        tri_ids = om.MIntArray()
        poly_iter = om.MItMeshPolygon(self.mesh)
        while not poly_iter.isDone():

            # get face triangles
            poly_index = poly_iter.index()
            poly_iter.getTriangles(tri_points, tri_ids, om.MSpace.kWorld)

            # get triangle data
            for i in xrange(tri_points.length() / 3):
                #  assert self.p0[i * 3] == tri_points[i * 3]
                #  assert self.p1[i * 3 + 1] == tri_points[i * 3 + 1]
                #  assert self.p2[i * 3 + 2] == tri_points[i * 3 + 2]
                print self.p0[i*3].x, tri_points[i*3].x
                print self.p0[i*3].y, tri_points[i*3].y
                print self.p0[i*3].z, tri_points[i*3].z
                print '-'
                print self.p0[i*3+1].x, tri_points[i*3+1].x
                print self.p0[i*3+1].y, tri_points[i*3+1].y
                print self.p0[i*3+1].z, tri_points[i*3+1].z
                print '-'
                print self.p0[i*3+2].x, tri_points[i*3+2].x
                print self.p0[i*3+2].y, tri_points[i*3+2].y
                print self.p0[i*3+2].z, tri_points[i*3+2].z
                #  except AssertionError:
                #      return False

                index += 1

            poly_iter.next()

        return True
        """



    ################################################################################################
    # cache property
    ################################################################################################