In this section
- Zoom render · kuiper-belt / learn-the-kuiper/202610050609/modules/zoom.js lines 701–1010
- One geodesy · kuiper-belt / learn-the-kuiper/202610050609/one.js lines 1–390
Zoom
A JavaScript file in the learn the kuiper folder of Kuiper Belt that sets count, converts to screen and world, calculates planar distances and angles and draws on a canvas.
renderkuiper-belt / learn-the-kuiper/202610050609/modules/zoom.js · lines 701–1010 of 1010 · version 2026-10-05 06:09 (continued from section 1534) · Entry point · pattern flightMusic (shared by 2 files)
- What it does
- It draws solar and cables. Defines 76 functions or classes, including fmt, fmtZoom, fmtDec, parseNum, el. 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: solar, cables.
- Inputs & outputs
- Out: canvas drawing.
- Downstream impact
- Used directly by 2 files: Zoom Test (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610042346/modules/zoom-test.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
- It parses num (`parseNum`), sets count (`setCount`) and computes keys real (`computeKeysReal`). Deep-zoom viewer of the real Kuiper law. It responds to pointerenter, pointerleave and click events.
- Why it matters
- Loaded by the Modes page at https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050609/modes.html. Checked by Zoom Test.
- Application
- kuiper-belt · learn-the-kuiper/202610050609/modules · script
- Uses
- none found
- Used by
- loaded by Zoom Test (script src), loaded by Modes (script src)
- Produces
- fmt, fmtZoom, fmtDec, parseNum, el, audioInit, note, penta, flightMusic, params, setCount, homeZoom
- Defines here
- open, rowBtn, on, joyUp, up, setReal, setScan, paintToggles, lit, makeSweep, attachSweep, openSheet, closeSheets, changeCount, pinchState, joyAt, stepJoy, frame, close
- 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/modules/zoom.js:701-1010 · blob 649d7a685331bb3138bbbeee29662510eba95fa6 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: agent_infra · users: ai_agent · canonical: unknown
function open(host) {
if (S) close();
var hw0 = host.clientWidth || window.innerWidth, hh0 = host.clientHeight || window.innerHeight;
var phone = Math.min(window.innerWidth, hw0) < 700 || Math.min(window.innerHeight, hh0) < 500;
S = { host: host, cam: { cx: 0, cy: 0, z: 1 }, pointers: new Map(), dirty: true, muted: false, ac: null, sel: null,
drawn: null, keys: [], visited: new Set(), boundary: null, phone: phone, real: !!realWafer(), scanOn: true, sweep: null, armId: null, btn: phone ? 56 : 72, btnFont: phone ? 24 : 28, big: phone ? 28 : 40, med: phone ? 24 : 28 };
host.style.background = '#000'; host.style.overflow = 'hidden';
if (getComputedStyle(host).position === 'static') host.style.position = 'relative';
var root = el('div', 'position:absolute;inset:0;font-family:' + FONT + ';color:#fff;user-select:none;-webkit-user-select:none;', null, host);
S.root = root;
var cv = el('canvas', 'position:absolute;left:0;top:0;touch-action:none;display:block;cursor:grab;', null, root);
S.canvas = cv; S.ctx = cv.getContext('2d');
// corners: zoom readout and count top left, X top right, one caption line at the top
var safe = 'env(safe-area-inset-top,0px)';
var top = el('div', 'position:absolute;left:0;right:0;top:0;padding:calc(8px + ' + safe + ') 10px 0;pointer-events:none;transition:opacity .3s;', null, root);
S.top = top;
var tl = el('div', 'margin-right:96px;', null, top);
S.zoomBox = el('div', 'color:' + C.cyan + ';opacity:0.9;font:bold ' + (phone ? 30 : 44) + 'px ' + FONT + ';white-space:nowrap;line-height:1.1;', 'ZOOM x1', tl);
S.countRead = el('div', 'color:' + C.blue + ';opacity:0.8;font:bold 24px ' + FONT + ';white-space:nowrap;overflow:hidden;text-overflow:ellipsis;', '', tl);
S.scanRead = el('div', 'color:' + C.green + ';opacity:0.75;font:bold 24px ' + FONT + ';line-height:1.15;min-height:28px;' + (phone ? 'white-space:normal;' : 'white-space:nowrap;overflow:hidden;text-overflow:ellipsis;'), '', tl);
S.capMain = el('div', 'color:#fff;font:bold ' + S.big + 'px ' + FONT + ';line-height:1.15;margin-top:6px;transition:opacity .8s;' + (phone ? '' : 'position:absolute;left:0;right:0;top:calc(14px + ' + safe + ');text-align:center;padding:0 240px;white-space:nowrap;'), '', top);
S.closeBtn = button('\u2715', root, function () { close(); }, 'position:absolute;top:calc(8px + ' + safe + ');right:10px;width:72px;height:72px;font-size:40px;color:rgba(255,255,255,0.8);border-color:rgba(255,255,255,0.5);z-index:4;');
// the bottom edge: one row of dim outline buttons; everything else opens in a sheet
var bottom = el('div', 'position:absolute;left:0;right:0;bottom:0;padding:0 8px calc(10px + env(safe-area-inset-bottom,0px));display:flex;justify-content:center;gap:' + (phone ? 6 : 12) + 'px;pointer-events:none;transition:opacity .3s;', null, root);
S.bottom = bottom;
function rowBtn(t, fn, extra) { var bt = button(t, bottom, fn, extra); bt.style.pointerEvents = 'auto'; return bt; }
rowBtn(phone ? 'MANY' : 'HOW MANY', function () { openSheet('many'); });
rowBtn(phone ? 'KEY' : 'GO TO KEY', function () { openSheet('key'); }, 'color:rgba(255,176,0,0.85);border-color:rgba(255,176,0,0.5);');
rowBtn(phone ? '\u2302' : 'HOME', function () { goHome(true); }, phone ? 'font-size:30px;' : '');
rowBtn('WHY', openWhy, 'color:rgba(34,238,119,0.85);border-color:rgba(34,238,119,0.5);');
S.muteBtn = rowBtn('\u266a', function () {
S.muted = !S.muted; S.muteBtn.textContent = S.muted ? (phone ? '\u00d7\u266a' : 'MUTE') : '\u266a';
if (!S.muted) audioInit();
}, 'font-size:' + (phone ? 28 : 34) + 'px;');
S.muteBtn.title = 'MUSIC ON / MUTE';
// two toggles that stay lit when on (GridAtlas style): REAL (issued lines only) and SCAN (the radar sweep)
S.toggles = el('div', 'display:flex;gap:' + (phone ? 6 : 12) + 'px;pointer-events:none;', null, bottom);
S.realBtn = button('REAL', S.toggles, function () { setReal(!S.real); });
S.scanBtn = button('SCAN', S.toggles, function () { setScan(!S.scanOn); });
S.realBtn.style.pointerEvents = S.scanBtn.style.pointerEvents = 'auto';
S.realBtn.title = 'REAL: ISSUED LINES ONLY / OFF: EVERY ADDRESS'; S.scanBtn.title = 'RADAR SCAN ON / OFF';
// touch screens: the simulator's joystick (pattern from globalgrid2050 energy-transition-simulator/202609282123/mod/walk-fps.js,
// our own code): a translucent ring and thumb bottom-left that FLIES the camera; push to fly, release to drift to a stop
S.joy = { x: 0, y: 0, id: null, vx: 0, vy: 0 };
var touch = (typeof navigator !== 'undefined' && (navigator.maxTouchPoints || 0) > 0) || !!(window.matchMedia && window.matchMedia('(pointer: coarse)').matches);
S.joyEl = el('div', 'position:absolute;left:calc(16px + env(safe-area-inset-left,0px));bottom:calc(' + (S.btn + 30) + 'px + env(safe-area-inset-bottom,0px));width:120px;height:120px;border-radius:50%;background:rgba(0,255,255,0.06);border:1px solid rgba(0,255,255,0.4);touch-action:none;z-index:3;display:' + (touch ? 'block' : 'none') + ';', null, root);
S.knob = el('div', 'position:absolute;left:40px;top:40px;width:40px;height:40px;border-radius:50%;background:rgba(102,204,255,0.55);pointer-events:none;', null, S.joyEl);
// bottom sheets: HOW MANY (box, /10, x10) and GO TO KEY (box, GO)
var lab = 'font:bold ' + (phone ? 24 : 28) + 'px ' + FONT + ';color:' + C.blue + ';flex:1 1 100%;';
var sheetCss = 'position:absolute;left:50%;transform:translateX(-50%);bottom:calc(' + (S.btn + 18) + 'px + env(safe-area-inset-bottom,0px));width:min(640px,calc(100% - 16px));box-sizing:border-box;display:none;flex-wrap:wrap;gap:10px;align-items:center;padding:14px;background:rgba(0,0,0,0.9);border:2px solid rgba(0,255,255,0.5);border-radius:14px;z-index:3;';
S.sheetMany = el('div', sheetCss, null, root);
el('div', lab, 'HOW MANY KEYS (1 TO 2^53)', S.sheetMany);
S.countBox = inputBox(S.sheetMany, 100, function (v) {
var n = parseNum(v); if (isFinite(n) && n >= 1) changeCount(n); else S.countBox.value = fmt(S.N);
});
S.countBox.style.flex = '1'; S.countBox.style.minWidth = '0';
button('/10', S.sheetMany, function () { changeCount(Math.max(1, Math.floor(S.N / 10))); });
button('x10', S.sheetMany, function () { changeCount(Math.min(EXACT, S.N * 10)); });
S.sheetKey = el('div', sheetCss, null, root);
el('div', lab, 'GO TO KEY (0 TO 2^53 - 1)', S.sheetKey);
S.keyBox = inputBox(S.sheetKey, 100, function (v) { var k = parseNum(v); if (isFinite(k)) { closeSheets(); goToKey(k); } });
S.keyBox.style.flex = '1'; S.keyBox.style.minWidth = '0';
S.keyBox.placeholder = '123456';
S.flyRow = el('div', 'display:flex;flex-wrap:wrap;gap:10px;flex:1 1 100%;order:5;', null, S.sheetKey);
button('KEY 0', S.flyRow, function () { closeSheets(); S.boundary = null; goToKey(0); });
button(phone ? 'NEWEST' : 'NEWEST WORK', S.flyRow, function () { closeSheets(); if (S.N < 59637070538) setCount(59637070538); flyToNewest(24); },
'color:' + C.amber + ';border-color:rgba(255,176,0,0.6);');
S.linkBtn = button(phone ? 'LINK' : 'COPY LINK', S.flyRow, function () {
shareHash(); var u = S.shareUrl || location.href;
try { navigator.clipboard.writeText(u); } catch (e) { }
S.linkBtn.textContent = 'COPIED'; var own = S; clearTimeout(own.linkT); own.linkT = setTimeout(function () { own.linkT = 0; if (S === own) own.linkBtn.textContent = phone ? 'LINK' : 'COPY LINK'; }, 1500);
});
button('GO', S.sheetKey, function () { var k = parseNum(S.keyBox.value); if (isFinite(k)) { closeSheets(); goToKey(k); } },
'color:' + C.amber + ';border-color:' + C.amber + ';');
// the selected-key card (a corner instrument with a leader line to the dot)
S.card = el('div', 'position:absolute;display:none;max-width:calc(100% - 16px);box-sizing:border-box;background:rgba(0,0,0,0.7);border:2px solid ' + C.amber + ';border-radius:8px;padding:8px 14px;pointer-events:none;', null, root);
var wrapCss = phone ? 'overflow-wrap:anywhere;' : 'white-space:nowrap;';
S.cardKey = el('div', 'color:' + C.amber + ';font:bold ' + (phone ? 28 : 40) + 'px ' + FONT + ';' + wrapCss, '', S.card);
S.cardDist = el('div', 'color:#fff;font:bold ' + (phone ? 26 : 32) + 'px ' + FONT + ';' + wrapCss, '', S.card);
S.cardTurn = el('div', 'color:' + C.cyan + ';font:bold ' + (phone ? 26 : 32) + 'px ' + FONT + ';' + wrapCss, '', S.card);
S.cardSmall = el('div', 'color:' + C.blue + ';font:bold 24px ' + FONT + ';white-space:normal;', '', S.card);
S.cardReal = el('div', 'color:' + C.green + ';font:bold 24px ' + FONT + ';max-width:' + (phone ? '100%' : '560px') + ';white-space:normal;margin-top:4px;', '', S.card);
S.cardLink = el('a', 'display:none;pointer-events:auto;margin-top:6px;color:' + C.cyan + ';font:bold 24px ' + FONT + ';border:2px solid rgba(0,255,255,0.5);border-radius:8px;padding:6px 10px;text-decoration:none;overflow-wrap:anywhere;', '', S.card);
S.cardLink.target = '_blank'; S.cardLink.rel = 'noopener';
// WHY popup
S.why = el('div', 'position:absolute;inset:0;display:none;background:#000;overflow:auto;z-index:5;', null, root);
var whyClose = button('BACK', S.why, function () { S.why.style.display = 'none'; }, 'position:sticky;top:10px;float:right;margin:10px;color:#fff;border-color:rgba(255,255,255,0.6);');
whyClose.style.zIndex = 6;
S.whyBody = el('div', '', null, S.why);
// input
S.on = [];
function on(t, ev, fn, opt) { t.addEventListener(ev, fn, opt); S.on.push([t, ev, fn, opt]); }
on(S.joyEl, 'pointerdown', function (e) { e.preventDefault(); audioInit && audioInit(); S.joy.id = e.pointerId; try { S.joyEl.setPointerCapture(e.pointerId); } catch (x) { } joyAt(e); });
on(S.joyEl, 'pointermove', function (e) { if (e.pointerId === S.joy.id) joyAt(e); });
function joyUp(e) { if (e.pointerId !== S.joy.id) return; S.joy.id = null; S.joy.x = S.joy.y = 0; S.knob.style.left = S.knob.style.top = '40px'; shareHash(); }
on(S.joyEl, 'pointerup', joyUp); on(S.joyEl, 'pointercancel', joyUp);
on(cv, 'wheel', function (e) {
e.preventDefault(); audioInit();
var dy = e.deltaY * (e.deltaMode === 1 ? 33 : e.deltaMode === 2 ? 800 : 1);
if (e.ctrlKey) dy *= 3; // trackpad pinch arrives as ctrl+wheel with small deltas
var r = cv.getBoundingClientRect();
zoomAt(e.clientX - r.left, e.clientY - r.top, Math.exp(-dy * 0.0022));
var now = performance.now();
if (!S.lastTick || now - S.lastTick > 90) { S.lastTick = now; note(220 * Math.pow(2, Math.log10(S.cam.z / homeZoom() + 1) / 2), 0, 0.12, 0.025); }
}, { passive: false });
on(cv, 'pointerdown', function (e) {
audioInit();
cv.setPointerCapture && cv.setPointerCapture(e.pointerId);
if (S.sweep && S.scanOn && S.pointers.size === 0 && S.armId === null && S.sweep.grab(e)) { // the player holds the arm and scans by hand
S.armId = e.pointerId; S.anim = null; S.zoomAnim = null; closeSheets(); S.dirty = true; return;
}
var r = cv.getBoundingClientRect();
S.pointers.set(e.pointerId, { x: e.clientX - r.left, y: e.clientY - r.top, x0: e.clientX - r.left, y0: e.clientY - r.top, t0: performance.now() });
if (S.pointers.size === 2) S.pinch = pinchState();
S.anim = null; S.zoomAnim = null; cv.style.cursor = 'grabbing'; closeSheets();
if (document.activeElement && document.activeElement.blur && document.activeElement !== document.body) document.activeElement.blur();
});
on(cv, 'pointermove', function (e) {
if (e.pointerId === S.armId) { S.sweep.grab(e); return; }
var p = S.pointers.get(e.pointerId); if (!p) return;
var r = cv.getBoundingClientRect(), x = e.clientX - r.left, y = e.clientY - r.top;
if (S.pointers.size === 1) {
S.cam.cx -= (x - p.x) / S.cam.z; S.cam.cy += (y - p.y) / S.cam.z;
if (Math.hypot(x - p.x0, y - p.y0) > 8) p.moved = true;
p.x = x; p.y = y;
} else if (S.pointers.size >= 2) {
p.x = x; p.y = y; p.moved = true;
var ps = pinchState(), q = S.pinch;
if (q && q.d > 0) {
var w = [S.cam.cx + (q.mx - S.W / 2) / S.cam.z, S.cam.cy - (q.my - S.H / 2) / S.cam.z];
S.cam.z = clampZ(S.cam.z * ps.d / q.d);
S.cam.cx = w[0] - (ps.mx - S.W / 2) / S.cam.z; S.cam.cy = w[1] + (ps.my - S.H / 2) / S.cam.z;
}
S.pinch = ps; S.pinched = true;
}
S.dirty = true;
});
function up(e) {
if (e.pointerId === S.armId) { S.armId = null; if (S.sweep) S.sweep.release(); return; }
var p = S.pointers.get(e.pointerId); if (!p) return;
S.pointers.delete(e.pointerId);
if (S.pointers.size === 1) S.pinch = null;
if (S.pointers.size === 0) {
cv.style.cursor = 'grab';
if (!p.moved && !S.pinched && e.type === 'pointerup' && performance.now() - p.t0 < 800) tapAt(p.x, p.y);
S.pinched = false;
}
}
on(cv, 'pointerup', up); on(cv, 'pointercancel', up);
on(document, 'keydown', function (e) {
if (!S) return;
var a = document.activeElement, inBox = a && (a.tagName === 'INPUT' || a.tagName === 'TEXTAREA');
if (e.key === 'Escape') {
if (inBox) { a.blur(); return; }
if (S.sheetMany.style.display === 'flex' || S.sheetKey.style.display === 'flex') { closeSheets(); return; }
if (S.why.style.display === 'block') { S.why.style.display = 'none'; return; }
close(); return;
}
if (inBox) return;
audioInit();
if (e.key === '+' || e.key === '=') zoomAt(S.W / 2, S.H / 2, 2);
else if (e.key === '-' || e.key === '_') zoomAt(S.W / 2, S.H / 2, 0.5);
else if (e.key === 'h' || e.key === 'H' || e.key === '0') goHome(true);
else if (e.key === 'ArrowLeft') { S.cam.cx -= 80 / S.cam.z; S.dirty = true; }
else if (e.key === 'ArrowRight') { S.cam.cx += 80 / S.cam.z; S.dirty = true; }
else if (e.key === 'ArrowUp') { S.cam.cy += 80 / S.cam.z; S.dirty = true; }
else if (e.key === 'ArrowDown') { S.cam.cy -= 80 / S.cam.z; S.dirty = true; }
});
on(window, 'resize', function () { layout(); });
layout();
var w1 = realWafer();
setCount(w1 ? w1.space : 1000000);
goHome(false);
S.raf = requestAnimationFrame(frame);
// the first second moves: a slow zoom in from the whole circle
S.cam.z = homeZoom() * 0.6; S.cam.cy = homeCy(); goHome(true);
var hk = readHash();
if (hk) { if (hk.key >= S.N) setCount(Math.min(EXACT, hk.key + 1)); var hq = KuiperLaw.place(hk.key); selectKey(hk.key, 'link'); S.anim = null; S.cam.cx = hq.x; S.cam.cy = hq.y; S.cam.z = clampZ(hk.zoom); S.dirty = true; }
attachSweep();
window.__zoomApi = { issued: issued, issuedBelow: issuedBelow, real: function () { return realView(); }, setReal: setReal, setScan: setScan,
sweep: function () { return S && S.sweep; }, stars: function () { return S && S.st ? { n: S.st.n, k: Array.prototype.slice.call(S.st.k, 0, S.st.n) } : null; },
setCam: function (cx, cy, z) { S.anim = null; S.zoomAnim = null; S.cam.cx = cx; S.cam.cy = cy; S.cam.z = clampZ(z); S.dirty = true; },
card: function () { return S && S.card.style.display !== 'none' ? S.card.innerText : ''; }, selEmpty: function () { return S && !!S.sel && !!S.selEmpty; }, scanOn: function () { return S && S.scanOn; },
newest: flyToNewest, address: address, realWafer: realWafer, goToKey: goToKey, setCount: changeCount, home: goHome, zoomAt: zoomAt, select: selectKey };
}
function setReal(on) {
var w = realWafer();
if (on && !w) { S.real = false; paintToggles(); return; }
S.real = !!on; S.realNote = null;
if (S.real && S.N > w.space) setCount(w.space);
else setCount(S.N);
S.capSig = null; S.dirty = true;
note(S.real ? 523 : 392, 0, 0.3, 0.05);
}
function setScan(on) {
S.scanOn = !!on && !!S.sweep;
if (S.sweep) S.sweep.setOn(S.scanOn);
if (!S.scanOn) { S.armId = null; if (S.sweep) S.sweep.release(); }
paintToggles(); S.dirty = true;
}
// a toggle is lit (bright outline) when on, dim when off
function paintToggles() {
if (!S || !S.realBtn) return;
function lit(b, onv, col) { b.style.color = onv ? col : 'rgba(0,255,255,0.4)'; b.style.borderColor = onv ? col : 'rgba(0,255,255,0.25)'; }
lit(S.realBtn, realView(), 'rgba(34,238,119,0.9)');
lit(S.scanBtn, S.scanOn && !!S.sweep, 'rgba(0,255,255,0.85)');
S.realBtn.style.display = realWafer() ? '' : 'none';
S.scanBtn.style.display = window.KGSweep && S.sweep ? '' : 'none';
}
function makeSweep() {
if (!S || S.sweep || !window.KGSweep) return;
var out = [0, 0];
S.sweep = window.KGSweep.create({
getStars: function () { return S && S.st; },
center: function () { return ORIGIN; },
toScreen: function (x, y, o) { o[0] = S.W / 2 + (x - S.cam.cx) * S.cam.z; o[1] = S.H / 2 - (y - S.cam.cy) * S.cam.z; return o; },
radius: function () { return S.rim * S.cam.z; },
onPing: function () { },
sound: function () { return S && !S.muted ? S.ac : null; }
});
S.sweep.setOn(S.scanOn);
paintToggles(); S.dirty = true;
}
// the radar sweep is a separate file: zoom.js never loads sweep.js itself. If a page has already loaded it
// (window.KGSweep), the SCAN toggle appears and uses it; otherwise SCAN stays hidden and nothing changes.
function attachSweep() {
if (window.KGSweep) makeSweep();
else { S.scanOn = false; paintToggles(); }
}
function openSheet(which) {
var m = which === 'many', s = m ? S.sheetMany : S.sheetKey, was = s.style.display === 'flex';
closeSheets();
if (was) return;
s.style.display = 'flex';
if (m) S.countBox.value = fmt(S.N);
(m ? S.countBox : S.keyBox).focus();
}
function closeSheets() { if (!S) return; S.sheetMany.style.display = 'none'; S.sheetKey.style.display = 'none'; }
function changeCount(n) {
var wasHome = S.cam.z <= homeZoom() * 1.08;
var old = S.N;
setCount(n);
note(S.N > old ? 523 : 330, 0, 0.35, 0.06);
if (S.sel && S.sel.key >= S.N) S.sel = null;
if (wasHome) goHome(true);
}
function pinchState() {
var a = Array.from(S.pointers.values());
return { mx: (a[0].x + a[1].x) / 2, my: (a[0].y + a[1].y) / 2, d: Math.hypot(a[0].x - a[1].x, a[0].y - a[1].y) };
}
function joyAt(e) {
var r = S.joyEl.getBoundingClientRect(), h = r.width / 2, x = (e.clientX - r.left - h) / (h - 10), y = (e.clientY - r.top - h) / (h - 10);
var d = Math.hypot(x, y); if (d > 1) { x /= d; y /= d; } S.joy.x = x; S.joy.y = y;
S.knob.style.left = (40 + x * 40) + 'px'; S.knob.style.top = (40 + y * 40) + 'px';
}
function stepJoy(now) {
var j = S.joy, dt = Math.min(0.1, Math.max(0, (now - (S.joyT || now)) / 1000)); S.joyT = now;
if (!j) return false;
var SP = 700, tx = j.x * SP, ty = -j.y * SP, k = 1 - Math.exp(-dt * 8); // screen px per second, eased like walk-fps
j.vx += (tx - j.vx) * k; j.vy += (ty - j.vy) * k;
if (Math.abs(j.vx) + Math.abs(j.vy) < 0.5) { j.vx = j.vy = 0; return false; }
S.anim = null; S.zoomAnim = null;
S.cam.cx += j.vx * dt / S.cam.z; S.cam.cy += j.vy * dt / S.cam.z;
return true;
}
function frame(now) {
if (!S) return;
var dt = Math.min(0.1, Math.max(0, (now - (S.lastFrame || now)) / 1000)); S.lastFrame = now;
var moving = stepAnim(now) || stepJoy(now);
if (S.sweep) S.sweep.step(dt);
if (moving || S.dirty) { S.dirty = false; draw(true); }
else if (S.sweep && S.scanOn) draw(false);
var busy = moving || S.pointers.size > 0 || S.armId !== null, op = busy ? '0.15' : '1';
if (S.bottom.style.opacity !== op) { S.bottom.style.opacity = op; S.top.style.opacity = busy ? '0.5' : '1'; if (S.toggles) S.toggles.style.opacity = op; }
showCaption();
S.raf = requestAnimationFrame(frame);
}
function close() {
if (!S) return;
var s = S;
cancelAnimationFrame(s.raf); clearTimeout(s.linkT);
(s.on || []).forEach(function (o) { o[0].removeEventListener(o[1], o[2], o[3]); });
try { if (s.sweep) s.sweep.destroy(); } catch (e) { }
try { if (s.ac) s.ac.close(); } catch (e) { }
if (s.root && s.root.parentNode) s.root.parentNode.removeChild(s.root);
S = null;
try { s.host.dispatchEvent(new CustomEvent('kgclose', { bubbles: true, detail: { id: 'zoom' } })); } catch (e) { }
}
(window.KGModules = window.KGModules || []).push({
id: 'zoom', label: 'ZOOM', sentence: 'Zoom into the Kuiper',
open: open, close: close
});
})();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 1–390 of 1166 · version 2026-10-05 06:09 · 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
- isqrt, stepOf, modParts, sectorOf, pad, D, dText, dFloor, dNum, dEq, dCmpSqT, dAddTenths, parseDec, parseWhole, sqrtInfo, degText, turnText, sectorsFor, fastStep, sheetFormulas, seeded, makeGame, newSlot, emit, slot, ringA, secOf, inBand, inSec, turnsOK
- 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:1-390 · 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
/* LEARN THE KUIPER: one.js. One circle, one dot, two numbers. The whole specification is ONE-SPEC.md with its
* three amendments.
* SQRT( [A] ) the first number sets how far out the dot is, and nothing else
* MOD( [B] x [M] , [C] ) the second number sets where round the circle the dot is, and nothing else
* LINK both numbers are the same KEY: the real Kuiper rule
* Three parts in one classic script: (1) exact arithmetic, (2) the game with no screen (node can run it),
* (3) the screen. Nothing is fetched. Sources of borrowed ideas are named where they are used.
*/
(function (root) {
'use strict';
// =====================================================================================================
// 1. EXACT ARITHMETIC. Every number shown or judged comes from here, in whole numbers (BigInt).
// =====================================================================================================
var MAX = 9007199254740991, MAXB = BigInt(MAX);
var REAL_M = 2654435769n, REAL_C = 4294967296n;
var LEVELS = [[1n, 4n], [1n, 12n], [1n, 360n], [5n, 12n], [222n, 360n], [REAL_M, REAL_C]];
// rings the linked targets are drawn from, by how many have been found: near the centre first, then outward
var STAGES = [[1, 3], [2, 6], [4, 10], [8, 20], [15, 40], [30, 100], [60, 300], [100, 1000]];
// what each target of a level needs, in order: [B] alone, then [A] alone, then both; a digit = whole turns
// asked for; d = a distance between two rings (a decimal [A]). After these, three targets ask for the LINK.
var PLAN = ['B', 'B', 'B1', 'A', 'A', 'A', 'AB', 'AB', 'AB', 'AB2', 'Ad', 'ABd', 'AB1'];
var LATER = ['AB', 'AB1', 'ABd', 'AB2'];
var LINK_AT = PLAN.length, LINK_N = 3;
var LIMIT_LINE = 'THAT NUMBER IS TOO LARGE FOR THIS COMPUTER TO SHOW. THE REAL LIMIT HERE IS 9,007,199,254,740,991.';
// FLOOR(SQRT(n)) in whole numbers: a first guess from the machine root, then corrected until n x n <= key < (n + 1) x (n + 1)
function isqrt(n) {
if (n < 2n) return n;
var x = BigInt(Math.floor(Math.sqrt(Number(n))));
while (x * x > n) x -= 1n;
while ((x + 1n) * (x + 1n) <= n) x += 1n;
return x;
}
function stepOf(k, M, C) { var s = (k * M) % C; return s < 0n ? s + C : s; } // the floor rule: MOD( -1 , 12 ) = 11
// B x M = Q x C + S with 0 <= S < C, for any whole B (negative too)
function modParts(b, M, C) { var P = b * M, S = stepOf(b, M, C); return { P: P, S: S, Q: (P - S) / C }; }
// which of N equal sectors a step stands in. Sector j is centred on j / N of a turn, so on a small circle
// (N = C) sector j is exactly step j with the mark in its middle. Whole numbers only.
function sectorOf(step, C, N) { var n = BigInt(N); return Number(((2n * step * n + C) / (2n * C)) % n); }
function pad(v, n) { var s = v.toString(); while (s.length < n) s = '0' + s; return s; }
// ---- a decimal number as typed: { n, s } means n / 10^s, exactly
function D(n, s) { while (s > 0 && n % 10n === 0n) { n /= 10n; s--; } return { n: n, s: s }; }
function dText(d) { if (d.s === 0) return d.n.toString(); var t = pad(d.n, d.s + 1); return t.slice(0, -d.s) + '.' + t.slice(-d.s); }
function dFloor(d) { return d.n / 10n ** BigInt(d.s); }
function dNum(d) { return Number(d.n) / Math.pow(10, d.s); }
function dEq(a, b) { return a.n === b.n && a.s === b.s; }
// is the number below, at, or above ( t / 10 ) squared? t is a distance in tenths. Exact.
function dCmpSqT(d, t) { var l = d.n * 100n, r = BigInt(t) * BigInt(t) * 10n ** BigInt(d.s); return l < r ? -1 : l > r ? 1 : 0; }
function dAddTenths(d, k) { var s = Math.max(d.s, 1), n = d.n * 10n ** BigInt(s - d.s) + BigInt(k) * 10n ** BigInt(s - 1); return n < 0n ? D(0n, 0) : D(n, s); }
// a typed decimal, 0 or more: { ok, value } or { ok: false, tooLarge }. Up to six places after the point.
function parseDec(str) {
var m = /^(\d*)(?:\.(\d*))?$/.exec(typeof str === 'string' ? str : '');
if (!m || (m[1] === '' && !m[2])) return { ok: false, tooLarge: false };
var whole = (m[1] || '0').replace(/^0+(?=\d)/, ''), frac = m[2] || '';
if (whole.length > 16 || BigInt(whole) > MAXB) return { ok: false, tooLarge: true };
if (BigInt(whole + frac) > MAXB * 10n ** BigInt(frac.length)) return { ok: false, tooLarge: true };
if (frac.length > 6) return { ok: false, tooLarge: false };
return { ok: true, value: D(BigInt(whole + frac), frac.length) };
}
// a typed whole number, negative allowed when signed: { ok, value } or { ok: false, tooLarge }
function parseWhole(str, signed) {
if (typeof str !== 'string' || !(signed ? /^-?\d+$/ : /^\d+$/).test(str)) return { ok: false, tooLarge: false };
var neg = str[0] === '-', digits = (neg ? str.slice(1) : str).replace(/^0+(?=\d)/, '');
if (digits.length > 16 || BigInt(digits) > MAXB) return { ok: false, tooLarge: true };
var v = BigInt(digits);
return { ok: true, value: neg ? -v : v };
}
// the square root of a decimal. Exact when there is an exact answer (6.25 gives 2.5, to as many places as it
// needs); otherwise two places, marked as rounded, and never the next whole number before it is reached.
function sqrtInfo(d) {
var n = d.n, s = d.s;
if (s % 2) { n *= 10n; s++; }
var r = isqrt(n);
if (r * r === n) return { exact: true, text: dText(D(r, s / 2)) };
var t = s <= 6 ? isqrt(n * 10n ** BigInt(6 - s)) : isqrt(n / 10n ** BigInt(s - 6)); // FLOOR( SQRT x 1000 )
var h = (t + 5n) / 10n, whole = isqrt(dFloor(d));
if (h / 100n > whole) h = whole * 100n + 99n;
return { exact: false, text: (h / 100n).toString() + '.' + pad(h % 100n, 2) };
}
// 360 x STEP / C to four places, rounded from the exact fraction
function degText(step, C) {
var u = (step * 3600000n * 2n + C) / (2n * C);
if (u >= 3600000n) u = 3599999n;
return (u / 10000n).toString() + '.' + pad(u % 10000n, 4);
}
// the signed turn from one step to another, in degrees to two places: the short way round
function turnText(s1, s2, C) {
var d = (((s2 - s1) % C) + C) % C, neg = false;
if (2n * d > C) { d = C - d; neg = true; }
var u = (d * 36000n * 2n + C) / (2n * C);
return (neg && u > 0n ? '-' : '+') + (u / 100n).toString() + '.' + pad(u % 100n, 2);
}
// how many sectors a target can have on a circle of C steps, largest cell first
function sectorsFor(C) {
if (C <= 24n) return [Number(C)];
var out = [12, 36, 120, 360].filter(function (n) { return BigInt(n) <= C; });
if (C < 360n && out[out.length - 1] !== Number(C)) out.push(Number(C));
return out;
}
// the same step in ordinary numbers, for searching many keys quickly (keys 0 and up). Exact for every key
// up to MAX: the real pair uses the split form of LESSON-CONTRACT.md (2654435769 = 40503 x 65536 + 31161);
// other pairs reduce the key first; anything that could round goes back to BigInt.
function fastStep(M, C) {
if (M === REAL_M && C === REAL_C) return function (k) { var a = k % 4294967296; return (((a * 40503) % 65536) * 65536 + a * 31161) % 4294967296; };
var c = Number(C), mr = Number(M % C);
if (C <= MAXB && (c - 1) * mr <= MAX) return function (k) { return ((k % c) * mr) % c; };
return function (k) { return Number((BigInt(k) * M) % C); };
}
// the two lines as spreadsheet formulas (first number in A2, second in B2). The real pair copies the split
// form that stays exact (LESSON-CONTRACT.md). Linked: both read the one key in A2.
function sheetFormulas(M, C, linked) {
var x = linked ? 'A2' : 'B2';
var b = (M === REAL_M && C === REAL_C)
? '=MOD(MOD(MOD(' + x + ',4294967296)*40503,65536)*65536+MOD(' + x + ',4294967296)*31161,4294967296)'
: (M === 1n ? '=MOD(' + x + ',' + C.toString() + ')' : '=MOD(' + x + '*' + M.toString() + ',' + C.toString() + ')');
return ['=SQRT(A2)', b];
}
// a small repeatable random source for tests (mulberry32); play uses Math.random
function seeded(a) {
return function () { a |= 0; a = (a + 0x6D2B79F5) | 0; var t = Math.imul(a ^ (a >>> 15), 1 | a); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
}
// =====================================================================================================
// 2. THE GAME, with no screen. Numbers in, events out.
// A typed, committed number that completes a target gives the full score; a rolled one a small one.
// =====================================================================================================
function makeGame(opts) {
opts = opts || {};
var rnd = opts.random || Math.random;
var M = LEVELS[0][0], C = LEVELS[0][1], level = 0, fast = fastStep(M, C);
var slots = [], i;
for (i = 0; i < 7; i++) slots.push(newSlot()); // six levels and one for the player's own [M] and [C]
var A = D(4n, 0), B = 0n, pA = A, pB = B, linked = false, sel = 'B', buf = null, score = 0, listeners = [];
var g = {}, inputBlocked = false;
function newSlot() { return { found: 0, lit: [], target: null, tries: 0, ghosts: [] }; }
function emit(type, data) { data = data || {}; for (var j = 0; j < listeners.length; j++) listeners[j](type, data); }
function slot() { return slots[level]; }
function ringA(a) { return Number(isqrt(dFloor(a))); }
function secOf(b, N) { return sectorOf(stepOf(b, M, C), C, N); }
function inBand(a, t) { return dCmpSqT(a, t.t0) >= 0 && dCmpSqT(a, t.t1) < 0; }
function inSec(b, t) { return secOf(b, t.N) === t.sec; }
function turnsOK(b, t) { return !t.turns || modParts(b, M, C).Q >= BigInt(t.turns); }
// one rule draws the cell and judges the hit: the distance band, the sector, the whole turns, the link
function isHit(a, b, t) { return !!t && inBand(a, t) && inSec(b, t) && turnsOK(b, t) && (!t.link || linked); }
function fastSector(st, N) {
var c = Number(C);
if (C <= MAXB && 2 * c * N + c <= MAX) {
var x = 2 * st * N + c, y = 2 * c, q = Math.floor(x / y), r = x - q * y;
if (r < 0) q--; else if (r >= y) q++;
return q % N;
}
return sectorOf(BigInt(st), C, N);
}
function isLit(s, t) { for (var j = 0; j < s.lit.length; j++) { var l = s.lit[j]; if (l.t0 === t.t0 && l.t1 === t.t1 && l.N === t.N && l.sec === t.sec) return true; } return false; }
// the first [B] of 0 or more that stands in a sector after going round at least `turns` times, or -1
function findB(sec, N, turns) {
var b0 = 0;
if (turns) { if (M === 0n) return -1; var need = (BigInt(turns) * C + M - 1n) / M; if (need > MAXB - 400000n) return -1; b0 = Number(need); }
var span = C > 400000n ? 400000 : Number(C);
for (var k = b0; k <= b0 + span; k++) if (fastSector(fast(k), N) === sec) return k;
return -1;
}
// the first key of a ring that stands in a sector, or -1
function findKey(n, N, sec) {
var lo = n * n, hi = Math.min(MAX, lo + Math.min(2 * n, 400000));
for (var k = lo; k <= hi; k++) if (fastSector(fast(k), N) === sec) return k;
return -1;
}
// a linked target is made from a real key T: the cell that T's dot stands in. It asks for the link.
function keyTarget(s) {
var gi = Math.max(0, s.found - LINK_AT), l = sectorsFor(C), N = l[Math.min(l.length - 1, Math.floor(gi / 4))];
var st = STAGES[Math.min(STAGES.length - 1, Math.floor(gi / 3))];
var cr = ringA(A), cs = secOf(B, N), fallback = null, cand = null;
for (var a = 0; a < 60; a++) {
var n = st[0] + Math.floor(rnd() * (st[1] - st[0] + 1));
var T = n * n + Math.floor(rnd() * (2 * n + 1));
cand = { t0: n * 10, t1: n * 10 + 10, N: N, sec: sectorOf(stepOf(BigInt(T), M, C), C, N), turns: 0, link: true, kind: 'KEY', a: String(T), b: String(T), hand: false };
if (n === cr && cand.sec === cs) continue; // never under the dot
fallback = fallback || cand;
if (!isLit(s, cand)) return cand;
}
return fallback || cand;
}
// an unlinked target is made from a real answer too: an [A] and a [B] that hit it are kept with it
function freeTarget(s) {
var f = s.found, later = f - LINK_AT - LINK_N, kind = f < PLAN.length ? PLAN[f] : LATER[Math.max(0, later) % LATER.length];
var N = sectorsFor(C)[0], cr = ringA(A), cs = secOf(B, N);
var wantA = kind.indexOf('A') >= 0, wantB = kind.indexOf('B') >= 0, dec = kind.indexOf('d') >= 0;
var turns0 = kind.indexOf('2') >= 0 ? 2 : kind.indexOf('1') >= 0 ? 1 : 0;
var st = f < PLAN.length ? [1, 3] : STAGES[Math.min(STAGES.length - 1, 1 + Math.floor(Math.max(0, later) / 4))];
var best = null, n, t0, t1, sec, b, turns, j, cand;
for (var a = 0; a < 40; a++) {
turns = turns0;
n = (!wantA && !dec && cr >= 1 && cr <= 9) ? cr : st[0] + Math.floor(rnd() * (st[1] - st[0] + 1)); // [A] already right: only [B] is needed
t0 = dec ? n * 10 + 4 : n * 10; t1 = dec ? n * 10 + 6 : n * 10 + 10;
if ((wantA || dec) && dCmpSqT(A, t0) >= 0 && dCmpSqT(A, t1) < 0) continue; // it must need a new [A]
sec = cs;
if (wantB) for (j = 0; j < 40; j++) { sec = fastSector(fast(Math.floor(rnd() * Math.min(Number(C), 1000000))), N); if (sec !== cs) break; }
b = findB(sec, N, turns);
if (b < 0 && turns) { turns = 0; b = findB(sec, N, 0); }
if (b < 0) continue;
var tc = dec ? (t0 + t1) / 2 : t0;
cand = { t0: t0, t1: t1, N: N, sec: sec, turns: turns, link: false, kind: kind, a: dText(D(BigInt(tc * tc), 2)), b: String(b), hand: false };
if (isHit(A, B, cand)) continue;
best = best || cand;
if (!isLit(s, cand)) return cand;
}
if (best) return best;
n = cr === 1 ? 2 : 1; // nothing else fits (a circle of one step, say): the next ring in or out
return { t0: n * 10, t1: n * 10 + 10, N: N, sec: cs, turns: 0, link: false, kind: 'A', a: String(n * n), b: String(Math.max(0, findB(cs, N, 0))), hand: false };
}
function makeTarget(s) { return (linked || (s.found >= LINK_AT && s.found < LINK_AT + LINK_N)) ? keyTarget(s) : freeTarget(s); }
// more for a smaller target (more sectors, longer numbers), more for fewer typed tries, twice for whole
// turns or a decimal when typed; a rolled find is a small quiet score
function basePoints(t) { return 10 * (Math.round(Math.log2(Math.max(1, t.N))) + String(Math.floor(t.t0 * t.t0 / 100)).length); }
function points(t, tries, typed) {
var b = basePoints(t), hard = t.turns > 0 || t.t1 - t.t0 < 10;
if (!typed) return Math.max(1, Math.round(b * 0.2));
return Math.max(Math.ceil(b * 0.3), Math.round(b / (1 + 0.25 * (Math.max(1, tries) - 1)))) * (hard ? 2 : 1);
}
function award(typed) {
var s = slot(), t = s.target, tries = Math.max(1, s.tries), p = points(t, tries, typed);
score += p;
s.lit.push({ t0: t.t0, t1: t.t1, N: t.N, sec: t.sec, a: dText(A), b: B.toString() });
if (s.lit.length > 400) s.lit.shift();
s.found++; s.tries = 0; s.ghosts = [];
s.target = makeTarget(s);
emit('hit', { typed: typed, points: p, tries: tries, target: t, score: score, a: A, b: B, key: linked ? B : null });
}
function setNumbers(m, c, how) {
if (c < 1n || m < 0n || m > MAXB || c > MAXB) return false;
var changed = m !== M || c !== C;
M = m; C = c; fast = fastStep(M, C);
var li = -1;
for (var j = 0; j < LEVELS.length; j++) if (LEVELS[j][0] === M && LEVELS[j][1] === C) li = j;
if (li >= 0) level = li;
else { level = 6; if (changed || !slots[6].target) slots[6] = newSlot(); }
if (!slot().target || (linked && !slot().target.link)) slot().target = makeTarget(slot());
emit('change', { how: how || 'numbers' });
return true;
}
function setAB(a, b) { if (!dEq(a, A) || b !== B) { pA = A; pB = B; } A = a; B = b; }
function setOne(which, v) { // v: a decimal for [A], a whole number for [B]; linked: one whole key for both
if (linked) setAB(D(v, 0), v);
else if (which === 'A') setAB(v, B);
else setAB(A, v);
}
// what a half-typed string means for the selected number, or null when it is not a number yet
function parseSel(str) {
var p;
if (sel === 'A' && !linked) { p = parseDec(str.replace(/\.$/, '')); return p.ok ? p.value : null; }
p = parseWhole(str, sel === 'B' && !linked); return p.ok ? p.value : null;
}
function fieldText() { return sel === 'M' ? M.toString() : sel === 'C' ? C.toString() : sel === 'A' ? dText(A) : B.toString(); }
// one key of the keypad or the keyboard: '0'..'9', 'dot', 'sign', 'back', 'clear', 'enter'
g.press = function (name) {
var cur, next, p, onAB = sel === 'A' || sel === 'B';
if (/^[0-9]$/.test(name)) {
if (inputBlocked) return; // freeze only while this refused draft remains active
cur = buf === null ? '' : buf; // after a commit the next digit starts a new number
next = cur === '0' ? name : cur === '-0' ? '-' + name : cur + name;
if (sel === 'A' && !linked) {
p = parseDec(next);
if (!p.ok) { buf=next.slice(0,128); emit('change',{how:'preview',which:sel}); if (p.tooLarge) { inputBlocked = true; emit('limit'); } return; }
} else {
p = parseWhole(next, sel === 'B' && !linked);
if (!p.ok) { buf=next.slice(0,128); emit('change',{how:'preview',which:sel}); if (p.tooLarge) { inputBlocked = true; emit('limit'); } return; } // the last good value stays
}
buf = next; emit('change', { how: 'preview', which: sel }); return;
}
if (name === 'dot') {
if (inputBlocked) return;
if (sel !== 'A' || linked) return;
cur = buf === null ? '' : buf;
if (cur.indexOf('.') >= 0) return;
buf = (cur === '' ? '0' : cur) + '.'; emit('change', { how: 'preview', which: sel }); return;
}
if (name === 'sign') {
if (inputBlocked) return;
if (sel !== 'B' || linked) return;
cur = buf === null ? '' : buf;
buf = cur[0] === '-' ? cur.slice(1) : '-' + cur; emit('change', { how: 'preview', which: sel }); return;
}
if (name === 'back') { inputBlocked = false; cur = buf === null ? fieldText() : buf; buf = cur.slice(0, -1); emit('change', { how: 'preview', which: sel }); return; }
if (name === 'clear') { inputBlocked = false; buf = ''; emit('change', { how: 'preview', which: sel }); return; }
if (name === 'enter') {
if (buf === null) return false;
if (inputBlocked) { g.dismissRefusal(); emit('limit'); return false; }
if (onAB) {
var v = parseSel(buf);
if (v === null) { if ((sel==='A'&&!linked?parseDec(buf):parseWhole(buf,sel==='B'&&!linked)).tooLarge) emit('limit'); return false; }
var s = slot(), which = sel;
// A commit of the same numerical value is not another try or a reward.
var changed = linked ? v !== B || !dEq(A, D(v, 0)) : which === 'A' ? !dEq(A, v) : v !== B;
if (!changed) { buf = null; inputBlocked = false; emit('change', { how: 'commit', which: which }); return true; }
s.tries++;
setOne(which, v); buf = null; inputBlocked = false;
emit('change', { how: 'commit', which: which });
if (isHit(A, B, s.target)) award(true);
else if (!s.ghosts.some(function (q) { return dEq(q.a, A) && q.b === B; })) { s.ghosts.push({ a: A, b: B }); if (s.ghosts.length > 60) s.ghosts.shift(); }
return true;
}
var f = sel, pv = parseWhole(buf, false);
if (!pv.ok) { if (pv.tooLarge) emit('limit'); return false; }
sel = 'B'; buf = null; inputBlocked = false;
if (!pv.ok || (f === 'C' && pv.value < 1n) || !setNumbers(f === 'M' ? pv.value : M, f === 'C' ? pv.value : C)) emit('change', { how: 'field' });
return true;
}
};
// Timeout/tick discard only a refused draft; a later valid edit must survive.
g.dismissRefusal = function () {
if (!inputBlocked) return;
buf = null; inputBlocked = false; emit('change', { how: 'field' });
};
// rolling: the number steps, the dot answers. fine = tenths, for [A] only.
g.roll = function (which, steps, fine) {
if (!steps) return;
if (which === 'M' || which === 'C') {
var v = (which === 'M' ? M : C) + BigInt(steps);
if (v > MAXB) { emit('limit'); return; }
if (v < (which === 'C' ? 1n : 0n)) return;
buf = null; inputBlocked = false; setNumbers(which === 'M' ? v : M, which === 'C' ? v : C); return;
}
buf = null; inputBlocked = false; sel = which;
if (linked) {
var k = B + BigInt(steps);
if (k > MAXB) { emit('limit'); k = MAXB; }
if (k < 0n) k = 0n;
setAB(D(k, 0), k);
} else if (which === 'A') {
var a = dAddTenths(A, fine ? BigInt(steps) : BigInt(steps) * 10n);
if (dFloor(a) > MAXB) { emit('limit'); return; }
setAB(a, B);
} else {
var b = B + BigInt(steps);
if (b > MAXB || b < -MAXB) { emit('limit'); return; }
setAB(A, b);
}
emit('change', { how: 'roll', which: which, steps: steps });
};
// the roll has come to rest: a target reached this way is found quietly
g.settle = function () { if (buf === null && isHit(A, B, slot().target)) { award(false); return true; } return false; };
g.select = function (f) { if ('ABMC'.indexOf(f) < 0 || f.length !== 1) return; sel = f; buf = null; inputBlocked = false; emit('change', { how: 'field' }); };
g.setLevel = function (li) { if (li < 0 || li > 5) return; if (sel !== 'A') sel = 'B'; buf = null; inputBlocked = false; setNumbers(LEVELS[li][0], LEVELS[li][1], 'level'); };
// LINK: both numbers become the same KEY. The key is the selected number, as a whole number of 0 or more.
g.setLink = function (on) {
on = !!on; if (on === linked) return;
var s = slot();
buf = null; inputBlocked = false; if (sel !== 'A') sel = 'B';
if (on) { var k = sel === 'A' ? dFloor(A) : (B < 0n ? 0n : B); linked = true; setAB(D(k, 0), k); }
else linked = false;
// the target must suit the way of playing: a linked target is always one a single key can hit
if (on ? !s.target.link : (s.target.link && !(s.found >= LINK_AT && s.found < LINK_AT + LINK_N))) { s.target = makeTarget(s); s.tries = 0; s.ghosts = []; }
emit('change', { how: 'link' });
};
// press and hold: the cell under the finger becomes the target, if a number can stand in it; otherwise the
// nearest cell of that ring that one can. So a target is always hittable.
g.setTargetAt = function (r, turn) {
var s = slot(), N = s.target ? s.target.N : sectorsFor(C)[0], c = Number(C);
var n = Math.max(1, Math.min(94906264, Math.floor(r)));
turn = ((turn % 1) + 1) % 1;
var want = Math.round(turn * N) % N, made = linked ? findKey(n, N, want) : findB(want, N, 0);
if (made < 0) { // nearest sector that a number does reach
var lo = linked ? n * n : 0, hi = linked ? Math.min(MAX, lo + Math.min(2 * n, 400000)) : Math.min(c, 400000), nd = Infinity;
for (var k = lo; k <= hi; k++) { var da = Math.abs(fast(k) / c - turn); if (da > 0.5) da = 1 - da; if (da < nd) { nd = da; made = k; } }
}
var sec = fastSector(fast(made), N);
s.target = { t0: n * 10, t1: n * 10 + 10, N: N, sec: sec, turns: 0, link: linked, kind: linked ? 'KEY' : 'AB', a: String(linked ? made : n * n), b: String(made), hand: true };
s.tries = 0; s.ghosts = [];
emit('target', { hand: true });
return s.target;
};
// how many keys of its ring hit a linked target (every key of the ring is tried)
g.countKeys = function (t) {
var n = t.t0 / 10, lo = n * n, hi = lo + 2 * n, cnt = 0;
for (var k = lo; k <= hi; k++) if (fastSector(fast(k), t.N) === t.sec) cnt++;
return cnt;
};
g.isHit = function (a, b, t) { return isHit(a, b, t || slot().target); };
// how near the dot is: 1 in the cell, falling with the ring gap and with the angle to the sector
g.warmth = function (a, b) {
var t = slot().target; if (!t) return 0;
var inB = inBand(a, t), inS = inSec(b, t);
if (inB && inS) return 1;
var d = Math.sqrt(dNum(a)), mid = (t.t0 + t.t1) / 20, wr = inB ? 1 : 1 - Math.min(1, Math.abs(d - mid) / (mid * 0.5 + 2));
var ang = Number(stepOf(b, M, C)) / Number(C), da = Math.abs(ang - t.sec / t.N); if (da > 0.5) da = 1 - da;