Advertisement
Guest User

Untitled

a guest
Aug 12th, 2017
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 11.51 KB | None | 0 0
  1.  
  2. # TOM ROWELL - TRAFFIK TSIMULATE
  3. import maya.cmds as cmds
  4. import time, sched, os, math, random
  5.  
  6. vehicles = []
  7. #streets = []
  8. sceneLength = 0
  9. timeIncrement = 0.0
  10. sceneFPS = 0
  11. globalSpeed = 10 #units per second
  12. globalSubstepValue = 0.1 #frames per tick - values below 0.05 are unstable
  13. globalAvoidDistance = 25
  14. pathPool = []
  15.  
  16. class cStreet:
  17.  
  18.     curveID = 0
  19.     nextCurve = 0
  20.     geometryObject = 'unused'
  21.     isBranched = 0
  22.     branch1 = 0
  23.     branch2 = 0
  24.     branch3 = 0
  25.     branch4 = 0
  26.     branch5 = 0
  27.  
  28.     def queryStreet(self):
  29.         print ("Curve ID: " + str(self.curveID))
  30.         print ("Next curve in chain: " + str(self.nextCurve))
  31.         print ("Curve object: " + self.geometryObject)
  32.  
  33.     def exportStreet(self):
  34.         return (self.curveID, self.nextCurve, self.geometryObject)
  35.  
  36. class cVehicle:
  37.  
  38.     id = 0
  39.     type = 'unused'
  40.     curveID = 0
  41.     nextCurve = 0
  42.     geometryObject = 'unused'
  43.     motionPath = 'unused'
  44.     currentPath = 0
  45.     ADL1 = 'unused'
  46.     ADL2 = 'unused'
  47.     ADL3 = 'unused'
  48.     vehicleVelocityMultiplier = 1.0
  49.     fallbackCurveID = 0
  50.  
  51.     def __init__(self):
  52.         self.geometryObject = cmds.polyCube()
  53.         for x in range(1, 4):
  54.             currentNode = cmds.createNode('addDoubleLinear')
  55.             exec("self.ADL" + str(x) + " = currentNode")
  56.  
  57.         exec("cmds.connectAttr( \'" + self.ADL1 + ".output\', \'" + self.geometryObject[0] + ".translateX\')")
  58.         exec("cmds.connectAttr( \'" + self.ADL2 + ".output\', \'" + self.geometryObject[0] + ".translateY\')")
  59.         exec("cmds.connectAttr( \'" + self.ADL3 + ".output\', \'" + self.geometryObject[0] + ".translateZ\')")
  60.  
  61.         exec("cmds.connectAttr( \'" + self.geometryObject[0] + ".transMinusRotatePivotX\', \'" + self.ADL1 + ".input1\')")
  62.         exec("cmds.connectAttr( \'" + self.geometryObject[0] + ".transMinusRotatePivotY\', \'" + self.ADL2 + ".input1\')")
  63.         exec("cmds.connectAttr( \'" + self.geometryObject[0] + ".transMinusRotatePivotZ\', \'" + self.ADL3 + ".input1\')")
  64.  
  65.         self.motionPath = cmds.createNode('motionPath')
  66.         exec("cmds.setAttr(\'" + self.motionPath + ".fractionMode\', 1)")
  67.         exec("cmds.connectAttr(\'" + self.motionPath + ".xCoordinate\', \'" + self.ADL1 + ".input2\')")
  68.         exec("cmds.connectAttr(\'" + self.motionPath + ".yCoordinate\', \'" + self.ADL2 + ".input2\')")
  69.         exec("cmds.connectAttr(\'" + self.motionPath + ".zCoordinate\', \'" + self.ADL3 + ".input2\')")
  70.         exec("cmds.connectAttr( \'" + self.motionPath + ".message\', \'" + self.geometryObject[0] + ".specifiedManipLocation\')")
  71.         exec("cmds.connectAttr( \'" + self.motionPath + ".rotateOrder\', \'" + self.geometryObject[0] + ".rotateOrder\')")
  72.         exec("cmds.connectAttr( \'" + self.motionPath + ".rotateX\', \'" + self.geometryObject[0] + ".rotateX\')")
  73.         exec("cmds.connectAttr( \'" + self.motionPath + ".rotateY\', \'" + self.geometryObject[0] + ".rotateY\')")
  74.         exec("cmds.connectAttr( \'" + self.motionPath + ".rotateZ\', \'" + self.geometryObject[0] + ".rotateZ\')")
  75.  
  76.     def queryVehicle(self):
  77.         print ("\n==Current Vehicle Query==")
  78.         print ("ID: " + str(self.id))
  79.         print ("Type: " + self.type)
  80.         print ("Geo Obj: " + str(self.geometryObject[0]))
  81.         print ("ADL1: " + self.ADL1)
  82.         print ("ADL2: " + self.ADL2)
  83.         print ("ADL3: " + self.ADL3)
  84.         print ("Current Curve: " + str(self.curveID))
  85.         print ("Next Curve: " + str(self.nextCurve))
  86.         print ("==END OF VEHICLE QUERY==\n")
  87.  
  88.     def queryCurveAttribs(self,curve):
  89.         x = findStreet(curve).geometryObject + ".curveID"
  90.         y = findStreet(curve).geometryObject + ".nextCurve"
  91.         self.curveID = cmds.getAttr(x)
  92.         self.nextCurve = cmds.getAttr(y)
  93.  
  94.     def attachToPath(self, curve):
  95.         self.curveID = curve;
  96.         print ("Attaching to path on curve \'" + str(curve) + "\'") # debug line
  97.         exec("cmds.setAttr(\'" + self.motionPath + ".uValue\', 0)")
  98.         exec("cmds.connectAttr( \'" + findStreet(curve).geometryObject + ".worldSpace[0]\', \'" + self.motionPath + ".geometryPath\', force = True)")
  99.  
  100.     def doSwitch(self):
  101.         print "Making switch!"
  102.         self.updatePathing()
  103.         self.attachToPath(self.curveID)
  104.  
  105.     def updatePathing(self):
  106.         print "Update Pathing called"
  107.         geoObj = (findStreet(self.curveID).geometryObject) + ".nextCurve" # get current curveID's matching geo object and append .nextCurve
  108.         self.curveID = cmds.getAttr(geoObj) # save next curve's id into curveID
  109.         print "PATHING UPDATED TO: " + str(self.curveID)
  110.  
  111.     def accelVehicle(self): # to be implemented into cVehicle class
  112.         if (self.vehicleVelocityMultiplier > globalVehicleSpeed):
  113.             self.vehicleVelocityMultiplier =+ globalAccelValue # increases vehicle velocity by globalAccelValue each iteration until vehicle reaches standard travel speed
  114.         else:
  115.             self.vehicleVelocityMultipier = globalVehicleSpeed # if value becomes higher than globalVehicleSpeed, value is replaced with GVS to prevent overspeeding
  116.  
  117.     def decelVehicle(self): # to be implemented into cVehicle class
  118.         if (self.vehicleVelocityMultiplier > 0):
  119.             self.vehicleVelocityMultiplier =- globalDecelValue # decreases vehicle velocity by globaDecelValue each iteration until value becomes 0.
  120.         else:
  121.             self.vehicleVelocityMultiplier = 0 # if value is less than 0, it is replaced with 0 to prevent negative values
  122.  
  123.     # reserved for future additions
  124.  
  125. def initVehicle( x ):
  126.     global vehicles
  127.     newV = cVehicle()
  128.     newV.id = x
  129.     newV.fallbackCurveID = 1
  130.     vehicles.extend([newV]) # add a new vehicle to the end of the list
  131.    
  132. def initStreet():
  133.     global streets
  134.     x = cmds.ls(sl = True)
  135.     y = x[0] + ".curveID"
  136.     z = x[0] + ".nextCurve"
  137.     newS = cStreet()
  138.     newS.curveID = cmds.getAttr(y)
  139.     newS.nextCurve = cmds.getAttr(z)
  140.     newS.geometryObject = x[0]
  141.     streets.extend([newS])
  142.  
  143. def initStreetFromFile(curveID, nextCurve, geometryObject):
  144.     global streets
  145.     streets = []
  146.     newS = cStreet()
  147.     newS.curveID = curveID
  148.     newS.nextCurve = nextCurve
  149.     newS.geometryObject = geometryObject
  150.     streets.extend([newS])
  151.  
  152. def findStreet( x ):
  153.     try:
  154.         global streets
  155.         for s in streets:
  156.             if s.curveID == x: return s
  157.     except:
  158.         return 0
  159.  
  160. def findVehicle( x ):
  161.     try:
  162.         global vehicles
  163.         for v in vehicles:
  164.             if v.id == x: return v
  165.     except:
  166.         return 0
  167.  
  168. def getSceneLength():
  169.     return cmds.playbackOptions( query = True, maxTime = True ) # get max length of scene
  170.  
  171. def doSim():
  172.     global globalSubstepValue
  173.     global sceneLength
  174.     sceneLength = getSceneLength()
  175.     cmds.currentTime(0 ,edit = True)
  176.     currentTime = 0
  177.     while currentTime < sceneLength:
  178.         for v in range(1,(len(vehicles)+1)):
  179.             print "Press X to terminate simulation"
  180.             c = getKey()
  181.             if (c == 'x'):
  182.                 cmds.currentTime(sceneLength, edit = True)
  183.             vehCurveID =(findVehicle(v).curveID)
  184.             curve = (findStreet(vehCurveID).geometryObject)
  185.             uValue = ((findVehicle(v).motionPath) + ".uValue")
  186.             getUValue = cmds.getAttr(uValue)
  187.             addIncValue = getPathIncrement(curve) # determines amount to add onto existing uValue per cycle
  188.             print ("\naddincValue = " + str(addIncValue))
  189.             incValue = (cmds.getAttr(uValue)) + addIncValue # adds incremental value onto the current u
  190.             print ("\nincValue = " + str(incValue))
  191.             if incValue > 1:
  192.                 cmds.setAttr(uValue, 1)
  193.                 print "Switching!"
  194.                 findVehicle(v).doSwitch()
  195.             else:
  196.                 if getUValue < 0.25:
  197.                     incValue = math.sin(incValue)
  198.                     print ("sin\'d incValue = " + str(incValue))
  199.                 cmds.setAttr(uValue, incValue)
  200.                 print cmds.getAttr(uValue)
  201.         z = currentTime + globalSubstepValue
  202.         cmds.currentTime(z, edit=True)
  203.         currentTime = cmds.currentTime(query = True)
  204.  
  205. def simulate():
  206.     global pathPool
  207.     for v in range(1,(len(vehicles)+1)):
  208.         vehCurveID =(findVehicle(v).curveID)
  209.         curve = (findStreet(vehCurveID).geometryObject)
  210.         uValue = ((findVehicle(v).motionPath) + ".uValue")
  211.         getUValue = cmds.getAttr(uValue)
  212.         addIncValue = getPathIncrement(curve) # determines amount to add onto existing uValue per cycle
  213.         incValue = (cmds.getAttr(uValue)) + addIncValue # adds incremental value onto the current u
  214.         getCurve(findVehicle(v).geometryObject)
  215.         print pathPool
  216.         if (len(pathPool) > 1):
  217.                 print ("Selecting random path number: " + str(random.randint(0, (len(pathPool)))))
  218.                 z = (random.randint(0, (len(pathPool))))
  219.                 print ("New path = " + str(pathPool[z]))
  220.         else:
  221.             z = 0
  222.         if incValue > 1:
  223.             cmds.setAttr(uValue, 1)
  224.             print "Switching!"
  225.             if (len(pathPool) > 0):
  226.                 print ("New path = " + str(pathPool[z]))
  227.                 findVehicle(v).attachToPath(pathPool[z])
  228.             else:
  229.                 print "Curve not found, connecting to fallback"
  230.                 findVehicle(v).attachToPath(findVehicle(v).fallbackCurveID)
  231.         else:
  232.             cmds.setAttr(uValue, incValue)
  233.  
  234. def getPathIncrement(curve):
  235.     global sceneLength
  236.     sceneLength = getSceneLength()
  237.     sceneFPS = cmds.currentUnit( query = True, time = True ) # get fps of scene
  238.     pathLength = cmds.arclen(curve)
  239.     if sceneFPS == "game": sceneFPS = 15.0
  240.     if sceneFPS == "film": sceneFPS = 24.0
  241.     if sceneFPS == "pal": sceneFPS = 25.0
  242.     if sceneFPS == "ntsc": sceneFPS = 30.0
  243.     if sceneFPS == "show": sceneFPS = 48.0
  244.     if sceneFPS == "palf": sceneFPS = 50.0
  245.     if sceneFPS == "ntscf": sceneFPS = 60.0
  246.     pathIncrement = (1.0 / pathLength) * (globalSpeed / sceneFPS)
  247.     return pathIncrement
  248.  
  249. def generatePathFile(scene):
  250.     projectDir = cmds.workspace( q=True, dir=True )
  251.     os.chdir(projectDir)
  252.     scene = (scene + ".tdf")
  253.     print ("Writing to " + os.getcwd())
  254.     f = open( scene, 'w')
  255.     y = range(1, (len(streets)+1))
  256.     for x in y:
  257.         print x
  258.         f.writelines(str(findStreet(x).curveID) + '\n')
  259.         f.writelines(str(findStreet(x).nextCurve) + '\n')
  260.         f.writelines(str(findStreet(x).geometryObject)+ '\n')
  261.         f.writelines(str(findStreet(x).isBranched)+ '\n')
  262.         f.writelines(str(findStreet(x).branch1)+ '\n')
  263.         f.writelines(str(findStreet(x).branch2)+ '\n')
  264.         f.writelines(str(findStreet(x).branch3)+ '\n')
  265.         f.writelines(str(findStreet(x).branch4)+ '\n')
  266.         f.writelines(str(findStreet(x).branch5)+ '\n')
  267.     f.close()
  268.  
  269. def readPathFile(scene):
  270.     projectDirectory = cmds.workspace(q=True, rd=True)
  271.     currentScene = os.path.abspath(cmds.file(q=True, sn=True))
  272.     if 'scene' in cmds.workspace(q=True, frl=True):
  273.         sceneDirectory = os.path.join(projectDirectory, cmds.workspace(fre='scene'))
  274.     os.chdir(projectDir)
  275.     f = open( scene, 'r')
  276.     for x in range(0,(len(streets)+1)):
  277.         while y < 9:
  278.             curveID = f.readline()
  279.             nextCurve = f.readline()
  280.             geometryObject = f.readline()
  281.             isBranched = f.readline()
  282.             brance1 = f.readline()
  283.             branch2 = f.readline()
  284.             branch3 = f.readline()
  285.             branch4 = f.readline()
  286.             branch5 = f.readline()
  287.         initStreetFromFile(fCurveID, fNextCurve, fGeometryObject)
  288.     f.close()
  289.  
  290. def get2dLineDist(vehicle1, vehicle2):
  291.     v1 = cmds.xform(vehicle1, t=True, ws=True, q=True)
  292.     v2 = cmds.xform(vehicle2, t=True, ws=True, q=True)
  293.     dX = (v1[0] - v2[0])
  294.     dZ = (v1[2] - v2[2])
  295.     xzLineDist = math.sqrt((dX * dX) + (dZ * dZ))
  296.     return xzLineDist
  297.  
  298. # def checkAvoidance():
  299.     # global globalAvoidDistance
  300.     # for x in vehicles:
  301.         # for y in vehicles:
  302.             # if findVehicle(x) == findVehicle(y):
  303.                 # continue
  304.             # else:
  305.             # z = get2dLineDist(x, y)
  306.             # z = get3dLineDist(x, y)
  307.             # if (z < globalAvoidDistance):
  308.                 # findVehicle(x).decelVehicle()
  309.             # else:
  310.                 # findVehicle(x).accelVehicle()
  311.  
  312. # exec code
  313.  
  314. # dynamic curve detection testing !!
  315.  
  316. def getCurve(vehicle):
  317.     global pathPool
  318.     pathPool = []
  319.     for x in range(1,(len(streets)+1)):
  320.         dist = (get2dLineDist(vehicle, (findStreet(x).geometryObject)))
  321.         if (dist < 0.25):
  322.             print ("Detected curve: " + str(findStreet(x).curveID))
  323.             pathPool.extend([findStreet(x).curveID])
  324.     print (len(pathPool))
  325.     if (len(pathPool) != 0):
  326.         for x in range(1, len(pathPool)):
  327.             print pathPool[x]
  328.  
  329.  
  330. streets = []
  331. vehicles = []          
  332. initStreet()
  333.  
  334. pathPool[0]
  335.  
  336. initVehicle(1)
  337. findVehicle(1).attachToPath(1)
  338.  
  339. cmds.expression(string=("python \"simulate()\";"))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement