vehicle traffic simulation - penn engineeringcse400/cse400_2010_2011/cis401_final_rep/4.… ·...

10
Vehicle Traffic Simulation CIS 400/401- Senior Project Final Report Norman Badler [email protected] Univ. of Pennsylvania Philadelphia, PA Joseph Weinhoffer [email protected] Univ. of Pennsylvania Philadelphia, PA Fen Fei Yang [email protected] Univ. of Pennsylvania Philadelphia, PA ABSTRACT Abstract: Computer graphics has recently become steadily more applicable for use in technological devices and enter- tainment. Along with that development, virtual crowd sim- ulations have become increasingly popular and necessary to successfully create realistic movies, video games, and train- ing simulations. An important component of designing a realistic population simulator is to incorporate automobiles, traffic, road networks, and the associated rules which allow those vehicles to properly interact with pedestrians and other vehicles. Many traffic simulators currently exist independently of a crowd simulator with human agents. The goal of this project is to design a traffic simulation system that can be incorpo- rated into an existing crowd simulation system, full scale 3D model city, and road network. Currently the crowd simula- tor does not include vehicles, and is therefore not entirely realistic. By including a traffic simulation the environment will gain another level of detail and realism. 1. INTRODUCTION Interaction with objects, places, and other people is a fun- damental piece of human life. Every day is defined by the interactions that we make with the world around us. These interactions often go unnoticed, and many decisions or ac- tions we take are autonomous and automatic. Many of the people that we pass each day, or locations that we move through, are hardly registered in our minds, but instead pro- vide a fluid and dynamic background. While these events might not have a direct impact on our lives, they are a fun- damental piece of our interaction with the world. If we try and picture a world where this extraneous background ac- tivity was absent, and nothing dynamic happened outside of what we directly interact with in our lives, the world would be a very monotonous place. Recent software has been used to simulate this interac- tion with human terrain, all of the action and life of people, vehicles, and objects that goes on unnoticed in the back- ground of a location. These simulations provide feasible background environments for any virtual world space. These virtual crowds have become popular and necessary to cre- ate realistic movies, video games, and training simulations. An important piece of this human terrain is vehicle traffic and interaction with automobiles. People drive in vehicles to achieve locomotion goals, cross streets in towns and cities where they must be aware of traffic, and occasionally use vehicles for sports and events. In current crowd simulators that are built with a road net- work, any absence of vehicles is extremely noticeable. Many traffic simulators currently exist independently of a crowd simulator with human agents. The focus of this project is to design a traffic simulation system that can be incor- porated into an already existing crowd simulation system, city, and road network. By building a traffic simulator, the simulation environments gain an additional level of detail and realism, and are more likely to be incorporated into fu- ture devices that require accurate and intelligent automated backgrounds. This paper first discusses past work related to vehicle sim- ulation, then highlights the system model for the vehicle and traffic simulator. Next, the implementation of key compo- nents of the system is explored, along with justification of various design decisions. Finally, the paper concludes with a summary of the system’s performance, a discussion of the ethicality of the project, and comments on potential future work. 2. RELATED WORK As interest in simulating individual people and crowds has grown, simulating traffic and vehicles to accompany those human interactions has become crucial. Traffic simulation has become an important development, helping city planners design roads that do not congest traffic or cause accidents. With current commercial software like VISSIM [9], simula- tions have been made easier. VISSIM can simulate complex dynamic systems such as traffic using a block diagram lan- guage that simplifies developing specific simulations. Cramer et al. [5] simulated the individualized behavior of autonomous cars. In the simulation, all of the cars correctly obey the laws of physics, such as acceleration and braking. Every car has some personality traits mimicking those of real drivers, such as how aggressive the car is, how atten- tive the car is to its surroundings, and how law-abiding the car is to traffic rules. Simulation of individualized agents is commonly referred to as a microscopic model of traffic (Fig. 1). On the opposite end of the spectrum is the macroscopic model of simulation. Sewall et al. [8] used a continuum based macroscopic model to simulate traffic. They focus on a large scale system where traffic can be simulated in real time. The model correctly handles lane changes, merges, and also changes in driving behavior due to changes in speed limit. This method demonstrates how a macroscopic model can be applied so that animating a great number of vehicles in a large-scale traffic network runs in an interactive rate. All of the cars in the simulation are described by a single

Upload: duongdat

Post on 19-Jul-2018

214 views

Category:

Documents


0 download

TRANSCRIPT

Vehicle Traffic Simulation

CIS 400/401- Senior Project Final Report

Norman [email protected]

Univ. of PennsylvaniaPhiladelphia, PA

Joseph [email protected]

Univ. of PennsylvaniaPhiladelphia, PA

Fen Fei [email protected]

Univ. of PennsylvaniaPhiladelphia, PA

ABSTRACTAbstract: Computer graphics has recently become steadilymore applicable for use in technological devices and enter-tainment. Along with that development, virtual crowd sim-ulations have become increasingly popular and necessary tosuccessfully create realistic movies, video games, and train-ing simulations. An important component of designing arealistic population simulator is to incorporate automobiles,traffic, road networks, and the associated rules which allowthose vehicles to properly interact with pedestrians and othervehicles.

Many traffic simulators currently exist independently of acrowd simulator with human agents. The goal of this projectis to design a traffic simulation system that can be incorpo-rated into an existing crowd simulation system, full scale 3Dmodel city, and road network. Currently the crowd simula-tor does not include vehicles, and is therefore not entirelyrealistic. By including a traffic simulation the environmentwill gain another level of detail and realism.

1. INTRODUCTIONInteraction with objects, places, and other people is a fun-

