Back to Drift City
SOURCE / PINNED RELEASE

Made of little things.

Drift City

Release
098731aa0f0f…
Author-recorded commit
2822ea0a4f5b…
License
LICENSE
Author’s source reference
nostr://npub12lm3rxsva8kfempyjkxupt09e02n3fezurkyadyqfejdc5e0r2kscqty6r/wss%3A%2F%2Fgit.napplet.soy%2F/n-a4c0039c855

Archive hash verified: b3323e408235502b…. The source-to-build association is the author’s claim; it has not been independently rebuilt.

src/game/traffic.ts
import * as THREE from 'three';
import type { Car } from './car.js';
import { ContactShadows } from './contact.js';
import type { Debris } from './debris.js';
import { RIGS, RIG_HITCH, TRAFFIC_COLORS, VEHICLES, brakeOn, buildVehicle, charMerged, disposeVehicle, partsFor, randomType, unmerge, type VehicleModel, type VehicleType } from './vehicles.js';
import type { RoadKind, World } from './world.js';

/**
 * Traffic: cars, pickups, box trucks and big rigs driving the roads of either map.
 *
 * The roads become a graph: city intersections and the points where roads meet are nodes,
 * the stretches between them edges. Each vehicle keeps to the right-hand lane of its edge
 * by steering at a point a little way ahead in the lane, chooses a new edge at each node
 * (mostly straight on; rigs keep to the open country roads), slows for bends and turns,
 * keeps its distance from whatever is ahead (the player included), goes round anything
 * stopped in its lane, and shows brake lights.
 *
 * Hit one and it breaks loose: momentum is shared by mass, so a sedan gets shoved and
 * spun while a loaded rig barely notices. Panels tear off where it was hit, and a hard
 * enough hit wrecks it (charred, smoking, staying put). Loose cars can hit others. A car
 * that's only been knocked about finds its road again; wrecks are replaced, out of sight.
 */

/** The player's car, for sharing momentum (kg). */
const PLAYER_MASS = 1200;
const RESTITUTION = 0.25;
/** Where a car's centre stops for a red light, short of the crossing's centre (m). */
const SIGNAL_LINE = 15.6;

export interface Edge {
  pts: { x: number; y: number; z: number }[];
  cum: number[];
  len: number;
  a: number;
  b: number;
  /** Two lanes each way (city streets and the highway) rather than one. */
  city: boolean;
  kind: RoadKind;
  /** Traffic may only go the way the points run (1), only the other way (-1), or both (0). */
  oneway: 1 | -1 | 0;
  speed: number;
  /** One end leads nowhere. */
  dead: boolean;
  /** Part of the open-road network a rig can drive round without ending up in town. */
  rigOk: boolean;
}

export interface Node {
  x: number;
  y: number;
  z: number;
  edges: number[];
  /** Run by traffic lights (rather than first come, first through). */
  signal: boolean;
  /** Who has right of way through this junction just now. */
  holder: Vehicle | null;
  /** A merge on the highway: nobody waits at it. */
  free: boolean;
}

/** A place on the road: an edge, which way along it, and how far along that way. */
export interface Cursor {
  edge: number;
  dir: 1 | -1;
  s: number;
}

export interface TrafficHit {
  /** How hard (closing speed, m/s). */
  power: number;
  wrecked: boolean;
  x: number;
  y: number;
  z: number;
  /** The player hit it (rather than two traffic cars meeting, or a rival). */
  player: boolean;
  /** The physics car in it (the player's or a rival's), if one was. */
  car: Car | null;
}

interface Vehicle {
  model: VehicleModel;
  type: VehicleType;
  len: number;
  wid: number;
  mass: number;
  rig: boolean;
  x: number;
  y: number;
  z: number;
  yaw: number;
  speed: number;
  /** The driver's own pace, as a share of the limit. */
  pace: number;
  cur: Cursor;
  next: { edge: number; dir: 1 | -1 } | null;
  /** Parked cars sit still (in their bay, or wherever they were knocked to) until hit. */
  state: 'drive' | 'loose' | 'wreck' | 'parked';
  /** The parking bay a parked car belongs in. */
  home: { x: number; z: number; yaw: number } | null;
  vx: number;
  vz: number;
  yawRate: number;
  /** Seconds in its present state. */
  t: number;
  /** Seconds held up behind something. */
  stuck: number;
  /** Seconds left going round an obstacle in the other lane. */
  passing: number;
  trailerYaw: number;
  braking: boolean;
  lost: number;
  pitch: number;
  smoke: number;
  /** The junction it has claimed (-1 none). */
  holds: number;
  /** Seconds stopped; seconds left ignoring others to break a deadlock. */
  waiting: number;
  ghost: number;
  /** The corner it will take from this edge onto the next... */
  turn: Turn | null;
  /** ...the one it's finishing on this edge... */
  exiting: Turn | null;
  /** ...and which pair of edges `turn` was worked out for (-1: none yet). */
  turnKey: number;
  /** Stopped for a red light (which isn't a standoff to break). */
  atLight: boolean;
  /** The edge it has pulled up at the line on to turn left (it may go once the way is clear). */
  committed: number;
  /** Its lane in town (0 the outer, 1 the inner), and how far right of the middle it is just now. */
  laneIdx: number;
  laneOff: number;
}

/**
 * A corner cut through a junction: rather than following each lane to the node and then
 * back out (which on a right turn means doubling back), the route leaves the incoming lane
 * at A, curves through C where the two lanes' lines cross, and joins the outgoing lane at
 * B. In route terms it spans from sA on the incoming edge to sB on the outgoing one (D
 * metres of cursor), though the curve itself is shorter or longer: ratio converts.
 */
interface Turn {
  outEdge: number;
  outDir: 1 | -1;
  sA: number;
  sB: number;
  D: number;
  ratio: number;
  /** +1 a right turn, -1 a left. */
  side: number;
  /** The lane it comes out in: the outer one turning right, the inner one turning left. */
  outLane: number;
  ax: number;
  az: number;
  cx: number;
  cz: number;
  bx: number;
  bz: number;
}

const wrap = (a: number) => Math.atan2(Math.sin(a), Math.cos(a));
/** The speed to be doing to pull up comfortably (at 4 m/s²) in the room left. */
const stopFor = (room: number) => Math.sqrt(8 * Math.max(0, room - 0.3));
/** How far right of the middle a lane runs: city streets have an outer (0) and an inner (1) lane each way, country roads one. */
const laneAt = (city: boolean, idx: number) => (city ? (idx ? 1.8 : 5.4) : 2.75);
/**
 * How far right of an edge's middle a lane runs. One-way roads keep both their lanes (or
 * their one) to themselves: two lanes either side of the middle, one lane down it.
 */
const laneOf = (e: Edge, idx: number) => (e.oneway ? (e.city ? (idx ? -1.8 : 1.8) : 0) : laneAt(e.city, idx));
/** The speed limit on each sort of road (m/s). */
const SPEED: Record<RoadKind, number> = { street: 13.9, lane: 11, country: 22, highway: 27, ramp: 16 };
/** Further apart up and down than this, two things are on different levels (the highway and the street under it). */
const LEVEL = 3;

export class RoadGraph {
  readonly nodes: Node[] = [];
  readonly edges: Edge[] = [];

