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/car.ts
import * as THREE from 'three';
import { withLampLight } from './night.js';
import { withLivery, type CarPaint, type LiveryUniforms } from './car-paint.js';
import { Cockpit, EYE } from './cockpit.js';
import type { Prop, World } from './world.js';

/**
 * The drift car. Its handling is Mini Samurai's toy car (W/S pedals, A/D wheel, a
 * handbrake that unsticks the tyres into a slide), scaled up to a full-size car: every
 * distance and speed is multiplied by SCALE, while turn rates and grip stay the same,
 * so it feels exactly like the toy, just bigger and faster.
 */

const SCALE = 2.2;
/** The tightest circle the car can turn on full lock without sliding, like a real car's (m). */
const TURN_RADIUS = 5.4;
/** Top speed in m/s: 165 km/h. */
export const CAR_SPEED = 165 / 3.6;
/** Fastest it backs up, in m/s (about 48 km/h). */
const REVERSE_SPEED = 6 * SCALE;
/** Pull from a standstill, in m/s² (fading towards top speed): 0-100 km/h in about 4 s. */
const ACCEL = 7.5;
/** How hard the brakes slow it, in m/s² (a little under 1 g). */
const BRAKING = 9;
/** Pull when backing up, in m/s². */
const REVERSE_ACCEL = 5;
const HALF_L = 2.2;
const HALF_W = 0.95;
/** The body is checked as three squares along its length. */
const PROBES = [-1.25, 0, 1.25];
const WHEEL_R = 0.38;
/** A bit stronger than real gravity, for snappier jumps. */
const GRAVITY = 18;
/**
 * Fastest a ramp can throw the car upwards, in m/s: what the steepest ramp gave at the
 * old 119 km/h top speed, so jumps stay as high as they were, just longer when faster.
 */
const MAX_LAUNCH = 14.5;
/** The road speed (m/s) each gear runs out at: 40, 72, 104 and 133 km/h. */
const GEAR_TOP = [12, 11, 20, 29, 37, Infinity];

export const PAINTS = [
  { name: 'Coral', color: 0xff4f5e },
  { name: 'Sunburst', color: 0xffb21e },
  { name: 'Mint', color: 0x2fc9a0 },
  { name: 'Ocean', color: 0x2f7fe0 },
  { name: 'Pearl', color: 0xf2f0ea },
  { name: 'Midnight', color: 0x2a2f3d },
];

const BOX = new THREE.BoxGeometry(1, 1, 1);

function box(parent: THREE.Object3D, x0: number, y0: number, z0: number, x1: number, y1: number, z1: number, m: THREE.Material): THREE.Mesh {
  const mesh = new THREE.Mesh(BOX, m);
  mesh.position.set((x0 + x1) / 2, (y0 + y1) / 2, (z0 + z1) / 2);
  mesh.scale.set(x1 - x0, y1 - y0, z1 - z0);
  mesh.castShadow = true;
  parent.add(mesh);
  return mesh;
}

/** A six-sided solid from its bottom and top rectangles (for the tapered cabin). */
function frustum(parent: THREE.Object3D, bottom: [number, number, number, number, number], top: [number, number, number, number, number], m: THREE.Material): THREE.Mesh {
  const [bx0, bx1, bz0, bz1, by] = bottom;
  const [tx0, tx1, tz0, tz1, ty] = top;
  const v = [
    [bx0, by, bz0], [bx1, by, bz0], [bx1, by, bz1], [bx0, by, bz1],
    [tx0, ty, tz0], [tx1, ty, tz0], [tx1, ty, tz1], [tx0, ty, tz1],
  ];
  const faces = [
    [3, 2, 6, 7], // front
    [1, 0, 4, 5], // back
    [2, 1, 5, 6], // right (+x)
    [0, 3, 7, 4], // left (-x)
    [7, 6, 5, 4], // top
  ];
  const pos: number[] = [];
  for (const [a, b, c, d] of faces) for (const i of [a, b, c, a, c, d]) pos.push(...v[i!]!);
  const g = new THREE.BufferGeometry();
  g.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
  g.computeVertexNormals();
  const mesh = new THREE.Mesh(g, m);
  mesh.castShadow = true;
  parent.add(mesh);
  return mesh;
}

export class Car {
  readonly root = new THREE.Group();
  readonly pos = new THREE.Vector3();
  yaw: number;
  /** Speed along its heading (negative when reversing). */
  speed = 0;
  /** Sideways slide across its heading: big while drifting on the handbrake. */
  slip = 0;
  /** Pedals and wheel this frame: throttle (W +1, S -1) and steering (D +1 right, A -1 left). */
  throttle = 0;
  turning = 0;
  /** The handbrake is pulled. */
  handbrake = false;
  /** How hard it hit something on the last step (0 if it didn't). */
  bump = 0;
  /** How fast its heading turned on the last step, for body roll and the camera. */
  yawRate = 0;
  /** Flying off a ramp. */
  airborne = false;
  /**
   * The back tyres have broken loose. Once sliding they stay loose (the throttle and
   * the wheel hold the angle) until the car is nearly straight again.
   */
  sliding = false;
  /** Vertical speed. */
  vy = 0;
  /** How fast it was falling when it touched down on the last step (0 if it didn't). */
  landed = 0;
  /** 0 reverse, 1 to 5 forward. Changes up and down by itself. */
  gear = 1;
  /** Seconds left in a gear change (clutch in, hand on the stick). */
  shifting = 0;
  /** Engine revs, 0 (idle) to about 1 (the red line). */
  rev = 0.2;

