Tuesday, August 11, 2009

columbarium_growth_by_grisha

this is my studio project "a multireligious columbarium"




and this is the script for it

import maya.cmds as cmds
import maya.cmds as cmds
import maya.mel as mm
import math
import sys
from random import*
from setColor import*

# increasing recursion limit to 8000 loops
sys.setrecursionlimit(8000)

#######################
### HELPING SCRIPTS ###
#######################

# getting center of the Face
def centerOfFace(facet):
#find the vertices that define that face.
vertex = cmds.polyListComponentConversion(facet, ff=1, tv=1)
cmds.select(vertex, r=1)
vertexFlat = cmds.ls(sl=1, fl=1)

#find out how many vertices define that face
vertCount = len(vertexFlat)
#print vertexFlat

#for each vertex go through and find it's world space position.
vertPositionSumX = 0.
vertPositionSumY = 0.
vertPositionSumZ = 0.
for a in range(0, vertCount, 1):
coordinate = cmds.pointPosition(vertexFlat[a], w=1)
vertPositionSumX += coordinate[0]
vertPositionSumY += coordinate[1]
vertPositionSumZ += coordinate[2]

centroidX = vertPositionSumX/float(vertCount)
centroidY = vertPositionSumY/float(vertCount)
centroidZ = vertPositionSumZ/float(vertCount)

return [centroidX, centroidY, centroidZ]

# distance between two points
def getDistance(start, end):
#start and end must be lists xyz
v = [start[0]-end[0], start[1]-end[1], start[2]-end[2]] #list format x,y,z
vector = "<<" + str(v[0]) + "," + str(v[1]) + "," + str(v[2]) + ">>"
mag = mm.eval("mag " + vector + ";")

return mag

# looking for closest locator through the list with locators to the LOCATOR
def closestLocator (locator, netOfLocs):
locatorPos = cmds.pointPosition(locator)
distance = 1000000000
closLocData = []
closestLocator = ""
for i in netOfLocs:
locPos = cmds.pointPosition(i)
currDist = getDistance(locatorPos, locPos)
if currDist < distance =" currDist" closlocator =" i" closlocpos =" locPos" closlocdist =" currDist" locatorpos =" Point" distance =" 1000000000" closlocdata =" []" closestlocator = "" locpos =" i[1]" currdist =" getDistance(locatorPos," distance =" currDist" closlocator =" i[0]" closlocpos =" locPos" closlocdist =" currDist" locatorpos =" Point" distance =" 1000000000" closlocdata =" []" closestlocator = "" locpos =" i" currdist =" getDistance(locatorPos," distance =" currDist" closlocator =" i[0]" closlocpos =" locPos" closlocdist =" currDist" locatorpos =" Point" distance =" 1000000000" closlocdata =" []" closestlocator = "" locpos =" i[2]" currdist =" getDistance(locatorPos," distance =" currDist" closlocator =" i[0]" grow =" i[1]" closlocpos =" locPos" closlocdist =" currDist" locatorpos =" Point" distance =" 1000000000" closlocdata =" []" closestlocator = "" locpos =" i[1]" currdist =" getDistance(locatorPos," distance =" currDist" closlocator =" i[0]" closlocpos =" locPos" closlocdist =" currDist" locatorpos =" center" distance =" 1000000000" closlocdata =" []" closestlocator = "" locpos =" i" currdist =" getDistance(locatorPos," distance =" currDist" closlocator =" i" closlocpos =" i" closlocdist =" currDist" x="0" y="0" z="0" n="0" ptpos =" cmds.pointPosition(i)" x="x+ptPos[0]" y="y+ptPos[1]" z="z+ptPos[2]" n="n+1" ptpos =" cmds.pointPosition(i)" x="x+ptPos[0]" y="y+ptPos[1]" z="z+ptPos[2]" n="n+1" midx =" x/n" midy =" y/n" midz =" z/n" midpt="[]" x="0" y="0" z="0" n="0" ptpos =" cmds.pointPosition(listLoc1[i])" x="x+ptPos[0]" y="y+ptPos[1]" z="z+ptPos[2]" n="n+1" ptpos =" listPt2" x="x+(ptPos[0]*len(listLoc1))" y="y+(ptPos[1]*len(listLoc1))" z="z+(ptPos[2]*len(listLoc1))" n="n+len(listLoc1)" midx =" x/n" midy =" y/n" midz =" z/n" midpt="[]" dire =" [" center =" center" loc2 =" loc2[0]" loc3 =" loc3[0]" loc4 =" loc4[0]" clpt1 =" closestPointToPoints" clpt2 =" closestPointToPoints" clpt1 =" clPt1[0]" clpt2 =" clPt2[0]" centerclosrelig =" centerClosRelig[0]" x =" (3*loc2[0]" y =" (3*loc2[1]" point =" [x,y,0]" x =" center[0]" y =" center[1]" new =" [x,y,0]" va =" (locPos[0]" vb =" (0,1,0)" angle =" cmds.angleBetween(v1=" v2="vb)" angle =" angle[3]" graves =" []" mitrary =" []" buddhism =" []" catholic=" []" orthodox =" []" hindu =" []" judaism =" []" protest =" []" islam =" []" allrelig =" []" otherr =" []" amitrary =" []" abuddhism =" []" acatholic=" []" aorthodox =" []" ahindu =" []" ajudaism =" []" aprotest =" []" aislam =" []" aallrelig =" []" ceremony =" []" entrance =" []" otherw =" []" otherm =" []" allrepuls =" []" trees =" []" treessrf=" []" cubes =" []" ff =" []" mitrary =" ff" ff =" []" buddhism =" ff" ff =" []" catholic =" ff" ff =" []" orthodox =" ff" ff =" []" hindu =" ff" ff =" []" judaism =" ff" ff =" []" protest =" ff" ff =" []" islam =" ff" ff =" []" amitrary =" ff" ff =" []" abuddhism =" ff" ff =" []" acatholic =" ff" ff =" []" aorthodox =" ff" ff =" []" ahindu =" ff" ff =" []" ajudaism =" ff" ff =" []" aprotest =" ff" ff =" []" aislam =" ff" otherrr =" []" otherr =" otherRR" allrelig =" self.mitrary" mmm="[]" mmmm="[]" ceremony =" mmm" entrance =" mmmm" otherw =" [centerOfFace('polySurface7766.f[0]'),centerOfFace('polySurface7770.f[0]'),centerOfFace('polySurface7767.f[0]'),centerOfFace('polySurface7769.f[0]'),centerOfFace('polySurface7771.f[0]')]" otherm =" [centerOfFace('polySurface7762.f[0]'),centerOfFace('polySurface7763.f[0]'),centerOfFace('polySurface7764.f[0]'),centerOfFace('polySurface7765.f[0]')]" allrepuls =" self.entrance" mm=" []" mmm =" []" m =" 'polySurface%d.f[0]'" n =" 'polySurface%d'" treessrf =" mmm" trees =" mm" r="True)" faces =" cmds.filterExpand(sm=" faces =" []" all="True)" cface =" centerOfFace(i)" loc =" cmds.spaceLocator(" p="(Cface[0],Cface[1],Cface[2])" graves =" FACES" all =" True)" locs =" cmds.filterExpand(sm=" pp =" []" loc =" i" lpos =" cmds.pointPosition(i)" oo =" []" graves =" PP" cubes =" []" position =" cmds.pointPosition(i)" cube =" cmds.polyCube" w ="size" h="size" d="size" repsize="10," pointsamount =" 4," n="0):" repulsivelocs =" self.allRepuls" locs =" self.graves" l="(repSize/5)*(i+1)" kpos =" k" closloc =" closestLocatorToPoint(Kpos," locpos =" closLoc[1]" clloc =" closLoc[0]" direc =" direction(LOCpos," newx =" ((direc[0]*6)/((i+1)*(i+1)))" newy =" ((direc[1]*6)/((i+1)*(i+1)))" newz =" ((direc[2]*6)/((i+1)*(i+1)))" cll =" [clLoc,LOCpos]" n="0," mn="0," bn="0," cn="0," on="0," hn="0," jn="0," pn="0," in="0," cubes =" []," max =" 150.0," cofcenmove="10" m =" [1]" b =" [2]" c =" [3]" o =" [4]" h =" [5]" j =" [6]" p =" [7]" i =" [8]" way ="=" way ="=" xxx =" randint" way ="=" xxx =" randint" n ="=" n ="=" n ="=" n="=" allrelig =" [M]+[B]+[C]+[O]+[H]+[J]+[P]+[I]" n="N+1" trees =" self.trees" closreligion =" closestPointToPoints1">= closReligion[1]:
M.append (midPtWater (self.otherW, self.otherM, M[2], self.ceremony, self.entrance, self.Amitrary, closReligion[2])) # midPt [3]
else:
closPT = closReligion[2]
g = M[2]
xx = g[0] - (closPT[0] - g[0])
yy = g[1] - (closPT[1] - g[1])
ptt = [xx, yy, 0]
M.append (midPtWater (self.otherW, self.otherM, M[2], self.ceremony, self.entrance, self.Amitrary, ptt)) # midPt [3]
#setting the center of growing
newCen = newCenter (M[2], M[3], cofCenMove)
M[2] = newCen
prevousPt = newCen

if M[1]/10 == 0:
GG = randint (0,1)
else:
GG = M[1]/10
#trees growth
for i in range (GG):
#looking for closest tree
closTree = closestTreeToPoint (M[2], Trees)
closTree = closTree[0]
#making a circle in new tree position
cmds.circle (c=(closTree[0], closTree[1], closTree[2]), r=1.5)
cmds.planarSrf (d=1)
#1 tree == 2 graves... so... looking for closest two graves to the tree and removing the from the list
for i in range (2):
closGrave = closestPointToPoints2 (closTree, allGraves)
closGraveName = [closGrave[0],closGrave[1]]
allGraves.remove (closGraveName)
# stop recursion because allGraves list is empty
if len(allGraves)==1:
return "Done."
# stop the loop if Trees list is empty
if len(Trees) < closgrave =" closestPointToPoints2" closgravepos =" closGrave[1]" closgravename =" [closGrave[0],closGrave[1]]">= MAX:
MN = 0
M2 = closGrave[1]
allGraves.remove (closGraveName)
break
else:
M2 = M[2]
#looking for angle rotate the box according it to face the center
angle = angleBetweenVectors (M[2], closGravePos)
#making the cube with size which is changing depends on counter
cube = cmds.polyCube (w =size*(MN/MAX) ,h=size*(MN/MAX) ,d=size*(MN/MAX))
CUBES.append (cube[0])
#move the cube to the locator position
cmds.move (closGravePos[0], closGravePos[1], closGravePos[2], cube)
#rotate the cube to face the center of the religion
cmds.rotate ( angle[0], angle[1], angle[2], cube, pivot=closGravePos )
#remove the locator from the list with locators according to not to loop through it next time
allGraves.remove (closGraveName)
# draw a curve between center of the religion and the locator
cmds.curve( p=[(M2[0],M2[1], M2[2]), (closGravePos[0], closGravePos[1], closGravePos[2])] )
prevousPt = closGravePos
# stop recursion because allGraves list is empty
if len(allGraves)==1:
return "Done."


