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/building-detail.ts
import * as THREE from 'three';
import { FACADE } from './facades.js';
import type { BuildingLog, BuildingSpec, WallSpec } from './geo.js';
import { LAMP, LAMP_GLSL, NIGHT, NIGHT_GLSL } from './night.js';

/**
 * The buildings' finer detail on the higher graphics settings, in 3D, near the camera:
 * window sills, lintels, frames and glazing bars, keystones and shutters, ribbon-window
 * ledges, glass towers' mullion fins, shop fascias, balconies with railings; door frames,
 * surrounds, steps and canopies; storey ledges, corner pilasters, cornice brackets, and
 * gutters and downpipes under pitched roofs.
 *
 * Built from the building log (see BuildingLog in geo.ts): every wall as it was laid out.
 * The window pieces are placed by the same layout (in 64ths of a cell) as the façade
 * atlas draws them, so each sill sits on its painted sill. Every piece is a box, drawn
 * instanced (without the face against the wall): per 80 m chunk of the map and 24 m band
 * of height (each drawn by its own distance, so a tower's top floors drop out), a draw for
 * the fine pieces (glazing bars, thin frames: drawn only close up), one for the rest of the
 * small ones (neither casts a shadow) and one for the big ones (balconies, canopies).
 * Chunks are built a few at a time, nearest the camera first, and drawn only within range
 * (Medium nearer than High).
 */

const CHUNK = 80;
/** Each chunk's pieces are split into bands this tall (m), each drawn by its own distance (a tower's top floors are far off). */
const BAND = 24;
/** How long building chunks may take each frame (ms). */
const BUDGET = 4;
/** How far the detail's drawn on each level (m): none on 0. */
const RANGE = [0, 130, 260] as const;
/** How far the fine pieces are (glazing bars, thin frames: a pixel or less further off). */
const FINE_RANGE = [0, 70, 130] as const;
/** Pieces standing out no more than this (m) are fine. */
const FINE = 0.065;

/** A box in a wall's frame: centred u along it, y up, o out from it; w along, h up, d out. */
interface Piece {
  u: number;
  y: number;
  o: number;
  w: number;
  h: number;
  d: number;
  color: number;
}

/** What a piece is, for how it's drawn: fine (close up only), small, or big (casting a shadow). */
type Grade = 'fine' | 'small' | 'big';

/** Each piece's box, its colour, and its grade. */
interface Placed {
  m: THREE.Matrix4;
  color: number;
  grade: Grade;
}

/** A unit box without its back face (-z: the face against the wall), for every piece. */
const BOX = (() => {
  const g = new THREE.BoxGeometry(1, 1, 1);
  // (Its faces in order +x, -x, +y, -y, +z, -z: six indices each.)
  g.setIndex(Array.from(g.getIndex()!.array).slice(0, 30));
  g.clearGroups();
  return g;
})();

/** The pieces' material: plain colours, lit by the sun and the street lamps (instanced). */
function detailMaterial(): THREE.MeshLambertMaterial {
  const m = new THREE.MeshLambertMaterial({ color: 0xffffff });
  m.onBeforeCompile = (shader) => {
    shader.uniforms.nightLights = NIGHT;
    Object.assign(shader.uniforms, LAMP);
    shader.vertexShader = shader.vertexShader
      .replace('#include <common>', '#include <common>\nvarying vec3 vLampPos;\nvarying vec3 vLampN;')
      .replace(
        '#include <project_vertex>',
        `#include <project_vertex>
        {
          vec4 wp = vec4(transformed, 1.0);
          vec3 wn = objectNormal;
          #ifdef USE_INSTANCING
            wp = instanceMatrix * wp;
            wn = mat3(instanceMatrix) * wn;
          #endif
          vLampPos = (modelMatrix * wp).xyz;
          vLampN = normalize(mat3(modelMatrix) * wn);
        }`,
      );
    shader.fragmentShader = shader.fragmentShader
      .replace('#include <common>', `#include <common>\nvarying vec3 vLampPos;\nvarying vec3 vLampN;\n${NIGHT_GLSL}\n${LAMP_GLSL}`)
      .replace('#include <emissivemap_fragment>', '#include <emissivemap_fragment>\nif (nightLights > 0.001) totalEmissiveRadiance += lampLight(vLampPos, vLampN, diffuseColor.rgb) * nightLights;');
  };
  return m;
}

