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/game.ts
import * as THREE from 'three';
import { Car, CAR_SPEED, PAINTS, REAR_WHEELS } from './car.js';
import { Debris } from './debris.js';
import { Clods, SkidMarks, Smoke, Spray } from './fx.js';
import type { Controls, Input } from './input.js';
import { setMenuMusic, sfxBank, sfxCrash, sfxKnock, sfxLand, sfxLost, updateCarSound, updateRivalSounds } from './sound.js';
import { SUN_SOFTNESS } from './shadows.js';
import { Sky } from './sky.js';
import { Post } from './post.js';
import { NIGHT } from './night.js';
import { BuildingDetail } from './building-detail.js';
import { CarPaint, type PaintOp } from './car-paint.js';
import { Garage } from './garage.js';
import { LampBake } from './lamp-bake.js';
import { setVehicleLights } from './vehicles.js';
import { RoomEnvironment } from 'three/examples/jsm/environments/RoomEnvironment.js';
import { contactShadow } from './contact.js';
import { Traffic, type RoadGraph, type TrafficHit } from './traffic.js';
import { RaceSession, START_S, type RaceEvent, type RaceInfo, type RaceRoute } from './race.js';
import { RaceGates } from './race-gates.js';
import { RaceTrail } from './race-trail.js';
import { Rival, collideCars, type Obstacle, type RivalSpec } from './rivals.js';

/** A slide that stops for longer than this (s) has ended. */
const DRIFT_GAP = 0.35;

/** The rivals in a race: each its own paint, pace and taste for drifting. */
const RIVALS: RivalSpec[] = [
  { name: 'Kestrel', paint: 0x2e6fd8, pace: 1, drift: 0.6 },
  { name: 'Vandal', paint: 0xe8c547, pace: 0.97, drift: 0.95 },
  { name: 'Nomad', paint: 0x2e8b57, pace: 0.94, drift: 0.4 },
];
import { World, type MapId, type Prop, type PropKind } from './world.js';

export type Mode = 'attract' | 'drive' | 'paused';

export type GameEvent =
  | { type: 'bank'; points: number; mult: number; best: boolean }
  | { type: 'lost'; points: number }
  | { type: 'crash'; power: number }
  | { type: 'smash'; points: number; label: string }
  /** A slide ended (not in a crash), seconds long. */
  | { type: 'drift'; seconds: number };

/** Live numbers for the HUD. */
export interface DriftState {
  speed: number;
  /** Points in the drift under way, not yet banked. */
  points: number;
  mult: number;
  /** 0..1: how close the multiplier is to its next step. */
  multProgress: number;
  drifting: boolean;
  /** Seconds left before an unbroken drift is banked. */
  grace: number;
  angle: number;
  /** Seconds in the air on the current jump (0 on the ground). */
  air: number;
  total: number;
  best: number;
}

/** The sun's path: how high it climbs at noon, and which way it's facing then (radians round from +x). */
const SUN_MAX_ELEVATION = (70 * Math.PI) / 180;
const SUN_NOON_HEADING = (97.6 * Math.PI) / 180;
const ZOOMS = [26, 38, 56];
/** The view after the chase distances: from the driver's seat. */
const FIRST_PERSON = 3;
/** How far above the car the camera looks down, in radians (about 34°). */
const BASE_PITCH = 0.6;
/** How far the view can be dragged round: a head's turn inside; outside, right round the car and from near the ground to overhead. */
const LOOK_INSIDE = { yaw: 2.2, pitchMin: -1.1, pitchMax: 0.6 };
const LOOK_OUTSIDE = { yaw: Infinity, pitchMin: -1.2, pitchMax: 0.75 };
const MAX_PITCH = 1.42;
const GRACE = 1.4;
const MULT_STEP = 1.8;
const MAX_MULT = 6;
const STEP = 1 / 120;
/** How much each kind of thing slows the car as it's knocked over. */
const KNOCK_DRAG: Record<PropKind, number> = { bush: 0.97, cone: 0.99, box: 0.985, hay: 0.9, trash: 0.97, barrier: 0.96, sign: 0.94, mailbox: 0.95, fence: 0.95, bench: 0.93, hydrant: 0.85, lamp: 0.88, tree: 0.82 };
/** Points for smashing each kind of thing. */
const KNOCK_POINTS: Record<PropKind, number> = { bush: 5, cone: 10, box: 10, hay: 20, trash: 20, barrier: 15, sign: 30, mailbox: 30, fence: 15, bench: 25, hydrant: 50, lamp: 40, tree: 20 };

/** The graphics settings: Auto picks one of the others from how quickly frames come. */
export type Quality = 'auto' | 'low' | 'medium' | 'high';
type Tier = Exclude<Quality, 'auto'>;
const TIERS: Tier[] = ['low', 'medium', 'high'];
/**
 * Each tier: the sharpest it draws (device pixels per CSS pixel), the sun's shadows (three's
 * plain PCF, or the soft shadows of shadows.ts) and their map's size, how far the small
 * things are drawn, post-processing (see post.ts): none, or with ambient occlusion; and the
 * buildings' walls (facades.ts): as they were, sharper with each wall's material, or with
 * rooms behind the windows too.
 */
const TIER: Record<Tier, { ratio: number; soft: boolean; shadowMap: number; detail: number; post: boolean; ao: boolean; lampShadows: number; facade: 0 | 1 | 2 }> = {
  low: { ratio: 1, soft: false, shadowMap: 1024, detail: 380, post: false, ao: false, lampShadows: 0, facade: 0 },
  medium: { ratio: 1.25, soft: true, shadowMap: 2048, detail: 650, post: true, ao: false, lampShadows: 2, facade: 1 },
  high: { ratio: 1.75, soft: true, shadowMap: 2048, detail: 950, post: true, ao: true, lampShadows: 4, facade: 2 },
};

const _v = new THREE.Vector3();
const _w = new THREE.Vector3();
const _back = new THREE.Vector3();
const _vel = new THREE.Vector3();

export class Game {
  readonly renderer: THREE.WebGLRenderer;
  readonly scene = new THREE.Scene();
  /** (Out to the fog's far end: everything beyond it is lost in the haze anyway.) */
  readonly camera = new THREE.PerspectiveCamera(50, 1, 1, 1950);
  world: World;
  readonly car: Car;
  /** The buildings' 3D detail near the camera (on Medium and High; see building-detail.ts). */
  buildingDetail!: BuildingDetail;
  mode: Mode = 'attract';
  onEvent: (e: GameEvent) => void = () => undefined;
  /** The pause key or button was pressed. */
  onPause: () => void = () => undefined;
  /** Something happened in the race (countdown, checkpoint, lap, finish). */
  onRace: (e: RaceEvent) => void = () => undefined;
  /** The race under way, if one is. */
  race: RaceSession | null = null;
  private gates: RaceGates | null = null;
  /** The blue arrows along the route ahead of the player. */
  private trail: RaceTrail | null = null;
  /** The rivals' cars, their contact shadows, and how long since each puffed tyre smoke. */
  rivals: Rival[] = [];
  private rivalContacts: THREE.Mesh[] = [];
  private rivalSmoke: number[] = [];
  /** The camera view changed (for saving it). */
  onZoom: (zoom: number) => void = () => undefined;
  private lastChase = 1;
  private wasFirstPerson = false;
  private lookYaw = 0;
  private lookPitch = 0;
  /** The chase camera's heading as placed: camYaw, swung round by looking around. */
  private viewYaw = 0;
  shakeEnabled = true;
  zoom = 1;
  readonly state: DriftState = { speed: 0, points: 0, mult: 1, multProgress: 0, drifting: false, grace: 0, angle: 0, air: 0, total: 0, best: 0 };

