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/city-plan.ts
import * as THREE from 'three';
import { rng } from './geo.js';

/**
 * The City map's layout, worked out before anything is built: where the streets run,
 * which district each block is in, the river, the raised highway with its ramps, and
 * the curving streets of the suburbs. Pure geometry: the World builds from it.
 *
 * The south quarter of the map (z below COUNTRY_Z) is countryside; everything north of
 * it is city, ringed by a straight boulevard (the outermost grid lines) and, outside
 * that, the highway loop. Four districts:
 *
 * - Downtown, in the middle and north to z = DOWNTOWN_Z1: towers and older low-rise.
 * - Old Town, the band beyond it to the north: narrow terraced houses, two or three
 *   storeys, with tall gables to the street.
 * - Industrial, to the east and along the south edge: warehouses, sheds, tanks and stacks,
 *   on blocks twice as long (every other cross street left out).
 * - Suburbs, to the west: houses on lawns along gently curving streets, the blocks twice
 *   as long north to south as the grid's.
 *
 * The river comes down out of the southern mountains, across the countryside, north
 * through Downtown and Old Town, and out past the highway to the sea in the north-east,
 * where the coast has a beach and a port. Streets crossing it at a decent angle get
 * bridges; the rest stop short of it.
 *
 * The highway is DECK_Y up: a loop round the city with wide, smooth corners, and a
 * crosstown run straight through the middle (over the street at z = CROSS_Z) that forks
 * at each end into two long curves joining the loop either way. On and off ramps lead
 * down from the loop to the boulevard.
 *
 * The Test map (LAYOUT 'test', see useLayout) is a small version for trying things out:
 * four blocks of each district round a short river with one bridge, a small highway loop
 * with one off and one on ramp, and a curvy country road (see World): the Suburbs and Old
 * Town in a column each to the west, the river down the middle, the Industrial district
 * and Downtown two by two to the east.
 */

export interface P3 {
  x: number;
  y: number;
  z: number;
}

export type District = 'downtown' | 'oldtown' | 'industrial' | 'suburbs';

/** Which map the plan is for: the City, or the small Test map. Set by useLayout. */
export type LayoutId = 'city' | 'test';
export let LAYOUT: LayoutId = 'city';

/** Streets every 80 m from `from`, `n` of them. */
const gridLines = (from: number, n: number): readonly number[] => Array.from({ length: n }, (_, i) => from + i * 80);
/** The grid: streets every 80 m, x from -720 to 720 and z from -400 to 720 (Test: x from -200 to 200, z from -160 to 160). */
export let XS = gridLines(-720, 19);
export let ZS = gridLines(-400, 15);
export const STREET_HW = 8;
/** The city, out to the far kerb of the boulevard. */
export let CITY = { x0: -720 - STREET_HW, x1: 720 + STREET_HW, z0: -400 - STREET_HW, z1: 720 + STREET_HW };
/** The suburbs lie west of this street (which is still a straight grid street). */
export let SUBURB_EDGE = -240;
/** Countryside south of this. */
export let COUNTRY_Z = -480;
/** The suburbs' curving streets: one lane each way. */
export const LANE_HW = 5.5;

/** Highway deck height, and half-widths of the highway (two lanes each way) and its ramps. */
export const DECK_Y = 9;
/** A deck's thickness (road surface to underside), and the clear height kept under any deck over a road. */
export const DECK_DEPTH = 1.2;
export const HEADROOM = 4.6;
/** The steepest an underpass dips (rise over run). */
const SLOPE = 0.055;
export const HIGHWAY_HW = 9;
export const RAMP_HW = 4;
/** The one-way curves between the crosstown and the loop: two lanes, and how far right of the highway's middle they run (the middle of its two right-hand lanes). */
export const ONEWAY_HW = 5.6;
export const LANE_SHIFT = 3.6;
/** The highway's outer lane, right of its middle: where a ramp leaves it. */
export const LANE_OUTER = 5.4;
/** The crosstown highway runs over this street. */
export const CROSS_Z = 160;
/** The loop: a rounded rectangle. */
let LOOP = { x0: -800, x1: 800, z0: -470, z1: 800, r: 260 };
/** Where the crosstown forks, and the radius of the curves from the fork onto the loop. */
const FORK_X = 560;
const FORK_R = 800 - FORK_X;

export const RIVER_HW = 14;
/** The riverside roads run this far out from the middle of the river (past a 3 m walk). */
export const BANK_D = RIVER_HW + 3 + LANE_HW;
/** How far the river's corridor reaches: to the far side of the riverside road's pavement. */
export const RIVER_REACH = BANK_D + LANE_HW + 3;
/** The radius of a street's curve round a corner. */
export const CORNER_R = 22;

/** A stretch of grid street: along z (x = s) or along x (z = s), from p0 to p1; whether each end is at a crossing. */
export interface Piece {
  key: string;
  alongZ: boolean;
  s: number;
  p0: number;
  p1: number;
  end0: boolean;
  end1: boolean;
  bridge: boolean;
}
/**
 * The City map reaches further east and north than the Country map (which is HALF either
 * way, square), for the coast: the far edges of its playable ground.
 */
export let CITY_EXTENT = { x1: 1200, z1: 1290 };

/**
 * Set the layout for the next plan: the grid, the city's edges, the countryside's, the
 * highway loop and the map's far edges. (The World sets it before it makes its CityPlan.)
 */
export function useLayout(id: LayoutId): void {
  LAYOUT = id;
  const test = id === 'test';
  XS = test ? gridLines(-200, 6) : gridLines(-720, 19);
  ZS = test ? gridLines(-160, 5) : gridLines(-400, 15);
  CITY = { x0: XS[0]! - STREET_HW, x1: XS[XS.length - 1]! + STREET_HW, z0: ZS[0]! - STREET_HW, z1: ZS[ZS.length - 1]! + STREET_HW };
  SUBURB_EDGE = test ? -120 : -240;
  COUNTRY_Z = test ? -230 : -480;
  CITY_EXTENT = test ? { x1: 400, z1: 280 } : { x1: 1200, z1: 1290 };
  // (Test: its straight north side just long enough for the two ramps, which land on the
  // boulevard crossings at x = -120 and 120.)
  LOOP = test ? { x0: -345, x1: 345, z0: -221, z1: 221, r: 65 } : { x0: -800, x1: 800, z0: -470, z1: 800, r: 260 };
}
/** The quay: a straight stretch of the coast in the north-east, from QUAY_A to QUAY_B. */
export const QUAY_A = { x: 1090, z: 630 };
export const QUAY_B = { x: 880, z: 880 };
/** Along the quay (unit), and out from it to sea (unit), and its length. */
const QL = Math.hypot(QUAY_B.x - QUAY_A.x, QUAY_B.z - QUAY_A.z);
export const QUAY = {
  ax: (QUAY_B.x - QUAY_A.x) / QL,
  az: (QUAY_B.z - QUAY_A.z) / QL,
  nx: (QUAY_B.z - QUAY_A.z) / QL,
  nz: -(QUAY_B.x - QUAY_A.x) / QL,
  len: QL,
};
/** A point's place in the port: t along the quay from QUAY_A, u inland from its edge. */
export function portFrame(x: number, z: number): { t: number; u: number } {
  const dx = x - QUAY_A.x;
  const dz = z - QUAY_A.z;
  return { t: dx * QUAY.ax + dz * QUAY.az, u: -(dx * QUAY.nx + dz * QUAY.nz) };
}
/** The point t along the quay and u inland. */
export function portPoint(t: number, u: number): { x: number; z: number } {
  return { x: QUAY_A.x + QUAY.ax * t - QUAY.nx * u, z: QUAY_A.z + QUAY.az * t - QUAY.nz * u };
}

