GLOBALGRID2050 / EXPLORE CODE

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

Kuiper Programs (part 124)

A JavaScript file in the cartridges folder of GlobalGrid2050 that draws interconnectors, london underground, grid 66kV and motorway services, and uses data from the faraday repository.

700 lines of JavaScript from globalgrid2050, in 1 file. Topic: Kuiper, cosmos and drawing engines. Section 1393 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/i0088/cartridges/008800000000-kuiper-programs.js lines 421–1120

Kuiper Programs

A JavaScript file in the cartridges folder of GlobalGrid2050 that draws interconnectors, london underground, grid 66kV and motorway services, and uses data from the faraday repository.

Set aside from the main view: 99% of its lines are the same as kuiper-grid/i0089/cartridges/008900000000-kuiper-programs.js (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 98% of lines shared with Kuiper Programs; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9873 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 kuiper-grid/i0089/cartridges/008900000000-kuiper-programs.js:1-4690 56db141d495fee7c1255ae88d29ac3f7a5fb8724
  • sha256 daff29fbdd867ff327ebc8c6c1338405afe422e1722b551bf8a6898ccb31880f
  • target sha256 71eba91ad4eea2f2602c4ca3427ad22b95e0514f9e9087cd231ed7dcf5fa4633
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

renderglobalgrid2050 / kuiper-grid/i0088/cartridges/008800000000-kuiper-programs.js · lines 421–1120 of 4659 (continued from section 1392) · Not reached from any entry point (candidate for review) · pattern drawLocalSystem (shared by 2 files)

What it does
It draws interconnectors, london underground, grid 66kV and motorway services. Defines 253 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, 750kV, 400kV, 275kV, 132kV, 110kV.
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: 750kV, 400kV, 275kV, 132kV, 110kV, 66kV, 50kV, 33kV.
What it achieves
It makes body (`makeBody`), sets tag (`setTag`) and draws tube map (`drawTubeMap`). A cartridge of the Kuiper shell. Its code works with 33 kV, 11 kV and 275 kV. It responds to click events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · kuiper-grid/i0088/cartridges · script
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
tubeHullOf, cr, tubeSwell, tubeLattice, tubeRoute, tubeInterchange, tubeAt, drawTubeMap, passed, tierOf, tubeAttribution, tubeFit, tubeFind, tubeNearest, score, tubeNation, tubeRegionSet, rad, tubeCage, tubeCard, put, localFromGraph, localSystem, localWords, localCut, localTrim, drawLocalSystem, slot, leg, say
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/i0088/cartridges/008800000000-kuiper-programs.js:421-1120 · blob d98009f128a079f2699fc0e940870cfd978bea61 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: agent_infra · users: ai_agent · canonical: duplicate_candidate
    for (const a of q) for (const [b, li] of TUBE_ADJ[a]) {
      if (kv && TUBE_DATA.stations[b][3] !== kv && b !== from) continue;
      links.add(li);
      if (!seen.has(b)) { seen.set(b, h + 1); next.push(b); } }
    q.length = 0; q.push(...next); }
  // a link is only inside the cage when BOTH its ends are
  for (const li of Array.from(links)) { const L = TUBE_DATA.links132[li];
    if (!seen.has(L[0]) || !seen.has(L[1])) links.delete(li); }
  return { set: seen, links }; }
// The outline itself: the precomputed hull when the data carries one, else the gift wrap in the page.
function tubeHullOf(pts){ if (pts.length < 3) return pts.slice();
  const p = pts.slice().sort((a, b) => a[0] - b[0] || a[1] - b[1]);
  const cr = (o, a, b) => (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);
  const lo = [], up = [];
  for (const q of p) { while (lo.length >= 2 && cr(lo[lo.length - 2], lo[lo.length - 1], q) <= 0) lo.pop(); lo.push(q); }
  for (let i = p.length - 1; i >= 0; i--) { const q = p[i];
    while (up.length >= 2 && cr(up[up.length - 2], up[up.length - 1], q) <= 0) up.pop(); up.push(q); }
  lo.pop(); up.pop(); return lo.concat(up); }
function tubeSwell(hull, pad){ if (hull.length < 2) return hull;
  let mx = 0, my = 0; for (const q of hull) { mx += q[0]; my += q[1]; } mx /= hull.length; my /= hull.length;
  return hull.map(q => { const dx = q[0] - mx, dy = q[1] - my, d = Math.max(1e-9, Math.hypot(dx, dy));
    return [q[0] + dx / d * pad, q[1] + dy / d * pad]; }); }

// ---- THE TUBE MAP: the caged set re-laid on an octilinear lattice ----------------------------
// Every station goes to the nearest free crossing of a square lattice; where two want the same
// crossing the second takes the nearest free one, searched outward in rings, so the ORDER of the
// network survives even though the geography does not. That is the whole trick of an underground
// map: keep the sequence, drop the miles.
function tubeLattice(ids, focus){
  const pitch = (TUBE_DATA.defaults && TUBE_DATA.defaults.pitch) || 0.16;
  const rot = ((TUBE_DATA.defaults && TUBE_DATA.defaults.rotation) || 0) * Math.PI / 180;
  const f = TUBE_GEO[focus], cosR = Math.cos(rot), sinR = Math.sin(rot);
  let far = 0; for (const i of ids) far = Math.max(far, Math.hypot(TUBE_GEO[i][0] - f[0], TUBE_GEO[i][1] - f[1]));
  const k = far > 1e-9 ? (pitch * 3.4) / far : 1;                 // the cage fills about seven pitches
  const taken = new Map(), out = new Map();
  const order = ids.slice().sort((a, b) =>
    Math.hypot(TUBE_GEO[a][0] - f[0], TUBE_GEO[a][1] - f[1]) - Math.hypot(TUBE_GEO[b][0] - f[0], TUBE_GEO[b][1] - f[1]));
  for (const i of order) { const dx = (TUBE_GEO[i][0] - f[0]) * k, dy = (TUBE_GEO[i][1] - f[1]) * k;
    const rx = dx * cosR - dy * sinR, ry = dx * sinR + dy * cosR;
    let gx = Math.round(rx / pitch), gy = Math.round(ry / pitch);
    for (let r = 0; r < 40; r++) { let done = false;
      for (let a = -r; a <= r && !done; a++) for (let b = -r; b <= r && !done; b++) {
        if (r > 0 && Math.abs(a) !== r && Math.abs(b) !== r) continue;
        const key = (gx + a) + ',' + (gy + b);
        if (!taken.has(key)) { taken.set(key, i); out.set(i, [(gx + a) * pitch, (gy + b) * pitch]); done = true; } }
      if (done) break; } }
  return out; }
// A LINK IS 0, 45 OR 90 DEGREES AND NOTHING ELSE: the diagonal is taken first and the straight run
// finishes the job, which is what makes a tube map read as a diagram rather than a sketch.
function tubeRoute(a, b){ const dx = b[0] - a[0], dy = b[1] - a[1];
  const ax = Math.abs(dx), ay = Math.abs(dy);
  if (ax < 1e-9 || ay < 1e-9 || Math.abs(ax - ay) < 1e-9) return [a, b];
  const d = Math.min(ax, ay), sx = Math.sign(dx), sy = Math.sign(dy);
  return [a, [a[0] + sx * d, a[1] + sy * d], b]; }
// AN INTERCHANGE is a station where classes meet - the one place a traveller changes line.
function tubeInterchange(i){ const c = TUBE_DATA.stations[i][3];
  for (const [b] of TUBE_ADJ[i]) if (TUBE_DATA.stations[b][3] !== c) return true;
  return false; }

// ---- the drawing ------------------------------------------------------------------------------
function tubeAt(i){ const g = TUBE_GEO[i];
  if (TUBE.lattice && TUBE.lattice.has(i)) { const l = TUBE.lattice.get(i), u = TUBE.morph;
    return [g[0] + (l[0] + TUBE_GEO[TUBE.focus][0] - g[0]) * u, g[1] + (l[1] + TUBE_GEO[TUBE.focus][1] - g[1]) * u]; }
  return g; }
