top of page

Get Closest Vertex Id using UV space (Maya API)

Updated: Jul 31, 2023

Hey guys,

So i am working on something in which I need to get vertex Id on my main mesh from the UV space from another mesh.

Like in this example: I have selected a vertex on my plane and its id is 8 and now using its UV space coordinates I will get the closest UV coordinates on the sphere and then from that get my vertex Id on the sphere.



And this is the UV space of plane(left), and sphere(right).




As you can see the UV space on left is selected as the same vertex on the plane. Now using this UV space from plane i shall get the closest UV id on the sphere and then get the vertex id.


So first let’s get all the information.



import maya.cmds as cmds
import maya.OpenMaya as OpenMaya
 
list = OpenMaya.MSelectionList()
sphereName = "pSphereShape1"
planeName = "pPlaneShape1"
 
list.add(sphereName)
list.add(planeName)
 
sphereObj = OpenMaya.MObject()
planeObj = OpenMaya.MObject()
 
list.getDependNode(0, sphereObj)
list.getDependNode(1, planeObj)
 
sphereMesh = OpenMaya.MFnMesh(sphereObj)
planeMesh = OpenMaya.MFnMesh(planeObj)
 
</code></pre>
So as we have all our variables now time to get the U and V from the plane mesh.
 
# Using the vertex id 8
id = 8
uUtil = OpenMaya.MScriptUtil()
vUtil = OpenMaya.MScriptUtil()
 
uPtr = uUtil.asFloatPtr()
vPtr = vUtil.asFloatPtr()
 
planeMesh.getUV(id, uPtr, vPtr)
 
u = uUtil.getFloat(uPtr)
v = vUtil.getFloat(vPtr)


So now that we have the u and v values from the plane mesh

Lets get the u and v array from the sphere so we can compare the values and get the closest uv id.



# Getting the UV information from smooth sphere mesh
 
uArray = OpenMaya.MFloatArray()
vArray = OpenMaya.MFloatArray()
 
oSphereMesh.getUVs(uArray, vArray)
 
cmds.select("pSphere2.map[71]")
 
map = 0
print u, v
for i in xrange(uArray.length()):
 
    if ic.isclose(uArray[i], u, rel_tol=1e-9, abs_tol=0.0001):
        if ic.isclose(vArray[i], v, rel_tol=1e-9, abs_tol=0.0001):
            map = i


From this i get the closest uv id on the sphere mesh and using the polyListComponentConversion we can get the vertex id.



sel = cmds.ls(cmds.polyListComponentConversion("pSphere2.map[%s]" % (map), fuv=True, tv=True))[0]
vtxId = re.findall('\d+', sel.partition(".")[2])


And so from this we can get the vertex id with different UV Space just by simple use of MFnMesh.

Feel free to ask questions and share if you found this useful


Until next time!



Komentar


Contact me

so we can create creative & technical projects together
  • Github
  • LinkedIn
  • Instagram
  • Vimeo
  • YouTube
Join my mailing list

Thanks for submitting!

© 2023 by Dilen Shah

bottom of page