  private readonly sun = new THREE.DirectionalLight(0xfff0d8, 2.6);
  private readonly sunDir = new THREE.Vector3();
  private readonly hemi = new THREE.HemisphereLight(0xcfe6ff, 0x7a8a5a, 1.15);
  private readonly sky = new Sky();
  /**
   * At night, the street lamps nearest the car shine real light that casts shadows (as
   * many as the graphics tier allows; the rest keep their pools: see World.lamps).
   */
  private lampLights: THREE.SpotLight[] = [];
  private lampClock = 0;
  /** The lamps the real lamp lights are at now (their baked light taken out meanwhile). */
  private lampsLit: number[] = [];
  /** Every lamp's light, baked (see lamp-bake.ts): made the first night on each map. */
  private lampBake: LampBake | null = null;
  /** The lights coming on (0 by day to 1 at night; see setTimeOfDay). */
  private lights = 0;
  /** The time of day, in hours (0 to 24): where the sun is, and so the sky and the light. */
  private hours = 15;
  private readonly smoke = new Smoke();
  private readonly skids = new SkidMarks();
  /** Mud and turf thrown up drifting on grass. */
  private readonly clods = new Clods();
  private readonly debris = new Debris();
  private readonly spray = new Spray();
  private traffic!: Traffic;
  private smashPoints = 0;
  private smashLabel = '';
  private smashClock = 0;
  private wreckSmoke = 0;
  private readonly touched = new Set<Prop>();
  private readonly camTarget = new THREE.Vector3();
  private camYaw = 0;
  private camPitch = BASE_PITCH;
  /** How far ahead of the car the camera aims, so more of the road ahead is in view. */
  private aimAhead = 0;
  private readonly aim = new THREE.Vector3();
  private camDist = ZOOMS[1]!;
  private orbit = 0;
  private shake = 0;
  private smokeClock = 0;
  private chainTime = 0;
  private airTime = 0;
  /** How long the slide going on has lasted, and how long since it last slid (s): short wobbles out of it don't end it. */
  private driftRun = 0;
  private driftGap = 0;
  /** The paint shop's studio, while it's open (the car's in it, and the town isn't drawn). */
  private garage: Garage | null = null;
  private inGarage = false;
  /** The player's livery (made the first time one's used). */
  private carPaint: CarPaint | null = null;
  private graceTime = 0;
  private acc = 0;
  private last = 0;
  private controls: Controls = { throttle: 0, steer: 0, handbrake: false, reset: false, camera: false, view: false, pause: false, look: { yaw: 0, pitch: 0 } };
  private pixelRatio: number;
  /** The soft shadow right under the player's car. */
  private readonly contact = contactShadow(4.4, 1.9);
  /** Drawn at a share of full resolution while frames are slow (adaptResolution). */
  private resScale = 1;
  private frameMs = 16;
  private lastFrame = 0;
  private resClock = 0;
  /** The graphics setting, and the tier it's at (Auto moves between them; see adaptQuality). */
  private quality: Quality = 'auto';
  private tier: Tier = 'medium';
  /** Auto: the slowest tier it has had to leave (it won't climb back to that), and its clock. */
  private ceiling = 3;
  private qualityClock = 0;
  private quickWindows = 0;
  private post: Post | null = null;

  constructor(
    private readonly canvas: HTMLCanvasElement,
    private readonly input: Input,
    paint: number,
    map: MapId = 'city',
    /** The map, built already (see World.create); else it's built here, all in one go. */
    world?: World,
  ) {
    this.renderer = new THREE.WebGLRenderer({ canvas, antialias: true, powerPreference: 'high-performance' });
    this.pixelRatio = Math.min(window.devicePixelRatio || 1, TIER[this.tier].ratio);
    this.renderer.setPixelRatio(this.pixelRatio);
    this.renderer.shadowMap.enabled = true;
    this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
    // The shadow map is drawn once a frame, then shared by the mirrors and the main view.
    this.renderer.shadowMap.autoUpdate = false;
    this.renderer.toneMapping = THREE.ACESFilmicToneMapping;
    this.renderer.toneMappingExposure = 1.05;

    this.scene.fog = new THREE.Fog(0xbfd2d6, 500, 1900);
    this.scene.background = new THREE.Color(0xbfd2d6);
    // The sky joins the scene once its shader is compiled, off to one side where the browser
    // can (compiling it in the middle of a frame stalls software rendering for seconds);
    // until then the plain haze colour stands in.
    this.renderer
      .compileAsync(this.sky.mesh, this.camera, this.scene)
      .catch(() => {})
      .then(() => {
        this.scene.add(this.sky.mesh);
        void this.sky.load(this.renderer);
      });

    this.scene.add(this.hemi);
    this.sun.castShadow = true;
    this.sun.shadow.mapSize.set(2048, 2048);
    this.sun.shadow.bias = -0.0004;
    this.sun.shadow.normalBias = 0.6;
    const sc = this.sun.shadow.camera;
    sc.near = 10;
    sc.far = 600;
    this.scene.add(this.sun, this.sun.target);

    this.world = world ?? new World(map);
    this.scene.add(this.world.root);
    this.newBuildingDetail();
    this.light();
    this.applyLights();
    this.warmUp();
    const s = this.world.spawn;
    this.car = new Car(s.x, s.z, s.yaw, paint);
    this.car.place(s.x, s.z, s.yaw, this.world.height(s.x, s.z));
    this.scene.add(this.car.root);
    // Something for the cars' paint, glass and chrome to reflect (a soft studio: their
    // materials are the only ones that use it; the map's and the sky's don't).
    const pmrem = new THREE.PMREMGenerator(this.renderer);
    this.scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
    pmrem.dispose();
    this.scene.add(this.skids.mesh, this.smoke.points, this.clods.root, this.debris.root, this.spray.points, this.contact);
    this.traffic = this.makeTraffic();

    this.camTarget.copy(this.car.pos);
    this.camYaw = this.car.yaw;
    this.setZoom(this.zoom);
    this.resize();
    new ResizeObserver(() => this.resize()).observe(canvas.parentElement ?? canvas);
    this.warmUp();
  }

  /** The world's buildings' 3D detail, and the walls' and small things' settings for the graphics tier. */
  private newBuildingDetail(): void {
    this.buildingDetail = new BuildingDetail(this.world.layout);
    this.scene.add(this.buildingDetail.root);
    this.world.detailDistance = TIER[this.tier].detail;
    this.world.setFacadeDetail(TIER[this.tier].facade);
    this.buildingDetail.setLevel(TIER[this.tier].facade);
  }

  get mapId(): MapId {
    return this.world.id;
  }

  /** Swap to another map: a fresh world, the car at its start, the score cleared. */
  setMap(id: MapId): void {
    if (id === this.world.id) return;
    this.endRace();
    this.scene.remove(this.world.root);
    this.world.dispose();
    this.lampBake?.dispose();
    this.lampBake = null;
    this.lampsLit = [];
    this.buildingDetail.dispose();
    this.world = new World(id);
    this.scene.add(this.world.root);
    this.newBuildingDetail();
    this.light();
    const s = this.world.spawn;
    this.car.place(s.x, s.z, s.yaw, this.world.height(s.x, s.z));
    this.skids.clear();
    this.debris.clear();
    this.smoke.clear();
    this.clods.clear();
    this.spray.clear();
    this.traffic.dispose();
    this.traffic = this.makeTraffic();
    this.clearDrift();
    this.state.total = 0;
    this.camTarget.copy(this.car.pos);
    this.camYaw = s.yaw;
    this.orbit = 0;
  }

  /** Traffic on the roads, or none (the parked cars stay either way). */
  private trafficOn = true;
  setTraffic(on: boolean): void {
    if (on === this.trafficOn) return;
    this.trafficOn = on;
    this.traffic.dispose();
    this.traffic = this.makeTraffic();
  }

  /** Traffic for the current map: busier with the City's streets to fill, quieter on the small Test map. */
  private makeTraffic(): Traffic {
    const t = new Traffic(this.world, !this.trafficOn ? 0 : this.world.id === 'city' ? 150 : this.world.id === 'test' ? 30 : 60, this.car.pos);
    this.scene.add(t.root);
    return t;
  }

  /** The race's clock, progress and positions; the rivals told when to go and how the player's doing. */
  private raceStep(dt: number): void {
    const race = this.race!;
    const rivals = this.rivals.map((r) => ({ name: r.name, prog: r.s - START_S, out: false, finished: r.finished }));
    const { events, finished } = race.update(dt, this.car.pos.x, this.car.pos.z, rivals);
    for (const r of this.rivals) if (finished.includes(r.name)) r.finished = race.time;
    for (const e of events) this.onRace(e);
  }

  /** Each rival decides this frame's pedals and wheel from what's on the road round it. */
  private rivalsThink(dt: number): void {
    const race = this.race!;
    const go = race.phase !== 'countdown';
    const leader = START_S + race.prog;
    const pv = this.car.velocity(_vel);
    for (const r of this.rivals) {
      const c = r.car;
      const obstacles: Obstacle[] = this.traffic.nearby(c.pos.x, c.pos.z, 70, c.pos.y);
      if (Math.abs(this.car.pos.y - c.pos.y) < 3) obstacles.push({ x: this.car.pos.x, z: this.car.pos.z, vx: pv.x, vz: pv.z, len: 4.4, wid: 1.9 });
      for (const rp of this.world.ramps) {
        const x = rp.x + rp.dx * rp.len * 0.5;
        const z = rp.z + rp.dz * rp.len * 0.5;
        if (Math.abs(x - c.pos.x) < 90 && Math.abs(z - c.pos.z) < 90) obstacles.push({ x, z, vx: 0, vz: 0, len: rp.len, wid: rp.w, ramp: { dx: rp.dx, dz: rp.dz } });
      }
      for (const o of this.rivals) {
        if (o === r) continue;
        const ov = o.car.velocity(_v);
        obstacles.push({ x: o.car.pos.x, z: o.car.pos.z, vx: ov.x, vz: ov.z, len: 4.4, wid: 1.9 });
      }
      r.think(dt, race.route, this.world, go, leader, obstacles);
    }
  }

  /** A bump somewhere off the player's car: heard (and seen) less the further away it is. */
  private distantCrash(power: number, at: THREE.Vector3): void {
    const near = Math.max(0, 1 - at.distanceTo(this.car.pos) / 140);
    if (near <= 0) return;
    if (power > 3) sfxCrash(power * 0.7 * near);
    this.smoke.crash(at, Math.floor(power / 3));
  }

  /** Points for smashing things, gathered into one pop-up every so often. */
  private smash(points: number, label?: string): void {
    this.state.total += points;
    this.smashPoints += points;
    if (label) this.smashLabel = label;
  }

  /** Bumps and crashes with traffic. */
  private trafficHits(hits: TrafficHit[]): void {
    for (const h of hits) {
      if (h.player) {
        this.crash(h.power, _w.set(h.x, h.y, h.z));
        this.smash(h.wrecked ? 500 : Math.round(Math.min(150, h.power * 10)), h.wrecked ? 'Wrecked!' : 'Crunch');
      } else if (h.car) {
        // A rival into the traffic.
        this.distantCrash(h.power, _w.set(h.x, h.y, h.z));
      } else {
        sfxCrash(h.power * 0.6);
        this.smoke.crash(_w.set(h.x, h.y, h.z), Math.floor(h.power / 2));
        if (h.wrecked) this.smash(300, 'Pile-up!');
      }
    }
  }

  /** The light for the time of day (the same on every map). */
  private light(): void {
    this.setTimeOfDay(this.hours);
  }

  get timeOfDay(): number {
    return this.hours;
  }

  /**
   * Set the time of day (hours, 0 to 24): the sun rises in the east at six, is highest at
   * noon (70 degrees up) and sets in the west at six; the moon is opposite it. The sky
   * follows the sun's height; the light comes from the sun by day (warm white, orange low
   * down) and the moon by night (dim and blue), the sky's light and the haze take the
   * sky's own colours. (A day and night cycle can drive this later.)
   */
  setTimeOfDay(hours: number): void {
    this.hours = ((hours % 24) + 24) % 24;
    // Up and down with the hour; round from east through south (noon) to west.
    const arc = ((this.hours - 6) / 12) * Math.PI;
    const y = Math.sin(SUN_MAX_ELEVATION) * Math.sin(arc);
    const heading = SUN_NOON_HEADING + ((this.hours - 12) / 12) * Math.PI;
    const flat = Math.sqrt(Math.max(0, 1 - y * y));
    const toSun = new THREE.Vector3(Math.cos(heading) * flat, y, Math.sin(heading) * flat);
    this.sky.setSun(toSun);
    // The light: the sun when it's up, the moon (opposite) when it isn't; and the sky's
    // glow, which lingers through twilight (the sun down to about 6 degrees below).
    const day = smooth(-0.1, 0.22, y);
    const night = smooth(-0.02, -0.1, y);
    // (Twilight's glow: the sky still bright low down, though the sun has set.)
    const dusk = smooth(-0.32, -0.06, y) * smooth(0.12, -0.02, y);
    const fromSun = y > -0.02;
    const dir = fromSun ? toSun.clone() : toSun.clone().negate();
    // (Never so low the shadows stretch for ever; and the moonlight from well up, so the
    // streets are as lit just after dusk, the moon low, as at midnight.)
    dir.y = Math.max(dir.y, fromSun ? 0.14 : 0.6);
    this.sunDir.copy(dir.normalize());
    const low = smooth(0.0, 0.4, y);
    this.sun.color.setRGB(1, 0.55 + 0.4 * low, 0.3 + 0.55 * low, THREE.SRGBColorSpace);
    if (!fromSun) this.sun.color.setRGB(0.6, 0.68, 0.9, THREE.SRGBColorSpace);
    this.sun.intensity = fromSun ? 2.6 * smooth(-0.02, 0.22, y) : 0.45 * night;
    // The sky's light, and the haze in the distance: the sky's own colours.
    const zenith = Sky.zenith(y, new THREE.Color());
    const horizon = Sky.horizon(y, new THREE.Color());
    this.hemi.color.copy(zenith).lerp(horizon, 0.4 * dusk).lerp(new THREE.Color(1, 1, 1), 0.45 * day);
    this.hemi.groundColor.setRGB(0.48, 0.54, 0.36, THREE.SRGBColorSpace).multiplyScalar(0.4 + 0.6 * day);
    this.hemi.intensity = 0.55 + 0.6 * day + 1.4 * dusk;
    this.smoke.setLight(this.sun, this.hemi);
    // The lights: on as the sun sinks below about 3 degrees, full once it's as far under.
    this.lights = smooth(0.06, -0.06, y);
    this.applyLights();
    // The cars' reflections fade with the daylight.
    this.scene.environmentIntensity = 0.06 + 0.24 * day;
    (this.scene.fog as THREE.Fog).color.copy(horizon);
    (this.scene.background as THREE.Color).copy(horizon);
  }

  /**
   * Compile the new map's shaders in the background (where the browser can: otherwise
   * they compile as each first appears, a hitch each time).
   */
  private warmUp(): void {
    void this.renderer.compileAsync(this.scene, this.camera).catch(() => {});
  }

  /** Everything that lights up at night, to the lights' level now. */
  private applyLights(): void {
    const n = this.lights;
    NIGHT.value = n;
    setVehicleLights(n);
    // (Not yet, while the constructor first sets the time of day.)
    (this.car as Car | undefined)?.setNight(n);
    for (const r of this.rivals) r.car.setNight(n);
    this.lampClock = Infinity;
  }

  setPaint(color: number): void {
    this.car.setPaint(color);
  }

  /** The player's livery, made on first use. */
  get paint(): CarPaint {
    return (this.carPaint ??= new CarPaint(this.renderer, this.car.paintMeshes));
  }

  /** Paint the player's car: a design's marks over its base colour, or (null) plain paint. */
  setLivery(design: { base: number; ops: readonly PaintOp[] } | null): void {
    if (!design) {
      this.car.setLivery(null);
      return;
    }
    this.paint.replay(design.ops);
    this.car.setPaint(design.base);
    this.car.setLivery(this.paint);
  }

  /** Into the paint shop: the car on the studio's turntable, by day. */
  openGarage(): Garage {
    this.garage ??= new Garage();
    if (!this.inGarage) {
      this.inGarage = true;
      this.garage.open(this.car, this.renderer);
      NIGHT.value = 0;
      this.car.setNight(0);
      this.car.setLivery(this.paint);
    }
    return this.garage;
  }

  /** Back out of the paint shop, the car where it was. */
  closeGarage(): void {
    if (!this.inGarage) return;
    this.inGarage = false;
    this.garage!.close(this.car);
    this.applyLights();
  }

  /** Camera views: three chase distances, then the driver's seat (FIRST_PERSON). */
  setZoom(z: number): void {
    const views = ZOOMS.length + 1;
    this.zoom = ((z % views) + views) % views;
    if (this.zoom !== FIRST_PERSON) this.lastChase = this.zoom;
    // The shadow box covers the road ahead that the camera shows.
    const r = this.zoom === FIRST_PERSON ? 90 : ZOOMS[this.zoom]! * 2 + 30;
    const sc = this.sun.shadow.camera;
    sc.left = sc.bottom = -r;
    sc.right = sc.top = r;
    // Penumbra per unit of shadow depth, in shadow-map UV (see shadows.ts).
    this.sun.shadow.radius = ((sc.far - sc.near) * SUN_SOFTNESS) / (2 * r);
    sc.updateProjectionMatrix();
    this.resize();
    this.onZoom(this.zoom);
  }

  /** Jump between the driver's seat and the last chase view. */
  toggleFirstPerson(): void {
    this.setZoom(this.zoom === FIRST_PERSON ? this.lastChase : FIRST_PERSON);
  }

  get firstPerson(): boolean {
    return this.zoom === FIRST_PERSON && this.mode !== 'attract';
  }

  resize(): void {
    const el = this.canvas.parentElement ?? this.canvas;
    const w = Math.max(1, el.clientWidth);
    const h = Math.max(1, el.clientHeight);
    this.renderer.setSize(w, h, false);
    this.post?.setSize(w, h, this.pixelRatio * this.resScale);
    this.camera.aspect = w / h;
    // Keep a wide enough view in tall, narrow frames.
    if (this.firstPerson) {
      // From the seat: a wider view, and a near plane close enough for the dashboard.
      this.camera.fov = w / h < 0.8 ? 96 : 80;
      // Close enough that turning the head never slices through the roof lining, which is
      // under 20 cm above the driver's eyes.
      this.camera.near = 0.06;
    } else {
      this.camera.fov = w / h < 0.8 ? 62 : 50;
      this.camera.near = 1;
    }
    this.camera.updateProjectionMatrix();
    this.smoke.resize(h * this.pixelRatio * this.resScale, this.camera.fov);
  }

  start(): void {
    this.mode = 'drive';
    this.camYaw = this.car.yaw;
  }

  /** The road network of the map, for planning race routes on. */
  get roads(): RoadGraph {
    return this.traffic.roads;
  }

  /**
   * Start a race along route: the player and three rivals on a grid behind the start
   * line, the gates up, a countdown, then go.
   */
  startRace(route: RaceRoute, laps: number): void {
    this.endRace();
    const p = route.at(START_S, { x: 0, z: 0, tx: 0, tz: 1, hw: 4 });
    const off = Math.min(2.6, p.hw * 0.42);
    // Two rows of two: rivals at the front and on the left of the second row, the player on its right.
    const slots = [
      { s: START_S - 7, off: -off },
      { s: START_S - 7, off },
      { s: START_S - 17, off: -off },
      { s: START_S - 17, off },
    ];
    const me = slots[3]!;
    this.race = new RaceSession(route, laps, me.s - START_S);
    this.rivals = RIVALS.map((spec, i) => new Rival(spec, route, slots[i]!, this.world));
    this.applyLights();
    // (Their headlights are new lights: the shaders for them compiled in the background.)
    this.warmUp();
    for (const r of this.rivals) {
      this.scene.add(r.car.root);
      const shadow = contactShadow(4.4, 1.9);
      this.scene.add(shadow);
      this.rivalContacts.push(shadow);
      this.rivalSmoke.push(0);
    }
    // Traffic off the grid and the first stretch of the route.
    for (let d = 0; d < 260; d += 30) {
      const q = route.at(d, { x: 0, z: 0, tx: 0, tz: 1, hw: 4 });
      this.traffic.clearAround(q.x, q.z, 28);
    }
    this.gates = new RaceGates(this.world, route, this.race, this.roads);
    this.traffic.setBlocked(this.gates.blocked, this.car.pos);
    this.scene.add(this.gates.root);
    this.trail = new RaceTrail(route, this.world);
    this.scene.add(this.trail.mesh);
    const g = route.at(me.s, { x: 0, z: 0, tx: 0, tz: 1, hw: 4 });
    const x = g.x - g.tz * me.off;
    const z = g.z + g.tx * me.off;
    const yaw = Math.atan2(g.tx, g.tz);
    this.car.place(x, z, yaw, this.world.height(x, z, (g.y ?? 0) + 0.5));
    this.clearDrift();
    this.state.total = 0;
    this.camTarget.copy(this.car.pos);
    this.camYaw = yaw;
    this.orbit = 0;
    this.mode = 'drive';
  }

  /** Stop the race: the rivals and the gates go. */
  endRace(): void {
    for (const r of this.rivals) r.car.root.removeFromParent();
    for (const c of this.rivalContacts) c.removeFromParent();
    this.rivals = [];
    this.rivalContacts = [];
    this.rivalSmoke = [];
    this.gates?.dispose();
    this.trail?.dispose();
    this.trail = null;
    this.traffic.setBlocked([], this.car.pos);
    this.gates = null;
    this.race = null;
  }

  /** The race's state for the HUD, if one is on. */
  raceInfo(): RaceInfo | null {
    return this.race?.info() ?? null;
  }

  /** Put the car back on the nearest road, facing along it. */
  resetCar(): void {
    if (this.race) {
      // In a race: back on the route where you left it, facing the way it goes.
      const p = this.race.route.at(START_S + Math.max(this.race.prog, -20), { x: 0, z: 0, tx: 0, tz: 1, hw: 4 });
      const yaw = Math.atan2(p.tx, p.tz);
      this.loseDrift(false);
      this.car.place(p.x, p.z, yaw, this.world.height(p.x, p.z, (p.y ?? 0) + 0.5));
      this.camYaw = yaw;
      this.skids.mark(0, this.car.pos, 0);
      this.skids.mark(1, this.car.pos, 0);
      return;
    }
    const r = this.world.closestRoad(this.car.pos.x, this.car.pos.z);
    let yaw = Math.atan2(r.dx, r.dz);
    // Keep roughly the way it was facing.
    if (Math.cos(yaw - this.car.yaw) < 0) yaw += Math.PI;
    this.loseDrift(false);
    this.car.place(r.x, r.z, yaw, this.world.height(r.x, r.z));
    this.camYaw = yaw;
    this.skids.mark(0, this.car.pos, 0);
    this.skids.mark(1, this.car.pos, 0);
  }

  run(): void {
    const frame = (now: number) => {
      requestAnimationFrame(frame);
      const dt = Math.min(0.05, this.last ? (now - this.last) / 1000 : 0.016);
      this.last = now;
      this.tick(dt);
    };
    requestAnimationFrame(frame);
  }

  private tick(dt: number): void {
    const car = this.car;
    if (this.inGarage) {
      this.garage!.render(this.renderer, dt);
      setMenuMusic(true);
      return;
    }
    this.input.lookRange = this.firstPerson ? LOOK_INSIDE : LOOK_OUTSIDE;
    this.controls = this.input.read(dt);
    if (this.controls.pause) this.onPause();
    const held = this.race?.phase === 'countdown';
    if (this.mode === 'drive') {
      car.throttle = held ? 0 : this.controls.throttle;
      car.turning = this.controls.steer;
      car.handbrake = held || this.controls.handbrake;
      if (this.controls.reset) this.resetCar();
      if (this.controls.camera) this.setZoom(this.zoom + 1);
      if (this.controls.view) this.toggleFirstPerson();
    } else {
      car.throttle = car.turning = 0;
      car.handbrake = true;
    }
    this.world.update(dt);
    this.sky.update(dt);
    if (this.mode !== 'paused') {
      if (this.race) this.rivalsThink(dt);
      // Fixed small steps so fast slides never tunnel through a lamp post.
      this.acc += dt;
      let worst = 0;
      let landing = 0;
      const rivalBump = this.rivals.map(() => 0);
      while (this.acc >= STEP) {
        this.acc -= STEP;
        car.update(STEP, this.world);
        worst = Math.max(worst, car.bump);
        landing = Math.max(landing, car.landed);
        this.knockProps();
        this.rivals.forEach((r, i) => {
          r.car.update(STEP, this.world);
          rivalBump[i] = Math.max(rivalBump[i]!, r.car.bump);
          this.knockProps(r.car);
          // Into the player, and into each other.
          const hit = collideCars(car, r.car);
          if (hit > 2) {
            worst = Math.max(worst, hit);
            this.smoke.crash(_w.copy(car.pos).add(r.car.pos).multiplyScalar(0.5), Math.floor(hit / 2));
          }
          for (let k = i + 1; k < this.rivals.length; k++) {
            const bump = collideCars(r.car, this.rivals[k]!.car);
            if (bump > 2) this.distantCrash(bump, _w.copy(r.car.pos).add(this.rivals[k]!.car.pos).multiplyScalar(0.5));
          }
        });
      }
      this.rivals.forEach((r, i) => {
        if (rivalBump[i]! > 4) this.distantCrash(rivalBump[i]!, r.car.pos);
      });
      if (worst > 4) this.crash(worst);
      if (landing > 5) this.land(landing);
      this.effects(dt);
      this.rivals.forEach((r, i) => this.tyreMarks(dt, r.car, 10 + i * 2, i));
      this.score(dt);
      this.smoke.update(dt);
      this.clods.update(dt);
      this.debris.update(dt, this.world);
      this.spray.update(dt);
      if (this.race) this.raceStep(dt);
      this.trafficHits(this.traffic.update(dt, car, this.debris, this.rivals.map((r) => r.car)));
      // Wrecks smoke.
      this.wreckSmoke += dt;
      if (this.wreckSmoke > 0.2) {
        this.wreckSmoke = 0;
        for (const p of this.traffic.smoking()) if (p.distanceTo(car.pos) < 220) this.smoke.crash(p, 0);
      }
      // Smash points pop up together.
      this.smashClock += dt;
      if (this.smashPoints > 0 && this.smashClock > 0.7) {
        this.onEvent({ type: 'smash', points: this.smashPoints, label: this.smashLabel || 'Smash' });
        this.smashPoints = 0;
        this.smashLabel = '';
        this.smashClock = 0;
      }
    }
    // Tyre sound from how fast the rubber is sliding across the road (the sideways
    // slip, m/s): a moan as they scrub at the edge of grip, a full squeal once they're
    // sliding, louder at speed; a chirp under hard braking; and wheelspin squeal when the
    // throttle keeps the back wheels spinning in a slide (donuts, power slides). Silent
    // in the air.
    const ease = (a: number, b: number, x: number) => {
      const t = Math.max(0, Math.min(1, (x - a) / (b - a)));
      return t * t * (3 - 2 * t);
    };
    const slipping = Math.abs(car.slip);
    const moving = Math.min(1, Math.hypot(car.speed, car.slip) / 6);
    const air = car.airborne ? 0 : 1;
    const gas = Math.max(0, car.throttle);
    const scrub = ease(0.6, 3.5, slipping) * moving * air;
    const braking = car.throttle < -0.5 && car.speed > 12 ? 0.35 : 0;
    const slide = Math.max(ease(2.5, 11, slipping) * moving, braking) * air;
    const spin = car.sliding ? ease(3, 10, slipping) * ease(0.5, 1, gas) * (1 - Math.min(1, car.speed / 32) * 0.6) * air : 0;
    updateCarSound({
      rev: car.rev,
      gear: car.gear,
      shifting: car.shifting,
      throttle: Math.max(0, car.gear === 0 ? -car.throttle : car.throttle),
      scrub,
      slide,
      spin,
      speed: Math.hypot(car.speed, car.slip),
      paved: this.world.paved(car.pos.x, car.pos.z, car.pos.y),
      inside: this.firstPerson,
      running: this.mode === 'drive',
    });
    this.updateCamera(dt);
    this.buildingDetail.update(this.camera.position);
    // Music while in the menus (the start menu, the race planner, the results), not
    // while driving or paused.
    setMenuMusic(this.mode === 'attract');
    // The rivals' engines, from where the camera is.
    _w.set(1, 0, 0).applyQuaternion(this.camera.quaternion);
    updateRivalSounds(
      this.mode === 'drive' && this.race
        ? this.rivals.map((r) => {
            const dx = r.car.pos.x - this.camera.position.x;
            const dz = r.car.pos.z - this.camera.position.z;
            const dist = Math.hypot(dx, dz, r.car.pos.y - this.camera.position.y);
            return { rev: r.car.rev, throttle: Math.max(0, r.car.throttle), gear: r.car.gear, shifting: r.car.shifting, dist, pan: (dx * _w.x + dz * _w.z) / Math.max(1, Math.hypot(dx, dz)) };
          })
        : [],
    );
    this.placeContact();
    if (this.race && this.trail) {
      const r = this.race;
      this.trail.update(dt, r.prog, r.phase !== 'finished' && !r.offRoute, r.route.loop ? null : r.finishS + 4);
    }
    this.rivals.forEach((r, i) => this.placeShadow(this.rivalContacts[i]!, r.car));
    this.adaptResolution();
    this.adaptQuality();
    this.placeLampLights(dt);
    this.bakeLamps();
    this.renderer.shadowMap.needsUpdate = true;
    if (this.firstPerson) car.cockpit.renderMirrors(this.renderer, this.scene, car.cockpit.root.parent!.matrixWorld, this.tier === 'low');
    if (this.post && TIER[this.tier].post) this.post.render();
    else this.renderer.render(this.scene, this.camera);
  }

