GLOBALGRID2050 / EXPLORE CODE

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

Kuiper Programs (part 78)

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.

700 lines of JavaScript from globalgrid2050, in 1 file. Topic: Kuiper, cosmos and drawing engines. Section 1336 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/i0083/cartridges/007500000000-kuiper-programs.js lines 1982–2681

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/007500000000-kuiper-programs.js · lines 1982–2681 of 2798 (continued from section 1333) · Not reached from any entry point (candidate for review) · pattern buildStringWalk (shared by 28 files)

What it does
It draws cables, solar, substations and transformers. Defines 181 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
shapeLayer, shapeScale, shapePoint, shapesGone, polyLen, polyAt, polySlice, polyThin, bez, potColour, dimColour, stringDrawing, term, put, poly, box, turned, cellX, cellY, round3, laneFor, faceX, faceY, freeRun, loopAt, needH, stubOf, round4, see, U
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/007500000000-kuiper-programs.js:1982-2681 · blob fd1c94cb3c97b4204a26c850e5e6d8a416ddd7b1 · 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
const CABLE_NOTE = 'black cables only with polarity marking in the field';
// THE LINE THAT HAS TO BE THERE EVERY TIME, in red, wherever an answer of this family is shown. It is
// not closable and it does not scroll away: this page is a place to think in, not a design.
const DEV_WARNING = 'Not real cable or array sizing - consult a design engineer. DEVELOPMENT ENVIRONMENT: estimates from a model, nothing measured.';
const DEV_WARNING_SHORT = 'Not real cable or array sizing - consult a design engineer.';
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 + ')'; }
function dimColour(css, k){ const m = /rgb\((\d+),(\d+),(\d+)\)/.exec(css);
  return m ? 'rgb(' + Math.round(m[1] * k) + ',' + Math.round(m[2] * k) + ',' + Math.round(m[3] * k) + ')' : css; }

