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/lamp-bake.ts
import * as THREE from 'three';
import { LAMP } from './night.js';

/**
 * Every street and highway lamp's light, shadows and all, baked into a top-down map (see
 * LAMP in night.ts, which the materials read). The lamps and what stands round them never
 * move, so each lamp's light is worked out once, on the GPU:
 *
 * 1. The map drawn once from straight above: the height of the top surface everywhere
 *    (roads, pavements, roofs, the highway's decks, treetops).
 * 2. For each lamp, a depth picture of the map from its head, looking down: what's in the
 *    way of its light (its own post, trees, benches, buildings, pillars).
 * 3. For each lamp, a disc drawn into the light map: at each point of the top surface, the
 *    light a three.js spot light there would give it (the same brightness, cone, fall-off
 *    and colour as the real lamp lights: see Game's lamp lights), unless the depth picture
 *    has something nearer the lamp, five taps softening the edge.
 *
 * It's done a few lamps a frame, nearest the car first, from the first time the lights come
 * on, so the game never waits for it. A lamp's light can be taken out again (drawn the
 * same way, subtracted): while it has a real light of its own, or once it's knocked over.
 */

/** A lamp: its head, the ground under it, the light's brightness (candela) and cone. */
export interface Lamp {
  x: number;
  y: number;
  z: number;
  ground: number;
  power: number;
  down: boolean;
}

/** The light map's resolution: metres a texel. */
const TEXEL = 0.5;
/** The lamps' cone (as the real lamp lights: Game) and reach. */
const ANGLE = 1.15;
const PENUMBRA = 0.85;
const CUTOFF = 20;
const SHADOW = 256;

const QUAD_VERT = /* glsl */ `
  uniform vec4 bounds;
  uniform vec4 rect;
  varying vec2 vXZ;
  void main() {
    vec2 xz = mix(rect.xy, rect.zw, uv);
    vXZ = xz;
    vec2 n = (xz - bounds.xy) / (bounds.zw - bounds.xy);
    gl_Position = vec4(n * 2.0 - 1.0, 0.0, 1.0);
  }
`;

export class LampBake {
  private readonly bounds: THREE.Vector4;
  private readonly light: THREE.WebGLRenderTarget;
  private readonly height: THREE.WebGLRenderTarget;
  private readonly shadow: THREE.WebGLRenderTarget;
  private readonly shadowCam = new THREE.PerspectiveCamera(120, 1, 0.2, CUTOFF);
  private readonly bakeScene = new THREE.Scene();
  private readonly quad: THREE.Mesh;
  private readonly quadMat: THREE.ShaderMaterial;
  private readonly heightMat: THREE.ShaderMaterial;
  private readonly depthMat = new THREE.MeshBasicMaterial({ colorWrite: false, side: THREE.DoubleSide });
  private readonly quadScene = new THREE.Scene();
  private readonly quadCam = new THREE.OrthographicCamera();
  /** Which lamps are in the map (+1), taken out (0), still to do (undefined). */
  private readonly state: (number | undefined)[] = [];
  private queue: number[] | null = null;
  private heightDone = false;
  /** All baked (so the queue's empty). */
  done = false;

  constructor(
    private readonly renderer: THREE.WebGLRenderer,
    private readonly root: THREE.Object3D,
    private readonly lamps: Lamp[],
    /** Show every chunk of the small things (the world culls them by distance). */
    private readonly showAll: () => void,
  ) {
    let x0 = Infinity;
    let x1 = -Infinity;
    let z0 = Infinity;
    let z1 = -Infinity;
    for (const l of lamps) {
      x0 = Math.min(x0, l.x);
      x1 = Math.max(x1, l.x);
      z0 = Math.min(z0, l.z);
      z1 = Math.max(z1, l.z);
    }
    const m = 22;
    this.bounds = new THREE.Vector4(x0 - m, z0 - m, x1 + m, z1 + m);
    const max = renderer.capabilities.maxTextureSize;
    const texel = Math.max(TEXEL, (x1 - x0 + 2 * m) / max, (z1 - z0 + 2 * m) / max);
    const w = Math.ceil((x1 - x0 + 2 * m) / texel);
    const h = Math.ceil((z1 - z0 + 2 * m) / texel);
    this.light = new THREE.WebGLRenderTarget(w, h, { type: THREE.HalfFloatType, format: THREE.RedFormat, depthBuffer: false, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter });
    this.height = new THREE.WebGLRenderTarget(w, h, { type: THREE.UnsignedByteType, format: THREE.RedFormat, depthBuffer: true, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter });
    this.shadow = new THREE.WebGLRenderTarget(SHADOW, SHADOW, { depthBuffer: true });
    this.shadow.depthTexture = new THREE.DepthTexture(SHADOW, SHADOW);
    this.shadowCam.up.set(0, 0, -1);
    this.heightMat = new THREE.ShaderMaterial({
      uniforms: { bounds: { value: this.bounds } },
      side: THREE.DoubleSide,
      vertexShader: /* glsl */ `
        uniform vec4 bounds;
        varying float vY;
        void main() {
          vec4 wp = modelMatrix * vec4(position, 1.0);
          vY = wp.y;
          vec2 n = (wp.xz - bounds.xy) / (bounds.zw - bounds.xy);
          gl_Position = vec4(n * 2.0 - 1.0, -wp.y / 200.0, 1.0);
        }
      `,
      fragmentShader: /* glsl */ `
        varying float vY;
        void main() { gl_FragColor = vec4((vY + 8.0) / 64.0, 0.0, 0.0, 1.0); }
      `,
    });
    this.quadMat = new THREE.ShaderMaterial({
      uniforms: {
        bounds: { value: this.bounds },
        rect: { value: new THREE.Vector4() },
        heightMap: { value: this.height.texture },
        shadowMap: { value: this.shadow.depthTexture },
        lampView: { value: new THREE.Matrix4() },
        lampPos: { value: new THREE.Vector3() },
        power: { value: 0 },
        near: { value: this.shadowCam.near },
        far: { value: this.shadowCam.far },
        texel: { value: 1 / SHADOW },
        cosOuter: { value: Math.cos(ANGLE) },
        cosInner: { value: Math.cos(ANGLE * (1 - PENUMBRA)) },
      },
      vertexShader: QUAD_VERT,
      fragmentShader: /* glsl */ `
        uniform vec4 bounds;
        uniform sampler2D heightMap;
        uniform sampler2D shadowMap;
        uniform mat4 lampView;
        uniform vec3 lampPos;
        uniform float power, near, far, texel, cosOuter, cosInner;
        varying vec2 vXZ;
        float linear(float d) { float z = d * 2.0 - 1.0; return 2.0 * near * far / (far + near - z * (far - near)); }
        void main() {
          vec2 uv = (vXZ - bounds.xy) / (bounds.zw - bounds.xy);
          float y = texture2D(heightMap, uv).r * 64.0 - 8.0;
          vec3 p = vec3(vXZ.x, y, vXZ.y);
          vec3 l = lampPos - p;
          float d = length(l);
          vec3 ld = l / d;
          // As three's spot light: the cone's soft edge, the inverse square with its cut-off,
          // on a surface facing up, through Lambert's 1/pi.
          float spot = smoothstep(cosOuter, cosInner, ld.y);
          float fall = 1.0 / max(d * d, 0.01) * pow(clamp(1.0 - pow(d / ${CUTOFF.toFixed(1)}, 4.0), 0.0, 1.0), 2.0);
          float e = power * max(ld.y, 0.0) * spot * fall / 3.14159265;
          if (e <= 0.0) discard;
          // In the lamp's depth picture: is anything nearer the lamp?
          vec4 c = lampView * vec4(p + vec3(0.0, 0.06, 0.0), 1.0);
          vec3 s = c.xyz / c.w * 0.5 + 0.5;
          if (s.x < 0.0 || s.y < 0.0 || s.x > 1.0 || s.y > 1.0 || c.w <= 0.0) discard;
          float me = linear(s.z);
          float lit = 0.0;
          for (int i = 0; i < 5; i++) {
            vec2 o = i == 0 ? vec2(0.0) : vec2(i == 1 ? 1.0 : i == 2 ? -1.0 : 0.0, i == 3 ? 1.0 : i == 4 ? -1.0 : 0.0);
            float there = linear(texture2D(shadowMap, s.xy + o * texel * 1.5).r);
            lit += step(me - 0.12 - me * 0.02, there);
          }
          gl_FragColor = vec4(e * lit / 5.0, 0.0, 0.0, 1.0);
        }
      `,
      blending: THREE.CustomBlending,
      blendSrc: THREE.OneFactor,
      blendDst: THREE.OneFactor,
      depthTest: false,
      depthWrite: false,
    });
    this.quad = new THREE.Mesh(new THREE.PlaneGeometry(1, 1), this.quadMat);
    this.quad.frustumCulled = false;
    this.quadScene.add(this.quad);
    LAMP.lampMap.value = this.light.texture;
    LAMP.lampHeight.value = this.height.texture;
    LAMP.lampBounds.value.copy(this.bounds);
  }

  /**
   * Each frame, once the lights are on: bake lamps for about budgetMs, nearest the given
   * point first (the order's set the first time).
   */
  step(near: { x: number; z: number }, budgetMs = 4): void {
    if (this.done) return;
    const t0 = performance.now();
    if (!this.heightDone) {
      this.bakeHeight();
      this.heightDone = true;
      return;
    }
    this.queue ??= this.lamps.map((_, i) => i).sort((a, b) => Math.hypot(this.lamps[a]!.x - near.x, this.lamps[a]!.z - near.z) - Math.hypot(this.lamps[b]!.x - near.x, this.lamps[b]!.z - near.z));
    let n = 0;
    while (this.queue.length && (n === 0 || performance.now() - t0 < budgetMs)) {
      const i = this.queue.shift()!;
      if (this.state[i] !== undefined) continue;
      if (!this.lamps[i]!.down) this.draw(i, 1);
      this.state[i] = this.lamps[i]!.down ? 0 : 1;
      n++;
    }
    if (!this.queue.length) this.done = true;
  }

  /** Take a lamp's light out of the map (it has a real light now, or it's been knocked over). */
  take(i: number): void {
    if (this.state[i] !== 1) {
      // (Not baked yet: it won't be, until it's given back.)
      if (this.state[i] === undefined) this.state[i] = 0;
      return;
    }
    this.draw(i, -1);
    this.state[i] = 0;
  }

  /** Put a lamp's light back in the map (unless it's been knocked over). */
  give(i: number): void {
    if (this.state[i] !== 0 || this.lamps[i]!.down || !this.heightDone) return;
    this.draw(i, 1);
    this.state[i] = 1;
  }

  /** The top surface's height everywhere, from above. */
  private bakeHeight(): void {
    const r = this.renderer;
    const was = r.getRenderTarget();
    const clear = r.getClearColor(new THREE.Color());
    const alpha = r.getClearAlpha();
    const culled: THREE.Object3D[] = [];
    this.withRoot(() => {
      this.root.traverse((o) => {
        if ((o as THREE.Mesh).isMesh && o.frustumCulled) {
          o.frustumCulled = false;
          culled.push(o);
        }
      });
      this.bakeScene.overrideMaterial = this.heightMat;
      r.setRenderTarget(this.height);
      r.setClearColor(0x000000, 1);
      r.clear();
      r.render(this.bakeScene, this.quadCam);
      for (const o of culled) o.frustumCulled = true;
    });
    r.setRenderTarget(this.light);
    r.setClearColor(0x000000, 1);
    r.clear();
    r.setClearColor(clear, alpha);
    r.setRenderTarget(was);
  }

  /** One lamp's light into the map (sign +1) or out of it (-1). */
  private draw(i: number, sign: 1 | -1): void {
    const l = this.lamps[i]!;
    const r = this.renderer;
    const was = r.getRenderTarget();
    // Its depth picture.
    const cam = this.shadowCam;
    cam.position.set(l.x, l.y, l.z);
    cam.lookAt(l.x, l.ground, l.z);
    cam.updateMatrixWorld();
    cam.updateProjectionMatrix();
    this.withRoot(() => {
      this.bakeScene.overrideMaterial = this.depthMat;
      r.setRenderTarget(this.shadow);
      r.clear();
      r.render(this.bakeScene, cam);
    });
    // Its disc, as far as its light reaches.
    const reach = Math.min(CUTOFF, Math.tan(ANGLE) * (l.y - l.ground)) + 1;
    const u = this.quadMat.uniforms;
    (u.rect!.value as THREE.Vector4).set(l.x - reach, l.z - reach, l.x + reach, l.z + reach);
    (u.lampView!.value as THREE.Matrix4).multiplyMatrices(cam.projectionMatrix, cam.matrixWorldInverse);
    (u.lampPos!.value as THREE.Vector3).set(l.x, l.y, l.z);
    u.power!.value = l.power;
    this.quadMat.blendEquation = sign > 0 ? THREE.AddEquation : THREE.ReverseSubtractEquation;
    // (Added to what's there: no clearing first.)
    const autoClear = r.autoClear;
    r.autoClear = false;
    r.setRenderTarget(this.light);
    r.render(this.quadScene, this.quadCam);
    r.autoClear = autoClear;
    r.setRenderTarget(was);
  }

  /** Render the world on its own (moved into the bake scene for the purpose), every chunk shown. */
  private withRoot(fn: () => void): void {
    const parent = this.root.parent;
    const r = this.renderer;
    const autoClear = r.autoClear;
    const shadows = r.shadowMap.enabled;
    r.autoClear = false;
    r.shadowMap.enabled = false;
    this.showAll();
    this.bakeScene.add(this.root);
    fn();
    parent?.add(this.root);
    r.autoClear = autoClear;
    r.shadowMap.enabled = shadows;
  }

  dispose(): void {
    this.light.dispose();
    this.height.dispose();
    this.shadow.dispose();
    this.quadMat.dispose();
    this.heightMat.dispose();
    this.depthMat.dispose();
    this.quad.geometry.dispose();
  }
}