  /** The body (everything but the wheels), rolling and pitching on the car; its frame is the paint's. */
  readonly body = new THREE.Group();
  /** The paint-coloured parts of the bodywork: what a livery can be painted on. */
  readonly paintMeshes: THREE.Mesh[] = [];
  /** The white racing stripe, hidden under a livery. */
  private readonly stripes: THREE.Mesh[] = [];
  private livery: LiveryUniforms | null = null;
  private readonly paint: THREE.MeshStandardMaterial;
  private readonly brakeLights: THREE.MeshStandardMaterial;
  private lamps!: THREE.MeshStandardMaterial;
  /** The headlights' light: a spot from each lamp, ahead down the road, on at night. */
  private readonly beams = [-1, 1].map(() => new THREE.SpotLight(0xfff1d8, 0, 150, 0.5, 0.55, 2));
  /** The lights coming on at night (0 to 1): headlights bright, tail lights lit. */
  private night = 0;
  private readonly wheels: THREE.Object3D[] = [];
  private readonly frontWheels: THREE.Object3D[] = [];
  /** The glass and roof, hidden from the driver's seat so the view isn't blocked. */
  private readonly cabin: THREE.Object3D[] = [];
  /** The cabin, the driver's arms and legs and the working mirrors, seen from the driver's seat. */
  readonly cockpit!: Cockpit;
  private roll = 0;
  private pitch = 0;
  private slopePitch = 0;
  private slopeRoll = 0;
  private lastSpeed = 0;

  constructor(x: number, z: number, yaw: number, paint: number) {
    this.pos.set(x, 0, z);
    this.yaw = yaw;
    this.paint = new THREE.MeshStandardMaterial({ color: paint, metalness: 0.35, roughness: 0.35, flatShading: true });
    this.brakeLights = new THREE.MeshStandardMaterial({ color: 0xff3b30, emissive: 0xc8201a, emissiveIntensity: 0.6 });
    this.build();
    // The street lamps' light on the bodywork, as it passes under them.
    const mats = new Set<THREE.Material>();
    this.body.traverse((o) => {
      const m = (o as THREE.Mesh).material;
      if (m) for (const x of Array.isArray(m) ? m : [m]) if ((x as THREE.MeshStandardMaterial).isMeshStandardMaterial) mats.add(x);
    });
    for (const m of mats) withLampLight(m);
    this.body.traverse((o) => {
      if ((o as THREE.Mesh).isMesh && (o as THREE.Mesh).material === this.paint) this.paintMeshes.push(o as THREE.Mesh);
    });
    // The headlights' beams, one from each lamp, a little apart down the road ahead.
    this.beams.forEach((h, i) => {
      const side = i ? 1 : -1;
      h.position.set(side * 0.68, 0.67, 2.3);
      h.target.position.set(side * 1.2, -0.5, 32);
      h.visible = false;
      this.root.add(h, h.target);
    });
    this.sync();
  }

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

  /**
   * Show a livery (the player's paint job) over the paint, or none (null): plain paint
   * and the racing stripe. The first time, the paint's shader is given the livery.
   */
  setLivery(paint: CarPaint | null): void {
    if (!this.livery) {
      if (!paint) return;
      const u = (this.livery = withLivery(this.paint));
      // The paint's frame: the body's, wherever the car is.
      const keep = () => u.bodyInverse.value.copy(this.body.matrixWorld).invert();
      for (const m of this.paintMeshes) m.onBeforeRender = keep;
    }
    this.livery.on.value = !!paint;
    this.livery.map.value = paint?.livery.texture ?? null;
    this.livery.surface.value = paint?.surface ?? null;
    for (const m of this.stripes) m.userData.livery = !!paint;
    this.showStripes();
  }

  /** The stripe shows on plain paint (the roof's half not from the driver's seat). */
  private showStripes(): void {
    this.stripes.forEach((m, i) => (m.visible = !m.userData.livery && (i === 0 || !this.cockpit.visible)));
  }

