Skip to content

Instantly share code, notes, and snippets.

@danbradham
Last active May 11, 2016 20:04
Show Gist options
  • Save danbradham/1f8ad74eb96d19a5e805 to your computer and use it in GitHub Desktop.
Save danbradham/1f8ad74eb96d19a5e805 to your computer and use it in GitHub Desktop.
Explode a bunch of meshes
import time
from maya.api import OpenMaya
MVector = OpenMaya.MVector
def get_dagnode(mesh):
sel = OpenMaya.MSelectionList()
sel.add(mesh)
return OpenMaya.MFnDagNode(sel.getDagPath(0))
def intersections_exist(dagnodes):
bounds = [dagnode.boundingBox for dagnode in dagnodes]
while bounds:
a = bounds.pop()
for b in bounds:
if a.intersects(b):
return True
return False
def intersects_with(a, dagnodes):
abounds = a.boundingBox
for dagnode in dagnodes:
if a == dagnode:
continue
if abounds.intersects(dagnode.boundingBox):
return True
return False
def explode_meshes(meshes, origin=None, factor=None, iterations=-1):
origin = origin or MVector(0, 0, 0)
factor = factor or MVector(1, 1, 1)
dagnodes = [get_dagnode(mesh) for mesh in meshes]
vectors = []
for dagnode in dagnodes:
v = MVector(dagnode.boundingBox.center - origin)
v = MVector(*[a*b for a, b in zip(v, factor)])
vectors.append(v)
i = 0
while intersections_exist(dagnodes):
if iterations > 0 and i > iterations:
break
for mesh, dagnode, vector in zip(meshes, dagnodes, vectors):
if not intersects_with(dagnode, list(dagnodes)):
continue
cmds.xform(mesh, ws=True, relative=True, translation=vector)
cmds.refresh()
time.sleep(0.01)
i += 1
if __name__ == '__main__':
cmds.undoInfo(openChunk=True)
explode_meshes(
cmds.ls(sl=True),
factor=MVector(1, 0.01, 1),
iterations=1000)
cmds.undoInfo(closeChunk=True)
from operator import itemgetter
from maya.api import OpenMaya
MVector = OpenMaya.MVector
def get_node(mesh):
sel = OpenMaya.MSelectionList()
sel.add(mesh)
return OpenMaya.MFnDagNode(sel.getDagPath(0))
def intersects_with(a, nodes):
bb = a.boundingBox
for node in nodes:
if a == node:
continue
if bb.intersects(node.boundingBox):
return True
return False
def explode_meshes(meshes, origin=MVector(0, 3, 0), factor=MVector(5, 1, 5)):
nodes = []
queue = []
for mesh in meshes:
node = get_node(mesh)
nodes.append(node)
bb = node.boundingBox
v = MVector(bb.center - origin).normalize()
v = MVector(v.x * factor.x, v.y * factor.y, v.z * factor.z)
area = bb.width * bb.height * bb.depth
queue.append((mesh, node, v, area))
queue = sorted(queue, key=itemgetter(3))
while queue:
mesh, node, vector, _ = queue.pop()
while intersects_with(node, nodes):
cmds.xform(mesh, ws=True, relative=True, translation=vector)
if __name__ == '__main__':
cmds.undoInfo(openChunk=True)
explode_meshes(cmds.ls(sl=True))
cmds.undoInfo(closeChunk=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment