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/geo.ts
import * as THREE from 'three';

/**
 * Low-poly geometry baking. The whole map is static, so every building, tree, road and
 * field is written as flat-shaded, vertex-coloured triangles into a few big buffers,
 * split into square chunks so the camera (and the shadow camera) can skip far ones.
 */

const _a = new THREE.Vector3();
const _b = new THREE.Vector3();
const _n = new THREE.Vector3();
const _c = new THREE.Color();

export type UV = readonly [number, number];

/** How a wall's windows are laid out (see Soup.facadeWall). */
export interface FacadeOpts {
  /** About how wide a bay (one window's width of wall) is, m. Without it the wall is plain. */
  bay?: number;
  /** About how tall a storey is, m. */
  storey?: number;
  /** Storeys are counted up from here (above a taller ground floor, say); below it the wall is plain. */
  base?: number;
  /** The window style and its variation (see facade() in world.ts). */
  facade?: number;
  /** Plain wall this tall along the top (where a cornice or a belfry goes), m. */
  attic?: number;
}

/**
 * An entrance in a wall's ground storey: a door style (a façade with its door in it) put
 * in place of the windows in one bay (or a few), at about `at` (0 to 1) along the wall.
 * every: another one every so many bays along (a row of shops, a door to each).
 */
export interface DoorOpts {
  style: number;
  at?: number;
  bays?: number;
  every?: number;
}

/** What a wall's made of (for its surface texture and its details, on the higher graphics settings). */
export type WallMaterial = 'brick' | 'stone' | 'plaster' | 'concrete' | 'glass' | 'siding' | 'metal' | 'wood';

/** The wall materials in order: a wall's vertices carry its material's place in this, plus 1 (0: not a wall). */
export const WALL_MATERIALS: readonly WallMaterial[] = ['brick', 'stone', 'plaster', 'concrete', 'glass', 'siding', 'metal', 'wood'];

/** The kinds of building (see the builders in world.ts). */
export type BuildingKind =
  | 'town-house'
  | 'walkup'
  | 'shops'
  | 'flats'
  | 'office'
  | 'tower-glass'
  | 'tower-stepped'
  | 'tower-deco'
  | 'tower-slab'
  | 'townhouse'
  | 'church'
  | 'shed'
  | 'factory'
  | 'house'
  | 'farmhouse'
  | 'cabin'
  | 'barn'
  | 'hangar'
  | 'control-tower'
  | 'port-office'
  | 'ship';

/**
 * One wall as it was built (see Soup.facadeWall): from a to b (facing left going from a
 * to b, seen from above, x right and z down), y0 to y1. With windows (bays > 0): that many
 * whole bays across, rows whole storeys sh tall up from base to y1 - attic, in the façade
 * style given; and the doors in its ground storey (each at a bay, so many bays wide).
 */
export interface WallSpec {
  building: number;
  ax: number;
  az: number;
  bx: number;
  bz: number;
  y0: number;
  y1: number;
  /** sRGB. */
  color: number;
  material: WallMaterial;
  bays: number;
  rows: number;
  base: number;
  sh: number;
  attic: number;
  /** The window style, and the fraction that varies it building to building. */
  facade: number;
  doors: { bay: number; bays: number; style: number }[];
}

/** A roof over a building: flat, pitched (its ridge along x or z, so high above y) or hipped. */
export interface RoofSpec {
  type: 'flat' | 'gable' | 'hip' | 'sawtooth';
  y: number;
  pitch: number;
  along?: 'x' | 'z';
  /** A turned roof's ridge: the way it runs (x, z). */
  dir?: [number, number];
  color: number;
}

/** A building as built: what it is, its walls (indices into the log's), the box round them, and its roof. */
export interface BuildingSpec {
  id: number;
  kind: BuildingKind;
  walls: number[];
  x0: number;
  z0: number;
  x1: number;
  z1: number;
  /** The tops of its walls (the highest), m. */
  height: number;
  roof?: RoofSpec;
  /** Its trim (cornices, ledges, sills), sRGB, where it has one. */
  trim?: number;
}

/**
 * The record of every building as built: the walls each Soup with this log lays out, put
 * under the building being built (see within()). For the buildings' details on the higher
 * graphics settings, and for tests.
 */
export class BuildingLog {
  readonly buildings: BuildingSpec[] = [];
  readonly walls: WallSpec[] = [];
  /** The building being built now, and what its walls are being built of. */
  current: BuildingSpec | null = null;
  material: WallMaterial = 'plaster';
  /** Walls built on a soup with this log but outside any building (there should be none). */
  stray = 0;

