In this section
- Kuiper Programs electrical · globalgrid2050 / kuiper-grid/i0090/cartridges/009000000000-kuiper-programs.js lines 3501–4074
- Kuiper Grid — I0090 Page render · globalgrid2050 / kuiper-grid/i0090/index.html lines 1–108
Kuiper Programs
A JavaScript file in the cartridges folder of GlobalGrid2050 covering interconnectors, london underground, grid 66kV and motorway services, using IEC 62446-1 and SHA-256, and uses data from the faraday repository.
Set aside from the main view: Near copy of kuiper-grid/i0091/cartridges/009100000000-kuiper-programs.js (globalgrid2050), which stays: reachable first, then the higher version. (near-copy-of, proposed by families.py). 90% of lines shared with Kuiper Programs; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.9041 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 kuiper-grid/i0090/cartridges/009000000000-kuiper-programs.js:1-4074 900ccf797d8055b28d45153c3fa3dbb44ccb03a5
- sha256 b6f885714556097456ac60c32e2ad0d400f4909d63e4663a2b2a01b1805180db
- target sha256 3b3ff8b2b317c0c59e1431b1d9e003c246ec9bb5227219e64e47d313656e2062
- group of 6 (identity.json near-copy edges >= 0.9)
- canonical rule: reachable, newest stamp, core repo, most lines
- re-pointed by apply.py version rule (was canonical)
electricalglobalgrid2050 / kuiper-grid/i0090/cartridges/009000000000-kuiper-programs.js · lines 3501–4074 of 4074 (continued from section 1407) · Not reached from any entry point (candidate for review) · pattern checkNetlist (shared by 2 files)
- What it does
- It draws interconnectors, london underground, grid 66kV and motorway services. Defines 220 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: interconnectors, 400kV, 275kV, 132kV, 66kV, 33kV.
- Inputs & outputs
- In: data source: faraday data; JSON file interconnectors.config.json; GeoJSON file london_underground.geojson; GeoJSON file grid_66kv.geojson; GeoJSON file motorway_services.geojson; GeoJSON file railways.geojson; JSON file current.json. Out: canvas drawing. Voltage levels named: 400kV, 275kV, 132kV, 66kV, 33kV, 11kV, 1500V.
- What it achieves
- It makes body (`makeBody`), sets tag (`setTag`) and merges menu (`mergeMenu`). A cartridge of the Kuiper shell. Its code works with 11 kV, 33 kV and 352 kVA. It responds to click and keydown events.
- Why it matters
- No other file in the estate was found to import it.
- Application
- globalgrid2050 · kuiper-grid/i0090/cartridges · script
- Uses
- Faraday — Index Page (estate URL), Wafer Development Environment — Proof S0004 Page (estate URL), ./fire.js
- Used by
- none found
- Produces
- reFire, closestPair, blackSky, nameInLines, makeBody, bodyTo, labels, bodyJump, bodyMove, bodyDrawnDiameter, bodyDotPx, sheet
- Defines here
- put2, shapeAsk, shapeTrack, netPieces, line, ring, sym, netFinal, bad, net, kvColour, V, val, typed, DATA, slug, findSite, fiveNames, checkNetlist, buildMap, count, tidy, ringAt
- 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/i0090/cartridges/009000000000-kuiper-programs.js:3501-4074 · blob 900ccf797d8055b28d45153c3fa3dbb44ccb03a5 · 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
// 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) {
// AT MACRO DISTANCE A CABLE IS ONE LINE. The casing and the centre line are what let a cable read
// over a cell grid up close; zoomed out to the whole string there is no cell grid, the casing is
// wider than the run is long, and thirty modules of cable turn into a band of grey. So below the
// zoom at which a module is about twenty pixels wide, each conductor is a single thin stroke in
// its own colour - black or red, which is the one thing that must survive - and it thickens back
// into the near treatment over a short band of zoom rather than snapping.
const thinAt = 16, fullAt = 34; // screen pixels to one metre
if (perM < fullAt) {
const t2 = Math.max(0, Math.min(1, (perM - thinAt) / (fullAt - thinAt)));
const ink2 = lit ? '#eaf6ff' : s.open ? SHAPE_WARN : (s.plus ? (SHEET ? '#c0271a' : '#ff4b3a') : (SHEET ? '#6f7887' : '#9fb0c4'));
if (t2 > 0.02) { path(s.pts); ctx.lineWidth = 1 + 3.0 * t2; ctx.strokeStyle = SHEET ? '#f2f4f7' : '#05070b'; ctx.stroke(); }
path(s.pts); ctx.lineWidth = 1 + 0.5 * t2; ctx.strokeStyle = ink2; ctx.stroke();
continue; }
// 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(); }
// 3a. THE MAP. A station, its interchange ring, and one coloured line for every circuit route
// out of it. Colour is the voltage level, weight is how many parallel circuits run that way.
// DASHED where the value was ASSUMED and SOLID where it came from the data, so provenance is in
// the drawing itself and not in a footnote. A line marked OPEN by an outage is drawn dead grey.
// The length in km is a quiet label and it appears only when the map is zoomed in far enough to
// read it: at map distance the shape of the network is the thing, not the numbers on it.
if (D.substation) {
for (const s of D.shapes) {
if (!s.pts || s.pts.length < 2 || !onScreen(s.pts)) continue;
const lit = shapeHover && shapeHover === s.node;
const done = front >= 0 && (s.order === undefined ? 0.5 : s.order) <= 0.5 + front * 0.5 + 1e-6;
const dead = !!s.dark;
const col = dead ? (SHEET ? '#c3c8cf' : '#39424e') : lit ? '#eaf6ff' : (s.colour || INK);
const w = Math.max(1, fine * (s.weight || 1));
ctx.setLineDash(s.assumed ? [5.5, 4.2] : []);
if (s.role === 'sldstation') {
path(s.pts); ctx.closePath();
ctx.fillStyle = dead ? (SHEET ? '#dfe3e8' : '#0a0e14') : (SHEET ? '#ffffff' : '#05080d'); ctx.fill();
ctx.lineWidth = w; ctx.strokeStyle = dead ? col : (SHEET ? '#10151c' : INK); ctx.stroke();
ctx.setLineDash([]); continue; }
// a line is drawn with a dark casing under it so two lines that meet are still two lines
path(s.pts); ctx.lineWidth = w + 3.0; ctx.strokeStyle = SHEET ? '#f2f4f7' : '#05080d'; ctx.setLineDash([]); ctx.stroke();
ctx.setLineDash(s.assumed ? [5.5, 4.2] : []);
path(s.pts); ctx.lineWidth = w + (lit ? 1.8 : 0); ctx.strokeStyle = done && !dead ? '#eaf6ff' : col; ctx.stroke();
ctx.setLineDash([]);
if (s.km && px > 900) {
const mid = s.pts[Math.max(0, s.pts.length - 2)], end = s.pts[s.pts.length - 1];
const a = S([(mid[0] + end[0]) / 2, (mid[1] + end[1]) / 2]);
ctx.font = '600 10px ui-monospace,SFMono-Regular,Menlo,monospace';
ctx.fillStyle = SHEET ? '#55606e' : '#7f8899'; ctx.textAlign = 'center';
ctx.fillText(s.km + ' km', Math.round(a[0]), Math.round(a[1]) - 7); } }
}
// 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;
// A BOX TOO SMALL TO BE A BOX IS A DOT, NOT A SMALLER BOX. Under six pixels across, a rectangle
// with an outline and a fill is three grey pixels that say nothing; what a reader wants at that
// distance is only WHERE the boxes are, so one dot is drawn and the box itself is dropped. This is
// the macro rule and it is crossed by zooming, not by the word: pinch in and the dots become boxes
// at the same threshold either way.
{ const aa = S(s.pts[0]), bb2 = S(s.pts[2]);
const bpx = Math.min(Math.abs(bb2[0] - aa[0]), Math.abs(bb2[1] - aa[1]));
if (bpx < 6) { const cx2 = (aa[0] + bb2[0]) / 2, cy2 = (aa[1] + bb2[1]) / 2;
ctx.beginPath(); ctx.arc(Math.round(cx2), Math.round(cy2), 1.3, 0, 6.2832);
ctx.fillStyle = SHEET ? '#55606e' : SHAPE_PENCIL; ctx.fill(); 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();
ctx.lineWidth = Math.max(0.8, fine * 0.8); ctx.strokeStyle = INK; ctx.stroke(); continue; }
if (s.role === 'slack') { if (!onScreen(s.pts)) continue;
path(s.pts); ctx.lineWidth = fine + 0.9; ctx.strokeStyle = SHAPE_EDGE; ctx.stroke();
path(s.pts); ctx.lineWidth = fine; ctx.strokeStyle = SHAPE_BLACK; 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
// WORDS ARE DROPPED, NEVER OVERLAPPED. The polarity marks and the module names go down first, then
// the numbers on the links, nearest the near end first; anything that would land on something already
// written is simply not written. A crowded drawing loses labels; it never turns into a smear.
ctx.textBaseline = 'middle';
const placed = [];
const order2 = D.marks.map((m, i) => [m, i]).sort((a, b) => ((a[0].rank || 0) - (b[0].rank || 0)) || (a[0].x - b[0].x));
// NO WORD IS EVER SHRUNK. Nine pixels is the floor for a word on this drawing: under it the word is
// not written at all. The MACRO words - M1, M10, M20, M30 and the inverter - are the only ones
// written when the whole string is on the screen, and they fade out as the near names fade in, so
// pinching from one view to the other is a change of what is worth saying and not a flicker.
const MACRO_OFF = 46;
// A WORD IS PAINTED IN THE GLASS'S OWN PIXELS. The rest of the drawing is laid out in css px on a
// layer scaled by the device ratio, which is right for a line: a hairline stays a hairline. A word is
// not a line. A word has one true size - the size it arrives at the eye - and that size is counted in
// the pixels the panel actually has. So for the marks alone the layer's scale is dropped, the word is
// asked for at its css size times the device ratio, and it lands where it would have landed anyway.
// The floor is then the floor the reader sees: NINE CSS PIXELS, in this one place, and under it the
// word is not written at all. Dropped, never shrunk - a word too small to read is worse than none.
const TEXT_FLOOR_PX = 9;
ctx.setTransform(1, 0, 0, 1, 0, 0);
for (const [m] of order2) {
const sizeCss = m.size || 11;
if (sizeCss < TEXT_FLOOR_PX) continue;
if (m.macro) { if (perM > MACRO_OFF) continue; }
else 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.globalAlpha = m.macro ? Math.max(0, Math.min(1, (MACRO_OFF - perM) / 12)) : 1;
ctx.font = '600 ' + (sizeCss * dpr) + 'px ui-monospace,Menlo,Consolas,monospace';
const px = Math.round(p[0] * dpr), py = Math.round(p[1] * dpr);
const w2 = ctx.measureText(m.text).width, h2 = (sizeCss + 3) * dpr;
const x0 = px - (m.mid ? w2 / 2 : 0), y0 = py - h2 / 2;
const box2 = [x0 - dpr, y0, x0 + w2 + dpr, y0 + h2];
if (m.dodge) { let clash = false;
for (const q of placed) if (box2[0] < q[2] && box2[2] > q[0] && box2[1] < q[3] && box2[3] > q[1]) { clash = true; break; }
if (clash) continue; }
placed.push(box2);
ctx.textAlign = m.mid ? 'center' : 'left';
ctx.fillStyle = SHEET ? (m.colour === SHAPE_RED ? '#b3271a' : m.colour === SHAPE_WARN ? '#8a6100' : '#10151c') : m.colour;
ctx.fillText(m.text, px, py); }
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.globalAlpha = 1;
ctx.textAlign = 'left'; ctx.textBaseline = 'alphabetic';
ctx.restore();
}
// ---- 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 { stringClampMicro(); 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);
addEventListener('pointercancel', net);
addEventListener('pointerout', function(e){ if (e.pointerType === 'mouse' && !e.relatedTarget && e.buttons === 0) net(e); });
addEventListener('blur', function(){ try { if (typeof pts !== 'undefined' && pts.clear) pts.clear();
if (typeof drag !== 'undefined') drag = null; if (typeof pinch !== 'undefined') pinch = null; } catch (_) {} });
}, 0);
// ===== ONE SUBSTATION AND ALL ITS POSSIBLE CONNECTIONS: fire substation {"site":"Barking"} ========
// NOT AN ENGINEER'S SINGLE LINE DIAGRAM. A reader does not need to know how a train works to use an
// underground map, and a politician or a banker does not need inverters, transformers or surge
// arresters to see where the power can go. So a substation is a STATION: a mark, an interchange ring
// when more than one voltage level meets there, and one coloured LINE for every circuit that leaves
// it, at 0, 45 or 90 degrees and nothing between. Colour is the voltage level. Weight is how many
// parallel circuits run that way. The far end is another station, named, and tapping it walks there.
// WHAT IS ASSUMED IS DRAWN ASSUMED: solid came from the data, dashed was assumed.
/* GRID-DATA:START */ const GRID_DATA = {"attribution":"line geometry, circuit names and voltage tags: open map data, (c) OpenStreetMap contributors, ODbL, via GridAtlas; connection site names: NESO open data portal register (contractual names, not measurements). Sandbox only: no confidential data, no real busbar arrangement, no real ratings.","made":"E:\\swarm\\grid\\build_grid_data.py - topology … [line shortened here: 329,641 characters; full line on GitHub]
// THE RED LINE FOR THIS FAMILY. Cable sizing is not what is drawn here, so the string's red line is
// not apt: this is the development-environment warning and what an open-data map actually is.
const DEV_WARNING_SUB = 'DEVELOPMENT ENVIRONMENT: estimates from a model, nothing measured. An ASSUMED arrangement drawn from open data: not the operator\'s diagram.';
// THE LINE COLOURS ARE THE VOLTAGE LEVELS, and they are the only colours on the map.
const KV_COLOUR = { 400:'#ffb454', 275:'#5ec8f2', 132:'#7ee081', 66:'#c58cf5', 33:'#f28fb2' };
function kvColour(kv){ return KV_COLOUR[kv] || '#9fb0c4'; }
(function (root) {
const F = root.FIRE; if (!F) return;
// A VALUE IS A VALUE AND ITS PROVENANCE. A bare number that arrives without provenance is read as
// ASSUMED and never as typed: the safe way to be wrong about a value is to say you assumed it.
const V = x => (x && typeof x === 'object' && 'value' in x) ? x : { value:x, status:'ASSUMED', source:'not stated' };
const val = x => V(x).value;
const typed = x => V(x).status === 'TYPED';
const DATA = () => (typeof GRID_DATA !== 'undefined' && GRID_DATA) ? GRID_DATA : { sites:[], netlists:{} };
const slug = s => String(s || '').toLowerCase().replace(/[^a-z0-9]/g, '');
function findSite(want){ const D = DATA(), w = slug(want);
if (!w) return D.sites && D.sites[0] ? D.sites[0] : null;
for (const s of (D.sites || [])) if (slug(s.id) === w || slug(s.label) === w) return s;
for (const s of (D.sites || [])) if (slug(s.label).indexOf(w) === 0) return s;
return null; }
function fiveNames(){ const D = DATA(), n = [];
for (const s of (D.sites || [])) { if (n.length >= 5) break; if (D.netlists && D.netlists[s.id]) n.push(s.label); }
for (const s of (D.sites || [])) { if (n.length >= 5) break; if (n.indexOf(s.label) < 0) n.push(s.label); }
return n.join(', '); }
// ---- THE RULES THAT REFUSE IN WORDS -----------------------------------------------------------
function checkNetlist(nl){
const bus = new Set((nl.busbars || []).map(b => b.id));
for (const b of (nl.bays || [])) if (b.busbar && !bus.has(b.busbar))
throw new Error('bay "' + b.id + '" hangs off busbar "' + b.busbar + '", and this netlist has no such busbar (it has ' + [...bus].join(', ') + '): the map is refused rather than drawn wrong');
const kvOf = {}; for (const b of (nl.busbars || [])) kvOf[b.id] = val(b.kv);
const hasTx = (nl.transformers || []).length > 0;
for (const c of (nl.conductors || [])) {
const bay = (nl.bays || []).find(b => val(b.circuit) === val(c.name)); if (!bay) continue;
const bkv = kvOf[bay.busbar];
if (bkv !== undefined && val(c.kv) !== bkv && !hasTx)
throw new Error('circuit "' + val(c.name) + '" is ' + val(c.kv) + ' kV and leaves a ' + bkv + ' kV busbar with no transformer between them: a netlist cannot change voltage without one');
}
return true; }
// ---- THE MAP ----------------------------------------------------------------------------------
// Eight directions and nothing between them. A line leaves the station along one of them; where two
// lines would share a direction the second steps sideways on a 90 degree jog and runs on parallel,
// which is exactly what an underground map does and keeps every angle at 0, 45 or 90.
const DIRS = [ [1,0], [0,1], [-1,0], [0,-1], [0.7071,0.7071], [-0.7071,0.7071], [-0.7071,-0.7071], [0.7071,-0.7071] ];
function buildMap(nl, site, opts){
const shapes = [], words = [], marks = [], conns = [], terminals = {};
const neigh = !!opts.neighbours, out = String(opts.outage || '').toLowerCase();
const levels = (nl.busbars || []).map(b => val(b.kv)).filter(v => v !== undefined);
const uniqKv = [...new Set(levels)].sort((a, b) => b - a);
let assumed = 0, total = 0; const tables = new Set();
const count = (x, table) => { total++; if (!typed(x)) { assumed++; if (table) tables.add(table); } return val(x); };
// ONE LINE PER FAR END, however many circuits run that way: the WEIGHT says how many.
const groups = new Map();
// WHICH WAY IS OUT. A circuit names a terminal at each end and the site that terminal is in; the
// far end is whichever of the two is not this station. A reader is shown the NAME, never the id.
const me = String((nl.substation && nl.substation.id) || '');
const tidy = id => String(id).replace(/^S-/, '').split('.')[0].replace(/-/g, ' ').replace(/\b\w/g, ch => ch.toUpperCase());
for (const c of (nl.conductors || [])) {
const toS = String(c.to_site || c.to || ''), fromS = String(c.from_site || c.from || '');
const far = (toS === me || toS.indexOf(me + '.') === 0) ? fromS : toS;
const nb = (nl.neighbours || []).find(x => String(x.id) === String(far));
const key = String(far);
if (!groups.has(key)) { total++; if (!nb || nb.status === 'ASSUMED') { assumed++; tables.add('far end identity'); }
groups.set(key, { id:key, label:(nb && (nb.label && nb.label.value !== undefined ? nb.label.value : nb.label)) || tidy(far),
farAssumed:!nb || nb.status === 'ASSUMED', kv:count(c.kv, 'circuit voltages'), circuits:[], km:0 }); }
const g = groups.get(key);
const km = count(c.length_km, 'circuit lengths');
count(c.name, 'circuit names');
g.circuits.push({ id:c.id, name:val(c.name), km, typed:typed(c.length_km) });
g.km = Math.max(g.km, km || 0); }
const list = [...groups.values()].sort((a, b) => (a.km || 0) - (b.km || 0));
let maxKm = 1e-6; for (const g of list) maxKm = Math.max(maxKm, g.km || 0);
const used = {};
const STATION = 0.052;
list.forEach((g, i) => {
const di = i % DIRS.length, d = DIRS[di], lane = used[di] || 0; used[di] = lane + 1;
const perp = [-d[1], d[0]], off = lane * 0.16;
const len = neigh ? (0.30 + 0.62 * (g.km / maxKm)) : 0.46 + 0.05 * lane;
const a = [d[0] * (STATION + 0.03), d[1] * (STATION + 0.03)];
const b = [a[0] + d[0] * 0.10, a[1] + d[1] * 0.10];
const c2 = [b[0] + perp[0] * off, b[1] + perp[1] * off];
const e = [c2[0] + d[0] * len, c2[1] + d[1] * len];
const pts = off ? [a, b, c2, e] : [a, e];
const allTyped = g.circuits.every(c => c.typed);
const dark = !!(out && (slug(out) === slug(g.id) || slug(out) === slug(g.label) || g.circuits.some(c => slug(c.id) === slug(out))));
shapes.push({ role:'sldline', node:'line:' + g.id, id:site.id + '.line.' + g.id, pts, dist:g.km || 0,
colour:kvColour(g.kv), weight:1.0 + 1.5 * Math.min(4, g.circuits.length), assumed:!allTyped, dark,
km:g.km, n:g.circuits.length, far:g.id, farLabel:g.label,
says:g.label + ': ' + g.circuits.length + ' circuit' + (g.circuits.length === 1 ? '' : 's') + ' at ' + g.kv + ' kV, ' + (g.km || '?') + ' km' });
// THE FAR STATION, a mark at the end of its line, and its name beside it.
const r = 0.030, ring = [];
for (let k = 0; k <= 28; k++) { const t = 2 * Math.PI * k / 28; ring.push([e[0] + r * Math.cos(t), e[1] + r * Math.sin(t)]); }
shapes.push({ role:'sldstation', node:'line:' + g.id, id:site.id + '.station.' + g.id, pts:ring, closed:true,
colour:kvColour(g.kv), weight:1.4, assumed:!!g.farAssumed, dark, far:g.id, farLabel:g.label, dist:(g.km || 0) + 0.01,
hit:true, says:g.label });
words.push({ x:e[0], y:e[1] + (d[1] < -0.5 ? -0.062 : 0.062), text:g.label, small:g.label.length > 13 ? g.label.split(' ')[0] : null });
conns.push({ from:site.label, to:g.label, node:'line:' + g.id, home:true,
metres:g.circuits.length + ' x ' + g.kv + ' kV, ' + (g.km || '?') + ' km' + (dark ? ', OPEN' : '') });
});
// THE STATION ITSELF: one mark, and an INTERCHANGE ring when more than one voltage level meets.
const inter = uniqKv.length > 1;
const ringAt = (rad, tag, w) => { const pts = [];
for (let k = 0; k <= 40; k++) { const t = 2 * Math.PI * k / 40; pts.push([rad * Math.cos(t), rad * Math.sin(t)]); }
shapes.push({ role:'sldstation', node:'site', id:site.id + '.station.' + tag, pts, closed:tag === 'core',
colour:kvColour(uniqKv[0]), weight:w, assumed:false, dist:0, says:site.label + ' - ' + uniqKv.map(k => k + ' kV').join(', ') }); };
ringAt(STATION, 'core', 2.2);
if (inter) ringAt(STATION + 0.026, 'interchange', 1.4);
words.push({ x:0, y:-STATION - (inter ? 0.10 : 0.075), text:site.label });
// THE PULSE: out from the station along every line, shortest first. The engine's own neon front
// walks these legs. It shows CONNECTIVITY, not power: no load flow is run here.
const legs = [];
for (const s of shapes) if (s.role === 'sldline' && !s.dark) legs.push({ s, len:Math.max(1e-6, polyLen(s.pts).total) });
let tot = 0; for (const L of legs) tot += L.len;
let c3 = 0; for (const L of legs) { L.u0 = c3 / Math.max(1e-9, tot); c3 += L.len; L.u1 = c3 / Math.max(1e-9, tot); }
let maxD = 1e-6; for (const s of shapes) maxD = Math.max(maxD, s.dist || 0);
for (const s of shapes) s.order = 0.5 + 0.5 * ((s.dist || 0) / maxD);
let x0 = 1e9, x1 = -1e9, y0 = 1e9, y1 = -1e9;
for (const s of shapes) for (const p of s.pts) { x0 = Math.min(x0, p[0]); x1 = Math.max(x1, p[0]); y0 = Math.min(y0, p[1]); y1 = Math.max(y1, p[1]); }
const midX = (x0 + x1) / 2;
words.push({ x:midX, y:y1 + 0.135, text:site.label + ' - ' + uniqKv.map(k => k + ' kV').join(' / ') + ', ' + list.length + ' ways out' });
words.push({ x:midX, y:y0 - 0.085, text:'A line is a circuit route, its colour the voltage and its weight how many circuits run that way. SOLID = from the data. DASHED = assumed.', note:true });
words.push({ x:midX, y:y0 - 0.125, text:String(DATA().attribution || ''), note:true });
words.push({ x:midX, y:y0 - 0.168, text:DEV_WARNING_SUB, danger:true, pinned:true });
return { kind:'string', substation:true, tube:true, shapes, marks, words, conns, terminals, wiring:false, crossings:[],
perM:1, open:false, g:null, assumed, total, tables:[...tables], site, nl, groups:list, outage:out,
bounds:{ x0:x0 - 0.20, y0:y0 - 0.20, x1:x1 + 0.20, y1:y1 + 0.17 }, near:{ x:midX, y:(y0 + y1) / 2 }, mPerUnit:1,
firstModuleX:midX, amps:12, front:-1, head:-1, walk:(legs.length ? { legs, total:tot } : false), t0:0 };
}
// ---- THE COMMAND ------------------------------------------------------------------------------
const INPUTS = [
{ key:'site', label:'Substation', kind:'choice', choices:(DATA().sites || []).slice(0, 40).map(s => [s.label, s.label]) },
{ key:'neighbours', label:'Far ends', kind:'choice', choices:[[0, 'even spacing'], [1, 'lengths to scale']] },
{ key:'pulse', label:'Pulse', kind:'choice', choices:[[0, 'still'], [1, 'run the front out']] },
{ key:'outage', label:'Line out', kind:'choice', choices:[['', 'none']] }
];
F.register('substation', 'THE GRID', function (i) {
const D = DATA();
const site = findSite(i.site);
if (!site) throw new Error('no substation called "' + i.site + '" in this sandbox. Try one of: ' + fiveNames());
const nl = (D.netlists || {})[site.id];
if (!nl) throw new Error(site.label + ' is named at the end of a circuit but has no netlist here yet, so it cannot be opened. Try one of: ' + fiveNames());
checkNetlist(nl);
const g = { c:{ view:'macro', sheet:i.sheet ? 1 : 0 }, pitch:0.30 };
const d = buildMap(nl, site, { neighbours:!!i.neighbours, outage:i.outage || '' });
d.g = g; g.__draw = d;
const k = d.assumed, n = d.total, outLine = i.outage ? String(i.outage) : '';
const drawable = d.groups.filter(x => (D.netlists || {})[x.id]).map(x => x.label);
const notDrawable = d.groups.filter(x => !(D.netlists || {})[x.id]).map(x => x.label);
const said = String(site.label) + ': ' + d.groups.length + ' ways out, ' + (nl.conductors || []).length + ' circuits, '
+ [...new Set((nl.busbars || []).map(b => val(b.kv)))].sort((a, b) => b - a).map(v => v + ' kV').join(' and ') + '. '
+ k + ' of ' + n + ' values assumed (' + (d.tables.join(', ') || 'none') + '), and those lines are drawn dashed. '
+ (outLine ? outLine + ' is OPEN: that line carries nothing and its far station goes dark; every other way out still lights. ' : '')
+ 'The pulse shows CONNECTIVITY, not power: no load flow is run here.';
return { numbers:{ ways_out:d.groups.length, circuits:(nl.conductors || []).length,
voltage_levels:[...new Set((nl.busbars || []).map(b => val(b.kv)))].length,
values_assumed:k, values_typed:n - k },
said,
how:'the netlist (' + (nl.schema || 'netlist') + ') drawn as a map, not as the diagram an engineer would draw: a station, an interchange ring where two voltages meet, one coloured line a circuit route. '
+ String(D.attribution || '')
+ ' Far ends that can be opened with fire substation {"site":"..."} : ' + (drawable.join(', ') || 'none in this sandbox yet')
+ (notDrawable.length ? '. Named but not yet in this sandbox: ' + notDrawable.join(', ') : ''),
substation:g, connections:d.conns, electrical_order:'out from the station, shortest circuit first' };
}, INPUTS);
// ---- TAPPING A FAR STATION WALKS THERE ---------------------------------------------------------
// The far end was only ever NAMED. A map you cannot walk is a picture. The engine's own hit-testing
// for shapes (shapeAsk) finds the mark under the finger; a tap is a press and a release in the same
// place, so a pan is never mistaken for a tap. A far end with a netlist re-fires this same command
// for that site; one without SAYS SO in words rather than doing nothing.
try {
let tapAt = null;
root.addEventListener('pointerdown', function (e) { tapAt = [e.clientX, e.clientY, Date.now()]; }, { passive:true });
root.addEventListener('pointerup', function (e) {
try {
const t = tapAt; tapAt = null;
if (!t || Math.hypot(e.clientX - t[0], e.clientY - t[1]) > 9 || Date.now() - t[2] > 700) return;
if (typeof sldShapes === 'undefined' || !sldShapes || !sldShapes.substation) return;
if (typeof shapeAsk !== 'function') return;
const s = shapeAsk(e.clientX, e.clientY);
if (!s || s.role !== 'sldstation' || !s.far) return;
const label = String(s.farLabel || s.far);
if ((DATA().netlists || {})[s.far]) {
if (typeof fireCommand === 'function') fireCommand('fire substation {"site":"' + label.replace(/"/g, '') + '"}', null);
} else {
sldShapes.saying = label + ' is named at the end of this circuit but has no netlist here yet, so it cannot be opened.';
if (typeof dirty !== 'undefined') dirty = true;
}
} catch (_) {}
}, { passive:true });
} catch (_) {}
try { if (root.FIRE_SLD_KIND) root.FIRE_SLD_KIND['substation'] = 'string'; } catch (_) {}
})(typeof window !== 'undefined' ? window : globalThis);
try { FIRE_SLD_KIND['substation'] = 'string'; } catch (_) {}
Kuiper Grid — I0090 Page
A web page in GlobalGrid2050 that uses SHA-256. Published at https://globalgrid2050.com/kuiper-grid/i0090/. It is built from the must step (`must`), the attr step (`attr`) and the sha256 step (`sha256`).
Set aside from the main view: 98% of its lines are the same as kuiper-grid/i0073/index.html (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 98% of lines shared with Kuiper Grid — I0097 Page; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.9802 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 kuiper-grid/i0073/index.html:1-108 073cc692d3750aac95d1654f9a0b315d2b568d11
- sha256 d8b64ea2972335bdf92eed589a32f83f4c10baea45012ad344b09db75579b3d5
- target sha256 fb96bcf6b8a812967bfc0fc386a3d015e90f507f76ce774101a57ea29aba253a
- group of 16 (identity.json near-copy edges >= 0.9)
- canonical rule: reachable, newest stamp, core repo, most lines
- re-pointed by apply.py version rule from file 3650 to file 3695; similarity was measured to file 3650
renderglobalgrid2050 / kuiper-grid/i0090/index.html · lines 1–108 of 108 · Entry point
- What it does
- It draws its content. Defines must, attr, sha256. Uses libraries …/NAME, ' + attr(url.href) + '. Side effects: changes the web page (DOM); 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).
- Inputs & outputs
- In: JSON file current.json. Out: web page.
- Downstream impact
- Used directly by 6 files: GlobalGrid2050 — Kuiper Grid Page (globalgrid2050, https://globalgrid2050.com/kuiper-grid/); GlobalGrid2050 Homepage Before Four Nests (globalgrid2050, https://globalgrid2050.com/homepage-before-four-nests-20260925.html); Homepage Versions — Before Refresh Page (globalgrid2050, https://globalgrid2050.com/homepage_versions/20260922-before-refresh/); Homepage V123 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v123.html); and 2 more. Reached from 103 other entry points, including GlobalGrid2050 Historical Builds (globalgrid2050, https://globalgrid2050.com/historical_builds.html); GlobalGrid2050 — Compute Page (globalgrid2050, https://globalgrid2050.com/compute/); GlobalGrid2050 — Kuiper Page (globalgrid2050, https://globalgrid2050.com/kuiper/). It is itself an entry point, published at https://globalgrid2050.com/kuiper-grid/i0090/.
- What it achieves
- THE WAY OUT. This page is a composer: with script off, or with a refused record, it renders nothing a reader can click. It reads `./current.json`.
- Why it matters
- Loaded by the Kuiper Grid page at https://globalgrid2050.com/kuiper-grid/ and 5 other pages.
- Application
- globalgrid2050 · kuiper-grid/i0090 · page
- Uses
- Manual (link), GlobalGrid2050 — Plant Page (link), GlobalGrid2050 — Kuiper Grid Page (link), GlobalGrid2050 — Compute Page (link), …/NAME, ' + attr(url.href) + '
- Used by
- linked from GlobalGrid2050 — Kuiper Grid Page (link), linked from GlobalGrid2050 Homepage Before Four Nests (link), linked from Homepage Versions — Before Refresh Page (link), linked from Homepage V123 (link), linked from Homepage V124 (link), linked from Homepage V125 (link)
- Produces
- must, attr, sha256
- Defines here
- must, attr, sha256
- 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/i0090/index.html:1-108 · blob 0494b748abdc4dc17b37013f19e40acc6aaaca79 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: agent_infra · users: ai_agent · canonical: production_core
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>globalgrid2050</title>
<style>
html,body{margin:0;background:#0b0d12;color:#d8dee9;font:13px/1.5 ui-monospace,Menlo,Consolas,monospace}
#composer{display:grid;place-items:center;min-height:50vh;padding:24px;text-align:center}
#composer strong{color:#5ec8f2;letter-spacing:.1em}
#composer small{color:#8b93a7}
#waysout{max-width:44rem;margin:0 auto;padding:0 20px 40px;border-top:1px solid #1b2030}
#waysout h2{font-size:14px;color:#5ec8f2;letter-spacing:.06em;text-transform:uppercase;margin:24px 0 8px}
#waysout p{color:#8b93a7;margin:8px 0}
#waysout ul{margin:10px 0;padding-left:1.1rem}
#waysout li{margin:7px 0;color:#8b93a7}
#waysout a{color:#5ec8f2;font-weight:600}
#waysout .small{font-size:12px;color:#6f7789}
</style>
</head>
<body data-composer="loading">
<main id="composer"><div><strong>GLOBALGRID2050</strong><br>checking this page against its record…<br><small>provided as is, without warranty of any kind; a chart, not a design</small></div></main>
<!-- THE WAY OUT. This page is a composer: with script off, or with a refused
record, it renders nothing a reader can click. Plain anchors, in the
served bytes, so this build is never a dead end. -->
<nav id="waysout">
<h2>Build i0090 — part of the Kuiper</h2>
<p>This address loads one development build. If it has not loaded, or you have script switched off, start from the plain pages:</p>
<ul>
<li><a href="/kuiper-grid/manual.html">The manual</a> — what this is, what to type, what the answer means, and what it refuses</li>
<li><a href="/plant/">Will this string go over 1500 V on the coldest morning?</a> — three commands ready to copy</li>
<li><a href="/kuiper-grid/">All development builds</a></li>
<li><a href="/compute/">Independent compute</a> · <a href="/">Everything else published here</a></li>
</ul>
<p class="small">A development build. Two of the four limits this engine measures a design against have no source in any document, and a verdict that turns on one of them is provisional. <a href="/kuiper-grid/manual.html#unsourced">The manual says which.</a></p>
<p class="small">A chart, not a design. Not a connection offer, not a constructability assessment, not a consenting design. No output of it is engineering.</p>
</nav>
<script type="module">
// THE COMPOSER. GridAtlas's pattern as it stands (gridatlas/atlas/index.html): one frozen shell, features as hashed
// cartridges, and current.json, the pointer, saying which. This page is the ONE ADDRESS that never changes. It reads
// the pointer, fetches the shell, fetches every cartridge the pointer names, and lets a cartridge in ONLY if its
// bytes hash to what the pointer says. A release is a change to the pointer; a rollback is the pointer put back;
// the shell is never edited. If anything does not match, nothing runs and the page says so in plain words.
//
// Two slots: replace-script the shell's <script src="…/NAME"> is pointed at the cartridge instead
// import-map an import of NAME anywhere in the shell resolves to the cartridge instead
// A cartridge is ONE file with no imports of its own neighbours: one file, one job.
const CLOSE = '</scr' + 'ipt>';
const box = document.getElementById('composer');
const must = (ok, why) => { if (!ok) throw new Error(why); };
const attr = v => String(v).replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<');
const sha256 = async bytes => [...new Uint8Array(await crypto.subtle.digest('SHA-256', bytes))].map(b => b.toString(16).padStart(2, '0')).join('');
try {
const r = await fetch('./current.json', { cache: 'no-store' });
must(r.ok, 'the record of this page could not be read (' + r.status + ')');
const cur = await r.json();
must(cur && cur.schema === 'globalgrid.current.v1', 'the record of this page is in a form this page does not know');
must(cur.architecture === 'IMMUTABLE_SHELL_PLUS_HASHED_CARTRIDGES', 'the record of this page names another architecture');
must(Array.isArray(cur.cartridge_order) && Array.isArray(cur.cartridges) && cur.shell, 'the record of this page is incomplete');
const shellUrl = new URL(cur.shell.index, location.href), shellBase = new URL(cur.shell.base, location.href).href;
const sr = await fetch(shellUrl, { cache: 'no-store' });
must(sr.ok, 'the page itself could not be fetched (' + sr.status + ')');
const shellBytes = await sr.arrayBuffer();
must(await sha256(shellBytes) === cur.shell.sha256, 'the page itself is not the one that was released');
let html = new TextDecoder('utf-8').decode(shellBytes);
must(/<head\b/i.test(html) && /<body\b/i.test(html), 'the page itself is not a page');
const byId = new Map(cur.cartridges.map(c => [c.id, c])), loaded = [], imports = {};
const tags = new RegExp('<script\\b([^>]*)\\bsrc=(["\'])([^"\']+)\\2([^>]*)>\\s*<\\/script>', 'gi');
for (const id of cur.cartridge_order) {
const c = byId.get(id);
must(c, 'a part named in the record is missing from it: ' + id);
must(/^[a-f0-9]{64}$/.test(c.sha256 || ''), id + ': the record holds no fingerprint for it');
must(c.slot === 'replace-script' || c.slot === 'import-map', id + ': a slot this page does not have');
must(typeof c.replaces === 'string' && c.replaces, id + ': the record does not say what it replaces');
const url = new URL(c.path, location.href);
const cr = await fetch(url, { cache: 'no-store' });
must(cr.ok, id + ' could not be fetched (' + cr.status + ')');
must(await sha256(await cr.arrayBuffer()) === c.sha256, id + ' is not the file that was released');
if (c.slot === 'import-map') imports[new URL(c.replaces, shellBase).href] = url.href;
else {
let done = false;
html = html.replace(tags, (full, a, q, src, b) => {
if (done || String(src).split(/[?#]/)[0].split('/').pop() !== c.replaces) return full; // matched by file name
done = true;
return '<script' + a + 'data-cartridge="' + attr(id) + '" src="' + attr(url.href) + '"' + b + '>' + CLOSE;
});
must(done, id + ': the page has no place for it (' + c.replaces + ')');
}
loaded.push({ id, generation: c.generation, sha256: c.sha256 });
}
const state = JSON.stringify({ schema: cur.schema, generation: cur.generation, shell: cur.shell, cartridges: loaded }).replace(/</g, '\\u003c');
const head = '\n<base href="' + attr(shellBase) + '">'
+ (Object.keys(imports).length ? '\n<script type="importmap">' + JSON.stringify({ imports }).replace(/</g, '\\u003c') + CLOSE : '')
+ '\n<script>window.__COMPOSED__=' + state + ';document.documentElement.dataset.generation=' + JSON.stringify(cur.generation) + ';' + CLOSE;
html = html.replace(/<head([^>]*)>/i, m => m + head);
document.open(); document.write(html); document.close();
} catch (e) {
console.error('[composer]', e);
document.body.dataset.composer = 'refused';
box.innerHTML = '<div><strong>THIS PAGE DID NOT OPEN</strong><br>' + String(e && e.message || e).replace(/[<>&]/g, '')
+ '<br><small>Nothing was run. The released page has not been changed. The plain pages below still work.<br>provided as is, without warranty of any kind; a chart, not a design</small></div>';
}
</script>
</body>
</html>