  /** The graphics setting: a tier, or Auto (from the medium tier, moving with the frame rate). */
  setQuality(q: Quality): void {
    this.quality = q;
    this.ceiling = 3;
    this.quickWindows = 0;
    this.applyTier(q === 'auto' ? 'medium' : q);
  }

  get graphics(): { quality: Quality; tier: Tier } {
    return { quality: this.quality, tier: this.tier };
  }

  /** Set everything a tier decides. */
  private applyTier(t: Tier): void {
    const was = this.tier;
    this.tier = t;
    const T = TIER[t];
    this.pixelRatio = Math.min(window.devicePixelRatio || 1, T.ratio);
    this.resScale = 1;
    this.renderer.setPixelRatio(this.pixelRatio);
    this.world.detailDistance = T.detail;
    this.world.setFacadeDetail(T.facade);
    // (Not yet, while the constructor first sets the tier.)
    (this.buildingDetail as BuildingDetail | undefined)?.setLevel(T.facade);
    // The shadows: a new map at the new size; the materials rebuilt if the filter changed.
    if (this.sun.shadow.mapSize.x !== T.shadowMap) {
      this.sun.shadow.mapSize.set(T.shadowMap, T.shadowMap);
      this.sun.shadow.map?.dispose();
      this.sun.shadow.map = null;
    }
    const type = T.soft ? THREE.PCFSoftShadowMap : THREE.PCFShadowMap;
    if (this.renderer.shadowMap.type !== type) {
      this.renderer.shadowMap.type = type;
      this.scene.traverse((o) => {
        const m = (o as THREE.Mesh).material;
        if (m) for (const x of Array.isArray(m) ? m : [m]) x.needsUpdate = true;
      });
    }
    // The shadow-casting lamp lights.
    if (this.lampLights.length !== T.lampShadows) {
      for (const l of this.lampLights) {
        this.scene.remove(l, l.target);
        l.shadow.map?.dispose();
        l.dispose();
      }
      this.lampLights = Array.from({ length: T.lampShadows }, () => {
        const l = new THREE.SpotLight(0xffc98a, 0, 20, 1.15, 0.85, 2);
        l.castShadow = true;
        l.shadow.mapSize.set(512, 512);
        l.shadow.bias = -0.0015;
        l.shadow.normalBias = 0.04;
        l.shadow.camera.near = 0.4;
        l.shadow.camera.far = 14;
        l.visible = false;
        this.scene.add(l, l.target);
        return l;
      });
      this.lampClock = Infinity;
    }
    if (T.post && !this.post) this.post = new Post(this.renderer, this.scene, this.camera);
    if (this.post) this.post.options = { ao: T.ao };
    this.resize();
    if (was !== t) this.onQuality(t);
  }

  /** The tier changed (Auto). */
  onQuality: (tier: Tier) => void = () => undefined;

  /**
   * Auto: while driving, after a few seconds' grace, every three seconds: frames slower
   * than about 42 a second step down a tier; quicker than about 75 a second, three times
   * running, step up one (never back up to a tier it's had to leave).
   */
  private adaptQuality(): void {
    if (this.quality !== 'auto' || this.mode !== 'drive') {
      this.qualityClock = 0;
      return;
    }
    this.qualityClock += this.frameMs;
    if (this.qualityClock < 3000) return;
    this.qualityClock = 0;
    const i = TIERS.indexOf(this.tier);
    if (this.frameMs > 24 && i > 0) {
      this.ceiling = i;
      this.quickWindows = 0;
      this.applyTier(TIERS[i - 1]!);
    } else if (this.frameMs < 13.5 && i + 1 < this.ceiling) {
      if (++this.quickWindows >= 3) {
        this.quickWindows = 0;
        this.applyTier(TIERS[i + 1]!);
      }
    } else this.quickWindows = 0;
  }

  /** Keep the car's contact shadow under it, fading as it leaves the ground. */
  private placeContact(): void {
    this.placeShadow(this.contact, this.car);
  }

  private placeShadow(shadow: THREE.Mesh, car: Car): void {
    const ground = this.world.height(car.pos.x, car.pos.z, car.pos.y);
    const up = Math.max(0, car.pos.y - ground);
    shadow.position.set(car.pos.x, ground + 0.08, car.pos.z);
    shadow.rotation.y = car.yaw;
    (shadow.material as THREE.MeshBasicMaterial).opacity = Math.max(0, 1 - up / 2.5);
    shadow.visible = up < 2.5;
  }

  /**
   * On a machine that can't keep up (frames slower than about 22 a second), draw at a
   * lower resolution, down to half; come back up once frames are quick again.
   */
  private adaptResolution(): void {
    const now = performance.now();
    const ms = this.lastFrame ? now - this.lastFrame : 16;
    this.lastFrame = now;
    if (ms <= 0 || ms > 3000) return;
    this.frameMs += (ms - this.frameMs) * 0.3;
    this.resClock += ms;
    if (this.resClock < 400) return;
    this.resClock = 0;
    if (this.tier !== 'low' && this.resScale === 1) return;
    let next = this.resScale;
    if (this.frameMs > 45) next = Math.max(0.5, next * 0.8);
    else if (this.frameMs < 25 && next < 1) next = Math.min(1, next * 1.1);
    if (next === this.resScale) return;
    this.resScale = next;
    this.renderer.setPixelRatio(this.pixelRatio * next);
    this.resize();
  }

  private crash(power: number, at?: THREE.Vector3): void {
    sfxCrash(power);
    this.shake = Math.min(1, power / 20);
    this.smoke.crash(at ?? this.car.local(0, Math.sign(this.car.speed || 1) * -2.2, _v), Math.floor(power));
    this.onEvent({ type: 'crash', power });
    if (power > 7) this.loseDrift(true);
  }

  /** Touching down after a jump: a thump, a jolt and a puff of dust. */
  private land(fall: number): void {
    sfxLand(fall);
    if (this.shakeEnabled) this.shake = Math.max(this.shake, Math.min(0.6, fall / 28));
    this.smoke.crash(this.car.pos, 2);
  }

  /** Small trees, bushes and lamp posts under the car fall over and slow it a little. */
  private knockProps(car: Car = this.car): void {
    const player = car === this.car;
    this.touched.clear();
    car.propsTouched(this.world, this.touched);
    if (!this.touched.size) return;
    // Flying high over them misses.
    if (car.pos.y - this.world.height(car.pos.x, car.pos.z, car.pos.y) > 1.2) return;
    car.velocity(_vel);
    const speed = Math.hypot(_vel.x, _vel.z);
    for (const p of this.touched) {
      let vx = _vel.x;
      let vz = _vel.z;
      // Barely moving: just nudge it away from the car.
      if (speed < 2) {
        vx = p.x - car.pos.x;
        vz = p.z - car.pos.z;
        const l = Math.hypot(vx, vz) || 1;
        vx = (vx / l) * 2;
        vz = (vz / l) * 2;
      }
      this.debris.add(this.world.knock(p), p, vx, vz);
      const lamp = this.world.lampIndexOf(p);
      if (lamp >= 0) this.lampBake?.take(lamp);
      const drag = KNOCK_DRAG[p.kind];
      car.speed *= drag;
      car.slip *= drag;
      if (player || car.pos.distanceTo(this.car.pos) < 80) sfxKnock(p.kind, player ? speed : speed * 0.5);
      // A broken hydrant gushes water.
      if (p.kind === 'hydrant') this.spray.burst(p.x, p.y, p.z);
      const light = drag > 0.95;
      this.smoke.crash(_w.set(p.x, p.y, p.z), light ? 0 : 3);
      if (!player) continue;
      if (!light) this.shake = Math.max(this.shake, Math.min(0.4, speed / 60));
      this.smash(KNOCK_POINTS[p.kind]);
    }
  }

