Showing posts with label assignments. Show all posts
Showing posts with label assignments. Show all posts

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


################################################################
## 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 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()


Sunday, June 14, 2009

I'm not stupid :-)




import maya.cmds as cmds

def IsBounded(item):
for x in item:
if x < 0:
return False
return True

class delauney:
def __init__(self):
self.vertices = []
self.regions = []
self.dimension = ""
self.path = "C:/MAYA/"
print "Instance of class Delauney created."

def load(self):
# Get vertices positions in the points.txt

print "Loading Qhull file..."
# Open the file and get the second line in order to get the number of vertices
f = open('C:/MAYA/points.txt', 'r')
d = f.readline()
i = f.readline()
i = int(i.strip())

# Get line by line the x, y positions (and z if it exists)
while i > 0:
l = f.readline()
t = l.split()
pt1 = float(t[0])
pt2 = float(t[1])
if len(t) > 2:
pt3 = float(t[2])
self.dimension = "3D"
self.vertices.append([pt1, pt2, pt3])

else:
pt3 = 0
self.dimension = "2D"
self.vertices.append([pt1, pt2])
i = i-1

# Feedback
print ">>> RESULTS"
print len(self.vertices), " vertices ", self.vertices

# Open the qHullResults.txt in order to get the name of the points to join.
# Get the first number, in order to get number of regions
# Daniel, I'm sorry for the hardcoding for the names of the files, and for the "region.append(int(t[2]))" if its not a 3D drawing, but i'm really tired
f = open('C:/MAYA/qHullResults.txt', 'r')
l = f.readline()
i = int(l)

# Get line by line the name of the points to join
while i > 0:
l = f.readline()
t = l.split()
region = []
j=0
while j < i:
region.append(int(t[0]))
region.append(int(t[1]))
region.append(int(t[2]))
j = j + 1
self.regions.append(region)
i = i-1

# Feedback
print len(self.regions), " regions ", self.regions
f.close()

def draw(self):
# draw a curve between the points to create the regions!

for region in filter(IsBounded, self.regions):
vs = []
neg = 0

for i in region:
if i < 0:
neg = 1
break

v = self.vertices[i]
vs.append(v)

if neg == 0:
crv = cmds.curve(ep=vs, d=1)
cmds.closeCurve(crv, rpo=1)

Saturday, June 13, 2009

this is my studio script (using classes). i wrote some more helping scripts in the beginning.

in the maya scene should be a few locators (which are attraction and repulsion points)


import maya.cmds as cmds
import maya.mel as mm
import math
import sys
from random import*
from setColor import*
sys.setrecursionlimit(8000)

############################################################################################################################

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]

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

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:
distance = currDist
closLocator = i
closLocPos = locPos
closLocDist = currDist
closLocData.append (closLocator)
closLocData.append (closLocPos)
closLocData.append (closLocDist)

return closLocData

def closestLocatorToPoint (Point, netOfLocs):

locatorPos = Point
distance = 1000000000
closLocData = []
closestLocator = ""
for i in netOfLocs:
locPos = cmds.pointPosition(i)
currDist = getDistance(locatorPos, locPos)
if currDist < distance:
distance = currDist
closLocator = i
closLocPos = locPos
closLocDist = currDist
closLocData.append (closLocator)
closLocData.append (closLocPos)
closLocData.append (closLocDist)

return closLocData

def midPoint (listPt1,listPt2):
x=0
y=0
z=0
n=0
for i in listPt1:
ptPos = cmds.pointPosition(i)
x=x+ptPos[0]
y=y+ptPos[1]
z=z+ptPos[2]
n=n+1
for i in listPt2:
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=[]
midPt.append (midX)
midPt.append (midY)
midPt.append (midZ)

return midPt

def midPointInPtLocs (listLoc1,listPt2):
x=0
y=0
z=0
n=0
for i in (1,len(listLoc1)-1,1):
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=[]
midPt.append (midX)
midPt.append (midY)
midPt.append (midZ)

return midPt

def direction(a,b):
"Returns the direction vector going from a to b"
# Calculate direction vector
dire = [ a[0] - b[0], a[1] - b[1], a[2] - b[2] ] # a-b
return dire

############################################################################################################################

class graves:
def __init__(self):
print "Instance of class Graves created."

def getData(self):
locs = cmds.filterExpand(sm=22)
return locs

def getRepulsiveLocs (self):
locs1 = cmds.filterExpand(sm=22)
return locs1

def getAllLocators (self, AmountOfAttractors):
repulciveLocs = cmds.filterExpand(sm=22)

locs =[]
for i in range (AmountOfAttractors):
L = repulciveLocs[0]
repulciveLocs.remove (L)
locs.append (L)
return locs, repulciveLocs

def polyCubesInLocators (self, locators, size):
cubes = []
for i in locators:
position = cmds.pointPosition(i)
cube = cmds.polyCube (w =size ,h=size ,d=size )
cmds.move (position[0], position[1], position[2], cube)
cubes.append (cube)

return cubes

def makeNet (self, locators, numRow, numCell):
allLocs = []
startLocs = []
x = randint (98,102)
x = x/100.0
for i in range (numRow):
for j in range (numCell):
newloc= cmds.spaceLocator( p=(j*10*x, i*10*x, 0) )
if i == 0:
startLocs.append (newloc)
elif i == (numRow-1):
startLocs.append (newloc)
else:
allLocs.append (newloc)
cmds.refresh()
return startLocs, allLocs

def changeNetBecauseRepulsive (self, allLocs, repulsiveLocs, repSize, pointsAmount = 4, N=0):
Empty =[]
LOCS = allLocs
for i in allLocs:
Empty.append (i)
C = pointsAmount

for k in repulsiveLocs:
for i in range (repSize):
L=(repSize/5)*(i+1)
for j in range (L):
Kpos = cmds.pointPosition(k)
closLoc = closestLocatorToPoint(Kpos, LOCS)
LOCpos = closLoc[1]
clLoc = closLoc[0]
direc = direction(LOCpos, Kpos)
newX = ((direc[0]*6)/((i+1)*(i+1)))
newY = ((direc[1]*6)/((i+1)*(i+1)))
newZ = ((direc[2]*6)/((i+1)*(i+1)))
cmds.move (newX, newY, newZ, clLoc)
LOCS.remove (clLoc)

cmds.refresh()
return Empty

def subdivStartLocs (self, startLocs, locs):
subStartLocs = []
lenLocs = len(locs)
lenStertLocs = len(startLocs)
locsPerUnit = lenStertLocs/lenLocs
for i in range (lenLocs):
groupOfLocs = []
groupOfLocs.append (locs[i])
for j in range (locsPerUnit):
numOfLoc = i*locsPerUnit+j
loccc = startLocs [numOfLoc]
loccc = loccc[0]
groupOfLocs.append (loccc)
subStartLocs.append (groupOfLocs)

return subStartLocs

def looping1 (self, subdivStartLocs, allLocs, locs, size, number, cubes):
#cmds.pause( sec=0.5 )
cmds.refresh()
size *= 1.03
color = 255/(size*10)
number = number + 1
print "number"
print number
temploryList = []
midPoints =[]
N=0
for i in subdivStartLocs:
if number == 1:
Pt1 = len(i)/2
midP = i[Pt1]
midP = cmds.pointPosition(midP)
remLocs = []
remLocs.append (i[0])
x = randint (2,len(i)+7)
else:
midP = i
remLocs = []
#remLocs.append (i)
x = randint (2,len(subdivStartLocs)+7)
n = 0
if len(allLocs)>x:
for g in range (x):
closLocData = closestLocatorToPoint (midP, allLocs)
closLocator = closLocData[0]
closLocPos = closLocData[1]
closLocDist = closLocData[2]

newSphere = cmds.polySphere (r=size, sx=4, sy=4)
cmds.move (closLocPos[0], closLocPos[1], closLocPos[2], newSphere)
remLocs.append (closLocator)
allLocs.remove (closLocator)
if len(allLocs)<2:
return "Done."

temploryList.append (remLocs)

#################################################################
if number == 1:
Pt1 = len(i)/2
midPt1 = i[Pt1]
midPt1 = cmds.pointPosition(midPt1)
ptPos = cmds.pointPosition(i[0])
midPt = midPoint (remLocs,i)
else:
ptPos = cmds.pointPosition(locs[N])
midPt = midPointInPtLocs (remLocs,i)

midX = midPt[0] - midP[0]
midY = midPt[1] - midP[1]
midX = ptPos[0] + (midX/2)
midY = ptPos[1] + (midY/2)
cmds.move (midX, midY, 0, cubes[N])
cmds.move (midX, midY, 0, locs[N])
midP = midPt
N = N+1
midPoints.append (midP)
##################################################################

subdivStartLocs = midPoints

if len(allLocs)>0:
self.looping1 (subdivStartLocs, allLocs, locs, size, number, cubes)
else:
return "Done."
this part is running the script in way like on the video above

g= graves()

locs, repulsiveLocs = g.getAllLocators (8)
cubes = g.polyCubesInLocators ( locs, 6)
cubes1 = g.polyCubesInLocators ( repulsiveLocs, 10)

startLocs, allLocs = g.makeNet(locs,48,48)
cubes2 = g.polyCubesInLocators ( startLocs, 1)
allLocsPPP = allLocs


ALLLOCS = g.changeNetBecauseRepulsive (allLocsPPP, repulsiveLocs, 13)


subd = g.subdivStartLocs(startLocs,locs)
g.looping1 (subd, ALLLOCS, locs, 1.2, 0, cubes)

Monday, May 25, 2009

01B-Alice-Questions

Thanks a lot Daniel for all the comments. I am happy to know the script is working in the right direction. :) Sorry for sending you back my questions again...late...

Refer to your comments

1) I understand what you said and why the value of the points should be generated inside the function. However, if I change my function to

def pointBoundary(iterations, ptA, ptB, ptC):

do I still need to, at least for once, use the random function to generate 3 points before I can call my function?
when I call the recursion, can I just say, for instance:

pointBoundary(10, ptA, ptB, ptC) or pointBoundary(10)

2) I am not clear what do you mean:
"it should be idented under the else statement, so that it is executed only if iterations are not equal to 0"
because I have already idented...what should I change?

3)I successfully created random points and store them in a list.

pts=["ptA","ptB","ptC"]
for i in range (len(pt)):
from random import *

x = uniform(-squareSideLength/2, squareSideLength/2)
y = uniform(-squareSideLength/2, squareSideLength/2)
pts[i] =(x,y)

Is that alright?

** I have extra questions -
any differences if I write "pts[%d]%i" but not "pt[i]" ??

4) How to make sure I offset the line outward but not inward, in relation to the centre of the square??

5) Would using "classes" will help to shortening the script? because I always need to repeat the each steps for A, B, C...but I can't simply use loop...

6) Other questions you haven't answered:

a) Can you run the Serpentine Pavilion Script? I have syntax error with the line "iterations-=i"
b) What does argument type -"boolean" and "linear" mean?
c) What does "break" mean?
d) I can check cmds.command on the python help list, but how about others like "random" commands, those kinds of none cmds. commands?

Thanks.

Sunday, May 24, 2009

01B - Alexandra+Micea - Recursion squares - ScreenShots







01B - Mircea+Alexandra - Recursion squares-Script


#assignment o1B_A+M

#create an initial square
#get the coordinates of the points on each line, depending on the percentage ( in this case the percenatege is a subdivison)
#create a new square with the center in each point we get in the previous step
#rotate the squares with an angle
#scale the initial square
#recursion (by each iteration a new square is created, and along the lines other squares are created and rotated in the same time)


import maya.cmds as cmds

#create one initial square
x=10
y=10
mySquare = cmds.nurbsSquare(sl1=x, sl2=y)


def recursion( iterations , amt , percentage):
it=iterations
pp=percentage

#select the square
cmds.select( mySquare, r=1 )
isSides = cmds.filterExpand( sm=9 )
print isSides

#go through all the lines of the square
for i in range(0, len(isSides), 1):
print i
line = isSides[i]
#get the coordinates on the lines depending on the percentages
for j in range(1, pp+1, 1):
procent = j/float(pp)
poc = cmds.pointOnCurve(line,pr=procent,top=True,p=True)
#create a new square with the center in each point;
#the side of the squares created either can have decreasing values or the same length
#newSquare = cmds.nurbsSquare(c=poc, sl1=1/float(x/pp), sl2=1/float(y/pp))
newSquare = cmds.nurbsSquare(c=poc, sl1=2, sl2=2)
#rotate squares with an angle
cmds.rotate(0,0,it*amt*2, newSquare, pivot=poc)

if iterations == 0:
return "Done."
else:
iterations -= 1
percentage -= 1
#scale the initial square
cmds.scale( 1/float( x/pp),1/float( x/pp), 1/float( x/pp) , mySquare, pivot=(0, 0, 0), absolute=True )
recursion(iterations, amt, percentage)


recursion(4,10,4)



Assignment 01B



Question:
How to get the intersection coordinate in this case?

Assignment 01B

import maya.cmds as cmds

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

#Step2:Create these two circles
cmds.circle(c=(0,0,0),r=30)
cmds.circle(c=(0,-28,0),r=2)

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

#2)offset the outmost circle based on the radius of next circle
cmds.circle(c=(0,0,0), r=BigRadius-NextRadius)
#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
#Question:
# How to find out the coordinate of the intersection point in this case??????????????????????

'''
#Loop through it based on previous steps
for i in range(2,BigRadius,1):
cmds.circle(c=(0,0,0),r=Minus-i)
radius=3
r1= radius
r2= radius+i
radius+=1
D=r1+r2
cmds.circle(c=(the center coordinate from the intersection point),r=D)
'''

Saturday, May 23, 2009

MY SCRIPT "RECURSION STUFF" - pic



MY SCRIPT "RECURSION STUFF" - it works)

 def PLAN():
   1)Create primitive (6 angle for ex-le)
   2)Use this primitive as a path (curve)
   3)Define the random amount of primitives(within Fibonacci numbers 1,1,3,5,8,13,21,44,65...)
   4)Dulicate them
   5)Pick a random point within pritive length 
   6)Move them on it 
   7)Scale primitives random
   8)enjoy)
PLAN()
###RECURSION STUFF#####
##
def primitives(numSides, radius):
#create a circle
myCircle = cmds.circle(radius = 30)
#get param steps, I will take 6 for ex-le
paramSteps = 1./6
#loop and get points coordinates
points = []
for i in range(0, 8, 1):
points.append(  cmds.pointOnCurve(myCircle[0], p=1, pr=paramSteps*i, top=1)  )
#create a curve connecting points
myPrimitive = cmds.curve(ep=points, d=1)
#close the curve
cmds.closeCurve(n="p_"+str(numSides)+"_sides", rpo=1)
#delete the circle 
cmds.delete(myCircle)
#return the name of the primitive
return myPrimitive
primitives(6, 30)

from random import *

def Whatamess():
#define the random amount of primitives
randomAmount = randint(21,44) # fibonachi number 1,1,3,5,8,13,21,44,65... and so on
for i in range (0,randomAmount,1):
#duplicate my primitiv
myDupObj2 = cmds.duplicate( 'curve1' ) 
# get the center of the duplicated object
myCenter = cmds.xform(myDupObj2, q=1, t=1, ws=1)
# get the maximun "length" of the curve, so we can pick a random point within this length
#I wanna use my Primitive as a curve. Why not?)
myCurveParam = cmds.getAttr("curve1.maxValue")
# select a random point on the curve
myPoint = cmds.pointOnCurve( 'curve1', pr = uniform(0,myCurveParam), p=True)
# select the previously duplicated object
cmds.select(myDupObj2)
# move it to the new location
cmds.move(myPoint[0],myPoint[1],myPoint[2])
#scales it
cmds.scale(uniform(1,1.5),uniform(1,1.5),uniform(1,1.5),a=1)

Whatamess()

### As You can see, I changed my consept a bit,
### from controlled variant to random, because I dont know how to put 
### mathematical formulas (Fibonacci x3 = x2+x1) But I included one of your "helpful" scripts and I like the result) after all

 
 def PLAN1():
   1)Create primitive (6 angle for ex-le)
   2)Use this primitive as a path (curve)
   3)Define the random amount of primitives(within Fibonacci numbers 1,1,3,5,8,13,21,44,65...)
   4)Dulicate them
   5)Pick a  point within pritive length ( I dont know how to pick different 
          points with Fibonacci proporsion-divide curve propotionally [1,1,3,5...])
   6)Move them on it  (I dont know how to put them, so they will not intersect)
   7)Scale primitives  (but I dont know how to scale them proportionally)
   8)enjoy more)
PLAN1()

It does not work and giving mistake:
UnboundLocalError: local variable 'Squares' referenced before assignment #


import maya.cmds as cmds
x=10
y=10
#Make a Square
initialSqare = cmds.nurbsSquare(sl1=x, sl2=y)
#get outline
isSides = cmds.filterExpand (sm=9)
print isSides
#make an empty list
Squares = []
Squares.append (1)

def squareINsquare (number):
#scale
x=10/(1.5*len(Squares)+1)
y=10/(1.5*len(Squares)+1)
#loop
for j in range (0,len(Squares),1):
cmds.select (Squares[j], r=True)
#get outline
isSides = cmds.filterExpand (sm=9)
#looping in outline
for i in range (0,2,1):
perc1 = 0
perc2 = 1
line1=isSides[1]
line2 = isSides[2]
if i == 0:
poc1 = cmds.pointOnCurve(line1, pr=perc1, top=True, p=True)
print poc1
#change the center of the new square
poc1[0]=poc1[0]-x/2
poc1[1]=poc1[1]+y/2
print poc1
#make a new square
initialSqare1 = cmds.nurbsSquare(c = poc1, sl1=x, sl2=y)
#the same for the oposit corner of the squre
else:
poc2 = cmds.pointOnCurve(line2, pr=perc2, top=True, p=True)
print poc2
poc2[0]=poc2[0]+x/2
poc2[1]=poc2[1]-y/2
print poc2
initialSqare2 = cmds.nurbsSquare(c = poc2, sl1=x, sl2=y)

Squares.append (initialSqare1)
Squares.append (initialSqare2)
Squares=Squares1
Squares1=[]
if number == 0 :
#stop
return "Done."
else:
#did not finish yet
#remove one unit (count down)
number -= 1

squareINsquare (number)

squareINsquare (3)

01B - alec' - Real recursion, soft code, optimized, updated, improved & commented new script...

In this script I mainly correct my mistakes! I changed the loop in a real recursive function, I used "soft code" instead of "hard code" and I tried to optimized my codes.

I also added a recursion "J" which makes vary the result every time we call the function once again. This new "j" parameter (called "recursions" with a "s") increase the rotation angle and the scale of the squares. (= the first 4th screenshots)

In this example, I used a loop at the end of the script to call the function 5times!
and I configured this script to show only the z-axis projection. (= the last screenshot)

I didn't managed to simplify the "projection part" ... from the line 53 to 65.



import maya.cmds as cmds

##########################
### INITIAL PARAMETERS ###
##########################
### drawx = project square on x axis, drawy = project square on y axis, drawz = project square on z axis
### delete3Dsquare = delete the original iterated squares
### deletelocator = delete locator related to the rotationpoint
### deleteSquareSurface = delete the nurbsSquare used for the pointPosition + offset function
drawx = 0 # 0 = Fasle /// 1 = True
drawy = 0 # 0 = Fasle /// 1 = True
drawz = 1 # 0 = Fasle /// 1 = True
delete3Dsquare = 1 # 0 = Fasle /// 1 = True
deletelocator = 1 # 0 = Fasle /// 1 = True
deleteSquareSurface = 1 # 0 = Fasle /// 1 = True
iterationgroup = cmds.group(em=True)
if cmds.objExists('j'):
print "rien"
else:
cmds.spaceLocator(n='j')
iterations = 1
j = []



############################
### DEF RECURSIVE SQUARE ###
############################
### Def the function according to 3 parameters; number of iterations, angle of rotation between each square, offset of the point of rotation
### rotationpoint [0,0,0] is the initial rotation point position /// these position are used only for the first iteration

def recursivesquares(j,iteration, angle, offset, rotationpoint=[0,0,0]):
group = cmds.group(em=True)

### Create the square, and rotate it according to the angle and rotationpoint parameters
nurbsSquare = cmds.nurbsSquare(sl1=iterations*5, sl2=iterations*5, c=rotationpoint, nry=1, nrz=0)
cmds.parent(nurbsSquare[0], group)
cmds.rotate(iterations*iteration*angle, iterations*iteration*angle, iterations*iteration*angle, [nurbsSquare[0]], pivot=(rotationpoint))

### Determining the position of each corner of this square
topposition = cmds.pointPosition('top'+nurbsSquare[0]+'.cv[0]', world=True)
leftposition = cmds.pointPosition('left'+nurbsSquare[0]+'.cv[0]', world=True)
rightposition = cmds.pointPosition('right'+nurbsSquare[0]+'.cv[0]', world=True)
bottomposition = cmds.pointPosition('bottom'+nurbsSquare[0]+'.cv[0]', world=True)

### Create a nurbs surface to use the pointOnSurface command with the offset parameter
### Create a locator in the position of this new rotationpoint
nurbsSquareSurface = cmds.squareSurface('top'+nurbsSquare[0], 'right'+nurbsSquare[0], 'bottom'+nurbsSquare[0], 'left'+nurbsSquare[0], ct1=1, ct2=1, ct3=1, ct4=1, po=0)
rotationpoint = cmds.pointOnSurface(nurbsSquareSurface[0], u=offset/(iteration+1), v=offset/(iteration+1), position=True)
locator = cmds.spaceLocator(p=rotationpoint)
cmds.parent(locator[0], nurbsSquareSurface[0], group)

### Project the squares on the x, y or/and z axis
if drawx == 1:
squaresonx = cmds.curve(d=1, p=[(topposition[0], topposition[1], 0),(leftposition[0], leftposition[1], 0),(bottomposition[0], bottomposition[1], 0),(rightposition[0], rightposition[1], 0), (topposition[0], topposition[1], 0)] )
cmds.parent(squaresonx, group)

if drawy == 1:
squaresony = cmds.curve(d=1, p=[(topposition[0], 0, topposition[2]),(leftposition[0], 0, leftposition[2]),(bottomposition[0], 0, bottomposition[2]),(rightposition[0], 0, rightposition[2]), (topposition[0], 0, topposition[2])] )
cmds.parent(squaresony, group)

if drawz == 1:
squaresonz = cmds.curve(d=1, p=[(0, topposition[1], topposition[2]),(0, leftposition[1], leftposition[2]),(0, bottomposition[1], bottomposition[2]),(0, rightposition[1], rightposition[2]), (0, topposition[1], topposition[2])] )
cmds.parent(squaresonz, group)

else:
print "project nothing"

### Clean the Scene
cmds.parent(group, iterationgroup)

if delete3Dsquare == 1:
cmds.delete(nurbsSquare[0])

if deletelocator == 1:
cmds.delete(locator[0])

if deleteSquareSurface == 1:
cmds.delete(nurbsSquareSurface[0])



### Iterate the function
if iteration == 0:
j.append(1)
return j

else:
iteration -= 1
recursivesquares(j,iteration, angle, offset, rotationpoint)


#############################
### CALL RECURSIVE SQUARE ###
#############################


for i in range (0, 5, 1):
recursivesquares(j,10,15,.9, [0,0,0])
iterations = len(j)+1
print iterations


Tuesday, May 19, 2009

Assignment 01B


import maya.cmds as cmds
import math
import maya.mel as mm



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


#########THIS IS THE NON_RECURSIVE PART ------ JUST SKIP#######################
'''
mySquare = cmds.nurbsSquare(sl1=10, sl2=15)

isSides = cmds.filterExpand (sm=9)

pos = []

for i in range (len(isSides)):
posa = cmds.pointPosition(isSides[i]+".cv[0]")
pos.append (posa)



diag = getDistance(pos[0],pos[2])
a = getDistance(pos[2],pos[3])
b = getDistance(pos[3],pos[0])

h = math.sqrt(a*a - ((a*diag)/(b+a)) * ((a*diag)/(b+a)))


mySquare2 = cmds.nurbsSquare(sl1=h, sl2=diag)
isSides2 = cmds.filterExpand (sm=9)
pos2 = []

for i in range (len(isSides2)):
posb = cmds.pointPosition(isSides2[i]+".cv[0]")
pos2.append (posb)

#get diference between actual location and move
dist = getDistance(pos[2],pos2[2])
p1 = pos[2]
p2 = pos2[2]
x=p2[0] - p1[0]
print x
y=p2[0] - p1[0]
cmds.move(x,-y,0,mySquare)



#get angle of rotation
sinF = getDistance(pos[0],pos[1])
alpha = math.asin(sinF/diag)
Ld= math.degrees (alpha)

cmds.rotate(0,0,Ld,mySquare2, pivot = pos2[2])
'''



#create initial rectangle
mySquare = cmds.nurbsSquare(sl1=a, sl2=b)


#define recursive function
def MyRecursive(iterations,a,b):

isSides = cmds.filterExpand (sm=9)

pos = []
for i in range (len(isSides)):
posa = cmds.pointPosition(isSides[i]+".cv[0]")
pos.append (posa)


#define length of diagonal in order to use it for next rectangle
diag = getDistance(pos[0],pos[2])
#define length of 2 sides to get height
a = getDistance(pos[2],pos[3])
b = getDistance(pos[3],pos[0])
#get height of triangle (diagonal and the two sides)
h = math.sqrt(a*a - ((a*diag)/(b+a)) * ((a*diag)/(b+a)))

#create new rectangle with l2=diagonal length and l1= height of triangle
mySquare2 = cmds.nurbsSquare(sl1=h, sl2=diag)
isSides2 = cmds.filterExpand (sm=9)

pos2 = []

for i in range (len(isSides2)):
posb = cmds.pointPosition(isSides2[i]+".cv[0]")
pos2.append (posb)

#get diference between actual location and move to future pivot point
dist = getDistance(pos[2],pos2[2])
p1 = pos[2]
p2 = pos2[2]
x=p2[0] - p1[0]
y=p2[0] - p1[0]
cmds.move(x,-y,0,mySquare)



#get angle of rotation from diagonal
sinF = getDistance(pos[0],pos[1])
alpha = math.asin(sinF/diag)
Ld= math.degrees (alpha)

#rotate on diagonal
cmds.rotate(0,0,Ld,mySquare2, pivot = pos2[2])

#recursion part
#if else conditions
if iterations == 0:
return "Done"
else:
iterations -= 1
MyRecursive(iterations, a,b)

#call function
MyRecursive(10,10,15)



The problems i have are first of all that the height of the triangle i am calculating is not corresponding to the actual height.

Second would be that the recursion is not working as it should.

What it should do is first create a rectangle, create another one(with length=diagonal, and width=height of the triangle formed by diagonal and two sides). Rotate the last created rectangle on the diagonal, so that one of the sides "becomes" the diagonal. And then repeat everything for the next one.

Irina_Algorithm Sketches






Alice_Assignment 01B script trial


import maya.cmds as cmds

#create an initial square
initialSquare = cmds.nurbsSquare (sl1=10, sl2=10)
isSides = cmds.filterExpand(sm=9)

#create 3 random points inside the square** (I don't know how to find this random command)
ptA =
ptB =
ptC =

def pointBoundary(iterations)
i=iterations

#Create 3 curves
lineA = cmds.curve(ep=(ptC,ptB),d=1)
lineB = cmds.curve(ep=(ptA,ptC),d=1)
lineC = cmds.curve(ep=(ptB,ptA),d=1)