  constructor(world: World) {
    const roads = world.roadNet();
    // Where roads meet: ends within 9 m of each other at the same height (a junction under
    // the highway is not one on it).
    const node = (x: number, y: number, z: number): number => {
      for (let i = 0; i < this.nodes.length; i++) {
        const n = this.nodes[i]!;
        if (Math.abs(n.y - y) < 2.5 && Math.hypot(n.x - x, n.z - z) < 9) return i;
      }
      this.nodes.push({ x, y, z, edges: [], holder: null, signal: false, free: false });
      return this.nodes.length - 1;
    };
    const addEdge = (pts: { x: number; y: number; z: number }[], kind: RoadKind, speed: number, oneway: 1 | -1 | 0) => {
      if (pts.length < 2) return;
      const cum = [0];
      for (let i = 1; i < pts.length; i++) cum.push(cum[i - 1]! + Math.hypot(pts[i]!.x - pts[i - 1]!.x, pts[i]!.z - pts[i - 1]!.z));
      const len = cum[cum.length - 1]!;
      if (len < 4) return;
      const a = node(pts[0]!.x, pts[0]!.y, pts[0]!.z);
      const b = node(pts[pts.length - 1]!.x, pts[pts.length - 1]!.y, pts[pts.length - 1]!.z);
      const e = this.edges.length;
      const city = kind === 'street' || kind === 'highway';
      this.edges.push({ pts, cum, len, a, b, city, kind, oneway, speed, dead: false, rigOk: false });
      this.nodes[a]!.edges.push(e);
      if (b !== a) this.nodes[b]!.edges.push(e);
    };
    // Roads are split where another road's end meets them (at the same height).
    const boxes = roads.map((r) => {
      let x0 = Infinity;
      let x1 = -Infinity;
      let z0 = Infinity;
      let z1 = -Infinity;
      for (const p of r.pts) {
        x0 = Math.min(x0, p.x);
        x1 = Math.max(x1, p.x);
        z0 = Math.min(z0, p.z);
        z1 = Math.max(z1, p.z);
      }
      return { x0: x0 - 6, x1: x1 + 6, z0: z0 - 6, z1: z1 + 6 };
    });
    const splits = roads.map(() => new Set<number>());
    roads.forEach((r, ri) => {
      if (r.closed) return;
      for (const p of [r.pts[0]!, r.pts[r.pts.length - 1]!])
        roads.forEach((o, oi) => {
          const bb = boxes[oi]!;
          if (oi === ri || p.x < bb.x0 || p.x > bb.x1 || p.z < bb.z0 || p.z > bb.z1) return;
          let best = -1;
          let bd = 6;
          o.pts.forEach((q, qi) => {
            if (Math.abs(q.y - p.y) > 2) return;
            const d = Math.hypot(q.x - p.x, q.z - p.z);
            if (d < bd) {
              bd = d;
              best = qi;
            }
          });
          if (best > 0 && best < o.pts.length - 1) splits[oi]!.add(best);
        });
    });
    roads.forEach((r, ri) => {
      const pts = r.pts.map((p) => ({ x: p.x, y: p.y, z: p.z }));
      // Speed by the sort of road: the airfield spur is slow.
      const spur = r.kind === 'country' && !r.closed && pts.some((p) => Math.hypot(p.x - 430, p.z + 640) < 20);
      const speed = spur ? 8.3 : SPEED[r.kind];
      const cuts = [...splits[ri]!].sort((a, b) => a - b);
      if (r.closed) {
        if (cuts.length < 2) cuts.push(0, Math.floor(pts.length / 2));
        cuts.sort((a, b) => a - b);
        for (let k = 0; k < cuts.length; k++) {
          const a = cuts[k]!;
          const b = cuts[(k + 1) % cuts.length]!;
          const piece = b > a ? pts.slice(a, b + 1) : [...pts.slice(a, pts.length - 1), ...pts.slice(0, b + 1)];
          addEdge(piece, r.kind, speed, 0);
        }
      } else {
        const marks = [0, ...cuts, pts.length - 1];
        for (let k = 0; k + 1 < marks.length; k++) addEdge(pts.slice(marks[k]!, marks[k + 1]! + 1), r.kind, speed, r.oneway ?? 0);
      }
    });
    for (const e of this.edges) e.dead = this.nodes[e.a]!.edges.length < 2 || this.nodes[e.b]!.edges.length < 2;
    // On the highway, junctions are merges: nobody stops at them.
    for (const n of this.nodes) n.free = n.edges.every((e) => this.edges[e]!.kind === 'highway' || this.edges[e]!.kind === 'ramp');
    // Rigs: country roads only, pruning any that lead only into town or a dead end.
    for (const e of this.edges) e.rigOk = e.kind === 'country' && !e.dead;
    for (let changed = true; changed; ) {
      changed = false;
      for (const e of this.edges) {
        if (!e.rigOk) continue;
        for (const n of [e.a, e.b]) {
          const onward = this.nodes[n]!.edges.some((o) => o !== this.edges.indexOf(e) && this.edges[o]!.rigOk);
          if (!onward && e.a !== e.b) {
            e.rigOk = false;
            changed = true;
            break;
          }
        }
      }
    }
  }

  /** The lane centre (and its height) and travel direction at a cursor, offset to the right. */
  at(c: Cursor, lane: number, out: { x: number; z: number; tx: number; tz: number; y?: number }): void {
    const e = this.edges[c.edge]!;
    const d = Math.max(0, Math.min(e.len, c.dir > 0 ? c.s : e.len - c.s));
    let i = 1;
    while (i < e.cum.length - 1 && e.cum[i]! < d) i++;
    const a = e.pts[i - 1]!;
    const b = e.pts[i]!;
    const f = (d - e.cum[i - 1]!) / (e.cum[i]! - e.cum[i - 1]! || 1);
    let tx = (b.x - a.x) * c.dir;
    let tz = (b.z - a.z) * c.dir;
    const l = Math.hypot(tx, tz) || 1;
    tx /= l;
    tz /= l;
    // The driver's right is (-tz, tx).
    out.x = a.x + (b.x - a.x) * f - tz * lane;
    out.z = a.z + (b.z - a.z) * f + tx * lane;
    out.y = a.y + (b.y - a.y) * f;
    out.tx = tx;
    out.tz = tz;
  }
  /** How far along a cursor's edge (its way) (x, z) is, searching near where it's thought to be. */
  project(c: Cursor, x: number, z: number): number {
    const e = this.edges[c.edge]!;
    const d0 = c.dir > 0 ? c.s : e.len - c.s;
    let best = d0;
    let bd = Infinity;
    for (let i = 0; i + 1 < e.pts.length; i++) {
      if (e.cum[i + 1]! < d0 - 12 || e.cum[i]! > d0 + 12) continue;
      const a = e.pts[i]!;
      const b = e.pts[i + 1]!;
      const vx = b.x - a.x;
      const vz = b.z - a.z;
      const l2 = vx * vx + vz * vz || 1;
      const t = Math.max(0, Math.min(1, ((x - a.x) * vx + (z - a.z) * vz) / l2));
      const d = Math.hypot(x - (a.x + vx * t), z - (a.z + vz * t));
      if (d < bd) {
        bd = d;
        best = e.cum[i]! + Math.sqrt(l2) * t;
      }
    }
    return c.dir > 0 ? best : e.len - best;
  }

  /**
   * The nearest place on any edge to (x, z), going the way that best matches yaw. Given a
   * height, a road on another level counts as much further off; without one, the ground.
   */
  nearest(x: number, z: number, yaw: number, y?: number): { cursor: Cursor; d: number } {
    let best = { cursor: { edge: 0, dir: 1 as 1 | -1, s: 0 }, d: Infinity };
    this.edges.forEach((e, ei) => {
      for (let i = 0; i + 1 < e.pts.length; i++) {
        const a = e.pts[i]!;
        const b = e.pts[i + 1]!;
        const vx = b.x - a.x;
        const vz = b.z - a.z;
        const l2 = vx * vx + vz * vz || 1;
        const t = Math.max(0, Math.min(1, ((x - a.x) * vx + (z - a.z) * vz) / l2));
        const py = a.y + (b.y - a.y) * t;
        const d = Math.hypot(x - (a.x + vx * t), z - (a.z + vz * t)) + Math.max(0, Math.abs(py - (y ?? 0)) - 1.5) * 4;
        if (d < best.d) {
          const along = e.cum[i]! + Math.sqrt(l2) * t;
          const fwd = e.oneway ? e.oneway > 0 : Math.cos(wrap(Math.atan2(vx, vz) - yaw)) >= 0;
          best = { cursor: { edge: ei, dir: fwd ? 1 : -1, s: fwd ? along : e.len - along }, d };
        }
      }
    });
    return best;
  }
}

const _p = { x: 0, z: 0, tx: 0, tz: 0, y: 0 };
const _q = { x: 0, z: 0, tx: 0, tz: 0, y: 0 };
const _v = new THREE.Vector3();

