GLOBALGRID2050 / EXPLORE CODE

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

Play and 2 more files (part 2)

A JavaScript module in the learn the kuiper folder of Kuiper Belt that adds rat (`addRat`), steps dec (`stepDec`), snaps to (`snapTo`) and calculates planar distances and angles (units: kV).

700 lines of JavaScript and HTML from kuiper-belt, in 3 files. Topic: Kuiper, cosmos and drawing engines. Section 1537 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. One geodesy · kuiper-belt / learn-the-kuiper/202610050609/one.js lines 1091–1166
  2. Play render · kuiper-belt / learn-the-kuiper/202610050609/play.html lines 1–10
  3. Play render · kuiper-belt / learn-the-kuiper/202610050609/play.js lines 1–614

One

A JavaScript file in the learn the kuiper folder of Kuiper Belt that parses dec (`parseDec`) and whole (`parseWhole`), makes game (`makeGame`), calculates planar distances and draws on a canvas.

geodesykuiper-belt / learn-the-kuiper/202610050609/one.js · lines 1091–1166 of 1166 · version 2026-10-05 06:09 (continued from section 1535) · Not reached from any entry point (candidate for review) · pattern cellCentre (shared by 2 files)

What it does
It draws its content. Defines 94 functions or classes, including isqrt, stepOf, modParts, sectorOf, pad. Uses libraries modules/realgame-data.js. Side effects: changes the web page (DOM).
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).
Inputs & outputs
Out: canvas drawing; SVG drawing.
What it achieves
It parses dec (`parseDec`), parses whole (`parseWhole`) and turns text (`turnText`). One circle, one dot, two numbers. It responds to webglcontextlost, mousedown and keydown events.
Why it matters
No other file in the estate was found to import it.
Application
kuiper-belt · learn-the-kuiper/202610050609 · script
VEDIC
LOCATE CELL CENTRE (GG2050-VEDIC-000079): Ventus Grid Engine · Geospatial and terrain intelligence. tile, col, row → Projected easting and northing pair.
Uses
modules/realgame-data.js
Used by
none found
Produces
isqrt, stepOf, modParts, sectorOf, pad, D, dText, dFloor, dNum, dEq, dCmpSqT, dAddTenths
Defines here
end, place, ptrEnd
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/one.js:1091-1166 · blob f6214a855d22573b499d83e2763778f71179f08f · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
      if (Math.abs(e.clientY - s.y) > 3) { clearTimeout(s.timer); s.timer = setTimeout(still, 2000); }
      s.v = s.v * 0.6 + vy * 0.4; s.y = e.clientY; s.t = now;
      var dy = s.y0 - e.clientY;
      if (!s.rolling && Math.abs(dy) > 8) s.rolling = true;
      if (!s.rolling) return;
      var n = dy < 0 ? Math.ceil(dy / STEP_PX) : Math.floor(dy / STEP_PX), dn = n - s.applied;
      if (dn) { s.applied = n; game.roll(which, dn, s.fine); rollTick(r, dn); }
    });
    function end(e) {
      if (!s || (e && e.pointerId !== s.id)) return;
      clearTimeout(s.timer); r.classList.remove('k1-fine');
      var me = s; s = null;
      if (me.rolling) {
        var idle = performance.now() - me.t;
        if (e && e.type === 'pointerup' && Math.abs(me.v) > 0.35 && idle < 80) mom = { which: which, rate: Math.max(-0.09, Math.min(0.09, me.v / STEP_PX)), acc: 0, fine: me.fine };
        else settleSoon(160);
        return;
      }
      if (!e || e.type !== 'pointerup') return;
      // a tap: on [M] or [C] in the heading, the keypad goes to that number; on the working of a long product, all of it shows
      var bx = r.box.getBoundingClientRect(), st = game.state();
      if (me.f) { game.select(st.sel === me.f ? 'B' : me.f); setPad(true); return; }
      if (me.more && (showFull || r.work.querySelector('.k1-more'))) { showFull = !showFull; render(); layout(); return; }
      // just above or below the box steps by one; on the number, the keypad opens to type it exactly
      if (e.clientY < bx.top - 1 && e.clientY > bx.top - 30 && Math.abs(e.clientX - (bx.left + bx.width / 2)) < bx.width / 2 + 12) { nudge(which, 1); return; }
      if (e.clientY > bx.bottom + 1 && e.clientY < bx.bottom + 30 && Math.abs(e.clientX - (bx.left + bx.width / 2)) < bx.width / 2 + 12) { nudge(which, -1); return; }
      var same = st.sel === which || (st.linked && (st.sel === 'A' || st.sel === 'B'));
      if (padOpen && same && st.buf === null) { setPad(false); return; }
      if (!same || st.buf !== null) game.select(which);
      setPad(true);
    }
    r.addEventListener('pointerup', end); r.addEventListener('pointercancel', end);
    r.addEventListener('wheel', function (e) { e.preventDefault(); nudge(which, e.deltaY < 0 ? 1 : -1); }, { passive: false });
  }
  rollerEvents(rA); rollerEvents(rB);

  // the circle: a tap puts the keypad away; press and hold sets a target there
  var ptr = null;
  function place(e) {
    var b = canvas.getBoundingClientRect(), x = e.clientX - b.left, y = e.clientY - b.top, sc = cv.R / Math.exp(view.lrv);
    var dx = x - cv.w / 2, dy = cv.h / 2 - y, turn = Math.atan2(dy, dx) / (2 * Math.PI);
    return { x: x, y: y, r: Math.hypot(dx, dy) / sc, turn: turn < 0 ? turn + 1 : turn };
  }
  canvas.addEventListener('pointerdown', function (e) {
    e.preventDefault(); audio();
    try { canvas.setPointerCapture(e.pointerId); } catch (err) {}
    var p = place(e), now = performance.now();
    ptr = { id: e.pointerId, x: p.x, y: p.y, moved: false, held: false, timer: 0 };
    if (p.r <= Math.exp(view.lrv) && p.r >= 1) {
      fx.hold = { x: p.x, y: p.y, t: now };
      var me = ptr; ptr.timer = setTimeout(function () { if (ptr !== me || me.moved) return; me.held = true; fx.hold = null; stopRoll(); game.setTargetAt(p.r, p.turn); }, 550);
    }
  });
  canvas.addEventListener('pointermove', function (e) {
    if (!ptr || e.pointerId !== ptr.id || ptr.held || ptr.moved) return;
    var p = place(e);
    if (Math.hypot(p.x - ptr.x, p.y - ptr.y) < 10) return;
    ptr.moved = true; clearTimeout(ptr.timer); fx.hold = null;
  });
  function ptrEnd(e) {
    if (!ptr || (e && e.pointerId !== ptr.id)) return;
    clearTimeout(ptr.timer); fx.hold = null;
    if (e && e.type === 'pointerup' && !ptr.held && !ptr.moved && padOpen) { if (game.state().buf !== null) game.select(game.state().sel); setPad(false); }
    ptr = null;
  }
  canvas.addEventListener('pointerup', ptrEnd); canvas.addEventListener('pointercancel', ptrEnd);
  document.addEventListener('contextmenu', function (e) { e.preventDefault(); });

  // ---------------------------------------------------------------- start
  window.addEventListener('resize', layout);
  window.addEventListener('orientationchange', function () { setTimeout(layout, 60); });
  if (window.ResizeObserver) new ResizeObserver(function () { sizeCanvas(); }).observe(stageEl);
  game.restore(query);
  if (document.fonts && document.fonts.ready) document.fonts.ready.then(function () { layout(); });
  requestAnimationFrame(function (t) { lastT = t; view.lrv = view.target; draw(t); });
})(typeof window === 'object' ? window : globalThis);

Play

A web page in the learn the kuiper folder of Kuiper Belt. Published at https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050609/play.html.

renderkuiper-belt / learn-the-kuiper/202610050609/play.html · lines 1–10 of 10 · version 2026-10-05 06:09 · Entry point