damental piece of human life. Every day is defined by theinteractions that we make with the world around us. Theseinteractions often go unnoticed, and many decisions or ac-tions we take are autonomous and automatic. Many of thepeople that we pass each day, or locations that we movethrough, are hardly registered in our minds, but instead pro-vide a fluid and dynamic background. While these eventsmight not have a direct impact on our lives, they are a fun-damental piece of our interaction with the world. If we tryand picture a world where this extraneous background ac-tivity was absent, and nothing dynamic happened outside ofwhat we directly interact with in our lives, the world wouldbe a very monotonous place.

Recent software has been used to simulate this interac-tion with human terrain, all of the action and life of people,vehicles, and objects that goes on unnoticed in the back-ground of a location. These simulations provide feasiblebackground environments for any virtual world space. Thesevirtual crowds have become popular and necessary to cre-ate realistic movies, video games, and training simulations.An important piece of this human terrain is vehicle trafficand interaction with automobiles. People drive in vehiclesto achieve locomotion goals, cross streets in towns and citieswhere they must be aware of traffic, and occasionally usevehicles for sports and events.

In current crowd simulators that are built with a road net-

work, any absence of vehicles is extremely noticeable. Manytraffic simulators currently exist independently of a crowdsimulator with human agents. The focus of this projectis to design a traffic simulation system that can be incor-porated into an already existing crowd simulation system,city, and road network. By building a traffic simulator, thesimulation environments gain an additional level of detailand realism, and are more likely to be incorporated into fu-ture devices that require accurate and intelligent automatedbackgrounds.

This paper first discusses past work related to vehicle sim-ulation, then highlights the system model for the vehicle andtraffic simulator. Next, the implementation of key compo-nents of the system is explored, along with justification ofvarious design decisions. Finally, the paper concludes witha summary of the system’s performance, a discussion of theethicality of the project, and comments on potential futurework.

2. RELATED WORKAs interest in simulating individual people and crowds has

grown, simulating traffic and vehicles to accompany thosehuman interactions has become crucial. Traffic simulationhas become an important development, helping city plannersdesign roads that do not congest traffic or cause accidents.With current commercial software like VISSIM [9], simula-tions have been made easier. VISSIM can simulate complexdynamic systems such as traffic using a block diagram lan-guage that simplifies developing specific simulations.

Cramer et al. [5] simulated the individualized behavior ofautonomous cars. In the simulation, all of the cars correctlyobey the laws of physics, such as acceleration and braking.Every car has some personality traits mimicking those ofreal drivers, such as how aggressive the car is, how atten-tive the car is to its surroundings, and how law-abiding thecar is to traffic rules. Simulation of individualized agentsis commonly referred to as a microscopic model of traffic(Fig. 1).

On the opposite end of the spectrum is the macroscopicmodel of simulation. Sewall et al. [8] used a continuum basedmacroscopic model to simulate traffic. They focus on a largescale system where traffic can be simulated in real time.The model correctly handles lane changes, merges, and alsochanges in driving behavior due to changes in speed limit.This method demonstrates how a macroscopic model canbe applied so that animating a great number of vehiclesin a large-scale traffic network runs in an interactive rate.All of the cars in the simulation are described by a single

Figure 1: Example of Traffic Control From [5]

computational cell that dictates each car’s actions.Both of these systems simulate traffic, but do not include

any human agents. Multiple systems have been developedthat specifically focus on realistically visualizing crowds andhuman interactions, such as Heisenberg [3] or CAROSA [2].Within these crowd simulations are virtual humans that eachhave specific sets of actions, goals, and responses to events.An interesting challenge faced when designing a traffic sys-tem for a crowd simulator is correctly implementing the nec-essary interactions between the human agents and the ve-hicles. Examples of this include behaviors such as a persongetting on or off of a bus, or a driver parking a car and thengetting out.

As better traffic simulations are used to help plan cities,research on these simulations has taken on other purposes.One such example is the work done on creating believabletraffic in entertainment such as video games. XaitTraffic[11] is one of the most sophisticated traffic simulations incomputer games. It focuses less on the overall city trafficflow, but on the main cars in action on the computer screen.The cars in focus are completely simulated with actions suchdifferent driving maneuvers, drifts, and crashes. The simu-lation is extremely advanced, but is only limited to a smallarea of interest. Such a sophisticated simulation would gen-erally not be used for large-scale crowd simulation projects.

In some recent work, Jan Krassnigg [7] worked on a mas-ters thesis about pedestrian and traffic simulation in a vir-tual city environment. He constructed a virtual model ofAachen in Germany, and created crowd and traffic simula-tion for the city. The traffic is done by creating roadmapsfrom the virtual city data and each car follows the same be-havioral pattern with some randomness. The simulation isdesigned to handle large numbers of vehicles at once in arealistic manner without accounting for more intricate de-tails. The cars all react to situations in the same way, withno differentiation between any two cars in the simulation.Possible expansion on such a simulation would be to addthe implementation of different vehicles. Examples wouldbe buses that follow a set route and pick up pedestrians, orprivate cars that drive through the city and eventually park.

As the simulation of traffic becomes more complex, pro-cessing speed becomes an issue. Anthony Chronopoulos etal. [4] worked on a traffic simulation that used parallel pro-cessing. Chronopoulos used a macroscopic continuum traffic

model which is based on traffic density, volume, and speedto simulate freeway traffic, which is very useful in applica-tions such as highway safety and driver guidance in highlydense traffic. Because the system maps the simulation toa parallel computer architecture, it is capable of simulatinghighway traffic flow in real time. The use of parallel pro-cessing greatly increases the simulation speed such that atwo hour traffic flow simulation that takes 2.35 min on asingle processor only takes 5.25 seconds on the parallel traf-fic system. When combining crowd and vehicle simulations,processing speed is not as much of a concern, since the sim-ulation occurs in the background and real time visualizationis not necessary.