#Get the distance between 3 points
lenA = cmds.distanceDimension(ptC,ptB)
lenB = cmds.distanceDimension(ptA,ptC)
lenC = cmds.distanceDimension(ptB,ptA)

#Radius of the 3 circles:riA,riB,riC
riA = (lenB + lenC - lenA)/2
riB = (lenA + lenC - lenB)/2
riC = (lenA + lenB - lenC)/2

#Create 3 circles
cirleA = cmds.circle(c=ptA,r=riA)
cirleB = cmds.circle(c=ptB,r=riB)
CirleC = cmds.circle(c=ptC,r=riC)

#Tangent points among the 3 circles
tanA = cmds.curveIntersect(lineA,circleB)
tanB = cmds.curveIntersect(lineB,circleC)
tanC = cmds.curveIntersect(lineC,circleA)

#Offset lenA, lenB, lenC to a long distance and create new lines offA, offB, offC
#(I am not sure if it offset to the right direction!!!)

offA = cmds.offsetCurve(lenA,1000)
offB = cmds.offsetCurve(lenB,1000)
offC = cmds.offsetCurve(lenC,1000)

nodeA = cmds.closestPointOnCurve(offA,tanA)
nodeB = cmds.closestPointOnCurve(offB,tanB)
nodeC = cmds.closestPointOnCurve(offC,tanC)

#Draw perpendicular lines
perA = cmds.curve(ep=(tanA,nodeA), d=1)
perB = cmds.curve(ep=(tanB,nodeB), d=1)
perC = cmds.curve(ep=(tanC,nodeC), d=1)


#Test if perpendicular lines intersect with which sides of the square
#Get coordinates of the 3 intersection points on the square and
#replace the existing values of ptA, ptB, ptC

for i in range(len(isSides)):
isIntA = cmds.curveIntersect(perA,isSides[i])
isIntB = cmds.curveIntersect(perB,isSides[i])
isIntC = cmds.curveIntersect(perC,isSides[i])
if isIntA != None:
ptA = isIntA
if isIntB != None:
ptB = isIntB
if isIntC != None:
ptC =isIntC


#Resize the initial Square
cmds.rotate(0,0,30,initialSquare)
cmds.scale(1.5,1.5,1,initialSquare)

#Recursion
if iterations ==0:
return "Done"
else:
iterations -=1

def pointBoundary(10)

Monday, May 18, 2009


import maya.cmds as cmds
x=10
y=10
#Make a Square
initialSqare = cmds.nurbsSquare(sl1=x, sl2=y)
#get outline
isSides = cmds.filterExpand (sm=9)
print isSides
#make an empty list
Squares = []
Squares.append (1)

def squareINsquare (number):
#scale
x=10/(1.5*len(Squares)+1)
y=10/(1.5*len(Squares)+1)
#loop
for j in range (0,len(Squares),1):
cmds.select (Squares[j], r=True)
#get outline
isSides = cmds.filterExpand (sm=9)
#looping in outline
for i in range (0,2,1):
perc1 = 0
perc2 = 1
line1=isSides[1]
line2 = isSides[2]
if i == 0:
poc1 = cmds.pointOnCurve(line1, pr=perc1, top=True, p=True)
print poc1
#change the center of the new square
poc1[0]=poc1[0]-x/2
poc1[1]=poc1[1]+y/2
print poc1
#make a new square
initialSqare1 = cmds.nurbsSquare(c = poc1, sl1=x, sl2=y)
#the same for the oposit corner of the squre
else:
poc2 = cmds.pointOnCurve(line2, pr=perc2, top=True, p=True)
print poc2
poc2[0]=poc2[0]+x/2
poc2[1]=poc2[1]-y/2
print poc2
initialSqare2 = cmds.nurbsSquare(c = poc2, sl1=x, sl2=y)

Squares.append (initialSqare1)
Squares.append (initialSqare2)
Squares=Squares1
Squares1=[]
if number == 0 :
#stop
return "Done."
else:
#did not finish yet
#remove one unit (count down)
number -= 1

squareINsquare (number)

squareINsquare (3)