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/post.ts
import * as THREE from 'three';
import { EffectComposer } from 'three/examples/jsm/postprocessing/EffectComposer.js';
import { Pass, FullScreenQuad } from 'three/examples/jsm/postprocessing/Pass.js';
import { UnrealBloomPass } from 'three/examples/jsm/postprocessing/UnrealBloomPass.js';
import { OutputPass } from 'three/examples/jsm/postprocessing/OutputPass.js';
import { ShaderPass } from 'three/examples/jsm/postprocessing/ShaderPass.js';

/**
 * Post-processing, for the medium and high graphics settings: the scene drawn into a
 * multisampled HDR target, then
 *
 * - ambient occlusion (high only): the creases where walls meet the ground, under eaves
 *   and between buildings darkened a little, worked out from the depth alone (no second
 *   pass over the scene), at half resolution and softened;
 * - bloom: only what's brighter than white glows (lit windows, street lamps and car lights
 *   at night, the glint of the low sun);
 * - tone mapping (the same filmic curve as without);
 * - a light grade: a touch more contrast and colour, warmer lights and cooler shadows.
 *
 * None of it touches the sky: every effect reads the depth, and leaves the pixels where
 * nothing's nearer than the far plane (where the sky is drawn) exactly as they were.
 */

/** The scene into the composer's target, noting where its depth went (for the passes after). */
class ScenePass extends Pass {
  depth: THREE.DepthTexture | null = null;
  constructor(
    private readonly scene: THREE.Scene,
    private readonly camera: THREE.Camera,
  ) {
    super();
    this.needsSwap = false;
  }
  override render(renderer: THREE.WebGLRenderer, _write: THREE.WebGLRenderTarget, read: THREE.WebGLRenderTarget): void {
    renderer.setRenderTarget(read);
    renderer.clear();
    renderer.render(this.scene, this.camera);
    this.depth = read.depthTexture;
  }
}

const QUAD_VERT = /* glsl */ `
  varying vec2 vUv;
  void main() {
    vUv = uv;
    gl_Position = vec4(position.xy, 0.0, 1.0);
  }
`;

/** View-space position from depth (shared by the AO shaders). */
const VIEW_POS = /* glsl */ `
  uniform mat4 invProj;
  vec3 viewPos(vec2 uv, float depth) {
    vec4 p = invProj * vec4(uv * 2.0 - 1.0, depth * 2.0 - 1.0, 1.0);
    return p.xyz / p.w;
  }
`;

/**
 * Ambient occlusion from depth: for each pixel, 12 points in the half-sphere over its
 * surface (radius RADIUS m, turned pixel by pixel), each counting as occluded if the
 * depth buffer has something in front of it there, nearer than the radius (so a distant
 * wall behind doesn't count). Written at half resolution; the composite softens it.
 */
class AOPass extends Pass {
  private readonly target = new THREE.WebGLRenderTarget(1, 1, { type: THREE.HalfFloatType });
  private readonly aoQuad: FullScreenQuad;
  private readonly mixQuad: FullScreenQuad;
  private readonly aoMat: THREE.ShaderMaterial;
  private readonly mixMat: THREE.ShaderMaterial;