export class Traffic {
  readonly root = new THREE.Group();
  private readonly graph: RoadGraph;
  /** Other cars driven by physics (race rivals): traffic keeps its distance from them and they collide like the player's. */
  private others: Car[] = [];
  private readonly vehicles: Vehicle[] = [];
  private seed = 7;
  /** Roads closed to traffic (for a race). */
  private blocked = new Set<number>();
  /** The soft shadows right under each vehicle. */
  private readonly contacts: ContactShadows;

  constructor(
    private readonly world: World,
    count: number,
    player: { x: number; z: number },
  ) {
    this.graph = new RoadGraph(world);
    for (const n of this.graph.nodes) n.signal = n.edges.length >= 3 && n.y < 1 && !!world.signals?.at(n.x, n.z);
    for (let i = 0; i < count; i++) this.spawn(i, player, 60);
    // About half the bays in the parking lots have a car in them.
    for (const bay of world.parking) if (this.rand() < 0.5) this.park(this.vehicles.length, bay);
    this.contacts = new ContactShadows(this.vehicles.length * 2);
    this.root.add(this.contacts.mesh);
  }

  /** A car parked in a bay (new, or one replacing a wreck). */
  private park(i: number, bay: { x: number; z: number; yaw: number }, reuse?: Vehicle, as?: { type: VehicleType; color: number }): Vehicle {
    // Cars and pickups: a box truck or a rig won't fit in a bay.
    let type: VehicleType;
    if (as) type = as.type;
    else {
      do type = randomType(() => this.rand(), false);
      while (type === 'box');
    }
    const spec = VEHICLES[type];
    if (reuse) {
      reuse.model.root.removeFromParent();
      disposeVehicle(reuse.model);
    }
    const model = buildVehicle(type, as ? as.color : TRAFFIC_COLORS[Math.floor(this.rand() * TRAFFIC_COLORS.length)]!, i);
    this.root.add(model.root);
    const v: Vehicle = {
      model,
      type,
      len: spec.len,
      wid: spec.wid,
      mass: spec.mass,
      rig: false,
      x: bay.x,
      y: this.world.height(bay.x, bay.z),
      z: bay.z,
      yaw: bay.yaw,
      speed: 0,
      pace: 1,
      cur: this.graph.nearest(bay.x, bay.z, bay.yaw).cursor,
      next: null,
      state: 'parked',
      vx: 0,
      vz: 0,
      yawRate: 0,
      t: 0,
      stuck: 0,
      passing: 0,
      trailerYaw: bay.yaw,
      braking: false,
      lost: 0,
      pitch: 0,
      smoke: 0,
      holds: -1,
      waiting: 0,
      ghost: 0,
      turn: null,
      exiting: null,
      turnKey: -1,
      atLight: false,
      committed: -1,
      laneIdx: 0,
      laneOff: laneAt(true, 0),
      home: bay,
    };
    if (reuse) Object.assign(reuse, v);
    else this.vehicles.push(v);
    return reuse ?? v;
  }

  /** The road network (for planning race routes on). */
  get roads(): RoadGraph {
    return this.graph;
  }

  // ---------------------------------------------------------------------------
  // Racing

  /**
   * Close roads off (a race's wrong turns, barriered): no traffic goes down them, and
   * any on them now is sent elsewhere.
   */
  setBlocked(edges: number[], player: { x: number; z: number }): void {
    this.blocked = new Set(edges);
    this.vehicles.forEach((v, i) => {
      if (v.state === 'drive' && this.blocked.has(v.cur.edge)) this.spawn(i, player, 120, v);
      else if (v.state === 'drive' && v.next && this.blocked.has(v.next.edge)) {
        v.next = null;
        v.turn = null;
        v.turnKey = -1;
      }
    });
  }

  /** Every vehicle within r of (x, z): where it is, how it's moving, how big it is (for rival drivers to see). */
  nearby(x: number, z: number, r: number, y = 0): { x: number; z: number; vx: number; vz: number; len: number; wid: number }[] {
    const out: { x: number; z: number; vx: number; vz: number; len: number; wid: number }[] = [];
    for (const v of this.vehicles) {
      if (Math.abs(v.x - x) > r || Math.abs(v.z - z) > r || Math.abs(v.y - y) > LEVEL) continue;
      const [vx, vz] = this.velocityOf(v);
      out.push({ x: v.x, z: v.z, vx, vz, len: v.len, wid: v.wid });
    }
    return out;
  }

  /** Send any traffic near (x, z) elsewhere (off a starting grid, say). */
  clearAround(x: number, z: number, r: number): void {
    this.vehicles.forEach((v, i) => {
      if (v.state === 'parked' || Math.hypot(v.x - x, v.z - z) > r) return;
      this.spawn(i, { x, z }, r + 60, v);
    });
  }

  private rand(): number {
    this.seed = (this.seed * 1664525 + 1013904223) >>> 0;
    return this.seed / 4294967296;
  }

  private lane(v: Vehicle): number {
    return v.laneOff;
  }

  /** Where the driver means to be: its lane in town; out of town, its side (or the other, going round something). */
  private laneTarget(v: Vehicle): number {
    const e = this.graph.edges[v.cur.edge]!;
    if (e.city || e.oneway) return laneOf(e, v.laneIdx);
    return v.passing > 0 ? -laneAt(false, 0) : laneAt(false, 0);
  }

  /** Is the lane idx free alongside and a little ahead (to move into it)? */
  private sideClear(v: Vehicle, idx: number, car: Car): boolean {
    const shift = laneOf(this.graph.edges[v.cur.edge]!, idx) - v.laneOff;
    const hx = Math.sin(v.yaw);
    const hz = Math.cos(v.yaw);
    const near = (x: number, z: number, yaw: number, len: number) => {
      const rx = x - v.x;
      const rz = z - v.z;
      if (Math.abs(rx) > 40 || Math.abs(rz) > 40 || Math.sin(yaw) * hx + Math.cos(yaw) * hz < 0.3) return false;
      const along = rx * hx + rz * hz;
      const right = -rx * hz + rz * hx;
      const reach = (v.len + len) / 2;
      return Math.abs(right - shift) < 2.4 && along > -reach - 4 && along < reach + 6 + v.speed;
    };
    for (const o of this.vehicles) if (o !== v && o.state === 'drive' && Math.abs(o.y - v.y) < LEVEL && near(o.x, o.z, o.yaw, o.len)) return false;
    const level = (c: Car) => Math.abs(c.pos.y - v.y) < LEVEL;
    return !(level(car) && near(car.pos.x, car.pos.z, car.yaw, 4.4)) && !this.others.some((c) => level(c) && near(c.pos.x, c.pos.z, c.yaw, 4.4));
  }

  /** Put a vehicle (new, or one being replaced) somewhere on the roads, away from the player. */
  private spawn(i: number, player: { x: number; z: number }, minDist: number, reuse?: Vehicle): void {
    // A parked car's wreck is replaced by a fresh one back in its bay.
    if (reuse?.home) {
      this.park(i, reuse.home, reuse);
      return;
    }
    const g = this.graph;
    const rigsOk = !reuse || reuse.rig;
    const anyRigRoad = g.edges.some((e) => e.rigOk);
    const type: VehicleType = reuse ? reuse.type : randomType(() => this.rand(), anyRigRoad);
    const rig = RIGS.has(type);
    const total = g.edges.reduce((s, e, i) => s + ((rig && !e.rigOk) || this.blocked.has(i) ? 0 : e.len), 0);
    let cursor: Cursor = { edge: 0, dir: 1, s: 0 };
    const laneIdx = this.rand() < 0.5 ? 0 : 1;
    for (let tries = 0; tries < 60; tries++) {
      let pick = this.rand() * total;
      let ei = 0;
      for (; ei < g.edges.length; ei++) {
        const e = g.edges[ei]!;
        const w = (rig && !e.rigOk) || this.blocked.has(ei) ? 0 : e.len;
        if (pick < w) break;
        pick -= w;
      }
      ei = Math.min(ei, g.edges.length - 1);
      const e = g.edges[ei]!;
      // Not right at a junction: a car dropped in mid-corner at speed would run wide.
      const margin = Math.min(35, e.len * 0.35);
      const way: 1 | -1 = this.rand() < 0.5 ? 1 : -1;
      cursor = { edge: ei, dir: e.oneway || way, s: margin + this.rand() * (e.len - 2 * margin) };
      g.at(cursor, laneOf(e, laneIdx), _p);
      const far = Math.hypot(_p.x - player.x, _p.z - player.z) > minDist;
      const clear = this.vehicles.every((o) => o === reuse || Math.abs(o.y - _p.y) > LEVEL || Math.hypot(o.x - _p.x, o.z - _p.z) > 14 + (rig || o.rig ? 12 : 0));
      if (far && clear) break;
    }
    void rigsOk;
    const e = g.edges[cursor.edge]!;
    g.at(cursor, laneOf(e, laneIdx), _p);
    const spec = VEHICLES[type];
    if (reuse) {
      reuse.model.root.removeFromParent();
      disposeVehicle(reuse.model);
    }
    const model = buildVehicle(type, TRAFFIC_COLORS[Math.floor(this.rand() * TRAFFIC_COLORS.length)]!, i);
    this.root.add(model.root);
    const yaw = Math.atan2(_p.tx, _p.tz);
    const v: Vehicle = {
      model,
      type,
      len: spec.len,
      wid: spec.wid,
      mass: spec.mass,
      rig,
      x: _p.x,
      y: this.world.height(_p.x, _p.z, (_p.y ?? 0) + 0.5),
      z: _p.z,
      yaw,
      speed: e.speed * 0.6,
      pace: rig ? 0.82 + this.rand() * 0.1 : 0.85 + this.rand() * 0.22,
      cur: cursor,
      next: null,
      state: 'drive',
      vx: 0,
      vz: 0,
      yawRate: 0,
      t: 0,
      stuck: 0,
      passing: 0,
      trailerYaw: yaw,
      braking: false,
      lost: 0,
      pitch: 0,
      smoke: 0,
      holds: -1,
      waiting: 0,
      ghost: 0,
      turn: null,
      exiting: null,
      turnKey: -1,
      atLight: false,
      committed: -1,
      laneIdx,
      laneOff: laneOf(e, laneIdx),
      home: null,
    };
    if (reuse) {
      this.release(reuse);
      Object.assign(reuse, v);
    }
    else this.vehicles.push(v);
  }

  /** The next edge after the node a vehicle is heading for. */
  private chooseNext(v: Vehicle): { edge: number; dir: 1 | -1 } {
    const g = this.graph;
    const e = g.edges[v.cur.edge]!;
    const n = v.cur.dir > 0 ? e.b : e.a;
    const node = g.nodes[n]!;
    // Heading at the end of this edge.
    g.at({ ...v.cur, s: e.len - 0.5 }, 0, _p);
    const options: { edge: number; dir: 1 | -1; w: number }[] = [];
    // Rigs keep to the open road where they can, but go on through town rather than turn
    // round in a junction.
    for (const strict of v.rig ? [true, false] : [false]) {
      for (const ei of node.edges) {
        if (ei === v.cur.edge && node.edges.length > 1) continue;
        const o = g.edges[ei]!;
        if (v.rig && (o.dead || (strict && !o.rigOk)) && node.edges.length > 1) continue;
        // Closed off for a race.
        if (this.blocked.has(ei)) continue;
        const dir: 1 | -1 = o.a === n ? 1 : -1;
        // Not the wrong way down a one-way road.
        if (o.oneway && o.oneway !== dir) continue;
        g.at({ edge: ei, dir, s: 1 }, 0, _q);
        const straight = _p.tx * _q.tx + _p.tz * _q.tz;
        options.push({ edge: ei, dir, w: 0.4 + Math.max(0, straight) * 3, straight } as { edge: number; dir: 1 | -1; w: number });
      }
      if (options.length) break;
    }
    // Not doubling back (off a ramp the wrong way onto the highway, say) where it can go on.
    const ahead = options.filter((o) => (o as { straight?: number }).straight! > -0.5);
    if (ahead.length && ahead.length < options.length) options.splice(0, options.length, ...ahead);
    if (!options.length) return { edge: v.cur.edge, dir: v.cur.dir > 0 ? -1 : 1 };
    const total = options.reduce((s, o) => s + o.w, 0);
    let pick = this.rand() * total;
    for (const o of options) {
      pick -= o.w;
      if (pick <= 0) return o;
    }
    return options[0]!;
  }

  /** The corner from the vehicle's edge onto its chosen next edge, or null if it's (nearly) straight on. */
  private makeTurn(v: Vehicle): Turn | null {
    const g = this.graph;
    const e = g.edges[v.cur.edge]!;
    const n = v.next!;
    const ne = g.edges[n.edge]!;
    // Which way it turns, then the lanes: from its own lane into the outer lane turning
    // right, or the inner lane turning left.
    g.at({ ...v.cur, s: e.len }, 0, _p);
    g.at({ edge: n.edge, dir: n.dir, s: 0 }, 0, _q);
    let cross = _p.tx * _q.tz - _p.tz * _q.tx;
    if (Math.abs(cross) < 0.3) return null;
    g.at({ ...v.cur, s: e.len }, laneOf(e, v.laneIdx), _p);
    g.at({ edge: n.edge, dir: n.dir, s: 0 }, laneOf(ne, cross > 0 ? 0 : 1), _q);
    cross = _p.tx * _q.tz - _p.tz * _q.tx;
    // Where the two lane lines cross: P1 + t T1 = P2 + s T2.
    const dx = _q.x - _p.x;
    const dz = _q.z - _p.z;
    const t = (dx * _q.tz - dz * _q.tx) / cross;
    const s = (dx * _p.tz - dz * _p.tx) / cross;
    if (Math.abs(t) > 25 || Math.abs(s) > 25) return null;
    const r = Math.min(e.city ? 6.5 : 9, e.len + t - 2, ne.len - s - 2);
    if (r < 2) return null;
    const cx = _p.x + _p.tx * t;
    const cz = _p.z + _p.tz * t;
    const tr: Turn = {
      outEdge: n.edge,
      outDir: n.dir,
      sA: e.len + t - r,
      sB: s + r,
      D: 0,
      ratio: 1,
      side: cross > 0 ? 1 : -1,
      outLane: cross > 0 ? 0 : 1,
      ax: cx - _p.tx * r,
      az: cz - _p.tz * r,
      cx,
      cz,
      bx: cx + _q.tx * r,
      bz: cz + _q.tz * r,
    };
    tr.D = e.len - tr.sA + tr.sB;
    let len = 0;
    let px = tr.ax;
    let pz = tr.az;
    for (let k = 1; k <= 8; k++) {
      this.onTurn(tr, k / 8, _q);
      len += Math.hypot(_q.x - px, _q.z - pz);
      px = _q.x;
      pz = _q.z;
    }
    tr.ratio = tr.D / Math.max(1, len);
    return tr;
  }

  /** A point (and heading) a share f of the way round a corner. */
  private onTurn(tr: Turn, f: number, out: typeof _p): void {
    const a = (1 - f) * (1 - f);
    const b = 2 * (1 - f) * f;
    const c = f * f;
    out.x = a * tr.ax + b * tr.cx + c * tr.bx;
    out.z = a * tr.az + b * tr.cz + c * tr.bz;
    const tx = (1 - f) * (tr.cx - tr.ax) + f * (tr.bx - tr.cx);
    const tz = (1 - f) * (tr.cz - tr.az) + f * (tr.bz - tr.cz);
    const l = Math.hypot(tx, tz) || 1;
    out.tx = tx / l;
    out.tz = tz / l;
  }

  /** Decide the next edge once it's in sight, and work out the corner onto it. */
  private plan(v: Vehicle): Turn | null {
    const e = this.graph.edges[v.cur.edge]!;
    if (!v.next && e.len - v.cur.s > 45) return null;
    v.next ??= this.chooseNext(v);
    const key = (((v.cur.edge * 2 + (v.cur.dir > 0 ? 1 : 0)) * 8192 + v.next.edge) * 2 + (v.next.dir > 0 ? 1 : 0)) * 2 + v.laneIdx;
    if (v.turnKey !== key) {
      v.turnKey = key;
      v.turn = this.makeTurn(v);
    }
    return v.turn;
  }

  /** A point d metres (of route) ahead of the vehicle, in its lane. */
  private ahead(v: Vehicle, d: number, out: typeof _p): void {
    const g = this.graph;
    const e = g.edges[v.cur.edge]!;
    const u = v.cur.s + d;
    // Still coming round the corner onto this edge.
    const ex = v.exiting;
    if (ex && v.cur.s < ex.sB) {
      if (u < ex.sB) this.onTurn(ex, 1 - (ex.sB - u) / ex.D, out);
      else g.at({ ...v.cur, s: Math.min(e.len, u) }, this.lane(v), out);
      return;
    }
    const tr = this.plan(v);
    if (tr && u >= tr.sA) {
      if (u < tr.sA + tr.D) {
        this.onTurn(tr, (u - tr.sA) / tr.D, out);
        return;
      }
      const ne = g.edges[tr.outEdge]!;
      g.at({ edge: tr.outEdge, dir: tr.outDir, s: Math.min(ne.len, u - e.len) }, laneOf(ne, tr.outLane), out);
      return;
    }
    if (u <= e.len) {
      g.at({ ...v.cur, s: u }, this.lane(v), out);
      return;
    }
    v.next ??= this.chooseNext(v);
    const ne = g.edges[v.next.edge]!;
    g.at({ edge: v.next.edge, dir: v.next.dir, s: Math.min(ne.len, u - e.len) }, laneOf(ne, v.laneIdx), out);
  }

  /** Circles covering a vehicle's body (and a rig's trailer), for collisions. */
  private circles(v: Vehicle): { x: number; z: number; r: number }[] {
    const out: { x: number; z: number; r: number }[] = [];
    const r = v.wid / 2;
    const hx = Math.sin(v.yaw);
    const hz = Math.cos(v.yaw);
    if (v.rig) {
      // Tractor, then the trailer swinging behind the hitch.
      for (const k of [6.6, 4.6]) out.push({ x: v.x + hx * (k - v.len / 2 + 2.6), z: v.z + hz * (k - v.len / 2 + 2.6), r });
      const hitchX = v.x + hx * (v.len / 2 - RIG_HITCH);
      const hitchZ = v.z + hz * (v.len / 2 - RIG_HITCH);
      const tx = Math.sin(v.trailerYaw);
      const tz = Math.cos(v.trailerYaw);
      for (let k = 0.6; k < v.len - RIG_HITCH; k += 2.2) out.push({ x: hitchX - tx * k, z: hitchZ - tz * k, r });
      return out;
    }
    const n = Math.max(2, Math.round(v.len / 1.8));
    for (let i = 0; i < n; i++) {
      const k = -v.len / 2 + r + ((v.len - 2 * r) * i) / (n - 1);
      out.push({ x: v.x + hx * k, z: v.z + hz * k, r });
    }
    return out;
  }

  private velocityOf(v: Vehicle): [number, number] {
    return v.state === 'drive' ? [Math.sin(v.yaw) * v.speed, Math.cos(v.yaw) * v.speed] : [v.vx, v.vz];
  }

  /** Knock a panel off where it was hit, sending it flying. */
  private tearPanel(v: Vehicle, cx: number, cz: number, nvx: number, nvz: number, debris: Debris): void {
    if (!v.model.panels.length) return;
    const rx = cx - v.x;
    const rz = cz - v.z;
    const hx = Math.sin(v.yaw);
    const hz = Math.cos(v.yaw);
    // Pursuit PIT's axes: lat to the right, lon forward. The right is (-hz, hx).
    const lat = rx * -hz + rz * hx;
    const lon = rx * hx + rz * hz;
    const parts = partsFor(v.len, v.wid);
    let best = -1;
    let bd = Infinity;
    parts.forEach((p, i) => {
      if (v.lost & (1 << i)) return;
      const d = Math.hypot(p.lat - lat, p.lon - lon) + (p.h < 0.1 ? 0.6 : 0);
      if (d < bd) {
        bd = d;
        best = i;
      }
    });
    if (best < 0) return;
    v.lost |= 1 << best;
    const [vx, vz] = this.velocityOf(v);
    const go = (m: THREE.Mesh) => {
      // Out of the vehicle's merged mesh, and off on its own.
      unmerge(v.model, m);
      const r = () => (Math.random() - 0.5) * 2;
      debris.fling(m, new THREE.Vector3(vx + nvx * 3 + r() * 2, 2.5 + Math.random() * 3, vz + nvz * 3 + r() * 2), new THREE.Vector3(r() * 8, r() * 8, r() * 8));
    };
    go(v.model.panels[best]!);
    for (const [part, m] of v.model.attached) if (part === best && m.parent) go(m);
  }

  /** Give up a claimed junction. */
  private release(v: Vehicle): void {
    if (v.holds >= 0) {
      const n = this.graph.nodes[v.holds]!;
      if (n.holder === v) n.holder = null;
    }
    v.holds = -1;
  }

  private wreck(v: Vehicle): void {
    this.release(v);
    v.state = 'wreck';
    v.t = 0;
    const char = (m: THREE.Mesh) => {
      const mat = m.material as THREE.MeshLambertMaterial;
      if (mat.color) mat.color.multiplyScalar(0.3);
    };
    char(v.model.core);
    char(v.model.cabin);
    if (v.model.panels[0]) char(v.model.panels[0]);
    // The same parts in the merged mesh (the materials above are for any torn off later).
    charMerged(v.model, [v.model.core, v.model.cabin, ...v.model.panels], 0.3);
    for (const b of v.model.brakes) b.visible = false;
  }

  /**
   * One step: drive everything, then resolve contacts with the player's car and between
   * vehicles. Returns the hits that happened.
   */
  update(dt: number, car: Car, debris: Debris, others: Car[] = []): TrafficHit[] {
    this.others = others;
    const hits: TrafficHit[] = [];
    this.contacts.begin();
    for (const v of this.vehicles) {
      v.t += dt;
      if (v.state === 'drive') this.drive(v, dt, car);
      else if (v.state !== 'parked') this.slide(v, dt, car);
      this.place(v, dt);
      // Too far off to make out: don't draw it.
      v.model.root.visible = Math.hypot(v.x - car.pos.x, v.z - car.pos.z) < (v.state === 'parked' ? 240 : 450);
      if (v.model.root.visible) this.contact(v);
    }
    this.contacts.end();
    // Drivers never drive through each other: ease any overlapping pair apart.
    const vs = this.vehicles;
    for (let i = 0; i < vs.length; i++) {
      const a = vs[i]!;
      if (a.state !== 'drive') continue;
      for (let k = i + 1; k < vs.length; k++) {
        const b = vs[k]!;
        if (b.state !== 'drive' || Math.abs(a.y - b.y) > LEVEL || Math.hypot(a.x - b.x, a.z - b.z) > (a.len + b.len) / 2 + 1) continue;
        const contact = this.deepest(this.circles(a), this.circles(b));
        if (!contact) continue;
        const share = b.mass / (a.mass + b.mass);
        a.x += contact.nx * contact.pen * share;
        a.z += contact.nz * contact.pen * share;
        b.x -= contact.nx * contact.pen * (1 - share);
        b.z -= contact.nz * contact.pen * (1 - share);
      }
    }
    // The player's car (and any rival's) against each vehicle.
    for (const c of [car, ...others]) this.collideCar(c, c === car, hits, debris);
    // Loose vehicles against the others.
    this.looseHits(hits, debris);
    return hits;
  }

