GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / galaxies-wafers / iterations/36-elements-assembly

Iterations — 37 Hidden Wires and 1 more file

A JavaScript module in Galaxies Wafers that draws blocks and compounds, and uses data from GitHub API and the star-maker and stars repositories. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/37-hidden-wires/.

700 lines of JavaScript from galaxies-wafers, in 2 files. Topic: Kuiper, cosmos and drawing engines. Section 1216 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Wafer render · galaxies-wafers / iterations/36-elements-assembly/wafer.mjs lines 1–234
  2. Iterations — 37 Hidden Wires render · galaxies-wafers / iterations/37-hidden-wires/app.mjs lines 1–466

Wafer

A JavaScript module in the iterations folder of Galaxies Wafers that draws on a canvas. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/36-elements-assembly/.

rendergalaxies-wafers / iterations/36-elements-assembly/wafer.mjs · lines 1–234 of 234 · pattern Wafer (shared by 2 files)

What it does
It draws its content. Defines Wafer, sh, mk, mark. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
README: "It is the basemap and it never changes (`wafer.mjs`)."
Inputs & outputs
Out: WebGL/WebGPU drawing.
Downstream impact
Used directly by 1 file: Assembly (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/36-elements-assembly/). Reached from 1 other entry point, including Iterations — 36 Elements Assembly Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/36-elements-assembly/).
What it achieves
It is built from the wafer class (`Wafer`) and the mark step (`mark`). Level 1's dark wafer (base: iteration 21, Dark Pixels).
Why it matters
Imported by Assembly.
Application
galaxies-wafers · iterations/36-elements-assembly · JavaScript module
Uses
Galaxies Wafers — Lib (import)
Used by
imported by Assembly (import)
Produces
Wafer
Defines here
Wafer, sh, mk, mark
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/36-elements-assembly/wafer.mjs:1-234 · blob ca85d1d8cb4c40e549671207f2b963e734e2c0ec · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
/* wafer.mjs — level 1's dark wafer (base: iteration 21, Dark Pixels).
 *
 * Every issued line key is one near-black point at the placement law of
 * lib.mjs (r = sqrt(key), theta = key x golden angle). Only one function's keys
 * are ever lit: a second, small buffer refilled when the chosen function
 * changes. The lit run is drawn in its sequence order (the order of the key
 * list in lines.bin), which is the order of the function's lines, not the
 * numeric order of the keys.
 *
 * SPEED (iteration 36b). The run line was first stroked on the 2D overlay as one
 * path of every segment, every frame. Measured in WebKit (iPhone 13 emulation)
 * that one stroke cost about 660 ms for the largest function's 6,517 segments,
 * while every GPU draw on the page cost about 1 ms: the whole 707 ms frame. The
 * run is now a third GPU buffer, each segment a thin quad built once per
 * function, drawn 1.1 CSS px wide in the same colour; a depth pass lets each
 * pixel take the colour once, as a single stroked path does where it crosses
 * itself. Only the three rings and the head dot stay on the overlay. Without
 * WebGL the page still strokes the path on the 2D canvas, as before.
 */
import { placeAll, place } from '../../lib.mjs';

const VS = `#version 300 es
precision highp float;
in vec2 a_pos;
uniform vec2 u_res; uniform vec2 u_cam; uniform float u_zoom; uniform float u_size;
void main(){
  vec2 p = (a_pos - u_cam) * u_zoom;
  gl_Position = vec4(p / (u_res * 0.5), 0.0, 1.0);
  gl_PointSize = u_size;
}`;
const FS = `#version 300 es
precision highp float;
uniform vec4 u_col;
out vec4 o;
void main(){
  vec2 d = gl_PointCoord - 0.5; float r = length(d);
  if (r > 0.5) discard;
  o = vec4(u_col.rgb, u_col.a * smoothstep(0.5, 0.35, r));
}`;

/* the run: one quad per segment, widened in device pixels in the vertex shader */
const RVS = `#version 300 es
precision highp float;
in vec2 a_p0; in vec2 a_p1; in vec2 a_ts;
uniform vec2 u_res; uniform vec2 u_cam; uniform float u_zoom; uniform float u_half;
void main(){
  vec2 c0 = (a_p0 - u_cam) * u_zoom, c1 = (a_p1 - u_cam) * u_zoom, d = c1 - c0;
  float l = length(d); d = l > 1e-6 ? d / l : vec2(1.0, 0.0);
  vec2 p = mix(c0, c1, a_ts.x) + vec2(-d.y, d.x) * a_ts.y * u_half;
  gl_Position = vec4(p / (u_res * 0.5), 0.0, 1.0);
}`;
const RFS = `#version 300 es
precision highp float;
uniform vec4 u_col;
out vec4 o;
void main(){ o = u_col; }`;
const QUAD = [0, -1, 0, 1, 1, -1, 1, -1, 0, 1, 1, 1];   /* (end, side) for the six corners */

export class Wafer {
  constructor(glCanvas, overlay) {
    this.cv = glCanvas; this.ov = overlay;
    this.view = { x: 0, y: 0, zoom: 1, w: 0, h: 0, dpr: 1 };
    this.groundN = 0; this.lit = null; this.litN = 0; this.seq = null; this.head = 1; this.ring = -1;
    this.gl = null; this.ctx = null; this.drawnLit = 0; this.frames = [];
  }
  init(keys) {
    const gl = this.cv.getContext('webgl2', { antialias: true, alpha: false });
    this.groundPos = placeAll(keys); this.groundN = keys.length;
    if (!gl) { this.ctx = this.cv.getContext('2d'); return false; }
    try {
      const sh = (t, s) => { const x = gl.createShader(t); gl.shaderSource(x, s); gl.compileShader(x); if (!gl.getShaderParameter(x, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(x)); return x; };
      const p = gl.createProgram();
      gl.attachShader(p, sh(gl.VERTEX_SHADER, VS)); gl.attachShader(p, sh(gl.FRAGMENT_SHADER, FS)); gl.linkProgram(p);
      if (!gl.getProgramParameter(p, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(p));
      this.p = p; this.loc = {};
      for (const u of ['u_res', 'u_cam', 'u_zoom', 'u_size', 'u_col']) this.loc[u] = gl.getUniformLocation(p, u);
      const al = gl.getAttribLocation(p, 'a_pos');
      const mk = data => {
        const vao = gl.createVertexArray(); gl.bindVertexArray(vao);
        const b = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, b); gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);
        gl.enableVertexAttribArray(al); gl.vertexAttribPointer(al, 2, gl.FLOAT, false, 0, 0);
        return { vao, b };
      };
      this.ground = mk(this.groundPos);
      this.litBuf = mk(new Float32Array(2));
      const rp = gl.createProgram();
      gl.attachShader(rp, sh(gl.VERTEX_SHADER, RVS)); gl.attachShader(rp, sh(gl.FRAGMENT_SHADER, RFS)); gl.linkProgram(rp);
      if (!gl.getProgramParameter(rp, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(rp));
      this.rp = rp; this.rloc = {};
      for (const u of ['u_res', 'u_cam', 'u_zoom', 'u_half', 'u_col']) this.rloc[u] = gl.getUniformLocation(rp, u);
      const rvao = gl.createVertexArray(); gl.bindVertexArray(rvao);
      const rb = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, rb); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(6), gl.DYNAMIC_DRAW);
      [['a_p0', 0], ['a_p1', 2], ['a_ts', 4]].forEach(([name, off]) => { const l = gl.getAttribLocation(rp, name); gl.enableVertexAttribArray(l); gl.vertexAttribPointer(l, 2, gl.FLOAT, false, 24, off * 4); });
      this.runBuf = { vao: rvao, b: rb }; this.runSegs = 0;
      gl.bindVertexArray(null);
      gl.enable(gl.BLEND); gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
      this.gl = gl;
      return true;
    } catch (e) {
      console.warn('WebGL setup failed, drawing without the GPU:', e.message);
      const fresh = this.cv.cloneNode(false); this.cv.replaceWith(fresh); this.cv = fresh;
      this.ctx = fresh.getContext('2d');
      return false;
    }
  }
  resize() {
    const v = this.view, r = this.cv.getBoundingClientRect();
    v.dpr = Math.min(window.devicePixelRatio || 1, 2); v.w = r.width; v.h = r.height;
    for (const c of [this.cv, this.ov]) {
      const W = Math.round(v.w * v.dpr), H = Math.round(v.h * v.dpr);
      if (c.width !== W || c.height !== H) { c.width = W; c.height = H; }
    }
    if (this.gl) this.gl.viewport(0, 0, this.cv.width, this.cv.height);
  }
  /* seq: the function's keys in sequence order (may repeat a key). */
  setRun(seq, ringKey) {
    this.seq = seq; this.ring = ringKey ?? -1;
    const distinct = [...new Set(seq)];
    this.lit = placeAll(distinct); this.litN = distinct.length;
    this.seqPos = placeAll(seq);
    if (this.gl) {
      const gl = this.gl; gl.bindBuffer(gl.ARRAY_BUFFER, this.litBuf.b); gl.bufferData(gl.ARRAY_BUFFER, this.lit, gl.DYNAMIC_DRAW);
      const S = this.seqPos, segs = Math.max(0, S.length / 2 - 1), q = new Float32Array(segs * 36);
      for (let i = 0, o = 0; i < segs; i++) {
        for (let k = 0; k < 12; k += 2, o += 6) {
          q[o] = S[i * 2]; q[o + 1] = S[i * 2 + 1]; q[o + 2] = S[i * 2 + 2]; q[o + 3] = S[i * 2 + 3]; q[o + 4] = QUAD[k]; q[o + 5] = QUAD[k + 1];
        }
      }
      gl.bindBuffer(gl.ARRAY_BUFFER, this.runBuf.b); gl.bufferData(gl.ARRAY_BUFFER, q, gl.DYNAMIC_DRAW);
      this.runSegs = segs;
    }
  }
  frame() {
    if (!this.seqPos || !this.seqPos.length) return;
    let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
    for (let i = 0; i < this.seqPos.length; i += 2) {
      const x = this.seqPos[i], y = this.seqPos[i + 1];
      if (x < x0) x0 = x; if (x > x1) x1 = x; if (y < y0) y0 = y; if (y > y1) y1 = y;
    }
    const v = this.view;
    v.x = (x0 + x1) / 2; v.y = (y0 + y1) / 2;
    v.zoom = Math.min(v.w / Math.max(x1 - x0, 6), v.h / Math.max(y1 - y0, 6)) * 0.8;
    this.fitZoom = v.zoom;
  }
  render() {
    const t0 = performance.now();
    const v = this.view, gl = this.gl;
    if (gl) {
      gl.clearColor(0.012, 0.014, 0.020, 1); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
      gl.useProgram(this.p);
      gl.uniform2f(this.loc.u_res, this.cv.width, this.cv.height);
      gl.uniform2f(this.loc.u_cam, v.x, v.y);
      gl.uniform1f(this.loc.u_zoom, v.zoom * v.dpr);
      /* ground: dark, size by zoom */
      gl.uniform1f(this.loc.u_size, Math.max(1, Math.min(10, 0.9 * Math.sqrt(v.zoom))) * v.dpr);
      gl.uniform4f(this.loc.u_col, 0.16, 0.18, 0.23, 0.55);
      gl.bindVertexArray(this.ground.vao); gl.drawArrays(gl.POINTS, 0, this.groundN);
      if (this.litN) {
        const s = Math.max(3, Math.min(22, 2.2 * Math.sqrt(v.zoom) + 3));
        gl.uniform1f(this.loc.u_size, (s + 5) * v.dpr);            /* halo so it reads on black */
        gl.uniform4f(this.loc.u_col, 0.0, 0.0, 0.0, 0.85);
        gl.bindVertexArray(this.litBuf.vao); gl.drawArrays(gl.POINTS, 0, this.litN);
        gl.uniform1f(this.loc.u_size, s * v.dpr);
        gl.uniform4f(this.loc.u_col, 1.0, 0.835, 0.29, 1.0);
        gl.drawArrays(gl.POINTS, 0, this.litN);
      }
      const S = this.seqPos;
      if (this.runSegs && S) {                                     /* the run, up to the head, over the lit keys */
        const upto = Math.max(1, Math.round(this.head * (S.length / 2)));
        const segs = Math.min(this.runSegs, upto - 1);
        if (segs > 0) {
          gl.useProgram(this.rp);
          gl.uniform2f(this.rloc.u_res, this.cv.width, this.cv.height);
          gl.uniform2f(this.rloc.u_cam, v.x, v.y);
          gl.uniform1f(this.rloc.u_zoom, v.zoom * v.dpr);
          gl.uniform1f(this.rloc.u_half, 0.55 * v.dpr);              /* 1.1 CSS px wide, as the 2D stroke */
          gl.uniform4f(this.rloc.u_col, 94 / 255, 200 / 255, 242 / 255, 0.75);
          gl.enable(gl.DEPTH_TEST); gl.depthFunc(gl.LESS);           /* each pixel takes the colour once */
          gl.bindVertexArray(this.runBuf.vao); gl.drawArrays(gl.TRIANGLES, 0, segs * 6);
          gl.disable(gl.DEPTH_TEST);
        }
      }
    } else if (this.ctx) {
      const c = this.ctx; c.setTransform(1, 0, 0, 1, 0, 0);
      c.fillStyle = '#030406'; c.fillRect(0, 0, this.cv.width, this.cv.height);
      c.fillStyle = '#1e222c';
      const step = v.zoom < 0.5 ? 7 : 1, P = this.groundPos;
      for (let i = 0; i < this.groundN; i += step) {
        const x = (P[i * 2] - v.x) * v.zoom * v.dpr + this.cv.width / 2, y = this.cv.height / 2 - (P[i * 2 + 1] - v.y) * v.zoom * v.dpr;
        if (x >= 0 && y >= 0 && x <= this.cv.width && y <= this.cv.height) c.fillRect(x, y, v.dpr, v.dpr);
      }
      c.fillStyle = '#ffd54a';
      for (let i = 0; i < this.litN; i++) {
        const x = (this.lit[i * 2] - v.x) * v.zoom * v.dpr + this.cv.width / 2, y = this.cv.height / 2 - (this.lit[i * 2 + 1] - v.y) * v.zoom * v.dpr;
        c.fillRect(x - 2 * v.dpr, y - 2 * v.dpr, 4 * v.dpr, 4 * v.dpr);
      }
    }
    this.drawRun();
    this.frames.push(performance.now() - t0); if (this.frames.length > 240) this.frames.shift();
  }
  toScreen(x, y) { const v = this.view; return [(x - v.x) * v.zoom + v.w / 2, v.h / 2 - (y - v.y) * v.zoom]; }
  /* the run: consecutive keys joined in sequence order, lit up to `head` (0..1) */
  drawRun() {
    const c = this.ov.getContext('2d'), v = this.view;
    c.setTransform(v.dpr, 0, 0, v.dpr, 0, 0); c.clearRect(0, 0, v.w, v.h);
    const S = this.seqPos; if (!S || S.length < 2) { this.drawnLit = 0; return; }
    const n = S.length / 2, upto = Math.max(1, Math.round(this.head * n));
    let drawn = 0;
    const gpu = !!(this.gl && this.runSegs);                       /* the line itself is drawn by render() on the GPU */
    const hw = v.w / 2, hh = v.h / 2, z = v.zoom;
    if (!gpu) { c.lineWidth = 1.1; c.strokeStyle = 'rgba(94,200,242,0.75)'; c.beginPath(); }
    for (let i = 0; i < upto; i++) {
      const x = (S[i * 2] - v.x) * z + hw, y = hh - (S[i * 2 + 1] - v.y) * z;
      if (!gpu) { if (i === 0) c.moveTo(x, y); else c.lineTo(x, y); }
      if (x > -20 && y > -20 && x < v.w + 20 && y < v.h + 20) drawn++;
    }
    if (!gpu) c.stroke();
    this.drawnLit = drawn;
    const mark = (x, y, col, r) => { c.strokeStyle = col; c.lineWidth = 1.5; c.beginPath(); c.arc(x, y, r, 0, 6.2832); c.stroke(); };
    const [fx, fy] = this.toScreen(S[0], S[1]); mark(fx, fy, '#ffffff', 9);
    const [lx, ly] = this.toScreen(S[(n - 1) * 2], S[(n - 1) * 2 + 1]); mark(lx, ly, '#5ec8f2', 12);
    if (this.ring >= 0) { const [p, q] = place(this.ring); const [rx, ry] = this.toScreen(p, q); mark(rx, ry, '#ffd54a', 15); }
    if (upto < n) { const [hx, hy] = this.toScreen(S[(upto - 1) * 2], S[(upto - 1) * 2 + 1]); c.fillStyle = '#ffd54a'; c.beginPath(); c.arc(hx, hy, 4, 0, 6.2832); c.fill(); }
  }
  nearestSeq(cx, cy) {
    const S = this.seqPos; if (!S) return -1;
    let best = -1, bd = 22 * 22;
    for (let i = 0; i < S.length / 2; i++) {
      const [x, y] = this.toScreen(S[i * 2], S[i * 2 + 1]);
      const d = (x - cx) ** 2 + (y - cy) ** 2; if (d < bd) { bd = d; best = i; }
    }
    return best;
  }
}

Iterations — 37 Hidden Wires

A JavaScript module in Galaxies Wafers that draws blocks and compounds, and uses data from GitHub API and the star-maker and stars repositories. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/37-hidden-wires/.

rendergalaxies-wafers / iterations/37-hidden-wires/app.mjs · lines 1–466 of 638 · Entry point · pattern endPointer (shared by 2 files)

What it does
It draws blocks and compounds. Defines 39 functions or classes, including $, el, fmt, short, FetchQueue. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
README: "The page (`index.html`, `app.mjs`, `lib.mjs`) is inherited unchanged from testcode/202609151339."
Inputs & outputs
In: data source: star-maker data; data source: stars data; data source: GitHub API; JSON file blocks.json; JSON file compounds.json; JSON file graph.json. Out: canvas drawing.
Downstream impact
Used directly by 1 file: Iterations — 37 Hidden Wires Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/37-hidden-wires/). Reached from 1 other entry point, including Iterations — 46 Chemistry Ledger Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/46-chemistry-ledger/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/37-hidden-wires/.
What it achieves
It fetches queue (`FetchQueue`), fetches once (`fetchOnce`) and updates ui state (`updateUIState`). Loading in Grid Atlas grammar, drawing on one canvas, one card re-filled. It responds to change, click and pointerdown events.
Why it matters
Loaded by the page of the same name at https://ventusltd.github.io/galaxies-wafers/iterations/37-hidden-wires/.
Application
galaxies-wafers · iterations/37-hidden-wires · JavaScript module
Uses
Wires (import)
Used by
loaded by Iterations — 37 Hidden Wires Page (script src)
Produces
$, el, fmt, short, FetchQueue, fetchOnce, updateUIState, hydrate, buildNodes, endpointOf, buildWires, wireShown
Defines here
$, el, fmt, short, FetchQueue, fetchOnce, updateUIState, hydrate, buildNodes, endpointOf, buildWires, wireShown, resize, fit, fitScale, sx, sy, wx, wy, schedule, inView, draw, label, finish, pinchStart, endPointer, clampK, tapAt, select
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/37-hidden-wires/app.mjs:1-466 · blob e41fd88b386a826ae6ce127b1f79159fb304fdb4 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: unknown · users: none · canonical: unknown
/* Hidden Wires — the page. Loading in Grid Atlas grammar, drawing on one
   canvas, one card re-filled. The arithmetic lives in wires.mjs. */
import * as W from './wires.mjs';

const STAR_MAKER_COMMIT = 'c5bf5f6518feba594bb057988e8e99ca81044952';
const RAW = `https://raw.githubusercontent.com/Ventusltd/star-maker/${STAR_MAKER_COMMIT}/`;
const URL_REGISTER = 'https://ventusltd.github.io/stars/blocks/blocks.json';
const URL_COMPOUNDS = RAW + 'chemistry/compounds.json';
const URL_GRAPH = RAW + 'chemistry/graph.json';
const URL_LEGEND = RAW + 'CHEMISTRY.md';
const URL_CVAA = 'https://api.github.com/repos/Ventusltd/cvaa/contents/vaccines';
const ROW_CAP = 200;

const $ = id => document.getElementById(id);
const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; };
const fmt = n => Number(n).toLocaleString('en-GB');
const short = s => String(s).slice(0, 12);

/* ── loading, as Grid Atlas does it ─────────────────────────────────────── */
class FetchQueue {
  constructor(concurrency) { this.concurrency = concurrency; this.active = 0; this.queue = []; this.peak = 0; }
  async add(task) {
    if (this.active >= this.concurrency) await new Promise(resolve => this.queue.push(resolve));
    this.active++; this.peak = Math.max(this.peak, this.active);
    try { return await task(); }
    finally { this.active--; if (this.queue.length > 0) this.queue.shift()(); }
  }
}
const queue = new FetchQueue(3);
const urlCache = new Map();
const fetchLog = [];

function fetchOnce(url, as) {
  if (urlCache.has(url)) return urlCache.get(url);
  const p = queue.add(async () => {
    const controller = new AbortController();
    const timer = setTimeout(() => controller.abort(), 15000);
    fetchLog.push(url);
    try {
      const res = await fetch(url, { signal: controller.signal, headers: as === 'github' ? { Accept: 'application/vnd.github+json' } : undefined });
      if (!res.ok) {
        let why = '';
        try { const j = await res.json(); if (j && j.message) why = ' ' + j.message; } catch (_) { /* no body */ }
        throw new Error(`HTTP ${res.status}${why}`);
      }
      return as === 'text' ? await res.text() : await res.json();
    } catch (err) {
      throw new Error(err && err.name === 'AbortError' ? 'timed out after 15 s' : (err && err.message) || String(err));
    } finally { clearTimeout(timer); }
  }).catch(err => { urlCache.delete(url); throw err; });
  urlCache.set(url, p);
  return p;
}

const RT = Object.fromEntries(['parts', 'declared', 'hidden', 'vaccines'].map(id => [id, { loaded: false, loading: null, status: 'WAIT', visible: false }]));

function updateUIState(id, state, detail) {
  RT[id].status = state;
  const span = $('lbl-' + id);
  if (span) span.textContent = `${span.getAttribute('data-base-label')} [${detail ? state + ' · ' + detail : state}]`;
}

const D = { reg: null, idx: null, chem: null, graph: null, legend: null, vaccines: null, vaccineError: null };

function hydrate(id) {
  const rt = RT[id];
  if (rt.loaded) return Promise.resolve(true);
  if (rt.loading) return rt.loading;
  updateUIState(id, 'LOAD');
  rt.loading = (async () => {
    try {
      if (id === 'parts' || id === 'declared') {
        const reg = await fetchOnce(URL_REGISTER, 'json');
        if (!D.idx) { D.reg = reg; D.idx = W.registerIndex(reg); buildNodes(); }
        if (!D.idx.blocks.length) { updateUIState(id, 'EMPTY', 'the register lists no blocks'); rt.loading = null; return false; }
        rt.loaded = true;
        updateUIState(id, 'OK', id === 'parts' ? `${fmt(D.idx.blocks.length)} blocks` : `${fmt(D.idx.edges.length)} depends_on lines`);
      } else if (id === 'hidden') {
        const partsOk = hydrate('parts');
        const [chem, graph, md] = await Promise.all([fetchOnce(URL_COMPOUNDS, 'json'), fetchOnce(URL_GRAPH, 'json'), fetchOnce(URL_LEGEND, 'text')]);
        const ok = await partsOk;
        if (!ok) throw new Error('the block register did not load, so no part can be placed');
        D.chem = W.countFailures(chem); D.chemDoc = chem; D.graph = graph; D.legend = W.legend(md);
        if (!D.chem.total) { updateUIState(id, 'EMPTY', 'compounds.json holds no compositions'); rt.loading = null; return false; }
        buildWires();
        rt.loaded = true;
        updateUIState(id, D.wires.length ? 'OK' : 'EMPTY', D.wires.length ? `${D.wires.length} wires from ${fmt(D.chem.failed)} failed compositions` : 'no failure message names a needed module');
        paintSummary(); buildRows(); paintQuestions();
      } else if (id === 'vaccines') {
        const list = await fetchOnce(URL_CVAA, 'github');
        if (!Array.isArray(list)) throw new Error('the contents endpoint did not return a list');
        D.vaccines = list.filter(x => x && x.type === 'file').map(x => x.name);
        rt.loaded = true;
        updateUIState(id, D.vaccines.length ? 'OK' : 'EMPTY', D.vaccines.length ? `${D.vaccines.length} vaccine names` : 'the vaccines folder lists no files');
        refreshVaccineCells(); paintQuestions();
      }
      rt.loading = null;
      schedule();
      if (S.sel) fillCard();
      return rt.loaded;
    } catch (err) {
      rt.loading = null;
      if (id === 'vaccines') { D.vaccineError = err.message; refreshVaccineCells(); if (S.sel) fillCard(); }
      updateUIState(id, 'FAIL', err.message + ' · tick again to retry');
      const box = document.querySelector(`input[data-layer="${id}"]`);
      if (box) box.checked = false;
      rt.visible = false;
      if (id === 'hidden') { $('summary').textContent = `FAIL — ${err.message}. Nothing is drawn in its place.`; }
      schedule();
      return false;
    }
  })();
  return rt.loading;
}

document.querySelectorAll('input[data-layer]').forEach(box => {
  box.checked = false;
  box.addEventListener('change', () => {
    const id = box.dataset.layer;
    RT[id].visible = box.checked;
    if (box.checked) hydrate(id);
    schedule();
  });
});

/* ── model for drawing ───────────────────────────────────────────────────── */
let NODES = [];            // {id, x, y, label, kind, block}
const NODE_BY_ID = new Map();
D.wires = [];

function buildNodes(extra = []) {
  const pos = W.layout(D.idx.blocks, extra);
  NODES = []; NODE_BY_ID.clear();
  for (const b of D.idx.blocks) {
    const [x, y] = pos.get(b.symbol);
    const n = { id: b.symbol, x, y, label: b.symbol, title: b.title, kind: 'block', block: b };
    NODES.push(n); NODE_BY_ID.set(n.id, n);
  }
  for (const name of new Set(extra)) {
    const [x, y] = pos.get('part:' + name);
    const n = { id: 'part:' + name, x, y, label: name, title: name, kind: 'part', block: null };
    NODES.push(n); NODE_BY_ID.set(n.id, n);
  }
}

function endpointOf(name) {
  const b = D.idx.byTitle.get(name);
  return b ? b.symbol : 'part:' + name;
}

function buildWires() {
  const extra = [];
  for (const w of D.chem.wires) {
    if (!D.idx.byTitle.has(w.reporter)) extra.push(w.reporter);
    if (!D.idx.byTitle.has(w.needed)) extra.push(w.needed);
  }
  buildNodes(extra);
  const max = Math.max(1, ...D.chem.wires.map(w => w.compositions));
  const symbols = Object.keys(D.legend);
  D.wires = D.chem.wires.map((w, i) => {
    const hostId = endpointOf(w.reporter);
    const host = NODE_BY_ID.get(hostId);
    let fromId = hostId;
    if (w.failing !== w.reporter) {
      /* the failing part is a module inside the reporting part: a satellite of it */
      fromId = 'sat:' + w.failing;
      if (!NODE_BY_ID.has(fromId)) {
        const len = Math.hypot(host.x, host.y) || 1;
        const ux = host.x / len || 0, uy = host.y / len || -1;
        const n = { id: fromId, x: host.x + ux * 9 - uy * 4, y: host.y + uy * 9 + ux * 4, label: w.failing, title: `${w.failing} (inside ${w.reporter})`, kind: 'sat', block: null, host: hostId };
        NODES.push(n); NODE_BY_ID.set(fromId, n);
      }
    }
    const toId = endpointOf(w.needed);
    const a = NODE_BY_ID.get(fromId), b = NODE_BY_ID.get(toId);
    const hostSymbol = symbols.find(s => D.legend[s] === w.reporter) || null;
    return {
      ...w, fromId, toId, hostId, hostSymbol,
      pts: W.curve([a.x, a.y], [b.x, b.y], i % 2 ? -0.18 : 0.18),
      width: 2 + 8 * Math.sqrt(w.compositions / max),
      decl: W.declaredNow(D.idx, w.reporter, w.needed),
      unplug: W.unplugSuppliers(D.chemDoc, w.text, hostSymbol, symbols),
      decay: W.decayEdges(D.graph, w.text)
    };
  });
  for (const w of D.wires) {
    let minx = Infinity, miny = Infinity, maxx = -Infinity, maxy = -Infinity;
    for (let i = 0; i < w.pts.length; i += 2) { minx = Math.min(minx, w.pts[i]); maxx = Math.max(maxx, w.pts[i]); miny = Math.min(miny, w.pts[i + 1]); maxy = Math.max(maxy, w.pts[i + 1]); }
    w.bbox = [minx, miny, maxx, maxy];
  }
  fit();
}