  private effects(dt: number): void {
    this.tyreMarks(dt, this.car, 0, -1);
  }

  /** Skid marks (wheel ids base, base + 1) and tyre smoke from a car's back wheels; clock -1 is the player's. */
  private tyreMarks(dt: number, car: Car, base: number, clock: number): void {
    const braking = car.throttle < -0.15 && car.speed > 12;
    const strength = car.airborne ? 0 : car.drifting ? Math.min(1, Math.abs(car.slip) / 12) : braking ? 0.35 : car.handbrake && Math.abs(car.speed) > 6 ? 0.25 : 0;
    // What each back wheel's on: its marks and spray follow the ground.
    const grounds = REAR_WHEELS.map(([lx, lz], i) => {
      car.local(lx, lz, _v);
      _v.y = this.world.height(_v.x, _v.z, car.pos.y);
      const ground = this.world.groundAt(_v.x, _v.z, car.pos.y) ?? 'asphalt';
      this.skids.mark(base + i, _v, strength, ground);
      return ground;
    });
    let t = clock < 0 ? this.smokeClock : this.rivalSmoke[clock]!;
    if (car.drifting && !car.airborne) {
      t += dt;
      const every = 0.045 - Math.min(0.025, Math.abs(car.slip) * 0.0015);
      car.velocity(_vel);
      _back.set(-Math.sin(car.yaw), 0, -Math.cos(car.yaw));
      while (t > every) {
        t -= every;
        REAR_WHEELS.forEach(([lx, lz], i) => {
          const s = Math.min(1, Math.abs(car.slip) / 10);
          const ground = grounds[i]!;
          car.local(lx, lz, _w);
          this.smoke.tyre(_w, _back, _vel, s, ground);
          // On grass, mud and clumps of turf thrown up too.
          if (ground === 'grass') {
            _w.y = this.world.height(_w.x, _w.z, car.pos.y);
            this.clods.spray(_w, _back, _vel, s);
          }
        });
      }
    } else t = 0;
    if (clock < 0) this.smokeClock = t;
    else this.rivalSmoke[clock] = t;
  }

  private score(dt: number): void {
    const car = this.car;
    const st = this.state;
    st.speed = Math.hypot(car.speed, car.slip);
    st.drifting = car.drifting && car.speed > 4;
    st.angle = car.driftAngle;
    if (car.airborne) this.airTime += dt;
    else this.airTime = 0;
    st.air = this.airTime;
    // Hopping off a kerb isn't a jump.
    const flying = this.airTime > 0.2;
    if (st.drifting || flying) {
      // Faster and more sideways scores more, and so does air time; keeping it going
      // raises the multiplier.
      this.chainTime += dt;
      st.mult = Math.min(MAX_MULT, 1 + Math.floor(this.chainTime / MULT_STEP));
      st.multProgress = st.mult >= MAX_MULT ? 1 : (this.chainTime % MULT_STEP) / MULT_STEP;
      const sideways = Math.min(1, st.angle / 0.9);
      if (st.drifting) st.points += (st.speed / CAR_SPEED) * (0.4 + sideways) * 140 * st.mult * dt;
      if (flying) st.points += 160 * st.mult * dt;
      this.graceTime = 0;
    } else if (st.points > 0) {
      this.graceTime += dt;
      if (this.graceTime > GRACE) this.bank();
    }
    st.grace = st.points > 0 && !st.drifting ? Math.max(0, GRACE - this.graceTime) : GRACE;
    // How long each slide lasts, for the longest-drift board.
    if (st.drifting) {
      this.driftRun += this.driftGap + dt;
      this.driftGap = 0;
    } else if (this.driftRun > 0) {
      this.driftGap += dt;
      if (this.driftGap > DRIFT_GAP) {
        if (this.driftRun >= 0.5) this.onEvent({ type: 'drift', seconds: this.driftRun });
        this.driftRun = this.driftGap = 0;
      }
    }
  }

  private bank(): void {
    const st = this.state;
    const points = Math.round(st.points);
    const best = points > st.best;
    st.total += points;
    if (best) st.best = points;
    sfxBank(Math.min(1, points / 5000));
    this.onEvent({ type: 'bank', points, mult: st.mult, best });
    this.clearDrift();
  }

  private loseDrift(announce: boolean): void {
    const st = this.state;
    // (A slide that ends in a crash or a reset doesn't count.)
    this.driftRun = this.driftGap = 0;
    if (st.points > 0 && announce) {
      sfxLost();
      this.onEvent({ type: 'lost', points: Math.round(st.points) });
    }
    this.clearDrift();
  }

  private clearDrift(): void {
    const st = this.state;
    st.points = 0;
    st.mult = 1;
    st.multProgress = 0;
    this.chainTime = 0;
    this.graceTime = 0;
  }