const hash = (a: number, b: number) => {
  let h = Math.imul(a, 374761393) ^ Math.imul(b, 668265263);
  h = Math.imul(h ^ (h >>> 13), 1274126177);
  return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
};

/** Colours of the pieces: shutters, shop signs, iron, metal, the gutters. */
const SHUTTERS = [0x3f5a4a, 0x2f4660, 0x6b3a32, 0x4a4d55, 0x5d6b3a];
const SIGNS = [0x2f4660, 0x6b2f3a, 0x2f5a4a, 0x8a6a2a, 0x3a3d42];
const IRON = 0x34363b;
const METAL = 0xb8bfc6;
const DARK = 0x4a4d52;
const GUTTER = 0xe6e2da;

/** Which kinds of building get which of the building-wide details. */
const LEDGED = new Set(['townhouse', 'flats', 'shops', 'town-house', 'farmhouse']);
const PILASTERED = new Set(['townhouse', 'flats', 'shops', 'town-house', 'church', 'walkup', 'farmhouse']);
const BRACKETED = new Set(['walkup', 'flats', 'shops']);

/**
 * The pieces for one wall (in its frame: u from its start a, y up, o out), from its window
 * and door styles laid out as the façade atlas draws them, and the building's own details.
 */
function wallPieces(w: WallSpec, b: BuildingSpec): Piece[] {
  const out: Piece[] = [];
  const len = Math.hypot(w.bx - w.ax, w.bz - w.az);
  if (len < 0.5) return out;
  const trim = b.trim ?? 0xe8e2d6;
  const add = (p: Piece) => {
    if (p.w > 0.005 && p.h > 0.005 && p.d > 0.005) out.push(p);
  };
  const glassTower = w.material === 'glass';
  if (w.bays > 0) {
    const bw = len / w.bays;
    const sh = w.sh;
    // A rect of the atlas (x, y, w, h in 64ths of the cell, y down from its top), in the
    // cell at bay k, row r: u0..u1 along the wall, y0..y1 up it. (The shader samples the
    // cell's middle 94%.)
    const fx = (px: number) => ((px / 64 - 0.03) / 0.94) * bw;
    const fy = (py: number) => ((1 - py / 64 - 0.03) / 0.94) * sh;
    const doorAt = new Map<number, number>();
    for (const d of w.doors) for (let k = d.bay; k < d.bay + d.bays; k++) doorAt.set(k, d.style);
    const style = Math.floor(w.facade + 0.001);
    const shutter = SHUTTERS[Math.floor(hash(b.id, 3) * SHUTTERS.length)]!;
    const sign = SIGNS[Math.floor(hash(b.id, 5) * SIGNS.length)]!;
    // The glass towers' and offices' lines, whole: a mullion fin up each bay line the full
    // height (above a door), and a band along the whole wall at each storey; the same for
    // ribbon windows' ledges and shops' fascias. (Not a piece per window: towers have
    // thousands.)
    const top = w.base + w.rows * sh;
    const run = (py: number, ph: number, o: number, d: number, color: number, rows: number[]) => {
      for (const r of rows) {
        const yb = w.base + r * sh;
        if (yb + sh < w.y0 + 0.2) continue;
        add({ u: len / 2, y: yb + (fy(py) + fy(py + ph)) / 2, o, w: len, h: fy(py) - fy(py + ph), d, color });
      }
    };
    const column = (px: number, pw: number, d: number, color: number, py0 = 0, py1 = 64) => {
      for (let k = 0; k < w.bays; k++) {
        // (From the storey above a door in its bay.)
        const lo = Math.max(w.y0, w.base + (doorAt.has(k) ? sh : 0) + fy(py1));
        const hi = top - sh + fy(py0);
        if (hi - lo < 0.2) continue;
        const u = k * bw + (fx(px) + fx(px + pw)) / 2;
        add({ u, y: (lo + hi) / 2, o: d / 2, w: fx(px + pw) - fx(px), h: hi - lo, d, color });
      }
    };
    const allRows = Array.from({ length: w.rows }, (_, r) => r);
    if (style === FACADE.curtain) {
      column(0, 2, 0.14, METAL);
      column(31, 2, 0.14, METAL);
      run(54, 4, 0.02, 0.04, METAL, allRows);
    } else if (style === FACADE.spandrel) {
      column(0, 3, 0.1, DARK);
      column(30, 4, 0.1, DARK);
      run(42, 3, 0.02, 0.04, DARK, allRows);
    } else if (style === FACADE.ribbon) {
      run(44, 2.5, glassTower ? 0.03 : 0.06, glassTower ? 0.06 : 0.12, glassTower ? METAL : trim, allRows);
      run(16, 2, 0.025, 0.05, glassTower ? METAL : trim, allRows);
    } else if (style === FACADE.shop) {
      // (The ground storey's: a door bay's fascia as well, the same sign.)
      run(4, 12, 0.075, 0.15, sign, [0]);
    }
    for (let r = 0; r < w.rows; r++) {
      const yb = w.base + r * sh;
      // (Not below the wall's foot: a wall stood on a slope.)
      if (yb + sh < w.y0 + 0.2) continue;
      for (let k = 0; k < w.bays; k++) {
        const u0 = k * bw;
        const box = (x: number, y: number, ww: number, hh: number, o: number, d: number, color: number) =>
          add({ u: u0 + (fx(x) + fx(x + ww)) / 2, y: yb + (fy(y) + fy(y + hh)) / 2, o, w: fx(x + ww) - fx(x), h: fy(y) - fy(y + hh), d, color });
        // (A slab standing out o.. from the wall, its depth d.)
        const slab = (x: number, y: number, ww: number, hh: number, d: number, color: number) => box(x, y, ww, hh, d / 2, d, color);
        const door = r === 0 ? doorAt.get(k) : undefined;
        if (door !== undefined) {
          doorPieces(door, box, slab, add, u0, yb, fx, trim);
          continue;
        }
        switch (style) {
          case FACADE.classic:
            slab(14, 10, 36, 5, 0.08, trim);
            slab(13, 45, 38, 4, 0.13, trim);
            slab(31, 15, 2, 30, 0.03, trim);
            slab(17, 29, 30, 2, 0.03, trim);
            break;
          case FACADE.arched:
            slab(30, 6, 4, 6, 0.07, trim);
            slab(18, 52, 28, 3, 0.13, trim);
            slab(31, 18, 2, 34, 0.03, trim);
            break;
          case FACADE.twin:
            for (const x of [9, 37]) {
              slab(x - 4, 16, 4, 28, 0.05, shutter);
              slab(x + 18, 16, 4, 28, 0.05, shutter);
              slab(x - 1, 44, 20, 3, 0.11, trim);
              slab(x - 1, 14, 20, 2, 0.05, trim);
            }
            break;
          case FACADE.ribbon:
            // (Its ledge and head: whole, above.)
            slab(0, 18, 2, 26, 0.06, DARK);
            slab(31, 18, 2, 26, 0.06, DARK);
            break;
          case FACADE.curtain:
          case FACADE.spandrel:
            // (All whole, above.)
            break;
          case FACADE.shop:
            // (Its fascia: whole, above.)
            slab(2, 54, 60, 7, 0.06, DARK);
            slab(31, 20, 2, 34, 0.04, DARK);
            slab(2, 18, 60, 2, 0.06, DARK);
            break;
          case FACADE.balcony: {
            // French windows' frame, and a balcony: its slab out 0.9 m, a railing round its edge.
            slab(31, 8, 2, 40, 0.03, trim);
            const yS = yb + fy(56);
            const yT = yb + fy(44);
            const ua = u0 + fx(8);
            const ub = u0 + fx(56);
            add({ u: (ua + ub) / 2, y: yS + 0.08, o: 0.45, w: ub - ua, h: 0.16, d: 0.9, color: 0xd9d4c8 });
            add({ u: (ua + ub) / 2, y: yT, o: 0.86, w: ub - ua, h: 0.05, d: 0.05, color: IRON });
            for (const ue of [ua + 0.02, ub - 0.02]) add({ u: ue, y: yT, o: 0.45, w: 0.05, h: 0.05, d: 0.9, color: IRON });
            for (let x = ua + 0.3; x < ub - 0.15; x += 0.3) add({ u: x, y: (yS + 0.16 + yT) / 2, o: 0.86, w: 0.025, h: yT - yS - 0.16, d: 0.025, color: IRON });
            break;
          }
        }
      }
    }
    // Storey ledges along the older buildings.
    if (LEDGED.has(b.kind) && w.rows > 1 && !glassTower)
      for (let r = 1; r < w.rows; r++) add({ u: len / 2, y: w.base + r * w.sh, o: 0.04, w: len + 0.08, h: 0.12, d: 0.08, color: trim });
    // Brackets under the cornice (it stands on the wall's plain top).
    if (BRACKETED.has(b.kind) && w.attic >= 0.8)
      for (let u = 0.45; u < len - 0.3; u += 0.9) add({ u, y: w.y1 - w.attic + 0.08, o: 0.16, w: 0.14, h: 0.22, d: 0.3, color: trim });
  }
  // Pilasters at the corners of the masonry buildings.
  if (PILASTERED.has(b.kind) && !glassTower) {
    const lo = Math.max(w.y0, 0);
    const hi = w.y1 - (w.bays ? w.attic : 0);
    for (const u of [0.16, len - 0.16]) add({ u, y: (lo + hi) / 2, o: 0.03, w: 0.32, h: hi - lo, d: 0.06, color: trim });
  }
  // Gutters along the eaves under a pitched roof, and a downpipe at each end.
  const roof = b.roof;
  if (roof && roof.type !== 'flat' && roof.type !== 'sawtooth' && Math.abs(w.y1 - roof.y) < 0.05 && eaves(w, b)) {
    add({ u: len / 2, y: roof.y - 0.06, o: 0.42, w: len + 0.9, h: 0.14, d: 0.14, color: GUTTER });
    for (const u of [0.18, len - 0.18]) {
      const lo = Math.max(w.y0, w.base);
      add({ u, y: (lo + roof.y) / 2, o: 0.1, w: 0.09, h: roof.y - lo, d: 0.09, color: GUTTER });
      add({ u, y: roof.y - 0.1, o: 0.26, w: 0.09, h: 0.09, d: 0.32, color: GUTTER });
    }
  }
  return out;
}

/** Is this wall under the eaves of its building's pitched roof (along the ridge)? Hipped roofs have eaves all round. */
function eaves(w: WallSpec, b: BuildingSpec): boolean {
  const roof = b.roof!;
  if (roof.type === 'hip') return true;
  const dx = Math.abs(w.bx - w.ax);
  const dz = Math.abs(w.bz - w.az);
  if (roof.along === 'x') return dx > dz;
  if (roof.along === 'z') return dz > dx;
  // (A turned roof: the walls running the way its ridge does.)
  if (roof.dir) return Math.abs((w.bx - w.ax) * roof.dir[0] + (w.bz - w.az) * roof.dir[1]) > 0.7 * Math.hypot(dx, dz);
  return false;
}

/** A door's pieces: its frame or surround, its step, and a canopy over the bigger ones. */
function doorPieces(
  style: number,
  box: (x: number, y: number, w: number, h: number, o: number, d: number, color: number) => void,
  slab: (x: number, y: number, w: number, h: number, d: number, color: number) => void,
  add: (p: Piece) => void,
  u0: number,
  yb: number,
  fx: (px: number) => number,
  trim: number,
): void {
  const step = (x0: number, x1: number, out: number) => add({ u: u0 + (fx(x0) + fx(x1)) / 2, y: yb + 0.07, o: out / 2, w: fx(x1) - fx(x0), h: 0.16, d: out, color: 0xbdb6a6 });
  switch (style) {
    case FACADE.shopDoor:
      // (Its fascia: the shop front's whole one, along the wall.)
      slab(25, 19, 1.5, 42, 0.06, DARK);
      slab(59.5, 19, 1.5, 42, 0.06, DARK);
      slab(25, 18, 36, 1.5, 0.06, DARK);
      break;
    case FACADE.entrance:
      slab(14, 12, 4, 49, 0.09, trim);
      slab(46, 12, 4, 49, 0.09, trim);
      box(12, 8, 40, 4, 0.5, 1.0, DARK);
      step(14, 50, 0.45);
      break;
    case FACADE.officeDoor:
      slab(13, 17, 1.5, 44, 0.06, DARK);
      slab(49.5, 17, 1.5, 44, 0.06, DARK);
      slab(13, 16, 38, 2, 0.06, DARK);
      break;
    case FACADE.lobby:
      slab(19, 23, 1.5, 38, 0.06, METAL);
      slab(43.5, 23, 1.5, 38, 0.06, METAL);
      slab(18, 20, 28, 4, 0.1, METAL);
      break;
    case FACADE.houseDoor:
      slab(20, 16, 4, 45, 0.06, trim);
      slab(40, 16, 4, 45, 0.06, trim);
      slab(19, 14, 26, 3, 0.08, trim);
      step(18, 46, 0.4);
      break;
    case FACADE.roller:
      slab(2, 8, 46, 4, 0.24, DARK);
      slab(3, 12, 1.5, 49, 0.08, DARK);
      slab(45.5, 12, 1.5, 49, 0.08, DARK);
      break;
    case FACADE.churchDoor:
      slab(11, 24, 5, 37, 0.14, trim);
      slab(48, 24, 5, 37, 0.14, trim);
      step(6, 58, 1.1);
      add({ u: u0 + (fx(10) + fx(54)) / 2, y: yb + 0.23, o: 0.35, w: fx(54) - fx(10), h: 0.16, d: 0.7, color: 0xbdb6a6 });
      break;
  }
}

