The showcase prompt, round 3, Fable 5.2

agent

+17:24

Fixing two generator bugs (loop-cut miss on tiny regions, slow rasterizer), then looking at the first maze renders.

  • Bashcd /tmp/tools && python3 - <<'EOF'

    command

    cd /tmp/tools && python3 - <<'EOF'
    s=open('gen.js').read()
    a=s.index("function wordMask"); b=s.index("// Build the whole labyrinth")
    new='''function wordMask(CW, CH, scale, ox, oy) {
      const SS = 3, sw = CW * SS, sh = CH * SS, fine = new Uint8Array(sw * sh);
      for (const [w, ...segs] of STROKES) for (const f of segs) for (let i = 0; i <= 200; i++) {
        const [x, y] = f(i / 200), r = w * scale / 2 * SS;
        const px = ((x - y * SLANT) * scale + ox) * SS, py = (y * scale + oy) * SS;
        for (let v = Math.max(0, py - r | 0); v <= Math.min(sh - 1, py + r); v++)
          for (let u = Math.max(0, px - r | 0); u <= Math.min(sw - 1, px + r); u++)
            if ((u + .5 - px) ** 2 + (v + .5 - py) ** 2 < r * r) fine[u + v * sw] = 1;
      }
      const m = new Uint8Array(CW * CH);
      for (let i = 0; i < sw * sh; i++) m[(i % sw / SS | 0) + (i / sw / SS | 0) * CW] += fine[i];
      return m.map(v => v >= 4);
    }
    
    '''
    s=s[:a]+new+s[b:]
    old='''    const x = 2 * (c % CW), y = 2 * (c / CW | 0), d = ri(4);
        if (tree[c] >> d & 1) continue;
        unlink(...[[x + 1, y, 1], [x, y + 1, 0], [x, y, 1], [x, y, 0]][d]); cut[reg[c]] = 1;'''
    new='''    const x = 2 * (c % CW), y = 2 * (c / CW | 0), d = shuffle([0, 1, 2, 3]).find(d => !(tree[c] >> d & 1));
        if (d === undefined) continue;
        unlink(...[[x + 1, y, 1], [x, y + 1, 0], [x, y, 1], [x, y, 0]][d]); cut[reg[c]] = 1;'''
    assert old in s
    s=s.replace(old,new)
    open('gen.js','w').write(s)
    EOF
    node maze.js 52

    result, 3 lines

    {"cells":21632,"passages":21631,"reached":21632,"regions":1146,"doors":1145,"pathLength":3816,"wordCells":3816,"pathInsideWord":3816,"perfect":true,"exact":true} ms 83 lair 2889 0.757
    dead ends 1811 junctions 1783
    Shell cwd was reset to ~/run
  • Read/tmp/probe/maze_unlit.png

    input

    {
      "file_path": "/tmp/probe/maze_unlit.png"
    }

    result

    no output

    maze_unlit.png
    maze_unlit.png
  • Read/tmp/probe/maze_lit.png

    input

    {
      "file_path": "/tmp/probe/maze_lit.png"
    }

    result

    no output

    maze_lit.png
    maze_lit.png
  • Bashcd /tmp/tools && python3 - <<'EOF'

    command

    cd /tmp/tools && python3 - <<'EOF'
    s=open('gen.js').read()
    rep=[
    ("[PEN, cubic([3.4, -11.6], [7, -12.8], [10.5, -10.6], [15.6, -9.4])],","[PEN, cubic([3.2, -12], [6.5, -13.4], [10, -11.4], [14.6, -10.2])],"),
    ("[PEN, cubic([37.2, -6.6], [38.6, -8.6], [40, -9.2], [41.8, -8.8])],","[HAIR, cubic([37.3, -6.2], [38.8, -8], [40.2, -8.4], [41.8, -7.6])],"),
    ("[PEN, line([47.2, -4.4], [56, -6.1]), arc(51.6, -5, 4.7, 5, -14, -322)],","[PEN, line([47.4, -3.9], [56.4, -5.7]), arc(51.8, -5.1, 4.9, 5.3, -8, -322)],"),
    ("line([46.6, -2], [47.6, -4.4])],","line([46.6, -2], [47.6, -3.9])],"),
    ("[PEN, cubic([55.3, -1.9], [57.6, 0.3], [60.6, -0.4], [63.4, -4.6])],","[PEN, cubic([55.6, -1.8], [57.8, 0.4], [60.8, -0.4], [63.6, -4.8])],"),
    ]
    for a,b in rep:
        assert a in s, a
        s=s.replace(a,b)
    s=s.replace("wordMask(CW, CH, 1.36, 14, 40.5)","wordMask(CW, CH, 1.36, 15, 40)")
    open('gen.js','w').write(s)
    EOF
    node maze.js 52

    result, 3 lines

    {"cells":21632,"passages":21631,"reached":21632,"regions":1135,"doors":1134,"pathLength":3796,"wordCells":3796,"pathInsideWord":3796,"perfect":true,"exact":true} ms 74 lair 2529 0.666
    dead ends 1817 junctions 1771
    Shell cwd was reset to ~/run
  • Read/tmp/probe/maze_half.png

    input

    {
      "file_path": "/tmp/probe/maze_half.png"
    }

    result

    no output

    maze_half.png
    maze_half.png
  • Write/tmp/tools/template.html

    input

    /tmp/tools/template.html
    
    <!doctype html>
    <html lang="en">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>A Fabled Clue</title>
    <!--
      A FABLED CLUE
      ─────────────
      One file. No libraries, no images, no fonts, no network. Everything you see is
      computed when the page loads, from the ~200 lines under "THE LABYRINTH" below.
    
      What to check, if you are the checking kind:
    
        · The labyrinth is a *perfect* maze: 21,632 cells, 21,631 passages, exactly one
          route between any two cells. (Open the console: the page proves it on load.)
        · Nothing in the walls gives the word away. The handwriting region and the
          rest of the maze are built by the same procedure, so their texture is identical.
        · The one route from IN to OUT visits every cell of the handwriting exactly
          once, and no cell outside it. The thread never crosses itself.
        · The rendering is one fragment shader: a perspective ray is cast per pixel
          and walked through the wall grid. The light is a flood-fill along corridors,
          so it turns corners and stops at walls, as light from a thread on the floor would.
        · ?seed=7 builds a different labyrinth around the same word.
        · "clue" really is "clew": a ball of thread. That part is not made up.
        · And the title is an anagram.
    -->
    <style>
      html, body { margin: 0; height: 100%; background: #05060a; }
      #stage { position: relative; width: 100%; height: 100%; min-height: 180px; overflow: hidden; background: #05060a;
               color: #e9dfca; -webkit-font-smoothing: antialiased; user-select: none; -webkit-user-select: none; cursor: crosshair; }
      #stage.drag { cursor: grabbing; }
      canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; touch-action: pan-y; }
      #stage.full canvas { touch-action: none; }
      #scrim { position: absolute; inset: 0; pointer-events: none;
               background: linear-gradient(#05060acc, #05060a00 17%, #05060a00 74%, #05060ad9); }
      #title { position: absolute; left: 0; right: 0; top: 6.2%; height: 1.2em; margin: 0; pointer-events: none;
               font: 500 clamp(9px, 1.55vw, 15px)/1.2 ui-sans-serif, system-ui, -apple-system, "Helvetica Neue", Arial, sans-serif; }
      #title span { position: absolute; left: 50%; top: 0; white-space: pre; will-change: transform; }
      #cap { position: absolute; left: 7%; right: 7%; bottom: 6.5%; margin: 0; text-align: center; pointer-events: none; text-wrap: balance;
             font: italic 400 clamp(13px, 2.35vw, 25px)/1.32 "Iowan Old Style", "Palatino Linotype", Palatino, "Book Antiqua", Georgia, serif;
             text-shadow: 0 0 .7em #05060a, 0 0 .3em #05060a, 0 1px 2px #000; letter-spacing: .005em; }
      #cap em { font-style: normal; color: #ffcf7a; letter-spacing: .04em; }
      #cap small { font: 500 .52em/1.6 ui-sans-serif, system-ui, -apple-system, "Helvetica Neue", Arial, sans-serif;
                   letter-spacing: .22em; text-transform: uppercase; color: #b9c7e6; }
      #ui { position: absolute; right: 1.6%; bottom: 3%; display: flex; gap: 2px; opacity: .5; transition: opacity .3s; }
      #ui:hover { opacity: 1; }
      #ui button { all: unset; cursor: pointer; width: 30px; height: 30px; display: grid; place-items: center; color: #cfd6e6; border-radius: 50%; }
      #ui button:hover { background: #ffffff1c; }
      #ui button:focus-visible { outline: 1px solid #ffcf7a; }
      #ui svg { width: 15px; height: 15px; fill: none; stroke: currentColor; stroke-width: 1.5; stroke-linecap: round; stroke-linejoin: round; }
      #nogl { position: absolute; inset: 0; display: none; place-items: center; text-align: center; padding: 8%;
              font: italic 17px/1.5 Georgia, serif; color: #cdbf9f; }
    </style>
    
    <div id="stage">
      <canvas id="gl"></canvas>
      <div id="scrim"></div>
      <h1 id="title" aria-label="Fig. 5.2: A Fabled Clue"></h1>
      <p id="cap" aria-live="polite"></p>
      <div id="ui">
        <button id="replay" title="Play it again" aria-label="Replay"><svg viewBox="0 0 16 16"><path d="M2.5 8a5.5 5.5 0 1 0 1.7-4"/><path d="M2.2 1.6v3h3"/></svg></button>
        <button id="full" title="Fullscreen" aria-label="Fullscreen"><svg viewBox="0 0 16 16"><path d="M2 6V2h4M10 2h4v4M14 10v4h-4M6 14H2v-4"/></svg></button>
      </div>
      <div id="nogl">This piece is drawn by your graphics card, and it couldn’t reach it (WebGL 2 is unavailable here).</div>
    </div>
    
    <script>
    'use strict';
    /*GEN*/
    
    // ───────────────────────────────────────────────────────────────────────────
    //  THE THREAD  (geometry of the route, and how its light spills down corridors)
    // ───────────────────────────────────────────────────────────────────────────
    const query = new URLSearchParams(location.search);
    const SEED = query.has('seed') ? +query.get('seed') : 52;
    const t0 = performance.now();
    const L = buildLabyrinth(SEED);
    const { W, H, N, path, open, DX, DY } = L, LEN = path.length;
    
    const ss = (a, b, x) => { x = Math.min(1, Math.max(0, (x - a) / (b - a))); return x * x * (3 - 2 * x); };
    const mix = (a, b, t) => a + (b - a) * t;
    const clamp = (x, a, b) => Math.min(b, Math.max(a, x));
    const dirTo = (a, b) => b - a === 1 ? 0 : b - a === W ? 1 : b - a === -1 ? 2 : 3;
    
    // For a route (list of cells starting at IN): which side the thread enters and leaves each cell by.
    function sides(r, loose) {
      const s = new Uint8Array(r.length);
      for (let i = 0; i < r.length; i++) {
        const a = i ? dirTo(r[i], r[i - 1]) : 2, last = i === r.length - 1;
        const b = last ? (loose ? a ^ 2 : 2) : dirTo(r[i], r[i + 1]);
        s[i] = a | b << 2 | 16 | (last && loose ? 32 : 0);
      }
      return s;
    }
    const goldSides = sides(path, false);
    
    // Where is the thread, u cells along the route? Straight through a cell, or a quarter-turn.
    function along(u) {
      u = clamp(u, 0, LEN - 1e-4);
      const i = u | 0, s = u - i, c = path[i], x = c % W + .5, y = (c / W | 0) + .5, a = goldSides[i] & 3, b = goldSides[i] >> 2 & 3;
      if (a === (b ^ 2)) return [x + DX[b] * (s - .5), y + DY[b] * (s - .5)];
      const co = Math.cos(s * Math.PI / 2) / 2, si = Math.sin(s * Math.PI / 2) / 2;
      return [x + (DX[a] + DX[b]) / 2 - DX[b] * co - DX[a] * si, y + (DY[a] + DY[b]) / 2 - DY[b] * co - DY[a] * si];
    }
    
    // Light walks. From every cell the thread lies in, flood a few steps along the corridors.
    // Each (cell, source) pair that improves on earlier sources becomes an entry, so the glow
    // at any moment is a pure function of how far the thread has got.
    const stamp = new Int32Array(N), queue = new Int32Array(N), qd = new Uint8Array(N);
    let stampId = 0;
    function flood(src, depth, visit) {
      stampId++; queue[0] = src; qd[0] = 0; stamp[src] = stampId;
      for (let h = 0, t = 1; h < t; h++) {
        const c = queue[h], d = qd[h];
        visit(c, d);
        if (d < depth) for (let k = 0; k < 4; k++) if (open[c] >> k & 1) {
          const m = c + DX[k] + DY[k] * W;
          if (stamp[m] !== stampId) { stamp[m] = stampId; queue[t] = m; qd[t++] = d + 1; }
        }
      }
    }
    const falloff = (d, D) => (1 - d / (D + 1)) ** 2 * .86 ** d;
    const eCell = [], eIdx = [], eVal = [];
    {
      const best = new Uint8Array(N).fill(255);
      path.forEach((c, i) => flood(c, 7, (m, d) => { if (d < best[m]) { best[m] = d; eCell.push(m); eIdx.push(i); eVal.push(falloff(d, 7)); } }));
    }
    const lightGold = new Float32Array(N), lightSilver = new Float32Array(N), silverGoal = new Float32Array(N), lightEmber = new Float32Array(N);
    flood(path[L.lair], 10, (m, d) => lightEmber[m] = falloff(d, 10));
    function goldLight(u) {
      lightGold.fill(0);
      for (let k = 0; k < eIdx.length && eIdx[k] <= u; k++) {
        const v = eVal[k] * Math.min(1, (u - eIdx[k]) / 4);
        if (v > lightGold[eCell[k]]) lightGold[eCell[k]] = v;
      }
    }
    
    // A heavily smoothed copy of the route for the camera to ride, so it glides while the thread scribbles.
    const track = new Float32Array(LEN * 2);
    {
      let a = new Float32Array(LEN * 2);
      path.forEach((c, i) => { a[2 * i] = c % W + .5; a[2 * i + 1] = (c / W | 0) + .5; });
      for (let [redacted: code variable flagged by the scan]; pass < 3; pass++) {
        const R = 110, b = new Float32Array(LEN * 2);
        for (let k = 0; k < 2; k++) {
          let sum = 0;
          for (let i = -R; i <= R; i++) sum += a[2 * clamp(i, 0, LEN - 1) + k];
          for (let i = 0; i < LEN; i++) {
            b[2 * i + k] = sum / (2 * R + 1);
            sum += a[2 * clamp(i + R + 1, 0, LEN - 1) + k] - a[2 * clamp(i - R, 0, LEN - 1) + k];
          }
        }
        a = b;
      }
      track.set(a);
    }
    const buildMs = performance.now() - t0;
    
    // ───────────────────────────────────────────────────────────────────────────
    //  THE TELLING  (a timeline: everything on screen is a function of t)
    // ───────────────────────────────────────────────────────────────────────────
    const T = { dive: 2.3, go: 4.9, lair: 15.4, back: 16.8, home: 25.2, six: 26.0, seven: 28.7, anagram: 30.0, free: 32.6 };
    const LINES = [
      [T.dive + .2, 6.5, 'Before Theseus walked into the Labyrinth, Ariadne handed him a ball of thread.'],
      [7.0, 10.3, 'The old word for a ball of thread is <em>clew</em>.'],
      [10.8, T.lair + .5, 'He tied one end to the door and unwound the rest, all the way in to the monster.'],
      [T.back - .3, 20.2, 'Then he followed it home.'],
      [20.7, T.home + .3, 'Which is why whatever leads you out of a maze is still called a <em>clue</em>.'],
      [T.six, T.seven - .3, 'This one has been writing as it went.'],
      [T.seven, T.free - .3, 'So has the title.'],
    ];
    const HINT = matchMedia('(hover: hover)').matches
      ? '<small>Your thread now · point anywhere · drag to move · click, then scroll, to look closer</small>'
      : '<small>Your thread now · tap anywhere · pinch to look closer</small>';
    
    function easing(speed) {                  // turn a speed profile into a 0→1 easing curve
      const a = new Float32Array(257);
      for (let i = 1; i <= 256; i++) a[i] = a[i - 1] + speed((i - .5) / 256);
      return x => { x = clamp(x, 0, 1) * 256; const i = Math.min(255, x | 0); return mix(a[i], a[i + 1], x - i) / a[256]; };
    }
    const outward = easing(x => (.03 + ss(0, .5, x)) * (1 - .94 * ss(.8, 1, x)));
    const homeward = easing(x => (.06 + ss(0, .22, x)) * (1 - .965 * ss(.66, 1, x)));
    const LAIR = L.lair + .5;
    function threadAt(t) {
      if (t < T.go) return 0;
      if (t < T.lair) return LAIR * outward((t - T.go) / (T.lair - T.go));
      if (t < T.back) return LAIR;
      return LAIR + (LEN - LAIR) * homeward((t - T.back) / (T.home - T.back));
    }
    
    // ───────────────────────────────────────────────────────────────────────────
    //  THE EYE  (a camera is five numbers: where it looks, from how far, tilt, turn)
    // ───────────────────────────────────────────────────────────────────────────
    const TAN = Math.tan(17 * Math.PI / 180), RAD = Math.PI / 180;
    let vw = 2, vh = 1;
    function overview() {
      const d = Math.max(H / (2 * .7 * TAN), W / (2 * .93 * TAN * vw / vh));
      return { x: W / 2, y: H / 2 + d * TAN * .03, d, phi: 0, psi: 0 };
    }
    function blend(a, b, k) {
      return { x: mix(a.x, b.x, k), y: mix(a.y, b.y, k), d: Math.exp(mix(Math.log(a.d), Math.log(b.d), k)), phi: mix(a.phi, b.phi, k), psi: mix(a.psi, b.psi, k) };
    }
    function cinema(t) {
      const u = threadAt(t), h = along(u), i = Math.min(LEN - 1, u | 0);
      const speed = (threadAt(t + .08) - threadAt(t - .08)) / .16, k = ss(14, 150, speed);
      const chase = {
        x: mix(h[0], track[2 * i], k) + 1.2, y: mix(h[1], track[2 * i + 1], k),
        d: mix(9, 40, ss(6, 300, speed) ** .8),
        phi: mix(54, 47, k) * RAD, psi: (-30 + 9 * Math.sin(t * .21)) * RAD,
      };
      const w = ss(T.dive, T.go + .9, t) * (1 - ss(T.back + 1.2, T.home - 2.4, t));
      const c = blend(overview(), chase, w);
      c.dof = w;
      return c;
    }
    function basis(c) {
      const sp = Math.sin(c.phi), cp = Math.cos(c.phi), sy = Math.sin(c.psi), cy = Math.cos(c.psi);
      return { pos: [c.x + c.d * sp * sy, c.y + c.d * sp * cy, c.d * cp], R: [cy, -sy, 0], U: [-sy * cp, -cy * cp, sp], F: [-sp * sy, -sp * cy, -cp] };
    }
    function pick(c, nx, ny) {                // screen (−1..1) → the point on the floor under it
      const b = basis(c), ax = nx * TAN * vw / vh, ay = ny * TAN;
      const d = [0, 1, 2].map(i => b.F[i] + b.R[i] * ax + b.U[i] * ay), t = -b.pos[2] / d[2];
      return [b.pos[0] + d[0] * t, b.pos[1] + d[1] * t];
    }
    
    // ───────────────────────────────────────────────────────────────────────────
    //  THE LIGHT  (one fragment shader: cast a ray per pixel, walk it through the walls)
    // ───────────────────────────────────────────────────────────────────────────
    const VERT = `#version 300 es
    void main() { gl_Position = vec4(vec2(gl_VertexID & 1, gl_VertexID >> 1) * 4. - 1., 0, 1); }`;
    
    const SCENE = `#version 300 es
    precision highp float; precision highp int; precision highp usampler2D;
    out vec4 O;
    uniform vec2 uRes;
    uniform vec3 uCam, uR, uU, uF;
    uniform float uTan, uFocus, uDof, uTime;
    uniform usampler2D uMaze, uSilver;         // walls + the gold route · your silver route
    uniform sampler2D uLight;                  // per-cell light: r gold, g silver, b the monster's ember
    uniform ivec2 uSize;
    uniform float uGold, uSilverLen, uEmber, uPulse, uDone;
    uniform vec4 uHead;                        // the clew: x, y, radius, spark
    uniform vec3 uHover, uLair;
    
    const float WH = .78;                      // wall height, in cells; walls are a quarter-cell thick
    const vec2 DIR[4] = vec2[4](vec2(1, 0), vec2(0, 1), vec2(-1, 0), vec2(0, -1));
    const vec3 MOON = vec3(.33, .47, .85), GOLD = vec3(1., .6, .19), SILVER = vec3(.42, .68, 1.), RED = vec3(1., .09, .03);
    const vec3 SUN = vec3(-.36, -.46, .81);    // direction to the moon, in fact
    
    float hash(vec2 p) { p = fract(p * vec2(.1031, .103)); p += dot(p, p.yx + 33.33); return fract((p.x + p.y) * p.x); }
    float noise(vec2 p) {
      vec2 i = floor(p), f = fract(p); f = f * f * (3. - 2. * f);
      return mix(mix(hash(i), hash(i + vec2(1, 0)), f.x), mix(hash(i + vec2(0, 1)), hash(i + 1.), f.x), f.y);
    }
    vec3 ray(vec2 frag) {
      vec2 n = frag / uRes * 2. - 1.;
      return normalize(uF + uR * (n.x * uTan * uRes.x / uRes.y) + uU * (n.y * uTan));
    }
    bool inside(ivec2 c) { return c.x >= 0 && c.y >= 0 && c.x < uSize.x && c.y < uSize.y; }
    uint walls(ivec2 c) { return texelFetch(uMaze, c, 0).r; }          // 1: wall to the west, 2: to the north, 4: corner post
    // Space is cut into quarter-cells; walls occupy the first quarter of each cell in x and in y.
    bool solid(ivec2 s) {
      ivec2 m = s & 3;
      if (m.x != 0 && m.y != 0) return false;
      ivec2 c = s >> 2;
      if (c.x < 0 || c.y < 0 || c.x > uSize.x || c.y > uSize.y) return false;
      return (walls(c) & (m.x == 0 ? (m.y == 0 ? 4u : 1u) : 2u)) != 0u;
    }
    vec3 glow(ivec2 c) { return inside(c) ? texelFetch(uLight, c, 0).rgb : vec3(0); }
    // Light is stored per cell. Blend toward a neighbour only through an open side, so it never leaks through a wall.
    vec3 glowAt(vec2 g) {
      ivec2 c = ivec2(floor(g)); vec2 a = g - vec2(c) - .5, w = abs(a);
      vec3 l0 = glow(c);
      bool ox = (walls(a.x > 0. ? c + ivec2(1, 0) : c) & 1u) == 0u, oy = (walls(a.y > 0. ? c + ivec2(0, 1) : c) & 2u) == 0u;
      vec3 lx = ox ? glow(c + ivec2(a.x > 0. ? 1 : -1, 0)) : l0, ly = oy ? glow(c + ivec2(0, a.y > 0. ? 1 : -1)) : l0;
      return l0 + (lx - l0) * w.x * (1. - 2. * w.y) + (ly - l0) * w.y * (1. - 2. * w.x);
    }
    vec3 lamp(vec3 l) { return GOLD * l.r * (2.5 + .5 * uDone) + SILVER * l.g * 2.2 + RED * l.b * uEmber * 3.4; }
    
    // The thread inside one cell: in one side, out another. Returns (signed distance, distance along the route).
    vec2 threadIn(vec2 l, uint bits, float idx) {
      int di = int(bits & 3u), dj = int((bits >> 2) & 3u);
      vec2 a = DIR[di] * .5, b = DIR[dj] * .5;
      if ((bits & 32u) != 0u) {                // a loose end stops in the middle of its cell
        float s = clamp(dot(l - a, -a) * 4., 0., 1.);
        return vec2(length(l - a * (1. - s)), idx + s * .5);
      }
      if (di == (dj ^ 2)) { vec2 t = DIR[dj]; return vec2(dot(l, vec2(-t.y, t.x)), idx + dot(l, t) + .5); }
      vec2 v = l - a - b;
      return vec2((length(v) - .5) * sign(a.x * b.y - a.y * b.x), idx + atan(dot(v, -a), dot(v, -b)) / 1.5707963);
    }
    // Two plies twisted together, lit as a tube; it widens to stay a pixel wide when seen from far away.
    vec4 thread(vec2 su, float len, float px, vec3 tint, float hot) {
      float r = max(.052, px * .8), x = su.x / r, e = px / r;
      float cov = smoothstep(1. + e, 1. - e, abs(x)) * smoothstep(len, len - .12, su.y) * pow(.052 / r, .35);
      float fine = smoothstep(.5, .16, e);
      float tube = sqrt(max(1. - x * x, 0.)), ply = sin(su.y * 31. + x * 2.5);
      float shade = mix(.82, tube * (.74 + .26 * ply), fine);
      vec3 c = tint * shade * (1.9 + hot) + vec3(1., .93, .8) * pow(tube, 5.) * .7 * fine;
      return vec4(c, cov);
    }
    
    vec3 floorAt(vec2 g, float px) {
      ivec2 c = ivec2(floor(g)); vec2 f = g - vec2(c);
      vec2 e = max(max(-g, g - vec2(uSize)), 0.);                       // how far outside the labyrinth
      float tone = .78 + .3 * hash(vec2(c)) + .16 * noise(g * 9.) + .1 * noise(g * 37.);
      vec3 alb = vec3(.3, .31, .345) * tone;
      if (!inside(c)) {
        float d = length(e), seam = smoothstep(.0, .03, abs(d - 1.5));
        return alb * MOON * (.9 * SUN.z + .2) * mix(.5, 1., seam) * exp(-d * d * .016) * step(d, 14.) + alb * lamp(glowAt(clamp(g, vec2(.5), vec2(uSize) - .5))) * exp(-d * 2.2);
      }
      uint b = walls(c), be = walls(c + ivec2(1, 0)), bs = walls(c + ivec2(0, 1));
      float ao = 1., sh = 1.;
      if ((b & 1u) != 0u) { ao *= .45 + .55 * smoothstep(0., .34, f.x - .125); sh = min(sh, smoothstep(.40, .52, f.x)); }
      if ((b & 2u) != 0u) { ao *= .45 + .55 * smoothstep(0., .34, f.y - .125); sh = min(sh, smoothstep(.50, .62, f.y)); }
      if ((be & 1u) != 0u) ao *= .45 + .55 * smoothstep(0., .34, .875 - f.x);
      if ((bs & 2u) != 0u) ao *= .45 + .55 * smoothstep(0., .34, .875 - f.y);
      vec2 jd = min(f, 1. - f);
      alb *= .72 + .28 * smoothstep(.0, .035, min(jd.x, jd.y));          // thresholds between paving stones
      vec3 l = glowAt(g);
      vec3 col = alb * (MOON * (.82 * SUN.z * sh + .2) * ao + lamp(l) * (.55 + .45 * ao));
    
      uvec4 m = texelFetch(uMaze, c, 0);
      if ((m.g & 16u) != 0u) {                                            // the gold thread
        vec2 su = threadIn(f - .5, m.g, float(m.b) + float(m.a) * 256.);
        if (su.y < uGold) {
          float d = abs(su.x), seen = smoothstep(uGold, uGold - .5, su.y);
          float hot = 3.2 * exp(-pow((su.y - uPulse) / 70., 2.)) + uDone * (.35 + .35 * sin(su.y * .045 - uTime * 2.2));
          col += alb * GOLD * (3.4 * exp(-d * d * 38.) + .8 * exp(-d * 5.)) * seen * (1. + hot * .4);
          vec4 th = thread(su, uGold, px, GOLD * vec3(1., 1.08, 1.25), hot);
          col = mix(col, th.rgb, th.a);
        }
      }
      uvec4 v = texelFetch(uSilver, c, 0);
      if ((v.r & 16u) != 0u) {                                            // yours
        vec2 su = threadIn(f - .5, v.r, float(v.g) + float(v.b) * 256.);
        su.x += .11 * sign(su.x + .0001) * step(1., float(m.g & 16u)) * 0.;
        if (su.y < uSilverLen) {
          float d = abs(su.x);
          col += alb * SILVER * (2.6 * exp(-d * d * 38.) + .6 * exp(-d * 5.)) * smoothstep(uSilverLen, uSilverLen - .5, su.y);
          vec4 th = thread(su, uSilverLen, px, SILVER * vec3(1.25, 1.1, 1.), .3);
          col = mix(col, th.rgb, th.a);
        }
      }
      float dh = length(g - uHead.xy);                                    // the spark where the thread is being laid
      col += alb * GOLD * uHead.w * 5. / (1. + dh * dh * 5.) * l.r;
      float ring = abs(length(g - uHover.xy) - .26);
      col += SILVER * uHover.z * 1.6 * smoothstep(.06, .0, ring);
      vec2 k = g - uLair.xy;                                              // a pair of horns, inlaid in the floor
      float horns = max(length(k) - .25, .2 - length(k + vec2(0, .13)));
      col += RED * uEmber * uLair.z * 5. * smoothstep(.03, .0, horns);
      return col;
    }
    
    vec3 topAt(vec2 g) {
      vec2 q = (g + .125) * 4., f = fract(q); ivec2 m = ivec2(floor(q)) & 3;
      float bevel = 1.;
      if (m.x == 0) bevel += (.5 - f.x) * .3;
      if (m.y == 0) bevel += (.5 - f.y) * .3;
      vec3 alb = vec3(.56, .585, .65) * (.8 + .22 * noise(g * 7.) + .14 * noise(g * 41.));
      return alb * (MOON * (.82 * SUN.z + .22) * bevel + lamp(texture(uLight, g / vec2(uSize)).rgb) * .13);
    }
    
    // Everything below the tops of the walls: step the ray through quarter-cells until it hits a wall face or the floor.
    vec3 below(vec3 rd, float px, out float t) {
      float tTop = (WH - uCam.z) / rd.z, tFloor = -uCam.z / rd.z;
      vec2 q = (uCam.xy + rd.xy * tTop + .125) * 4., dq = rd.xy * 4.;
      ivec2 s = ivec2(floor(q)), st = ivec2(sign(dq));
      vec2 inv = 1. / max(abs(dq), vec2(1e-6));
      vec2 tm = tTop + (vec2(st) * (vec2(s) - q) + max(vec2(st), 0.)) * inv;
      if (st.x == 0) tm.x = 1e9;
      if (st.y == 0) tm.y = 1e9;
      int axis = -1; t = tFloor;
      for (int i = 0; i < 30; i++) {
        bool xf = tm.x < tm.y; float tn = xf ? tm.x : tm.y;
        if (tn >= tFloor) break;
        if (xf) { s.x += st.x; tm.x += inv.x; } else { s.y += st.y; tm.y += inv.y; }
        if (solid(s)) { t = tn; axis = xf ? 0 : 1; break; }
      }
      vec3 p = uCam + rd * t;
      if (axis < 0) return floorAt(p.xy, px * t);
      vec2 n = axis == 0 ? vec2(-float(st.x), 0) : vec2(0, -float(st.y));
      ivec2 c = ivec2(floor(p.xy + n * .06));
      float z = p.z / WH, dh = length(p.xy - uHead.xy);
      vec3 l = glow(c);
      vec3 alb = vec3(.47, .49, .55) * (.8 + .2 * noise(vec2(p.x + p.y, p.z) * vec2(6., 14.)) + .14 * noise(vec2(p.x + p.y, p.z) * 43.));
      vec3 col = alb * (MOON * (.82 * max(dot(n, SUN.xy), 0.) + .2) * mix(.5, 1., z) + lamp(l) * mix(1.05, .5, z));
      col += alb * GOLD * uHead.w * 4. / (1. + dh * dh * 5.) * l.r;
      return col;
    }
    
    void main() {
      vec3 rd = ray(gl_FragCoord.xy);
      float px = 2. * uTan / uRes.y;
      // Antialias the wall tops, the sharpest edges in the picture, with eight cheap taps.
      float cov = 0.; vec3 rdOpen = rd; bool anyOpen = false;
      for (int k = 0; k < 8; k++) {
        vec3 d = ray(gl_FragCoord.xy + vec2(float(k) + .5, fract(float(k) * .375 + .0625) * 8.) / 8. - .5);
        vec2 g = uCam.xy + d.xy * ((WH - uCam.z) / d.z);
        if (solid(ivec2(floor((g + .125) * 4.)))) cov += .125; else if (!anyOpen) { anyOpen = true; rdOpen = d; }
      }
      float t = (WH - uCam.z) / rd.z;
      vec3 col = vec3(0);
      if (cov > 0.) col += cov * topAt(uCam.xy + rd.xy * t);
      if (cov < 1.) { float tb; col += (1. - cov) * below(rdOpen, px, tb); if (cov < .5) t = tb; }
    
      // The clew itself: a ball of thread, shrinking as it pays out.
      if (uHead.z > .005) {
        vec3 ce = vec3(uHead.xy, uHead.z), oc = uCam - ce;
        float b = dot(oc, rd), h = b * b - dot(oc, oc) + uHead.z * uHead.z;
        if (h > 0. && -b - sqrt(h) < t) {
          t = -b - sqrt(h);
          vec3 n = (uCam + rd * t - ce) / uHead.z;
          float a = uGold * 1.3 / max(uHead.z, .05) * .02 + uTime * .6;
          n.xz = mat2(cos(a), -sin(a), sin(a), cos(a)) * n.xz;
          float wind = max(max(sin(dot(n, vec3(.8, .6, 0)) * 34.), sin(dot(n, vec3(-.5, .5, .7)) * 34.)), sin(dot(n, vec3(.1, -.7, .7)) * 34.));
          float edge = smoothstep(0., px * t * 4. * uHead.z + 1e-4, sqrt(h));
          vec3 ball = GOLD * vec3(1., 1.05, 1.2) * (.55 + .5 * wind) * (.9 + 1.1 * max(dot((uCam + rd * t - ce) / uHead.z, SUN), 0.)) + GOLD * .5;
          col = mix(col, ball, edge);
        }
      }
      // Distance: haze beyond the point of focus, and a blur radius for the lens (kept in alpha).
      float far = max(t - uFocus, 0.) / uFocus;
      col = mix(col, vec3(.008, .012, .028), (1. - exp(-far * 1.1)) * uDof);
      O = vec4(ENC(col), clamp(abs(t - uFocus) / uFocus * 2.2, 0., 1.) * uDof);
    }`;
    
    const BLUR = `#version 300 es
    precision highp float; out vec4 O;
    uniform sampler2D uA, uB; uniform vec2 uInv; uniform float uUp;
    void main() {
      vec2 uv = gl_FragCoord.xy * uInv, h = uInv * .5;
      if (uUp < .5) {                          // downsample (dual Kawase)
        O = (texture(uA, uv) * 4. + texture(uA, uv - h) + texture(uA, uv + h) + texture(uA, uv + vec2(h.x, -h.y)) + texture(uA, uv - vec2(h.x, -h.y))) / 8.;
      } else {                                 // upsample the level below and average it in
        vec4 s = texture(uB, uv + vec2(-2. * h.x, 0)) + texture(uB, uv + vec2(2. * h.x, 0)) + texture(uB, uv + vec2(0, 2. * h.y)) + texture(uB, uv + vec2(0, -2. * h.y))
               + 2. * (texture(uB, uv + vec2(-h.x, h.y)) + texture(uB, uv + h) + texture(uB, uv + vec2(h.x, -h.y)) + texture(uB, uv - h));
        O = mix(texture(uA, uv), s / 12., .58);
      }
    }`;
    
    const FINAL = `#version 300 es
    precision highp float; out vec4 O;
    uniform sampler2D uScene, uSoft, uSofter, uBloom; uniform vec2 uRes; uniform float uFade, uTime;
    float hash(vec2 p) { p = fract(p * vec2(.1031, .103)); p += dot(p, p.yx + 33.33); return fract((p.x + p.y) * p.x); }
    void main() {
      vec2 uv = gl_FragCoord.xy / uRes;
      vec4 s = texture(uScene, uv);
      vec3 c = DEC(s.rgb);
      c = mix(c, DEC(texture(uSoft, uv).rgb), smoothstep(.0, .45, s.a));       // the lens: out-of-focus distances go soft
      c = mix(c, DEC(texture(uSofter, uv).rgb), smoothstep(.45, 1., s.a));
      c += DEC(texture(uBloom, uv).rgb) * .42;                                  // bright things bleed
      vec2 v = uv - .5;
      c *= 1. - dot(v, v) * .85;
      c *= 1.25;
      c = (c * (2.51 * c + .03)) / (c * (2.43 * c + .59) + .14);                // filmic curve (ACES fit)
      c = pow(clamp(c, 0., 1.), vec3(1. / 2.2)) * uFade;
      c += (hash(gl_FragCoord.xy + fract(uTime) * 91.) - .5) / 110.;            // grain, which also hides banding
      O = vec4(c, 1);
    }`;
    
    const stage = document.getElementById('stage'), canvas = document.getElementById('gl');
    const gl = canvas.getContext('webgl2', { antialias: false, alpha: false, powerPreference: 'high-performance' });
    if (!gl) { document.getElementById('nogl').style.display = 'grid'; throw new Error('WebGL 2 unavailable'); }
    const HDR = !!(gl.getExtension('EXT_color_buffer_float') || gl.getExtension('EXT_color_buffer_half_float'));
    const CODEC = HDR ? '#define ENC(c) (c)\n#define DEC(c) (c)\n' : '#define ENC(c) sqrt(clamp((c) / 8., 0., 1.))\n#define DEC(c) ((c) * (c) * 8.)\n';
    
    function program(fs) {
      const p = gl.createProgram();
      for (const [type, src] of [[gl.VERTEX_SHADER, VERT], [gl.FRAGMENT_SHADER, fs.replace('out vec4 O;', 'out vec4 O;\n' + CODEC)]]) {
        const s = gl.createShader(type);
        gl.shaderSource(s, src); gl.compileShader(s);
        if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s));
        gl.attachShader(p, s);
      }
      gl.linkProgram(p);
      if (!gl.getProgramParameter(p, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(p));
      const u = {};
      for (let i = 0; i < gl.getProgramParameter(p, gl.ACTIVE_UNIFORMS); i++) {
        const name = gl.getActiveUniform(p, i).name; u[name] = gl.getUniformLocation(p, name);
      }
      return { p, u };
    }
    const pScene = program(SCENE), pBlur = program(BLUR), pFinal = program(FINAL);
    gl.bindVertexArray(gl.createVertexArray());
    
    function texture(w, h, internal, format, type, filter, data) {
      const t = gl.createTexture();
      gl.bindTexture(gl.TEXTURE_2D, t);
      gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
      gl.texImage2D(gl.TEXTURE_2D, 0, internal, w, h, 0, format, type, data || null);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filter); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filter);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
      return t;
    }
    // The maze as a texture, one texel per cell (plus one extra row and column for the far walls).
    const mazeData = new Uint8Array((W + 1) * (H + 1) * 4);
    for (let y = 0; y <= H; y++) for (let x = 0; x <= W; x++) {
      const c = x + y * W, o = (x + y * (W + 1)) * 4;
      let b = 4;
      if (y < H && (x === 0 ? c !== L.A && c !== L.B : x === W || !(open[c] >> 2 & 1))) b |= 1;
      if (x < W && (y === 0 || y === H || !(open[c] >> 3 & 1))) b |= 2;
      mazeData[o] = b;
    }
    path.forEach((c, i) => { const o = (c % W + (c / W | 0) * (W + 1)) * 4; mazeData[o + 1] = goldSides[i]; mazeData[o + 2] = i & 255; mazeData[o + 3] = i >> 8; });
    const texMaze = texture(W + 1, H + 1, gl.RGBA8UI, gl.RGBA_INTEGER, gl.UNSIGNED_BYTE, gl.NEAREST, mazeData);
    const silverData = new Uint8Array(N * 4), lightData = new Uint8Array(N * 4);
    const texSilver = texture(W, H, gl.RGBA8UI, gl.RGBA_INTEGER, gl.UNSIGNED_BYTE, gl.NEAREST, silverData);
    const texLight = texture(W, H, gl.RGBA8, gl.RGBA, gl.UNSIGNED_BYTE, gl.LINEAR, lightData);
    
    // Render targets: the scene, then a chain of halvings for lens blur and bloom.
    let targets = null, scale = 1, pw = 0, ph = 0;
    function target(w, h) {
      const tex = HDR ? texture(w, h, gl.RGBA16F, gl.RGBA, gl.HALF_FLOAT, gl.LINEAR) : texture(w, h, gl.RGBA8, gl.RGBA, gl.UNSIGNED_BYTE, gl.LINEAR);
      const fb = gl.createFramebuffer();
      gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
      gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
      return { tex, fb, w, h };
    }
    const maxRatio = query.has('ratio') ? +query.get('ratio') : Math.min(devicePixelRatio || 1, 2);
    function resize() {
      vw = Math.max(2, stage.clientWidth); vh = Math.max(2, stage.clientHeight);
      const w = Math.max(2, Math.round(vw * maxRatio * scale)), h = Math.max(2, Math.round(vh * maxRatio * scale));
      if (w === pw && h === ph) return;
      pw = canvas.width = w; ph = canvas.height = h;
      if (targets) for (const t of [targets.scene, ...targets.down, ...targets.up]) if (t) { gl.deleteTexture(t.tex); gl.deleteFramebuffer(t.fb); }
      targets = { scene: target(w, h), down: [], up: [] };
      for (let i = 0, a = w, b = h; i < 6; i++) {
        a = Math.max(1, a >> 1); b = Math.max(1, b >> 1);
        targets.down.push(target(a, b)); targets.up.push(i > 0 && i < 5 ? target(a, b) : null);
      }
      layoutTitle();
    }
    
    // ───────────────────────────────────────────────────────────────────────────
    //  THE TITLE  (eleven letters that know two places to stand)
    // ───────────────────────────────────────────────────────────────────────────
    const titleEl = document.getElementById('title'), capEl = document.getElementById('cap');
    //            glyph, place in "FIG. 5.2 — A FABLED CLUE", place in "CLAUDE FABLE 5.2", how it travels
    const GLYPHS = [
      ['FIG.', 0, -1, 0], ['5.2', 1, 12, -1.5], ['—', 2, -1, 0],
      ['A', 3, 2, 1.25], ['F', 5, 6, -1], ['A', 6, 7, -1], ['B', 7, 8, -1], ['L', 8, 9, -1], ['E', 9, 10, -1], ['D', 10, 4, 1.25],
      ['C', 12, 0, .55], ['L', 13, 1, .55], ['U', 14, 3, .55], ['E', 15, 5, .55],
    ].map(([s, a, b, hop]) => ({ s, a, b, hop, el: titleEl.appendChild(Object.assign(document.createElement('span'), { textContent: s })) }));
    const GAPS_A = { 0: .9, 1: .9, 2: .9, 3: 1.05, 10: 1.05 }, GAPS_B = { 5: 1.05, 10: 1.25 };   // wider spaces after these places
    function layoutTitle() {
      const em = parseFloat(getComputedStyle(titleEl).fontSize), track = .4 * em;
      for (const g of GLYPHS) { g.el.style.letterSpacing = g.s.length > 1 ? '.16em' : '0'; g.w = g.el.getBoundingClientRect().width || g.s.length * em * .7; }
      for (const [key, gaps] of [['a', GAPS_A], ['b', GAPS_B]]) {
        const row = GLYPHS.filter(g => g[key] >= 0).sort((p, q) => p[key] - q[key]);
        let x = 0;
        for (const g of row) { g['x' + key] = x; x += g.w + track + (gaps[g[key]] || 0) * em; }
        const width = x - track;
        for (const g of row) g['x' + key] -= width / 2;
      }
      for (const g of GLYPHS) if (g.b < 0) g.xb = g.xa;
      titleEl.em = em;
    }
    function drawTitle(t) {
      const k = clamp((t - T.anagram) / 2.3, 0, 1), em = titleEl.em || 12, lit = ss(.55, 1, k), show = ss(.4, 1.6, t);
      for (const g of GLYPHS) {
        const d = clamp(k * 1.35 - (g.hop > 1 ? .12 : g.hop > 0 ? 0 : .22), 0, 1), e = d * d * (3 - 2 * d);
        const x = mix(g.xa, g.xb, e), y = -g.hop * em * Math.sin(Math.PI * e) * .95;
        g.el.style.transform = `translate(${x.toFixed(2)}px,${y.toFixed(2)}px)`;
        const quiet = g.s.length > 1;
        g.el.style.opacity = show * (g.b < 0 ? 1 - ss(0, .3, k) : 1) * (quiet ? mix(.5, 1, g.b < 0 ? 0 : lit) : mix(.86, 1, lit));
        g.el.style.color = `rgb(${mix(222, 255, lit) | 0},${mix(214, 207, lit) | 0},${mix(198, 122, lit) | 0})`;
        g.el.style.textShadow = lit > .01 ? `0 0 ${(.9 * em).toFixed(1)}px rgba(255,170,60,${(lit * .75).toFixed(3)})` : '0 0 8px #000';
      }
    }
    let capShown = -2;
    function drawCaption(t, hint) {
      let which = -1, alpha = 0;
      LINES.forEach(([a, b], i) => { if (t >= a && t < b) { which = i; alpha = ss(a, a + .55, t) * (1 - ss(b - .45, b, t)); } });
      if (which < 0 && hint > 0) { which = LINES.length; alpha = hint; }
      if (which !== capShown && which >= 0) capEl.innerHTML = which < LINES.length ? LINES[which][2] : HINT;
      capShown = which;
      capEl.style.opacity = alpha.toFixed(3);
    }
    
    // ───────────────────────────────────────────────────────────────────────────
    //  YOUR THREAD  (after the telling: the route from the door to wherever you point)
    // ───────────────────────────────────────────────────────────────────────────
    let silver = [], silverLen = 0, hoverCell = -1, hoverGlow = 0, hoverXY = [0, 0];
    function runThreadTo(cell) {
      if (cell === hoverCell) return;
      hoverCell = cell;
      const r = cell < 0 ? [] : L.route(cell);
      let same = 0;
      while (same < r.length && same < silver.length && r[same] === silver[same]) same++;
      for (const c of silver) silverData[c * 4] = 0;
      const s = sides(r, true);
      r.forEach((c, i) => { silverData[c * 4] = s[i]; silverData[c * 4 + 1] = i & 255; silverData[c * 4 + 2] = i >> 8; });
      gl.bindTexture(gl.TEXTURE_2D, texSilver);
      gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, W, H, gl.RGBA_INTEGER, gl.UNSIGNED_BYTE, silverData);
      silverGoal.fill(0);
      for (const c of r) flood(c, 4, (m, d) => { const v = falloff(d, 4); if (v > silverGoal[m]) silverGoal[m] = v; });
      silver = r; silverLen = Math.min(silverLen, same);
      if (cell >= 0) hoverXY = [cell % W + .5, (cell / W | 0) + .5];
    }
    
    // ───────────────────────────────────────────────────────────────────────────
    //  THE HAND  (pointer, wheel, pinch; the embed never traps the page's scroll)
    // ───────────────────────────────────────────────────────────────────────────
    let cam = overview(), free = null, engaged = false, lastTouch = 0;
    const pointers = new Map();
    let pinch = null, moved = 0, pointerNDC = null;
    const ndc = e => { const r = canvas.getBoundingClientRect(); return [(e.clientX - r.left) / r.width * 2 - 1, 1 - (e.clientY - r.top) / r.height * 2]; };
    function takeOver() { if (!free) free = { x: cam.x, y: cam.y, d: cam.d }; return free; }
    function tiltFor(d) {                     // the closer you look, the more the camera leans in
      const o = overview(), z = clamp(Math.log(o.d / d) / Math.log(o.d / 7), 0, 1);
      return { phi: 57 * RAD * ss(.04, .85, z), psi: -26 * RAD * ss(.1, 1, z) };
    }
    function zoomAt(p, factor) {
      const f = takeOver(), o = overview(), before = pick({ ...f, ...tiltFor(f.d) }, p[0], p[1]);
      f.d = clamp(f.d * factor, 7, o.d * 1.1);
      const after = pick({ ...f, ...tiltFor(f.d) }, p[0], p[1]);
      f.x += before[0] - after[0]; f.y += before[1] - after[1];
    }
    function hover(e) {
      pointerNDC = ndc(e);
      if (now() < T.home) return;
      const g = pick(cam, pointerNDC[0], pointerNDC[1]), x = Math.floor(g[0]), y = Math.floor(g[1]);
      runThreadTo(x >= 0 && y >= 0 && x < W && y < H ? x + y * W : hoverCell);
    }
    canvas.addEventListener('pointerdown', e => {
      canvas.setPointerCapture(e.pointerId);
      pointers.set(e.pointerId, ndc(e)); moved = 0; pinch = null;
      if (e.pointerType === 'mouse') engaged = true; else lastTouch = performance.now();
    });
    canvas.addEventListener('pointermove', e => {
      const p = ndc(e), was = pointers.get(e.pointerId);
      if (!was) { if (e.pointerType === 'mouse') hover(e); return; }
      pointers.set(e.pointerId, p);
      if (pointers.size === 1) {
        moved += Math.hypot(p[0] - was[0], p[1] - was[1]);
        if (moved > .02) {
          const f = takeOver(), c = { ...f, ...tiltFor(f.d) }, a = pick(c, was[0], was[1]), b = pick(c, p[0], p[1]);
          f.x += a[0] - b[0]; f.y += a[1] - b[1];
          stage.classList.add('drag');
        }
      } else if (pointers.size === 2) {
        const [a, b] = [...pointers.values()], mid = [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2], gap = Math.hypot((a[0] - b[0]) * vw / vh, a[1] - b[1]);
        if (pinch) {
          const f = takeOver(), c = { ...f, ...tiltFor(f.d) }, g0 = pick(c, pinch.mid[0], pinch.mid[1]), g1 = pick(c, mid[0], mid[1]);
          f.x += g0[0] - g1[0]; f.y += g0[1] - g1[1];
          zoomAt(mid, pinch.gap / Math.max(gap, 1e-3));
        }
        pinch = { mid, gap }; moved = 1;
      }
    });
    const release = e => {
      if (pointers.has(e.pointerId) && pointers.size === 1 && moved <= .02 && e.type === 'pointerup') hover(e);
      pointers.delete(e.pointerId); pinch = null; stage.classList.remove('drag');
    };
    canvas.addEventListener('pointerup', release);
    canvas.addEventListener('pointercancel', release);
    canvas.addEventListener('pointerleave', e => { if (e.pointerType === 'mouse') { engaged = false; pointerNDC = null; } });
    canvas.addEventListener('wheel', e => {
      if (!engaged && !e.ctrlKey && !document.fullscreenElement) return;      // let the page scroll past us
      e.preventDefault();
      zoomAt(ndc(e), Math.exp(clamp(e.deltaY, -120, 120) * (e.ctrlKey ? .01 : .0022)));
    }, { passive: false });
    canvas.addEventListener('dblclick', e => { const f = takeOver(); zoomAt(ndc(e), f.d > overview().d * .3 ? .28 : 3.6); });
    document.getElementById('replay').onclick = () => { clock = 0; free = null; runThreadTo(-1); silverLen = 0; hintSeen = 0; playing = true; };
    const fullBtn = document.getElementById('full');
    if (!stage.requestFullscreen) fullBtn.style.display = 'none';
    fullBtn.onclick = () => document.fullscreenElement ? document.exitFullscreen() : stage.requestFullscreen();
    document.addEventListener('fullscreenchange', () => stage.classList.toggle('full', !!document.fullscreenElement));
    
    // ───────────────────────────────────────────────────────────────────────────
    //  THE LOOP
    // ───────────────────────────────────────────────────────────────────────────
    const still = matchMedia('(prefers-reduced-motion: reduce)').matches;
    let clock = query.has('t') ? +query.get('t') : still ? T.free + 1 : 0, playing = !query.has('t'), visible = false, lastFrame = 0, hintSeen = 0;
    let slow = 0, quick = 0;
    const now = () => clock;
    
    function draw(t, dt) {
      resize();
      const u = threadAt(t), head = along(u), done = ss(T.home, T.home + 1.2, t);
    
      // camera: the film's, until you take hold of it
      const film = cinema(t);
      if (free) {
        const goal = { ...free, ...tiltFor(free.d), dof: ss(0, 1, Math.log(overview().d / free.d)) }, k = 1 - Math.exp(-dt * 9);
        cam = { ...blend(cam, goal, k), dof: mix(cam.dof || 0, goal.dof, k) };
      } else cam = film;
      const b = basis(cam);
    
      // light
      goldLight(u);
      const kS = 1 - Math.exp(-dt * 10);
      silverLen += (silver.length - silverLen) * (1 - Math.exp(-dt * 7)) + Math.sign(silver.length - silverLen) * Math.min(Math.abs(silver.length - silverLen), dt * 40);
      silverLen = clamp(silverLen, 0, silver.length);
      hoverGlow += ((hoverCell >= 0 ? 1 : 0) - hoverGlow) * kS;
      for (let i = 0; i < N; i++) {
        lightSilver[i] += (silverGoal[i] - lightSilver[i]) * kS;
        lightData[4 * i] = lightGold[i] * 255; lightData[4 * i + 1] = lightSilver[i] * 255; lightData[4 * i + 2] = lightEmber[i] * 255;
      }
      gl.activeTexture(gl.TEXTURE2); gl.bindTexture(gl.TEXTURE_2D, texLight);
      gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, W, H, gl.RGBA, gl.UNSIGNED_BYTE, lightData);
      gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, texMaze);
      gl.activeTexture(gl.TEXTURE1); gl.bindTexture(gl.TEXTURE_2D, texSilver);
    
      // scene
      const S = pScene.u;
      gl.useProgram(pScene.p);
      gl.bindFramebuffer(gl.FRAMEBUFFER, targets.scene.fb); gl.viewport(0, 0, pw, ph);
      gl.uniform2f(S.uRes, pw, ph);
      gl.uniform3fv(S.uCam, b.pos); gl.uniform3fv(S.uR, b.R); gl.uniform3fv(S.uU, b.U); gl.uniform3fv(S.uF, b.F);
      gl.uniform1f(S.uTan, TAN); gl.uniform1f(S.uFocus, cam.d); gl.uniform1f(S.uDof, cam.dof || 0); gl.uniform1f(S.uTime, t % 1000);
      gl.uniform1i(S.uMaze, 0); gl.uniform1i(S.uSilver, 1); gl.uniform1i(S.uLight, 2);
      gl.uniform2i(S.uSize, W, H);
      gl.uniform1f(S.uGold, u); gl.uniform1f(S.uSilverLen, silverLen);
      const dying = ss(T.lair + .25, T.back, t);                               // the monster: a flare, then nothing
      gl.uniform1f(S.uEmber, (1 - dying) * (.72 + .28 * Math.sin(t * 3.1) + 2.4 * ss(T.lair - .1, T.lair + .25, t)));
      gl.uniform1f(S.uPulse, t < T.home ? -1e4 : (t - T.home) / 1.5 * LEN);
      gl.uniform1f(S.uDone, done);
      const paying = t >= T.go && t < T.home ? 1 : 0;
      gl.uniform4f(S.uHead, head[0], head[1], .3 * Math.cbrt(Math.max(0, 1 - u / LEN)) * (t < T.home ? 1 : 0), paying * (.6 + .4 * Math.sin(t * 23)));
      gl.uniform3f(S.uHover, hoverXY[0], hoverXY[1], hoverGlow);
      const lairXY = along(LAIR);
      gl.uniform3f(S.uLair, lairXY[0], lairXY[1], 1);
      gl.drawArrays(gl.TRIANGLES, 0, 3);
    
      // lens and bloom
      const B = pBlur.u;
      gl.useProgram(pBlur.p); gl.uniform1i(B.uA, 0); gl.uniform1i(B.uB, 1);
      gl.activeTexture(gl.TEXTURE0);
      let src = targets.scene;
      gl.uniform1f(B.uUp, 0);
      for (const d of targets.down) {
        gl.bindFramebuffer(gl.FRAMEBUFFER, d.fb); gl.viewport(0, 0, d.w, d.h);
        gl.uniform2f(B.uInv, 1 / d.w, 1 / d.h); gl.bindTexture(gl.TEXTURE_2D, src.tex);
        gl.drawArrays(gl.TRIANGLES, 0, 3); src = d;
      }
      gl.uniform1f(B.uUp, 1);
      for (let i = 4; i >= 1; i--) {
        const d = targets.up[i];
        gl.bindFramebuffer(gl.FRAMEBUFFER, d.fb); gl.viewport(0, 0, d.w, d.h);
        gl.uniform2f(B.uInv, 1 / d.w, 1 / d.h);
        gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, targets.down[i].tex);
        gl.activeTexture(gl.TEXTURE1); gl.bindTexture(gl.TEXTURE_2D, src.tex);
        gl.drawArrays(gl.TRIANGLES, 0, 3); src = d;
      }
      const F = pFinal.u;
      gl.useProgram(pFinal.p);
      gl.bindFramebuffer(gl.FRAMEBUFFER, null); gl.viewport(0, 0, pw, ph);
      [targets.scene, targets.down[0], targets.down[1], targets.up[1]].forEach((x, i) => { gl.activeTexture(gl.TEXTURE0 + i); gl.bindTexture(gl.TEXTURE_2D, x.tex); });
      gl.uniform1i(F.uScene, 0); gl.uniform1i(F.uSoft, 1); gl.uniform1i(F.uSofter, 2); gl.uniform1i(F.uBloom, 3);
      gl.uniform2f(F.uRes, pw, ph); gl.uniform1f(F.uFade, ss(.05, 1.5, t)); gl.uniform1f(F.uTime, t % 1000);
      gl.drawArrays(gl.TRIANGLES, 0, 3);
    
      // words
      drawTitle(t);
      if (t > T.free && !hintSeen) hintSeen = t;
      drawCaption(t, hintSeen ? ss(T.free, T.free + .8, t) * (1 - ss(hintSeen + 9, hintSeen + 11, t)) : 0);
    }
    
    function frame(ms) {
      requestAnimationFrame(frame);
      const dt = Math.min(.1, (ms - lastFrame) / 1000 || 0);
      lastFrame = ms;
      if (!visible) return;
      if (playing) clock += dt;
      draw(clock, dt);
      // keep it smooth: trade resolution for frame rate on slow machines, and take it back on fast ones
      if (dt > .034) { quick = 0; if (++slow > 20 && scale > .45) { scale *= .8; slow = 0; } }
      else if (dt < .02) { slow = 0; if (++quick > 240 && scale < 1) { scale = Math.min(1, scale * 1.12); quick = 0; } }
    }
    new IntersectionObserver(es => { visible = es[0].isIntersecting; }, { threshold: .25 }).observe(stage);
    addEventListener('resize', () => visible || draw(clock, 0));
    resize(); draw(clock, 0);
    requestAnimationFrame(frame);
    
    // For anyone driving this from outside (it is how the video was captured): clue.seek(12.5)
    window.clue = { T, labyrinth: L, seek(t) { playing = false; clock = t; draw(t, 1 / 30); gl.finish(); }, play() { playing = true; } };
    
    const P = L.proof, sorted = s => [...s.replace(/\W/g, '')].sort().join('');
    console.log('%cA FABLED CLUE', 'font: 600 15px Georgia; color: #d9a441', `\n
      ${P.perfect ? '✓' : '✗'} ${P.cells.toLocaleString()} cells, ${P.passages.toLocaleString()} passages, all reachable: a perfect maze (one route between any two cells)
      ${P.exact ? '✓' : '✗'} the route from IN to OUT is ${P.pathLength.toLocaleString()} cells long and covers the handwriting exactly (${P.pathInsideWord.toLocaleString()} of ${P.wordCells.toLocaleString()})
      ${sorted('A FABLED CLUE') === sorted('CLAUDE FABLE') ? '✓' : '✗'} "A FABLED CLUE" and "CLAUDE FABLE" are the same eleven letters
      built from seed ${SEED} in ${buildMs.toFixed(0)} ms · ${P.regions.toLocaleString()} regions, ${P.doors.toLocaleString()} doors · try ?seed=7\n`);
    </script>
    </html>
    

    result, 1 line

    File created successfully at: /tmp/tools/template.html (file state is current in your context — no need to Read it back)
  • Bashcd /tmp/tools && cat > build.js <<'EOF'

    command

    cd /tmp/tools && cat > build.js <<'EOF'
    const fs = require('fs');
    const gen = fs.readFileSync(__dirname + '/gen.js', 'utf8');
    const body = gen.slice(gen.indexOf('/*GEN*/') + 8, gen.indexOf('/*END GEN*/')).trim();
    const html = fs.readFileSync(__dirname + '/template.html', 'utf8').replace('/*GEN*/', () => body);
    fs.writeFileSync('~/run/a-fabled-clue.html', html);
    console.log('built', html.length, 'bytes');
    EOF
    cat > shot.js <<'EOF'
    // usage: node shot.js out_prefix WxH t1,t2,... [query]
    const { chromium } = require('playwright');
    (async () => {
      const [, , prefix, size = '1280x720', times = '0', extra = ''] = process.argv;
      const [w, h] = size.split('x').map(Number);
      const b = await chromium.launch({ args: ['--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--ignore-gpu-blocklist'] });
      const p = await b.newPage({ viewport: { width: w, height: h } });
      p.on('console', m => console.log('[console]', m.text().slice(0, 1200)));
      p.on('pageerror', e => console.log('[pageerror]', String(e).slice(0, 3000)));
      await p.goto('file://~/run/a-fabled-clue.html?t=0&ratio=1' + extra);
      await p.waitForTimeout(600);
      for (const t of times.split(',')) {
        const t0 = Date.now();
        await p.evaluate(t => { window.clue.seek(t); window.clue.seek(t); }, +t);
        await p.screenshot({ path: `${prefix}_${t}.png` });
        console.log('t', t, Date.now() - t0, 'ms');
      }
      await b.close();
    })().catch(e => { console.error(String(e).slice(0, 3000)); process.exit(1); });
    EOF
    node build.js && timeout 300 node shot.js /tmp/probe/a 1280x720 1.8

    result, 25 lines

    <persisted-output>
    Output too large (38.3KB). Full output saved to: /opt/cfg/projects/~-run/613c2b2d-cede-40d5-96b2-63d6a8cee271/tool-results/bxkajd5h2.txt
    
    Preview (first 2KB):
    built 52706 bytes
    [console] %cA FABLED CLUE font: 600 15px Georgia; color: #d9a441 
    
      ✓ 21,632 cells, 21,631 passages, all reachable: a perfect maze (one route between any two cells)
      ✓ the route from IN to OUT is 3,796 cells long and covers the handwriting exactly (3,796 of 3,796)
      ✓ "A FABLED CLUE" and "CLAUDE FABLE" are the same eleven letters
      built from seed 52 in 133 ms · 1,135 regions, 1,134 doors · try ?seed=7
    
    [console] [.WebGL-0x2d140037e400] GL_INVALID_OPERATION: glDrawArrays: Mismatch between texture format and sampler type (signed/unsigned/float/shadow).
    [console] [.WebGL-0x2d140037e400] GL_INVALID_OPERATION: glDrawArrays: Mismatch between texture format and sampler type (signed/unsigned/float/shadow).
    [console] [.WebGL-0x2d140037e400] GL_INVALID_OPERATION: glDrawArrays: Mismatch between texture format and sampler type (signed/unsigned/float/shadow).
    [console] [.WebGL-0x2d140037e400] GL_INVALID_OPERATION: glDrawArrays: Mismatch between texture format and sampler type (signed/unsigned/float/shadow).
    [console] [.WebGL-0x2d140037e400] GL_INVALID_OPERATION: glDrawArrays: Mismatch between texture format and sampler type (signed/unsigned/float/shadow).
    [console] [.WebGL-0x2d140037e400] GL_INVALID_OPERATION: glDrawArrays: Mismatch between texture format and sampler type (signed/unsigned/float/shadow).
    [console] [.WebGL-0x2d140037e400] GL_INVALID_OPERATION: glDrawArrays: Mismatch between texture format and sampler type (signed/unsigned/float/shadow).
    [console] [.WebGL-0x2d140037e400] GL_INVALID_OPERATION: glDrawArrays: Mismatch between texture format and sampler type (signed/unsigned/float/shadow).
    [console] [.WebGL-0x2d140037e400] GL_INVALID_OPERATION: glDrawArrays: Mismatch between texture format and sampler type (signed/unsigned/float/shadow).
    [console] [.WebGL-0x2d140037e400] GL_INVALID_OPERATION: glDrawArrays: Mismatch between texture format and sampler type (signed/unsigned/float/shadow).
    ...
    </persisted-output>
    Shell cwd was reset to ~/run