/** The coastline, from the south-east round to the north-west, the sea on its left (north-east). */
export class Coast {
  readonly pts: { x: number; z: number }[] = [];
  private readonly line: Line | null = null;
  /** Every tenth point, reaching much further, for the rough side of far-off points. */
  private readonly far: Line | null = null;
  /** No coast at all (the Test map): everywhere is far inland. */
  constructor(none = false) {
    if (none) return;
    const smooth = (ctrl: [number, number][], step: number) => {
      const c = new THREE.CatmullRomCurve3(
        ctrl.map(([x, z]) => new THREE.Vector3(x, 0, z)),
        false,
        'centripetal',
      );
      return c.getSpacedPoints(Math.round(c.getLength() / step)).map((p) => ({ x: p.x, z: p.z }));
    };
    // In from the east edge to the quay; the quay, straight; on round past the river's
    // mouth to the north edge.
    const before = smooth(
      [
        [2100, 80],
        [1500, 380],
        [1250, 520],
        [1135, 597],
        [QUAY_A.x, QUAY_A.z],
      ],
      6,
    );
    const quay = Array.from({ length: Math.round(QL / 6) + 1 }, (_, k) => portPoint((k / Math.round(QL / 6)) * QL, 0));
    const after = smooth(
      [
        [QUAY_B.x, QUAY_B.z],
        [832, 948],
        [770, 1040],
        [690, 1128],
        [600, 1205],
        [480, 1290],
        [330, 1420],
        [60, 2100],
      ],
      6,
    );
    this.pts = [...before.slice(0, -1), ...quay, ...after.slice(1)];
    this.line = new Line(this.pts, 100);
    this.far = new Line(
      this.pts.filter((_, i) => i % 10 === 0),
      800,
      160,
    );
  }

  /** How far out to sea (x, z) is: positive in the sea, negative on land. */
  seaDist(x: number, z: number): number {
    if (!this.line || !this.far) return -1e4;
    const fine = this.line.nearest(x, z);
    const n = fine ?? this.far.nearest(x, z);
    const pts = fine ? this.pts : this.far.pts;
    if (!n) {
      // Far from the coast: which side of the quay's line.
      const dx = x - QUAY_A.x;
      const dz = z - QUAY_A.z;
      return dx * QUAY.nx + dz * QUAY.nz;
    }
    const a = pts[n.i]!;
    const b = pts[n.i + 1]!;
    const cross = (b.x - a.x) * (z - a.z) - (b.z - a.z) * (x - a.x);
    return cross < 0 ? n.d : -n.d;
  }
}

/** Downtown runs north as far as this street; Old Town is beyond it. */
export const DOWNTOWN_Z1 = 480;

export function districtAt(x: number, z: number): District | null {
  if (x < CITY.x0 || x > CITY.x1 || z < CITY.z0 || z > CITY.z1) return null;
  if (x < SUBURB_EDGE - STREET_HW) return 'suburbs';
  // Test: Old Town west of the river, the Industrial district south of the middle street
  // east of it, Downtown north.
  if (LAYOUT === 'test') return x < 0 ? 'oldtown' : z < 0 ? 'industrial' : 'downtown';
  if (Math.abs(x) <= 240 + STREET_HW && z >= -240 - STREET_HW && z <= DOWNTOWN_Z1 + STREET_HW) return 'downtown';
  if (x > 240 + STREET_HW) return 'industrial';
  if (z > DOWNTOWN_Z1 + STREET_HW) return 'oldtown';
  return 'industrial';
}

/** A polyline with a spatial index, for distance queries. */
export class Line {
  readonly cum: number[] = [0];
  readonly len: number;
  private readonly cells = new Map<number, number[]>();

  constructor(
    readonly pts: { x: number; z: number }[],
    reach: number,
    private readonly cell = 40,
  ) {
    for (let i = 1; i < pts.length; i++) this.cum.push(this.cum[i - 1]! + Math.hypot(pts[i]!.x - pts[i - 1]!.x, pts[i]!.z - pts[i - 1]!.z));
    this.len = this.cum[this.cum.length - 1]!;
    for (let i = 0; i + 1 < pts.length; i++) {
      const a = pts[i]!;
      const b = pts[i + 1]!;
      const x0 = Math.floor((Math.min(a.x, b.x) - reach) / cell);
      const x1 = Math.floor((Math.max(a.x, b.x) + reach) / cell);
      const z0 = Math.floor((Math.min(a.z, b.z) - reach) / cell);
      const z1 = Math.floor((Math.max(a.z, b.z) + reach) / cell);
      for (let cx = x0; cx <= x1; cx++)
        for (let cz = z0; cz <= z1; cz++) {
          const k = (cx + 1000) * 4096 + cz + 1000;
          let list = this.cells.get(k);
          if (!list) this.cells.set(k, (list = []));
          list.push(i);
        }
    }
  }

  /** The nearest point within reach: distance, how far along, and the segment. */
  nearest(x: number, z: number): { d: number; s: number; i: number; t: number } | null {
    const list = this.cells.get((Math.floor(x / this.cell) + 1000) * 4096 + Math.floor(z / this.cell) + 1000);
    if (!list) return null;
    let best: { d: number; s: number; i: number; t: number } | null = null;
    for (const i of list) {
      const a = this.pts[i]!;
      const b = this.pts[i + 1]!;
      const vx = b.x - a.x;
      const vz = b.z - a.z;
      const l2 = vx * vx + vz * vz || 1;
      const t = Math.max(0, Math.min(1, ((x - a.x) * vx + (z - a.z) * vz) / l2));
      const d = Math.hypot(x - a.x - vx * t, z - a.z - vz * t);
      if (!best || d < best.d) best = { d, s: this.cum[i]! + Math.sqrt(l2) * t, i, t };
    }
    return best;
  }

  /** Distance to the line (Infinity beyond reach). */
  dist(x: number, z: number): number {
    return this.nearest(x, z)?.d ?? Infinity;
  }
}

/** A stretch of raised road. */
export interface Deck {
  pts: P3[];
  hw: number;
  kind: 'highway' | 'ramp';
  closed: boolean;
  /** Traffic goes only the way the points run (1), only the other way (-1), or both (0). */
  oneway: 1 | -1 | 0;
}

/** One straight piece of a deck, for height and footprint queries. */
interface DeckSeg {
  ax: number;
  ay: number;
  az: number;
  bx: number;
  by: number;
  bz: number;
  hw: number;
  deck: number;
  /** The first or last piece of a deck that ends (not a closed loop). */
  first: boolean;
  last: boolean;
}

/** Evenly spaced points (about every `step` m) along a curve given densely. */
function respace(dense: { x: number; z: number }[], step: number): { x: number; z: number; s: number }[] {
  const cum = [0];
  for (let i = 1; i < dense.length; i++) cum.push(cum[i - 1]! + Math.hypot(dense[i]!.x - dense[i - 1]!.x, dense[i]!.z - dense[i - 1]!.z));
  const total = cum[cum.length - 1]!;
  const n = Math.max(1, Math.round(total / step));
  const out: { x: number; z: number; s: number }[] = [];
  let j = 1;
  for (let k = 0; k <= n; k++) {
    const s = (k / n) * total;
    while (j < dense.length - 1 && cum[j]! < s) j++;
    const a = dense[j - 1]!;
    const b = dense[j]!;
    const f = (s - cum[j - 1]!) / (cum[j]! - cum[j - 1]! || 1);
    out.push({ x: a.x + (b.x - a.x) * f, z: a.z + (b.z - a.z) * f, s });
  }
  return out;
}

export class CityPlan {
  /** Grid street pieces left out: 'x:i:j' (along x = XS[i], from ZS[j] to ZS[j+1]) and 'z:j:i'. */
  private readonly removed = new Set<string>();
  /** Grid pieces cut short by the river (or a curved corner): the stretches kept. */
  private readonly cut = new Map<string, [number, number][]>();
  /** The bridges: streets along z = s from x = a to x = b, from one riverside road to the other. */
  readonly spans: { s: number; a: number; b: number }[] = [];
  /** Crossings made into curved corners ('i:j'). */
  private readonly rounded = new Set<string>();
  /** The riverside roads, one along each bank, split where bridges cross them. */
  readonly banks: { x: number; z: number }[][] = [];
  private bankLines: Line[] = [];
  /** The curved corners' centre lines. */
  readonly corners: { x: number; z: number }[][] = [];
  private cornerLines: Line[] = [];
  readonly river: Line;
  /** The river again, coarser and reaching further: for the level valley it runs along. */
  readonly valley: Line;
  readonly coast = new Coast(LAYOUT !== 'city');
  /** The river's centre line from its mouth to the south edge, densely. */
  readonly riverPts: { x: number; z: number }[];
  readonly decks: Deck[] = [];
  private readonly deckSegs: DeckSeg[] = [];
  private readonly deckCells = new Map<number, DeckSeg[]>();
  /** The suburbs' curving streets, each from one junction to the next. */
  readonly lanes: { x: number; z: number }[][] = [];
  /** Where suburb streets meet. */
  readonly laneNodes: { x: number; z: number }[] = [];

  constructor() {
    // The river, from its mouth up: out of the sea, west past the north side of the
    // highway, south through Old Town and Downtown (mostly down the middle of a row of
    // blocks, crossing the north-south streets on the slant), under the south boulevard
    // and the loop, and away south across the countryside into the mountains.
    //
    // Through the city it's laid exactly as it always was (the streets are cut round it);
    // the stretch out to the sea and the one up into the mountains are joined on to that,
    // running on smoothly from it.
    const spaced = (ctrl: [number, number][]) => {
      const curve = new THREE.CatmullRomCurve3(
        ctrl.map(([x, z]) => new THREE.Vector3(x, 0, z)),
        false,
        'centripetal',
      );
      return respace(
        curve.getSpacedPoints(800).map((p) => ({ x: p.x, z: p.z })),
        3,
      ).map(({ x, z }) => ({ x, z }));
    };
    if (LAYOUT === 'test') {
      // Test: straight down the middle of the town (the column of blocks it takes, x from
      // -40 to 40), bending a little either way out beyond the highway into the mountains.
      this.riverPts = spaced([
        [-40, 440],
        [-10, 330],
        [0, 240],
        [0, -240],
        [10, -330],
        [40, -440],
      ]);
    } else {
      const town = spaced([
        [-120, 960],
        [-110, 820],
        [-40, 700],
        [40, 600],
        [40, 500],
        [-40, 410],
        [-40, 320],
        [40, 230],
        [120, 130],
        [120, 20],
        [40, -80],
        [40, -170],
        [120, -270],
        [100, -380],
        [70, -543],
      ]);
      const i0 = town.findIndex((p) => p.z <= 880);
      let i1 = town.length - 1;
      while (i1 > 0 && town[i1]!.z < -470) i1--;
      const J = town[i0]!;
      const K = town[i1]!;
      const near = (pts: { x: number; z: number }[], p: { x: number; z: number }) =>
        pts.reduce((best, q, i) => (Math.hypot(q.x - p.x, q.z - p.z) < Math.hypot(pts[best]!.x - p.x, pts[best]!.z - p.z) ? i : best), 0);
      // (Running on from K the way the river runs into it.)
      const back = (p: { x: number; z: number }, q: { x: number; z: number }, d: number): [number, number] => {
        const l = Math.hypot(p.x - q.x, p.z - q.z) || 1;
        return [p.x + ((p.x - q.x) / l) * d, p.z + ((p.z - q.z) / l) * d];
      };
      const north = spaced([
        [722, 1182],
        [600, 1100],
        [450, 1034],
        [280, 1004],
        [110, 986],
        // (A wide bend, 75 m round, from the way it heads at J (north) round to the east.)
        ...[90, 65, 40, 20, 6].map((deg): [number, number] => {
          // (Its heading at J: from the point after J to the one before.)
          const p = town[i0 - 1]!;
          const q = town[i0 + 1]!;
          const l = Math.hypot(p.x - q.x, p.z - q.z) || 1;
          const dx = (p.x - q.x) / l;
          const dz = (p.z - q.z) / l;
          // The bend's centre, off to the east; J round it by -deg.
          const cx = J.x + dz * 75;
          const cz = J.z - dx * 75;
          const vx = J.x - cx;
          const vz = J.z - cz;
          const a = (-deg * Math.PI) / 180;
          return [cx + vx * Math.cos(a) - vz * Math.sin(a), cz + vx * Math.sin(a) + vz * Math.cos(a)];
        }),
        [J.x, J.z],
        [town[i0 + 2]!.x, town[i0 + 2]!.z],
      ]);
      const south = spaced([
        [town[i1 - 6]!.x, town[i1 - 6]!.z],
        [K.x, K.z],
        back(K, town[i1 - 6]!, 25),
        [44, -572],
        [62, -680],
        [40, -782],
        [30, -880],
        [22, -1000],
      ]);
      this.riverPts = [...north.slice(0, near(north, J)), ...town.slice(i0, i1 + 1), ...south.slice(near(south, K) + 1)];
    }
    this.river = new Line(this.riverPts, RIVER_HW + 40);
    this.valley = new Line(
      this.riverPts.filter((_, i) => i % 4 === 0),
      RIVER_REACH + 140,
      80,
    );

    this.planGrid();
    this.planHighway();
    this.planRiverStreets();
    this.pruneDeadEnds();
    this.planCorners();
    this.planSuburbs();
  }

  // ---------------------------------------------------------------------------
  // Grid

  /** The kept stretches of a grid street piece (all of it, unless the river cuts it). */
  private partsOf(key: string, a: number, b: number): [number, number][] {
    if (this.removed.has(key)) return [];
    return this.cut.get(key) ?? [[a, b]];
  }

  /** Is there a grid street piece along x = XS[i] from ZS[j] to ZS[j+1] (or any of it)? */
  private xPiece(i: number, j: number): boolean {
    if (i < 0 || i >= XS.length || j < 0 || j + 1 >= ZS.length) return false;
    if (XS[i]! < SUBURB_EDGE && i !== 0) return false;
    return !this.removed.has(`x:${i}:${j}`);
  }

  private zPiece(j: number, i: number): boolean {
    if (j < 0 || j >= ZS.length || i < 0 || i + 1 >= XS.length) return false;
    if (XS[i]! < SUBURB_EDGE && j !== 0 && j !== ZS.length - 1) return false;
    return !this.removed.has(`z:${j}:${i}`);
  }

  /** Does the grid have a street along x = XS[i) from ZS[j] to ZS[j+1], all the way? */
  xStreet(i: number, j: number): boolean {
    return this.xPiece(i, j) && !this.cut.has(`x:${i}:${j}`);
  }

  /** Does the grid have a street along z = ZS[j] from XS[i] to XS[i+1], all the way? */
  zStreet(j: number, i: number): boolean {
    return this.zPiece(j, i) && !this.cut.has(`z:${j}:${i}`);
  }

  /** The stretches of grid street there are, each with whether its ends are at a crossing. */
  pieces(): Piece[] {
    const out: Piece[] = [];
    for (let i = 0; i < XS.length; i++)
      for (let j = 0; j + 1 < ZS.length; j++) {
        if (!this.xPiece(i, j)) continue;
        const key = `x:${i}:${j}`;
        for (const [p0, p1] of this.partsOf(key, ZS[j]!, ZS[j + 1]!))
          out.push({ key, alongZ: true, s: XS[i]!, p0, p1, end0: p0 === ZS[j], end1: p1 === ZS[j + 1], bridge: false });
      }
    for (let j = 0; j < ZS.length; j++)
      for (let i = 0; i + 1 < XS.length; i++) {
        if (!this.zPiece(j, i)) continue;
        const key = `z:${j}:${i}`;
        for (const [p0, p1] of this.partsOf(key, XS[i]!, XS[i + 1]!))
          out.push({ key, alongZ: false, s: ZS[j]!, p0, p1, end0: p0 === XS[i], end1: p1 === XS[i + 1], bridge: false });
      }
    this.spans.forEach((b, k) => out.push({ key: `b:${k}`, alongZ: false, s: b.s, p0: b.a, p1: b.b, end0: false, end1: false, bridge: true }));
    return out;
  }

  /** Is there a crossing (or T) of grid streets at (XS[i], ZS[j]), a square of asphalt? */
  junction(i: number, j: number): boolean {
    if (i < 0 || j < 0 || i >= XS.length || j >= ZS.length || this.rounded.has(`${i}:${j}`)) return false;
    const X = XS[i]!;
    const Z = ZS[j]!;
    const touches = (key: string, a: number, b: number, at: number) => this.partsOf(key, a, b).some(([p0, p1]) => p0 === at || p1 === at);
    return (
      (this.xPiece(i, j) && touches(`x:${i}:${j}`, Z, ZS[j + 1]!, Z)) ||
      (this.xPiece(i, j - 1) && touches(`x:${i}:${j - 1}`, ZS[j - 1]!, Z, Z)) ||
      (this.zPiece(j, i) && touches(`z:${j}:${i}`, X, XS[i + 1]!, X)) ||
      (this.zPiece(j, i - 1) && touches(`z:${j}:${i - 1}`, XS[i - 1]!, X, X))
    );
  }

