In this section
- Pilot interaction · globalgrid2050 / testcode/wafer-development-environment/202609180245-real-systems/pilot.mjs lines 1–299
- Wafer Development Environment — One Wafer Page render · globalgrid2050 / testcode/wafer-development-environment/202609191255-one-wafer/index.html lines 1–258
Pilot
A JavaScript module in the testcode folder of GlobalGrid2050 that draws electron, using IEC 60909 and uses data from the ventus-grid-engine repository. Served with the page at https://globalgrid2050.com/testcode/wafer-development-environment/202609180245-real-systems/.
interactionglobalgrid2050 / testcode/wafer-development-environment/202609180245-real-systems/pilot.mjs · lines 1–299 of 299 · version 2026-09-18 02:45 · Entry point · pattern clockTargets (shared by 3 files)
- What it does
- It draws electron, qubit and entangle. Defines 29 functions or classes, including $, here, hash32, mulberry32, atomOf. Side effects: changes the web page (DOM); makes network requests; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: 400kV, 132kV.
- Inputs & outputs
- In: data source: ventus-grid-engine data; data source: gridatlas data; data source: pipelinenews data; data source: grid-dictionary data; data source: spiders data; data source: star-solar-star data; data source: code-generator data; data source: testcode data. Out: browser storage (setItem); canvas drawing. Voltage levels named: 400kV, 132kV.
- Downstream impact
- Used directly by 1 file: Wafer Development Environment — Real Systems Page (globalgrid2050, https://globalgrid2050.com/testcode/wafer-development-environment/202609180245-real-systems/). Reached from 146 other entry points, including GlobalGrid2050 Historical Builds (globalgrid2050, https://globalgrid2050.com/historical_builds.html); GlobalGrid2050 Homepage Before Four Nests (globalgrid2050, https://globalgrid2050.com/homepage-before-four-nests-20260925.html); Homepage V037 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v037.html). It is itself an entry point, published at https://globalgrid2050.com/testcode/wafer-development-environment/202609180245-real-systems/.
- What it achieves
- It describes line (`describeLine`) and loads net (`loadNet`). Quantum Twin — primary key to actual code flights. Its code works with 132 kV, 400 kV and 100 kW. It responds to pointerdown, pointermove and pointerup events.
- Why it matters
- Loaded by the Real Systems page at https://globalgrid2050.com/testcode/wafer-development-environment/202609180245-real-systems/.
- Application
- globalgrid2050 · testcode/wafer-development-environment/202609180245-real-systems · JavaScript module
- Uses
- GridAtlas — Atlas Page (estate URL), Grid Dictionary — Index Page (estate URL), Spiders — Index Page (estate URL), Code Generator — Index Page (estate URL), Galaxies Wafers — Index Page (estate URL), Stars — Index Page (estate URL)
- Used by
- loaded by Wafer Development Environment — Real Systems Page (script src)
- Produces
- $, here, hash32, mulberry32, atomOf, twinOf, say, esc, fly, gh, signal, plainLabel
- Defines here
- $, here, hash32, mulberry32, atomOf, twinOf, say, esc, fly, gh, signal, plainLabel, describeLine, run, earthUrl, W, hud, repoOf, scopeKeys, scopeFail, rasterLogo, toWafer, logoTargets, panelLink, j, loadNet, networkTargets, clockTargets, put
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/wafer-development-environment/202609180245-real-systems/pilot.mjs:1-299 · blob 092df31ee93df9e7a2d055497bd6b7a98c258908 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, network, storage · domain stage: experimental · users: none · canonical: production_core
// Quantum Twin — primary key to actual code flights. The pilot on top of the Line Wafer.
// Two twins: the permanent key (chronological, never reused) and the actual line it stands for (repo, commit, path, line).
// This file drives the wafer through its own controls (line number · connect to… · FLY) and adds a command box,
// a narration card, qubit/measure (the Quantum Twin Star's own model and generator), apps, entanglement and engine calls.
// It runs in two modes: on the website (static files, engine imported live from ventus-grid-engine's published modules)
// and in CPU WORLD (a local server adds read-from-git and the runner swarm). No model, no colour beyond the wafer's own.
const $ = id => document.getElementById(id);
const here = (() => { const m = document.querySelector('meta[name="wafer-data"]'); return m ? new URL(m.content, location.href).href : new URL('.', location.href).href; })();
const ENGINE_WEB = 'https://ventusltd.github.io/ventus-grid-engine/engine/';
let labels = null, apps = null, keysDb = null, qubit = null, entangle = null, serverMode = false; const born = { count: 0, seed: '2026-09-14' };
const DIES = ['sld-sandbox', 'substation-intelligence', 'place-global-search', 'streaming-parquet-bridge'];
// The Quantum Twin Star's own generator (testcode/202609142202/quantum.js), copied exactly so a measurement here reproduces one there.
function hash32(str){ let h = 0x811c9dc5 >>> 0; for (let i = 0; i < str.length; i++) { h ^= str.charCodeAt(i); h = Math.imul(h, 0x01000193) >>> 0; } return h >>> 0; }
function mulberry32(a){ return function(){ a |= 0; a = a + 0x6D2B79F5 | 0; let t = Math.imul(a ^ a >>> 15, 1 | a); t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t; return ((t ^ t >>> 14) >>> 0) / 4294967296; }; }
function atomOf(k){ if (!keysDb || !qubit) return null; const i = keysDb.keys.indexOf(k); if (i < 0) return null; const fid = String(keysDb.family[i]); const a = qubit.atoms[fid]; return a ? { fid, i, ...a } : null; }
function twinOf(k){ if (!keysDb) return null; const i = keysDb.keys.indexOf(k); if (i < 0) return null; const pl = keysDb.places[keysDb.place[i]]; return { repo: pl[0], commit: pl[1], path: pl[2], line: keysDb.line[i] }; }
const css = document.createElement('style'); css.textContent = `
#pilot{position:fixed;left:0;right:0;bottom:0;display:flex;gap:8px;padding:8px 12px;background:#0e121bf2;border-top:1px solid #1b2030;z-index:20}
#pilot input{flex:1;font:12px/1.45 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;background:#11151f;color:#cfe3f2;border:1px solid #1b2030;border-radius:6px;padding:.6rem .9rem}
#pilot input:focus{outline:1px solid #5ec8f2}
#say{position:fixed;left:50%;top:12vh;transform:translateX(-50%);width:min(72ch,84vw);max-height:70vh;min-width:280px;min-height:64px;background:#0e121bf2;border:1px solid #1b2030;border-radius:8px;padding:0;font:14px/1.5 ui-monospace,Menlo,Consolas,monospace;color:#cfe3f2;display:none;z-index:20;white-space:pre-wrap;resize:both;overflow:hidden;display:none;flex-direction:column}
#say.open{display:flex} #say.max{left:12px;top:12px;right:12px;bottom:60px;transform:none;width:auto;max-height:none;height:auto}
#say.min{height:auto!important;max-height:none;resize:none;width:min(48ch,84vw)} #say.min #saybody{display:none}
#saybar{display:flex;align-items:center;gap:6px;padding:4px 8px;border-bottom:1px solid #1b2030;background:#11151f;cursor:move;user-select:none;font-size:11px;color:#8b93a7;letter-spacing:.06em;text-transform:uppercase}
#saybar span{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} #saybar button{font:12px ui-monospace,Menlo,Consolas,monospace;background:#0e121b;color:#cfe3f2;border:1px solid #1b2030;border-radius:4px;width:24px;height:22px;cursor:pointer;padding:0}
#saybar button:hover{border-color:#5ec8f2} #saybody{padding:.8rem 1.1rem;overflow:auto;flex:1}
#saybody b{color:#5ec8f2} #say i{color:#f2b05e;font-style:normal} #say a{color:#5ec8f2} #saybody pre{max-height:38vh;overflow:auto;background:#11151f;border:1px solid #1b2030;border-radius:4px;padding:6px 8px;margin:6px 0;font:12px/1.5 ui-monospace,Menlo,Consolas,monospace;white-space:pre}
#saybody pre em{color:#5b6377;font-style:normal} #saybody pre u{display:block;text-decoration:none;color:#5b6377;font-size:11px;padding-left:4.2em;margin:0 0 2px}
#saybody pre .hit u{color:#8b93a7}
#saybody pre .hit{display:inline-block;width:100%;background:#1b2030;color:#f2b05e}
#saybody a.dev{float:right;font-size:11px;color:#5b6377}
#say code{display:block;background:#11151f;border:1px solid #1b2030;border-radius:4px;padding:2px 6px;color:#cfe3f2;margin:4px 0}
#eg{position:fixed;right:12px;bottom:58px;background:#0e121bf2;border:1px solid #1b2030;border-radius:8px;padding:.5rem .7rem;display:flex;flex-direction:column;gap:4px;max-width:46vw;z-index:20}
#eg label{font:11px ui-monospace,Menlo,Consolas,monospace;letter-spacing:.08em;text-transform:uppercase;color:#8b93a7}
#eg select{font:12px ui-monospace,Menlo,Consolas,monospace;background:#11151f;color:#cfe3f2;border:1px solid #1b2030;border-radius:6px;padding:.45rem .7rem}
#plog{position:fixed;left:12px;bottom:58px;max-height:30vh;overflow:hidden;font:11px/1.5 ui-monospace,Menlo,Consolas,monospace;color:#8b93a7;white-space:pre;pointer-events:none;z-index:19}
#beam{bottom:58px !important}
#core button{pointer-events:auto;min-height:44px;min-width:44px;padding:.55rem .9rem;font:13px/1.2 ui-monospace,Menlo,Consolas,monospace;letter-spacing:.04em;background:#0e121bf2;color:#cfe3f2;border:1px solid #5ec8f2;border-radius:8px;cursor:pointer;touch-action:manipulation}
#core button:hover,#core button:focus-visible{background:#11151f;border-color:#f2b05e;outline:none} #core button small{display:block;color:#8b93a7;font-size:10px;letter-spacing:.06em;text-transform:uppercase}
@media (max-width:640px){#earth{position:fixed;inset:0;z-index:30;display:none;flex-direction:column;background:#0b0e15}
#earth.open{display:flex}
#earthbar{display:flex;align-items:center;gap:10px;padding:6px 12px;background:#11151f;border-bottom:1px solid #1b2030;font:12px ui-monospace,Menlo,Consolas,monospace;color:#cfe3f2}
#earthbar b{color:#f2b05e;letter-spacing:.08em} #earthbar span{flex:1;color:#8b93a7;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
#earthbar button,#earthbar a{font:12px ui-monospace,Menlo,Consolas,monospace;background:#0e121b;color:#5ec8f2;border:1px solid #1b2030;border-radius:6px;padding:.4rem .8rem;cursor:pointer;text-decoration:none}
#earthframe{flex:1;border:0;width:100%;background:#000}
`; document.head.appendChild(css);
document.body.insertAdjacentHTML('beforeend', `
<div id="say"></div><div id="plog"></div>
<div id="eg"><label>examples: pick one, it lands in the box, press Enter</label><select id="egs">
<option value="">— choose an example sentence —</option><option value="draw grid">Draw the grid: 400 kV, 132 kV and every substation</option><option value="draw grid400">Draw the 400 kV grid</option><option value="draw grid132">Draw the 132 kV network</option><option value="draw substations">Draw every substation</option><option value="draw shotwick">Draw Shotwick Solar Farm and the grid around it … [line shortened here: 965 characters; full line on GitHub]
<option value="block 39885">Go to the most-copied line in the estate (39885)</option>
<option value="twin 39885">The code behind block 39885, in the card</option>
<option value="state 39885">State of block 39885: HOME or AWAY, from its callers</option>
<option value="measure 39885">Measure block 39885: one recorded draw, HOME or AWAY</option>
<option value="connect 39885 1217">Connect two lines with the beam</option>
<option value="app gridatlas">Go to GridAtlas</option>
<option value="land gridatlas">Land on GridAtlas: the live app, inside this page</option>
<option value="land pipelinenews">Land on Pipeline News</option>
<option value="space">Back to space: the wafer</option>
<option value="apps">List every app on the wafer</option>
<option value="run voltage-drop.voltageDropVolts {"currentA":120,"lengthM":250,"resistanceOhmPerKm":0.32,"powerFactor":0.95,"phases":"three"}">Engine: voltage drop, 120 A over 250 m, 0.32 Ω/km, pf 0.95</option>
<option value="entangle">Check: how many blocks are found at their recorded line</option>
<option value="help">Help</option></select></div>
<form id="pilot"><input id="pin" autocomplete="off" autofocus placeholder="type a sentence or a command: block 39885 · twin 39885 · state 39885 · measure 39885 · app gridatlas · run voltage-drop… · help"></form>`);
const EARTH_HTML = '<div id="earth"><div id="earthbar"><b>EARTH</b><span id="earthname"></span><a id="earthtab" target="_blank">open in its own tab</a><button id="earthback">back to space</button></div><iframe id="earthframe" title="the live app"></iframe></div>';
const lines = []; const log = s => { lines.push(s); if (lines.length > 12) lines.shift(); $('plog').textContent = lines.join('\n'); };
// the card is a small window: minimise, maximise, resize (drag the corner), close; any new answer reopens it
const sayEl = $('say'); sayEl.innerHTML = '<div id="saybar"><span id="saytitle">card</span><button id="saymin" title="minimise">–</button><button id="saymax" title="maximise">▢</button><button id="sayclose" title="close">×</button></div><div id="saybody"></div>';
let lastCard = '';
const say = html => { if (!html) { sayEl.classList.remove('open'); return; } lastCard = html; $('saybody').innerHTML = html; const t = $('saybody').querySelector('b'); $('saytitle').textContent = t ? t.textContent : 'card'; sayEl.classList.remove('min'); sayEl.classList.add('open'); };
$('saymin').onclick = e => { e.stopPropagation(); sayEl.classList.toggle('min'); }; $('saymax').onclick = e => { e.stopPropagation(); sayEl.classList.remove('min'); sayEl.classList.toggle('max'); }; $('sayclose').onclick = e => { e.stopPropagation(); sayEl.classList.remove('open', 'max', 'min'); };
$('saybar').ondblclick = () => sayEl.classList.toggle('min');
(() => { let d = null; $('saybar').addEventListener('pointerdown', e => { if (e.target.tagName === 'BUTTON' || sayEl.classList.contains('max')) return; const r = sayEl.getBoundingClientRect(); d = { x: e.clientX - r.left, y: e.clientY - r.top }; sayEl.style.transform = 'none'; sayEl.style.left = r.left + 'px'; sayEl.style.top = r.top + 'px'; $('saybar').setPointerCapture(e.pointerId); });
$('saybar').addEventListener('pointermove', e => { if (!d) return; sayEl.style.left = Math.max(0, e.clientX - d.x) + 'px'; sayEl.style.top = Math.max(0, e.clientY - d.y) + 'px'; }); $('saybar').addEventListener('pointerup', () => { d = null; }); $('saybar').addEventListener('pointercancel', () => { d = null; }); })();
window.__card = () => ({ open: sayEl.classList.contains('open'), min: sayEl.classList.contains('min'), max: sayEl.classList.contains('max'), w: sayEl.offsetWidth, h: sayEl.offsetHeight, title: $('saytitle').textContent });
const esc = s => String(s).replace(/</g, '<');
const fly = (a, b) => { $('a').value = String(a); $('b').value = b ? String(b) : ''; $('beam').requestSubmit(); };
const gh = t => `https://github.com/${t.repo}/blob/${t.commit}/${t.path}#L${t.line}`;
const signal = o => { if (serverMode) fetch('/signal', { method: 'POST', body: JSON.stringify(o) }).catch(() => {}); try { const L = JSON.parse(localStorage.getItem('qt-signals') || '[]'); L.push({ ...o, t: new Date().toISOString() }); localStorage.setItem('qt-signals', JSON.stringify(L.slice(-500))); } catch {} };
// ---------- plain English: engine calls get a label; every line in the code view gets a note (same rules as pipeline/describe.py) ----------
const PLAIN = {
'voltage-drop.voltageDropVolts': a => `voltage drop for ${a.currentA} A over ${a.lengthM} m at ${a.resistanceOhmPerKm} Ω/km${a.reactanceOhmPerKm ? ' (reactance ' + a.reactanceOhmPerKm + ')' : ''}, power factor ${a.powerFactor}, ${a.phases || 'three'}-phase`,
'voltage-drop.dropPercent': a => `${a.dropVolts} V drop as a share of ${a.nominalVolts} V`, 'voltage-drop.lossesWatts': a => `heat lost in the cable: ${a.currentA} A over ${a.lengthM} m at ${a.resistanceOhmPerKm} Ω/km`,
'diversified-demand.diversifiedDemandKw': a => `demand of ${a.unitCount} units at ${a.perUnitKw} kW each, coincidence ${a.coincidenceFactor}`,
'current-from-power.currentA': a => `current for ${a.apparentPowerVa} VA at ${a.voltageV} V, ${a.phases || 'three'}-phase`, 'firm-capacity.apparentPowerMva': a => `apparent power for ${a.mw} MW at power factor ${a.powerFactor}`,
'power-factor.reactivePowerKvar': a => `reactive power for ${a.kw} kW at power factor ${a.powerFactor}`,
};
const plainLabel = (mod, fn, args) => { const f = PLAIN[`${mod}.${fn}`]; try { return f ? f(args) : `${mod.replace(/-/g, ' ')}: ${fn.replace(/([A-Z])/g, ' $1').toLowerCase()}`; } catch { return `${mod}.${fn}`; } };
const DESCRIBE_RULES = [
[/^\s*$/, 'blank line'], [/^\s*\/\//, 'a comment'], [/^\s*\/\*|^\s*\*/, 'a comment block'],
[/^\s*(import|export)\b/, 'brings code in or out of this file'], [/^\s*(?:async\s+)?function\s+(\w+)/, 'defines the function $1'],
[/^\s*(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s*)?\(?[^=]*=>/, 'defines the function $1'], [/^\s*(?:const|let|var)\s+(\w+)\s*=/, 'sets $1'],
[/\.addEventListener\(\s*['"](\w+)/, 'listens for a $1 on the page'], [/^\s*return\b/, 'hands a result back'], [/^\s*if\b/, 'decides: only when the condition holds'],
[/^\s*(?:else|\} else)/, 'otherwise'], [/^\s*for\b|^\s*while\b/, 'repeats for each item'], [/^\s*try\b/, 'tries, ready to catch a failure'], [/^\s*catch\b|\} catch/, 'handles a failure'],
[/\.(?:querySelector|getElementById)\(/, 'finds a part of the page'], [/\.innerHTML\s*=|\.textContent\s*=/, 'writes text onto the page'], [/\bfetch\(/, 'asks a server for data'],
[/\bclassList\./, 'changes how a part of the page looks'], [/\bconsole\./, 'writes to the developer console'], [/\bthrow\b/, 'stops with an error'],
[/^\s*\}\s*\)?;?\s*$|^\s*\]\s*;?\s*$/, 'closes a block'], [/^\s*(\w+)\s*\(.*\)\s*;?\s*$/, 'calls $1'], [/\bawait\b/, 'waits for a result'], [/=/, 'sets a value'],
];
const describeLine = line => { for (const [re, note] of DESCRIBE_RULES) { const m = line.match(re); if (m) return note.replace(/\$(\d)/g, (_, i) => m[+i] || ''); } return 'a line of code'; };
window.__describe = describeLine;
const cmds = {
help(){ say(`<b>commands</b>\nblock <key> · twin <key> · read <key> · state <key> · measure <key> [seed] · connect <a> <b> · land <app> · space · app <name> · apps · engine · run <module>.<fn> {…} · entangle · reset\nor a sentence: "fly to 39885", "show me gridatlas", "voltage drop for 120 A over 250 m at 0.32 ohm pf 0.95"\n\nEach … [line shortened here: 501 characters; full line on GitHub]
block(k){ k = parseInt(k, 10); if (!Number.isFinite(k)) return log('block <key>'); fly(k); say(`<b>block ${k}</b>\nthe beam is on line ${k}; the panel on the left shows what it is.\n<i>next:</i> twin ${k}`); log(`block ${k}`); },
fly(k){ return cmds.block(k); }, goto(k){ return cmds.block(k); },
async twin(k){ k = parseInt(k, 10); const t = twinOf(k); if (!t) return log(`twin ${k}: this block has no recorded line`); fly(k); return cmds.showCode(k, t, 'twin'); },
async read(k){ k = parseInt(k, 10); const t = twinOf(k); if (!t) return log(`read ${k}: this block has no recorded line`); fly(k); return cmds.showCode(k, t, 'read'); },
// the code itself, in the card, scrollable, the line highlighted; the source link is a fallback for developers
async showCode(k, t, verb){ const raw = `https://raw.githubusercontent.com/${t.repo}/${t.commit}/${t.path}`; let lines = null;
try { const r = await fetch(raw); if (r.ok) lines = (await r.text()).split(/\r?\n/); } catch {}
if (!lines && serverMode) { try { const r = await (await fetch('/line?key=' + k)).json(); if (!r.error) lines = [...r.before, r.text, ...r.after].map(x => x ?? ''); } catch {} }
const head = `<b>${verb} ${k}</b> — ${esc(t.repo.split('/').pop())} · ${esc(t.path.split('/').pop())} · line ${t.line}`;
if (!lines) { say(`${head}
could not load the file here.
<a target="_blank" href="${gh(t)}">source, for developers</a>`); return log(`${verb} ${k}: file not loaded; source link shown`); }
const from = Math.max(1, t.line - 20), to = Math.min(lines.length, t.line + 20); const rows = [];
for (let n = from; n <= to; n++) rows.push(`<span class="${n === t.line ? 'hit' : ''}"><em>${String(n).padStart(5)}</em> ${esc(lines[n - 1] ?? '')}<u>${esc(describeLine(lines[n - 1] ?? ''))}</u></span>`);
say(`${head}
<pre id="code">${rows.join('\n')}</pre><i>next:</i> state ${k} <a class="dev" target="_blank" href="${gh(t)}">source, for developers</a>`);
const hit = document.querySelector('#code .hit'); if (hit) hit.scrollIntoView({ block: 'center' }); log(`${verb} ${k}: ${t.path.split('/').pop()} line ${t.line}: ${(lines[t.line - 1] || '').trim().slice(0, 60)}`); },
state(k){ k = parseInt(k, 10); const a = atomOf(k); if (!a) return log(`state ${k}: this block has no family record`); const n = a.K + a.L + a.M; const pAway = n ? a.M / n : 0; const theta = 2 * Math.asin(Math.sqrt(pAway)); fly(k);
say(`<b>state ${k}</b> — block family #${esc(a.fid)} ${esc(a.name && a.name !== '(anonymous)' ? a.name : 'unnamed')} (${a.source === 'electron.json' ? 'from the published data' : 'estimated from where its copies sit'})\ncallers: K ${a.K} same directory · L ${a.L} same repository · M ${a.M} other repositories\nHOME P = ${(1 - pAway).toFixed(3)} · AWAY P = ${pAway.toFixed(3)} (AWAY = M ÷ (K+L+M) … [line shortened here: 594 characters; full line on GitHub]
qubit(k){ return cmds.state(k); },
measure(rest){ const [ks, seedArg] = (rest || '').split(/\s+/); const k = parseInt(ks, 10); const a = atomOf(k); if (!a) return log(`measure ${ks}: this block has no family record`); if (seedArg) born.seed = seedArg;
const n = a.K + a.L + a.M; const pAway = n ? a.M / n : 0; const r = mulberry32(hash32(`${born.seed}|${a.fid}|${born.count}`))(); born.count++; const away = r < pAway; const outcome = away ? 'AWAY' : 'HOME';
const audit = `Draw ${born.count + 1}: seed "${born.seed}" · state #${a.fid} · r=${r.toFixed(6)} ${away ? '<' : '≥'} P(away)=${pAway.toFixed(3)} → ${outcome}`;
say(`<b>measure ${k}</b> — result: <b>${outcome}</b>\n${esc(audit)}\nThe same seed, block and count always give the same result. Type <i>state ${k}</i> to see the probabilities again.`); log(audit);
signal({ kind: 'born', key: k, family: a.fid, seed: born.seed, count: born.count, r, p_away: pAway, outcome: away ? 'AWAY' : 'HOME', shells: { K: a.K, L: a.L, M: a.M } }); },
connect(ab){ const [a, b] = (ab || '').split(/\s+/).map(x => parseInt(x, 10)); if (!Number.isFinite(a) || !Number.isFinite(b)) return log('connect <a> <b>'); fly(a, b); say(`<b>connect ${a} → ${b}</b>\nthe beam joins two keys; both twins are real lines.`); log(`connect ${a} ${b}`); },
apps(){ if (!apps) return log('apps not loaded'); const list = apps.apps.filter(a => a.app); say(`<b>${list.length} apps</b> (${esc(apps.rule)})\n` + list.map((a, i) => { const L = labels && labels.labels[a.name]; return `${i + 1}. ${a.name} — ${L ? labels.kinds[L.kind] + ': ' + L.what : ''} · ${a.keys.toLocaleString()} blocks`; }).join('\n') + `\n<i>next:</i> app <name>`); log(`${list.len … [line shortened here: 416 characters; full line on GitHub]
app(name){ if (!apps) return log('apps not loaded'); const list = apps.apps.filter(a => a.app); const a = list.find(x => x.name === (name || '').toLowerCase()) || list.find(x => x.name.includes((name || '').toLowerCase())); if (!a) return log(`no app "${name}"`);
const [k0, k1] = apps.first[a.repo]; fly(k0, k1); const url = a.name === 'globalgrid2050' ? 'https://globalgrid2050.com/' : `https://ventusltd.github.io/${a.name}/`;
say(`<b>app ${esc(a.name)}</b> — ${(() => { const L = labels && labels.labels[a.name]; return L ? esc(labels.kinds[L.kind] + '. ' + L.what) : ''; })()}\n${a.keys.toLocaleString()} blocks in ${a.families} gates · index ${esc(a.index || '?')}\nthe beam spans its first and middle lines (${k0} → ${k1}).\n<a target="_blank" href="${url}">open ${esc(a.name)} — see the code in action</a> · <a targe … [line shortened here: 491 characters; full line on GitHub]
async engine(){ const mods = ['voltage-drop', 'diversified-demand', 'current-from-power', 'firm-capacity', 'power-factor', 'connection-capacity']; const out = []; for (const m of mods) { try { const mod = await import(ENGINE_WEB + m + '.js'); out.push(`${m}: ${Object.keys(mod).filter(k => typeof mod[k] === 'function').join(', ')}`); } catch (e) { out.push(`${m}: (not reachable: ${e.message})`); … [line shortened here: 404 characters; full line on GitHub]
say(`<b>engine</b> — ventus-grid-engine, imported live from its published modules\n${esc(out.join('\n'))}\n<i>next:</i> run voltage-drop.voltageDropVolts {…}`); log('engine listed'); },
async run(rest){ const m = /^([a-z0-9-]+)\.([A-Za-z0-9_]+)\s*(\{[\s\S]*\})?$/.exec((rest || '').trim()); if (!m) return log('run <module>.<fn> {…}'); let args = {}; try { args = m[3] ? JSON.parse(m[3]) : {}; } catch { return log('run: arguments are not valid JSON'); }
let result, err, us = 0; try { const mod = await import(ENGINE_WEB + m[1] + '.js'); if (typeof mod[m[2]] !== 'function') throw new Error(`no function ${m[2]} in ${m[1]}; has ${Object.keys(mod).filter(k => typeof mod[k] === 'function').join(', ')}`); const t0 = performance.now(); result = mod[m[2]](args); us = (performance.now() - t0) * 1000; } catch (e) { err = e.message; }
if (err) { say(`<b>engine ${esc(m[1])}.${esc(m[2])}</b>\n<code>refused: ${esc(err)}</code>`); return log(`run refused: ${err}`); }
const big = (result?.unit && /^(kW|kVA)$/.test(result.unit) && result.value > 100) || (result?.unit && /^(MW|MVA)$/.test(result.unit) && result.value > 0.1) || Object.entries(args).some(([k, v]) => (/mw|mva/i.test(k) && v * 1000 > 100) || (/kw|kva/i.test(k) && v > 100));
say(`<b>${esc(plainLabel(m[1], m[2], args))}</b>\nengine ${esc(m[1])}.${esc(m[2])} · ${us.toFixed(0)} µs · imported from ventusltd.github.io/ventus-grid-engine\nin <code>${esc(JSON.stringify(args))}</code>out <code>${esc(JSON.stringify(result, null, 1))}</code>${big ? '<i>above 100 kW: a chartered electrical engineer must sign any real design.</i>\n' : ''}This page shows figures; it is not the … [line shortened here: 564 characters; full line on GitHub]
entangle(){ if (!entangle) return log('entangle not loaded'); say(`<b>entangle</b> (${esc(entangle.generated_utc)})\n${entangle.resolved.toLocaleString()} of ${entangle.keys.toLocaleString()} blocks reach their twin line (${(entangle.rate * 100).toFixed(2)} %) · ${entangle.broken.toLocaleString()} broken\nmeasured by fetching every twin from its commit and hashing the line (pipeline/entangle.py) … [line shortened here: 504 characters; full line on GitHub]
reset(){ $('a').value = ''; $('b').value = ''; $('panel').hidden = true; say(''); log('reset'); }, home(){ return cmds.reset(); },
die(w){ return log('die: available in CPU WORLD (needs route-gridatlas.json)'); }, light(w){ return cmds.app('gridatlas'); },
};
async function run(line){ const [c, ...rest] = line.trim().split(/\s+/); const w = (c || '').toLowerCase(); const fn = Object.hasOwn(cmds, w) ? cmds[w] : null;
if (!fn) { const p = plan(line, { appNames: apps ? apps.apps.filter(a => a.app).map(a => a.name) : [], dies: DIES }); log(`> ${line}`); log(` plan: ${p.commands.length ? p.commands.join(' → ') : '(none)'} — ${p.because}`); if (p.commands.length) log(` you could have typed: ${p.commands.join(' then ')}`);
for (const c2 of p.commands) { const [w2, ...r2] = c2.split(/\s+/); if (Object.hasOwn(cmds, w2)) { try { await cmds[w2](r2.join(' ')); } catch (e) { log('error: ' + e.message); } } } signal({ kind: 'pilot', sentence: line, plan: p.commands }); return; }
log(`> ${line}`); try { await fn(rest.join(' ')); } catch (e) { log('error: ' + e.message); } }
$('pilot').onsubmit = e => { e.preventDefault(); const v = $('pin').value; $('pin').value = ''; if (v.trim()) run(v); };
$('egs').onchange = e => { if (e.target.value) { if (e.target.value === $('pin').dataset.last && lastCard && !sayEl.classList.contains('open')) { say(lastCard); log('card reopened'); } else { $('pin').value = e.target.value; $('pin').dataset.last = e.target.value; log('example loaded — press Enter to run it'); $('pin').focus(); } } e.target.selectedIndex = 0; };
addEventListener('keydown', e => { const t = e.target.tagName; if (t === 'INPUT' || t === 'SELECT' || t === 'TEXTAREA' || t === 'BUTTON') return; if (e.key.length === 1) $('pin').focus(); });
// ---------- space <-> earth: the live apps, by name, inside the page ----------
const EARTH = { gridatlas: 'https://ventusltd.github.io/gridatlas/atlas/', pipelinenews: 'https://ventusltd.github.io/pipelinenews/', globalgrid2050: 'https://globalgrid2050.com/', 'grid-dictionary': 'https://ventusltd.github.io/grid-dictionary/', spiders: 'https://ventusltd.github.io/spiders/', 'star-solar-star': 'https://ventusltd.github.io/star-solar-star/', 'code-generator': 'https://ventusltd … [line shortened here: 890 characters; full line on GitHub]
document.body.insertAdjacentHTML('beforeend', EARTH_HTML);
const earthUrl = name => EARTH[name] || (apps && apps.apps.find(a => a.app && a.name === name) ? `https://ventusltd.github.io/${name}/` : null);
cmds.land = function(name){ name = (name || '').toLowerCase().trim(); const key = Object.keys(EARTH).find(k => k === name) || Object.keys(EARTH).find(k => k.includes(name)) || (apps ? (apps.apps.find(a => a.app && a.name.includes(name)) || {}).name : null);
const url = key ? earthUrl(key) : null; if (!url) return log(`land <app>: ${Object.keys(EARTH).join(', ')}`);
$('earthname').textContent = `${key} · ${url}`; $('earthtab').href = url; $('earthframe').src = url; $('earth').classList.add('open'); say(''); log(`landed on ${key} — type space to come back`); };
cmds.visit = cmds.land; cmds.go = cmds.land; cmds.open = cmds.land;
cmds.space = function(){ $('earth').classList.remove('open'); $('earthframe').src = 'about:blank'; log('back in space: the wafer'); };
$('earthback').onclick = () => cmds.space();
document.body.insertAdjacentHTML('beforeend', '<div id="hud" style="position:fixed;right:12px;top:44px;font:11px/1.5 ui-monospace,Menlo,Consolas,monospace;color:#8b93a7;pointer-events:none;z-index:19"></div>');
const W = () => window.__wafer; const fmtN = n => n.toLocaleString('en-GB');
const hud = s => { const st = W() && W().state(); if (!st) return; $('hud').textContent = `showing ${fmtN(st.scopeN)} of ${fmtN(st.n)} lines${s ? ' · ' + s : ''}`; };
let scopeName = 'all';
const repoOf = name => { if (!apps) return null; const a = apps.apps.find(x => x.name === name) || apps.apps.find(x => x.name.includes(name)); return a ? a.repo : null; };
// a scope is a set with a rule: all · an app (apps.json keys per repo) · module <path> · gate <family#> · line <key>
function scopeKeys(spec){ const s = (spec || 'all').trim(); const [kind, ...r] = s.split(/\s+/); const arg = r.join(' ');
if (!s || s === 'all' || s === 'estate') return { name: 'all', keys: null };
if (kind === 'line' || kind === 'key') { const k = parseInt(arg, 10); return Number.isFinite(k) ? { name: `line ${k}`, keys: [k] } : null; }
if (kind === 'gate' || kind === 'family') { if (!keysDb) return null; const fid = parseInt(arg, 10); const ks = []; for (let i = 0; i < keysDb.keys.length; i++) if (keysDb.family[i] === fid) ks.push(keysDb.keys[i]); return ks.length ? { name: `gate ${fid}`, keys: ks } : null; }
if (kind === 'module' || kind === 'file' || kind === 'die') { if (!keysDb) return null; const ks = []; for (let i = 0; i < keysDb.keys.length; i++) if (keysDb.places[keysDb.place[i]][2].includes(arg)) ks.push(keysDb.keys[i]); return ks.length ? { name: `module ${arg}`, keys: ks } : null; }
const repo = repoOf(s.toLowerCase()); const ks = repo && apps.keys ? apps.keys[repo] : null; return ks ? { name: repo.split('/').pop(), keys: ks } : null; }
const scopeFail = spec => { log(`scope ${spec}: not a scope — try all, an app name (apps), module <path>, gate <family#>, line <key>`); };
cmds.scope = function(spec){ if (!W()) return log('the wafer is not ready'); const sc = scopeKeys(spec); if (!sc) return scopeFail(spec); const r = W().scope(sc.keys); scopeName = sc.name; hud(sc.name);
log(`scope ${sc.name}: showing ${fmtN(r.shown)} of ${fmtN(r.of)} lines${r.missing ? ` · ${fmtN(r.missing)} keys not numbered here` : ''}`); return r; };
cmds.gravity = async function(spec){ if (!W()) return log('the wafer is not ready'); const sc = scopeKeys(spec); if (!sc) return scopeFail(spec); scopeName = sc.name; const k = W().kepler();
log(`gravity ${sc.name}: Kepler r(θ) = p/(1 + e·cos θ), e = ${k.e}, p = ${k.p.toFixed(1)}, the wafer's centre at the focus, points in key order`); const r = await W().gravity(sc.keys); hud(sc.name + ' · kepler'); log(`gravity ${sc.name}: ${fmtN(r.shown)} lines in orbit${r.missing ? ` · ${fmtN(r.missing)} keys not numbered here` : ''}`); return r; };
cmds.orbit = cmds.gravity; cmds.isolate = cmds.gravity;
cmds.release = async function(){ if (!W()) return log('the wafer is not ready'); const r = await W().release(); scopeName = 'all'; hud(); log(`release: showing ${fmtN(r.shown)} of ${fmtN(r.of)} lines, back on the wafer law`); return r; };
// LOGO: the same dust, the same blend; the target is the wordmark rasterised once, deterministically, off screen (sampled only, never shown)
const LOGO = { lines: ['VENTUS — CABLES AND CONNECTIVITY', 'GLOBALGRID2050'], font: 'bold 120px ui-monospace', step: 2, lineGap: 150, fill: 1.6 };
let logoRaster = null;
function rasterLogo(){ if (logoRaster) return logoRaster; const c = document.createElement('canvas'); const g = c.getContext('2d'); g.font = LOGO.font;
const w = Math.ceil(Math.max(...LOGO.lines.map(t => g.measureText(t).width))) + 40, h = LOGO.lineGap * LOGO.lines.length + 40; c.width = w; c.height = h; g.font = LOGO.font; g.textAlign = 'center'; g.textBaseline = 'middle'; g.fillStyle = '#fff';
LOGO.lines.forEach((t, i) => g.fillText(t, w / 2, 20 + LOGO.lineGap * (i + 0.5))); const px = g.getImageData(0, 0, w, h).data; const on = new Uint8Array(w * h); const samples = [];
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) { if (px[(y * w + x) * 4 + 3] > 127) { on[y * w + x] = 1; if (x % LOGO.step === 0 && y % LOGO.step === 0) samples.push(x, y); } }
const st = W().state(); const s = LOGO.fill * Math.sqrt(st.max) / w; /* wafer units per canvas px: the text spans 1.6·R inside the wafer */
const G = W().kepler().coreOut; /* the two lines part around the core: line 1 lifted by 0.10·R, line 2 lowered by it; the pupil stays empty */
const toWafer = (x, y) => [(x - w / 2) * s, (h / 2 - y) * s + (y < h / 2 ? G : -G)]; const toCanvas = (X, Y) => [X / s + w / 2, h / 2 - (Y > 0 ? Y - G : Y + G) / s];
return (logoRaster = { w, h, on, samples, n: samples.length / 2, s, toWafer, toCanvas }); }
function logoTargets(m){ const L = rasterLogo(); const t = new Float32Array(m * 2); const S = L.n;
for (let j = 0; j < m; j++) { let q, dx = 0, dy = 0; if (m <= S) q = Math.floor(j * S / m); else { q = j % S; const c = Math.floor(j / S); dx = ((c * 7) % LOGO.step) / LOGO.step - 0.5; dy = ((c * 3) % LOGO.step) / LOGO.step - 0.5; } /* cycle with a tiny deterministic offset */
const [X, Y] = L.toWafer(L.samples[2 * q] + dx, L.samples[2 * q + 1] + dy); t[2 * j] = X; t[2 * j + 1] = Y; } return t; }
cmds.logo = async function(spec){ if (!W()) return log('the wafer is not ready'); const sc = scopeKeys(spec || scopeName); if (!sc) return scopeFail(spec); const r = await W().scope(sc.keys); scopeName = sc.name; const L = rasterLogo(); const m = W().state().scopeN;
log(`logo ${sc.name}: ${fmtN(m)} lines → "${LOGO.lines.join(' / ')}" (${fmtN(L.n)} glyph samples, ${LOGO.font}, grid ${LOGO.step} px)`); await W().blend(logoTargets(m)); hud(sc.name + ' · logo'); log(`logo ${sc.name}: assembled`); return r; };
cmds.wordmark = cmds.logo;
// test instrument: share of in-scope points within tolPx (screen px) of a glyph pixel
window.__logoCheck = (tolPx = 3) => { const L = rasterLogo(); const st = W().state(); const rad = Math.max(1, Math.ceil(tolPx / (st.view.zoom * L.s))); const P = W().positions(); let hit = 0;
for (const [, X, Y] of P) { const [cx, cy] = L.toCanvas(X, Y); let ok = false; for (let y = Math.round(cy) - rad; y <= Math.round(cy) + rad && !ok; y++) for (let x = Math.round(cx) - rad; x <= Math.round(cx) + rad; x++) if (x >= 0 && y >= 0 && x < L.w && y < L.h && L.on[y * L.w + x]) { ok = true; break; } if (ok) hit++; }
return { n: P.length, hit, share: P.length ? hit / P.length : 0, radiusCanvasPx: rad, samples: L.n }; };
window.__scopeKeys = spec => { const sc = scopeKeys(spec); return sc ? { name: sc.name, count: sc.keys ? sc.keys.length : null } : null; };
setTimeout(() => hud(), 1500);
// an app is a scope with gravity: app <name> and land <name> pull that app's lines in under Kepler; space releases them to the wafer law
{ const _app = cmds.app, _land = cmds.land, _space = cmds.space;
cmds.app = async function(name){ const r = _app.call(cmds, name); if (W() && name && scopeKeys(name)) await cmds.gravity(name); return r; };
cmds.land = async function(name){ if (W() && name && scopeKeys(name)) await cmds.gravity(name); return _land.call(cmds, name); };
cmds.space = function(){ const r = _space.call(cmds); if (W()) cmds.release(); return r; }; }
window.__earth = () => ({ open: $('earth').classList.contains('open'), name: $('earthname').textContent, src: $('earthframe').src });
// the particles do the work: when the wafer's own panel opens for a line, add one plain link to the app that line belongs to
const APP_OF_REPO = { gridatlas: 'gridatlas', pipelinenews: 'pipelinenews', globalgrid2050: 'globalgrid2050', 'ventus-grid-engine': 'spider sandbox', elements: 'periodic table', 'grid-dictionary': 'grid-dictionary', spiders: 'spiders', 'star-solar-star': 'star-solar-star', 'code-generator': 'code-generator', testcode: 'testcode', 'galaxies-wafers': 'galaxies-wafers', stars: 'stars' };
const panelLink = () => { const body = $('panelbody'); if (!body || body.querySelector('.landlink')) return; const m = (body.innerText || '').match(/Line\s+([\d,]+)/); if (!m) return; const key = +m[1].replace(/,/g, ''); const t = twinOf(key); if (!t) return;
const repo = t.repo.split('/')[1]; const app = APP_OF_REPO[repo]; if (!app) return; const url = EARTH[app] || `https://ventusltd.github.io/${repo}/`;
body.insertAdjacentHTML('beforeend', `<p class="landlink" style="margin:.6rem 0 0"><a href="${url}" style="color:#5ec8f2">land on ${app} — this line's app</a> <span style="color:#8b93a7">· or type: land ${app}</span></p>`);
body.querySelector('.landlink a').addEventListener('click', e => { e.preventDefault(); run('land ' + app); }); };
new MutationObserver(panelLink).observe($('panelbody'), { childList: true, subtree: true });
window.__pilot = run;
(async () => {
serverMode = /^(127\.0\.0\.1|localhost)$/.test(location.hostname) && await fetch('/gpu', { cache: 'no-store' }).then(r => r.ok).catch(() => false);
if (serverMode) (async function poll(){ try { const { lines: L } = await (await fetch('/pilot/next')).json(); for (const l of L) { log(`[powershell] ${l}`); await run(l); } } catch {} setTimeout(poll, 500); })();
const j = async f => fetch(here + f).then(r => r.ok ? r.json() : null).catch(() => null);
[keysDb, qubit, apps, entangle, labels] = await Promise.all([j('keys.json'), j('qubit.json'), j('apps.json'), j('entangle.json'), j('labels.json')]);
log(`Quantum Twin — primary key to actual code. ${keysDb ? keysDb.count.toLocaleString() : '?'} blocks with a recorded line; ${qubit ? Object.keys(qubit.atoms).length.toLocaleString() : '?'} block families.`);
log('Type a sentence or a command. Every answer shows the command it became. Try: block 39885');
const qd = new URLSearchParams(location.search).get('draw'); const start = qd ? (['logo', 'clock'].includes(qd) ? qd : 'draw ' + qd) : document.querySelector('meta[name="wafer-start"]')?.content; if (start) { await new Promise(r => setTimeout(r, 1500)); const m = /^(land|visit|go|open)\s+(\S+)/.exec(start); if (m) { await run('app ' + m[2]); log(`This page stops here. To enter ${m[2]}, type: lan … [line shortened here: 581 characters; full line on GitHub]
})();
// ---------- NETWORK: a whole system drawn from a typed command, on the wafer's own dust (no new looks) ----------
// draw underground: the London Underground's topology (Transport for London open data; stations and the order of
// stops) laid out by an eight-direction schematic law, then the in-scope particles are placed along its edges and at
// its stations by the same blend gravity and the logo use. Positions are computed, never stored; identity never moves.
const netCache = {};
const NETWORKS = { grid: 'the grid: 400 kV, 132 kV and every substation', underground: 'the London Underground', grid400: 'the 400 kV grid', grid132: 'the 132 kV network', substations: 'every substation', shotwick: 'Shotwick Solar Farm and its grid', uk: 'the British Isles', world: 'the world', trench: 'a cable trench in flat formation (a stated arrangement, not a design)', fault: 'a fault study: … [line shortened here: 480 characters; full line on GitHub]
const loadNet = async name => netCache[name] || (netCache[name] = await fetch(new URL(name + '-network.json', location.href)).then(r => r.ok ? r.json() : null).catch(() => null));
function networkTargets(N, m){
const S = 0.85 * W().kepler().R, st = N.stations, E = N.edges, GA = 2.399963229728653;
const perStation = E.length ? 9 : Math.max(1, Math.floor(m / st.length)), stationDots = Math.min(m, perStation * st.length), edgeDots = E.length ? m - stationDots : 0;
const lens = E.map(([a, b, w]) => Math.hypot(st[b][0] - st[a][0], st[b][1] - st[a][1]) * (w == null ? 1 : w)); const L = lens.reduce((a, b) => a + b, 0) || 1;
const t = new Float32Array(m * 2); let j = 0;
for (let e = 0; e < E.length && j < edgeDots; e++) { const [a, b] = E[e]; const k = Math.max(1, Math.round(edgeDots * lens[e] / L));
for (let i = 0; i < k && j < edgeDots; i++, j++) { const u = (i + 0.5) / k; t[2 * j] = S * (st[a][0] + (st[b][0] - st[a][0]) * u); t[2 * j + 1] = S * (st[a][1] + (st[b][1] - st[a][1]) * u); } }
for (let s = 0; j < m; s++, j++) { const q = s % st.length, c = Math.floor(s / st.length), th = c * GA, r = 0.004 * S * Math.sqrt(c);
t[2 * j] = S * st[q][0] + r * Math.cos(th); t[2 * j + 1] = S * st[q][1] + r * Math.sin(th); }
return t;
}
cmds.draw = async function(spec){
let what = (spec || '').trim().toLowerCase().split(/\s+/)[0] || ''; if (/^(tube|london)$/.test(what)) what = 'underground';
if (!NETWORKS[what]) return log('draw <system> — one of: ' + Object.keys(NETWORKS).join(', '));
if (!W()) return log('the wafer is not ready');
const N = await loadNet(what); if (!N) return log(`draw ${what}: ${what}-network.json missing`);
await W().scope(null); const m = W().state().scopeN;
log(`draw ${what}: ${N.stations.length} nodes, ${N.edges.length} edges; ${m.toLocaleString('en-GB')} lines placed by: ${N.law}`);
await W().blend(networkTargets(N, m)); hud(what);
say(`<b>${NETWORKS[what]}, drawn from a typed command</b>
${N.stations.length.toLocaleString('en-GB')} nodes and ${N.edges.length.toLocaleString('en-GB')} edges from ${N.source}, drawn with the wafer's own particles. Every dot is still a numbered line of code; only the law that places it changed. It charts published data; it is not a design.
<i>next:</i> draw ${Object.keys(NETWORKS).filter(k => k !== what).slice(0, 3).join(' · draw ')} · release · logo
<small>${N.attribution}</small>`);
log(`draw ${what}: drawn`); return { system: what, nodes: N.stations.length, edges: N.edges.length, placed: m };
};
cmds.underground = () => cmds.draw('underground'); cmds.tube = cmds.underground;
// ---------- CLOCK: time as a law on the same dust. The face is a ring of ticks, the hands are lines of particles
// from the centre; positions are a pure function of the clock at the moment of drawing; redrawn every 10 s while on.
let clockTimer = null;
function clockTargets(m, d){
const R = 0.85 * W().kepler().R, t = new Float32Array(m * 2); let j = 0;
const put = (x, y) => { if (j < m) { t[2 * j] = x; t[2 * j + 1] = y; j++; } };
const ring = Math.floor(m * 0.45), ticks = Math.floor(m * 0.15), hands = m - ring - ticks;
for (let i = 0; i < ring; i++) { const a = i / ring * 2 * Math.PI; put(R * Math.cos(a), R * Math.sin(a)); }
for (let i = 0; i < ticks; i++) { const h = i % 12, u = (Math.floor(i / 12) % 40) / 40, a = Math.PI / 2 - h * Math.PI / 6; const r = R * (0.86 + 0.1 * u); put(r * Math.cos(a), r * Math.sin(a)); }
const s = d.getSeconds() + d.getMilliseconds() / 1000, mi = d.getMinutes() + s / 60, h = (d.getHours() % 12) + mi / 60;
const handSpec = [[Math.PI / 2 - h * Math.PI / 6, 0.5, 0.45], [Math.PI / 2 - mi * Math.PI / 30, 0.75, 0.4], [Math.PI / 2 - s * Math.PI / 30, 0.8, 0.15]];
const total = handSpec.reduce((a, [, , w]) => a + w, 0);
for (const [a, len, w] of handSpec) { const n = Math.floor(hands * w / total); const side = 0.012 * R;
for (let i = 0; i < n; i++) { const u = i / n, off = ((i % 5) - 2) / 2 * side; put(u * len * R * Math.cos(a) - off * Math.sin(a), u * len * R * Math.sin(a) + off * Math.cos(a)); } }
while (j < m) put(R * Math.cos(j), R * Math.sin(j));
return t;
}
cmds.clock = async function(){
if (!W()) return log('the wafer is not ready');
await W().scope(null); const m = W().state().scopeN; const d = new Date();
await W().blend(clockTargets(m, d)); hud('clock'); scopeName = 'clock';
log(`clock: ${d.toTimeString().slice(0, 8)} drawn with ${m.toLocaleString('en-GB')} lines; the hands are a pure function of the time; redrawn every 10 s`);
say(`<b>a clock, drawn from a typed command</b>\n${d.toTimeString().slice(0, 8)}. The face, the twelve ticks and the three hands are the wafer's own particles; their positions are a pure function of the clock, so this drawing can be recomputed for any instant. Time is a law like any other.\n<i>next:</i> release · draw grid · logo`);
if (clockTimer) clearInterval(clockTimer);
clockTimer = setInterval(async () => { if (scopeName !== 'clock') { clearInterval(clockTimer); clockTimer = null; return; } await W().blend(clockTargets(W().state().scopeN, new Date())); }, 10000);
log('draw clock: drawn'); return { drawn: m };
};
cmds.time = cmds.clock;
Wafer Development Environment — One Wafer Page
A web page in the testcode folder of GlobalGrid2050 that converts to world (`toWorld`), calculates planar distances, draws on a canvas and reads inputs for gotoin. Published at https://globalgrid2050.com/testcode/wafer-development-environment/202609191255-one-wafer/.
renderglobalgrid2050 / testcode/wafer-development-environment/202609191255-one-wafer/index.html · lines 1–258 of 258 · version 2026-09-19 12:55 · Entry point · pattern keyAt (shared by 25 files)
- What it does
- It draws its content. Defines 18 functions or classes, including fmt, words, prog, U, tsv. Side effects: changes the web page (DOM); makes network requests.
- Why it exists in the grid workflow
- Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
- Inputs & outputs
- In: form fields (user input). Out: web page; WebGL/WebGPU drawing.
- Downstream impact
- Used directly by 5 files: GlobalGrid2050 Homepage Before Four Nests (globalgrid2050, https://globalgrid2050.com/homepage-before-four-nests-20260925.html); Homepage Versions — Before Refresh Page (globalgrid2050, https://globalgrid2050.com/homepage_versions/20260922-before-refresh/); Homepage V123 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v123.html); Homepage V124 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v124.html); and 1 more. Reached from 83 other entry points, including GlobalGrid2050 Historical Builds (globalgrid2050, https://globalgrid2050.com/historical_builds.html); Homepage V037 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v037.html); Homepage V038 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v038.html). It is itself an entry point, published at https://globalgrid2050.com/testcode/wafer-development-environment/202609191255-one-wafer/.
- What it achieves
- It is built from the tsv step (`tsv`), the resize step (`resize`) and the fly to helper (`flyTo`). Defines `fmt`, `words`, `prog` and 14 more. It responds to webglcontextlost, resize and pointerdown events.
- Why it matters
- Loaded by the GlobalGrid2050 Homepage Before Four Nests page at https://globalgrid2050.com/homepage-before-four-nests-20260925.html and 4 other pages.
- Application
- globalgrid2050 · testcode/wafer-development-environment/202609191255-one-wafer · page
- Uses
- none found
- Used by
- linked from GlobalGrid2050 Homepage Before Four Nests (link), linked from Homepage Versions — Before Refresh Page (link), linked from Homepage V123 (link), linked from Homepage V124 (link), linked from Homepage V125 (link)
- Produces
- fmt, words, prog, U, tsv, resize, flyTo, home, keyPlace, findBy, address, describe
- Defines here
- fmt, words, prog, U, tsv, resize, flyTo, home, keyPlace, findBy, address, describe, keyAt, frame, draw, toWorld, show, goKey
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/wafer-development-environment/202609191255-one-wafer/index.html:1-258 · blob 5d428a7e928e015b7da31d73f6220bc79e7be604 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, network · domain stage: experimental · users: none · canonical: production_core
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>Kuiper belt</title>
<style>
:root{--bg:#090c13;--ink:#d5dcea;--dim:#7d8799;--line:#1a2030;--hot:#e8b36a}
*{box-sizing:border-box}
html,body{margin:0;height:100%;background:var(--bg);color:var(--ink);
font:12px/1.55 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;overflow:hidden}
canvas{position:fixed;inset:0;width:100%;height:100%;display:block}
#c{z-index:1} #o{z-index:3;pointer-events:none}
#top{position:fixed;top:0;left:0;padding:10px 14px;z-index:10;pointer-events:none;max-width:60vw;background:#090c13d9;border-bottom-right-radius:6px}
#big{font-size:19px;letter-spacing:.03em} #sub{color:var(--dim);margin-top:2px}
#hud{position:fixed;top:0;right:0;padding:10px 14px;z-index:10;color:var(--dim);text-align:right;white-space:pre-line;max-width:38vw;background:#090c13d9;border-bottom-left-radius:6px}
#card{position:fixed;left:14px;bottom:64px;z-index:10;color:var(--ink);background:#090c13ee;
border:1px solid var(--line);padding:9px 12px;white-space:pre-line;display:none;max-width:min(680px,92vw)}
#card b{color:var(--hot);font-weight:600}
#foot{position:fixed;left:0;right:0;bottom:0;padding:8px 14px;color:var(--dim);border-top:1px solid var(--line);
background:#090c13ee;z-index:10;line-height:1.7}
#foot b{color:var(--ink);font-weight:600} a{color:#66ccff}
#goto{position:fixed;left:50%;top:38%;transform:translateX(-50%);z-index:20;display:none;background:var(--bg);
border:1px solid var(--dim);padding:10px 12px;min-width:min(520px,86vw)}
#goto input{width:100%;background:var(--bg);color:var(--ink);border:0;outline:0;font:14px ui-monospace,Consolas,monospace}
</style>
</head>
<body>
<canvas id="c"></canvas><canvas id="o"></canvas>
<div id="top"><div id="big">loading</div><div id="sub"> </div></div>
<div id="hud">starting</div>
<div id="card"></div>
<div id="goto"><input id="gotoin" autocomplete="off" spellcheck="false" placeholder="a key, or a repository name to send light through"></div>
<div id="foot">
<b>r</b> random line · <b>/</b> a key, or a repository to light · <b>click</b> lights the repository under the
pointer through all of time · drag · scroll · <b>backspace</b> whole wafer · one law at every zoom:
r = √key, θ = key × golden angle · dark rings are silence between commits, measured · unresolved
pixels are computed from the law, not drawn · provided as is, without warranty of any kind; a chart, not a design
· <a href="https://github.com/Ventusltd/law">the laws</a>
</div>
<script type="module">
// THE KUIPER BELT AS ONE WAFER. Every line in every file in every commit, one key each, in the
// order time issued them.
//
// THE LAW, and there is only one, at every zoom:
// key k -> r = sqrt(k), theta = 2 pi frac(k G / 2^32), G = 2654435769
// It inverts, k = r squared, so the number of keys in any annulus is arithmetic. Nothing is ever
// drawn 38,000 times into a pixel to discover a number the law already states.
//
// THE RINGS ARE TIME. Before each commit a run of keys is left UNISSUED in proportion to the
// silence since the commit before it (tools/wafer_keys.py, a declared constant). A night is a dark
// ring. The dark fraction of every pixel is computed exactly from a prefix sum of issued keys, so
// even the rings are arithmetic. A line not yet written already has its place, on the rim, the
// way an address in RAM exists before anything is stored at it.
//
// UNRESOLVED pixels state a computed count as a shade. RESOLVED fields draw exactly the issued keys
// whose radius can be on screen, each at its own place. There is no sampling and no white flash,
// because a pixel is never asked to be more than it is.
const G32 = 2654435769, TW = 4096;
const cv = document.getElementById('c'), ov = document.getElementById('o'), o2 = ov.getContext('2d');
const gl = cv.getContext('webgl2', { antialias:false, alpha:false, powerPreference:'high-performance' });
const hud = document.getElementById('hud'), big = document.getElementById('big'),
sub = document.getElementById('sub'), card = document.getElementById('card');
const fmt = n => Math.round(n).toLocaleString('en-GB');
function words(n){ if (n >= 1e9) return (n/1e9).toFixed(2)+' billion'; if (n >= 1e6) return (n/1e6).toFixed(2)+' million';
if (n >= 1e3) return (n/1e3).toFixed(1)+' thousand'; return n >= 10 ? n.toFixed(0) : n.toFixed(2); }
if (!gl) { hud.textContent = 'WebGL2 is not available. Refusing rather than drawing a fraction.'; throw 0; }
const VS_FULL = `#version 300 es
void main(){ vec2 p = vec2(float((gl_VertexID<<1)&2), float(gl_VertexID&2)); gl_Position = vec4(p*2.0-1.0,0.0,1.0); }`;
const FS_FIELD = `#version 300 es
precision highp float; precision highp sampler2D;
uniform vec2 u_res, u_center; uniform float u_zoom, u_R, u_points;
uniform sampler2D u_commits; uniform int u_n, u_litRepo;
out vec4 o;
vec4 C(int i){ return texelFetch(u_commits, ivec2(i % ${TW}, i / ${TW}), 0); } // k0, k1, issued before, repo
int find(float k){ int lo = 0, hi = u_n - 1;
for (int s = 0; s < 16; ++s){ if (lo >= hi) break; int m = (lo+hi+1)/2; if (C(m).r <= k) lo = m; else hi = m-1; } return lo; }
// how many ISSUED keys lie below address k: a prefix sum, so any annulus is one subtraction
float issuedBelow(float k){ vec4 c = C(find(k)); return c.b + clamp(k - c.r, 0.0, c.g - c.r); }
void main(){
vec2 w = u_center + (gl_FragCoord.xy - 0.5*u_res) / u_zoom;
float r = length(w), h = 0.75 / u_zoom;
vec3 bg = vec3(0.035,0.047,0.075), dust = vec3(0.79,0.83,0.90);
if (r > u_R + h) { float rim = smoothstep(2.5/u_zoom, 0.0, abs(r - u_R)); o = vec4(bg + rim*0.10, 1.0); return; }
float ka = max(r-h, 0.0), kb = r+h; ka *= ka; kb *= kb;
float cov = clamp((issuedBelow(kb) - issuedBelow(ka)) / max(kb - ka, 1.0), 0.0, 1.0); // issued share of this pixel
float perPx = cov / (3.14159265 * u_zoom * u_zoom); // issued keys in this pixel
float v = (u_points > 0.5) ? 0.0 : clamp(0.24 + 0.13*log(1.0+perPx)/2.302585, 0.0, 0.88) * pow(cov, 0.55);
vec3 col = mix(bg, dust, v);
// THE LIGHT. Which repository owns the key at the centre of this pixel. This one is a tap, not
// a count: it says where a repository's work lies in time, and no number is read off it.
if (u_litRepo >= 0) { float kc = r*r; vec4 c = C(find(kc)); if (kc <= c.g && int(c.a + 0.5) == u_litRepo)
col = mix(col, vec3(0.95,0.72,0.40), u_points > 0.5 ? 0.10 : 0.72); }
o = vec4(col, 1.0);
}`;
const VS_KEYS = `#version 300 es
precision highp float;
uniform uint u_k0lo; uniform float u_R0, u_zoom, u_hot; uniform vec2 u_center, u_res;
out float v_hot;
void main(){
float d = float(gl_VertexID);
float r = u_R0 + (d + 0.5) / (u_R0 + sqrt(u_R0*u_R0 + d + 0.5) + 1e-9); // sqrt(k0+d+.5), kept precise
uint m = (u_k0lo + uint(gl_VertexID)) * ${G32}u;
float A = 6.283185307179586 * float(m >> 16) / 65536.0, B = 6.283185307179586 * float(m & 0xFFFFu) / 4294967296.0;
vec2 cs = vec2(cos(A)*cos(B) - sin(A)*sin(B), sin(A)*cos(B) + cos(A)*sin(B));
gl_Position = vec4((r*cs - u_center) * u_zoom / (0.5*u_res), 0.0, 1.0);
gl_PointSize = clamp(u_zoom * 0.34, 1.0, 9.0); v_hot = u_hot;
}`;
const FS_KEYS = `#version 300 es
precision highp float; in float v_hot; out vec4 o;
void main(){ if (length(gl_PointCoord-0.5) > 0.5) discard;
o = vec4(mix(vec3(0.79,0.83,0.90), vec3(0.97,0.74,0.40), v_hot), 1.0); }`;
function prog(vs, fs){ const p = gl.createProgram();
for (const [t,s] of [[gl.VERTEX_SHADER,vs],[gl.FRAGMENT_SHADER,fs]]) { const sh = gl.createShader(t);
gl.shaderSource(sh,s); gl.compileShader(sh);
if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(sh)); gl.attachShader(p,sh); }
gl.linkProgram(p); if (!gl.getProgramParameter(p, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(p)); return p; }
const PF = prog(VS_FULL, FS_FIELD), PK = prog(VS_KEYS, FS_KEYS);
const U = (p, n) => gl.getUniformLocation(p, n);
gl.bindVertexArray(gl.createVertexArray());
let lost = false;
cv.addEventListener('webglcontextlost', e => { e.preventDefault(); lost = true;
hud.textContent = 'CONTEXT LOST. Nothing on screen is a count. Reload.'; });
// --------------------------------------------------------------------------------- the data
// cosmos/wafer.tsv: every commit in time order with its measured lines and the unissued keys
// before it. One file, about 400 kB, and then nothing else is ever fetched to draw the whole.
let N = 0, SPACE = 0, repos = [], commits = [];
async function tsv(url){ const r = await fetch(url); if (!r.ok) throw new Error(url);
return (await r.text()).split('\n').filter(l => l && l[0] !== '#').map(l => l.split('\t')); }
Promise.all([tsv('cosmos/repos.tsv'), tsv('cosmos/wafer.tsv')]).then(([rr, ww]) => {
repos = rr.map(p => ({ i:+p[0], name:p[1], lines:+p[2], seen:0, commits:0 }));
let k = 0, issued = 0;
commits = ww.map(p => { k += +p[4]; const c = { unix:+p[0], lines:+p[1], repo:+p[2], sha:p[3], gap:+p[4], k0:k, cum:issued };
k += c.lines; issued += c.lines; c.k1 = k; repos[c.repo].seen += c.lines; repos[c.repo].commits++; return c; });
const bad = repos.find(r => r.seen !== r.lines);
if (bad) { hud.textContent = 'REFUSED: the commits of ' + bad.name + ' sum to ' + fmt(bad.seen) + ', the belt says ' + fmt(bad.lines); return; }
N = issued; SPACE = k;
const H = Math.ceil(commits.length / TW), a = new Float32Array(TW * H * 4);
commits.forEach((c, i) => { a[i*4] = c.k0; a[i*4+1] = c.k1; a[i*4+2] = c.cum; a[i*4+3] = c.repo; });
gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, gl.createTexture());
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, TW, H, 0, gl.RGBA, gl.FLOAT, a);
big.textContent = words(N) + ' lines · one wafer';
sub.textContent = fmt(N) + ' keys issued, one per line in every file in every commit · ' + fmt(commits.length) + ' commits in '
+ repos.length + ' repositories, in the order time issued them · ' + words(SPACE - N) + ' keys left unissued as silence · '
+ new Date(commits[0].unix*1000).toISOString().slice(0,10) + ' at the centre, ' + new Date(commits[commits.length-1].unix*1000).toISOString().slice(0,10)
+ ' at the rim, and the next line ever written lands beyond it';
home(); dirty = true;
}).catch(() => { hud.textContent = 'cosmos/wafer.tsv did not load. The wafer will not invent its keys.'; });
// ------------------------------------------------------------------------ camera and address
let cx = 0, cy = 0, zoom = 1, dirty = true, tween = null, litRepo = -1, target = null;
function resize(){ cv.width = ov.width = innerWidth; cv.height = ov.height = innerHeight; gl.viewport(0,0,cv.width,cv.height); dirty = true; }
addEventListener('resize', resize); resize();
function flyTo(x, y, z){ tween = { t0:performance.now(), x0:cx, y0:cy, z0:zoom, x1:x, y1:y, z1:z, dur:900 }; }
function home(){ flyTo(0, 0, (Math.min(cv.width, cv.height)/2) * 0.9 / Math.sqrt(SPACE)); }
function keyPlace(k){ const m = Math.imul((k % 4294967296) >>> 0, G32) >>> 0, th = 2*Math.PI*m/4294967296, r = Math.sqrt(k + 0.5);
return [r*Math.cos(th), r*Math.sin(th)]; }
function findBy(field, v){ let lo = 0, hi = commits.length - 1; while (lo < hi) { const m = (lo+hi+1)>>1; if (commits[m][field] <= v) lo = m; else hi = m-1; } return lo; }
// an address key resolves to a commit by binary search; no walking, and silence is an answer too
function address(k){ if (!(k >= 0) || k >= SPACE) return null; const i = findBy('k0', k), c = commits[i];
return (k >= c.k0 && k < c.k1) ? { k, i, c, m:k - c.k0 } : { k, i, c, silent:true, next:commits[i + (k < c.k0 ? 0 : 1)] }; }
function describe(a){
if (!a) return '';
if (a.silent) { const n = a.next; return 'key <b>' + fmt(a.k) + '</b> was never issued\nsilence' + (n ? ' of ' + words((n.gap/ (n.gap ? 1 : 1))) + ' keys before ' + repos[n.repo].name + ' / ' + n.sha + ', '
+ new Date(n.unix*1000).toISOString().slice(0,16) + 'Z' : ''); }
const r = repos[a.c.repo];
return 'key <b>' + fmt(a.k) + '</b> · line ' + fmt(a.c.cum + a.m + 1) + ' of ' + fmt(N) + ' ever issued\n' + r.name + ' (' + words(r.lines) + ' lines in ' + fmt(r.commits) + ' commits)'
+ '\ncommit <b>' + a.c.sha + '</b> ' + new Date(a.c.unix*1000).toISOString().slice(0,16) + 'Z · line ' + fmt(a.m + 1) + ' of ' + fmt(a.c.lines)
+ '\nthe text itself: python tools/key.py ' + a.k;
}
function keyAt(wx, wy){ const r = Math.hypot(wx, wy), kc = Math.round(r*r), span = Math.ceil(6*r + 8); let best = -1, bd = 0.6;
for (let k = Math.max(0, kc - span); k <= Math.min(SPACE-1, kc + span); k++) { const p = keyPlace(k), d = Math.hypot(p[0]-wx, p[1]-wy); if (d < bd) { bd = d; best = k; } }
return best; }
// --------------------------------------------------------------------------------- the frame
const POINTS_FROM = 1.0, MAX_CALLS = 3000;
function frame(){
if (lost) return;
if (tween) { const u = Math.min(1, (performance.now()-tween.t0)/tween.dur), e = u<0.5 ? 2*u*u : 1-Math.pow(-2*u+2,2)/2;
zoom = Math.exp(Math.log(tween.z0) + (Math.log(tween.z1)-Math.log(tween.z0))*e);
cx = tween.x0 + (tween.x1-tween.x0)*e; cy = tween.y0 + (tween.y1-tween.y0)*e; dirty = true; if (u >= 1) tween = null; }
if (dirty && N) { draw(); dirty = false; }
requestAnimationFrame(frame);
}
function draw(){
const R = Math.sqrt(SPACE), W = cv.width, H = cv.height;
const x0 = cx - W/2/zoom, x1 = cx + W/2/zoom, y0 = cy - H/2/zoom, y1 = cy + H/2/zoom;
const dx = x0 > 0 ? x0 : (x1 < 0 ? -x1 : 0), dy = y0 > 0 ? y0 : (y1 < 0 ? -y1 : 0);
const rmin = Math.hypot(dx, dy), rmax = Math.max(Math.hypot(x0,y0), Math.hypot(x1,y0), Math.hypot(x0,y1), Math.hypot(x1,y1));
const ka = Math.min(SPACE, Math.floor(rmin*rmin)), kb = Math.min(SPACE, Math.ceil(rmax*rmax));
// the screen's radii are a contiguous run of addresses; the issued ones among them are whole commits and two part commits
let i0 = findBy('k0', ka), segs = [], total = 0;
if (zoom >= POINTS_FROM) for (let i = i0; i < commits.length && commits[i].k0 < kb && segs.length <= MAX_CALLS; i++) {
const s0 = Math.max(commits[i].k0, ka), s1 = Math.min(commits[i].k1, kb); if (s1 > s0) { segs.push([s0, s1, commits[i].repo]); total += s1 - s0; } }
const points = zoom >= POINTS_FROM && segs.length <= MAX_CALLS && total < 1.6e9;
gl.useProgram(PF);
gl.uniform2f(U(PF,'u_res'), W, H); gl.uniform2f(U(PF,'u_center'), cx, cy); gl.uniform1f(U(PF,'u_zoom'), zoom);
gl.uniform1f(U(PF,'u_R'), R); gl.uniform1f(U(PF,'u_points'), points ? 1 : 0);
gl.uniform1i(U(PF,'u_commits'), 0); gl.uniform1i(U(PF,'u_n'), commits.length); gl.uniform1i(U(PF,'u_litRepo'), litRepo);
gl.drawArrays(gl.TRIANGLES, 0, 3);
let ms = 0;
if (points) { const t0 = performance.now(); gl.useProgram(PK);
gl.uniform1f(U(PK,'u_zoom'), zoom); gl.uniform2f(U(PK,'u_center'), cx, cy); gl.uniform2f(U(PK,'u_res'), W, H);
for (const [s0, s1, rp] of segs) { gl.uniform1f(U(PK,'u_hot'), rp === litRepo ? 1 : 0);
for (let off = s0; off < s1; off += 4000000) { // bounded calls; the driver watchdog is real
gl.uniform1ui(U(PK,'u_k0lo'), (off % 4294967296) >>> 0); gl.uniform1f(U(PK,'u_R0'), Math.sqrt(off));
gl.drawArrays(gl.POINTS, 0, Math.min(4000000, s1 - off)); } }
gl.finish(); ms = performance.now() - t0; }
const L = [];
L.push(points ? 'RESOLVED · every issued key whose radius is in the field, drawn at its own place'
: 'UNRESOLVED · up to ' + words(1/(Math.PI*zoom*zoom)) + ' keys to a pixel · each pixel’s issued count is computed from the law, not drawn');
if (points) L.push(fmt(total) + ' issued keys from ' + fmt(segs.length) + ' commits passed to the GPU in ' + ms.toFixed(0) + ' ms');
L.push('the whole · ' + fmt(N) + ' issued + ' + fmt(SPACE - N) + ' silent = ' + fmt(SPACE) + ' addresses');
if (litRepo >= 0) L.push('LIGHT · ' + repos[litRepo].name + ' · ' + words(repos[litRepo].lines) + ' lines in ' + fmt(repos[litRepo].commits) + ' commits, wherever in time they fall');
L.push(zoom >= 1 ? 'zoom ' + zoom.toFixed(1) + ' px per key spacing' : 'zoom 1 px = ' + words(1/zoom) + ' units');
hud.textContent = L.join('\n');
o2.clearRect(0,0,ov.width,ov.height);
if (target) { const x = (target.x - cx)*zoom + ov.width/2, y = ov.height/2 - (target.y - cy)*zoom;
o2.strokeStyle = 'rgba(232,179,106,.95)'; o2.lineWidth = 1; o2.beginPath();
for (const [a,b,c,d] of [[-16,0,-6,0],[6,0,16,0],[0,-16,0,-6],[0,6,0,16]]) { o2.moveTo(x+a,y+b); o2.lineTo(x+c,y+d); } o2.stroke(); }
}
// ------------------------------------------------------------------------------ the controls
function toWorld(px, py){ return [cx + (px - innerWidth/2)/zoom, cy - (py - innerHeight/2)/zoom]; }
function show(a){ card.style.display = 'block'; card.innerHTML = describe(a); if (a && !a.silent) litRepo = a.c.repo; dirty = true; }
function goKey(k){ const p = keyPlace(k); target = { x:p[0], y:p[1] }; show(address(k)); flyTo(p[0], p[1], 14); }
let drag = null, moved = 0;
cv.addEventListener('pointerdown', e => { drag = [e.clientX, e.clientY]; moved = 0; });
addEventListener('pointerup', e => {
if (drag && moved < 4 && N) { const [wx, wy] = toWorld(e.clientX, e.clientY), r = Math.hypot(wx, wy);
if (r*r < SPACE) { let k = zoom >= POINTS_FROM ? keyAt(wx, wy) : -1; const exact = k >= 0; if (!exact) k = Math.floor(r*r);
target = exact ? { x:keyPlace(k)[0], y:keyPlace(k)[1] } : null; show(address(k)); } }
drag = null; });
addEventListener('pointermove', e => { if (!drag) return; moved += Math.abs(e.clientX-drag[0]) + Math.abs(e.clientY-drag[1]);
cx -= (e.clientX-drag[0])/zoom; cy += (e.clientY-drag[1])/zoom; drag = [e.clientX, e.clientY]; tween = null; dirty = true; });
addEventListener('wheel', e => { const [wx, wy] = toWorld(e.clientX, e.clientY), f = e.deltaY < 0 ? 1.18 : 1/1.18;
zoom = Math.max(1e-4, Math.min(60, zoom*f)); cx = wx - (e.clientX - innerWidth/2)/zoom; cy = wy + (e.clientY - innerHeight/2)/zoom;
tween = null; dirty = true; }, { passive:true });
const gbox = document.getElementById('goto'), gin = document.getElementById('gotoin');
gin.addEventListener('keydown', e => { e.stopPropagation(); if (e.key === 'Escape') { gbox.style.display = 'none'; return; }
if (e.key !== 'Enter') return; gbox.style.display = 'none'; const raw = gin.value.trim(), q = raw.replace(/[ ,_]/g,'');
if (/^\d+$/.test(q)) goKey(Math.min(SPACE-1, Number(q)));
else { const r = repos.find(x => x.name.toLowerCase() === raw.toLowerCase()) || repos.find(x => x.name.toLowerCase().includes(raw.toLowerCase()));
if (r) { litRepo = r.i; target = null; card.style.display = 'none'; home(); dirty = true; } } });
addEventListener('keydown', e => { if (gbox.style.display === 'block') return;
if (e.key === 'r' && N) { const j = Math.floor(Math.random()*N), c = commits[findBy('cum', j)]; goKey(c.k0 + (j - c.cum)); } // uniform over issued lines
else if (e.key === '/') { e.preventDefault(); gbox.style.display = 'block'; gin.value = ''; gin.focus(); }
else if (e.key === 'Backspace') { e.preventDefault(); target = null; litRepo = -1; card.style.display = 'none'; home(); } });
requestAnimationFrame(frame);
</script>
</body>
</html>