Recent work done by Jur van den Berg et al. [10] of theUniversity of Carolina attempts to simulate traffic throughreal world data and animate the events between time peri-ods. The basic idea is for sensors in the real world, currentlylocated in Chapel Hill, NC, to take sample data in time in-tervals. The simulation will take that data, analyze the po-sition of the cars between samples and create a simulationof the car moving from one location to another using trafficsimulation. It reconstructs the movements of the car whileminimizing lane changes, keeping a safe distance from othercars, and smoothing the overall traffic. The whole simula-tion works in real time, allowing the user to see virtualizedtraffic of the real world.

3. SYSTEM MODELThis project involves designing a traffic simulation system,

which includes vehicle dynamics, direct interaction with aroad network, and incorporation of traffic rules. The over-all benefit of designing this system will be to add a nec-essary component of detail and realism to an already wellestablished, functional, and realistic human simulator. Thiscombined simulation can then be used as a highly realisticbackdrop for any type of virtual world.

The primary function of the system is to take as inputa road network, generate dynamic vehicles based on thatnetwork data, and display the simulation in an accurateway. The road networks are obtained from CityEngine, a3D Modeling program used to generate procedural cities androad networks. An example of one such generated city canbe seen in Fig. 2. Once the road network is received by thesimulation, the system generates an internal data structureto store the road data. Simulated vehicles are then cre-ated specifically mapped to exact locations obtained fromthe road data structure. When the simulation begins, pre-determined algorithms determine the actions taken by eachvehicle along the roads they have been assigned to. Finally,the positions of each vehicle are smoothly animated in a des-ignated display, which includes making turns, acceleratingand decelerating to account for additional cars and avoidcollisions, and stopping at traffic lights.

The most important piece of the system is the simulationcodebase. The simulation code has at its core a road networkdata structure, constructed from CityEngine data, whichmonitors every vehicle’s current position on the streets. Thereis also a global list of all vehicles currently being simulated.Each vehicle stores its currents position, direction, and ve-locity. The simulation can be updated, a process which,when executed, moves all of the vehicles one step forward intime. After the simulation connects to a display, the displaycan easily access both the road network data structure and

Figure 2: City Engine Example City

the list of vehicles. From these lists, the current locationcoordinates in CityEngine world space can be retrieved foreach street and vehicle, which can subsequently be used todraw the objects on the screen. When a display update oc-curs, a call is made to the simulation to update all of thevehicle positions. This update process takes into accountfor each vehicle whether it is turning, stopped at a trafficlight, or moving among other vehicles, and then calculatesthe appropriate new location based on those factors. Onceall of the vehicles have been updated by this process, thedisplay can simply iterate over the vehicle list and redrawthem in their new positions. Because the simulation updateis called whenever the display updates, the system animatessmoothly. Fig. 3 visualizes this model.

Figure 3: 2D Simulation Workflow

The diagram illustrates the initial step of road networkdata being retrieved from CityEngine and the correspond-ing data structure being constructed. This data structure isthen provided to the simulation codebase, where vehicles areinstantiated and generated. Because vehicles are generateddirectly on specific roads in the network data structure, ve-hicle positions are computed relative to the roads they aretraveling on. The vehicle position data is then sent to thedisplay, and the vehicles are drawn. Next, the system en-ters an animation loop where the display sends requests tothe simulation to update the positions of all vehicles. Af-

ter the update, the display iterates over the list of vehiclesand redraws them at their current positions. This processcontinues until the simulation is closed.

The system is currently implemented in both 2D and 3Denvironments. The 2D implementation launches a very sim-ple display created with OpenGL, primarily used for thedevelopment and testing of the simulation codebase. The3D system is integrated with the Unity game engine, andwill eventually be coupled with the Heisenberg crowd simu-lation, in order to place the traffic simulation inside a mod-ifiable, full scale, 3D city environment. Both the 2D and3D systems utilize the same basic simulation codebase andframework. However, the 2D system utilizes OpenGL as itsdisplay, depicted in Fig. 3, while the 3D system uses a fullgame engine, Unity, depicted in Fig. 4, in order to incor-porate the 3D city model from CityEngine and any crowdsimulator. The Heisenberg crowd simulation system cur-

Figure 4: 3D Simulation Workflow

rently runs using the Unity game engine, and also obtainsits urban environment from CityEngine. Because of thesesimilarities, it is simple to add the vehicle simulation sys-tem into this workflow as well.

Once incorporated, the game engine simply queries thevehicle simulation system for updated vehicle positions todisplay, along with calls to the crowd simulation system forupdated pedestrian positions. The game engine handles thedisplay of both simulations simultaneously, and renders full3D models for the city, pedestrians, and vehicles instead ofsimple OpenGL primitives. Fig. 5 depicts this combinedworkflow. The left half of the pipeline is the same vehiclesimulation model as developed and used in the Unity 3Dsystem (Fig. 4), with the difference being the addition ofthe crowd simulation codebase and human agents. Datafrom CityEngine is sent to the crowd and vehicle simulationsystems concurrently, allowing the positions of all people andvehicles to be generated in reference to the city terrain androads. All position data is then received by Unity, whichupdates the positions for each object and renders them tothe 3D display. Unity then enters into a loop with bothsimulation codebases, requesting updates for both vehicleand pedestrian locations from their respective systems, andcontinually retrieving updated lists of positions. The displayis then updated by iterating over these lists of vehicles andpedestrians and redrawing each entity. Interactions betweenvehicles and human agents are handled dynamically by thegame engine, since it stores data on every object’s locationand controls the events broadcast to the world.

4. SYSTEM IMPLEMENTATIONThe traffic simulation system code is written in C++. The

2D system display is generated using OpenGL, while the

Figure 5: 3D Simulation Workflow Including CrowdSimulation System

3D system is run and rendered using the Unity game en-gine. The simulation system was implemented in two pieces,a simulation codebase and a display layer, and each piecehas multiple components. Implementation history has beenrecorded on a blog for reference and development progresstracking [12].

