In this section
- Play render · kuiper-belt / learn-the-kuiper/202610050609/play.js lines 615–1314
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 615–1314 of 1722 · version 2026-10-05 06:09 (continued from section 1537) · 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
- warm, defaults, rng, sprite, glowSprite, nowMs, open, iconBtn, on, need, close, muted, showMute, readHash, hashText, f, saveHash, findDec, buildFormula, dA, selN, refresh, chips, tween, setNow, busy, windDur, set, mark, onInput
- 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:615-1314 · 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
if (Array.isArray(U.levels) && U.levels.length) {
var lv = U.levels.filter(function (l) { return l && l.angleDeg > 0 && l.angleDeg <= 180 && l.distance > 0 && isFinite(l.angleDeg) && isFinite(l.distance); });
if (lv.length) T.levels = lv;
}
if (typeof U.equalArea === 'boolean') T.equalArea = U.equalArea;
if (U.warmth && typeof U.warmth === 'object') T.warmth = { curve: U.warmth.curve || TUNING.warmth.curve, width: U.warmth.width > 0 ? U.warmth.width : TUNING.warmth.width, steps: U.warmth.steps >= 0 ? U.warmth.steps : TUNING.warmth.steps };
if (U.lights === 1 || U.lights === 2) T.lights = U.lights;
if (typeof U.typedPair === 'boolean') T.typedPair = U.typedPair;
if (Array.isArray(U.triesBand) && U.triesBand.length >= 2) T.triesBand = U.triesBand;
}
return T;
}
// warmth with the tuned curve: strictly falls with distance, everywhere
function warm(T, tg, x, y) {
var cx = tg.kind === 'xy' ? tg.x : tg.d * Math.cos(tg.deg * RAD), cy = tg.kind === 'xy' ? tg.y : tg.d * Math.sin(tg.deg * RAD);
var s = (tg.kind === 'xy' ? tg.s : Math.min(tg.wd, tg.wdeg * RAD * Math.max(tg.d, 1e-9))) / 2 * T.warmth.width;
var e = Math.sqrt((x - cx) * (x - cx) + (y - cy) * (y - cy)) / Math.max(s, 1e-12), w;
if (T.warmth.curve === 'inv') w = 1 / (1 + e);
else if (T.warmth.curve === 'exp') w = Math.exp(-e / 8);
else w = 1 / (1 + Math.log(1 + e) / 3);
if (T.warmth.steps > 1) w = Math.ceil(w * T.warmth.steps) / T.warmth.steps;
return w;
}
M.warm = function (tg, x, y, T) { return warm(T || TUNING, tg, x, y); };
function defaults() { return { found: [], score: 0, rung: 1, start: 40, mod: 360, dist: 3, turn: 90, step: 0, count: 12, speed: 20, grow: 0, newDots: 1, t: 0, xy: false, sel: 1, turnSet: false, txt: {}, facts: {}, stars: 0, findOn: null, muted: false }; }
function rng(seed) { var a = seed >>> 0; return function () { a = (a + 0x6D2B79F5) >>> 0; var t = a; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; }
function sprite(r, g, b) {
var c = document.createElement('canvas'); c.width = c.height = 64; var x = c.getContext('2d'), gr = x.createRadialGradient(32, 32, 0, 32, 32, 32);
gr.addColorStop(0, 'rgba(255,255,255,1)'); gr.addColorStop(0.16, 'rgba(255,255,255,1)'); gr.addColorStop(0.3, 'rgba(' + r + ',' + g + ',' + b + ',.85)');
gr.addColorStop(0.55, 'rgba(' + r + ',' + g + ',' + b + ',.22)'); gr.addColorStop(1, 'rgba(' + r + ',' + g + ',' + b + ',0)');
x.fillStyle = gr; x.fillRect(0, 0, 64, 64); return c;
}
function glowSprite(r, g, b) {
var c = document.createElement('canvas'); c.width = c.height = 128; var x = c.getContext('2d'), gr = x.createRadialGradient(64, 64, 0, 64, 64, 64);
gr.addColorStop(0, 'rgba(' + r + ',' + g + ',' + b + ',.9)'); gr.addColorStop(0.4, 'rgba(' + r + ',' + g + ',' + b + ',.3)'); gr.addColorStop(1, 'rgba(' + r + ',' + g + ',' + b + ',0)');
x.fillStyle = gr; x.fillRect(0, 0, 128, 128); return c;
}
function nowMs() { return (root.performance && performance.now) ? performance.now() : Date.now(); }
function open(host, opts) {
if (S) close(true);
opts = opts || {}; css();
var p = KEEP || defaults(), fr = opts.from, i;
KEEP = p;
if (!fr && opts.hash !== false) readHash(p);
if (fr) {
if (typeof fr.turn === 'number' && isFinite(fr.turn)) { p.turn = fr.turn * (p.mod / 360); p.turnSet = true; p.txt.turn = null; }
var fn = fr.howMany != null ? fr.howMany : fr.count; if (typeof fn === 'number' && fn >= 0 && isFinite(fn)) p.count = Math.min(LIMIT, Math.floor(fn));
if (typeof fr.start === 'number' && isFinite(fr.start)) p.start = fr.start;
if (typeof fr.t === 'number' && isFinite(fr.t)) p.t = fr.t;
}
if (opts.rung >= 1 && opts.rung <= 4 && p.rung !== (opts.rung | 0)) { p.rung = opts.rung | 0; if (!p.turnSet) p.turn = (p.rung >= 3 ? 30 : 90) * (p.mod / 360); p.sel = p.rung === 2 ? 1 : p.rung >= 3 ? M.count(p) : 0; }
var s = S = {
host: host, opts: opts, p: p, a: {}, T: tuning(), tw: {}, on: [], timers: [], raf: 0, closed: false,
W: 0, H: 0, dpr: 1, box: { l: 0, t: 0, r: 0, b: 0 }, cx: 0, cy: 0, R: 100, cxT: 0, cyT: 0, RT: 100, first: true,
cam: { x: 0, y: 0, z: 20 }, camT: { x: 0, y: 0, z: 20 }, viewR: 4, zoomMul: 1,
xy: new Float64Array(2 * CAP + 2), nDraw: 0, nTrue: 0, dirty: true, last: 0, t0: nowMs(),
ptw: { on: false, x0: 0, y0: 0, x1: 0, y1: 0, t0: 0, dur: 1 },
drag: null, press: null, pinch: null, ptr: [{ id: -1, x: 0, y: 0 }, { id: -1, x: 0, y: 0 }],
playing: false, tape: null, hashT: 0, fitT: 0, keptDeg: 0,
probe: { on: false, x: 0, y: 0, sx: 0, sy: 0, vx: 0, vy: 0 }, joy: { x: 0, y: 0, id: null, on: false, t0: 0, max: 0 },
find: { on: false, seq: 0, target: null, ghosts: new Float64Array(24), gN: 0, gI: 0, tries: 0, explored: false, typedIds: {}, lastHow: '', evalAt: 0, heat: 0, hot: -1, inside: false, softAt: -1e9, nextAt: 0, lastFlash: -1e9, novas: 0, softs: 0, flashTimes: [], born: 0, held: false,
nova: { on: false, t0: 0, x: 0, y: 0, scale: 1, gentle: false } },
cele: { t0: -1e9, kind: '' }, stackPulse: -1e9, lastCirc: 0, lastLand: 0, ac: null, lastNote: 0, mutedLocal: !!p.muted,
part: new Float32Array(4 * 96), labels: {}, rimKey: '', rimStep: 30, rimMinor: 10, rand: rng(opts.seed != null ? opts.seed : (Date.now() & 0x7fffffff)),
reduced: !!(root.matchMedia && root.matchMedia('(prefers-reduced-motion: reduce)').matches)
};
if (opts.reducedMotion != null) s.reduced = !!opts.reducedMotion;
for (i = 0; i < IDS.length; i++) { s.a[IDS[i]] = p[IDS[i]]; s.tw[IDS[i]] = { on: false, from: 0, to: 0, t0: 0, dur: 1 }; }
s.a.rung = p.rung;
var rootEl = s.root = E('div', 'kgf-root', null, host);
s.cv = E('canvas', 'kgf-cv', null, rootEl); s.ctx = s.cv.getContext('2d');
s.sprC = sprite(0, 255, 255); s.sprA = sprite(255, 176, 0); s.sprH = sprite(255, 214, 120); s.glowG = glowSprite(0, 255, 255); s.glowW = glowSprite(255, 236, 190);
s.F = create(rootEl, { onInput: onInput, onInvalid: function () { s.find.pending = false; s.find.evalAt = 0; s.find.lastHow = ''; s.F.setText('ang',''); s.F.setText('rootEquals',''); s.F.setText('rootValue',''); s.F.workingEl.textContent=''; }, onEdit: onEdit, onCommit: onCommit, onEq: flip, onMore: function () { if (S) { chips(); layout(); } }, onLand: function () { landNote(); exploreCheck() … [line shortened here: 439 characters; full line on GitHub]
s.pips = pips(rootEl, { active: p.rung - 1, names: false, onPick: pick });
var ic = s.icons = E('div', 'kgf-icons', null, rootEl);
s.findBtn = iconBtn(ic, SVG.star, 'find', function () { if (s.starHeld) { s.starHeld = false; return; } setFind(!s.find.on); });
on(s.findBtn, 'pointerdown', function () { s.starHeld = false; clearTimeout(s.starT); s.starT = setTimeout(function () { if (S !== s || s.p.rung !== 1) return; s.starHeld = true; M.place(s.p, 0, PT); dropTarget(PT.x, PT.y); }, 560); });
on(s.findBtn, 'pointerup', function () { clearTimeout(s.starT); }); on(s.findBtn, 'pointerleave', function () { clearTimeout(s.starT); });
s.joyBtn = iconBtn(ic, SVG.joy, 'joystick', function () { setJoy(!s.joy.on); });
s.muteBtn = iconBtn(ic, SVG.note, 'sound', function () { var m = !muted(); if (root.KGAudio && typeof root.KGAudio.setMuted === 'function') root.KGAudio.setMuted(m); else s.mutedLocal = m; p.muted = m; showMute(); if (!m) { gesture(); landNote(); } });
if (opts.standalone !== true && opts.close !== false) s.closeBtn = iconBtn(ic, SVG.x, 'close', function () { close(); });
// the clock (rung 4): play, and a tape to drag both ways
s.timeEl = E('div', 'kgf-time', null, rootEl);
s.playBtn = iconBtn(s.timeEl, SVG.play, 'play', function () { setPlaying(!s.playing); });
s.tape = E('canvas', null, null, s.timeEl);
// the joystick: the simulator's own DOM and pointer logic
s.joyEl = E('div', 'kgf-joy', null, rootEl); s.knob = E('div', 'kgf-knob', null, s.joyEl);
bind();
buildFormula();
layout(); s.cx = s.cxT; s.cy = s.cyT; s.R = s.RT;
fit(true); camTarget(); s.cam.x = s.camT.x; s.cam.y = s.camT.y; s.cam.z = s.camT.z;
showMute(); refresh();
var fo = opts.find != null ? !!opts.find : (p.findOn != null ? p.findOn : s.T.findOnOpen);
s.findBtn.style.display = p.rung === 1 ? '' : 'none';
if (fo && p.rung === 1) setFind(true, true);
s.timers.push(setTimeout(function () { if (S === s && p.rung === 1) s.F.pulse('='); }, 900));
s.last = nowMs(); need();
return api;
}
function iconBtn(parent, svg, label, fn) { var b = E('button', 'kgf-ic', null, parent); b.innerHTML = svg; b.setAttribute('aria-label', label); b.addEventListener('click', function (e) { gesture(); fn(e); }); return b; }
function on(el, type, fn, opt) { el.addEventListener(type, fn, opt || false); S.on.push([el, type, fn, opt || false]); }
function need() { if (S && !S.raf) S.raf = requestAnimationFrame(tick); }
function close(silent) {
if (!S) return;
var s = S; S = null; s.closed = true;
if (s.raf) cancelAnimationFrame(s.raf);
s.timers.forEach(function (t) { clearTimeout(t); }); clearTimeout(s.hashT); clearTimeout(s.starT); if (s.press) clearTimeout(s.press.hold);
s.on.forEach(function (o) { o[0].removeEventListener(o[1], o[2], o[3]); });
if (s.ro) { try { s.ro.disconnect(); } catch (e) { } }
s.F.destroy();
try { if (s.ac) s.ac.close(); } catch (e) { }
if (s.root && s.root.parentNode) s.root.parentNode.removeChild(s.root);
if (silent !== true) { try { s.host.dispatchEvent(new CustomEvent('kgclose', { bubbles: true, detail: { id: 'play' } })); } catch (e) { } }
}
function muted() { return (root.KGAudio && root.KGAudio.muted) || (S && S.mutedLocal); }
function showMute() { var m = muted(); S.muteBtn.className = 'kgf-ic' + (m ? ' off' : ''); S.muteBtn.querySelector('.s').style.display = m ? '' : 'none'; }
// ------------------------------------------------------------------ the page address carries the numbers
function readHash(p) {
var h; try { h = String(root.location.hash || '').replace(/^#/, ''); } catch (e) { return; }
if (!/(^|&)rung=/.test(h)) return;
var map = { a: 'start', d: 'dist', m: 'mod', turn: 'turn', step: 'step', n: 'count', t: 't', sp: 'speed', gr: 'grow', nd: 'newDots' };
var cf = { mod: { pos: true }, count: { int: true, min: 0 }, newDots: { min: 0 } };
h.split('&').forEach(function (kv) {
var i = kv.indexOf('='); if (i < 1) return;
var k = kv.slice(0, i), raw; try { raw = decodeURIComponent(kv.slice(i + 1)); } catch (e) { return; }
var v = parse(raw);
if (k === 'rung') { if (v >= 1 && v <= 4) p.rung = Math.floor(v); return; }
if (k === 'xy') { p.xy = raw === '1'; return; }
if (!map[k] || v !== v) return;
var c = check(cf[map[k]] || {}, v); if (!c) return;
p[map[k]] = c.v; p.txt[map[k]] = raw.indexOf('/') > 0 ? raw : null; if (k === 'turn') p.turnSet = true;
});
}
function hashText() {
var p = S.p, r = p.rung, o = 'rung=' + r, t = p.txt;
function f(k, id) { o += '&' + k + '=' + encodeURIComponent(t[id] || plain(p[id], 9)); }
f('a', 'start'); f('d', 'dist'); f('m', 'mod');
if (r >= 2) { f('turn', 'turn'); f('step', 'step'); }
if (r >= 3) f('n', 'count');
if (r >= 4) { f('t', 't'); f('sp', 'speed'); f('gr', 'grow'); f('nd', 'newDots'); }
if (r === 1 && p.xy) o += '&xy=1';
return o;
}
function saveHash() {
var s = S; if (!s || s.opts.hash === false) return;
clearTimeout(s.hashT);
s.hashT = setTimeout(function () { if (S !== s) return; try { root.history.replaceState(null, '', '#' + hashText()); } catch (e) { } }, 350);
}
// ------------------------------------------------------------------ the formula for each rung
function findDec(which) {
var s = S, tg = s.find.on ? s.find.target : null; if (!tg) return which === 'a' ? 1 : 2;
if (tg.kind === 'xy') return Math.min(4, stepDec(tg.s) + 1);
return which === 'a' ? Math.min(4, Math.max(1, stepDec(tg.wdeg * (s.p.mod / 360) / 2))) : Math.min(4, stepDec(tg.wd) + 1);
}
function buildFormula() {
var s = S, p = s.p, r = p.rung, L = [], cA = '#00ffff', cD = '#66ccff', cT = '#00ffff', cM = '#9fdcff';
function dA() { return findDec('a'); } function dD() { return findDec('d'); }
if (r === 1 && p.xy) {
L.push([['X', { eq: 1 }, { out: 'r1', color: cD }, '×', 'COS(', { out: 'th1', color: cA }, ')'], ['=', { id: 'x', cfg: { color: '#fff', dec: dD, show: 2, fixed: true, step: 0.1 } }]]);
L.push([['Y', { eq: 1 }, { out: 'r2', color: cD }, '×', 'SIN(', { out: 'th2', color: cA }, ')'], ['=', { id: 'y', cfg: { color: '#fff', dec: dD, show: 2, fixed: true, step: 0.1 } }]]);
} else {
var t = [r === 1 ? ['MOD(', { id: 'start', cfg: { color: cA, intDigits: 3, dec: dA, step: 1 } }] : ['ANGLE', '=', 'MOD(', { id: 'start', cfg: { color: cA, intDigits: 3, dec: dA, step: 1 } }]];
if (r >= 2) t.push(['+', { id: 'sel', cfg: { color: '#ffb000', int: true, min: 0, label: 'N', dec: 0 } }, '×', { id: 'turn', cfg: { color: cT, intDigits: 3, dec: 1, step: 1 } }]);
if (r >= 4) t.push(['+', 'T', '×', { id: 'speed', cfg: { color: '#fff', label: 'SPEED', step: 1 } }]);
t.push([',', { id: 'mod', cfg: { color: cM, pos: true, intDigits: 3, dec: 0, step: 1 } }, ')']);
t.push([r === 1 ? { eq: 1 } : '=', { out: 'ang', color: r >= 2 ? '#ffb000' : '#fff' }]);
L.push(t);
var d = r === 1 ? [['SQRT(', { id: 'square', cfg: { color: '#fff', dec: dD, step: 1, min: 0 } }, ')'], [{ out: 'rootEquals' }, { out: 'rootValue' }]] : [['DISTANCE', '=', { id: 'dist', cfg: { color: cD, dec: dD, step: 0.1, min: 0 } }]];
if (r >= 2) d.push(['+', 'N', '×', { id: 'step', cfg: { color: cD, dec: 1, step: 0.1 } }]);
if (r >= 4) d.push(['+', 'T', '×', { id: 'grow', cfg: { color: '#fff', label: 'GROW', step: 0.1 } }]);
if (r >= 2) d.push(['=', { out: 'dis', color: '#ffb000' }]);
L.push(d);
if (r >= 3) { var h = [['HOW MANY', { id: 'count', cfg: { color: '#fff', int: true, min: 0, dec: 0, intDigits: 2 } }]]; if (r >= 4) h.push(['T', '=', { id: 't', cfg: { color: '#fff', show: 1, fixed: true, step: 0.1 } }]); L.push(h); }
if (r >= 4) L.push([['NEW DOTS', { id: 'newDots', cfg: { color: '#fff', min: 0, step: 1 } }, 'A SECOND']]);
}
s.F.setLines(L); s.F.el.classList.toggle('rung-one', r === 1);
s.F.setChips([
{ id: 'c_d', label: 'DISTANCE', cfg: { color: cD, show: 2, fixed: true, dec: dD, step: 0.1, min: 0 } },
{ id: 'c_sq', label: 'SQUARE', cfg: { color: cD, show: 2, fixed: true, dec: 1, min: 0, step: 1 } },
{ id: 'c_area', label: 'AREA', cfg: { color: cD, show: 2, fixed: true, dec: 1, min: 0, step: 1 } },
{ id: 'c_ang', label: 'ANGLE', cfg: { color: cA, show: 2, intDigits: 3, dec: dA, step: 1 } },
{ id: 'c_rem', label: 'REMAINDER', cfg: { color: cA, show: 2, intDigits: 3, dec: dA, step: 1 } },
{ id: 'c_x', label: 'X', cfg: { color: '#fff', show: 2, fixed: true, dec: dD, step: 0.1 } },
{ id: 'c_y', label: 'Y', cfg: { color: '#fff', show: 2, fixed: true, dec: dD, step: 0.1 } }
]);
}
function selN() { var s = S, p = s.p; if (p.rung <= 1) return 0; var n = M.count(p), m = p.rung === 2 ? 1 : n; return p.sel < 0 ? 0 : p.sel > m ? m : p.sel; }
// put every number on screen from the true state (the dot or, while roaming, the probe)
function refresh() {
var s = S, p = s.p, F = s.F, r = p.rung, n = selN(), i, id;
for (i = 0; i < IDS.length; i++) { id = IDS[i]; if (F.has(id)) F.setValue(id, p[id], p.txt[id]); }
if (F.has('sel')) F.setValue('sel', n);
M.place(p, n, PT);
if (PT.d !== 0) s.keptDeg = PT.d < 0 ? mod(PT.deg + 180, 360) : PT.deg;
if (r === 1 && p.xy) {
F.workingEl.textContent = ''; F.workingEl.style.display = 'none';
F.setValue('x', PT.x); F.setValue('y', PT.y);
var rs = fmt(Math.abs(p.dist), 2), ts = fmt(PT.d < 0 ? mod(PT.deg + 180, 360) : PT.deg, 2) + '°';
F.setText('r1', rs); F.setText('r2', rs); F.setText('th1', ts); F.setText('th2', ts);
} else {
var ex = exact(p,n); F.setText('ang', ex ? ex.m : fmt(mod(M.raw(p,n),p.mod),4));
F.workingEl.textContent = ex ? ex.raw + ' = ' + ex.q + ' × ' + String(p.mod) + ' + ' + ex.m : '';
F.workingEl.style.display = '';
if (r === 1) {
var square = p.square == null ? p.dist * p.dist : p.square;
F.setValue('square', square);
var shownRoot = plain(p.dist, 4), rn = Number(shownRoot);
var ar=ratio(square), rr=ratio(shownRoot);
var isExact = rr.n*rr.n*ar.d===ar.n*rr.d*rr.d;
F.setText('rootEquals', isExact ? '=' : '≈'); F.setText('rootValue', fmt(p.dist, 4));
}
if (r >= 2) F.setText('dis', fmt(M.dist(p, n), 4));
}
chips();
s.dirty = true; need();
}
function chips() {
var s = S, F = s.F, pr = s.probe;
if (!F.moreOpen() && !probeFns.length) return;
if (pr.on) M.six(pr.x, pr.y, s.p.mod, s.keptDeg, SIX); else { M.place(s.p, selN(), PT2); M.six(PT2.x, PT2.y, s.p.mod, s.keptDeg, SIX); }
if (!F.moreOpen()) return;
F.setValue('c_d', SIX.d); F.setValue('c_sq', SIX.sq); F.setValue('c_area', SIX.area); F.setValue('c_ang', SIX.deg); F.setValue('c_rem', SIX.rem); F.setValue('c_x', SIX.x); F.setValue('c_y', SIX.y);
}
// ------------------------------------------------------------------ changes
function tween(id, to, dur) { var s = S, w = s.tw[id]; if (s.a[id] === to) { w.on = false; return; } w.from = s.a[id]; w.to = to; w.t0 = nowMs(); w.dur = dur; w.on = true; }
function setNow(id, v) { S.a[id] = v; S.tw[id].on = false; }
function busy() { var s = S, i; if (s.ptw.on) return true; for (i = 0; i < IDS.length; i++) if (s.tw[IDS[i]].on) return true; return false; }
function windDur(d, c) { var t = Math.abs(d) / c; return 170 + 900 * Math.pow(t > 2.4 ? 2.4 : t, 0.8); }
function set(id, v, how) {
var s = S, p = s.p, ease = how === 'type' || how === 'digit' || how === 'restore' || how === 'tap';
if (id === 'turn') p.turnSet = true;
if (id === 'dist') p.square = null;
p[id] = v; p.txt[id] = null;
if (id === 'mod' || id === 't' || id === 'newDots' || !ease) { setNow(id, v); return; }
tween(id, v, id === 'start' ? windDur(v - s.a.start, p.mod) : id === 'turn' ? Math.min(900, 220 + 40 * Math.abs(v - s.a.turn) / p.mod * 12) : id === 'count' ? 320 : 180);
}
function mark(how, id) {
var f = S.find; f.quietAt=0;
if (how === 'type') { f.typedIds[id] = 1; f.lastHow = 'type'; f.pending = true; S.zoomMul = 1; }
else { f.typedIds = {}; f.explored = true; f.lastHow = 'explore'; f.evalAt = 0; f.pending = false; }
}
// the keypad, the keyboard, a dragged number, the wheel and the digit arrows all arrive here
function onInput(id, v, how) {
var s = S, p = s.p, r = p.rung, n = selN(), w = CHIP[id];
gesture();
if (w) {
M.place(p, n, PT); PT.deg = s.keptDeg;
M.fromSix(w, v, PT, p.mod, Q);
if (r === 1 && (w === 'd' || w === 'sq' || w === 'area')) set('dist', w === 'd' ? v : Q.d, how);
else if (r === 1 && (w === 'deg' || w === 'rem')) set('start', w === 'rem' ? mod(v, p.mod) : mod(v, 360) * (p.mod / 360), how);
else moveDot(n, Q.x, Q.y, how, false);
} else if (id === 'square') { set('dist', Math.sqrt(v), how); p.square = v; if (Number.isSafeInteger(v) && Number.isSafeInteger(p.dist) && BigInt(p.dist)*BigInt(p.dist)===BigInt(v)) s.ringFlash={d:p.dist,t:nowMs()}; } else if (id === 'sel') { p.sel = v; landNote(); }
else set(id, v, how);
if (id === 'count' && r >= 3 && p.sel >= M.count(p) - 1) p.sel = M.count(p);
if (id === 't') drawTape();
mark(how, id);
after(how);
if (how !== 'type') exploreCheck();
}
function after(how) { var s = S; refresh(); if (!s.drag) fit(false); camTarget(); saveHash(); }
function onEdit(id, done) {
var s = S; if (!s) return;
if (id) { s.probe.on = false; s.F.pulse(id); }
refresh(); layout();
if (done) committed(done);
s.dirty = true; need();
}
// a typed number was committed (Enter, the keypad's enter, or a tap away): this is the only thing that is judged
function committed(id) { var s = S, f = s.find; if (id && id in s.p.txt || id && IDS.indexOf(id) >= 0) s.p.txt[id] = s.F.txt(id); if (f.pending) { f.pending = false; if (f.on && f.target && !f.target.found) f.evalAt = nowMs(); s.factsDue = true; } landNote(); saveHash(); need(); }
function onCommit(id, typed) { var s = S, f = s.find; if (typed) committed(id); return !!(f.on && f.target && !f.target.found); }
// move dot n to a point: dot 0 changes START and DISTANCE, a later dot changes TURN and STEP
function moveDot(n, x, y, how, snap) {
var s = S, p = s.p, z = s.cam.z, ease = how !== 'explore';
if (p.rung === 1 && (p.xy || ease)) { M.place(s.a, 0, PT2); if (s.ptw.on) { PT2.x = s.xy[0]; PT2.y = s.xy[1]; } }
if (snap) {
var qd = niceDown(3.2 / z);
if (p.rung === 1 && p.xy) { x = snapTo(x, qd); y = snapTo(y, qd); }
}
M.inverse(p, n, x, y, INV);
if (snap && !(p.rung === 1 && p.xy)) {
var dpx = Math.max(20, Math.sqrt(x * x + y * y) * z), qu = niceDown(3.2 / dpx / RAD * (p.mod / 360)), qd2 = niceDown(3.2 / z);
if (n === 0 || p.rung < 2) { INV.start = snapTo(INV.start, qu); INV.dist = snapTo(INV.dist, qd2); }
else { INV.turn = snapTo(INV.turn, niceDown(qu / n)); INV.step = snapTo(INV.step, niceDown(qd2 / n)); }
}
if (n === 0 || p.rung < 2) {
p.start = INV.start; p.dist = INV.dist; p.square = null; p.txt.start = p.txt.dist = null;
if (p.rung === 1 && ease) { setNow('start', p.start); setNow('dist', p.dist); M.place(p, 0, PT); var w = s.ptw; w.x0 = PT2.x; w.y0 = PT2.y; w.x1 = PT.x; w.y1 = PT.y; w.t0 = nowMs(); w.dur = 200; w.on = true; }
else if (ease) { tween('start', p.start, 200); tween('dist', p.dist, 200); }
else { setNow('start', p.start); setNow('dist', p.dist); s.ptw.on = false; }
} else {
p.turn = INV.turn; p.step = INV.step; p.turnSet = true; p.txt.turn = p.txt.step = null;
if (ease) { tween('turn', p.turn, 200); tween('step', p.step, 200); } else { setNow('turn', p.turn); setNow('step', p.step); }
}
}
function flip() {
var s = S, p = s.p; if (p.rung !== 1) return;
s.F.close(true); p.xy = !p.xy;
buildFormula(); refresh(); layout(); saveHash(); landNote();
if (s.find.on) newTarget(false);
}
function pick(r) {
var s = S, p = s.p;
if (r === 5) { var KL = root.KGLesson; if (!KL || typeof KL.open !== 'function') return; var h = s.host, st = exportState(); close(true); KL.open(h, { from: {howMany:st.howMany}, hash:false }); return; }
setRung(r);
}
function setRung(r) {
var s = S, p = s.p; if (r < 1 || r > 4 || r === p.rung) return;
s.F.close(true); if (s.playing) setPlaying(false);
var was = p.rung; p.rung = r; s.a.rung = r;
if (!p.turnSet) { p.turn = (r >= 3 ? 30 : 90) * (p.mod / 360); tween('turn', p.turn, 400); }
p.sel = r === 2 ? 1 : r >= 3 ? M.count(p) : 0;
if (r >= 3 && was < 3) { s.a.count = Math.min(2, p.count); tween('count', p.count, 700); }
s.ptw.on = false;
s.findBtn.style.display = r === 1 ? '' : 'none';
if (r !== 1 && s.find.on) setFind(false, true); else if (r === 1 && p.findOn && !s.find.on) setFind(true, true);
s.pips.set(r - 1); buildFormula(); refresh(); layout(); fit(true); camTarget(); saveHash(); landNote();
}
function exportState() { var p = S.p; return { start: p.start, turn: p.turn * (360 / p.mod), howMany: p.count, t: p.t, mod: p.mod, distance: p.dist, step: p.step, rung: p.rung }; }
// ------------------------------------------------------------------ the view: the circle always fits what was typed
function maxDist() {
var s = S, p = s.p, n = M.count(p), m = Math.abs(M.dist(p, 0)), e = n > 1 ? Math.abs(M.dist(p, n - 1)) : 0, tg = s.find.on ? s.find.target : null;
if (e > m) m = e;
if (tg) { e = tg.kind === 'xy' ? Math.sqrt(tg.x * tg.x + tg.y * tg.y) + tg.s : tg.d + tg.wd / 2; if (e > m) m = e; }
return m;
}
function fit(force) {
var s = S, m = maxDist(); if (!(m > 0)) return; if (m > 1.8e16) m = 1.8e16;
var q = m / s.viewR;
if (force || q > 0.93 || q < 0.3) { s.viewR = m / 0.75; if (s.viewR < 1e-6) s.viewR = 1e-6; }
}
// where the camera should be: the whole circle, or closing in on the target and the dot nearest to it
function camTarget() {
var s = S, f = s.find, tg = f.on ? f.target : null, c = s.camT, zd = s.R / s.viewR;
c.x = 0; c.y = 0; c.z = zd;
// FIND keeps the whole circle in view; no automatic target close-up.
return;
}
// ------------------------------------------------------------------ layout: a true circle, as large as the screen allows
function safe() {
var s = S; if (!s.probeEl) { s.probeEl = E('div', null, null, s.root); s.probeEl.style.cssText = 'position:absolute;visibility:hidden;pointer-events:none;padding:env(safe-area-inset-top,0px) env(safe-area-inset-right,0px) env(safe-area-inset-bottom,0px) env(safe-area-inset-left,0px)'; }
var c = getComputedStyle(s.probeEl); return { t: parseFloat(c.paddingTop) || 0, r: parseFloat(c.paddingRight) || 0, b: parseFloat(c.paddingBottom) || 0, l: parseFloat(c.paddingLeft) || 0 };
}
function layout() {
var s = S, host = s.host, W = host.clientWidth || root.innerWidth || 390, H = host.clientHeight || root.innerHeight || 844;
var dpr = Math.min(3, root.devicePixelRatio || 1), sf = safe(), F = s.F, editing = !!F.editing(), r = s.p.rung;
s.W = W; s.H = H; s.dpr = dpr;
var cw = Math.round(W * dpr), ch = Math.round(H * dpr);
if (s.cv.width !== cw || s.cv.height !== ch) { s.cv.width = cw; s.cv.height = ch; }
var wide = s.wide = W >= H * 1.15, short = wide && H < 600, fs = wide && !short ? Math.max(28, Math.min(32, Math.round(W / 42))) : 28;
var es = F.el.style, cs = F.chipsEl.style, ps = F.padEl.style, ts = s.timeEl.style, b = s.box, padH = 0, PW = 0;
es.fontSize = fs + 'px'; s.fs = fs;
F.padEl.classList.remove('row');
s.pips.set(r - 1, !wide && W >= 900);
if (wide) {
PW = Math.max(330, Math.min(520, W - H)); if (short) PW = Math.max(330, Math.min(470, W - H + 16));
var px = W - PW - sf.r;
s.pips.el.style.cssText = 'left:' + (px + 4) + 'px;top:' + (4 + sf.t) + 'px';
s.icons.style.cssText = 'right:' + (4 + sf.r) + 'px;top:' + (4 + sf.t) + 'px';
es.cssText = 'font-size:' + fs + 'px;left:' + (px + 10) + 'px;top:' + (56 + sf.t) + 'px;width:' + (PW - 18) + 'px;bottom:auto;justify-content:flex-start';
var twoRows = short && PW >= 400;
F.padEl.classList.toggle('row', twoRows);
if (short) { ps.cssText = 'left:' + px + 'px;width:' + PW + 'px;bottom:' + sf.b + 'px;height:'+(twoRows?104:196)+'px'; }
else ps.cssText = 'left:' + px + 'px;width:' + PW + 'px;bottom:0;padding-bottom:' + (6 + sf.b) + 'px';
padH = editing ? F.padEl.offsetHeight : 0;
if (short) { es.maxHeight = Math.max(48,H - sf.t - sf.b - 96 - (editing ? (twoRows?108:200) : 8)) + 'px'; es.overflowY = 'auto'; es.pointerEvents = 'auto'; }
var fh = F.el.offsetHeight;
F.workingEl.style.cssText = 'left:'+(px+10)+'px;top:'+(56+sf.t+fh+4)+'px;width:'+(PW-20)+'px;height:32px';
ts.cssText = 'left:' + (px + 6) + 'px;width:' + (PW - 12) + 'px;top:' + (56 + sf.t + fh + 6) + 'px';
cs.cssText = 'left:' + (px + 10) + 'px;width:' + (PW - 20) + 'px;bottom:' + ((editing ? padH : sf.b) + 8) + 'px';
b.l = sf.l; b.r = px; b.t = sf.t; b.b = H - sf.b;
F.limitEl.style.cssText = 'left:' + (b.l + 12) + 'px;right:' + (W - b.r + 12) + 'px;top:' + (b.t + 60) + 'px';
} else {
s.pips.el.style.cssText = 'left:6px;top:' + (4 + sf.t) + 'px';
s.icons.style.cssText = 'right:4px;top:' + (4 + sf.t) + 'px';
ps.cssText = 'left:0;right:0;bottom:0;padding-bottom:' + (6 + sf.b) + 'px';
padH = editing ? F.padEl.offsetHeight : 0;
es.cssText = 'font-size:' + fs + 'px;left:12px;right:10px;top:auto;bottom:' + (editing ? padH + 4 : sf.b + 10) + 'px;min-height:' + (W < 520 ? [3, 5, 6, 8][r - 1] * 1.32 : 0) + 'em';
if (r === 1) { es.minHeight = '0'; }
es.bottom = ((editing ? padH + 4 : sf.b + 10) + 36) + 'px';
F.workingEl.style.cssText = 'left:12px;right:10px;bottom:'+(editing ? padH+4 : sf.b+10)+'px;height:32px';
var top = H - (editing ? padH + 4 : sf.b + 10) - 36 - F.el.offsetHeight;
if (r >= 4 && !editing) { top -= 52; ts.cssText = 'left:6px;right:6px;top:' + top + 'px'; }
cs.cssText = 'left:10px;right:10px;bottom:' + (H - top + 6) + 'px';
b.l = 0; b.r = W; b.t = 50 + sf.t; b.b = top - 4;
F.limitEl.style.cssText = 'left:12px;right:12px;top:' + (b.t + 44) + 'px';
}
s.timeEl.classList.toggle('on', r >= 4 && !(editing && !wide));
var chipsHide = editing && !F.moreOpen();
F.chipsEl.style.display = chipsHide ? 'none' : 'flex';
var bw = b.r - b.l, bh = b.b - b.t;
var strip = 36;
s.RT = Math.max(1, Math.min(bw, bh - strip) / 2 - 8); s.cxT = (b.l + b.r) / 2; s.cyT = (b.t + strip + b.b) / 2;
s.cx = s.cxT; s.cy = s.cyT; s.R = s.RT; s.first = false;
s.cam.x = 0; s.cam.y = 0; s.cam.z = s.R / s.viewR;
s.joyEl.style.left = (b.l + 16) + 'px'; s.joyEl.style.top = (b.b - 150) + 'px';
drawTape(); camTarget();
s.dirty = true; need();
}
// ------------------------------------------------------------------ pointer, wheel and keys on the drawing
function X(wx) { return S.cx + (wx - S.cam.x) * S.cam.z; }
function Y(wy) { return S.cy - (wy - S.cam.y) * S.cam.z; }
function WX(sx) { return S.cam.x + (sx - S.cx) / S.cam.z; }
function WY(sy) { return S.cam.y - (sy - S.cy) / S.cam.z; }
function sampleN(i) { var n = S.nAnim; return n > CAP ? Math.floor(i * n / CAP) : i; }
function hit(x, y, rad) {
var s = S, xy = s.xy, n = s.nDraw + (s.ghost ? 1 : 0), i, best = -1, bd = rad * rad, dx, dy, d;
for (i = 0; i < n; i++) { dx = X(xy[2 * i]) - x; dy = Y(xy[2 * i + 1]) - y; d = dx * dx + dy * dy; if (d < bd - 0.25) { bd = d; best = i; } }
return best;
}
function inBox(x, y, m) { var b = S.box; m = m || 0; return x >= b.l + m && x <= b.r - m && y >= b.t + m && y <= b.b - m; }
function bind() {
var s = S, cv = s.cv;
function pos(e, o) { var r = cv.getBoundingClientRect(); o.x = e.clientX - r.left; o.y = e.clientY - r.top; }
var P = { x: 0, y: 0 };
function slotOf(id) { return s.ptr[0].id === id ? s.ptr[0] : s.ptr[1].id === id ? s.ptr[1] : null; }
function gap() { var a = s.ptr[0], b = s.ptr[1]; return Math.sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y)) || 1; }
function cancelPress() { if (s.press) { clearTimeout(s.press.hold); s.press = null; } }
on(cv, 'pointerdown', function (e) {
gesture();
if (e.pointerType === 'mouse' && e.button !== 0) return;
var sl = s.ptr[0].id < 0 ? s.ptr[0] : s.ptr[1].id < 0 ? s.ptr[1] : null; if (!sl) return;
pos(e, P); sl.id = e.pointerId; sl.x = P.x; sl.y = P.y;
try { cv.setPointerCapture(e.pointerId); } catch (_) { }
if (s.ptr[0].id >= 0 && s.ptr[1].id >= 0) { if (s.drag) return; cancelPress(); s.pinch = { d0: gap(), v0: s.viewR, m0: s.zoomMul }; return; }
if (!inBox(P.x, P.y)) return;
var closing = !!s.F.editing() || s.F.moreOpen();
var h = hit(P.x, P.y, e.pointerType === 'mouse' ? 20 : 32);
if (h >= 0) {
var N = h >= s.nDraw ? s.nAnim : sampleN(h);
s.drag = { n: N, pid: e.pointerId, ox: P.x - X(s.xy[2 * h]), oy: P.y - Y(s.xy[2 * h + 1]), x0: P.x, y0: P.y, moved: false };
s.probe.on = false;
if (s.p.rung >= 2 && s.p.sel !== N) { s.p.sel = N; refresh(); }
s.dirty = true; need();
} else {
if (closing) return;
var pr = s.press = { pid: e.pointerId, x0: P.x, y0: P.y, t0: nowMs(), moved: false, held: false, hold: 0 };
pr.hold = setTimeout(function () { if (S !== s || s.press !== pr || pr.moved || s.p.rung !== 1) return; pr.held = true; dropTarget(WX(pr.x0), WY(pr.y0)); }, 560);
}
});
on(cv, 'pointermove', function (e) {
pos(e, P);
var sl = slotOf(e.pointerId); if (sl) { sl.x = P.x; sl.y = P.y; }
if (s.pinch && s.ptr[0].id >= 0 && s.ptr[1].id >= 0) {
var q = gap() / s.pinch.d0;
if (s.camT.x === 0 && s.camT.y === 0) { s.viewR = Math.min(2.4e16, Math.max(1e-6, s.pinch.v0 / q)); camTarget(); s.cam.z = s.camT.z; }
else { s.zoomMul = Math.min(40, Math.max(0.05, s.pinch.m0 * q)); camTarget(); }
s.dirty = true; need(); return;
}
var d = s.drag;
if (d && d.pid === e.pointerId) {
if (!d.moved) { if (Math.abs(P.x - d.x0) + Math.abs(P.y - d.y0) < 4) return; d.moved = true; s.F.close(true); }
moveDot(d.n, WX(P.x - d.ox), WY(P.y - d.oy), 'explore', true); mark('explore'); refresh(); saveHash();
return;
}
var pr = s.press;
if (pr && pr.pid === e.pointerId) { if (!pr.moved && Math.abs(P.x - pr.x0) + Math.abs(P.y - pr.y0) > 10) { pr.moved = true; clearTimeout(pr.hold); } return; }
if (e.pointerType === 'mouse' && !e.buttons && !s.joy.on) {
if (inBox(P.x, P.y, 2) && !s.F.editing()) { s.probe.on = true; s.probe.x = WX(P.x); s.probe.y = WY(P.y); emitProbe(); }
else if (s.probe.on) { s.probe.on = false; chips(); }
s.dirty = true; need();
}
});
function up(e) {
gesture();
var sl = slotOf(e.pointerId); if (sl) sl.id = -1;
try { cv.releasePointerCapture(e.pointerId); } catch (_) { }
if (s.pinch) { s.pinch = null; return; }
var d = s.drag;
if (d && d.pid === e.pointerId) {
s.drag = null;
if (d.moved) { fit(false); camTarget(); exploreCheck(); saveHash(); }
landNote(); s.dirty = true; need(); return;
}
var pr = s.press;
if (pr && pr.pid === e.pointerId) {
s.press = null; clearTimeout(pr.hold);
if (e.type === 'pointerup' && !pr.moved && !pr.held && nowMs() - pr.t0 < 450 && s.p.rung <= 2 && inBox(pr.x0, pr.y0)) dropDot(WX(pr.x0), WY(pr.y0));
}
}
on(cv, 'pointerup', up); on(cv, 'pointercancel', up);
on(cv, 'pointerleave', function (e) { if (e.pointerType === 'mouse' && s.probe.on && !s.joy.on) { s.probe.on = false; chips(); s.dirty = true; need(); } });
on(cv, 'contextmenu', function (e) { e.preventDefault(); });
on(cv, 'wheel', function (e) {
e.preventDefault();
var f = Math.exp((e.deltaMode === 1 ? e.deltaY * 16 : e.deltaY) * 0.0015);
if (s.camT.x === 0 && s.camT.y === 0) s.viewR = Math.min(2.4e16, Math.max(1e-6, s.viewR * f)); else s.zoomMul = Math.min(40, Math.max(0.05, s.zoomMul / f));
camTarget(); s.dirty = true; need();
}, { passive: false });
function rs() { if (S === s) { s.needLayout = true; need(); } }
on(root, 'resize', rs); on(root, 'orientationchange', rs);
if (root.ResizeObserver) { s.ro = new ResizeObserver(rs); s.ro.observe(s.host); s.ro.observe(s.F.el); }
on(document, 'keydown', function (e) {
if (e.defaultPrevented || s.F.editing()) return;
if (e.key === 'Escape') { if (s.F.moreOpen()) s.F.more(false); else if (s.closeBtn) close(); }
else if (e.key === ' ' && s.p.rung >= 4) { e.preventDefault(); gesture(); setPlaying(!s.playing); }
});
// the tape: drag the clock both ways
var td = null;
on(s.tape, 'pointerdown', function (e) { gesture(); td = { pid: e.pointerId, x0: e.clientX, t0: s.p.t }; try { s.tape.setPointerCapture(e.pointerId); } catch (_) { } if (s.playing) setPlaying(false); });
on(s.tape, 'pointermove', function (e) {
if (!td || td.pid !== e.pointerId) return;
var t = Number((td.t0 - (e.clientX - td.x0) / 44).toFixed(2)); if (t > LIMIT) t = LIMIT; if (t < -LIMIT) t = -LIMIT;
if (t === s.p.t) return;
set('t', t, 'explore'); mark('explore', 't'); refresh(); fit(false); camTarget(); drawTape();
});
function tu(e) { if (td && td.pid === e.pointerId) { td = null; saveHash(); exploreCheck(); } }
on(s.tape, 'pointerup', tu); on(s.tape, 'pointercancel', tu);
// the joystick (pointer logic as in the simulator: capture, clamp to the ring, release to zero)
var joy = s.joy, joyEl = s.joyEl, knob = s.knob;
var joyAt = function (e) {
var r = joyEl.getBoundingClientRect(), h = r.width / 2; var 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; } joy.x = x; joy.y = y; if (d > joy.max) joy.max = d;
knob.style.left = (36 + x * 40) + 'px'; knob.style.top = (36 + y * 40) + 'px';
};
on(joyEl, 'pointerdown', function (e) { gesture(); e.preventDefault(); joy.id = e.pointerId; joy.t0 = nowMs(); joy.max = 0; try { joyEl.setPointerCapture(e.pointerId); } catch (_) { } joyAt(e); need(); });
on(joyEl, 'pointermove', function (e) { if (e.pointerId === joy.id) { joyAt(e); need(); } });
var ju = function (e) {
if (e.pointerId !== joy.id) return; joy.id = null; joy.x = joy.y = 0; knob.style.left = knob.style.top = '36px';
if (e.type === 'pointerup' && nowMs() - joy.t0 < 320 && joy.max < 0.3 && s.probe.on && s.p.rung <= 2) dropDot(s.probe.x, s.probe.y);
need();
};
on(joyEl, 'pointerup', ju); on(joyEl, 'pointercancel', ju);
}
// a tap, a click or the joystick knob drops the dot on a point: exploring, eased, never rewarded
function dropDot(wx, wy) {
var s = S; s.F.close(true);
moveDot(selN(), wx, wy, 'tap', true); mark('explore'); after('tap');
s.timers.push(setTimeout(function () { if (S === s) { landNote(); exploreCheck(); } }, 240));
}
function setJoy(on) {
var s = S; s.joy.on = !!on; s.joyEl.classList.toggle('on', s.joy.on); s.joyBtn.classList.toggle('lit', s.joy.on);
if (!on) { s.probe.on = false; s.probe.vx = s.probe.vy = 0; chips(); }
else { M.place(s.p, selN(), PT); s.probe.x = PT.x; s.probe.y = PT.y; s.probe.on = true; emitProbe(); }
s.dirty = true; need();
}
function emitProbe() {
var s = S, pr = s.probe, i; chips();
if (!probeFns.length) return;
M.six(pr.x, pr.y, s.p.mod, s.keptDeg, SIX);
for (i = 0; i < probeFns.length; i++) { try { probeFns[i](SIX.deg, SIX.d); } catch (e) { } }
}
// ------------------------------------------------------------------ the clock
function setPlaying(on) { var s = S; s.playing = !!on && s.p.rung >= 4; s.playBtn.innerHTML = s.playing ? SVG.pause : SVG.play; s.playBtn.setAttribute('aria-label', s.playing ? 'pause' : 'play'); if (!s.playing) saveHash(); s.last = nowMs(); need(); }
function drawTape() {
var s = S, c = s.tape; if (!c || s.p.rung < 4) return;
var w = c.clientWidth, h = 48, dpr = s.dpr; if (!w) return;
if (c.width !== Math.round(w * dpr) || c.height !== Math.round(h * dpr)) { c.width = Math.round(w * dpr); c.height = Math.round(h * dpr); }
var x = c.getContext('2d'), t = s.p.t, pp = 44, k0 = Math.floor(t - w / 2 / pp) - 1, k1 = Math.ceil(t + w / 2 / pp) + 1, k, X0, every = Math.abs(t) < 90 ? 2 : Math.abs(t) < 9000 ? 5 : 0;
x.setTransform(dpr, 0, 0, dpr, 0, 0); x.clearRect(0, 0, w, h);
x.strokeStyle = 'rgba(102,204,255,.5)'; x.lineWidth = 1.5; x.beginPath(); x.moveTo(0, 40.5); x.lineTo(w, 40.5);
if (k1 - k0 > 80) k1 = k0 + 80;
for (k = k0; k <= k1; k++) { X0 = w / 2 + (k - t) * pp; x.moveTo(X0, 40); x.lineTo(X0, every && k % every === 0 ? 28 : 34); }
x.stroke();
x.font = '400 24px ' + FONT; x.textAlign = 'center'; x.textBaseline = 'middle'; x.fillStyle = 'rgba(255,255,255,.6)';
if (every) for (k = k0; k <= k1; k++) if (k % every === 0) x.fillText(String(k), w / 2 + (k - t) * pp, 14);
x.fillStyle = '#ffb000'; x.beginPath(); x.moveTo(w / 2, 30); x.lineTo(w / 2 - 7, 46); x.lineTo(w / 2 + 7, 46); x.closePath(); x.fill();
}
// ------------------------------------------------------------------ sound: soft, after a gesture, pitch from the angle
var SCALE = [0, 2, 4, 7, 9, 12, 14, 16, 19, 21, 24];
function gesture() {
var s = S; if (!s || muted()) return;
if (s.ac) { if (s.ac.state === 'suspended') { try { s.ac.resume(); } catch (e) { } } return; }
var AC = root.AudioContext || root.webkitAudioContext; if (!AC) return;
try { s.ac = new AC(); } catch (e) { s.ac = null; }
}
function tone(freq, vol, dur, delay) {
var s = S; if (!s || !s.ac || muted() || s.ac.state !== 'running') return;
try {
var ac = s.ac, t = ac.currentTime + (delay || 0), o = ac.createOscillator(), g = ac.createGain();
o.type = 'sine'; o.frequency.value = freq;
g.gain.setValueAtTime(0.0001, t); g.gain.exponentialRampToValueAtTime(vol, t + 0.015); g.gain.exponentialRampToValueAtTime(0.0001, t + dur);
o.connect(g); g.connect(ac.destination); o.start(t); o.stop(t + dur + 0.05);
} catch (e) { }
}
function landNote() {
var s = S, now = nowMs(); if (!s || now - s.lastNote < 45) return; s.lastNote = now;
M.place(s.p, selN(), PT2);
var deg = PT2.d < 0 ? mod(PT2.deg + 180, 360) : PT2.deg;
tone(220 * Math.pow(2, SCALE[Math.floor(deg / 360 * 10)] / 12), 0.1, 0.4, 0);
}
function phrase(n, base, vol) { var i; for (i = 0; i < n; i++) tone((base || 330) * Math.pow(2, SCALE[i * 2] / 12), vol || 0.09, 0.5, i * 0.11); }
// ------------------------------------------------------------------ FIND: a target, typed tries, a supernova
function setFind(on, quiet) {
var s = S, f = s.find; if (on && s.p.rung !== 1) return;
f.on = !!on; if (!quiet || on) s.p.findOn = f.on;
s.findBtn.classList.toggle('lit', f.on);
if (f.on) { if (!f.target) newTarget(false); } else { f.target = null; f.gN = 0; f.nova.on = false; s.zoomMul = 1; }
fit(false); camTarget(); refresh();
}
function targetSize(base) { return { angleDeg: Math.max(5, base.angleDeg), distance: Math.max(0.25, base.distance) }; }
function seqDef(i) {
var s = S, L = s.T.levels, q = [], k;
for (k = 0; k < L.length; k++) q.push({ lv: k, turns: 0 });
return q[i < q.length ? i : q.length - 1];
}
function p10(v) { return Math.pow(10, Math.floor(Math.log10(v) + 1e-9)); }
function isMult(v, q) { var r = v / q; return Math.abs(r - Math.round(r)) < 1e-6; }
function cellFor(def, u, d) { // a polar cell at u (circle units), d; equal in area wherever it sits
var s = S, T = s.T, base = targetSize(T.levels[def.lv]), C = s.p.mod, wdeg = base.angleDeg;
if (T.equalArea && d > 0) wdeg = Math.min(90, base.angleDeg * T.refDistance / d);
return { kind: 'polar', deg: mod(u, C) * (360 / C), u: mod(u, C), d: d, wdeg: Math.max(5, wdeg), wd: base.distance, turns: def.turns, lv: def.lv, found: false };
}
function newTarget(advance) {
var s = S, f = s.find, p = s.p, T = s.T, R = s.rand, def, base, i, C = p.mod, tg = null;
if (advance) f.seq++;
def = seqDef(f.seq); base = targetSize(T.levels[def.lv]);
M.place(p, 0, PT2);
var cd = Math.abs(PT2.d), cdeg = PT2.d < 0 ? mod(PT2.deg + 180, 360) : PT2.deg;
if (p.rung === 1 && p.xy) {
var sz = base.distance, q = p10(sz), x = 0, y = 0;
for (i = 0; i < 60; i++) {
x = snapTo((R() * 2 - 1) * 3.4, q); y = snapTo((R() * 2 - 1) * 3.4, q);
var h = Math.sqrt(x * x + y * y); if (h < 1 || h > 4.6) continue;
if (i < 40 && def.lv >= 1 && isMult(x, q * 10) && isMult(y, q * 10)) continue;
if (i < 40 && (Math.abs(x - PT2.x) < sz + 0.4 || Math.abs(y - PT2.y) < sz + 0.4)) continue;
break;
}
if (Math.abs(x - PT2.x) < sz || Math.abs(y - PT2.y) < sz) { x = PT2.x < 0 ? 2 : -2; y = PT2.y < 0 ? 2 : -2; }
tg = { kind: 'xy', x: x, y: y, s: sz, turns: 0, lv: def.lv, found: false };
} else {
var qd = Math.max(0.1, p10(base.distance)), qa = Math.max(0.01, p10(base.angleDeg * C / 360)), d = 3, u = 0;
for (i = 0; i < 60; i++) {
d = snapTo(1.5 + R() * 3, qd); u = snapTo(R() * C, qa); if (u >= C) u = 0;
if (i < 40 && def.lv >= 2 && isMult(d, qd * 10)) continue;
if (i < 40 && def.lv >= 1 && isMult(u, qa * 10)) continue;
var dd = Math.abs(mod(u * 360 / C - cdeg + 180, 360) - 180);
if (dd < Math.max(25, base.angleDeg) || Math.abs(d - cd) < base.distance * 0.75 + 0.3) continue;
break;
}
if (i === 60) { d = cd < 3 ? 4.5 : 1.5; u = snapTo(mod(cdeg + 180, 360) * C / 360, qa); }
tg = cellFor(def, u, d);
}
f.target = tg; f.gN = 0; f.gI = 0; f.tries = 0; f.explored = false; f.typedIds = {}; f.lastHow = ''; f.evalAt = 0; f.born = nowMs(); f.held = false;
s.zoomMul = 1; fit(false); camTarget(); s.dirty = true; need();
}
// press and hold in the circle: a target there, for someone else to find
function dropTarget(wx, wy) {
var s = S, f = s.find, p = s.p, def = seqDef(f.seq), base = targetSize(s.T.levels[def.lv]);
if (!f.on) { f.on = true; p.findOn = true; s.findBtn.classList.add('lit'); }
if (p.rung === 1 && p.xy) { var q = p10(base.distance); f.target = { kind: 'xy', x: snapTo(wx, q), y: snapTo(wy, q), s: base.distance, turns: 0, lv: def.lv, found: false }; }
else {
M.six(wx, wy, p.mod, 0, SIX);
f.target = cellFor({ lv: def.lv, turns: 0 }, snapTo(SIX.rem, p10(base.angleDeg * p.mod / 360)), Math.max(p10(base.distance), snapTo(SIX.d, p10(base.distance))));
}
f.gN = 0; f.gI = 0; f.tries = 0; f.explored = false; f.typedIds = {}; f.lastHow = ''; f.evalAt = 0; f.born = nowMs(); f.held = true;
tone(660, 0.08, 0.5, 0); fit(false); camTarget(); refresh();
}
function typedOK() { return S.find.lastHow === 'type'; }
function ghost(x, y) {
var f = S.find, g = f.ghosts, i;
for (i = 0; i < f.gN; i++) if (g[2 * i] === x && g[2 * i + 1] === y) return;
g[2 * f.gI] = x; g[2 * f.gI + 1] = y; f.gI = (f.gI + 1) % 12; if (f.gN < 12) f.gN++;
}
// which true dot (if any) is in the cell: returns its number or -1; near = the closest dot's place, in PT
function inCell(needTurns) {
var s = S, p = s.p, tg = s.find.target, n = M.count(p), lim = n > CAP ? CAP : n, i, N, be = Infinity, e, bx = 0, by = 0, hitN = -1;
var tx = tg.kind === 'xy' ? tg.x : tg.d * Math.cos(tg.deg * RAD), ty = tg.kind === 'xy' ? tg.y : tg.d * Math.sin(tg.deg * RAD);
for (i = 0; i < lim; i++) {
N = n > CAP ? Math.floor(i * n / CAP) : i; M.place(p, N, PT2);
e = (PT2.x - tx) * (PT2.x - tx) + (PT2.y - ty) * (PT2.y - ty); if (e < be) { be = e; bx = PT2.x; by = PT2.y; }
if (hitN < 0 && M.inside(tg, PT2)) hitN = N;
}
PT.x = bx; PT.y = by;
return hitN;
}
function judge(now) {
var s = S, f = s.find; if (!f.target || f.target.found) return;
var h = inCell(true);
if (h >= 0 && typedOK()) { supernova(now); return; }
f.tries++; ghost(PT.x, PT.y);
if (h >= 0 || inCell(false) >= 0) soft(now);
}
function exploreCheck() { var s = S, f = s.find; if (!s || !f.on || !f.target || f.target.found) return; if (inCell(false) >= 0) soft(nowMs()); }
// reached without typing (or without enough circles): a soft glow, and the numbers ask to be typed
function soft(now) {
var s = S, f = s.find; if (now - f.softAt < 700) return;
f.softAt = now; f.softs++;
if (s.p.rung === 1 && s.p.xy) { s.F.pulse('x'); s.F.pulse('y'); } else { s.F.pulse('start'); if (!f.target.turns) s.F.pulse('square'); }
tone(392, 0.05, 0.6, 0);
}
function supernova(now) {
var s = S, f = s.find, tg = f.target, nv = f.nova, tr = f.tries + 1, band = s.T.triesBand, i, P = s.part;
tg.found = true; f.novas++; s.p.stars++;
// the score only goes up: more for a smaller target, more for fewer typed tries
s.p.score += 10 * (tg.lv + 1) * (tr <= band[0] ? 3 : tr <= band[1] ? 2 : 1);
s.p.found.push(tg.kind === 'xy' ? tg.x : tg.d * Math.cos(tg.deg * RAD), tg.kind === 'xy' ? tg.y : tg.d * Math.sin(tg.deg * RAD)); if (s.p.found.length > 160) s.p.found.splice(0, 2);
nv.on = true; nv.t0 = now; nv.scale = tr <= band[0] ? 1.6 : tr <= band[1] ? 1.25 : 1;
nv.x = tg.kind === 'xy' ? tg.x : tg.d * Math.cos(tg.deg * RAD); nv.y = tg.kind === 'xy' ? tg.y : tg.d * Math.sin(tg.deg * RAD);
nv.gentle = s.reduced || now - f.lastFlash < 400;