A web remaster of the original WPF traffic simulator: draw a city out of roads and junctions, fill it with traffic and watch it flow — now in the browser, with a new driving model, coordinated traffic lights, a living city around the roads, day and night, rain, and an interface in Russian and English. People commute between homes, offices and shops, buses run on lines you draw, ambulances race to accidents, pedestrians cross at zebras, and the simulator can point out bottlenecks, compare versions of your city, set you challenges on a budget and import real streets from OpenStreetMap.
Live demo: https://victornagibator.github.io/TrafficSimulationWeb/
Everything runs client-side: a TypeScript simulation engine, a Canvas 2D renderer and a small Preact interface. No server, no account; the city is saved in the browser and can be exported to a file.
| Area | What it does |
|---|---|
| Road network | Two-way and one-way roads, 1–5 lanes per direction, names, speed limits, road condition |
| Editing | Draw roads by clicking; crossing an existing road creates a junction automatically; chain roads; snap to junctions, roads, a 5 m grid or 15° angles; drag junctions to reshape the network while traffic keeps running; bulldozer; undo/redo |
| Driving | Intelligent Driver Model: smooth acceleration and braking, a personal safe gap and headway for every driver, slower in curves, in the rain and on worn roads |
| Lanes | Lane discipline (right turns from the right lane, left turns from the left lane), route-driven lane changes, overtaking slower traffic, pulling out around broken-down vehicles |
| Junctions | Smooth turning paths; conflict detection between paths; give way to the right; left turns give way to oncoming traffic; "don't block the box"; deadlock resolution; drivers re-route around jammed exits |
| Roundabouts | Any junction of three or more roads can become a single-lane roundabout: entering vehicles give way to the ring, judged by when circulating traffic will reach their entry point |
| Traffic lights | Junction-level signal plans: opposite approaches share a phase, green → yellow → all-red → next phase, per-phase green time, switch phase manually, left-turners clear at the end of the phase |
| Adaptive signals and green waves | Adaptive signals keep the green while vehicles keep arriving, end it early when the road empties, extend it for the longest queue and skip empty phases; fixed-time signals can be linked into green waves (common cycle, offsets propagated along the streets) |
| Trips | In the commuter model the city's land use follows its shape (offices in the centre, shops around them, homes on the outskirts); vehicles drive from one to another along the fastest route, which takes congestion into account, with morning and evening rush hours |
| Public transport | Bus stops placed beside roads, bus lines through them in order, buses that pull in to the kerb and dwell, bus lanes that other traffic only enters to turn right |
| Emergencies | An ambulance is sent to every accident; traffic ahead pulls over or changes lane, it crosses junctions on red and clears the accident when it arrives |
| Pedestrians | People cross at the zebras of every junction: in gaps in the traffic, with priority after waiting, and only against red at signals; vehicles wait for them |
| Incidents | Accidents (sometimes involving two cars) and breakdowns block a lane for a while, with hazard lights, warning triangles and debris |
| Environment | Rain periods (slower, longer headways, more accidents, wet look), day/night cycle with headlights, street lamps, lit windows and sun-angle shadows |
| Road wear | Every pass wears the road down; worn roads get cracks and potholes, slow traffic down, raise the accident rate, and are repaired by road works |
| City | Buildings, courtyards, parks and trees are generated in every block enclosed by roads |
| Overlays | Traffic density, road condition and land use maps, street names, speed-limit signs, lane arrows, one-way arrows, scale bar |
| Inspectors | Click a road, junction, vehicle, bus stop or line to inspect and edit it; follow a vehicle with the camera and see its route to its destination and why it is waiting |
| Statistics | Vehicles, average speed with a history chart, junction crossings per minute, trips and their duration, incidents, pedestrians |
| Bottlenecks | Smoothed queue statistics of every approach find the worst bottlenecks and suggest a fix (rebalance greens, adaptive signals, a roundabout or lights, another lane), which can be applied with one click |
| Compare | Remember the city as variant A, change it, then measure both with exactly the same traffic in a Web Worker; the results come side by side |
| Challenges | Three cities with a problem, a budget and a goal; your changes are priced, tested in a worker with the original traffic and earn up to three stars |
| Real streets | Import the streets around any place from OpenStreetMap (search by Nominatim, data from the Overpass API) |
| Sharing | A link that contains the whole city, compressed into the URL fragment; video recording and screenshots of the map |
| Persistence | Autosave in the browser, export/import to a .json file, four starting templates |
| Interface | Russian and English, keyboard shortcuts, touch support (pan and pinch zoom), responsive layout |
Requirements: Node.js 20+.
git clone https://github.com/VictorNagibator/TrafficSimulationWeb.git
cd TrafficSimulationWeb
npm install
npm run dev # development server with hot reload
npm test # unit and integration tests (Vitest)
npm run build # type check and production build into dist/
npm run preview # serve the production buildThe production build is a static site (dist/), so it can be hosted anywhere that serves files.
Every push to main is deployed to GitHub Pages by .github/workflows/pages.yml.
| Control | Action |
|---|---|
| City menu (top left) | Start from a template (grid town, ring city, village, empty map), save to / open from a file, clear the map |
| Play / speed | Pause or run at 0.5× – 8× |
Select tool (V) |
Click a road, junction, vehicle or bus stop to open it; drag a junction to move it; drag the map to pan |
Road tool (R) |
Click to start, click to place the end, keep clicking to chain roads; Shift snaps the angle; right click or Esc stops. Lane count, direction, speed limit and grid snapping are set in the tool panel |
Transit tool (B) |
Click beside a road to put a stop on that side; click stops in order and press Create line (or Enter) for a bus line |
Bulldozer (X) |
Click a road, junction, vehicle or stop to remove it |
| Vehicles | Add 10 vehicles (in the commuter model: make the rush hour busier), remove all, send tow trucks to clear incidents |
| Overlays | Traffic density (T), road condition (Q), land use (Z), street names (N) |
| Analysis | Bottlenecks, Compare variants and Challenges in the top bar |
| City menu extras | Copy a link to the city, import streets from OpenStreetMap |
| Recording | Record a video of the map (WebM, or MP4 where the browser prefers it) or save a screenshot |
| Settings | Traffic model and rush-hour size, ambulances, pedestrians, time of day and day length, weather, incident rates and durations, road wear and repairs, overtaking eagerness, default green time, green waves |
| Other keys | Space play/pause, Ctrl+Z / Ctrl+Y undo/redo, Del delete selection, F fit the city, +/− zoom, ? help |
src/
├── engine/ # the simulation: no DOM, runs in Node for tests
│ ├── math.ts # vectors, angles, segments, polylines (Y axis points down)
│ ├── random.ts # seeded RNG: a seed reproduces a run exactly
│ ├── constants.ts # physical constants
│ ├── settings.ts # city settings and their validation
│ ├── network.ts # what the user edits: junctions, roads, editing operations
│ ├── geometry.ts # derived: lanes, turning paths, conflicts, approaches, signal phases
│ ├── signals.ts # junction-level signal controller
│ ├── vehicle.ts # vehicle types and state
│ ├── simulation.ts # the step: weather, clock, signals, junction control, driving
│ ├── routing.ts # shortest-time routes over road directions, cached per destination
│ ├── demand.ts # land use and the daily profile of trips
│ ├── pedestrians.ts # people crossing at zebras
│ ├── greenwave.ts # common cycle and offsets for coordinated signals
│ ├── monitor.ts # smoothed queue statistics of every approach and road
│ ├── advisor.ts # bottleneck finder and its fixes
│ ├── benchmark.ts # headless runs for comparisons and challenges
│ ├── challenges.ts # challenge cities, prices and stars
│ ├── osm.ts # OpenStreetMap streets to a network
│ ├── share.ts # cities in links
│ ├── presets.ts # template cities
│ └── persistence.ts # save files
├── workers/
│ └── benchmark.worker.ts # runs benchmarks off the main thread
├── render/ # Canvas 2D drawing
│ ├── camera.ts # metres <-> pixels, zoom and pan
│ ├── scene.ts # cached road surfaces and markings (Path2D)
│ ├── decor.ts # city blocks, buildings and trees from the faces of the road graph
│ ├── sprites.ts # top-down vehicle artwork, cached per size
│ ├── effects.ts # light, tree and ground textures
│ ├── transit.ts # bus stop markers and line routes
│ └── renderer.ts # the frame: ground, roads, vehicles, people, lights, weather, overlays
└── ui/ # Preact interface
├── controller.ts # main loop, tools, undo history, autosave
├── i18n.ts # Russian and English strings
└── *.tsx # panels and controls
The engine keeps the split the original refactoring introduced: it knows nothing about pixels, the renderer only reads it, and the interface talks to it through the controller.
Network stores only what a person edits: junction positions and the roads between them with
their properties. Everything else is derived by buildGeometry whenever the network's
geometry revision changes:
- each road is trimmed back from its junctions far enough for the widest neighbour and a zebra crossing, and split into lanes (lane 0 is the rightmost lane, as in the original);
- every lane gets connectors: Bézier turning paths to the lanes it may continue on, following the lane discipline; a lane that would otherwise lead nowhere takes the turn on its side;
- every pair of connectors from different lanes that cross, come too close or merge into the same lane is marked as conflicting;
- approaches are grouped into signal phases by axis.
Editing while vehicles drive is safe: after a rebuild every vehicle is mapped back onto the new lanes by position, so splitting a road, adding lanes or moving a junction does not teleport anyone. The original paused the simulation while a road was being edited.
Because new roads automatically get a junction wherever they cross an existing one, the road graph is always planar. The renderer uses that to find the city blocks — the faces of the graph — and fills them with buildings, courtyards, parks and trees.
The simulation advances in fixed steps of 1/20 s:
- The world changes: clock, weather, road repairs and signal timers.
- Junctions hand out permissions: the vehicle at the front of each approach lane asks to enter. It may go when its light allows it, no conflicting path is occupied or already granted, there is room behind the junction, and it does not have to give way (to the right at an uncontrolled junction, to oncoming traffic when turning left). A vehicle that was already allowed keeps its permission; if everybody waits for everybody, the one that has waited longest goes.
- Every vehicle decides how to accelerate from the same snapshot of the world, using the Intelligent Driver Model against whatever is ahead — another vehicle, a stop line, or the speed of the coming turn — and considers lane changes.
- Every vehicle moves. The distance covered is capped by the gap ahead, so vehicles never overlap, whatever the model says.
Lengths are metres, durations seconds, speed limits km/h (converted to m/s by the dynamics). Incident and rain rates are percentages per minute, so they do not depend on the step length.
| Original behaviour | Now |
|---|---|
| Accident and breakdown chances were per 0.1 s tick (0.3 % + 0.3 %), so every car was disabled every ~17 seconds; rain (1 % per tick) almost never stopped | Rates are per minute, with sensible defaults |
Splitting a road reset the pieces' speed limit and quality to the city defaults (City.AddRoad overwrote them) |
Pieces keep every property of the original road |
| Deleting a road left its traffic lights running in the controller | Signals belong to junctions and follow the network |
| Lights of one junction were independent and could show conflicting greens | One plan per junction, one green phase at a time, with yellow and all-red clearance |
| Four cars arriving at once at an uncontrolled junction waited for each other forever | Deadlock detection lets the longest-waiting driver go; permissions are sticky |
| Vehicles stopped instantly (speed set to 0), teleported across junctions and between lanes | Physical acceleration and braking, smooth turning paths, animated lane changes |
| New cars could appear on top of existing ones | Spawning checks the gap on the lane |
| Roads only ever wore down | Worn roads are repaired by road works (optional) |
| Junctions left without roads stayed in the index | They are removed; a junction that only joins two halves of a straight road is merged back |
| A new road could not cross an existing one | The crossing becomes a junction |
| No save/load, Windows-only | Autosave, file export/import, runs in any modern browser |
- Roads are straight segments; curves are made of several roads, and roundabouts have one circulating lane.
- In the random drivers model vehicles have no destination: at each junction they pick a movement, preferring straight on and avoiding congested exits. The commuter trips model gives them destinations.
- Pedestrians only appear around junctions; they do not walk the whole length of the pavements.
- The visible simulation runs on the main thread; Web Workers are used for the headless runs of comparisons and challenges.
- OpenStreetMap areas are simplified: junction nodes closer than 10 m are merged, bends closer than 17 m are straightened, and pieces the editor rejects (often one carriageway of a dual carriageway) are skipped.
Every direction of every road is a node of the routing graph, and movements through junctions are its edges. A route is found backwards from the destination with Dijkstra; the tree is cached per destination and refreshed every 20 simulated seconds, so drivers react to congestion without each of them searching at every junction. Travel time on a road grows steeply with its occupancy; junctions add a few seconds for signals, give-way rules and left turns.
The land use of each road is derived from the shape of the city: offices near its centre, shops in a ring around them and homes towards the outskirts, with noise so every district is mixed. Trips go from homes to work in the morning, back in the evening and to the shops during the day, and the number of vehicles on the road follows the clock.
npm testThe engine tests run in Node and cover geometry helpers, network editing (automatic junctions, splitting, merging, validation, persistence), lane and turn generation, path conflicts, signal phases, and driving behaviour: acceleration limits, car following without contact, overtaking broken-down vehicles, stopping at red lights, giving way to the right, resolving the four-way standoff, not blocking junctions, U-turns at dead ends, incident rates, road wear and repairs, editing under traffic, determinism, and three-minute runs of every template city with invariant checks (no overlaps, no NaN, traffic keeps flowing).
The newer features have their own tests: routing and trips, bus lines, stops and bus lanes, ambulances and making way, roundabouts (no two vehicles ever overlap on the ring), adaptive signals and green waves, pedestrians (no vehicle enters a zebra someone is crossing), links, the bottleneck advisor, benchmarks, challenge prices and stars, and OpenStreetMap import.