4.1 SimulationThe key components of designing the simulation codebase

can be divided into generating the road network data struc-ture, creating the vehicles, controlling vehicle movement,implementing and controlling traffic lights, and preventingcollisions.

4.1.1 Road NetworkThe road network data is received from the CityEngine

program. In any generated city, one can choose to view onlythe road network and then easily select all of the street edges,as seen in Fig. 6. Each street contains a vertex pair, and ad-jacent streets will contain the same vertex data. CityEnginehas an option to export graph data into a Drawing ExchangeFormat (DXF) file. DXF files are human readable and arecomposed of pairs of codes with associated values. Thereare multiple tables and documents online that explain eachcode’s meaning and its potential values, particularly pub-lished by Autodesk [6] and AutoCAD [1]. After exportingthe file and correctly identifying the codes which define thestreet edges, the file is parsed. As the DXF file is parsed,streets are added to the network dynamically. The networkalso immediately updates its current streets to reflect anynew additions. In this way, when parsing is completed theentire street network is formed and correctly connected. Thenetwork is also an identical copy of the original found inCityEngine, as seen by comparing the simulation display ofthe network in Fig. 7 to its representation within CityEnginein Fig. 6.

Each pair of vertices that define a street is placed inside a

Figure 6: City Engine Road Network

Figure 7: Full Road Network as Displayed in Simu-lation System

street object. Every street object contains references to allof the streets connected to each of its two vertices. Streetsare also broken down further into two edge objects, whichrepresent the directions that a vehicle could travel on thatstreet, one for each “lane”. One edge will travel from V 0 toV 1 while the other edge will travel from V 1 to V 0. Thisimplementation was used so that vehicles could be travel-ing specifically on one edge, instead of a street in general.This design allows for effective replication of two way streetswith different lanes, prevents vehicles from overlapping oneanother in the simulation, simplifies checking for collisions,and reduces the amount of searching done to discover whichvehicles are close in proximity.

In its current state the simulation code does not account

for any highways or one way streets; every road in the sim-ulation is a simple two-way street. The DXF file exportedfrom CityEngine does not contain any parameters relating tolane width or number of lanes for the roads, so this informa-tion was not available for use in the simulation. Generatingrandom highways throughout the road network would notbe realistic, and would also have a high performance cost,so the design decision was made to make every road functionidentically at this time.

4.1.2 VehiclesAfter the street network is formed, vehicle objects are cre-

ated and randomly assigned to edges, along with their re-spective streets. Because the road network is implementedas a list of streets, each containing two edges, the streetcan be chosen randomly by selecting an arbitrary list index.Every new vehicle is added to a global vehicle list. Eachvehicle also contains a reference to the edge and street thatit is currently driving on, and vice versa. In this way, theredoes not need to exist a global map of which streets containwhich vehicles, which would require an immense amount ofmemory to store, and an infeasible amount of time to searchthrough and update. After a vehicle is designated to a par-ticular street, it is given a direction by random selection ofone of the street’s two edges. After the edge is chosen, asimple identification of any point between the two edge ver-tices gives the vehicle its starting position. A small offset inthe direction perpendicular to the edge is used in order toseparate vehicles on the same street and give the illusion ofvehicles driving in distinct lanes. This also allows all vehiclesto properly obey the rule of driving on one side of a road.Because these computations take place whenever a vehicleis instantiated on a given street, at its moment of its cre-ation it immediately has a calculated position and direction.Base speed is provided for all vehicles by a global time stepconstant, retrieved from the user interface or game engine,which is then modified on a per vehicle basis to simulateacceleration and deceleration. Because the vehicle positionsare computed directly from the road network data receivedfrom CityEngine, the world space coordinates for the posi-tions in the simulation directly correspond to the coordinatesin CityEngine world space. Therefore, the simulation systemcan easily function in the full 3D CityEngine environmentwithout modifying or scaling any vehicle positions.

4.1.3 MovementEvery vehicle has a current position, direction (given by

the edge it is currently associated with), and speed. Whenan update call is made by the display function, the vehi-cle’s updated position in the given direction is computed asa modifier of its speed and a time step constant. If the newposition remains within the vertex boundaries of the cur-rent edge, the position is updated and returned. However,if the computed position is a location beyond the edge’s endvertex, the vehicle must choose to move on to a new street.In this way, the vehicles’ positions are always interpolationsbetween the two street vertices, and they never leave theconfines of the street edges. To simplify this procedure, assoon as a vehicle is placed on a street it checks which pos-sible streets it could move to after overstepping its currentstreet and randomly selects one. Because of this, whenevera vehicle’s new position is seen to extend beyond the cur-rent street, the remaining distance is calculated and that

distance is simply transferred to the new edge and traveledin that new direction. Once the vehicle switches to a newedge, its direction is also automatically updated to reflectthe orientation of the new edge’s vertices.

4.1.4 Traffic LightsAfter the street data structure is created, traffic lights

are generated for the road network. Due to the complexityof creating traffic lights for any intersections, it was deter-mined that only four way intersections in the road networkwould have traffic lights. The light generation algorithmsearches through the global list of street vertices, which arethe endpoints used in creating the streets themselves. Ev-ery vertex keeps track of the streets it belongs to, so a fourway intersection can be found by location all vertices thatcontain pointers to four street endpoints. At each of thesevertices, a traffic light is created located at that vertex’s lo-cation. The light is then appended to a global traffic lightlist. Each traffic light data structure contains its position,two light signals, and two edge lists corresponding to thelanes that must obey the light’s signals. Each light signalis either red, indicating that vehicles should stop, or green,indicating that vehicles should proceed through the inter-section. These two lights signals are programmed to alwaysbe opposites. Therefore, if one light signal is green then theother must be red. Each of a traffic light’s two light sig-nals corresponds to two edges on opposite sides of the lightand the intersection. Therefore, when a light turns green,vehicles positioned on the same street on either side of theintersection are allowed to move and turn.

However, not every four way intersection has two perfectlystraight roads that are perpendicular to each other. To findthe most suitable edges to match together for one of thetraffic light’s signals when street shapes and angles are ir-regular, the angle between the edges of the intersection arecalculated and used to determine the best potential matches.For every possible pairing of two edges in the four way in-tersection, the angle between them is calculated using thedot product operation and compared to the same calcula-tion for all of the other pairs. The best match for a givenstreet is to have the angle between two edges be exactly 180degrees, implying that the edges are parallel and the con-nected street is perfectly straight. However, in most casesthis is not possible, so the edges that form an angle closestto 180 degrees are chosen as one of the pairs and joined to alight signal. Then, the two remaining edges are assigned tothe other light signal. To ensure the angle returned from thedot product calculation is always within a range of zero to180 degrees, and that the direction of travel from one edgeto another is always the same, the angle calculation uses thevertex incident on both edges as the endpoint of the linesegments.

Each edge that ends in a four way intersection containsa reference to a traffic light. The vehicles traveling alongan edge check to see if a traffic light exists at the end ofthe edge. When they reach the end of the edge, the lightsignal for the edge is checked. If the light signal is green,then the vehicle’s motion path is unaffected and it contin-ues as normal. However, if the light is red, the vehicle’spath is blocked at the end of the edge by the light signal.Therefore, the vehicle reacts accordingly and decelerates asit approaches the intersection.

4.1.5 Collision PreventionA key component of the vehicle simulation is the preven-

tion of collisions. The simplest collisions are prevented be-tween vehicles moving along the same street edge. Each ve-hicle has a certain amount of space in front of it “reserved”,generally computed to be proportional to the vehicle’s cur-rent speed. When two vehicles are traveling along the sameedge where the following vehicle is moving faster than thefront vehicle, the former will smoothly decelerate until itreaches a location where the front vehicle does not enterits reserved space. In this way, a pre-determined constantfollowing distance is always enforced between two vehiclesthrough their reserved space. Fig. 8 depicts the use of this

Figure 8: Reserved Space Algorithm Example

algorithm. The single car has its set reserved space in frontof it, but because there are no other vehicles that could ob-struct its path it is able to accelerate and continue movingforwards. On the other hand, the two adjacent vehicles aretraveling at the same speed. The vehicle in the back caughtup to the vehicle in front, and when it could not proceedany further without having a conflict inside its designatedreserved space area, it maintains a steady velocity. The re-served space ensures that a collision will not occur betweenthese vehicles.

When a vehicle approaches the end of an edge, it checksto see if any vehicles are already present on the street it willmove on to after leaving the current street. This check issimple because every street contains a list of the vehiclescurrently on it. The vehicle seeking to move on to the streetcompares its position with that of the vehicle closest to iton the next street, if one exists. If the distance betweenthem is greater than the reserved space amount, then itcontinues movement as normal. If, however, the distanceis less than the amount of reserved space, the vehicle waitsand does not move forwards until another update is calledand the distance between them is increased. In this way, theconstant amount of reserved space is still preserved betweentwo vehicles during turns and collisions are avoided.

Preventing collisions at intersections between vehicles trav-eling in different directions is a related but more complicatedproblem. Each vehicle has its designated amount of reservedspace as described above. When a vehicle is moving along a

road and reaches a point where its reserved space is greaterthan the remaining distance to be traveled on that edge, theedge that the vehicle will travel to next is flagged as occu-pied. This flag persists until the vehicle crosses onto thatedge. With this flag implementation, whenever a vehicleapproaches an intersection it checks the flag of the edge itwill travel to next. If the edge is flagged, it is an indica-tion that another vehicle is approaching and going to turnonto that street first. The vehicle stops before the crossingand waits for the flag to disappear, which indicates that nomore vehicles are approaching, before continuing movementby checking reserved space as indicated earlier.

In general, traffic lights also act to prevent collisions. Sim-ilar to real life, traffic lights control vehicles for each direc-tion of a given street by restricting movement to only oneside of the traffic light at any given time. In this way, colli-sions between vehicles located at a four way intersection areimpossible when combined with the edge flagging systemdescribed above. One factor that was taken into accountwith the addition of traffic lights to the system along withthe edge flags was the potential negative effect of creating amini-deadlock. It was possible that one vehicle could obtaina flag for the next edge it wanted to move to, but wouldthen be stopped at a red light. Since the flag was taken,although unused, other vehicles that had a green light butwanted to move to the same edge were unable to move be-cause it remained flagged. This caused a temporary lock onsome vehicles for one traffic light cycle until the vehicle withthe edge flag received a green signal from the traffic light,continued travel, and ultimately released the edge flag. Thisproblem was resolved by changing the edge flagging systemso that vehicles would release their flags when stopped atred lights, which allowed other vehicles to continuing mov-ing uninhibited. The edge flagging system and the trafficlights now work simultaneously and synergistically to pre-vent collisions at four way intersections. Even on intersec-tions that are not four way, the edge flag implementationhas proved effective for preventing collisions. Section 5 il-lustrates the overall progress made in decreasing collisionsduring the development of the system.

4.2 2D DisplayFor the 2D system, the display layer was implemented us-

ing OpenGL. Each street and vehicle object have specifiedOpenGL drawing parameters defined in a Draw() method.The display is included as one component of the overall UI,which is designed using FLTK. The UI contains options forcontrolling the camera location, number of cars, and globaltime step to modify the execution speed of the entire simula-tion. Additionally, the camera can be moved using keyboardinput, allowing the user to pan around the scene as well aszoom in and out. The camera points in a fixed downward-facing direction, and the orientation of the axes is exactlythe same as CityEngine’s coordinate system. An examplescreenshot of the simulation with animated vehicles, turn-ing animations, and traffic lights can be seen in Fig. 9

4.2.1 RoadsRoads are drawn as GL Quads. The four vertices for the

quad are computed based on the two street vertices. Thesevertices are offset in the direction perpendicular to the lineformed between the two vertices in order to create a rect-angular road. The offset value is determined by a preset

Figure 9: 2D Simulation Display Example inOpenGL

lane width constant. Because the street network is stableand does not change during animation, a display list is cre-ated for the street network during instantiation so that thestreets do not need to be redrawn every iteration. Becausethe coordinate axes and up vector of the 2D display are ex-actly the same as those in CityEngine, the road networksare visually identical in each system See Fig. 6 and Fig. 7above for an example of this similarity.

4.2.2 VehiclesVehicles are drawn in the 2D display as simple cubes

scaled to fit the road network dimensions. In the display,the vehicles are red boxes with green fronts. The small greenpiece was added to the front of each box so the vehicle’scurrent direction could be easily identified. Whenever thedisplay sends a call to the simulation to update the vehi-cle positions, it also makes a call to redraw the display. Toupdate the positions of the vehicles each iteration, the dis-play makes a call to retrieve the list of all vehicles from thesimulation. The display then iterates over the entire list,calling the Draw() method on each vehicle. Because eachvehicle contains the computations internally for where andhow to draw itself, the process is extremely simplified andefficient. Vehicles also orient themselves at an angle specificto the street edge they are currently traveling on. This wasaccomplished by taking the dot product of the street edgevector and the X axis to compute an angle of rotation, whichis then applied to every vehicle before it is drawn.

4.2.3 Turning AnimationsWhen any vehicle approaches an intersection with another

street it enters into a special turning animation, separatefrom the normal functions that update location. The anglebetween the two streets is calculated, and from that anglea turning circle is defined. The vehicles then travel alongthe arc of the circle in order to turn smoothly. In order to

compute and execute this turn properly, many steps mustbe taken. Fig. 10 illustrates the process. First, the intersec-

Figure 10: Turning Animation Diagram

tion between the vehicle’s current and next edge, not street,is calculated. The distance from the start point of the turnand the end point of the turn to this intersection point isa fixed constant, labelled as x in Fig. 10. Once the inter-section point is found, the turn start and end points can beeasily computed by using this distance. The lines from thestart and end points to the edge intersection point form vec-tors that are both tangent to the turning circle. Computingthese vectors is simple, and once obtained it is trivial to findthe parallel vector in the direction of the turning circle’scenter. At this point, the intersection point between thesetwo vectors is found, which is exactly the center of the cir-cle. By then calculating the distance from the start and endpositions to the center, the circle’s radius r is discovered.

Now that the turning circle radius r is computed, the in-cremental position steps around the arc of the circle for theturn can be calculated. The total turn angle θ is found bytaking the dot product of the street edges. The amount ofthe angle travelled per time increment is a function of thevehicle’s current speed, the overall time step, and the radiusof the circle.

X = turnCircleCenterX + r ∗ cos(currentAngle) (1)

Z = turnCircleCenterZ + r ∗ sin(currentAngle) (2)

Once all of these values are set, the new X position of anyturn can easily be calculated from equation 1 and the new Zposition from equation 2. The position of each turning ve-hicle will be updated in this manner until the current angleis greater than the total angle θ. At this point, the vehicle’scurrent edge and street are set appropriately, all other val-ues are reset, and movement along the next edge continuesnormally.

4.2.4 Traffic LightsTraffic lights are also displayed in a unique way in the

simulation. For each traffic light at the four way intersec-tions in the simulation, a group of four small GL Circles isdrawn, representing the current light state on each of thefour streets. The streets that are closest to being parallelwith one another form the first pair of lights, while the re-maining two streets form the second. The colors of each

pair of lights are linked together so they are always equal.When one pair of lights is green, the other will be red, andvice versa. The current light color is set by a simple booleanvariable, which flips in the simulation after a certain numberof update iterations have passed. Each traffic light is instan-tiated randomly so that the direction showing a red light isnot the same throughout the road network. The lights alsoall start with a different number of “counted” updates, sothat the lights do not all switch simultaneously.

4.2.5 User InterfaceThe simulation display is incorporated inside of the FLTK

user interface toolkit to allow for dynamic modification ofthe simulation. The UI currently includes functionality forcontrolling the camera, changing the number of cars beingsimulated, and increasing or decreasing the global time stepof the simulation. Changing the time step directly affectsboth the speed of the vehicles and how quickly the traf-fic lights change colors. The UI is linked to the simulationcodebase so any modifications to parameters in the UI areautomatically and instantaneously reflected in the simula-tion.

4.3 3D DisplayThe Unity game engine is used to display the vehicle simu-

lation in 3D. The simulation codebase was designed to func-tion separately from the display. Therefore, the simulationcodebase was compiled and compressed into a Dynamic LinkLibrary (DLL) which can be imported into Unity. The DLLis defined with specific methods that give access to core func-tions of the simulation codebase. These functions are:

• Init, which takes in as parameters a CityEngine DXFfile and the desired number of vehicles. Init then ini-tializes the entire simulation by setting up the roadnetwork and creating all of the vehicles.

• GetStreets, which returns a list of street objects forevery street in the road network. Every street objectcontains the positions of its four corner vertices, whichare subsequently used to draw the road network in the3D display. This is generally only used once during theinitialization of the system.

• GetNumStreets, which returns the number of streetsin the road network. This is also generally only usedduring the initialization of the system.

• Step, which causes the simulation to take one step intothe future based on a provided time step. This stepis calculated by updating all of the vehicle positionsonce.

• GetState, which returns a list of positions and direc-tions for all of the vehicles in the simulation.