/**
 * The parts of a wall hidden behind another wall of the same building standing just in
 * front of it (a factory's office block on its hall's front): u and y ranges along it,
 * where its pieces would poke through.
 */
function covers(log: BuildingLog, w: WallSpec, b: BuildingSpec): { u0: number; u1: number; y0: number; y1: number }[] {
  const len = Math.hypot(w.bx - w.ax, w.bz - w.az);
  const ux = (w.bx - w.ax) / len;
  const uz = (w.bz - w.az) / len;
  const out: { u0: number; u1: number; y0: number; y1: number }[] = [];
  for (const i of b.walls) {
    const v = log.walls[i]!;
    if (v === w) continue;
    const vl = Math.hypot(v.bx - v.ax, v.bz - v.az);
    // Facing the same way, and in front of this one by up to half a metre.
    if (((v.bx - v.ax) * ux + (v.bz - v.az) * uz) / vl < 0.99) continue;
    const off = (v.ax - w.ax) * -uz + (v.az - w.az) * ux;
    if (off < -0.001 || off > 0.5) continue;
    const a = (v.ax - w.ax) * ux + (v.az - w.az) * uz;
    const c = (v.bx - w.ax) * ux + (v.bz - w.az) * uz;
    out.push({ u0: Math.min(a, c) - 0.3, u1: Math.max(a, c) + 0.3, y0: v.y0 - 0.3, y1: v.y1 + 0.3 });
  }
  return out;
}