  private planGrid(): void {
    const test = LAYOUT === 'test';
    // Industrial blocks are twice as long: every other cross street left out, staggered.
    for (let i = 0; i < XS.length; i++)
      for (let j = 0; j + 1 < ZS.length; j++) {
        const x = XS[i]!;
        const zm = (ZS[j]! + ZS[j + 1]!) / 2;
        if (i === XS.length - 1 || (!test && x <= 240) || districtAt(x + 1, zm) !== 'industrial' || districtAt(x - 1, zm) !== 'industrial') continue;
        if ((i + j) % 2 === 0) this.removed.add(`x:${i}:${j}`);
      }
    if (test) {
      // The streets either side of the river's column would run right alongside its
      // riverside roads: left out (the streets across stop at the riverside road, or cross
      // on the bridge).
      for (const x of [-40, 40]) for (let j = 0; j + 1 < ZS.length; j++) this.removed.add(`x:${XS.indexOf(x)}:${j}`);
      return;
    }
    // The south strip of the Industrial district: long blocks the other way.
    for (let j = 1; j < ZS.length; j++)
      for (let i = 0; i + 1 < XS.length; i++) {
        const z = ZS[j]!;
        const xm = (XS[i]! + XS[i + 1]!) / 2;
        if (z >= -240 || Math.abs(xm) > 240) continue;
        if ((i + j) % 2 === 1) this.removed.add(`z:${j}:${i}`);
      }
  }

  /**
   * The river's streets. A road runs along each bank (BANK_D out from the middle of the
   * river, past a riverside walk), from the south boulevard to the north one. Every other
   * east-west street crosses the river on a bridge (and the boulevards); every other
   * east-west street that reaches the river stops at the riverside road in a T. The
   * north-south streets don't run up to it: the stretch from the last crossing to the
   * riverside road is left out (the ground it leaves goes to the blocks and parks), and
   * pruneDeadEnds takes out anything that leaves going nowhere. Streets that would run
   * alongside the riverside road, too close to it, are left out too.
   */
  private planRiverStreets(): void {
    const D = BANK_D;
    const pieceAt = (alongZ: boolean, s: number, t: number) => (alongZ ? this.river.dist(s, t) : this.river.dist(t, s));
    const doPiece = (key: string, alongZ: boolean, s: number, a: number, b: number) => {
      if (this.removed.has(key)) return;
      let min = Infinity;
      for (let t = a; t <= b; t += 1) min = Math.min(min, pieceAt(alongZ, s, t));
      if (min > D + LANE_HW + STREET_HW + 3) return;
      if (min >= D) {
        // Alongside the riverside road, too close to it: left out.
        this.removed.add(key);
        return;
      }
      // Cut where it meets the riverside road, from either end.
      const cutFrom = (from: number, to: number) => {
        const step = to > from ? 0.25 : -0.25;
        let t = from;
        if (pieceAt(alongZ, s, t) < D) return null;
        while ((step > 0 ? t < to : t > to) && pieceAt(alongZ, s, t + step) >= D) t += step;
        return t;
      };
      // A north-south street: the whole stretch up to the riverside road goes.
      if (alongZ) {
        this.removed.add(key);
        return;
      }
      const parts: [number, number][] = [];
      const ea = cutFrom(a, b);
      if (ea !== null && ea - a > 4) parts.push([a, ea]);
      const eb = cutFrom(b, a);
      if (eb !== null && b - eb > 4) parts.push([eb, b]);
      if (parts.length) this.cut.set(key, parts);
      else this.removed.add(key);
    };
    const last = ZS.length - 1;
    for (let i = 0; i < XS.length; i++) for (let j = 0; j + 1 < ZS.length; j++) doPiece(`x:${i}:${j}`, true, XS[i]!, ZS[j]!, ZS[j + 1]!);
    for (let j = 0; j < ZS.length; j++) for (let i = 0; i + 1 < XS.length; i++) doPiece(`z:${j}:${i}`, false, ZS[j]!, XS[i]!, XS[i + 1]!);
    // The riverside roads: the river's line, out to each side, from the south boulevard to
    // the north one; each split where a bridge crosses it (the bridge meets it there).
    const z0 = ZS[0]!;
    const z1 = ZS[last]!;
    const lines: { x: number; z: number }[][] = [];
    for (const side of [-1, 1]) {
      const pts = this.riverPts;
      const off: { x: number; z: number }[] = [];
      for (let k = 0; k < pts.length; k++) {
        const p = pts[Math.max(0, k - 2)]!;
        const q = pts[Math.min(pts.length - 1, k + 2)]!;
        const l = Math.hypot(q.x - p.x, q.z - p.z) || 1;
        off.push({ x: pts[k]!.x - ((q.z - p.z) / l) * D * side, z: pts[k]!.z + ((q.x - p.x) / l) * D * side });
      }
      // Clip to between the boulevards, ends exactly on them.
      const line: { x: number; z: number }[] = [];
      for (let k = 0; k + 1 < off.length; k++) {
        const a = off[k]!;
        const b = off[k + 1]!;
        const inA = a.z >= z0 && a.z <= z1;
        if (inA) line.push(a);
        for (const zc of [z0, z1])
          if ((a.z - zc) * (b.z - zc) < 0) {
            const f = (zc - a.z) / (b.z - a.z);
            line.push({ x: a.x + (b.x - a.x) * f, z: zc });
          }
      }
      lines.push(line);
    }
    // The bridges: on every other east-west street (and the two boulevards), wherever it
    // crosses the river, from where it meets one riverside road to where it meets the other.
    const cross = (line: { x: number; z: number }[], zb: number) => {
      const xs: number[] = [];
      for (let k = 0; k + 1 < line.length; k++) {
        const a = line[k]!;
        const b = line[k + 1]!;
        if (a.z === zb) xs.push(a.x);
        else if ((a.z - zb) * (b.z - zb) < 0) xs.push(a.x + ((b.x - a.x) * (zb - a.z)) / (b.z - a.z));
      }
      const e = line[line.length - 1]!;
      if (e.z === zb) xs.push(e.x);
      return xs;
    };
    for (let j = 0; j < ZS.length; j++) {
      // (Test: just the one, on the middle street.)
      if (LAYOUT === 'test' ? j !== 2 : j % 2 !== 0 && j !== last) continue;
      const zb = ZS[j]!;
      for (const xr of cross(this.riverPts, zb)) {
        if (xr < XS[0]! || xr > XS[XS.length - 1]!) continue;
        const ends = lines.map((l) => cross(l, zb).reduce((best, x) => (Math.abs(x - xr) < Math.abs(best - xr) ? x : best), Infinity));
        if (ends.some((x) => !isFinite(x) || Math.abs(x - xr) > D * 2.5)) continue;
        this.spans.push({ s: zb, a: Math.min(...ends), b: Math.max(...ends) });
      }
    }
    // Each riverside road split where a bridge meets it (not at its very ends, on a boulevard).
    for (const line of lines) {
      let cur: { x: number; z: number }[] = [];
      for (let k = 0; k < line.length; k++) {
        const p = line[k]!;
        cur.push(p);
        const q = line[k + 1];
        if (!q) break;
        for (const sp of this.spans) {
          if (!((p.z - sp.s) * (q.z - sp.s) < 0)) continue;
          const x = p.x + ((q.x - p.x) * (sp.s - p.z)) / (q.z - p.z);
          if (x < sp.a - 1 || x > sp.b + 1) continue;
          const hit = { x, z: sp.s };
          cur.push(hit);
          this.banks.push(respace(cur, 3).map(({ x, z }) => ({ x, z })));
          cur = [hit];
        }
      }
      if (cur.length > 1) this.banks.push(respace(cur, 3).map(({ x, z }) => ({ x, z })));
    }
    this.bankLines = this.banks.map((b) => new Line(b, LANE_HW + 12));
  }