Based on this DLL specification, Unity can easily set upand run the simulation by repeatedly calling the Step func-tion and then retrieving the list of updated positions fromGetState. Any 3D model can be specified as the vehicle,which is then replicated and rendered at all of the positionsreturned by simulation DLL. An example 3D display fromUnity can be seen in Fig. 11.

A crowd simulation system can be easily incorporated intothis same “scene” in Unity by using a similar DLL design.

Figure 11: 3D Simulation Display Example in Unity

Including a crowd simulation DLL would enable Unity tomake function calls for that system very similar to thoseused in the vehicle simulation. Unity could then simultane-ously get updates and render objects at their new locationsfor both simulation systems. This would result in dynamichuman agents also present in the same display as the ve-hicles. This simulation could ultimately also import andinclude the full 3D city model from CityEngine, resulting inthe desired highly realistic and dynamic simulated environ-ment.

5. SYSTEM PERFORMANCEJudging system performance for any simulation program

is relatively difficult, because there are no simple ways ofrunning quantitative tests to ensure correctness. Becausethe system is designed to function as a realistic replica ofa road network and vehicle interactions, the optimal wayto determine if the system is performing correctly is to vi-sually compare the system to the real world. Currently,the system does not take into account all traffic laws whencalculating vehicle positions, and is also lacking key compo-nents of real life travel such as highways and multiple laneroads. Because of these absences, the simulation is not yetidentical to traffic. However, the development of the sys-tem has resulted in many features that do correspond verywell to the real world. Vehicles travel smoothly on the roadnetwork without crossing over lanes or colliding. They alsoaccelerate and decelerate at the appropriate times, such asspeeding up when no other vehicles are present on the roadand slowing down when approaching an intersection. Trafficlights switch on and off at realistic intervals, and vehicles re-act appropriately to the laws imposed by the lights at fourway intersections. Finally, vehicles turn smoothly aroundcorners and curves in the roads, moving faster for quickerhairpin turns and at a much slower pace for long drawn outcurves. All of the visual tests that have been run for thecurrently implemented features have passed with successfuldegrees of realism, so up to this point system performanceis as expected.

Although overall realism of the system is difficult to de-termine by running empirical tests, the number of collisionsthat occur in the simulation can be monitored and recorded.By checking during each position update to see if any vehi-cle objects have moved too close to one another, a collisioncan easily be detected. As development of the system pro-gressed, the number of collisions was tracked. To perform

the collision test on each iteration of the design, the simula-tion was run on the same specific CityEngine road networkmap with 10 cars for a period of exactly 60 seconds. The re-sults of these tests can be seen in Fig. 12. The graph, plotted

1

10

100

1000

10000

100000

1 2 3 4 5 6 7 8 Num

ber o

f Col

lisio

ns (L

og B

ase

10)

Project Version

Vehicle Collision Over Time

Figure 12: Vehicle Collisions Over Time

on a log scale, clearly shows that collisions have drasticallydecreased over time as the simulation has continued devel-opment. During the first implementation of the system, carswere not placed on distinct edges, so the collision count isextremely high. Once cars moving in different directionsare separated on their respective streets, the numbers dropconsiderably and vary from a few hundred collisions to aminimum at 90. Iterations four and five of the system werethe first to include turning animations and traffic lights atintersections. Before all of the bugs were solved and thesefeatures were perfected, there was an increase in collisions ascars turned at the same time, took incorrect turning paths,or decided to disobey red lights and drive through intersec-tions. However, it can be concluded from this graph thatcollisions in the most recent versions of the system are thelowest of the entire development process. Therefore, by thisexperimental test of system performance, the simulation hasbeen consistently improving over time.

6. ETHICAL ISSUESOne potential ethical issue that could occur during use of

the traffic simulation system is if a user decides to importand run a simulation on proprietary street network datafrom CityEngine without consent of the creator. While thiscould be done in theory, as there are no privacy settings orchecks on the imported DXF file, CityEngine is designed toprocedurally generate cities so the possibility of copyrightconcerns being raised is minute. Additionally, even if thiswere to occur while using the simulation system, the use ofproprietary data is not inherently connected to our system inany way. Therefore, this possibility is not an ethical concernfor the simulation.

Overall, the traffic system is more or less risk free for theuser. The system does not ask for any personal informationfrom a user, and does not record any data about the userssimulation. It also does not require nor retrieve informationfrom the users’ computer while the simulation is running.As there is no private data associated with the program, itis impossible to share or publish any information that couldharm the user. Additionally, the using the simulation doesnot require any network connection and is completely self-contained. The program is also incapable of manipulating

or running other software and runs independently of otherprograms, excepting the programming and display librariesit utilizes.

A final ethical discussion could be raised concerning thesimulation traffic corresponding to drivers or traffic patternsin the real world. Recording and using the driving styles ofreal people without their consent definitely poses an ethi-cal problem, because those people may not necessarily becomfortable with information about their driving habits be-ing used in a simulation. However, in the traffic system themovements of the vehicles in the simulation are not basedon any specific real world drivers or traffic movement. Thevehicles in the simulation determine their movements ran-domly. Because the system does not utilize real world data,it does not invade anyones privacy. The ultimate goal of thetraffic simulation is to create a more realistic environmentand background for existing crowd and other simulations.These systems are primarily designed for research and usein academia, and do not attempt to interact with users ona personal level. Once all of these points are considered to-gether, the simulation system can be seen as very ethicaland safe to run.

7. FUTURE WORKThe basic functionality of the system is in place, and all of