/** One chunk of the map's detail: its walls, its meshes once built, and its box (for range). */
interface Chunk {
  walls: number[];
  x0: number;
  z0: number;
  x1: number;
  z1: number;
  built: boolean;
  /** Its meshes: each a grade of piece in a band of height, and the box round its pieces (for its distance). */
  meshes: { mesh: THREE.InstancedMesh; grade: Grade; box: THREE.Box3 }[];
}

export class BuildingDetail {
  readonly root = new THREE.Group();
  private readonly chunks: Chunk[] = [];
  private readonly material = detailMaterial();
  private level: 0 | 1 | 2 = 0;

  constructor(private readonly log: BuildingLog) {
    this.root.name = 'building-detail';
    const byKey = new Map<string, Chunk>();
    log.walls.forEach((w, i) => {
      const mx = (w.ax + w.bx) / 2;
      const mz = (w.az + w.bz) / 2;
      const key = `${Math.floor(mx / CHUNK)},${Math.floor(mz / CHUNK)}`;
      let c = byKey.get(key);
      if (!c) {
        c = { walls: [], x0: Infinity, z0: Infinity, x1: -Infinity, z1: -Infinity, built: false, meshes: [] };
        byKey.set(key, c);
        this.chunks.push(c);
      }
      c.walls.push(i);
      c.x0 = Math.min(c.x0, w.ax, w.bx) - 2;
      c.x1 = Math.max(c.x1, w.ax, w.bx) + 2;
      c.z0 = Math.min(c.z0, w.az, w.bz) - 2;
      c.z1 = Math.max(c.z1, w.az, w.bz) + 2;
    });
    this.root.visible = false;
  }

  /** The detail on (1 Medium, 2 High: further) or off (0). */
  setLevel(level: 0 | 1 | 2): void {
    this.level = level;
    this.root.visible = level > 0;
  }

  /** How many chunks are built, of how many (for tests). */
  get progress(): { built: number; of: number } {
    return { built: this.chunks.filter((c) => c.built).length, of: this.chunks.length };
  }