#return "Done."
cmds.refresh()

####### ALL THE RELIGIONS HAVE SIMILAR LOGIC BUT DIFFERENT NUMBERS

######BUDDISM######
closReligion = closestPointToPoints1 (B[2], ALLRELIG) #dist - [3]
if B[1] >= closReligion[1]:
B.append (midPtWater (self.otherW, self.otherM, B[2], self.ceremony, self.entrance, self.Abuddhism, closReligion[2])) # midPt [3]
else:
closPT = closReligion[2]
g = B[2]
xx = g[0] - (closPT[0] - g[0])
yy = g[1] - (closPT[1] - g[1])
ptt = [xx, yy, 0]
B.append (midPtWater (self.otherW, self.otherM, B[2], self.ceremony, self.entrance, self.Abuddhism, ptt)) # midPt [3]
newCen = newCenter (B[2], B[3], cofCenMove)
B[2] = newCen
prevousPt = newCen

if B[1]/10 == 0:
GG = randint (0,1)
else:
GG = B[1]/10
for i in range (GG):
closTree = closestTreeToPoint (B[2], Trees)
closTree = closTree[0]
cmds.circle (c=(closTree[0], closTree[1], closTree[2]), r=1.5)
cmds.planarSrf (d=1)
#print "closTree"
#print closTree
for i in range (2):
closGrave = closestPointToPoints2 (closTree, allGraves)
closGraveName = [closGrave[0],closGrave[1]]
allGraves.remove (closGraveName)
if len(allGraves)==1:
return "Done."
if len(Trees) < closgrave =" closestPointToPoints2" closgravepos =" closGrave[1]" closgravename =" [closGrave[0],closGrave[1]]">= MAX:
BN = 0
B2 = closGrave[1]
allGraves.remove (closGraveName)
break
else:
B2 = B[2]
cube = cmds.polyCube (w =size*(BN/MAX) ,h=size*(BN/MAX) ,d=size*(BN/MAX))
CUBES.append (cube[0])
cmds.move (closGravePos[0], closGravePos[1], closGravePos[2], cube)
allGraves.remove (closGraveName)
cmds.curve( p=[(B2[0],B2[1], B2[2]), (closGravePos[0], closGravePos[1], closGravePos[2])] )
prevousPt = closGravePos
if len(allGraves)==1:
return "Done."

cmds.refresh()

######Catholics######
closReligion = closestPointToPoints1 (C[2], ALLRELIG) #dist - [3]
if C[1] >= closReligion[1]:
C.append (midPtWater (self.otherW, self.otherM, C[2], self.ceremony, self.entrance, self.Acatholic, closReligion[2])) # midPt [3]
else:
closPT = closReligion[2]
g = C[2]
xx = g[0] - (closPT[0] - g[0])
yy = g[1] - (closPT[1] - g[1])
ptt = [xx, yy, 0]
C.append (midPtWater (self.otherW, self.otherM, C[2], self.ceremony, self.entrance, self.Acatholic, ptt)) # midPt [3]
newCen = newCenter (C[2], C[3], cofCenMove)
C[2] = newCen
prevousPt = newCen

if C[1]/10 == 0:
GG = randint (0,1)
else:
GG = C[1]/10
for i in range (GG):
closTree = closestTreeToPoint (C[2], Trees)
closTree = closTree[0]
cmds.circle (c=(closTree[0], closTree[1], closTree[2]), r=1.5)
cmds.planarSrf (d=1)
#print "closTree"
#print closTree
for i in range (2):
closGrave = closestPointToPoints2 (closTree, allGraves)
closGraveName = [closGrave[0],closGrave[1]]
allGraves.remove (closGraveName)
if len(allGraves)==1:
return "Done."
if len(Trees) < closgrave =" closestPointToPoints2" closgravepos =" closGrave[1]" closgravename =" [closGrave[0],closGrave[1]]">= MAX:
CN = 0
C2 = closGrave[1]
allGraves.remove (closGraveName)
break
else:
C2 = C[2]
cube = cmds.polyCube (w =size*(CN/MAX) ,h=size*(CN/MAX) ,d=size*(CN/MAX))
CUBES.append (cube[0])
cmds.move (closGravePos[0], closGravePos[1], closGravePos[2], cube)
allGraves.remove (closGraveName)
cmds.curve( p=[(C2[0],C2[1], C2[2]), (closGravePos[0], closGravePos[1], closGravePos[2])] )
prevousPt = closGravePos
if len(allGraves)==1:
return "Done."

cmds.refresh()

######Orthodox######
closReligion = closestPointToPoints1 (O[2], ALLRELIG) #dist - [3]
if O[1] >= closReligion[1]:
O.append (midPtWater (self.otherW, self.otherM, O[2], self.ceremony, self.entrance, self.Aorthodox, closReligion[2])) # midPt [3]
else:
closPT = closReligion[2]
g = O[2]
xx = g[0] - (closPT[0] - g[0])
yy = g[1] - (closPT[1] - g[1])
ptt = [xx, yy, 0]
O.append (midPtWater (self.otherW, self.otherM, O[2], self.ceremony, self.entrance, self.Aorthodox, ptt)) # midPt [3]
newCen = newCenter (O[2], O[3], cofCenMove)
O[2] = newCen
prevousPt = newCen

if O[1]/10 == 0:
GG = randint (0,1)
else:
GG = O[1]/10
for i in range (GG):
closTree = closestTreeToPoint (O[2], Trees)
closTree = closTree[0]
cmds.circle (c=(closTree[0], closTree[1], closTree[2]), r=1.5)
cmds.planarSrf (d=1)
#print "closTree"
#print closTree
for i in range (2):
closGrave = closestPointToPoints2 (closTree, allGraves)
closGraveName = [closGrave[0],closGrave[1]]
allGraves.remove (closGraveName)
if len(allGraves)==1:
return "Done."
if len(Trees) < closgrave =" closestPointToPoints2" closgravepos =" closGrave[1]" closgravename =" [closGrave[0],closGrave[1]]">= MAX:
ON = 0
O2 = closGrave[1]
allGraves.remove (closGraveName)
break
else:
O2 = O[2]
cube = cmds.polyCube (w =size*(ON/MAX) ,h=size*(ON/MAX) ,d=size*(ON/MAX))
CUBES.append (cube[0])
cmds.move (closGravePos[0], closGravePos[1], closGravePos[2], cube)
allGraves.remove (closGraveName)
cmds.curve( p=[(O2[0],O2[1], O2[2]), (closGravePos[0], closGravePos[1], closGravePos[2])] )
prevousPt = closGravePos
if len(allGraves)==1:
return "Done."

cmds.refresh()

######HINDU######
closReligion = closestPointToPoints1 (H[2], ALLRELIG) #dist - [3]
if H[1] >= closReligion[1]:
H.append (midPtWater (self.otherW, self.otherM, H[2], self.ceremony, self.entrance, self.Aprotest, closReligion[2])) # midPt [3]
else:
closPT = closReligion[2]
g = H[2]
xx = g[0] - (closPT[0] - g[0])
yy = g[1] - (closPT[1] - g[1])
ptt = [xx, yy, 0]
H.append (midPtWater (self.otherW, self.otherM, H[2], self.ceremony, self.entrance, self.Aprotest, ptt)) # midPt [3]
newCen = newCenter (H[2], H[3], cofCenMove)
H[2] = newCen
prevousPt = newCen

if H[1]/10 == 0:
GG = randint (0,1)
else:
GG = H[1]/10
for i in range (GG):
closTree = closestTreeToPoint (H[2], Trees)
closTree = closTree[0]
cmds.circle (c=(closTree[0], closTree[1], closTree[2]), r=1.5)
cmds.planarSrf (d=1)
#print "closTree"
#print closTree
for i in range (2):
closGrave = closestPointToPoints2 (closTree, allGraves)
closGraveName = [closGrave[0],closGrave[1]]
allGraves.remove (closGraveName)
if len(allGraves)==1:
return "Done."
if len(Trees) < closgrave =" closestPointToPoints2" closgravepos =" closGrave[1]" closgravename =" [closGrave[0],closGrave[1]]">= MAX:
HN = 0
H2 = closGrave[1]
allGraves.remove (closGraveName)
break
else:
H2 = H[2]
cube = cmds.polyCube (w =size*(HN/MAX) ,h=size*(HN/MAX) ,d=size*(HN/MAX))
CUBES.append (cube[0])
cmds.move (closGravePos[0], closGravePos[1], closGravePos[2], cube)
allGraves.remove (closGraveName)
cmds.curve( p=[(H2[0],H2[1], H2[2]), (closGravePos[0], closGravePos[1], closGravePos[2])] )
prevousPt = closGravePos
if len(allGraves)==1:
return "Done."

cmds.refresh()

######JUDAISM######
closReligion = closestPointToPoints1 (J[2], ALLRELIG) #dist - [3]
if J[1] >= closReligion[1]:
J.append (midPtWater (self.otherW, self.otherM, J[2], self.ceremony, self.entrance, self.Ajudaism, closReligion[2])) # midPt [3]
else:
closPT = closReligion[2]
g = J[2]
xx = g[0] - (closPT[0] - g[0])
yy = g[1] - (closPT[1] - g[1])
ptt = [xx, yy, 0]
J.append (midPtWater (self.otherW, self.otherM, J[2], self.ceremony, self.entrance, self.Ajudaism, ptt)) # midPt [3]
newCen = newCenter (J[2], J[3], cofCenMove)
J[2] = newCen
prevousPt = newCen

if J[1]/10 == 0:
GG = randint (0,1)
else:
GG = J[1]/10
for i in range (GG):
closTree = closestTreeToPoint (J[2], Trees)
closTree = closTree[0]
cmds.circle (c=(closTree[0], closTree[1], closTree[2]), r=1.5)
cmds.planarSrf (d=1)
#print "closTree"
#print closTree
for i in range (2):
closGrave = closestPointToPoints2 (closTree, allGraves)
closGraveName = [closGrave[0],closGrave[1]]
allGraves.remove (closGraveName)
if len(allGraves)==1:
return "Done."
if len(Trees) < closgrave =" closestPointToPoints2" closgravepos =" closGrave[1]" closgravename =" [closGrave[0],closGrave[1]]">= MAX:
JN = 0
J2 = closGrave[1]
allGraves.remove (closGraveName)
break
else:
J2 = J[2]
cube = cmds.polyCube (w =size*(JN/MAX) ,h=size*(JN/MAX) ,d=size*(JN/MAX))
CUBES.append (cube[0])
cmds.move (closGravePos[0], closGravePos[1], closGravePos[2], cube)
allGraves.remove (closGraveName)
cmds.curve( p=[(J2[0],J2[1], J2[2]), (closGravePos[0], closGravePos[1], closGravePos[2])] )
prevousPt = closGravePos
if len(allGraves)==1:
return "Done."

cmds.refresh()

