GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / globalgrid2050 / kuiper-grid/i0073/cartridges

Kuiper Programs (part 19)

A JavaScript module in the cartridges folder of GlobalGrid2050 covering solar, cables, substations and transformers, using SHA-256, and uses data from the faraday repository.

700 lines of JavaScript from globalgrid2050, in 1 file. Topic: Kuiper, cosmos and drawing engines. Section 1268 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Kuiper Programs render · globalgrid2050 / kuiper-grid/i0073/cartridges/005700000000-kuiper-programs.js lines 1123–1822

Kuiper Programs

A JavaScript module in the cartridges folder of GlobalGrid2050 covering solar, cables, substations and transformers, using SHA-256, and uses data from the faraday repository.

renderglobalgrid2050 / kuiper-grid/i0073/cartridges/005700000000-kuiper-programs.js · lines 1123–1822 of 1827 (continued from section 1266) · Not reached from any entry point (candidate for review) · pattern stringViewSpanM (shared by 41 files)

What it does
It draws solar, cables, substations and transformers. Defines 145 functions or classes, including closestPair, blackSky, nameInLines, makeBody, bodyTo. 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: solar, cables, 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/i0073/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
closestPair, blackSky, nameInLines, makeBody, bodyTo, labels, bodyJump, bodyMove, bodyDrawnDiameter, bodyDotPx, sheet, setTag
Defines here
sldNetwork, sldPieces, line, ring, sldLayout, SYMBOL, sldFinal, makeSldBody, nameLayer, amberName, pocWords, makeSldNames, at, addAmberName, placeSldNames, sldUniforms, sldTick, stringViewSpanM, stringOpenView, stringWholeView, stringNearView, sldStart, shapeLayer, shapeScale, shapePoint, shapesGone, polyLen, polyAt, polySlice, polyThin
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/i0073/cartridges/005700000000-kuiper-programs.js:1123-1822 · blob 9922de4b9416a84236b16ab452db8771120692a0 · 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
  if (out.name === 'string') { const row = el('div', 'viewrow');
    for (const [words, go] of [['the near end', () => stringNearView()], ['the whole row', () => stringWholeView()]]) {
      const b = el('button', null, words); b.type = 'button';
      b.addEventListener('click', e => { e.stopPropagation(); try { go(); } catch (_) {} }); row.append(b); }
    nodes.push(row);
    if (out.electrical_order) nodes.push(el('p', 'dimtext', 'Electrical order: ' + out.electrical_order)); }
  nodes.push(more, hidden);
  open(title, nodes);
  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); 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); } }      // THE DOTS DRAW THE NETWORK OF THIS COMMAND
    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.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.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 'the circuit is open here: no current anywhere in this string';
  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, warn:false, note:!!w.note }));
    // 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.
    if (d.open) out.push({ x:d.bounds.x0 + (d.bounds.x1 - d.bounds.x0) * 0.5, y:d.bounds.y0, dy:0.12,
      text:'the circuit is open: ' + d.g.short.length + ' links do not reach, so no current flows anywhere in this string', warn:true });
    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;
  if (el.childElementCount !== list.length || el.dataset.said !== String(said)) {
    el.dataset.said = String(said);
    el.replaceChildren(...list.map(n => { const sp = document.createElement('span');
      sp.textContent = n.text; if (n.warn) sp.className = 'warn'; else if (n.note) sp.className = 'note';
      else if (n.hover) sp.className = 'said'; return sp; }));
  }
  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; }
    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.
    if (px0 < -260 || px0 > innerWidth + 260 || py0 < -60 || py0 > innerHeight + 60) { sp.style.visibility = 'hidden'; return; }
    sp.style.visibility = ''; sp.style.left = px0 + 'px'; sp.style.top = py0 + 'px'; });
}
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;
    const f = (t < 0 || !live) ? -1 : Math.min(1, t / T2);
    sldShapes.front = f;
    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; }
      const reach = Math.abs(o - 0.5) <= f * 0.5 + 1e-6;                        // the front, measured the same way the line is
      const atFront = Math.abs(Math.abs(o - 0.5) - f * 0.5) < 0.035;
      S.vals[j] = atFront ? 1.25 : (reach ? 0.10 : base); }
    sldUniforms(); placeSldNames();
    if (arrived && !S.placed) { S.placed = true; try { if (window.__placeSay) window.__placeSay(); } catch (_) {}
      try { stringOpenView(); } catch (_) {} }
    dirty = true;
    if (t < T2 + 0.4) 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)); }
function stringOpenView(){
  const D = sldShapes; if (!D || D.opened) return; D.opened = true;
  const R = Math.sqrt(SPACE), f = BODY_RADIUS_MAX, span = stringViewSpanM() * D.perM;
  const z = Math.max(1e-6, innerWidth * 0.94 / (span * R * f));
  if (typeof flyTo === 'function') flyTo((D.near.x + span * 0.5) * R * f, D.near.y * R * f, z);
}
function stringWholeView(){
  const D = sldShapes; if (!D) return;
  const R = Math.sqrt(SPACE), f = BODY_RADIUS_MAX, b = D.bounds;
  const w = Math.max(1e-6, b.x1 - b.x0), h = Math.max(1e-6, b.y1 - b.y0);
  const z = Math.min(innerWidth * 0.94 / (w * R * f), innerHeight * 0.70 / (h * R * f));
  if (typeof flyTo === 'function') flyTo((b.x0 + b.x1) / 2 * R * f, (b.y0 + b.y1) / 2 * R * f, Math.max(1e-6, z));
}
function stringNearView(){ const D = sldShapes; if (!D) return; D.opened = false; stringOpenView(); }
function sldStart(){ if (!sldLoop) sldLoop = requestAnimationFrame(sldTick); }