/* ── state ──────────────────────────────────────────────────────────────── */
const S = { filter: 'all', sel: null, view: { x: 0, y: 0, k: 1 }, fitK: 1 };
const wireShown = w => S.filter === 'all' || w.decl.declared === false;

$('filter').addEventListener('click', e => {
  const b = e.target.closest('button[data-f]');
  if (!b) return;
  S.filter = b.dataset.f;
  $('filter').querySelectorAll('button').forEach(x => x.setAttribute('aria-pressed', String(x === b)));
  $('worktitle').textContent = S.filter === 'all' ? 'hidden wires' : 'hidden, not yet declared';
  for (const [id, r] of rowById) { const w = D.wires.find(x => x.id === id); r.li.hidden = !wireShown(w); }
  paintWorkCount();
  if (!RT.hidden.visible && S.filter === 'undeclared') { const box = document.querySelector('input[data-layer="hidden"]'); box.checked = true; RT.hidden.visible = true; hydrate('hidden'); }
  schedule();
});

/* ── canvas ─────────────────────────────────────────────────────────────── */
const canvas = $('plane');
const ctx = canvas.getContext('2d');
let W_CSS = 1, H_CSS = 1, DPR = 1;
const R = 100;

function resize() {
  const r = canvas.getBoundingClientRect();
  W_CSS = Math.max(1, r.width); H_CSS = Math.max(1, r.height);
  DPR = Math.min(2, window.devicePixelRatio || 1);
  canvas.width = Math.round(W_CSS * DPR); canvas.height = Math.round(H_CSS * DPR);
  const wasFit = Math.abs(S.view.k - S.fitK) < 1e-9;
  S.fitK = fitScale();
  if (wasFit) S.view.k = S.fitK;
  schedule();
}
function fit() { S.fitK = fitScale(); S.view = { x: 0, y: 0, k: S.fitK }; schedule(); }
new ResizeObserver(resize).observe(canvas);
$('fit').addEventListener('click', fit);

function fitScale() { return Math.max(0.2, (Math.min(W_CSS, H_CSS) - 40) / (2 * 1.25 * R + 12)); }
const sx = x => W_CSS / 2 + (x - S.view.x) * S.view.k;
const sy = y => H_CSS / 2 + (y - S.view.y) * S.view.k;
const wx = px => S.view.x + (px - W_CSS / 2) / S.view.k;
const wy = py => S.view.y + (py - H_CSS / 2) / S.view.k;

let pending = false;
function schedule() { if (!pending) { pending = true; requestAnimationFrame(draw); } }
const drawn = { nodes: 0, lines: 0, wires: 0, ms: 0, frames: 0 };
let lastDrawnText = '';

function inView(minx, miny, maxx, maxy, pad = 20) {
  return sx(maxx) >= -pad && sx(minx) <= W_CSS + pad && sy(maxy) >= -pad && sy(miny) <= H_CSS + pad;
}