  /**
   * Build a building: its walls (laid out inside fn) recorded under it. fn can set its kind
   * and roof (on current) and its walls' material as it goes. A building that turns out to
   * have no walls (its lot taken, say) isn't kept.
   */
  within<T>(kind: BuildingKind, material: WallMaterial, fn: () => T): T {
    const was = [this.current, this.material] as const;
    const b: BuildingSpec = { id: this.buildings.length, kind, walls: [], x0: Infinity, z0: Infinity, x1: -Infinity, z1: -Infinity, height: -Infinity };
    this.current = b;
    this.material = material;
    try {
      return fn();
    } finally {
      if (b.walls.length) this.buildings.push(b);
      [this.current, this.material] = was;
    }
  }

  /** A plain box's walls, built some other way (on a soup without the log), recorded as Soup.box would lay them out. */
  plainBox(x0: number, y0: number, z0: number, x1: number, y1: number, z1: number, color: number): void {
    const faces = [
      [x0, z1, x1, z1],
      [x1, z0, x0, z0],
      [x1, z1, x1, z0],
      [x0, z0, x0, z1],
    ] as const;
    for (const [ax, az, bx, bz] of faces) this.add({ ax, az, bx, bz, y0, y1, color, bays: 0, rows: 0, base: y0, sh: 0, attic: 0, facade: 0, doors: [] });
  }

  /** A wall just built (by Soup.facadeWall). */
  add(w: Omit<WallSpec, 'building' | 'material'>): void {
    const b = this.current;
    if (!b) {
      this.stray++;
      return;
    }
    // (Its id once kept: buildings without walls aren't, so it's the next one.)
    b.id = this.buildings.length;
    b.walls.push(this.walls.length);
    this.walls.push({ ...w, building: b.id, material: this.material });
    b.x0 = Math.min(b.x0, w.ax, w.bx);
    b.x1 = Math.max(b.x1, w.ax, w.bx);
    b.z0 = Math.min(b.z0, w.az, w.bz);
    b.z1 = Math.max(b.z1, w.az, w.bz);
    b.height = Math.max(b.height, w.y1);
  }
}

/** Where a door went: the middle of its foot, the way along the wall, how wide and tall it is. */
export interface DoorSpot {
  x: number;
  z: number;
  /** Unit vector along the wall (a to b). */
  ux: number;
  uz: number;
  w: number;
  y0: number;
  y1: number;
}

/** One growing triangle soup. */
export class Soup {
  readonly pos: number[] = [];
  readonly nor: number[] = [];
  readonly col: number[] = [];
  readonly uv: number[] = [];
  /** Which façade (window style) each vertex's texture tile is drawn from. */
  readonly facade: number[] = [];
  /** Each vertex's wall material (see WALL_MATERIALS: its place plus 1, 0 for none). */
  readonly wallMat: number[] = [];
  /** Each vertex's window cell: the bay's width and the storey's height, m (0 where there are no windows), and 1 on a tower (0 elsewhere). */
  readonly cell: number[] = [];
  /** What kind of ground each vertex is (see SURFACE), for the ground's detail shader. */
  readonly surf: number[] = [];
  /** How brightly each vertex glows once the lights come on at night (lamp lenses), 0 for none. */
  readonly glow: number[] = [];
  /** The ground kind for triangles being added now. */
  surface = 0;
  /** The glow for triangles being added now. */
  glowing = 0;
  /** The façade for walls being added now (see box's facade option). */
  private face = 0;
  /** The wall material and window cell for walls being added now. */
  private mat = 0;
  private cellSize: [number, number, number] = [0, 0, 0];

  /** The baked geometry, once build() has run. */
  geometry: THREE.BufferGeometry | null = null;

  constructor(
    readonly withUv = false,
    /** Where the walls built here are recorded, if anywhere. */
    readonly log: BuildingLog | null = null,
  ) {}

  get empty(): boolean {
    return this.pos.length === 0;
  }