// ===== SOLID SHAPES: THE WAY THIS PAGE DRAWS A WIRING DIAGRAM ===================================
// WHY THERE ARE TWO WAYS OF DRAWING AND NOT ONE. Dots are right for the MACRO view: a population of
// work, a whole estate, a field of addresses. They are wrong for a drawing somebody has to READ. At
// module level a cable made of dots is a smear, and no reader can tell which box joins which. So a
// diagram is described ONCE, as SHAPES, and the shapes are drawn as fine vector lines on one layer
// that follows the camera exactly. Vectors stay sharp at any zoom and on any screen.
//
// A SHAPE IS DATA, NOT A DRAWING INSTRUCTION:
//   { role, node, order, pot, volts, earth_v, pts, closed, fill, weight, dash, gap, says }
//   role     what it is: inverter, terminal, module, cells, box, lead, cable, loop, mark
//   node     the conductor or electrical node it belongs to, so a tap can light one whole link
//   order    its place along the electrical path, 0 at the - end of the string, 1 at the + end
//   pot      the potential at that point, 0 at the - end and 1 at the + end, one module's volts a module
//   volts    that potential in volts above the - end
//   earth_v  the same point's volts TO EARTH. A floating array on a transformerless inverter sits
//            roughly symmetric about earth, so this is about minus half to plus half of the string
//            voltage end to end. It is carried now, unused, because an earth fault study needs it: the
//            FIRST fault pins one point to earth and re-references every other potential (the far end
//            rises toward the whole string voltage: insulation stress, little current), and a SECOND
//            fault closes a loop through earth that bypasses the modules between and drives their short
//            circuit current round it. Nothing of that is computed here; the model is ready for it.
// The dot pieces are produced from the SAME list, so the dots and the drawing can never disagree.
//
// THREE STATES, AND THE PHYSICS DECIDES WHICH ONE IS SHOWN:
//   DRAWN      the pencil drawing, grey. What was designed, before any question of current.
//   OPEN       a series string with ONE link whose leads do not meet carries NO current ANYWHERE. Not
//              "that link is amber": the whole string is dead. Every gap is drawn as the gap it is,
//              with its shortfall in metres beside it, and nothing fuses.
//   ENERGISED  the loop is closed. A WAVEFRONT starts AT THE MODULES and runs out along both
//              conductors TO THE INVERTER, which is the way the power goes, and behind the front the
//              pencil line FUSES into a solid one. The front is fast because energy arrives as a field,
//              at a large fraction of the speed of light; the electrons themselves drift about a fifth
//              of a millimetre a second at 17 A in 6 mm2, which is why nothing crawls along a wire in
//              this drawing. The fused line's WEIGHT is the current, the same all round a series string
//              because charge is conserved at every node, and it would ADD where two strings meet. Its
//              COLOUR is the POTENTIAL at that point: black at the - end, red at the + end, one
//              module's voltage higher at each module, so only the two home runs are fully - and + .
// CLARITY OVER FANCY. The pencil drawing, the marked boxes, the module names and the followable cables
// are what the picture is for. The fusing, the potential colour and the loop shading are drawn UNDER
// them and never over a label or a box.
const SHAPE_PENCIL = '#94a2b5', SHAPE_FAINT = '#333c49', SHAPE_FILL = '#111823', SHAPE_INK = '#d5e4f0',
      SHAPE_RED = '#ff4b3a', SHAPE_BLACK = '#080b11', SHAPE_EDGE = '#6d7d92', SHAPE_WARN = '#ffb454';
const CABLE_NOTE = 'black cables only with polarity marking in the field';
let sldShapes = null;                                  // the prepared drawing now on the screen
let shapeHover = null;                                 // the link the pointer is over, if any
// ---- the layer -------------------------------------------------------------------------------
function shapeLayer(){
  let el = document.getElementById('sldshapes');
  if (!el) { el = document.createElement('canvas'); el.id = 'sldshapes'; el.setAttribute('aria-hidden', 'true');
    const st = document.createElement('style');
    st.textContent = '#sldshapes{position:fixed;inset:0;z-index:2;pointer-events:none}';
    document.head.append(st);
    const c = document.getElementById('c');
    if (c && c.parentNode) c.parentNode.insertBefore(el, c.nextSibling); else document.body.append(el); }
  return el;
}
// the drawing's own units to the screen, by the same arithmetic the words overlay uses
function shapeScale(){ return Math.sqrt(SPACE) * BODY_RADIUS_MAX * zoom; }
function shapePoint(p){ const R = Math.sqrt(SPACE), f = BODY_RADIUS_MAX;
  return [(p[0] * R * f - cx) * zoom + innerWidth / 2, innerHeight / 2 - (p[1] * R * f - cy) * zoom]; }
function shapesGone(){ sldShapes = null; shapeHover = null;
  const el = document.getElementById('sldshapes'); if (!el) return;
  const ctx = el.getContext && el.getContext('2d');
  if (ctx) { ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.clearRect(0, 0, el.width, el.height); } }
// ---- polyline arithmetic ---------------------------------------------------------------------
function polyLen(pts){ let t = 0; const cum = [0];
  for (let i = 1; i < pts.length; i++) { t += Math.hypot(pts[i][0] - pts[i-1][0], pts[i][1] - pts[i-1][1]); cum.push(t); }
  return { total:t, cum }; }