What it does
It draws its content. Side effects: changes the web page (DOM).
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).
Inputs & outputs
Out: web page.
Downstream impact
Used directly by 1 file: Menu (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050354/menu.html). Reached from 2 other entry points, including Lesson (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050609/lesson.html); Solid (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050609/solid.html). It is itself an entry point, published at https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050609/play.html.
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
Loaded by the Menu page at https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050354/menu.html.
Application
kuiper-belt · learn-the-kuiper/202610050609 · page
Uses
Audio Unlock (script src), Play (script src), Menu (link)
Used by
linked from Menu (link)
Produces
none declared
Defines here
none
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/play.html:1-10 · blob 18183f6d05512bce7075efc8fda09a5e1ba2bc99 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: agent_infra · users: ai_agent · canonical: unknown
<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"><meta name="color-scheme" content="dark"><title>Learn the Kuiper</title>
<style>html,body{margin:0;height:100%;background:#000;overflow:hidden;overscroll-behavior:none}body,#host{position:fixed;inset:0;touch-action:none}</style></head>
<body><div id="host"></div><script src="audio-unlock.js"></script><script src="play.js"></script><script>
var q=new URLSearchParams(location.search),o={standalone:true,hash:false};
if(q.has('rung'))o.rung=+q.get('rung');if(q.has('find'))o.find=q.get('find')!=='0';if(q.has('seed'))o.seed=+q.get('seed');if(q.has('calm'))o.reducedMotion=q.get('calm')!=='0';
KGPlay.open(document.getElementById('host'),o);
</script><style>#host{top:40px!important}.kgm{position:fixed;left:0;top:0;height:40px;display:flex;align-items:center;padding:0 12px;z-index:60;font:400 24px/1 "Segoe UI",system-ui,-apple-system,Arial,sans-serif;color:rgba(255,255,255,.75);text-decoration:none;letter-spacing:.04em}</style>
<a class="kgm" href="menu.html">MENU</a>
</body></html>

Play

A JavaScript module in the learn the kuiper folder of Kuiper Belt that adds rat (`addRat`), steps dec (`stepDec`), snaps to (`snapTo`) and calculates planar distances and angles (units: kV).

renderkuiper-belt / learn-the-kuiper/202610050609/play.js · lines 1–614 of 1722 · version 2026-10-05 06:09 · Entry point · pattern exportState (shared by 2 files)

What it does
It draws wind. Defines 156 functions or classes, including divmod, ratio, addRat, mulRat, ratText. Side effects: changes the web page (DOM); reads or writes files.
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: wind.
Inputs & outputs
Out: canvas drawing; SVG drawing.
Downstream impact
Used directly by 1 file: Play (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050609/play.html). Reached from 3 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); Solid (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050609/solid.html).
What it achieves
It adds rat (`addRat`), parses one (`parseOne`) and opens editor (`openEditor`). `play.js` LEARN THE KUIPER: place a dot with numbers. It responds to click, pointerdown and pointerup events.
Why it matters
Loaded by the page of the same name at https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050609/play.html.
Application
kuiper-belt · learn-the-kuiper/202610050609 · JavaScript module
Uses
none found
Used by
loaded by Play (script src)
Produces
divmod, ratio, addRat, mulRat, ratText, exact, mod, circles, clean, r9, parseOne, parse
Defines here
divmod, ratio, addRat, mulRat, ratText, exact, mod, circles, clean, r9, parseOne, parse, group, plain, fmt, decimalsOf, niceDown, niceUp, stepDec, snapTo, check, css, E, create, show, token, part, sweep, chip, stepFor
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/play.js:1-614 · blob e238ce0b975aa329e9d9faa4a5413541775d5a8d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: agent_infra · users: ai_agent · canonical: unknown
// play.js  LEARN THE KUIPER: place a dot with numbers.
// Rungs 1 DOT, 2 DOTS, RING, TIME on one canvas; FIND; the formula line, keypad and number chips (window.KGFormula).
// Plain script, no build step, works from file:// with no network. Loads in Node for the truth test (module.exports).
// Every position is the formula on screen: angle = 360 x MOD(number, d) / d degrees anticlockwise from 3 o'clock,
// x = distance x cos(angle), y = distance x sin(angle), y up on screen.
(function (root) {
  'use strict';

  // ------------------------------------------------------------------ the numbers of FIND, in one place.
  // window.KGPlayTuning (gpu/trillion/play-tuning.js, when it is there) replaces any of these; they are the defaults.
  var TUNING = {
    // target sizes, one level after another: a piece of a ring this many degrees wide and this deep
    levels: [
      { angleDeg: 30, distance: 1, digits: 0 },
      { angleDeg: 10, distance: 0.3, digits: 0 },
      { angleDeg: 3, distance: 0.1, digits: 0 },
      { angleDeg: 1, distance: 0.03, digits: 0 },
      { angleDeg: 0.1, distance: 0.01, digits: 1 },
      { angleDeg: 0.01, distance: 0.001, digits: 2 }
    ],
    equalArea: true,       // a target keeps the same area wherever it sits: wider in angle near the centre, narrower far out
    refDistance: 3,        // the distance at which a level is exactly angleDeg wide
    warmth: { curve: 'log', width: 1, steps: 0 },   // the light: 'log' (one step per ten times closer), 'inv' or 'exp'
    lights: 2,             // 2 = the dot warms and the target answers; 1 = the dot only
    typedPair: true,       // after exploring, two different numbers must be typed before a find is rewarded
    triesBand: [2, 4],     // found within this many typed tries: the biggest burst; the middle burst
    findOnOpen: true       // the first screen already has a target glowing
  };
  var LIMIT = 9007199254740991;
  var LIMIT_TEXT = 'THAT NUMBER IS TOO LARGE FOR THIS COMPUTER TO SHOW. THE REAL LIMIT HERE IS 9,007,199,254,740,991.';
  var FONT = '"Segoe UI",system-ui,-apple-system,"Helvetica Neue",Arial,sans-serif';
  var RAD = Math.PI / 180, TAU = Math.PI * 2;
  var CAP = 6000;                       // most dots drawn in one frame; larger counts draw a fair sample
  var PIPS = ['1 DOT', '2 DOTS', 'RING', 'TIME', 'KUIPER'];

  // ------------------------------------------------------------------ the maths (pure; used by the page and by the test)
  // MOD as a spreadsheet gives it: the result has the sign of the divisor, never -0.
  // circles = FLOOR(number / d), remainder = number - circles x d, 0 <= remainder < d. Decimals are worked as typed:
  // both numbers are scaled to whole numbers first when they are decimals of up to nine places (0.3 on a circle of
  // 0.1 leaves 0), so the binary form of a decimal never leaks into the remainder.
  var DM = { m: 0, q: 0 }, P10 = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9];
  function divmod(a, c) {
    var k, s, A, C, ra, rc, m;
    if (Number.isSafeInteger(a) && Number.isSafeInteger(c) && c > 0) { var ba = BigInt(a), bc = BigInt(c), bm = ((ba % bc) + bc) % bc; DM.m = Number(bm); DM.q = Number((ba - bm) / bc); return DM; }
    for (k = 1; k < 10; k++) {
      s = P10[k]; A = a * s; C = c * s; ra = Math.round(A); rc = Math.round(C);
      if (Math.abs(A) > 9007199254740991 || C > 9007199254740991) break;
      if (Math.abs(A - ra) <= 4.5e-16 * Math.abs(A) && Math.abs(C - rc) <= 4.5e-16 * C && rc > 0) { m = ra % rc; if (m < 0) m += rc; DM.m = m / s + 0; DM.q = (ra - m) / rc + 0; return DM; }
    }
    m = a % c; if (m < 0) m += c; if (m >= c) m = 0;
    DM.m = m + 0; DM.q = Math.round((a - m) / c) + 0; return DM;
  }
  function ratio(v) {
    var t = String(v), z = /^([+-]?)(\d+)(?:\.(\d*))?(?:e([+-]?\d+))?$/i.exec(t);
    if (!z) return null;
    var k = (z[3] || '').length - Number(z[4] || 0), n = BigInt(z[2] + (z[3] || '')) * (z[1] === '-' ? -1n : 1n);
    return k < 0 ? { n: n * 10n ** BigInt(-k), d: 1n } : { n: n, d: 10n ** BigInt(k) };
  }
  function addRat(a,b) { return { n: a.n*b.d+b.n*a.d, d:a.d*b.d }; }
  function mulRat(a,b) { return { n:a.n*b.n, d:a.d*b.d }; }
  function ratText(a) {
    var n=a.n, d=a.d, neg=n<0n, out; if(neg)n=-n;
    out=String(n/d); n%=d;
    if(n) { out+='.'; for(var i=0;n && i<340;i++) { n*=10n; out+=String(n/d); n%=d; } }
    return (neg?'-':'')+out;
  }
  function exact(p,n) {
    var a=ratio(p.start), c=ratio(p.mod), term={n:0n,d:1n};
    if(!a || !c || c.n<=0n)return null;
    if(p.rung>=2) { term=mulRat(ratio(n),ratio(p.turn)); a=addRat(a,term); }
    if(p.rung>=4) a=addRat(a,mulRat(ratio(p.t),ratio(p.speed)));
    var num=a.n*c.d, den=a.d*c.n, q=num/den; if(num%den<0n)q--;
    var rem={n:a.n*c.d-q*c.n*a.d,d:a.d*c.d};
    return {raw:ratText(a), q:String(q), m:ratText(rem), product:ratText(term)};
  }
  function mod(a, c) { return divmod(a, c).m; }
  // whole circles thrown away: circles x c + mod = a
  function circles(a, c) { return divmod(a, c).q; }
  function clean(v) { return v === 0 ? 0 : v; }

  var IN = { x: 0, y: 0, d: 0, deg: 0 };
  function r9(v) { return Math.round(v * 1e9) / 1e9; }
  var M = {
    mod: mod, circles: circles, divmod: divmod, exact: exact,
    // how many dots the formula on this rung places
    count: function (p) {
      if (p.rung <= 1) return 1; if (p.rung === 2) return 2;
      var n = Math.floor(p.count);
      if (p.rung >= 4) { var e = Math.floor(p.t * p.newDots); if (e > 0) n += e; }
      return n > 0 ? n : 0;
    },
    // the number inside MOD( ... ) for dot n
    raw: function (p, n) { var a = p.start; if (p.rung >= 2) a += n * p.turn; if (p.rung >= 4) a += p.t * p.speed; return a; },
    // distance never goes below 0: it stops at the centre
    dist: function (p, n) { var d = p.dist; if (p.rung >= 2) d += n * p.step; if (p.rung >= 4) d += p.t * p.grow; return d > 0 ? d : 0; },
    deg: function (p, n) {
      var raw=M.raw(p,n), product=p.rung>=2?n*p.turn:0, time=p.rung>=4?p.t*p.speed:0;
      if(Number.isSafeInteger(p.start) && Number.isSafeInteger(p.mod) &&
         (p.rung<2 || Number.isSafeInteger(n) && Number.isSafeInteger(p.turn) && Number.isSafeInteger(product)) &&
         (p.rung<4 || Number.isSafeInteger(p.t) && Number.isSafeInteger(p.speed) && Number.isSafeInteger(time)) &&
         Number.isSafeInteger(p.start+product) && Number.isSafeInteger(raw)) {
        var rem=raw%p.mod; if(rem<0)rem+=p.mod; return rem*(360/p.mod);
      }
      var e=exact(p,n); return (e ? Number(e.m) : mod(raw,p.mod)) * (360 / p.mod);
    },
    place: function (p, n, out) {
      var deg = M.deg(p, n), d = M.dist(p, n), r = deg * RAD;
      out.deg = deg; out.d = d; out.x = clean(d * Math.cos(r)); out.y = clean(d * Math.sin(r));
      return out;
    },
    // the drag inverse: which numbers put dot n exactly on the point (x, y). Dot 0 changes START and DISTANCE;
    // any later dot changes TURN and STEP. The angle moves the short way round from where the dot is now.
    inverse: function (p, n, x, y, out) {
      var d = Math.sqrt(x * x + y * y), deg = Math.atan2(y, x) / RAD; if (deg < 0) deg += 360;
      var u = deg * (p.mod / 360), A = M.raw(p, n), dl = u - mod(A, p.mod), h = p.mod / 2;
      if (dl > h) dl -= p.mod; else if (dl <= -h) dl += p.mod;
      if (d === 0) dl = 0;                                   // the centre has every angle: keep the one it had
      var tg = p.rung >= 4 ? p.t * p.grow : 0;
      out.start = p.start; out.dist = p.dist; out.turn = p.turn; out.step = p.step;
      if (n === 0 || p.rung < 2) { out.start = p.start + dl; out.dist = d - tg > 0 ? d - tg : 0; }
      else { out.turn = p.turn + dl / n; out.step = (d - p.dist - tg) / n; }
      return out;
    },
    // the six numbers of a point (x, y) on a circle of c steps. At the centre the angle is the one handed in.
    six: function (x, y, c, keepDeg, out) {
      var d = Math.sqrt(x * x + y * y), deg;
      if (d === 0) deg = keepDeg || 0; else { deg = Math.atan2(y, x) / RAD; if (deg < 0) deg += 360; if (deg >= 360) deg = 0; }
      out.d = d; out.sq = d * d; out.area = Math.PI * d * d; out.deg = deg + 0; out.rem = deg * (c / 360) + 0; out.x = clean(x); out.y = clean(y);
      return out;
    },
    // type one of them: the point it gives. which: 'd','sq','area','deg','rem','x','y'; pt = {x, y, deg (kept angle)}.
    fromSix: function (which, v, pt, c, out) {
      var d = Math.sqrt(pt.x * pt.x + pt.y * pt.y), deg = d === 0 ? (pt.deg || 0) : Math.atan2(pt.y, pt.x) / RAD, x = pt.x, y = pt.y, polar = true;
      if (deg < 0) deg += 360;
      if (which === 'd') d = v < 0 ? 0 : v;
      else if (which === 'sq') d = v < 0 ? 0 : Math.sqrt(v);
      else if (which === 'area') d = v < 0 ? 0 : Math.sqrt(v / Math.PI);
      else if (which === 'deg') deg = mod(v, 360);
      else if (which === 'rem') deg = mod(v, c) * (360 / c);
      else { polar = false; if (which === 'x') x = v; else y = v; }
      if (polar) { x = clean(d * Math.cos(deg * RAD)); y = clean(d * Math.sin(deg * RAD)); }
      else { d = Math.sqrt(x * x + y * y); if (d > 0) { deg = Math.atan2(y, x) / RAD; if (deg < 0) deg += 360; } }
      out.x = x; out.y = y; out.d = d; out.deg = deg + 0;
      return out;
    },
    // is a point inside a target? Tested in the target's own coordinates, lower edge in, upper edge out.
    // polar target: a piece of a ring, centre (deg, d), widths (wdeg, wd); pt = {deg, d}. square: centre (x, y), side s; pt = {x, y}.
    inside: function (tg, pt) {
      // differences are taken to nine decimal places, so a typed decimal exactly on an edge is judged as the decimal it is
      if (tg.kind === 'xy') { var dx = r9(pt.x - tg.x), dy = r9(pt.y - tg.y), h = r9(tg.s / 2); return dx >= -h && dx < h && dy >= -h && dy < h; }
      var da = r9(mod(r9(mod(pt.deg, 360) - tg.deg + 180), 360) - 180), dr = r9(pt.d - tg.d), ha = r9(tg.wdeg / 2), hd = r9(tg.wd / 2);
      return da >= -ha && da < ha && dr >= -hd && dr < hd;
    },
    insideAt: function (tg, x, y) { IN.x = x; IN.y = y; IN.d = Math.sqrt(x * x + y * y); IN.deg = Math.atan2(y, x) / RAD; if (IN.deg < 0) IN.deg += 360; return M.inside(tg, IN); },
    // how many different places n equal turns land on (step 0): the smallest count that already closes, or n
    places: function (n, turn, c) {
      var k, lim = n > 4000 ? 4000 : n;
      for (k = 1; k <= lim; k++) if (exact({rung:2,start:0,turn:turn,mod:c},k).m === '0') return k;
      return n;
    }
  };

  // ------------------------------------------------------------------ numbers as text
  function parseOne(s) { return /^[+-]?(\d+\.?\d*|\.\d+)(e[+-]?\d+)?$/i.test(s) ? Number(s) : NaN; }
  // text to a number: digits, sign, decimal point, thousands commas, one fraction bar (360/12). Anything else is NaN.
  function parse(text) {
    var s = String(text == null ? '' : text).replace(/[\s ]/g, '').replace(/−/g, '-');
    if (/^[+-]?\d{1,3}(,\d{3})+(\.\d*)?$/.test(s)) s = s.replace(/,/g, '');
    else if (/^[+-]?\d*,\d+$/.test(s)) s = s.replace(',', '.');
    var i = s.indexOf('/');
    if (i > 0) { var p = parseOne(s.slice(0, i)), q = parseOne(s.slice(i + 1)); return (p !== p || q !== q || q === 0) ? NaN : p / q; }
    return parseOne(s);
  }
  function group(s) { var i = s.indexOf('.'), a = i < 0 ? s : s.slice(0, i), b = i < 0 ? '' : s.slice(i); return a.replace(/\B(?=(\d{3})+(?!\d))/g, ',') + b; }
  // a number as plain digits: never an exponent, never -0, never NaN. dec = most decimals; fixed keeps trailing zeros.
  function plain(v, dec, fixed) {
    if (v !== v || v === Infinity || v === -Infinity) return '0';
    if (dec == null) dec = 4;
    var a = Math.abs(v); if (a > LIMIT) a = LIMIT;
    var s = a.toFixed(dec);
    if (!fixed && s.indexOf('.') >= 0) s = s.replace(/0+$/, '').replace(/\.$/, '');
    return (v < 0 && /[1-9]/.test(s) ? '-' : '') + s;
  }
  function fmt(v, dec, fixed) { var s = plain(v, dec, fixed), neg = s.charAt(0) === '-'; if (neg) s = s.slice(1); return (neg ? '-' : '') + (s.replace(/\..*/, '').length > 4 ? group(s) : s); }
  function decimalsOf(v) { var s = plain(v, 4), i = s.indexOf('.'); return i < 0 ? 0 : s.length - i - 1; }
  // the largest 1, 2, 5 x 10^k that is not above v; and the smallest that is not below v
  function niceDown(v) { if (!(v > 0)) return 1; var k = Math.pow(10, Math.floor(Math.log10(v))), f = v / k; return (f >= 5 ? 5 : f >= 2 ? 2 : 1) * k; }
  function niceUp(v) { if (!(v > 0)) return 1; var k = Math.pow(10, Math.floor(Math.log10(v))), f = v / k; return (f <= 1.0000001 ? 1 : f <= 2 ? 2 : f <= 5 ? 5 : 10) * k; }
  function stepDec(q) { var d = Math.ceil(-Math.log10(q) - 1e-9); return d < 0 ? 0 : d > 9 ? 9 : d; }
  function snapTo(v, q) { return Number((Math.round(v / q) * q).toFixed(stepDec(q))) + 0; }
  // a value checked against a field: null = not acceptable (the last good value stays); lim = it was above the real limit
  function check(cfg, v) {
    if (v !== v) return null;
    if (cfg.int && isFinite(v) && !Number.isInteger(v)) return null;
    if (cfg.min != null && v < cfg.min) return null;
    if (cfg.pos && !(v > 0)) return null;
    var lim = false;
    if (v > LIMIT) { v = LIMIT; lim = true; } else if (v < -LIMIT) { v = -LIMIT; lim = true; }
    return { v: v + 0, lim: lim };
  }

  // ------------------------------------------------------------------ the look (one style block, added once)
  var CSS = '' +
    '.kgf-root{position:absolute;left:0;top:0;right:0;bottom:0;background:#000;overflow:hidden;font-family:' + FONT + ';font-weight:400;color:#fff;user-select:none;-webkit-user-select:none;touch-action:none;-webkit-tap-highlight-color:transparent;font-variant-numeric:tabular-nums}' +
    '.kgf-root canvas.kgf-cv{position:absolute;left:0;top:0;width:100%;height:100%;touch-action:none;display:block}' +
    '.kgf-block{position:absolute;box-sizing:border-box;display:flex;flex-direction:column;justify-content:flex-end;font:400 28px/1.32 ' + FONT + ';font-variant-numeric:tabular-nums;color:#fff;touch-action:none;pointer-events:none}' +
    '.kgf-line{display:flex;flex-wrap:wrap;align-items:baseline;column-gap:.24em;padding-left:1.1em}.kgf-line>.kgf-term:first-child{margin-left:-1.1em}' +
    '.kgf-term{display:inline-flex;align-items:baseline;gap:.2em;white-space:nowrap}' +
    '.kgf-w{color:rgba(255,255,255,.7);font-size:24px;letter-spacing:.01em}' +
    '.kgf-op{color:rgba(255,255,255,.62)}' +
    '.kgf-n{color:#ffb000}' +
    '.kgf-out{color:#fff}' +
    '.kgf-num{position:relative;display:inline-flex;align-items:baseline;justify-content:center;padding:0 .34em;min-width:.7em;color:#0ff;cursor:ns-resize;touch-action:none;pointer-events:auto;border-radius:5px}' +
    '.kgf-num::before,.kgf-num::after{content:"";position:absolute;top:.2em;bottom:.14em;width:.2em;border:2px solid currentColor;opacity:.6;box-sizing:border-box}' +
    '.kgf-num::before{left:0;border-right:0}.kgf-num::after{right:0;border-left:0}' +
    '.kgf-hit{position:absolute;left:-4px;right:-4px;top:-7px;bottom:-7px}' +
    '.kgf-lab{font-size:24px;color:rgba(255,255,255,.62);margin-right:.3em}' +
    '.kgf-num.kgf-edit{color:#ffb000;background:rgba(255,176,0,.14)}' +
    '.kgf-num.kgf-edit .kgf-v::after{content:"";display:inline-block;width:2px;height:.86em;background:#ffb000;margin-left:2px;vertical-align:-.08em;animation:kgf-blink 1s steps(2,start) infinite}' +
    '@keyframes kgf-blink{to{visibility:hidden}}' +
    '.kgf-eq{position:relative;color:#0ff;cursor:pointer;pointer-events:auto;padding:0 .12em}' +
    '.kgf-eq .kgf-hit{left:-12px;right:-12px}' +
    '.kgf-pulse{animation:kgf-pulse .9s ease-out 1}' +
    '@keyframes kgf-pulse{0%{transform:scale(1)}35%{transform:scale(1.4);text-shadow:none}100%{transform:scale(1)}}' +
    '.kgf-chips{position:absolute;display:flex;align-items:flex-end;gap:14px;font:400 28px/1.2 ' + FONT + ';font-variant-numeric:tabular-nums;pointer-events:none;box-sizing:border-box}' +
    '.kgf-chip{display:flex;flex-direction:column;align-items:flex-start;pointer-events:auto}' +
    '.kgf-cl{font-size:24px;line-height:1.1;color:rgba(255,255,255,.55);white-space:nowrap}' +
    '.kgf-dots{width:56px;height:56px;border:1.5px solid rgba(0,255,255,.4);border-radius:10px;background:none;color:rgba(0,255,255,.85);font:400 28px/1 ' + FONT + ';pointer-events:auto;cursor:pointer;padding:0 0 12px 0;margin-left:auto}' +
    '.kgf-dots.on{background:rgba(0,255,255,.16)}' +
    '.kgf-more{position:absolute;right:0;bottom:100%;margin-bottom:8px;display:none;grid-template-columns:auto auto;gap:10px 22px;padding:12px 14px;background:rgba(0,0,0,.9);border:1.5px solid rgba(0,255,255,.35);border-radius:12px;pointer-events:auto}' +
    '.kgf-more.on{display:grid}' +
    '.kgf-pad{position:absolute;display:none;box-sizing:border-box;padding:6px;gap:6px;background:#000;touch-action:none;flex-direction:column;z-index:6}' +
    '.kgf-pad.on{display:flex}.kgf-pad.row{flex-direction:row;align-items:stretch}' +
    '.kgf-digits{display:flex;justify-content:center;align-items:stretch;gap:2px;height:104px;flex:none}' +
    '.kgf-pad.row .kgf-digits{height:auto;min-width:250px}' +
    '.kgf-dcol{display:flex;flex-direction:column;align-items:stretch;flex:0 1 54px;min-width:30px}' +
    '.kgf-dsep{flex:none;align-self:center;font:400 30px/1 ' + FONT + ';color:#ffb000;width:8px;text-align:center}' +
    '.kgf-dbtn{flex:1;border:0;background:none;padding:0;margin:0;cursor:pointer;display:flex;align-items:center;justify-content:center;color:rgba(0,255,255,.8);touch-action:none}' +
    '.kgf-dbtn svg{width:26px;height:16px;display:block}.kgf-dbtn.on{color:#fff}' +
    '.kgf-dval{font:400 30px/36px ' + FONT + ';font-variant-numeric:tabular-nums;color:#ffb000;text-align:center;height:36px;flex:none}' +
    '.kgf-dval.z{color:rgba(255,176,0,.4)}' +
    '.kgf-keys{display:grid;grid-template-columns:repeat(4,1fr);gap:4px;flex:1}' +
    '.kgf-pad.row .kgf-keys{grid-template-columns:repeat(8,1fr)}' +
    '.kgf-key{height:56px;min-width:0;border:1.5px solid rgba(0,255,255,.4);border-radius:10px;background:transparent;color:#fff;font:400 28px/1 ' + FONT + ';padding:0;margin:0;cursor:pointer;touch-action:none;display:flex;align-items:center;justify-content:center}' +
    '.kgf-key svg{width:30px;height:30px}.kgf-key.on{background:rgba(0,255,255,.28)}' +
    '.kgf-limit{position:absolute;left:12px;right:12px;display:none;font:400 24px/1.25 ' + FONT + ';color:#ffb000;text-align:center;pointer-events:none;z-index:7;text-shadow:none}' +
    '.kgf-limit.on{display:block}' +
    '.kgf-pips{position:absolute;display:flex;align-items:center;height:44px;z-index:3}' +
    '.kgf-pip{height:44px;min-width:26px;display:inline-flex;align-items:center;justify-content:center;cursor:pointer;font-size:24px;color:rgba(102,204,255,.8);touch-action:manipulation}' +
    '.kgf-pip i{width:12px;height:12px;border-radius:50%;border:2px solid rgba(102,204,255,.85);box-sizing:border-box;flex:none}' +
    '.kgf-pip b{margin:0 10px 0 6px;font-weight:400}' +
    '.kgf-pip.on{color:#ffb000;cursor:default}.kgf-pip.on i{background:#ffb000;border-color:#ffb000}' +
    '.kgf-pip.dim{opacity:.3;cursor:default}' +
    '.kgf-icons{position:absolute;display:flex;z-index:3}' +
    '.kgf-ic{width:44px;height:44px;background:none;border:0;padding:0;margin:0;cursor:pointer;color:rgba(255,255,255,.72);display:inline-flex;align-items:center;justify-content:center;touch-action:manipulation}' +
    '.kgf-ic svg{width:28px;height:28px;display:block}.kgf-ic.off{color:rgba(255,255,255,.3)}.kgf-ic.lit{color:#ffb000}' +
    '.kgf-time{position:absolute;display:none;align-items:center;gap:6px;height:48px;box-sizing:border-box}' +
    '.kgf-time.on{display:flex}.kgf-time canvas{flex:1;height:48px;min-width:0;touch-action:none;cursor:ew-resize}' +
    /* the joystick: the simulator's own (prospect/snippets/joystick.js), restyled for the bottom left */
    '.kgf-joy{position:absolute;z-index:4;width:120px;height:120px;border-radius:50%;background:rgba(156,219,255,.04);border:1px solid rgba(156,219,255,.35);touch-action:none;display:none}' +
    '.kgf-joy.on{display:block}' +
    '.kgf-knob{position:absolute;left:36px;top:36px;width:48px;height:48px;border-radius:50%;border:1px solid rgba(156,219,255,.5);background:rgba(156,219,255,.12);box-sizing:border-box}';
  CSS += '.kgf-root *{font-weight:400;text-shadow:none!important}' +
    '.kgf-root .kgf-num,.kgf-root .kgf-out,.kgf-root .kgf-n,.kgf-root .kgf-eq,.kgf-root .kgf-limit,.kgf-root .kgf-pip,.kgf-root .kgf-dval,.kgf-root .kgf-dsep,.kgf-root .kgf-dbtn{color:#fff!important}' +
    '.kgf-root .kgf-num{border:1px solid #fff;border-radius:0;padding:0 .2em;font-size:32px;background:#000}' +
    '.kgf-root .kgf-num::before,.kgf-root .kgf-num::after{display:none}' +
    '.kgf-root .kgf-num.kgf-edit{background:#000;border-bottom:3px solid #fff}' +
    '.kgf-root .kgf-num.kgf-edit .kgf-v::after{background:#fff}' +
    '.kgf-root .kgf-key,.kgf-root .kgf-dots,.kgf-root .kgf-more{border:1px solid #fff;border-radius:0;color:#fff;background:#000}' +
    '.kgf-root .kgf-key.on{background:#222}.kgf-root .kgf-pip i{border-color:#fff}.kgf-root .kgf-pip.on i{background:#fff}' +
    '.kgf-root .kgf-ic.lit{color:#fff}.kgf-root .kgf-digits{display:none}' +
    '.kgf-root .kgf-key{height:44px}.kgf-root .kgf-pad{padding:6px;gap:4px}' +
    '.kgf-root .kgf-block{overflow-x:auto}.kgf-root .kgf-num *{touch-action:none}' +
    '.kgf-root .kgf-line{row-gap:4px;margin:4px 0;flex-shrink:0}.kgf-root .kgf-term{flex-shrink:0}';
  CSS += '.kgf-working{position:absolute;color:rgba(255,255,255,.7);font:400 24px/32px ' + FONT + ';white-space:nowrap;overflow-x:auto;pointer-events:auto;touch-action:pan-x}' +
    '.kgf-root .kgf-block.rung-one .kgf-line{flex-wrap:nowrap}.kgf-root .kgf-key{color:#fff!important;border-color:#fff!important}';
  function css() {
    if (typeof document === 'undefined' || document.getElementById('kgf-style')) return;
    var st = document.createElement('style'); st.id = 'kgf-style'; st.textContent = CSS; document.head.appendChild(st);
  }
  function E(tag, cls, text, parent) { var e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; if (parent) parent.appendChild(e); return e; }
  var SVG = {
    up: '<svg viewBox="0 0 26 16"><path d="M3 13 L13 3 L23 13" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/></svg>',
    down: '<svg viewBox="0 0 26 16"><path d="M3 3 L13 13 L23 3" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/></svg>',
    ok: '<svg viewBox="0 0 30 30"><path d="M24 6 V17 H8 M13 11 L7 17 L13 23" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round"/></svg>',
    back: '<svg viewBox="0 0 30 30"><path d="M11 7 H26 V23 H11 L3 15 Z M15 11 L22 19 M22 11 L15 19" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linejoin="round" stroke-linecap="round"/></svg>',
    x: '<svg viewBox="0 0 28 28"><path d="M6 6 L22 22 M22 6 L6 22" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round"/></svg>',
    note: '<svg viewBox="0 0 28 28"><path d="M4 11 H9 L15 5 V23 L9 17 H4 Z" fill="currentColor"/><path d="M19 10 Q22 14 19 18" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round"/><path class="s" style="display:none" d="M5 4 L24 24" stroke="currentColor" stroke-width="3" stroke-linecap="round"/></svg>',
    star: '<svg viewBox="0 0 28 28"><path d="M14 2.5 L17.3 10.2 L25.6 10.9 L19.3 16.4 L21.2 24.5 L14 20.2 L6.8 24.5 L8.7 16.4 L2.4 10.9 L10.7 10.2 Z" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linejoin="round"/></svg>',
    joy: '<svg viewBox="0 0 28 28"><circle cx="14" cy="14" r="11" fill="none" stroke="currentColor" stroke-width="2"/><circle cx="17" cy="11" r="4.5" fill="currentColor"/></svg>',
    play: '<svg viewBox="0 0 28 28"><path d="M8 5 L23 14 L8 23 Z" fill="currentColor"/></svg>',
    pause: '<svg viewBox="0 0 28 28"><path d="M7 5 H12 V23 H7 Z M16 5 H21 V23 H16 Z" fill="currentColor"/></svg>'
  };

  // ------------------------------------------------------------------ the formula line, the chips and the keypad
  var probeFns = [];
  // create(host, opts): opts.onInput(id, value, how) with how = 'type' (keys or keypad), 'explore' (drag a number,
  // wheel, digit arrows) or 'restore' (Escape); opts.onEdit(id or null); opts.onEq(); opts.onLand(id).
  function create(host, opts) {
    css(); opts = opts || {};
    var F = { el: E('div', 'kgf-block', null, host), chipsEl: E('div', 'kgf-chips', null, host), padEl: E('div', 'kgf-pad', null, host), limitEl: E('div', 'kgf-limit', null, host) };
    var nums = {}, outs = {}, ed = null, drag = null, limT = 0, rep = 0, repT = 0, moreEl = null, dotsBtn = null, digN = -1, dead = false, padEv = null;
    F.workingEl = E('div', 'kgf-working', null, host);
    var digitsEl = E('div', 'kgf-digits', null, F.padEl), keysEl = E('div', 'kgf-keys', null, F.padEl);
    var KEYS = ['7', '8', '9', 'back', '4', '5', '6', 'C', '1', '2', '3', '-', '0', '.', '/', 'ok'];
    KEYS.forEach(function (k) {
      var b = E('button', 'kgf-key', null, keysEl); b.setAttribute('data-k', k); b.setAttribute('aria-label', k === 'back' ? 'backspace' : k === 'C' ? 'clear' : k === '-' ? 'minus' : k === 'ok' ? 'enter' : k);
      if (k === 'back') b.innerHTML = SVG.back; else if (k === 'ok') { b.innerHTML = SVG.ok; b.style.color = '#fff'; b.style.borderColor = '#fff'; } else b.textContent = k === '-' ? '−' : k;
    });

    function show(n) { n.vEl.textContent = ed && ed.n === n ? ed.buf : (n.txt || fmt(n.v, n.cfg.show == null ? 4 : n.cfg.show, n.cfg.fixed)); }
    function token(parent, p) {
      var cfg = p.cfg || {}, el = E('span', 'kgf-num', null, parent), n = nums[p.id];
      el.style.color = '#fff';
      el.setAttribute('data-id', p.id);
      if (cfg.label) E('span', 'kgf-lab', cfg.label, el);
      var v = E('span', 'kgf-v', '', el); E('span', 'kgf-hit', null, el);
      if (!n) n = nums[p.id] = { id: p.id, v: p.v == null ? 0 : p.v, txt: null };
      n.cfg = cfg; n.el = el; n.vEl = v; n.live = true;
      if (ed && ed.n === n) el.classList.add('kgf-edit');
      show(n);
      return n;
    }
    function part(parent, p) {
      if (typeof p === 'string') {
        var c = p === 'N' ? 'kgf-n' : /^[A-Z][A-Z ]*\(?$/.test(p) && p !== 'T' && p !== 'X' && p !== 'Y' ? 'kgf-w' : /^[A-Z]$/.test(p) ? 'kgf-w' : 'kgf-op';
        E('span', c, p, parent); return;
      }
      if (p.id) { token(parent, p); return; }
      if (p.out) { var o = E('span', 'kgf-out', outs[p.out] ? outs[p.out].text : '', parent); o.style.color = '#fff'; outs[p.out] = { el: o, text: o.textContent }; return; }
      if (p.eq) { var q = E('span', 'kgf-eq', '=', parent); E('span', 'kgf-hit', null, q); q.setAttribute('data-eq', '1'); }
    }
    function sweep() { var k; for (k in nums) if (!nums[k].live) { if (ed && ed.n === nums[k]) closeEditor(true); delete nums[k]; } }
    // lines = [ line, ... ]; line = [ term, ... ]; term = [ part, ... ]. A line wraps only between terms.
    F.setLines = function (lines) {
      var k; for (k in nums) if (!nums[k].chip) nums[k].live = false;
      for (k in outs) outs[k].el = null;
      F.el.textContent = '';
      lines.forEach(function (ln) { var L = E('div', 'kgf-line', null, F.el); ln.forEach(function (tm) { var T = E('span', 'kgf-term', null, L); tm.forEach(function (p) { part(T, p); }); }); });
      sweep();
    };
    // chips = [ {id, label, cfg, big}, ... ]: one row; the big ones stay, the rest open from the "..." chip
    F.setChips = function (chips) {
      var k; for (k in nums) if (nums[k].chip) nums[k].live = false;
      var wasOpen = moreEl && moreEl.classList.contains('on');
      F.chipsEl.textContent = '';
      var small = chips.filter(function (c) { return !c.big; });
      function chip(parent, c) { var w = E('div', 'kgf-chip', null, parent); E('span', 'kgf-cl', c.label, w); var n = token(w, c); n.chip = true; return w; }
      chips.forEach(function (c) { if (c.big) chip(F.chipsEl, c); });
      dotsBtn = moreEl = null;
      if (small.length) {
        dotsBtn = E('button', 'kgf-dots', '...', F.chipsEl); dotsBtn.setAttribute('aria-label', 'more numbers');
        moreEl = E('div', 'kgf-more' + (wasOpen ? ' on' : ''), null, F.chipsEl);
        small.forEach(function (c) { chip(moreEl, c); });
        if (wasOpen) dotsBtn.classList.add('on');
        dotsBtn.addEventListener('click', function () { F.more(!moreEl.classList.contains('on')); });
      }
      sweep();
    };
    F.more = function (on) { if (!moreEl) return; if (!on && ed && ed.n.el && moreEl.contains(ed.n.el)) closeEditor(true); moreEl.classList.toggle('on', !!on); dotsBtn.classList.toggle('on', !!on); if (opts.onMore) opts.onMore(!!on); };
    F.moreOpen = function () { return !!(moreEl && moreEl.classList.contains('on')); };
    // set a number from outside (a dragged dot, the clock): no callback. txt keeps a typed fraction on show.
    F.setValue = function (id, v, txt) {
      var n = nums[id]; if (!n) return;
      if (ed && ed.n === n) { if (Math.abs(v - n.v) <= 1e-9 * Math.max(1, Math.abs(v))) { n.v = v; return; } n.v = v; n.txt = null; ed.buf = plain(v, 6); ed.fresh = true; show(n); digits(); return; }
      if (n.v === v && n.txt === (txt || null) && n.vEl.textContent !== '') return;
      n.v = v; n.txt = txt || null; show(n);
    };
    F.setCfg = function (id, key, val) { var n = nums[id]; if (n && n.cfg[key] !== val) { n.cfg[key] = val; show(n); } };
    F.setText = function (key, text) { var o = outs[key]; if (!o) return; if (o.text !== text) { o.text = text; if (o.el) o.el.textContent = text; } };
    F.get = function (id) { return nums[id] ? nums[id].v : undefined; };
    F.txt = function (id) { return nums[id] ? nums[id].txt : null; };
    F.has = function (id) { return !!nums[id]; };
    F.editing = function () { return ed ? ed.n.id : null; };
    F.buffer = function () { return ed ? ed.buf : null; };
    F.pulse = function (id) {
      var el = nums[id] ? nums[id].el : id === '=' ? F.el.querySelector('.kgf-eq') : outs[id] ? outs[id].el : null; if (!el) return;
      el.classList.remove('kgf-pulse'); void el.offsetWidth; el.classList.add('kgf-pulse');
    };
    F.limit = function () { F.limitEl.textContent = LIMIT_TEXT; F.limitEl.classList.add('on'); clearTimeout(limT); limT = setTimeout(function () { F.limitEl.classList.remove('on'); }, 4500); };

    function stepFor(n) {
      if(n.id==='square' || n.id==='start')return 1;
      var a = Math.abs(n.v), cfg = n.cfg, s = a >= 10 ? Math.pow(10, Math.floor(Math.log10(a)) - 1) : (cfg.step || (cfg.int ? 1 : 0.1));
      if (cfg.int && s < 1) s = 1; return s;
    }
    // put a value into a number; clamp = an explored value below the floor stops at the floor
    function apply(n, v, how, clamp) {
      var c = check(n.cfg, v);
      if (!c) { if (!clamp || v !== v) return false; if (n.cfg.min != null && v < n.cfg.min) c = { v: n.cfg.min }; else return false; }
      if (c.lim) { F.limit(); return false; }
      F.limitEl.classList.remove('on');
      if (how !== 'type' && ed && ed.n === n) { ed.typed = false; ed.valid = false; }
      if (how !== 'type' && c.v === n.v) return true;
      n.v = c.v; if (how !== 'type') n.txt = null;
      show(n);
      if (opts.onInput) opts.onInput(n.id, c.v, how);
      return true;
    }
    function openEditor(n) {
      if (ed && ed.n === n) return;
      if (ed) closeEditor(true);
      ed = { n: n, buf: n.txt || plain(n.v, 6), fresh: true, v0: n.v, txt0: n.txt, typed: false, valid: false };
      n.el.classList.add('kgf-edit'); show(n); digN = -1; digits();
      F.padEl.classList.add('on');
      if (opts.onEdit) opts.onEdit(n.id);
    }
    function closeEditor(commit) {
      if (!ed) return;
      var e = ed, n = e.n; var accepted = commit && e.typed && e.valid; ed = null; stopRep();
      if (n.el) n.el.classList.remove('kgf-edit');
      if (!commit || (e.typed && !e.valid)) { var ch = n.v !== e.v0; n.v = e.v0; n.txt = e.txt0; if (ch && opts.onInput) opts.onInput(n.id, n.v, 'restore'); }
      else if (accepted) {
        var p = parse(e.buf), c = p !== p ? null : check(n.cfg, p);
        n.txt = (c && !c.lim && c.v === n.v && (e.buf.indexOf('/') > 0 || /\.\d{5,}/.test(e.buf))) ? e.buf : null;
      }
      if (n.vEl) show(n);
      F.padEl.classList.remove('on');
      if (opts.onEdit) opts.onEdit(null, accepted ? n.id : null);
    }
    F.open = function (id) { if (nums[id]) openEditor(nums[id]); };
    F.close = function (commit) { closeEditor(commit !== false); };
    // one key of the keypad or the keyboard: '0'..'9', '.', '-', '/', 'back', 'C'
    function key(k) {
      if (!ed || !/^(?:[0-9eE+]|\.|-|\/|back|C)$/.test(k)) return;
      var n = ed.n, b = ed.fresh ? '' : ed.buf, seg;
      if (ed.blocked && k !== 'back' && k !== 'C' && !ed.fresh) return;
      ed.blocked = false;
      if (k === 'C') b = '';
      else if (k === 'back') b = ed.buf.slice(0, -1);
      else if (k === '-') b = (ed.fresh || !ed.typed) ? '-' : (ed.buf.charAt(0) === '-' ? ed.buf.slice(1) : '-' + ed.buf);
      else if (k === '.') { if (ed.fresh) b = '0.'; else { seg = b.slice(b.lastIndexOf('/') + 1); if (seg.indexOf('.') >= 0) return; b += (seg === '' || seg === '-') ? '0.' : '.'; } }
      else if (k === '/') { if (ed.fresh) b = ed.buf; if (b === '' || b === '-' || b.indexOf('/') >= 0) return; b += '/'; }
      else { if (b.length >= 22) return; seg = b.slice(b.lastIndexOf('/') + 1); if (seg === '0') b = b.slice(0, -1); else if (seg === '-0') b = b.slice(0, -1); b += k; }
      ed.buf = b; ed.fresh = false; ed.typed = true; ed.valid = false; show(n);
      var p = parse(b);
      if (p === p) {
        var c = check(n.cfg, p), typedRatio = b.indexOf('/') < 0 && isFinite(p) ? ratio(b.replace(/^([+-]?)\./,'$10.')) : null;
        if(typedRatio && (typedRatio.n>BigInt(LIMIT)*typedRatio.d || typedRatio.n<-BigInt(LIMIT)*typedRatio.d)) c={lim:true};
        if (c && c.lim) { ed.blocked = true; F.limit(); } else if (c) { ed.valid = true; F.limitEl.classList.remove('on'); n.v = c.v; if (opts.onInput) opts.onInput(n.id, c.v, 'type'); }
      }
      if (!ed.valid && opts.onInvalid) opts.onInvalid(n.id);
      digits();
    }
    F.key = key;
    // Enter (or the keypad's enter): the typed number is committed. opts.onCommit may keep the number open for the next try.
    function enter() {
      if (!ed) return;
      var n = ed.n, typed = ed.typed && ed.valid, keep = false;
      if (ed.typed && !ed.valid) {
        n.v = ed.v0; n.txt = ed.txt0;
        if (opts.onInput) opts.onInput(n.id, n.v, 'restore');
        if (opts.onInvalid) opts.onInvalid(n.id);
        ed.fresh = true; ed.typed = false; ed.valid = false; show(n); digits(); return;
      }
      if (typed) { var p = parse(ed.buf), c = p !== p ? null : check(n.cfg, p); n.txt = (c && !c.lim && c.v === n.v && (ed.buf.indexOf('/') > 0 || /\.\d{5,}/.test(ed.buf))) ? ed.buf : null; }
      if (opts.onCommit) keep = opts.onCommit(n.id, typed) === true;
      if (!ed || ed.n !== n) return;
      if (keep) { ed.buf = n.txt || plain(n.v, 6); ed.fresh = true; ed.v0 = n.v; ed.txt0 = n.txt; ed.typed = false; ed.valid = false; show(n); digits(); }
      else { ed.typed = false; closeEditor(true); }
    }
    F.enter = enter;

    // ---- the digit arrows over the selected number: one press changes one place
    function places(n) {
      var cfg = n.cfg, a = Math.abs(n.v), nd = typeof cfg.dec === 'function' ? cfg.dec() : cfg.dec;
      var intD = Math.max(cfg.intDigits || 1, a >= 1 ? Math.floor(Math.log10(a) + 1e-12) + 1 : 1), dec = cfg.int ? 0 : Math.max(nd == null ? 1 : nd, decimalsOf(n.v));
      if (dec > 4) dec = 4;
      while (intD + dec > 7 && dec > 0) dec--;
      var low = intD > 7 ? intD - 7 : 0;
      return { hi: intD - 1, lo: dec > 0 ? -dec : low, dec: dec };
    }
    function digits() {
      if (!ed) return;
      var n = ed.n, P = places(n), cols = P.hi - P.lo + 1, sig = cols * 100 + P.dec * 10 + (n.v < 0 ? 1 : 0), i, p, col;
      if (sig !== digN) {
        digN = sig; digitsEl.textContent = '';
        if (n.v < 0) E('span', 'kgf-dsep', '−', digitsEl).style.width = '18px';
        for (p = P.hi; p >= P.lo; p--) {
          if (p === -1) E('span', 'kgf-dsep', '.', digitsEl);
          col = E('div', 'kgf-dcol', null, digitsEl); col.setAttribute('data-p', p);
          var u = E('button', 'kgf-dbtn', null, col); u.innerHTML = SVG.up; u.setAttribute('data-s', '1'); u.setAttribute('aria-label', 'up');
          E('div', 'kgf-dval', '0', col);
          var d = E('button', 'kgf-dbtn', null, col); d.innerHTML = SVG.down; d.setAttribute('data-s', '-1'); d.setAttribute('aria-label', 'down');
        }
      }
      var s = Math.abs(n.v).toFixed(P.dec).replace('.', ''), vals = digitsEl.querySelectorAll('.kgf-dval'), lead = true;
      while (s.length < P.hi + 1 + P.dec) s = '0' + s;
      for (i = 0; i < vals.length; i++) {
        var ch = s.charAt(s.length - (P.hi + P.dec + 1) + i + (P.dec > 0 ? 0 : 0)) || '0', pp = P.hi - i;
        if (ch !== '0' || pp <= 0) lead = false;
        if (vals[i].textContent !== ch) vals[i].textContent = ch;
        vals[i].className = 'kgf-dval' + (lead ? ' z' : '');
      }
    }
    function bump(p, s) {
      if (!ed) return;
      var n = ed.n, P = places(n), q = Math.pow(10, p), v = Number((n.v + s * q).toFixed(P.dec));
      if (apply(n, v, 'digit', true)) { ed.buf = plain(n.v, 6); ed.fresh = true; show(n); digits(); if (opts.onLand) opts.onLand(n.id); }
    }
    function stopRep() { clearTimeout(repT); clearInterval(rep); rep = 0; repT = 0; }
    function padDown(e) {
      var t = e.target.closest ? e.target.closest('.kgf-key,.kgf-dbtn') : null;
      e.preventDefault(); padEv = e;
      if (!t || !ed) return;
      t.classList.add('on'); setTimeout(function () { t.classList.remove('on'); }, 110);
      if (t.classList.contains('kgf-key')) { var kk = t.getAttribute('data-k'); if (kk === 'ok') enter(); else key(kk); return; }
      var p = +t.parentNode.getAttribute('data-p'), s = +t.getAttribute('data-s');
      bump(p, s); stopRep();
      repT = setTimeout(function () { rep = setInterval(function () { bump(p, s); }, 110); }, 420);
    }
    F.padEl.addEventListener('pointerdown', padDown);
    F.padEl.addEventListener('pointerup', stopRep); F.padEl.addEventListener('pointercancel', stopRep); F.padEl.addEventListener('pointerleave', stopRep);
    F.padEl.addEventListener('contextmenu', function (e) { e.preventDefault(); });

    // ---- a number: tap to type, drag up or down to step, wheel to step
    function onDown(e) {
      var t = e.target.closest ? e.target.closest('.kgf-num,.kgf-eq') : null; if (!t || drag) return;
      e.preventDefault();
      if (t.classList.contains('kgf-eq')) drag = { eq: true, pid: e.pointerId, y0: e.clientY, x0: e.clientX, el: t };
      else { var n = nums[t.getAttribute('data-id')]; if (!n) return; drag = { n: n, pid: e.pointerId, x0: e.clientX, y0: e.clientY, v0: n.v, step: stepFor(n), moved: false, el: t }; }
      try { t.setPointerCapture(e.pointerId); } catch (_) { }
    }
    function onMove(e) {
      if (!drag || drag.pid !== e.pointerId || !drag.n) return;
      var dy = drag.y0 - e.clientY, a = Math.abs(dy) - 8;
      if (!drag.moved) { if (a < 0) return; drag.moved = true; if (ed && ed.n !== drag.n) closeEditor(true); }
      if (a < 0) a = 0;
      var k = Math.round(Math.pow(a / 9, 1.3)) * (dy < 0 ? -1 : 1);
      apply(drag.n, snapTo(drag.v0 + k * drag.step, drag.step), 'explore', true);
      if (ed && ed.n === drag.n) { ed.buf = plain(drag.n.v, 6); ed.fresh = true; show(drag.n); digits(); }
    }
    function onUp(e) {
      if (!drag || drag.pid !== e.pointerId) return;
      var d = drag; drag = null;
      try { d.el.releasePointerCapture(e.pointerId); } catch (_) { }
      if (e.type === 'pointercancel') return;
      if (d.eq) { if (Math.abs(e.clientX - d.x0) + Math.abs(e.clientY - d.y0) < 16 && opts.onEq) opts.onEq(); return; }
      if (!d.moved) openEditor(d.n); else if (opts.onLand) opts.onLand(d.n.id);
    }
    function onWheel(e) {
      var t = e.target.closest ? e.target.closest('.kgf-num') : null; if (!t) return;
      e.preventDefault(); e.stopPropagation();
      if (!e.deltaY) return;
      var n = nums[t.getAttribute('data-id')]; if (!n) return;
      var s = stepFor(n);
      apply(n, snapTo(n.v + (e.deltaY < 0 ? s : -s), s), 'explore', true);
      if (ed && ed.n === n) { ed.buf = plain(n.v, 6); ed.fresh = true; show(n); digits(); }
      if(opts.onRoll)opts.onRoll(n.id);
    }
    [F.el, F.chipsEl].forEach(function (el) {
      el.addEventListener('pointerdown', onDown); el.addEventListener('pointermove', onMove);
      el.addEventListener('pointerup', onUp); el.addEventListener('pointercancel', onUp);
      el.addEventListener('wheel', onWheel, { passive: false });
    });
    // the keyboard (bubble phase on the document; nothing is captured)
    function onKey(e) {
      if (dead || !ed || e.ctrlKey || e.metaKey || e.altKey) return;
      var k = e.key, h = true;
      if (k >= '0' && k <= '9' && k.length === 1) key(k);
      else if (k === '.' || k === ',') key('.');
      else if (k === '-' || k === '−') key('-');
      else if (k === '/') key('/');
      else if (k === 'e' || k === 'E' || k === '+') key(k);
      else if (k === 'Backspace') key('back');
      else if (k === 'Delete' || k === 'c' || k === 'C') key('C');
      else if (k === 'Enter') enter();
      else if (k === 'Escape') closeEditor(false);
      else if (k === 'ArrowUp' || k === 'ArrowDown') { var n = ed.n, s = stepFor(n); apply(n, snapTo(n.v + (k === 'ArrowUp' ? s : -s), s), 'explore', true); ed.buf = plain(n.v, 6); ed.fresh = true; show(n); digits(); if(opts.onRoll)opts.onRoll(n.id); }
      else if (k === 'Tab') { var ids = Object.keys(nums).filter(function (id) { return nums[id].el && nums[id].el.offsetParent; }), i = ids.indexOf(ed.n.id); closeEditor(true); if (ids.length) openEditor(nums[ids[(i + (e.shiftKey ? ids.length - 1 : 1)) % ids.length]]); }
      else h = false;
      if (h) { e.preventDefault(); e.stopPropagation(); }
    }
    // a tap anywhere else applies the number
    function onDocDown(e) {
      if (dead) return;
      var t = e.target, inPad = e === padEv || F.padEl.contains(t);
      if (ed && !(ed.n.el && ed.n.el.contains(t)) && !inPad) closeEditor(true);
      if (moreEl && moreEl.classList.contains('on') && !F.chipsEl.contains(t) && !inPad) F.more(false);
    }
    document.addEventListener('keydown', onKey);
    document.addEventListener('pointerdown', onDocDown);
    F.destroy = function () {
      dead = true; stopRep(); clearTimeout(limT); ed = null;
      document.removeEventListener('keydown', onKey); document.removeEventListener('pointerdown', onDocDown);
      [F.el, F.chipsEl, F.padEl, F.limitEl, F.workingEl].forEach(function (el) { if (el.parentNode) el.parentNode.removeChild(el); });
    };
    return F;
  }

  // the five pips (the same look as the KUIPER rung draws): pips(parent, {active, names, onPick}) -> {el, set(active, names), kuiper(on)}
  function pips(parent, o) {
    css();
    var el = E('div', 'kgf-pips', null, parent), kids = [], act = o.active, kOn = true, names = !!o.names;
    PIPS.forEach(function (nm, i) {
      var p = E('span', 'kgf-pip', null, el); E('i', null, null, p); p._b = E('b', null, nm, p); kids.push(p);
      p.addEventListener('click', function () { if (i === act || (i === 4 && !kOn)) return; o.onPick(i + 1); });
    });
    function paint() { kids.forEach(function (p, i) { p.className = 'kgf-pip' + (i === act ? ' on' : (i === 4 && !kOn ? ' dim' : '')); p._b.style.display = (names || i === act) ? '' : 'none'; }); }
    paint();
    return { el: el, set: function (a, nm) { act = a; if (nm != null) names = !!nm; paint(); }, kuiper: function (on) { if (kOn !== !!on) { kOn = !!on; paint(); } } };
  }

  // ------------------------------------------------------------------ PLAY: the four rungs on one canvas
  var S = null;        // the open instance
  var KEEP = null;     // the player's numbers, kept between opens
  var PT = { x: 0, y: 0, d: 0, deg: 0 }, PT2 = { x: 0, y: 0, d: 0, deg: 0 }, INV = {}, SIX = {}, Q = {};
  var IDS = ['start', 'mod', 'dist', 'turn', 'step', 'count', 'speed', 'grow', 'newDots', 't'];
  var CHIP = { c_d: 'd', c_sq: 'sq', c_area: 'area', c_ang: 'deg', c_rem: 'rem', c_x: 'x', c_y: 'y', x: 'x', y: 'y' };

  function tuning() {
    var T = {}, U = root.KGPlayTuning, k;
    for (k in TUNING) T[k] = TUNING[k];
    if (U && typeof U === 'object') {