######PROTESTANTISM######
closReligion = closestPointToPoints1 (P[2], ALLRELIG) #dist - [3]
if P[1] >= closReligion[1]:
P.append (midPtWater (self.otherW, self.otherM, P[2], self.ceremony, self.entrance, self.Ahindu, closReligion[2])) # midPt [3]
else:
closPT = closReligion[2]
g = P[2]
xx = g[0] - (closPT[0] - g[0])
yy = g[1] - (closPT[1] - g[1])
ptt = [xx, yy, 0]
P.append (midPtWater (self.otherW, self.otherM, P[2], self.ceremony, self.entrance, self.Ahindu, ptt)) # midPt [3]
newCen = newCenter (P[2], P[3], cofCenMove)
P[2] = newCen
prevousPt = newCen

if P[1]/10 == 0:
GG = randint (0,1)
else:
GG = P[1]/10
for i in range (GG):
closTree = closestTreeToPoint (P[2], Trees)
closTree = closTree[0]
cmds.circle (c=(closTree[0], closTree[1], closTree[2]), r=1.5)
cmds.planarSrf (d=1)
#print "closTree"
#print closTree
for i in range (2):
closGrave = closestPointToPoints2 (closTree, allGraves)
closGraveName = [closGrave[0],closGrave[1]]
allGraves.remove (closGraveName)
if len(allGraves)==1:
return "Done."
if len(Trees) < closgrave =" closestPointToPoints2" closgravepos =" closGrave[1]" closgravename =" [closGrave[0],closGrave[1]]">= MAX:
PN = 0
P2 = closGrave[1]
allGraves.remove (closGraveName)
break
else:
P2 = P[2]
cube = cmds.polyCube (w =size*(PN/MAX) ,h=size*(PN/MAX) ,d=size*(PN/MAX))
CUBES.append (cube[0])
cmds.move (closGravePos[0], closGravePos[1], closGravePos[2], cube)
allGraves.remove (closGraveName)
cmds.curve( p=[(P2[0],P2[1], P2[2]), (closGravePos[0], closGravePos[1], closGravePos[2])] )
prevousPt = closGravePos
if len(allGraves)==1:
return "Done."

cmds.refresh()

######ISLAM######
closReligion = closestPointToPoints1 (I[2], ALLRELIG) #dist - [3]
if I[1] >= closReligion[1]:
I.append (midPtWater (self.otherW, self.otherM, I[2], self.ceremony, self.entrance, self.Aislam, closReligion[2])) # midPt [3]
else:
closPT = closReligion[2]
g = I[2]
xx = g[0] - (closPT[0] - g[0])
yy = g[1] - (closPT[1] - g[1])
ptt = [xx, yy, 0]
I.append (midPtWater (self.otherW, self.otherM, I[2], self.ceremony, self.entrance, self.Aislam, ptt)) # midPt [3]
newCen = newCenter (I[2], I[3], cofCenMove)
I[2] = newCen
prevousPt = newCen

if I[1]/10 == 0:
GG = randint (0,1)
else:
GG = I[1]/10
for i in range (GG):
closTree = closestTreeToPoint (I[2], Trees)
closTree = closTree[0]
cmds.circle (c=(closTree[0], closTree[1], closTree[2]), r=1.5)
cmds.planarSrf (d=1)
#print "closTree"
#print closTree
for i in range (2):
closGrave = closestPointToPoints2 (closTree, allGraves)
closGraveName = [closGrave[0],closGrave[1]]
allGraves.remove (closGraveName)
if len(allGraves)==1:
return "Done."
if len(Trees) < closgrave =" closestPointToPoints2" closgravepos =" closGrave[1]" closgravename =" [closGrave[0],closGrave[1]]">= MAX:
IN = 0
I2 = closGrave[1]
allGraves.remove (closGraveName)
break
else:
I2 = I[2]
cube = cmds.polyCube (w =size*(IN/MAX) ,h=size*(IN/MAX) ,d=size*(IN/MAX))
CUBES.append (cube[0])
cmds.move (closGravePos[0], closGravePos[1], closGravePos[2], cube)
allGraves.remove (closGraveName)
cmds.curve( p=[(I2[0],I2[1], I2[2]), (closGravePos[0], closGravePos[1], closGravePos[2])] )
prevousPt = closGravePos
if len(allGraves)==1:
return "Done."

cmds.refresh()

#duplicate and move all the cubes to see the growth progress after running the script
sss = cmds.duplicate( CUBES )
gr = cmds.group( sss )
cmds.select (gr, r=True)
cmds.move( 0, 300*N, 0 )

#run the recursion again if there are more elements in the locators list then 0
if len(allGraves)>0:
self.GROWTH (Way, minGrow, maxGrow, size, allGraves, M2, B2, C2, O2, H2, J2, P2, I2, N, MN, BN, CN, ON, HN, JN, PN, IN, CUBES, MAX = 150.0, cofCenMove=10)
else:
return "Done."

to run the script


g= graves()
allGraves=g.allLocs()
g.getAll()
g.changeNetBecauseRepulsive()
allGraves = g.allLocs1()
g.deleteTrees ()
#'Random'-1 'Normal'-2 'War'-3
g.GROWTH (1,3,80,1.5,allGraves,0,0,0,0,0,0,0,0)
maya file

Friday, August 7, 2009

Crowd system - first attempt

It doesn't always consider the obstacles as it should. Sometimes the objects are rejected (although they should be deleted) and sometimes they just ignore the obstacles.


#######################################################################################################
##
## Crowd System
## student Andreea Nica
##
## Active agents: predacious & small fishes
## Passive agents: edge & fishing line
##
## Rules:
## - fishes meet the edge - delete fishes
## - fishes meet the fishing line - delete fishes
## - small fish meets predacious - delete small fish
## - small fish meets small fish - scale 0.5
## - predacious meets predacious - duplicate predacious
##
#######################################################################################################


import maya.cmds as cmds
from random import *



def hit(hit, agent):
### define what to do when it some collision is detected
#all transformations are made only on the agent, as the hit object will perform the same queries on this agent
#if it hit the cube, ignore
if hit == "wall_rigid":
return
agentRole = cmds.getAttr(agent + ".role")
hitRole = cmds.getAttr(hit + ".role")
if hitRole == agentRole:
#check if both are bad
if hitRole == "bad":
#then delete - edge rule
cmds.delete('agent')
else:
#if good, increase size
cmds.delete( 'agent')
elif hitRole != agentRole:
if hitRole == "bad":
#means agent role is good (small fish)
cmds.scale(.5,.5,.5, agent, r=1)
elif hitRole == "good":
#means agent was bad (predacious - duplicate)
cmds.duplicate( 'agent')


class Agent:
def __init__(self, solver, role, position=(0,0,0), size=(3,3,3), color=(0,0,0), objType="cube", rigidType="active", bounciness=.6, collide=1):
#set agent atributes
self.bounciness = bounciness
self.collide = collide
self.rigidType = rigidType
self.solver=solver
self.role = role
self.initialScale = size
#create the agent and scale it
self.object = cmds.polyCube(ax=(0,0,1))
cmds.scale(size[0], size[1], size[2])
#apply a color to the agent
#set the object color
#sh = createShader(color, transparency=0, type="lambert")
#applyShaderOnObject(self.object[0], sh)

#create the rigid body
self.rigid = cmds.rigidBody(self.object,
name=self.object[0] + "_rigid",
p=position,
b=self.bounciness,
impulse=(0,0,0),
sio=objType, #stand in object
cc = 1, #contact count
cp = 1, #contact position
cn = 1, #contact name
solver=self.solver)

#add attribute to the rigid body to store the type of agent
cmds.select(self.rigid, r=1)
cmds.addAttr(ln="role", dt="string", keyable=1)
cmds.setAttr(self.rigid + ".role", "good", type="string")

if self.rigidType == "active":
cmds.setAttr(self.rigid + ".active", 1)
else:
cmds.setAttr(self.rigid + ".active", 0)

#apply the expression
self.applyExpression()

def applyExpression(self):
"Function to apply the expression to the agent"
#first disconnect the rotation attributes because we want to controll it via expressions
cmds.disconnectAttr (self.rigid + "ry.output", self.object[0] + ".rotateY")
cmds.disconnectAttr (self.rigid + "rx.output", self.object[0] + ".rotateX")
cmds.disconnectAttr (self.rigid + "rz.output", self.object[0] + ".rotateZ")
# Create expression for VehicleF with a random multiplier added to the expression.
randX = random.uniform(-3,3)
randY = random.uniform(3,-3)
####COMPOSE THE EXPRESSION STRING

#now put the text above in a python string
#the first lines define how the agent will wander
expString = "// Set wander motion of vehicle and add random multipliers.\n"
expString += "%s.impulseX" % self.rigid
expString += " = sin(time * %f);\n" % randX
expString += "%s.impulseY" % self.rigid
expString += " = (noise(time) * %f);\n\n" % randY
#the second part, how it rotates according to the direction it is going (velocity vector)
expString += "// Set orientation of Vehicle according to the velocity direction.\n"
expString += "float $fVel[];\n"
expString += "$fVel = `getAttr %s.velocity`;\n\n" % (self.rigid)
expString += "%s.rotateX = 0;\n" % self.object[0]
expString += "%s.rotateZ = atan2d( $fVel[0], $fVel[1] );\n" % (self.object[0])
expString += "%s.rotateY = 0;\n\n" % self.object[0]
#the third part, checking bumps on other agents
expString += "//checking bumps on other agents\n"
expString += "string $lastHit;\n"
expString += "if (%s.contactCount > 0){\n" % self.rigid
expString += " int $contactCount = `getAttr %s.contactCount`;\n" % self.rigid
expString += " $lastHit = `getAttr %s.contactName[0]`;\n" %self.rigid
expString += ' string $rigid = "%s";\n' % self.rigid
expString += ' python("hit(\'"+$lastHit+"\', \'"+ $rigid +"\')");\n'
expString += "};//endif\n"

self.expString = expString
cmds.expression(s=expString)



class Crowd:
def __init__(self):
"Initialize attributes"
#objects for obstacles
self.collectObjects = []
#number of vehicles
self.vNumber = 0
#boolean for obstacles
self.obst = 0
#boolean for global forces
self.gforces = 0
#dictionary for UI elements
self.UIelements = {}
#set timeline
cmds.playbackOptions(min= 1, max=1000)
#get selected objects
self.collectObjects = cmds.ls(sl=1)
#start UI
self.crowdSystemUI()

def crowdSystemUI(self):
"Assembles and displays the UI for the Crowd System"
self.UIelements["window"] = cmds.window(title="Crowd System",
widthHeight=(300, 200)
)

self.UIelements["form"] = cmds.formLayout()
txt = cmds.text(label="Number of Vehicles")
collection = cmds.radioCollection()
radiob1 = cmds.radioButton(label="10", data=1, changeCommand=self.changeVnumber)
radiob2 = cmds.radioButton(label="20", onCommand="vNumber = 20")
cmds.setParent(upLevel=1)
cmds.setParent(upLevel=1)

txtOB = cmds.text(label="Obstacles")
collection2 = cmds.radioCollection()
radiob3 = cmds.radioButton(label="On", changeCommand=self.changeObst)
radiob4 = cmds.radioButton(label="Off")
cmds.setParent(upLevel=1)
cmds.setParent(upLevel=1)

txtGF = cmds.text( label = "Global Forces")
collection3 = cmds.radioCollection()
radiob5 = cmds.radioButton(label= "On" ,changeCommand =self.changeGforces)
radiob6 = cmds.radioButton(label="Off")
cmds.setParent(upLevel=1)
cmds.setParent(upLevel=1)

cmds.radioCollection(collection, edit=1, select=radiob1)
cmds.radioCollection(collection2, edit=1, select=radiob4)
cmds.radioCollection(collection3, edit=1, select=radiob6)

# Place Vehicle options
form = self.UIelements["form"]
cmds.formLayout(form,
edit=1,
attachForm= [
( txt, "top", 20),
(txt ,"left", 70),
(radiob1,"top", 10),
(radiob1,"left", 20),
(radiob2,"top", 30),
(radiob2,"left", 20)
]
)
# Place environment options
cmds.formLayout(form,
edit=1,
attachForm= [
(txtOB, "top", 80),
(txtOB, "left", 80),
(radiob3, "top", 80),
(radiob3, "left", 150),
(radiob4 ,"top", 80),
(radiob4, "left", 190),
(txtGF, "top", 110),
(txtGF, "left", 63),
(radiob5, "top", 110),
(radiob5, "left", 150),
(radiob6, "top", 110),
(radiob6, "left", 190)
]
)
# Create buttons
button1 = cmds.button(label = "Create")
button2 = cmds.button(label = "Cancel")

# Place buttons in the window
cmds.formLayout(form,
edit=1,
attachForm =[
(button1, "bottom", 10),
(button1, "left", 185),
(button2, "bottom", 10),
(button2, "right", 10)
]
)
# Add the commands to the buttons.
cmds.button(button1, edit=1, command=self.createCrowd )
cmds.button(button2, edit=1, command=self.deleteUI )

cmds.showWindow(self.UIelements["window"])
## UI help functions
def changeVnumber(self, *args):
if args[0] == "true":
self.vNumber = 10
else:
self.vNumber = 20
print "vNumber:",self.vNumber
def changeObst(self, *args):
if args[0] == "true":
self.obst = 1
else:
self.obst = 0
print "Obst:", self.obst
def changeGforces(self, *args):
if args[0] == "true":
self.gforces = 1
else:
self.gforces = 0
print "gforces:", self.gforces
def deleteUI(self, *args):
cmds.deleteUI(self.UIelements["window"])
self.UIelements["window"] = ""

## MAIN METHODS
def createCrowdSolver(self):
"Creates the main rigidSolver for the elements in the Crowd System"
self.crowdSolver = cmds.rigidSolver( create=1,
current=1,
name="crowdSolver",
velocityVectorScale=0.5,
displayVelocity=1
)
cmds.setAttr(self.crowdSolver + ".allowDisconnection", 1)

def createVehicle(self, vType, N):
"Creates one vehicle and add fields and expressions to it."
#first verify if the vehicle is of type follower (F) or leader (L)
#and set the size of the cube according to the type (leaders are bigger! :)
if vType == "F":
w = 1 #width
h = .5 #height
d = 1 #depth
else:
w = 5
h = 3
d = 5

#creates the basic cube
vehicle = cmds.polyCube(w=w,d=d,h=h)

#create a vehicle force to the agent
field = cmds.radial(position = [0,0,0],
magnitude = 50, #positive magnitude means repoulsion, negative magnitude means atraction
attenuation = 0.3,
maxDistance = 8.0
)

cmds.parent(field[0],vehicle[0])
cmds.hide(field)

if vType == "L":
Lfield = cmds.radial(position = [0,0,0],
magnitude =-1,
attenuation = .2,
maxDistance = 50
)
cmds.parent(Lfield[0],vehicle[0])
cmds.hide(Lfield)


#convert it to a rigid body with random placement
rigid = cmds.rigidBody(
vehicle[0],
n="rigidVeh1%s%d" % (vType, N),
active=1,
mass=1,
bounciness=0,
damping=1.5,
position=(uniform(-70,70),uniform(-70,70),0),
impulse=(0,0,0),
standInObject="cube",
solver=self.crowdSolver
)

#disconnect the rotation attributes of the vehicle
cmds.disconnectAttr(rigid + "rx.output", vehicle[0]+".rx")
cmds.disconnectAttr(rigid + "ry.output", vehicle[0]+".ry")
cmds.disconnectAttr(rigid + "rz.output", vehicle[0]+".rz")

#add expression for movement
randX = uniform(-3,3)
randY = uniform(-3,3)

expString = "%s.impulseX = sin(time * %f);" % (rigid, randX)
expString += "%s.impulseY = (noise(time)*%f);" % (rigid, randY)
expString += "float $Vel[] = `getAttr %s.velocity`;" % rigid
expString += "%s.rotateX = 0;" % vehicle[0]
expString += "%s.rotateY = 0;" % vehicle[0]
expString += "%s.rotateZ = atan2d( $Vel[0], $Vel[2] );" % vehicle[0]

cmds.expression(s=expString)

if vType== "F":
return [rigid,field]
else:
return [rigid, field, Lfield]



def createCrowd(self, *args):
"Method to assemble the whole system"
#creates a rigidSolver to add the vehicle to
self.createCrowdSolver()
#turn on the velocity arrow
cmds.setAttr(self.crowdSolver + ".displayVelocity", 1)
cmds.setAttr(self.crowdSolver + ".scaleVelocity", .5)

#allow disconnections on the rigidSolver
cmds.setAttr(self.crowdSolver + ".allowDisconnection", 1)



##create amount of agents
if self.vNumber == 10: #vNumber = number of vehicles
FNumber = 8 #followers
LNumber = 2 #leaders
elif self.vNumber ==20:
FNumber =18
LNumber =2

#create empty lists to store followers and leaders
followers = []
leaders = []


#creating the followrs
for i in range(FNumber):
v = self.createVehicle("F",i)
followers.append(v)
#creating the leaders
for i in range(LNumber):
v = self.createVehicle("L",i)
leaders.append(v)

#CONNECT THE FIELDS TO THE RIGID BODIES (AGENTS)
#1) connect the leaders (predacious fishes) to the followers (small fishes)
for i in range (LNumber):
Lfield = leaders[i][2]
lfield = leaders[i][1]
for j in range(FNumber):
Frigid = followers[j][0]
#connect the fields
cmds.connectDynamic(Frigid, fields=Lfield)
cmds.connectDynamic(Frigid, fields=lfield)

#2) connect followers (small fishes) to leaders (predacious fishes)
for i in range(FNumber):
Ffield = followers[i][1]
for j in range(LNumber):
Lrigid = leaders[j][0]
cmds.connectDynamic(Lrigid, fields=Ffield)

#3) connect leaders (predacious fishes) to leaders ((predacious fishes))
for i in range(LNumber):
Lfield = leaders[i][1]
for j in range(LNumber):
if i==j: continue
L1rigid = leaders[j][0]
cmds.connectDynamic(L1rigid, fields=Lfield)

#4) connect followers (small fishes) to followes (small fishes)
for i in range(FNumber):
Ffield = followers[i][1]
for j in range(FNumber):
if i==j: continue
F1rigid = followers[j][0]

cmds.connectDynamic(F1rigid, fields=Ffield)





#create obstacles if I want
if self.obst: self.collectObstacles()

#disable solver warnings
cmds.cycleCheck(e=0)

def collectObstacles(self):
"Collects all obstacles"
if len(self.collectObjects) == 0:
#there is nothing selected
return "There is nothing selected!"

for o in self.collectObjects:
cmds.rigidBody( o,
passive=1,
name=o+"_rb",
bounciness=2.0 )






### create an instance of this class
c = Crowd()

Thursday, August 6, 2009

Assignment01B

I managed to make the part with the rotation and the scale of the square but when i tried to make it recursive i could not manage to select all the time the last square created. I tried to make a list where to store all of them and always refer to it from the list but it doesn't work as well.


###########################
###assignment01B
###student Andreea Nica


import maya.cmds as cmds


def squares (it,i):

##select the needed sides of the square
t=i-1
cmds.select('nurbsSquare%d'%t)
isSides = cmds.filterExpand(sm=9)

line1 = isSides[0]
line2 = isSides[1]

##get the point on the side of the square at the specific proportion
poc1 = cmds.pointOnCurve( line1, pr=perc1, top=True, p=True ) #rightnurbsSquare
poc2 = cmds.pointOnCurve( line2, pr=perc2, top=True, p=True )

##find the corner of the square in order to find the exact position where the second square will be moved
perc3 =1
corner = cmds.pointOnCurve( line2, pr=perc3, top=True, p=True )

##create the second square

cmds.duplicate('nurbsSquare%d'%t)
if t <> 1:
SquaresList.append('nurbsSquare%d'%t)

##find the position where the last square will be placed
x = corner[0]-poc1[0]
xx=float(x/3)
y= corner[0]
yy=float(y/3)

##move the square
cmds.move (xx,yy,0, 'nurbsSquare%d'%i)
cmds.select('nurbsSquare%d'%i)

##find the pivot for scale and rotation
x1=float(poc2[0])
y1=float(poc2[1])

##scale and rotate
cmds.scale( .8, .8, .8, 'nurbsSquare%d'%i, pivot=(x1, y1, 0), absolute=True )
cmds.rotate(0,0,'20deg',pivot=(x1, y1, 0),absolute=True)

##select only the last square created
cmds.select( clear=True )
cmds.select('nurbsSquare%d'%i)

cmds.hide('nurbsSquare%d'%t)

##check if the last iteration was reached or not
if it == 0 :
#stop
cmds.showHidden( all=True )
print 'gataaaaaaaaaaaaaaaa'
return "Done."
else:
#did not finish yet
#remove one unit (count down)
it -= 1
i += 1

squares(it,i)

##create the initial square
initialSquare = cmds.nurbsSquare( sl1=10, sl2=10 )
isSides = cmds.filterExpand(sm=9)
print isSides
perc1 = 1./3
perc2 = 2./3

SquaresList = []
SquaresList.append('nurbsSquare1')
print SquaresList
##call the recursive function

squares(4,2)

print 'Final List'
print SquaresList

Thursday, July 30, 2009

Tuesday, July 28, 2009

Assignment 01B, fianl, Liu

















#######################################################
# Assignment 01B Recursion
# Editted by Liu, Ko-cheng
# Logic:
# Step1: Set up initial conditions
# setup01): Create Biggest and smallest circles
# setup02): Make these two circles tangent
# Step2: Define the principles of how to get the next cirlce tangent with previous two
# Step3: Start the recursion by the loop
###########################################################



import maya.cmds as cmds

#Step1:Define the biggest and smallest circles
BigRadius=30
SmallRadius=2
Minus= BigRadius-SmallRadius

# Create these two circles which are tangent to each other
cmds.circle(c=(0,0,0),r=30)
cmds.circle(c=(0,-28,0),r=2)

#Step2:Generate two circles which follow the tangent princples
#2.1)r1+r2=D
NextRadius=SmallRadius+1
D= NextRadius+SmallRadius
cmds.circle(n="Mcircle",c=(0,-28,0),r=D)

#2.2)offset the outmost circle based on the radius of next circle
cmds.circle(n="Moffset",c=(0,0,0), r=BigRadius-NextRadius)
#2.3)Get the intersection point at the right side and as the center point of the new circle
# which is tangent with previous two circles

inters = cmds.curveIntersect('Mcircle','Moffset')
inters = inters.split()
print inters
inters1 = inters[1:2]
for i in inters1:
u = float(i)
pos1=cmds.pointOnCurve("Mcircle", p=1, pr=u)
myCircle=cmds.circle(c=pos1,r=3)
cmds.delete('Mcircle','Moffset')

#Step3: Loop through it based on previous steps
for i in range(1,BigRadius-3,1):
cmds.circle(n="myOffset"+str(i),c=(0,0,0),r=Minus-i-1)
cmds.rotate
radius=2+i
r1= radius
r2= radius+1
D=r1+r2

cmds.circle(n="mycircle"+str(i),c=pos1,r=D)
cmds.rotate(0,0,20*i,cp=u)
myInters= cmds.curveIntersect('mycircle'+str(i),'myOffset'+str(i))
myInters= myInters.split()
print myInters

myInters= myInters[0:2]
for j in myInters:
u=float(j)
if 4 < pos2="cmds.pointOnCurve(" p="1,pr="u)" mycircle="cmds.circle(c="pos2,r="i+3)" pos1="pos2">

Assignment 03 Shi xinyu & Liu

There are still some problems among the scripting, we would like to ask how to solve the problems.
1) Since our initial idea is to show the good and bad objects in certain time, and the agent will be attracted. But we couldn't find out how to show the object in some specific times. (Which command we need to use in the scripting?)
2) We can make it work when the agent hits the good angel, but not working in Bad Evil. We still don't know why it doesn't work. We know the "hit" part is among the mel scripting and we couldn't understand the mel code so well.

These are the two main problems we have met so far. We have done our best, and thank you for your teaching in whole semester!

Liu & Shi

Assignment 03 Shi xinyu & Liu


################################################################
## Assignment03 Crowd System
## Professor: Daniel da Rocha
## Students: Liu, ko-cheng & Shi, xinyu
##
## Logic
## Create 3 kinds of objs
## 1. agent
## a) active movement
## 2. Good Angel (helps increase the size of agent)
## a) passive movement
## 3. Bad Evil (shrink the size of agent)
## a) non-movable
## When the agents hit the Good Angel, they increase the size.
## On ther other hand, they shrink when they hit the Bad Evil
##
## Initial Set up:
## 1. Create a cyclinder as wall that holds all the objs inside
###################################################################

import maya.cmds as cmds
import maya.mel as mel
import random
import math

def hit(hit, agent, GoodAngel, BadEvil):
### define what to do when it some collision is detected
#all transformations are made only on the agent, as the hit object will perform the same queries on this agent
#if it hit the cube, ignore
if hit == "wall_rigid":
return
agentRole = cmds.getAttr(agent + ".role")
hitRole = cmds.getAttr(hit + ".role")
GoodAngelRole= cmds.getAttr(GoodAngel+".role")
BadEvilRole= cmds.getAttr(BadEvil+".role")
if hitRole == GoodAngelRole:
if hitRole== "good":
cmds.scale(1.1,1.1,1.1, agent, r=1)
elif hitRole == GoodAngelRole:
if hitRole == "bad":
cmds.scale(.1,.1,.1, agent, r=1)
elif hitRole == agentRole:
#check if both are bad
if hitRole == "bad":
#then shrink
cmds.scale(.9,.9,.9, agent, r=1)
else:
#if good, increase size
cmds.scale(1.1,1.1,1.1, agent, r=1)
elif hitRole != agentRole:
if hitRole == "bad":
#means agent role is good
cmds.scale(.90,.90,.90, agent, r=1)
elif hitRole == "good":
#means agent was bad
cmds.scale(1.1,1.1,1.1, agent, r=1)


#function to create shader
def createShader(color, transparency=0, type="lambert"):
#steps to create a new material
shadingNode1 = cmds.shadingNode(type, asShader=1)
shadingNode2 = cmds.sets(renderable=1, noSurfaceShader = 1, empty=1, name=shadingNode1+"SG")
cmds.connectAttr(shadingNode1+".outColor", shadingNode2 + ".surfaceShader", force=1)
#steps to modify material attributes
cmds.setAttr(shadingNode1 + ".color", color[0],color[1], color[2]) #color in r g b values
cmds.setAttr(shadingNode1 + ".transparency", transparency, transparency, transparency)

return shadingNode2

def applyShaderOnObject(obj, shader):
cmds.sets(obj, e=1, forceElement=shader)




class Agent:
def __init__(self, solver, role, position=(0,0,0), size=(3,3,3), color=(0,0,0), objType="cube", rigidType="active", bounciness=.6, collide=1):
#set agent atributes
self.bounciness = bounciness
self.collide = collide
self.rigidType = rigidType
self.solver=solver
self.role = role
self.initialScale = size
#create the agent and scale it
self.object = cmds.polyCube(ax=(0,0,1))
cmds.scale(size[0], size[1], size[2])
#apply a color to the agent
#set the object color
sh = createShader(color, transparency=0, type="lambert")
applyShaderOnObject(self.object[0], sh)

#create the rigid body
self.rigid = cmds.rigidBody(self.object,
name=self.object[0] + "_rigid",
p=position,
b=self.bounciness,
impulse=(0,0,0),
sio=objType, #stand in object
cc = 1, #contact count
cp = 1, #contact position
cn = 1, #contact name
solver=self.solver)

#add attribute to the rigid body to store the type of agent
cmds.select(self.rigid, r=1)
cmds.addAttr(ln="role", dt="string", keyable=1)
cmds.setAttr(self.rigid + ".role", "good", type="string")

if self.rigidType == "active":
cmds.setAttr(self.rigid + ".active", 1)
else:
cmds.setAttr(self.rigid + ".active", 0)

#apply the expression
self.applyExpression()

def applyExpression(self):
"Function to apply the expression to the agent"
#first disconnect the rotation attributes because we want to controll it via expressions
cmds.disconnectAttr (self.rigid + "ry.output", self.object[0] + ".rotateY")
cmds.disconnectAttr (self.rigid + "rx.output", self.object[0] + ".rotateX")
cmds.disconnectAttr (self.rigid + "rz.output", self.object[0] + ".rotateZ")
# Create expression for VehicleF with a random multiplier added to the expression.
randX = random.uniform(-3,3)
randY = random.uniform(3,-3)
####COMPOSE THE EXPRESSION STRING
#this is how it should look like (in MEL)
'''
// Set wander motion of vehicle and add random multipliers.
pCube1_rigid_0.impulseX = sin(time * -2.808801);
pCube1_rigid_0.impulseY = (noise(time) * -1.041035);

// Set orientation of Vehicle according to the velocity direction.
float $fVel[];
$fVel = `getAttr pCube1_rigid_0.velocity`;

pCube1.rotateX = 0;
pCube1.rotateZ = atan2d( $fVel[0], $fVel[1] );
pCube1.rotateY = 0;

//checking bumps on other agents
string $lastHit;
if (pCube1_rigid_0.contactCount > 0){
int $contactCount = `getAttr pCube1_rigid_0.contactCount`;
$lastHit = `getAttr pCube1_rigid_0.contactName[0]`;
string $rigid = "pCube1_rigid_0";
string $rigid01 = "pSphere1_rigid_0";
python("hit('"+$lastHit+"', '"+ $rigid +"','"+rigid01+"')");
};//endif
'''
#now put the text above in a python string
#the first lines define how the agent will wander
expString = "// Set wander motion of vehicle and add random multipliers.\n"
expString += "%s.impulseX" % self.rigid
expString += " = sin(time * %f);\n" % randX
expString += "%s.impulseY" % self.rigid
expString += " = (noise(time) * %f);\n\n" % randY
#the second part, how it rotates according to the direction it is going (velocity vector)
expString += "// Set orientation of Vehicle according to the velocity direction.\n"
expString += "float $fVel[];\n"
expString += "$fVel = `getAttr %s.velocity`;\n\n" % (self.rigid)
expString += "%s.rotateX = 0;\n" % self.object[0]
expString += "%s.rotateZ = atan2d( $fVel[0], $fVel[1] );\n" % (self.object[0])
expString += "%s.rotateY = 0;\n\n" % self.object[0]
#the third part, checking bumps on other agents
expString += "//checking bumps on other agents\n"
expString += "string $lastHit;\n"
expString += "if (%s.contactCount > 0){\n" % self.rigid
expString += " int $contactCount = `getAttr %s.contactCount`;\n" % self.rigid
expString += " $lastHit = `getAttr %s.contactName[0]`;\n" %self.rigid
expString += ' string $rigid = "%s";\n' % self.rigid
expString += ' string $rigid01 = "%s";\n' % self.rigid
expString += ' string $rigid02 = "%s";\n' % self.rigid
expString += ' python("hit(\'"+$lastHit+"\', \'"+ $rigid +"\',\'"+ $rigid01 +"\',\'"+ $rigid02 +"\')");\n'
expString += "};//endif\n"



self.expString = expString
cmds.expression(s=expString)

class Goodobj:
def __init__(self, solver, role, position=(0,0,0), size=(3,3,3), color=(0,0,0), objType="cube", rigidType="active", bounciness=.6, collide=1):
#set Goodobj atributes
self.bounciness = bounciness
self.collide = collide
self.rigidType = rigidType
self.solver=solver
self.role = role
self.initialScale = size
#create the agent and scale it
self.object = cmds.polySphere(ax=(0,0,1))
cmds.scale(size[0], size[1], size[2])
#apply a color to the agent
#set the object color
sh = createShader(color, transparency=0, type="lambert")
applyShaderOnObject(self.object[0], sh)

#create the rigid body
self.rigid01 = cmds.rigidBody(self.object,
name=self.object[0] + "_rigid",
p=position,
b=self.bounciness,
impulse=(0,0,0),
sio=objType, #stand in object
cc = 1, #contact count
cp = 1, #contact position
cn = 1, #contact name
solver=self.solver)

#add attribute to the rigid body to store the type of agent
cmds.select(self.rigid01, r=1)
cmds.addAttr(ln="role", dt="string", keyable=1)
cmds.setAttr(self.rigid01 + ".role", "good", type="string")

if self.rigidType == "active":
cmds.setAttr(self.rigid01 + ".active", 1)
else:
cmds.setAttr(self.rigid01 + ".active", 0)


class Badobj:
def __init__(self, solver, role, position=(0,0,0), size=(3,3,3), color=(0,0,0), objType="cube", rigidType="active", bounciness=.6, collide=1):
#set Goodobj atributes
self.bounciness = bounciness
self.collide = collide
self.rigidType = rigidType
self.solver=solver
self.role = role
self.initialScale = size
#create the agent and scale it
self.object = cmds.polyCone(ax=(0,0,1))
cmds.scale(size[0], size[1], size[2])
#apply a color to the agent
#set the object color
sh = createShader(color, transparency=0, type="lambert")
applyShaderOnObject(self.object[0], sh)

#create the rigid body
self.rigid02 = cmds.rigidBody(self.object,
name=self.object[0] + "_rigid",
p=position,
b=self.bounciness,
impulse=(0,0,0),
sio=objType, #stand in object
cc = 1, #contact count
cp = 1, #contact position
cn = 1, #contact name
solver=self.solver)

#add attribute to the rigid body to store the type of agent
cmds.select(self.rigid02, r=1)
cmds.addAttr(ln="role", dt="string", keyable=1)
cmds.setAttr(self.rigid02 + ".role", "good", type="string")

if self.rigidType == "active":
cmds.setAttr(self.rigid02 + ".active", 0)
else:
cmds.setAttr(self.rigid02 + ".active", 0)

##############################################
class Crowd:
def __init__(self, numAgents=20, numGoodobjs=20, numBadobjs=20,minPosition=-70, maxPosition=70, walls=0):
#set the playback options to increase the time range
cmds.playbackOptions(min= 1, max=5000)
self.numAgents = numAgents
self.numGoodobjs= numGoodobjs
self.numBadobjs= numBadobjs
self.minPosition = minPosition
self.maxPosition = maxPosition
#get any selected objects
self.wallObjs = cmds.ls(sl=1)
#create the rigid solver
self.solver = self.createSolver()
#create the agents
self.createAgents()
#create the goodobjs
self.createGoodobj()
#create the badobjs
self.createBadobj()
#create the walls
if walls: self.makeWalls()

def createSolver(self):
solver = cmds.rigidSolver( create=1,
current=1,
name="crowdSolver",
velocityVectorScale=0.5,
displayVelocity=1,
sc=1, #showcollision
ctd=1 #contact data
)
cmds.setAttr(solver + ".allowDisconnection", 1)
return solver

def createAgents(self):
type = ["good", (3,3,3), (1,1,0)] #name, scale, color
self.goodAgents = []
for i in range(self.numAgents):
#get the agent type randomly
#get random x and y
x = random.uniform(self.minPosition,self.maxPosition)
y = random.uniform(self.minPosition,self.maxPosition)
#create the agents
a = Agent(self.solver, type[0], color=type[2], size=type[1], position=(x,y,0))

self.goodAgents.append(a)
def createGoodobj(self):
type = ["good", (3,3,3), (1,0,0)] #name, scale, color
self.goodobjs = []
for i in range(self.numGoodobjs):
#get the agent type randomly
#get random x and y
x = random.uniform(self.minPosition,self.maxPosition)
y = random.uniform(self.minPosition,self.maxPosition)
#create the agents
a = Goodobj(self.solver, type[0], color=type[2], size=type[1], position=(x,y,0))

self.goodobjs.append(a)

def createBadobj(self):
type = ["bad", (2,2,2), (0,0,0)] #name, scale, color
self.Badobjs = []
for i in range(self.numBadobjs):
#get the agent type randomly
#get random x and y
x = random.uniform(self.minPosition,self.maxPosition)
y = random.uniform(self.minPosition,self.maxPosition)
#create the agents
a = Badobj(self.solver, type[0], color=type[2], size=type[1], position=(x,y,0))
self.Badobjs.append(a)


def makeWalls(self):
#get selected object,
#which should be already with its normals facing to the right directions,
#and convert it to passive rigid bodies
if len(self.wallObjs) == 0:
return "No wall objects were selected."
else:
for w in self.wallObjs:
self.wallRigid = cmds.rigidBody(w, passive=1, name= "wall_rigid", bounciness=.8)
########################################
c=Crowd(numAgents=2,numGoodobjs=10,numBadobjs=20,walls=1)

Monday, July 27, 2009

assignment 01B-Shi Xinyu




###############################################################
## Assignment 01
## Pof.Daniel da Rocha
## Student.SHI Xinyu
###############################################################

# logic
# 1) creste an initial square
# 2) find these two points (pocA & pocB) for rotate the square:
# 1) get current line
# 2) use pointOnCurve find the four points of the square
# 3) use the formula to find the pocA or pocB
# 1) if this is even number times, find pocA as rotation piont
# 2) if this is odd number times, find pocB as rotation piont
# 3) select the initail square
# 4) copy & rotate the square by pocA or pocB
# 5) select the last square and run this again

import maya.cmds as cmds

# creating initial square
mySquare = cmds.nurbsSquare(sl1=6,sl2=20)

def realRecursionOpt2(iterations):
#select mySquare
cmds.select( cl=1 )
cmds.select( mySquare )
mySquareNew = cmds.duplicate( mySquare )

sides = cmds.filterExpand( sm=9 )

#create a list to store the positions
positions = []
for i in range( len(sides) ):
pos = cmds.pointPosition( sides[i] +".cv[0]" )
positions.append(pos)
print positions

Xa = ((positions[1][0] + positions[2][0])/2 + positions[0][0])/2
Ya = ((positions[1][1] + positions[2][1])/2 + positions[0][1])/2
Za = ((positions[1][2] + positions[2][2])/2 + positions[0][2])/2

Xb = ((positions[1][0] + positions[2][0])/2 + positions[3][0])/2
Yb = ((positions[1][1] + positions[2][1])/2 + positions[3][1])/2
Zb = ((positions[1][2] + positions[2][2])/2 + positions[3][2])/2

if iterations/2 ==0:
cmds.rotate( 0,0,30, pivot=(Xa, Ya, Za) )
else:
cmds.rotate( 0,0,30, pivot=(Xb, Yb, Zb) )

mySquare = mySquareNew

#recursion part
if iterations ==0:
return "Done"
else:
iterations -=1
realRecursionOpt2(iterations)

realRecursionOpt2(1)

Tuesday, July 21, 2009

Assignment 03 B - second try

This is what should be our assignment. The error is the same like in the previous script. Here we added more pavilions and a field for each pavilion and we connected the elements.





###############crowd system
###Assignment 03B

#generate random static attractors
#generate random static repulsors
#generate random dynamic principle attractors
#generate random dynamic followers

#


import maya.cmds as cmds
from random import *


class Crowd:
def __init__(self):
"Initialize attributes"
#objects for obstacles
self.collectObjects = []
#number of vehicles
self.vNumber = 0
#boolean for obstacles
self.obst = 0
#boolean for global forces
self.gforces = 0
#dictionary for UI elements
self.UIelements = {}
#set timeline
cmds.playbackOptions(min= 1, max=1000)
#get selected objects
self.collectObjects = cmds.ls(sl=1)
#start UI
self.crowdSystemUI()

def crowdSystemUI(self):
"Assembles and displays the UI for the Crowd System"
self.UIelements["window"] = cmds.window(title="Crowd System",
widthHeight=(300, 200)
)

self.UIelements["form"] = cmds.formLayout()
txt = cmds.text(label="Number of Vehicles")
collection = cmds.radioCollection()
radiob1 = cmds.radioButton(label="10", data=1, changeCommand=self.changeVnumber)
radiob2 = cmds.radioButton(label="20", onCommand="vNumber = 20")
cmds.setParent(upLevel=1)
cmds.setParent(upLevel=1)

txtOB = cmds.text(label="Obstacles")
collection2 = cmds.radioCollection()
radiob3 = cmds.radioButton(label="On", changeCommand=self.changeObst)
radiob4 = cmds.radioButton(label="Off")
cmds.setParent(upLevel=1)
cmds.setParent(upLevel=1)

txtGF = cmds.text( label = "Global Forces")
collection3 = cmds.radioCollection()
radiob5 = cmds.radioButton(label= "On" ,changeCommand =self.changeGforces)
radiob6 = cmds.radioButton(label="Off")
cmds.setParent(upLevel=1)
cmds.setParent(upLevel=1)

cmds.radioCollection(collection, edit=1, select=radiob1)
cmds.radioCollection(collection2, edit=1, select=radiob4)
cmds.radioCollection(collection3, edit=1, select=radiob6)

# Place Vehicle options
form = self.UIelements["form"]
cmds.formLayout(form,
edit=1,
attachForm= [
( txt, "top", 20),
(txt ,"left", 70),
(radiob1,"top", 10),
(radiob1,"left", 20),
(radiob2,"top", 30),
(radiob2,"left", 20)
]
)
# Place environment options
cmds.formLayout(form,
edit=1,
attachForm= [
(txtOB, "top", 80),
(txtOB, "left", 80),
(radiob3, "top", 80),
(radiob3, "left", 150),
(radiob4 ,"top", 80),
(radiob4, "left", 190),
(txtGF, "top", 110),
(txtGF, "left", 63),
(radiob5, "top", 110),
(radiob5, "left", 150),
(radiob6, "top", 110),
(radiob6, "left", 190)
]
)
# Create buttons
button1 = cmds.button(label = "Create")
button2 = cmds.button(label = "Cancel")

# Place buttons in the window
cmds.formLayout(form,
edit=1,
attachForm =[
(button1, "bottom", 10),
(button1, "left", 185),
(button2, "bottom", 10),
(button2, "right", 10)
]
)
# Add the commands to the buttons.
cmds.button(button1, edit=1, command=self.createCrowd )
cmds.button(button2, edit=1, command=self.deleteUI )

cmds.showWindow(self.UIelements["window"])
## UI help functions
def changeVnumber(self, *args):
if args[0] == "true":
self.vNumber = 10
else:
self.vNumber = 20
print "vNumber:",self.vNumber
def changeObst(self, *args):
if args[0] == "true":
self.obst = 1
else:
self.obst = 0
print "Obst:", self.obst
def changeGforces(self, *args):
if args[0] == "true":
self.gforces = 1
else:
self.gforces = 0
print "gforces:", self.gforces
def deleteUI(self, *args):
cmds.deleteUI(self.UIelements["window"])
self.UIelements["window"] = ""

## MAIN METHODS
def createCrowdSolver(self):
"Creates the main rigidSolver for the elements in the Crowd System"
self.crowdSolver = cmds.rigidSolver( create=1,
current=1,
name="crowdSolver",
velocityVectorScale=0.5,
displayVelocity=1
)
cmds.setAttr(self.crowdSolver + ".allowDisconnection", 1)

def createVehicle(self, vType, N):
"Creates one vehicle and add fields and expressions to it."
#first verify if the vehicle is of type follower (F) or leader (L)
#and set the size of the cube according to the type (leaders are bigger! :)
if vType == "P1":
w = 70 #width
h = 70#height
d = 70 #depth
if vType == "P2":
w = 100 #width
h = 100 #height
d = 100 #depth


if vType == "F1":
w = 2 #width
h = 2 #height
d = 2 #depth
if vType == "F2":
w = 2 #width
h = 4 #height
d = 2 #depth
if vType == "F3":
w = 2 #width
h = 6 #height
d = 2 #depth

if vType == "L1":
w = 5 #width
h = 3 #height
d = 5 #depth
if vType == "L2":
w = 5 #width
h = 5 #height
d = 5 #depth
else:
w = 5
h = 7
d = 5

#creates the basic cube
vehicle = cmds.polyCube(w=w,d=d,h=h)

#creates the pavilion
pavilion1 = cmds.polyCube(w=w,d=d,h=h)
pavilion2 = cmds.polyCube(w=w,d=d,h=h)

#create a vehicule force to the agent - force 1
field1=cmds.radial(position=[0,0,0],
magnitude=50,
attenuation = 0.3,
maxDistance = 8.0
)

cmds.parent(field1[0], vehicle[0])
cmds.hide(field1)

if vType=="L1":
Lfield1 = cmds.radial(position=[0,0,0],
magnitude=-1,
attenuation=.2,
maxDistance=50
)

cmds.parent(Lfield1[0], vehicle[0])
cmds.hide(Lfield1)

#create a vehicule force to the agent - force 2
field2=cmds.radial(position=[0,0,0],
magnitude=50,
attenuation = 0.3,
maxDistance = 8.0
)

cmds.parent(field2[0], vehicle[0])
cmds.hide(field2)

if vType=="L2":
Lfield2 = cmds.radial(position=[0,0,0],
magnitude=-1,
attenuation=.2,
maxDistance=50
)

cmds.parent(Lfield2[0], vehicle[0])
cmds.hide(Lfield2)

#create a vehicule force to the agent - force 3
field3=cmds.radial(position=[0,0,0],
magnitude=50,
attenuation = 0.3,
maxDistance = 8.0
)

cmds.parent(field3[0], vehicle[0])
cmds.hide(field3)

if vType=="L3":
Lfield3 = cmds.radial(position=[0,0,0],
magnitude=-1,
attenuation=.2,
maxDistance=50
)

cmds.parent(Lfield3[0], vehicle[0])
cmds.hide(Lfield3)

#create a static force to the agent - force 4
field4=cmds.radial(position=[0,0,0],
magnitude=50,
attenuation = 0.3,
maxDistance = 8.0
)

cmds.parent(field4[0], pavilion1[0])
cmds.hide(field4)

if vType=="P1":
Lfield4 = cmds.radial(position=[0,0,0],
magnitude=-1,
attenuation=.2,
maxDistance=70
)

cmds.parent(Lfield4[0], pavilion1[0])
cmds.hide(Lfield4)

#create a static force to the agent - force 5
field5=cmds.radial(position=[0,0,0],
magnitude=50,
attenuation = 0.3,
maxDistance = 8.0
)

cmds.parent(field5[0], pavilion2[0])
cmds.hide(field5)

if vType=="P2":
Lfield5 = cmds.radial(position=[0,0,0],
magnitude=-1,
attenuation=.2,
maxDistance=100
)

cmds.parent(Lfield5[0], pavilion2[0])
cmds.hide(Lfield5)


#convert vehicle to a rigid body with random placement
rigid = cmds.rigidBody(
vehicle[0],
n="rigidVeh1%s%d" %(vType, N),
active=1,
mass=1,
bounciness=0,
damping=1.5,
position=(uniform(-70,70),uniform(-70,70),0),
impulse=(0,0,0),
standInObject="cube",
solver=self.crowdSolver
)

#convert pavillion1 to a passive rigid body with random placement
rigid = cmds.rigidBody(
pavilion1[0],
n="rigidVeh1%s%d" %(vType, N),
active=0,
mass=1,
bounciness=0,
damping=1.5,
position=(uniform(-70,70),uniform(-70,70),0),
impulse=(0,0,0),
standInObject="cube",
solver=self.crowdSolver
)

#convert pavillion2 to a passive rigid body with random placement
rigid = cmds.rigidBody(
pavilion2[0],
n="rigidVeh1%s%d" %(vType, N),
active=0,
mass=1,
bounciness=0,
damping=1.5,
position=(uniform(-70,70),uniform(-70,70),0),
impulse=(0,0,0),
standInObject="cube",
solver=self.crowdSolver
)

#disconnect the rotation attributes of the vehicle
cmds.disconnectAttr(rigid + "rx.output", vehicle[0]+".rx")
cmds.disconnectAttr(rigid + "ry.output", vehicle[0]+".ry")
cmds.disconnectAttr(rigid + "rz.output", vehicle[0]+".rz")

#add expression for movement
randX = uniform(-3,3)
randY = uniform(-3,3)

expString = "%s.impulseX = sin(time * %f);" % (rigid, randX)
expString += "%s.impulseY = (noise(time)*%f);" % (rigid, randY)
expString += "float $Vel[] = `getAttr %s.velocity`;" % rigid
expString += "%s.rotateX = 0;" % vehicle[0]
expString += "%s.rotateY = 0;" % vehicle[0]
expString += "%s.rotateZ = atan2d( $Vel[0], $Vel[2] );" % vehicle[0]

cmds.expression(s=expString)

if vType == "F1":
return [rigid, field] #returns the name of the function

else:
return[rigid, field, Lfield1]

if vType == "F2":
return [rigid, field] #returns the name of the function

else:
return[rigid, field, Lfield2]

if vType == "F3":
return [rigid, field] #returns the name of the function

else:
return[rigid, field, Lfield3]

def createCrowd(self, *args):
"Method to assemble the whole system"
#creates a rigidSolver to add the vehicle to
self.createCrowdSolver()
#turn on the velocity arrow
cmds.setAttr(self.crowdSolver + ".displayVelocity", 1)
cmds.setAttr(self.crowdSolver + ".scaleVelocity", .5)

#allow disconnections on the rigidSolver
cmds.setAttr(self.crowdSolver + ".allowDisconnection", 1)

###create amount of agents
if self.vNumber == 10:
FNumber = 8
LNumber = 2
elif self.vNumber == 20:
FNumber=18
Lnumber=2


#create empty lists to store followers and leaders
followers1=[]
leaders1=[]
followers2=[]
leaders2=[]
followers3=[]
leaders3=[]
pavilions1=[]
pavilions2=[]

#create the followers
for i in range(FNumber):
if i%3 == 0:
v=self.createVehicle("F1",i)
followers1.append(v)

if i%3 == 1:
v=self.createVehicle("F2",i)
followers2.append(v)

if i%3 == 2:
v=self.createVehicle("F3",i)
followers3.append(v)

#create the leaders
for i in range(LNumber):
if i%3 == 0:
v=self.createVehicle("L1",i)
leaders1.append(v)

if i%3 == 1:
v=self.createVehicle("L2",i)
leaders2.append(v)

if i%3 == 2:
v=self.createVehicle("L3",i)
leaders3.append(v)

#create static attractor
for i in range(2):
if i%2 == 0:
v=self.createVehicle("P1",i)
pavilions1.append(v)

if i%2 == 1:
v=self.createVehicle("P2",i)
pavilions2.append(v)



cmds.polyCube( sx=10, sy=15, sz=5, h=20 )
#result is a 20 units height rectangular box
#with 10 subdivisions along X, 15 along Y and 20 along Z.





#CONNECT THE FIELDS TO THE RIGID BODIES(AGENTS)
#1) Connect the leaders with the followers 1-1

for i in range(LNumber):
if i%3 == 0:
Lfield1=leaders1[i][2]
lfield1=leaders1[i][1]
for j in range (FNumber):
if j%3 == 0:
Frigid1 = followers1[j][0]
#connect the fields
cmds.connectDynamic(Frigid1, fields=Lfields)
cmds.connectDynamic(Frigid1, fields=lfields)

if i%3 == 1:
Lfield2=leaders2[i][2]
lfield2=leaders2[i][1]
for j in range (FNumber):
if j%3 == 1:
Frigid1 = followers2[j][0]
#connect the fields
cmds.connectDynamic(Frigid2, fields=Lfields)
cmds.connectDynamic(Frigid2, fields=lfields)

else:
Lfield3=leaders3[i][2]
lfield3=leaders3[i][1]
for j in range (FNumber):
if j%3 == 2:
Frigid3 = followers3[j][0]
#connect the fields
cmds.connectDynamic(Frigid3, fields=Lfields)
cmds.connectDynamic(Frigid3, fields=lfields)




#2) Connect followers to leaders
for i in range(FNumber):
if i%3 == 0:
Ffield1 = followers1[i][1]
for j in range(LNumber):
if j%3 == 0:
Lrigid1 = leaders1[j][0]
cmds.connectDynamic(Lrigid1, fields=Ffield)


if i%3 == 1:
Ffield2 = followers2[i][1]
for j in range(LNumber):
if j%3 == 1:
Lrigid2 = leaders2[j][0]
cmds.connectDynamic(Lrigid2, fields=Ffield)

else:
Ffield3 = followers3[i][1]
for j in range(LNumber):
if j%3 == 2:
Lrigid3 = leaders3[j][0]
cmds.connectDynamic(Lrigid3, fields=Ffield)




#3) Connect leaders to leaders
for i in range (LNumber):
if i%3 == 0:
Lrigid1 = leaders1[i][0]
Lfield1 = leaders1[i][1]
for j in range(LNumber):
if i == f: continue
if j%3 == 0:
L1rigid = leaders1[j][0]
#l1field = leaders1[j][1]
cmds.connectDynamic(L1rigid, fields=Lfield)

if i%3 == 1:
Lrigid2 = leaders2[i][0]
Lfield2 = leaders2[i][1]
for j in range(LNumber):
if i == f: continue
if j%3 == 1:
L1rigid = leaders2[j][0]
#l1field = leaders1[j][1]
cmds.connectDynamic(L1rigid, fields=Lfield)

if i%3 == 2:
Lrigid3 = leaders3[i][0]
Lfield3 = leaders3[i][1]
for j in range(LNumber):
if i == f: continue
if j%3 == 2:
L1rigid = leaders3[j][0]
#l1field = leaders1[j][1]
cmds.connectDynamic(L1rigid, fields=Lfield)

#4) Connect followers to followers
for i in range(FNumber):
if i%3 == 0:
Ffield1=followers1[i][1]
for j in range(FNumber):
if i==j: continue
if j%3 == 0:
Frigid1 = followers1[j][0]

cmds.connectDynamics(Frigid1, fields=Ffield)
if i%3 == 1:
Ffield2=followers2[i][1]
for j in range(FNumber):
if i==j: continue
if j%3 == 1:
Frigid2 = followers2[j][0]

cmds.connectDynamics(Frigid2, fields=Ffield)
else:
Ffield3=followers3[i][1]
for j in range(FNumber):
if i==j: continue
if j%3 == 2:
Frigid3 = followers3[j][0]

cmds.connectDynamics(Frigid3, fields=Ffield)





#create obstacles if i want
if self.obst:self.collectObstacles()




#disable solver warnings
cmds.cycleCheck(e=0)

#disable solver warnings
cmds.cycleCheck(e=0)

def collectObstacles(self):
"Collects all obstacles"
if len(self.collectObjects) == 0:
#there is nothing selected
return "There is nothing selected!"