function polyAt(pts, cum, total, u){ const want = Math.max(0, Math.min(1, u)) * total;
  for (let i = 1; i < pts.length; i++) if (cum[i] >= want || i === pts.length - 1) {
    const seg = (cum[i] - cum[i-1]) || 1, t = Math.min(1, Math.max(0, (want - cum[i-1]) / seg));
    return [pts[i-1][0] + (pts[i][0] - pts[i-1][0]) * t, pts[i-1][1] + (pts[i][1] - pts[i-1][1]) * t, i]; }
  return [pts[0][0], pts[0][1], 1]; }
function polySlice(pts, u0, u1){ const m = polyLen(pts); if (m.total < 1e-12 || u1 <= u0 + 1e-9) return [];
  const a = polyAt(pts, m.cum, m.total, u0), b = polyAt(pts, m.cum, m.total, u1), out = [[a[0], a[1]]];
  for (let i = a[2]; i < b[2]; i++) out.push(pts[i]);
  out.push([b[0], b[1]]); return out; }
function polyThin(pts, n){ const m = polyLen(pts), out = [];               // the same curve, fewer points
  for (let i = 0; i <= n; i++) { const p = polyAt(pts, m.cum, m.total, i / n); out.push([p[0], p[1]]); }
  return out; }
function bez(p0, c0, c1, p1, n){ const out = [];
  for (let i = 0; i <= n; i++) { const t = i / n, u = 1 - t, a = u*u*u, b = 3*u*u*t, c = 3*u*t*t, d = t*t*t;
    out.push([a*p0[0] + b*c0[0] + c*c1[0] + d*p1[0], a*p0[1] + b*c0[1] + c*c1[1] + d*p1[1]]); }
  return out; }
// THE POTENTIAL AS A COLOUR: black at the - end of the string, red at the +. Nothing in between is
// either, which is the point: only the two home runs are at a whole polarity.
function potColour(t){ const u = Math.max(0, Math.min(1, t));
  const r = Math.round(10 + 245 * Math.pow(u, 0.75)), g = Math.round(12 + 63 * u * u), b = Math.round(18 + 40 * u * u);
  return 'rgb(' + r + ',' + g + ',' + b + ')'; }

