Aligned faces pyramid worm in Python

April 3rd, 2009

A Python version of the Aligned faces pyramid worm MEL script, for Maya:

Code and commentary follows:

# start: Aligned faces pyramid worm
from pymel import *
import random

# find the center of a face
def centerOfFace(face):
  # get locations of all vertices in an array
  pos = xform(face, q = 1, ws = 1, t = 1)

  # get length of the array: # vertices * 3
  posSize = len(pos)
  # put the average of all vectors into 1st vector
  for i in range(3):
    for j in range(i+3,posSize,3):
      pos[i] += pos[j]
    pos[i] /= posSize/3

  return (pos[0], pos[1], pos[2])

# make a tetrahedron
cone = polyCone(r=1, h=1.414214, sx=3)[0]
# move its pivot point to the bottom face
xform(rp=(0, -0.707107, 0))
# move to origin and freeze xforms
xform(t=(0, 0.707107, 0))
makeIdentity(apply=True, t=1)

# turn off constraint warnings
cycleCheck(e=False)

for i in range(500):
  # select a random face
  randf = random.randint(0,len(cone.f)-1)
  sel = cone.f[randf]
  # find center of face
  fc = centerOfFace(sel);
  # instance cone
  cone = instance(cone)[0]
  # move instance to face
  xform(cone, a=1, t=(fc[0], fc[1], fc[2]))
  # align instance to face with a temporary normal constraint
  tmpConst = normalConstraint(sel, cone, aim=(0, 1, 0))
  delete(tmpConst)

  # animate visibility
  setKeyframe(cone, attribute = "visibility", v = 0, t = 0)
  setKeyframe(cone, attribute = "visibility", v = 1, t = i)

cycleCheck(e=True)
# end

I did a few time trials on the MEL and Python code, like so:

// MEL timing code:
$startTime = `timerX`;
// code to be timed here
$totalTime = `timerX -startTime $startTime`;
print ("Total Time: "+$totalTime+"\n");

# Python timing code:
startTime=timerX()
### code to be timed here
totalTime = timerX(startTime=startTime)
print("Total Time: "+str(totalTime))

It turns out the MEL version of this code is about 5% faster than the Python, and xform() is about 5% faster than set().

« previously: Random walk pyramids in Python | Home | next: Machu Picchu Post »

Leave a Reply