Wednesday, July 1, 2009

w07 - recap and scripts

On our 7th class, we looked into some vector math to help us with certain calculations in Maya. We then developed the following functions:

#######
##
## VECTOR FUNCTIONS
##

import maya.cmds as cmds
import math

#find the magnitude (length) of a vector
def magnitude(v):
#v is a list of x,y,z values
x = v[0]
y = v[1]
z = v[2]
m = math.sqrt( (x*x) + (y*y) + (z*z) )

return m

#find the distance between two points
#by getting the vector between the points and
#getting its magnitude
def distance(p1, p2):
#subtract both vectors
x1 = p1[0]
y1 = p1[1]
z1 = p1[2]
x2 = p2[0]
y2 = p2[1]
z2 = p2[2]
x = x1 - x2
y = y1 - y2
z = z1 - z2
m = magnitude([x,y,z])
return m

#find the unit vector of a given vector
def unit(v):
"returns unit vector of v"
#firt get magnitude
m = magnitude(v)
x = v[0]
y = v[1]
z = v[2]
#divide each element by magnitude
x = x/m
y = y/m
z = z/m
vu = [x,y,z]
return vu

#find the new position of an object which
#it supposed to move a certain amount in the
#direction of a vector (which should be a unit vector)
def move(v, amount):
"Move by certain amount in direction v"
x = v[0]
y = v[1]
z = v[2]
x = x + amount
y = y + amount
z = z + amount
newP = [x,y,z]
return newP

#find the vector between two given points
def vectorBetweenPoints(p1, p2):
"Returns vector between p1 and p2"
#subtract both vectors
x1 = p1[0]
y1 = p1[1]
z1 = p1[2]
x2 = p2[0]
y2 = p2[1]
z2 = p2[2]
x = x1 - x2
y = y1 - y2
z = z1 - z2
newV = [x,y,z]
return newV

We then used a bit of this content to extrude the faces of a certain polygonal object according to its distance to a certain locator, by using the function below:
def extrudeToLocator():
"Extrude based on distance to a certain locator"
#get selected poly
#get selected locator
#get faces of poly
#loop through faces
# find center
# get distance from center to locator
# extrude based on distance
selPoly = cmds.filterExpand(sm=12)
selLoc = cmds.filterExpand(sm=22)

selPoly = selPoly[0]

allFaces = cmds.ls(selPoly + ".f[:]", fl=1)
#loop
for face in allFaces:
vertex = cmds.polyListComponentConversion( face, fromFace=1, toVertex=1 )
vertex = cmds.ls(vertex, fl=1)
#find the center of the face
xs = 0
ys = 0
zs = 0
#loop through vertices
for v in vertex:
pos = cmds.pointPosition(v)
x = pos[0]
y = pos[1]
z = pos[2]
xs = xs + x
ys = ys + y
zs = zs + z
centerX = xs/len(vertex)
centerY = ys/len(vertex)
centerZ = zs/len(vertex)
#check by placing a locator
cmds.spaceLocator(p=(centerX, centerY, centerZ))

#find distance to locator
posLoc = cmds.pointPosition(selLoc)
d = distance([centerX, centerY, centerZ], posLoc)
print d

#extrude based on distance
cmds.polyExtrudeFacet( face, ltz=d)

No comments:

Post a Comment