  private build(): void {
    const b = this.body;
    this.root.add(b);
    const paint = this.paint;
    const black = new THREE.MeshStandardMaterial({ color: 0x1b1d22, roughness: 0.8, flatShading: true });
    const trim = new THREE.MeshStandardMaterial({ color: 0x2c3038, roughness: 0.6, flatShading: true });
    const glass = new THREE.MeshStandardMaterial({ color: 0x1c2a3a, metalness: 0.6, roughness: 0.15, flatShading: true });
    const chrome = new THREE.MeshStandardMaterial({ color: 0xd0d6dc, metalness: 0.8, roughness: 0.25, flatShading: true });
    const lamp = new THREE.MeshStandardMaterial({ color: 0xfff6d8, emissive: 0xffe7a0, emissiveIntensity: 0.8 });
    this.lamps = lamp;
    // Lower body, a sloping bonnet and boot, and side skirts.
    // The lower body is a tub: solid at the nose and tail, with the cabin open between its
    // sides (the glasshouse covers it from outside), so there's room inside for a driver.
    box(b, -HALF_W, 0.32, 1.14, HALF_W, 0.78, HALF_L, paint);
    box(b, -HALF_W, 0.32, -HALF_L, HALF_W, 0.78, -1.25, paint);
    box(b, 0.86, 0.32, -1.25, HALF_W, 0.78, 1.14, paint);
    box(b, -HALF_W, 0.32, -1.25, -0.86, 0.78, 1.14, paint);
    box(b, -0.86, 0.32, -1.25, 0.86, 0.36, 1.14, trim);
    frustum(b, [-HALF_W, HALF_W, 0.9, HALF_L, 0.78], [-HALF_W + 0.05, HALF_W - 0.05, 0.9, HALF_L - 0.25, 0.9], paint);
    frustum(b, [-HALF_W, HALF_W, -HALF_L, -1.25, 0.78], [-HALF_W + 0.05, HALF_W - 0.05, -HALF_L + 0.15, -1.25, 0.92], paint);
    box(b, -HALF_W - 0.03, 0.26, -1.6, -HALF_W + 0.05, 0.4, 1.6, trim);
    box(b, HALF_W - 0.05, 0.26, -1.6, HALF_W + 0.03, 0.4, 1.6, trim);
    // Cabin: tinted glass, with the roof and pillars in paint.
    this.cabin.push(frustum(b, [-0.86, 0.86, -1.25, 0.9, 0.78], [-0.68, 0.68, -0.85, 0.2, 1.36], glass));
    this.cabin.push(frustum(b, [-0.66, 0.66, -0.82, 0.17, 1.36], [-0.62, 0.62, -0.75, 0.1, 1.42], paint));
    // Bumpers, grille, lights.
    box(b, -HALF_W - 0.02, 0.28, HALF_L - 0.1, HALF_W + 0.02, 0.5, HALF_L + 0.06, trim);
    box(b, -HALF_W - 0.02, 0.28, -HALF_L - 0.06, HALF_W + 0.02, 0.5, -HALF_L + 0.1, trim);
    box(b, -0.45, 0.52, HALF_L - 0.02, 0.45, 0.7, HALF_L + 0.02, black);
    for (const x of [-0.68, 0.68]) {
      box(b, x - 0.2, 0.6, HALF_L - 0.04, x + 0.2, 0.74, HALF_L + 0.03, lamp);
      box(b, x - 0.22, 0.6, -HALF_L - 0.03, x + 0.22, 0.74, -HALF_L + 0.04, this.brakeLights);
    }
    // Rear wing.
    for (const x of [-0.6, 0.6]) box(b, x - 0.05, 0.92, -2.0, x + 0.05, 1.15, -1.9, trim);
    box(b, -HALF_W + 0.02, 1.15, -2.15, HALF_W - 0.02, 1.2, -1.82, trim);
    this.buildDetails(paint, black, trim, chrome);
    // Mirrors and a racing stripe.
    const stripe = new THREE.MeshStandardMaterial({ color: 0xf6f3ea, roughness: 0.5, flatShading: true });
    this.stripes.push(box(b, -0.12, 0.905, 0.9, 0.12, 0.915, HALF_L - 0.25, stripe));
    this.stripes.push(box(b, -0.12, 1.425, -0.75, 0.12, 1.435, 0.1, stripe));
    this.cabin.push(this.stripes[1]!);
    (this as { cockpit: Cockpit }).cockpit = new Cockpit(b, this.buildDoorMirrors(paint, trim));
    // Exhaust.
    const pipe = new THREE.Mesh(new THREE.CylinderGeometry(0.07, 0.07, 0.2, 8), chrome);
    pipe.rotation.x = Math.PI / 2;
    pipe.position.set(0.55, 0.3, -HALF_L - 0.08);
    b.add(pipe);
    // Wheels: chunky low-poly tyres with dished five-spoke rims.
    const tyreGeo = new THREE.CylinderGeometry(WHEEL_R, WHEEL_R, 0.3, 12);
    const rimGeo = new THREE.CylinderGeometry(WHEEL_R * 0.66, WHEEL_R * 0.66, 0.31, 12);
    const hubGeo = new THREE.CylinderGeometry(WHEEL_R * 0.16, WHEEL_R * 0.16, 0.34, 6);
    const dish = new THREE.MeshStandardMaterial({ color: 0x3a3e45, metalness: 0.5, roughness: 0.5, flatShading: true });
    const silver = new THREE.MeshStandardMaterial({ color: 0xc8ccd2, metalness: 0.3, roughness: 0.4, flatShading: true });
    for (const x of [-HALF_W + 0.1, HALF_W - 0.1])
      for (const z of [-1.35, 1.38]) {
        const w = new THREE.Group();
        w.position.set(x, WHEEL_R, z);
        w.rotation.order = 'YXZ';
        const tyre = new THREE.Mesh(tyreGeo, black);
        tyre.rotation.z = Math.PI / 2;
        tyre.castShadow = true;
        w.add(tyre);
        const rim = new THREE.Mesh(rimGeo, dish);
        rim.rotation.z = Math.PI / 2;
        w.add(rim);
        const hub = new THREE.Mesh(hubGeo, chrome);
        hub.rotation.z = Math.PI / 2;
        w.add(hub);
        // Spokes on the outer face.
        for (let k = 0; k < 5; k++) {
          const spoke = new THREE.Mesh(BOX, silver);
          const a = (k / 5) * Math.PI * 2;
          spoke.position.set(Math.sign(x) * 0.158, Math.cos(a) * WHEEL_R * 0.36, Math.sin(a) * WHEEL_R * 0.36);
          spoke.rotation.x = a;
          spoke.scale.set(0.02, WHEEL_R * 0.6, 0.07);
          w.add(spoke);
        }
        this.root.add(w);
        this.wheels.push(w);
        if (z > 0) this.frontWheels.push(w);
      }
  }

