In this section
- Descent geodesy · kuiper-belt / learn-the-kuiper/202610050609/modules/descent.js lines 701–1035
- Grid render · kuiper-belt / learn-the-kuiper/202610050609/modules/grid.js lines 1–365
Descent
A JavaScript file in the learn the kuiper folder of Kuiper Belt that maps sat s, using Web Mercator and haversine and uses data from the GridAtlas repository.
geodesykuiper-belt / learn-the-kuiper/202610050609/modules/descent.js · lines 701–1035 of 1035 · version 2026-10-05 06:09 (continued from section 1529) · Entry point · pattern nearestToCentre (shared by 2 files)
- What it does
- It maps sat s, l sat and substations. Defines 70 functions or classes, including loadScript, ensureGridData, merc, unmercLat, decode. 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: substations, 400kV, 132kV, 76kV, 27kV, 22kV.
- Inputs & outputs
- In: data source: gridatlas data; JSON file style.json; GeoJSON file kv.geojson. Out: interactive map; canvas drawing. Coordinate systems named: Web Mercator / EPSG:3857. Voltage levels named: 400kV, 132kV, 76kV, 27kV, 22kV, 8kV.
- Downstream impact
- Used directly by 1 file: 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 loads script (`loadScript`), decodes lines (`decodeLines`) and places ui (`placeUI`). `descent.js` SEE THROUGH, a LEARN THE KUIPER module (id 'descent'). Its code works with 400 kV and 132 kV. It responds to click, pointerenter and pointerleave events.
- Why it matters
- Loaded by the Modes page at https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050609/modes.html.
- Application
- kuiper-belt · learn-the-kuiper/202610050609/modules · script
- VEDIC
- SWITCH (GG2050-VEDIC-000033): See Through / Kuiper · Computer science / Interactive visualisation. view, user_flag → selected_view
- VEDIC
- SEARCH (GG2050-VEDIC-000030): See Through / Kuiper · Computer science / Interactive visualisation. query, substation_names → match_count_and_indices
- VEDIC
- CHOOSE (GG2050-VEDIC-000031): See Through / Kuiper · Computer science / Interactive visualisation. query, match_list → selection_or_refusal
- Uses
- GridAtlas — Atlas Page (estate URL), Overlay (estate URL)
- Used by
- loaded by Modes (script src), mentioned in Standalone (comment link)
- Produces
- loadScript, ensureGridData, merc, unmercLat, decode, arr, decodeLines, voltText, opText, nameOf, keyOfSub, bearingOf
- Defines here
- tower, stageOf, stageCaption, caption, attrib, readout, showCard, row, brow, link, hideCard, arrive, btn, lit, pick, open, holdBtn, stop, up, 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/descent.js:701-1035 · blob ddb8b021cc84ebde41b09748a4015396b5387c9e · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: agent_infra · users: ai_agent · canonical: unknown
// PYLONS: towers stand up along the arrow as it grows, conductors sag between them (an illustration, not a route)
// towers only on a published overhead circuit; a cable is drawn dashed; a distance arrow carries no towers at all
var gap = S.phone ? 54 : 70, nT = (sp.kind === 'published' && !A.cable) ? Math.min(40, Math.floor(len * p / gap)) : 0;
g.strokeStyle = colr; g.lineWidth = 1.2; g.globalAlpha = 0.85;
var hpx = S.phone ? 16 : 20;
for (var q = 1; q <= nT; q++) tower(g, x0 + ux * gap * q, y0 + uy * gap * q, hpx);
g.beginPath();
var px = x0, py = y0 - hpx * 0.9;
for (q = 1; q <= nT; q++) { var qx = x0 + ux * gap * q, qy = y0 + uy * gap * q - hpx * 0.9; g.moveTo(px, py); g.quadraticCurveTo((px + qx) / 2, (py + qy) / 2 + 7, qx, qy); px = qx; py = qy; }
g.stroke();
// the arrow itself, with an arrowhead where it has reached (spider look: ventus-grid-engine index.html spokes)
g.globalAlpha = 1; g.lineWidth = 2; if (sp.kind !== 'published' || A.cable) g.setLineDash(A.cable ? [10, 6] : [4, 6]);
g.beginPath(); g.moveTo(x0, y0); g.lineTo(ex, ey); g.stroke(); g.setLineDash([]);
g.fillStyle = colr; g.beginPath(); g.moveTo(ex, ey); g.lineTo(ex - ux * 14 - uy * 7, ey - uy * 14 + ux * 7); g.lineTo(ex - ux * 14 + uy * 7, ey - uy * 14 - ux * 7); g.closePath(); g.fill();
if (p > 0.95) {
// label at the far end if it is inside the porthole, otherwise where the arrow meets the rim
var lx = tx, ly = ty, rr = Math.sqrt((tx - cx) * (tx - cx) + (ty - cy) * (ty - cy));
if (rr > R - 40) { var bx = x0 - cx, by = y0 - cy, bb = bx * ux + by * uy, cc = bx * bx + by * by - (R - 50) * (R - 50), s = -bb + Math.sqrt(Math.max(0, bb * bb - cc)); lx = x0 + ux * s; ly = y0 + uy * s; }
g.font = 'bold 24px ' + FONT; g.textAlign = 'center'; g.textBaseline = 'middle';
var txt = A.label + (A.cable && A.corridor ? ' ROUTE EST ' + (+A.corridor).toFixed(1) + ' KM' : '');
g.lineWidth = 4; g.strokeStyle = 'rgba(0,0,0,0.85)'; g.strokeText(txt, lx, ly); g.fillStyle = colr; g.fillText(txt, lx, ly);
}
}
void mpp;
g.restore();
}
function tower(g, x, y, h) { // a lattice tower glyph, proportions from TOWER (400 kV class), base at (x, y)
var k = h / TOWER.H, bw = TOWER.base * k * 1.6, top = y - h;
g.beginPath();
g.moveTo(x - bw, y); g.lineTo(x - 1, top); g.lineTo(x + 1, top); g.lineTo(x + bw, y);
g.moveTo(x - bw, y); g.lineTo(x + bw * 0.45, y - h * 0.4); g.moveTo(x + bw, y); g.lineTo(x - bw * 0.45, y - h * 0.4);
for (var a = 0; a < 3; a++) { var zy = y - h * TOWER.armZ[a], al = TOWER.arm[a] * k * 0.9; g.moveTo(x - al, zy); g.lineTo(x + al, zy); }
g.stroke();
}
// ---------------- words on screen ----------------
var STAGES = ['THE KUIPER: A STAR FOR EVERY LINE OF CODE', 'THE STARS GATHER INTO THE GRID', 'ONE REGION', 'ONE SUBSTATION'];
function stageOf(D) { return D < 0.9 ? 0 : (D < 1.95 ? 1 : (D < 3.6 ? 2 : 3)); }
function stageCaption() {
var st = stageOf(S.D);
if (st !== S.stage) {
S.stage = st;
if (!S.flight || st === 3) caption(st === 3 && S.T >= 0 ? 'ONE SUBSTATION: ' + nameOf(S.T).toUpperCase() : STAGES[st]);
S.attDirty = true;
}
var mapShown = S.mapVis ? 1 : 0;
if (mapShown !== S.mapShownC) { S.mapShownC = mapShown; if (mapShown && !S.flight) caption(S.view === 'sat' ? 'THE REAL GROUND, FROM ABOVE' : 'THE REAL MAP'); S.attDirty = true; }
}
var SHORT = { 'SEE THROUGH THE UNIVERSE TO ONE SUBSTATION': 'SEE THROUGH TO ONE SUBSTATION', 'THE KUIPER: A STAR FOR EVERY LINE OF CODE': 'A STAR FOR EVERY LINE OF CODE' };
function caption(t) {
if (!S) return;
if (S.phone) { t = SHORT[t] || t; if (/^ONE SUBSTATION: /.test(t)) t = 'ONE SUBSTATION'; if (/^DOWN TO /.test(t)) t = 'DOWN TO THE SUBSTATION'; }
S.cap.textContent = t; S.cap.style.transition = 'none'; S.cap.style.opacity = '1';
clearTimeout(S.capT); S.capT = setTimeout(function () { if (S) { S.cap.style.transition = 'opacity 1.6s'; S.cap.style.opacity = '0.35'; } }, 3500);
}
function attrib() {
var t = [];
if (S.D > 1.5) t.push(ATTR_SUBS);
if (S.mapVis) { t.push(ATTR_MAP); if (S.view === 'sat') t.push(ATTR_SAT); }
S.att.textContent = t.join(S.phone ? ' · ' : '\n');
if (S.mapState === 'failed' && wantMap() && S.D > 1.5) { // one plain line, big enough to read
el('div', 'font:bold 24px/1.2 ' + FONT + ';color:rgba(255,176,0,0.9);margin-top:6px', S.mapWhy === 'webgl' ? 'THIS BROWSER CANNOT DRAW THE REAL MAP' : 'REAL MAP NEEDS THE INTERNET', S.att);
}
S.att.style.display = S.att.childNodes.length ? 'block' : 'none';
}
function readout(cam) {
var s;
if (S.D < 1) s = fmt(S.NP) + ' STARS KUIPER';
else { var lat = unmercLat(cam.y), mpp = 40075016.686 * Math.cos(lat * Math.PI / 180) / (S.D < 2 ? S.wsUK : cam.ws);
s = 'ZOOM ' + (S.D < 2 ? S.zUK : cam.z).toFixed(1) + ' 1 PX = ' + (mpp >= 1000 ? (mpp / 1000).toFixed(1) + ' KM' : (mpp >= 10 ? Math.round(mpp) : mpp.toFixed(1)) + ' M'); }
if (s !== S.roS) { S.roS = s; S.ro.textContent = s; }
}
function showCard() {
var i = S.T; if (i < 0) return;
var key = keyOfSub(i), p = window.KuiperLaw.place(key), lat = D0.lat[i], lon = D0.lon[i];
var c = S.card; c.innerHTML = '';
function row(t, col, bold) { return el('div', 'color:' + (col || '#fff') + ';' + (bold ? 'font-weight:bold;' : ''), t, c); }
var head = row(nameOf(i).toUpperCase(), C.amber, true);
head.style.cursor = 'pointer'; head.title = 'more or less';
var body = el('div', '', null, c);
function brow(t, col) { return el('div', 'color:' + (col || '#fff'), t, body); }
brow(voltText(i) + ', ' + opText(i), C.white);
brow(Math.abs(lat).toFixed(5) + (lat >= 0 ? 'N ' : 'S ') + Math.abs(lon).toFixed(5) + (lon >= 0 ? 'E' : 'W'), C.sky);
brow('STAR KEY ' + fmt(key), C.cyan);
brow('BEARING ' + bearingOf(p).toFixed(1) + '° RANGE ' + fmt(p.r), C.cyan);
if (S.spiderOn && S.spider) {
var sp = S.spider;
brow(sp.kind === 'published' ? 'PUBLISHED CIRCUITS, NESO ETYS 2025' : 'NEAREST BY DISTANCE, NOT CONNECTIONS', C.amber);
if (sp.caveat) brow(sp.caveat, 'rgba(255,255,255,0.6)');
for (var k = 0; k < sp.arrows.length && k < 8; k++) brow((sp.arrows[k].name || '').toUpperCase() + ' ' + sp.arrows[k].label, '#ddd');
if (sp.listed.length) brow('NO COORDINATES PUBLISHED: ' + sp.listed.slice(0, 12).join(', ').toUpperCase(), 'rgba(255,255,255,0.6)');
}
var links = el('div', 'margin-top:6px', null, body);
function link(t, href, why) {
var a = el('a', 'display:block;font:24px/1.35 ' + FONT + ';color:' + C.cyan + ';text-decoration:underline;text-underline-offset:4px;opacity:0.85', t + ' ↗', links);
a.href = href; a.target = '_blank'; a.rel = 'noopener'; a.title = why; return a;
}
link('OPEN IN GRIDATLAS', ATLAS_URL + '?latitude=' + lat.toFixed(5) + '&longitude=' + lon.toFixed(5) + '&zoom=15', 'GridAtlas reads latitude, longitude and zoom; it opens at this point with its own card');
link('FLY IT IN THE SIMULATOR', SIM_URL + '?lat=' + lat.toFixed(6) + '&lon=' + lon.toFixed(6), 'opens the simulator at this point');
brow('', 'rgba(255,255,255,0.45)');
// WHY: the exact rule and the sources (one tap, closed by default)
var why = el('div', 'margin-top:6px;color:' + C.cyan + ';cursor:pointer;text-decoration:underline;text-underline-offset:4px', S.whyOpen ? 'WHY -' : 'WHY +', body);
why.addEventListener('click', function () { S.whyOpen = !S.whyOpen; showCard(); });
if (S.whyOpen) {
var w = el('div', 'color:rgba(255,255,255,0.8);font-size:24px', null, body);
[
'A star is a line of code, not a substation. The stars gather into the grid as a picture; the Kuiper does not address substations.',
'STAR KEY = floor((j + 0.5) x ' + fmt(S.SPACE) + ' / 20,000) for substation j of the public file, the same rule as DRAW THE GRID. Its place is KuiperLaw.place(key): angle = (key x 2654435769 mod 2^32) / 2^32 turns, RANGE r = sqrt(key + 0.5). BEARING = 90 - angle in degrees, clockwise from up.',
'Name, voltage, operator and position: OpenStreetMap (ODbL), as published at globalgrid2050.com/grid_substations.geojson. Map: CARTO dark matter. Satellite: Esri World Imagery. Both are the sources GridAtlas uses.',
'Every layer uses one Web Mercator mapping (512 x 2^zoom pixels round the world), so the marker and the map agree to the pixel.'
].forEach(function (t) { el('div', 'margin-top:6px', t, w); });
}
var collapsed = S.phone && !S.cardOpen;
body.style.display = collapsed ? 'none' : 'block';
head.textContent = nameOf(i).toUpperCase() + (S.phone ? (collapsed ? ' +' : ' -') : '');
head.addEventListener('click', function () { S.cardOpen = !S.cardOpen; showCard(); });
c.style.display = 'block'; S.cardOn = true;
}
function hideCard() { if (S) { S.card.style.display = 'none'; S.cardOn = false; S.cardDirty = S.T >= 0; } }
function arrive() { // like the Pipeline News MAP arrival in GridAtlas: on the point, then the card, then the lines
S.cardDirty = true; S.mN = 0; S.mTotal = 0; ping(12, 0.04); ping(19, 0.025);
caption('ONE SUBSTATION: ' + nameOf(S.T).toUpperCase());
}
// ---------------- input ----------------
function btn(label, parent, fn, title) {
var b = el('button', 'pointer-events:auto;font:bold 24px ' + FONT + ';color:' + C.cyan + ';background:transparent;border:1px solid rgba(0,255,255,0.5);border-radius:8px;opacity:0.6;cursor:pointer;white-space:nowrap;letter-spacing:0.5px;transition:opacity .2s,background .2s;touch-action:manipulation', label, parent);
b.type = 'button'; if (title) b.setAttribute('aria-label', title);
b.addEventListener('pointerenter', function () { b.style.opacity = '1'; });
b.addEventListener('pointerleave', function () { if (!b.dataset.on) b.style.opacity = '0.6'; });
if (fn) b.addEventListener('click', function (e) { e.stopPropagation(); audio(); fn(); });
S.allBtns.push(b);
return b;
}
function lit(b, onv) { if (onv) { b.dataset.on = '1'; b.style.background = 'rgba(0,255,255,0.14)'; b.style.opacity = '1'; } else { delete b.dataset.on; b.style.background = 'transparent'; b.style.opacity = '0.6'; } }
function pick(px, py) {
var n = S.D < 2 ? S.NP : NSUB, best = -1, bd = (S.phone ? 34 : 28), bd2 = bd * bd, sx = S.sx, sy = S.sy;
for (var i = 0; i < n; i++) { var dx = sx[i] - px, dy = sy[i] - py, d = dx * dx + dy * dy; if (d < bd2) { bd2 = d; best = i; } }
if (best < 0) return false;
var sub = S.pSub[best];
if (S.D < 2) { flyTo(sub); S.flight.phase = 'down'; setTarget(sub, false); S.Dgoal = DMAX; caption('DOWN TO ' + nameOf(sub).toUpperCase()); }
else { setTarget(sub, true); S.Dgoal = Math.max(S.Dgoal, Math.min(DMAX, S.D + 1.5)); ping(5, 0.03); caption(nameOf(sub).toUpperCase()); }
return true;
}
function open(host) {
if (S) close();
if (!SUB || !window.KuiperLaw) { host.textContent = 'descent.js: data or KuiperLaw missing'; return; }
S = { host: host, listeners: [], allBtns: [], D: 0, Dgoal: 0, speed: 2.4, hold: 0, T: -1, corrA: 0, corrX: 0, corrY: 0, cam: { x: 0, y: 0, z: 0, ws: 1 },
view: 'map', viewTouched: false, mapState: 'none', mapVis: false, mapA: -1, camKey: '', subs: true, grid: false, spiderOn: false, hops: 1,
scan: true, sw: Math.PI / 2, muted: false, stage: -1, roT: 0, roS: '', mIdx: new Int32Array(200), mN: 0, mTotal: 0, q: '',
ft: new Float32Array(120), fi: 0, fiv: new Float32Array(240), fj: 0, lite: false, cardOn: false, cardDirty: false, cardOpen: false, mapShownC: 0, pointers: {} };
S.SPACE = window.KuiperLaw.constants.SPACE;
host.style.position = host.style.position || 'fixed'; host.style.overflow = 'hidden'; host.style.background = '#000';
S.mapEl = el('div', 'position:absolute;inset:0;visibility:hidden;opacity:0;pointer-events:none;background:#000', null, host);
var cv = el('canvas', 'position:absolute;left:0;top:0;touch-action:none;display:block', null, host);
cv.setAttribute('aria-label', 'See through the universe to one substation');
S.cv = cv; S.ctx = cv.getContext('2d');
var ui = el('div', 'position:absolute;inset:0;pointer-events:none;font:24px ' + FONT + ';color:#fff', null, host); S.ui = ui;
var pad = 'env(safe-area-inset-top)';
S.cap = el('div', 'position:absolute;left:16px;top:calc(16px + ' + pad + ');font:bold 26px/1.15 ' + FONT + ';color:#fff;max-height:62px;overflow:hidden', '', ui);
S.ro = el('div', 'position:absolute;left:16px;font:24px ' + FONT + ';color:rgba(0,255,255,0.7);white-space:nowrap', '', ui);
S.att = el('div', 'position:absolute;font:16px/1.3 ' + FONT + ';color:rgba(160,210,255,0.85);display:none;text-shadow:0 0 3px #000;white-space:pre-line', '', ui);
S.card = el('div', 'position:absolute;background:rgba(0,0,0,0.8);border:1px solid rgba(255,176,0,0.55);border-radius:10px;padding:8px 12px;font:24px/1.3 ' + FONT + ';display:none;pointer-events:auto;overflow:auto;box-sizing:border-box', '', ui);
S.card.addEventListener('pointerdown', function (e) { e.stopPropagation(); });
// the search box: GridAtlas position and style (dark box, cyan outline GO)
S.search = el('div', 'position:absolute;display:flex;gap:8px;pointer-events:auto', null, ui);
S.input = el('input', 'flex:1;min-width:0;box-sizing:border-box;background:rgba(0,0,0,0.85);color:#fff;border:1px solid rgba(0,255,255,0.35);border-radius:6px;padding:0 12px;font:24px ' + FONT + ';outline:none', null, S.search);
S.input.type = 'text'; S.input.placeholder = 'Substation name'; S.input.maxLength = 80; S.input.autocomplete = 'off'; S.input.spellcheck = false;
S.input.setAttribute('aria-label', 'Substation name');
S.input.addEventListener('input', function () { audio(); doSearch(); });
S.input.addEventListener('keydown', function (e) {
if (e.key === 'Enter') { e.preventDefault(); goSearch(); }
else if (e.key === 'Escape') { e.preventDefault(); S.input.blur(); }
e.stopPropagation();
});
S.input.addEventListener('focus', function () { S.input.style.borderColor = 'rgba(0,255,255,0.8)'; });
S.input.addEventListener('blur', function () { S.input.style.borderColor = 'rgba(0,255,255,0.35)'; });
S.goB = btn('GO', S.search, goSearch, 'go to this substation');
S.goB.style.cssText += ';border-color:rgba(0,255,255,0.8);opacity:0.85';
S.note = el('div', 'position:absolute;font:24px/1.2 ' + FONT + ';color:rgba(255,176,0,0.9);text-shadow:0 0 4px #000', '', ui);
// top right: X and mute
S.xbtn = btn('X', ui, function () { M.close(); }, 'close');
S.xbtn.style.cssText += ';position:absolute;right:calc(8px + env(safe-area-inset-right));top:calc(8px + ' + pad + ');font-size:34px;padding:0;opacity:0.7';
S.mute = btn('♪', ui, function () { S.muted = !S.muted; S.mute.textContent = S.muted ? '♪ OFF' : '♪'; if (S.og) S.og.gain.value = 0; }, 'mute');
S.mute.style.position = 'absolute';
// bottom-left: GRID SUBS SPIDER, lit when on (GridAtlas mobile chips)
S.grpBL = el('div', 'position:absolute;display:flex;gap:6px;pointer-events:none', null, ui);
S.gridB = btn('GRID', S.grpBL, function () { S.grid = !S.grid; lit(S.gridB, S.grid); if (S.map && S.mapState === 'ready') GA_LINES.forEach(function (L) { try { S.map.setLayoutProperty('ga' + L[0], 'visibility', S.grid ? 'visible' : 'none'); } catch (e) {} }); caption(S.grid ? '400 kV AND 132 kV LINES, OPENSTREETMAP' : 'LINES OFF'); S.attDirty = true; }, 'grid lines');
S.subsB = btn('SUBS', S.grpBL, function () { S.subs = !S.subs; lit(S.subsB, S.subs); caption(S.subs ? 'EVERY SUBSTATION' : 'SUBSTATIONS OFF'); }, 'substations');
S.spB = btn('SPIDER', S.grpBL, function () { S.spiderOn = !S.spiderOn; lit(S.spB, S.spiderOn); S.spider = null; S.spiderT0 = performance.now(); if (!S.spiderOn) caption('SPIDER OFF'); else if (S.T < 0 || S.D < 2.4) caption('CHOOSE A SUBSTATION FIRST'); S.cardDirty = true; }, 'spider arrows');
lit(S.subsB, true);
// view switch
S.grpView = el('div', 'position:absolute;display:flex;gap:6px;pointer-events:none', null, ui);
S.viewBtns = [['kuiper', 'KUIPER'], ['map', 'MAP'], ['sat', 'SATELLITE']].map(function (v) {
var b = btn(v[1], S.grpView, function () { setView(v[0], true); }, v[1].toLowerCase() + ' view'); b.dataset.v = v[0]; return b;
});
S.satB = S.viewBtns[2]; lit(S.viewBtns[1], true);
// DESCEND / ASCEND: hold to keep moving, tap for one step
S.grpUD = el('div', 'position:absolute;display:flex;gap:6px;pointer-events:none', null, ui);
function holdBtn(label, dir, title) {
var b = btn(label, S.grpUD, null, title), t0 = 0;
b.addEventListener('pointerdown', function (e) { e.stopPropagation(); audio(); S.flight = null; S.hold = dir; t0 = performance.now(); try { b.setPointerCapture(e.pointerId); } catch (x) {} });
var stop = function () { if (S && S.hold === dir) { S.hold = 0; if (performance.now() - t0 < 220) S.Dgoal = clamp(S.Dgoal + dir * 0.6, 0, DMAX); } };
b.addEventListener('pointerup', stop); b.addEventListener('pointercancel', stop); b.addEventListener('lostpointercapture', stop);
b.addEventListener('keydown', function (e) { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); S.Dgoal = clamp(S.Dgoal + dir * 0.6, 0, DMAX); } });
return b;
}
S.upB = holdBtn('▲', -1, 'ascend'); S.dnB = holdBtn('▼', 1, 'descend');
S.upB.dataset.cmd = 'ascend'; S.dnB.dataset.cmd = 'descend';
// particles: the DRAW THE GRID keys; particle j < 5800 lands on substation j, the rest gather around substations
// Desktop: all 20,000 DRAW THE GRID keys, particle p carries key index p. Phone: the first 5,800 the same, then every
// second key of the rest (12,900 stars). Particle p goes to substation p mod 5,800, so substation j always gets the star
// with key index j: its STAR KEY is grid.js keyOf(j) on every device.
var L = window.KuiperLaw, phoneNow = Math.min(host.clientWidth || innerWidth, host.clientHeight || innerHeight) < 600;
var n = phoneNow ? NSUB + Math.ceil((NRULE - NSUB) / 2) : NRULE; S.NP = n;
S.kx = new Float32Array(n); S.ky = new Float32Array(n); S.delay = new Float32Array(n); S.pSub = new Int32Array(n);
S.ox = new Float32Array(n); S.oy = new Float32Array(n); S.sx = new Float32Array(n); S.sy = new Float32Array(n);
S.subKey = new Float64Array(NSUB);
S.starCv = document.createElement('canvas'); S.starCtx = S.starCv.getContext('2d'); S.starKey = ''; S.layoutN = 0;
S.bCnt = new Int32Array(360); S.bStart = new Int32Array(361); S.bItem = new Int32Array(n); S.bOf = new Int16Array(n); S.bucketsOK = false;
var Rw = Math.sqrt(S.SPACE + 0.5);
for (var p = 0; p < n; p++) {
var ki = (phoneNow && p >= NSUB) ? NSUB + 2 * (p - NSUB) : p, key = Math.floor((ki + 0.5) * S.SPACE / NRULE), pl = L.place(key);
S.kx[p] = pl.x; S.ky[p] = pl.y; S.delay[p] = 0.3 * pl.r / Rw;
var c = Math.floor(p / NSUB); S.pSub[p] = p % NSUB; if (c === 0) S.subKey[p] = key;
var th = c * GA, rr = 2.2 * Math.sqrt(c); S.ox[p] = rr * Math.cos(th); S.oy[p] = rr * Math.sin(th);
}
// canvas input: tap picks, wheel and pinch descend, a drag grabs the sweep arm
on(cv, 'pointerdown', function (e) {
audio(); S.pointers[e.pointerId] = { x: e.clientX, y: e.clientY, x0: e.clientX, y0: e.clientY };
var ids = Object.keys(S.pointers);
if (ids.length === 2) { var a = S.pointers[ids[0]], b = S.pointers[ids[1]]; S.pinch = Math.hypot(a.x - b.x, a.y - b.y) || 1; S.flight = null; }
try { cv.setPointerCapture(e.pointerId); } catch (x) {}
});
on(cv, 'pointermove', function (e) {
var pp = S.pointers[e.pointerId]; if (!pp) return; pp.x = e.clientX; pp.y = e.clientY;
var ids = Object.keys(S.pointers);
if (ids.length === 2 && S.pinch) {
var a = S.pointers[ids[0]], b = S.pointers[ids[1]], d = Math.hypot(a.x - b.x, a.y - b.y) || 1;
S.Dgoal = clamp(S.Dgoal + Math.log(d / S.pinch) / Math.LN2 * 0.9, 0, DMAX); S.pinch = d;
} else if (ids.length === 1 && Math.hypot(pp.x - pp.x0, pp.y - pp.y0) > 12) {
var r = cv.getBoundingClientRect(); S.grab = true; S.sw = -Math.atan2(pp.y - r.top - S.cy, pp.x - r.left - S.cx);
}
});
function up(e) {
var pp = S.pointers[e.pointerId]; delete S.pointers[e.pointerId];
if (Object.keys(S.pointers).length < 2) S.pinch = 0;
if (!pp) return;
if (!S.grab && Math.hypot(pp.x - pp.x0, pp.y - pp.y0) < 12 && e.type === 'pointerup') {
var r = cv.getBoundingClientRect(); pick(e.clientX - r.left, e.clientY - r.top);
}
if (!Object.keys(S.pointers).length) { if (S.grab) { S.sw = (S.sw + 2 * Math.PI) % (2 * Math.PI); } S.grab = false; }
}
on(cv, 'pointerup', up); on(cv, 'pointercancel', up);
on(cv, 'wheel', function (e) {
e.preventDefault(); audio(); S.flight = null;
var dy = +e.deltaY || 0; if (e.deltaMode === 1) dy *= 30; else if (e.deltaMode === 2) dy *= 600;
if (!isFinite(dy)) return;
S.Dgoal = clamp(S.Dgoal + clamp(dy * 0.0025, -0.8, 0.8), 0, DMAX);
}, { passive: false });
on(window, 'keydown', function (e) {
var tg = e.target && e.target.tagName;
if (e.key === 'Escape') {
if (tg === 'INPUT' || tg === 'TEXTAREA') { e.target.blur(); return; }
M.close(); return;
}
if (tg === 'INPUT' || tg === 'TEXTAREA') return;
var k = e.key;
if (k === 'ArrowDown' || k === 'PageDown' || k === '+' || k === '=') { e.preventDefault(); audio(); S.flight = null; S.Dgoal = clamp(S.Dgoal + 0.5, 0, DMAX); }
else if (k === 'ArrowUp' || k === 'PageUp' || k === '-' || k === '_') { e.preventDefault(); audio(); S.flight = null; S.Dgoal = clamp(S.Dgoal - 0.5, 0, DMAX); }
else if (k === 'Home') { S.flight = null; S.Dgoal = 0; }
else if (k === 'End') { S.flight = null; S.Dgoal = DMAX; }
else if (k === '1') setView('kuiper', true); else if (k === '2') setView('map', true); else if (k === '3') setView('sat', true);
else if (k === '/' ) { e.preventDefault(); S.input.focus(); }
});
on(window, 'resize', function () { if (S) layout(); });
on(window, 'orientationchange', function () { setTimeout(function () { if (S) layout(); }, 200); });
on(document, 'visibilitychange', function () {
if (!S) return;
if (document.hidden) { cancelAnimationFrame(S.raf); S.raf = 0; if (S.og) S.og.gain.value = 0; }
else if (!S.raf) { S.last = 0; S.raf = requestAnimationFrame(frame); }
});
decode();
layout();
caption('SEE THROUGH THE UNIVERSE TO ONE SUBSTATION');
S.stage = 0;
S.raf = requestAnimationFrame(frame);
// fetch the map library while the player is still among the stars, so its first parse does not stall the fall
S.preT = setTimeout(function () { if (S && wantMap()) loadMap(); }, 1500);
window.__descent = {
state: function () { return S && { D: S.D, Dgoal: S.Dgoal, T: S.T, name: S.T >= 0 ? nameOf(S.T) : '', view: S.view, mapState: S.mapState, mapVis: S.mapVis,
tileOK: S.tileOK || 0, tileErr: S.tileErr || 0, z: S.cam.z, W: S.W, H: S.H, Rpx: S.Rpx, NP: S.NP, cap: S.cap.textContent, note: S.note.textContent,
mN: S.mN, mTotal: S.mTotal, card: S.cardOn ? S.card.textContent : '', att: S.att.textContent, flight: S.flight && S.flight.phase,
spider: S.spider && { kind: S.spider.kind, n: S.spider.arrows.length, labels: S.spider.arrows.map(function (a) { return a.name + ' ' + a.label; }) }, lite: S.lite, grid: S.grid, subs: S.subs }; },
frameTimes: function () { return Array.prototype.slice.call(S.ft); },
frameIntervals: function () { return Array.prototype.slice.call(S.fiv, 0, Math.min(S.fj, S.fiv.length)); },
setD: function (d) { S.flight = null; S.Dgoal = clamp(+d || 0, 0, DMAX); },
jumpD: function (d) { S.flight = null; S.D = S.Dgoal = clamp(+d || 0, 0, DMAX); },
target: function (i) { setTarget(i, false); },
fly: function (i) { flyTo(i); },
find: function (name) { var q = String(name).toLowerCase(); for (var i = 0; i < D0.n; i++) if (D0.low[i] === q) return i; return -1; },
sub: function (i) { return { name: D0.names[i], lat: D0.lat[i], lon: D0.lon[i], volt: voltText(i), op: opText(i) }; },
screenOf: function (i) { return [S.sx[i], S.sy[i]]; },
mapPointOf: function (i) { if (!S.map) return null; var p = S.map.project([D0.lon[i], D0.lat[i]]); return [p.x, p.y]; },
mapReady: function () { return !!(S.map && S.mapState === 'ready' && S.map.loaded() && S.map.areTilesLoaded()); }
};
ensureGridData(function () {
if (!S) return;
var names = window.KGGridData && window.KGGridData.substations && window.KGGridData.substations.names;
if (names) for (var q = 0; q < D0.n; q++) { D0.names[q] = names[q] || ''; D0.low[q] = D0.names[q].toLowerCase(); }
else caption('grid-data.js did not load: names and lines are missing');
});
}
function close() {
if (!S) return;
cancelAnimationFrame(S.raf); clearTimeout(S.capT); clearTimeout(S.libTimer); clearTimeout(S.preT);
S.listeners.forEach(function (l) { l[0].removeEventListener(l[1], l[2], l[3]); });
if (S.map) { try { S.map.remove(); } catch (e) {} }
if (S.ac) { try { S.osc.stop(); S.ac.close(); } catch (e) {} }
var h = S.host; S = null;
while (h.firstChild) h.removeChild(h.firstChild);
window.__descent = null;
}
var M = { id: 'descent', label: 'SEE THROUGH', sentence: 'See through the universe to one substation', open: open, close: close };
(window.KGModules = window.KGModules || []).push(M);
})();Grid
A JavaScript file in the learn the kuiper folder of Kuiper Belt that converts to scr (`toScr`), makes stars (`makeStars`), draws sel (`drawSel`) and calculates planar distances.
renderkuiper-belt / learn-the-kuiper/202610050609/modules/grid.js · lines 1–365 of 437 · version 2026-10-05 06:09 · Entry point · pattern flightMusic (shared by 2 files)
- What it does
- It draws substations, 400kV and 132kV. Defines 37 functions or classes, including ensureData, keyOf, decode, networkTargets, audio. 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: substations, 400kV, 132kV.
- Inputs & outputs
- Out: canvas drawing. Voltage levels named: 400kV, 132kV.
- Downstream impact
- Used directly by 2 files: Grid Test (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610042346/modules/grid-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 makes stars (`makeStars`), draws sel (`drawSel`) and closes pop (`closePop`). The wafer at rest (every place from KuiperLaw.place), then the same particles fly onto the UK grid and back. Its code works with 132 kV and 400 kV. 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 Grid Test.
- Application
- kuiper-belt · learn-the-kuiper/202610050609/modules · script
- Uses
- none found
- Used by
- loaded by Grid Test (script src), loaded by Modes (script src)
- Produces
- ensureData, keyOf, decode, networkTargets, audio, note, flightMusic, cam, toScr, bearingOf, el, layout
- Defines here
- ensureData, keyOf, decode, networkTargets, audio, note, flightMusic, cam, toScr, bearingOf, el, layout, makeStars, rnd, render, compass, drawSel, blendTo, draw, release, fadeControls, caption, attrib, readout, btn, popup, closePop, drawMenu, whyMenu, h
- 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/grid.js:1-365 · blob cf6d88a96c2cf6f32ed438a1d64409201f8bd417 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: agent_infra · users: ai_agent · canonical: unknown
// grid.js DRAW THE GRID, a LEARN THE KUIPER module.
// The wafer at rest (every place from KuiperLaw.place), then the same particles fly onto the UK grid and back.
// Reused from the public page globalgrid2050 testcode/wafer-development-environment/202609180245-real-systems:
// pilot.mjs networkTargets() the rule that lays particles along edges by length and clusters them at stations
// on the angle GA (adapted: edge networks put every particle on edges).
// app.mjs blendTo() drawn = from + (target - from) * ease(u), cubic in-out ease, one target per particle.
// app.mjs release() every particle back to its own law place exactly.
// pilot.mjs NETWORKS + the "Draw every substation / 400 kV / 132 kV / British Isles / Release" sentences.
// Data: grid-data.js (window.KGGridData), built from the same folder's *-network.json files, attribution kept.
(function () {
'use strict';
var SCRIPT_SRC = (document.currentScript && document.currentScript.src) || '';
var C = { bg: '#000', cyan: '#00ffff', sky: '#66ccff', amber: '#ffb000', green: '#22ee77', white: '#ffffff' };
var FONT = '"Segoe UI", Arial, sans-serif';
var N = 20000; // particles shown
var MOVE_MS = 2600; // app.mjs MOVE_MS is 2000; a little slower so the eye can follow
var GA = 2.399963229728653; // 2 pi (1 - 0.6180339887) radians, as pilot.mjs networkTargets uses for station clusters
var ORDER = ['substations', 'grid400', 'grid132', 'uk'];
var SENT = {
substations: 'DRAW EVERY SUBSTATION', grid400: 'DRAW THE 400 kV GRID', grid132: 'DRAW THE 132 kV NETWORK',
uk: 'DRAW THE BRITISH ISLES', release: 'RELEASE: EVERY PARTICLE BACK TO ITS OWN PLACE'
};
var S = null; // module state while open
function ensureData(cb) {
if (window.KGGridData) return cb();
var s = document.createElement('script');
s.src = SCRIPT_SRC ? SCRIPT_SRC.replace(/grid\.js(\?.*)?$/, 'grid-data.js') : 'modules/grid-data.js';
s.onload = function () { cb(); };
s.onerror = function () { cb(); };
document.head.appendChild(s);
}
// ---- the key rule (stated in WHY) ----
// particle i carries key K_i = floor((i + 0.5) * SPACE / N): N keys spread evenly over SPACE (issued and unissued addresses).
// Node j of a network takes the key of particle j (file order); a particle's place at rest is KuiperLaw.place(K_i).
function keyOf(i, SPACE) { return Math.floor((i + 0.5) * SPACE / N); }
function decode(net) {
if (net._st) return net;
var n = net.n, st = new Float32Array(2 * n), xy = net.xy, i;
for (i = 0; i < n; i++) { st[2 * i] = xy[2 * i] / 10000; st[2 * i + 1] = xy[2 * i + 1] / 10000; }
var e = net.e, m = e.length / 2, E = new Int32Array(2 * m), a = 0;
for (i = 0; i < m; i++) { a += e[2 * i]; E[2 * i] = a; E[2 * i + 1] = a + e[2 * i + 1]; }
net._st = st; net._E = E; net._m = m;
return net;
}
// pilot.mjs networkTargets(N, m), adapted. Writes world targets (scale Sc) and the node each particle belongs to.
function networkTargets(net, Sc) {
decode(net);
var st = net._st, E = net._E, mE = net._m, n = net.n;
var t = new Float32Array(2 * N), node = new Int32Array(N), j = 0, e, i;
if (mE > 0) {
var lens = new Float64Array(mE), L = 0;
for (e = 0; e < mE; e++) { var a = E[2 * e], b = E[2 * e + 1]; lens[e] = Math.hypot(st[2 * b] - st[2 * a], st[2 * b + 1] - st[2 * a + 1]); L += lens[e]; }
L = L || 1;
// largest-remainder share so the counts add to exactly N (pilot.mjs rounds and lets the station clusters fill the rest)
var share = new Int32Array(mE), rem = [], used = 0;
for (e = 0; e < mE; e++) { var q = N * lens[e] / L; share[e] = Math.floor(q); used += share[e]; rem.push([q - share[e], e]); }
rem.sort(function (p, r) { return r[0] - p[0]; });
for (i = 0; used < N && i < rem.length; i++, used++) share[rem[i][1]]++;
for (e = 0; e < mE && j < N; e++) {
var a2 = E[2 * e], b2 = E[2 * e + 1], k = share[e];
for (i = 0; i < k && j < N; i++, j++) {
var u = (i + 0.5) / k;
t[2 * j] = Sc * (st[2 * a2] + (st[2 * b2] - st[2 * a2]) * u);
t[2 * j + 1] = Sc * (st[2 * a2 + 1] + (st[2 * b2 + 1] - st[2 * a2 + 1]) * u);
node[j] = u < 0.5 ? a2 : b2;
}
}
}
for (var s = 0; j < N; s++, j++) { // pilot.mjs: station q = s mod n, ring c, GA-angle cluster
var q2 = s % n, c = Math.floor(s / n), th = c * GA, r = 0.004 * Sc * Math.sqrt(c);
t[2 * j] = Sc * st[2 * q2] + r * Math.cos(th); t[2 * j + 1] = Sc * st[2 * q2 + 1] + r * Math.sin(th);
node[j] = q2;
}
return { t: t, node: node };
}
// ---- sound: soft WebAudio after the first gesture ----
var PENTA = [0, 2, 4, 7, 9, 12, 14, 16, 19, 21];
function audio() {
if (!S || S.muted) return null;
if (!S.ac) { try { S.ac = new (window.AudioContext || window.webkitAudioContext)(); } catch (e) { return null; } }
if (S.ac.state === 'suspended') S.ac.resume();
return S.ac;
}
function note(semi, when, dur, gain, type) {
var ac = audio(); if (!ac) return;
var t0 = ac.currentTime + (when || 0), o = ac.createOscillator(), g = ac.createGain();
o.type = type || 'sine'; o.frequency.value = 220 * Math.pow(2, semi / 12);
g.gain.setValueAtTime(0, t0); g.gain.linearRampToValueAtTime(gain || 0.05, t0 + 0.04);
g.gain.exponentialRampToValueAtTime(0.0001, t0 + (dur || 0.6));
o.connect(g); g.connect(ac.destination); o.start(t0); o.stop(t0 + (dur || 0.6) + 0.05);
}
function flightMusic(up) {
for (var i = 0; i < 10; i++) note(PENTA[up ? i : 9 - i] + 12, i * 0.22, 0.9, 0.035, 'triangle');
[0, 7, 16].forEach(function (s, k) { note(s + (up ? 12 : 0), 2.5 + k * 0.03, 2.2, 0.03, 'sine'); });
}
// ---- geometry helpers ----
function cam() { return { cx: 0, cy: 0, zoom: S.zoom }; }
function toScr(x, y) { return [S.W / 2 + x * S.zoom, S.H / 2 - y * S.zoom]; } // KuiperLaw.toScreen with cam (0,0): y UP
function bearingOf(p) { var b = (90 - p.deg) % 360; return b < 0 ? b + 360 : b; } // clockwise from up on screen
function el(tag, css, text, parent) {
var d = document.createElement(tag); if (css) d.style.cssText = css; if (text != null) d.textContent = text;
if (parent) parent.appendChild(d); return d;
}
function layout() {
var host = S.host, dpr = Math.max(1, window.devicePixelRatio || 1);
var W = host.clientWidth || window.innerWidth, H = host.clientHeight || window.innerHeight;
S.W = W; S.H = H; S.dpr = dpr; S.phone = Math.min(W, H) < 600;
S.cv.width = Math.round(W * dpr); S.cv.height = Math.round(H * dpr);
S.cv.style.width = W + 'px'; S.cv.style.height = H + 'px';
S.Rpx = Math.min(W, H) / 2 * (S.phone ? 0.94 : 0.88); // the wafer edge on screen, a true circle
S.zoom = S.Rpx / S.Rw;
var bh = S.phone ? 56 : 72, side = (W - 2 * S.Rpx) / 2 - 24;
var landPhone = S.phone && W > H;
S.att.style.maxWidth = (landPhone ? Math.max(200, side) : W - 110) + 'px';
S.att.style.bottom = landPhone ? 'calc(80px + env(safe-area-inset-bottom))' : 'calc(' + (bh + 16) + 'px + env(safe-area-inset-bottom))';
S.card.style.maxWidth = (landPhone ? Math.max(220, side) : Math.min(560, W - 32)) + 'px';
S.selRO.style.display = S.phone ? 'none' : 'block';
S.btns.forEach(function (b) { b.style.height = bh + 'px'; b.style.minWidth = bh + 'px'; b.style.padding = S.phone ? '0 9px' : '0 20px'; });
S.xbtn.style.width = S.xbtn.style.height = '72px';
makeStars();
S.dirty = true;
}
function makeStars() {
var n = Math.round(S.W * S.H / 2600), a = [], seed = 12345;
function rnd() { seed = (seed * 1664525 + 1013904223) >>> 0; return seed / 4294967296; }
for (var i = 0; i < n; i++) a.push([rnd() * S.W, rnd() * S.H, rnd()]);
S.stars = a;
}
// ---- drawing ----
function render() {
var g = S.ctx, dpr = S.dpr, W = S.W, H = S.H, cx = W / 2, cy = H / 2, R = S.Rpx, i;
g.setTransform(dpr, 0, 0, dpr, 0, 0);
g.globalCompositeOperation = 'source-over';
g.fillStyle = C.bg; g.fillRect(0, 0, W, H);
// stars: far dimmer than the dots
for (i = 0; i < S.stars.length; i++) { var s = S.stars[i]; g.fillStyle = 'rgba(160,190,255,' + (0.08 + 0.18 * s[2]).toFixed(3) + ')'; g.fillRect(s[0], s[1], 1, 1); }
// instruments: range rings, ticks, compass rose
g.lineWidth = 1; g.strokeStyle = 'rgba(0,255,255,0.16)';
for (i = 1; i <= 4; i++) { g.beginPath(); g.arc(cx, cy, R * i / 4, 0, 2 * Math.PI); g.stroke(); }
for (i = 0; i < 360; i += 5) {
var a = (i - 90) * Math.PI / 180, l = i % 30 === 0 ? 14 : (i % 10 === 0 ? 8 : 4);
g.strokeStyle = i % 30 === 0 ? 'rgba(0,255,255,0.45)' : 'rgba(0,255,255,0.22)';
g.beginPath(); g.moveTo(cx + Math.cos(a) * (R + 3), cy + Math.sin(a) * (R + 3)); g.lineTo(cx + Math.cos(a) * (R + 3 + l), cy + Math.sin(a) * (R + 3 + l)); g.stroke();
}
g.font = '24px ' + FONT; g.fillStyle = 'rgba(102,204,255,0.55)'; g.textAlign = 'center'; g.textBaseline = 'middle';
if (!S.phone) {
[[0, '000'], [90, '090'], [270, '270']].forEach(function (p) {
var a2 = (p[0] - 90) * Math.PI / 180, rr = R + 36; g.fillText(p[1], cx + Math.cos(a2) * rr, cy + Math.sin(a2) * rr);
});
}
if (S.phone && W > H) compass(g, W - 44, 130, 20); else compass(g, S.phone ? 40 : 58, H - (S.phone ? 56 : 72) - (S.phone ? 50 : 70), S.phone ? 20 : 28);
// the dots: brightest thing on screen
var P = S.pos, z = S.zoom, sz = S.phone ? 1.7 : 2;
g.globalCompositeOperation = 'lighter';
// star look (as zoom.js): a faint cyan halo pass, then a white-cyan core
var hz = sz * 3.2; g.fillStyle = 'rgba(0,255,255,0.10)'; g.beginPath();
for (i = 0; i < N; i++) { var hx = cx + P[2 * i] * z, hy = cy - P[2 * i + 1] * z; g.rect(hx - hz / 2, hy - hz / 2, hz, hz); }
g.fill();
g.fillStyle = 'rgba(220,255,255,0.95)';
g.beginPath();
for (i = 0; i < N; i++) { var x = cx + P[2 * i] * z, y = cy - P[2 * i + 1] * z; g.rect(x - sz / 2, y - sz / 2, sz, sz); }
g.fill();
g.globalCompositeOperation = 'source-over';
// the selection: amber, with an engineering annotation from the wafer centre to the key's home place
if (S.sel) drawSel(g, cx, cy);
}
function compass(g, x, y, r) {
g.save(); g.strokeStyle = 'rgba(0,255,255,0.45)'; g.lineWidth = 1;
g.beginPath(); g.arc(x, y, r, 0, 2 * Math.PI); g.stroke();
g.beginPath(); g.moveTo(x, y - r - 6); g.lineTo(x + 6, y); g.lineTo(x, y + r + 6); g.lineTo(x - 6, y); g.closePath(); g.stroke();
g.fillStyle = 'rgba(0,255,255,0.7)'; g.beginPath(); g.moveTo(x, y - r - 6); g.lineTo(x + 6, y); g.lineTo(x - 6, y); g.closePath(); g.fill();
g.font = 'bold 24px ' + FONT; g.textAlign = 'center'; g.textBaseline = 'bottom'; g.fillText('N', x, y - r - 8);
g.restore();
}
function drawSel(g, cx, cy) {
var sel = S.sel, h = toScr(sel.home.x, sel.home.y), p = toScr(S.pos[2 * sel.i], S.pos[2 * sel.i + 1]);
g.save();
g.strokeStyle = 'rgba(255,176,0,0.55)'; g.lineWidth = 1; g.setLineDash([6, 5]);
g.beginPath(); g.moveTo(cx, cy); g.lineTo(h[0], h[1]); g.stroke(); // range line on the wafer
var a0 = -Math.PI / 2, a1 = -sel.home.theta, rr = Math.min(60, Math.hypot(h[0] - cx, h[1] - cy) * 0.5);
// bearing arc, clockwise from up to the home place
var b = bearingOf(sel.home) * Math.PI / 180;
g.beginPath(); g.arc(cx, cy, rr, a0, a0 + b, false); g.stroke();
if (Math.hypot(p[0] - h[0], p[1] - h[1]) > 4) { g.beginPath(); g.moveTo(h[0], h[1]); g.lineTo(p[0], p[1]); g.stroke(); }
g.setLineDash([]);
g.strokeStyle = C.amber; g.lineWidth = 2;
g.beginPath(); g.arc(p[0], p[1], 11, 0, 2 * Math.PI); g.stroke();
g.beginPath(); g.arc(h[0], h[1], 7, 0, 2 * Math.PI); g.stroke();
g.fillStyle = C.amber; g.font = 'bold 24px ' + FONT; g.textBaseline = 'middle';
g.textAlign = h[0] > cx ? 'left' : 'right';
g.fillText('K ' + sel.key.toLocaleString('en-GB'), h[0] + (h[0] > cx ? 14 : -14), h[1]);
g.restore();
}
// ---- motion: app.mjs blendTo, per particle, with a gentle wave from the centre outward ----
function blendTo(target, up, done) {
var from = new Float32Array(S.pos), token = ++S.token, t0 = performance.now(), P = S.pos, i;
var delay = S.delay;
S.moving = true; fadeControls(true); flightMusic(up);
(function step(t) {
if (!S || token !== S.token) return;
var u = Math.min(1, (t - t0) / MOVE_MS);
if (u >= 1) P.set(target);
else for (i = 0; i < N; i++) {
var v = (u - delay[i]) / 0.7; v = v < 0 ? 0 : (v > 1 ? 1 : v);
var e = v < 0.5 ? 4 * v * v * v : 1 - Math.pow(-2 * v + 2, 3) / 2;
P[2 * i] = from[2 * i] + (target[2 * i] - from[2 * i]) * e;
P[2 * i + 1] = from[2 * i + 1] + (target[2 * i + 1] - from[2 * i + 1]) * e;
}
render();
if (u < 1) S.raf = requestAnimationFrame(step);
else { S.moving = false; fadeControls(false); if (done) done(); }
})(t0);
}
function draw(name) {
closePop();
var net = window.KGGridData && window.KGGridData[name];
if (!net) { caption('the network data did not load'); return; }
if (!S.targets[name]) S.targets[name] = networkTargets(net, 0.85 * S.Rw);
S.mode = name; S.sel = null; hideCard(); S.selRO.textContent = '';
var lab = net.label.charAt(0).toUpperCase() + net.label.slice(1);
caption(S.phone ? lab : SENT[name].charAt(0) + SENT[name].slice(1).toLowerCase().replace('kv', 'kV'));
attrib(/OpenStreetMap/.test(net.attribution) ? '(c) OpenStreetMap contributors, ODbL' : 'Coastline: Natural Earth, public domain');
readout();
blendTo(S.targets[name].t, true, function () { caption(lab); });
}
function release() {
closePop(); S.mode = 'wafer'; S.sel = null; hideCard(); attrib(''); S.selRO.textContent = '';
caption('Release: every particle back to its own place'); readout();
blendTo(S.home, false, function () { S.pos.set(S.home); render(); caption(S.phone ? 'The wafer' : 'The wafer: every place from KuiperLaw.place'); });
}
// ---- UI ----
function fadeControls(on) { S.bar.style.opacity = on ? '0.15' : '1'; }
function caption(t) {
S.cap.textContent = t; S.cap.style.transition = 'none'; S.cap.style.opacity = '1';
clearTimeout(S.capT); S.capT = setTimeout(function () { if (S) { S.cap.style.transition = 'opacity 1.6s'; S.cap.style.opacity = '0.35'; } }, 4000);
}
function attrib(t) { S.att.textContent = t; S.att.style.display = t ? 'block' : 'none'; }
function readout() {
var lab = S.mode === 'wafer' ? 'WAFER' : ({ substations: 'SUBSTATIONS', grid400: '400 kV', grid132: '132 kV', uk: 'BRITISH ISLES' })[S.mode];
var net = S.mode !== 'wafer' && window.KGGridData && window.KGGridData[S.mode];
var cnt = net ? ' ' + net.n.toLocaleString('en-GB') + (net.e.length && !S.phone ? ' NODES' : '') : '';
S.ro.textContent = (S.phone ? '' : N.toLocaleString('en-GB') + ' PARTICLES ') + lab + cnt;
}
function btn(label, parent, fn, title) {
var b = el('button', 'pointer-events:auto;font:bold 24px ' + FONT + ';color:' + C.cyan + ';background:transparent;border:1px solid rgba(0,255,255,0.5);border-radius:8px;opacity:0.62;cursor:pointer;white-space:nowrap;letter-spacing:0.5px;transition:opacity .2s,border-color .2s', label, parent);
b.type = 'button'; if (title) b.setAttribute('aria-label', title);
b.addEventListener('pointerenter', function () { b.style.opacity = '1'; });
b.addEventListener('pointerleave', function () { b.style.opacity = '0.62'; });
b.addEventListener('click', function (e) { e.stopPropagation(); audio(); fn(); });
return b;
}
function popup(build) {
closePop(); hideCard(); if (S.sel) { S.sel = null; render(); }
var p = el('div', 'position:absolute;left:50%;transform:translateX(-50%);bottom:calc(' + (S.phone ? 72 : 96) + 'px + env(safe-area-inset-bottom));width:min(720px,calc(100% - 32px));max-height:calc(100% - ' + (S.phone ? 150 : 200) + 'px);overflow:auto;background:rgba(0,0,0,0.94);border:1px solid rgba(0,255,255,0.45);border-radius:12px;padding:12px;box-sizing:border-box;pointer-events:auto;color … [line shortened here: 443 characters; full line on GitHub]
p.addEventListener('pointerdown', function (e) { e.stopPropagation(); });
build(p); S.pop = p; return p;
}
function closePop() { if (S && S.pop) { S.pop.remove(); S.pop = null; } }
function drawMenu() {
popup(function (p) {
ORDER.concat(['release']).forEach(function (k, i) {
var b = btn(SENT[k], p, function () { k === 'release' ? release() : draw(k); });
b.style.cssText += ';display:block;width:100%;text-align:left;margin:' + (i ? 8 : 0) + 'px 0 0;height:auto;min-height:' + (S.phone ? 56 : 64) + 'px;padding:8px 14px;font-size:24px;white-space:normal;line-height:1.1';
if (k === 'release') b.style.color = C.green, b.style.borderColor = 'rgba(34,238,119,0.5)';
b.dataset.cmd = k;
});
});
}
function whyMenu() {
var D = window.KGGridData || {}, L = window.KuiperLaw.constants;
popup(function (p) {
function h(t) { el('div', 'font:bold 26px ' + FONT + ';color:' + C.cyan + ';margin:14px 0 6px', t, p); }
function para(t, col) { el('div', 'margin:0 0 8px;color:' + (col || '#fff'), t, p); }
h('WHY: how a key is given to each node');
para('Particle i (i = 0 to ' + (N - 1).toLocaleString('en-GB') + ') carries key K = floor((i + 0.5) x SPACE / N), with SPACE = ' + L.SPACE.toLocaleString('en-GB') + ' (SPACE includes issued and unissued addresses) and N = ' + N.toLocaleString('en-GB') + '. So the keys are spread evenly over the wafer.');
para('Node j of a network, in the order of the public file, takes the key of particle j. A substation\'s KEY is that K. On the lines, particles are shared out along each edge in proportion to its length (pilot.mjs networkTargets), in file order, so the rule is fixed and repeatable.');
h('Why the same key always comes back to the same place');
para('The place at rest is a pure function of the key, the real law (KuiperLaw.place, kuiper-belt index.html:250): m = (K x 2654435769) mod 2^32, theta = 2 pi m / 2^32, r = sqrt(K + 0.5). The key computes an ideal wafer home; this animation keeps rounded home, target and current positions in memory (Float32), and RELEASE copies those stored home positions back. Nothing is random. Network geo … [line shortened here: 546 characters; full line on GitHub]
para('Bearing is measured clockwise from the top of the wafer: bearing = 90 - theta in degrees. Range is r, in wafer units, out of ' + Math.round(S.Rw).toLocaleString('en-GB') + ' at the rim.', C.sky);
h('The motion');
para('Every frame, drawn = from + (target - from) x ease(u), cubic in and out, over ' + (MOVE_MS / 1000) + ' s (app.mjs blendTo), started a little later the further a particle sits from the centre.');
h('Source and attribution of the network data');
ORDER.forEach(function (k) {
var n = D[k]; if (!n) return;
para(n.label.toUpperCase() + ': ' + n.n.toLocaleString('en-GB') + ' nodes, ' + (n.e.length / 2).toLocaleString('en-GB') + ' edges. Source: ' + n.source + '. ' + n.attribution + '. Law: ' + n.law + '.', '#cfe');
});
para('From the public globalgrid2050 network files (*-network.json). Coordinates kept to 4 decimals as published; circuit names on line vertices dropped. It charts published data; it is not a design.', C.sky);
});
}
function showCard(lines) {
S.card.innerHTML = '';
lines.forEach(function (l, i) { el('div', 'color:' + (i === 0 ? C.amber : (l.c || '#fff')) + ';' + (i === 0 ? 'font-weight:bold;' : ''), l.t || l, S.card); });
S.card.style.display = 'block';
}
function hideCard() { if (S) S.card.style.display = 'none'; }
function pick(sx, sy) {
var cx = S.W / 2, cy = S.H / 2, z = S.zoom, best = -1, bd = 900, P = S.pos; // within 30 px
for (var i = 0; i < N; i++) { var dx = cx + P[2 * i] * z - sx, dy = cy - P[2 * i + 1] * z - sy, d = dx * dx + dy * dy; if (d < bd) { bd = d; best = i; } }
if (best < 0) { S.sel = null; hideCard(); render(); return; }
var D = window.KGGridData, sub = D && D.substations, lines = [], i2 = best, key, home;
if (S.mode === 'substations' || S.mode === 'wafer') {
var nt = S.targets.substations || (S.targets.substations = networkTargets(sub, 0.85 * S.Rw));
var q = nt.node[best], nm = sub.names[q]; // the substation this particle belongs to
if (S.mode === 'wafer') {
key = keyOf(best, S.SPACE); home = window.KuiperLaw.place(key);
lines.push({ t: 'KEY ' + key.toLocaleString('en-GB') });
lines.push({ t: 'flies to: ' + (nm || 'substation ' + q + ' (no name in the public file)'), c: C.sky });
} else {
key = keyOf(q, S.SPACE); home = window.KuiperLaw.place(key); i2 = q;
lines.push({ t: nm ? nm : 'Substation ' + q + ' (no name in the public file)' });
lines.push({ t: 'KEY ' + key.toLocaleString('en-GB') });
}
} else {
var t = S.targets[S.mode], node = t.node[best];
key = keyOf(best, S.SPACE); home = window.KuiperLaw.place(key);
lines.push({ t: (S.mode === 'uk' ? 'Coastline' : D[S.mode].label.replace('the ', '')) + ' node ' + node });
lines.push({ t: 'KEY ' + key.toLocaleString('en-GB') });
}
lines.push({ t: 'BEARING ' + bearingOf(home).toFixed(1) + ' deg RANGE ' + Math.round(home.r).toLocaleString('en-GB'), c: C.sky });
S.sel = { i: i2 < N ? i2 : best, key: key, home: home };
S.selRO.textContent = 'KEY ' + key.toLocaleString('en-GB') + ' ' + bearingOf(home).toFixed(1) + ' deg r ' + Math.round(home.r).toLocaleString('en-GB');
showCard(lines); render();
note(PENTA[key % 7] + 12, 0, 0.5, 0.05, 'sine');
}
function open(host) {
if (S) close();
S = { host: host, token: 0, targets: {}, mode: 'wafer', muted: false, listeners: [] };
host.style.position = host.style.position || 'fixed';
host.style.overflow = 'hidden'; host.style.background = '#000';
var cv = el('canvas', 'position:absolute;left:0;top:0;touch-action:none;display:block', null, host);
cv.setAttribute('aria-label', 'Kuiper particles drawing the UK grid');
S.cv = cv; S.ctx = cv.getContext('2d');
var ui = el('div', 'position:absolute;inset:0;pointer-events:none;font:24px ' + FONT + ';color:#fff', null, host); S.ui = ui;
var pad = 'env(safe-area-inset-top)';
S.cap = el('div', 'position:absolute;left:16px;right:96px;top:calc(18px + ' + pad + ');font:bold 26px ' + FONT + ';color:' + C.white + ';white-space:nowrap;overflow:hidden;text-overflow:ellipsis', '', ui);
S.ro = el('div', 'position:absolute;left:16px;right:96px;overflow:hidden;text-overflow:ellipsis;top:calc(56px + ' + pad + ');font:24px ' + FONT + ';color:rgba(0,255,255,0.7);white-space:nowrap', '', ui);
S.selRO = el('div', 'position:absolute;left:16px;top:calc(88px + ' + pad + ');font:24px ' + FONT + ';color:rgba(255,176,0,0.85);white-space:nowrap', '', ui);
S.att = el('div', 'position:absolute;right:16px;bottom:calc(' + 84 + 'px + env(safe-area-inset-bottom));font:24px ' + FONT + ';color:rgba(102,204,255,0.75);text-align:right;max-width:calc(100% - 32px);display:none', '', ui);
S.card = el('div', 'position:absolute;left:16px;top:calc(124px + ' + pad + ');max-width:min(560px,calc(100% - 32px));background:rgba(0,0,0,0.78);border:1px solid rgba(255,176,0,0.55);border-radius:10px;padding:8px 12px;font:24px/1.3 ' + FONT + ';display:none;pointer-events:auto', '', ui);
S.card.addEventListener('pointerdown', function (e) { e.stopPropagation(); S.sel = null; hideCard(); render(); });