function draw() {
  pending = false;
  const t0 = performance.now();
  ctx.setTransform(DPR, 0, 0, DPR, 0, 0);
  ctx.fillStyle = '#05060a';
  ctx.fillRect(0, 0, W_CSS, H_CSS);
  let nNodes = 0, nLines = 0, nWires = 0;
  const k = S.view.k;

  if (!D.idx) {
    ctx.fillStyle = '#8b93a7'; ctx.font = '12px ui-monospace,Menlo,Consolas,monospace'; ctx.textAlign = 'center';
    ctx.fillText('WAIT — tick a layer', W_CSS / 2, H_CSS / 2);
    finish(t0, 0, 0, 0); return;
  }

  /* charted plane guides: the register disc and the ring of unregistered parts */
  ctx.strokeStyle = '#141925'; ctx.lineWidth = 1;
  ctx.beginPath(); ctx.arc(sx(0), sy(0), R * 1.04 * k, 0, Math.PI * 2); ctx.stroke();
  if (RT.hidden.loaded && RT.hidden.visible) { ctx.setLineDash([2, 6]); ctx.beginPath(); ctx.arc(sx(0), sy(0), R * 1.25 * k, 0, Math.PI * 2); ctx.stroke(); ctx.setLineDash([]); }

  const selNode = S.sel && S.sel.type === 'node' ? S.sel.id : null;
  const selEdge = S.sel && S.sel.type === 'edge' ? S.sel.i : -1;
  const dimDeclared = S.filter === 'undeclared';

  /* declared needs: solid, cased */
  if (RT.declared.loaded && RT.declared.visible) {
    const hi = [];
    const casing = new Path2D(), core = new Path2D();
    D.idx.edges.forEach((e, i) => {
      const a = NODE_BY_ID.get(e.from), b = NODE_BY_ID.get(e.to);
      if (!inView(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.max(a.x, b.x), Math.max(a.y, b.y))) return;
      nLines++;
      if (e.from === selNode || e.to === selNode || i === selEdge) { hi.push([a, b]); return; }
      casing.moveTo(sx(a.x), sy(a.y)); casing.lineTo(sx(b.x), sy(b.y));
      core.moveTo(sx(a.x), sy(a.y)); core.lineTo(sx(b.x), sy(b.y));
    });
    ctx.lineCap = 'round';
    ctx.globalAlpha = dimDeclared ? 0.35 : 0.9; ctx.strokeStyle = '#000'; ctx.lineWidth = 3.4; ctx.stroke(casing);
    ctx.globalAlpha = dimDeclared ? 0.25 : 0.7; ctx.strokeStyle = '#5b6780'; ctx.lineWidth = 1.2; ctx.stroke(core);
    ctx.globalAlpha = 1;
    for (const [a, b] of hi) {
      ctx.strokeStyle = '#000'; ctx.lineWidth = 5; ctx.beginPath(); ctx.moveTo(sx(a.x), sy(a.y)); ctx.lineTo(sx(b.x), sy(b.y)); ctx.stroke();
      ctx.strokeStyle = '#c3ccda'; ctx.lineWidth = 2; ctx.stroke();
    }
  }

  /* dots */
  const partsOn = RT.parts.loaded && RT.parts.visible;
  const wiresOn = RT.hidden.loaded && RT.hidden.visible;
  const onWire = new Set();
  if (wiresOn) for (const w of D.wires) if (wireShown(w)) { onWire.add(w.fromId); onWire.add(w.toId); onWire.add(w.hostId); }
  const rDot = Math.max(2, Math.min(6, 1 + k * 0.9));
  if (partsOn || (RT.declared.loaded && RT.declared.visible)) {
    const casing = new Path2D(), fill = new Path2D();
    for (const n of NODES) {
      if (n.kind !== 'block' || onWire.has(n.id)) continue;
      if (!partsOn) continue;
      const X = sx(n.x), Y = sy(n.y);
      if (X < -10 || X > W_CSS + 10 || Y < -10 || Y > H_CSS + 10) continue;
      nNodes++;
      casing.moveTo(X + rDot + 1.5, Y); casing.arc(X, Y, rDot + 1.5, 0, Math.PI * 2);
      fill.moveTo(X + rDot, Y); fill.arc(X, Y, rDot, 0, Math.PI * 2);
    }
    ctx.fillStyle = '#000'; ctx.fill(casing);
    ctx.fillStyle = '#aeb6c4'; ctx.fill(fill);
  }

  /* hidden wires: dashed, neutral, thickness by compositions */
  if (wiresOn) {
    for (const w of D.wires) {
      if (!wireShown(w)) continue;
      const [a0, b0, a1, b1] = w.bbox;
      if (!inView(a0, b0, a1, b1, 40)) continue;
      nWires++;
      const sel = S.sel && S.sel.type === 'wire' && S.sel.id === w.id;
      const path = new Path2D();
      for (let i = 0; i < w.pts.length; i += 2) { const X = sx(w.pts[i]), Y = sy(w.pts[i + 1]); i ? path.lineTo(X, Y) : path.moveTo(X, Y); }
      ctx.lineCap = 'butt'; ctx.lineJoin = 'round';
      if (sel) { ctx.strokeStyle = 'rgba(239,233,220,0.22)'; ctx.lineWidth = w.width + 14; ctx.stroke(path); }
      ctx.strokeStyle = '#000'; ctx.lineWidth = w.width + 4; ctx.stroke(path);
      ctx.setLineDash([Math.max(8, w.width * 2.2), Math.max(6, w.width * 1.4)]);
      ctx.strokeStyle = '#efe9dc'; ctx.lineWidth = w.width; ctx.stroke(path);
      ctx.setLineDash([]);
      /* arrowhead near the needed end */
      const n = w.pts.length / 2, j = Math.floor(n * 0.8);
      const ax = sx(w.pts[j * 2]), ay = sy(w.pts[j * 2 + 1]), bx = sx(w.pts[(j + 1) * 2]), by = sy(w.pts[(j + 1) * 2 + 1]);
      const ang = Math.atan2(by - ay, bx - ax), s = 7 + w.width;
      ctx.beginPath(); ctx.moveTo(bx + Math.cos(ang) * s * 0.6, by + Math.sin(ang) * s * 0.6);
      ctx.lineTo(bx + Math.cos(ang + 2.5) * s, by + Math.sin(ang + 2.5) * s); ctx.lineTo(bx + Math.cos(ang - 2.5) * s, by + Math.sin(ang - 2.5) * s); ctx.closePath();
      ctx.fillStyle = '#efe9dc'; ctx.strokeStyle = '#000'; ctx.lineWidth = 2; ctx.stroke(); ctx.fill();
    }
    /* wire ends */
    ctx.font = '11px ui-monospace,Menlo,Consolas,monospace'; ctx.textAlign = 'left'; ctx.textBaseline = 'middle';
    for (const id of onWire) {
      const n = NODE_BY_ID.get(id);
      const X = sx(n.x), Y = sy(n.y);
      if (X < -60 || X > W_CSS + 60 || Y < -20 || Y > H_CSS + 20) continue;
      nNodes++;
      ctx.beginPath(); ctx.arc(X, Y, 8, 0, Math.PI * 2); ctx.fillStyle = '#000'; ctx.fill();
      ctx.beginPath(); ctx.arc(X, Y, 6, 0, Math.PI * 2);
      if (n.kind === 'block') { ctx.fillStyle = '#ffffff'; ctx.fill(); }
      else { ctx.lineWidth = 2.2; ctx.strokeStyle = '#ffffff'; ctx.setLineDash(n.kind === 'part' ? [3, 2.5] : []); ctx.stroke(); ctx.setLineDash([]); }
      const text = n.kind === 'block' ? `${n.label} ${n.title}` : n.label;
      /* ends on the right half label inward so the text stays on the plane */
      if (n.x > 0 && n.kind === 'part') { ctx.textAlign = 'right'; label(text, X - 11, Y + 14); ctx.textAlign = 'left'; }
      else if (n.kind === 'part') label(text, X - 6, Y + 14);
      else label(text, X + 11, Y);
    }
  }

  /* block labels when zoomed in far enough to separate them */
  if (partsOn && k > 3.2) {
    ctx.font = '10px ui-monospace,Menlo,Consolas,monospace'; ctx.textAlign = 'left'; ctx.textBaseline = 'middle';
    for (const n of NODES) {
      if (n.kind !== 'block' || onWire.has(n.id)) continue;
      const X = sx(n.x), Y = sy(n.y);
      if (X < -40 || X > W_CSS + 4 || Y < -10 || Y > H_CSS + 10) continue;
      label(k > 9 ? `${n.label} ${n.title.slice(0, 28)}` : n.label, X + rDot + 3, Y, '#8b93a7');
    }
  }

  if (selNode) {
    const n = NODE_BY_ID.get(selNode);
    if (n) { ctx.beginPath(); ctx.arc(sx(n.x), sy(n.y), 12, 0, Math.PI * 2); ctx.strokeStyle = '#ffffff'; ctx.lineWidth = 1.5; ctx.stroke(); }
  }
  finish(t0, nNodes, nLines, nWires);
}

