In this section
- Repokuiper render · cosmic / tools/explore/repokuiper/repokuiper.js lines 1–690
Repokuiper
A JavaScript file in the explore folder of Cosmic that finds path (`findPath`), converts to screen (`toScreen`) and world (`toWorld`), calculates planar distances and draws on a canvas, using SHA-256.
rendercosmic / tools/explore/repokuiper/repokuiper.js · lines 1–690 of 690 · Not reached from any entry point (candidate for review) · pattern stepTween (shared by 2 files)
- What it does
- It draws its content. Defines 52 functions or classes, including $, esc, fmt, pct, emit. Side effects: changes the web page (DOM); makes network requests.
- Inputs & outputs
- Out: canvas drawing.
- What it achieves
- It finds path (`findPath`), fits scale (`fitScale`) and closes card (`closeCard`). One repository as a Kuiper universe. Its code works with 30 Hz. It responds to pointerdown, pointermove and pointerup events.
- Why it matters
- No other file in the estate was found to import it.
- Application
- cosmic · tools/explore/repokuiper · script
- Uses
- none found
- Used by
- none found
- Produces
- $, esc, fmt, pct, emit, key2u, key2th, omega, prepare, restyle, place, bodyPath
- Defines here
- $, esc, fmt, pct, emit, key2u, key2th, omega, prepare, restyle, place, bodyPath, findPath, view, camX, toScreen, toWorld, panBy, refollow, fitScale, flyTo, travel, pullBack, goHome, stepTween, STARS, moonsOf, overlays, draw, SX
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/repokuiper/repokuiper.js:1-690 · blob 29809a6b53ebfc3de8e88f0ab789d11d6816e7a6 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: unknown · users: none · canonical: unreached_review
// repokuiper.js: one repository as a Kuiper universe. Vanilla canvas, no dependencies.
// POSITIONS ARE COMPUTED FROM THE ORDINAL, NEVER STORED. Each body's ordinal k is the first 32 bits
// of sha256(path); u = k/2^32 and theta = frac(k * golden ratio) * 2pi. A folder sits in its parent's
// annulus, a file in its folder's core. The same law is implemented in build.py (layout()), and the
// Playwright check compares the two. Motion is a time offset on theta, nothing more.
//
// window.KUIPER is the plugin API (contract: /tmp/vk/kuiper4/CONTRACT.md, mirrored in build.py MODULES).
// Modules repokuiper-<name>.js register with KUIPER.use(name, (K) => {...}); they run once the data is in.
(() => {
'use strict';
const PHI = 0.6180339887498949, TAU = Math.PI * 2, R0 = 1000;
const CI = 0.44, CS = 0.40, CR = 0.24, W0 = 0.05, GA = 2.399963229728653;
const $ = (id) => document.getElementById(id);
const cv = $('sky'), g = cv.getContext('2d', { alpha: false });
const IDX = document.body.dataset.index === '1';
const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
const fmt = (n) => n.toLocaleString('en-GB');
const RM = matchMedia('(prefers-reduced-motion: reduce)').matches;
let D = null, NF = 0, NB = 0, ready = false;
let fpar, fdepth, fth, fdr, fom, fx, fy, fr, fpath, fkids, fnfiles; // folders
let bfo, bth, bdr, bom, bx, by, brw, bcol, breach, bentry, bout, bin; // bodies
let fsub, fcol, fsmall, frep, erep; // level of detail per folder
let bsx, bsy, bsr, vis, nvis = 0, lw; // per-frame screen cache (no per-frame allocation)
let dcol = null, dalpha = null, dscale = null, stylerName = null; // display style (a plugin colour/size mode)
// Frame budget (large repositories, e.g. globalgrid2050 ~2,450 files / ~850 folders):
// 1. level of detail: a folder whose ring is smaller than lodPx on screen is drawn as one dot, and edges into it are
// bundled into one arc per folder pair; lodPx grows while frames take longer than BUDGET_MS and shrinks back;
// 2. when the detail limit is reached, the canvas resolution steps down (res 1 -> 0.5 of the device ratio);
// 3. idle orbit motion is paced to 30 frames a second while frames are expensive (interaction stays at 60).
const LOD_MIN = 7, LOD_MAX = 48, BUDGET_MS = 24, EDGE_BUDGET = 900; // ~40 frames a second
let edgePx = LOD_MIN, lodPx = LOD_MIN, emaMs = 0, lastSig = '', res = 1, cheap = 0, lastDraw = 0, dirty = true, paced = false;
let W = 0, H = 0, DPR = 1, safeTop = 0;
const cam = { x: 0, y: 0, s: 1, r: 0 }; // r: rotation in radians (K2 two-finger rotate)
let cR = 1, sR = 0;
let follow = 0, focus = 0, home = 0;
let t = 0, paused = RM, last = performance.now();
let showEdges = false, showNames = IDX, xray = false, sel = -1, selMoon = -1, tween = null;
const drawMs = [], dtMs = [];
const pct = (a, p) => { const s = [...a].sort((x, y) => x - y); return s.length ? s[Math.min(s.length - 1, Math.floor(p * s.length))] : 0; };
// ------------------------------------------------------------------ plugin registry
const H_ = { frame: [], overlays: [], cards: [], keys: {}, ev: {}, uses: [], panels: [] };
const emit = (e, ...a) => { let r = false; for (const f of (H_.ev[e] || [])) { try { if (f(...a) === true) r = true; } catch (x) { console.warn('kuiper ' + e, x); } } return r; };
// ------------------------------------------------------------------ the law
const key2u = (k) => k / 4294967296;
const key2th = (k) => ((k * PHI) % 1) * TAU;
const omega = (rel) => W0 / Math.sqrt(0.15 + rel);
function prepare(d) {
D = d; NF = d.folders.length; NB = d.files.length;
const [FI, FS] = d.band || [0.04, 0.34];
fpar = new Int32Array(NF); fdepth = new Int32Array(NF); fth = new Float64Array(NF); fdr = new Float64Array(NF);
fom = new Float64Array(NF); fx = new Float64Array(NF); fy = new Float64Array(NF); fr = new Float64Array(NF);
fpath = []; fkids = []; fnfiles = new Int32Array(NF);
for (let i = 0; i < NF; i++) {
const [name, p, k] = d.folders[i];
fpar[i] = p; fkids.push([]);
if (p < 0) { fr[i] = R0; fpath.push(''); continue; }
fdepth[i] = fdepth[p] + 1; fr[i] = fr[p] * CR;
fth[i] = key2th(k); fdr[i] = CI + CS * Math.sqrt(key2u(k)); fom[i] = omega(fdr[i]);
fpath.push(fpath[p] ? fpath[p] + '/' + name : name); fkids[p].push(i);
}
bfo = new Int32Array(NB); bth = new Float64Array(NB); bdr = new Float64Array(NB); bom = new Float64Array(NB);
bx = new Float64Array(NB); by = new Float64Array(NB); brw = new Float64Array(NB);
bsx = new Float64Array(NB); bsy = new Float64Array(NB); bsr = new Float64Array(NB); vis = new Int32Array(NB);
lw = new Float32Array(NB).fill(-1);
bcol = []; breach = new Uint8Array(NB); bentry = new Uint8Array(NB); bout = []; bin = [];
for (let i = 0; i < NB; i++) {
const f = d.files[i];
bfo[i] = f[1]; fnfiles[f[1]]++;
bth[i] = key2th(f[2]); bdr[i] = FI + FS * Math.sqrt(key2u(f[2])); bom[i] = omega(bdr[i]);
const sq = Math.sqrt(Math.max(1, f[3]));
brw[i] = IDX ? R0 * 0.006 * Math.min(7, Math.max(0.6, sq / 20)) : fr[f[1]] * 0.018 * Math.min(4, Math.max(0.45, sq / 8));
bcol.push((d.roles[f[4]] || ['', '', '#4c5a65'])[2]);
breach[i] = f[5] & 1; bentry[i] = (f[5] & 2) ? 1 : 0; bout.push([]); bin.push([]);
}
for (const [a, b] of d.edges) { bout[a].push(b); bin[b].push(a); }
fsub = new Int32Array(NF); fsmall = new Uint8Array(NF); frep = new Int32Array(NF); erep = new Int32Array(NF);
for (let i = 0; i < NB; i++) { let f = bfo[i]; while (f >= 0) { fsub[f]++; f = fpar[f]; } }
restyle();
home = 0;
while (fnfiles[home] === 0 && fkids[home].length === 1) home = fkids[home][0];
}
// display colour/alpha/size per body: role colour unless a plugin styler is active; folder dots take the most common
function restyle() {
dcol = bcol.slice(); dalpha = null; dscale = null;
const fn = H_.styler;
if (fn) {
dalpha = new Float32Array(NB).fill(NaN); dscale = new Float32Array(NB).fill(1);
for (let i = 0; i < NB; i++) {
let s = null; try { s = fn(i); } catch (e) { s = null; }
if (!s) continue;
if (s.col) dcol[i] = s.col;
if (s.alpha != null) dalpha[i] = Math.max(0.03, Math.min(1, s.alpha));
if (s.scale != null) dscale[i] = Math.max(0.2, Math.min(6, s.scale));
}
}
fcol = new Array(NF).fill('#a6adbb');
const tally = []; for (let i = 0; i < NF; i++) tally.push({});
for (let i = 0; i < NB; i++) { let f = bfo[i]; while (f >= 0) { tally[f][dcol[i]] = (tally[f][dcol[i]] || 0) + 1; f = fpar[f]; } }
for (let i = 0; i < NF; i++) { let best = 0; for (const c in tally[i]) if (tally[i][c] > best) { best = tally[i][c]; fcol[i] = c; } }
dirty = true;
}
function place(time) {
for (let i = 1; i < NF; i++) {
const p = fpar[i], a = fth[i] + fom[i] * time, d = fr[p] * fdr[i];
fx[i] = fx[p] + d * Math.cos(a); fy[i] = fy[p] + d * Math.sin(a);
}
for (let i = 0; i < NB; i++) {
const f = bfo[i], a = bth[i] + bom[i] * time, d = fr[f] * bdr[i];
bx[i] = fx[f] + d * Math.cos(a); by[i] = fy[f] + d * Math.sin(a);
}
}
const bodyPath = (i) => (fpath[bfo[i]] ? fpath[bfo[i]] + '/' : '') + D.files[i][0];
let pathMap = null;
function findPath(p) {
if (!pathMap) {
pathMap = new Map();
for (let i = 0; i < NF; i++) pathMap.set('d:' + fpath[i], i);
for (let i = 0; i < NB; i++) pathMap.set('f:' + (IDX ? D.files[i][0] : bodyPath(i)), i);
}
p = String(p || '').replace(/^\/+|\/+$/g, '');
if (pathMap.has('f:' + p)) return { kind: 'file', i: pathMap.get('f:' + p) };
if (pathMap.has('d:' + p)) return { kind: 'folder', i: pathMap.get('d:' + p) };
return null;
}
// ------------------------------------------------------------------ camera
function view() { // the safe rectangle: below the header, above a phone card
const card = $('card');
const narrow = W < 760;
const bottom = (!card.hidden && narrow) ? H - card.offsetHeight : H;
const right = (!card.hidden && !narrow) ? W - card.offsetWidth - 24 : W;
return { cx: right / 2, cy: (safeTop + bottom) / 2, w: right, h: Math.max(80, bottom - safeTop) };
}
const camX = () => fx[follow] + cam.x, camY = () => fy[follow] + cam.y;
function toScreen(wx, wy, v) { v = v || view(); const c = Math.cos(cam.r), n = Math.sin(cam.r), dx = (wx - camX()) * cam.s, dy = (wy - camY()) * cam.s; return [dx * c - dy * n + v.cx, dx * n + dy * c + v.cy]; }
function toWorld(sx, sy, v) { v = v || view(); const c = Math.cos(cam.r), n = Math.sin(cam.r), dx = sx - v.cx, dy = sy - v.cy; return [(dx * c + dy * n) / cam.s + camX(), (-dx * n + dy * c) / cam.s + camY()]; }
// a screen-space drag (dx, dy) as a world-space camera offset, honouring rotation
function panBy(dx, dy) { const c = Math.cos(cam.r), n = Math.sin(cam.r); return [(dx * c + dy * n) / cam.s, (-dx * n + dy * c) / cam.s]; }
function refollow(i) { cam.x += fx[follow] - fx[i]; cam.y += fy[follow] - fy[i]; follow = i; }
function fitScale(i) { const v = view(); return Math.min(v.w, v.h) * 0.46 / fr[i]; }
function flyTo(folder, ox, oy, s, ms) {
refollow(folder);
ms = RM ? 0 : (ms == null ? 650 : ms);
if (ms <= 0) { tween = null; cam.x = ox; cam.y = oy; cam.s = s; dirty = true; return; }
tween = { t0: performance.now(), ms, x0: cam.x, y0: cam.y, l0: Math.log(cam.s), x1: ox, y1: oy, l1: Math.log(s) };
}
function travel(i) { focus = i; flyTo(i, 0, 0, fitScale(i)); crumb(); emit('travel', i); }
function pullBack() {
travel(focus > 0 ? fpar[focus] : 0);
}
function goHome() { closeCard(); travel(home); }
function stepTween(now) {
if (!tween) return;
let k = Math.min(1, (now - tween.t0) / tween.ms); const e = k < 0.5 ? 2 * k * k : 1 - Math.pow(-2 * k + 2, 2) / 2;
cam.x = tween.x0 + (tween.x1 - tween.x0) * e; cam.y = tween.y0 + (tween.y1 - tween.y0) * e;
cam.s = Math.exp(tween.l0 + (tween.l1 - tween.l0) * e);
if (k >= 1) { tween = null; emit('camera'); }
}
// ------------------------------------------------------------------ drawing
const STARS = (() => { let s = 2463534242; const r = () => ((s ^= s << 13, s ^= s >>> 17, s ^= s << 5) >>> 0) / 4294967296; const a = []; for (let i = 0; i < 260; i++) a.push([r(), r(), r(), r()]); return a; })();
function moonsOf(i, sx, sy, r) {
const sigs = D.files[i][11] || [], out = [];
for (let j = 0; j < sigs.length; j++) {
const ring = r * (1.9 + 0.75 * (j % 4)) + 4;
const a = j * GA + t * (0.6 / (1 + (j % 4)));
out.push([sx + ring * Math.cos(a), sy + ring * Math.sin(a), Math.max(1.4, r * 0.12)]);
}
return out;
}
const ovMs = {};
function overlays(z) {
for (const o of H_.overlays) {
if (o.z !== z) continue;
const st = ovMs[o.name] || (ovMs[o.name] = { ema: 0, skip: false });
if (!o.keep && st.ema > 4 && (st.skip = !st.skip)) continue; // a slow overlay draws every other frame (keep: never)
const t0 = performance.now();
g.save();
try { o.draw(g, K); } catch (e) { console.warn('kuiper overlay ' + o.name, e); }
g.restore();
const ms = performance.now() - t0; st.ema = st.ema ? st.ema * 0.9 + ms * 0.1 : ms;
}
}
function draw() {
const v = view();
const cx = camX(), cy = camY(), s = cam.s, vcx = v.cx, vcy = v.cy;
cR = Math.cos(cam.r); sR = Math.sin(cam.r);
const SX = (wx, wy) => ((wx - cx) * cR - (wy - cy) * sR) * s + vcx, SY = (wx, wy) => ((wx - cx) * sR + (wy - cy) * cR) * s + vcy;
g.globalCompositeOperation = 'source-over'; g.globalAlpha = 1;
g.fillStyle = '#000'; g.fillRect(0, 0, W, H);
// stars: fixed by a seeded generator, drifting with the camera for depth (one path)
const ox = cx * s * 0.004, oy = cy * s * 0.004;
g.fillStyle = '#fff'; g.globalAlpha = 0.35; g.beginPath();
for (const [a, b, c] of STARS) {
const x = ((a * W - ox * (0.3 + c)) % W + W) % W, y = ((b * H - oy * (0.3 + c)) % H + H) % H;
const z = c > 0.85 ? 1.5 : 1; g.rect(x, y, z, z);
}
g.fill();
// orbits: every folder is a ring around its own centre (one path for the plain rings)
g.lineWidth = 1;
let labels = 0; const flabels = [];
g.globalAlpha = 0.16; g.strokeStyle = '#a6adbb'; g.beginPath();
const big6 = 6 * Math.max(W, H);
for (let i = 0; i < NF; i++) {
const R = fr[i] * s; if (R < 3) continue;
const sx = SX(fx[i], fy[i]), sy = SY(fx[i], fy[i]);
if (sx + R < 0 || sx - R > W || sy + R < 0 || sy - R > H) continue;
if (R > big6 && i !== focus) continue;
if (i !== focus) { g.moveTo(sx + R, sy); g.arc(sx, sy, R, 0, TAU); }
if (i > 0 && R > (showNames ? 26 : 60) && labels < 120) { labels++; flabels.push(i, sx, sy, R); }
}
g.stroke();
if (focus >= 0 && fr[focus] * s >= 3) {
const sx = SX(fx[focus], fy[focus]), sy = SY(fx[focus], fy[focus]);
g.globalAlpha = 0.55; g.strokeStyle = '#00ffff'; g.beginPath(); g.arc(sx, sy, fr[focus] * s, 0, TAU); g.stroke();
}
g.font = '11px ui-monospace,Menlo,monospace'; g.textAlign = 'center';
for (let j = 0; j < flabels.length; j += 4) {
const i = flabels[j], isF = i === focus;
g.globalAlpha = isF ? 0.95 : 0.7; g.fillStyle = isF ? '#00ffff' : '#a6adbb';
g.fillText(D.folders[i][0] + (IDX ? '' : '/'), flabels[j + 1], Math.max(safeTop + 12, flabels[j + 2] - flabels[j + 3] - 4));
}
g.textAlign = 'left';
// level of detail: fsmall 1 = folder drawn as one dot, 2 = inside such a folder; frep = the dot that stands for it
for (let i = 0; i < NF; i++) {
const p = fpar[i];
if (p >= 0 && fsmall[p]) { fsmall[i] = 2; frep[i] = frep[p]; continue; }
if (fr[i] * s >= lodPx || i === focus) { fsmall[i] = 0; frep[i] = -1; continue; }
fsmall[i] = 1; frep[i] = i;
}
// screen positions of every body not hidden inside a dot, once per frame
nvis = 0;
for (let i = 0; i < NB; i++) {
bsx[i] = SX(bx[i], by[i]); bsy[i] = SY(bx[i], by[i]);
bsr[i] = Math.max(0.9, brw[i] * s * (dscale ? dscale[i] : 1));
if (fsmall[bfo[i]] && sel !== i) continue;
const r = bsr[i];
if (bsx[i] < -r - 60 || bsx[i] > W + r + 60 || bsy[i] < -r - 60 || bsy[i] > H + r + 60) continue;
vis[nvis++] = i;
}
// edges, on demand, plus the selected body's own edges always. Edges into folders drawn as dots are bundled:
// one arc per pair of dots, wider for more edges (level of detail for edges too)
const onScr = (x, y) => x > -40 && x < W + 40 && y > -40 && y < H + 40;
const curve = (x1, y1, x2, y2) => { g.moveTo(x1, y1); g.quadraticCurveTo((x1 + x2) / 2 - (y2 - y1) * 0.18, (y1 + y2) / 2 + (x2 - x1) * 0.18, x2, y2); };
const arcs = (pairs, col, alpha, w) => {
g.globalAlpha = alpha; g.strokeStyle = col; g.lineWidth = w;
let n = 0; g.beginPath();
for (const [a, b] of pairs) { curve(bsx[a], bsy[a], bsx[b], bsy[b]); if (++n % 48 === 0) { g.stroke(); g.beginPath(); } }
g.stroke();
};
overlays('under');
if (showEdges) {
// edges have their own detail threshold (edgePx >= lodPx) that keeps the drawn arcs near EDGE_BUDGET
const ep = Math.max(lodPx, edgePx);
for (let i = 0; i < NF; i++) {
const p = fpar[i];
erep[i] = (p >= 0 && erep[p] >= 0) ? erep[p] : (frep[i] >= 0 ? frep[i] : (i !== focus && fr[i] * s < ep ? i : -1));
}
const bundles = new Map(), single = [];
const fsx = (f) => SX(fx[f], fy[f]), fsy = (f) => SY(fx[f], fy[f]);
for (const [a, b] of D.edges) {
const ra = erep[bfo[a]], rb = erep[bfo[b]];
if (ra < 0 && rb < 0) { if (onScr(bsx[a], bsy[a]) || onScr(bsx[b], bsy[b])) single.push(a, b); continue; }
if (ra >= 0 && ra === rb) continue;
const ka = ra >= 0 ? ra : NF + a, kb = rb >= 0 ? rb : NF + b, key = ka < kb ? ka * 1e6 + kb : kb * 1e6 + ka;
bundles.set(key, (bundles.get(key) || 0) + 1);
}
g.globalAlpha = 0.14; g.strokeStyle = '#66ccff'; g.lineWidth = 1; g.beginPath();
for (let j = 0, n = 0; j < single.length; j += 2) { curve(bsx[single[j]], bsy[single[j]], bsx[single[j + 1]], bsy[single[j + 1]]); if (++n % 48 === 0) { g.stroke(); g.beginPath(); } }
g.stroke();
const tiers = [[], [], []];
for (const [key, n] of bundles) {
const ka = Math.floor(key / 1e6), kb = key - ka * 1e6;
const x1 = ka < NF ? fsx(ka) : bsx[ka - NF], y1 = ka < NF ? fsy(ka) : bsy[ka - NF];
const x2 = kb < NF ? fsx(kb) : bsx[kb - NF], y2 = kb < NF ? fsy(kb) : bsy[kb - NF];
if (!onScr(x1, y1) && !onScr(x2, y2)) continue;
tiers[n >= 12 ? 2 : n >= 3 ? 1 : 0].push(x1, y1, x2, y2);
}
const drawn = single.length / 2 + (tiers[0].length + tiers[1].length + tiers[2].length) / 4;
if (drawn > EDGE_BUDGET && edgePx < 400) { edgePx = Math.max(lodPx, edgePx) * 1.25; dirty = true; }
else if (drawn < EDGE_BUDGET * 0.4 && edgePx > lodPx) { edgePx = Math.max(lodPx, edgePx / 1.1); dirty = true; }
tiers.forEach((a, k) => {
g.globalAlpha = [0.14, 0.2, 0.28][k]; g.lineWidth = [1, 1.8, 3][k]; g.beginPath();
for (let j = 0, n = 0; j < a.length; j += 4) { curve(a[j], a[j + 1], a[j + 2], a[j + 3]); if (++n % 48 === 0) { g.stroke(); g.beginPath(); } }
g.stroke();
});
}
if (sel >= 0) { arcs(bout[sel].map((b) => [sel, b]), '#66ccff', 0.85, 1.4); arcs(bin[sel].map((a) => [a, sel]), '#00ffff', 0.85, 1.4); }
g.lineWidth = 1;
if (xray) g.globalCompositeOperation = 'lighter';
// folder dots, batched by colour
const dots = {};
for (let i = 0; i < NF; i++) {
if (fsmall[i] !== 1 || !fsub[i]) continue;
const sx = SX(fx[i], fy[i]), sy = SY(fx[i], fy[i]);
if (sx < -20 || sx > W + 20 || sy < -20 || sy > H + 20) continue;
const r = Math.max(1.2, Math.min(fr[i] * s * 0.5, 1 + Math.sqrt(fsub[i]) * 0.6));
(dots[fcol[i]] || (dots[fcol[i]] = [])).push(sx, sy, r);
}
g.globalAlpha = xray ? 0.5 : 0.75;
for (const c in dots) {
const a = dots[c]; g.fillStyle = c; g.beginPath();
for (let j = 0; j < a.length; j += 3) { g.moveTo(a[j] + a[j + 2], a[j + 1]); g.arc(a[j], a[j + 1], a[j + 2], 0, TAU); }
g.fill();
}
// bodies, batched by colour and brightness
let names = 0; const big = [], buckets = {}, rings = [], labels2 = [];
for (let n = 0; n < nvis; n++) {
const i = vis[n], sx = bsx[i], sy = bsy[i], r = bsr[i];
const al = dalpha && dalpha[i] === dalpha[i] ? dalpha[i] : (xray ? 0.5 : breach[i] ? 1 : 0.3);
const k = dcol[i] + '|' + al.toFixed(2);
(buckets[k] || (buckets[k] = [])).push(sx, sy, r);
if (bentry[i] && r > 2.5) rings.push(sx, sy, r);
if (r > 9 && !IDX) big.push([i, sx, sy, r]);
if (((showNames && r > 2.5) || r > 13) && names++ < 260) labels2.push(i, sx, sy, r);
}
for (const k in buckets) {
const a = buckets[k], bar = k.lastIndexOf('|');
g.globalAlpha = +k.slice(bar + 1); g.fillStyle = k.slice(0, bar); g.beginPath();
for (let j = 0; j < a.length; j += 3) {
const sx = a[j], sy = a[j + 1], r = a[j + 2];
if (r < 1.6) g.rect(sx - r, sy - r, 2 * r, 2 * r); else { g.moveTo(sx + r, sy); g.arc(sx, sy, r, 0, TAU); }
}
g.fill();
}
if (rings.length) {
g.globalAlpha = 0.6; g.strokeStyle = '#00ffff'; g.beginPath();
for (let j = 0; j < rings.length; j += 3) { g.moveTo(rings[j] + rings[j + 2] + 2.5, rings[j + 1]); g.arc(rings[j], rings[j + 1], rings[j + 2] + 2.5, 0, TAU); }
g.stroke();
}
g.font = '11px ui-monospace,Menlo,monospace'; g.fillStyle = '#fff';
// Labels never overlap: biggest bodies (and the selected one) first; a label that would collide with one already
// drawn is left out until the user zooms in and the bodies spread apart. Text widths are measured once per body.
const order = [];
for (let j = 0; j < labels2.length; j += 4) order.push(j);
order.sort((a, b) => (labels2[b] === sel) - (labels2[a] === sel) || labels2[b + 3] - labels2[a + 3]);
const placed = [];
for (const j of order) {
const i = labels2[j], text = D.files[i][0], x = labels2[j + 1] + labels2[j + 3] + 4, y = labels2[j + 2] + 4;
if (lw[i] < 0) lw[i] = g.measureText(text).width;
const box = [x - 2, y - 11, x + lw[i] + 2, y + 3];
let clash = false;
for (let q = 0; q < placed.length; q++) { const p = placed[q]; if (box[0] < p[2] && box[2] > p[0] && box[1] < p[3] && box[3] > p[1]) { clash = true; break; } }
if (clash) continue;
placed.push(box); g.globalAlpha = breach[i] ? 0.9 : 0.55; g.fillText(text, x, y);
}
g.globalCompositeOperation = 'source-over';
// moons: the functions of any body big enough to hold them
big.sort((a, b) => b[3] - a[3]);
for (const [i, sx, sy, r] of big.slice(0, 40)) {
const ms = moonsOf(i, sx, sy, r);
g.fillStyle = dcol[i];
for (let j = 0; j < ms.length; j++) {
g.globalAlpha = (sel === i && selMoon === j) ? 1 : 0.75;
g.beginPath(); g.arc(ms[j][0], ms[j][1], ms[j][2], 0, TAU); g.fill();
if (r > 34 && j < 40) { g.globalAlpha = 0.7; g.fillStyle = '#a6adbb'; g.font = '10px ui-monospace,Menlo,monospace'; g.fillText(D.files[i][11][j].split('(')[0], ms[j][0] + 4, ms[j][1] + 3); g.fillStyle = dcol[i]; }
}
}
if (sel >= 0) {
const sx = bsx[sel], sy = bsy[sel], r = bsr[sel];
g.globalAlpha = 1; g.strokeStyle = '#fff'; g.lineWidth = 1.5; g.beginPath(); g.arc(sx, sy, r + 5, 0, TAU); g.stroke(); g.lineWidth = 1;
}
g.globalAlpha = 1;
overlays('over');
overlays('hud');
g.globalAlpha = 1; g.globalCompositeOperation = 'source-over';
}
function frame(now) {
const dt = Math.min(100, now - last); last = now;
if (!paused) t += dt / 1000;
stepTween(now);
for (const f of H_.frame) { try { if (f(now, dt) === true) dirty = true; } catch (e) { console.warn('kuiper onFrame', e); } }
// nothing moves while paused: skip the frame unless the camera, the selection or a toggle changed
const sig = [cam.x, cam.y, cam.s, cam.r, follow, focus, sel, selMoon, showEdges, showNames, xray, W, H, safeTop, res].join();
const still = sig === lastSig && !tween && !dirty;
// idle orbit motion only (no input, no tween): paced to 30 frames a second while frames are expensive
if (emaMs > BUDGET_MS * 0.7) paced = true; else if (emaMs < BUDGET_MS * 0.45) paced = false;
const idleGap = paced ? 32 : 0;
if (!(still && (paused || now - lastDraw < idleGap))) {
lastSig = sig; dirty = false; lastDraw = now;
const t0 = performance.now();
place(t); draw();
const ms = performance.now() - t0;
drawMs.push(ms); dtMs.push(dt);
if (drawMs.length > 600) { drawMs.shift(); dtMs.shift(); }
// frame budget: the frame interval includes the GPU/raster time the draw call itself does not show, but a screen
// capped at 30 Hz (phone low-power mode) is not slowness: cost = draw time + the interval beyond the usual one
const base = Math.min(34, Math.max(8, pct(dtMs.slice(-120), 0.1)));
const cost = ms + Math.max(0, dt - base);
emaMs = emaMs ? emaMs * 0.9 + cost * 0.1 : cost;
if (emaMs > BUDGET_MS && lodPx < LOD_MAX) { lodPx = Math.min(LOD_MAX, lodPx * 1.15); cheap = 0; }
else if (emaMs > BUDGET_MS * 1.3 && res > 0.5) { res = Math.max(0.5, res * 0.8); cheap = 0; emaMs = BUDGET_MS; resize(); }
else if (emaMs < BUDGET_MS * 0.5) {
if (res < 1 && ++cheap > 90) { res = Math.min(1, res * 1.25); cheap = 0; resize(); }
else if (res >= 1 && lodPx > LOD_MIN) lodPx = Math.max(LOD_MIN, lodPx / 1.05);
}
}
requestAnimationFrame(frame);
}
// ------------------------------------------------------------------ hit testing and cards
// a folder drawn as one dot (level of detail): its files are not drawn, so they cannot be tapped
const collapsed = (f) => f !== focus && fr[f] * cam.s < lodPx;
function hit(sx, sy) {
const v = view();
let best = -1, bd = 1e9, moon = -1;
for (let i = 0; i < NB; i++) {
if (collapsed(bfo[i]) && i !== sel) continue;
const [x, y] = toScreen(bx[i], by[i], v), r = Math.max(0.9, brw[i] * cam.s * (dscale ? dscale[i] : 1));
if (r > 9 && !IDX) {
const ms = moonsOf(i, x, y, r);
for (let j = 0; j < ms.length; j++) { const dm = Math.hypot(ms[j][0] - sx, ms[j][1] - sy); if (dm < Math.max(8, ms[j][2] + 4) && dm < bd) { bd = dm; best = i; moon = j; } }
}
const d = Math.hypot(x - sx, y - sy);
if (d < Math.max(r + 6, 16) && d - r < bd) { bd = Math.max(0, d - r); best = i; moon = -1; }
}
return [best, moon];
}
function folderAt(sx, sy) {
const v = view(); let best = -1, bdep = -1, bd = 1e9;
for (let i = 1; i < NF; i++) {
const R = fr[i] * cam.s, dot = collapsed(i) && fsub[i] > 0 && !(fpar[i] >= 0 && collapsed(fpar[i]));
if (R < 14 && !dot) continue;
const [x, y] = toScreen(fx[i], fy[i], v), d = Math.hypot(x - sx, y - sy);
if (d <= Math.max(R, dot ? 16 : 0) && (fdepth[i] > bdep || (fdepth[i] === bdep && d < bd))) { best = i; bdep = fdepth[i]; bd = d; }
}
return best;
}
function tap(sx, sy) {
place(t);
if (emit('tap', sx, sy)) return;
const [i, m] = hit(sx, sy);
if (i >= 0) { select(i, m); return; }
const f = folderAt(sx, sy);
if (f >= 0 && f !== focus) { closeCard(); travel(f); return; }
closeCard();
}
function role(i) { return D.roles[D.files[i][4]] || ['other', 'Other', '#4c5a65']; }
function select(i, moon) {
sel = i; selMoon = moon == null ? -1 : moon; dirty = true;
const f = D.files[i], c = $('card'), base = D.base, ro = role(i);
let h = '<button class="x" data-close aria-label="close">×</button>';
if (IDX) {
h += `<h2>${esc(f[0])}</h2><div class="m"><span class="chip" style="background:${ro[2]}"></span>mostly ${esc(ro[1])}</div>`
+ `<p class="syn">${esc(f[8])}</p><div class="key">${esc(f[0])}@${esc(f[15].slice(0, 12))} · ordinal k = ${f[2]}</div>`
+ `<div class="links"><a href="${esc(f[14])}"><b>open its Kuiper →</b></a><a href="${esc(base + f[6])}">repository page</a>`
+ `<a href="${esc(D.gh + '/' + f[0] + '/tree/' + f[15])}" rel="noopener">GitHub</a></div>`;
} else {
const p = bodyPath(i), lines = f[3], commit = D.commit;
const ghf = `${D.gh}/blob/${commit}/${p.split('/').map(encodeURIComponent).join('/')}`;
const fl = [f[12], fmt(lines) + ' lines', (f[5] & 1) ? 'reachable' : 'unreached', (f[5] & 2) ? 'entry point' : '', (f[5] & 4) ? 'pure' : '',
f[10] ? 'reached from ' + fmt(f[10]) + ' entries' : '', f[13] && f[13] !== 'unknown' && !f[13].startsWith('unreached') ? f[13].replace(/_/g, ' ') : ''].filter(Boolean).join(' · ');
if (moon >= 0) {
h += `<h2>${esc(f[11][moon])}</h2><div class="m">function ${moon + 1} of ${f[11].length} in <b>${esc(f[0])}</b> (from the signatures)</div>`;
} else {
h += `<h2>${esc(f[7])}</h2>`;
}
h += `<div class="m"><span class="chip" style="background:${ro[2]}"></span>${esc(ro[1])}</div>`
+ `<p class="syn">${esc(f[8])}</p>`
+ `<div class="key">${esc(D.repo)}@${commit.slice(0, 12)} ${esc(p)}:1-${lines}<br>blob ${f[9] ? esc(f[9]) : '<span class="m">not read: no clone holds this commit</span>'}<br>ordinal k = ${f[2]} (sha256(path)[:32 bits])</div>`
+ `<div class="m">${fl}${f[11].length ? ' · ' + f[11].length + ' functions' : ''}</div>`;
const list = (arr, label) => arr.length ? `<div class="m">${label} (${arr.length}):</div><ul>${arr.slice(0, 12).map((j) => `<li><a data-sel="${j}" href="#">${esc(bodyPath(j))}</a></li>`).join('')}${arr.length > 12 ? '<li>…</li>' : ''}</ul>` : '';
h += list(bout[i], 'uses') + list(bin[i], 'used by');
h += `<div class="links">${f[6] ? `<a href="${esc(base + f[6])}">section page</a>` : ''}<a href="${esc(ghf + '#L1-L' + lines)}" rel="noopener">GitHub</a>`
+ `<a href="${esc(base + D.repo_page)}">repository page</a><a href="#" data-go="${bfo[i]}">travel in →</a></div>`;
}
for (const s of H_.cards) {
let x = ''; try { x = s.fn(i, selMoon) || ''; } catch (e) { console.warn('kuiper card ' + s.name, e); }
if (x) h += `<section class="kc" data-kc="${esc(s.name)}">${x}</section>`;
}
c.innerHTML = h; c.hidden = false;
emit('select', i, selMoon);
}
function closeCard() { const was = sel; sel = -1; selMoon = -1; $('card').hidden = true; dirty = true; if (was >= 0) emit('deselect'); }
function centreOn(i) {
const f = bfo[i];
focus = f; crumb();
place(t);
const s = Math.max(fitScale(f), 30 / Math.max(1e-9, brw[i]) / 4);
flyTo(f, bx[i] - fx[f], by[i] - fy[f], Math.min(s, fitScale(f) * 6));
}
// ------------------------------------------------------------------ chrome
function crumb() {
const parts = []; let i = focus; while (i >= 0) { parts.unshift(i); i = fpar[i]; }
$('crumb').innerHTML = parts.map((j) => `<a data-go="${j}">${esc(j === 0 ? (D.repo || 'all repositories') : D.folders[j][0])}</a>`).join(' / ')
+ ` <span style="color:#a6adbb">· ${fmt(fsub[focus])} bodies here</span>`;
}
function setOn(k, on) { const b = document.querySelector(`#tools button[data-k="${k}"]`); if (b) b.classList.toggle('on', on); }
function key(k, ev) {
for (const f of (H_.keys[k] || [])) { try { if (f(ev) === true) return true; } catch (e) { console.warn('kuiper key ' + k, e); } }
switch (k) {
case 'Backspace': if (ev) ev.preventDefault(); closeCard(); pullBack(); break;
case 'Escape': closeCard(); $('find').hidden = true; $('help').hidden = true; for (const p of H_.panels) if (p.dataset.esc !== '0') p.hidden = true; break;
case 'h': goHome(); break;
case 'e': showEdges = !showEdges; setOn('e', showEdges); break;
case 'l': showNames = !showNames; setOn('l', showNames); break;
case 'x': xray = !xray; setOn('x', xray); break;
case 'p': paused = !paused; setOn('p', paused); break;
case 'f': { const f = $('find'); f.hidden = !f.hidden; setOn('f', !f.hidden); if (!f.hidden) { fill(''); $('q').value = ''; $('q').focus(); } break; }
case '?': $('help').hidden = !$('help').hidden; break;
case '+': case '=': zoomAt(W / 2, H / 2, 1.4); break;
case '-': zoomAt(W / 2, H / 2, 1 / 1.4); break;
default: return false;
}
return true;
}
function fill(q) {
q = q.toLowerCase(); const out = [];
for (let i = 0; i < NB && out.length < 300; i++) {
const p = IDX ? D.files[i][0] : bodyPath(i);
if (!q || p.toLowerCase().includes(q) || D.files[i][7].toLowerCase().includes(q)) out.push(`<li data-sel="${i}">${esc(p)} <span>${fmt(D.files[i][3])}</span></li>`);
}
$('list').innerHTML = out.join('') || '<li><span>nothing matches</span></li>';
}
function zoomAt(sx, sy, f) {
tween = null; const v = view();
const [wx, wy] = toWorld(sx, sy, v);
cam.s = Math.min(1e7, Math.max(1e-4, cam.s * f));
const [wx2, wy2] = toWorld(sx, sy, v); cam.x += wx - wx2; cam.y += wy - wy2;
}
function resize() {
DPR = Math.max(0.75, Math.min(2, window.devicePixelRatio || 1) * res);
W = window.innerWidth; H = window.innerHeight;
cv.width = Math.round(W * DPR); cv.height = Math.round(H * DPR);
g.setTransform(DPR, 0, 0, DPR, 0, 0);
safeTop = $('hud').offsetHeight;
for (const id of ['find', 'help']) $(id).style.top = (safeTop + 4) + 'px';
for (const p of H_.panels) if (p.dataset.top !== '0') p.style.top = (safeTop + 4) + 'px';
dirty = true;
if (ready) emit('resize');
}
// ------------------------------------------------------------------ input: touch first
const pts = new Map(); let drag = null, pinch = null, wheelT = 0;
cv.addEventListener('pointerdown', (e) => {
cv.setPointerCapture(e.pointerId); pts.set(e.pointerId, [e.clientX, e.clientY]);
if (pts.size === 1) drag = { x: e.clientX, y: e.clientY, cx: cam.x, cy: cam.y, t: performance.now(), moved: false };
else if (pts.size === 2) {
const [a, b] = [...pts.values()]; drag = null; tween = null;
pinch = { d: Math.hypot(a[0] - b[0], a[1] - b[1]), s: cam.s, mx: (a[0] + b[0]) / 2, my: (a[1] + b[1]) / 2 };
}
});
cv.addEventListener('pointermove', (e) => {
if (!pts.has(e.pointerId)) return;
pts.set(e.pointerId, [e.clientX, e.clientY]);
if (pinch && pts.size >= 2) {
const [a, b] = [...pts.values()], d = Math.hypot(a[0] - b[0], a[1] - b[1]);
const mx = (a[0] + b[0]) / 2, my = (a[1] + b[1]) / 2;
zoomAt(pinch.mx, pinch.my, pinch.s * d / Math.max(1, pinch.d) / cam.s);
const [px, py] = panBy(mx - pinch.mx, my - pinch.my); cam.x -= px; cam.y -= py; pinch.mx = mx; pinch.my = my;
} else if (drag) {
const dx = e.clientX - drag.x, dy = e.clientY - drag.y;
if (!drag.moved && Math.hypot(dx, dy) > 7) { drag.moved = true; tween = null; drag.cx = cam.x - 0; drag.cy = cam.y; drag.x = e.clientX; drag.y = e.clientY; return; }
if (drag.moved) { const [px, py] = panBy(dx, dy); cam.x = drag.cx - px; cam.y = drag.cy - py; }
}
});
const up = (e) => {
if (!pts.has(e.pointerId)) return;
pts.delete(e.pointerId);
const moved = (drag && drag.moved) || pinch;
if (drag && !drag.moved && e.type === 'pointerup' && performance.now() - drag.t < 600) tap(e.clientX, e.clientY);
if (pts.size < 2) pinch = null;
if (pts.size === 1) { const [p] = [...pts.values()]; drag = { x: p[0], y: p[1], cx: cam.x, cy: cam.y, t: 0, moved: true }; } else if (pts.size === 0) { drag = null; if (moved) emit('camera'); }
};
cv.addEventListener('pointerup', up); cv.addEventListener('pointercancel', up);
cv.addEventListener('wheel', (e) => {
e.preventDefault(); zoomAt(e.clientX, e.clientY, Math.exp(-e.deltaY * (e.deltaMode ? 0.05 : 0.0015)));
clearTimeout(wheelT); wheelT = setTimeout(() => emit('camera'), 200);
}, { passive: false });
window.addEventListener('keydown', (e) => {
if (e.target && (e.target.id === 'q' || /^(INPUT|TEXTAREA|SELECT)$/.test(e.target.tagName) || e.target.isContentEditable)) { if (e.key === 'Escape') key('Escape'); return; }
if (e.metaKey || e.ctrlKey || e.altKey) return;
key(e.key, e);
});
document.addEventListener('click', (e) => {
const el = e.target.closest('[data-k],[data-close],[data-sel],[data-go]'); if (!el) return;
if (el.dataset.k) { key(el.dataset.k); return; }
e.preventDefault();
if (el.hasAttribute('data-close')) closeCard();
else if (el.dataset.sel != null) { const i = +el.dataset.sel; $('find').hidden = true; setOn('f', false); select(i, -1); centreOn(i); }
else if (el.dataset.go != null) { travel(+el.dataset.go); }
});
$('q').addEventListener('input', (e) => fill(e.target.value));
window.addEventListener('resize', resize);
// ------------------------------------------------------------------ window.KUIPER: the plugin API (CONTRACT.md v1)
const pageBase = (document.body.dataset.json || '').replace(/\.json$/, '');
const jsonCache = {};
let legendEl = null;
const K = {
version: 1,
use(name, init) { H_.uses.push([name, init]); if (ready) runUse(name, init); },
get D() { return D; }, get isIndex() { return IDX; }, get ready() { return ready; }, get NB() { return NB; }, get NF() { return NF; },
get t() { return t; }, get W() { return W; }, get H() { return H; }, get safeTop() { return safeTop; }, get cam() { return cam; },
get focus() { return focus; }, get sel() { return sel; }, get selMoon() { return selMoon; }, get follow() { return follow; },
get homeFolder() { return home; }, get lodPx() { return lodPx; }, get paused() { return paused; }, get reducedMotion() { return RM; },
get styler() { return stylerName; }, get edges() { return showEdges; },
get arr() { return { fx, fy, fr, fpar, fdepth, fkids, fsub, fpath, bx, by, brw, bfo, breach, bentry, bout, bin, bsx, bsy, bsr, dcol }; },
bodyPath, folderPath: (f) => fpath[f], findPath, view, toScreen, toWorld, collapsed,
visibleBodies() { return Array.from(vis.subarray(0, nvis)); },
select(i, moon) { select(i, moon); }, closeCard, travel, centreOn, pullBack, home: goHome, flyTo, zoomAt,
goHome,
setCam(c) { tween = null; if (c.x != null) cam.x = c.x; if (c.y != null) cam.y = c.y; if (c.s != null) cam.s = c.s; if (c.r != null) cam.r = c.r; dirty = true; },
setPaused(b) { paused = !!b; setOn('p', paused); dirty = true; },
setEdges(b) { showEdges = !!b; setOn('e', showEdges); },
redraw() { dirty = true; },
onFrame(fn) { H_.frame.push(fn); },
addOverlay(name, o) { H_.overlays = H_.overlays.filter((x) => x.name !== name); H_.overlays.push({ name, z: o.z || 'over', draw: o.draw, keep: !!o.keep }); dirty = true; },
removeOverlay(name) { H_.overlays = H_.overlays.filter((x) => x.name !== name); dirty = true; },
setStyler(name, fn) { if (typeof name === 'function') { fn = name; name = 'custom'; } stylerName = fn ? name : null; H_.styler = fn || null; if (D) restyle(); emit('style', stylerName); },
restyle() { if (D) restyle(); },
addCardSection(name, fn) { H_.cards.push({ name, fn }); },
addButton(o) {
const b = document.createElement('button'); b.type = 'button'; b.id = 'kb-' + o.id; b.textContent = o.label; b.title = o.title || o.label;
b.dataset.mod = o.id;
b.addEventListener('click', (e) => { e.preventDefault(); e.stopPropagation(); const on = o.toggle ? !b.classList.contains('on') : true; if (o.toggle) b.classList.toggle('on', on); if (o.onClick) o.onClick(on); });
const tools = $('tools'), upEl = $('up'), helpB = tools.querySelector('button[data-k="?"]');
tools.insertBefore(b, helpB || upEl || null);
if (o.key) K.addKey(o.key, () => { b.click(); return true; });
resize();
return b;
},
setButtonOn(id, on) { const b = $('kb-' + id); if (b) b.classList.toggle('on', !!on); },
addKey(k, fn) { (H_.keys[k] || (H_.keys[k] = [])).push(fn); },
on(e, fn) { (H_.ev[e] || (H_.ev[e] = [])).push(fn); },
emit,
panel(id) {
let p = $('kp-' + id); if (p) return p;
p = document.createElement('div'); p.className = 'kp'; p.id = 'kp-' + id; p.hidden = true;
p.style.top = (safeTop + 4) + 'px';
document.body.appendChild(p); H_.panels.push(p); return p;
},
legend(html) {
if (!legendEl) { legendEl = document.createElement('div'); legendEl.id = 'kp-legend'; legendEl.className = 'kp kp-legend'; document.body.appendChild(legendEl); }
legendEl.innerHTML = html || ''; legendEl.hidden = !html;
},
loadJSON(suffix) {
const url = pageBase + '.' + suffix + '.json';
return jsonCache[url] || (jsonCache[url] = fetch(url).then((r) => (r.ok ? r.json() : null)).catch(() => null));
},
async ordinal(path) {
if (!(window.crypto && crypto.subtle)) return null;
const h = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(path)));
return ((h[0] << 24) >>> 0) + (h[1] << 16) + (h[2] << 8) + h[3];
},
esc, fmt,
perf() { const o = {}; for (const k in ovMs) o[k] = +ovMs[k].ema.toFixed(2); return { lodPx, emaMs, res, dpr: DPR, ...window.__rk.stats(), overlays: o }; },
};
function runUse(name, init) { try { init(K); } catch (e) { console.error('kuiper module ' + name + ' failed', e); } }
window.KUIPER = K;
// ------------------------------------------------------------------ self-test surface (read by the Playwright check)
window.__rk = {
ready: false,
layout0() { place(0); const r = { folders: [], files: [] }; for (let i = 0; i < NF; i++) r.folders.push([fx[i], fy[i], fr[i]]); for (let i = 0; i < NB; i++) r.files.push([bx[i], by[i]]); place(t); return r; },
screenOf(i) { place(t); return toScreen(bx[i], by[i], view()); },
visible() { const v = view(), out = []; place(t); for (let i = 0; i < NB; i++) { if (collapsed(bfo[i])) continue; const [x, y] = toScreen(bx[i], by[i], v); if (x > 10 && x < W - 10 && y > safeTop + 10 && y < H - 10) out.push([i, brw[i] * cam.s]); } return out; },
lod() { return { px: lodPx, ema: emaMs, res, dpr: DPR }; },
stats() { return { frames: drawMs.length, draw_mean: drawMs.reduce((a, b) => a + b, 0) / Math.max(1, drawMs.length), draw_p95: pct(drawMs, 0.95), dt_mean: dtMs.reduce((a, b) => a + b, 0) / Math.max(1, dtMs.length), dt_p95: pct(dtMs, 0.95) }; },
// flush = read one pixel after each frame, forcing the raster work into the measurement (true cost, not just JS)
bench(n, flush) { const a = []; for (let k = 0; k < n; k++) { const t0 = performance.now(); t += 1 / 60; place(t); draw(); if (flush) g.getImageData(0, 0, 1, 1); a.push(performance.now() - t0); } return { frames: n, mean: a.reduce((x, y) => x + y, 0) / n, p50: pct(a, 0.5), p95: pct(a, 0.95) }; },
setLod(px, r) { if (px != null) lodPx = px; if (r != null) { res = r; resize(); } },
zoom(f) { zoomAt(W / 2, H / 2, f); },
pause(on) { paused = on; setOn('p', paused); },
select, travel, get sel() { return sel; }, get focus() { return focus; }, get N() { return NB; },
};
const src = document.body.dataset.json;
fetch(src).then((r) => { if (!r.ok) throw new Error(r.status); return r.json(); }).then((d) => {
prepare(d); resize(); place(0);
focus = home; follow = home; cam.s = fitScale(home); crumb();
setOn('l', showNames); setOn('p', paused);
ready = true;
for (const [name, init] of H_.uses) runUse(name, init);
requestAnimationFrame((n) => { last = n; frame(n); });
window.__rk.ready = true;
}).catch((e) => {
const el = $('err'); el.hidden = false;
el.textContent = src + ' did not load (' + e.message + '). The universe will not invent its bodies. Serve this folder over http; file:// blocks fetch.';
});
})();