function drawTubeMap(){
  if (!TUBE.on) return;
  const el2 = tubeLayer(), t = performance.now();
  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 (el2.width !== W || el2.height !== H) { el2.width = W; el2.height = H; }
  const ctx = el2.getContext('2d'); if (!ctx) return;
  ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, innerWidth, innerHeight);
  // THE GROUND. True black, because the marks are what must be read and the disc beneath is not part
  // of this picture at all.
  ctx.fillStyle = TUBE_GROUND; ctx.fillRect(0, 0, innerWidth, innerHeight);
  const band = tubeBand(); TUBE.bandTop = band.top;
  // THE LOCAL SYSTEM IS A PICTURE OF ITS OWN and does not share the nation's camera; it is drawn
  // straight onto the band, because one station's system has no geography worth keeping.
  if (TUBE.view === 'local' && TUBE.local) { drawLocalSystem(ctx, dpr, band, t);
    TUBE.drawMs = TUBE.drawMs * 0.8 + (performance.now() - t) * 0.2; return; }
  const px = shapeScale(), S = p => shapePoint(p);
  const caged = TUBE.lit, cagedL = TUBE.litLinks;
  // THE SWEEP. The ring leaves the tapped station and everything it has passed that belongs to the
  // cage stays lit; everything else goes dark. It advances on the frames the shell already draws.
  let sweep = 1e9;
  if (TUBE.phase === 'pulse') { const u = Math.min(1, (t - TUBE.t0) / 1100);
    sweep = u * Math.hypot(innerWidth, innerHeight) * 0.75;
    if (u >= 1) { TUBE.phase = 'lay'; TUBE.t0 = t; }
    try { dirty = true; } catch (_) {} }
  else if (TUBE.phase === 'lay') { const u = Math.min(1, (t - TUBE.t0) / 700);
    TUBE.morph = u < 1 ? u * u * (3 - 2 * u) : 1;
    if (u >= 1) TUBE.phase = 'tube'; try { dirty = true; } catch (_) {} }
  const centre = TUBE.focus >= 0 ? S(tubeAt(TUBE.focus)) : null;
  const passed = p => !centre || sweep >= 1e8 || Math.hypot(p[0] - centre[0], p[1] - centre[1]) <= sweep;
  ctx.lineCap = 'round'; ctx.lineJoin = 'round';
  // 1. THE LINKS. Dark ones first, in one batched path, so a phone strokes once and not 5,800 times.
  const L = TUBE_DATA.links132;
  if (!caged || TUBE.phase === 'pulse') { ctx.beginPath();
    for (let i = 0; i < L.length; i++) { if (caged && cagedL.has(i)) continue;
      const a = S(tubeAt(L[i][0])), b = S(tubeAt(L[i][1]));
      if (Math.max(a[0], b[0]) < -40 || Math.min(a[0], b[0]) > innerWidth + 40) continue;
      if (Math.max(a[1], b[1]) < -40 || Math.min(a[1], b[1]) > innerHeight + 40) continue;
      ctx.moveTo(a[0], a[1]); ctx.lineTo(b[0], b[1]); }
    ctx.lineWidth = 1; ctx.strokeStyle = TUBE_DARK; ctx.stroke(); }
  // 2. THE LIT LINKS, one stroke per voltage class, weight by how many circuits run the route.
  // THE WHOLE NETWORK IS MORE THAN ONE CLASS. The cage walks the 132 kV graph, which is the one whose
  // shape has been checked; but a nation view drawn in 132 kV alone shows a country with no
  // transmission on it. So when the richer set is carried, THE NATION VIEW DRAWS IT - every link at
  // its own class colour - and the cage stays on the graph it can honestly walk.
  const ALLL = (!caged && TUBE_DATA.linksAll && TUBE_DATA.linksAll.length) ? TUBE_DATA.linksAll : null;
  const src = ALLL || L;
  const wantL = caged ? Array.from(cagedL) : src.map((_, i) => i);
  const byW = new Map();
  for (const i of wantL) { const lk = src[i];
    if (caged && (!passed(S(tubeAt(lk[0]))) && !passed(S(tubeAt(lk[1]))))) continue;
    const kvc = ALLL ? lk[2] : Math.max(TUBE_DATA.stations[lk[0]][3], TUBE_DATA.stations[lk[1]][3]);
    const key = kvc + ':' + Math.min(4, (ALLL ? lk[4] : lk[3]) || 1);
    if (!byW.has(key)) byW.set(key, []); byW.get(key).push(i); }
  // HIGHEST CLASS LAST, so a 400 kV route is never buried under a 33 kV one it crosses.
  const order2 = Array.from(byW.keys()).sort((a, b) => Number(a.split(':')[0]) - Number(b.split(':')[0]));
  for (const key of order2) { const list = byW.get(key), [kvc, par] = key.split(':').map(Number);
    ctx.beginPath();
    for (const i of list) { const lk = src[i];
      const pts = TUBE.lattice && TUBE.morph > 0.5 ? tubeRoute(S(tubeAt(lk[0])), S(tubeAt(lk[1])))
                                                   : [S(tubeAt(lk[0])), S(tubeAt(lk[1]))];
      ctx.moveTo(pts[0][0], pts[0][1]); for (let j = 1; j < pts.length; j++) ctx.lineTo(pts[j][0], pts[j][1]); }
    ctx.lineWidth = (TUBE.lattice ? 3.2 : 1.3) * (0.8 + 0.35 * par);
    ctx.strokeStyle = tubeInk(kvc); ctx.globalAlpha = caged ? 1 : 0.85; ctx.stroke(); }
  ctx.globalAlpha = 1;
  // 3. THE STATIONS. Binned by voltage class and batched; below a zoom a station is a mark and not a
  //    ring, because 5,800 rings on a telephone is a grey cloud and says nothing.
  const rad = TUBE.lattice ? 5.2 : Math.max(1.1, Math.min(4.2, px * 0.010));
  const bins = new Map(); TUBE.hit = [];
  for (let i = 0; i < TUBE_DATA.stations.length; i++) {
    const inCage = !caged || caged.has(i);
    const p = S(tubeAt(i));
    if (p[0] < -30 || p[0] > innerWidth + 30 || p[1] < -30 || p[1] > innerHeight + 30) continue;
    if (caged && !inCage) { if (TUBE.lattice) continue; }
    if (caged && inCage && !passed(p)) continue;
    const kvc = TUBE_DATA.stations[i][3], key = (caged && !inCage) ? 'dark' : String(kvc);
    if (!bins.has(key)) bins.set(key, []); bins.get(key).push([p, i]);
    if (!caged || inCage) TUBE.hit.push([p[0], p[1], i]); }
  for (const [key, list] of bins) { const dark = key === 'dark';
    ctx.beginPath();
    for (const [p] of list) { ctx.moveTo(p[0] + rad, p[1]); ctx.arc(p[0], p[1], dark ? rad * 0.6 : rad, 0, 6.2832); }
    ctx.fillStyle = dark ? TUBE_DARK : tubeInk(Number(key)); ctx.fill();
    if (!dark && rad >= 3) { ctx.lineWidth = 1.2; ctx.strokeStyle = TUBE_GROUND; ctx.stroke(); } }
  // AN INTERCHANGE RING, only where classes actually meet and only when there is room for it to be a
  // ring rather than a smudge.
  if (rad >= 3) { ctx.beginPath(); let any = false;
    for (const [, list] of bins) for (const [p, i] of list) { if (!tubeInterchange(i)) continue;
      if (caged && !caged.has(i)) continue;
      ctx.moveTo(p[0] + rad * 1.9, p[1]); ctx.arc(p[0], p[1], rad * 1.9, 0, 6.2832); any = true; }
    if (any) { ctx.lineWidth = 1.6; ctx.strokeStyle = TUBE_LIT; ctx.stroke(); } }
  // 4. THE CAGE ITSELF, a fine outline round the lit set, and the ring while it is still travelling.
  if (TUBE.hull && TUBE.phase !== 'pulse') { const h = TUBE.hull.map(q => S(q));
    if (h.length > 2) { ctx.beginPath(); ctx.moveTo(h[0][0], h[0][1]);
      for (let i = 1; i < h.length; i++) ctx.lineTo(h[i][0], h[i][1]);
      ctx.closePath(); ctx.setLineDash([5, 5]); ctx.lineWidth = 1.2; ctx.strokeStyle = TUBE_CAGE;
      ctx.globalAlpha = 0.75; ctx.stroke(); ctx.setLineDash([]); ctx.globalAlpha = 1; } }
  if (TUBE.phase === 'pulse' && centre) { ctx.beginPath(); ctx.arc(centre[0], centre[1], Math.max(1, sweep), 0, 6.2832);
    ctx.lineWidth = 2.2; ctx.strokeStyle = TUBE_CAGE; ctx.globalAlpha = 0.55; ctx.stroke(); ctx.globalAlpha = 1; }
  // 5. THE NAMES. By tier as the camera comes in, never shrunk, never overlapped, and never under
  //    nine pixels: a name too small to read is worse than no name at all.
  const tiers = TUBE_DATA.labelTiers || {};
  // TRANSMISSION IS ALWAYS TIER ONE, by the Atlas's own test, so the first names a reader sees on
  // this map are the first names they would see on that one.
  const tierOf = i => tubeIsTransmission(TUBE_DATA.stations[i][3]) ? 1
    : (tiers[1] && tiers[1].indexOf(i) >= 0) ? 1 : (tiers[2] && tiers[2].indexOf(i) >= 0) ? 2 : 3;
  const showTier = TUBE.lattice ? 3 : px < 900 ? 1 : px < 2400 ? 2 : 3;
  const size = TUBE.lattice ? 12 : px < 1600 ? 10 : 11;
  ctx.setTransform(1, 0, 0, 1, 0, 0);
  ctx.font = '600 ' + (size * dpr) + 'px ui-monospace,Menlo,Consolas,monospace';
  ctx.textBaseline = 'middle'; ctx.textAlign = 'left';
  const put = [];
  // HOW MANY NAMES A SCREEN CAN HOLD. Dropping what clashes is not enough on its own: five thousand
  // candidates fill every gap and the result is a page of words with a map hidden under it. An
  // underground map names every stop because it has forty of them. So the nation view is given a
  // BUDGET - about one name per two thousand square pixels - spent on the biggest junctions first,
  // and the rest of the names wait for the reader to come closer. Inside a cage every station is
  // named, because that is the whole point of having drawn the cage.
  const budget = TUBE.lattice ? 1e9 : Math.max(8, Math.round(innerWidth * innerHeight / 2000));
  let spent = 0;
  const cand = [];
  for (const [, list] of bins) for (const [p, i] of list) {
    if (caged && !caged.has(i)) continue;
    if (tierOf(i) > showTier) continue;
    // A STATION WITH NO NAME HAS NOTHING TO SAY ON THE NATION VIEW. The word "unnamed" written five
    // hundred times is not information; it is the picture telling the reader about the data's gaps
    // instead of about the network. Inside a cage the mark is named, because there the reader has
    // asked about that station in particular and needs to know the data does not carry its name.
    if (!TUBE_DATA.stations[i][5] && !TUBE.lattice) continue;
    cand.push([p, i]); }
  cand.sort((a, b) => (tierOf(a[1]) - tierOf(b[1])) || (tubeDegree(b[1]) - tubeDegree(a[1])));
  // A NAME NEVER SITS ON A MARK, not its own and not its neighbour's. Every mark on the screen is put
  // into the same collision list the names are tested against BEFORE any name is placed, so the only
  // places left for a word are places where there is no station under it.
  for (const [, list] of bins) for (const [p] of list) {
    const r2 = (rad + 2) * dpr;
    put.push([p[0] * dpr - r2, p[1] * dpr - r2, p[0] * dpr + r2, p[1] * dpr + r2]); }
  // THE ORDER THE SLOTS ARE TRIED IN IS THE DATA'S. The runner works out which side of a mark is
  // emptiest for this layout and writes it down as label_slot_order; the page obeys it instead of
  // always reaching to the right first.
  const SLOT_ORDER = (TUBE_DATA.defaults && TUBE_DATA.defaults.label_slot_order) || [0, 1, 2, 3];
  if (size >= TUBE_TEXT_FLOOR_PX) for (const [p, i] of cand) {
    if (spent >= budget) break;
    const text = TUBE_DATA.stations[i][5] || 'unnamed station';
    const w = ctx.measureText(text).width, h2 = (size + 4) * dpr;
    const all = [[rad + 6, 0], [-(rad + 6) - w / dpr, 0], [-w / dpr / 2, -(rad + 10)], [-w / dpr / 2, rad + 10]];
    const slots = SLOT_ORDER.map(k => all[k]).filter(Boolean);
    for (const [ox, oy] of (slots.length ? slots : all)) {
      const x0 = Math.round((p[0] + ox) * dpr), y0 = Math.round((p[1] + oy) * dpr) - h2 / 2;
      const pad = (TUBE.lattice ? 2 : 6) * dpr;
      const box = [x0 - pad, y0 - pad * 0.5, x0 + w + pad, y0 + h2 + pad * 0.5];
      if (box[1] < band.top * dpr || box[3] > band.bottom * dpr) continue;
      let clash = false; for (const q of put) if (box[0] < q[2] && box[2] > q[0] && box[1] < q[3] && box[3] > q[1]) { clash = true; break; }
      if (clash) continue;
      put.push(box); spent++; ctx.fillStyle = TUBE_LIT; ctx.fillText(text, x0, y0 + h2 / 2); break; } }
  ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  tubeAttribution(ctx, dpr, band);
  ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  TUBE.drawMs = TUBE.drawMs * 0.8 + (performance.now() - t) * 0.2;
}
// WHERE THE PICTURE CAME FROM, ALWAYS, AND INSIDE ITS OWN BAND. The attribution used to be written
// upward from a guessed line and landed on top of the page's own "provided as is"; now it is wrapped
// to the width, measured, given a band of its own with a floor under it, and that band is placed
// ABOVE everything the page has already claimed - the foot, the answer window. Two sentences that
// overlap are two sentences nobody can read, and provenance that cannot be read is not provenance.
function tubeAttribution(ctx, dpr, band){
  const small = Math.max(TUBE_TEXT_FLOOR_PX, 10), lh = small + 4;
  ctx.font = '500 ' + (small * dpr) + 'px ui-monospace,Menlo,Consolas,monospace';
  ctx.textBaseline = 'middle'; ctx.textAlign = 'left';
  const maxW = (innerWidth - 24) * dpr, lines = [];
  let cur = '';
  for (const w of String(TUBE_DATA.attribution || '').split(' ')) { const t2 = cur ? cur + ' ' + w : w;
    if (ctx.measureText(t2).width > maxW && cur) { lines.push(cur); cur = w; } else cur = t2; }
  if (cur) lines.push(cur);
  const h = lines.length * lh + 8;
  const y0 = Math.max(band.top, band.bottom - h);
  ctx.fillStyle = '#04060ae8'; ctx.fillRect(0, y0 * dpr, innerWidth * dpr, h * dpr);
  ctx.fillStyle = '#2a3444'; ctx.fillRect(0, y0 * dpr, innerWidth * dpr, Math.max(1, dpr));
  ctx.fillStyle = '#8aa0b6';
  lines.forEach((ln, k) => ctx.fillText(ln, Math.round(12 * dpr), Math.round((y0 + 4 + lh * k + lh / 2) * dpr)));
  return y0; }