  constructor(
    private readonly camera: THREE.PerspectiveCamera,
    private readonly scenePass: ScenePass,
  ) {
    super();
    this.aoMat = new THREE.ShaderMaterial({
      uniforms: { tDepth: { value: null }, invProj: { value: new THREE.Matrix4() }, proj: { value: new THREE.Matrix4() }, radius: { value: 1.6 } },
      vertexShader: QUAD_VERT,
      fragmentShader: /* glsl */ `
        uniform sampler2D tDepth;
        uniform mat4 proj;
        uniform float radius;
        varying vec2 vUv;
        ${VIEW_POS}
        void main() {
          float d = texture2D(tDepth, vUv).r;
          if (d >= 0.99999) { gl_FragColor = vec4(1.0); return; }
          vec3 p = viewPos(vUv, d);
          vec3 n = normalize(cross(dFdx(p), dFdy(p)));
          // A basis about the normal, turned by a per-pixel angle.
          float turn = 6.2831853 * fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715))));
          vec3 t = normalize(abs(n.y) < 0.99 ? cross(n, vec3(0.0, 1.0, 0.0)) : cross(n, vec3(1.0, 0.0, 0.0)));
          vec3 b = cross(n, t);
          float r = radius * clamp(-p.z / 40.0, 0.35, 1.0);
          float occ = 0.0;
          for (int i = 0; i < 12; i++) {
            float fi = float(i);
            float a = fi * 2.39996323 + turn;
            float k = (fi + 0.5) / 12.0;
            float lift = sqrt(1.0 - k);
            vec3 dir = (t * cos(a) + b * sin(a)) * sqrt(k) + n * lift;
            vec3 s = p + dir * r * (0.25 + 0.75 * k * k);
            vec4 c = proj * vec4(s, 1.0);
            vec2 suv = c.xy / c.w * 0.5 + 0.5;
            if (suv.x < 0.0 || suv.x > 1.0 || suv.y < 0.0 || suv.y > 1.0) continue;
            float sz = viewPos(suv, texture2D(tDepth, suv).r).z;
            // (Only what's within reach counts: nothing far in front, so no halos round outlines.)
            float near = 1.0 - smoothstep(r * 0.5, r * 1.2, abs(p.z - sz));
            occ += step(s.z + 0.05, sz) * near;
          }
          gl_FragColor = vec4(vec3(1.0 - occ / 12.0), 1.0);
        }
      `,
    });
    this.mixMat = new THREE.ShaderMaterial({
      uniforms: { tDiffuse: { value: null }, tAO: { value: null }, tDepth: { value: null }, texel: { value: new THREE.Vector2() }, strength: { value: 0.9 } },
      vertexShader: QUAD_VERT,
      fragmentShader: /* glsl */ `
        uniform sampler2D tDiffuse;
        uniform sampler2D tAO;
        uniform sampler2D tDepth;
        uniform vec2 texel;
        uniform float strength;
        varying vec2 vUv;
        void main() {
          vec4 c = texture2D(tDiffuse, vUv);
          if (texture2D(tDepth, vUv).r >= 0.99999) { gl_FragColor = c; return; }
          // Softened: the half-resolution AO, nine taps.
          float ao = 0.0;
          for (int x = -1; x <= 1; x++)
            for (int y = -1; y <= 1; y++) ao += texture2D(tAO, vUv + vec2(float(x), float(y)) * texel * 1.5).r;
          ao /= 9.0;
          gl_FragColor = vec4(c.rgb * mix(1.0, ao, strength), c.a);
        }
      `,
    });
    this.aoQuad = new FullScreenQuad(this.aoMat);
    this.mixQuad = new FullScreenQuad(this.mixMat);
  }

  override setSize(w: number, h: number): void {
    this.target.setSize(Math.max(1, Math.round(w / 2)), Math.max(1, Math.round(h / 2)));
    (this.mixMat.uniforms.texel!.value as THREE.Vector2).set(2 / w, 2 / h);
  }

  override render(renderer: THREE.WebGLRenderer, write: THREE.WebGLRenderTarget, read: THREE.WebGLRenderTarget): void {
    const depth = this.scenePass.depth;
    this.aoMat.uniforms.tDepth!.value = depth;
    (this.aoMat.uniforms.proj!.value as THREE.Matrix4).copy(this.camera.projectionMatrix);
    (this.aoMat.uniforms.invProj!.value as THREE.Matrix4).copy(this.camera.projectionMatrixInverse);
    renderer.setRenderTarget(this.target);
    this.aoQuad.render(renderer);
    this.mixMat.uniforms.tDiffuse!.value = read.texture;
    this.mixMat.uniforms.tAO!.value = this.target.texture;
    this.mixMat.uniforms.tDepth!.value = depth;
    renderer.setRenderTarget(this.renderToScreen ? null : write);
    this.mixQuad.render(renderer);
  }

  override dispose(): void {
    this.target.dispose();
    this.aoMat.dispose();
    this.mixMat.dispose();
    this.aoQuad.dispose();
    this.mixQuad.dispose();
  }
}

/**
 * The grade, after tone mapping (on the display's colours): a gentle S-curve for
 * contrast, a little more saturation, the highlights a shade warmer and the shadows a
 * shade cooler. Not on the sky.
 */
const GradeShader = {
  uniforms: { tDiffuse: { value: null }, tDepth: { value: null }, amount: { value: 1 } },
  vertexShader: QUAD_VERT,
  fragmentShader: /* glsl */ `
    uniform sampler2D tDiffuse;
    uniform sampler2D tDepth;
    uniform float amount;
    varying vec2 vUv;
    void main() {
      vec4 c = texture2D(tDiffuse, vUv);
      if (texture2D(tDepth, vUv).r >= 0.99999) { gl_FragColor = c; return; }
      vec3 g = c.rgb;
      float l = dot(g, vec3(0.2126, 0.7152, 0.0722));
      // Saturation.
      g = mix(vec3(l), g, 1.1);
      // Contrast: a soft S about the middle (not deepening the darks: night stays readable).
      g = mix(g, g * g * (3.0 - 2.0 * g), 0.22 * smoothstep(0.1, 0.4, l));
      // Warm highlights, cool shadows.
      g += (vec3(0.03, 0.012, -0.025) * smoothstep(0.45, 1.0, l)) + (vec3(-0.012, 0.0, 0.022) * (1.0 - smoothstep(0.0, 0.45, l)));
      gl_FragColor = vec4(mix(c.rgb, clamp(g, 0.0, 1.0), amount), c.a);
    }
  `,
};

export interface PostOptions {
  ao: boolean;
}

export class Post {
  private readonly composer: EffectComposer;
  private readonly scenePass: ScenePass;
  private readonly ao: AOPass;
  private readonly bloom: UnrealBloomPass;
  private readonly grade: ShaderPass;
  private readonly bloomDepth = { value: null as THREE.Texture | null };

  constructor(
    renderer: THREE.WebGLRenderer,
    scene: THREE.Scene,
    camera: THREE.PerspectiveCamera,
  ) {
    const target = new THREE.WebGLRenderTarget(1, 1, { type: THREE.HalfFloatType, samples: 4 });
    target.depthTexture = new THREE.DepthTexture(1, 1);
    this.composer = new EffectComposer(renderer, target);
    if (!this.composer.renderTarget2.depthTexture) this.composer.renderTarget2.depthTexture = new THREE.DepthTexture(1, 1);
    this.scenePass = new ScenePass(scene, camera);
    this.ao = new AOPass(camera, this.scenePass);
    this.bloom = new UnrealBloomPass(new THREE.Vector2(256, 256), 0.32, 0.45, 1.05);
    // The bright pass, but nothing of the sky.
    const hp = (this.bloom as unknown as { materialHighPassFilter: THREE.ShaderMaterial }).materialHighPassFilter;
    hp.uniforms.tDepth = this.bloomDepth;
    hp.fragmentShader = hp.fragmentShader
      .replace('uniform sampler2D tDiffuse;', 'uniform sampler2D tDiffuse;\nuniform sampler2D tDepth;')
      .replace('gl_FragColor = mix( outputColor, texel, alpha );', 'alpha *= 1.0 - step( 0.99999, texture2D( tDepth, vUv ).r );\ngl_FragColor = mix( outputColor, texel, alpha );');
    hp.needsUpdate = true;
    this.grade = new ShaderPass(GradeShader);
    this.composer.addPass(this.scenePass);
    this.composer.addPass(this.ao);
    this.composer.addPass(this.bloom);
    this.composer.addPass(new OutputPass());
    this.composer.addPass(this.grade);
  }

  set options(o: PostOptions) {
    this.ao.enabled = o.ao;
  }

  setSize(w: number, h: number, pixelRatio: number): void {
    this.composer.setPixelRatio(pixelRatio);
    this.composer.setSize(w, h);
  }

  render(): void {
    // (The passes after the scene read its depth; the target it went to alternates.)
    this.bloomDepth.value = this.composer.readBuffer.depthTexture;
    (this.grade.uniforms as Record<string, THREE.IUniform>).tDepth!.value = this.composer.readBuffer.depthTexture;
    this.composer.render();
  }

  dispose(): void {
    this.composer.dispose();
  }
}