Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # TOM ROWELL - TRAFFIK TSIMULATE
- import maya.cmds as cmds
- import time, sched, os, math, random
- vehicles = []
- #streets = []
- sceneLength = 0
- timeIncrement = 0.0
- sceneFPS = 0
- globalSpeed = 10 #units per second
- globalSubstepValue = 0.1 #frames per tick - values below 0.05 are unstable
- globalAvoidDistance = 25
- pathPool = []
- class cStreet:
- curveID = 0
- nextCurve = 0
- geometryObject = 'unused'
- isBranched = 0
- branch1 = 0
- branch2 = 0
- branch3 = 0
- branch4 = 0
- branch5 = 0
- def queryStreet(self):
- print ("Curve ID: " + str(self.curveID))
- print ("Next curve in chain: " + str(self.nextCurve))
- print ("Curve object: " + self.geometryObject)
- def exportStreet(self):
- return (self.curveID, self.nextCurve, self.geometryObject)
- class cVehicle:
- id = 0
- type = 'unused'
- curveID = 0
- nextCurve = 0
- geometryObject = 'unused'
- motionPath = 'unused'
- currentPath = 0
- ADL1 = 'unused'
- ADL2 = 'unused'
- ADL3 = 'unused'
- vehicleVelocityMultiplier = 1.0
- fallbackCurveID = 0
- def __init__(self):
- self.geometryObject = cmds.polyCube()
- for x in range(1, 4):
- currentNode = cmds.createNode('addDoubleLinear')
- exec("self.ADL" + str(x) + " = currentNode")
- exec("cmds.connectAttr( \'" + self.ADL1 + ".output\', \'" + self.geometryObject[0] + ".translateX\')")
- exec("cmds.connectAttr( \'" + self.ADL2 + ".output\', \'" + self.geometryObject[0] + ".translateY\')")
- exec("cmds.connectAttr( \'" + self.ADL3 + ".output\', \'" + self.geometryObject[0] + ".translateZ\')")
- exec("cmds.connectAttr( \'" + self.geometryObject[0] + ".transMinusRotatePivotX\', \'" + self.ADL1 + ".input1\')")
- exec("cmds.connectAttr( \'" + self.geometryObject[0] + ".transMinusRotatePivotY\', \'" + self.ADL2 + ".input1\')")
- exec("cmds.connectAttr( \'" + self.geometryObject[0] + ".transMinusRotatePivotZ\', \'" + self.ADL3 + ".input1\')")
- self.motionPath = cmds.createNode('motionPath')
- exec("cmds.setAttr(\'" + self.motionPath + ".fractionMode\', 1)")
- exec("cmds.connectAttr(\'" + self.motionPath + ".xCoordinate\', \'" + self.ADL1 + ".input2\')")
- exec("cmds.connectAttr(\'" + self.motionPath + ".yCoordinate\', \'" + self.ADL2 + ".input2\')")
- exec("cmds.connectAttr(\'" + self.motionPath + ".zCoordinate\', \'" + self.ADL3 + ".input2\')")
- exec("cmds.connectAttr( \'" + self.motionPath + ".message\', \'" + self.geometryObject[0] + ".specifiedManipLocation\')")
- exec("cmds.connectAttr( \'" + self.motionPath + ".rotateOrder\', \'" + self.geometryObject[0] + ".rotateOrder\')")
- exec("cmds.connectAttr( \'" + self.motionPath + ".rotateX\', \'" + self.geometryObject[0] + ".rotateX\')")
- exec("cmds.connectAttr( \'" + self.motionPath + ".rotateY\', \'" + self.geometryObject[0] + ".rotateY\')")
- exec("cmds.connectAttr( \'" + self.motionPath + ".rotateZ\', \'" + self.geometryObject[0] + ".rotateZ\')")
- def queryVehicle(self):
- print ("\n==Current Vehicle Query==")
- print ("ID: " + str(self.id))
- print ("Type: " + self.type)
- print ("Geo Obj: " + str(self.geometryObject[0]))
- print ("ADL1: " + self.ADL1)
- print ("ADL2: " + self.ADL2)
- print ("ADL3: " + self.ADL3)
- print ("Current Curve: " + str(self.curveID))
- print ("Next Curve: " + str(self.nextCurve))
- print ("==END OF VEHICLE QUERY==\n")
- def queryCurveAttribs(self,curve):
- x = findStreet(curve).geometryObject + ".curveID"
- y = findStreet(curve).geometryObject + ".nextCurve"
- self.curveID = cmds.getAttr(x)
- self.nextCurve = cmds.getAttr(y)
- def attachToPath(self, curve):
- self.curveID = curve;
- print ("Attaching to path on curve \'" + str(curve) + "\'") # debug line
- exec("cmds.setAttr(\'" + self.motionPath + ".uValue\', 0)")
- exec("cmds.connectAttr( \'" + findStreet(curve).geometryObject + ".worldSpace[0]\', \'" + self.motionPath + ".geometryPath\', force = True)")
- def doSwitch(self):
- print "Making switch!"
- self.updatePathing()
- self.attachToPath(self.curveID)
- def updatePathing(self):
- print "Update Pathing called"
- geoObj = (findStreet(self.curveID).geometryObject) + ".nextCurve" # get current curveID's matching geo object and append .nextCurve
- self.curveID = cmds.getAttr(geoObj) # save next curve's id into curveID
- print "PATHING UPDATED TO: " + str(self.curveID)
- def accelVehicle(self): # to be implemented into cVehicle class
- if (self.vehicleVelocityMultiplier > globalVehicleSpeed):
- self.vehicleVelocityMultiplier =+ globalAccelValue # increases vehicle velocity by globalAccelValue each iteration until vehicle reaches standard travel speed
- else:
- self.vehicleVelocityMultipier = globalVehicleSpeed # if value becomes higher than globalVehicleSpeed, value is replaced with GVS to prevent overspeeding
- def decelVehicle(self): # to be implemented into cVehicle class
- if (self.vehicleVelocityMultiplier > 0):
- self.vehicleVelocityMultiplier =- globalDecelValue # decreases vehicle velocity by globaDecelValue each iteration until value becomes 0.
- else:
- self.vehicleVelocityMultiplier = 0 # if value is less than 0, it is replaced with 0 to prevent negative values
- # reserved for future additions
- def initVehicle( x ):
- global vehicles
- newV = cVehicle()
- newV.id = x
- newV.fallbackCurveID = 1
- vehicles.extend([newV]) # add a new vehicle to the end of the list
- def initStreet():
- global streets
- x = cmds.ls(sl = True)
- y = x[0] + ".curveID"
- z = x[0] + ".nextCurve"
- newS = cStreet()
- newS.curveID = cmds.getAttr(y)
- newS.nextCurve = cmds.getAttr(z)
- newS.geometryObject = x[0]
- streets.extend([newS])
- def initStreetFromFile(curveID, nextCurve, geometryObject):
- global streets
- streets = []
- newS = cStreet()
- newS.curveID = curveID
- newS.nextCurve = nextCurve
- newS.geometryObject = geometryObject
- streets.extend([newS])
- def findStreet( x ):
- try:
- global streets
- for s in streets:
- if s.curveID == x: return s
- except:
- return 0
- def findVehicle( x ):
- try:
- global vehicles
- for v in vehicles:
- if v.id == x: return v
- except:
- return 0
- def getSceneLength():
- return cmds.playbackOptions( query = True, maxTime = True ) # get max length of scene
- def doSim():
- global globalSubstepValue
- global sceneLength
- sceneLength = getSceneLength()
- cmds.currentTime(0 ,edit = True)
- currentTime = 0
- while currentTime < sceneLength:
- for v in range(1,(len(vehicles)+1)):
- print "Press X to terminate simulation"
- c = getKey()
- if (c == 'x'):
- cmds.currentTime(sceneLength, edit = True)
- vehCurveID =(findVehicle(v).curveID)
- curve = (findStreet(vehCurveID).geometryObject)
- uValue = ((findVehicle(v).motionPath) + ".uValue")
- getUValue = cmds.getAttr(uValue)
- addIncValue = getPathIncrement(curve) # determines amount to add onto existing uValue per cycle
- print ("\naddincValue = " + str(addIncValue))
- incValue = (cmds.getAttr(uValue)) + addIncValue # adds incremental value onto the current u
- print ("\nincValue = " + str(incValue))
- if incValue > 1:
- cmds.setAttr(uValue, 1)
- print "Switching!"
- findVehicle(v).doSwitch()
- else:
- if getUValue < 0.25:
- incValue = math.sin(incValue)
- print ("sin\'d incValue = " + str(incValue))
- cmds.setAttr(uValue, incValue)
- print cmds.getAttr(uValue)
- z = currentTime + globalSubstepValue
- cmds.currentTime(z, edit=True)
- currentTime = cmds.currentTime(query = True)
- def simulate():
- global pathPool
- for v in range(1,(len(vehicles)+1)):
- vehCurveID =(findVehicle(v).curveID)
- curve = (findStreet(vehCurveID).geometryObject)
- uValue = ((findVehicle(v).motionPath) + ".uValue")
- getUValue = cmds.getAttr(uValue)
- addIncValue = getPathIncrement(curve) # determines amount to add onto existing uValue per cycle
- incValue = (cmds.getAttr(uValue)) + addIncValue # adds incremental value onto the current u
- getCurve(findVehicle(v).geometryObject)
- print pathPool
- if (len(pathPool) > 1):
- print ("Selecting random path number: " + str(random.randint(0, (len(pathPool)))))
- z = (random.randint(0, (len(pathPool))))
- print ("New path = " + str(pathPool[z]))
- else:
- z = 0
- if incValue > 1:
- cmds.setAttr(uValue, 1)
- print "Switching!"
- if (len(pathPool) > 0):
- print ("New path = " + str(pathPool[z]))
- findVehicle(v).attachToPath(pathPool[z])
- else:
- print "Curve not found, connecting to fallback"
- findVehicle(v).attachToPath(findVehicle(v).fallbackCurveID)
- else:
- cmds.setAttr(uValue, incValue)
- def getPathIncrement(curve):
- global sceneLength
- sceneLength = getSceneLength()
- sceneFPS = cmds.currentUnit( query = True, time = True ) # get fps of scene
- pathLength = cmds.arclen(curve)
- if sceneFPS == "game": sceneFPS = 15.0
- if sceneFPS == "film": sceneFPS = 24.0
- if sceneFPS == "pal": sceneFPS = 25.0
- if sceneFPS == "ntsc": sceneFPS = 30.0
- if sceneFPS == "show": sceneFPS = 48.0
- if sceneFPS == "palf": sceneFPS = 50.0
- if sceneFPS == "ntscf": sceneFPS = 60.0
- pathIncrement = (1.0 / pathLength) * (globalSpeed / sceneFPS)
- return pathIncrement
- def generatePathFile(scene):
- projectDir = cmds.workspace( q=True, dir=True )
- os.chdir(projectDir)
- scene = (scene + ".tdf")
- print ("Writing to " + os.getcwd())
- f = open( scene, 'w')
- y = range(1, (len(streets)+1))
- for x in y:
- print x
- f.writelines(str(findStreet(x).curveID) + '\n')
- f.writelines(str(findStreet(x).nextCurve) + '\n')
- f.writelines(str(findStreet(x).geometryObject)+ '\n')
- f.writelines(str(findStreet(x).isBranched)+ '\n')
- f.writelines(str(findStreet(x).branch1)+ '\n')
- f.writelines(str(findStreet(x).branch2)+ '\n')
- f.writelines(str(findStreet(x).branch3)+ '\n')
- f.writelines(str(findStreet(x).branch4)+ '\n')
- f.writelines(str(findStreet(x).branch5)+ '\n')
- f.close()
- def readPathFile(scene):
- projectDirectory = cmds.workspace(q=True, rd=True)
- currentScene = os.path.abspath(cmds.file(q=True, sn=True))
- if 'scene' in cmds.workspace(q=True, frl=True):
- sceneDirectory = os.path.join(projectDirectory, cmds.workspace(fre='scene'))
- os.chdir(projectDir)
- f = open( scene, 'r')
- for x in range(0,(len(streets)+1)):
- while y < 9:
- curveID = f.readline()
- nextCurve = f.readline()
- geometryObject = f.readline()
- isBranched = f.readline()
- brance1 = f.readline()
- branch2 = f.readline()
- branch3 = f.readline()
- branch4 = f.readline()
- branch5 = f.readline()
- initStreetFromFile(fCurveID, fNextCurve, fGeometryObject)
- f.close()
- def get2dLineDist(vehicle1, vehicle2):
- v1 = cmds.xform(vehicle1, t=True, ws=True, q=True)
- v2 = cmds.xform(vehicle2, t=True, ws=True, q=True)
- dX = (v1[0] - v2[0])
- dZ = (v1[2] - v2[2])
- xzLineDist = math.sqrt((dX * dX) + (dZ * dZ))
- return xzLineDist
- # def checkAvoidance():
- # global globalAvoidDistance
- # for x in vehicles:
- # for y in vehicles:
- # if findVehicle(x) == findVehicle(y):
- # continue
- # else:
- # z = get2dLineDist(x, y)
- # z = get3dLineDist(x, y)
- # if (z < globalAvoidDistance):
- # findVehicle(x).decelVehicle()
- # else:
- # findVehicle(x).accelVehicle()
- # exec code
- # dynamic curve detection testing !!
- def getCurve(vehicle):
- global pathPool
- pathPool = []
- for x in range(1,(len(streets)+1)):
- dist = (get2dLineDist(vehicle, (findStreet(x).geometryObject)))
- if (dist < 0.25):
- print ("Detected curve: " + str(findStreet(x).curveID))
- pathPool.extend([findStreet(x).curveID])
- print (len(pathPool))
- if (len(pathPool) != 0):
- for x in range(1, len(pathPool)):
- print pathPool[x]
- streets = []
- vehicles = []
- initStreet()
- pathPool[0]
- initVehicle(1)
- findVehicle(1).attachToPath(1)
- cmds.expression(string=("python \"simulate()\";"))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement