Here's a proof-of-concept for an alternative approach (which definitely has it's own drawbacks, too). This module estimates the componentPivot location as the average of each face's verts, then rotates the face normal by the angleBetween.
rotateEachComponent.py
import maya.cmds as mc
import maya.mel as mm
from math import pi
import re
from operator import sub
"""
# DEMO:
# import rotateEachComponent as rec
# rec.run()
https://forums.autodesk.com/t5/maya-programming/optimizing-loopfunction-python/td-p/9111923
angleBetweenVectors.append((cmds.angleBetween( euler=True, v1=(geoNormals[current]), v2=(camList))))
cmds.manipRotateContext( mode = 9, orientObject = facePoly[current], activeHandle=0, rotate = (((1 - abs(thresoldRatio[current]))*(angleBetweenVectors[current][0])), ((1 - abs(thresoldRatio[current])))*(angleBetweenVectors[current][1]), ((1 - abs(thresoldRatio[current]))*(angleBetweenVectors[current][2]))), useManipPivot = True, tweakMode = False)
Improve a way to rotate each poly component to a new angle (angleBetween), in a way that doesn't leave a trail of rotateContexts and rotateManips in its wake
Also, make it fast, and scale well to a poly mesh with thousands of faces.
Also, use the component's pivot for rotation. This might be fine to use the components center, or average vertex position.
# Added this into render post-frame mel:
print("post-render message1\n");
python("import rotateEachComponent as rec; reload(rec); rec.loadForUpdate([\"pSphere1\"],[\"locator1\"]); rec.updateAims()")
print("post-render message2\n");
"""
space = re.compile(' +')
shapesToAim = []
aimTargetTransforms = []
def updateAims():
# A helper method to update the aiming (for use on frame changes)
#
for pair in zip(shapesToAim, aimTargetTransforms):
print "updating pair %s"%(pair,)
rotateEachComponent(pair[0], mc.xform(pair[1],q=1,t=1,ws=1))
def loadForUpdate(listOfShapes, listOfAimTargetTransforms):
# loads the module globals with the shape-of-components and the aiming points
# (for use when loading saved scenes instead of regenerating them from the run() method)
global shapesToAim, aimTargetTransforms
print "shapes to aim: %s"%(listOfShapes,)
print "target transforms: %s"%(listOfAimTargetTransforms,)
shapesToAim = listOfShapes
aimTargetTransforms = listOfAimTargetTransforms
def run():
# for doing basic setup to create a test scene:
#
global shapesToAim, aimTargetTransforms
mc.file(f=1,new=1)
Tx = createShape(shape='sphere')
detachFaces(Tx)
shapesToAim = []
aimTargetTransforms = []
shapesToAim.append(Tx) # load shape-transform into the global list
aimLocator = mc.spaceLocator()[0]
aimLocation = (1,1,1)
mc.move(aimLocation[0], aimLocation[1], aimLocation[2], aimLocator)
aimTargetTransforms.append(aimLocator) # load aim transform into the global list
# mc.scale(0.1, 0.1, 0.1, aimLocator)
rotateEachComponent(Tx, aimLocation)
# for convenience, print out the syntax to re-load these components for use later
print "rec.loadForUpdate([\"%s\"],[\"%s\"])"%(Tx,aimLocator)
print "rec.rotateEachComponent(\"%s\",mc.xform(\"%s\",q=1,t=1,ws=1))"%(Tx,aimLocator)
pass
def detachFaces(Tx):
# detaches a mesh so that faces do not share edges
#
numVerts = mc.polyEvaluate(Tx,v=True)
mc.select(Tx + ".vtx[0:%d]"%(numVerts-1) )
mm.eval("performDetachComponents")
mc.select(cl=1)
def createShape(shape='cube'):
# do timing tests:
if shape is 'sphere':
(Tx, history) = mc.polySphere(r=100)
#(Tx, history) = mc.polySphere(sx=100,sy=100)
elif shape is 'torus':
(Tx, history) = mc.polyTorus()
else: # cube
(Tx, history) = mc.polyCube()
return Tx
pass
def getCenterOfFace(faceStr):
facePts = mc.xform(faceStr,q=1,t=1,ws=1)
numPts = len(facePts) / 3
center = [0]*3
for pt in xrange(numPts):
center[0] += facePts[pt*3]
center[1] += facePts[pt*3+1]
center[2] += facePts[pt*3+2]
invNumPts = 1.0/numPts
center[0] *= invNumPts
center[1] *= invNumPts
center[2] *= invNumPts
"""
# for validation, add a small locator at that point
addLocator(center)
"""
return center
def addLocator(point):
loc = mc.spaceLocator()
mc.move(point[0],point[1],point[2],loc)
mc.scale(0.1,0.1,0.1,loc)
def parsePolyInfoFaceNormals(shape):
"""
The polyInfo command irritatingly returns information for text printout, not in a data
structure. This method builds a data structure form the text printout for face normals.
"""
stringResult = mc.polyInfo(shape,faceNormals=True)
fns = []
for rest in stringResult:
rest = space.sub(",",rest)
rest = rest.split(",")
#print(rest)
fns.append([ float(rest[2]),float(rest[3]),float(rest[4])])
#print fv
return fns
def rotateEachComponent(shape, aimAtPos=None):
# For each face in 'shape', compute the angle needed to aim the component's normal at
# aimAtPos's world-space position.
""" Find vector from camera to object"""
if aimAtPos is None:
# Use vector of default camera
#
aimAtPos = mc.xform("persp", t=True, ws=1, q=1)
aimAtVec = aimAtPos
# If false, aim the component in the aimAtPos direction-from-origin rather than
# the aimAtPos direction from the component.
wantComponentAim = True
faceNormals = parsePolyInfoFaceNormals(shape)
numFaces = mc.polyEvaluate(shape, f=True)
for faceNum in range(numFaces):
faceStr = shape+".f[%d]"%faceNum
# estimate pivot for component:
faceCenter = getCenterOfFace(faceStr)
if wantComponentAim:
aimAtVec = map(sub,aimAtPos,faceCenter) # v1 - v2 (aim from v2 to v1)
angle = mc.angleBetween(v1=faceNormals[faceNum], v2=aimAtVec, euler=True)
mc.rotate(angle[0], angle[1], angle[2], faceStr, pivot=faceCenter)
pass