for o in self.collectObjects:
cmds.rigidBody( o,
passive = 1,
name=o+"_rb",
bounciness=2.0)

#craete an instance for this class
c=Crowd()

Assignment 03B - first try

In this script we tried to add pavilions(by script) and obstacles(manually in maya). It seams to be something wrong when we define the pavilions. Pavilions are static rigid bodies. The only difference between vehicles and pavilions is the varriable active, which is 0 for pavilions. It is a wrong way to define pavilions like that?


#######################################################################################################
##
## CROWD SYSTEM
## Adapted from original idea by Mark R. Wilkins and Chris Kazmier
##
## Modified: 22.06.09 by Daniel da Rocha
##
## Last Modified: 21.07.09 by Alexandra Virlan and Mircea Mogan
##
#######################################################################################################


import maya.cmds as cmds
from random import *


class Crowd:
def __init__(self):
"Initialize attributes"
#objects for obstacles
self.collectObjects = []
#number of vehicles
self.vNumber = 0
#boolean for obstacles
self.obst = 0
#boolean for global forces
self.gforces = 0
#dictionary for UI elements
self.UIelements = {}
#set timeline
cmds.playbackOptions(min= 1, max=1000)
#get selected objects
self.collectObjects = cmds.ls(sl=1)
#start UI
self.crowdSystemUI()

def crowdSystemUI(self):
"Assembles and displays the UI for the Crowd System"
self.UIelements["window"] = cmds.window(title="Crowd System",
widthHeight=(300, 200)
)

self.UIelements["form"] = cmds.formLayout()
txt = cmds.text(label="Number of Vehicles")
collection = cmds.radioCollection()
radiob1 = cmds.radioButton(label="10", data=1, changeCommand=self.changeVnumber)
radiob2 = cmds.radioButton(label="20", onCommand="vNumber = 20")
cmds.setParent(upLevel=1)
cmds.setParent(upLevel=1)

txtOB = cmds.text(label="Obstacles")
collection2 = cmds.radioCollection()
radiob3 = cmds.radioButton(label="On", changeCommand=self.changeObst)
radiob4 = cmds.radioButton(label="Off")
cmds.setParent(upLevel=1)
cmds.setParent(upLevel=1)

txtGF = cmds.text( label = "Global Forces")
collection3 = cmds.radioCollection()
radiob5 = cmds.radioButton(label= "On" ,changeCommand =self.changeGforces)
radiob6 = cmds.radioButton(label="Off")
cmds.setParent(upLevel=1)
cmds.setParent(upLevel=1)

cmds.radioCollection(collection, edit=1, select=radiob1)
cmds.radioCollection(collection2, edit=1, select=radiob4)
cmds.radioCollection(collection3, edit=1, select=radiob6)

# Place Vehicle options
form = self.UIelements["form"]
cmds.formLayout(form,
edit=1,
attachForm= [
( txt, "top", 20),
(txt ,"left", 70),
(radiob1,"top", 10),
(radiob1,"left", 20),
(radiob2,"top", 30),
(radiob2,"left", 20)
]
)
# Place environment options
cmds.formLayout(form,
edit=1,
attachForm= [
(txtOB, "top", 80),
(txtOB, "left", 80),
(radiob3, "top", 80),
(radiob3, "left", 150),
(radiob4 ,"top", 80),
(radiob4, "left", 190),
(txtGF, "top", 110),
(txtGF, "left", 63),
(radiob5, "top", 110),
(radiob5, "left", 150),
(radiob6, "top", 110),
(radiob6, "left", 190)
]
)
# Create buttons
button1 = cmds.button(label = "Create")
button2 = cmds.button(label = "Cancel")

# Place buttons in the window
cmds.formLayout(form,
edit=1,
attachForm =[
(button1, "bottom", 10),
(button1, "left", 185),
(button2, "bottom", 10),
(button2, "right", 10)
]
)
# Add the commands to the buttons.
cmds.button(button1, edit=1, command=self.createCrowd )
cmds.button(button2, edit=1, command=self.deleteUI )

cmds.showWindow(self.UIelements["window"])
## UI help functions
def changeVnumber(self, *args):
if args[0] == "true":
self.vNumber = 10
else:
self.vNumber = 20
print "vNumber:",self.vNumber
def changeObst(self, *args):
if args[0] == "true":
self.obst = 1
else:
self.obst = 0
print "Obst:", self.obst
def changeGforces(self, *args):
if args[0] == "true":
self.gforces = 1
else:
self.gforces = 0
print "gforces:", self.gforces
def deleteUI(self, *args):
cmds.deleteUI(self.UIelements["window"])
self.UIelements["window"] = ""

## MAIN METHODS
def createCrowdSolver(self):
"Creates the main rigidSolver for the elements in the Crowd System"
self.crowdSolver = cmds.rigidSolver( create=1,
current=1,
name="crowdSolver",
velocityVectorScale=0.5,
displayVelocity=1
)
cmds.setAttr(self.crowdSolver + ".allowDisconnection", 1)

def createVehicle(self, vType, N):
"Creates one vehicle and add fields and expressions to it."
#first verify if the vehicle is of type follower (F) or leader (L)
#and set the size of the cube according to the type (leaders are bigger! :)
if vType == "F":
w = 2 #width
h = 2.5 #height
d = 2 #depth

if vType == "P":
w = 100 #width
h = 100 #height
d = 100 #depth

else:
w = 5
h = 3.5
d = 5

#creates the basic cube
vehicle = cmds.polyCube(w=w,d=d,h=h)
pavilion = cmds.polyCube(w=w,d=d,h=h)

#create a vehicule force to the agent
field=cmds.radial(position=[0,0,0],
magnitude=50,
attenuation = 0.3,
maxDistance = 8.0
)

cmds.parent(field[0], vehicle[0])
cmds.parent(field[0], pavilion[0])
cmds.hide(field)

if vType=="L":
Lfield = cmds.radial(position=[0,0,0],
magnitude=-1,
attenuation=.2,
maxDistance=50
)

cmds.parent(Lfield[0], vehicle[0])
cmds.hide(Lfield)

#convert it to a rigid body with random placement
rigid = cmds.rigidBody(
vehicle[0],
n="rigidVeh1%s%d" %(vType, N),
active=1,
mass=1,
bounciness=0,
damping=1.5,
position=(uniform(-70,70),uniform(-70,70),0),
impulse=(0,0,0),
standInObject="cube",
solver=self.crowdSolver
)

rigid = cmds.rigidBody(
pavilion[0],
n="rigidVeh1%s%d" %(vType, N),
active=0,
mass=1,
bounciness=0,
damping=1.5,
position=(uniform(-70,70),uniform(-70,70),0),
impulse=(0,0,0),
standInObject="cube",
solver=self.crowdSolver
)

#disconnect the rotation attributes of the vehicle ??)?)?)?)
cmds.disconnectAttr(rigid + "rx.output", vehicle[0]+".rx")
cmds.disconnectAttr(rigid + "ry.output", vehicle[0]+".ry")
cmds.disconnectAttr(rigid + "rz.output", vehicle[0]+".rz")

#add expression for movement
randX = uniform(-3,3)
randY = uniform(-3,3)

expString = "%s.impulseX = sin(time * %f);" % (rigid, randX)
expString += "%s.impulseY = (noise(time)*%f);" % (rigid, randY)
expString += "float $Vel[] = `getAttr %s.velocity`;" % rigid
expString += "%s.rotateX = 0;" % vehicle[0]
expString += "%s.rotateY = 0;" % vehicle[0]
expString += "%s.rotateZ = atan2d( $Vel[0], $Vel[2] );" % vehicle[0]

cmds.expression(s=expString)

if vType == "F":
return [rigid, field] #returns the name of the function

if vType == "L":
return[rigid, field, Lfield]

else:
return[rigid, field, Pfield]

def createCrowd(self, *args):
"Method to assemble the whole system"
#creates a rigidSolver to add the vehicle to
self.createCrowdSolver()
#turn on the velocity arrow
cmds.setAttr(self.crowdSolver + ".displayVelocity", 1)
cmds.setAttr(self.crowdSolver + ".scaleVelocity", .5)

#allow disconnections on the rigidSolver
cmds.setAttr(self.crowdSolver + ".allowDisconnection", 1)

###create amount of agents
if self.vNumber == 10:
FNumber = 8
LNumber = 2
elif self.vNumber == 20:
FNumber=18
Lnumber=2

#create empty lists to store followers and leaders
followers=[]
leaders=[]
pavilions=[]
#create the followers
for i in range(FNumber):
v=self.createVehicle("F",i)
followers.append(v)

#create the leaders
for i in range(LNumber):
v=self.createVehicle("L",i)
leaders.append(v)

create pavilion
for i in range(1):
v=self.createVehicle("P",i)
pavilions.append(v)



#CONNECT THE FIELDS TO THE RIGID BODIES(AGENTS)
#1) Connect the leaders with the followers

for i in range(LNumber):
Lfield=leaders[i][2]
lfield=leaders[i][1]
for j in range (FNumber):
Frigid = followers[j][0]
#connect the fields
cmds.connectDynamic(Frigid, fields=Lfields)
cmds.connectDynamic(Frigid, fields=lfields)


#2) Connect followers to leaders
for i in range(FNumber):
Ffield = followers[i][1]
for j in range(LNumber):
Lrigid = leaders[j][0]
cmds.connectDynamic(Lrigid, fields=Ffield)

#3) Connect leaders to leaders
for i in range (LNumber):
Lrigid = leaders[i][0]
Lfield = leaders[i][1]
for j in range(LNumber):
if i == f: continue
L1rigid = leaders[j][0]
#l1field = leaders[j][1]
cmds.connectDynamic(L1rigid, fields=Lfield)

#4) Connect followers to followers
for i in range(FNumber):
Ffield=followers[i][1]
for j in range(FNumber):
if i==j: continue
Frigid = followers[j][0]

cmds.connectDynamics(Frigid, fields=Ffield)

#5) Connect the pavilion with the leaders

for i in range(1):
Pfield=pavilions[i][2]
Lfield=pavilions[i][1]

for j in range (LNumber):
Frigid = leaders[j][0]
#connect the fields
cmds.connectDynamic(Frigid, fields=Pfields)
cmds.connectDynamic(Frigid, fields=Lfields)


#6) Connect leaders to pavilions
for i in range(LNumber):
Lfield = leaders[i][1]
for j in range(1):
Frigid = pavilions[j][0]
cmds.connectDynamic(Prigid, fields=Lfield)

#create obstacles if i want
if self.obst:self.collectObstacles()

#disable solver warnings
cmds.cycleCheck(e=0)

#disable solver warnings
cmds.cycleCheck(e=0)

def collectObstacles(self):
"Collects all obstacles"
if len(self.collectObjects) == 0:
#there is nothing selected
return "There is nothing selected!"

for o in self.collectObjects:
cmds.rigidBody( o,
passive = 1,
name=o+"_rb",
bounciness=2.0)

#craete an instance for this class
c=Crowd()