  /** A triangle, counter-clockwise seen from the side it faces. */
  tri(
    ax: number, ay: number, az: number,
    bx: number, by: number, bz: number,
    cx: number, cy: number, cz: number,
    color: number | THREE.Color,
    uvs?: readonly [UV, UV, UV],
  ): void {
    _a.set(bx - ax, by - ay, bz - az);
    _b.set(cx - ax, cy - ay, cz - az);
    _n.crossVectors(_a, _b).normalize();
    const col = typeof color === 'number' ? _c.setHex(color) : color;
    this.pos.push(ax, ay, az, bx, by, bz, cx, cy, cz);
    this.surf.push(this.surface, this.surface, this.surface);
    this.glow.push(this.glowing, this.glowing, this.glowing);
    for (let i = 0; i < 3; i++) {
      this.nor.push(_n.x, _n.y, _n.z);
      this.col.push(col.r, col.g, col.b);
    }
    if (this.withUv) {
      const u = uvs ?? [[0.02, 0.02], [0.02, 0.02], [0.02, 0.02]];
      for (const [x, y] of u) this.uv.push(x, y);
      this.facade.push(this.face, this.face, this.face);
      this.wallMat.push(this.mat, this.mat, this.mat);
      for (let i = 0; i < 3; i++) this.cell.push(this.cellSize[0], this.cellSize[1], this.cellSize[2]);
    }
  }

  /** A quad like quad(), but with its own colour at each corner, shaded smoothly between. */
  shadedQuad(
    a: readonly [number, number, number],
    b: readonly [number, number, number],
    c: readonly [number, number, number],
    d: readonly [number, number, number],
    colors: readonly [THREE.Color, THREE.Color, THREE.Color, THREE.Color],
  ): void {
    // Each triangle goes in in one colour, then its last two corners are recoloured.
    const recolour = (p: THREE.Color, q: THREE.Color) => {
      const n = this.col.length;
      this.col.splice(n - 6, 6, p.r, p.g, p.b, q.r, q.g, q.b);
    };
    this.tri(a[0], a[1], a[2], b[0], b[1], b[2], c[0], c[1], c[2], colors[0]);
    recolour(colors[1], colors[2]);
    this.tri(a[0], a[1], a[2], c[0], c[1], c[2], d[0], d[1], d[2], colors[0]);
    recolour(colors[2], colors[3]);
  }

  /** A quad a-b-c-d, counter-clockwise seen from the side it faces. */
  quad(
    a: readonly [number, number, number],
    b: readonly [number, number, number],
    c: readonly [number, number, number],
    d: readonly [number, number, number],
    color: number | THREE.Color,
    uvs?: readonly [UV, UV, UV, UV],
  ): void {
    this.tri(a[0], a[1], a[2], b[0], b[1], b[2], c[0], c[1], c[2], color, uvs && [uvs[0], uvs[1], uvs[2]]);
    this.tri(a[0], a[1], a[2], c[0], c[1], c[2], d[0], d[1], d[2], color, uvs && [uvs[0], uvs[2], uvs[3]]);
  }

  /** Flat rectangle lying on the ground at height y. */
  flat(x0: number, z0: number, x1: number, z1: number, y: number, color: number | THREE.Color, surface?: number): void {
    const was = this.surface;
    this.surface = surface ?? was;
    this.quad([x0, y, z0], [x0, y, z1], [x1, y, z1], [x1, y, z0], color);
    this.surface = was;
  }

  /**
   * An axis-aligned box (no bottom face). With bays set, the walls get windows, as
   * facadeWall lays them out. door: an entrance in one face's ground storey (side: 0 the
   * +z face, 1 -z, 2 +x, 3 -x). Returns where the door went.
   */
  box(
    x0: number, y0: number, z0: number, x1: number, y1: number, z1: number,
    color: number | THREE.Color,
    opts: FacadeOpts & { top?: number | THREE.Color; surface?: number; door?: DoorOpts & { side: number } } = {},
  ): DoorSpot | null {
    const top = opts.top ?? color;
    const door = opts.door;
    // +z face, -z face, +x face, -x face (each from a to b, facing out).
    const faces: [number, number, number, number][] = [
      [x0, z1, x1, z1],
      [x1, z0, x0, z0],
      [x1, z1, x1, z0],
      [x0, z0, x0, z1],
    ];
    let spot: DoorSpot | null = null;
    faces.forEach(([ax, az, bx, bz], k) => {
      const at = this.facadeWall(ax, az, bx, bz, y0, y1, color, opts, door?.side === k ? door : undefined);
      spot ??= at;
    });
    this.untag();
    const was = this.surface;
    this.surface = opts.surface ?? was;
    this.quad([x0, y1, z1], [x1, y1, z1], [x1, y1, z0], [x0, y1, z0], top);
    this.surface = was;
    return spot;
  }

