Skip to content

Instantly share code, notes, and snippets.

@sonictk
Created October 11, 2016 05:48
Show Gist options
  • Save sonictk/8e4baf84717f8a464dbf272d3d8e6f85 to your computer and use it in GitHub Desktop.
Save sonictk/8e4baf84717f8a464dbf272d3d8e6f85 to your computer and use it in GitHub Desktop.
import maya.OpenMaya as om
import pprint
import cProfile
selList = om.MSelectionList()
# selList.add('test_num_of_mesh_shells:pCubeShape1')
selList.add('test_num_of_mesh_shells:pSphereShape1')
# selList.add('theCubeShape')
node = om.MObject()
selList.getDependNode(0, node)
def findNumOfMeshShells(node):
"""
This function finds the number of isolated mesh islands there are under
a given shape **node**.
Args:
node (MObject): The node representing the DAG shape node to find the
number of mesh islands for.
Returns:
(int): The number of mesh islands.
"""
# Sanity checks
if node.isNull():
raise RuntimeError('The internal Maya Object represented by this node '
'does not exist!')
if node.apiType() != om.MFn.kMesh:
raise TypeError('The **node** given does not represent a Maya mesh shape!')
faceConnectionMappings = {}
itMeshPoly = om.MItMeshPolygon(node)
while not itMeshPoly.isDone():
try:
currentFaceIdx = itMeshPoly.index()
connectedFaceIdxs = om.MIntArray()
itMeshPoly.getConnectedFaces(connectedFaceIdxs)
faceConnectionMappings[currentFaceIdx] = [connectedFaceIdxs[idx]
for idx in xrange(connectedFaceIdxs.length())]
itMeshPoly.next()
except RuntimeError as err:
print "failed to iterate"
break
trees = {}
visitedNodes = []
for faceIdx, connectedFacesIdxs in faceConnectionMappings.iteritems():
if faceIdx in visitedNodes:
continue
visitedNodes.append(faceIdx)
if len(connectedFacesIdxs) == 0:
trees[faceIdx] = []
else:
trees[faceIdx] = connectedFacesIdxs
for idx in connectedFacesIdxs:
if idx in visitedNodes:
continue
for c_idx in faceConnectionMappings.get(idx, []):
if c_idx in visitedNodes:
continue
if c_idx not in trees[faceIdx]:
trees[faceIdx].append(c_idx)
visitedNodes.append(idx)
return len(trees.keys())
print findNumOfMeshShells(node)
cProfile.run('findNumOfMeshShells(node)')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment