In this section
- Kuiper Programs render · globalgrid2050 / kuiper-grid/i0083/cartridges/007600000000-kuiper-programs.js lines 1284–1983
Kuiper Programs
A JavaScript module in the cartridges folder of GlobalGrid2050 covering cables, solar, substations and transformers, using SHA-256, and uses data from the faraday repository.
renderglobalgrid2050 / kuiper-grid/i0083/cartridges/007600000000-kuiper-programs.js · lines 1284–1983 of 2835 (continued from section 1337) · Not reached from any entry point (candidate for review) · pattern stringClampMicro (shared by 18 files)
- What it does
- It draws cables, solar, substations and transformers. Defines 177 functions or classes, including reFire, closestPair, blackSky, nameInLines, makeBody. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
- 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: cables, solar, substations, transformers, 400kV.
- Inputs & outputs
- In: data source: faraday data; JSON file current.json. Out: canvas drawing. Voltage levels named: 400kV.
- What it achieves
- It makes body (`makeBody`), sets tag (`setTag`) and merges menu (`mergeMenu`). A cartridge of the Kuiper shell. Its code works with 400 kV, 50 kW and 500 kW. It responds to click, keydown and pointerdown events.
- Why it matters
- No other file in the estate was found to import it.
- Application
- globalgrid2050 · kuiper-grid/i0083/cartridges · JavaScript module
- Uses
- Faraday — Index Page (estate URL), Wafer Development Environment — Proof S0004 Page (estate URL), ./fire.js
- Used by
- mentioned in Standalone (comment link)
- Produces
- reFire, closestPair, blackSky, nameInLines, makeBody, bodyTo, labels, bodyJump, bodyMove, bodyDrawnDiameter, bodyDotPx, sheet
- Defines here
- runsHere, fill, shownList, refresh, drawChips, findByCommand, runIt, openApps, stop, c0, boxValues, makeBoxes, el, cmd, goNow, later, take, fireCommand, el, bold, open, label, table, restBits, sldNetwork, sldPieces, line, ring, sldLayout, SYMBOL
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 kuiper-grid/i0083/cartridges/007600000000-kuiper-programs.js:1284-1983 · blob 42b8f1f46705bb79b8353fdd093469fddca73144 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
// is there, and the name is read off the command itself when it is not.
function runsHere(c){
try { if (window.FIRE && window.FIRE.parse) return FIRE_DRAWS.includes(window.FIRE.parse(c.command).name); } catch (_) {}
const m = /^fire\s+([a-z][a-z-]*)/i.exec(String((c && c.command) || ''));
return !!m && FIRE_DRAWS.includes(m[1].toLowerCase());
}
let ALL = STRING_TESTS.concat(dedupeCommands(FIRE_FALLBACK.filter(runsHere))), PINS = STRING_TESTS.concat(curateCommands(ALL.slice(STRING_TESTS.length), PICKER_SHOWN));
let SAID = 'the few tests kept inside this page are listed while the published list is read';
const fill = list => { egs.replaceChildren(new Option(list.length ? '— choose an example sentence —' : '— nothing matches —', ''));
for (const c of list) { const o = new Option(plainName(c), c.command); o.title = c.sentence || ''; egs.append(o); } };
const shownList = () => { const q = pin.value.trim();
if (!q || /^fire\s+\S/i.test(q)) return PINS.slice(0, PICKER_SHOWN);
return dedupeCommands(searchCommands(ALL, q)).slice(0, PICKER_SHOWN); };
const refresh = () => { fill(shownList()); };
const drawChips = () => { chips.replaceChildren();
for (const c of PINS.slice(0, CHIPS_SHOWN)) { const b = document.createElement('button'); b.type = 'button';
b.textContent = chipWords(c); b.title = c.sentence || plainName(c);
b.addEventListener('click', e => { e.stopPropagation(); runIt(c); }); chips.append(b); }
const a = document.createElement('button'); a.type = 'button'; a.textContent = 'apps'; a.id = 'chipapps';
a.addEventListener('click', e => { e.stopPropagation(); openApps(); }); chips.append(a); };
function findByCommand(cmd){ return ALL.find(c => c.command === cmd) || PINS.find(c => c.command === cmd) || null; }
// CHOOSING A PRESET FIRES IT, AND THE BAR KEEPS ITS NAME, NOT ITS JSON.
function runIt(c){ const cmd = typeof c === 'string' ? c : c.command;
const rec = typeof c === 'string' ? findByCommand(cmd) : c;
pin.value = rec ? plainName(rec) : '';
fireCommand(cmd, rec);
}
closeFireMenu = () => { egs.selectedIndex = 0; };
fireAgain = runIt; // a window may ask for its preset back
function openApps(){
const wrap = [];
const h = document.createElement('p'); h.innerHTML = '<b>The applications</b>'; wrap.push(h);
if (appsEl) wrap.push(appsEl);
const p2 = document.createElement('p'); p2.innerHTML = '<b>The view</b>'; wrap.push(p2, viewRow);
const note = document.createElement('p'); note.className = 'dimtext'; note.textContent = SAID; wrap.push(note);
showSay('apps', wrap);
}
loadFireConfig(FIRE_CONFIG).then(r => {
if (r.ok) {
const listed = dedupeCommands(r.commands.filter(runsHere));
if (listed.length) {
const dropped = r.commands.filter(runsHere).length - listed.length;
ALL = STRING_TESTS.concat(listed);
const pinned = listed.filter(c => typeof c.pin === 'number').sort((a, b) => a.pin - b.pin);
PINS = STRING_TESTS.concat(pinned.length ? pinned : curateCommands(listed, PICKER_SHOWN));
SAID = listed.length + ' tests, list ' + r.generation + ', fetched with no cache and hashed here'
+ (dropped ? '; ' + dropped + ' repeats of another test left out' : '');
} else SAID = 'the published list holds nothing this device can run, so the few kept in this page are listed';
} else SAID = 'the published list was not used (' + r.reason + '), so the few kept in this page are listed';
drawChips(); refresh();
}).catch(e => { SAID = 'the published list was not used (' + (e && e.message ? e.message : e) + '), so the few kept in this page are listed';
drawChips(); refresh(); });
drawChips(); refresh();
// KEYS TYPED IN THE BAR STAY IN THE BAR, and a press inside the window never reaches the disc behind
// it. Escape is not a key they keep: it closes the window and hands the keyboard back.
const stop = e => {
if (e.type === 'keydown' && e.key === 'Escape') { e.stopPropagation(); shutSay(); pin.blur(); return; }
e.stopPropagation();
};
for (const x of [pin, eg, chips, sayEl]) for (const ev of ['keydown', 'keyup', 'keypress', 'pointerdown', 'mousedown', 'touchstart', 'wheel', 'click']) x.addEventListener(ev, stop);
egs.addEventListener('change', e => { const v = e.target.value; if (v) runIt(v); e.target.selectedIndex = 0; });
pin.addEventListener('input', refresh);
pin.addEventListener('keydown', e => {
if (e.key === 'Escape') { shutSay(); pin.blur(); return; }
if (e.key !== 'Enter') return;
const q = pin.value.trim(); if (!q) return;
if (/^fire\s+\S/i.test(q)) { fireCommand(q, findByCommand(q)); return; }
if (/^apps?$/i.test(q)) { openApps(); return; }
// THE TWO VIEWS ARE TWO WORDS. Typing "macro" or "micro" moves the camera of a drawing already on
// the screen and changes nothing else; if no string is drawn, the word fires one and it opens there.
if (/^macro$/i.test(q) || /^micro$/i.test(q)) { const want = q.toLowerCase();
pin.value = '';
if (typeof sldShapes !== 'undefined' && sldShapes && sldShapes.g) {
try { sldShapes.g.c.view = want; if (want === 'macro') stringWholeView(); else stringNearView(); } catch (_) {}
return; }
fireCommand('fire string {"view":"' + want + '"}', null); return; }
if (/^help$/i.test(q)) { const p = document.createElement('p');
p.innerHTML = '<b>How this bar works</b>'; const q2 = document.createElement('p'); q2.className = 'dimtext';
q2.textContent = 'Type what you want to see in plain words - "tree of 12", "on its export limit", "the most solar that fits" - and press Enter: the first test that matches runs here, on your device, and the dots draw its network. Or pick one from the examples above. Type "apps" for the applications. Every command can be typed in full; press "show the command" in any answer to see and change … [line shortened here: 419 characters; full line on GitHub]
showSay('help', [p, q2]); return; }
const first = shownList()[0];
if (first) runIt(first);
else { const p = document.createElement('p'); p.innerHTML = '<b>Nothing matches</b>';
const d = document.createElement('p'); d.className = 'dimtext';
d.textContent = 'No test in the published list has all of those words in it. Try fewer words, or a shape: chain, star, tree, sub-board.';
showSay('nothing matches', [p, d]); }
});
addEventListener('keydown', e => { if (e.key === 'Escape' && sayEl.classList.contains('open')) { e.preventDefault(); shutSay(); pin.blur(); } });
if (typeof layout === 'function') layout();
// ?fire=<command> still runs a command on arrival: every firing is a link
try { const q = new URLSearchParams(location.search).get('fire'); if (q) setTimeout(() => fireCommand(/^fire\s/i.test(q) ? q : 'fire ' + q), 600); } catch (_) {}
}
// SOMETHING IS ON THE SCREEN AT ONCE. The bar is built as soon as this file runs, not after the whole
// record has arrived, so a visitor on a slow line has the bar and the chips while the megabyte loads.
if (document.readyState === 'loading') addEventListener('DOMContentLoaded', () => { try { makeFireBar(); } catch (e) { console.error('the bar was not built: ' + (e && e.stack ? e.stack : e)); } });
else { try { makeFireBar(); } catch (e) { console.error('the bar was not built: ' + (e && e.stack ? e.stack : e)); } }
let lastFire = null;
const c0 = text => { try { return window.FIRE.parse(text).inputs; } catch (_) { return {}; } };
// THE FIGURES A READER ACTUALLY WANTS, in the order an engineer would read them out. Everything else is
// behind MORE: the card used to be a table of fourteen rows and a paragraph, which is a page, not an answer.
const CARD_FIRST = ['connection point kw', 'lowest volts pu', 'highest volts pu', 'worst transformer pct', 'busiest cable amps',
'p poc kw', 'worst tx pct', 'export limit kw'];
// ===== THE INPUTS AS BOXES ======================================================================
// A COMMAND IS A SENTENCE UNTIL SOMEBODY WANTS TO TRY A DIFFERENT NUMBER, and then it has to be a set
// of boxes. Every command declares its own inputs (key, label, unit, kind, min, max, step, choices) and
// the window builds one labelled box for each: a number box with its range and its step, or a small
// list for a choice. Changing a box FIRES THE COMMAND AGAIN at once - a third of a second after the
// last keystroke, or straight away on Enter - and the sentence, the figures and the drawing all move
// together, IN PLACE: the work does not fly home and gather again for a changed decimal.
// A box that is empty or outside its range is refused QUIETLY: the last good value is kept, the box is
// marked, and nothing is thrown. Presets still fill every box and fire; after an edit the bar carries
// the preset's plain name with "(changed)" after it, never the command itself, and one press puts the
// preset back. The command in full stays under "more", and it always says what the boxes now say, so
// it can be copied, shared and pasted back into the bar.
function boxValues(out){
const v = {};
for (const b of (out.boxes || [])) {
let x = (out.inputs_used && out.inputs_used[b.key] !== undefined && out.inputs_used[b.key] !== null)
? out.inputs_used[b.key] : (out.inputs ? out.inputs[b.key] : undefined);
if (x !== undefined && x !== null) v[b.key] = x; else if (b.optional) v[b.key] = null;
}
return v;
}
function makeBoxes(out, rec){
const el = (tag, cls, t) => { const e = document.createElement(tag); if (cls) e.className = cls; if (t !== undefined) e.textContent = t; return e; };
const vals = boxValues(out), wrap = el('div', 'boxes');
let timer = 0;
const cmd = () => 'fire ' + out.name + ' ' + JSON.stringify(vals);
const goNow = () => { clearTimeout(timer);
const bar = document.getElementById('pin');
if (bar) bar.value = (rec ? plainName(rec) : out.family) + ' (changed)';
fireCommand(cmd(), rec, true); };
const later = () => { clearTimeout(timer); timer = setTimeout(goNow, 300); };
for (const spec of out.boxes) {
// A BOX MAY BE EMPTY ON PURPOSE. Some inputs have no honest default; the box is shown, blank, with a
// hint of what a sensible figure looks like, and the model refuses the figures that depend on it
// rather than guessing one. That refusal is part of the protocol, not a gap in it.
const empty = vals[spec.key] === undefined || vals[spec.key] === null;
if (empty && !spec.optional) continue;
const id = 'box-' + out.name + '-' + spec.key;
const row = el('div', 'boxrow'), lab = el('label', 'boxlab', spec.label + (spec.unit ? ' (' + spec.unit + ')' : ''));
lab.htmlFor = id;
let inp;
if (spec.kind === 'choice') {
inp = document.createElement('select');
for (const c of spec.choices) inp.append(new Option(c[1], String(c[0])));
inp.value = String(vals[spec.key]);
inp.addEventListener('change', () => { const hit = spec.choices.find(c => String(c[0]) === inp.value);
if (!hit) return; vals[spec.key] = hit[0]; goNow(); });
} else {
inp = document.createElement('input'); inp.type = 'number'; inp.inputMode = 'decimal';
if (spec.min !== undefined) inp.min = spec.min;
if (spec.max !== undefined) inp.max = spec.max;
if (spec.step !== undefined) inp.step = spec.step;
inp.value = empty ? '' : String(vals[spec.key]);
if (spec.hint) { inp.placeholder = spec.hint; inp.title = spec.hint; }
let good = empty ? null : vals[spec.key];
const take = () => { const n = Number(inp.value);
if (String(inp.value).trim() === '' && spec.optional) { inp.classList.remove('bad'); good = null; delete vals[spec.key]; return true; }
if (String(inp.value).trim() === '' || !isFinite(n)
|| (spec.min !== undefined && n < spec.min) || (spec.max !== undefined && n > spec.max)) {
inp.classList.add('bad'); return false; }
inp.classList.remove('bad'); good = n; vals[spec.key] = n; return true; };
inp.addEventListener('input', () => { if (take()) later(); });
inp.addEventListener('keydown', e => { if (e.key === 'Enter') { e.preventDefault(); if (take()) goNow(); } });
inp.addEventListener('blur', () => { if (inp.classList.contains('bad')) { inp.value = good === null ? '' : String(good); inp.classList.remove('bad'); } });
}
inp.id = id; row.append(lab, inp); wrap.append(row);
}
if (rec) { const back = el('button', 'edit', 'back to the preset'); back.type = 'button';
back.addEventListener('click', e => { e.stopPropagation(); if (fireAgain) fireAgain(rec); });
wrap.append(back); }
return { wrap, vals, cmd };
}
function fireCommand(text, rec, inPlace){
if (closeFireMenu) { try { closeFireMenu(); } catch (_) {} }
const F = (typeof window !== 'undefined' && window.FIRE) || null;
const el = (tag, cls, t) => { const e = document.createElement(tag); if (cls) e.className = cls; if (t !== undefined) e.textContent = t; return e; };
const bold = t => { const p = document.createElement('p'); const b = document.createElement('b'); b.textContent = t; p.append(b); return p; };
const open = (title, nodes) => { if (sayOpen) sayOpen(title, nodes, true); };
let out;
try { if (!F) throw new Error('the commands did not load'); out = F.fire(text); }
catch (e) { open('not run', [bold('Not run'), el('p', 'dimtext', String(e.message || e))]);
lastFire = { ran:false, error:String(e.message || e) }; return lastFire; }
if (!out.ran) { open('not run', [bold('Not run'),
el('p', 'dimtext', 'No command called "' + out.name + '" runs here yet. These do: ' + F.names.join(', ') + '.')]);
lastFire = { ran:false, name:out.name }; return lastFire; }
const title = rec ? plainName(rec) : out.family;
const rows = [];
for (const [k, v] of Object.entries(out.numbers)) { if (v && typeof v === 'object') for (const [k2, v2] of Object.entries(v)) rows.push([k + ' ' + k2, v2]); else rows.push([k, v]); }
const label = k => k.replace(/_/g, ' ');
const lead = [], rest = [];
for (const r of rows) (CARD_FIRST.includes(label(r[0])) ? lead : rest).push(r);
while (lead.length < 4 && rest.length) lead.push(rest.shift());
const table = list => { const tb = document.createElement('table');
for (const [k, v] of list) { const tr = document.createElement('tr');
tr.append(el('td', null, label(k)), el('td', null, v === null ? 'none' : String(v))); tb.append(tr); }
return tb; };
const restBits = () => { const bits = [table(lead.slice(4).concat(rest)), el('p', 'dimtext', 'How: ' + out.how),
el('p', 'dimtext', 'The command that ran:'), el('code', null, text)];
const edit = el('button', 'edit', 'put this command in the bar, to change a number and fire it again'); edit.type = 'button';
edit.addEventListener('click', () => { const b = document.getElementById('pin'); if (b) { b.value = text; b.focus(); } });
bits.push(edit, el('p', 'dimtext', 'Every input is a public estimate. It runs here and nothing you type leaves this device. An estimate, not a study; provided as is, without warranty of any kind.'));
return bits; };
// A CHANGED BOX DOES NOT REBUILD THE WINDOW. What the reader is typing in stays exactly where it is,
// with the caret still in it; only the sentence, the figures and the working are written again.
if (inPlace && fireLive && fireLive.name === out.name && fireLive.said && fireLive.said.isConnected) {
fireLive.said.textContent = out.said;
fireLive.leadBox.replaceChildren(table(lead.slice(0, 4)));
if (fireLive.order) fireLive.order.textContent = out.electrical_order ? 'Electrical order: ' + out.electrical_order : '';
fireLive.hidden.replaceChildren(...restBits());
} else {
const nodes = [];
if (out.family === 'STRINGS' || out.family === 'FARM') { const d2 = el('p', 'danger', DEV_WARNING); nodes.push(d2); }
nodes.push(bold(title), el('p', null, out.said));
const saidP = nodes[1];
const leadBox = el('div'); leadBox.append(table(lead.slice(0, 4))); nodes.push(leadBox);
const hidden = el('div'); hidden.style.display = 'none'; hidden.append(...restBits());
const more = el('button', 'more', 'more, and show the command'); more.type = 'button';
more.addEventListener('click', () => { const on = hidden.style.display === 'none';
hidden.style.display = on ? 'block' : 'none'; more.textContent = on ? 'less' : 'more, and show the command'; });
// A ROW OF THIRTY MODULES IS WIDER THAN ANY SCREEN. Two presses: the near end, where the inverter and
// the first modules can be read, and the whole row, which is every one of the thirty at once.
if (out.name === 'string') { const row = el('div', 'viewrow');
for (const [words, go] of [['macro: the whole string', () => stringWholeView()], ['micro: M1-M4', () => stringNearView()],
['the modules to scale', () => reFire({ view:'scale' })], ['back to the wiring', () => reFire({ view:'macro' })]]) {
const b = el('button', null, words); b.type = 'button';
b.addEventListener('click', e => { e.stopPropagation(); try { go(); } catch (_) {} }); row.append(b); }
nodes.push(row);
// THE CONNECTION LIST IN WORDS, beside the picture: every hop from the inverter's minus terminal
// round to its plus, in the order the current runs. Touch a line and that one cable lights up.
if (out.connections) { const list = el('div', 'conns');
for (const q of out.connections) { const b2 = el('button', null,
q.from + ' \u2192 ' + q.to + (q.home ? ' (' + q.metres + ' m of site cable)'
: ' (' + q.needed.toFixed(2) + ' m needed, ' + q.pair.toFixed(2) + ' m of lead'
+ (q.reaches ? '' : q.jumper ? ', ' + q.jumper.toFixed(2) + ' m jumper' : ', DOES NOT REACH') + ')'));
b2.type = 'button'; if (!q.reaches && !q.jumper) b2.className = 'bad';
b2.addEventListener('click', e => { e.stopPropagation();
shapeHover = q.node; if (sldShapes) sldShapes.saying = q.from + ' to ' + q.to; dirty = true;
try { placeSldNames(); } catch (_) {} });
list.append(b2); }
nodes.push(el('p', 'dimtext', 'Every connection, in the order the current runs:'), list); } }
const orderP = el('p', 'dimtext', out.electrical_order ? 'Electrical order: ' + out.electrical_order : '');
nodes.push(orderP);
let boxes = null;
if (out.boxes && out.boxes.length) { boxes = makeBoxes(out, rec); nodes.push(boxes.wrap); }
nodes.push(more, hidden);
open(title, nodes);
fireLive = { name:out.name, said:saidP, leadBox, hidden, order:orderP, boxes, rec };
}
lastFire = { ran:true, name:out.name, family:out.family, numbers:out.numbers };
try { const fp = FIRE_PROGRAM;
if (out.name === 'site-pulse' || out.name === 'network' || out.name === 'string') {
fp.sld = out.name === 'string' ? { kind:'string', g:out.string } : out.name === 'network' ? { kind:'network', net:out.net, solved:out.solved, inputs:c0(text) } : c0(text);
// THE WORK DOES NOT FLY HOME FOR A CHANGED DECIMAL. The same dots are given the new places at once,
// the camera is left exactly where the reader put it, and the front runs again over the new drawing.
// THE ISOLATE HOLDS ITS OWN COPY OF THE PROGRAM, so the new drawing has to be put there too or
// the dots would be laid out along the drawing before the change.
if (iso && iso.prog) iso.prog.sld = fp.sld;
const live = inPlace && iso && body && body.sld && sldNow && !bodyAnim && ASM;
let moved = false;
if (live) { const nb = makeSldBody(iso);
if (nb) { body = nb; body.shown = true; body.k = 0; body.gap = body.states[0].gap;
body.pos.set(body.states[0].to); bodyTo(body.pos); bodyAnim = null;
sldNow.t0 = 0; sldNow.placed = true; if (sldShapes) sldShapes.opened = true;
sldStart(); dirty = true; moved = true; } }
if (!moved) { if (typeof unisolate === 'function' && iso) unisolate(true);
programs.push(fp); try { isolate('fire'); } finally { const at = programs.indexOf(fp); if (at >= 0) programs.splice(at, 1); } } }
else if (programs.find(p => p.name === 'tests')) isolate('tests'); } catch (e) { console.warn('fire: the dots did not respond', e); }
return lastFire;
}
// ===== THE SINGLE LINE DIAGRAM, DRAWN BY THE DOTS ================================================
// A site pulse has a real network: grid, connection point, intake cable, busbar, generator, feeders, transformers, loads, solar.
// The lines of the repository that holds the tests leave their places and BECOME that diagram: one dot a line of code, placed along
// the busbar, the feeders and the transformer rings. Then the two pulses of the method run on it: currents summed back to the
// grid, volts out from it; what is over a limit ends amber; what is disconnected ends dark. The engine computes (FIRE.sitePulse.solve);
// the dots show and switch. Values ride in a uniform array read by dot number, so the shell's one draw call is unchanged.
const SLD_MAX = 896; // 224 four-number uniforms: inside what every WebGL 2 device must offer
let sldNow = null, sldLoop = 0;
function sldNetwork(inputs){
const SP = window.FIRE && window.FIRE.sitePulse; if (!SP) return null;
const sc = SP.SCENARIOS[inputs.scenario]; if (!sc) return null;
const site = inputs.site || SP.standardSite(), share = inputs.load_share === undefined ? 1 : inputs.load_share;
const r = SP.solve(site, sc[1], sc[2], sc[3], share), c = SP.CANDIDATE;
return { site, r, c, pvShare:sc[1], genOn:sc[2], off:sc[3], over: Math.max(0, -r.p_poc_kw) > site.export_limit_kw };
}
// every piece of the drawing: a list of [x0,y0,x1,y1] lines and [cx,cy,r] rings, each with a tag and its distance from the grid
function sldPieces(net){
const P = [], subs = net.site.subs, n = subs.length, kmMax = Math.max(...subs.map(s => s.km));
const line = (tag, d, x0, y0, x1, y1) => P.push({ tag, d, kind:'line', x0, y0, x1, y1, len:Math.hypot(x1 - x0, y1 - y0) });
const ring = (tag, d, cx, cy, r) => P.push({ tag, d, kind:'ring', cx, cy, r, len:2 * Math.PI * r });
ring('grid', 0, 0, 0.88, 0.07);
line('poc', 0.07, 0, 0.80, 0, 0.62); line('poc', 0.25, -0.07, 0.61, 0.07, 0.61);
line('board', 0.27, 0, 0.59, 0, 0.44);
line('bus', 0.45, -0.92, 0.42, 0.92, 0.42); line('bus', 0.45, -0.92, 0.395, 0.92, 0.395);
line('gen', 0.45, -0.62, 0.445, -0.62, 0.57); ring('gen', 0.6, -0.62, 0.65, 0.075);
subs.forEach((s, i) => { const x = n === 1 ? 0 : -0.8 + 1.6 * i / (n - 1), dx = 0.45 + Math.abs(x), L = 0.12 + 0.2 * s.km / kmMax;
const t = 'f' + s.n, yT = 0.37 - L;
line(t, dx, x, 0.37, x, yT);
ring(t, dx + L, x, yT - 0.06, 0.05); ring(t, dx + L + 0.1, x, yT - 0.175, 0.05);
const yL = yT - 0.235; line(t, dx + L + 0.2, x, yL, x, yL - 0.12);
line('load' + s.n, dx + L + 0.32, x - 0.045, yL - 0.13, x, yL - 0.2); line('load' + s.n, dx + L + 0.32, x + 0.045, yL - 0.13, x, yL - 0.2);
if (s.n === net.site.pv_on) { const sx = x + (x > 0.5 ? -0.13 : 0.13); line('pv', dx + L + 0.26, x + Math.sign(sx - x) * 0.015, yL - 0.05, sx - Math.sign(sx - x) * 0.05, yL - 0.05);
ring('pv', dx + L + 0.4, sx, yL - 0.05, 0.045); ring('pv', dx + L + 0.4, sx, yL - 0.05, 0.016); } });
return P;
}
function sldLayout(net, m){
const P = net.kind === 'string' ? stringPieces(net.g) : net.kind === 'network' ? netPieces(net.net) : sldPieces(net), total = P.reduce((t, p) => t + p.len, 0), s = total / m;
// A SYMBOL IS NOT A LENGTH. Dots were handed out in proportion to how long each piece is, so a cable
// hundreds of units long took hundreds of dots and the generator - one short stub and a circle two
// hundredths of the drawing across - got the floor of five, which is a faint pentagon nobody can find.
// The Supervisor looked at a tree of twelve with its generator RUNNING and could not see a generator.
// The pieces that are SYMBOLS (the grid, the generator, the solar) are given enough dots to read as the
// thing they are; the long cables give them up, which costs a cable nothing.
const SYMBOL = t => t === 'grid' || t === 'gen' || t === 'inv' || t.startsWith('pv');
let counts = P.map(p => Math.max(SYMBOL(p.tag) ? (p.kind === 'ring' ? 16 : 6) : (p.kind === 'ring' ? 5 : 2), Math.round(p.len / s)));
let diff = m - counts.reduce((a, b) => a + b, 0);
const order = P.map((p, i) => i).sort((a, b) => P[b].len - P[a].len); // the rounding is taken up by the longest pieces
for (let q = 0; diff !== 0 && q < 10 * m; q++) { const i = order[q % order.length]; if (diff > 0) { counts[i]++; diff--; }
else if (counts[i] > (SYMBOL(P[i].tag) ? (P[i].kind === 'ring' ? 16 : 6) : 3)) { counts[i]--; diff++; } }
const unit = new Float32Array(2 * m), tag = new Array(m), dist = new Float32Array(m); let j = 0, dMax = 0;
P.forEach((p, i) => { for (let q = 0; q < counts[i] && j < m; q++, j++) { const u = (q + 0.5) / counts[i];
// A PIECE THAT CARRIES ITS OWN PLACE ALONG THE ELECTRICAL PATH keeps it: a wiring drawing numbers its
// pieces 0 at the - end and 1 at the +, and adding the piece's own length to that would mean nothing.
// A CURVE IS NOT A CHORD. A piece that carries a whole path puts its dots ON that path, so a dot of
// a cable that bends is never left sitting off the line it belongs to.
if (p.kind === 'path') { const q = polyAt(p.pts, p.cum, p.len, u); unit[2*j] = q[0]; unit[2*j+1] = q[1]; dist[j] = p.flat ? p.d : p.d + p.len * u; }
else if (p.kind === 'line') { unit[2*j] = p.x0 + (p.x1 - p.x0) * u; unit[2*j+1] = p.y0 + (p.y1 - p.y0) * u; dist[j] = p.flat ? p.d : p.d + p.len * u; }
else { const a = 2 * Math.PI * u + i; unit[2*j] = p.cx + p.r * Math.cos(a); unit[2*j+1] = p.cy + p.r * Math.sin(a); dist[j] = p.d + p.r; }
tag[j] = p.tag; dMax = Math.max(dMax, dist[j]); } });
for (; j < m; j++) { unit[2*j] = unit[0]; unit[2*j+1] = unit[1]; tag[j] = 'grid'; }
return { unit, tag, dist, dMax, spacing:s };
}
// what each dot ends as: 0..1 brightness, 2 = over a limit (amber), -1 = disconnected (dark)
function sldFinal(net, tag){
const r = net.r, c = net.c, vs = Object.values(r.V), vBad = Math.max(...vs) > c.volts_high_pu || Math.min(...vs) < c.volts_low_pu;
return tag.map(t => {
if (t === 'grid') return 0.95; if (t === 'poc') return net.over ? 2 : 0.95; if (t === 'board') return 0.9; if (t === 'bus') return vBad ? 2 : 0.95;
if (t === 'gen') return net.genOn ? 1 : -1; if (t === 'pv') return net.pvShare > 0 ? 1 : -1;
const k = +t.replace(/\D/g, ''), load = r.tx_loading_pct['lv' + k];
if (load === undefined) return -1; // a disconnected substation
if (t[0] === 'l') return (net.off.includes('pvload') && k === net.site.pv_on) ? -1 : 0.85;
return load > 100 ? 2 : 0.3 + 0.65 * Math.min(1, load / 100); });
}
function makeSldBody(st){
const net = (st.prog.sld && (st.prog.sld.kind === 'network' || st.prog.sld.kind === 'string')) ? st.prog.sld : sldNetwork(st.prog.sld || {}); if (!net) return null;
// EVERY DOT OF THE SKY CAN BE CALLED: the diagram's dots are lines of code from the whole record, evenly through all the keys,
// so they leave from everywhere on the disc at once.
// EVERY DOT OF THE DIAGRAM IS A REAL LINE OF CODE, AND SAYS WHOSE. The shell answers a tap on dot j with the piece of work
// st.idx[j]; a diagram has more dots than the application has pieces of work, so a tap found nothing, threw, and never let the
// mouse go. So dot j is given the piece of work that issued its key (commits are in key order: a halving search), its place is
// that work's own middle line, and a tap on the diagram opens that work.
const m = SLD_MAX, from = new Float32Array(2 * m), owner = new Array(m);
for (let j = 0; j < m; j++) { const key = Math.floor((j + 0.5) * SPACE / m); let lo = 0, hi = commits.length - 1;
while (lo < hi) { const mid = (lo + hi) >> 1; if (commits[mid].k1 > key) hi = mid; else lo = mid + 1; }
owner[j] = lo; const c0 = commits[lo], p = keyPlace(Math.min(Math.max(key, c0.k0), Math.max(c0.k0, c0.k1 - 1))); from[2*j] = p[0]; from[2*j+1] = p[1]; }
st.idx = owner;
const lay = sldLayout(net, m), R = Math.sqrt(SPACE), frac = BODY_RADIUS_MAX, to = new Float32Array(2 * m);
// THE DRAWING FILLS THE DISC. Each drawing was laid out in its own units and then scaled by how far its
// farthest point lay FROM THE ORIGIN, which is not where the drawing is: a network whose busbar sits high
// and whose loads hang low was pushed off centre and left using about half the disc, with a ring of empty
// dark around it. Its own extent is found, its middle is moved to the middle of the disc, and it is blown
// up until its farthest dot is at the rim. Nothing about the drawing changes but its size and its place.
// A ROW OF THIRTY MODULES IS NOT A DISC AND IS NOT SQUEEZED INTO ONE. A wiring drawing is laid out in
// its own units, as tall as the disc and as wide as it needs to be, and the reader drags along it; a
// network, which really is a picture, is still fitted to the disc as it always was.
if (net.kind !== 'string') {
let x0 = Infinity, x1 = -Infinity, y0 = Infinity, y1 = -Infinity;
for (let j = 0; j < m; j++) { const x = lay.unit[2*j], y = lay.unit[2*j+1];
if (x < x0) x0 = x; if (x > x1) x1 = x; if (y < y0) y0 = y; if (y > y1) y1 = y; }
const mx = (x0 + x1) / 2, my = (y0 + y1) / 2;
let far = 0;
for (let j = 0; j < m; j++) { const d = Math.hypot(lay.unit[2*j] - mx, lay.unit[2*j+1] - my); if (d > far) far = d; }
const k = far > 1e-9 ? 0.97 / far : 1;
for (let j = 0; j < m; j++) { lay.unit[2*j] = (lay.unit[2*j] - mx) * k; lay.unit[2*j+1] = (lay.unit[2*j+1] - my) * k; }
lay.spacing *= k; }
for (let q = 0; q < 2 * m; q++) to[q] = lay.unit[q] * R * frac;
const gap = closestPair(lay.unit) * R * frac;
sldNow = { net, lay, final:net.kind === 'string' ? stringFinal(net, lay.tag) : net.kind === 'network' ? netFinal(net, lay.tag) : sldFinal(net, lay.tag), t0:0, vals:new Float32Array(SLD_MAX) };
// THE SOLID DRAWING COMES FROM THE SAME DESCRIPTION THE DOTS CAME FROM, so the two can never disagree.
shapeLayer(); sldShapes = net.kind === 'string' ? (net.g.__draw || stringDrawing(net.g)) : null;
if (sldShapes) { sldShapes.front = -1; sldShapes.head = -1; sldShapes.walk = null; sldShapes.t0 = 0; shapeHover = null; }
nameLayer();
sldNames = makeSldNames(lay, net);
if (net.kind !== 'string') { const amber = addAmberName(lay, sldNow.final); if (amber) sldNames.push(amber); }
return { n:m, from, pos:new Float32Array(from), states:[{ shape:'sld', to, gap, frac, hold:0, unresolved:false }], k:-1, gap:0, shown:false, sld:true, fineDots:net.kind === 'string', sldGap:lay.spacing * R * frac };
}
// ===== THE FEWEST WORDS A DIAGRAM NEEDS ==========================================================
// A picture of nine substations with no word on it anywhere is a pattern, not a single line diagram, to
// anybody who is not an engineer. Three words are added, and no more: GRID where the grid is, what the
// connection point is doing (exports 50 kW, or imports 1,649 kW) where the connection point is, and the
// name of whatever ended AMBER, because amber is the only thing on the picture that is a warning and a
// colour nobody can look up. They are drawn as plain text over the canvas, no boxes and no lines, at the
// place the drawing itself puts them, and they appear only once the dots have landed.
let sldNames = null;
function nameLayer(){
let el = document.getElementById('sldnames');
if (!el) { el = document.createElement('div'); el.id = 'sldnames';
const st = document.createElement('style');
st.textContent = '#sldnames{position:fixed;inset:0;z-index:4;pointer-events:none}'
+ '#sldnames span{position:absolute;transform:translate(-50%,-50%);color:#cfeaf2;font-size:10.5px;letter-spacing:.06em;'
+ 'white-space:nowrap;text-shadow:0 0 6px #000,0 0 3px #000}'
+ '#sldnames span.warn{color:#ffb454}'
+ '#sldnames span.note{color:#7f8899;font-size:10px;letter-spacing:.04em}'
+ '#sldnames span.danger{color:#ff5a4f;font-size:10.5px;font-weight:600;letter-spacing:.05em}'
// A PINNED LINE MAY WRAP. It is a sentence, not a name, and on a telephone it is longer than the
// screen; a key that runs off the edge is a key nobody reads.
+ '#sldnames span.pinned{white-space:normal;text-align:center;transform:translate(-50%,-100%);line-height:1.35}'
+ '#sldnames span.said{color:#eaf6ff;font-size:11.5px;background:#0b0f16e8;border:1px solid #2a3444;'
+ 'border-radius:4px;padding:3px 8px;letter-spacing:.03em}'
+ '@media (max-width:700px){#sldnames span{font-size:9.5px}#sldnames span.note{font-size:9px}}';
document.head.append(st); document.body.append(el); }
return el;
}
const AMBER_WORDS = { bus:'volts outside the band', poc:'over the export limit', grid:'', board:'' };
function amberName(tag){
if (!tag) return '';
if (AMBER_WORDS[tag] !== undefined) return AMBER_WORDS[tag];
// A SERIES STRING WITH ONE LINK THAT DOES NOT MEET IS NOT "AMBER THERE". It carries no current at all.
if (tag.startsWith('short')) return 'open here, and live: no current, full open circuit voltage across the break';
if (tag.startsWith('tx')) return 'transformer over its rating';
if (tag.startsWith('load')) return 'volts outside the band at the load';
if (tag.startsWith('hv')) return 'volts outside the band on this cable';
if (tag.startsWith('f')) return 'transformer over its rating';
return '';
}
// WHAT THE CONNECTION POINT IS DOING, in the words the bench itself uses: minus is out to the grid.
function pocWords(net){
let kw = null;
if (net.kind === 'network' && net.solved) kw = net.solved.p;
else if (net.r && net.r.p_poc_kw !== undefined) kw = net.r.p_poc_kw;
if (kw === null || kw === undefined || !isFinite(kw)) return '';
const n = Math.abs(Math.round(kw));
return (kw < 0 ? 'exports ' : 'imports ') + (typeof fmt === 'function' ? fmt(n) : String(n)) + ' kW';
}
// the places, in the drawing's own units AFTER it has been fitted to the disc, so they follow the dots
function makeSldNames(lay, net){
const want = [], first = tag => { for (let j = 0; j < lay.tag.length; j++) if (lay.tag[j] === tag) return j; return -1; };
const at = j => ({ x:lay.unit[2*j], y:lay.unit[2*j+1] });
// A WIRING DRAWING CARRIES ITS OWN WORDS, and they were written when it was described: the inverter,
// the two free ends, what a sequential string lays extra, and the one note about red and black. Red
// and black here are how the drawing is READ; in the field both conductors are black cable and only
// the polarity marking tells them apart.
if (net.kind === 'string') { const d = net.g.__draw || stringDrawing(net.g);
const out = d.words.map(w => ({ x:w.x, y:w.y, dy:0, dx:0, text:w.text, small:w.small, warn:!!w.warnLine, note:!!w.note, danger:!!w.danger,
wide:!!w.wide, narrow:!!w.narrow, off:!!w.off, pinned:w.pinned }));
// A SERIES STRING WITH ONE LINK THAT DOES NOT MEET IS DEAD ALL THE WAY ROUND, and that is said once,
// under the drawing, not thirty times along it.
return out; }
const g = first('grid'); if (g >= 0) want.push(Object.assign(at(g), { text:'GRID', dy:-0.10, warn:false }));
const pc = first('poc'), words = pocWords(net);
if (pc >= 0 && words) want.push(Object.assign(at(pc), { text:words, dy:0, dx:0.22, warn:false }));
return want;
}
function addAmberName(lay, final){
const seen = new Set();
for (let j = 0; j < final.length; j++) {
if (final[j] !== 2) continue;
const words = amberName(lay.tag[j]);
if (!words || seen.has(words)) continue;
seen.add(words);
return { x:lay.unit[2*j], y:lay.unit[2*j+1], text:words, dy:-0.06, warn:true };
}
return null;
}
// THE WORDS FOLLOW THE PICTURE. They are put where they belong every time the camera moves, and nowhere
// else: no animation loop of their own is started, because a loop that runs for ever to move three words
// is a loop that runs for ever.
function placeSldNames(){
const el = document.getElementById('sldnames');
if (!el) return;
if (!sldNames || !body || !body.sld || !body.shown || bodyAnim || !sldNow) { el.replaceChildren(); return; }
const R = Math.sqrt(SPACE), frac = BODY_RADIUS_MAX;
// WHAT A TAP OR A HOVER HAS FOUND is one more word, and it comes and goes, so the list is rebuilt
// whenever its length changes and no sooner.
const said = sldShapes && shapeHover ? sldShapes.saying : null;
const list = said ? sldNames.concat([{ x:0, y:0, text:said, hover:true }]) : sldNames;
const small = innerWidth < 760;
// A LINE THAT BELONGS TO ONE SIZE OF SCREEN IS NOT BUILT FOR THE OTHER.
if (sldNames.some(n => n.wide || n.narrow || n.off)) sldNames = sldNames.filter(n => !n.off && (small ? !n.wide : !n.narrow));
if (el.childElementCount !== list.length || el.dataset.said !== String(said) || el.dataset.small !== String(small)) {
el.dataset.said = String(said); el.dataset.small = String(small);
el.replaceChildren(...list.map(n => { const sp = document.createElement('span');
sp.textContent = (small && n.small) ? n.small : n.text;
if (n.danger) sp.className = 'danger'; else if (n.warn) sp.className = 'warn'; else if (n.note) sp.className = 'note';
else if (n.hover) sp.className = 'said';
if (n.pinned !== undefined) sp.className += ' pinned'; return sp; }));
}
const pinBand = (sldShapes && sldShapes.kind === 'string') ? shapeBand() : null;
list.forEach((n, i) => { const sp = el.children[i]; if (!sp) return;
if (n.hover) { sp.style.left = Math.round(innerWidth / 2) + 'px';
sp.style.top = Math.round(Math.min(innerHeight - 120, innerHeight * 0.80)) + 'px'; return; }
// A PINNED LINE SITS AT THE FOOT OF THE BAND. Where exactly is settled in one pass afterwards,
// because these lines WRAP and a stack of guessed heights is a stack of sentences on top of
// each other, which is what a first attempt at this looked like.
if (n.pinned !== undefined && pinBand) { sp.style.visibility = '';
sp.style.left = Math.round((pinBand.left + pinBand.right) / 2) + 'px';
sp.style.maxWidth = Math.round(Math.min(900, pinBand.right - pinBand.left - 8)) + 'px';
return; }
const wx = (n.x + (n.dx || 0)) * R * frac, wy = (n.y + (n.dy || 0)) * R * frac;
const px0 = Math.round((wx - cx) * zoom + innerWidth / 2), py0 = Math.round(innerHeight / 2 - (wy - cy) * zoom);
// A WORD OFF THE SCREEN IS NOT LAID OUT. Thirty modules is several screens wide and the browser
// should not be asked to place what nobody can see; and text is put on whole pixels so it is crisp.
const bd = (sldShapes && sldShapes.kind === 'string') ? shapeBand(true) : { left:-260, right:innerWidth + 260, top:-60, bottom:innerHeight + 60 };
if (px0 < bd.left - 6 || px0 > bd.right + 6 || py0 < bd.top - 4 || py0 > bd.bottom + 4) { sp.style.visibility = 'hidden'; return; }
sp.style.visibility = ''; sp.style.left = px0 + 'px'; sp.style.top = py0 + 'px';
// A WORD IS NOT ALLOWED UNDER THE WINDOW EITHER, wherever the reader has put it.
const w2 = sayRect();
if (w2) { const b2 = sp.getBoundingClientRect();
if (b2.width > 0 && b2.right > w2.left && b2.left < w2.right && b2.bottom > w2.top && b2.top < w2.bottom) sp.style.visibility = 'hidden'; } });
// THE PINNED LINES ARE STACKED FROM THE BOTTOM UP, each one measured after it has wrapped.
if (pinBand) { const pins = [];
list.forEach((n, i) => { if (n.pinned !== undefined && el.children[i]) pins.push([n.pinned, el.children[i]]); });
pins.sort((a, b) => a[0] - b[0]);
let y = pinBand.bottom - 4;
for (const [, sp] of pins) { sp.style.top = Math.round(y) + 'px'; y -= (sp.offsetHeight || 14) + 2; }
pinHeight = Math.max(0, pinBand.bottom - 4 - y); }
}
addEventListener('wheel', placeSldNames, { passive:true });
addEventListener('pointermove', placeSldNames);
addEventListener('pointerup', placeSldNames);
addEventListener('resize', placeSldNames);
addEventListener('orientationchange', placeSldNames);
function sldUniforms(){
if (!BP) return; gl.useProgram(BP);
const on = !!(body && body.sld && sldNow);
gl.uniform1f(gl.getUniformLocation(BP, 'u_sld'), on ? 1 : 0);
if (on) gl.uniform4fv(gl.getUniformLocation(BP, 'u_val[0]'), sldNow.vals);
}
function sldTick(now){
sldLoop = 0; if (!(body && body.sld && sldNow)) return;
const S = sldNow, m = body.n, arrived = !bodyAnim && body.shown;
if (arrived && !S.t0) S.t0 = now;
const t = S.t0 ? (now - S.t0) / 1000 : -1;
// A WIRING DRAWING HAS ITS OWN TIMING: the dots settle, and then, ONLY IF THE LOOP IS CLOSED, one
// wavefront leaves the modules and runs out along both conductors to the inverter. Behind it the
// pencil line fuses solid and the dots under it MELT AWAY, because the line is the drawing now.
// An open string never starts: no current anywhere, so nothing to run.
if (S.net.kind === 'string' && sldShapes) {
const T2 = 1.3, live = !sldShapes.open;
// each dot goes out at its own moment, so the drawing is uncovered rather than switched off
if (!S.melt) { S.melt = new Float32Array(m); for (let j = 0; j < m; j++) S.melt[j] = 0.15 + 0.8 * ((j * 2654435761) % 1000) / 1000; }
const f = (t < 0 || !live) ? -1 : Math.min(1, t / T2);
sldShapes.front = f;
// THE NEON FRONT RUNS ON THIS SAME CLOCK. Not a second animation: the head is set here, beside the
// fuse front, and the shape pass draws it. One head, steady speed, running the ELECTRICAL WALK the
// model already names - inverter - round through every module to inverter +. An open string is
// given no head at all, because it carries nothing.
sldShapes.head = (live && t >= 0) ? ((t / 3.6) % 1) : -1;
for (let j = 0; j < m; j++) { const o = S.lay.dist[j], base = S.final[j];
if (t < 0) { S.vals[j] = 0.55; continue; }
if (f < 0) { S.vals[j] = base; continue; }
// AND THEN THEY ARE GONE. The dots are the way in - the work flies from the record and settles
// along the drawing - and once the line is there they melt away completely, because a drawing
// made of fine lines with dots scattered over it is two drawings. A value under -1.5 is thrown
// away by the shader, so nothing at all is left behind.
const gone = Math.min(1, Math.max(0, (t - 0.25) / 0.9));
const reach = Math.abs(o - 0.5) <= f * 0.5 + 1e-6;
const atFront = Math.abs(Math.abs(o - 0.5) - f * 0.5) < 0.035;
const still = atFront ? 1.25 : (reach ? 0.10 : base);
S.vals[j] = (gone >= 1 || (S.melt && S.melt[j] <= gone)) ? -2 : still; }
sldUniforms(); placeSldNames();
if (arrived && !S.placed) { S.placed = true; try { if (window.__placeSay) window.__placeSay(); } catch (_) {}
try { stringOpenView(); } catch (_) {} }
dirty = true;
if (live || t < Math.max(T2, 1.2) + 0.5) sldLoop = requestAnimationFrame(sldTick);
return;
}
const T = 1.5, D = S.lay.dMax, w = D * 0.06;
for (let j = 0; j < m; j++) { const d = S.lay.dist[j], f = S.final[j]; let v;
if (t < 0) v = 0.55; // in flight: every dot alike
else if (t < T) { const front = D * (1 - t / T); v = Math.abs(d - front) < w ? 1.25 : (d > front ? 0.5 : 0.22); } // PULSE ONE: back toward the grid
else if (t < 2 * T) { const front = D * (t / T - 1); v = Math.abs(d - front) < w ? 1.25 : (d < front ? f : 0.22); } // PULSE TWO: out from the grid, leaving the answer
else v = f;
S.vals[j] = v; }
sldUniforms(); placeSldNames();
if (arrived && !S.placed) { S.placed = true; try { if (window.__placeSay) window.__placeSay(); } catch (_) {} }
dirty = true;
if (t < 2 * T + 0.2) sldLoop = requestAnimationFrame(sldTick);
}
// WHERE THE VIEW OPENS. A thirty module row is several screens wide, so the reader is put at the NEAR
// END, with the inverter and the first few modules big enough to read on a phone, and drags along the
// row for the rest. The whole row is one press away.
function stringViewSpanM(){ return Math.max(9.5, Math.min(17, innerWidth / 40)); }
// THE BAND THE DRAWING LIVES IN. The answer window must never cover a shape or a word, so the free part
// of the screen is measured - what the foot takes, what the chips take, and where the window is docked -
// the row is laid out INTO that band, and the drawing layer is CLIPPED to it. A row several screens long
// would otherwise run on under the window, and a drawing nobody can read is not a drawing.
function sayRect(){ const el = document.getElementById('say');
if (!el || !el.classList.contains('open')) return null;
const r = el.getBoundingClientRect();
return (r.width > 8 && r.height > 8) ? r : null; }
let pinHeight = 0; // what the pinned key took last time it was laid out
function shapeBand(reserve){
let left = 14, right = innerWidth - 14, top = 14, bottom = innerHeight - 14;
const foot = document.getElementById('foot');
if (foot) { const r = foot.getBoundingClientRect(); if (r.height > 2) bottom = Math.min(bottom, r.top - 10); }
{ const r = sayRect();
if (r) { if (r.width > innerWidth * 0.7) top = Math.max(top, r.bottom + 10); // across the top: go under it
else if (r.left > innerWidth * 0.5) right = Math.min(right, r.left - 12); // docked to the right
else left = Math.max(left, r.right + 12); } }
const chips = document.getElementById('presets');
if (chips) { const c = chips.getBoundingClientRect(); if (c.height > 2 && c.left < right) top = Math.max(top, c.bottom + 10); }
if (right - left < 220) { left = 14; right = innerWidth - 14; }
if (bottom - top < 150) { top = 14; bottom = innerHeight - 14; }
// THE KEY IS NOT PART OF THE PICTURE AND THE PICTURE DOES NOT RUN UNDER IT. What the key took last
// time is kept out of the band the drawing is laid into and clipped to; the key itself is placed
// against the band that has NOT been shortened, or it would walk up the screen a line a frame.
if (reserve && pinHeight > 0) bottom = Math.max(top + 120, bottom - pinHeight - 6);
return { left, right, top, bottom };
}
function stringPlaceView(spanM, whole){
const D = sldShapes; if (!D || typeof flyTo !== 'function') return;
const R = Math.sqrt(SPACE), f = BODY_RADIUS_MAX, b = shapeBand(true);
if (whole) { const bb = D.bounds, w = Math.max(1e-6, bb.x1 - bb.x0), h = Math.max(1e-6, bb.y1 - bb.y0);
const z = Math.max(1e-9, Math.min((b.right - b.left) * 0.98 / (w * R * f), (b.bottom - b.top) * 0.92 / (h * R * f)));
flyTo((bb.x0 + bb.x1) / 2 * R * f - ((b.left + b.right) / 2 - innerWidth / 2) / z,
(bb.y0 + bb.y1) / 2 * R * f + ((b.top + b.bottom) / 2 - innerHeight / 2) / z, z); return; }
// THE NEAR VIEW FILLS THE BAND, in both directions. It used to be set by width alone, so on a
// telephone a two tier table sat in a third of the screen with empty dark above and below it. The
// zoom is now whichever of the two fits - the whole drawing's height into the band's height, or
// three modules across its width - so the picture is as large as it can be and still legible, and it
// starts at M1 rather than at the inverter, because the modules are what is being read.
const hUnits = Math.max(1e-6, D.bounds.y1 - D.bounds.y0);
const zH = (b.bottom - b.top) * 0.97 / (hUnits * R * f);
// MICRO IS FOUR MODULES, and it is four on a telephone and four on a desk: the view is named by what
// it shows, not by how much of the screen happens to be free. M1 to M4 across the band, with a hair
// of margin so the fourth module is not cut by the edge.
const wantM = 4.06 * D.g.pitch;
const zW = (b.right - b.left) * 0.97 / (wantM * D.perM * R * f);
const z = Math.max(1e-9, Math.min(zH, zW));
const firstX = D.firstModuleX !== undefined ? D.firstModuleX : D.near.x;
flyTo(firstX * R * f - (b.left + 6 - innerWidth / 2) / z,
(D.bounds.y0 + D.bounds.y1) / 2 * R * f + ((b.top + b.bottom) / 2 - innerHeight / 2) / z, z);
}
// WHICH VIEW THE DRAWING OPENS IN IS THE DECLARED INPUT, and nothing else decides it: `view` says macro
// or micro, its default is micro on a telephone and macro on a desk, and the two typed words set it.
function stringViewWord(D){ const c = D && D.g && D.g.c; const v = String((c && c.view) || '').toLowerCase();
if (v === 'macro' || v === 'micro') return v;
return (innerWidth < 700) ? 'micro' : 'macro'; }
function stringOpenView(){ const D = sldShapes; if (!D || D.opened) return; D.opened = true;
stringPlaceView(stringViewSpanM(), stringViewWord(D) === 'macro'); }
function stringWholeView(){ stringPlaceView(0, true); } // MACRO: the whole string, fitted to the width
function stringNearView(){ const D = sldShapes; if (!D) return; stringPlaceView(stringViewSpanM(), false); }
// THE MICRO END HAS A FLOOR UNDER IT. Going in is going in until the module you are reading fills the
// band - and then it stops. Past that point the wheel only cuts the thing you came to look at: the top
// of the module goes off the top of the band, the bottom off the bottom, and the reader is left with a
// slab of glass and no edges to hold on to. So the camera is CLAMPED. One module, whole, inside the
// band, is the closest the drawing will go; and when the clamp bites the module under the middle of
// the screen is also brought to the middle of the band, so what stops is centred and not half gone.
function stringClampMicro(){
const D = sldShapes; if (!D || !D.shapes || typeof flyTo !== 'function' || typeof zoom !== 'number') return;
const R = Math.sqrt(SPACE), f = BODY_RADIUS_MAX, b = shapeBand(true);
let hU = 0, wU = 0;
for (const s of D.shapes) { if (s.role !== 'module' || !s.pts || s.pts.length < 2) continue;
let y0 = 1e9, y1 = -1e9, x0 = 1e9, x1 = -1e9;
for (const p of s.pts) { if (p[1] < y0) y0 = p[1]; if (p[1] > y1) y1 = p[1];
if (p[0] < x0) x0 = p[0]; if (p[0] > x1) x1 = p[0]; }
hU = Math.max(hU, y1 - y0); wU = Math.max(wU, x1 - x0); break; }
if (!(hU > 0) || !(wU > 0)) return;
const zMax = Math.min((b.bottom - b.top) * 0.90 / (hU * R * f), (b.right - b.left) * 0.90 / (wU * R * f));
if (!(zMax > 0)) return;
const zUse = Math.min(zoom, zMax);
// the module nearest the middle of the screen is the one the reader is on; centre it in the band
const midX = innerWidth / 2, midY = (b.top + b.bottom) / 2;
let best = null, bd = 1e18;
for (const s of D.shapes) { if (s.role !== 'module' || !s.pts || s.pts.length < 2) continue;
let y0 = 1e9, y1 = -1e9, x0 = 1e9, x1 = -1e9;
for (const p of s.pts) { const q = shapePoint(p);
if (q[1] < y0) y0 = q[1]; if (q[1] > y1) y1 = q[1]; if (q[0] < x0) x0 = q[0]; if (q[0] > x1) x1 = q[0]; }
const dx = (x0 + x1) / 2 - midX, dy = (y0 + y1) / 2 - midY, d2 = dx * dx + dy * dy;
if (d2 < bd) { bd = d2; best = s; } }
if (!best) return;
// ONLY WHEN IT IS ACTUALLY CUT. The clamp is not a rule about zoom, it is a rule about the module
// the reader is on: if that module already sits whole inside the band at the zoom in hand, nothing
// moves. It moves when the module is too big for the band, or when it fits and is simply hanging
// over an edge - and then the same move fixes both, because the module is put in the middle.
let sx0 = 1e9, sx1 = -1e9, sy0 = 1e9, sy1 = -1e9;
for (const p of best.pts) { const q = shapePoint(p);
if (q[0] < sx0) sx0 = q[0]; if (q[0] > sx1) sx1 = q[0]; if (q[1] < sy0) sy0 = q[1]; if (q[1] > sy1) sy1 = q[1]; }
const inside = sx0 >= b.left && sx1 <= b.right && sy0 >= b.top && sy1 <= b.bottom;
if (inside && zoom <= zMax * 1.02) return;
let ux0 = 1e9, ux1 = -1e9, uy0 = 1e9, uy1 = -1e9;
for (const p of best.pts) { if (p[0] < ux0) ux0 = p[0]; if (p[0] > ux1) ux1 = p[0];
if (p[1] < uy0) uy0 = p[1]; if (p[1] > uy1) uy1 = p[1]; }
const xc = (ux0 + ux1) / 2 * R * f, yc = (uy0 + uy1) / 2 * R * f;
flyTo(xc - (midX - innerWidth / 2) / zUse, yc + (midY - innerHeight / 2) / zUse, zUse);
}
function sldStart(){ if (!sldLoop) sldLoop = requestAnimationFrame(sldTick); }
// THE ELECTRICAL WALK, READ OFF THE DRAWING ITSELF. Nothing is measured or placed here: every
// conductor shape already says which terminal it leaves and which it joins, so the order is found by
// following those names from INV- to INV+, and each leg's share of the walk is the TRUE LENGTH of the
// polyline that was drawn for it. A module is a leg too - the walk goes in at its - box and out at its