GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / kuiper-belt / learn-the-kuiper/202610050609

Start Here

A JavaScript file in the learn the kuiper folder of Kuiper Belt that draws wafer meta and solar. It places real (`placeReal`), starts next (`startNext`) and fits line (`fitLine`).

663 lines of JavaScript from kuiper-belt, in 1 file. Topic: Kuiper, cosmos and drawing engines. Section 1540 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. Start Here render · kuiper-belt / learn-the-kuiper/202610050609/start-here.js lines 1–663

Start Here

A JavaScript file in the learn the kuiper folder of Kuiper Belt that draws wafer meta and solar. It places real (`placeReal`), starts next (`startNext`) and fits line (`fitLine`).

renderkuiper-belt / learn-the-kuiper/202610050609/start-here.js · lines 1–663 of 663 · version 2026-10-05 06:09 · Entry point · pattern mulmod (shared by 2 files)

What it does
It draws wafer meta and solar. Defines 118 functions or classes, including mod, fmt, f1, f2, ease. Side effects: changes the web page (DOM); reads or writes files; makes network requests; starts processes; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage agent_infra (path word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). Domain terms in the code: solar.
Inputs & outputs
In: JSON file wafer-meta.json; browser storage (getItem); command-line arguments. Out: JSON file; browser storage (setItem); canvas drawing.
Downstream impact
Used directly by 2 files: Sheet (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610042346/sheet.html); Modes (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050609/modes.html). Reached from 4 other entry points, including Lesson (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050609/lesson.html); Menu (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050354/menu.html); Play (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050609/play.html).
What it achieves
One sheet, like an engineering drawing. window.KGStartHere.open / .close / .run(sentence) The real law is window.KuiperLaw.place (lifted verbatim from the live kuiper-belt `index.html`). It accepts `--random` and `--prove-until`. It responds to click, keydown and input events.
Why it matters
Loaded by the Sheet page at https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610042346/sheet.html and 1 other page.
Application
kuiper-belt · learn-the-kuiper/202610050609 · script
Uses
Kuiper Belt — Index Page (estate URL), What Is Kuiper (estate URL)
Used by
loaded by Sheet (script src), loaded by Modes (script src)
Produces
mod, fmt, f1, f2, ease, hue, isReal, degPerKey, placeReal, place, limitLine, formulaText
Defines here
mod, fmt, f1, f2, ease, hue, isReal, degPerKey, placeReal, place, limitLine, formulaText, plainWords, totalTurn, reset, oneLine, tooLarge, compact, narrow, startNext, land, address, aweText, celebrate, glowDot, fitLine, mulmod, turnExact, sprite, bloomStart
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
kuiper-belt@26fba12ab1b5bab8e71934ab86c58273e5f32682 learn-the-kuiper/202610050609/start-here.js:1-663 · blob 04487a55e5e01fffae462aa010649c497dc8cb4f · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, process, storage · domain stage: agent_infra · users: ai_agent · canonical: unknown
// LEARN THE KUIPER: START HERE. One sheet, like an engineering drawing. window.KGStartHere.open() / .close() / .run(sentence)
// The real law is window.KuiperLaw.place (lifted verbatim from the live kuiper-belt index.html): distance = sqrt(key + 0.5),
// turn = key x 2654435769 mod 2^32 as a share of one lap (222.49 degrees further per key, anticlockwise from 3 o clock).
// Every field of that law is a lever here (PRACTICE). REAL KUIPER snaps them all back and routes placement through KuiperLaw.
// Real lines of Kuiper's own code (tools/wafer_keys.py, tools/key.py, README.md, file order, repeats kept) ride the keys.
// Sheet pattern adapted from the Line Wafer (globalgrid2050 real-systems page): one canvas, a sentence list, a command line, a log.
(function (root) {
  'use strict';
  var G32 = 2654435769, TWO32 = 4294967296, PI2 = 2 * Math.PI, DEG_PER_KEY = 360 * G32 / TWO32, MAXN = 9007199254740992;
  var LINES = [["wafer_keys.py","#!/usr/bin/env python3"],["wafer_keys.py","\"\"\"tools/wafer_keys.py - issue every lin"],["wafer_keys.py",""],["wafer_keys.py","THE RINGS ARE TIME. The CPU wafer is bea"],["wafer_keys.py","numbers that were never issued. This est"],["wafer_keys.py","commit in every repository is put in one"],["wafer_keys.py","of keys is left UNISSUED in proportion t"],["wafer_keys.  … [line shortened here: 12,954 characters; full line on GitHub]
  var PROOF = 'THE SAME PLACES AS THE LIVE KUIPER, KEY FOR KEY';
  var REAL_ISSUED = 43486619138, REAL_SPACE = 59637070538;   // cosmos/wafer-meta.json, 4 Oct 2026
  var PAL = { bg: '#000', ink: '#fff', cyan: '#00ffff', amber: '#ffb000', ring: '#0d2a30', faint: '#0a1a1e' };
  var FONT = '"Segoe UI", "Helvetica Neue", Arial, sans-serif';
  function mod(a, n) { return n === 0 ? 0 : ((a % n) + n) % n; }
  function fmt(n) { if (!isFinite(n)) return String(n); var s = String(Math.round(Math.abs(n))); if (Math.abs(n) >= 1e21) s = Math.abs(n).toExponential(3); return (n < 0 ? '-' : '') + s.replace(/\B(?=(\d{3})+(?!\d))/g, ','); }
  function f1(n) { return (Math.round(n * 10) / 10).toFixed(1); }
  function f2(n) { return (Math.round(n * 100) / 100).toFixed(2); }
  function ease(t) { return t < 0 ? 0 : t > 1 ? 1 : t * t * (3 - 2 * t); }
  function hue(s) { var h = 0; for (var i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) >>> 0; return 'hsl(' + (h % 360) + ',95%,65%)'; }

  // ---------- THE FIELDS OF THE LAW (every one typeable; REAL snaps back) ----------
  var REAL = { firstKey: 0, turnNumber: G32, wrapSize: TWO32, degrees: null, power: 0.5, offset: 0.5, skipPerSec: 600, capSec: 1209600, burstLines: 0, restSec: 3600, dotSize: 1 };
  var FIELDS = [
    ['firstKey', 'FIRST KEY'], ['turnNumber', 'THE TURN NUMBER'], ['wrapSize', 'THE WRAP SIZE (ONE LAP)'], ['degrees', 'HOW FAR ROUND EACH TIME (DEGREES)'],
    ['power', 'HOW FAST IT SPREADS OUT (POWER)'], ['offset', 'START OFFSET'], ['skipPerSec', 'KEYS SKIPPED PER SECOND'], ['capSec', 'LONGEST QUIET COUNTED (SECONDS)'],
    ['burstLines', 'WORK: LINES PER BURST (0 = NO RESTS)'], ['restSec', 'REST: SECONDS BETWEEN BURSTS'], ['dotSize', 'DOT SIZE']
  ];
  var F = {}; function setReal() { for (var k in REAL) F[k] = REAL[k]; }
  function isReal() { for (var k in REAL) if (k !== 'dotSize' && F[k] !== REAL[k]) return false; return true; }
  function degPerKey() { return F.degrees != null ? F.degrees : (F.wrapSize ? 360 * mod(F.turnNumber, F.wrapSize) / F.wrapSize : 0); }
  function placeReal(k) { var L = root.KuiperLaw; if (L) return L.place(k);
    var m = Math.imul((k % TWO32) >>> 0, G32) >>> 0, th = PI2 * m / TWO32, r = Math.sqrt(k + 0.5); return { key: k, m: m, turns: m / TWO32, deg: m / TWO32 * 360, theta: th, r: r, x: r * Math.cos(th), y: r * Math.sin(th) }; }
  function place(k) {
    if (isReal()) { var p = placeReal(k); p.total = k * DEG_PER_KEY; return p; }
    var deg, total;
    if (F.degrees != null) { total = k * F.degrees; deg = turnExact(k, F.degrees); }
    else if (F.wrapSize === TWO32 && Number.isInteger(F.turnNumber) && k < TWO32 * 2) { var m = Math.imul((k % TWO32) >>> 0, F.turnNumber >>> 0) >>> 0; deg = m / TWO32 * 360; total = k * mod(F.turnNumber, TWO32) / TWO32 * 360; }
    else { var w = F.wrapSize; var mm = w ? mod(mod(k, w) * mod(F.turnNumber, w), w) : 0; deg = w ? mm / w * 360 : 0; total = w ? k * mod(F.turnNumber, w) / w * 360 : 0; }
    var base = k + F.offset, r = base < 0 ? -Math.pow(-base, F.power) : Math.pow(base, F.power); if (!isFinite(r)) r = 0;
    var th = deg * Math.PI / 180; return { key: k, r: r, deg: deg, theta: th, x: r * Math.cos(th), y: r * Math.sin(th), total: total }; }
  // one plain line about what the fields do to the shape (never crash, just say it)
  function limitLine() {
    if (isReal()) return ''; var d = degPerKey(), lines = [];
    if (F.degrees == null && F.wrapSize !== TWO32 && F.wrapSize >= 1 && F.wrapSize <= 60 && Number.isInteger(F.wrapSize)) lines.push('WRAP SIZE ' + fmt(F.wrapSize) + ': ONLY ' + fmt(F.wrapSize) + ' DIRECTIONS, ' + fmt(F.wrapSize) + ' SPOKES');
    else if (mod(d, 360) === 0) lines.push('TURN ' + fmt(d) + ': EVERY DOT LANDS ON ONE LINE (' + (d === 0 ? 'NO TURN AT ALL' : 'A FULL LAP EACH TIME') + ')');
    else if (Math.abs(d) < 0.01) lines.push('TURN ' + d + ': THE DOTS CRAWL ROUND, ONE TIGHT ARM');
    else if (Math.abs(360 / (mod(d, 360) || 1) - Math.round(360 / (mod(d, 360) || 1))) < 1e-9 && Math.round(360 / mod(d, 360)) <= 24) lines.push('TURN ' + f1(d) + ': ' + Math.round(360 / mod(d, 360)) + ' SPOKES');
    if (F.power >= 2) lines.push('POWER ' + F.power + ': DOTS FLY OUT, THE CENTRE EMPTIES'); else if (F.power === 1) lines.push('POWER 1: CROWDED CENTRE, THIN RIM'); else if (F.power <= 0) lines.push('POWER ' + F.power + ': ' + (F.power === 0 ? 'EVERY DOT AT DISTANCE 1, ONE RING' : 'INSIDE OUT: BIG KEYS FALL TO THE CENTRE'));
    if (F.offset < 0) lines.push('OFFSET ' + fmt(F.offset) + ': THE FIRST ' + fmt(-F.offset) + ' KEYS HAVE NO DISTANCE, THEY SIT MIRRORED');
    return lines.join('. '); }
  function formulaText() { var d = degPerKey(); return 'DISTANCE = (KEY + ' + F.offset + ')' + (F.power === 0.5 ? ' SQUARE ROOTED' : ' TO THE POWER ' + F.power) + '.  TURN = KEY x ' + f2(d) + ' DEGREES, FULL LAPS THROWN AWAY.  QUIET TIME: ' + fmt(F.skipPerSec) + ' KEYS SKIPPED PER SECOND.'; }
  function plainWords() { if (isReal()) return 'FURTHER OUT EACH TIME. TURNS A LITTLE MORE THAN HALF WAY ROUND EACH TIME. FULL LAPS THROWN AWAY.'; return 'PRACTICE: ' + (limitLine() || 'YOUR OWN SHAPE. TURN ' + f2(degPerKey()) + ' EACH TIME, SPREAD POWER ' + F.power + '.'); }

  // ---------- state ----------
  var UI = null, cv = null, g = null, raf = 0, lastT = 0, S = null, PREF = { fs: 1, muted: false, formula: false, lv: 0, pal: 'KUIPER', by: 'group', mood: 'CALM', seenHints: [] };
  function totalTurn(p) { return p.total != null ? p.total : p.key * DEG_PER_KEY; }
  function reset() { S = { i: 0, key: F.firstKey, keys: [], playing: false, speed: 0.6, anim: null, scale: 1.6, scaleTarget: 1.6, cap: '', work: '', flash: 0, sel: -1, counts: {}, file: '', done: false, dup: false, geom: null, probe: null, drag: null, big: null, mag: null, log: (S && S.log) || [], wonder: null, nightCap: 0,
      addressed: (S && S.addressed) || 0, awe: (S && S.awe) || {}, ring: null, shadows: !!(S && S.shadows), bigSel: null, ptrs: {}, pinch: null, hold: null, lastTap: 0, bloom: null, dragged: false };
    // V9: OPEN ON ONE PARTICLE: key 0 (the first key) alone, so count N is always keys 0 to N - 1 (commander finding d); annotated (its radius line, its angle arc). The count reads 1. x10 or +1 lays the keys out from the first key.
    S.i = 0; S.key = F.firstKey; S.file = ''; startNext(); land(S.anim.p); S.anim = null;
    S.sel = 0; S.flash = 0; var q = S.keys[0]; S.cap = 'KEY ' + fmt(q.key) + ': THE FIRST KEY'; S.work = oneLine(q); }
  function oneLine(q) { if (narrow()) return 'DISTANCE ' + f2(q.r) + ', ANGLE ' + f1(q.deg) + '\u00b0'; return 'DISTANCE ' + f2(q.r) + ' FROM THE CENTRE. ANGLE ' + f1(q.deg) + '\u00b0 FROM 3 O\'CLOCK.'; }
  function tooLarge(limit) { var line = 'THAT NUMBER IS TOO LARGE FOR THIS COMPUTER TO SHOW. THE REAL LIMIT HERE IS ' + fmt(limit) + '.'; if (narrow()) { S.cap = 'TOO LARGE FOR THIS COMPUTER.'; S.work = 'LIMIT ' + fmt(limit); } else S.cap = line; hint(line, true); return line; }
  function compact() { return !!(UI && (UI.root.clientWidth < 700 || UI.root.clientHeight < 500)); }
  function narrow() { return !!(UI && UI.root.clientWidth < 700); }
  function startNext() {
    if (S.i >= LINES.length) { S.playing = false; S.done = true; S.cap = 'EVERY LINE PLACED: ' + fmt(S.keys.length) + ' KEYS. PRESS PLAY TO RUN IT AGAIN.'; S.work = 'NOTHING IS STORED BUT THE RULE. EVERY DOT IS WORKED OUT FROM ITS KEY.'; return; }
    if (F.burstLines > 0 && S.i > 0 && S.i % F.burstLines === 0 && F.restSec > 0) { var skip = Math.round(Math.min(F.restSec, F.capSec) * F.skipPerSec); if (skip > 0) { S.key += skip; S.nightCap = skip; S.restSec = F.restSec; } }
    var L = LINES[S.i], file = L[0], text = L[1], newFile = file !== S.file; S.file = file;
    var k = S.key++, p = place(k); p.text = text; p.file = file; p.newFile = newFile; p.night = S.nightCap || 0; p.restSec = S.restSec; S.nightCap = 0;
    S.anim = { p: p, t: 0, dur: Math.max(0.08, Math.min(2.2, 1 / S.speed)) }; S.i++;
  }
  function land(p) { S.keys.push(p); S.counts[p.text] = (S.counts[p.text] || 0) + 1; S.flash = 0.6; S.scaleTarget = Math.max(S.scaleTarget, Math.abs(p.r) * 1.1); tone(p.r); address(1); }
  // THE AWE COUNTER: every particle ever addressed on this sheet, and the coordinates stored to do it (none)
  function address(n) { if (n > 0) S.addressed += n; }
  // V5: ONE COUNT. countNow() is the only number of keys shown anywhere on the sheet.
  function aweText() { return 'KEYS ON THE SHEET: ' + fmt(countNow()) + '    COORDINATES STORED: 0'; }
  // CELEBRATIONS: a ring of light and a rising chord, once each (first drag, first million, first trillion)
  function chord() { if (!gestured || PREF.muted) return; try { ac(); var t = AC.currentTime; [262, 330, 392, 523, 659, 784].forEach(function (fq, i) { var o = AC.createOscillator(), gn = AC.createGain(), t0 = t + i * 0.11; o.type = 'triangle'; o.frequency.value = fq; gn.gain.setValueAtTime(0.0001, t0); gn.gain.exponentialRampToValueAtTime(0.05, t0 + 0.04); gn.gain.exponentialRampToValueAtTime(0.0  … [line shortened here: 511 characters; full line on GitHub]
  function celebrate(id, text) { if (!S || S.awe[id]) return; S.awe[id] = true; S.ring = { t: 0 }; chord(); hint(text, true); }
  function drawRing(cx, cy, R) { if (!S.ring) return; var f = ease(S.ring.t / 2.5), a = Math.max(0, 1 - S.ring.t / 2.5), rr = 10 + R * 1.5 * f; g.strokeStyle = PAL.cyan; g.globalAlpha = a * 0.22; g.lineWidth = 28; g.beginPath(); g.arc(cx, cy, rr, 0, PI2); g.stroke(); g.globalAlpha = a * 0.55; g.lineWidth = 10; g.stroke(); g.strokeStyle = '#fff'; g.globalAlpha = a; g.lineWidth = 3; g.stroke(); g.gl  … [line shortened here: 416 characters; full line on GitHub]
  // THE DOTS ARE THE MAIN EVENT: a soft halo, a bright body, a white-hot heart
  // V5 THE STAR LOOK, copied from modules/zoom.js draw(): a soft halo from 0.5 r to 2.6 r at 0.35, a bright body, a white heart from 5 px up.
  function glowDot(x, y, r, col, al) { al = al == null ? 1 : al; if (!isFinite(x) || !isFinite(y)) return; var hr = r * 2.6, gr = g.createRadialGradient(x, y, r * 0.5, x, y, hr); gr.addColorStop(0, col); gr.addColorStop(1, 'rgba(0,0,0,0)');
    g.globalAlpha = 0.35 * al; g.fillStyle = gr; g.beginPath(); g.arc(x, y, hr, 0, PI2); g.fill(); g.globalAlpha = al; g.fillStyle = col; g.beginPath(); g.arc(x, y, r, 0, PI2); g.fill();
    if (r >= 5) { g.fillStyle = '#fff'; g.globalAlpha = 0.9 * al; g.beginPath(); g.arc(x, y, r * 0.45, 0, PI2); g.fill(); } g.globalAlpha = 1; }
  // the chosen star: an amber ring and an amber glow (zoom.js drawSelection)
  function selStar(x, y, r) { if (!isFinite(x) || !isFinite(y)) return; g.strokeStyle = PAL.amber; g.lineWidth = 3; g.beginPath(); g.arc(x, y, Math.max(14, r * 1.9), 0, PI2); g.stroke(); g.save(); g.shadowColor = PAL.amber; g.shadowBlur = 30; g.fillStyle = PAL.amber; g.beginPath(); g.arc(x, y, r, 0, PI2); g.fill(); g.restore(); if (r >= 5) { g.fillStyle = 'rgba(255,255,255,0.9)'; g.beginPath(); g.  … [line shortened here: 442 characters; full line on GitHub]
  // a faint star field in the spare black outside the rim only (never inside the wafer: every dot in the circle is a key)
  function starField(W, H, cx, cy, R, al) { var lim = (R + 10) * (R + 10); for (var i = 0; i < 170; i++) { var x = h01(i * 3 + 11) * W, y = h01(i * 3 + 12) * H, d = (x - cx) * (x - cx) + (y - cy) * (y - cy); if (d < lim) continue; var b = h01(i * 3 + 13); g.globalAlpha = (0.12 + 0.26 * b) * (al == null ? 1 : al); g.fillStyle = b > 0.7 ? '#ffffff' : '#66ccff'; var sz = b > 0.85 ? 2 : 1.3; g.fillRec  … [line shortened here: 457 characters; full line on GitHub]
  var SOFT = 'rgba(102,204,255,0.7)';
  // captions are ONE line and never cut mid-word: the longest run of whole clauses (else whole words) that fits the width
  function fitLine(text, e) { text = String(text == null ? '' : text); if (!g || !e) return text; var cs = getComputedStyle(e), avail = e.clientWidth - 2; if (!(avail > 40)) return text; g.save(); g.font = cs.fontWeight + ' ' + cs.fontSize + ' ' + FONT; function w(t) { return g.measureText(t).width; }
    if (w(text) <= avail) { g.restore(); return text; } var cut = '', re = /[.:,;]\s+|\s{2,}/g, m; while ((m = re.exec(text))) { var head = text.slice(0, m.index + 1).replace(/[,:;\s]+$/, ''); if (w(head) <= avail) cut = head; else break; }
    if (!cut) { var words = text.split(' '), out = ''; for (var i = 0; i < words.length; i++) { var nx = out ? out + ' ' + words[i] : words[i]; if (w(nx) > avail) break; out = nx; } cut = out.replace(/[,:;(\s]+$/, ''); } g.restore(); return cut; }
  // exact (a x b) mod m for whole numbers below 2^29 (k x degrees would lose precision before the modulo at huge keys)
  function mulmod(a, b, m) { var bh = Math.floor(b / 32768), bl = b % 32768; return (((a * bh) % m) * 32768 + a * bl) % m; }
  var DEGQ = 360000000;   // one lap in millionths of a degree
  function turnExact(k, d) { var D = Math.round(d * 1e6); if (!Number.isInteger(k) || k < 0 || Math.abs(d * 1e6 - D) > 1e-6 || Math.abs(D) > 9e15) return mod(k * d, 360); return mulmod(k % DEGQ, mod(D, DEGQ), DEGQ) / 1e6; }
  var SPR = {}, SPRN = 0;
  function sprite(col, rad) { var dpr = Math.min(3, window.devicePixelRatio || 1), key = col + '|' + Math.round(rad * 4) + '|' + dpr, sp = SPR[key]; if (sp) return sp; if (SPRN++ > 60) { SPR = {}; SPRN = 0; }
    var half = Math.ceil(rad * (rad >= 3 ? 2.6 : 1.6)) + 1, px = Math.ceil(half * 2 * dpr), c = document.createElement('canvas'); c.width = c.height = px; var q = c.getContext('2d'), rgb = col.charAt(0) === '#' && col.length === 7 ? hex(col).join(',') : '0,255,255', gr = q.createRadialGradient(px / 2, px / 2, 0, px / 2, px / 2, px / 2), core = rad / half;
    gr.addColorStop(0, rad >= 5 ? '#ffffff' : 'rgba(' + rgb + ',1)'); gr.addColorStop(core * 0.45, rad >= 5 ? 'rgba(255,255,255,0.9)' : 'rgba(' + rgb + ',1)'); gr.addColorStop(core * 0.5, 'rgba(' + rgb + ',1)'); gr.addColorStop(core * 0.92, 'rgba(' + rgb + ',1)'); gr.addColorStop(Math.min(0.98, core * 1.1), 'rgba(' + rgb + ',' + (rad >= 3 ? 0.3 : 0.16) + ')'); gr.addColorStop(1, 'rgba(' + rgb + ',  … [line shortened here: 500 characters; full line on GitHub]
  // ---------- V5: THE OPENING MOMENT. One dot, a bloom to a sunflower, one line. 6 seconds. Any tap skips. ----------
  var INTRO_N = 600, INTRO_LINE = ['EVERY DOT HAS AN ADDRESS.', 'LEARN THE RULE.', 'HELP ELECTRIFY THE WORLD.'];
  function bloomStart() { if (!UI || !S) return; S.bloom = { t: 0, sung: false }; UI.root.classList.add('bloom'); }
  function bloomSkip() { if (!S || !S.bloom) return false; S.bloom = null; if (UI) { UI.root.classList.remove('bloom'); UI.capAt = performance.now(); } return true; }
  function bloomSong() { if (!gestured || PREF.muted) return; try { ac(); var t = AC.currentTime; [262, 294, 330, 392, 440, 523, 587, 659, 784, 1047].forEach(function (fq, i) { var o = AC.createOscillator(), gn = AC.createGain(), t0 = t + i * 0.3; o.type = 'triangle'; o.frequency.value = fq; gn.gain.setValueAtTime(0.0001, t0); gn.gain.exponentialRampToValueAtTime(0.05, t0 + 0.05); gn.gain.exponent  … [line shortened here: 535 characters; full line on GitHub]
  function drawBloom(W, H) { var I = S.bloom, ge = S.geom; if (!I || !ge) return; var t = I.t, a = t > 5 ? Math.max(0, 6 - t) : 1, b = ease((t - 1.2) / 3.2), cx = ge.cx, cy = ge.cy, R = ge.R, i;
    var n = Math.max(1, Math.round(1 + (INTRO_N - 1) * b * b)), view = 1.6 + (Math.sqrt(INTRO_N) * 1.06 - 1.6) * b, unit = R / view, dr = Math.max(2.5, Math.min(10, unit * 0.3));
    g.globalAlpha = a; g.fillStyle = '#000'; g.fillRect(0, 0, W, H); g.globalAlpha = 1; starField(W, H, cx, cy, R, a);
    for (var k = n; k >= 1; k--) { var p = placeReal(k), u = k / INTRO_N, col = k === 1 ? '#ffffff' : u < 0.6 ? mix('#fff2c0', '#ffb000', u / 0.6) : mix('#ffb000', '#00ffff', (u - 0.6) / 0.4); glowDot(cx + p.x * unit, cy - p.y * unit, k === 1 ? dr + (t < 1.2 ? 3 + 2 * Math.sin(t * 6) : 2) : dr, col, a); }
    var ta = ease((t - 1.5) / 1.0) * a; if (ta > 0) { var nr = W < 700, lines = nr ? INTRO_LINE : [INTRO_LINE[0] + ' ' + INTRO_LINE[1], INTRO_LINE[2]], size = Math.max(24, (nr || H < 500 ? 26 : 34) * PREF.fs), lh = size * 1.25, barB = UI && W < 700 ? UI.bar.offsetHeight : 0, below = H - barB - (cy + R), y0 = below > lines.length * lh + 30 ? cy + R + (below - lines.length * lh) / 2 + lh / 2 : H - b  … [line shortened here: 438 characters; full line on GitHub]
      g.globalAlpha = ta * 0.7; g.fillStyle = '#000'; g.fillRect(0, y0 - lh * 0.75, W, lines.length * lh + lh * 0.5); g.globalAlpha = ta; for (i = 0; i < lines.length; i++) txt(lines[i], W / 2, y0 + i * lh, i === lines.length - 1 ? PAL.amber : '#fff', size, 'center'); }
    g.globalAlpha = 1; }
  function reflow() { var rm = 1.6; for (var i = 0; i < S.keys.length; i++) { var o = S.keys[i], p = place(o.key); p.text = o.text; p.file = o.file; p.newFile = o.newFile; p.night = o.night; p.restSec = o.restSec; S.keys[i] = p; if (Math.abs(p.r) > rm) rm = Math.abs(p.r); } S.scaleTarget = rm * 1.1; if (S.probe) probeAt(S.probe.r, S.probe.deg); }
  function working(p, phase) {
    var total = totalTurn(p), laps = Math.floor(total / 360); if (narrow()) return phase === 0 ? 'KEY ' + fmt(p.key) + ' ...' : (laps > 0 ? fmt(laps) + (laps === 1 ? ' LAP + ' : ' LAPS + ') : 'TURN ') + f1(p.deg) + '\u00b0, DISTANCE ' + f2(p.r);
    var s = 'KEY ' + fmt(p.key) + ' -> TURN ' + f2(degPerKey()) + ' x ' + fmt(p.key) + ' = ' + f1(total);
    if (phase === 0) return s + ' ...';
    return s + (laps > 0 ? ' = ' + fmt(laps) + (laps === 1 ? ' LAP' : ' LAPS') + ' + ' + f1(p.deg) : '') + ' -> DISTANCE ' + f2(p.r) + (isReal() ? '' : '  (PRACTICE: YOUR FIELDS)');
  }
  function lineText(p) { return p.text === '' ? '(AN EMPTY LINE: IT STILL GETS A KEY)' : p.text; }
  function logLine(s) { S.log.push(s); if (S.log.length > 2) S.log.shift(); if (UI) UI.log.textContent = S.log.join('\n'); }

  function update(dt) {
    S.scale += (S.scaleTarget - S.scale) * Math.min(1, dt * 3); if (S.flash > 0) S.flash -= dt;
    if (S.ring) { S.ring.t += dt; if (S.ring.t > 2.5) S.ring = null; }
    if (S.bloom) { S.bloom.t += dt; if (S.bloom.t > 1.2 && !S.bloom.sung) { S.bloom.sung = true; bloomSong(); } if (S.bloom.t >= 6) bloomSkip(); }
    if (S.big) S.big.t = Math.min(1, S.big.t + dt / 2.5);
    if (S.wonder) wonderStep(dt);
    if (S.anim) { var a = S.anim; a.t += dt; var p = a.p, f = a.t / a.dur;
      if (p.night && f < 0.35) { S.cap = 'QUIET TIME: ' + fmt(p.restSec || 10) + ' SECONDS WITH NO CODE. ' + fmt(F.skipPerSec) + ' KEYS A SECOND PASS EMPTY: ' + fmt(p.night) + ' SKIPPED.'; S.work = PREF.formula ? 'THE NEXT LINE GETS KEY ' + fmt(p.key) + ' AND LANDS FURTHER OUT.' : 'NIGHT OFF: EMPTY RING.'; }
      else { S.cap = 'KEY ' + fmt(p.key) + (p.newFile ? '  NEW FILE ' + p.file + ':  ' : ':  ') + lineText(p); S.work = working(p, f < 0.3 ? 0 : 1); }
      if (a.t >= a.dur) { land(p); S.anim = null; S.work = working(p, 1); var c = S.counts[p.text]; if (c > 1) S.cap = 'KEY ' + fmt(p.key) + ':  ' + lineText(p) + '   (SEEN ' + c + ' TIMES: ' + c + ' KEYS, ONE COLOUR)'; } }
    if (S.playing && !S.anim && S.sel < 0 && !S.big) {
      if (S.speed >= 12) { var n = Math.max(1, Math.round(S.speed * dt)); for (var i = 0; i < n && S.i < LINES.length; i++) { startNext(); if (S.anim) { var q = S.anim.p; land(q); S.anim = null; S.cap = 'KEY ' + fmt(q.key) + ':  ' + lineText(q); S.work = working(q, 1); } } if (S.i >= LINES.length) startNext(); }
      else startNext(); }
  }

  // ---------- the drawing ----------
  function txt(s, x, y, c, size, align) { g.fillStyle = c; g.font = '400 ' + size + 'px ' + FONT; g.textAlign = align; g.textBaseline = 'middle'; g.fillText(s, x, y); }
  function leader(x, y, label, color, size, side) { var lx = x + (side < 0 ? -70 : 70), ly = y - 36; g.strokeStyle = color; g.lineWidth = 2; g.beginPath(); g.moveTo(x, y); g.lineTo(lx, ly); g.lineTo(lx + (side < 0 ? -14 : 14), ly); g.stroke(); txt(label, lx + (side < 0 ? -18 : 18), ly - size * 0.1, color, size, side < 0 ? 'right' : 'left'); }
  function draw(W, H) { drawSheet(W, H); if (S.bloom) drawBloom(W, H); }
  function drawSheet(W, H) {
    g.fillStyle = PAL.bg; g.fillRect(0, 0, W, H); if (S.geom) starField(W, H, S.geom.cx, S.geom.cy, S.geom.R);
    var TOD = tod(), top = (!TOD && UI) ? Math.max(0, UI.top.offsetHeight - 8) : 0, bot = TOD ? 110 * PREF.fs : 0, Wd = W, free = H - top - bot;
    var R = TOD ? Math.max(60, Math.min(Wd / 2 - 8, free / 2 - 12)) : Math.max(60, Math.min(Wd / 2 - 8, H / 2 - 8)), cx = Wd / 2, cy = TOD ? top + free / 2 : H / 2, fs = Math.max(24, 26 * PREF.fs);
    if (S.big) { drawBig(W, H, cx, cy, R, fs); hud(W, H, cx, cy, R, fs); return; }
    var unit = R / S.scale, ds = Math.max(0.2, F.dotSize);
    g.strokeStyle = PAL.ring; g.lineWidth = 2; g.beginPath(); g.arc(cx, cy, R, 0, PI2); g.stroke();
    rings(cx, cy, unit, R);
    g.strokeStyle = PAL.ring; g.lineWidth = 2; g.beginPath(); g.moveTo(cx, cy); g.lineTo(cx + R, cy); g.stroke();   // 3 o clock, where every turn starts
    var n = S.keys.length, i, p, x, y, dr = Math.max(2, Math.min(10, unit * 0.3)) * ds * (TOD ? 1.5 : 1), rmNow = 0, selText = S.sel >= 0 ? S.keys[S.sel].text : null; S.dr = dr;
    for (i = 0; i < n; i++) { p = S.keys[i]; x = cx + p.x * unit; y = cy - p.y * unit; if (isFinite(p.r) && Math.abs(p.r) > rmNow) rmNow = Math.abs(p.r); if (Math.abs(p.r) * unit > R + 4 || !isFinite(x)) continue;
      if (S.intro && i === 0 && n === 2) { g.fillStyle = '#2f5560'; g.beginPath(); g.arc(x, y, dr * 0.5, 0, PI2); g.fill(); continue; }   // the opening: one particle (key 1); key 0 waits, dim, on the 0 line
      var same = selText !== null && p.text === selText, rep = S.dup && S.counts[p.text] > 1;
      if (S.dup && !rep && !same && i !== S.sel) { g.fillStyle = '#1c2a30'; g.beginPath(); g.arc(x, y, dr, 0, PI2); g.fill(); } else if (i === S.sel) selStar(x, y, dr + 2); else glowDot(x, y, same ? dr + 2 : dr, same ? PAL.ink : dotColour(p, i, n));
      if (p.moved && p.trueX != null) { var tx0 = cx + p.trueX * unit, ty0 = cy - p.trueY * unit; g.strokeStyle = PAL.ink; g.setLineDash([6, 6]); g.lineWidth = 2; g.beginPath(); g.moveTo(x, y); g.lineTo(tx0, ty0); g.stroke(); g.setLineDash([]); g.beginPath(); g.arc(tx0, ty0, dr + 3, 0, PI2); g.stroke(); if (i === S.sel) txt('TRUE PLACE', tx0, ty0 - fs * 0.9, PAL.ink, fs * 0.9, 'center'); } }
    S.rimNow = rmNow;
    // X/Y SHADOWS: the selected dot drops a line to the floor (X) and to the wall (Y)
    if (S.shadows && !S.anim) { var sp = S.sel >= 0 ? S.keys[S.sel] : S.probe; if (sp && isFinite(sp.x)) { var sx0 = cx + sp.x * unit, sy0 = cy - sp.y * unit; if (Math.hypot(sx0 - cx, sy0 - cy) <= R + 4) {
      g.strokeStyle = PAL.green; g.setLineDash([6, 6]); g.lineWidth = 3; g.beginPath(); g.moveTo(sx0, sy0); g.lineTo(sx0, cy); g.moveTo(sx0, sy0); g.lineTo(cx, sy0); g.stroke(); g.setLineDash([]);
      g.strokeStyle = PAL.green; g.lineWidth = 2; g.beginPath(); g.moveTo(cx - R, cy); g.lineTo(cx + R, cy); g.moveTo(cx, cy - R); g.lineTo(cx, cy + R); g.stroke();
      txt('X ' + f2(sp.x), sx0, cy + (sp.y >= 0 ? fs * 0.8 : -fs * 0.8), PAL.green, fs, 'center'); txt('Y ' + f2(sp.y), cx + (sp.x >= 0 ? -10 : 10), sy0, PAL.green, fs, sp.x >= 0 ? 'right' : 'left'); } } }
    // THE DIAL: how far round each key, and the laps thrown away (the MOD)
    if (false) { var dR = Math.max(36, Math.min(60, R * 0.16)), dx0 = 16 + dR, dy0 = cy + R - dR - 4, dg0 = degPerKey(), dth = mod(dg0, 360) * Math.PI / 180;
      g.strokeStyle = PAL.ring; g.lineWidth = 2; g.beginPath(); g.arc(dx0, dy0, dR, 0, PI2); g.stroke(); g.fillStyle = 'rgba(255,176,0,0.2)'; g.beginPath(); g.moveTo(dx0, dy0); g.arc(dx0, dy0, dR, 0, -dth, true); g.closePath(); g.fill();
      g.strokeStyle = PAL.amber; g.lineWidth = 4; g.beginPath(); g.moveTo(dx0, dy0); g.lineTo(dx0 + dR * Math.cos(dth), dy0 - dR * Math.sin(dth)); g.stroke(); g.strokeStyle = PAL.ring; g.lineWidth = 2; g.beginPath(); g.moveTo(dx0, dy0); g.lineTo(dx0 + dR, dy0); g.stroke();
      txt('EACH KEY: +' + f2(dg0), dx0 + dR + 10, dy0 - fs * 0.6, PAL.amber, fs * 0.92, 'left'); var selp = S.sel >= 0 ? S.keys[S.sel] : (n ? S.keys[n - 1] : null); if (selp) txt('LAPS THROWN AWAY: ' + fmt(Math.floor(totalTurn(selp) / 360)), dx0 + dR + 10, dy0 + fs * 0.6, PAL.ink, fs * 0.92, 'left'); }
    drawRing(cx, cy, R);
    if (S.flash > 0 && n && !S.anim && Math.abs(S.keys[n - 1].r) * unit <= R + 4) { p = S.keys[n - 1]; g.fillStyle = 'rgba(255,255,255,' + Math.min(1, S.flash) + ')'; g.beginPath(); g.arc(cx + p.x * unit, cy - p.y * unit, dr + 10 * S.flash, 0, PI2); g.fill(); }
    var a = S.anim;
    if (a) { p = a.p; var f = a.t / a.dur, fr = ease(f / 0.3), ft = ease((f - 0.3) / 0.5), fd = ease((f - 0.8) / 0.2), rr = Math.min(R, Math.abs(p.r) * unit);
      if (p.night) { var r0 = n ? Math.abs(S.keys[n - 1].r) * unit : 0; g.fillStyle = 'rgba(255,176,0,0.14)'; g.beginPath(); g.arc(cx, cy, r0 + (rr - r0) * fr, 0, PI2); g.arc(cx, cy, r0, 0, PI2, true); g.fill(); }
      g.strokeStyle = PAL.cyan; g.lineWidth = 3; g.setLineDash([8, 8]); g.beginPath(); g.arc(cx, cy, rr * fr, 0, PI2); g.stroke(); g.setLineDash([]);
      if (f > 0.3) { var laps = Math.floor(totalTurn(p) / 360), lapsShown = Math.min(Math.max(laps, 0), 3), nowTurn = (lapsShown * 360 + p.deg) * ft, th = mod(nowTurn, 360) * Math.PI / 180;
        g.fillStyle = 'rgba(255,176,0,0.18)'; g.beginPath(); g.moveTo(cx, cy); g.arc(cx, cy, R * 0.5, 0, -th, true); g.closePath(); g.fill();
        g.strokeStyle = PAL.amber; g.lineWidth = 5; g.beginPath(); g.moveTo(cx, cy); g.lineTo(cx + R * Math.cos(th), cy - R * Math.sin(th)); g.stroke();
        if (laps > 0) txt((PREF.formula ? 'LAPS THROWN AWAY: ' : 'FULL LAPS THROWN AWAY: ') + fmt(Math.floor(ft * laps + 1e-9)), cx, cy + R * 0.72, PAL.amber, fs, 'center'); }
      if (f > 0.8) { var dx = cx + p.x * unit, dy = cy - p.y * unit, sx = cx + (dx - cx) * fd, sy = top + (dy - top) * fd; g.fillStyle = dotColour(p, n, n + 1); g.beginPath(); g.arc(sx, sy, dr + 4, 0, PI2); g.fill(); } }
    else if (S.sel >= 0 && S.keys[S.sel]) { p = S.keys[S.sel]; if (TOD) todAnnotate(cx, cy, R, unit, p, fs); else annotate(cx, cy, R, unit, p, 'KEY ' + fmt(p.key), fs); }
    if (TOD && isReal() && !S.anim && n >= 30 && S.sel < 0) drawSmile(cx, cy, R);
    if (S.probe) { var q = S.probe; annotate(cx, cy, R, unit, q, 'YOUR DOT', fs); g.fillStyle = PAL.ink; g.beginPath(); g.arc(cx + q.x * unit, cy - q.y * unit, dr + 5, 0, PI2); g.fill(); }
    S.geom = { cx: cx, cy: cy, unit: unit, R: R }; hud(W, H, cx, cy, R, fs);
  }
  function annotate(cx, cy, R, unit, p, name, fs) { var th = p.deg * Math.PI / 180, r2 = Math.min(R, Math.abs(p.r) * unit), x = cx + p.x * unit, y = cy - p.y * unit; if (Math.hypot(x - cx, y - cy) > R) { x = cx + r2 * Math.cos(th); y = cy - r2 * Math.sin(th); }
    g.strokeStyle = PAL.cyan; g.setLineDash([8, 8]); g.lineWidth = 3; g.beginPath(); g.arc(cx, cy, r2, 0, PI2); g.stroke(); g.setLineDash([]);
    g.fillStyle = 'rgba(255,176,0,0.15)'; g.beginPath(); g.moveTo(cx, cy); g.arc(cx, cy, Math.min(r2, R * 0.5), 0, -th, true); g.closePath(); g.fill();
    g.strokeStyle = PAL.amber; g.lineWidth = 4; g.beginPath(); g.moveTo(cx, cy); g.lineTo(x, y); g.stroke();
    var side = x < cx ? 1 : -1, up = y > cy ? -1 : 1; var lx = x + side * 60, ly = y + up * 40;   // v4: the numbers live in the corner readout, the centre stays clear
    // the arc from 3 o clock round to the dot, anticlockwise, with an arrow head: this IS the angle
    g.strokeStyle = PAL.amber; g.lineWidth = 4; g.beginPath(); g.arc(cx, cy, r2, 0, -th, true); g.stroke(); var ax = cx + r2 * Math.cos(th), ay = cy - r2 * Math.sin(th), tang = th + Math.PI / 2; g.beginPath(); g.moveTo(ax, ay); g.lineTo(ax - 14 * Math.cos(tang) + 8 * Math.cos(th), ay + 14 * Math.sin(tang) - 8 * Math.sin(th)); g.moveTo(ax, ay); g.lineTo(ax - 14 * Math.cos(tang) - 8 * Math.cos(th),   … [line shortened here: 457 characters; full line on GitHub]
    var tx = lx + side * 18, al = side < 0 ? 'right' : 'left';
    if (true) {} else if (name === 'YOUR DOT') { txt('ANGLE ' + f1(p.deg) + ' DEGREES', tx, ly - fs * 1.1, PAL.amber, fs, al); txt('FROM 3 O\'CLOCK, ANTICLOCKWISE', tx, ly, PAL.ink, fs * 0.85, al); txt('DISTANCE ' + f2(p.r), tx, ly + fs * 1.1, PAL.cyan, fs, al); }
    else { txt(name, tx, ly - fs * 1.1, PAL.ink, fs, al); txt('DISTANCE ' + f2(p.r), tx, ly, PAL.cyan, fs, al); txt('TURN ' + f1(p.deg), tx, ly + fs * 1.1, PAL.amber, fs, al); }
    if (name === 'YOUR DOT') glowDot(x, y, 9, '#ffffff'); else selStar(x, y, Math.max(9, (S.dr || 8) + 2)); }   // amber dot in a cyan ring: the selected-dot look
  // HOW MANY: the whole circle at N dots (a fair sample of 20,000, placed with the law in force), rim = sqrt(N) for the real law
  function rings(cx, cy, unit, Rpx) { var step = 1, m = [2, 2.5, 2], j = 0; while (step * unit < 26 && step < 1e15) { step *= m[j % 3]; j++; } S.ringStep = step; g.strokeStyle = '#143840'; g.lineWidth = 1; for (var k = 1; k * step * unit < Rpx - 2 && k < 60; k++) { g.beginPath(); g.arc(cx, cy, k * step * unit, 0, PI2); g.stroke(); } }
  var SAMPLE = null, SAMPLE_KEY = '';
  function h01(i) { var h = Math.imul(i + 1, 2654435761) >>> 0; h ^= h >>> 15; h = Math.imul(h, 2246822519) >>> 0; h ^= h >>> 13; return (h >>> 0) / 4294967296; }
  function hmix(a) { a = (a ^ 0x9E3779B9) >>> 0; a = Math.imul(a ^ (a >>> 16), 0x85EBCA6B) >>> 0; a = Math.imul(a ^ (a >>> 13), 0xC2B2AE35) >>> 0; return (a ^ (a >>> 16)) >>> 0; }
  function u53(i) { var a = hmix((1 ^ hmix(i >>> 0)) >>> 0), b = hmix((a + 0x6D2B79F5 + i) >>> 0); return (a * 2097152 + (b >>> 11)) / 9007199254740992; }   // 53 random bits: a 32-bit fraction aliases at spans of 2^32 x p
  function sampOff(i, step, N, M) { var lo = Math.floor(step * i), hi = i === M - 1 ? N : Math.floor(step * (i + 1)); if (hi <= lo) hi = lo + 1; var off = lo + Math.floor(u53(i) * (hi - lo)); return off >= hi ? hi - 1 : off; }
  function sampleCap() { var R = S && S.geom ? Math.round(S.geom.R / 20) * 20 : 0; return R ? Math.max(1000, Math.min(20000, Math.round(Math.PI * R * R / (R < 260 ? 90 : 64)))) : 20000; }
  function sampleFor(N) { var cap = sampleCap(), key = N + '|' + cap + '|' + JSON.stringify(F); if (SAMPLE_KEY === key) return SAMPLE; var M = Math.min(cap, Math.max(1, Math.round(N))), out = new Float64Array(2 * M), step = N / M, rm = 0; for (var i = 0; i < M; i++) { var k = F.firstKey + (M >= N ? i : Math.min(N - 1, sampOff(i, step, N, M))), p = place(k); out[2 * i] = p.x; out[2 * i + 1] = p.y;   … [line shortened here: 541 characters; full line on GitHub]
  function drawBig(W, H, cx, cy, R, fs) { var B = S.big, N = B.N, smp = sampleFor(N), rim = smp.rim, f = ease(B.t), TOD = tod(); if (!B.view) { B.view = rim / 0.98; B.viewFrom = B.view; } var vNow = B.viewFrom + (B.view - B.viewFrom) * f, unit = R / vNow, rFrom = B.rimFrom > 0 ? B.rimFrom : rim, rNow = (rFrom + (rim - rFrom) * f) * unit, grow = rNow / R;
    g.strokeStyle = PAL.ring; g.lineWidth = 2; g.beginPath(); g.arc(cx, cy, rNow, 0, PI2); g.stroke();
    if (f < 1 && B.rimFrom > 0) { g.strokeStyle = PAL.amber; g.globalAlpha = 1 - f; g.lineWidth = 3; g.setLineDash([10, 8]); g.beginPath(); g.arc(cx, cy, rFrom * unit, 0, PI2); g.stroke(); g.setLineDash([]); if (!TOD) txt('WAS ' + fmt(B.nFrom || 0), cx, cy - rFrom * unit + fs * 0.9, PAL.amber, fs, 'center'); g.globalAlpha = 1; }
    
    rings(cx, cy, unit, rNow); S.rimNow = rim;
    var pts = smp.pts, brad = Math.max(2, Math.min(10, 0.3 * rNow * Math.sqrt(Math.PI / smp.M) / 1.77)) * (TOD ? 1.3 : 1), spr = sprite(PAL.cyan, brad), hf = spr.half, lim2 = (rNow + 3) * (rNow + 3), i, x, y; for (i = 0; i < smp.M; i++) { x = cx + pts[2 * i] * unit; y = cy - pts[2 * i + 1] * unit; if (isFinite(x) && (x - cx) * (x - cx) + (y - cy) * (y - cy) <= lim2) g.drawImage(spr.c, x - hf, y -   … [line shortened here: 422 characters; full line on GitHub]
    var rimLabel = (isReal() ? 'RIM = SQRT(N) = ' : 'RIM = ') + fmt(rim); 
    if (S.mag) { var m = S.mag, mr = Math.min(R * 0.42, 150); g.fillStyle = '#000'; g.beginPath(); g.arc(m.sx, m.sy, mr, 0, PI2); g.fill(); g.strokeStyle = PAL.amber; g.lineWidth = 3; g.stroke();
      var z = mr / m.win; for (var j = 0; j < m.pts.length; j += 2) { var px = m.sx + (m.pts[j] - m.wx) * z, py = m.sy - (m.pts[j + 1] - m.wy) * z; if (Math.hypot(px - m.sx, py - m.sy) < mr - 4) { g.fillStyle = PAL.cyan; g.beginPath(); g.arc(px, py, 4, 0, PI2); g.fill(); } }
      }
    if (S.bigSel) { var bs = S.bigSel, bx = cx + bs.x * unit, by = cy - bs.y * unit; if (isFinite(bx)) { selStar(bx, by, 6); if (true) { g.strokeStyle = PAL.amber; g.lineWidth = TOD ? 5 : 2; g.beginPath(); g.moveTo(cx, cy); g.lineTo(bx, by); g.stroke(); g.setLineDash([10, 10]); g.strokeStyle = PAL.cyan; g.lineWidth = 3; g.beginPath(); g.arc(cx, cy, Math.hypot(bx - cx, by - cy), 0, PI2); g.stroke()  … [line shortened here: 1,041 characters; full line on GitHub]
    drawRing(cx, cy, rNow);
    S.geom = { cx: cx, cy: cy, unit: unit, R: R }; }
  function magnify(x, y) { var ge = S.geom, N = S.big.N, wx = (x - ge.cx) / ge.unit, wy = -(y - ge.cy) / ge.unit, r0 = Math.hypot(wx, wy), win = 6; if (!isReal()) { S.mag = null; return; } if (r0 > Math.sqrt(N)) return;
    var kLo = Math.max(0, Math.floor(Math.pow(Math.max(0, r0 - win), 2))), kHi = Math.min(N, Math.ceil(Math.pow(r0 + win, 2))), pts = [], scanned = 0, LIM = 3000000;
    for (var k = kLo; k < kHi && scanned < LIM; k++, scanned++) { var p = placeReal(k); if (Math.abs(p.x - wx) <= win && Math.abs(p.y - wy) <= win) pts.push(p.x, p.y); }
    S.mag = { sx: x, sy: y, wx: wx, wy: wy, win: win, pts: pts, count: pts.length / 2, partial: scanned >= LIM }; S.work = 'MAGNIFIED: ' + fmt(pts.length / 2) + ' REAL KEYS IN A ' + (2 * win) + ' x ' + (2 * win) + ' WINDOW' + (scanned >= LIM ? ' (PART OF THE BAND SCANNED)' : '') + '. EACH KEY OWNS AN AREA OF PI AT EVERY SCALE.'; tone(r0 / 10); }
  // THE WONDER: one particle pulls back to a trillion, about 20 seconds, any tap skips
  var WONDER = [10, 100, 10000, 1000000, REAL_ISSUED, 1000000000000];
  function wonderStart() { menuClose(); S.wonder = { i: 0, t: 0 }; S.playing = false; S.sel = -1; S.probe = null; wonderStage(); }
  function wonderStage() { var w = S.wonder, N = WONDER[w.i]; S.intro = false; var vf = S.big && S.big.view ? S.big.view : S.scale, rf = S.big ? sampleFor(S.big.N).rim : S.scale / 1.1, nf = countNow(); S.big = { N: N, t: 0, rimFrom: rf, nFrom: nf, view: sampleFor(N).rim / 0.98, viewFrom: vf }; address(N); S.mag = null; S.cap = fmt(N) + ' KEYS' + (N === REAL_ISSUED ? ': TODAY\'S REAL KUIPER' : '');  … [line shortened here: 615 characters; full line on GitHub]
  function wonderStep(dt) { var w = S.wonder; w.t += dt; if (w.t > 3.2) { w.t = 0; w.i++; if (w.i >= WONDER.length) { if (w.i === WONDER.length) { S.big = null; S.cap = 'ALL OF THIS FROM ONE NUMBER AND ONE RULE. NOTHING STORED.'; S.work = 'TAP A DOT, DRAG IT, OR PRESS / FOR THE SENTENCES.'; S.sel = Math.min(1, S.keys.length - 1); return; } S.wonder = null; return; } wonderStage(); } }
  function wonderSkip() { if (!S.wonder) return; S.wonder = null; S.big = null; S.sel = Math.min(1, S.keys.length - 1); if (S.sel >= 0) { var q = S.keys[S.sel]; S.cap = 'KEY ' + fmt(q.key) + ':  ' + lineText(q); S.work = working(q, 1); } }
  // ---------- COLOURS: five palettes (background stays true black), and what the colour means ----------
  var PALETTES = { KUIPER: ['#00ffff', '#66ccff', '#ffb000', '#22ee77'], SUNSET: ['#ff8c42', '#ffd166', '#ff3d7f', '#ffe9c2'], OCEAN: ['#39c6ff', '#1f7aff', '#8af0ff', '#c8fff6'], RAINBOW: ['#ffffff', '#66ccff', '#ffb000', '#22ee77'], NEON: ['#39ff14', '#ff00e6', '#fff200', '#00e5ff'] };
  var BANDS = { SUNSET: [340, 80], OCEAN: [170, 90], NEON: [0, 360] }, PAL_NAMES = Object.keys(PALETTES), BYS = ['group', 'age', 'turn'], BY_NAME = { group: 'DUPLICATE GROUP', age: 'AGE (OLD TO NEW)', turn: 'TURN (0 TO 360)' };
  function hex(c) { c = c.replace('#', ''); return [parseInt(c.slice(0, 2), 16), parseInt(c.slice(2, 4), 16), parseInt(c.slice(4, 6), 16)]; }
  function mix(a, b, t) { var A = hex(a), B = hex(b); return 'rgb(' + Math.round(A[0] + (B[0] - A[0]) * t) + ',' + Math.round(A[1] + (B[1] - A[1]) * t) + ',' + Math.round(A[2] + (B[2] - A[2]) * t) + ')'; }
  function dotColour(p, i, n) { var pal = PALETTES[PREF.pal] || PALETTES.KUIPER;
    if (PREF.by === 'age') return mix(pal[1], pal[2], n > 1 ? i / (n - 1) : 1);
    if (PREF.by === 'turn') return 'hsl(' + Math.round(p.deg || 0) + ',95%,62%)';
    if (PREF.pal === 'RAINBOW') return 'hsl(' + Math.round(360 * i / Math.max(1, n)) + ',95%,62%)';
    if (PREF.pal === 'KUIPER') return S && S.dup ? hue(p.text) : PAL.cyan;   // V5: every star cyan (the zoom look, and no colour jump at 300 keys); DUPLICATES lights the repeats in their own colours
    var h = 0, s = p.text || ''; for (var j = 0; j < s.length; j++) h = (h * 31 + s.charCodeAt(j)) >>> 0; var b = BANDS[PREF.pal] || [0, 360]; return 'hsl(' + ((b[0] + h % b[1]) % 360) + ',100%,60%)'; }
  function applyPalette() { var pal = PALETTES[PREF.pal] || PALETTES.KUIPER; PAL.cyan = pal[0]; PAL.amber = pal[2]; PAL.green = pal[3]; PAL.ink = '#fff'; if (UI) { UI.root.style.setProperty('--c', PAL.cyan); UI.coloursBtn.textContent = PREF.pal === 'KUIPER' ? 'COLOURS' : PREF.pal; } }

  // ---------- LEVERS, ONE AT A TIME: start with PLAY and the particle, each press reveals the next ----------
  // HOW MANY DOTS and TURN EACH TIME are on the sheet from the start (the two levers); these come one at a time:
  var LEVERS = [
    ['SPREAD', 'HOW IT SPREADS OUT', 'HOW IT SPREADS OUT: SQUARE ROOT, STRAIGHT, OR CUBE ROOT. PRESS THE BUTTON TO TRY EACH.', 'THE SQUARE ROOT GIVES EVERY KEY THE SAME AREA (PI), CENTRE TO RIM.'],
    ['SHADOWS', 'X/Y SHADOWS', 'X/Y SHADOWS: THE DOT CASTS A SHADOW ON THE FLOOR (X) AND ON THE WALL (Y).', 'X = DISTANCE x COS(TURN).   Y = DISTANCE x SIN(TURN).   EXCEL DRAWS THE DOT FROM THOSE TWO.'],
    ['QUIET', 'QUIET TIME', 'QUIET TIME: WHEN NO CODE ARRIVES, 600 KEYS A SECOND PASS EMPTY AND LEAVE A DARK RING.', 'THE LONGEST QUIET COUNTED IS 14 DAYS. PRESS QUIET TIME TO TAKE A NIGHT OFF.'],
    ['REAL', 'REAL KUIPER', 'REAL KUIPER: 222.49 DEGREES PER KEY, DISTANCE = SQUARE ROOT OF (KEY + 0.5), FROM KEY 0.', 'EVERYTHING IS OPEN NOW: THE FIELDS, THE SHAPES, EVERY SENTENCE. PRESS / TO SEE THEM ALL.']
  ];
  var NEED = { NIGHT: 3, SHAPE: 4, FIELD: 4, REAL: 4, FIELDS: 4, MEASURE: 4, EXCEL: 4, CHECK: 4, SPREAD: 1, SHADOWS: 2, COLOURBY: 4 };
  var TIP = 'CLICK THE CIRCLE TO SEE AN ANGLE. PRESS x10 TO GROW IT.   0 IS AT 3 O\'CLOCK. ANGLES TURN ANTICLOCKWISE.';
  function countNow() { return S.big ? S.big.N : Math.max(1, S.keys.length + (S.anim ? 1 : 0)); }
  // HOW MANY DOTS by clicks: up to 300 the real lines of code stay on the sheet (drag them); above that, the sampled disc
  function setCount(N) { S.intro = false; N = Math.round(N); if (!(N >= 1)) N = 1; var tooBig = N > MAXN; if (tooBig) N = MAXN; S.playing = false; S.anim = null; S.sel = -1; S.probe = null; S.mag = null; S.bigSel = null;
    if (N > LINES.length) { run('HOWMANY ' + N); if (tooBig) tooLarge(MAXN); return; }
    S.big = null; S.i = 0; S.key = F.firstKey; S.keys = []; S.counts = {}; S.file = ''; S.done = false; S.nightCap = 0; var was = S.speed; S.speed = 99; while (S.keys.length < N && S.i < LINES.length) { startNext(); if (S.anim) { S.keys.push(S.anim.p); S.counts[S.anim.p.text] = (S.counts[S.anim.p.text] || 0) + 1; S.anim = null; } } S.speed = was;
    var rm = 1.6; for (var i = 0; i < S.keys.length; i++) if (Math.abs(S.keys[i].r) > rm) rm = Math.abs(S.keys[i].r); S.scaleTarget = rm * 1.1; S.flash = 0.6; address(N);
    S.cap = fmt(N) + (N === 1 ? ' DOT: KEY ' + fmt(F.firstKey) : ' DOTS: KEYS ' + fmt(F.firstKey) + ' TO ' + fmt(F.firstKey + N - 1)) + '. RIM ' + f2(rm) + ' = SQUARE ROOT OF ' + fmt(N) + '.' + (N < 20 ? ' PRESS +1 TO ADD THE NEXT KEY.' : ' PRESS x10 TO GROW IT.'); S.work = 'THE AREA PER KEY NEVER CHANGES: PI AT EVERY SCALE. THE CIRCLE GROWS LIKE THE SQUARE ROOT OF THE COUNT.'; whoosh(N); if (UI)   … [line shortened here: 448 characters; full line on GitHub]
  function turnTo(d) { S.intro = false; if (d === null) { F.degrees = null; } else { d = Math.round(d * 1000) / 1000; F.degrees = d; } afterFields(); var dp = degPerKey(); S.cap = 'TURN EACH TIME: ' + f2(dp) + ' DEGREES.' + (isReal() ? ' THE REAL KUIPER.' : mod(dp, 360) === 90 ? ' 4 SPOKES: EVERY 4TH KEY LANDS ON THE SAME LINE.' : mod(dp, 360) === 120 ? ' 3 SPOKES.' : Math.abs(dp - 137.507764) < 0  … [line shortened here: 713 characters; full line on GitHub]
  function allowed(cmd) { var c = String(cmd).replace(/^\s*NIGHT\s+OFF/i, 'NIGHT').match(/^[A-Za-z]+/); if (!c) return true; var n = NEED[c[0].toUpperCase()]; return n == null || PREF.lv >= n; }
  function levelOf(name) { for (var i = 0; i < LEVERS.length; i++) if (LEVERS[i][0] === name) return i + 1; return 0; }
  function applyLevel() { if (!UI) return; var lv = PREF.lv; for (var name in UI.lever) { var need = levelOf(name); UI.lever[name].forEach(function (e) { e.style.display = lv >= need ? '' : 'none'; }); } UI.nextBtn.style.display = lv >= LEVERS.length ? 'none' : ''; }
  function nextLever() { if (PREF.lv >= LEVERS.length) return; var L = LEVERS[PREF.lv]; PREF.lv++; savePref(); applyLevel(); S.big = null; S.cap = L[2]; S.work = L[3]; logLine('LEVER ' + PREF.lv + ' OF ' + LEVERS.length + ': ' + L[1]); tone(PREF.lv * 3); if (L[0] === 'SHADOWS') { S.shadows = true; if (S.sel < 0 && S.keys.length) S.sel = S.keys.length - 1; } if (L[0] === 'REAL') applyFields(null);   … [line shortened here: 401 characters; full line on GitHub]
  function showEverything() { PREF.lv = LEVERS.length; savePref(); applyLevel(); S.cap = 'EVERYTHING IS OPEN: EVERY LEVER, EVERY FIELD, EVERY SHAPE.'; S.work = 'PRESS / FOR THE SENTENCES. FIELDS SHOWS EVERY NUMBER OF THE LAW.'; }
  var SPREADS = [[0.5, 'SQUARE ROOT'], [1, 'STRAIGHT (DISTANCE = KEY)'], [1 / 3, 'CUBE ROOT']];
  function spreadNext() { var i = 0; for (var j = 0; j < SPREADS.length; j++) if (Math.abs(F.power - SPREADS[j][0]) < 1e-9) i = (j + 1) % SPREADS.length; F.power = SPREADS[i][0]; afterFields(); S.cap = 'HOW IT SPREADS OUT: ' + SPREADS[i][1] + '.'; S.work = 'DISTANCE = (KEY + ' + F.offset + ')' + (F.power === 0.5 ? ' SQUARE ROOTED' : F.power === 1 ? '' : ' CUBE ROOTED') + (isReal() ? '. THE REAL KU  … [line shortened here: 474 characters; full line on GitHub]

  // ---------- FADING HINTS: one line about what you just did, never a question ----------
  var HINTS = [
    ['play', 'EVERY LINE OF CODE GETS THE NEXT KEY. THE KEY ALONE SAYS WHERE IT LANDS.'], ['play', 'THE DOTS NEVER COLLIDE. EACH KEY HAS ITS OWN DISTANCE.'],
    ['step', 'ONE KEY, ONE DOT, A LITTLE FURTHER OUT THAN THE LAST.'], ['step', 'THE HAND TURNS 222.49 DEGREES EACH TIME. FULL LAPS ARE THROWN AWAY.'],
    ['tap', 'TAP A DOT AND ITS LINE OF CODE COMES BACK. NOTHING WAS STORED TO FIND IT.'], ['drag', 'DRAG IT ANYWHERE. REAL KUIPER PUTS IT BACK WHERE THE RULE SAYS.'], ['drag', 'DISTANCE AND TURN ARE THE WHOLE ADDRESS.'],
    ['free', 'YOUR DOT HAS A DISTANCE AND AN ANGLE TOO. THE NEAREST KEY IS NAMED.'], ['turn', 'TURN 90 MAKES 4 SPOKES. TURN 120 MAKES 3. TRY 137.5 FOR THE MIRROR SPIRAL.'], ['turn', 'THROWING AWAY FULL LAPS IS CALLED MOD. A CLOCK DOES IT EVERY 12 HOURS.'],
    ['spread', 'THE SQUARE ROOT GIVES EVERY KEY THE SAME AREA, CENTRE TO RIM.'], ['spread', 'STRAIGHT (DISTANCE = KEY) CROWDS THE CENTRE AND THINS THE RIM.'],
    ['howmany', 'TEN TIMES THE DOTS MAKES THE CIRCLE ONLY 3.16 TIMES WIDER.'], ['howmany', 'A TRILLION DOTS AND STILL ONE RULE. TAP THE DISC TO MAGNIFY.'],
    ['shadows', 'X IS THE FLOOR SHADOW, Y IS THE WALL SHADOW. EXCEL DRAWS THE DOT FROM THOSE TWO.'], ['quiet', 'A NIGHT WITH NO CODE LEAVES A DARK RING. THE KEYS STILL PASSED.'], ['quiet', 'SKIPPED KEYS ARE NEVER REUSED. TIME IS WRITTEN INTO THE CIRCLE.'],
    ['real', 'THE REAL KUIPER TODAY HOLDS 43.5 BILLION KEYS. TRY HOW MANY 43486619138.'], ['colours', 'THE COLOURS CHANGE. THE PLACES NEVER DO.'], ['music', 'EVERY NOTE FOLLOWS A DISTANCE. THE RULE SINGS.'],
    ['faster', 'AT FULL SPEED THE SUNFLOWER APPEARS. THE RULE WAS THERE ALL ALONG.'], ['lever', 'EACH LEVER IS ONE NUMBER OF THE SAME RULE. NOTHING ELSE CHANGES.']
  ];
  var HINT = { at: 0, last: '', seen: {}, timer: null };
  function hint(tagOrText, force) { var now = performance.now(); if (!force && now - HINT.at < 20000) return; var text = tagOrText;
    if (!force) { var pool = HINTS.filter(function (h) { return h[0] === tagOrText && h[1] !== HINT.last; }); if (!pool.length) return; var fresh = pool.filter(function (h) { return !HINT.seen[h[1]]; }); text = (fresh.length ? fresh : pool)[0][1]; HINT.seen[text] = true; PREF.seenHints = Object.keys(HINT.seen).slice(-40); savePref(); }
    if (text === HINT.last && !force) return; HINT.at = now; HINT.last = text; HINT.until = now + 6000; if (!UI) return; var h = UI.hint; h.textContent = text; h.classList.remove('fade'); h.classList.add('show'); if (HINT.timer) clearTimeout(HINT.timer); HINT.timer = setTimeout(function () { h.classList.remove('show'); h.classList.add('fade'); }, 2500); }

  // ---------- MUSIC: three moods and mute; nothing sounds before the first tap ----------
  var MUS = { timer: null, i: 0, period: 0 }; var NOTES = [262, 330, 392, 523, 392, 330], MOODS = ['CALM', 'ARCADE', 'PIANO', 'MUTE'];
  function ac() { if (!AC) AC = new (window.AudioContext || window.webkitAudioContext)(); return AC; }
  function musicTick() { if (!S || PREF.muted || !gestured || PREF.mood === 'MUTE') return; try { ac(); var t = AC.currentTime, o = AC.createOscillator(), gn = AC.createGain(), mood = PREF.mood;
      if (mood === 'CALM') { o.type = 'triangle'; o.frequency.value = NOTES[MUS.i++ % NOTES.length] / 2; gn.gain.setValueAtTime(0.0001, t); gn.gain.exponentialRampToValueAtTime(0.03, t + 0.7); gn.gain.exponentialRampToValueAtTime(0.0001, t + 1.9); o.stop(t + 2); }
      else if (mood === 'ARCADE') { o.type = 'square'; o.frequency.value = NOTES[(MUS.i++ * 2) % NOTES.length]; gn.gain.setValueAtTime(0.018, t); gn.gain.exponentialRampToValueAtTime(0.0001, t + 0.12); o.stop(t + 0.13); }
      else { var last = S.keys.length ? S.keys[S.keys.length - 1] : null, r = last ? Math.abs(last.r) : 1, scale = [0, 2, 4, 7, 9, 12, 14, 16], nn = scale[Math.floor(r) % scale.length] + 12 * (Math.floor(r / 8) % 2); o.type = 'sine'; o.frequency.value = 262 * Math.pow(2, nn / 12); gn.gain.setValueAtTime(0.05, t); gn.gain.exponentialRampToValueAtTime(0.0001, t + 0.9); o.stop(t + 0.95); }
      o.connect(gn); gn.connect(AC.destination); o.start(t); } catch (e) {} }
  function musicSync() { var on = gestured && S && !MOD && !PREF.muted && PREF.mood !== 'MUTE', period = PREF.mood === 'ARCADE' ? 250 : PREF.mood === 'PIANO' ? 700 : 2000;
    if (on) { if (!MUS.timer || MUS.period !== period) { if (MUS.timer) clearInterval(MUS.timer); MUS.period = period; MUS.timer = setInterval(musicTick, period); } } else if (MUS.timer) { clearInterval(MUS.timer); MUS.timer = null; } }
  function whoosh(N) { if (!gestured || PREF.muted) return; try { ac(); var t = AC.currentTime, o = AC.createOscillator(), gn = AC.createGain(), top = 200 + Math.min(1800, Math.log10(Math.max(1, N)) * 110); o.type = 'sawtooth'; o.frequency.setValueAtTime(120, t); o.frequency.exponentialRampToValueAtTime(top, t + 0.7); gn.gain.setValueAtTime(0.0001, t); gn.gain.exponentialRampToValueAtTime(0.035, t  … [line shortened here: 554 characters; full line on GitHub]
  function swell() { if (!gestured || PREF.muted) return; try { ac(); var t = AC.currentTime; [262, 330, 392, 523].forEach(function (fq, i) { var o = AC.createOscillator(), gn = AC.createGain(); o.type = 'sine'; o.frequency.value = fq; gn.gain.setValueAtTime(0.0001, t); gn.gain.exponentialRampToValueAtTime(0.05, t + 0.8 + i * 0.1); gn.gain.exponentialRampToValueAtTime(0.0001, t + 3.5); o.connect(g  … [line shortened here: 481 characters; full line on GitHub]

  // ---------- SCALE LOGIC plug-in (scale-logic.js, window.KuiperScale) for picking a key at any scale ----------
  function scaleParams() { return { first: F.firstKey, count: S.big ? S.big.N : Math.max(1, S.key), turnNumber: F.turnNumber, wrap: F.wrapSize, degreesPerKey: F.degrees, power: F.power, offset: F.offset, skipPerSecond: F.skipPerSec, capSeconds: F.capSec }; }
  function pickAt(wx, wy) { var KS = root.KuiperScale; if (KS && KS.pick) { try { var hit = KS.pick(scaleParams(), wx, wy, { zoom: S.geom ? S.geom.unit : 1 }); if (hit && hit.place) { var pl = hit.place; return { key: hit.key, x: pl.x, y: pl.y, r: pl.r != null ? pl.r : Math.hypot(pl.x, pl.y), deg: pl.deg != null ? pl.deg : mod(Math.atan2(pl.y, pl.x) * 180 / Math.PI, 360), away: hit.distance }; } }  … [line shortened here: 415 characters; full line on GitHub]
    if (!isReal()) return null; var r0 = Math.hypot(wx, wy), N = S.big ? S.big.N : S.key, kLo = Math.max(0, Math.floor(Math.pow(Math.max(0, r0 - 2), 2))), kHi = Math.min(N, Math.ceil(Math.pow(r0 + 2, 2))), best = null, bd = 1e18; for (var k = kLo; k < kHi && k < kLo + 400000; k++) { var p = placeReal(k), d = Math.hypot(p.x - wx, p.y - wy); if (d < bd) { bd = d; best = p; } } return best ? { key: b  … [line shortened here: 477 characters; full line on GitHub]
  function moveSelected(how, a, b) { var o = S.sel >= 0 ? S.keys[S.sel] : null; if (!o) throw new Error('TAP A DOT FIRST'); if (o.trueX == null) { o.trueX = o.x; o.trueY = o.y; }
    if (how === 'xy') { o.x = a; o.y = b; o.r = Math.hypot(a, b); o.deg = mod(Math.atan2(b, a) * 180 / Math.PI, 360); } else { o.r = a; o.deg = mod(b, 360); var th = o.deg * Math.PI / 180; o.x = o.r * Math.cos(th); o.y = o.r * Math.sin(th); }
    o.moved = true; var KS = root.KuiperScale; if (KS && KS.setPosition) { try { KS.setPosition(o.key, o.x, o.y); } catch (e) {} } S.scaleTarget = Math.max(S.scaleTarget, Math.abs(o.r) * 1.1);
    S.cap = 'KEY ' + fmt(o.key) + ' MOVED BY HAND TO X ' + f2(o.x) + ', Y ' + f2(o.y) + ' (DISTANCE ' + f2(o.r) + ', TURN ' + f1(o.deg) + ').'; S.work = 'ITS TRUE PLACE IS MARKED. REAL KUIPER PUTS IT BACK.'; tone(o.r); if (UI) moveRefresh(); }
  function moveRefresh() { if (!UI || !UI.mv) return; var o = S.sel >= 0 ? S.keys[S.sel] : null; ['x', 'y', 'r', 'deg'].forEach(function (k) { var inp = UI.mv[k]; if (inp && document.activeElement !== inp) inp.value = o ? f2(o[k]) : ''; }); if (UI.mvKey) UI.mvKey.textContent = o ? 'MOVE KEY ' + fmt(o.key) + ' BY TYPING' : 'TAP A DOT, THEN MOVE IT BY TYPING'; }
  // the retro tones (square wave, like the engine's bleep): pitch follows distance, soft, only after a gesture, mutable
  var AC = null, gestured = false; function tone(r) { if (!gestured || PREF.muted || S.speed >= 12) return; try { if (!AC) AC = new (window.AudioContext || window.webkitAudioContext)(); var o = AC.createOscillator(), gn = AC.createGain(); o.type = 'square'; o.frequency.value = 330 + Math.min(1200, Math.max(0, Math.abs(r) * 40)); gn.gain.value = 0.03; gn.gain.exponentialRampToValueAtTime(0.0001, AC  … [line shortened here: 523 characters; full line on GitHub]

  // ---------- sentences and commands: one list, one page ----------
  var SENTENCES = [
    ['Show everything: every lever, field and shape at once', 'EVERYTHING'], ['Next lever', 'NEXT'],
    ['Place the next line of code', 'STEP'], ['Play: place every line of Kuiper\'s own code', 'PLAY'], ['Pause', 'PAUSE'], ['Speed up', 'FASTER'], ['Slow down', 'SLOWER'],
    ['How it spreads out: square root, straight, cube root', 'SPREAD'], ['X/Y shadows on the chosen dot', 'SHADOWS'], ['Colours: the next palette', 'COLOURS'], ['Colour by age, by turn, or by duplicate group', 'COLOURBY'], ['Music: the next mood (calm, arcade, piano, mute)', 'MUSIC'],
    ['Move the chosen dot to X 2 Y 3', 'MOVE XY 2 3'], ['Move the chosen dot to distance 4 angle 45', 'MOVE POLAR 4 45'],
    ['Show me the wonder', 'WONDER'], ['Go to key 12 and show how it was placed', 'KEY 12'], ['Show every repeated line in the same colour', 'DUPLICATES'], ['Take a night off: skip keys and leave a dark ring', 'NIGHT OFF'],
    ['Turn key 1 to 90 degrees', 'TURN 1 TO 90'], ['Put a dot at distance 3 and angle 45', 'DOT 3 45'],
    ['Shape: SUNFLOWER (the real Kuiper)', 'SHAPE SUNFLOWER'], ['Shape: 4 SPOKES (turn 90)', 'SHAPE 4 SPOKES'], ['Shape: 3 SPOKES (turn 120)', 'SHAPE 3 SPOKES'], ['Shape: 5 SPOKES (turn 72)', 'SHAPE 5 SPOKES'], ['Shape: SPIRAL ARMS (turn 91)', 'SHAPE SPIRAL ARMS'], ['Shape: CROWDED CENTRE (distance = key)', 'SHAPE CROWDED CENTRE'], ['Shape: DARK RINGS (rest an hour every 40 lines)', 'SHAPE DARK RI  … [line shortened here: 406 characters; full line on GitHub]
    ['Set the turn per key to 137.5 (the mirror of the real one)', 'FIELD degrees 137.507764'], ['Try turn 360', 'FIELD degrees 360'], ['Try turn 0', 'FIELD degrees 0'], ['Try wrap size 7', 'FIELD wrapSize 7'], ['Try power 3', 'FIELD power 3'], ['Try offset -1000', 'FIELD offset -1000'],
    ['Show the circle with 100 dots', 'HOWMANY 100'], ['Show the circle with 1 million dots', 'HOWMANY 1000000'], ['Show the circle with 43.5 billion dots (today\'s real Kuiper)', 'HOWMANY 43486619138'], ['Show the circle with 1 trillion dots', 'HOWMANY 1000000000000'], ['Try 9 quadrillion keys (2^53, the exact-number limit)', 'HOWMANY 9007199254740992'], ['Try a century of quiet time', 'FIELD res  … [line shortened here: 418 characters; full line on GitHub]
    ['Back to the lines of code', 'LINES'], ['Real Kuiper: every field back to the true law', 'REAL'], ['Show the fields (every number of the law)', 'FIELDS'], ['Measure this against the real Kuiper code', 'MEASURE'],
    ['Show the five Excel columns', 'EXCEL'], ['How do I find this key in the real Kuiper?', 'CHECK 1'], ['Bigger text', 'BIGGER'], ['Smaller text', 'SMALLER'], ['Mute or unmute the tones', 'MUTE'], ['Start again from the first key', 'RESTART'], ['Help', 'HELP']
  ];
  var SHAPES = { 'SUNFLOWER': null, '4 SPOKES': { degrees: 90 }, '3 SPOKES': { degrees: 120 }, '5 SPOKES': { degrees: 72 }, 'SPIRAL ARMS': { degrees: 91 }, 'CROWDED CENTRE': { power: 1, offset: 0 }, 'DARK RINGS': { burstLines: 40, restSec: 3600 } };
  function applyFields(ch) { setReal(); if (ch) for (var k in ch) F[k] = ch[k]; afterFields(); }
  function afterFields() { if (S.big) { S.big = { N: S.big.N, t: 1, view: S.big.view, viewFrom: S.big.view }; S.mag = null; S.bigSel = null; } reflow(); if (UI) fieldsRefresh(); S.cap = isReal() ? 'THE REAL KUIPER.' : 'PRACTICE: ' + (limitLine() || 'YOUR OWN SHAPE'); S.work = S.sel >= 0 && S.keys[S.sel] ? working(S.keys[S.sel], 1) : plainWords(); tone(3); }
  function measure() { var N = S.big ? Math.min(S.big.N, 1000000) : 1000000, L = root.KuiperLaw; if (!L) return 'KUIPER-LAW.JS IS NOT LOADED: NOTHING TO MEASURE AGAINST';
    if (!isReal()) { var a = place(1), b = L.place(1); return 'YOUR FIELDS: NOT THE REAL KUIPER. KEY 1 SITS ' + f2(Math.hypot(a.x - b.x, a.y - b.y)) + ' AWAY FROM THE REAL KEY 1.'; }
    var diff = 0, t0 = Date.now(); for (var k = 0; k < N; k++) { var e = L.keyPlace(k), p = place(k); if (e[0] !== p.x || e[1] !== p.y) diff++; } return 'CHECKED ' + fmt(N) + ' KEYS AGAINST THE LIVE keyPlace: ' + diff + ' DIFFERENCES (' + (Date.now() - t0) + ' MS)'; }
  function run(sentence) {
    var raw = String(sentence || '').trim(); if (!raw) return; var s = raw; var up = s.toUpperCase();
    for (var i = 0; i < SENTENCES.length; i++) if (SENTENCES[i][0].toUpperCase() === up) { s = SENTENCES[i][1]; break; }
    s = s.replace(/^\s*HOW\s+MANY/i, 'HOWMANY').replace(/^\s*NIGHT\s+OFF/i, 'NIGHT'); var m = s.match(/^([A-Za-z]+)\s*(.*)$/); if (!m) return; var c = m[1].toUpperCase(), rest = m[2].trim(), nums = rest.replace(/,/g, '').match(/-?\d+(\.\d+)?(e[+-]?\d+)?/gi) || [];
    wonderSkip(); bloomSkip(); S.intro = false; logLine('> ' + s); var out = '';
    try {
      if (c === 'PLAY') { if (S.done) reset(); S.sel = -1; S.probe = null; S.big = null; S.playing = true; out = 'PLAYING: ' + speedLabel(); hint('play'); }
      else if (c === 'PAUSE') { S.playing = false; out = 'PAUSED AT KEY ' + fmt(S.key - 1); }
      else if (c === 'STEP') { S.big = null; step(); out = 'ONE LINE'; hint('step'); }
      else if (c === 'FASTER') { faster(1); out = speedLabel(); hint('faster'); } else if (c === 'SLOWER') { faster(-1); out = speedLabel(); }
      else if (c === 'NEXT') { nextLever(); out = PREF.lv >= LEVERS.length ? 'EVERY LEVER IS OPEN' : 'LEVER ' + PREF.lv + ' OF ' + LEVERS.length; hint('lever'); }
      else if (c === 'EVERYTHING') { showEverything(); out = 'EVERYTHING IS OPEN'; }
      else if (c === 'SPREAD') { S.big = null; out = 'HOW IT SPREADS OUT: ' + spreadNext(); hint('spread'); }
      else if (c === 'SHADOWS') { S.shadows = !S.shadows; S.big = null; if (S.shadows && S.sel < 0 && S.keys.length) S.sel = S.keys.length - 1; var shp = S.sel >= 0 ? S.keys[S.sel] : null; out = S.shadows ? 'X/Y SHADOWS ON' : 'X/Y SHADOWS OFF'; S.cap = S.shadows && shp ? 'KEY ' + fmt(shp.key) + ': FLOOR SHADOW X ' + f2(shp.x) + ', WALL SHADOW Y ' + f2(shp.y) + '.' : out; if (S.shadows && shp) S.wo  … [line shortened here: 562 characters; full line on GitHub]
      else if (c === 'COLOURS' || c === 'COLOUR' || c === 'PALETTE') { var want = rest.toUpperCase().trim(); PREF.pal = PALETTES[want] ? want : PAL_NAMES[(PAL_NAMES.indexOf(PREF.pal) + 1) % PAL_NAMES.length]; applyPalette(); savePref(); out = 'COLOURS: ' + PREF.pal; hint('colours'); }
      else if (c === 'COLOURBY') { var wb = rest.toLowerCase().trim(); PREF.by = BYS.indexOf(wb) >= 0 ? wb : BYS[(BYS.indexOf(PREF.by) + 1) % BYS.length]; savePref(); out = 'COLOUR BY ' + BY_NAME[PREF.by]; S.cap = out + '.'; S.work = PREF.by === 'group' ? 'LINES THAT REPEAT SHARE A COLOUR: THEY ARE THE SAME TEXT WITH DIFFERENT KEYS.' : PREF.by === 'age' ? 'OLD KEYS NEAR THE CENTRE, NEW KEYS AT THE  … [line shortened here: 471 characters; full line on GitHub]
      else if (c === 'MUSIC' || c === 'MOOD') { var wm = rest.toUpperCase().trim(); PREF.mood = MOODS.indexOf(wm) >= 0 ? wm : MOODS[(MOODS.indexOf(PREF.mood) + 1) % MOODS.length]; savePref(); musicSync(); UI.musicBtn.textContent = 'MUSIC: ' + PREF.mood; out = 'MUSIC: ' + PREF.mood; hint('music'); }
      else if (c === 'MOVE') { var mv = rest.toUpperCase().match(/^(XY|POLAR)\s+(-?[\d.,e+-]+)\s+(-?[\d.,e+-]+)/i); if (!mv) throw new Error('MOVE XY x y, OR MOVE POLAR distance angle'); var ma = parseFloat(mv[2].replace(/,/g, '')), mb = parseFloat(mv[3].replace(/,/g, '')); if (!isFinite(ma) || !isFinite(mb)) throw new Error('THOSE ARE NOT NUMBERS'); S.big = null; moveSelected(mv[1].toUpperCase()   … [line shortened here: 464 characters; full line on GitHub]
      else if (c === 'WONDER') { wonderStart(); out = 'WATCH. ANY TAP SKIPS.'; }
      else if (c === 'KEY' && nums.length) { var n = parseInt(nums[0], 10); S.big = null; S.playing = false; S.anim = null; S.probe = null; var idx = -1, j; for (j = 0; j < S.keys.length; j++) if (S.keys[j].key === n) idx = j;
        if (idx < 0) { while (S.i < LINES.length && S.key <= n) { startNext(); land(S.anim.p); S.anim = null; } for (j = 0; j < S.keys.length; j++) if (S.keys[j].key === n) idx = j; }
        if (idx >= 0) { S.sel = idx; var q = S.keys[idx]; S.cap = 'KEY ' + fmt(n) + ':  ' + lineText(q); S.work = working(q, 1); out = working(q, 1); }
        else { var pp = place(n); pp.text = '(NO LINE OF CODE HAS THIS KEY: AN EMPTY ADDRESS)'; S.probe = pp; S.scaleTarget = Math.max(S.scaleTarget, Math.abs(pp.r) * 1.1); S.cap = 'KEY ' + fmt(n) + ': ' + pp.text; S.work = working(pp, 1); out = working(pp, 1); } }
      else if (c === 'NIGHT') { S.big = null; var skip = Math.round(Math.min(F.restSec || 3600, F.capSec) * F.skipPerSec); S.key += skip; S.nightCap = skip; S.restSec = F.restSec || 3600; S.playing = false; S.sel = -1; startNext(); out = fmt(skip) + ' KEYS SKIPPED'; }
      else if (c === 'DUPLICATES' || c === 'DUP') { S.dup = !S.dup; S.big = null; S.cap = S.dup ? 'LINES THAT REPEAT ARE LIT. KUIPER COUNTS EVERY LINE, EVEN REPEATS: EACH GETS ITS OWN KEY.' : 'ALL LINES SHOWN.'; var reps = 0; for (var t in S.counts) if (S.counts[t] > 1) reps++; out = reps + ' LINES REPEAT'; }
      else if (c === 'TURN' && /^BY\s+SET/i.test(rest)) { if (!nums.length || isNaN(parseFloat(nums[0]))) throw new Error('THAT IS NOT A NUMBER'); var tv = parseFloat(nums[0]), tbT = !isFinite(tv) || Math.abs(tv) > MAXN; if (tbT) tv = (tv < 0 ? -1 : 1) * MAXN; turnTo(tv); out = tbT ? tooLarge(MAXN) : S.cap; }
      else if (c === 'TURN' && nums.length >= 2) { var kk = parseInt(nums[0], 10), dg = parseFloat(nums[1]), ix = -1; for (j = 0; j < S.keys.length; j++) if (S.keys[j].key === kk) ix = j; if (ix < 0) throw new Error('KEY ' + kk + ' IS NOT PLACED YET');
        var o = S.keys[ix], th = dg * Math.PI / 180; o.deg = mod(dg, 360); o.x = o.r * Math.cos(th); o.y = o.r * Math.sin(th); o.moved = true; S.sel = ix; S.big = null; S.cap = 'KEY ' + fmt(kk) + ' TURNED TO ' + f1(dg) + ' BY HAND. DRAG IT TOO.'; S.work = working(o, 1); out = 'MOVED'; tone(o.r); }
      else if (c === 'DOT' && nums.length >= 2) { S.big = null; S.sel = -1; probeAt(parseFloat(nums[0]), parseFloat(nums[1])); out = S.work; }
      else if (c === 'SHAPE') { var nm = rest.toUpperCase(); if (!(nm in SHAPES)) throw new Error('SHAPES: ' + Object.keys(SHAPES).join(', ')); applyFields(SHAPES[nm]); out = nm; }
      else if (c === 'FIELD') { var fm = rest.match(/^(\w+)\s+(.+)$/); if (!fm) throw new Error('FIELD name value'); var name = fm[1]; var ok = false; FIELDS.forEach(function (f) { if (f[0].toLowerCase() === name.toLowerCase()) { name = f[0]; ok = true; } }); if (!ok) throw new Error('FIELDS: ' + FIELDS.map(function (f) { return f[0]; }).join(', '));
        var v = fm[2].trim().toUpperCase() === 'REAL' || fm[2].trim() === '' ? REAL[name] : parseFloat(fm[2].replace(/,/g, '')); var flim = name === 'firstKey' ? MAXN - 200050 : MAXN, tbF = v !== null && !isNaN(v) && (!isFinite(v) || Math.abs(v) > flim); if (tbF) v = (v < 0 ? -1 : 1) * flim; if (fm[2].trim().toUpperCase() !== 'REAL' && !isFinite(v)) throw new Error('THAT IS NOT A NUMBER'); if (nam  … [line shortened here: 811 characters; full line on GitHub]
      else if (c === 'REAL' || c === 'RESET') { applyFields(null); for (j = 0; j < S.keys.length; j++) if (S.keys[j].moved) { var rp = place(S.keys[j].key); rp.text = S.keys[j].text; rp.file = S.keys[j].file; S.keys[j] = rp; } S.probe = null; S.bigSel = null; if (root.KuiperScale && root.KuiperScale.clearMoves) { try { root.KuiperScale.clearMoves(); } catch (e0) {} } moveRefresh(); out = 'THE REAL  … [line shortened here: 532 characters; full line on GitHub]
      else if (c === 'HOWMANY' || c === 'SCALE' || c === 'COUNT') { var N = /^[-+]?inf/i.test(rest) ? Infinity : parseFloat((nums[0] || '100').replace(/,/g, '')); if (!(N >= 1)) N = 1; var tooBigN = N > MAXN; if (tooBigN) N = MAXN; S.playing = false; var rimFrom = S.big ? sampleFor(S.big.N).rim : S.scale / 1.1, nFrom = S.big ? S.big.N : S.keys.length, viewFrom = S.big && S.big.view ? S.big.view :   … [line shortened here: 646 characters; full line on GitHub]
        S.cap = fmt(N) + ' DOTS: KEYS ' + fmt(F.firstKey) + ' TO ' + fmt(F.firstKey + N - 1) + '. RIM ' + fmt(rim) + '.' + (N > sampleFor(N).M ? ' SHOWING ' + fmt(sampleFor(N).M) + ' OF THEM.' : '') + (N === MAXN ? ' THE LIMIT FOR EXACT WHOLE NUMBERS IN A COMPUTER (2^53). THE MATHS HAS NO LIMIT.' : isReal() ? ' TAP THE DISC TO MAGNIFY.' : ' (PRACTICE FIELDS)');
        S.work = N > MAXN ? 'ABOVE 9 QUADRILLION PLAIN 64-BIT FLOATING POINT CANNOT COUNT EXACTLY: IN THIS BROWSER NEIGHBOURS MERGE. THE LAW ITSELF HOLDS.' : N === MAXN ? 'THE EXACT-NUMBER LIMIT. ' + fmt(MAXN / REAL_ISSUED) + ' TIMES TODAY\'S REAL KUIPER (43.5 BILLION).' : N >= 1e12 ? 'ANGLES REPEAT EVERY 4,294,967,296 KEYS (' + fmt(N / TWO32) + ' TIMES BY ' + fmt(N) + '); DOTS NEVER COLLIDE: EACH  … [line shortened here: 993 characters; full line on GitHub]
      else if (c === 'LINES') { S.big = null; S.mag = null; out = 'BACK TO THE LINES OF CODE'; S.cap = S.keys.length ? 'KEY ' + fmt(S.keys[S.keys.length - 1].key) + ':  ' + lineText(S.keys[S.keys.length - 1]) : ''; }
      else if (c === 'FIELDS') { menuClose(); UI.fields.classList.toggle('open'); fieldsRefresh(); out = UI.fields.classList.contains('open') ? 'THE FIELDS ARE OPEN: TYPE A NUMBER, PRESS ENTER' : 'FIELDS HIDDEN'; }
      else if (c === 'FORMULA') { out = formulaText(); S.cap = out; }
      else if (c === 'MEASURE') { out = measure(); S.cap = out; }
      else if (c === 'EXCEL') { note('BUILD IT IN EXCEL: FIVE COLUMNS, FILL DOWN, THEN AN XY SCATTER OF D:E.<br>A  KEY: 1, THEN =A2+1<br>B  DISTANCE: =SQRT(A2)<br>C  TURN: =2*PI()*MOD(A2*2654435769,4294967296)/4294967296<br>D  X: =B2*COS(C2)<br>E  Y: =B2*SIN(C2)<br>ROW 2 SHOULD READ 1, 3.883222, -0.737369, -0.675490.'); logLine('THE FIVE COLUMNS ARE ON SCREEN'); return; }
      else if (c === 'CHECK') { var ck = nums.length ? parseInt(nums[0], 10) : (S.sel >= 0 ? S.keys[S.sel].key : 1); var rq = placeReal(ck); note('OPEN <a href="https://ventusltd.github.io/kuiper-belt/" target="_blank" rel="noopener">THE LIVE KUIPER</a>, PRESS /, TYPE ' + fmt(ck) + ', ENTER.' + (ck === 1 ? ' KEY 1 SITS LOWER LEFT.' : '') + '<br>KEY ' + fmt(ck) + ': DISTANCE ' + f2(rq.r) + ', TURN   … [line shortened here: 524 characters; full line on GitHub]
      else if (c === 'BIGGER') { scaleText(1); out = 'TEXT x ' + PREF.fs; } else if (c === 'SMALLER') { scaleText(-1); out = 'TEXT x ' + PREF.fs; }
      else if (c === 'MUTE') { PREF.muted = !PREF.muted; savePref(); if (root.KGAudio) root.KGAudio.setMuted(PREF.muted); UI.muteBtn.textContent = PREF.muted ? 'SOUND ON' : 'MUTE'; out = PREF.muted ? 'MUTED' : 'TONES ON'; }
      else if (c === 'RESTART') { reset(); out = 'THE FIRST KEYS ARE PLACED. PLAY FOR THE REST.'; }
      else if (c === 'HELP') { note('THIS IS ONE SHEET. THE CIRCLE IS THE DRAWING. EVERY LINE OF CODE GETS THE NEXT KEY, AND THE KEY ALONE SAYS WHERE IT LANDS.<br>TAP A DOT: ITS LINE AND ITS NUMBERS. DRAG IT. TAP EMPTY SPACE: YOUR OWN DOT AND THE NEAREST KEY.<br>FIELDS: CHANGE ANY NUMBER OF THE LAW AND WATCH THE SHAPE MORPH. REAL KUIPER PUTS IT ALL BACK.<br>HOW MANY: TYPE A COUNT UP TO 9 QUADRILLI  … [line shortened here: 477 characters; full line on GitHub]
      else if (c === 'MODULE') { if (!modOpen(rest.toLowerCase())) throw new Error('THAT MODULE IS NOT LOADED'); out = 'OPENED ' + rest.toUpperCase(); }
      else if (c === 'CLOSE') {}
      else throw new Error('NOT A SENTENCE I KNOW. PRESS / FOR THE LIST.');
    } catch (e) { out = 'NO: ' + (e.message || e); }
    if (out) logLine(out); cmdClose(); setPlay();
  }
  function probeAt(r, deg) { var th = deg * Math.PI / 180, q = { key: null, r: r, deg: mod(deg, 360), x: r * Math.cos(th), y: r * Math.sin(th), text: '' };
    var best = -1, bd = 1e18, lim = Math.min(200000, Math.ceil(Math.pow(Math.abs(r) + 2, 1 / Math.max(0.2, F.power))) + 50); for (var jj = 0; jj < lim; jj++) { var k = F.firstKey + jj; var p = place(k); var d = Math.hypot(p.x - q.x, p.y - q.y); if (d < bd) { bd = d; best = k; } }
    q.key = best; S.probe = q; S.scaleTarget = Math.max(S.scaleTarget, Math.abs(r) * 1.1); S.cap = 'YOUR DOT: DISTANCE ' + f2(r) + ', ANGLE ' + f1(mod(deg, 360)) + ' FROM 3 O CLOCK, ANTICLOCKWISE.'; S.work = 'UNDER THESE FIELDS, KEY ' + fmt(best) + ' LANDS CLOSEST (' + f2(bd) + ' AWAY). DRAG THE DOT.'; if (narrow()) { S.cap = 'YOUR DOT: ANGLE ' + f1(mod(deg, 360)) + '°'; S.work = 'NEAREST KEY ' +   … [line shortened here: 440 characters; full line on GitHub]
  function note(html) { menuClose(); UI.note.innerHTML = html; UI.note.style.display = 'block'; UI.rows.style.display = 'none'; UI.cmd.classList.add('open'); }
  function cmdOpen() { wonderSkip(); menuClose(); UI.cmd.classList.add('open'); UI.cin.value = ''; UI.note.style.display = 'none'; UI.rows.style.display = 'block'; filter(''); if (!(window.matchMedia && window.matchMedia('(pointer:coarse)').matches)) UI.cin.focus(); }
  function cmdClose() { if (!UI) return; UI.cmd.classList.remove('open'); UI.cin.blur(); }
  function filter(q) { q = q.trim().toUpperCase(); var first = true; UI.rows.innerHTML = ''; SENTENCES.forEach(function (c) { if (!allowed(c[1])) return; if (q && c[0].toUpperCase().indexOf(q) < 0 && c[1].toUpperCase().indexOf(q) < 0) return; var b = document.createElement('button'); b.textContent = c[0]; b.dataset.cmd = c[1]; if (first) { b.className = 'hit'; first = false; } b.addEventListener('  … [line shortened here: 466 characters; full line on GitHub]
  function topHit() { var b = UI.rows.querySelector('.hit'); return b ? b.dataset.cmd : ''; }
  function fieldsRefresh() { if (!UI) return; FIELDS.forEach(function (f) { var inp = UI.fieldInputs[f[0]]; if (inp && document.activeElement !== inp) inp.value = F[f[0]] === null ? '' : String(F[f[0]]); var cur = UI.fieldCur[f[0]]; if (cur) cur.textContent = f[0] === 'degrees' ? 'NOW ' + f2(degPerKey()) + (F.degrees == null ? ' (FROM THE TURN NUMBER)' : '') : 'NOW ' + (F[f[0]] === null ? '' : fmt  … [line shortened here: 734 characters; full line on GitHub]

  // ---------- shell ----------
  var CSS = '.sh{position:fixed;inset:0;background:#000;color:#fff;font-family:' + FONT + ';font-weight:700;z-index:2147483000;overflow:hidden;-webkit-user-select:none;user-select:none;--s:1;--c:#00ffff}' +
    '.sh-awe{font-size:calc(24px*var(--s));line-height:1.2;color:var(--c);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;padding-bottom:calc(4px*var(--s))}' +
    '.sh-hint{position:absolute;left:calc(16px*var(--s));right:calc(16px*var(--s));bottom:0;font-size:calc(28px*var(--s));line-height:1.2;color:#ffb000;text-align:center;opacity:0;pointer-events:none;text-shadow:0 0 8px #000,0 0 16px #000}' +
    '.sh-hint.show{opacity:1;transition:opacity .3s}.sh-hint.fade{opacity:0;transition:opacity 6s linear}' +
    '.sh-btns .hm .pr{display:flex;align-items:center;gap:calc(8px*var(--s));flex:1 1 300px;min-width:0}.sh-btns .hm .pr input{flex:1 1 0;width:100%;min-width:calc(140px*var(--s))}' +
    '.sh-btns .hm button.k{flex:0 0 auto;min-width:calc(84px*var(--s));padding:0 calc(10px*var(--s))}.sh-btns .tip{flex:1 1 0;min-width:0;font-size:calc(24px*var(--s));color:#fff;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;text-align:left;padding:0 calc(6px*var(--s))}' +
    '@media (max-width:700px){.sh-top .sh-proof{display:none}.sh-btns .hm .pr{order:-1;flex:1 1 100%}.sh-btns .hm button.k{min-width:calc(56px*var(--s));flex:1 1 20%;min-height:calc(56px*var(--s));padding:0}.sh-btns .tip{flex:1 1 100%;text-align:center}}' +
    '.sh *{box-sizing:border-box}.sh canvas{position:absolute;inset:0;width:100%;height:100%;display:block;touch-action:none}' +
    '.sh-top{position:absolute;left:0;right:0;top:0;padding:calc(10px*var(--s)) calc(16px*var(--s)) 0;pointer-events:none;background:linear-gradient(#000 70%,transparent)}' +
    '.sh-cap{font-size:calc(40px*var(--s));line-height:1.15;color:#fff;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}' +
    '.sh-work{font-size:calc(32px*var(--s));line-height:1.15;color:#00ffff;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}' +
    '.sh-proof{font-size:calc(24px*var(--s));line-height:1.2;color:#fff;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;padding-bottom:calc(4px*var(--s))}.sh-proof span{color:#00ffff}' +
    '.sh-btns{position:absolute;left:0;right:0;bottom:0;display:flex;flex-wrap:wrap;gap:calc(8px*var(--s));padding:calc(8px*var(--s)) calc(12px*var(--s)) calc(12px*var(--s));background:linear-gradient(transparent,#000 40%)}' +
    '.sh button{font-family:inherit;font-weight:700;font-size:calc(32px*var(--s));min-height:calc(72px*var(--s));padding:0 calc(14px*var(--s));background:#000;color:#00ffff;border:3px solid #00ffff;cursor:pointer;letter-spacing:.04em;touch-action:manipulation}' +
    '.sh-btns button{flex:1 1 auto;white-space:nowrap}.sh-btns button.sm{flex:0 0 auto}.sh button.on{background:#00ffff;color:#000}' +
    '.sh-btns .hm{display:flex;flex-wrap:wrap;align-items:center;gap:calc(8px*var(--s));flex:1 1 100%;min-width:0}.sh-btns .hm label{font-size:calc(24px*var(--s));color:#fff;white-space:normal;line-height:1.05;max-width:calc(200px*var(--s));flex:0 0 auto}' +
    '.sh input{font-family:inherit;font-weight:700;font-size:calc(32px*var(--s));min-height:calc(72px*var(--s));background:#000;color:#fff;border:3px solid #00ffff;outline:0;padding:0 calc(12px*var(--s));min-width:0}' +
    '.sh-btns .hm input{flex:1 1 0;width:100%}.sh-btns .hm label.x,.sh-btns .hm input.x{display:inline-block}' +
    '.sh-cmd{position:absolute;left:0;right:0;top:0;bottom:0;display:none;flex-direction:column;background:#000;padding:calc(12px*var(--s))}' +
    '.sh-cmd.open{display:flex}.sh-cmd .h{font-size:calc(28px*var(--s));color:#00ffff;padding:0 0 calc(8px*var(--s))}' +
    '.sh-cmd .rows{flex:1;overflow:auto;-webkit-overflow-scrolling:touch;border-top:3px solid #00ffff}.sh-cmd .rows button{display:block;width:100%;text-align:left;border:0;border-bottom:2px solid #0d2a30;color:#fff;font-size:calc(32px*var(--s));min-height:calc(64px*var(--s));white-space:normal;line-height:1.15}' +
    '.sh-cmd .rows button.hit{background:#00ffff;color:#000}.sh-cmd .note{flex:1;overflow:auto;color:#fff;font-size:calc(30px*var(--s));padding:calc(10px*var(--s)) 0;line-height:1.3;display:none}.sh-cmd .note a{color:#00ffff}' +
    '.sh-cmd .log{font-size:calc(24px*var(--s));color:#00ffff;white-space:pre-wrap;min-height:2.6em;padding:calc(6px*var(--s)) 0}.sh-cmd input{width:100%}' +
    '.sh-fields{position:absolute;right:0;top:0;bottom:0;width:min(560px,100%);display:none;flex-direction:column;background:#000;border-left:3px solid #00ffff;padding:calc(12px*var(--s));overflow:auto}' +
    '.sh-fields.open{display:flex}.sh-fields .h{font-size:calc(28px*var(--s));color:#00ffff;padding-bottom:calc(8px*var(--s))}.sh-fields .mode{font-size:calc(32px*var(--s));color:#fff;padding-bottom:calc(8px*var(--s))}' +
    '.sh-fields .row{display:flex;flex-direction:column;gap:4px;padding:calc(6px*var(--s)) 0;border-bottom:2px solid #0d2a30}.sh-fields .row label{font-size:calc(24px*var(--s));color:#fff}.sh-fields .row .cur{font-size:calc(24px*var(--s));color:#00ffff}.sh-fields .row input{width:100%;min-height:calc(60px*var(--s));font-size:calc(28px*var(--s))}' +
    '.sh-fields .b{display:flex;gap:calc(8px*var(--s));padding-top:calc(8px*var(--s))}.sh-fields .b button{flex:1}' +
    '@media (max-width:700px){.sh-cap{font-size:calc(28px*var(--s));white-space:normal;max-height:2.4em}.sh-work{font-size:calc(24px*var(--s));white-space:normal;max-height:2.5em}.sh-proof{font-size:calc(24px*var(--s))}.sh-btns button.x,.sh-btns .hm label.x,.sh-btns .hm input.x{display:none}.sh-top .sh-proof:last-child{display:none}.sh-btns button{flex:1 1 40%;min-height:calc(56px*var(--s))}.sh-bt  … [line shortened here: 851 characters; full line on GitHub]
    // LAYOUT. Phone: a compact bar (PLAY, /10, x10, TURN -10, TURN +10, TOUCH, MORE); MORE opens the rest. Wide laptop: one side column, the circle keeps the height.
    '.sh-more{display:none}' +
    // VERSION 4 COCKPIT. The canvas is the whole screen. Captions overlay the top and fade back. One row of dim outline buttons. Everything else in one popup menu.
    '.sh-top{background:linear-gradient(rgba(0,0,0,.6) 70%,transparent);padding:calc(6px*var(--s) + env(safe-area-inset-top,0px)) calc(16px*var(--s)) calc(10px*var(--s));text-align:center;transition:opacity 1.2s;z-index:2}.sh-top.dim{opacity:.3}' +
    '.sh .sh-cap{font-size:calc(32px*var(--s));font-weight:400;color:#fff;white-space:nowrap;max-height:none}.sh .sh-work{font-size:calc(24px*var(--s));font-weight:400;color:var(--c);white-space:nowrap;max-height:none}' +
    '@media (max-width:700px),(max-height:500px){.sh .sh-cap{font-size:calc(26px*var(--s))}}' +
    '.sh-bar{position:absolute;left:0;right:0;bottom:0;display:flex;justify-content:center;align-items:flex-end;gap:calc(10px*var(--s));padding:0 calc(12px*var(--s) + env(safe-area-inset-right,0px)) calc(10px*var(--s) + env(safe-area-inset-bottom,0px)) calc(12px*var(--s) + env(safe-area-inset-left,0px));pointer-events:none;z-index:3;transition:opacity .8s}' +
    '.sh-bar .gap{display:none;flex:1 1 auto}@media (orientation:landscape){.sh-bar{justify-content:space-between}.sh-bar .gap{display:block}}' +
    '.sh .sh-bar button{pointer-events:auto;flex:0 1 auto;font-size:calc(26px*var(--s));font-weight:400;min-height:calc(72px*var(--s));min-width:calc(72px*var(--s));padding:0 calc(14px*var(--s));background:rgba(0,0,0,.3);border:1.5px solid var(--c);color:var(--c);opacity:.55;border-radius:calc(10px*var(--s));white-space:nowrap;transition:opacity .3s}' +
    '.sh .sh-bar button:hover,.sh .sh-bar button:active,.sh .sh-bar button:focus-visible{opacity:1}.sh .sh-bar button.on{color:#fff;border-color:#fff;background:rgba(0,0,0,.3)}.sh.quiet .sh-bar{opacity:.3}' +
    '@media (max-width:700px),(max-height:500px){.sh .sh-bar{gap:6px}.sh .sh-bar button{font-size:calc(24px*var(--s));min-height:calc(56px*var(--s));min-width:calc(56px*var(--s));padding:0 calc(9px*var(--s));letter-spacing:0}}' +
    '.sh .sh-btns{display:none;left:0;right:0;top:auto;bottom:0;max-height:84%;overflow:auto;-webkit-overflow-scrolling:touch;background:rgba(0,0,0,.93);border-top:2px solid var(--c);z-index:4;align-content:flex-start;padding:calc(10px*var(--s)) calc(12px*var(--s)) calc(12px*var(--s) + env(safe-area-inset-bottom,0px))}.sh .sh-btns.open{display:flex}' +
    '@media (min-width:1000px){.sh .sh-btns{left:50%;right:auto;transform:translateX(-50%);width:min(1000px,100%);border:2px solid var(--c);border-bottom:0}}' +
    '.sh .sh-btns button{border-width:2px;font-weight:400}.sh .sh-btns button.x,.sh .sh-btns .hm label.x,.sh .sh-btns .hm input.x{display:inline-block}.sh .sh-btns .sh-proof{flex:1 1 100%;white-space:normal;display:block}.sh .sh-btns .tip{flex:1 1 100%;white-space:normal;text-align:left}' +
    '.sh .sh-btns button.sm{flex:1 1 auto;padding:0 calc(14px*var(--s));min-width:calc(72px*var(--s))}.sh .sh-btns .hm .pr{flex:1 1 100%;order:-1}.sh .sh-btns .hm button.k{flex:1 1 18%;min-width:0;padding:0}.sh .sh-btns .hero0{order:-5;flex:1 1 100%}.sh .sh-btns .hero{order:-3}.sh .sh-btns .tip.hero{order:-2;flex:1 1 50%}.sh .sh-btns button.hero2{order:-1;flex:1 1 100%}' +
    '@media (max-width:700px){.sh .sh-btns .hm button.rl{flex:1 1 100%}}' +
    '.sh button.on{background:transparent;color:#fff;border-color:#fff}.sh-cmd,.sh-fields{z-index:7}.sh.tod .sh-bar{display:none}' +
    '.sh button.round{border-radius:50%;width:calc(128px*var(--s));height:calc(128px*var(--s));min-height:0;padding:0;flex:0 0 auto;font-size:calc(24px*var(--s));letter-spacing:0;line-height:1.05;background:rgba(0,0,0,.3);color:#ffb000;border:2px solid #ffb000;font-weight:400}' +
    '.sh button.sh-x{position:absolute;right:calc(12px*var(--s));top:calc(12px*var(--s));display:none;width:calc(84px*var(--s));height:calc(84px*var(--s));min-height:0;border-radius:50%;font-size:calc(48px*var(--s));padding:0;z-index:5;background:#000;color:#fff;border-color:#fff}' +
    '.sh.tod .sh-top,.sh.tod .sh-btns,.sh.tod .sh-hint{display:none}.sh.tod .sh-x{display:block}' +
    '.sh-tb{position:absolute;left:0;right:0;bottom:calc(12px*var(--s));display:none;justify-content:center;gap:calc(24px*var(--s));pointer-events:none;z-index:5}.sh.tod .sh-tb{display:flex}.sh .sh-tb button.round{pointer-events:auto;width:calc(104px*var(--s));height:calc(104px*var(--s))}.sh .sh-tb button.big{font-size:calc(64px*var(--s));line-height:1}.sh .sh-tb button.on{color:#fff;border-color:  … [line shortened here: 408 characters; full line on GitHub]
    '.sh-deep{position:absolute;inset:0;display:none;flex-direction:column;background:#000;color:#fff;z-index:8;padding:calc(12px*var(--s))}.sh-deep.open{display:flex}' +
    '.sh-deep .body{flex:1;overflow:auto;-webkit-overflow-scrolling:touch;font-size:calc(28px*var(--s));line-height:1.35;white-space:pre-wrap;word-break:break-word;font-weight:400;-webkit-user-select:text;user-select:text}.sh-deep .body b{color:#00ffff;font-weight:700}.sh-deep .body a{color:#ffb000}.sh-deep .b{display:flex;gap:calc(8px*var(--s));padding-bottom:calc(8px*var(--s))}.sh-deep .b button  … [line shortened here: 411 characters; full line on GitHub]
    // VERSION 5. The dots are the brightest thing: captions, readouts and menu buttons step back. Phone captions wrap (no cut words). Landscape: one caption line above the circle.
    '.sh .sh-cap{color:rgba(255,255,255,.85)}.sh .sh-work{opacity:.75}.sh .sh-btns button{opacity:.8;border-width:1.5px}.sh .sh-btns button:hover,.sh .sh-btns button:active{opacity:1}.sh .sh-btns .tip{font-weight:400;color:rgba(255,255,255,.8)}.sh .sh-btns .hm label{font-weight:400}.sh .sh-btns input{border-width:1.5px;font-weight:400}' +
    '.sh{top:0;left:0;right:0;bottom:auto;height:100%;height:100dvh}' +
    '.sh .sh-cap,.sh .sh-work{white-space:nowrap;overflow:hidden;text-overflow:clip;line-height:1.2;height:1.2em}@media (max-width:700px){.sh .sh-cap{font-size:calc(24px*var(--s))}}' +
    '.sh .sh-cmd .rows button.hit{background:transparent;color:var(--c);border-left:6px solid var(--c)}' +
    '@media (max-height:500px){.sh .sh-work{display:none}.sh .sh-top{padding-bottom:calc(4px*var(--s))}}' +
    '.sh.hinting .sh-mission,.sh.hinting .sh-sound{opacity:0}@media (max-width:700px),(max-height:500px){.sh-hint{font-size:calc(24px*var(--s))}}@media (max-height:500px){.sh-hint{left:30%;right:30%}}' +
    '.sh button.sh-mission{position:absolute;left:calc(14px + env(safe-area-inset-left,0px));bottom:0;z-index:3;font-size:calc(24px*var(--s));font-weight:400;line-height:1.2;text-align:left;background:transparent;border:0;color:var(--c);opacity:.6;padding:0;min-height:0;letter-spacing:0;white-space:nowrap;transition:opacity .8s}.sh button.sh-mission span{color:#fff;opacity:.75}' +
    '.sh button.sh-mission:hover,.sh button.sh-mission:active{opacity:1}.sh.quiet .sh-mission{opacity:.25}.sh.tod .sh-mission{display:none}' +
    '.sh button.sh-sound{position:absolute;left:calc(14px + env(safe-area-inset-left,0px));bottom:0;z-index:3;font-size:calc(24px*var(--s));font-weight:400;line-height:1.2;text-align:left;background:transparent;border:0;color:var(--c);opacity:.75;padding:0;min-height:0;letter-spacing:0;white-space:nowrap}.sh.tod .sh-sound{display:none}.sh.bloom .sh-sound{opacity:0;pointer-events:none}' +
    '.sh.bloom .sh-top,.sh.bloom .sh-mission,.sh.bloom .sh-hint{opacity:0;pointer-events:none}.sh.bloom .sh-bar{opacity:.6}' +
    '.sh .sh-bar button{opacity:1;color:#c8ffff;border-color:rgba(0,255,255,.5);background:rgba(0,0,0,.45);text-shadow:0 0 6px #000}.sh.quiet .sh-bar{opacity:.75}.sh.bloom .sh-bar{opacity:1}.sh.bloom .sh-bar button:first-child{display:none}' +
    '.sh button.sh-mission{display:none}.sh .sh-top{background:transparent}.sh .sh-work{display:none}@media (max-width:700px),(max-height:500px){.sh .sh-work{display:none}.sh .sh-cap{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-height:1.3em}}' +
    '.sh .sh-btns .sh-mods{order:-4;flex:1 1 100%;display:flex;flex-wrap:wrap;gap:calc(8px*var(--s))}.sh .sh-btns .sh-mods:empty{display:none}.sh .sh-btns .sh-mods button{flex:1 1 30%;min-height:calc(72px*var(--s));white-space:normal;line-height:1.05;color:#fff;border-color:var(--c)}' +
    '@media (max-width:700px){.sh .sh-btns .sh-mods button{flex:1 1 45%;min-height:calc(64px*var(--s))}}' +
    '.sh .sh-btns .sh-off{flex:1 1 100%;font-size:calc(24px*var(--s));font-weight:400;line-height:1.25;color:rgba(255,255,255,.8)}.sh .sh-btns .sh-off a{display:none;color:var(--c);border:1.5px solid var(--c);border-radius:calc(10px*var(--s));min-height:calc(64px*var(--s));line-height:calc(64px*var(--s));text-align:center;text-decoration:none;margin-bottom:calc(8px*var(--s));font-size:calc(26px*va  … [line shortened here: 464 characters; full line on GitHub]
  // ---------- V5: MODULES (window.KGModules). Each gets a big MENU entry and a sentence; opening one gives it a full-screen host above the sheet. ----------
  var MOD = null, MODSENT = {};
  function modsList() { return (root.KGModules || []).filter(function (m) { return m && m.id && typeof m.open === 'function'; }); }
  function modsSync() { modsList().forEach(function (m) { if (!MODSENT[m.id]) { MODSENT[m.id] = true; SENTENCES.splice(2, 0, [m.sentence || m.label || m.id, 'MODULE ' + m.id]); }
      if (UI && !UI.modBtn[m.id]) { var b = btn(String(m.label || m.id).toUpperCase(), function () { modOpen(m.id); }, 'mod'); b.dataset.mod = m.id; UI.mods.appendChild(b); UI.modBtn[m.id] = b; if (m.id === 'deep' && UI.deepBtn) UI.deepBtn.style.display = 'none'; } }); }
  function modOpen(id) { if (!UI || MOD) return false; var m = modsList().filter(function (x) { return x.id === id; })[0]; if (!m) { hint(String(id).toUpperCase() + ' IS NOT LOADED HERE.', true); return false; }
    wonderSkip(); bloomSkip(); cmdClose(); menuClose(); UI.fields.classList.remove('open'); S.playing = false; S.drag = null; if (S.hold) { clearTimeout(S.hold); S.hold = null; }
    var host = el('div', 'kg-module-host'); host.id = 'kg-module-host'; host.style.cssText = 'position:' + (open.mount ? 'absolute' : 'fixed') + ';left:0;top:0;width:100%;height:100%;background:#000;z-index:2147483600;overflow:hidden';
    (open.mount || document.body).appendChild(host);
    var rec = MOD = { m: m, id: m.id, host: host, orig: m.close, done: false, called: false, obs: null };
    // pause the sheet: its loop, its music and its key listener (so the module owns the keyboard)
    cancelAnimationFrame(raf); raf = 0; if (MUS.timer) { clearInterval(MUS.timer); MUS.timer = null; } try { if (AC && AC.state === 'running') AC.suspend(); } catch (e) {} window.removeEventListener('keydown', onKey, true);
    m.close = function () { if (!rec.called) { rec.called = true; try { if (typeof rec.orig === 'function') rec.orig.apply(m, arguments); } catch (e) {} } modDone(rec); };
    ['kgclose', 'kg-close', 'kgmodule:close'].forEach(function (ev) { host.addEventListener(ev, function () { modDone(rec); }); });
    try { m.open(host); } catch (e) { rec.called = true; modDone(rec); hint('THAT MODULE DID NOT OPEN.', true); return false; }
    if (!rec.done && window.MutationObserver) { rec.obs = new MutationObserver(function () { if (!host.firstChild) modDone(rec); }); rec.obs.observe(host, { childList: true }); }
    return !rec.done; }
  function modDone(rec) { if (!rec || rec.done) return; rec.done = true; if (!rec.called) { rec.called = true; try { if (typeof rec.orig === 'function') rec.orig.call(rec.m); } catch (e) {} }
    rec.m.close = rec.orig; if (rec.obs) { try { rec.obs.disconnect(); } catch (e) {} } if (rec.host.parentNode) rec.host.parentNode.removeChild(rec.host); if (MOD === rec) MOD = null;
    if (!UI) return; window.addEventListener('keydown', onKey, true); try { if (AC && AC.state === 'suspended' && gestured) AC.resume(); } catch (e) {} lastT = 0; S.wake = performance.now(); UI.capAt = performance.now(); size(); if (!raf) raf = requestAnimationFrame(frame); musicSync(); }
  function tod() { return !!(UI && UI.root.classList.contains('tod')); }
  function wide() { return false; }
  function menuOpen() { if (!UI) return; wonderSkip(); bloomSkip(); modsSync(); UI.btns.classList.add('open'); }
  function menuClose() { if (UI) UI.btns.classList.remove('open'); }
  var TURNS = [90, 120, 72, 137.507764, null];   // the TURN button walks the shapes: 4 spokes, 3, 5, the mirror spiral, the real Kuiper
  function turnNext() { var d = degPerKey(), i = -1; for (var j = 0; j < TURNS.length; j++) if (TURNS[j] !== null && Math.abs(TURNS[j] - d) < 0.01) i = j; turnTo(TURNS[(i + 1) % TURNS.length]); }
  // ---------- THE COCKPIT: thin instrument readouts in the corners, fine ticks on the rim, a small compass rose. The centre stays clear. ----------
  function hud(W, H, cx, cy, R, fs) { var TOD = tod(), i, a, c = PAL.cyan;
    g.strokeStyle = c; g.globalAlpha = 0.45; g.lineWidth = 1; g.beginPath(); for (i = 0; i < 72; i++) { a = i * Math.PI / 36; var l = i % 18 === 0 ? 18 : i % 6 === 0 ? 12 : i % 2 === 0 ? 7 : 4; g.moveTo(cx + (R - l) * Math.cos(a), cy - (R - l) * Math.sin(a)); g.lineTo(cx + R * Math.cos(a), cy - R * Math.sin(a)); } g.stroke(); g.globalAlpha = 1;
    if (TOD) return;
    var f = Math.max(24, 24 * PREF.fs), lh = f * 1.2, m = 14, y0 = UI.top.offsetHeight + f * 0.7, dim = 'rgba(102,204,255,0.6)', barH = UI.bar.offsetHeight, nNow = countNow();
    function t4(str, x, y, col, al, alpha) { g.globalAlpha = alpha == null ? 1 : alpha; g.fillStyle = col; g.font = '400 ' + f + 'px ' + FONT; g.textAlign = al; g.textBaseline = 'middle'; g.fillText(str, x, y); g.globalAlpha = 1; }
    // V10 two short lines, top left: the count (one source of truth), then the selected key (amber) or the turn
    var sp = S.big ? S.bigSel : (S.sel >= 0 ? S.keys[S.sel] : (S.probe || (S.anim ? S.anim.p : null)));
    t4(fmt(nNow) + (nNow === 1 ? ' KEY' : ' KEYS') + (isReal() ? '' : ', PRACTICE'), m, y0, c, 'left', 0.85);
    if (sp && isFinite(sp.r)) { var probe = !S.big && S.sel < 0 && sp === S.probe; t4((probe ? 'YOUR DOT' : 'KEY ' + fmt(sp.key)) + ': ' + f2(sp.r) + ', ' + f1(sp.deg) + '°', m, y0 + lh, PAL.amber, 'left', 0.9); }
    else t4('TURN ' + f2(degPerKey()) + '°', m, y0 + lh, c, 'left', 0.7);
    function mark(str, x, y, al) { if (S.big) { g.font = '400 ' + f + 'px ' + FONT; var mw = g.measureText(str).width + 10; g.fillStyle = 'rgba(0,0,0,0.72)'; g.fillRect(al === 'right' ? x - mw + 5 : x - 5, y - f * 0.6, mw, f * 1.2); } t4(str, x, y, SOFT, al); }
    if (W - (cx + R) > 150) t4('0°', cx + R + 12, cy, SOFT, 'left'); else mark('0°', cx + R - 24, cy - f * 0.7, 'right'); mark('90°', cx + 10, Math.max(cy - R + f * 1.2, UI.top.offsetHeight + f * 0.9), 'left'); }
  // ---------- TOUCH MODE: play by touch; every function by touch; the numbers huge and optional ----------
  function happy(kind) { if (!gestured || PREF.muted) return; try { ac(); var t = AC.currentTime, seq = kind === 2 ? [392, 523, 659, 784] : kind === 1 ? [523, 659] : [659, 784]; seq.forEach(function (fq, i) { var o = AC.createOscillator(), gn = AC.createGain(); o.type = 'triangle'; o.frequency.value = fq; gn.gain.setValueAtTime(0.0001, t + i * 0.09); gn.gain.exponentialRampToValueAtTime(0.06, t +   … [line shortened here: 599 characters; full line on GitHub]
  function todOn() { if (!UI) return; wonderSkip(); cmdClose(); menuClose(); UI.fields.classList.remove('open'); UI.deep.classList.remove('open'); UI.root.classList.add('tod'); S.shadows = false; S.probe = null; S.sel = -1; S.big = null; S.mag = null; S.bigSel = null; S.dup = false; if (S.keys.length < 40) setCount(60); S.scale = S.scaleTarget; S.speed = 4; gestured = true; musicSync(); setPlay();  … [line shortened here: 402 characters; full line on GitHub]
  function todOff() { if (!UI) return; UI.root.classList.remove('tod'); S.playing = false; S.tod = null; setPlay(); S.cap = isReal() ? 'THE REAL KUIPER.' : 'PRACTICE: ' + (limitLine() || 'YOUR OWN SHAPE'); S.work = plainWords(); }
  function todDown(e, x, y) { S.ptrs[e.pointerId] = [x, y]; var ids = Object.keys(S.ptrs), now = performance.now(), ge = S.geom;
    if (ids.length >= 2) { var a = S.ptrs[ids[0]], b = S.ptrs[ids[1]]; S.pinch = { d: Math.hypot(a[0] - b[0], a[1] - b[1]), ang: Math.atan2(a[1] - b[1], a[0] - b[0]), N: S.big ? S.big.N : Math.max(2, S.keys.length), deg: degPerKey(), moved: false, noTwist: true }; if (S.hold) { clearTimeout(S.hold); S.hold = null; } S.tod = null; return; }
    if (now - S.lastTap < 300) { S.lastTap = 0; S.tod = null; run('REAL'); happy(2); return; } S.lastTap = now;
    var hit = -1, bd = 30; if (S.big) { var wx = (x - ge.cx) / ge.unit, wy = -(y - ge.cy) / ge.unit, bh = pickAt(wx, wy); if (bh) { S.bigSel = bh; hit = 1; happy(1); } magnify(x, y); }
    else { for (var i = 0; i < S.keys.length; i++) { var q = S.keys[i], d = Math.hypot(x - (ge.cx + q.x * ge.unit), y - (ge.cy - q.y * ge.unit)); if (d < bd) { bd = d; hit = i; } } if (hit >= 0) { S.sel = hit; S.playing = false; S.anim = null; setPlay(); tone(S.keys[hit].r); happy(1); } }
    S.tod = { x: x, y: y, t: now, moved: false, hit: hit };
    S.hold = setTimeout(function () { S.hold = null; if (S.tod && !S.tod.moved) { S.tod = null; S.big = null; S.sel = -1; run('NIGHT'); } }, 550); }
  function todMove(x, y) { var T = S.tod; if (!T || S.pinch) return; var ge = S.geom; if (!T.moved && Math.hypot(x - T.x, y - T.y) < 14) return; T.moved = true; if (S.hold) { clearTimeout(S.hold); S.hold = null; }
    var deg = mod(Math.atan2(-(y - ge.cy), x - ge.cx) * 180 / Math.PI, 360); if (Math.abs(deg - DEG_PER_KEY) < 5) F.degrees = null; else F.degrees = Math.round(deg * 10) / 10; S.big = null; S.sel = -1; S.playing = false; reflow(); if (UI) { fieldsRefresh(); UI.degBox.value = F.degrees == null ? '' : String(F.degrees); } if (!S.toneT || performance.now() - S.toneT > 120) { S.toneT = performance.now  … [line shortened here: 423 characters; full line on GitHub]
  function todUp() { var T = S.tod; S.tod = null; if (!T) return; var quick = S.hold != null; if (S.hold) { clearTimeout(S.hold); S.hold = null; } if (!T.moved && quick && T.hit < 0 && !S.big) { step(); happy(0); } setPlay(); }
  function todAnnotate(cx, cy, R, unit, p, fs) { var th = p.deg * Math.PI / 180, r2 = Math.min(R, Math.abs(p.r) * unit), x = cx + p.x * unit, y = cy - p.y * unit; if (!isFinite(x)) return; if (Math.hypot(x - cx, y - cy) > R) { x = cx + r2 * Math.cos(th); y = cy - r2 * Math.sin(th); }
    g.strokeStyle = PAL.cyan; g.lineWidth = 4; g.setLineDash([10, 10]); g.beginPath(); g.arc(cx, cy, r2, 0, PI2); g.stroke(); g.setLineDash([]);
    g.fillStyle = 'rgba(255,176,0,0.22)'; g.beginPath(); g.moveTo(cx, cy); g.arc(cx, cy, r2, 0, -th, true); g.closePath(); g.fill();
    g.strokeStyle = PAL.amber; g.lineWidth = 6; g.beginPath(); g.arc(cx, cy, r2, 0, -th, true); g.stroke(); g.beginPath(); g.moveTo(cx, cy); g.lineTo(x, y); g.stroke();
    g.fillStyle = 'rgba(255,255,255,0.35)'; g.beginPath(); g.arc(x, y, 24, 0, PI2); g.fill(); g.fillStyle = '#fff'; g.beginPath(); g.arc(x, y, 12, 0, PI2); g.fill();
    var big = fs * 2.4, dirY = y < cy ? -1 : 1, tx = Math.max(cx - R + big * 1.6, Math.min(cx + R - big * 1.6, x)), ty = y + dirY * big * 0.9;
    txt(fmt(p.key), tx, ty, '#fff', big, 'center'); txt(f1(p.deg) + '°', tx, ty + dirY * big * 0.75, PAL.amber, fs * 1.4, 'center'); }
  function drawSmile(cx, cy, R) { g.fillStyle = '#fff'; g.beginPath(); g.arc(cx - R * 0.22, cy - R * 0.18, Math.max(6, R * 0.045), 0, PI2); g.fill(); g.beginPath(); g.arc(cx + R * 0.22, cy - R * 0.18, Math.max(6, R * 0.045), 0, PI2); g.fill(); g.strokeStyle = '#fff'; g.lineWidth = Math.max(6, R * 0.03); g.lineCap = 'round'; g.beginPath(); g.arc(cx, cy, R * 0.36, Math.PI * 0.18, Math.PI * 0.82); g.  … [line shortened here: 431 characters; full line on GitHub]
  // ---------- DEEP: the exact law, the receipts, the number theory, the honest comparison (plain text, big, scrollable) ----------
  function contFrac() { try { var a = BigInt(G32), b = BigInt(TWO32), t = [], conv = [], h0 = 1n, h1 = 0n, k0 = 0n, k1 = 1n; while (b > 0n && t.length < 40) { var q = a / b; t.push(q); var h = q * h1 + h0, k = q * k1 + k0; conv.push(h + '/' + k); h0 = h1; h1 = h; k0 = k1; k1 = k; var r = a % b; a = b; b = r; } var ones = 0; for (var i = 1; i < t.length && t[i] === 1n; i++) ones++; return { terms:   … [line shortened here: 616 characters; full line on GitHub]
  function esc(s) { return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;'); }
  function deepHtml() { var cf = contFrac(), conv = cf.conv.slice(1, 26).join('  '), later = cf.terms.slice(cf.ones + 1, cf.ones + 12).join(', ');
    var P = [
      ['THE LIVE LAW, VERBATIM', 'kuiper-belt index.html line 92:  const G32 = 2654435769, TW = 4096;\nindex.html lines 250 to 251:  function keyPlace(k){ const m = Math.imul((k % 4294967296) >>> 0, G32) >>> 0, th = 2*Math.PI*m/4294967296, r = Math.sqrt(k + 0.5); return [r*Math.cos(th), r*Math.sin(th)]; }\nindex.html lines 143 to 148 (the GPU vertex shader, one vertex per key):  float d = float(gl  … [line shortened here: 1,124 characters; full line on GitHub]
      ['THE SAME RULE AS THE LIVE KUIPER', 'Every dot here is placed by kuiper-law.js, which holds the rule of the live Kuiper page word for word. ' + PROOF + '.'],
      ['WHY 2654435769', '4294967296 / 1.6180339887... = 2654435769.497..., so 2654435769 = floor(2^32 / 1.6180339887...). Multiply the key by it and keep the low 32 bits: that is m. The turn per key is 2654435769 / 2^32 = 0.6180339886 of a lap.\nIts continued fraction is 0; ' + cf.ones + ' ones, then ' + later + '. While the partial quotients are 1, the near-repeats of the angle come at the conve  … [line shortened here: 763 characters; full line on GitHub]
      ['THE FACTS THAT FOLLOW', 'Angles repeat every 2^32 = 4,294,967,296 keys: m depends only on key mod 2^32. The distance never repeats, so no two keys ever share a place.\nExact to 2^53: key mod 2^32 and Math.imul are exact for every whole key below 9,007,199,254,740,992. The half in sqrt(key + 0.5) is kept exactly below 2^52 and rounds above it, the same rounding in the live code and here, so  … [line shortened here: 1,486 characters; full line on GitHub]
      ['H3, S2 AND SPACE-FILLING CURVES', 'Uber H3 (Apache License 2.0, (c) Uber Technologies, Inc.): a hexagonal hierarchical index for the globe, 16 resolutions, aperture 7, 64-bit cell ids, parent and child by bit operations, neighbour rings in constant time.\nGoogle S2 Geometry (Apache License 2.0, (c) Google Inc.): the sphere cut into a cube, 31 levels, cells numbered along six space-filling   … [line shortened here: 1,345 characters; full line on GitHub]
      ['LINKS', '<a href="https://ventusltd.github.io/kuiper-belt/" target="_blank" rel="noopener">The live Kuiper</a> (press /, type a key, Enter: the same place as here).  <a href="https://github.com/Ventusltd/kuiper-belt" target="_blank" rel="noopener">The kuiper-belt repository</a> (index.html holds every line quoted above).  <a href="https://ventusltd.github.io/kuiper-belt/what-is-kuiper.html  … [line shortened here: 454 characters; full line on GitHub]
    ];
    return P.map(function (s) { return '<b>' + s[0] + '</b>\n' + (s[0] === 'LINKS' ? s[1] : esc(s[1])); }).join('\n\n'); }
  function deepOpen() { if (!UI) return; wonderSkip(); cmdClose(); menuClose(); UI.fields.classList.remove('open'); if (!UI.deepBody.innerHTML) UI.deepBody.innerHTML = deepHtml(); UI.deep.classList.add('open'); UI.deepBody.scrollTop = 0; }
  function deepClose() { if (UI) UI.deep.classList.remove('open'); }
  function el(tag, cls, t) { var e = document.createElement(tag); if (cls) e.className = cls; if (t != null) e.textContent = t; return e; }
  function btn(label, on, cls) { var b = el('button', cls || '', label); b.addEventListener('click', function (e) { e.preventDefault(); gestured = true; if (S && S.bloom) bloomSkip(); on(b); musicSync(); }); return b; }
  function setPlay() { musicSync(); if (!UI) return; UI.play.textContent = S.playing ? 'PAUSE' : 'PLAY'; UI.play.classList.toggle('on', S.playing); if (UI.tPlay) { UI.tPlay.textContent = S.playing ? 'STOP' : 'PLAY'; UI.tPlay.classList.toggle('on', S.playing); } }
  function speedLabel() { return S.speed < 1 ? '1 LINE EVERY ' + f1(1 / S.speed) + ' S' : fmt(S.speed) + ' LINES A SECOND'; }
  function faster(d) { S.speed = Math.max(0.25, Math.min(64, S.speed * (d > 0 ? 2 : 0.5))); S.work = 'SPEED: ' + speedLabel(); if (S.anim) S.anim.dur = Math.min(S.anim.dur, Math.max(0.08, 1 / S.speed)); }
  function step() { S.intro = false; S.playing = false; S.sel = -1; S.probe = null; if (S.done) { reset(); S.playing = false; } if (!S.anim) startNext(); setPlay(); }
  function savePref() { try { localStorage.setItem('kg-sh-pref', JSON.stringify(PREF)); } catch (e) {} }
  function scaleText(d) { PREF.fs = Math.max(1, Math.min(1.8, Math.round((PREF.fs + d * 0.15) * 100) / 100)); UI.root.style.setProperty('--s', PREF.fs); savePref(); }
  function frame(t) { if (!UI) return; if (MOD) { raf = 0; return; } var dt = lastT ? Math.min(0.1, (t - lastT) / 1000) : 0; lastT = t; var dpr0 = Math.min(3, window.devicePixelRatio || 1); if (cv.width !== Math.round(UI.root.clientWidth * dpr0) || cv.height !== Math.round(UI.root.clientHeight * dpr0)) size();
    try { update(dt); draw(UI.root.clientWidth, UI.root.clientHeight); } catch (e) { S.cap = 'ERROR ' + String(e).slice(0, 60); }
    var fw = UI.top.clientWidth; if (UI.capRaw !== S.cap || UI.workRaw !== S.work || UI.fitW !== fw) { if (UI.capRaw !== S.cap || UI.workRaw !== S.work) UI.capAt = t; UI.capRaw = S.cap; UI.workRaw = S.work; UI.fitW = fw; UI.cap.textContent = fitLine(S.cap, UI.cap); UI.work.textContent = fitLine(S.work, UI.work); }
    UI.top.classList.toggle('dim', t - UI.capAt > 5000); var busy = S.drag || S.pinch || (S.tod && S.tod.moved) || (S.playing && !(S.wake && performance.now() - S.wake < 3000)); UI.root.classList.toggle('quiet', !!busy); var pr = formulaText() + '   ' + plainWords(); if (UI.proofTxt.textContent !== pr) UI.proofTxt.textContent = pr;
    if (document.activeElement !== UI.howmany) { var cs = String(countNow()); if (UI.howmany.value !== cs) UI.howmany.value = cs; } var mb = Math.round(UI.bar.offsetHeight + Math.max(24, 24 * PREF.fs) * 1.7) + 'px'; if (UI.mission.style.bottom !== mb) UI.mission.style.bottom = mb; var sb = mb; if (UI.sound.style.bottom !== sb) UI.sound.style.bottom = sb; var KA = root.KGAudio, st = !KA ? '' : PREF  … [line shortened here: 666 characters; full line on GitHub]
    var aw = countNow() > 2 ? aweText() : TIP; if (UI.awe.textContent !== aw) UI.awe.textContent = aw; var hinting = compact() && performance.now() < (HINT.until || 0), hb = Math.round((UI.root.clientHeight < 500 ? 0 : UI.bar.offsetHeight) + (compact() ? 14 : Math.max(24, 24 * PREF.fs) * 2.7 + 8)) + 'px'; if (UI.hint.style.bottom !== hb) UI.hint.style.bottom = hb; UI.root.classList.toggle('hinting  … [line shortened here: 469 characters; full line on GitHub]
    raf = requestAnimationFrame(frame); }
  function size() { if (!UI) return; var dpr = Math.min(3, window.devicePixelRatio || 1); cv.width = Math.round(UI.root.clientWidth * dpr); cv.height = Math.round(UI.root.clientHeight * dpr); g.setTransform(dpr, 0, 0, dpr, 0, 0); }
  function xy(e) { var r = cv.getBoundingClientRect(); return [e.clientX - r.left, e.clientY - r.top]; }
  // touch gestures on a touch screen: pinch = HOW MANY, two-finger twist = turn, long press = quiet time, double tap = REAL KUIPER
  function touchDown(e, x, y) { S.ptrs[e.pointerId] = [x, y]; var ids = Object.keys(S.ptrs), now = performance.now();
    if (ids.length === 2) { var a = S.ptrs[ids[0]], b = S.ptrs[ids[1]]; S.pinch = { d: Math.hypot(a[0] - b[0], a[1] - b[1]), ang: Math.atan2(a[1] - b[1], a[0] - b[0]), N: S.big ? S.big.N : Math.max(2, S.keys.length), deg: degPerKey(), moved: false }; if (S.hold) { clearTimeout(S.hold); S.hold = null; } S.drag = null; return true; }
    if (ids.length === 1) { if (now - S.lastTap < 300) { S.lastTap = 0; run('REAL'); return true; } S.lastTap = now; S.hold = setTimeout(function () { S.hold = null; if (S.ptrs[e.pointerId] && !S.pinch) { S.drag = null; run('NIGHT'); } }, 550); } return false; }
  function down(e) { gestured = true; musicSync(); S.wake = performance.now(); if (S.bloom) { bloomSkip(); chord(); return; } if (!S.wonder) S.intro = false; if (UI.btns.classList.contains('open')) { menuClose(); return; } if (S.wonder) { wonderSkip(); return; } var p = xy(e), x = p[0], y = p[1], ge = S.geom; if (!ge) return; e.preventDefault(); try { cv.setPointerCapture(e.pointerId); } catch (x0  … [line shortened here: 404 characters; full line on GitHub]
    if (tod()) { todDown(e, x, y); return; }
    if (e.pointerType === 'touch' && touchDown(e, x, y)) return;
    if (S.big) { var wx = (x - ge.cx) / ge.unit, wy = -(y - ge.cy) / ge.unit, hit = pickAt(wx, wy); if (hit) { S.bigSel = hit; S.work = 'KEY ' + fmt(hit.key) + ': DISTANCE ' + f2(hit.r) + ', TURN ' + f1(hit.deg) + ', X ' + f2(hit.x) + ', Y ' + f2(hit.y) + '. WORKED OUT FROM THE KEY ALONE.'; } magnify(x, y); if (hit) S.work = 'KEY ' + fmt(hit.key) + ': DISTANCE ' + f2(hit.r) + ', TURN ' + f1(hit.de  … [line shortened here: 553 characters; full line on GitHub]
    var best = -1, bd = 24; for (var i = 0; i < S.keys.length; i++) { var q = S.keys[i], d = Math.hypot(x - (ge.cx + q.x * ge.unit), y - (ge.cy - q.y * ge.unit)); if (d < bd) { bd = d; best = i; } }
    if (S.probe && Math.hypot(x - (ge.cx + S.probe.x * ge.unit), y - (ge.cy - S.probe.y * ge.unit)) < 26) { S.drag = 'probe'; return; }
    if (best >= 0) { S.sel = best; S.probe = null; S.playing = false; S.anim = null; S.drag = 'sel'; var q2 = S.keys[best], c = S.counts[q2.text]; S.cap = 'KEY ' + fmt(q2.key) + ':  ' + lineText(q2) + (c > 1 ? '   (SEEN ' + c + ' TIMES: ' + c + ' KEYS, ONE COLOUR)' : ''); S.work = working(q2, 1); setPlay(); tone(q2.r); moveRefresh(); hint('tap'); }
    else { var r = Math.hypot(x - ge.cx, y - ge.cy) / ge.unit; if (r <= S.scale * 1.02) { S.sel = -1; S.playing = false; probeAt(r, mod(Math.atan2(-(y - ge.cy), x - ge.cx) * 180 / Math.PI, 360)); S.drag = 'probe'; setPlay(); tone(r); hint('free'); } } }
  function pinchMove(e, p) { S.ptrs[e.pointerId] = p; var ids = Object.keys(S.ptrs); if (ids.length < 2 || !S.pinch) return; var a = S.ptrs[ids[0]], b = S.ptrs[ids[1]], d = Math.hypot(a[0] - b[0], a[1] - b[1]), ang = Math.atan2(a[1] - b[1], a[0] - b[0]), P = S.pinch;
    var ratio = d / Math.max(1, P.d), da = ang - P.ang; if (da > Math.PI) da -= PI2; if (da < -Math.PI) da += PI2;
    if (Math.abs(da) > 0.25 && !P.noTwist) { var nd = mod(P.deg - da * 180 / Math.PI * 0.5, 360); F.degrees = Math.round(nd * 100) / 100; P.moved = true; if (S.big) { S.big = { N: S.big.N, t: 1, view: S.big.view, viewFrom: S.big.view }; S.mag = null; S.bigSel = null; } reflow(); S.cap = 'TWIST: HOW FAR ROUND EACH TIME = ' + f2(F.degrees) + ' DEGREES.'; S.work = 'PRACTICE: REAL KUIPER PUTS IT BACK   … [line shortened here: 479 characters; full line on GitHub]
    else if (Math.abs(Math.log(ratio)) > 0.08) { var N = Math.round(Math.min(MAXN, Math.max(1, P.N * Math.pow(ratio, 6)))); P.moved = true; S.playing = false; S.big = { N: N, t: 1 }; S.mag = null; S.sel = -1; S.probe = null; S.cap = 'PINCH: HOW MANY = ' + fmt(N) + ' DOTS. RIM ' + fmt(sampleFor(N).rim) + '.'; S.work = 'THE AREA PER KEY NEVER CHANGES: PI AT EVERY SCALE. THE CIRCLE GROWS LIKE THE SQU  … [line shortened here: 575 characters; full line on GitHub]
  function move(e) { if (tod()) { var tp = xy(e); if (S.ptrs[e.pointerId]) S.ptrs[e.pointerId] = tp; if (S.pinch) { pinchMove(e, tp); return; } todMove(tp[0], tp[1]); return; }
    if (e.pointerType === 'touch' && S.ptrs[e.pointerId]) { var pp = xy(e); if (S.pinch) { pinchMove(e, pp); return; } var p0 = S.ptrs[e.pointerId]; if (S.hold && Math.hypot(pp[0] - p0[0], pp[1] - p0[1]) > 12) { clearTimeout(S.hold); S.hold = null; } }
    if (!S.drag || !S.geom) return; var p = xy(e), ge = S.geom, r = Math.max(0.05, Math.hypot(p[0] - ge.cx, p[1] - ge.cy) / ge.unit), dg = mod(Math.atan2(-(p[1] - ge.cy), p[0] - ge.cx) * 180 / Math.PI, 360);
    S.dragged = true; if (S.drag === 'probe') probeAt(r, dg);
    else if (S.drag === 'sel' && S.sel >= 0) { var o = S.keys[S.sel], th = dg * Math.PI / 180; o.r = Math.min(r, S.scale); o.deg = dg; o.x = o.r * Math.cos(th); o.y = o.r * Math.sin(th); o.moved = true; S.cap = 'KEY ' + fmt(o.key) + ' MOVED BY HAND: DISTANCE ' + f2(o.r) + ', TURN ' + f1(dg) + '. REAL KUIPER PUTS IT BACK.'; S.work = PREF.formula ? 'X = ' + f2(o.r) + ' x COS(' + f1(dg) + ') = ' + f2  … [line shortened here: 531 characters; full line on GitHub]
    if (!S.toneT || performance.now() - S.toneT > 90) { S.toneT = performance.now(); tone(r); } }
  function up(e) { if (tod()) todUp();
    if (S.dragged) { S.dragged = false; if (S.drag) celebrate('drag', 'YOU MOVED A DOT. THE RULE STILL KNOWS ITS TRUE PLACE.'); }
    if (S.drag === 'sel' && S.sel >= 0 && S.keys[S.sel] && S.keys[S.sel].moved) { var o = S.keys[S.sel]; if (o.trueX == null) { var tp = place(o.key); o.trueX = tp.x; o.trueY = tp.y; } moveRefresh(); hint('drag'); } S.drag = null;
    if (e && e.pointerId != null) { delete S.ptrs[e.pointerId]; if (Object.keys(S.ptrs).length < 2) S.pinch = null; if (S.hold) { clearTimeout(S.hold); S.hold = null; } } }
  function onKey(e) { if (!UI || MOD) return; if (S.bloom) { bloomSkip(); e.preventDefault(); e.stopImmediatePropagation(); return; } var inCmd = UI.cmd.classList.contains('open'), tag = (e.target && e.target.tagName) || '';
    if (e.key === 'Escape') { if (tag === 'INPUT' && e.target !== UI.cin) { e.stopImmediatePropagation(); e.target.blur(); return; } e.preventDefault(); e.stopImmediatePropagation(); if (UI.btns.classList.contains('open')) menuClose(); else if (UI.deep.classList.contains('open')) deepClose(); else if (tod()) todOff(); else if (inCmd) cmdClose(); else if (UI.fields.classList.contains('open')) UI.fi  … [line shortened here: 484 characters; full line on GitHub]
    // a typed box: run its Enter here (this capture listener fires before the box would see the key, so it must not swallow it)
    if (tag === 'INPUT' && e.target !== UI.cin) { if (e.key === 'Enter' && typeof e.target.onEnter === 'function') { e.preventDefault(); e.stopImmediatePropagation(); gestured = true; e.target.onEnter(); } else if (e.key === 'Escape') { e.stopImmediatePropagation(); e.target.blur(); } return; }
    if (inCmd) { if (e.key === 'Enter') { e.preventDefault(); e.stopImmediatePropagation(); var v = UI.cin.value.trim(); var hit = topHit(); run(!v ? hit : (hit && !/^[A-Za-z]+(\s|$)/.test(v) ? hit + ' ' + v : (hit && SENTENCES.some(function (c) { return c[0].toUpperCase() === v.toUpperCase(); }) ? hit : v))); } e.stopImmediatePropagation(); return; }
    if (e.key === '/') { e.preventDefault(); e.stopImmediatePropagation(); cmdOpen(); return; }
    if (e.key === ' ' || e.key === 'Enter') { e.preventDefault(); e.stopImmediatePropagation(); run(S.playing ? 'PAUSE' : 'PLAY'); return; }
    if (e.key === 'ArrowRight') { e.preventDefault(); e.stopImmediatePropagation(); step(); return; }
    if (e.key === 'ArrowUp' || e.key === '+') { e.preventDefault(); e.stopImmediatePropagation(); faster(1); return; } if (e.key === 'ArrowDown' || e.key === '-') { e.preventDefault(); e.stopImmediatePropagation(); faster(-1); return; }
    if (/^[A-Za-z0-9]$/.test(e.key)) { e.preventDefault(); e.stopImmediatePropagation(); cmdOpen(); UI.cin.focus(); UI.cin.value = e.key; filter(e.key); return; } }
  function open(opts) {
    if (UI) return; opts = opts || {}; var kgi = document.getElementById('kgi'); if (kgi && kgi.blur) kgi.blur();
    try { var pv = JSON.parse(localStorage.getItem('kg-sh-pref') || '{}'); if (pv.fs) PREF.fs = pv.fs; PREF.muted = !!pv.muted; if (root.KGAudio && PREF.muted) root.KGAudio.setMuted(true); PREF.formula = !!pv.formula; if (pv.lv >= 0 && pv.lv <= LEVERS.length) PREF.lv = pv.lv | 0; if (PALETTES[pv.pal]) PREF.pal = pv.pal; if (BYS.indexOf(pv.by) >= 0) PREF.by = pv.by; if (MOODS.indexOf(pv.mood) >= 0)  … [line shortened here: 565 characters; full line on GitHub]
    if (opts.level != null) PREF.lv = Math.max(0, Math.min(LEVERS.length, opts.level | 0));
    var st = document.getElementById('kg-start-here-css'); if (!st) { st = el('style'); st.id = 'kg-start-here-css'; st.textContent = CSS; document.head.appendChild(st); }
    var r = el('div', 'sh'); r.id = 'kg-start-here'; if (open.mount) { r.style.position = 'absolute'; r.style.height = '100%'; } (open.mount || document.body).appendChild(r); r.style.setProperty('--s', PREF.fs);
    cv = el('canvas'); r.appendChild(cv); g = cv.getContext('2d');
    var top = el('div', 'sh-top'), cap = el('div', 'sh-cap', ''), work = el('div', 'sh-work', ''), proof = el('div', 'sh-proof'); var proofTxt = el('div', 'sh-proof', ''), awe = el('div', 'sh-awe', ''); proof.innerHTML = '<span>' + PROOF + '</span>'; top.appendChild(cap); top.appendChild(work); top.appendChild(proofTxt); top.appendChild(awe); top.appendChild(proof); r.appendChild(top);
    var hintEl = el('div', 'sh-hint', ''); r.appendChild(hintEl);
    var lever = {}; function lv(name, e) { (lever[name] = lever[name] || []).push(e); return e; }
    function box(label, aria, onEnter, placeholder) { var pr = el('div', 'pr'), lb = el('label', '', label), inp = el('input'); inp.inputMode = 'decimal'; inp.setAttribute('aria-label', aria); if (placeholder) inp.placeholder = placeholder; inp.onEnter = function () { onEnter(inp.value); inp.blur(); }; inp.addEventListener('keydown', function (e) { e.stopPropagation(); if (e.key === 'Enter') { e.p  … [line shortened here: 543 characters; full line on GitHub]
    var btns = el('div', 'sh-btns'); var play = btn('PLAY', function () { run(S.playing ? 'PAUSE' : 'PLAY'); }, 'ph');
    btns.appendChild(btn('STEP', function () { run('STEP'); })); var nextBtn = btn('+ NEXT LEVER', function () { run('NEXT'); }); btns.appendChild(nextBtn);
    btns.appendChild(btn('FASTER', function () { run('FASTER'); }, 'x')); btns.appendChild(btn('SLOWER', function () { run('SLOWER'); }, 'x'));
    btns.appendChild(lv('SPREAD', btn('HOW IT SPREADS OUT', function () { run('SPREAD'); }))); btns.appendChild(lv('SHADOWS', btn('X/Y SHADOWS', function () { run('SHADOWS'); }))); btns.appendChild(lv('QUIET', btn('QUIET TIME', function () { run('NIGHT'); })));
    btns.appendChild(btn('/ SENTENCES', cmdOpen)); var fb = lv('REAL', btn('FIELDS', function () { run('FIELDS'); })); btns.appendChild(fb); var formulaBtn = null;
    var realBtn = lv('REAL', btn('REAL KUIPER', function () { run('REAL'); }, 'on')); btns.appendChild(realBtn);
    var coloursBtn = btn('COLOURS', function () { run('COLOURS'); }, 'sm x'); btns.appendChild(coloursBtn); var musicBtn = btn('MUSIC: ' + PREF.mood, function () { run('MUSIC'); }, 'sm x'); btns.appendChild(musicBtn);
    // THE TWO LEVERS, impossible to miss: big click buttons, no typing needed
    var hm = el('div', 'hm'); var hmBox = box('HOW MANY DOTS', 'how many dots', function (v) { setCount(parseFloat(String(v).replace(/,/g, ''))); }, '2'), hi = hmBox.input; hi.value = '2';
    hm.className = 'hm ph'; hm.appendChild(btn('/10', function () { setCount(Math.max(1, Math.round(countNow() / 10))); }, 'k ph')); hm.appendChild(btn('-1', function () { setCount(countNow() - 1); }, 'k')); hm.appendChild(hmBox); hm.appendChild(btn('+1', function () { setCount(countNow() + 1); }, 'k')); hm.appendChild(btn('x10', function () { setCount(countNow() * 10); }, 'k ph')); btns.appendChi  … [line shortened here: 407 characters; full line on GitHub]
    var tm = el('div', 'hm'); var dBox = box('TURN EACH TIME (DEGREES)', 'degrees per key', function (v) { v.trim() === '' ? turnTo(null) : run('TURN BY SET ' + v); }, '222.49');
    tm.className = 'hm ph'; tm.appendChild(btn('-10', function () { turnTo(degPerKey() - 10); }, 'k ph t')); tm.appendChild(btn('-1', function () { turnTo(degPerKey() - 1); }, 'k')); tm.appendChild(dBox); tm.appendChild(btn('+1', function () { turnTo(degPerKey() + 1); }, 'k')); tm.appendChild(btn('+10', function () { turnTo(degPerKey() + 10); }, 'k ph t'));
    tm.appendChild(btn('TURN', turnNext, 'k')); tm.appendChild(btn('90', function () { turnTo(90); }, 'k')); tm.appendChild(btn('120', function () { turnTo(120); }, 'k x')); tm.appendChild(btn('137.5', function () { turnTo(137.507764); }, 'k x')); tm.appendChild(btn('222.49 REAL', function () { turnTo(null); }, 'k rl')); btns.appendChild(tm);
    var tip = el('div', 'tip', TIP); btns.appendChild(tip); awe = tip; top.removeChild(top.querySelector('.sh-awe'));
    var muteBtn = btn(PREF.muted ? 'SOUND ON' : 'MUTE', function () { run('MUTE'); }, 'sm x'); btns.appendChild(muteBtn); btns.appendChild(btn('A+', function () { scaleText(1); }, 'sm')); btns.appendChild(btn('A-', function () { scaleText(-1); }, 'sm'));
    var todBtn = btn('TOUCH', todOn, 'round ph hero'); todBtn.setAttribute('aria-label', 'Touch mode'); btns.appendChild(todBtn); var todSay = el('div', 'tip hero', 'TOUCH: PLAY BY TOUCH. DEEP: THE WHOLE LAW.'); btns.appendChild(todSay);
    var deepBtn = btn('DEEP', deepOpen, 'hero2'); btns.appendChild(deepBtn); var mods = el('div', 'sh-mods'); btns.appendChild(mods);
    // V5 DOWNLOAD AND RUN OFFLINE: the whole folder runs with the network off. The zip link shows only when learn-the-kuiper.zip is really there (asked over http only; never from file://).
    var off = el('div', 'sh-off'), offA = el('a', '', 'DOWNLOAD AND RUN OFFLINE'); offA.href = 'learn-the-kuiper.zip'; offA.setAttribute('download', 'learn-the-kuiper.zip'); off.appendChild(offA); off.appendChild(el('div', '', 'THIS WHOLE GAME RUNS OFFLINE: KEEP THE FOLDER, OPEN INDEX.HTML, NO NETWORK NEEDED.')); btns.appendChild(off);
    try { if (/^https?:$/.test(location.protocol) && window.fetch) fetch('learn-the-kuiper.zip', { method: 'HEAD' }).then(function (rs) { if (rs && rs.ok) offA.classList.add('have'); }).catch(function () {}); } catch (e0) {} var moreBtn = btn('MORE', function () { btns.classList.toggle('more'); moreBtn.textContent = btns.classList.contains('more') ? 'LESS' : 'MORE'; }, 'sm ph sh-more'); btns.appen  … [line shortened here: 547 characters; full line on GitHub]
    // the one floating row: PLAY, /10, x10, TURN, MENU. Dim outlines until touched. In landscape it splits to the two bottom corners, clear of the circle.
    var bar = el('div', 'sh-bar'); play.className = ''; bar.appendChild(play); bar.appendChild(el('div', 'gap')); bar.appendChild(btn('MENU', function () { if (UI.btns.classList.contains('open')) menuClose(); else menuOpen(); })); r.appendChild(bar);
    // V5 the mission, stated as the mission. A tap opens SOLAR STRINGS.
    var mission = btn('', function () { if (!modOpen('strings')) hint('SOLAR STRINGS IS NOT LOADED HERE.', true); }, 'sh-mission'); mission.innerHTML = '<span>MISSION:</span> 75 TWp<br>OF SOLAR BY 2050'; mission.setAttribute('aria-label', 'Mission: 75 TWp of solar by 2050. Open solar strings.'); r.appendChild(mission);
    // V9 the SOUND readout (audio-unlock.js): SOUND ON only when a tracked AudioContext is running; a tap is the gesture that unlocks it
    var soundEl = btn('TAP FOR SOUND', function () { if (PREF.muted) run('MUTE'); }, 'sh-sound'); soundEl.setAttribute('aria-label', 'sound'); r.appendChild(soundEl);
    // the touch sheet: a big X, and three round buttons (PLAY pours the particles in, + and - grow and shrink)
    var xBtn = btn('X', todOff, 'sh-x'); xBtn.setAttribute('aria-label', 'leave touch mode'); r.appendChild(xBtn);
    var tb = el('div', 'sh-tb'); var tMinus = btn('-', function () { setCount(Math.max(1, Math.round(countNow() / 10))); happy(0); }, 'round big'), tPlay = btn('PLAY', function () { if (S.big) { S.big = null; setCount(60); } run(S.playing ? 'PAUSE' : 'PLAY'); S.sel = -1; happy(1); }, 'round'), tPlus = btn('+', function () { setCount(countNow() * 10); happy(0); }, 'round big'); tb.appendChild(tMinu  … [line shortened here: 468 characters; full line on GitHub]
    var deep = el('div', 'sh-deep'), deepBar = el('div', 'b'), deepBody = el('div', 'body'); deepBar.appendChild(btn('CLOSE', deepClose)); deepBar.appendChild(btn('REAL KUIPER', function () { run('REAL'); deepClose(); })); deep.appendChild(deepBar); deep.appendChild(deepBody); r.appendChild(deep);
    var cmd = el('div', 'sh-cmd'), h = el('div', 'h', 'CHOOSE A SENTENCE, OR TYPE ONE BELOW. ENTER RUNS IT. ESC CLOSES.'), rows = el('div', 'rows'), nt = el('div', 'note'), lg = el('div', 'log', ''), cin = el('input');
    cin.placeholder = 'TYPE A SENTENCE OR A COMMAND'; cin.autocomplete = 'off'; cin.spellcheck = false; cin.setAttribute('aria-label', 'command');
    cmd.appendChild(h); cmd.appendChild(rows); cmd.appendChild(nt); cmd.appendChild(lg); cmd.appendChild(cin); r.appendChild(cmd);
    cin.addEventListener('input', function () { nt.style.display = 'none'; rows.style.display = 'block'; filter(cin.value); });
    // the fields panel: every number of the law, labelled, typeable
    var fp = el('div', 'sh-fields'), fh = el('div', 'h', 'THE FIELDS OF THE LAW. TYPE A NUMBER, PRESS ENTER. ANY VALUE IS ALLOWED.'), mode = el('div', 'mode', 'REAL KUIPER'); fp.appendChild(fh); fp.appendChild(mode);
    var fieldInputs = {}, fieldCur = {};
    FIELDS.forEach(function (f) { var row = el('div', 'row'), lab = el('label', '', f[1] + (REAL[f[0]] !== null ? '  (REAL ' + fmt(REAL[f[0]]) + (String(REAL[f[0]]).indexOf('.') >= 0 ? ' = ' + REAL[f[0]] : '') + ')' : '  (REAL: FROM THE TURN NUMBER)')), inp = el('input'), cur = el('div', 'cur', ''); inp.inputMode = 'decimal'; inp.setAttribute('aria-label', f[1]);
      inp.onEnter = function () { run('FIELD ' + f[0] + ' ' + (inp.value.trim() === '' ? 'REAL' : inp.value)); }; inp.addEventListener('keydown', function (e) { e.stopPropagation(); if (e.key === 'Enter') { e.preventDefault(); inp.onEnter(); } }); inp.addEventListener('change', function () { inp.onEnter(); }); row.appendChild(lab); row.appendChild(inp); row.appendChild(cur); fp.appendChild(row); f  … [line shortened here: 449 characters; full line on GitHub]
    // move the selected dot by typing (practice): X and Y, or DISTANCE and ANGLE; its true place stays marked
    var mvKey = el('div', 'mode', 'TAP A DOT, THEN MOVE IT BY TYPING'), mv = {}; fp.appendChild(mvKey);
    [['x', 'X (FLOOR SHADOW)'], ['y', 'Y (WALL SHADOW)'], ['r', 'DISTANCE FROM THE CENTRE'], ['deg', 'ANGLE (DEGREES FROM 3 O\'CLOCK, ANTICLOCKWISE)']].forEach(function (m) { var row = el('div', 'row'), lab = el('label', '', m[1]), inp = el('input'); inp.inputMode = 'decimal'; inp.setAttribute('aria-label', m[1]);
      inp.onEnter = function () { var v = parseFloat(inp.value.replace(/,/g, '')); if (!isFinite(v)) return; run(m[0] === 'x' || m[0] === 'y' ? 'MOVE XY ' + (m[0] === 'x' ? v : parseFloat(mv.x.value)) + ' ' + (m[0] === 'y' ? v : parseFloat(mv.y.value)) : 'MOVE POLAR ' + (m[0] === 'r' ? v : parseFloat(mv.r.value)) + ' ' + (m[0] === 'deg' ? v : parseFloat(mv.deg.value))); };
      inp.addEventListener('keydown', function (e) { e.stopPropagation(); if (e.key === 'Enter') { e.preventDefault(); inp.onEnter(); } }); row.appendChild(lab); row.appendChild(inp); fp.appendChild(row); mv[m[0]] = inp; });
    var fbRow = el('div', 'b'); fbRow.appendChild(btn('REAL KUIPER', function () { run('REAL'); })); fbRow.appendChild(btn('HIDE', function () { fp.classList.remove('open'); })); fp.appendChild(fbRow); r.appendChild(fp);
    UI = { root: r, cap: cap, work: work, proofTxt: proofTxt, awe: awe, top: top, btns: btns, play: play, cmd: cmd, cin: cin, rows: rows, note: nt, log: lg, fields: fp, fieldInputs: fieldInputs, fieldCur: fieldCur, mode: mode, realBtn: realBtn, formulaBtn: formulaBtn, muteBtn: muteBtn, howmany: hi, degBox: dBox.input, hint: hintEl, lever: lever, nextBtn: nextBtn, coloursBtn: coloursBtn, musicBtn:   … [line shortened here: 593 characters; full line on GitHub]
    setReal(); S = null; reset(); S.intro = true; modsSync(); fieldsRefresh(); setPlay(); applyLevel(); applyPalette(); moveRefresh(); if (S.log.length) lg.textContent = S.log.join('\n');
    cv.addEventListener('wheel', function (e) { e.preventDefault(); if (!S || S.bloom || MOD) return; S.wheelAcc = (S.wheelAcc || 0) + e.deltaY; var now = performance.now(); if (now - (S.wheelT || 0) < 120) return; S.wheelT = now; var f = Math.pow(1.0025, -S.wheelAcc); S.wheelAcc = 0; var n0 = countNow(), n1 = Math.round(n0 * f); if (n1 === n0) n1 = n0 + (f > 1 ? 1 : -1); setCount(Math.max(1, Math  … [line shortened here: 441 characters; full line on GitHub]
    cv.addEventListener('pointerdown', down); cv.addEventListener('pointermove', move); cv.addEventListener('pointerup', up); cv.addEventListener('pointercancel', up);
    window.addEventListener('keydown', onKey, true); window.addEventListener('resize', size); window.addEventListener('orientationchange', size); size(); lastT = 0; raf = requestAnimationFrame(frame);
    if (!opts.quiet) bloomStart();   // V5: the opening moment (6 s, any tap skips). WONDER stays a sentence.
  }
  function close() { if (!UI) return; if (MOD) modDone(MOD); if (MUS.timer) { clearInterval(MUS.timer); MUS.timer = null; } cancelAnimationFrame(raf); window.removeEventListener('keydown', onKey, true); window.removeEventListener('resize', size); window.removeEventListener('orientationchange', size); if (UI.root.parentNode) UI.root.parentNode.removeChild(UI.root); UI = null; cv = null; g = null; i  … [line shortened here: 460 characters; full line on GitHub]
  // the front door of the game: on its title screen Enter, space or a tap opens START HERE (capture phase, the engine never sees it)
  function titleHook(e) { if (UI) return; var KG = root.KG; if (!KG || !KG.state || KG.state.mode !== 'title') return;
    if (e.type === 'keydown') { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); e.stopImmediatePropagation(); gestured = true; open(); } return; }
    var k = document.getElementById('kg'); if (k && e.target === k) { e.preventDefault(); e.stopImmediatePropagation(); gestured = true; open(); } }
  if (typeof window !== 'undefined') { window.addEventListener('keydown', titleHook, true); window.addEventListener('pointerdown', titleHook, true); }
  setReal();
  root.KGStartHere = { open: open, close: close, run: run, lines: LINES, placeReal: placeReal, place: place, fields: F, real: REAL, setReal: setReal, measure: measure, sentences: SENTENCES, state: function () { return S; }, degPerKey: DEG_PER_KEY, proof: PROOF, toddler: todOn, leaveToddler: todOff, deep: deepOpen, closeDeep: deepClose, sample: sampleFor, menu: menuOpen, closeMenu: menuClose, count  … [line shortened here: 739 characters; full line on GitHub]
  if (typeof module !== 'undefined' && module.exports) module.exports = root.KGStartHere;
})(typeof window !== 'undefined' ? window : globalThis);