  /** A physics car against every vehicle: pushed apart, momentum shared by mass. */
  private collideCar(car: Car, player: boolean, hits: TrafficHit[], debris: Debris): void {
    const pv = car.velocity(_v);
    let pvx = pv.x;
    let pvz = pv.z;
    let hit = false;
    const phx = Math.sin(car.yaw);
    const phz = Math.cos(car.yaw);
    const pc = [-1.25, 0, 1.25].map((k) => ({ x: car.pos.x + phx * k, z: car.pos.z + phz * k, r: 1.05 }));
    for (const v of this.vehicles) {
      if (Math.hypot(v.x - car.pos.x, v.z - car.pos.z) > v.len / 2 + 5) continue;
      if (Math.abs(v.y - car.pos.y) > 2.2) continue;
      const contact = this.deepest(pc, this.circles(v));
      if (!contact) continue;
      const { nx, nz, pen, cx, cz } = contact;
      const [vx, vz] = this.velocityOf(v);
      // Push the two apart, mostly moving the lighter one.
      const share = v.mass / (v.mass + PLAYER_MASS);
      car.pos.x += nx * pen * share;
      car.pos.z += nz * pen * share;
      if (v.state !== 'drive' || !v.rig) {
        v.x -= nx * pen * (1 - share);
        v.z -= nz * pen * (1 - share);
      }
      const vn = (pvx - vx) * nx + (pvz - vz) * nz;
      if (vn >= 0) continue;
      const j = (-(1 + RESTITUTION) * vn) / (1 / PLAYER_MASS + 1 / v.mass);
      pvx += (j / PLAYER_MASS) * nx;
      pvz += (j / PLAYER_MASS) * nz;
      const dv = j / v.mass;
      const wrecked = this.shove(v, vx - dv * nx, vz - dv * nz, dv, cx, cz, -nx, -nz, debris);
      hits.push({ power: -vn, wrecked, x: cx, y: v.y + 0.8, z: cz, player, car });
      hit = true;
    }
    if (hit) car.setVelocity(pvx, pvz);
  }

  /** Loose (and wrecked) vehicles knocking into the others. */
  private looseHits(hits: TrafficHit[], debris: Debris): void {
    for (const a of this.vehicles) {
      if (a.state !== 'loose') continue;
      for (const b of this.vehicles) {
        if (b === a || Math.abs(a.y - b.y) > LEVEL || Math.hypot(a.x - b.x, a.z - b.z) > (a.len + b.len) / 2 + 2) continue;
        const contact = this.deepest(this.circles(a), this.circles(b));
        if (!contact) continue;
        const { nx, nz, pen, cx, cz } = contact;
        const [avx, avz] = this.velocityOf(a);
        const [bvx, bvz] = this.velocityOf(b);
        const share = b.mass / (a.mass + b.mass);
        a.x += nx * pen * share;
        a.z += nz * pen * share;
        b.x -= nx * pen * (1 - share);
        b.z -= nz * pen * (1 - share);
        const vn = (avx - bvx) * nx + (avz - bvz) * nz;
        if (vn >= 0) continue;
        const j = (-(1 + RESTITUTION) * vn) / (1 / a.mass + 1 / b.mass);
        a.vx += (j / a.mass) * nx;
        a.vz += (j / a.mass) * nz;
        const dv = j / b.mass;
        const wrecked = this.shove(b, bvx - dv * nx, bvz - dv * nz, dv, cx, cz, -nx, -nz, debris);
        if (-vn > 3) hits.push({ power: -vn, wrecked, x: cx, y: b.y + 0.8, z: cz, player: false, car: null });
      }
    }
  }

  /** A vehicle shoved by a hit: it breaks loose, spins, may lose a panel or be wrecked. */
  private shove(v: Vehicle, vx: number, vz: number, dv: number, cx: number, cz: number, nx: number, nz: number, debris: Debris): boolean {
    if (v.state === 'drive' || v.state === 'parked') {
      if (dv < 0.6) return false;
      v.state = 'loose';
      this.release(v);
      v.t = 0;
    }
    v.vx = vx;
    v.vz = vz;
    // Spin from where it was hit: torque about its centre.
    const rx = cx - v.x;
    const rz = cz - v.z;
    v.yawRate += ((rz * nx - rx * nz) * dv * 4) / Math.max(4, v.len * v.len * 0.4);
    if (dv > 2.2) this.tearPanel(v, cx, cz, nx, nz, debris);
    if (dv > 4.5) this.tearPanel(v, cx, cz, nx, nz, debris);
    if (v.state !== 'wreck' && dv > (v.rig ? 5 : 9.5)) {
      this.wreck(v);
      return true;
    }
    return false;
  }

  /** The deepest overlap between two sets of circles: normal from b to a. */
  private deepest(a: { x: number; z: number; r: number }[], b: { x: number; z: number; r: number }[]): { nx: number; nz: number; pen: number; cx: number; cz: number } | null {
    let best: { nx: number; nz: number; pen: number; cx: number; cz: number } | null = null;
    for (const p of a)
      for (const q of b) {
        const dx = p.x - q.x;
        const dz = p.z - q.z;
        const d = Math.hypot(dx, dz);
        const pen = p.r + q.r - d;
        if (pen > 0 && (!best || pen > best.pen)) {
          const nx = d > 1e-4 ? dx / d : 1;
          const nz = d > 1e-4 ? dz / d : 0;
          best = { nx, nz, pen, cx: q.x + nx * q.r, cz: q.z + nz * q.r };
        }
      }
    return best;
  }

  private drive(v: Vehicle, dt: number, car: Car): void {
    const g = this.graph;
    const e = g.edges[v.cur.edge]!;
    // Advance the cursor along the route (faster or slower than the car round a corner,
    // whose curve is shorter or longer than the lanes it cuts across).
    const plan = this.plan(v);
    const ex = v.exiting && v.cur.s < v.exiting.sB ? v.exiting : null;
    // (Or turning round at a dead end, where the car heads back down the edge it's on.)
    const uTurn = v.next?.edge === v.cur.edge && e.len - v.cur.s < 20;
    const cornering = ex || (plan && v.cur.s >= plan.sA);
    // Along the lanes, first bring the cursor level with the car itself: a car cutting the
    // bends of a winding road would otherwise fall behind its cursor's idea of where it is,
    // and steer at a point beside it.
    if (!cornering && !uTurn) v.cur.s = Math.max(v.cur.s - 3, g.project(v.cur, v.x, v.z));
    v.cur.s += v.speed * dt * (ex ? ex.ratio : cornering ? plan!.ratio : 1);
    while (v.cur.s > g.edges[v.cur.edge]!.len) {
      v.cur.s -= g.edges[v.cur.edge]!.len;
      const n = v.next ?? this.chooseNext(v);
      v.exiting = v.turn && v.turn.outEdge === n.edge && v.turn.outDir === n.dir ? v.turn : null;
      v.turn = null;
      v.turnKey = -1;
      v.committed = -1;
      // Round a corner, it has come out in the lane the corner led to.
      if (v.exiting) {
        v.laneIdx = v.exiting.outLane;
        v.laneOff = laneOf(g.edges[n.edge]!, v.laneIdx);
      }
      v.cur = { edge: n.edge, dir: n.dir, s: v.cur.s };
      v.next = null;
    }
    // Ease across into the lane it means to be in.
    const lt = this.laneTarget(v);
    v.laneOff += Math.max(-2.5 * dt, Math.min(2.5 * dt, lt - v.laneOff));
    // Steer at a point ahead in the lane.
    const look = (v.rig ? 6.5 : 4.5) + v.speed * (v.rig ? 0.35 : 0.45);
    this.ahead(v, look, _p);
    const want = Math.atan2(_p.x - v.x, _p.z - v.z);
    // Wheels only turn a car that's rolling.
    const turnRate = (v.rig ? 0.9 : 2.2) * Math.min(1, v.speed / 2);
    v.yaw += Math.max(-turnRate * dt, Math.min(turnRate * dt, wrap(want - v.yaw)));
    // Speed: the limit at this driver's pace, slower for bends and turns ahead.
    let target = e.speed * v.pace;
    this.ahead(v, 2, _q);
    const h0 = Math.atan2(_q.tx, _q.tz);
    for (const d of [12, 24, 40]) {
      this.ahead(v, d, _q);
      const bend = Math.abs(wrap(Math.atan2(_q.tx, _q.tz) - h0));
      if (bend > 0.08) target = Math.min(target, Math.sqrt((3 * d) / bend) * (v.rig ? 0.8 : 1));
    }
    // Junctions: let go of the last one once clear of it; claim the next one on the way
    // in, or wait at the line while someone else is crossing.
    const ce = g.edges[v.cur.edge]!;
    const nodeAhead = v.cur.dir > 0 ? ce.b : ce.a;
    if (v.holds >= 0 && v.holds !== nodeAhead) {
      const held = g.nodes[v.holds]!;
      if (Math.hypot(held.x - v.x, held.z - v.z) > 14) this.release(v);
    }
    const junction = g.nodes[nodeAhead]!;
    const toNode = ce.len - v.cur.s;
    const signals = this.world.signals;
    v.atLight = false;
    // A race coming through: give way to it, waiting short of the junction while a racer is
    // bearing down on it (unless this car's on the race line itself, ahead of them).
    if (this.others.length && junction.edges.length >= 3 && !junction.free && toNode < 45) {
      for (const c of this.others) {
        if (Math.abs(c.pos.y - v.y) > LEVEL) continue;
        const dx = junction.x - c.pos.x;
        const dz = junction.z - c.pos.z;
        const d = Math.hypot(dx, dz);
        const cv = c.velocity(_v);
        const closing = (cv.x * dx + cv.z * dz) / Math.max(1, d);
        if (d < 70 && (closing > 4 || d < 18) && d / Math.max(4, closing) < 4) {
          // Same way as the racer and ahead of it: carry on.
          const same = Math.sin(v.yaw) * cv.x + Math.cos(v.yaw) * cv.z > 0 && (v.x - c.pos.x) * cv.x + (v.z - c.pos.z) * cv.z > 0;
          if (!same) target = Math.min(target, stopFor(toNode - (ce.city ? 14 : 18)));
        }
      }
    }
    if (junction.signal && signals) {
      // Traffic lights: stop at the line on red, and on amber if there's room to. Turning
      // left, also wait for a gap in the oncoming traffic.
      const room = toNode - SIGNAL_LINE;
      if (room > -1.5 && toNode < 120) {
        g.at({ ...v.cur, s: ce.len }, 0, _q);
        const light = signals.state(Math.abs(_q.tz) > Math.abs(_q.tx) ? 'ns' : 'ew');
        const turn = this.plan(v);
        const left = turn?.side === -1;
        // Turning left from the line, reached before the red: finish the turn once the
        // oncoming traffic has stopped, as drivers do.
        if (left && room < 2.5 && light !== 'red') v.committed = v.cur.edge;
        let stop = (light === 'red' && v.committed !== v.cur.edge) || (light === 'amber' && room > (v.speed * v.speed) / 14 + 0.5 && !(left && room < 2.5));
        v.atLight = stop;
        if (!stop && left && room < 12 && this.oncoming(v, nodeAhead)) stop = true;
        if (stop) target = Math.min(target, stopFor(room));
      }
    } else if (junction.edges.length >= 3 && !junction.free && toNode < (ce.city ? 22 : 34) && v.ghost <= 0) {
      const h = junction.holder;
      const holderGone = !h || h.state !== 'drive' || (h.holds !== nodeAhead && Math.hypot(junction.x - h.x, junction.z - h.z) > 14);
      if (h === v || holderGone) {
        if (h && h !== v) h.holds = h.holds === nodeAhead ? -1 : h.holds;
        if (v.holds >= 0 && v.holds !== nodeAhead) this.release(v);
        junction.holder = v;
        v.holds = nodeAhead;
      } else {
        // Stop at the line, short of the crossing.
        const line = ce.city ? SIGNAL_LINE : 13;
        target = Math.min(target, stopFor(toNode - line));
      }
    }
    // Keep a gap behind anything ahead in the lane: other vehicles and the player.
    const hx = Math.sin(v.yaw);
    const hz = Math.cos(v.yaw);
    let blocked = false;
    const check = (x: number, z: number, len: number, wid: number, moving: number, facing: number) => {
      const rx = x - v.x;
      const rz = z - v.z;
      const along = rx * hx + rz * hz;
      if (along <= 0 || along > 45) return;
      const lat = Math.abs(rx * hz - rz * hx);
      // Traffic coming the other way only counts if it's square in the path: on a bend, a
      // car in the other lane can look as if it's ahead in this one.
      if (lat > (v.wid + wid) / 2 + (facing < -0.5 ? -0.1 : 0.7)) return;
      const gap = along - (v.len + len) / 2;
      target = Math.min(target, Math.max(0, (gap - 4) * 0.8 + Math.max(0, moving) * 0.6));
      if (gap < 12 && moving < 1) blocked = true;
    };
    // Waiting far too long (two drivers each waiting for the other): ignore the junction
    // and the lower-ranked driver for a few seconds.
    v.waiting = v.speed < 0.3 && !v.atLight ? v.waiting + dt : 0;
    if (v.waiting > 8 && v.ghost <= 0) v.ghost = 4;
    if (v.ghost > 0) v.ghost -= dt;
    // Breaking a standoff, only give way to the drivers ranked above (so one side goes).
    const rank = this.vehicles.indexOf(v);
    for (let i = 0; i < this.vehicles.length; i++) {
      const o = this.vehicles[i]!;
      if (o === v || (v.ghost > 0 && i < rank) || Math.abs(o.x - v.x) > 50 || Math.abs(o.z - v.z) > 50 || Math.abs(o.y - v.y) > LEVEL) continue;
      // Whoever has the junction doesn't wait for those queued to get into it.
      if (v.holds === nodeAhead && o.state === 'drive' && o.holds !== nodeAhead && o.speed < 1) {
        const oe = this.graph.edges[o.cur.edge]!;
        if ((o.cur.dir > 0 ? oe.b : oe.a) === nodeAhead) continue;
      }
      const [ovx, ovz] = this.velocityOf(o);
      check(o.x, o.z, o.len, o.wid, ovx * hx + ovz * hz, o.state === 'drive' ? Math.sin(o.yaw) * hx + Math.cos(o.yaw) * hz : 1);
    }
    for (const c of [car, ...this.others]) {
      if (Math.abs(c.pos.y - v.y) > LEVEL) continue;
      const cv = c.velocity(_v);
      check(c.pos.x, c.pos.z, 4.4, 1.9, cv.x * hx + cv.z * hz, Math.sin(c.yaw) * hx + Math.cos(c.yaw) * hz);
    }
    // Held up behind something stopped: go round it in the other lane (but not a queue
    // at a junction).
    v.stuck = blocked && v.speed < 2 ? v.stuck + dt : 0;
    if (ce.city) {
      // In town there are two lanes each way: get into the outer one for a right turn and
      // the inner one for a left, and otherwise change lanes round anything stopped.
      const turn = this.plan(v);
      const settled = Math.abs(v.laneOff - laneOf(ce, v.laneIdx)) < 0.3;
      if (turn && toNode < 90 && toNode > 20 && settled) {
        const want = turn.side > 0 ? 0 : 1;
        if (v.laneIdx !== want && this.sideClear(v, want, car)) v.laneIdx = want;
      } else if (v.stuck > 1.5 && settled && (toNode > 90 || junction.edges.length < 3) && this.sideClear(v, 1 - v.laneIdx, car)) {
        v.laneIdx = 1 - v.laneIdx;
        v.stuck = 0;
      }
    } else if (!ce.oneway && v.stuck > 2.5 && v.passing <= 0 && (toNode > 50 || junction.edges.length < 3) && this.laneClear(v, 70)) v.passing = 5;
    // Something coming the other way: tuck back in.
    if (v.passing > 0 && !this.laneClear(v, 25)) v.passing = 0;
    v.passing = Math.max(0, v.passing - dt);
    const accel = v.rig ? 1.2 : 2.6;
    const brake = 7;
    v.braking = target < v.speed - 0.4;
    v.speed += Math.max(-brake * dt, Math.min(accel * dt, target - v.speed));
    v.speed = Math.max(0, v.speed);
    v.x += hx * v.speed * dt;
    v.z += hz * v.speed * dt;
    // The trailer follows the tractor round.
    if (v.rig) v.trailerYaw += wrap(v.yaw - v.trailerYaw) * Math.min(1, (v.speed / (v.len - RIG_HITCH)) * dt * 1.6);
    else v.trailerYaw = v.yaw;
    // Hopelessly stuck (wedged at an angle, say) and out of sight: start it afresh elsewhere.
    if (v.waiting > 25 && Math.hypot(v.x - car.pos.x, v.z - car.pos.z) > 120) this.spawn(this.vehicles.indexOf(v), car.pos, 150, v);
  }

  /** Is the other lane free of oncoming traffic for some way ahead (to go round something)? */
  private laneClear(v: Vehicle, dist: number): boolean {
    const lane = laneAt(false, 0);
    const hx = Math.sin(v.yaw);
    const hz = Math.cos(v.yaw);
    for (const o of this.vehicles) {
      if (o === v || o.state !== 'drive' || Math.abs(o.x - v.x) > dist + 10 || Math.abs(o.z - v.z) > dist + 10 || Math.abs(o.y - v.y) > LEVEL) continue;
      const rx = o.x - v.x;
      const rz = o.z - v.z;
      const along = rx * hx + rz * hz;
      if (along < -5 || along > dist) continue;
      // How far to the right of this driver (its own lane is 0, the other lane -2 lanes).
      const right = -rx * hz + rz * hx;
      const oncoming = Math.sin(o.yaw) * hx + Math.cos(o.yaw) * hz < 0;
      if (oncoming && right < -lane * 0.6 && right > -lane * 3.5) return false;
    }
    return true;
  }

  /** Is anything coming the other way through a junction (for a driver turning left across it)? */
  private oncoming(v: Vehicle, node: number): boolean {
    const g = this.graph;
    const n = g.nodes[node]!;
    const hx = Math.sin(v.yaw);
    const hz = Math.cos(v.yaw);
    for (const o of this.vehicles) {
      if (o === v || o.state !== 'drive' || o.speed < 0.5 || Math.abs(o.y - v.y) > LEVEL) continue;
      const d = Math.hypot(o.x - n.x, o.z - n.z);
      if (d > 55 || Math.sin(o.yaw) * hx + Math.cos(o.yaw) * hz > -0.7) continue;
      const oe = g.edges[o.cur.edge]!;
      // Coming up to the crossing (unless turning left too: they pass each other), or in it.
      if ((o.cur.dir > 0 ? oe.b : oe.a) === node) {
        if (!(o.turn && o.turn.side === -1)) return true;
      } else if (d < 12) return true;
    }
    return false;
  }

  /** A loose or wrecked vehicle sliding to a stop; a loose one then finds the road again. */
  private slide(v: Vehicle, dt: number, car: Car): void {
    const sp = Math.hypot(v.vx, v.vz);
    const fr = Math.min(sp, (v.state === 'wreck' ? 8 : 6.5) * dt);
    if (sp > 1e-4) {
      v.vx -= (v.vx / sp) * fr;
      v.vz -= (v.vz / sp) * fr;
    }
    v.yawRate *= Math.exp(-1.6 * dt);
    const nx = v.x + v.vx * dt;
    const nz = v.z + v.vz * dt;
    if (this.world.squareBlocked(nx, nz, v.wid / 2, true, v.y)) {
      v.vx *= -0.35;
      v.vz *= -0.35;
      v.yawRate *= 0.5;
    } else {
      v.x = nx;
      v.z = nz;
    }
    v.yaw += v.yawRate * dt;
    if (v.rig) v.trailerYaw += wrap(v.yaw - v.trailerYaw) * Math.min(1, dt * 0.5);
    v.braking = false;
    const still = sp < 0.6 && Math.abs(v.yawRate) < 0.3;
    const far = Math.hypot(v.x - car.pos.x, v.z - car.pos.z);
    if (v.state === 'loose' && still && v.t > 2 && v.home) {
      // A parked car knocked about stays wherever it ends up.
      v.state = 'parked';
    } else if (v.state === 'loose' && still && v.t > 2) {
      const near = this.graph.nearest(v.x, v.z, v.yaw, v.y);
      if (near.d < 9) {
        v.state = 'drive';
        v.cur = near.cursor;
        v.next = null;
        v.turn = null;
        v.exiting = null;
        v.turnKey = -1;
        v.speed = 0;
        v.t = 0;
        v.passing = 0;
        v.laneOff = laneOf(this.graph.edges[v.cur.edge]!, v.laneIdx);
      } else if (far > 120 && v.t > 10) this.spawn(this.vehicles.indexOf(v), car.pos, 150, v);
    }
    // Wrecks are cleared away once nobody's looking.
    if (v.state === 'wreck' && v.t > 25 && far > 120) this.spawn(this.vehicles.indexOf(v), car.pos, 150, v);
  }

  /** Move the model: ground height, the slope under it, brake lights, trailer. */
  private place(v: Vehicle, dt: number): void {
    const w = this.world;
    // On whatever it's on: the ground, or the highway's deck it's driving along.
    const hint = v.y + 0.5;
    v.y = w.height(v.x, v.z, hint);
    const hx = Math.sin(v.yaw);
    const hz = Math.cos(v.yaw);
    const k = Math.min(3, v.len / 3);
    const pitch = Math.atan2(w.height(v.x + hx * k, v.z + hz * k, hint) - w.height(v.x - hx * k, v.z - hz * k, hint), 2 * k);
    v.pitch += (pitch - v.pitch) * Math.min(1, dt * 8);
    const m = v.model;
    m.root.position.set(v.x, v.y, v.z);
    m.root.rotation.set(-v.pitch, v.yaw, 0, 'YXZ');
    if (m.trailer) m.trailer.rotation.y = v.trailerYaw - v.yaw;
    const lit = v.braking && v.state === 'drive';
    for (const b of m.brakes) {
      b.userData.off ??= b.material;
      if (b.visible) b.material = lit ? brakeOn : (b.userData.off as THREE.Material);
    }
    // Far away, don't draw it.
    m.root.visible = true;
  }

  /** The soft shadow under a vehicle: one under a car, one each under a rig's tractor and trailer. */
  private contact(v: Vehicle): void {
    const y = v.y + 0.08;
    if (!v.rig) {
      this.contacts.add(v.x, y, v.z, v.yaw, v.len, v.wid);
      return;
    }
    const hx = Math.sin(v.yaw);
    const hz = Math.cos(v.yaw);
    const cab = RIG_HITCH + 1.2;
    this.contacts.add(v.x + hx * (v.len / 2 - cab / 2), y, v.z + hz * (v.len / 2 - cab / 2), v.yaw, cab, v.wid);
    const hitchX = v.x + hx * (v.len / 2 - RIG_HITCH);
    const hitchZ = v.z + hz * (v.len / 2 - RIG_HITCH);
    const tl = v.len - RIG_HITCH;
    this.contacts.add(hitchX - Math.sin(v.trailerYaw) * tl / 2, y, hitchZ - Math.cos(v.trailerYaw) * tl / 2, v.trailerYaw, tl, v.wid);
  }

  /** Wrecks that should be smoking, for the game to puff smoke from. */
  smoking(): THREE.Vector3[] {
    const out: THREE.Vector3[] = [];
    for (const v of this.vehicles)
      if (v.state === 'wreck') {
        const hx = Math.sin(v.yaw);
        const hz = Math.cos(v.yaw);
        out.push(new THREE.Vector3(v.x + hx * v.len * 0.3, v.y + 1.2, v.z + hz * v.len * 0.3));
      }
    return out;
  }

  /** How many vehicles are out, by state (for tests and the HUD). */
  stats(): { driving: number; loose: number; wrecked: number; edges: number; nodes: number } {
    return {
      driving: this.vehicles.filter((v) => v.state === 'drive').length,
      loose: this.vehicles.filter((v) => v.state === 'loose').length,
      wrecked: this.vehicles.filter((v) => v.state === 'wreck').length,
      edges: this.graph.edges.length,
      nodes: this.graph.nodes.length,
    };
  }

  /** Positions and speeds, for tests. */
  snapshot(): { x: number; z: number; yaw: number; speed: number; state: string; type: string; edge: number; offRoad: number }[] {
    return this.vehicles.map((v) => {
      const near = this.world.nearestRoad(v.x, v.z);
      return { x: v.x, z: v.z, yaw: v.yaw, speed: v.speed, state: v.state, type: v.type, edge: v.cur.edge, offRoad: near ? near.edge : 99 };
    });
  }

  dispose(): void {
    this.root.removeFromParent();
  }
}