  private updateCamera(dt: number): void {
    const car = this.car;
    car.velocity(_vel);
    const k = (rate: number) => 1 - Math.exp(-rate * dt);
    const fp = this.firstPerson;
    if (fp !== this.wasFirstPerson) {
      this.wasFirstPerson = fp;
      car.setCockpit(fp);
      this.camera.up.set(0, 1, 0);
      this.resize();
      // Climbing back out: pick the chase camera up from behind the car.
      this.camTarget.copy(car.pos);
      this.camYaw = car.yaw;
    }
    // Looking around (Q / E / F, mouse drag, right stick), inside or out: springs back when let go.
    const look = this.controls.look;
    // (The short way round: outside, the view can be dragged right round the car.)
    this.lookYaw = wrap(this.lookYaw + wrap(look.yaw - this.lookYaw) * k(8));
    this.lookPitch += (look.pitch - this.lookPitch) * k(8);
    if (fp) {
      // In the driver's seat: the view rides with the car (slopes and body roll
      // included) and turns a little towards where it's sliding.
      car.root.updateMatrixWorld(true);
      // Looking down, the head leans forward and down over the wheel to see the pedals.
      const lean = Math.max(0, -this.lookPitch);
      this.camera.position.set(Car.EYE.x, Car.EYE.y - lean * 0.12, Car.EYE.z + lean * 0.2).applyMatrix4(car.root.matrixWorld);
      const moving = Math.hypot(_vel.x, _vel.z);
      let heading = car.yaw;
      if (moving > 3 && car.speed > 0) heading += wrap(Math.atan2(_vel.x, _vel.z) - car.yaw) * 0.35;
      this.camYaw += wrap(heading - this.camYaw) * k(10);
      _w.set(0, 0, 1).transformDirection(car.root.matrixWorld);
      const p = this.camera.position;
      // Looking around turns the head from there. Sat on the left, the driver looks a touch towards the middle of the car, which
      // keeps both door mirrors in view.
      const yaw = this.camYaw + this.lookYaw - 0.12;
      const pitch = Math.asin(Math.max(-1, Math.min(1, _w.y))) - 0.1 + this.lookPitch;
      this.aim.set(p.x + Math.sin(yaw) * Math.cos(pitch) * 10, p.y + Math.sin(pitch) * 10, p.z + Math.cos(yaw) * Math.cos(pitch) * 10);
      this.camera.up.set(0, 1, 0).transformDirection(car.root.matrixWorld);
      if (this.shake > 0 && this.shakeEnabled) {
        const s = this.shake * this.shake * 0.15;
        p.x += (Math.random() - 0.5) * s;
        p.y += (Math.random() - 0.5) * s;
      }
      this.shake = Math.max(0, this.shake - dt * 2.5);
      this.camera.lookAt(this.aim);
      this.camTarget.copy(car.pos);
      this.followSun();
      return;
    }
    if (this.mode === 'attract') {
      // Slow orbit around the parked car behind the start menu.
      this.orbit += dt * 0.12;
      this.camYaw = car.yaw + this.orbit;
      this.camTarget.lerp(car.pos, k(4));
      this.camPitch += (0.62 - this.camPitch) * k(2);
      this.camDist += (44 - this.camDist) * k(2);
      this.aimAhead += (0 - this.aimAhead) * k(2);
    } else {
      // Swing round behind the car, leaning towards the way it's actually going so a
      // drift shows off the car's side.
      const moving = Math.hypot(_vel.x, _vel.z);
      let want = car.yaw;
      if (moving > 3 && car.speed > 0) {
        const travel = Math.atan2(_vel.x, _vel.z);
        want = car.yaw + wrap(travel - car.yaw) * 0.6;
      }
      this.camYaw += wrap(want - this.camYaw) * k(2.6);
      _v.copy(car.pos).addScaledVector(_vel, 0.35);
      this.camTarget.lerp(_v, k(6));
      const dist = ZOOMS[this.zoom]! * (1 + Math.min(1, moving / CAR_SPEED) * 0.12);
      this.camDist += (dist - this.camDist) * k(3);
      const ahead = this.camDist * 0.4 + Math.min(1, moving / CAR_SPEED) * 6;
      this.aimAhead += (ahead - this.aimAhead) * k(2);
      // Climb over buildings that would hide the car (seen from wherever it's being looked
      // at from: dragging the view swings the camera round).
      this.viewYaw = this.camYaw + this.lookYaw;
      let pitch = Math.max(0.04, Math.min(1.5, BASE_PITCH - this.lookPitch * 0.75));
      while (pitch < MAX_PITCH && this.blocked(pitch)) pitch += 0.08;
      this.camPitch += (pitch - this.camPitch) * k(pitch > this.camPitch ? 5 : 1.5);
    }
    // Dragging the view swings the chase camera round the car (and back when let go).
    const view = this.mode === 'attract' ? 0 : this.lookYaw;
    this.viewYaw = this.camYaw + view;
    this.placeCamera(this.camPitch, this.camera.position);
    // Never dip under a hill.
    const floor = this.world.height(this.camera.position.x, this.camera.position.z, this.car.pos.y) + 3;
    if (this.camera.position.y < floor) this.camera.position.y = floor;
    if (this.shake > 0 && this.shakeEnabled) {
      const s = this.shake * this.shake * 0.8;
      this.camera.position.x += (Math.random() - 0.5) * s;
      this.camera.position.y += (Math.random() - 0.5) * s;
      this.camera.position.z += (Math.random() - 0.5) * s;
    }
    this.shake = Math.max(0, this.shake - dt * 2.5);
    // Look past the car down the road; the car sits in the lower part of the view.
    // (Swung round, it looks back at the car rather than on down the road.)
    const ahead = this.aimAhead * Math.max(0, Math.cos(view));
    this.aim.set(this.camTarget.x + Math.sin(this.viewYaw) * ahead, this.camTarget.y + 1, this.camTarget.z + Math.cos(this.viewYaw) * ahead);
    this.camera.lookAt(this.aim);
    this.followSun();
  }

  /** Keep the sky round the camera and the sun's shadow box over the car and the road ahead. */
  /**
   * A few times a second at night: the shadow-casting lamp lights moved to the lit lamps
   * nearest the car (within 120 m), each hanging from its lamp's head and shining down;
   * those lamps' pools put out while they have a real light.
   */
  private placeLampLights(dt: number): void {
    const n = this.lights;
    this.lampClock += dt;
    if (this.lampClock < 0.25) return;
    this.lampClock = 0;
    const on = n > 0.01 && this.lampLights.length > 0;
    const lamps = on ? this.world.nearestLamps(this.car.pos, this.lampLights.length, 120) : [];
    // Those lamps' baked light out (their real light stands in), the others' back.
    const now = lamps.map((l) => l.index);
    for (const i of this.lampsLit) if (!now.includes(i)) this.lampBake?.give(i);
    for (const i of now) if (!this.lampsLit.includes(i)) this.lampBake?.take(i);
    this.lampsLit = now;
    // (All of them on all night, a spare one dark: three rebuilds its shaders whenever the
    // number of lights changes, so they only come and go at dusk and dawn.)
    this.lampLights.forEach((l, i) => {
      const lamp = lamps[i];
      l.visible = on;
      if (!lamp) {
        l.intensity = 0;
        return;
      }
      l.position.set(lamp.x, lamp.y, lamp.z);
      l.target.position.set(lamp.x, lamp.ground, lamp.z);
      l.target.updateMatrixWorld();
      l.intensity = n * lamp.power;
    });
  }

  /**
   * At night, every lamp's light baked a little at a time (nearest the car first), the
   * first night on each map; the small things culled again after (the bake shows them all).
   */
  private bakeLamps(): void {
    if (this.lights < 0.01) return;
    if (!this.lampBake) {
      const lamps = this.world.lamps;
      if (!lamps.length) return;
      const world = this.world;
      this.lampBake = new LampBake(this.renderer, world.root, lamps, () => world.showAllDetail());
      for (const i of this.lampsLit) this.lampBake.take(i);
    }
    if (this.lampBake.done) return;
    this.lampBake.step(this.car.pos);
    this.world.cull(this.camera.position);
  }

  private followSun(): void {
    this.sky.mesh.position.copy(this.camera.position);
    // (The small things far from the camera left undrawn.)
    this.world.cull(this.camera.position);
    // Snapped to whole shadow texels to stop shimmer.
    const texel = (this.sun.shadow.camera.right * 2) / this.sun.shadow.mapSize.x;
    const tx = Math.round((this.camTarget.x + this.aim.x) / 2 / texel) * texel;
    const tz = Math.round((this.camTarget.z + this.aim.z) / 2 / texel) * texel;
    const ty = this.camTarget.y;
    this.sun.target.position.set(tx, ty, tz);
    this.sun.position.set(tx + this.sunDir.x * 300, ty + this.sunDir.y * 300, tz + this.sunDir.z * 300);
  }

  private placeCamera(pitch: number, out: THREE.Vector3): THREE.Vector3 {
    const d = this.camDist;
    return out.set(
      this.camTarget.x - Math.sin(this.viewYaw) * Math.cos(pitch) * d,
      this.camTarget.y + 1 + Math.sin(pitch) * d,
      this.camTarget.z - Math.cos(this.viewYaw) * Math.cos(pitch) * d,
    );
  }

  /** Is the view from this pitch to the car cut by a building? */
  private blocked(pitch: number): boolean {
    this.placeCamera(pitch, _w);
    const tx = this.camTarget.x;
    const ty = this.camTarget.y + 1.2;
    const tz = this.camTarget.z;
    for (let i = 1; i <= 14; i++) {
      const t = i / 15;
      if (this.world.pointInside(tx + (_w.x - tx) * t, ty + (_w.y - ty) * t, tz + (_w.z - tz) * t)) return true;
    }
    return false;
  }
}

function wrap(a: number): number {
  return Math.atan2(Math.sin(a), Math.cos(a));
}

/** 0 below a, 1 above b, smoothly in between (b may be below a). */
function smooth(a: number, b: number, x: number): number {
  const t = Math.min(1, Math.max(0, (x - a) / (b - a)));
  return t * t * (3 - 2 * t);
}

export { PAINTS };