  /**
   * The bodywork's finer points, seen from outside: bolt-on flares round the wheel
   * arches, a front lip and rear diffuser, door shut lines and handles, pillars between
   * the side windows, number plates, indicators and bonnet vents.
   */
  private buildDetails(paint: THREE.Material, black: THREE.Material, trim: THREE.Material, chrome: THREE.Material): void {
    const b = this.body;
    const amber = new THREE.MeshStandardMaterial({ color: 0xffa634, emissive: 0x8a4a00, emissiveIntensity: 0.4 });
    const plate = new THREE.MeshStandardMaterial({ color: 0xf2efe4, roughness: 0.6 });
    // A bar from one point to another (in the body's frame), w wide across, d deep.
    const strut = (a: THREE.Vector3, c: THREE.Vector3, w: number, d: number, m: THREE.Material) => {
      const dir = c.clone().sub(a);
      const mesh = new THREE.Mesh(BOX, m);
      mesh.position.copy(a).add(c).multiplyScalar(0.5);
      mesh.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), dir.clone().normalize());
      mesh.scale.set(w, dir.length(), d);
      mesh.castShadow = true;
      b.add(mesh);
      return mesh;
    };
    for (const side of [-1, 1]) {
      const x = side * (HALF_W + 0.035);
      // Bolt-on over-fenders in paint, each with a dark lip round its arch.
      for (const z of [-1.35, 1.38]) {
        // Built round the arch (in front, behind and over the top), leaving the tyre in view.
        const [xa, xb] = [side * (HALF_W - 0.04), side * (HALF_W + 0.07)].sort((m, n) => m - n) as [number, number];
        box(b, xa, 0.42, z - 0.62, xb, 0.8, z - 0.4, paint);
        box(b, xa, 0.42, z + 0.4, xb, 0.8, z + 0.62, paint);
        box(b, xa, 0.77, z - 0.4, xb, 0.84, z + 0.4, paint);
        const pts = [-0.5, -0.36, 0, 0.36, 0.5].map((k) => new THREE.Vector3(x + side * 0.04, WHEEL_R + Math.sqrt(Math.max(0, 0.44 * 0.44 - k * k * 0.7)), z + k));
        pts[0]!.y = pts[pts.length - 1]!.y = 0.46;
        for (let i = 0; i + 1 < pts.length; i++) strut(pts[i]!, pts[i + 1]!, 0.02, 0.06, trim);
      }
      // Door shut lines, a handle, and the pillars between the windows.
      for (const z of [0.88, -0.38]) box(b, side * HALF_W - 0.006, 0.4, z - 0.012, side * HALF_W + 0.006, 0.77, z + 0.012, black);
      box(b, side * (HALF_W + 0.012) - 0.012, 0.66, -0.2, side * (HALF_W + 0.012) + 0.012, 0.69, -0.04, chrome);
      this.cabin.push(strut(new THREE.Vector3(side * 0.85, 0.79, -0.36), new THREE.Vector3(side * 0.675, 1.355, -0.36), 0.04, 0.1, paint));
      this.cabin.push(strut(new THREE.Vector3(side * 0.85, 0.79, 0.88), new THREE.Vector3(side * 0.675, 1.355, 0.18), 0.04, 0.07, paint));
      this.cabin.push(strut(new THREE.Vector3(side * 0.85, 0.79, -1.23), new THREE.Vector3(side * 0.675, 1.355, -0.83), 0.04, 0.12, paint));
      // Indicators at the front corners and a side repeater.
      box(b, side * 0.86 - 0.05, 0.6, HALF_L - 0.02, side * 0.86 + 0.05, 0.7, HALF_L + 0.035, amber);
      box(b, side * HALF_W - 0.01, 0.62, 1.55, side * HALF_W + 0.01, 0.66, 1.65, amber);
      // Bonnet vents either side of the stripe.
      for (const z of [1.3, 1.45, 1.6]) box(b, side * 0.3 - 0.13, 0.9, z, side * 0.3 + 0.13, 0.912, z + 0.06, black);
    }
    // A splitter under the nose, and a diffuser with fins under the tail.
    box(b, -HALF_W + 0.05, 0.22, HALF_L - 0.05, HALF_W - 0.05, 0.26, HALF_L + 0.14, black);
    box(b, -0.7, 0.22, -HALF_L - 0.12, 0.7, 0.26, -HALF_L + 0.1, black);
    for (const x of [-0.45, -0.15, 0.15, 0.45]) box(b, x - 0.015, 0.22, -HALF_L - 0.12, x + 0.015, 0.32, -HALF_L + 0.05, black);
    // Number plates.
    box(b, -0.26, 0.3, HALF_L + 0.06, 0.26, 0.42, HALF_L + 0.075, plate);
    box(b, -0.26, 0.55, -HALF_L - 0.025, 0.26, 0.67, -HALF_L - 0.01, plate);
  }

  /**
   * Door mirrors, like a normal car's: on a little sail at the front corner of each door
   * window, sticking out past the body. Returns their glass, left then right.
   */
  private buildDoorMirrors(paint: THREE.Material, trim: THREE.Material): THREE.Mesh[] {
    const b = this.body;
    const plain = new THREE.MeshStandardMaterial({ color: 0x9fb4c8, metalness: 0.9, roughness: 0.1, side: THREE.DoubleSide });
    return [1, -1].map((s) => {
      // The sail on the door, then the housing out on its arm.
      box(b, s * 0.9, 0.8, 0.72, s * 0.98, 0.92, 0.9, trim);
      box(b, s * 0.97, 0.86, 0.78, s * 1.02, 0.9, 0.86, trim);
      box(b, s * 1.0, 0.88, 0.76, s * 1.24, 1.04, 0.88, paint);
      const glass = new THREE.Mesh(new THREE.PlaneGeometry(1, 1), plain);
      glass.position.set(s * 1.12, 0.96, 0.755);
      glass.scale.set(0.22, 0.14, 1);
      b.add(glass);
      return glass;
    });
  }

  /** Switch between the outside view and the driver's seat. */
  setCockpit(on: boolean): void {
    if (this.cockpit.visible === on) return;
    this.cockpit.visible = on;
    for (const m of this.cabin) m.visible = !on;
    this.showStripes();
  }

  /** Where the driver's eyes are, in the car's own frame (x left, y up, z forward). */
  static readonly EYE = EYE;

  /** Would the car's body overlap anything solid here? */
  private blockedAt(world: World, x: number, z: number, yaw: number): boolean {
    const hx = Math.sin(yaw);
    const hz = Math.cos(yaw);
    for (const k of PROBES) if (world.squareBlocked(x + hx * k, z + hz * k, HALF_W, true, this.pos.y)) return true;
    return false;
  }

  /** Knockable props under the car's body right now. */
  propsTouched(world: World, out: Set<Prop>): void {
    const hx = Math.sin(this.yaw);
    const hz = Math.cos(this.yaw);
    for (const k of PROBES) world.propsIn(this.pos.x + hx * k, this.pos.z + hz * k, HALF_W, out, this.pos.y);
  }

  /** Move to the nearest spot (or heading) where the body fits, searching outward. */
  private escape(world: World): void {
    for (let r = 0.15 * SCALE; r <= 2.4 * SCALE; r += 0.15 * SCALE) {
      for (let i = 0; i < 16; i++) {
        const a = (i / 16) * Math.PI * 2;
        const x = this.pos.x + Math.cos(a) * r;
        const z = this.pos.z + Math.sin(a) * r;
        if (this.blockedAt(world, x, z, this.yaw)) continue;
        this.pos.x = x;
        this.pos.z = z;
        this.speed *= 0.3;
        this.slip = 0;
        return;
      }
    }
    for (let i = 1; i < 12; i++) {
      const yaw = this.yaw + (i / 12) * Math.PI;
      if (!this.blockedAt(world, this.pos.x, this.pos.z, yaw)) {
        this.yaw = yaw;
        return;
      }
    }
  }

  /** The back has let go and it's sliding at an angle, hard enough to smoke the tyres. */
  get drifting(): boolean {
    return this.sliding && Math.abs(this.slip) > 2.5 && this.driftAngle > 0.17;
  }

  /** The angle between where it points and where it's going, in radians. */
  get driftAngle(): number {
    return Math.atan2(Math.abs(this.slip), Math.abs(this.speed));
  }

  /** Put it down somewhere, stopped. */
  place(x: number, z: number, yaw: number, y = 0): void {
    this.pos.set(x, y, z);
    this.yaw = yaw;
    this.speed = this.slip = this.vy = 0;
    this.airborne = this.sliding = false;
    this.roll = this.pitch = this.slopePitch = this.slopeRoll = 0;
    this.sync();
  }

  /**
   * Drive one step like a car: W accelerates, S brakes and then reverses, A and D steer
   * (the wheels only turn it while it's rolling, and less sharply the faster it goes).
   * With no pedal it coasts to a stop.
   *
   * The handbrake locks the back wheels and they lose their sideways grip, so the car
   * swings out into a slide. A hard brake into a turn, or flooring it on full lock at low
   * speed, breaks them loose too. Once sliding, the back stays loose: steer into the turn
   * and stay on the throttle to hold the angle, counter-steer or lift off to straighten
   * up and grip again. A slide keeps most of its momentum.
   *
   * Hitting a wall square on bounces off it; at a glancing angle the car scrapes along.
   */
  update(dt: number, world: World): void {
    const pedal = this.throttle;
    const brake = this.handbrake;
    const air = this.airborne;
    const gas = pedal > 0.15;
    const braking = pedal < -0.15 && this.speed > 1;
    this.bump = 0;
    this.landed = 0;
    if (air) {
      // Wheels off the ground: no grip, no pedals, just a little air drag.
      this.speed *= Math.exp(-0.05 * dt);
    } else if (brake && pedal <= 0.15) {
      // Locked back wheels scrub off speed slowly.
      this.speed *= Math.exp(-0.7 * dt);
    } else if (gas) {
      // On the handbrake the throttle still pushes (a power slide), just a little less hard.
      // The pull fades a little towards top speed.
      // Sliding costs some pace: the spinning tyres push the car sideways as much as forward.
      const target = CAR_SPEED * Math.min(1, pedal / 0.6) * (brake ? 0.85 : this.sliding ? 0.85 : 1);
      let rate = (this.speed < 0 ? BRAKING : ACCEL) * (brake ? 0.75 : 1);
      if (this.speed > 0) rate *= 1 - 0.7 * Math.min(1, this.speed / target) ** 2;
      this.speed = this.speed < target ? Math.min(target, this.speed + rate * dt) : this.speed * Math.exp(-0.7 * dt);
    } else if (pedal < -0.15) {
      // Brake first, then back up (more slowly).
      const target = -REVERSE_SPEED * Math.min(1, -pedal / 0.6);
      const rate = this.speed > 0 ? BRAKING : REVERSE_ACCEL;
      this.speed = Math.max(target, this.speed - rate * dt);
    } else {
      // Rolling: engine braking and drag, stronger the faster it goes.
      const slow = (1.5 + 0.12 * Math.abs(this.speed)) * dt;
      this.speed = Math.abs(this.speed) <= slow ? 0 : this.speed - Math.sign(this.speed) * slow;
      if (Math.abs(this.speed) < 0.05) this.speed = 0;
    }
    // Steering: right turns clockwise seen from above; backing up swings the nose the other way.
    const wheel = Math.max(-1, Math.min(1, this.turning));
    const grounded = air ? 0 : 1;
    // The way the car is actually travelling, before it turns.
    const fx0 = Math.sin(this.yaw);
    const fz0 = Math.cos(this.yaw);
    const vx = fx0 * this.speed + fz0 * this.slip;
    const vz = fz0 * this.speed - fx0 * this.slip;
    if (this.blockedAt(world, this.pos.x, this.pos.z, this.yaw)) this.escape(world);
    const v = Math.hypot(this.speed, this.slip);
    // Slip angle: positive when the car is travelling to the left of where it points.
    const beta = Math.atan2(this.slip, Math.max(1, Math.abs(this.speed)));
    if (!air) {
      const brakeTurn = braking && Math.abs(wheel) > 0.5 && this.speed > 15;
      const donut = pedal > 0.8 && Math.abs(wheel) > 0.8 && this.speed > 3 && this.speed < 16;
      if (brake || brakeTurn || donut || Math.abs(beta) > 0.3) this.sliding = true;
      else if (Math.abs(beta) < 0.1 || v < 4) this.sliding = false;
    }
    const oldYaw = this.yaw;
    const dir = Math.sign(this.speed);
    if (this.sliding && !air) {
      // The wheel swings the tail; the tyres pull the nose back towards the way it's
      // going unless the throttle keeps the back wheels spinning.
      // (The tail swings it round tighter than the front wheels alone could, but it still
      // needs some way on to pivot.)
      const steer = Math.min((brake ? 3.0 : 2.6) / (1 + v / 40), v / (TURN_RADIUS * 0.5));
      const align = brake ? 1.0 : gas ? 1.6 - 1.4 * Math.min(1, pedal) : 1.6;
      this.yaw += (-wheel * steer * dir + align * beta) * dt;
    } else {
      // Gripping: the faster it goes, the wider it turns; slowly, it turns no tighter than
      // its front wheels on full lock allow, like a real car.
      const steer = Math.min(2.4 / (1 + Math.max(0, Math.abs(this.speed) - 8) / 18), Math.abs(this.speed) / TURN_RADIUS);
      this.yaw -= wheel * steer * grounded * dir * dt;
    }
    if (this.yaw !== oldYaw && this.blockedAt(world, this.pos.x, this.pos.z, this.yaw)) this.yaw = oldYaw;
    this.yawRate = (this.yaw - oldYaw) / dt;
    // Re-measure that travel against the new heading: what isn't along it is a slide,
    // which the tyres scrub away: fast while they grip, slowly once they've let go.
    const fx1 = Math.sin(this.yaw);
    const fz1 = Math.cos(this.yaw);
    this.speed = vx * fx1 + vz * fz1;
    let slip = vx * fz1 - vz * fx1;
    if (!air) {
      const scrub = !this.sliding ? 14 : brake ? 1.6 : gas ? 2.0 : braking ? 5 : 4.5;
      if (this.sliding && this.speed > 0) {
        // A slide keeps its momentum: what the tyres take out sideways mostly turns into
        // forward speed, less a little friction.
        const keep = Math.hypot(this.speed, slip) * Math.exp(-(brake ? 0.9 : gas ? 0.15 : 0.45) * dt);
        slip *= Math.exp(-scrub * dt);
        this.speed = Math.sqrt(Math.max(0, keep * keep - slip * slip));
      } else slip *= Math.exp(-scrub * dt);
    }
    this.slip = slip;
    for (const w of this.frontWheels) w.rotation.y += (-wheel * 0.5 - w.rotation.y) * Math.min(1, dt * 12);
    // Move, unless the bumper would hit something solid, or a face too tall to roll up
    // (the back or side of a ramp).
    // (Heights are for something at the car's height: on the highway, it's the deck.)
    const level = this.pos.y;
    const smoothBefore = world.smoothHeight(this.pos.x, this.pos.z, level);
    const rampBefore = world.rampHeight(this.pos.x, this.pos.z);
    const x0 = this.pos.x;
    const z0 = this.pos.z;
    const wall = (x: number, z: number) => this.blockedAt(world, x, z, this.yaw) || world.height(x, z, level) > this.pos.y + 0.35;
    let wx = fx1 * this.speed + fz1 * this.slip;
    let wz = fz1 * this.speed - fx1 * this.slip;
    const nx = this.pos.x + wx * dt;
    const nz = this.pos.z + wz * dt;
    if (wx !== 0 || wz !== 0) {
      if (!wall(nx, nz)) {
        this.pos.x = nx;
        this.pos.z = nz;
      } else {
        // Glance off it: the way out of whatever it hit (a curved barrier's face, say, at any
        // angle), the speed into it taken away (a little bounce back) and the speed along it
        // kept, less some scraping; the nose swings round to follow it the harder it hit.
        // Scraping along whichever axis is free, or bouncing back, if there's no face to read.
        const scrape = Math.exp(-1.5 * dt);
        const hx = Math.sin(this.yaw);
        const hz = Math.cos(this.yaw);
        let ox = 0;
        let oz = 0;
        for (const k of PROBES) {
          const n = world.pushOut(nx + hx * k, nz + hz * k, HALF_W + 0.05, this.pos.y);
          if (n) {
            ox += n.x;
            oz += n.z;
          }
        }
        const ol = Math.hypot(ox, oz);
        const vn = ol > 1e-6 ? (wx * ox + wz * oz) / ol : 0;
        if (ol > 1e-6 && vn < 0) {
          ox /= ol;
          oz /= ol;
          this.bump = -vn;
          const tx = (wx - vn * ox) * scrape;
          const tz = (wz - vn * oz) * scrape;
          wx = tx - vn * ox * 0.15;
          wz = tz - vn * oz * 0.15;
          // Swing the nose towards the way along the wall (backwards if reversing into it).
          const along = Math.hypot(tx, tz);
          if (along > 1) {
            let want = Math.atan2(tx, tz);
            if (this.speed < 0) want += Math.PI;
            const d = Math.atan2(Math.sin(want - this.yaw), Math.cos(want - this.yaw));
            const turn = Math.min(Math.abs(d), (0.4 + Math.min(1, -vn / 10) * 2.5) * dt) * Math.sign(d);
            if (!this.blockedAt(world, this.pos.x, this.pos.z, this.yaw + turn)) this.yaw += turn;
          }
          const mx = this.pos.x + wx * dt;
          const mz = this.pos.z + wz * dt;
          if (!wall(mx, mz)) {
            this.pos.x = mx;
            this.pos.z = mz;
          } else if (!wall(this.pos.x + ox * 0.05, this.pos.z + oz * 0.05)) {
            this.pos.x += ox * 0.05;
            this.pos.z += oz * 0.05;
          }
        } else if (!wall(nx, this.pos.z)) {
          this.bump = Math.abs(wz);
          this.pos.x = nx;
          wx *= scrape;
          wz *= -0.2;
        } else if (!wall(this.pos.x, nz)) {
          this.bump = Math.abs(wx);
          this.pos.z = nz;
          wz *= scrape;
          wx *= -0.2;
        } else {
          this.bump = Math.hypot(wx, wz);
          wx *= -0.3;
          wz *= -0.3;
        }
        // (Against the heading it has now: a glance may have swung it round.)
        const f = Math.sin(this.yaw);
        const g = Math.cos(this.yaw);
        this.speed = wx * f + wz * g;
        this.slip = wx * g - wz * f;
      }
    }
    // Up and down: follow the ground, carrying the climb of a ramp into the air off its
    // lip, then fall under gravity until the wheels touch again.
    const ground = world.height(this.pos.x, this.pos.z, level);
    if (air) {
      this.vy -= GRAVITY * dt;
      this.pos.y += this.vy * dt;
      if (this.pos.y <= ground) {
        this.landed = -this.vy;
        this.pos.y = ground;
        this.vy = 0;
        this.airborne = false;
      }
    } else {
      const fly = this.pos.y + this.vy * dt - 0.5 * GRAVITY * dt * dt;
      // It stays planted over gentle rises and ditch edges; only a sudden drop (a ramp's
      // lip, a kerb) or a sharp crest at speed lets go of it.
      if (fly > ground + 0.06) {
        this.airborne = true;
        this.pos.y = fly;
        this.vy -= GRAVITY * dt;
      } else {
        // Only smooth rises (ramps, the lie of the land) carry it upwards, never a kerb's edge.
        const rise = world.smoothHeight(this.pos.x, this.pos.z, level) - smoothBefore;
        // A rise steeper than any ramp is a step (a kerb, a seam), not a launch.
        const run = Math.hypot(this.pos.x - x0, this.pos.z - z0);
        // Ramps launch it at full climb; banks and rises in the ground only lift it
        // gently, so cutting over one at speed is a hop rather than a flight.
        const rampRise = world.rampHeight(this.pos.x, this.pos.z) - rampBefore;
        const groundRise = rise - rampRise;
        this.vy = run > 1e-4 && Math.abs(rise / run) > 0.6 ? 0 : Math.max(-20, Math.min(MAX_LAUNCH, rampRise / dt)) + Math.max(-20, Math.min(4, groundRise / dt));
        this.pos.y = ground;
      }
    }
    if (this.airborne) {
      // In the air the nose follows the arc and the body levels out.
      const arc = Math.max(-0.45, Math.min(0.45, Math.atan2(this.vy, Math.max(4, Math.abs(this.speed))) * 0.8));
      this.slopePitch += (arc - this.slopePitch) * Math.min(1, dt * 3);
      this.slopeRoll += (0 - this.slopeRoll) * Math.min(1, dt * 3);
    } else {
      // Tilted to the slope under the wheels.
      const hf = world.height(this.pos.x + fx1 * 1.4, this.pos.z + fz1 * 1.4, level);
      const hb = world.height(this.pos.x - fx1 * 1.4, this.pos.z - fz1 * 1.4, level);
      const hl = world.height(this.pos.x + fz1 * 0.9, this.pos.z - fx1 * 0.9, level);
      const hr = world.height(this.pos.x - fz1 * 0.9, this.pos.z + fx1 * 0.9, level);
      const slopePitch = Math.atan2(hf - hb, 2.8);
      this.slopePitch += (slopePitch - this.slopePitch) * Math.min(1, dt * 15);
      this.slopeRoll += (Math.atan2(hl - hr, 1.8) - this.slopeRoll) * Math.min(1, dt * 15);
      // Hills pull it back as it climbs and speed it up going down, unless it's parked.
      const parked = brake && pedal <= 0.15 && Math.abs(this.speed) < 2;
      if (!parked) this.speed -= 9.8 * Math.sin(slopePitch) * 0.7 * dt;
    }
    for (const w of this.wheels) w.rotation.x += (this.speed * dt) / WHEEL_R;
    // Body roll in turns and slides, and a squat or dive under the pedals.
    const accel = (this.speed - this.lastSpeed) / dt;
    this.lastSpeed = this.speed;
    const rollTarget = Math.max(-0.09, Math.min(0.09, this.yawRate * this.speed * 0.0016 - this.slip * 0.006));
    const pitchTarget = Math.max(-0.05, Math.min(0.05, -accel * 0.0025));
    this.roll += (rollTarget - this.roll) * Math.min(1, dt * 6);
    this.pitch += (pitchTarget - this.pitch) * Math.min(1, dt * 6);
    this.brakeLights.emissiveIntensity = pedal < -0.15 && this.speed > 0.5 ? 2.2 + this.night * 1.5 : brake ? 1.6 + this.night : 0.6 + this.night * 1.2;
    this.updateGear(dt, pedal);
    if (this.cockpit.visible) this.driveCockpit(dt, pedal, brake);
    this.sync();
  }

  /**
   * An automatic five-speed: up a gear as each runs out of road speed, down again a
   * little below that, and into reverse to back up. Each change takes a moment with the
   * clutch in. The revs climb through each gear's range.
   */
  private updateGear(dt: number, pedal: number): void {
    this.shifting = Math.max(0, this.shifting - dt);
    const s = this.speed;
    let g = this.gear;
    if (s < -0.5 || (Math.abs(s) < 0.5 && pedal < -0.15)) g = 0;
    else if (g === 0 && s > -0.1 && pedal > 0.15) g = 1;
    if (g > 0) {
      while (g < 5 && s > GEAR_TOP[g]!) g++;
      while (g > 1 && s < GEAR_TOP[g - 1]! - 3) g--;
    }
    if (g !== this.gear) {
      this.gear = g;
      this.shifting = 0.32;
    }
    const hi = g === 5 ? CAR_SPEED + 2 : g === 0 ? REVERSE_SPEED + 1 : GEAR_TOP[g]!;
    // Revs in proportion to road speed through each gear's ratio, as a real gearbox: the
    // red line at the gear's top speed, so an upshift drops the revs by the ratio step
    // (7000 in first lands around 4300 in second), never back to idle. 0.2 is idle.
    let target = 0.2 + Math.max(0, Math.min(1, Math.abs(s) / hi) - 0.12) / 0.88 * 0.75;
    // Pulling away, the clutch slips with the revs held up around 3500.
    if (g === 1 && this.throttle > 0.15) target = Math.max(target, 0.2 + 0.28 * Math.min(1, this.throttle / 0.6));
    // Spinning the tyres in a slide revs it higher; the clutch in lets them drop.
    if (this.drifting && this.throttle > 0.15) target += 0.15;
    // Mid-change the revs simply fall to the new gear's speed as the clutch comes up.
    this.rev += (target - this.rev) * Math.min(1, dt * 8);
  }

  /** Work the driver's hands and feet from the pedals, wheel and gearbox. */
  private driveCockpit(dt: number, pedal: number, handbrake: boolean): void {
    const reverse = this.gear === 0;
    const stopped = Math.abs(this.speed) < 1 && Math.abs(pedal) <= 0.15;
    this.cockpit.update(dt, {
      wheel: Math.max(-1, Math.min(1, this.turning)),
      gas: Math.max(0, reverse ? -pedal : pedal),
      brake: Math.max(0, reverse ? pedal : -pedal),
      clutch: this.shifting > 0 || handbrake || stopped ? 1 : 0,
      handbrake: handbrake ? 1 : 0,
      gear: this.gear,
      shifting: this.shifting,
      speed: Math.abs(this.speed) / CAR_SPEED,
      rev: this.rev,
    });
  }

  /** The lights coming on (0 by day to 1 at night): the headlights bright, the tail lights lit. */
  setNight(n: number): void {
    this.night = n;
    this.lamps.emissiveIntensity = 0.8 + n * 1.5;
    for (const h of this.beams) {
      h.intensity = n * 480;
      h.visible = n > 0.01;
    }
  }

  /** World position of a point given in the car's own frame (x left, z forward). */
  local(lx: number, lz: number, out: THREE.Vector3): THREE.Vector3 {
    const c = Math.cos(this.yaw);
    const s = Math.sin(this.yaw);
    return out.set(this.pos.x + lx * c + lz * s, this.pos.y, this.pos.z - lx * s + lz * c);
  }

  /** The car's velocity in the world. */
  velocity(out: THREE.Vector3): THREE.Vector3 {
    const fx = Math.sin(this.yaw);
    const fz = Math.cos(this.yaw);
    return out.set(fx * this.speed + fz * this.slip, 0, fz * this.speed - fx * this.slip);
  }

  /**
   * Set the car's velocity in the world (after a collision shoves it). Whatever isn't
   * along its heading becomes a slide, so a hard side-on hit breaks the tail loose.
   */
  setVelocity(vx: number, vz: number): void {
    const fx = Math.sin(this.yaw);
    const fz = Math.cos(this.yaw);
    this.speed = vx * fx + vz * fz;
    this.slip = vx * fz - vz * fx;
    if (Math.abs(this.slip) > 4) this.sliding = true;
  }

  private sync(): void {
    this.root.position.copy(this.pos);
    this.root.rotation.set(-this.slopePitch, this.yaw, this.slopeRoll, 'YXZ');
    this.body.rotation.set(this.pitch, 0, this.roll);
  }
}

export const REAR_WHEELS: readonly [number, number][] = [
  [-HALF_W + 0.1, -1.35],
  [HALF_W - 0.1, -1.35],
];