  /** An upright wall from (ax, az) to (bx, bz), facing to the left going from a to b (seen from above, x right and z down), laid out as facadeWall does. */
  wall(
    ax: number, az: number, bx: number, bz: number, y0: number, y1: number,
    color: number | THREE.Color,
    opts: FacadeOpts = {},
    door?: DoorOpts,
  ): DoorSpot | null {
    const spot = this.facadeWall(ax, az, bx, bz, y0, y1, color, opts, door);
    this.untag();
    return spot;
  }

  /** Back to untagged triangles (not a wall's) after a wall. */
  private untag(): void {
    this.mat = 0;
    this.cellSize = [0, 0, 0];
  }

  /**
   * A wall with windows from the façade atlas, each a whole window: as many bays across as
   * fit nearest to the bay width asked for (stretched a little to fit exactly; too narrow
   * for one and it's plain wall), and whole storeys up from the base, stretched the same
   * way. Below the base and in the attic it's plain wall. A door takes the place of the
   * windows in its bay (or bays) of the ground storey.
   */
  private facadeWall(ax: number, az: number, bx: number, bz: number, y0: number, y1: number, color: number | THREE.Color, opts: FacadeOpts, door?: DoorOpts): DoorSpot | null {
    // (Its material, from the building log: plaster where there's none.)
    this.mat = WALL_MATERIALS.indexOf(this.log?.material ?? 'plaster') + 1;
    this.cellSize = [0, 0, 0];
    const plain = (lo: number, hi: number) => {
      if (hi - lo < 0.001) return;
      this.quad([ax, lo, az], [bx, lo, bz], [bx, hi, bz], [ax, hi, az], color);
    };
    const len = Math.hypot(bx - ax, bz - az);
    const bay = opts.bay;
    const st = opts.storey ?? 3.5;
    const base = opts.base ?? 0;
    const top = y1 - (opts.attic ?? 0);
    const from = Math.max(y0, base);
    const n = bay && len >= bay * 0.6 ? Math.max(1, Math.round(len / bay)) : 0;
    const rows = Math.round((top - base) / st);
    const hex = typeof color === 'number' ? color : color.getHex();
    const record = (bays: number, sh: number, doors: WallSpec['doors']) =>
      this.log?.add({ ax, az, bx, bz, y0, y1, color: hex, bays, rows: bays ? rows : 0, base, sh, attic: bays ? (opts.attic ?? 0) : 0, facade: opts.facade ?? 0, doors });
    if (!n || rows < 1 || top - from < 0.3) {
      plain(y0, y1);
      record(0, 0, []);
      return null;
    }
    // The storey height that makes the rows whole.
    const sh = (top - base) / rows;
    plain(y0, from);
    plain(top, y1);
    this.cellSize = [len / n, sh, this.log?.current?.kind.startsWith('tower') ? 1 : 0];
    const v = (y: number) => (y - base) / sh;
    const face = opts.facade ?? 0;
    const seed = face - Math.floor(face);
    // A run of bays u0 to u1 (counted in bays), from lo to hi up the wall, in a façade.
    const part = (u0: number, u1: number, lo: number, hi: number, f: number) => {
      if (u1 <= u0 || hi - lo < 0.001) return;
      const t0 = u0 / n;
      const t1 = u1 / n;
      this.face = f;
      this.quad(
        [ax + (bx - ax) * t0, lo, az + (bz - az) * t0],
        [ax + (bx - ax) * t1, lo, az + (bz - az) * t1],
        [ax + (bx - ax) * t1, hi, az + (bz - az) * t1],
        [ax + (bx - ax) * t0, hi, az + (bz - az) * t0],
        color,
        [[u0, v(lo)], [u1, v(lo)], [u1, v(hi)], [u0, v(hi)]],
      );
      this.face = 0;
    };
    // The door (or doors) only where the wall comes down to the ground storey.
    const span = Math.min(n, door?.bays ?? 1);
    // (A wall stood on the pavement, a step up, still has its ground storey.)
    if (!door || y0 > base + 0.5) {
      part(0, n, from, top, face);
      record(n, sh, []);
      return null;
    }
    const first = Math.max(0, Math.min(n - span, Math.round((door.at ?? 0.5) * n - span / 2)));
    // (Spread both ways from the first door, every so many bays.)
    const every = door.every && door.every > span ? door.every : 0;
    const doors = [first];
    if (every) {
      for (let k = first - every; k >= 0; k -= every) doors.unshift(k);
      for (let k = first + every; k + span <= n; k += every) doors.push(k);
    }
    const ground = base + sh;
    part(0, n, ground, top, face);
    let u = 0;
    for (const k of doors) {
      part(u, k, from, ground, face);
      part(k, k + span, from, ground, door.style + seed);
      u = k + span;
    }
    part(u, n, from, ground, face);
    const t = (first + span / 2) / n;
    const spot = { x: ax + (bx - ax) * t, z: az + (bz - az) * t, ux: (bx - ax) / len, uz: (bz - az) / len, w: (len / n) * span, y0: from, y1: ground };
    record(
      n,
      sh,
      doors.map((k) => ({ bay: k, bays: span, style: door.style })),
    );
    return spot;
  }

  /** A pitched roof over a rectangle, its ridge running along x or z. */
  gable(x0: number, z0: number, x1: number, z1: number, y: number, h: number, color: number, along: 'x' | 'z', gableColor = color): void {
    if (along === 'x') {
      const zm = (z0 + z1) / 2;
      this.quad([x0, y, z1], [x1, y, z1], [x1, y + h, zm], [x0, y + h, zm], color);
      this.quad([x1, y, z0], [x0, y, z0], [x0, y + h, zm], [x1, y + h, zm], color);
      this.tri(x1, y, z1, x1, y, z0, x1, y + h, zm, gableColor);
      this.tri(x0, y, z0, x0, y, z1, x0, y + h, zm, gableColor);
    } else {
      const xm = (x0 + x1) / 2;
      this.quad([x1, y, z1], [x1, y, z0], [xm, y + h, z0], [xm, y + h, z1], color);
      this.quad([x0, y, z0], [x0, y, z1], [xm, y + h, z1], [xm, y + h, z0], color);
      this.tri(x0, y, z1, x1, y, z1, xm, y + h, z1, gableColor);
      this.tri(x1, y, z0, x0, y, z0, xm, y + h, z0, gableColor);
    }
  }

  /** A hipped roof over a rectangle: four slopes up to a ridge along the longer side. */
  hip(x0: number, z0: number, x1: number, z1: number, y: number, h: number, color: number | THREE.Color): void {
    const along = x1 - x0 >= z1 - z0;
    const inset = (along ? z1 - z0 : x1 - x0) / 2;
    if (along) {
      const zm = (z0 + z1) / 2;
      const ra = x0 + inset;
      const rb = x1 - inset;
      this.quad([x0, y, z1], [x1, y, z1], [rb, y + h, zm], [ra, y + h, zm], color);
      this.quad([x1, y, z0], [x0, y, z0], [ra, y + h, zm], [rb, y + h, zm], color);
      this.tri(x1, y, z1, x1, y, z0, rb, y + h, zm, color);
      this.tri(x0, y, z0, x0, y, z1, ra, y + h, zm, color);
    } else {
      const xm = (x0 + x1) / 2;
      const ra = z0 + inset;
      const rb = z1 - inset;
      this.quad([x1, y, z1], [x1, y, z0], [xm, y + h, ra], [xm, y + h, rb], color);
      this.quad([x0, y, z0], [x0, y, z1], [xm, y + h, rb], [xm, y + h, ra], color);
      this.tri(x0, y, z1, x1, y, z1, xm, y + h, rb, color);
      this.tri(x1, y, z0, x0, y, z0, xm, y + h, ra, color);
    }
  }

  /** Upright prism (or a cone/frustum when the top radius differs). */
  cylinder(x: number, z: number, r0: number, r1: number, y0: number, y1: number, seg: number, color: number | THREE.Color, rot = 0, cap = true): void {
    for (let i = 0; i < seg; i++) {
      const a0 = rot + (i / seg) * Math.PI * 2;
      const a1 = rot + ((i + 1) / seg) * Math.PI * 2;
      const c0 = Math.cos(a0), s0 = Math.sin(a0), c1 = Math.cos(a1), s1 = Math.sin(a1);
      if (r1 > 0.001)
        this.quad([x + c0 * r0, y0, z + s0 * r0], [x + c0 * r1, y1, z + s0 * r1], [x + c1 * r1, y1, z + s1 * r1], [x + c1 * r0, y0, z + s1 * r0], color);
      else this.tri(x + c0 * r0, y0, z + s0 * r0, x, y1, z, x + c1 * r0, y0, z + s1 * r0, color);
      if (cap && r1 > 0.001) this.tri(x, y1, z, x + c1 * r1, y1, z + s1 * r1, x + c0 * r1, y1, z + s0 * r1, color);
    }
  }