  /**
   * No dead ends: a stretch of street whose crossing at one end has nothing else coming
   * into it (left alone by the river cutting the streets round it) goes, and so on until
   * every stretch leads somewhere at both ends.
   */
  private pruneDeadEnds(): void {
    for (let changed = true; changed; ) {
      changed = false;
      // How many stretches come into each crossing.
      const count = new Map<string, number>();
      const ends: { key: string; part: [number, number]; at: string[] }[] = [];
      for (const p of this.pieces()) {
        const at: string[] = [];
        if (p.end0) at.push(p.alongZ ? `${XS.indexOf(p.s)}:${ZS.indexOf(p.p0)}` : `${XS.indexOf(p.p0)}:${ZS.indexOf(p.s)}`);
        if (p.end1) at.push(p.alongZ ? `${XS.indexOf(p.s)}:${ZS.indexOf(p.p1)}` : `${XS.indexOf(p.p1)}:${ZS.indexOf(p.s)}`);
        for (const k of at) count.set(k, (count.get(k) ?? 0) + 1);
        ends.push({ key: p.key, part: [p.p0, p.p1], at });
      }
      for (const e of ends) {
        if (!e.at.some((k) => count.get(k) === 1)) continue;
        // Its crossing goes nowhere else: take this stretch out.
        const [kind, , b] = e.key.split(':');
        const full = kind === 'x' ? [ZS[Number(b)]!, ZS[Number(b) + 1]!] : [XS[Number(b)]!, XS[Number(b) + 1]!];
        const left = this.partsOf(e.key, full[0]!, full[1]!).filter(([p0, p1]) => p0 !== e.part[0] || p1 !== e.part[1]);
        if (left.length) this.cut.set(e.key, left);
        else {
          this.cut.delete(e.key);
          this.removed.add(e.key);
        }
        changed = true;
      }
    }
  }

  /**
   * Corners: a crossing where only two streets meet, one turning into the other square
   * on, becomes a curve (a quarter circle of CORNER_R m), the streets stopping short of it.
   */
  private planCorners(): void {
    const R = CORNER_R;
    for (let i = 0; i < XS.length; i++)
      for (let j = 0; j < ZS.length; j++) {
        if (!this.junction(i, j)) continue;
        const X = XS[i]!;
        const Z = ZS[j]!;
        // The parts touching it, with the way each leaves it.
        const ways: { key: string; dx: number; dz: number; a: number; b: number; atStart: boolean }[] = [];
        const look = (ok: boolean, key: string, a: number, b: number, at: number, dx: number, dz: number) => {
          if (!ok) return;
          for (const [p0, p1] of this.partsOf(key, a, b)) {
            if (p0 === at) ways.push({ key, dx, dz, a, b, atStart: true });
            else if (p1 === at) ways.push({ key, dx, dz, a, b, atStart: false });
          }
        };
        look(this.xPiece(i, j), `x:${i}:${j}`, Z, ZS[j + 1] ?? Z, Z, 0, 1);
        look(this.xPiece(i, j - 1), `x:${i}:${j - 1}`, ZS[j - 1] ?? Z, Z, Z, 0, -1);
        look(this.zPiece(j, i), `z:${j}:${i}`, X, XS[i + 1] ?? X, X, 1, 0);
        look(this.zPiece(j, i - 1), `z:${j}:${i - 1}`, XS[i - 1] ?? X, X, X, -1, 0);
        if (ways.length !== 2) continue;
        const [u, v] = ways as [(typeof ways)[0], (typeof ways)[0]];
        if (u.dx * v.dx + u.dz * v.dz !== 0) continue;
        // Long enough to stop short by R.
        const len = (w: typeof u) => {
          const at = w.dx ? X : Z;
          const p = this.partsOf(w.key, w.a, w.b).find(([p0, p1]) => p0 === at || p1 === at);
          return p ? p[1] - p[0] : 0;
        };
        if (len(u) < R + 12 || len(v) < R + 12) continue;
        // Shorten each part by R at this end.
        for (const w of [u, v]) {
          const parts = this.partsOf(w.key, w.a, w.b).map(([p0, p1]): [number, number] => {
            const at = w.dx ? X : Z;
            if (p0 === at) return [p0 + R, p1];
            if (p1 === at) return [p0, p1 - R];
            return [p0, p1];
          });
          this.cut.set(w.key, parts);
        }
        this.rounded.add(`${i}:${j}`);
        // The quarter circle from one to the other, round its centre in the corner.
        const cx = X + (u.dx + v.dx) * R;
        const cz = Z + (u.dz + v.dz) * R;
        const pts: { x: number; z: number }[] = [];
        const a0 = Math.atan2(-v.dz, -v.dx);
        const a1 = Math.atan2(-u.dz, -u.dx);
        let da = a1 - a0;
        if (da > Math.PI) da -= Math.PI * 2;
        if (da < -Math.PI) da += Math.PI * 2;
        const n = 16;
        // From the end of v's part round to the end of u's.
        for (let k = 0; k <= n; k++) {
          const a = a1 - (da * k) / n;
          pts.push({ x: cx + Math.cos(a) * R, z: cz + Math.sin(a) * R });
        }
        this.corners.push(pts);
      }
    this.cornerLines = this.corners.map((c) => new Line(c, STREET_HW + 10));
  }

  /** Is (x, z) on one of the river's bridges (its roadway)? */
  onBridge(x: number, z: number, margin = 0): boolean {
    return this.spans.some((b) => Math.abs(z - b.s) < STREET_HW + margin && x > b.a - margin && x < b.b + margin);
  }

  /** Is (x, z) in the river (between its walls)? */
  inRiver(x: number, z: number, margin = 0): boolean {
    return this.river.dist(x, z) < RIVER_HW + margin;
  }

  /** Is (x, z) on a city street: a grid street or crossing, a curved corner, or a riverside road? */
  onStreet(x: number, z: number, margin = 0): boolean {
    for (const l of this.bankLines) if (l.dist(x, z) < LANE_HW + margin) return true;
    if (this.onBridge(x, z, margin)) return true;
    for (const l of this.cornerLines) if (l.dist(x, z) < STREET_HW + margin) return true;
    const hw = STREET_HW + margin;
    const i = Math.round((x - XS[0]!) / 80);
    const j = Math.round((z - ZS[0]!) / 80);
    const onX = i >= 0 && i < XS.length && Math.abs(x - XS[i]!) < hw;
    const onZ = j >= 0 && j < ZS.length && Math.abs(z - ZS[j]!) < hw;
    if (!onX && !onZ) return false;
    if (onX && onZ && this.junction(i, j)) return true;
    const jz = Math.floor((z - ZS[0]!) / 80);
    const ix = Math.floor((x - XS[0]!) / 80);
    if (onX && this.xPiece(i, jz) && this.partsOf(`x:${i}:${jz}`, ZS[jz]!, ZS[jz + 1]!).some(([p0, p1]) => z >= p0 - margin && z <= p1 + margin)) return true;
    if (onZ && this.zPiece(j, ix) && this.partsOf(`z:${j}:${ix}`, XS[ix]!, XS[ix + 1]!).some(([p0, p1]) => x >= p0 - margin && x <= p1 + margin)) return true;
    return false;
  }

  // ---------------------------------------------------------------------------
  // Highway

  private addDeck(d: Deck): void {
    const k = this.decks.length;
    this.decks.push(d);
    const n = d.pts.length;
    for (let i = 0; i + 1 < n; i++) {
      const a = d.pts[i]!;
      const b = d.pts[i + 1]!;
      const seg: DeckSeg = { ax: a.x, ay: a.y, az: a.z, bx: b.x, by: b.y, bz: b.z, hw: d.hw, deck: k, first: !d.closed && i === 0, last: !d.closed && i === n - 2 };
      this.deckSegs.push(seg);
      const r = d.hw + 2;
      for (let cx = Math.floor((Math.min(a.x, b.x) - r) / 20); cx <= Math.floor((Math.max(a.x, b.x) + r) / 20); cx++)
        for (let cz = Math.floor((Math.min(a.z, b.z) - r) / 20); cz <= Math.floor((Math.max(a.z, b.z) + r) / 20); cz++) {
          const key = (cx + 1000) * 4096 + cz + 1000;
          let list = this.deckCells.get(key);
          if (!list) this.deckCells.set(key, (list = []));
          list.push(seg);
        }
    }
  }