  /** Each frame: chunks in range shown (and the nearest unbuilt ones built, a few ms' worth), the rest hidden. */
  update(eye: THREE.Vector3, budget = BUDGET): void {
    if (!this.level) return;
    const range = RANGE[this.level];
    const fine = FINE_RANGE[this.level];
    const dist = this.chunks.map((c) => Math.hypot(Math.max(c.x0 - eye.x, 0, eye.x - c.x1), Math.max(c.z0 - eye.z, 0, eye.z - c.z1)));
    // The nearest unbuilt chunks in range built first, then everything shown or hidden by distance.
    const near = this.chunks.map((c, i) => ({ c, d: dist[i]! })).filter((x) => x.d < range && !x.c.built);
    near.sort((a, b) => a.d - b.d);
    const t0 = performance.now();
    for (const { c } of near) {
      this.build(c);
      if (performance.now() - t0 > budget) break;
    }
    this.chunks.forEach((c, i) => {
      // (Only those of chunks in reach: then each mesh by its own distance, up and all.)
      const reach = dist[i]! < range;
      for (const m of c.meshes) m.mesh.visible = reach && m.box.distanceToPoint(eye) < (m.grade === 'fine' ? fine : range);
    });
  }

  /** How many pieces each kind of building has, all told, and how many of them are fine (for tests). */
  census(): Record<string, { pieces: number; fine: number }> {
    const out: Record<string, { pieces: number; fine: number }> = {};
    for (const w of this.log.walls) {
      const b = this.log.buildings[w.building];
      if (!b) continue;
      const c = (out[b.kind] ??= { pieces: 0, fine: 0 });
      for (const p of wallPieces(w, b)) {
        c.pieces++;
        if (p.d <= FINE && !(p.d >= 0.3 && p.w >= 0.3)) c.fine++;
      }
    }
    return out;
  }

  /** Build everything at once (for tests and screenshots). */
  buildAll(): void {
    for (const c of this.chunks) if (!c.built) this.build(c);
  }

  private build(c: Chunk): void {
    c.built = true;
    const placed: Placed[] = [];
    const U = new THREE.Vector3();
    const Y = new THREE.Vector3(0, 1, 0);
    const O = new THREE.Vector3();
    const P = new THREE.Vector3();
    for (const i of c.walls) {
      const w = this.log.walls[i]!;
      const b = this.log.buildings[w.building];
      if (!b) continue;
      const len = Math.hypot(w.bx - w.ax, w.bz - w.az);
      U.set((w.bx - w.ax) / len, 0, (w.bz - w.az) / len);
      // (Outward: the wall faces left going from a to b.)
      O.set(-U.z, 0, U.x);
      const hidden = covers(this.log, w, b);
      for (const p of wallPieces(w, b)) {
        if (hidden.some((c) => p.u >= c.u0 && p.u <= c.u1 && p.y >= c.y0 && p.y <= c.y1)) continue;
        P.set(w.ax, 0, w.az).addScaledVector(U, p.u).addScaledVector(O, p.o);
        P.y = p.y;
        const m = new THREE.Matrix4().makeBasis(U.clone().multiplyScalar(p.w), Y.clone().multiplyScalar(p.h), O.clone().multiplyScalar(p.d)).setPosition(P);
        placed.push({ m, color: p.color, grade: p.d >= 0.3 && p.w >= 0.3 ? 'big' : p.d <= FINE ? 'fine' : 'small' });
      }
    }
    // A mesh for each grade in each band of height.
    const groups = new Map<string, Placed[]>();
    for (const p of placed) {
      const key = `${p.grade}:${Math.floor(p.m.elements[13]! / BAND)}`;
      const g = groups.get(key);
      if (g) g.push(p);
      else groups.set(key, [p]);
    }
    for (const [key, list] of groups) {
      const grade = key.split(':')[0] as Grade;
      const big = grade === 'big';
      const box = new THREE.Box3();
      const at = new THREE.Vector3();
      for (const p of list) box.expandByPoint(at.setFromMatrixPosition(p.m));
      // (Out by the biggest piece's half-size, roughly.)
      box.expandByScalar(2);
      const mesh = new THREE.InstancedMesh(BOX, this.material, list.length);
      const color = new THREE.Color();
      list.forEach((p, k) => {
        mesh.setMatrixAt(k, p.m);
        mesh.setColorAt(k, color.setHex(p.color));
      });
      mesh.instanceMatrix.needsUpdate = true;
      if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
      mesh.computeBoundingSphere();
      mesh.castShadow = big;
      mesh.receiveShadow = true;
      mesh.matrixAutoUpdate = false;
      mesh.updateMatrix();
      // (Hidden until the next update decides.)
      mesh.visible = false;
      c.meshes.push({ mesh, grade, box });
      this.root.add(mesh);
    }
  }

  dispose(): void {
    for (const c of this.chunks) for (const m of c.meshes) m.mesh.dispose();
    this.material.dispose();
    this.root.removeFromParent();
  }
}