the fundamental components of the simulation are workingas intended. However, there are still many improvementsand additions that can be made. The highest priority taskfor continuing the project will be to integrate the 3D displayfrom Unity with the crowd simulation system and the fullscale 3D city environment. The crowd simulation systemthe vehicle simulation will most likely interact with is calledHeisenberg and is described by Badler et al. [3]. The systemthat Heisenberg was built on top of, called CAROSA, de-scribed in detail by Allbeck et al. [2], creates multiple smarthuman agents that have pre-defined actions that occur whenevents are broadcasted to the world. By combining the ve-hicle simulation system with the Heisenberg system, whichincorporates this agent structure, the vehicles will also beagents. Proper integration will therefore require convertingeach vehicle to be an agent. Additionally, vehicle interactionwith the pedestrian agents must be implemented to enableunique actions, such as getting in a car and utilizing it tocomplete locomotion objectives. The combined simulationsneed to handle clever traffic laws and integrate easily withlarge populations of people. Luckily, because both the Unitygame engine and the crowd simulation system already havein place abilities to properly handle agent interaction anddisplay, for example not drawing and using resources on anyagents that are not currently being displayed, this should besimple to extend to the vehicles to provide increased perfor-mance and efficiency.

Additional improvements will also be made to the sim-ulation codebase and associated displays as necessary. Inthe current 3D environment, the vehicles are representedby simple cubes and cylinders with a basic texture map.An obvious next step to give heightened realism is to pur-chase or create multiple 3D models of vehicles to use instead.In this way, multiple styles of vehicles could be present inthe simulation. This could also correspond with vehicles asagents, because then different classes of vehicles would havedistinct 3D models. Also, in its current state the simulationcode does not account for any highways or one way streets;

every road in the simulation is a simple two-way street be-cause highway data could not be retrieved from CityEngine.Generating random highways throughout the road networkwould not be realistic, and would also have a high perfor-mance cost, so the design decision was made to make everyroad uniform. If a possible method of acquiring additionaldata specific to highways or other types of roads is discov-ered in the future, adjustments can be made to include themin the system.

On a related note, all of the roads in the 2D and 3D en-vironment have a uniform width as set by a constant lanewidth parameter. The simulation code generates vehicle po-sitions based on the street vertices with a small offset toaccount for lane separation. However, in the 3D CityEngineenvironment almost all of the roads have differing widths.Therefore, it is possible that when the simulation codebaseis used to generate vehicles and their positions in the 3Dcity, the vehicles could be located offset from the center ofthe designated lane on the roads (ex: on sidewalks, or tooclose to the road median line), causing visual discrepanciesor collisions. If this problem occurs, work will need to bedone to account for these varying street widths.

8. CONCLUSIONUltimately, the goal of designing a realistic traffic sim-

ulation system has been achieved in compliance with theoriginal project proposal. The developed system is a fullyfunctional traffic simulation that runs in both 2D and 3Denvironments. The program is able to receive as input adata file from CityEngine, extract street information, andgenerate a full road network for use in the simulation. Thesystem constructs an internal data structure for both thestreet map and the vehicles which are directly connected tothose streets. The coordinates used in the traffic simulationare exactly the same as those in the CityEngine world space.Therefore, the simulation can be easily adapted to any crowdsimulation system that utilizes the same city model. Thevehicles move along the streets in realistic ways and obeybasic traffic laws. Every vehicles movement is determinedby an algorithm based on the equations of motion whichcalculates speed, acceleration and deceleration. The vehi-cles turn smoothly from the edge of one street to anotherby traveling along the arc of a calculated turning circle for aspecific angle amount. The implemented collision preventionalgorithms keep vehicles from running into each other byutilizing methods such as reserved space, edge flagging, andtraffic lights. One of the highly successful design decisionsfor the project was to keep the display layer and graphicscomponents separated from the simulation codebase. Thisseparation greatly facilitated importing the traffic simula-tion into different visual programs such as an OpenGL 2Ddisplay and a 3D display in the Unity game engine. Theresulting system is a realistic traffic simulation that can beeasily displayed and incorporated into any game engine orother simulation program.

9. REFERENCES[1] AutoCAD 2008. Dxf reference. http:

//images.autodesk.com/adsk/files/acad_dxf0.pdf,2007.

[2] Jan M. Allbeck, Norman I. Badler, and NuriaPelechano. Virtual Crowds: Methods, Simulation, and

Control, volume 8 of Synthesis Lectures on ComputerGraphics and Animation. Morgan and ClaypoolPublishers, 2008.

[3] Norman I. Badler and Ben Sunshine-Hill. Perceptuallyrealistic behavior through alibi generation. InConference on Artificial Intelligence and InteractiveDigital Entertainment (AIIDE), 2010.

[4] A.T. Chronopoulos and C.M. Johnston. A real-timetraffic simulation system. IEEE Transactions onVehicular Technology, 47(1):321–331, February 1998.

[5] James Cremer, Joseph Kearney, and Peter Willemsen.A directable vehicle behavior model for virtual drivingenvironments. In Conference on AI, Simulation andPlanning in High Autonomy Systems, 1996.

[6] Autodesk Inc. Ascii dxf files.http://www.autodesk.com/techpubs/autocad/

acad2000/dxf/ascii_dxf_files_dxf_aa.htm, 2010.

[7] Jan Krassnigg. Interactive pedestrian and trafficsimulation in a virtual city enviornment. Master’sthesis, University of Aachen, 2010.

[8] Jason Sewall, David Wilkie, Paul Merrell, andMing C. Lin. Continuum traffic simulation.EUROGRAPHICS, 2010.

[9] Visual Solutions. Vissim. http://www.vissim.com,2010.

[10] Jur van den Berg, Jason Sewall, Ming Lin, and DineshManocha. Virtualized traffic: Reconstructing trafficflows from discrete spatio-temporal data. IEEE, 2009.

[11] Xaitment. Xaittraffic.http://www.xaitment.com/english/blog/news/

xaitment-generated-traffic-gets-the-thumbs-up-39.

html, 2009.

[12] Fen Fei Yang and Joe Weinhoffer. Vehicle trafficsimulation. http://vehiclesimulator.blogspot.com,2010.