// ---- firing it --------------------------------------------------------------------------------
function tubeFit(ids, laid){ if (!ids.length || typeof flyTo !== 'function') return;
  const R = Math.sqrt(SPACE) * BODY_RADIUS_MAX;
  let x0 = 1e9, x1 = -1e9, y0 = 1e9, y1 = -1e9;
  const f = TUBE.focus >= 0 ? TUBE_GEO[TUBE.focus] : [0, 0];
  for (const i of ids) { const l = laid && TUBE.lattice && TUBE.lattice.get(i);
    const p = l ? [l[0] + f[0], l[1] + f[1]] : tubeAt(i);
    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 w = Math.max(0.05, (x1 - x0) * R), h = Math.max(0.05, (y1 - y0) * R);
  // A NAME IS AS WIDE AS THE STATION IT NAMES IS SMALL, so the room left round a tube map is much
  // wider than round a scatter of marks: the widest name on this data is about 14 characters.
  const room = laid ? [2.30, 1.90] : [1.35, 1.55];
  const z = Math.min(innerWidth / (w * room[0]), innerHeight / (h * room[1]));
  flyTo((x0 + x1) / 2 * R, (y0 + y1) / 2 * R, z); }
function tubeFind(place){ const q = String(place || '').trim().toLowerCase(); if (!q) return -1;
  const S = TUBE_DATA.stations;
  for (let i = 0; i < S.length; i++) if (S[i][5] && S[i][5].toLowerCase() === q) return i;
  for (let i = 0; i < S.length; i++) if (S[i][0].toLowerCase() === q) return i;
  for (let i = 0; i < S.length; i++) if (S[i][5] && S[i][5].toLowerCase().indexOf(q) === 0) return i;
  for (let i = 0; i < S.length; i++) if (S[i][5] && S[i][5].toLowerCase().indexOf(q) >= 0) return i;
  return -1; }
// A PLACE THAT MATCHES NOTHING IS REFUSED IN WORDS, with five names to try instead. A picture that
// quietly shows the wrong station is worse than one that says it does not know.
function tubeNearest(place){ const q = String(place || '').trim().toLowerCase();
  const names = TUBE_DATA.stations.map(s => s[5]).filter(Boolean).sort();
  const score = n => { const a = n.toLowerCase(); let k = 0; for (let i = 0; i < Math.min(a.length, q.length); i++) { if (a[i] !== q[i]) break; k++; } return -k; };
  return names.slice().sort((a, b) => score(a) - score(b) || a.localeCompare(b)).slice(0, 5).sort();
}
function tubeNation(){ TUBE.on = true; TUBE.local = null; TUBE.hitLocal = [];
  TUBE.view = 'nation'; TUBE.focus = -1; TUBE.phase = 'nation';
  TUBE.lit = null; TUBE.litLinks = null; TUBE.hull = null; TUBE.lattice = null; TUBE.morph = 0;
  tubeLayer(); try { document.body.classList.add('tube-on'); } catch (_) {}
  tubeFit(TUBE_DATA.stations.map((_, i) => i));
  try { dirty = true; } catch (_) {} }
// A REGION IS MILES, NOT HOPS. The cage answers "what is two stops from here along the wires"; a
// council officer asks "what is in my district", which is a circle on the ground and includes the
// stations this data does not yet know how to join up. Both are real questions and they are not the
// same question, so the region view is its own selection and says so in its own words.
function tubeRegionSet(i, km){ const S = TUBE_DATA.stations, a = S[i];
  const set = new Map(), R = 6371;
  const rad = d => d * Math.PI / 180;
  for (let j = 0; j < S.length; j++) { const dLat = rad(S[j][2] - a[2]), dLon = rad(S[j][1] - a[1]);
    const h = Math.sin(dLat / 2) ** 2 + Math.cos(rad(a[2])) * Math.cos(rad(S[j][2])) * Math.sin(dLon / 2) ** 2;
    if (2 * R * Math.asin(Math.min(1, Math.sqrt(h))) <= km) set.set(j, 1); }
  set.set(i, 0);
  const links = new Set();
  TUBE_DATA.links132.forEach((L, k) => { if (set.has(L[0]) && set.has(L[1])) links.add(k); });
  return { set, links }; }
function tubeCage(i, hops, kv, given){
  const r = given || tubeBFS(i, Math.max(1, Math.min(3, hops || 2)), kv || 0);
  TUBE.on = true; TUBE.local = null; TUBE.hitLocal = [];
  TUBE.view = (given && given.view) || 'station'; TUBE.focus = i; TUBE.hops = hops; TUBE.kv = kv || 0;
  TUBE.lit = r.set; TUBE.litLinks = r.links; TUBE.morph = 0;
  const ids = Array.from(r.set.keys());
  TUBE.lattice = tubeLattice(ids, i);
  const pre = TUBE_DATA.cages && TUBE_DATA.cages[i];
  TUBE.hull = null;
  TUBE.phase = 'pulse'; TUBE.t0 = performance.now();
  tubeLayer(); try { document.body.classList.add('tube-on'); } catch (_) {}
  // FIT THE LATTICE, NOT THE GEOGRAPHY: the picture the reader ends on is the tube map, so the room
  // made for it is the room the tube map needs, names and all.
  tubeFit(ids, true);
  // the outline is taken from the data when the runner has worked it out, else wrapped here
  setTimeout(() => { if (TUBE.focus !== i) return;
    const pts = ids.map(j => { const l = TUBE.lattice.get(j); return [l[0] + TUBE_GEO[i][0], l[1] + TUBE_GEO[i][1]]; });
    TUBE.hull = tubeSwell(pre && pre.hull ? pre.hull : tubeHullOf(pts), 0.07); }, 0);
  try { dirty = true; } catch (_) {}
  return ids.length; }
// ---- TWO CLICKS: the card ---------------------------------------------------------------------
// The engine's own card element and its own classes; every figure says where it came from, and the
// one sentence that keeps a reader honest is at the foot of it.
function tubeCard(i){
  if (typeof card === 'undefined' || !card) return;
  cardToken++; cardShown = null; card.replaceChildren(); card.style.display = 'block'; card.scrollTop = 0;
  card.classList.add('short');
  const x = el('button', 'cc-x', '×'); x.type = 'button'; x.setAttribute('aria-label', 'close');
  x.addEventListener('click', () => { card.style.display = 'none'; try { dirty = true; } catch (_) {} });
  card.append(x);
  const put = (s, cls) => card.append(el('div', cls || 'cc-plain', s));
  const S = TUBE_DATA.stations[i];
  put(S[5] || 'unnamed station', 'cc-title');
  const classes = new Set([S[3]]); for (const [b] of TUBE_ADJ[i]) classes.add(TUBE_DATA.stations[b][3]);
  const cls = Array.from(classes).map(v => tubeClassOf(v) === null ? v + ' kV (unclassified)' : tubeClassOf(v) + ' kV');
  put('voltage classes here: ' + cls.join(', ') + ' · from open data'
    + (tubeIsTransmission(S[3]) ? ' · transmission' : ''));
  const deg = tubeDegree(i);
  const bridge = TUBE_ADJ[i].some(([, li]) => TUBE_BRIDGES.has(li));
  put(deg === 1 ? 'SINGLE FED: one link in and out. Losing it loses this station.'
    : bridge ? 'On a BRIDGE link: one of its links, if lost, cuts the network in two.'
             : deg + ' links, none of them a bridge · from open data');
  // THE WAY INTO THE STATION'S OWN SYSTEM, from the card the reader already has open, because that is
  // where the question "and what does it actually feed?" is asked.
  { const go = el('div', 'cc-plain', 'open the local system →');
    go.style.cursor = 'pointer'; go.style.textDecoration = 'underline'; go.style.color = '#7ff0ff';
    go.addEventListener('click', () => { try { fireLocal({ station: S[0] }); card.style.display = 'none'; } catch (_) {} });
    card.append(go); }
  put('links from here · from open data', 'cc-plain');
  for (const [b, li] of TUBE_ADJ[i]) { const lk = TUBE_DATA.links132[li];
    const row = el('div', 'cc-plain', (TUBE_DATA.stations[b][5] || 'unnamed station') + '  · ' + lk[2] + ' km · '
      + (lk[3] > 1 ? lk[3] + ' circuits' : '1 circuit') + (TUBE_BRIDGES.has(li) ? ' · BRIDGE' : ''));
    row.style.cursor = 'pointer'; row.style.textDecoration = 'underline';
    row.setAttribute('data-tube-to', String(b));
    row.addEventListener('click', () => { tubeCage(b, TUBE.hops, TUBE.kv); tubeCard(b); });
    card.append(row); }
  const n1 = tubeBFS(i, 1, 0).set.size - 1, n2 = tubeBFS(i, 2, 0).set.size - 1, n3 = tubeBFS(i, 3, 0).set.size - 1;
  put('within 1 hop: ' + n1 + ' · within 2: ' + n2 + ' · within 3: ' + n3 + ' · from open data');
  put('Topology from open map data; says nothing about capacity or headroom.', 'cc-refuse');
  put(TUBE_NOT + ' Queue position, committed connections, thermal and fault headroom, consent and commercial terms decide that, and none of them is in this data.', 'cc-plain');
  put(TUBE_DATA.attribution);
  if (typeof layout === 'function') layout(); }

// ---- ONE CLICK on the picture -----------------------------------------------------------------
// The layer takes no pointer events at all; the window listens, exactly as the shapes layer does,
// so the shell's own tap on a dot is untouched when this picture is not up.
addEventListener('pointerdown', function (e) {
  if (!TUBE.on || !TUBE.hit.length) return;
  let best = -1, bd = 22;
  for (const [x, y, i] of TUBE.hit) { const d = Math.hypot(e.clientX - x, e.clientY - y); if (d < bd) { bd = d; best = i; } }
  if (best < 0) return;
  if (TUBE.view !== 'nation' && TUBE.lit && TUBE.lit.has(best)) tubeCard(best);     // two clicks: the card
  else tubeCage(best, TUBE.hops, TUBE.kv);                                          // one click: the cage
}, { passive: true });
// INSIDE A LOCAL SYSTEM every mark is a station, and tapping one asks the same question of it: show
// me THAT station's system. One gesture, one meaning, wherever the reader is standing.
addEventListener('pointerdown', function (e) {
  if (!TUBE.on || TUBE.view !== 'local' || !TUBE.hitLocal.length) return;
  let best = null, bd = 28;
  for (const [x, y, id] of TUBE.hitLocal) { const d = Math.hypot(e.clientX - x, e.clientY - y);
    if (d < bd) { bd = d; best = id; } }
  if (best) { try { fireLocal({ station: best }); } catch (_) {} }
}, { passive: true });
addEventListener('keydown', function (e) { if (e.key === 'Escape' && TUBE.on) tubeGone(); });

// ===== THE LOCAL SYSTEM =========================================================================
// WHAT THIS IS FOR. The nation view answers "where is it". This answers the only question a council
// officer actually has to answer: WHAT IS THIS STATION'S SYSTEM. It is the same tube map drawn at
// one station's scale - the supply comes in from the top, the station sits in the middle, and the
// loads hang below it - so a reader who has learnt the nation view has nothing new to learn here.
// IT REFUSES TO PRETEND. Anything the data guessed is DASHED, anything that runs off the edge of what
// we know is drawn as an open terminus, and a line in plain words says how much of the system is
// actually on the page. A picture that quietly closes its own gaps is worse than no picture.
/* LOCAL-DATA:START */
const LOCAL_DATA = {
 "attribution": "Contains open map data © OpenStreetMap contributors, available under the Open Database License (ODbL) v1.0. https://www.openstreetmap.org/copyright",
 "made": "2026-09-20T18:00:00Z",
 "note": "A HAND-MADE FIXTURE of three systems, here so the picture can be built and judged before the real runs land. Every id beginning fix- is invented. It is not a real network and no real station is described by it.",
 "systems": {
  "fix-hartmoor": {
   "station": { "id": "fix-hartmoor", "name": "Hartmoor (fixture)", "kv": [132, 33] },
   "gsp": { "id": "fix-westcombe", "name": "Westcombe grid supply point (fixture)" },
   "incomers": [
    { "corridor": "fix-c1", "kv": 132, "km": 12.4, "circuits": 2, "from": { "id": "fix-westcombe", "name": "Westcombe GSP (fixture)" }, "guessed": false },
    { "corridor": "fix-c2", "kv": 132, "km": 18.9, "circuits": 1, "from": { "id": "fix-northhay", "name": "North Hay (fixture)" }, "guessed": false }
   ],
   "outgoers": [
    { "corridor": "fix-o1", "kv": 33, "km": 4.1, "circuits": 2, "to": { "id": "fix-millbank", "name": "Millbank primary (fixture)" }, "ends": "station", "loads": [], "guessed": false },
    { "corridor": "fix-o2", "kv": 33, "km": 6.6, "circuits": 1, "to": { "id": "fix-corran", "name": "Corran spur end (fixture)" }, "ends": "station", "loads": [], "guessed": false },
    { "corridor": "fix-o3", "kv": 33, "km": 2.2, "circuits": 1, "to": null, "ends": "load", "loads": [{ "id": "fix-l1", "kind": "works", "name": "Quarry works (fixture)" }], "guessed": false },
    { "corridor": "fix-o4", "kv": 33, "km": 9.8, "circuits": 1, "to": null, "ends": "edge-of-map", "loads": [], "guessed": false },
    { "corridor": "fix-o5", "kv": 33, "km": 5.0, "circuits": 1, "to": null, "ends": "load", "loads": [{ "id": "fix-l2", "kind": "primary", "name": null }], "guessed": true }
   ],
   "ties": [
    { "corridor": "fix-t1", "kv": 132, "km": 7.3, "circuits": 1, "to": { "id": "fix-eastlea", "name": "Eastlea (fixture)" }, "ends": "station", "loads": [], "guessed": false }
   ],
   "completeness": { "score": 0.62, "missing": ["one outgoer runs off the edge of the map", "one join is guessed", "no circuit count on three corridors"] }
  },
  "fix-millbank": {
   "station": { "id": "fix-millbank", "name": "Millbank primary (fixture)", "kv": [33, 11] },
   "gsp": { "id": "fix-westcombe", "name": "Westcombe grid supply point (fixture)" },
   "incomers": [
    { "corridor": "fix-o1", "kv": 33, "km": 4.1, "circuits": 2, "from": { "id": "fix-hartmoor", "name": "Hartmoor (fixture)" }, "guessed": false }
   ],
   "outgoers": [
    { "corridor": "fix-m1", "kv": 11, "km": 1.8, "circuits": 1, "to": null, "ends": "load", "loads": [{ "id": "fix-l3", "kind": "town", "name": "Millbank town (fixture)" }], "guessed": false },
    { "corridor": "fix-m2", "kv": 11, "km": 3.4, "circuits": 1, "to": null, "ends": "load", "loads": [{ "id": "fix-l4", "kind": "industrial", "name": "Cold store (fixture)" }], "guessed": false },
    { "corridor": "fix-m3", "kv": 11, "km": 2.9, "circuits": 1, "to": null, "ends": "edge-of-map", "loads": [], "guessed": true }
   ],
   "ties": [
    { "corridor": "fix-m4", "kv": 33, "km": 5.5, "circuits": 1, "to": { "id": "fix-eastlea", "name": "Eastlea (fixture)" }, "ends": "station", "loads": [], "guessed": false },
    { "corridor": "fix-m5", "kv": 33, "km": 6.1, "circuits": 1, "to": { "id": "fix-corran", "name": "Corran spur end (fixture)" }, "ends": "station", "loads": [], "guessed": false }
   ],
   "completeness": { "score": 0.78, "missing": ["one outgoer runs off the edge of the map", "the ring is closed on a guess"] }
  },
  "fix-corran": {
   "station": { "id": "fix-corran", "name": "Corran spur end (fixture)", "kv": [33, 11] },
   "gsp": { "id": "fix-westcombe", "name": "Westcombe grid supply point (fixture)" },
   "incomers": [
    { "corridor": "fix-o2", "kv": 33, "km": 6.6, "circuits": 1, "from": { "id": "fix-hartmoor", "name": "Hartmoor (fixture)" }, "guessed": false }
   ],
   "outgoers": [
    { "corridor": "fix-r1", "kv": 11, "km": 2.4, "circuits": 1, "to": null, "ends": "load", "loads": [{ "id": "fix-l5", "kind": "village", "name": "Corran village (fixture)" }], "guessed": false }
   ],
   "ties": [],
   "completeness": { "score": 0.9, "missing": ["nothing joins the far end: this is where the wires stop"] }
  }
 }
};
/* LOCAL-DATA:END */

const LOCAL_TERM = { station: '#eaf6ff', load: '#ffd27f', 'edge-of-map': '#7ff0ff' };
// EVERY STATION HAS A SYSTEM, even the ones nobody has written up yet. When the data carries a real
// one it is used; otherwise the picture is BUILT FROM THE GRAPH ITSELF - higher voltage in, lower
// voltage out, the same class to the side - and every line of it is marked guessed, because that is
// exactly what it is. A reader is never told "no data"; they are told what is known and how.
function localFromGraph(i){ const S = TUBE_DATA.stations, me = S[i];
  const here = me[3];
  const inc = [], out = [], ties = [];
  for (const [b, li] of TUBE_ADJ[i]) { const lk = TUBE_DATA.links132[li], o = S[b];
    const leg = { corridor: 'g' + li, kv: Math.max(here, o[3]), km: lk[2], circuits: lk[3] || 1,
      ends: 'station', loads: [], guessed: true };
    if (o[3] > here) inc.push(Object.assign({ from: { id: o[0], name: o[5] || 'unnamed station' } }, leg));
    else if (o[3] < here) out.push(Object.assign({ to: { id: o[0], name: o[5] || 'unnamed station' } }, leg));
    else ties.push(Object.assign({ to: { id: o[0], name: o[5] || 'unnamed station' } }, leg)); }
  // WITH NOTHING ABOVE IT, the first tie is read as the incomer: a station fed at its own class is
  // still fed from somewhere, and drawing no supply at all would say something untrue.
  if (!inc.length && ties.length) { const t2 = ties.shift();
    inc.push({ corridor: t2.corridor, kv: t2.kv, km: t2.km, circuits: t2.circuits,
      from: { id: t2.to.id, name: t2.to.name }, guessed: true }); }
  const missing = ['every join here is read off the map, not from a register'];
  if (!out.length) missing.push('no outgoers are known: the load side of this station is not in the data');
  if (!inc.length) missing.push('no supply is known: nothing higher than ' + here + ' kV reaches this station in the data');
  return { station: { id: me[0], name: me[5] || 'unnamed station', kv: [here] },
    gsp: null, incomers: inc, outgoers: out, ties,
    completeness: { score: 0.25, missing }, derived: true }; }
function localSystem(key){ const k = String(key || '').trim();
  const sys = LOCAL_DATA.systems || {};
  if (sys[k]) return sys[k];
  const lower = k.toLowerCase();
  for (const id in sys) if (sys[id].station && String(sys[id].station.name || '').toLowerCase() === lower) return sys[id];
  for (const id in sys) if (sys[id].station && String(sys[id].station.name || '').toLowerCase().indexOf(lower) === 0) return sys[id];
  const i = tubeFind(k);
  if (i >= 0) { const byId = sys[TUBE_DATA.stations[i][0]]; return byId || localFromGraph(i); }
  return null; }
// THE COMPLETENESS LINE, IN PLAIN WORDS AND COUNTED, NOT ASSERTED. The numbers are read off the very
// legs that were drawn, so the sentence can never drift away from the picture above it.
function localWords(sys){ const o = sys.outgoers || [], all = o.concat(sys.incomers || [], sys.ties || []);
  const edge = o.filter(L => L.ends === 'edge-of-map').length;
  const guessed = all.filter(L => L.guessed).length;
  const bits = [];
  if (o.length) bits.push(edge + ' of ' + o.length + ' outgoers end at the edge of the map');
  else bits.push('no outgoers are drawn');
  bits.push(guessed === 1 ? '1 join is guessed' : guessed + ' joins are guessed');
  const miss = (sys.completeness && sys.completeness.missing) || [];
  return bits.join('; ') + (miss.length ? '. ' + miss.join('; ') + '.' : '.'); }
// A LINE CUT AT THE FRONT. The pulse is the engine's own front travelling the corridor, so a length of
// the corridor is lit and the rest is not; this returns the lit length of an octilinear route.
function localCut(pts, f){ if (f >= 1) return pts.slice();
  if (f <= 0) return [];
  let total = 0; for (let i = 1; i < pts.length; i++) total += Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]);
  let want = total * f, out = [pts[0]];
  for (let i = 1; i < pts.length; i++) { const d = Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]);
    if (want >= d) { out.push(pts[i]); want -= d; continue; }
    const u = d > 1e-9 ? want / d : 0;
    out.push([pts[i - 1][0] + (pts[i][0] - pts[i - 1][0]) * u, pts[i - 1][1] + (pts[i][1] - pts[i - 1][1]) * u]);
    return out; }
  return out; }
function localTrim(ctx, s, maxW){ if (ctx.measureText(s).width <= maxW) return s;
  let t2 = s; while (t2.length > 3 && ctx.measureText(t2 + '…').width > maxW) t2 = t2.slice(0, -1);
  return t2 + '…'; }
function drawLocalSystem(ctx, dpr, band, t){
  const sys = TUBE.local; if (!sys) return;
  ctx.setTransform(1, 0, 0, 1, 0, 0);
  const W = innerWidth * dpr, top = band.top * dpr, foot = tubeAttribution(ctx, dpr, band) * dpr;
  // THE COMPLETENESS LINE IS MEASURED BEFORE ANYTHING IS PLACED, and the room it needs is taken out
  // of the picture rather than written over the top of it. A sentence about what is missing, laid
  // across the names of the things that ARE there, loses both.
  const cfs = Math.max(TUBE_TEXT_FLOOR_PX * dpr, Math.max(TUBE_TEXT_FLOOR_PX, innerWidth < 520 ? 9.5 : 11) * dpr - dpr);
  ctx.font = '500 ' + cfs + 'px ui-monospace,Menlo,Consolas,monospace';
  const cLines = []; { let c2 = '';
    for (const w of localWords(sys).split(' ')) { const t3 = c2 ? c2 + ' ' + w : w;
      if (ctx.measureText(t3).width > W - 24 * dpr && c2) { cLines.push(c2); c2 = w; } else c2 = t3; }
    if (c2) cLines.push(c2); }
  while (cLines.length > 3) cLines.pop();
  const bot = foot - (18 + 14 * cLines.length) * dpr;
  const fs = Math.max(TUBE_TEXT_FLOOR_PX, innerWidth < 520 ? 9.5 : 11) * dpr;
  ctx.textBaseline = 'middle'; ctx.textAlign = 'center'; ctx.lineCap = 'round'; ctx.lineJoin = 'round';
  const inc = sys.incomers || [], out = sys.outgoers || [], ties = sys.ties || [];
  const yIn = top + 44 * dpr, yMid = top + (bot - top) * 0.46, yOut = bot - 46 * dpr;
  const cx = W / 2;
  const slot = (n, k) => W * (k + 1) / (n + 1);
  // THE PULSE: one front, from the grid supply point at the top, through the station, out to the
  // loads. It is the engine's own front and it advances on the shell's frames, not a loop of ours.
  let u = 1;
  if (TUBE.phase === 'localpulse') { u = Math.min(1, (performance.now() - TUBE.t0) / 1900);
    if (u >= 1) TUBE.phase = 'local'; try { dirty = true; } catch (_) {} }
  const fIn = Math.max(0, Math.min(1, u / 0.38));
  const fSt = u >= 0.38 ? Math.min(1, (u - 0.38) / 0.10) : 0;
  const fOut = u >= 0.48 ? Math.min(1, (u - 0.48) / 0.46) : 0;
  TUBE.hitLocal = [];
  const stW = Math.min(W * 0.52, 240 * dpr), stH = 42 * dpr;
  const port = [cx, yMid];
  const leg = (pts, L, lit) => {
    const w = 2.2 * dpr * (0.8 + 0.35 * Math.min(4, L.circuits || 1));
    ctx.beginPath(); ctx.moveTo(pts[0][0], pts[0][1]);
    for (let i = 1; i < pts.length; i++) ctx.lineTo(pts[i][0], pts[i][1]);
    // ANYTHING GUESSED IS DASHED. A solid line on this picture is a claim; a dashed one is a question.
    ctx.setLineDash(L.guessed ? [6 * dpr, 5 * dpr] : []);
    ctx.lineWidth = w; ctx.strokeStyle = TUBE_DARK; ctx.globalAlpha = 1; ctx.stroke();
    const cut = localCut(pts, lit);
    if (cut.length > 1) { ctx.beginPath(); ctx.moveTo(cut[0][0], cut[0][1]);
      for (let i = 1; i < cut.length; i++) ctx.lineTo(cut[i][0], cut[i][1]);
      ctx.lineWidth = w; ctx.strokeStyle = tubeInk(L.kv); ctx.stroke(); }
    ctx.setLineDash([]); };
  const say = (s, x, y, col, maxW) => { ctx.font = '600 ' + fs + 'px ui-monospace,Menlo,Consolas,monospace';
    ctx.fillStyle = col || '#9fb3c8'; ctx.fillText(localTrim(ctx, s, maxW || W / 3.2), x, y); };
  // THE GRID SUPPLY POINT, named across the top, because every incomer on this page comes from that
  // side of the system and a reader must be told which side that is.
  ctx.font = '600 ' + fs + 'px ui-monospace,Menlo,Consolas,monospace';
  ctx.fillStyle = '#7f8899';
  ctx.fillText(sys.gsp ? ('from the grid supply point · ' + sys.gsp.name)
                       : 'from the higher voltage side', cx, top + 14 * dpr);
  // 1. THE INCOMERS, entering from the top.
  inc.forEach((L, k) => { const x = slot(inc.length, k), a = [x, yIn], b = [cx + (x > cx ? 1 : x < cx ? -1 : 0) * stW * 0.3, yMid - stH / 2];
    leg(tubeRoute(a, b), L, fIn);
    ctx.beginPath(); ctx.arc(x, yIn, 5.5 * dpr, 0, 6.2832);
    ctx.fillStyle = fIn > 0.02 ? tubeInk(L.kv) : TUBE_DARK; ctx.fill();
    ctx.lineWidth = 1.4 * dpr; ctx.strokeStyle = TUBE_GROUND; ctx.stroke();
    say((L.from && L.from.name) || 'unnamed station', x, yIn - 15 * dpr, '#eaf6ff', (W / (inc.length + 1)) - 14 * dpr);
    say(L.kv + ' kV · ' + (L.km != null ? L.km.toFixed(1) + ' km · ' : '')
      + ((L.circuits || 1) > 1 ? L.circuits + ' circuits' : '1 circuit'),
      x, yIn + 16 * dpr, '#7f8899', (W / (inc.length + 1)) - 14 * dpr);
    if (L.from && L.from.id) TUBE.hitLocal.push([x / dpr, yIn / dpr, L.from.id]); });
  // 2. THE TIES, to the side, because a tie is neither supply nor load: it is the other way round.
  ties.forEach((L, k) => { const right = k % 2 === 0;
    const x = right ? W - 26 * dpr : 26 * dpr, y = yMid + (Math.floor(k / 2) * 38 + 30) * dpr;
    leg(tubeRoute([x, y], [cx + (right ? stW / 2 : -stW / 2), yMid]), L, fSt);
    ctx.beginPath(); ctx.arc(x, y, 5 * dpr, 0, 6.2832); ctx.fillStyle = tubeInk(L.kv); ctx.fill();
    ctx.textAlign = right ? 'right' : 'left';
    say('tie · ' + ((L.to && L.to.name) || 'unnamed') + ' · ' + L.kv + ' kV',
      right ? x - 10 * dpr : x + 10 * dpr, y - 14 * dpr, '#9fb3c8', W * 0.42);
    ctx.textAlign = 'center';
    if (L.to && L.to.id) TUBE.hitLocal.push([x / dpr, y / dpr, L.to.id]); });
  // 3. THE OUTGOERS, leaving downward to their load points.
  out.forEach((L, k) => { const x = slot(out.length, k), b = [x, yOut];
    const a = [cx + (x > cx ? 1 : x < cx ? -1 : 0) * stW * 0.3, yMid + stH / 2];
    leg(tubeRoute(a, b), L, fOut);
    const kind = L.ends || 'station', col = LOCAL_TERM[kind] || '#eaf6ff';
    const on = fOut > 0.98;
    // THE TERMINUS SAYS WHAT KIND OF END IT IS: a filled mark is another station, a small square is a
    // load point, and an open mark with the wire running past it is the EDGE OF WHAT WE KNOW.
    if (kind === 'edge-of-map') { ctx.beginPath(); ctx.arc(x, yOut, 6 * dpr, 0, 6.2832);
      ctx.setLineDash([3 * dpr, 3 * dpr]); ctx.lineWidth = 1.6 * dpr; ctx.strokeStyle = col; ctx.stroke(); ctx.setLineDash([]); }
    else if (kind === 'load') { ctx.fillStyle = on ? col : TUBE_DARK;
      ctx.fillRect(x - 5 * dpr, yOut - 5 * dpr, 10 * dpr, 10 * dpr);
      ctx.lineWidth = 1.3 * dpr; ctx.strokeStyle = col; ctx.strokeRect(x - 5 * dpr, yOut - 5 * dpr, 10 * dpr, 10 * dpr); }
    else { ctx.beginPath(); ctx.arc(x, yOut, 6 * dpr, 0, 6.2832); ctx.fillStyle = on ? col : TUBE_DARK; ctx.fill();
      ctx.lineWidth = 1.4 * dpr; ctx.strokeStyle = col; ctx.stroke(); }
    const wide = (W / (out.length + 1)) - 10 * dpr;
    const nm = kind === 'edge-of-map' ? 'edge of the map'
      : (L.to && L.to.name) || (L.loads && L.loads[0] && (L.loads[0].name || L.loads[0].kind)) || 'load point';
    say(nm, x, yOut + 17 * dpr, col, wide);
    say(L.kv + ' kV · ' + (L.km != null ? L.km.toFixed(1) + ' km' : 'length unknown')
      + (L.guessed ? ' · guessed' : ''), x, yOut + 30 * dpr, '#7f8899', wide);
    if (L.to && L.to.id) TUBE.hitLocal.push([x / dpr, yOut / dpr, L.to.id]); });
  // 4. THE STATION ITSELF, in the middle, where the reader's eye starts.
  ctx.beginPath();
  const r2 = 8 * dpr, x0 = cx - stW / 2, y0 = yMid - stH / 2;
  ctx.moveTo(x0 + r2, y0); ctx.lineTo(x0 + stW - r2, y0); ctx.quadraticCurveTo(x0 + stW, y0, x0 + stW, y0 + r2);
  ctx.lineTo(x0 + stW, y0 + stH - r2); ctx.quadraticCurveTo(x0 + stW, y0 + stH, x0 + stW - r2, y0 + stH);
  ctx.lineTo(x0 + r2, y0 + stH); ctx.quadraticCurveTo(x0, y0 + stH, x0, y0 + stH - r2);
  ctx.lineTo(x0, y0 + r2); ctx.quadraticCurveTo(x0, y0, x0 + r2, y0); ctx.closePath();
  ctx.fillStyle = fSt > 0.5 ? '#0d1a26' : '#0a1018'; ctx.fill();
  ctx.lineWidth = 2 * dpr; ctx.strokeStyle = fSt > 0.5 ? TUBE_CAGE : '#2a3444'; ctx.stroke();
  const kvs = (sys.station.kv || []).filter(v => v != null);
  say(sys.station.name || 'unnamed station', cx, yMid - 7 * dpr, '#eaf6ff', stW - 16 * dpr);
  say(kvs.length ? kvs.join('/') + ' kV' : 'voltage not in the data', cx, yMid + 9 * dpr, '#9fb3c8', stW - 16 * dpr);
  TUBE.hitLocal.push([cx / dpr, yMid / dpr, sys.station.id]);
  // 5. HOW MUCH OF THE SYSTEM IS ACTUALLY ON THIS PAGE, in plain words, above the provenance.
  ctx.font = '500 ' + cfs + 'px ui-monospace,Menlo,Consolas,monospace';
  ctx.fillStyle = '#ffb454'; ctx.textAlign = 'left';
  cLines.forEach((ln, k) => ctx.fillText(ln, 12 * dpr, foot - (cLines.length - k) * 14 * dpr - 2 * dpr));
  ctx.textAlign = 'center'; }