// ===== 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 wX = g.wX, wY = g.wY, port = g.port, rows = g.rows, cols = g.cols, tableTop = g.rowY[rows - 1] + wY;
  const cellCols = Math.max(1, Math.round(c.cell_cols === undefined ? 6 : c.cell_cols));
  const cellRows = Math.max(2, Math.round(c.cell_rows === undefined ? 22 : c.cell_rows));
  // TWO VIEWS OF THE SAME STRING, and the WIRING one is what anybody actually asks a drawing for.
  // Looking at the BACK of the modules: plain backs, no cell grid, the junction boxes drawn several
  // times their real size because what is being read is WHICH BOX JOINS WHICH, and a true-to-scale box
  // at row zoom is three pixels of nothing. Every cable is a line you can follow with a finger from one
  // box terminal to the next. The other view keeps the module to scale with its cells, for when the
  // question is how big the thing is rather than how it is wired.
  const wiring = String(c.view || 'wiring').toLowerCase() !== 'scale';
  // PLAIN SMALL BOXES, the same in both views. Drawn several times life size the boxes became a strip
  // of black rectangles across the module and the drawing stopped looking like a drawing.
  const boxW = port ? 0.24 : 0.16, boxH = port ? 0.16 : 0.24;
  const boxY = g.rowY[0] + wY / 2;
  // EVERY TERMINAL IS DECLARED, by name, once. A cable may begin and end nowhere else, and that is
  // checked rather than trusted: this list is what the checks walk.
  const terminals = [];
  const term = (id, x, y, kind, module) => { terminals.push({ id, x, y, kind, module }); return [x, y]; };
  const vmp = c.module_vmp === undefined ? 38.1 : +c.module_vmp, vString = N * vmp;
  const vOpen = N * (c.module_voc === undefined ? 45.9 : +c.module_voc);
  const shapes = [], marks = [], words = [], conns = [];
  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 = boxY - 1.14, invY1 = boxY + 1.14;
  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' });
    term(sign === '+' ? 'INV+' : 'INV-', invX1 + 0.16, y, sign === '+' ? 'inv+' : 'inv-', 0);
    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 = g.x0(k), x1 = x0 + wX, yb = g.y0(k), yt = yb + wY;
    const o = (2 * g.order.indexOf(k) + 1) / chain, pot = (g.order.indexOf(k) + 1) / N;
    box('module', o, x0, yb, x1, yt, { 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.
    // THE CELLS FOLLOW THE MODULE ROUND. A module laid on its side has its columns of cells across the
    // table and its rows up it: the count belongs to the module, not to the table.
    // EVERY CELL IS A THING, not a stripe of a pattern. The grid is carried as DATA - how many across
    // and up, the gap between cells, the wider gap where the two halves of the module meet, and for
    // every cell which cell string it is in and which bypass diode guards it - because what comes next
    // is lighting, shading and faulting cells one at a time. The lines drawn from it are quiet: they sit
    // UNDER the cables, and they are only drawn when a cell is wide enough on the screen to be a cell.
    const cA = port ? cellCols : cellRows, cB = port ? cellRows : cellCols;
    const gapC = 0.002, midG = 0.012;                       // between cells, and across the middle of the module
    const cw = (wX - gapC * (cA - 1)) / cA, ch = (wY - gapC * (cB - 1) - midG) / cB;
    const cellX = i2 => x0 + i2 * (cw + gapC);
    const cellY = j2 => yb + j2 * (ch + gapC) + (j2 >= cB / 2 ? midG : 0);
    put({ role:'cells', order:o, pot, node:'M' + k, module:k, pts:[[x0, yb], [x1, yt]],
          grid:{ across:cA, up:cB, cell_w:cw, cell_h:ch, gap:gapC, mid_gap:midG, x0, y0:yb,
                 cell_strings:3, diodes:3, per_string:Math.round(cA * cB / 3) } });
    // THREE SPLIT BOXES ON THE MID LINE, which is what a modern module really has: the two outer ones
    // carry the leads, one - and one +, and the middle one carries a bypass diode and nothing else.
    // Each lead leaves its box SIDEWAYS along that line and ends in a connector you can see.
    const midPt = [(g.minusPt(k)[0] + g.plusPt(k)[0]) / 2, (g.minusPt(k)[1] + g.plusPt(k)[1]) / 2];
    box('box', o, midPt[0] - boxW / 2, midPt[1] - boxH / 2, midPt[0] + boxW / 2, midPt[1] + boxH / 2,
      { fill:'#060a10', node:'M' + k, weight:1, big:wiring, diodeOnly:true });
    for (const [pt, sign] of [[g.minusPt(k), '−'], [g.plusPt(k), '+']]) {
      box('box', o, pt[0] - boxW / 2, pt[1] - boxH / 2, pt[0] + boxW / 2, pt[1] + boxH / 2,
        { fill:'#060a10', node:'M' + k, weight:1, big:wiring, diode:true });
      term('M' + k + (sign === '+' ? '+' : '-'), pt[0], pt[1], sign === '+' ? 'module+' : 'module-', k);
      marks.push({ x:pt[0] + (port ? 0 : boxW * 0.5 + 0.17), y:pt[1] - (port ? boxH / 2 + 0.17 : 0),
        text:sign, size:11, colour:sign === '+' ? SHAPE_RED : SHAPE_INK, minPx:22, mid:port, rank:0 }); }
    marks.push({ x:(x0 + x1) / 2, y:yb - 0.34, text:'M' + k, size:11, colour:SHAPE_INK, minPx:18, mid:true, rank:0, dodge:true });
    if (turned(k)) marks.push({ x:(x0 + x1) / 2, y:yb - 0.62, text:'rear', size:9, colour:SHAPE_EDGE, minPx:60, mid:true, dodge:true, rank:3 });
  }
  // WHAT HOLDS THE TABLE UP, where it changes the geometry: the ridge of an east west table and the
  // torque tube of a tracker are each drawn as the one fine line they are.
  for (let r = 0; r + 1 < rows; r++) { const gapTop = g.rowY[r + 1], gapBot = g.rowY[r] + wY;
    if (gapTop - gapBot > c.gap_up_m + 1e-6) poly('tube', 0, [[-0.4, (gapTop + gapBot) / 2], [cols * g.pitch + 0.2, (gapTop + gapBot) / 2]], { node:'tube' }); }

  // ---- the links: a curve from the + box of one module to the - box of the next, made of two leads
  let laneHi = tableTop, laneLo = g.rowY[0];
  // A LEAD IS NOT AN ARCH, AND IT IS NOT SCATTERED EITHER. It leaves its own box, runs behind the
  // modules and plugs into the box it mates with, and the line drawn here is THAT ROUTE, AT ITS TRUE
  // LENGTH: 0.84 m of lead is 0.84 m of line at this drawing's scale.
  // HOW AN INSTALLER CLIPS CABLE, WHICH IS THE WHOLE OF IT. A cable on the back of a table is not hung
  // and it does not wander: it leaves the box face SQUARE ON, runs the short way to a CLIP LINE that
  // runs parallel to the row of boxes, runs ALONG that line, and turns square into the box it mates
  // with. Corners are rounded, because a square corner is a busbar and not a cable.
  // TWO CLIP LINES AND NO MORE: one clearly ABOVE the row of boxes for the links on the way out, one
  // clearly BELOW it for the links on the way back, so an out link can never meet a return link. Each
  // line stands at least CLIP_CLEAR of a MODULE HEIGHT off the row. That distance is the point: a
  // drawing that put the lines a few centimetres off the boxes turned the row into one thick smudge in
  // which nothing could be followed, and no cable may hug the boxes it is not going into.
  // PARALLEL RUNS ARE BESIDE EACH OTHER, NEVER ON TOP OF EACH OTHER. Two links whose runs share any
  // stretch of the same clip line are put in their own LANES, one cable spacing apart, chosen by the
  // stretch each one really occupies, so a return line carrying several cables reads as several cables.
  // Colour stays with POLARITY, not with direction: red is the + lead and black the -.
  // THE SPARE CABLE IS ONE SMALL SERVICE LOOP AT THE MATED CONNECTOR, which is where a jointer really
  // leaves it. It is not spent raising the run, because the run's height is the clip line's and belongs
  // to the table, not to this link.
  const stub = Math.max(0.13, wX * 0.22), lip = boxW * 0.60;
  const CLIP_CLEAR = 0.18, CABLE_SPACING = Math.max(0.06, boxH * 0.5);
  const clipBase = Math.max(CLIP_CLEAR * wY, boxH / 2 + 0.08);
  const bendR = Math.min(0.13, boxH * 0.55, CABLE_SPACING * 0.9);
  // ROUNDED CORNERS, the same little fillet at every turn of every clipped cable.
  const round3 = (pp, r2) => { if (pp.length < 3) return pp.slice(); const out = [pp[0]];
    for (let i2 = 1; i2 + 1 < pp.length; i2++) { const a2 = pp[i2 - 1], b2 = pp[i2], c2 = pp[i2 + 1];
      const u1 = [a2[0] - b2[0], a2[1] - b2[1]], u2 = [c2[0] - b2[0], c2[1] - b2[1]];
      const L1 = Math.max(1e-6, Math.hypot(u1[0], u1[1])), L2 = Math.max(1e-6, Math.hypot(u2[0], u2[1]));
      const k1 = Math.min(r2, L1 * 0.45), k2 = Math.min(r2, L2 * 0.45);
      const s1 = [b2[0] + u1[0] / L1 * k1, b2[1] + u1[1] / L1 * k1], s2 = [b2[0] + u2[0] / L2 * k2, b2[1] + u2[1] / L2 * k2];
      out.push(s1); for (let q = 1; q < 5; q++) { const t2 = q / 5, w2 = (1 - t2) * (1 - t2), mm = 2 * (1 - t2) * t2, e2 = t2 * t2;
        out.push([w2 * s1[0] + mm * b2[0] + e2 * s2[0], w2 * s1[1] + mm * b2[1] + e2 * s2[1]]); }
      out.push(s2); }
    out.push(pp[pp.length - 1]); return out; };
  // THE LANE A RUN GETS: the lowest one on its own clip line that nothing already on it overlaps.
  const lanes = {};
  const laneFor = (key, a, b) => { const lo = Math.min(a, b) - CABLE_SPACING * 0.5, hi = Math.max(a, b) + CABLE_SPACING * 0.5;
    const rowsK = lanes[key] || (lanes[key] = []);
    for (let n = 0; n < rowsK.length; n++) if (rowsK[n].every(s => hi <= s[0] || lo >= s[1])) { rowsK[n].push([lo, hi]); return n; }
    rowsK.push([[lo, hi]]); return rowsK.length - 1; };
  const faceX = (bx, towards) => bx + (towards >= bx ? 1 : -1) * boxW / 2;
  const faceY = (by, towards) => by + (towards >= by ? 1 : -1) * boxH / 2;
  // WHERE THE BOXES ARE, so no cable is ever drawn through one it does not plug into. The rectangles
  // are the ones already drawn above, read back, so there is one truth and not a second copy.
  const BOX_MARGIN = Math.max(0.03, boxW * 0.18);
  const boxRects = shapes.filter(s => s.role === 'box' && s.pts).map(s => {
    let a = 1e9, b = 1e9, cc = -1e9, dd = -1e9;
    for (const z of s.pts) { a = Math.min(a, z[0]); cc = Math.max(cc, z[0]); b = Math.min(b, z[1]); dd = Math.max(dd, z[1]); }
    return { node:s.node, x0:a, y0:b, x1:cc, y1:dd }; });
  // HOW FAR A RUN ALONG A CLIP LINE MAY GO BEFORE IT MUST STOP: up to the near face of the first box
  // that is not its own, with a clear margin, and never one millimetre past it.
  const freeRun = (x, y, dirx, mine) => { let best = Infinity;
    for (const r of boxRects) { if (r.node === mine) continue;
      if (y < r.y0 - BOX_MARGIN || y > r.y1 + BOX_MARGIN) continue;
      const far = (dirx > 0 ? r.x1 + BOX_MARGIN : r.x0 - BOX_MARGIN - 0) ;
      if ((far - x) * dirx <= 0) continue;                       // the box is behind this run
      const near = dirx > 0 ? r.x0 - BOX_MARGIN : r.x1 + BOX_MARGIN;
      best = Math.min(best, Math.max(0, (near - x) * dirx)); }
    return best; };
  // A SERVICE LOOP OF EXACTLY THE SPARE CABLE, coiled at the connector the way a jointer leaves it.
  const loopAt = (p, tx, ty, side, extra) => { const rr = extra / (2 * 18 * Math.sin(Math.PI / 18)), ring = [];
    const cxx = p[0] - ty * side * rr, cyy = p[1] + tx * side * rr, a0 = Math.atan2(p[1] - cyy, p[0] - cxx);
    for (let q = 1; q <= 18; q++) { const a = a0 + 6.2832 * side * q / 18; ring.push([cxx + Math.cos(a) * rr, cyy + Math.sin(a) * rr]); }
    ring[ring.length - 1] = [p[0], p[1]];
    laneHi = Math.max(laneHi, cyy + rr); laneLo = Math.min(laneLo, cyy - rr);
    return ring; };
  // EVERY CONDUCTOR RUNS BETWEEN THE TWO TERMINALS THE MODEL SAYS IT JOINS, and nowhere else. The link
  // list is the netlist: out along the odd modules, M1+ to M3-, M3+ to M5-, and back through the even
  // ones. Nothing is drawn from a module to itself, nothing leaves the middle box - the middle box has
  // no lead, it holds a diode - and nothing is invented to make the picture tidy.
  //
  // AND EVERY LEAD IS ITS TRUE LENGTH. The drawing is to scale, so a lead of 0.30 m is 0.30 m of line.
  // Two leads that reach are drawn as one curve whose ARC LENGTH is the two lead lengths added: the
  // spare cable shows as the gentle bow it really makes, not as a decorative arch. Two leads that do
  // NOT reach are drawn straight out from their own boxes, each to its own length, each ending in its
  // connector, with nothing at all between them. The gap IS the message: no dashes, no dots, no amber
  // line pretending a cable is there.
  g.links.forEach((l, i) => {
    const Ac = g.plusPt(l.from), Bc = g.minusPt(l.to);
    const A = port ? [faceX(Ac[0], Bc[0]), Ac[1]] : [Ac[0], faceY(Ac[1], Bc[1])];
    const B = port ? [faceX(Bc[0], Ac[0]), Bc[1]] : [Bc[0], faceY(Bc[1], Ac[1])];
    const dx = B[0] - A[0], dy = B[1] - A[1], L = Math.max(1e-6, Math.hypot(dx, dy));
    // OUT ABOVE, RETURN BELOW: an out link is clipped to the line above the row of boxes and a return
    // link to the line below it, so two cables sharing a module are told apart by which line they are
    // on and not by a guess.
    const ux = dx / L, uy = dy / L;
    const o = (2 * i + 2) / chain, pot = (i + 1) / N;
    const lp = c.lead_plus_m, lm = c.lead_minus_m, pair = lp + lm;
    const fromId = 'M' + l.from + '+', toId = 'M' + l.to + '-';
    const node = 'L' + i;
    const says = fromId + ' to ' + toId + ', needs ' + l.need.toFixed(2) + ' m, leads ' + pair.toFixed(2) + ' m'
               + (l.reaches ? '' : ', short by ' + (l.need - pair).toFixed(2) + ' m');
    conns.push({ node, from:fromId, to:toId, needed:l.need, pair, reaches:l.reaches, jumper:l.jumper || 0 });
    if (pair >= L) {
      // SQUARE OUT OF THE BOX, ALONG THE CLIP LINE, AND SQUARE IN. Both ends start inside the face of
      // the box they name, so no cable begins in the air and none begins on a box it does not belong to.
      const up = !l.back, sgn = up ? 1 : -1, face = boxH * 0.47;
      const Ar = [Ac[0], Ac[1] + sgn * face], Br = [Bc[0], Bc[1] + sgn * face];
      const base = up ? Math.max(Ac[1], Bc[1]) + clipBase : Math.min(Ac[1], Bc[1]) - clipBase;
      const lane = laneFor((up ? 'o' : 'b') + Math.round(base * 200), Ac[0], Bc[0]);
      const cy = base + sgn * lane * CABLE_SPACING;
      // THE ROUTE MAY NEVER BE LONGER THAN THE CABLE. If the clip line stands so far off that the two
      // leads could not reach along it, the line is brought down to the height they CAN pay for, and
      // if even that is too far the pair runs straight. A drawing that shows more cable than the string
      // has is a lie, and this one would rather be plain than untrue.
      const dxAB = Math.abs(Ar[0] - Br[0]);
      const needH = h => Math.abs(h - Ar[1]) + Math.abs(h - Br[1]) + dxAB;
      let cyU = cy;
      if (needH(cyU) > pair - 0.02) {
        const room = (pair - 0.02 - dxAB) / 2, mid = (Ar[1] + Br[1]) / 2;
        const lim = up ? Math.max(Ar[1], Br[1]) : Math.min(Ar[1], Br[1]), h = mid + sgn * room;
        cyU = sgn * (h - lim) >= 0 ? h : null; }
      const raw = cyU === null ? [Ar, Br]
                : (dxAB > 1e-6 ? [Ar, [Ar[0], cyU], [Br[0], cyU], Br] : [Ar, [Ar[0], cyU], Br]);
      const pts = round3(raw, bendR);
      for (const q of pts) { laneHi = Math.max(laneHi, q[1]); laneLo = Math.min(laneLo, q[1]); }
      // THE LENGTH IS STILL THE CABLE'S OWN. What the clipped route does not spend is not lost and it is
      // not hidden: it is ONE small service loop at the connector that is mated, the way it is left on
      // site, so the line a finger follows is still lead-plus-lead long.
      const m2 = polyLen(pts), t = Math.min(0.92, Math.max(0.08, lp / pair));
      const j = polyAt(pts, m2.cum, m2.total, t), tan = polyAt(pts, m2.cum, m2.total, Math.min(1, t + 0.02));
      let tvx = tan[0] - j[0], tvy = tan[1] - j[1];
      const tl = Math.max(1e-6, Math.hypot(tvx, tvy)); tvx /= tl; tvy /= tl;
      // EACH LEAD IS ITS OWN TRUE LENGTH, not half a route each. The route is split where the two
      // connectors mate, and what each lead has over and above its share of the route is coiled AT that
      // connector as its own service loop - the + lead's loop one side, the - lead's the other.
      let head = polySlice(pts, 0, t); let tail = polySlice(pts, t, 1);
      const hL = polyLen(head).total, tL = polyLen(tail).total;
      if (lp - hL > 0.02) head = head.concat(loopAt(j, tvx, tvy, 1, lp - hL));
      if (lm - tL > 0.02) tail = [[j[0], j[1]]].concat(loopAt(j, tvx, tvy, -1, lm - tL), tail);
      poly('lead', o, head, { node, pot, plus:true, link:l, says, hit:true, from:fromId, to:'mate' + i, metres:lp });
      poly('lead', o, tail, { node, pot, plus:false, link:l, says, hit:true, from:'mate' + i, to:toId, metres:lm });
      put({ role:'mate', order:o, pot, node, pts:[[j[0], j[1]]], link:l, says, mated:true, along:[tvx, tvy] });
    } else {
      // NEITHER LEAD REACHES. Each is drawn straight out from its own box, at its own length, and stops.
      // NEITHER LEAD REACHES, AND A LEAD THAT DOES NOT REACH IS STILL A CLIPPED CABLE. It leaves its
      // own box square, rises to its own clip line, runs ALONG that line towards the box it cannot get
      // to, and STOPS in clear air before the first box it does not belong to - never inside one, and
      // never across the gap. What it still has in hand at that stop is coiled there, so the line is
      // its full declared length and the gap between the two connectors is the honest shortfall.
      const up = !l.back, sgn = up ? 1 : -1, face = boxH * 0.47;
      const stubOf = (Pc, mine, towardsX, metres, plus) => {
        const y0s = Pc[1] + sgn * face;
        const base = Pc[1] + sgn * clipBase;
        const lane = laneFor((up ? 'o' : 'b') + Math.round(base * 200) + 's', Pc[0], Pc[0] + (towardsX - Pc[0]) * 0.5);
        const cyS = base + sgn * lane * CABLE_SPACING;
        const rise = Math.abs(cyS - Pc[1]);
        let ptsS, endT = [0, 0];
        if (rise >= metres) { const e = [Pc[0], Pc[1] + sgn * metres]; ptsS = [Pc, e]; endT = [0, sgn]; }
        else {
          const dirx = towardsX >= Pc[0] ? 1 : -1;
          const run = Math.min(metres - rise, Math.abs(towardsX - Pc[0]) * 0.45, Math.max(0, freeRun(Pc[0], cyS, dirx, mine)));
          const e = [Pc[0] + dirx * run, cyS];
          ptsS = round3(run > 1e-6 ? [Pc, [Pc[0], cyS], e] : [Pc, [Pc[0], cyS]], bendR);
          endT = run > 1e-6 ? [dirx, 0] : [0, sgn];
        }
        const have = polyLen(ptsS).total, endP = ptsS[ptsS.length - 1];
        if (metres - have > 0.02) ptsS = ptsS.concat(loopAt(endP, endT[0], endT[1], plus ? 1 : -1, metres - have));
        for (const q of ptsS) { laneHi = Math.max(laneHi, q[1]); laneLo = Math.min(laneLo, q[1]); }
        return { ptsS, endP, endT };
      };
      const sa = stubOf(Ac, 'M' + l.from, Bc[0], lp, true);
      const sb = stubOf(Bc, 'M' + l.to, Ac[0], lm, false);
      poly('lead', o, sa.ptsS, { node, pot, plus:true, link:l, says, hit:true, open:true, from:fromId, to:'open' + i, metres:lp });
      poly('lead', o, sb.ptsS.slice().reverse(), { node, pot, plus:false, link:l, says, hit:true, open:true, from:'open' + i, to:toId, metres:lm });
      put({ role:'plug', order:o, pot, node, pts:[[sa.endP[0], sa.endP[1]]], male:true, along:sa.endT });
      put({ role:'plug', order:o, pot, node, pts:[[sb.endP[0], sb.endP[1]]], male:false, along:sb.endT });
      laneHi = Math.max(laneHi, A[1], B[1]); laneLo = Math.min(laneLo, A[1], B[1]);
    }
  });

  // ---- 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];
  laneHi = Math.max(laneHi, tableTop); laneLo = Math.min(laneLo, g.rowY[0]);
  const topLane = laneHi + 0.70, botLane = laneLo - 0.70;
  const nP = g.minusPt(first), pP = g.plusPt(last), xn = nP[0], xp = pP[0];
  // ROUNDED, like every other cable here: a square corner is a busbar, not a cable.
  const round4 = (pp, r2) => { const out = [pp[0]];
    for (let i2 = 1; i2 + 1 < pp.length; i2++) { const a2 = pp[i2 - 1], b2 = pp[i2], c2 = pp[i2 + 1];
      const u1 = [a2[0] - b2[0], a2[1] - b2[1]], u2 = [c2[0] - b2[0], c2[1] - b2[1]];
      const L1 = Math.max(1e-6, Math.hypot(u1[0], u1[1])), L2 = Math.max(1e-6, Math.hypot(u2[0], u2[1]));
      const k1 = Math.min(r2, L1 * 0.45), k2 = Math.min(r2, L2 * 0.45);
      const s1 = [b2[0] + u1[0] / L1 * k1, b2[1] + u1[1] / L1 * k1], s2 = [b2[0] + u2[0] / L2 * k2, b2[1] + u2[1] / L2 * k2];
      out.push(s1); for (let q = 1; q < 6; q++) { const t2 = q / 6, w2 = (1 - t2) * (1 - t2), m2 = 2 * (1 - t2) * t2, e2 = t2 * t2;
        out.push([w2 * s1[0] + m2 * b2[0] + e2 * s2[0], w2 * s1[1] + m2 * b2[1] + e2 * s2[1]]); }
      out.push(s2); }
    out.push(pp[pp.length - 1]); return out; };
  // THE HOME RUNS SPEAK THE SAME LANGUAGE: square out of the box face, along a line of their own well
  // clear of the row, and square into the inverter. They too end INSIDE the box they name.
  const nEdge = [xn, nP[1] + boxH * 0.47];
  const pEdge = [xp, pP[1] - boxH * 0.47];

  const homeNeg = round4([[invX1 + 0.16, negY], [invX1 + 0.70, negY], [invX1 + 0.70, topLane], [xn, topLane], nEdge], 0.45);
  conns.unshift({ node:'home-', from:'INV-', to:'M' + first + '-', needed:c.near_end_m, pair:null, reaches:true, home:true });
  conns.push({ node:'home+', from:'M' + last + '+', to:'INV+', needed:c.near_end_m, pair:null, reaches:true, home:true });
  poly('cable', 0, homeNeg, { node:'home-', pot:0, plus:false, weight:1.2, from:'INV-', to:'M' + first + '-', says:'the home run to the string’s − end' });
  // DRAWN THE WAY THE CURRENT GOES, from the string's + terminal back to the inverter's, so that the
  // line's first point IS the terminal it says it starts at. It ran the other way, and the check that
  // asks "does every cable begin on the terminal it names" found it at once.
  const homePos = round4([pEdge, [xp, botLane], [invX1 + 0.55, botLane], [invX1 + 0.55, posY], [invX1 + 0.16, posY]], 0.45);
  poly('cable', 1, homePos, { node:'home+', pot:1, plus:true, weight:1.2, from:'M' + last + '+', to:'INV+',
    says:g.bothNear ? 'the home run from the string’s + end' : 'the far end return: one more cable, ' + g.ret.toFixed(1) + ' m of it' });

  // ---- the loop the string encloses: what a nearby stroke couples into
  const loopPts = [[xn, nP[1]], [xp, pP[1]], [xp, botLane], [invX1 + 0.55, botLane], [invX1 + 0.70, topLane], [xn, topLane], [xn, nP[1]]];
  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:'inverter − to M' + first + '−' });
  words.push({ x:xp, y:botLane - 0.30, text:'M' + last + '+ to inverter +' });

  if (!g.bothNear) words.push({ x:g.row / 2, y:botLane - 0.62, text:'additional far end return, about ' + g.ret.toFixed(1) + ' m' });
  // THE KEY IS PINNED TO THE SCREEN, NOT LAID OUT IN THE DRAWING. It was written into the picture under
  // the row, which meant that the moment a reader zoomed in to read a module - the whole point of the
  // near view - the key was a hundred metres below the bottom of the screen and nobody ever saw it. A
  // key is not part of the thing it explains: it stays at the foot of the band, at every zoom, at every
  // size, without scrolling and without opening anything. The warning sits above it, in the same place.
  // EVERY LINE HAS A SHORT FORM. On a telephone the long forms wrapped into four paragraphs that took
  // half the screen and sat on the drawing, which is worse than not showing them at all. Each line is
  // written twice, and the narrow screen gets the short one, on one line.
  if (g.short.length) words.push({ pinned:2, warnLine:true,
    text:'the circuit is open and BOTH ENDS ARE LIVE: ' + g.short.length + ' links do not reach, so no current flows, but up to '
      + Math.round(vOpen) + ' V stands across a break and that is where an arc starts',
    small:'OPEN and LIVE: ' + g.short.length + ' links short, up to ' + Math.round(vOpen) + ' V across a break' });
  // THE NOTE ITSELF IS NEVER SHORTENED. Those are the owner's words and they are short enough already.
  // ONE LINE OF ARITHMETIC UNDER THE PICTURE, so the whole answer is on the page without opening a thing.
  words.push({ pinned:3, note:true, off:true,
    text:(g.links.length - g.short.length) + ' of ' + g.links.length + ' links reach \u00b7 ' + g.lead_m.toFixed(1)
      + ' m of module lead \u00b7 ' + g.field_m.toFixed(1) + ' m of site cable \u00b7 ' + g.ohm.toFixed(3)
      + ' ohm with the leads at ' + c.t_lead_c + ' C and the cable at ' + c.t_site_c + ' C',
    small:(g.links.length - g.short.length) + '/' + g.links.length + ' reach \u00b7 ' + g.lead_m.toFixed(0)
      + ' m lead \u00b7 ' + g.field_m.toFixed(0) + ' m cable \u00b7 ' + g.ohm.toFixed(3) + ' ohm' });
  words.push({ pinned:4, danger:true, text:DEV_WARNING, small:DEV_WARNING_SHORT });
  // ON A TELEPHONE THE KEY IS ONE LINE. Four lines of grey took a quarter of the screen off the
  // drawing, which is the thing the reader came for; the owner's own words are kept inside that line.
  words.push({ pinned:1, note:true, narrow:true,
    text:CABLE_NOTE + ' · red +, black − · the back of the modules, boxes and cables enlarged' });
  if (wiring) words.push({ pinned:2, note:true, wide:true,
    text:'you are looking at the BACK of the modules; the junction boxes are drawn larger than life and the cables longer than life, so that which box joins which can be followed',
    small:'the back of the modules; boxes and cables enlarged so the wiring can be followed' });
  words.push({ pinned:1, text:CABLE_NOTE, note:true, wide:true });
  words.push({ pinned:0, note:true, wide:true,
    text:'red is the + conductor and black the \u2212; the array floats, so either terminal may sit at up to half the array voltage to earth, and black does not mean earthed',
    small:'red is +, black is \u2212; the array floats, so black is not earthed' });
  words.push({ pinned:-1, note:true, wide:true,
    text:'the moving highlight shows the instant the circuit closes; after that the current is the same all the way round, so the line does not thicken or thin',
    small:'the highlight is the instant the circuit closes; after it, one current all the way round' });

  // ---- 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 t2 of terminals) see(t2.x, t2.y);
  for (const w of words) if (w.pinned === undefined) 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 t2 of terminals) { const u = U(t2.x, t2.y); t2.x = u[0]; t2.y = u[1]; }
  for (const w of words) { if (w.pinned !== undefined) continue; const u = U(w.x, w.y); w.x = u[0]; w.y = u[1]; }
  const open = g.short.length > 0;
  // WHERE ONE CABLE CROSSES ANOTHER, worked out once from the geometry and written down. A wiring
  // drawing has always done this: the cable on top keeps its line unbroken and the one underneath is
  // broken for a few pixels each side, so the eye can follow either through the crossing. Which is on
  // top is decided by where they sit on the electrical path, so it is the same picture every time.
  const crossings = [];
  { const cab = shapes.filter(q => (q.role === 'lead' || q.role === 'cable') && q.pts && q.pts.length > 1);
    const box2 = q => { let a = 1e9, b = 1e9, c2 = -1e9, d2 = -1e9;
      for (const z of q.pts) { a = Math.min(a, z[0]); c2 = Math.max(c2, z[0]); b = Math.min(b, z[1]); d2 = Math.max(d2, z[1]); }
      return [a, b, c2, d2]; };
    const bb = cab.map(box2), cum = cab.map(q => polyLen(q.pts));
    for (const q of cab) q.breaks = [];
    for (let a = 0; a < cab.length; a++) for (let b = a + 1; b < cab.length; b++) {
      if (cab[a].node === cab[b].node) continue;
      const A2 = bb[a], B2 = bb[b];
      if (A2[0] > B2[2] || A2[2] < B2[0] || A2[1] > B2[3] || A2[3] < B2[1]) continue;
      const pa = cab[a].pts, pb = cab[b].pts;
      for (let i2 = 1; i2 < pa.length; i2++) for (let j2 = 1; j2 < pb.length; j2++) {
        const x1 = pa[i2-1][0], y1 = pa[i2-1][1], x2 = pa[i2][0], y2 = pa[i2][1];
        const x3 = pb[j2-1][0], y3 = pb[j2-1][1], x4 = pb[j2][0], y4 = pb[j2][1];
        const den = (x2 - x1) * (y4 - y3) - (y2 - y1) * (x4 - x3);
        if (Math.abs(den) < 1e-12) continue;
        const t = ((x3 - x1) * (y4 - y3) - (y3 - y1) * (x4 - x3)) / den;
        const u = ((x3 - x1) * (y2 - y1) - (y3 - y1) * (x2 - x1)) / den;
        if (t < 0 || t > 1 || u < 0 || u > 1) continue;
        const ua = (cum[a].cum[i2-1] + (cum[a].cum[i2] - cum[a].cum[i2-1]) * t) / Math.max(1e-9, cum[a].total);
        const ub = (cum[b].cum[j2-1] + (cum[b].cum[j2] - cum[b].cum[j2-1]) * u) / Math.max(1e-9, cum[b].total);
        if (ua < 0.03 || ua > 0.97 || ub < 0.03 || ub > 0.97) continue;
        const overA = (cab[a].order || 0) >= (cab[b].order || 0);
        (overA ? cab[b] : cab[a]).breaks.push(overA ? ub : ua);
        crossings.push({ x:x1 + (x2 - x1) * t, y:y1 + (y2 - y1) * t,
          over:(overA ? cab[a] : cab[b]).node, under:(overA ? cab[b] : cab[a]).node,
          u_over:overA ? ua : ub, u_under:overA ? ub : ua });
      } } }
  return { kind:'string', shapes, marks, words, conns, terminals, wiring, crossings, perM:S, open, g,
           firstModuleX:U(-0.06, 0)[0], volts:vString, volts_open:vOpen, 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, head:-1, walk:null, 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; }
    if (s.role === 'tube') { line('mod', s.order, s.pts[0], s.pts[1]); 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;
  // THE BAND, LESS THE WINDOW ITSELF. Laying the row out beside the window is not enough on its own:
  // the row is several screens long, and a reader may open, drag or grow the window over it. So the
  // window's own box is cut OUT of what may be drawn. The picture then ends where the window begins,
  // at any zoom and after any drag, instead of showing faintly through it.
  // THE SAME DRAWING ON PAPER. A wiring drawing has been read on white for a very long time and it is
  // easier to read there; the night is the wafer's own and stays the default. Nothing moves between the
  // two: only the ink changes.
  const SHEET = !!(D.g && D.g.c && String(D.g.c.sheet) === '1');
  const band = shapeBand(true), win = sayRect();
  if (SHEET) { ctx.fillStyle = '#eef1f5';
    ctx.fillRect(band.left, band.top, band.right - band.left, band.bottom - band.top); }
  ctx.save(); ctx.beginPath(); ctx.rect(band.left, band.top, band.right - band.left, band.bottom - band.top);
  // ONLY THE PART OF THE WINDOW THAT IS INSIDE THE BAND IS CUT OUT. Two rules cross here and the first
  // draft got it wrong: an even-odd path adds a second rectangle that lies OUTSIDE the first instead of
  // taking it away, so a window docked beyond the band quietly opened that strip up and the row painted
  // straight through it. The overlap is taken, a hair larger than the window so the soft edge of the cut
  // falls on the window and not on the picture, and only then subtracted.
  if (win) { const l = Math.max(band.left, win.left - 2), t = Math.max(band.top, win.top - 2),
    r2 = Math.min(band.right, win.right + 2), b2 = Math.min(band.bottom, win.bottom + 2);
    if (r2 > l && b2 > t) ctx.rect(l, t, r2 - l, b2 - t); }
  ctx.clip('evenodd');
  const px = shapeScale();                                     // screen pixels to one drawing unit
  const perM = D.perM * px;                                    // screen pixels to one metre
  const fine = 1.15, hair = 0.7;
  const INK = SHEET ? '#10151c' : SHAPE_INK, PENCIL = SHEET ? '#55606e' : SHAPE_PENCIL,
        FAINT = SHEET ? '#b9c2cd' : SHAPE_FAINT, EDGE2 = SHEET ? '#6c7886' : SHAPE_EDGE,
        BODY = SHEET ? '#e3e7ec' : '#0c1119', BOXFILL = SHEET ? '#cdd4dc' : '#05080d';
  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 MODULE BACKS FIRST, because everything else is clipped TO them and must be drawn ON them.
  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.role === 'module' ? BODY : (SHEET ? '#e6eaef' : s.fill); ctx.fill(); }
      ctx.lineWidth = fine * 0.8; ctx.strokeStyle = s.role === 'inverter' ? INK : PENCIL; ctx.stroke(); continue; }
    // THE CELLS, from the grid the module carries. Each one is drawn as the cell it is, with the real
    // gap between cells and the wider gap across the middle where the two halves meet. They appear as
    // soon as a cell is wide enough on the screen to BE a cell, and they fade in rather than arriving as
    // a moire; they are quiet, because the cables are what is being followed.
    if (s.role === 'cells' && s.grid) { if (!onScreen(s.pts)) continue;
      const G = s.grid, cwPx = G.cell_w * perM, chPx = G.cell_h * perM;
      if (Math.min(cwPx, chPx) < 1.3) continue;                 // a cell that cannot be a cell is left out
      const fade = Math.min(1, (Math.min(cwPx, chPx) - 1.3) / 2.2);
      ctx.globalAlpha = 0.85 * fade; ctx.lineWidth = hair; ctx.strokeStyle = FAINT;
      ctx.beginPath();
      for (let j2 = 0; j2 < G.up; j2++) for (let i2 = 0; i2 < G.across; i2++) {
        const x2 = G.x0 + i2 * (G.cell_w + G.gap), y2 = G.y0 + j2 * (G.cell_h + G.gap) + (j2 >= G.up / 2 ? G.mid_gap : 0);
        const a = S([x2, y2]), b = S([x2 + G.cell_w, y2 + G.cell_h]);
        ctx.rect(a[0], b[1], b[0] - a[0], a[1] - b[1]); }
      ctx.stroke(); ctx.globalAlpha = 1; } }
  // 3. THE CONDUCTORS, on top of the backs. Fused behind the front, pencil ahead of it; a gap is 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);
    // POLARITY IS THE COLOUR, AND NOTHING ELSE IS. The minus conductor is a BLACK cable: a dark core
    // with ONE hairline of light round it, because black on a near black sky is otherwise nothing at
    // all, and a pale grey line would be a lie about what is in the trench. The plus conductor is ONE
    // CLEAR RED all the way along. Shading it by how far up the string each point sits was mine, and it
    // was wrong: thirty steps of red do not read as voltage, they read as shading, and the first thing
    // a reader must get is which conductor is which. The potential is still carried on every shape, for
    // the earth fault work, and it is said in words instead of being hinted at in a colour.
    // CURRENT decides the WEIGHT, not the colour, so a fused line is the same conductor, thicker and
    // brighter edged, and never a different cable.
    // AN OPEN LEAD IS NOT DIMMED. It carries no current, so it is drawn thin; it carries the full open
    // circuit voltage right up to the break, so it keeps its colour and its polarity, and the break
    // itself is marked amber. A stub drawn faint would say "safe", and it is the opposite of safe.
    // A BLACK CABLE ON A BLACK MODULE BACK IS NOTHING AT ALL. On the wiring drawing the negative is
    // given a pale body with a dark centre line down it - which is how a black cable actually catches
    // the light - and the pale part is at least a whole pixel each side on a telephone. The positive is
    // red and thick enough to follow with a finger. On the scale drawing, where the cable is a pencil
    // line beside a cell grid, the older fine treatment is kept.
    // A CABLE IS A TUBE. A light edge with a dark core is how a cable catches the light, and it is the
    // only way a BLACK cable on a dark module back can be seen at all: what the eye follows is the pair
    // of bright edges. Never thinner than five pixels in all, at any zoom, so a finger can follow it.
    if (D.wiring) {
      // A THIN, SHARP LINE with a dark casing under it, so it reads over the cell grid without being a
      // tube. The negative is the pale one with a dark centre - which is how a black cable catches the
      // light - and the positive is red. Broken where another cable passes over it.
      const core = Math.max(1.5, Math.min(3.2, perM * 0.022));
      const ink = lit ? '#eaf6ff' : s.open ? SHAPE_WARN : (s.plus ? (SHEET ? '#c0271a' : '#ff4b3a') : (SHEET ? '#8a94a2' : '#aebdd0'));
      const casing = SHEET ? '#f2f4f7' : '#05070b';
      const gaps = (s.breaks && s.breaks.length) ? s.breaks : null;
      const total = polyLen(s.pts).total * px, runs = [];
      if (!gaps) runs.push([0, 1]);
      else { const hw = Math.min(0.2, (core * 3.4) / Math.max(1e-6, total));
        const cut = gaps.map(u => [Math.max(0, u - hw), Math.min(1, u + hw)]).sort((a, b) => a[0] - b[0]);
        let at = 0;
        for (const [c0, c1] of cut) { if (c0 > at) runs.push([at, c0]); at = Math.max(at, c1); }
        if (at < 1) runs.push([at, 1]); }
      for (const [r0, r1] of runs) { const seg = polySlice(s.pts, r0, r1); if (seg.length < 2) continue;
        // THE CASING IS WHAT MAKES A THIN LINE READ OVER A CELL GRID: 1.5 px wider each side than the
        // line itself, laid down first along the same path, so the eye always sees the cable against
        // its own dark ground and never against a grid line. Still a line, not a tube.
        path(seg); ctx.lineWidth = core + 3.0; ctx.strokeStyle = casing; ctx.stroke();
        path(seg); ctx.lineWidth = core; ctx.strokeStyle = ink; ctx.stroke();
        if (!s.plus && !s.open) { path(seg); ctx.lineWidth = Math.max(0.6, core * 0.4);
          ctx.strokeStyle = SHEET ? '#20262f' : '#14181f'; ctx.stroke(); } }
      continue; }
    const core = s.plus ? SHAPE_RED : SHAPE_BLACK;
    const rim = lit ? '#eaf6ff' : s.open ? SHAPE_WARN : (s.plus ? (fused ? '#933428' : '#552722') : (fused ? '#a3b4c9' : SHAPE_EDGE));
    const grow = lit ? 1.7 : 1.0;
    path(s.pts); ctx.lineWidth = w + grow; ctx.strokeStyle = rim; ctx.stroke();
    path(s.pts); ctx.lineWidth = w; ctx.strokeStyle = fused ? core : dimColour(core, 0.62); ctx.stroke(); }
  // 3b. THE NEON HEAD, on the conductors that were actually drawn. The walk is not invented here: every
  //     conductor already carries the two terminals it joins, so the chain is followed from INV- by
  //     name - home run, lead, mate, lead, and box to box across each module - to INV+. If the chain
  //     breaks anywhere, or any lead is open, there is no walk and NOTHING lights: an open string
  //     carries no current, and a neon running over a break would be a lie. Speed is steady (the head
  //     is the sldTick clock); WEIGHT is the current, never the colour.
  if (D.head >= 0 && !D.open) {
    if (D.walk === null || D.walk === undefined) D.walk = buildStringWalk(D);
    const W = D.walk;
    if (W) {
      const hl = 0.055, h1 = D.head, spans = h1 - hl < 0 ? [[0, h1], [1 + h1 - hl, 1]] : [[h1 - hl, h1]];
      const amps = 1 + 0.5 * Math.min(1, (D.amps || 0) / 20);
      ctx.save(); ctx.globalCompositeOperation = 'lighter'; ctx.shadowColor = '#7ff0ff';
      for (const L of W.legs) for (const [a0, a1] of spans) {
        const a = Math.max(L.u0, a0), b = Math.min(L.u1, a1);
        if (b <= a) continue;
        if (L.s) { const d = Math.max(1e-9, L.u1 - L.u0);
          const seg = polySlice(L.s.pts, (a - L.u0) / d, (b - L.u0) / d);
          if (seg.length < 2 || !onScreen(seg)) continue;
          const wN = Math.max(2.2, (D.wiring ? Math.max(1.5, Math.min(3.2, perM * 0.022)) : fine * (L.s.weight || 1)) * 1.1) * amps;
          ctx.shadowBlur = wN * 2.6;
          path(seg); ctx.lineWidth = wN * 2.1; ctx.strokeStyle = 'rgba(86,214,255,0.22)'; ctx.stroke();
          path(seg); ctx.lineWidth = wN; ctx.strokeStyle = 'rgba(224,250,255,0.92)'; ctx.stroke(); }
        else if (L.mod && onScreen(L.mod.pts)) {      // box to box THROUGH the module: its own outline lights
          ctx.shadowBlur = 7 * amps;
          path(L.mod.pts); ctx.closePath(); ctx.lineWidth = Math.max(1.4, fine * 1.2) * amps;
          ctx.strokeStyle = 'rgba(120,232,255,0.55)'; ctx.stroke(); } }
      ctx.restore(); ctx.shadowBlur = 0; }
  }
  // 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) || true) 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 (false) {
      } }
  // 5. THE BOXES AND WHAT SITS ON THEM, over the cable ends, so a cable is seen to enter its box.
  for (const s of D.shapes) {
    if (s.role === 'box') { if (!onScreen(s.pts)) continue;
      path(s.pts); ctx.closePath(); ctx.fillStyle = BOXFILL; ctx.fill();
      ctx.lineWidth = fine; ctx.strokeStyle = INK; ctx.stroke();
      // THE MIDDLE BOX HAS NO CABLE: it carries a bypass diode, and it is drawn as one so that nobody
      // takes it for a third connection.
      // EACH OF THE THREE BOXES HOLDS ONE BYPASS DIODE, one per cell string. The two outer boxes carry a
      // smaller mark of the same symbol, kept clear of the box edge where the lead lands.
      if (s.diodeOnly || s.diode) { const a = S(s.pts[0]), b = S(s.pts[2]);
        const cxm = (a[0] + b[0]) / 2, cym = (a[1] + b[1]) / 2, r2 = Math.min(Math.abs(b[0] - a[0]), Math.abs(b[1] - a[1])) * (s.diodeOnly ? 0.30 : 0.22);
        if (r2 > 2) { ctx.beginPath(); ctx.moveTo(cxm - r2, cym - r2); ctx.lineTo(cxm - r2, cym + r2); ctx.lineTo(cxm + r2, cym);
          ctx.closePath(); ctx.lineWidth = Math.max(0.8, fine * 0.6); ctx.strokeStyle = EDGE2; ctx.stroke();
          ctx.beginPath(); ctx.moveTo(cxm + r2, cym - r2); ctx.lineTo(cxm + r2, cym + r2); ctx.stroke(); } }
      continue; }
    if (s.role === 'terminal' && s.pts.length > 1) { if (!onScreen(s.pts)) continue;
      path(s.pts); ctx.lineWidth = fine; ctx.strokeStyle = INK; ctx.stroke(); continue; }
    if (s.role === 'tube') { if (!onScreen(s.pts)) continue;
      path(s.pts); ctx.lineWidth = hair; ctx.strokeStyle = EDGE2; ctx.stroke(); continue; }
    if (s.role === 'landing' && false) { const q = S(s.pts[0]);
      if (q[0] < -20 || q[0] > innerWidth + 20 || q[1] < -20 || q[1] > innerHeight + 20) continue;
      // THE DOT ON THE BOX where the cable lands. Small, but it is the difference between a cable that
      // joins a box and a line that happens to pass near one.
      const r2 = Math.max(1.6, Math.min(4, perM * 0.018));
      ctx.beginPath(); ctx.arc(q[0], q[1], r2, 0, 6.2832);
      ctx.fillStyle = s.plus ? (SHEET ? '#c0271a' : SHAPE_RED) : (SHEET ? '#20262f' : '#cfe0ee'); ctx.fill(); continue; }
    if (s.role === 'plug') { const q = S(s.pts[0]);
      if (q[0] < -20 || q[0] > innerWidth + 20 || q[1] < -20 || q[1] > innerHeight + 20) continue;
      // A CONNECTOR IS AN OBJECT, and the two halves are different objects: a plug is a barrel with a
      // collar, a socket is a sleeve with two latches. Facing each other across a gap, they say what is
      // wrong better than any words: these two were meant to meet and they do not.
      const a2 = s.along || [1, 0], L2 = Math.max(1e-6, Math.hypot(a2[0], a2[1]));
      const ux = a2[0] / L2, uy = a2[1] / L2, nx = -uy, ny = ux;
      const len = Math.max(7, Math.min(26, perM * 0.16)), rad = len * 0.30;
      const put2 = (px2, py2) => [q[0] + ux * px2 + nx * py2, q[1] + uy * px2 + ny * py2];
      ctx.lineWidth = Math.max(0.8, fine * 0.7); ctx.strokeStyle = INK; ctx.fillStyle = SHEET ? '#f3f5f8' : '#10151d';
      ctx.beginPath();
      if (s.male) { const a = put2(0, -rad), b = put2(len * 0.75, -rad * 0.55), c2 = put2(len * 0.75, rad * 0.55), d2 = put2(0, rad);
        ctx.moveTo(a[0], a[1]); ctx.lineTo(b[0], b[1]); ctx.lineTo(c2[0], c2[1]); ctx.lineTo(d2[0], d2[1]); ctx.closePath(); }
      else { const a = put2(0, -rad), b = put2(-len * 0.8, -rad), c2 = put2(-len * 0.8, rad), d2 = put2(0, rad);
        ctx.moveTo(a[0], a[1]); ctx.lineTo(b[0], b[1]); ctx.lineTo(c2[0], c2[1]); ctx.lineTo(d2[0], d2[1]); ctx.closePath(); }
      ctx.fill(); ctx.stroke();
      { const e = s.male ? put2(len * 0.3, 0) : put2(-len * 0.45, 0), f = s.male ? put2(len * 0.3, 0) : put2(-len * 0.45, 0);
        ctx.beginPath(); ctx.moveTo(e[0] + nx * rad, e[1] + ny * rad); ctx.lineTo(f[0] - nx * rad, f[1] - ny * rad);
        ctx.lineWidth = Math.max(0.8, fine * 0.5); ctx.strokeStyle = SHAPE_EDGE; ctx.stroke(); }
      continue; }
    if (s.role === 'mate') { const q = S(s.pts[0]);
      if (q[0] < -20 || q[0] > innerWidth + 20 || q[1] < -20 || q[1] > innerHeight + 20) continue;
      // WHERE RED BECOMES BLACK: the mated pair, as a small lozenge across the cable, so a reader can
      // see that two leads meet here rather than one cable changing its mind about its colour.
      const a2 = s.along || [1, 0], L2 = Math.max(1e-6, Math.hypot(a2[0], a2[1]));
      const ux = a2[0] / L2, uy = -a2[1] / L2, r2 = Math.max(2.6, Math.min(7, perM * 0.035)), r3 = r2 * 0.5;
      ctx.beginPath();
      ctx.moveTo(q[0] + ux * r2, q[1] + uy * r2); ctx.lineTo(q[0] - uy * r3, q[1] + ux * r3);
      ctx.lineTo(q[0] - ux * r2, q[1] - uy * r2); ctx.lineTo(q[0] + uy * r3, q[1] - ux * r3);
      ctx.closePath(); ctx.fillStyle = SHEET ? '#f3f5f8' : '#0a0d13'; ctx.fill();