function label(text, X, Y, colour = '#ffffff') {
  ctx.lineWidth = 3; ctx.strokeStyle = '#000'; ctx.strokeText(text, X, Y);
  ctx.fillStyle = colour; ctx.fillText(text, X, Y);
}

function finish(t0, nNodes, nLines, nWires) {
  drawn.nodes = nNodes; drawn.lines = nLines; drawn.wires = nWires; drawn.ms = performance.now() - t0; drawn.frames++;
  const text = `drawn last frame: ${nNodes} dots · ${nLines} declared lines · ${nWires} hidden wires`;
  if (text !== lastDrawnText) { $('drawn').textContent = text; lastDrawnText = text; }
}

/* ── touch: drag to pan, pinch or wheel to zoom, tap to read ────────────── */
const pointers = new Map();
let gesture = null;
canvas.addEventListener('pointerdown', e => {
  canvas.setPointerCapture(e.pointerId);
  pointers.set(e.pointerId, { x: e.offsetX, y: e.offsetY });
  if (pointers.size === 1) gesture = { tap: true, t: performance.now(), x0: e.offsetX, y0: e.offsetY, vx: S.view.x, vy: S.view.y };
  else { gesture = { tap: false, pinch: pinchStart() }; }
});
canvas.addEventListener('pointermove', e => {
  if (!pointers.has(e.pointerId) || !gesture) return;
  pointers.set(e.pointerId, { x: e.offsetX, y: e.offsetY });
  if (pointers.size === 1 && !gesture.pinch) {
    const dx = e.offsetX - gesture.x0, dy = e.offsetY - gesture.y0;
    if (Math.hypot(dx, dy) > 8) gesture.tap = false;
    if (!gesture.tap) { S.view.x = gesture.vx - dx / S.view.k; S.view.y = gesture.vy - dy / S.view.k; schedule(); }
  } else if (pointers.size >= 2 && gesture.pinch) {
    const [p, q] = [...pointers.values()];
    const d = Math.hypot(p.x - q.x, p.y - q.y) || 1, mx = (p.x + q.x) / 2, my = (p.y + q.y) / 2;
    const g = gesture.pinch;
    const k = clampK(g.k * d / g.d);
    S.view.k = k; S.view.x = g.wx - (mx - W_CSS / 2) / k; S.view.y = g.wy - (my - H_CSS / 2) / k;
    schedule();
  }
});
function pinchStart() {
  const [p, q] = [...pointers.values()];
  const mx = (p.x + q.x) / 2, my = (p.y + q.y) / 2;
  return { d: Math.hypot(p.x - q.x, p.y - q.y) || 1, k: S.view.k, wx: wx(mx), wy: wy(my) };
}
function endPointer(e) {
  if (!pointers.has(e.pointerId)) return;
  pointers.delete(e.pointerId);
  if (gesture && gesture.tap && pointers.size === 0 && e.type === 'pointerup' && performance.now() - gesture.t < 600) tapAt(e.offsetX, e.offsetY);
  if (pointers.size === 0) gesture = null;
  else if (pointers.size === 1) { const [p] = [...pointers.values()]; gesture = { tap: false, x0: p.x, y0: p.y, vx: S.view.x, vy: S.view.y }; }
}
canvas.addEventListener('pointerup', endPointer);
canvas.addEventListener('pointercancel', endPointer);
canvas.addEventListener('wheel', e => {
  e.preventDefault();
  const k = clampK(S.view.k * Math.exp(-e.deltaY * 0.0015));
  const X = wx(e.offsetX), Y = wy(e.offsetY);
  S.view.k = k; S.view.x = X - (e.offsetX - W_CSS / 2) / k; S.view.y = Y - (e.offsetY - H_CSS / 2) / k;
  schedule();
}, { passive: false });
const clampK = k => Math.max(S.fitK * 0.5, Math.min(S.fitK * 60, k));

function tapAt(px, py) {
  if (!D.idx) return;
  let best = null;
  if (RT.hidden.loaded && RT.hidden.visible) {
    for (const w of D.wires) {
      if (!wireShown(w)) continue;
      let d = Infinity;
      for (let i = 2; i < w.pts.length; i += 2) d = Math.min(d, W.distToSegment(px, py, sx(w.pts[i - 2]), sy(w.pts[i - 1]), sx(w.pts[i]), sy(w.pts[i + 1])));
      const tol = 18 + w.width / 2;
      if (d <= tol && (!best || d < best.d)) best = { d, sel: { type: 'wire', id: w.id } };
    }
  }
  if (!best) {
    for (const n of NODES) {
      const visible = (n.kind === 'block' && RT.parts.loaded && RT.parts.visible) || (RT.hidden.loaded && RT.hidden.visible && D.wires.some(w => wireShown(w) && (w.fromId === n.id || w.toId === n.id || w.hostId === n.id)));
      if (!visible) continue;
      const d = Math.hypot(sx(n.x) - px, sy(n.y) - py);
      if (d <= 16 && (!best || d < best.d)) best = { d, sel: { type: 'node', id: n.id } };
    }
  }
  if (!best && RT.declared.loaded && RT.declared.visible) {
    D.idx.edges.forEach((e, i) => {
      const a = NODE_BY_ID.get(e.from), b = NODE_BY_ID.get(e.to);
      const d = W.distToSegment(px, py, sx(a.x), sy(a.y), sx(b.x), sy(b.y));
      if (d <= 10 && (!best || d < best.d)) best = { d, sel: { type: 'edge', i } };
    });
  }
  select(best ? best.sel : null);
}

function select(sel) {
  S.sel = sel;
  for (const [id, r] of rowById) r.btn.classList.toggle('on', !!(sel && sel.type === 'wire' && sel.id === id));
  if (sel && sel.type === 'wire' && !RT.vaccines.loaded && !RT.vaccines.loading) {
    /* reading a wire asks whether a vaccine names it: one listing, fetched once */