function tubeLocal(sys){ TUBE.on = true; TUBE.view = 'local'; TUBE.local = sys; TUBE.lattice = null;
  TUBE.lit = null; TUBE.litLinks = null; TUBE.hull = null; TUBE.hit = [];
  TUBE.phase = 'localpulse'; TUBE.t0 = performance.now();
  tubeLayer(); try { document.body.classList.add('tube-on'); } catch (_) {}
  try { dirty = true; } catch (_) {} }
function fireLocal(i){ i = i || {};
  const key = i.station === undefined ? '' : String(i.station);
  if (!key.trim()) throw new Error('name a station: fire local {station:"Hartmoor (fixture)"}. '
    + 'Written-up systems here: ' + Object.keys(LOCAL_DATA.systems).join(', '));
  if (typeof endIsolate === 'function') { try { endIsolate(); } catch (_) {} }
  const sys = localSystem(key);
  if (!sys) throw new Error('no station of that name is in this data. Nearest names to try: '
    + tubeNearest(key).join(', '));
  tubeLocal(sys);
  const o = sys.outgoers || [];
  return { numbers: { incomers: (sys.incomers || []).length, outgoers: o.length, ties: (sys.ties || []).length,
      ends_at_the_edge_of_the_map: o.filter(L => L.ends === 'edge-of-map').length },
    said: sys.station.name + ': ' + localWords(sys),
    how: sys.derived
      ? 'built here from the open map graph - higher voltage in, lower voltage out, same class to the side - so every join is drawn dashed and marked guessed'
      : 'from the local system data; ' + LOCAL_DATA.attribution }; }
const LOCAL_INPUTS = [{ key: 'station', label: 'station', kind: 'text' }];
// ===== THE LOCAL SYSTEM: END ====================================================================

// ---- the typed command ------------------------------------------------------------------------
const TUBE_INPUTS = [
  { key: 'view', label: 'view', kind: 'choice', choices: [['nation', 'the whole network'], ['region', 'a region'], ['station', 'one station and its cage']] },
  { key: 'place', label: 'place', kind: 'text' },
  { key: 'hops', label: 'hops along the network', unit: 'stops', kind: 'number', min: 1, max: 3, step: 1 },
  { key: 'km', label: 'how far a region reaches', unit: 'km', kind: 'number', min: 5, max: 120, step: 5 },
  { key: 'kv', label: 'voltage class', kind: 'choice', choices: [[0, 'all']].concat(TUBE_CLASSES_KV.map(v => [v, v + ' kV'])) }
];
function fireGrid(i){ i = i || {};
  const hops = Math.max(1, Math.min(3, i.hops === undefined ? 2 : Number(i.hops) || 2));
  const kv = i.kv === undefined || Number(i.kv) === 0 ? 0 : tubeClassOf(Number(i.kv));
  if (i.kv !== undefined && Number(i.kv) !== 0 && kv === null)
    throw new Error('that is not one of the voltage classes this grid is drawn in: ' + TUBE_CLASSES_KV.join(', ') + ' kV');
  if (typeof endIsolate === 'function') { try { endIsolate(); } catch (_) {} }
  const view = i.view === 'region' ? 'region' : (i.place ? 'station' : (i.view || 'nation'));
  // A REGION IS ASKED FOR IN MILES AND IS ANSWERED IN MILES. Asked for without a place it used to fall
  // silently back to the nation, which is a different answer wearing the name of the one requested.
  if (view === 'region') {
    const at = tubeFind(i.place);
    if (at < 0) throw new Error('a region is a circle drawn round a place, so it needs one: '
      + 'fire grid {view:"region", place:"..."}. ' + (i.place
        ? 'No station of that name is in this data. Nearest names to try: ' + tubeNearest(i.place).join(', ')
        : 'No place was given.'));
    const km = Math.max(5, Math.min(120, Number(i.km) || 45));
    const r = tubeRegionSet(at, km); r.view = 'region';
    TUBE.hops = hops; TUBE.kv = kv;
    tubeCage(at, hops, kv, r);
    return { numbers: { stations_in_the_region: r.set.size, radius_km: km, links: r.links.size },
      said: 'the region within ' + km + ' km of ' + tubeName(at) + ': ' + r.set.size
        + ' stations, laid out as a tube map',
      how: 'a circle measured on the ground, not hops along the network; stations from open map data' }; }
  if (view === 'station' || i.place) {
    const at = tubeFind(i.place);
    if (at < 0) throw new Error('no station of that name is in this data. Nearest names to try: '
      + tubeNearest(i.place).join(', '));
    TUBE.hops = hops; TUBE.kv = kv;
    const n = tubeCage(at, hops, kv);
    return { numbers: { stations_in_the_cage: n, hops, links: TUBE.litLinks.size },
      said: 'the cage is around ' + tubeName(at) + ': ' + n + ' stations within ' + hops + ' hops, laid out as a tube map',
      how: 'hops counted along the network from open map data; the outline is the convex hull of the caged set' }; }
  tubeNation(); TUBE.hops = hops; TUBE.kv = kv;
  return { numbers: { stations: TUBE_DATA.stations.length, links: TUBE_DATA.links132.length },
    said: 'the whole network: tap a station, or type a place, to throw the cage around it',
    how: 'stations and links from open map data, ' + TUBE_DATA.attribution }; }