  /** A lumpy low-poly ball (an icosahedron, its corners jittered). */
  blob(x: number, y: number, z: number, r: number, color: number | THREE.Color, rand: () => number, squash = 1): void {
    const g = BLOB;
    const p = g.attributes.position as THREE.BufferAttribute;
    const jit: number[] = [];
    for (let i = 0; i < BLOB_CORNERS.length; i++) jit.push(0.85 + rand() * 0.3);
    const v = (i: number): [number, number, number] => {
      const k = jit[BLOB_INDEX[i]!]!;
      return [x + p.getX(i) * r * k, y + p.getY(i) * r * k * squash, z + p.getZ(i) * r * k];
    };
    for (let i = 0; i < p.count; i += 3) {
      const a = v(i), b = v(i + 1), c = v(i + 2);
      this.tri(a[0], a[1], a[2], b[0], b[1], b[2], c[0], c[1], c[2], color);
    }
  }

  build(): THREE.BufferGeometry {
    const g = new THREE.BufferGeometry();
    g.setAttribute('position', new THREE.Float32BufferAttribute(this.pos, 3));
    g.setAttribute('normal', new THREE.Float32BufferAttribute(this.nor, 3));
    g.setAttribute('color', new THREE.Float32BufferAttribute(this.col, 3));
    g.setAttribute('surf', new THREE.Float32BufferAttribute(this.surf, 1));
    // (Only where something glows: elsewhere the shaders read it as 0.)
    if (this.glow.some((v) => v > 0)) g.setAttribute('glow', new THREE.Float32BufferAttribute(this.glow, 1));
    if (this.withUv) {
      g.setAttribute('uv', new THREE.Float32BufferAttribute(this.uv, 2));
      g.setAttribute('facade', new THREE.Float32BufferAttribute(this.facade, 1));
      g.setAttribute('wallMat', new THREE.Float32BufferAttribute(this.wallMat, 1));
      g.setAttribute('cell', new THREE.Float32BufferAttribute(this.cell, 3));
    }
    g.computeBoundingSphere();
    g.computeBoundingBox();
    this.geometry = g;
    return g;
  }
}

// The icosahedron's triangles, with each corner tagged by which of the 12 shared
// vertices it is, so a blob's jitter keeps the surface closed.
const BLOB = new THREE.IcosahedronGeometry(1, 0);
const BLOB_CORNERS: THREE.Vector3[] = [];
const BLOB_INDEX: number[] = [];
{
  const p = BLOB.attributes.position as THREE.BufferAttribute;
  for (let i = 0; i < p.count; i++) {
    const v = new THREE.Vector3(p.getX(i), p.getY(i), p.getZ(i));
    let k = BLOB_CORNERS.findIndex((c) => c.distanceToSquared(v) < 1e-6);
    if (k < 0) {
      k = BLOB_CORNERS.length;
      BLOB_CORNERS.push(v);
    }
    BLOB_INDEX.push(k);
  }
}

/** Soups bucketed into square chunks of the map, one set per material. */
export class Chunked {
  private readonly cells = new Map<string, Soup>();

  constructor(
    private readonly size: number,
    private readonly withUv = false,
    private readonly log: BuildingLog | null = null,
  ) {}

  /** The soup for whatever sits at (x, z). */
  at(x: number, z: number): Soup {
    const key = `${Math.floor(x / this.size)},${Math.floor(z / this.size)}`;
    let s = this.cells.get(key);
    if (!s) {
      s = new Soup(this.withUv, this.log);
      this.cells.set(key, s);
    }
    return s;
  }

  /** Every soup in it. */
  soups(): IterableIterator<Soup> {
    return this.cells.values();
  }

  meshes(material: THREE.Material, shadows: { cast: boolean; receive: boolean }): THREE.Mesh[] {
    const out: THREE.Mesh[] = [];
    for (const soup of this.cells.values()) {
      if (soup.empty) continue;
      const m = new THREE.Mesh(soup.build(), material);
      // Knocked-over props rewrite their part of the buffer.
      (m.geometry.attributes.position as THREE.BufferAttribute).setUsage(THREE.DynamicDrawUsage);
      m.castShadow = shadows.cast;
      m.receiveShadow = shadows.receive;
      m.matrixAutoUpdate = false;
      out.push(m);
    }
    return out;
  }
}

/** Small deterministic random generator, so the map is the same every visit. */
export function rng(seed: number): () => number {
  let a = seed >>> 0;
  return () => {
    a = (a + 0x6d2b79f5) >>> 0;
    let t = a;
    t = Math.imul(t ^ (t >>> 15), t | 1);
    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}