  private planHighway(): void {
    const H = DECK_Y;
    const L = LOOP;
    // The loop, anticlockwise seen from above (x right, z down the screen): straight sides
    // and quarter circles at the corners, a point every 2 m.
    const loop: { x: number; z: number }[] = [];
    const side = (x0: number, z0: number, x1: number, z1: number) => {
      const n = Math.max(1, Math.round(Math.hypot(x1 - x0, z1 - z0) / 2));
      for (let k = 0; k < n; k++) loop.push({ x: x0 + ((x1 - x0) * k) / n, z: z0 + ((z1 - z0) * k) / n });
    };
    const arc = (cx: number, cz: number, a0: number, a1: number) => {
      const n = Math.max(2, Math.round((Math.abs(a1 - a0) * L.r) / 2));
      for (let k = 0; k < n; k++) {
        const a = a0 + ((a1 - a0) * k) / n;
        loop.push({ x: cx + Math.cos(a) * L.r, z: cz + Math.sin(a) * L.r });
      }
    };
    // East side going +z, north-east corner, north side going -x, and so on round.
    side(L.x1, L.z0 + L.r, L.x1, L.z1 - L.r);
    arc(L.x1 - L.r, L.z1 - L.r, 0, Math.PI / 2);
    side(L.x1 - L.r, L.z1, L.x0 + L.r, L.z1);
    arc(L.x0 + L.r, L.z1 - L.r, Math.PI / 2, Math.PI);
    side(L.x0, L.z1 - L.r, L.x0, L.z0 + L.r);
    arc(L.x0 + L.r, L.z0 + L.r, Math.PI, Math.PI * 1.5);
    side(L.x0 + L.r, L.z0, L.x1 - L.r, L.z0);
    arc(L.x1 - L.r, L.z0 + L.r, Math.PI * 1.5, Math.PI * 2);
    loop.push({ ...loop[0]! });
    this.addDeck({ pts: loop.map((p) => ({ x: p.x, y: H, z: p.z })), hw: HIGHWAY_HW, kind: 'highway', closed: true, oneway: 0 });

    // (No crosstown on the Test map.)
    if (LAYOUT === 'city') {
      // The crosstown, straight over the street at CROSS_Z.
      const cross: P3[] = [];
      for (let x = -FORK_X; x <= FORK_X + 0.01; x += 4) cross.push({ x, y: H, z: CROSS_Z });
      this.addDeck({ pts: cross, hw: HIGHWAY_HW, kind: 'highway', closed: false, oneway: 0 });
      // A one-way road keeps to the right of the way its traffic goes: its lanes line up with
      // the right-hand lanes of the two-way highway it leaves or joins, so traffic never
      // crosses the other way's lanes. (For a one-way road laid out against its traffic,
      // `against`, the right is the other side.)
      const keepRight = (pts: { x: number; z: number }[], by: number, against: boolean) =>
        pts.map((p, i) => {
          const a = pts[Math.max(0, i - 1)]!;
          const b = pts[Math.min(pts.length - 1, i + 1)]!;
          const l = Math.hypot(b.x - a.x, b.z - a.z) || 1;
          // Right of the way the points run is (-tz, tx).
          const k = against ? -by : by;
          return { x: p.x - ((b.z - a.z) / l) * k, z: p.z + ((b.x - a.x) / l) * k };
        });
      // At each end it forks into two quarter circles onto the loop. Each is one way, the way
      // that turns right off one road and joins the next from its right: east, from the
      // crosstown out onto the loop going north (z up), and from the loop going north in onto
      // the crosstown going west; west, from the crosstown out onto the loop going south, and
      // from the loop going south in onto the crosstown going east.
      for (const sx of [1, -1])
        for (const sz of [1, -1]) {
          const cz = CROSS_Z + sz * FORK_R;
          const arc: { x: number; z: number }[] = [];
          const n = Math.round((FORK_R * Math.PI) / 2 / 3);
          for (let k = 0; k <= n; k++) {
            const t = (k / n) * (Math.PI / 2);
            arc.push({ x: sx * (FORK_X + FORK_R * Math.sin(t)), z: cz - sz * FORK_R * Math.cos(t) });
          }
          // Out from the crosstown where it turns right (east going north, west going south).
          const out = sx * sz > 0;
          this.addDeck({
            pts: keepRight(arc, LANE_SHIFT, !out).map((p) => ({ x: p.x, y: H, z: p.z })),
            hw: ONEWAY_HW,
            kind: 'highway',
            closed: false,
            oneway: out ? 1 : -1,
          });
        }
    }

    // On and off ramps, one lane, one way. Each leaves a highway from its right-hand lane,
    // eases out sideways (an S-bend over `ease` m) until it's clear of it, runs alongside
    // coming down a smooth slope, and (off the loop) curves in to meet a crossing on the
    // boulevard square on. `exit`: traffic goes down it, from the highway; otherwise up it.
    const ramp = (sx: number, sz: number, dx: number, dz: number, nx: number, nz: number, ease: number, off: number, run: number, turn: number, tail: number, hold: number, exit: boolean) => {
      const dense: { x: number; z: number }[] = [];
      // From the outer lane's line (5.4 m out) to `off` m out.
      const o0 = LANE_OUTER;
      for (let d = 0; d <= ease + run; d += 1) {
        const f = Math.min(1, d / ease);
        const o = o0 + (off - o0) * f * f * (3 - 2 * f);
        dense.push({ x: sx + dx * d + nx * o, z: sz + dz * d + nz * o });
      }
      if (turn !== 0) {
        // A quarter circle round, then straight on into the crossing: turning on the way it
        // eased out (turn > 0), or back the other way (turn < 0), under the highway it left.
        const g = Math.sign(turn);
        const T = Math.abs(turn);
        const cx = sx + dx * (ease + run) + nx * (off + g * T);
        const cz = sz + dz * (ease + run) + nz * (off + g * T);
        const n = Math.round((T * Math.PI) / 2);
        for (let k = 1; k <= n; k++) {
          const a = (k / n) * (Math.PI / 2);
          dense.push({ x: cx - nx * g * T * Math.cos(a) + dx * T * Math.sin(a), z: cz - nz * g * T * Math.cos(a) + dz * T * Math.sin(a) });
        }
        for (let d = 1; d <= tail; d += 1) dense.push({ x: cx + dx * T + nx * g * d, z: cz + dz * T + nz * g * d });
      }
      const pts = respace(dense, 3);
      const total = pts[pts.length - 1]!.s;
      // Level with the highway until it's clear of it, then down a smooth slope (gentle at
      // the top and the bottom), level again for the last few metres into the crossing.
      const flat = 6;
      this.addDeck({
        pts: pts.map((p) => {
          const u = Math.max(0, Math.min(1, (p.s - hold) / (total - hold - flat)));
          return { x: p.x, y: H * (0.5 + 0.5 * Math.cos(Math.PI * u)), z: p.z };
        }),
        hw: RAMP_HW,
        kind: 'ramp',
        closed: false,
        oneway: exit ? 1 : -1,
      });
    };
    if (LAYOUT === 'test') {
      // Test: one exit and one entry, off the north side for traffic going west (on its
      // right, the city side), down to the boulevard crossings at x = 120 and -120: 60 m
      // easing out to 16 m, 60 m alongside, a 35 m radius turn, a little steeper than the
      // City's.
      ramp(275, L.z1, -1, 0, 0, -1, 60, 16, 60, 35, 10, 50, true);
      ramp(-275, L.z1, 1, 0, 0, -1, 60, 16, 60, 35, 10, 50, false);
      return;
    }
    // Off the loop's long north and south sides, down to the boulevard crossings at x = ±240,
    // each on the city side: so on the north side for traffic going west (whose right that
    // is), an exit at the east end and an entry at the west; on the south side the same for
    // traffic going east. 100 m easing out to 20 m, 100 m alongside, a 45 m radius turn and
    // the last few metres.
    ramp(485, L.z1, -1, 0, 0, -1, 100, 20, 100, 45, 15, 90, true);
    ramp(-485, L.z1, 1, 0, 0, -1, 100, 20, 100, 45, 15, 90, false);
    ramp(-485, L.z0, 1, 0, 0, 1, 100, 20, 100, 45, 5, 90, true);
    ramp(485, L.z0, -1, 0, 0, 1, 100, 20, 100, 45, 5, 90, false);
    // And exits for the traffic going the other way, whose right is the outside of the
    // loop: each leaves from the outer lane on the right, eases out 25 m beyond the loop,
    // comes down alongside it, then turns back in, under the loop near the ground, to a
    // boulevard crossing. On the north side for traffic going east, on the south side for
    // traffic going west.
    ramp(395, L.z1, 1, 0, 0, 1, 100, 25, 100, -45, 60, 90, true);
    ramp(-395, L.z0, -1, 0, 0, -1, 100, 25, 100, -45, 50, 90, true);
    // Off the crosstown in the middle of Downtown, a diamond: on the +z side (the right of
    // traffic going east) an entry from the west and an exit to the east, and on the -z
    // side (the right of traffic going west) an exit to the west and an entry from the
    // east, each down to the streets at Downtown's edges (meeting them square on, in a T).
    ramp(-20, CROSS_Z, -1, 0, 0, 1, 70, 16, 150, 0, 0, 68, false);
    ramp(20, CROSS_Z, 1, 0, 0, 1, 70, 16, 150, 0, 0, 68, true);
    ramp(-20, CROSS_Z, -1, 0, 0, -1, 70, 16, 150, 0, 0, 68, true);
    ramp(20, CROSS_Z, 1, 0, 0, -1, 70, 16, 150, 0, 0, 68, false);
    // Streets the crosstown ramps come down across, low over them: left out.
    for (const x of [-160, 160]) {
      this.removed.add(`x:${XS.indexOf(x)}:${ZS.indexOf(CROSS_Z)}`);
      this.removed.add(`x:${XS.indexOf(x)}:${ZS.indexOf(CROSS_Z) - 1}`);
    }
    this.planInterchanges();
  }