if (typeof window !== 'undefined') {
  window.KUIPER_TUBE = { data: TUBE_DATA, state: TUBE, fire: fireGrid, cage: tubeCage, card: tubeCard,
                         nation: tubeNation, find: tubeFind, bridges: TUBE_BRIDGES, drawMs: () => TUBE.drawMs,
                         local: LOCAL_DATA, fireLocal, system: localSystem, words: localWords };
  // THE REGISTRY IS DEFINED FURTHER DOWN THIS SAME FILE. At this line window.FIRE does not exist yet,
  // so a plain register() was thrown away in silence and a typed `fire grid` answered "no command
  // called grid", while the picture itself worked perfectly when driven from the console. The commands
  // are OFFERED AGAIN, on a short beat, until the registry is there to take them.
  const tubeOffer = () => { try { if (window.FIRE && window.FIRE.register) {
      window.FIRE.register('grid', 'THE GRID', fireGrid, TUBE_INPUTS);
      window.FIRE.register('local', 'THE LOCAL SYSTEM', fireLocal, LOCAL_INPUTS);
      return true; } } catch (_) {} return false; };
  if (!tubeOffer()) { let n = 0; const iv = setInterval(() => { if (tubeOffer() || ++n > 400) clearInterval(iv); }, 20); }
  // THE SHELL'S OWN FRAME, not a loop of this file's: the same hook the shapes layer uses.
  try { if (window.__wafer && window.__wafer.onDraw) window.__wafer.onDraw.add(function(){ try { drawTubeMap(); } catch (_) {} }); } catch (_) {}