// ===== ONE STRING, DRAWN AS A WIRING DRAWING ===================================================
// The row as it really stands: every module a rectangle of its true proportions with its cells in
// hairlines, its two junction boxes where they truly are (a split box at mid height on the back,
// box_spacing_m apart, centred on the width), each box MARKED - or + in text and not by colour alone,
// its lead leaving it at the lead's own length and ending in a connector. Where two connectors do not
// meet, the gap between them is the shortfall, drawn as a gap and given in metres.
function stringDrawing(g){
  const c = g.c, N = g.N, pitch = g.pitch;
  const wM = c.width_m, hM = (c.module_height_m === undefined ? 2.384 : +c.module_height_m);
  const cols = Math.max(1, Math.round(c.cell_cols === undefined ? 6 : c.cell_cols));
  const rows = Math.max(2, Math.round(c.cell_rows === undefined ? 22 : c.cell_rows));
  const boxW = 0.22, boxH = 0.15, boxY = hM / 2;
  const vmp = c.module_vmp === undefined ? 38.1 : +c.module_vmp, vString = N * vmp;
  const shapes = [], marks = [], words = [];
  const chain = 2 * N;                                              // home-, module, link, module ... home+
  let put = o => { shapes.push(o); return o; };
  const put0 = put;
  put = o => { if (o.pot === undefined) o.pot = 0; o.volts = o.pot * vString; o.earth_v = (o.pot - 0.5) * vString;
    if (o.node === undefined) o.node = null; return put0(o); };
  const poly = (role, o, pts, extra) => put(Object.assign({ role, order:o, pot:0, pts, weight:1 }, extra || {}));
  const box = (role, o, x0, y0, x1, y1, extra) => poly(role, o, [[x0,y0],[x1,y0],[x1,y1],[x0,y1],[x0,y0]], extra);

  // ---- the inverter: a filled block with a - terminal and a + terminal, both marked
  const invW = 3.0, standOff = 2.2;
  const invX1 = -standOff, invX0 = invX1 - invW, invY0 = 0.05, invY1 = hM - 0.05;
  const negY = invY1 - (invY1 - invY0) * 0.26, posY = invY0 + (invY1 - invY0) * 0.26;
  box('inverter', 0, invX0, invY0, invX1, invY1, { fill:SHAPE_FILL, node:'inv' });
  for (const [y, sign] of [[negY, '−'], [posY, '+']]) {
    poly('terminal', 0, [[invX1, y], [invX1 + 0.16, y]], { node:'inv' });
    put({ role:'terminal', order:0, pot:sign === '+' ? 1 : 0, node:'inv', pts:[[invX1 + 0.16, y]], dot:0.10 });
    marks.push({ x:invX1 - 0.30, y, text:sign, size:12, colour:sign === '+' ? SHAPE_RED : SHAPE_EDGE, minPx:14 }); }

  // ---- the modules, to true proportion, with their cells and their two boxes
  const turned = k => g.turned(k);
  for (let k = 1; k <= N; k++) {
    const x0 = (k - 1) * pitch, x1 = x0 + wM, o = (2 * g.order.indexOf(k) + 1) / chain, pot = (g.order.indexOf(k) + 1) / N;
    box('module', o, x0, 0, x1, hM, { fill:'#0c1119', node:'M' + k, weight:1 });
    // THE CELLS. This module class is cols x rows half cells with the break across the middle where the
    // two halves meet. They are hairlines and they are dropped entirely when they would turn to mush.
    const cl = [];
    for (let i = 1; i < cols; i++) cl.push([[x0 + wM * i / cols, 0], [x0 + wM * i / cols, hM]]);
    for (let j = 1; j < rows; j++) if (j !== rows / 2) cl.push([[x0, hM * j / rows], [x1, hM * j / rows]]);
    put({ role:'cells', order:o, pot, node:'M' + k, lines:cl, pts:[[x0, 0], [x1, hM]],
          split:[[x0, hM / 2], [x1, hM / 2]] });                       // where the two halves of the module meet
    for (const [bx, sign] of [[g.minus(k), '−'], [g.plus(k), '+']]) {
      box('box', o, bx - boxW / 2, boxY - boxH / 2, bx + boxW / 2, boxY + boxH / 2, { fill:'#060a10', node:'M' + k, weight:1 });
      marks.push({ x:bx, y:boxY - boxH / 2 - 0.16, text:sign, size:11, colour:sign === '+' ? SHAPE_RED : SHAPE_INK, minPx:26, mid:true }); }
    marks.push({ x:(x0 + x1) / 2, y:-0.34, text:'M' + k, size:11, colour:SHAPE_INK, minPx:18, mid:true });
    if (turned(k)) marks.push({ x:(x0 + x1) / 2, y:-0.62, text:'turned end for end', size:9, colour:SHAPE_EDGE, minPx:44, mid:true });
  }

  // ---- the links: a curve from the + box of one module to the - box of the next, made of two leads
  let laneHi = hM, laneLo = 0;
  g.links.forEach((l, i) => {
    const xa = l.x_from, xb = l.x_to, span = Math.abs(xb - xa), dir = l.back ? -1 : 1;
    const lane = (l.back ? 2.30 : 2.05) + span * 0.30 + (i % 3) * 0.26;
    const ctrl = boxY + dir * lane, apex = boxY + dir * 0.75 * lane;
    laneHi = Math.max(laneHi, apex); laneLo = Math.min(laneLo, apex);
    const pts = bez([xa, boxY + dir * boxH / 2], [xa, ctrl], [xb, ctrl], [xb, boxY + dir * boxH / 2], 26);
    const o = (2 * i + 2) / chain, pot = (i + 1) / N;
    const need = Math.max(1e-6, l.need), lp = c.lead_plus_m, lm = c.lead_minus_m;
    const says = 'M' + l.from + '+ to M' + l.to + '−, needs ' + l.need.toFixed(2) + ' m, leads ' + g.pair.toFixed(2) + ' m'
               + (l.reaches ? '' : ', short by ' + (l.need - g.pair).toFixed(2) + ' m');
    const node = 'L' + i;
    if (l.reaches) { const t = Math.min(0.92, Math.max(0.08, lp / Math.max(1e-6, g.pair)));
      poly('lead', o, polySlice(pts, 0, t), { node, pot, plus:true, link:l, says, hit:true });
      poly('lead', o, polySlice(pts, t, 1), { node, pot, plus:false, link:l, says, hit:true });
      const m = polyLen(pts), j = polyAt(pts, m.cum, m.total, t);
      put({ role:'joint', order:o, pot, node, pts:[[j[0], j[1]]], link:l, says }); }
    else { const a = Math.min(0.86, Math.max(0.06, lp / need)), b = Math.min(0.96, Math.max(a + 0.04, 1 - lm / need));
      poly('lead', o, polySlice(pts, 0, a), { node, pot, plus:true, link:l, says, hit:true, open:true });
      poly('lead', o, polySlice(pts, b, 1), { node, pot, plus:false, link:l, says, hit:true, open:true });
      const m = polyLen(pts), p0 = polyAt(pts, m.cum, m.total, a), p1 = polyAt(pts, m.cum, m.total, b);
      put({ role:'gap', order:o, pot, node, pts:[[p0[0], p0[1]], [p1[0], p1[1]]], link:l, says,
            short:l.need - g.pair, mid:[(p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2] }); }
  });

  // ---- the two home runs, above everything and below everything, so they never cross a module
  const first = g.order[0], last = g.order[g.order.length - 1];
  const topLane = laneHi + 0.70, botLane = laneLo - 0.70;
  const xn = g.minus(first), xp = g.plus(last);
  const homeNeg = [[invX1 + 0.16, negY], [invX1 + 0.70, negY], [invX1 + 0.70, topLane], [xn, topLane], [xn, boxY + boxH / 2]];
  poly('cable', 0, homeNeg, { node:'home-', pot:0, plus:false, weight:1.2, says:'the home run to the string’s − end' });
  const homePos = [[invX1 + 0.16, posY], [invX1 + 0.55, posY], [invX1 + 0.55, botLane], [xp, botLane], [xp, boxY - boxH / 2]];
  poly('cable', 1, homePos, { node:'home+', pot:1, plus:true, weight:1.2,
    says:g.leap ? 'the home run from the string’s + end' : 'the far end return: one more cable, the length of the row' });

  // ---- the loop the string encloses: what a nearby stroke couples into
  const loopPts = [[xn, boxY], [xp, boxY], [xp, botLane], [invX1 + 0.55, botLane], [invX1 + 0.70, topLane], [xn, topLane], [xn, boxY]];
  put({ role:'loop', order:0, pot:0, pts:loopPts, closed:true });

  // ---- the words the drawing needs, in the page's own overlay
  words.push({ x:(invX0 + invX1) / 2, y:invY1 + 0.55, text:'INVERTER' });
  words.push({ x:xn, y:topLane + 0.40, text:'FREE − M' + first + '−' });
  words.push({ x:xp, y:botLane - 0.30, text:'FREE + M' + last + '+' });
  if (!g.leap) words.push({ x:g.row / 2, y:botLane - 0.62, text:'additional far end return, about ' + g.row.toFixed(1) + ' m' });
  words.push({ x:g.row / 2, y:botLane - 1.15, text:CABLE_NOTE, note:true });

  // ---- everything measured, then put into the page's units with the row laid out LARGE
  let x0 = 1e9, x1 = -1e9, y0 = 1e9, y1 = -1e9;
  const see = (x, y) => { if (x < x0) x0 = x; if (x > x1) x1 = x; if (y < y0) y0 = y; if (y > y1) y1 = y; };
  for (const s of shapes) { if (s.pts) for (const p of s.pts) see(p[0], p[1]); if (s.lines) for (const l of s.lines) { see(l[0][0], l[0][1]); see(l[1][0], l[1][1]); } }
  for (const m of marks) see(m.x, m.y); for (const w of words) see(w.x, w.y);
  // THE DRAWING IS NOT SQUEEZED INTO THE DISC. It is as tall as the disc and as wide as it needs to be,
  // which for thirty modules is several screens: the view opens on the near end and the reader drags.
  const S = 1.85 / Math.max(0.5, y1 - y0), my = (y0 + y1) / 2, mx = x0;
  const U = (x, y) => [(x - mx) * S - 0.95, (y - my) * S];
  for (const s of shapes) { if (s.pts) s.pts = s.pts.map(p => U(p[0], p[1]));
    if (s.split) s.split = s.split.map(p => U(p[0], p[1]));
    if (s.lines) s.lines = s.lines.map(l => [U(l[0][0], l[0][1]), U(l[1][0], l[1][1])]);
    if (s.mid) s.mid = U(s.mid[0], s.mid[1]); }
  for (const m of marks) { const u = U(m.x, m.y); m.x = u[0]; m.y = u[1]; }
  for (const w of words) { const u = U(w.x, w.y); w.x = u[0]; w.y = u[1]; }
  const open = g.short.length > 0;
  return { kind:'string', shapes, marks, words, perM:S, open, g, volts:vString, earth_node:'earth',
           bounds:{ x0:U(x0, y0)[0], y0:U(x0, y0)[1], x1:U(x1, y1)[0], y1:U(x1, y1)[1] },
           near:{ x:U(invX0, boxY)[0], y:U(invX0, boxY)[1] }, mPerUnit:1 / S,
           amps:open ? 0 : c.amps, front:-1, t0:0 };
}
// THE DOTS COME FROM THE SAME DRAWING. They are the entrance and nothing else: they fly in from the
// record, settle along the conductors and the frames, and melt away under the line as it fuses. They
// are kept off the cells, the boxes and the words, where they would sit on top of what must be read.
function stringPieces(g){
  const d = g.__draw || (g.__draw = stringDrawing(g)), P = [];
  const line = (tag, o, a, b) => { const len = Math.hypot(b[0] - a[0], b[1] - a[1]);
    if (len > 1e-7) P.push({ tag, d:o, flat:true, kind:'line', x0:a[0], y0:a[1], x1:b[0], y1:b[1], len }); };
  const ring = (tag, o, cx0, cy0, r) => P.push({ tag, d:o, flat:true, kind:'ring', cx:cx0, cy:cy0, r, len:2 * Math.PI * r });
  const track = (tag, o, pts) => { if (!pts || pts.length < 2) return; const m = polyLen(pts);
    if (m.total > 1e-7) P.push({ tag, d:o, flat:true, kind:'path', pts, cum:m.cum, len:m.total }); };
  for (const s of d.shapes) {
    if (s.role === 'inverter') { const c0 = [(s.pts[0][0] + s.pts[1][0]) / 2, (s.pts[0][1] + s.pts[2][1]) / 2];
      ring('inv', 0, c0[0], c0[1], Math.abs(s.pts[2][1] - s.pts[0][1]) * 0.32); continue; }
    if (s.role === 'module') { line('mod', s.order, s.pts[0], s.pts[1]); line('mod', s.order, s.pts[2], s.pts[3]); continue; }
    if (s.role === 'lead') { track((s.open ? 'short' : 'lead') + s.node, s.order, s.pts); continue; }
    if (s.role === 'cable') { track(s.node === 'home+' ? 'ret' : 'home', s.order, s.pts); continue; }
  }
  return P;
}
function stringFinal(net, tag){
  return tag.map(t => t === 'inv' ? 0.95 : t === 'home' || t === 'ret' ? 0.9 : t === 'mod' ? 0.30
    : t.indexOf('short') === 0 ? 2 : 0.95);
}
// ---- the renderer -----------------------------------------------------------------------------
// One pass, back to front: the loop shading, then the fused conductors, then the pencil drawing, then
// the boxes and the words. Nothing that is only decoration is ever drawn over something that must be
// read. Everything is in device pixels and every word is put on a whole pixel.
function drawSldShapes(){
  const el = document.getElementById('sldshapes'); if (!el) return;
  const dpr = Math.max(1, Math.min(3, window.devicePixelRatio || 1));
  const W = Math.max(1, Math.round(innerWidth * dpr)), H = Math.max(1, Math.round(innerHeight * dpr));
  if (el.width !== W || el.height !== H) { el.width = W; el.height = H; }
  const ctx = el.getContext('2d'); if (!ctx) return;
  ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, innerWidth, innerHeight);
  const D = sldShapes; if (!D) return;
  if (typeof body === 'undefined' || !body || !body.sld || !body.shown || bodyAnim || !sldNow) return;
  const px = shapeScale();                                     // screen pixels to one drawing unit
  const perM = D.perM * px;                                    // screen pixels to one metre
  const fine = 1.1, hair = 0.7;
  ctx.lineCap = 'round'; ctx.lineJoin = 'round';
  const S = p => shapePoint(p);
  const path = pts => { const s = pts.map(S); ctx.beginPath(); ctx.moveTo(s[0][0], s[0][1]);
    for (let i = 1; i < s.length; i++) ctx.lineTo(s[i][0], s[i][1]); return s; };
  const onScreen = pts => { for (const p of pts) { const s = S(p);
    if (s[0] > -60 && s[0] < innerWidth + 60 && s[1] > -60 && s[1] < innerHeight + 60) return true; } return false; };
  const front = D.front;
  // 1. THE LOOP THE STRING ENCLOSES, very faintly. The band between the conductor going out and the
  //    conductor coming back is where the energy actually travels, and it is the same area a nearby
  //    lightning stroke couples into: a long open ribbon for a sequential string, a sliver for leapfrog.
  for (const s of D.shapes) if (s.role === 'loop' && onScreen(s.pts)) {
    path(s.pts); ctx.closePath(); ctx.fillStyle = 'rgba(94,200,242,0.035)'; ctx.fill(); }
  // 2. THE CONDUCTORS. Fused behind the front, pencil ahead of it; a gap is always a gap.
  for (const s of D.shapes) {
    if (s.role !== 'lead' && s.role !== 'cable') continue;
    if (!s.pts.length || !onScreen(s.pts)) continue;
    // THE FRONT LEAVES THE MODULES AND REACHES THE INVERTER LAST, on both conductors at once.
    const fused = front >= 0 && Math.abs((s.order === undefined ? 0.5 : s.order) - 0.5) <= front * 0.5 + 1e-6;
    const lit = shapeHover && shapeHover === s.node;
    const w = fine * (s.weight || 1) * (fused ? 1 + 0.45 * Math.min(1, (D.amps || 0) / 20) : 1);
    path(s.pts); ctx.lineWidth = w + (lit ? 1.6 : fused ? 0.7 : 0.8); ctx.strokeStyle = lit ? '#eaf6ff' : (s.open ? SHAPE_WARN : SHAPE_EDGE); ctx.stroke();
    path(s.pts); ctx.lineWidth = w; ctx.strokeStyle = fused ? potColour(s.pot === undefined ? 0 : s.pot) : (s.open ? '#3a3020' : SHAPE_BLACK); ctx.stroke();
    if (!fused) { path(s.pts); ctx.lineWidth = hair; ctx.strokeStyle = s.open ? SHAPE_WARN : SHAPE_PENCIL; ctx.stroke(); } }
  // 3. THE GAP, and what it is short by, said in metres
  for (const s of D.shapes) { if (s.role !== 'gap' || !onScreen(s.pts)) continue;
    const a = S(s.pts[0]), b = S(s.pts[1]);
    ctx.setLineDash([2.5, 3.5]); ctx.beginPath(); ctx.moveTo(a[0], a[1]); ctx.lineTo(b[0], b[1]);
    ctx.lineWidth = hair; ctx.strokeStyle = SHAPE_WARN; ctx.stroke(); ctx.setLineDash([]);
    for (const p of [a, b]) { ctx.beginPath(); ctx.arc(p[0], p[1], 1.9, 0, 6.2832); ctx.fillStyle = SHAPE_WARN; ctx.fill(); }
    // WHAT IT IS SHORT BY, only when there is room for it to be read and never over a module's name.
    if (perM > 46) { const m = S(s.mid); ctx.font = '600 10px ui-monospace,Menlo,Consolas,monospace';
      ctx.textAlign = 'center'; ctx.fillStyle = SHAPE_WARN;
      ctx.fillText(s.short.toFixed(2) + ' m short', Math.round(m[0]), Math.round(m[1]) - 7); } }
  // 4. THE MODULES: the frame, a quiet fill so it reads as a body, and the cells in hairlines
  for (const s of D.shapes) {
    if (s.role === 'module' || s.role === 'inverter') { if (!onScreen(s.pts)) continue;
      path(s.pts); ctx.closePath(); if (s.fill) { ctx.fillStyle = s.fill; ctx.fill(); }
      ctx.lineWidth = fine; ctx.strokeStyle = s.role === 'inverter' ? SHAPE_INK : SHAPE_PENCIL; ctx.stroke(); continue; }
    // THE CELLS THIN OUT BEFORE THEY TURN TO MUSH. At whole row zoom they are not drawn at all; they
    // appear when a reader is close enough for them to be crisp, and never as a grey wash.
    if (s.role === 'cells') { if (perM < 34 || !onScreen(s.pts)) continue;
      ctx.lineWidth = hair; ctx.strokeStyle = SHAPE_FAINT; ctx.beginPath();
      for (const l of s.lines) { const a = S(l[0]), b = S(l[1]); ctx.moveTo(a[0], a[1]); ctx.lineTo(b[0], b[1]); }
      ctx.stroke();
      if (s.split) { const a = S(s.split[0]), b = S(s.split[1]);
        ctx.beginPath(); ctx.moveTo(a[0], a[1]); ctx.lineTo(b[0], b[1]);
        ctx.lineWidth = 1; ctx.strokeStyle = SHAPE_EDGE; ctx.stroke(); }
      continue; }
    if (s.role === 'box') { if (!onScreen(s.pts)) continue;
      path(s.pts); ctx.closePath(); ctx.fillStyle = '#05080d'; ctx.fill();
      ctx.lineWidth = fine; ctx.strokeStyle = SHAPE_INK; ctx.stroke(); continue; }
    if (s.role === 'terminal' && s.pts.length > 1) { if (!onScreen(s.pts)) continue;
      path(s.pts); ctx.lineWidth = fine; ctx.strokeStyle = SHAPE_INK; ctx.stroke(); continue; }
    if (s.role === 'joint' && perM > 18) { const p = S(s.pts[0]);
      if (p[0] < -20 || p[0] > innerWidth + 20) continue;
      ctx.beginPath(); ctx.arc(p[0], p[1], 1.7, 0, 6.2832); ctx.fillStyle = '#0a0d13'; ctx.fill();
      ctx.lineWidth = hair; ctx.strokeStyle = SHAPE_INK; ctx.stroke(); } }
  // 5. THE MARKS: - and + beside every box and terminal, and the module's name under it, on whole pixels
  ctx.textBaseline = 'middle';
  for (const m of D.marks) { if (perM < (m.minPx || 0)) continue;
    const p = S([m.x, m.y]); if (p[0] < -40 || p[0] > innerWidth + 40 || p[1] < -20 || p[1] > innerHeight + 20) continue;
    ctx.font = '600 ' + m.size + 'px ui-monospace,Menlo,Consolas,monospace';
    ctx.textAlign = m.mid ? 'center' : 'left'; ctx.fillStyle = m.colour;
    ctx.fillText(m.text, Math.round(p[0]), Math.round(p[1])); }
  ctx.textAlign = 'left'; ctx.textBaseline = 'alphabetic';
}
// ---- what the pointer is over -----------------------------------------------------------------
// A HOVER OR A TAP LIGHTS ONE WHOLE LINK AND NAMES IT. It never takes the pointer: this layer has no
// pointer events at all, the window listens, and the shell's own tap on a dot is untouched.
function shapeAsk(px0, py0){
  const D = sldShapes; if (!D) return null;
  let best = null, bd = 14;
  for (const s of D.shapes) { if (!s.hit || !s.pts || s.pts.length < 2) continue;
    const pts = s.pts.map(shapePoint);
    for (let i = 1; i < pts.length; i++) { const a = pts[i-1], b = pts[i];
      const dx = b[0] - a[0], dy = b[1] - a[1], L = dx*dx + dy*dy;
      let t = L > 0 ? ((px0 - a[0]) * dx + (py0 - a[1]) * dy) / L : 0; t = Math.max(0, Math.min(1, t));
      const d = Math.hypot(px0 - (a[0] + t*dx), py0 - (a[1] + t*dy));
      if (d < bd) { bd = d; best = s; } } }
  return best;
}
function shapeTrack(e){
  if (!sldShapes || !body || !body.sld || !body.shown || bodyAnim) { if (shapeHover) { shapeHover = null; dirty = true; } return; }
  const s = shapeAsk(e.clientX, e.clientY), node = s ? s.node : null;
  if (node === shapeHover) return;
  shapeHover = node; sldShapes.saying = s ? s.says : null; dirty = true; placeSldNames();
}
addEventListener('pointermove', shapeTrack, { passive:true });
addEventListener('pointerdown', shapeTrack, { passive:true });
// AFTER EVERY FRAME THE SHELL DRAWS, not on a loop of this file's own and not on a guessed list of
// events: the shell says it has drawn, and the words and the drawing are put where the dots are.
try { if (window.__wafer && window.__wafer.onDraw) window.__wafer.onDraw.add(function(){ try { placeSldNames(); drawSldShapes(); } catch (_) {} }); } catch (_) {}
// ===== ANY RADIAL NETWORK, DRAWN BY THE DOTS: fire network {"seed":N} ==========================
// The generator's network (a star, a chain, a tree, sub-boards) laid out as a single line diagram: the busbar on top, every
// substation in its own column, a branch leaving its parent's tee sideways and then down, so no two lines ever share a place.
function netPieces(net){
  const P = [], subs = net.subs, n = subs.length, kids = {}; subs.forEach(s => (kids[s.parent] = kids[s.parent] || []).push(s.n));
  const col = {}, depth = {}; let c = 0;
  (function walk(p, d){ for (const k of (kids[p] || [])) { col[k] = c++; depth[k] = d; walk(k, d + 1); } })(0, 1);
  const maxD = Math.max(...Object.values(depth)), dy = Math.min(0.17, 1.05 / maxD), X = k => n === 1 ? 0 : -0.9 + 1.8 * col[k] / (n - 1), Y = k => 0.37 - dy * (depth[k] - 1) - 0.05;
  const line = (tag, d, x0, y0, x1, y1) => { const len = Math.hypot(x1 - x0, y1 - y0); if (len > 1e-6) P.push({ tag, d, kind:'line', x0, y0, x1, y1, len }); return d + len; };
  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.9, 0.06); let d0 = line('poc', 0.06, 0, 0.83, 0, 0.66); line('poc', d0, -0.06, 0.65, 0.06, 0.65); d0 = line('board', d0, 0, 0.63, 0, 0.45);
  line('bus', d0, -0.95, 0.43, 0.95, 0.43); line('bus', d0, -0.95, 0.405, 0.95, 0.405);
  const teeD = { 0: d0 };
  const sym = (tagT, tagL, tagP, d, x, y, s, r) => {                     // transformer, load and any solar, hanging from (x, y)
    let dd = line(tagT, d, x, y - 0.012, x, y - 0.04); ring(tagT, dd, x, y - 0.04 - r, r); ring(tagT, dd + 0.05, x, y - 0.04 - 3 * r - 0.012, r);
    const yl = y - 0.04 - 4 * r - 0.024; dd = line(tagT, dd + 0.1, x, yl, x, yl - 0.05);
    line(tagL, dd, x - 0.03, yl - 0.06, x, yl - 0.105); line(tagL, dd, x + 0.03, yl - 0.06, x, yl - 0.105);
    if (s.pv_kw > 0) { const sx = x + 0.06; line(tagP, dd, x + 0.012, yl - 0.025, sx - 0.03, yl - 0.025); ring(tagP, dd + 0.05, sx, yl - 0.025, 0.026); ring(tagP, dd + 0.05, sx, yl - 0.025, 0.009); }
    if (net.generator_at === s.n && net.generator_kw > 0) { const gx = x - 0.06; line('gen', dd, x - 0.012, yl - 0.025, gx + 0.03, yl - 0.025); ring('gen', dd + 0.05, gx, yl - 0.025, 0.028); } };
  if (net.generator_at === 0 && net.generator_kw > 0) { line('gen', d0, -0.75, 0.455, -0.75, 0.56); ring('gen', d0 + 0.15, -0.75, 0.62, 0.06); }
  const r = Math.min(0.032, 0.6 / n / 2.4 + 0.012);
  (function walk(p){ for (const k of (kids[p] || [])) { const s = subs[k - 1], x = X(k), y = Y(k), t = 'hv' + k; let d;
      if (p === 0) d = line(t, teeD[0] + Math.abs(x), x, 0.393, x, y);
      else { d = line(t, teeD[p], X(p) + 0.012, Y(p), x, Y(p)); d = line(t, d, x, Y(p) - 0.012, x, y); }
      teeD[k] = d; sym('tx' + k, 'load' + k, 'pv' + k, d, x, y, s, r); walk(k); } })(0);
  let far = 0; for (const p of P) far = Math.max(far, p.kind === 'ring' ? Math.hypot(p.cx, p.cy) + p.r : Math.max(Math.hypot(p.x0, p.y0), Math.hypot(p.x1, p.y1)));
  const k = 0.98 / Math.max(0.98, far);                                   // the whole drawing inside the disc
  for (const p of P) { if (p.kind === 'ring') { p.cx *= k; p.cy *= k; p.r *= k; } else { p.x0 *= k; p.y0 *= k; p.x1 *= k; p.y1 *= k; } p.len *= k; }
  return P;
}
function netFinal(model, tag){
  const net = model.net, r = model.solved, e = r.each, c = window.FIRE.topo.C, over = Math.max(0, -r.p) > net.export_limit_kw, aMax = Math.max(1e-9, r.amps);
  const bad = v => v > c.volts_high_pu || v < c.volts_low_pu;
  return tag.map(t => { if (t === 'grid') return 0.95; if (t === 'poc') return over ? 2 : 0.95; if (t === 'board') return 0.9; if (t === 'bus') return bad(e.volts.board) ? 2 : 0.95;
    if (t === 'gen') return model.inputs.generator ? 1 : -1;
    const k = t.replace(/\D/g, '');
    if (t.startsWith('pv')) return (model.inputs.solar === undefined ? 1 : model.inputs.solar) > 0 ? 1 : -1;
    if (t.startsWith('load')) return bad(e.volts['lv' + k]) ? 2 : 0.85;
    if (t.startsWith('tx')) return e.tx['lv' + k] > 100 ? 2 : 0.3 + 0.65 * Math.min(1, e.tx['lv' + k] / 100);
    return bad(e.volts['hv' + k]) ? 2 : 0.3 + 0.65 * Math.min(1, e.amps['hv' + k] / aMax); });
}

// ===== THE POINTER IS ALWAYS LET GO ==============================================================
// THE FAULT: the shell answers a tap on body dot j with commits[iso.idx[j]] and calls pointerGone(e)
// AFTERWARDS. A drawn diagram has 896 dots and an application has however many pieces of work it has,
// so for most dots iso.idx[j] was undefined, reading .k0 of undefined threw, pointerGone never ran,
// the pointer stayed in the map and the disc went on following a mouse whose button was up. The cure
// above gives every diagram dot its own piece of work, so nothing throws. THIS is the second belt:
// whatever any handler does, the pointer is let go. A listener added here runs AFTER the shell's own
// (they are on the same target in the same phase, and an exception in one listener never stops the
// next), so a throw anywhere in the shell's answer can no longer leave a button pressed for ever.
// It is registered from a timer so that it is registered after the shell's, whatever the load order.
setTimeout(function(){
  var net = function(e){ try { if (typeof pointerGone === 'function') pointerGone(e); } catch (_) {} };
  addEventListener('pointerup', net);