  /**
   * Where the crosstown meets the loop, the left turns: the quarter-circle curves only
   * turn right, so at each end two more connectors make it a full semi-directional T
   * interchange, every way from one road onto the other with no traffic crossing any
   * other at grade. Left turns leave on the right and cross over or under on bridges:
   *
   * - Crosstown onto the loop's far side (east end: going east, onto the loop going south):
   *   a flyover off the right-hand lane, up to 16 m, round to the left over the curves and
   *   the loop, and down outside it into the far side's lanes from their right.
   * - The loop's far side onto the crosstown (east end: from the loop going south, onto the
   *   crosstown going west): off the outer lane, out beyond the loop and down to 5.8 m,
   *   round to the left under the loop (and under the curve, over the boulevard), and up
   *   into the crosstown's lanes from their right.
   *
   * The west end is the same turned half round (about the middle of the crosstown).
   */
  private planInterchanges(): void {
    type Op = ['ease', number, number] | ['line', number] | ['arc', number, number];
    // A path from (x, z) heading (hx, hz): easing sideways (to the right, +) over a length,
    // straight on, or round a quarter-ish circle (radius, angle; + left, - right).
    const path = (x: number, z: number, hx: number, hz: number, ops: Op[]) => {
      const out: { x: number; z: number }[] = [{ x, z }];
      for (const op of ops) {
        const rx = -hz;
        const rz = hx;
        if (op[0] === 'line' || op[0] === 'ease') {
          const len = op[1];
          const side = op[0] === 'ease' ? op[2] : 0;
          for (let d = 1; d <= len; d++) {
            const f = d / len;
            const o = side * f * f * (3 - 2 * f);
            out.push({ x: x + hx * d + rx * o, z: z + hz * d + rz * o });
          }
          x += hx * len + rx * side;
          z += hz * len + rz * side;
        } else {
          const [, R, A] = op;
          const g = Math.sign(A);
          // The centre is to the left for a left turn (left of the heading is -right).
          const cx = x - rx * g * R;
          const cz = z - rz * g * R;
          const n = Math.max(2, Math.round(R * Math.abs(A)));
          for (let k = 1; k <= n; k++) {
            const a = (k / n) * Math.abs(A);
            out.push({ x: cx + rx * g * R * Math.cos(a) + hx * R * Math.sin(a), z: cz + rz * g * R * Math.cos(a) + hz * R * Math.sin(a) });
          }
          const c = Math.cos(A);
          const s = Math.sin(A);
          // Turning left by A: the heading swings towards the left (-right).
          const nhx = hx * c - rx * s;
          const nhz = hz * c - rz * s;
          x = out[out.length - 1]!.x;
          z = out[out.length - 1]!.z;
          hx = nhx;
          hz = nhz;
        }
      }
      return out;
    };
    // Heights along the path: smooth steps [from s, to s, from y, to y].
    const lay = (dense: { x: number; z: number }[], steps: [number, number, number, number][], flip: boolean) => {
      const pts = respace(dense, 3);
      return pts.map((p) => {
        let y = steps[0]![2];
        for (const [s0, s1, y0, y1] of steps) {
          if (p.s <= s0) break;
          const f = Math.min(1, (p.s - s0) / (s1 - s0));
          y = y0 + (y1 - y0) * f * f * (3 - 2 * f);
        }
        return { x: flip ? -p.x : p.x, y, z: flip ? 2 * CROSS_Z - p.z : p.z };
      });
    };
    const H = DECK_Y;
    const L = LOOP;
    for (const flip of [false, true]) {
      // East end (the west end is it turned half round). The crosstown going east to the
      // loop going south: off the right-hand lane at x = 380.
      const over = path(380, CROSS_Z + LANE_OUTER, 1, 0, [
        ['ease', 100, 16.6],
        ['line', 150],
        ['arc', 200, Math.PI / 2],
        ['line', 132],
        ['ease', 55, -(L.x1 + 30 - (L.x1 + LANE_OUTER))],
      ]);
      this.addDeck({ pts: lay(over, [[20, 200, H, 16], [490, 690, 16, H]], flip), hw: RAMP_HW, kind: 'ramp', closed: false, oneway: 1 });
      // The loop going south to the crosstown going west: off the outer lane at z = 380.
      const under = path(L.x1 + LANE_OUTER, 380, 0, -1, [
        ['ease', 80, L.x1 + 30 - (L.x1 + LANE_OUTER)],
        ['line', 260],
        ['arc', 60, Math.PI / 2],
        ['line', 10],
        ['ease', 320, -(CROSS_Z - LANE_OUTER + 20)],
      ]);
      this.addDeck({ pts: this.underpass(lay(under, [[0, 1, H, H]], flip), 95), hw: RAMP_HW, kind: 'ramp', closed: false, oneway: 1 });
    }
  }

  /**
   * Fit a deck that passes under others: wherever another deck is above it, it comes down
   * far enough to leave HEADROOM under that deck's underside (the deck above stays where it
   * is); over a street it stays high enough to leave the same over the street. In between
   * it eases down and back up on gentle slopes, smoothed so there's no kink to hop off.
   */
  private underpass(pts: P3[], join: number): P3[] {
    const n = pts.length;
    const cum = [0];
    for (let k = 1; k < n; k++) cum.push(cum[k - 1]! + Math.hypot(pts[k]!.x - pts[k - 1]!.x, pts[k]!.z - pts[k - 1]!.z));
    const total = cum[n - 1]!;
    const ceil = pts.map((p, k0) => {
      let c = Infinity;
      // (Not where it joins the highway at either end, running into it level.)
      if (cum[k0]! < join || cum[k0]! > total - join) return c;
      // Any deck over its footprint (its middle or either edge).
      for (const o of [-RAMP_HW, 0, RAMP_HW]) {
        const k = pts.indexOf(p);
        const a = pts[Math.max(0, k - 1)]!;
        const b = pts[Math.min(n - 1, k + 1)]!;
        const l = Math.hypot(b.x - a.x, b.z - a.z) || 1;
        const x = p.x - ((b.z - a.z) / l) * o;
        const z = p.z + ((b.x - a.x) / l) * o;
        const near = this.deckNear(x, z);
        if (near && !near.beyond && near.edge < 0.5) c = Math.min(c, near.y - DECK_DEPTH - HEADROOM);
      }
      return c;
    });
    const floor = pts.map((p) => (this.onStreet(p.x, p.z, RAMP_HW) ? DECK_DEPTH + HEADROOM : 0));
    // The highest it can be at each point: under every ceiling, and down from each one no
    // steeper than SLOPE.
    let y = pts.map((p) => p.y);
    for (let k = 0; k < n; k++)
      if (ceil[k]! < Infinity) for (let j = 0; j < n; j++) y[j] = Math.min(y[j]!, ceil[k]! + Math.abs(cum[j]! - cum[k]!) * SLOPE);
    // Smooth (never back up into a ceiling), then keep clear of the streets below.
    for (let pass = 0; pass < 8; pass++) {
      const s = y.map((v, k) => (k === 0 || k === n - 1 ? v : (y[k - 1]! + 2 * v + y[k + 1]!) / 4));
      y = s.map((v, k) => Math.min(v, ceil[k]!, pts[k]!.y));
    }
    return pts.map((p, k) => ({ x: p.x, y: Math.max(y[k]!, floor[k]!), z: p.z }));
  }

  /**
   * The deck under (x, z) that something at height y is on (or just climbing onto): its
   * height, or null if there's none (it's on the ground, or under the deck). Where two
   * decks overlap (a ramp pulling away from the highway), the one nearest its height: it
   * stays on whichever it's driving along, never hopping up onto the other.
   */
  deckAt(x: number, z: number, y: number, margin = 0.25): number | null {
    const list = this.deckCells.get((Math.floor(x / 20) + 1000) * 4096 + Math.floor(z / 20) + 1000);
    if (!list) return null;
    // Each deck's height here is from its nearest piece only: next to a joint, the piece
    // before also reaches (its end clamped), and taking that would make a slope a staircase.
    const near = new Map<number, { d: number; y: number }>();
    for (const s of list) {
      const vx = s.bx - s.ax;
      const vz = s.bz - s.az;
      const l2 = vx * vx + vz * vz || 1;
      const t = Math.max(0, Math.min(1, ((x - s.ax) * vx + (z - s.az) * vz) / l2));
      const d = Math.hypot(x - s.ax - vx * t, z - s.az - vz * t);
      if (d > s.hw + margin) continue;
      const was = near.get(s.deck);
      if (!was || d < was.d) near.set(s.deck, { d, y: s.ay + (s.by - s.ay) * t });
    }
    let best: number | null = null;
    for (const { y: dy } of near.values()) {
      if (dy < 0.01 || y < dy - 1.6) continue;
      if (best === null || Math.abs(dy - y) < Math.abs(best - y)) best = dy;
    }
    return best;
  }
  /**
   * How far (x, z) is from the edge of the nearest deck footprint (negative inside), and
   * that deck's height there, looking within `reach` of the edge.
   */
  deckNear(x: number, z: number, skip = -1): { edge: number; y: number; deck: number; beyond: boolean } | null {
    const list = this.deckCells.get((Math.floor(x / 20) + 1000) * 4096 + Math.floor(z / 20) + 1000);
    if (!list) return null;
    let best: { edge: number; y: number; deck: number; beyond: boolean } | null = null;
    for (const s of list) {
      if (s.deck === skip) continue;
      const vx = s.bx - s.ax;
      const vz = s.bz - s.az;
      const l2 = vx * vx + vz * vz || 1;
      const raw = ((x - s.ax) * vx + (z - s.az) * vz) / l2;
      const t = Math.max(0, Math.min(1, raw));
      const edge = Math.hypot(x - s.ax - vx * t, z - s.az - vz * t) - s.hw;
      // Past the very end of a deck that ends: near it, but not on it.
      const beyond = (s.first && raw < 0) || (s.last && raw > 1);
      if (!best || edge < best.edge) best = { edge, y: s.ay + (s.by - s.ay) * t, deck: s.deck, beyond };
    }
    return best;
  }


  /** Is any deck (other than skip) within r of (x, z), lower than y? (Where a pillar from a deck at y would stand on it.) */
  deckBelow(x: number, z: number, r: number, y: number, skip: number): boolean {
    const list = this.deckCells.get((Math.floor(x / 20) + 1000) * 4096 + Math.floor(z / 20) + 1000);
    if (!list) return false;
    for (const s of list) {
      if (s.deck === skip) continue;
      const vx = s.bx - s.ax;
      const vz = s.bz - s.az;
      const l2 = vx * vx + vz * vz || 1;
      const t = Math.max(0, Math.min(1, ((x - s.ax) * vx + (z - s.az) * vz) / l2));
      if (Math.hypot(x - s.ax - vx * t, z - s.az - vz * t) - s.hw < r && s.ay + (s.by - s.ay) * t < y) return true;
    }
    return false;
  }

  /** Does a rectangle come within `margin` of any deck (high enough to matter)? */
  rectNearDeck(x0: number, z0: number, x1: number, z1: number, margin: number): boolean {
    for (let x = x0; x <= x1 + 0.01; x += Math.max(1, (x1 - x0) / Math.ceil((x1 - x0) / 4)))
      for (let z = z0; z <= z1 + 0.01; z += Math.max(1, (z1 - z0) / Math.ceil((z1 - z0) / 4))) {
        const n = this.deckNear(x, z);
        if (n && n.edge < margin && !n.beyond) return true;
      }
    return false;
  }

  // ---------------------------------------------------------------------------
  // Suburbs

  private planSuburbs(): void {
    const r = rng(77031);
    const cols = XS.map((x, i) => ({ x, i })).filter((c) => c.x >= XS[0]! && c.x <= SUBURB_EDGE);
    // Crossings on every other grid line across (so the blocks are twice as long that way,
    // half as many crossings), every grid line along. (Test, one column wide: a lane across
    // on every grid line, for four blocks of houses.)
    const RZ = LAYOUT === 'test' ? ZS : ZS.filter((_, j) => j % 2 === 0);
    const rows = RZ.length;
    const nc = cols.length;
    // A junction for each of those crossings, those inside nudged about a little.
    const id = (c: number, j: number) => c * rows + j;
    const pos: { x: number; z: number }[] = [];
    for (let c = 0; c < nc; c++)
      for (let j = 0; j < rows; j++) {
        const edge = c === 0 || c === nc - 1 || j === 0 || j === rows - 1;
        pos.push({ x: cols[c]!.x + (edge ? 0 : (r() - 0.5) * 20), z: RZ[j]! + (edge ? 0 : (r() - 0.5) * 24) });
      }
    // Streets between neighbouring junctions (the outer lines are the grid's own straight
    // streets), each bowed gently one way or the other.
    const links: [number, number][] = [];
    for (let c = 0; c + 1 < nc; c++) for (let j = 1; j + 1 < rows; j++) links.push([id(c, j), id(c + 1, j)]);
    for (let c = 1; c + 1 < nc; c++) for (let j = 0; j + 1 < rows; j++) links.push([id(c, j), id(c, j + 1)]);
    // Leave a few out for variety, as long as everything still joins up and every inside
    // junction keeps three ways out.
    const degree = new Map<number, number>();
    for (const [a, b] of links) {
      degree.set(a, (degree.get(a) ?? 0) + 1);
      degree.set(b, (degree.get(b) ?? 0) + 1);
    }
    const keep = links.map(() => true);
    const isEdge = (n: number) => {
      const c = Math.floor(n / rows);
      const j = n % rows;
      return c === 0 || c === nc - 1 || j === 0 || j === rows - 1;
    };
    for (let k = 0; k < links.length; k++) {
      const [a, b] = links[k]!;
      if (isEdge(a) || isEdge(b) || r() > 0.16) continue;
      if (degree.get(a)! < 4 || degree.get(b)! < 4) continue;
      keep[k] = false;
      degree.set(a, degree.get(a)! - 1);
      degree.set(b, degree.get(b)! - 1);
    }
    const used = new Set<number>();
    links.forEach(([a, b], k) => {
      if (!keep[k]) return;
      const A = pos[a]!;
      const B = pos[b]!;
      const len = Math.hypot(B.x - A.x, B.z - A.z);
      const nx = -(B.z - A.z) / len;
      const nz = (B.x - A.x) / len;
      const bow = (r() < 0.5 ? -1 : 1) * (4 + r() * 4) * (len / 80);
      const mx = (A.x + B.x) / 2 + nx * bow * 2;
      const mz = (A.z + B.z) / 2 + nz * bow * 2;
      const dense: { x: number; z: number }[] = [];
      for (let i = 0; i <= 120; i++) {
        const t = i / 120;
        const u = 1 - t;
        dense.push({ x: u * u * A.x + 2 * u * t * mx + t * t * B.x, z: u * u * A.z + 2 * u * t * mz + t * t * B.z });
      }
      this.lanes.push(respace(dense, 4).map(({ x, z }) => ({ x, z })));
      used.add(a);
      used.add(b);
    });
    for (const n of used) if (!isEdge(n)) this.laneNodes.push(pos[n]!);
  }
}