GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Maps, GIS and field navigation / globalgrid2050 / energy-transition-simulator/202609280259/mod

LiDAR Stream and 3 more files

A JavaScript file in GlobalGrid2050 that maps LiDAR terrain, using EPSG:27700 and OSTN15. It saves day (`saveDay`), sets open (`setOpen`) and shows text (`showText`).

669 lines of JavaScript and HTML from globalgrid2050, in 4 files. Topic: Maps, GIS and field navigation. Section 489 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. LiDAR Stream geodesy · globalgrid2050 / energy-transition-simulator/202609280259/mod/lidar-stream.js lines 1–310
  2. Grid Engine — Route Obstacles Page render · globalgrid2050 / grid_engine/202609060213-route-obstacles/index.html lines 1–254
  3. Whole Site Route View render · globalgrid2050 / kuiper-grid/drawing/whole-site-route-view.js lines 1–48
  4. Whole Site Routes transform · globalgrid2050 / kuiper-grid/drawing/whole-site-routes.js lines 1–57

LiDAR Stream

A JavaScript file in GlobalGrid2050 that maps LiDAR terrain, using EPSG:27700 and OSTN15. It saves day (`saveDay`), sets open (`setOpen`) and shows text (`showText`).

geodesyglobalgrid2050 / energy-transition-simulator/202609280259/mod/lidar-stream.js · lines 1–310 of 310 · version 2026-09-28 02:59 · Not reached from any entry point (candidate for review) · pattern fetchProduct (shared by 2 files)

What it does
It maps LiDAR terrain. Defines 27 functions or classes, including PF, wait, today, dayUsed, saveDay. Side effects: changes the web page (DOM); uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage site_feasibility (path word 'lidar'): substation-to-site feasibility (terrain, LiDAR and connection evidence before design), a journey named in Ventus Ltd's brief. Domain terms in the code: LiDAR terrain.
Inputs & outputs
In: browser storage (getItem). Out: browser storage (setItem). Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326.
What it achieves
Rule R5 (the site tile) in the browser. It responds to click, resize and keydown events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · energy-transition-simulator/202609280259/mod · script
VEDIC
HEIGHT (GG2050-VEDIC-000011): Solar Design Studio / LiDAR · Mathematics / Raster sampling. bng_easting_m, bng_northing_m → height_receipt_or_null
Uses
none found
Used by
none found
Produces
PF, wait, today, dayUsed, saveDay, panel, setOpen, summary, show, showText, frame, hAt
Defines here
PF, wait, today, dayUsed, saveDay, panel, setOpen, summary, show, showText, frame, hAt, exag, elevNow, terrainAt, demAt, heightAt, probe, draw, X, satMode, sync, captions, place, fetchProduct, step, arrive
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 energy-transition-simulator/202609280259/mod/lidar-stream.js:1-310 · blob 6c7adbf2dfaa00df474d431135288dbab6307dd8 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, storage · domain stage: site_feasibility · users: IPP_developer, landowner_planner · canonical: unreached_review
// lidar-stream: rule R5 (the site tile) in the browser. On ARRIVAL (a find or go ends, or Walk, Drone or Build here
// starts, or the "Stream ground" button), the 2,048 m lattice tile under the view centre is streamed from the
// Environment Agency WCS: the DTM first, the DSM at least 40 s later. Each is decoded in memory, turned into a
// wireframe and a receipt; the heights stay in memory only (for heightAt) and are never stored. Moving (walk, fly, pan, zoom) never asks the service.
// Ground: an 8 m wire grid of measured DTM heights, each node drawn at its own DTM height (ODN), not one anchor height. Above ground: DSM minus DTM over 1 m, as wire posts (derived).
// Coordinates: every node is a British National Grid cell centre (e0 + k + 0.5) turned into WGS84 by the
// overlay's one conversion (place-frame fromBng: OSTN15 where loaded, Helmert otherwise, and the label says which).
// Outside coverage the module says "no measured ground here" and draws nothing (never 0 m).
(function () {
  const HERE = document.currentScript ? document.currentScript.src : location.href;
  const STEP = 8, ABOVE_M = 1, DAY_KEY = 'lidarStream.day';
  const PF = () => window.__pf && window.__pf.PF;
  let R5 = null, pacer = null, fetchImpl = null, on = true, btn = null, box = null, gapOverride = null;
  const tiles = new Map(); // tile key -> { tile, dtm: {..}|null, dsm: {..}|null, blocks: [], status }
  let current = null, timer = null, arriving = false;
  function wait(f) { if (window.SIM && PF()) f(); else setTimeout(() => wait(f), 200); }
  const today = () => new Date().toISOString().slice(0, 10);
  function dayUsed() { try { const d = JSON.parse(localStorage.getItem(DAY_KEY) || '{}'); return d.date === today() ? d.used | 0 : 0; } catch (e) { return 0; } }
  function saveDay() { try { localStorage.setItem(DAY_KEY, JSON.stringify({ date: today(), used: pacer.state.used })); } catch (e) { /* private window */ } }

  // The receipt collapses to ONE dim line (tile + receipt sha8); a click on it opens the full receipt, licence and
  // attribution above it, a second click closes it. The line is placed clear of every visible caption (place()).
  let line = null, full = null, open = false;
  function panel() {
    if (box) return full;
    box = document.createElement('div'); box.id = 'lidar-stream-receipt';
    box.style.cssText = 'position:fixed;left:10px;bottom:8px;z-index:5;display:flex;flex-direction:column-reverse;align-items:flex-start;gap:4px;max-width:calc(100vw - 120px)';
    line = document.createElement('div'); line.id = 'lidar-stream-line'; line.title = 'Measured ground: click for the full receipt, licence and attribution';
    line.style.cssText = 'font:11px/15px system-ui,sans-serif;color:var(--dim,#8a9a9a);text-shadow:0 0 3px #000,0 0 1px #000;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:100%;cursor:pointer';
    full = document.createElement('div'); full.id = 'lidar-stream-full'; full.hidden = true;
    full.style.cssText = 'max-width:min(560px,calc(100vw - 32px));max-height:50vh;overflow:auto;font:11px/1.35 monospace;color:#dfe;background:rgba(0,0,0,.8);padding:6px 8px;border-radius:6px;white-space:pre-wrap;word-break:break-all';
    line.addEventListener('click', () => setOpen(!open));
    box.append(line, full); document.body.appendChild(box); return full;
  }
  function setOpen(v) { panel(); open = !!v; full.hidden = !open; place(); }
  function summary(t) {
    if (!t) return 'measured ground: arrive somewhere to stream its tile';
    const at = `tile ${t.tile.e0}/${t.tile.n0}`, d = t.dtm;
    if (d && d.sha) return `measured ground: EA LiDAR 1 m, ${at}, receipt ${d.sha.slice(0, 8)}${t.dsm && t.dsm.sha ? '' : t.status && t.status !== 'complete' ? ` (${t.status})` : ''}`;
    return `measured ground: ${at}, ${t.status || (d && d.none) || 'waiting'}`;
  }
  function show() { showText(); place(); }
  function showText() {
    const t = current && tiles.get(current), P = PF();
    panel(); line.textContent = summary(t);
    if (!t) { full.textContent = 'Measured ground (R5): arrive somewhere to stream its 2,048 m tile.'; return; }
    const eng = P && P.engine ? P.engine : (t.engine || '');
    const L = t.arrived ? [t.arrived] : [];
    L.push(`Measured ground, tile ${t.tile.e0} E ${t.tile.n0} N (2,048 m, EPSG:27700): ${t.status}`);
    for (const k of ['dtm', 'dsm']) {
      const r = t[k];
      if (!r) continue;
      if (r.none) { L.push(r.failed ? r.none : `${k.toUpperCase()}: no measured ground here (${r.none})`); continue; }
      if (r.pending) { L.push(`${k.toUpperCase()}: ${r.pending}`); continue; }
      L.push(`${k.toUpperCase()} receipt ${r.sha.slice(0, 12)}: ${r.src.product}, ${r.src.release}; survey year not read yet, so these heights count as pre-construction ground (R5 rule 9); ` +
        `box E ${r.box.e0}-${r.box.e1} N ${r.box.n0}-${r.box.n1}; fetched ${r.at}; ${(r.valid * 100).toFixed(1)}% cells measured; sha256(cells) ${r.sha}`);
    }
    if (t.objects != null) L.push(`Above ground (DSM - DTM > ${ABOVE_M} m, derived): ${t.objects} posts on the ${STEP} m grid.`);
    L.push(`Placed by ${t.engine || eng || 'place-frame'}. ${R5 ? R5.LICENCE : ''} Source: Environment Agency.`);
    panel().textContent = L.join('\n');
  }

  // Tile -> local wire frame: exact at three control nodes, affine between them (OSTN15 varies by mm over 2 km).
  function frame(t) {
    const P = PF(), g = P.fromBng(t.e0 + 1024, t.n0 + 1024), anchor = P.placeKey(g.lat, g.lon);
    const o = P.bngToWire(anchor, t.e0, t.n0), ex = P.bngToWire(anchor, t.e0 + 2048, t.n0), ny = P.bngToWire(anchor, t.e0, t.n0 + 2048);
    const ax = (ex.x - o.x) / 2048, ay = (ex.y - o.y) / 2048, bx = (ny.x - o.x) / 2048, by = (ny.y - o.y) / 2048;
    return { anchor, engine: g.engine || '', xy: (e, n) => { const de = e - t.e0, dn = n - t.n0; return [o.x + ax * de + bx * dn, o.y + ay * de + by * dn]; } };
  }
  // Height at cell (i, j) counted from the tile's SW corner, or NaN (unmeasured or outside the box).
  function hAt(r, i, j) {
    if (!r || r.none || r.pending) return NaN;
    const c = r.tile.e0 + i - r.geo.west, rr = r.geo.north - (r.tile.n0 + j) - 1;
    if (c < 0 || rr < 0 || c >= r.geo.width || rr >= r.geo.height) return NaN;
    const k = rr * r.geo.width + c; return r.mask[k] ? r.geo.data[k] : NaN;
  }
  // Terrain exaggeration: MapLibre 4.7 returns queryTerrainElevation multiplied by the exaggeration and relative to the
  // centre's elevation (transform.elevation, also exaggerated). terrainAt is the RENDER lift in that same frame, so it
  // must stay exactly what perf.js adds (the per-node cancellation H - gz + gz = H needs the same number on both sides).
  // demAt is the map DEM in true metres (ODN), divided by the exaggeration like coords-readout.js, for DEM vs DTM.
  const exag = () => { const m = window.SIM.map, t = m.getTerrain && m.getTerrain(); return (t && t.exaggeration) || 1; };
  const elevNow = () => (window.SIM.map.transform && window.SIM.map.transform.elevation) || 0;
  function terrainAt(lon, lat) { const m = window.SIM.map; return (m.queryTerrainElevation && m.queryTerrainElevation([lon, lat])) || 0; }
  function demAt(lon, lat) {
    const m = window.SIM.map; if (!(m.getTerrain && m.getTerrain() && m.queryTerrainElevation)) return null;
    const v = m.queryTerrainElevation([lon, lat]); return v == null ? null : (v + (m.transform.elevation || 0)) / exag();
  }
  // The measured DTM height (m, ODN) of the 1 m cell holding (e, n), with the receipt it came from; null outside.
  function heightAt(e, n) {
    for (const t of tiles.values()) {
      const r = t.dtm; if (!r || r.none || r.pending) continue;
      const i = Math.floor(e - t.tile.e0), j = Math.floor(n - t.tile.n0);
      if (i < 0 || j < 0 || i >= 2048 || j >= 2048) continue;
      const h = hAt(r, i, j);
      return Number.isFinite(h) ? { h, receipt: r.sha.slice(0, 12), prov: 'measured', cell: [t.tile.e0 + i, t.tile.n0 + j] } : { h: null, receipt: r.sha.slice(0, 12), why: 'cell not measured' };
    }
    return { h: null, why: 'no streamed tile here' };
  }
  // Datum probe: for up to n wire nodes, the height the GPU draws (buffer z + the overlay's live anchor lift, in
  // metres at the node) minus heightAt at the node. Also the map DEM at the node minus heightAt (for information).
  function probe(n = 200) {
    const P = PF(), out = [];
    for (const [key, t] of tiles) {
      if (!t.H) continue;
      const blk = (t.blks || []).find(b => b.kind === 'ground'); if (!blk) continue;
      const idx = []; for (let k = 0; k < t.N * t.N; k++) if (t.seg[k] >= 0) idx.push(k);
      const gzNow = terrainAt(t.anchor.lon, t.anchor.lat), stride = Math.max(1, Math.floor(idx.length / n));
      for (let q = 0; q < idx.length && out.length < n; q += stride) {
        const k = idx[q], a = k % t.N, b = (k - a) / t.N, e = t.tile.e0 + a * STEP + STEP / 2 + 0.5, nn = t.tile.n0 + b * STEP + STEP / 2 + 0.5;
        const g = P.fromBng(e, nn), mz = blk.buf[6 * t.seg[k] + 2] + P.toMercator(t.anchor.lat, t.anchor.lon, gzNow + elevNow()).z; // back to ODN
        const drawn = mz / P.toMercator(g.lat, g.lon, 1).z, truth = heightAt(e, nn);
        out.push({ e, n: nn, drawn, truth: truth.h, D: drawn - truth.h, demD: demAt(g.lon, g.lat) == null ? null : demAt(g.lon, g.lat) - truth.h, receipt: truth.receipt });
      }
    }
    const D = out.map(o => Math.abs(o.D)), exaggeration = exag(), dm = out.filter(o => o.demD != null), M = dm.map(o => Math.abs(o.demD));
    return { nodes: out.length, maxAbsD: Math.max(...D), meanD: out.reduce((s, o) => s + o.D, 0) / (out.length || 1),
      demNodes: dm.length, maxAbsDemD: M.length ? Math.max(...M) : null, meanDemD: dm.length ? dm.reduce((s, o) => s + o.demD, 0) / dm.length : null, receipt: out[0] && out[0].receipt, exaggeration, sample: out.slice(0, 3) };
  }
  function draw(key) {
    const t = tiles.get(key), S = window.SIM, P = PF();
    S.removeWhere(b => b.lidarStream === key); if (t) t.blks = [];
    if (!t || !t.dtm || t.dtm.none || t.dtm.pending) return;
    const f = frame(t.tile); t.engine = f.engine;
    const N = 2048 / STEP;
    // HEIGHT DATUM: the overlay lifts every block by the map terrain at its anchor (gz). Each vertex is written as
    // (its own DTM height - gz), so on screen every node sits at its own measured height (ODN), never at one anchor
    // height per block. gz is re-read when the map goes idle and the block is rebuilt if it moved (terrain loading).
    // FRAME (r3): MapLibre 4.7 custom layers draw in a frame whose zero is the centre's elevation (transform.elevation,
    // E), and gz is relative to E too. So a vertex is (H - gz - E): drawn = H - gz - E + gz = H - E, the node at its
    // own measured height in the map's frame. Without E the wire floated E metres up once E was set (Walk: a band overhead).
    const gz = terrainAt(f.anchor.lon, f.anchor.lat), E = elevNow(), base = gz + E;
    const H = new Float32Array(N * N), seg = new Int32Array(N * N).fill(-1);
    for (let b = 0; b < N; b++) for (let a = 0; a < N; a++) H[b * N + a] = hAt(t.dtm, a * STEP + STEP / 2, b * STEP + STEP / 2);
    const X = (a, b) => { const c = STEP / 2, p = f.xy(t.tile.e0 + a * STEP + c + 0.5, t.tile.n0 + b * STEP + c + 0.5); return [p[0], p[1], H[b * N + a] - base]; };
    const L = [];
    for (let b = 0; b < N; b++) for (let a = 0; a < N; a++) {
      if (!Number.isFinite(H[b * N + a])) continue; const p = X(a, b), k0 = L.length;
      if (a + 1 < N && Number.isFinite(H[b * N + a + 1])) { const q = X(a + 1, b); L.push([p[0], p[1], p[2], q[0], q[1], q[2]]); }
      if (b + 1 < N && Number.isFinite(H[(b + 1) * N + a])) { const q = X(a, b + 1); L.push([p[0], p[1], p[2], q[0], q[1], q[2]]); }
      if (L.length > k0) seg[b * N + a] = k0;
    }
    t.gz = gz; t.E = E; t.H = H; t.seg = seg; t.N = N; t.anchor = f.anchor;
    t.blks.push({ lon: f.anchor.lon, lat: f.anchor.lat, anchor: f.anchor, lines: L, buf: P.wireBuffer(f.anchor, L), lidarStream: key,
      prov: 'measured', receipt: t.dtm.sha, kind: 'ground', gz, E });
    t.segs = L.length;
    if (t.dsm && !t.dsm.none && !t.dsm.pending) {
      const O = []; let n = 0;
      for (let b = 0; b < N; b++) for (let a = 0; a < N; a++) {
        let top = -Infinity, gi = NaN;
        for (let v = 0; v < STEP; v++) for (let u = 0; u < STEP; u++) {
          const i = a * STEP + u, j = b * STEP + v, s = hAt(t.dsm, i, j), g = hAt(t.dtm, i, j);
          if (Number.isFinite(s) && Number.isFinite(g) && s - g > top) { top = s - g; gi = g; }
        }
        if (!(top > ABOVE_M)) continue;
        n++;
        const p = f.xy(t.tile.e0 + a * STEP + STEP / 2 + 0.5, t.tile.n0 + b * STEP + STEP / 2 + 0.5), z0 = gi - base, z1 = z0 + top, d = 2;
        O.push([p[0], p[1], z0, p[0], p[1], z1],
          [p[0] - d, p[1] - d, z1, p[0] + d, p[1] - d, z1], [p[0] + d, p[1] - d, z1, p[0] + d, p[1] + d, z1],
          [p[0] + d, p[1] + d, z1, p[0] - d, p[1] + d, z1], [p[0] - d, p[1] + d, z1, p[0] - d, p[1] - d, z1]);
      }
      t.objects = n;
      if (O.length) t.blks.push({ lon: f.anchor.lon, lat: f.anchor.lat, anchor: f.anchor, lines: O, buf: P.wireBuffer(f.anchor, O), lidarStream: key,
        prov: 'derived', receipt: t.dsm.sha, kind: 'above-ground', gz, E });
    }
    sync();
  }

  // LAYER ORDER. Wire and Dark: the blocks ride the overlay's solid wire layer, as before. Satellite: they move to this
  // module's own layer, drawn above the imagery in the same colour (still solid, continuous lines = measured) but at
  // alpha SAT_ALPHA with no depth write, so the satellite stays visible through the 8 m grid at close range.
  // DEPTH_BIAS (r3): the map DEM is coarser than the 1 m DTM and sits up to ~2 m above measured nodes at the walker, so
  // a plain depth test hid the near wire at grazing angles. The bias moves only the depth (NDC z, same for x and y, so
  // every line stays exactly where it was measured on screen); in metres it grows with distance, and hills still hide.
  // r5: 0.0006 let 60/3,993 nodes behind a synthetic 180 m ridge show at the crest (1.5 %); 0.0005 draws 2 (0.05 %),
  // with 2,288/2,301 visible far nodes still drawn (tests/lidar-stream.cjs, ridge check).
  const SAT_ALPHA = 0.35, sat = [], DEPTH_BIAS = 0.0005;
  const satMode = () => { const m = window.SIM.map; return !!(m.getSource && m.getSource('sat')); };
  const layer = { id: 'lidar-stream-sat', type: 'custom', renderingMode: '3d',
    onAdd(m, gl) { const sh = (ty, src) => { const o = gl.createShader(ty); gl.shaderSource(o, src); gl.compileShader(o); return o; };
      this.pr = gl.createProgram();
      gl.attachShader(this.pr, sh(gl.VERTEX_SHADER, 'uniform mat4 u; uniform float k; attribute vec3 p; void main(){ gl_Position = u * vec4(p, 1.0); gl_Position.z -= k * gl_Position.w; }'));
      gl.attachShader(this.pr, sh(gl.FRAGMENT_SHADER, 'precision mediump float; uniform vec4 c; void main(){ gl_FragColor = c; }'));
      gl.linkProgram(this.pr); this.vbo = new WeakMap(); },
    render(gl, args) {
      if (!sat.length) return;
      const m = (args && args.defaultProjectionData && args.defaultProjectionData.mainMatrix) || args, P = PF(), loc = gl.getAttribLocation(this.pr, 'p');
      gl.useProgram(this.pr); gl.enable(gl.BLEND); gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); gl.depthMask(false);
      gl.uniform4f(gl.getUniformLocation(this.pr, 'c'), 0.55, 0.9, 1.0, SAT_ALPHA); gl.uniform1f(gl.getUniformLocation(this.pr, 'k'), DEPTH_BIAS);
      for (const b of sat) {
        let v = this.vbo.get(b); if (!v) { v = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, v); gl.bufferData(gl.ARRAY_BUFFER, b.buf, gl.STATIC_DRAW); this.vbo.set(b, v); }
        const o = P.toMercator(b.anchor.lat, b.anchor.lon, b.gz + (b.E || 0) - elevNow()), r = new Float32Array(m); // build lift, kept in the live frame as E moves
        for (let k = 0; k < 4; k++) r[12 + k] = m[k] * o.x + m[4 + k] * o.y + m[8 + k] * o.z + m[12 + k];
        gl.bindBuffer(gl.ARRAY_BUFFER, v); gl.enableVertexAttribArray(loc); gl.vertexAttribPointer(loc, 3, gl.FLOAT, false, 0, 0);
        gl.uniformMatrix4fv(gl.getUniformLocation(this.pr, 'u'), false, r); gl.drawArrays(gl.LINES, 0, b.buf.length / 3);
      }
      gl.depthMask(true);
    } };
  function sync() {
    const S = window.SIM, s = satMode();
    S.removeWhere(b => b.lidarStream); sat.length = 0;
    for (const t of tiles.values()) for (const b of t.blks || []) if (s) sat.push(b); else S.addBlock(b);
    try { if (!S.map.getLayer(layer.id)) S.map.addLayer(layer); } catch (e) { /* style still loading; style.load re-adds */ }
    S.repaint();
  }
  // The one-line receipt never covers a caption: it starts just above the attribution strip and steps up above any
  // VISIBLE caption it would touch (#where, #sim-note, the pylon and procedural captions, anything fixed at the foot).
  function captions() {
    const out = [];
    for (const el of document.body.querySelectorAll('body > *, body > * > [id]')) {
      if (el === box || box.contains(el) || el.id === 'sim-menu' || el.tagName === 'SCRIPT' || !el.textContent.trim()) continue;
      const cs = getComputedStyle(el); if (cs.position !== 'fixed' && cs.position !== 'absolute') continue;
      if (el.checkVisibility && !el.checkVisibility({ checkOpacityProperty: true, checkVisibilityCSS: true })) continue;
      const r = el.getBoundingClientRect(); if (r.width > 0 && r.height > 0 && r.top > innerHeight / 2) out.push(r);
    }
    return out;
  }
  function place() {
    if (!box) return;
    let bottom = 0; const cs = captions();
    for (let k = 0; k < 12; k++) {
      box.style.bottom = bottom + 'px';
      const a = line.getBoundingClientRect(), hit = cs.find(c => a.left < c.right && c.left < a.right && a.top < c.bottom && c.top < a.bottom);
      if (!hit) break; bottom = Math.ceil(innerHeight - hit.top + 3);
    }
  }
  async function fetchProduct(key, k) {
    const t = tiles.get(key), src = R5.SOURCES[k], b = R5.clip(t.tile, src.env);
    if (!b) { t[k] = { none: 'outside the service envelope' }; return; }
    if (!pacer.take()) return; // caller checked why() first
    saveDay();
    const url = R5.wcsUrl(src, b), at = new Date().toISOString(); let status = 0;
    t[k] = { pending: 'streaming...' }; show();
    try {
      const res = await (fetchImpl || fetch)(url, { mode: 'cors' }); status = res.status;
      if (!res.ok) throw Error(`HTTP ${res.status}${res.status === 403 || res.status === 429 ? ', refused; pausing' : ''}`);
      const geo = await R5.decodeGeoTiff(await res.arrayBuffer()), m = R5.measuredMask(geo);
      if (!m.valid) { t[k] = { none: 'no survey: sea, not flown, or a border (exact zeros)' }; return; }
      const sha = await R5.cellSha256(geo.data, crypto.subtle);
      t[k] = { src, box: b, url, at, geo, mask: m.mask, valid: m.frac, sha, tile: t.tile };
    } catch (e) {
      // Status 0 = the request never got an HTTP answer (network, abort, or a response the browser refused). One retry,
      // in this arrival only, through the pacer (40 s gap); movement never triggers it. 403/429 go to the pause via done().
      const reason = (e && e.message) || 'network error';
      t.tries = t.tries || {};
      if (status === 0 && !t.tries[k]) { t.tries[k] = 1; t[k] = null; t.retryNote = `${k.toUpperCase()} fetch failed (${reason}); retrying once`; }
      else if (status === 0) t[k] = { none: `${k.toUpperCase()} fetch failed (${reason}); no measured ground shown`, failed: true };
      else t[k] = { none: e.message };
    } finally { pacer.done(status); if (gapOverride != null) pacer.state.next = Date.now() + gapOverride; }
  }

  function step() {
    clearTimeout(timer); timer = null;
    const t = current && tiles.get(current);
    if (!t || !on) return;
    const need = !t.dtm ? 'dtm' : (!t.dsm && t.dtm && !t.dtm.none && !t.dtm.pending) ? 'dsm' : null;
    if (!need) { t.status = t.dtm && t.dtm.failed ? t.dtm.none : t.dtm && t.dtm.none ? 'no measured ground here' : 'complete'; show(); return; }
    const why = pacer.why(), retry = t.tries && t.tries[need] ? `${t.retryNote}: ` : '';
    if (why) {
      t.status = `${retry}${need.toUpperCase()} ${why}`; show();
      if (!pacer.state.stopped && !/daily cap/.test(why)) timer = setTimeout(step, 1000);
      return;
    }
    t.status = `${retry}streaming the ${need.toUpperCase()}`; show();
    const key = current;
    fetchProduct(key, need).then(() => { draw(key); if (current === key) step(); show(); });
  }

  // ARRIVAL: the only place that may start a fetch (R5 rule 6). Stored wireframe first (rule 5).
  function arrive(why) {
    if (!on || !R5) return null;
    const S = window.SIM, P = PF(), c = S.map.getCenter(), g = P.toBng(c.lat, c.lng), tile = R5.tileOf(g.e, g.n);
    current = tile.key;
    if (!tiles.has(tile.key)) tiles.set(tile.key, { tile, dtm: null, dsm: null, status: `arrived (${why})` });
    const t = tiles.get(tile.key);
    if (!R5.clip(tile, R5.SOURCES.dtm.env)) { t.dtm = { none: 'outside the EA LiDAR envelope (England only)' }; t.status = 'no measured ground here'; }
    // The arrival line lives only in this module's own receipt panel; #info (the landing caption) is never touched.
    t.arrived = `Arrived (${why}): measured ground for tile ${tile.e0} E ${tile.n0} N streams here; moving never fetches.`;
    show(); step(); return tile;
  }

  wait(async () => {
    const S = window.SIM;
    R5 = await import(new URL('lidar-stream/r5.mjs', HERE).href);
    pacer = R5.createPacer({ used: dayUsed() });
    btn = S.addButton ? S.addButton('Stream ground', () => arrive('button')) : null;
    // Arrival hooks, no edits to the overlay: a flyTo (find/go) that ends, and the Walk, Drone and Build here buttons.
    const fly = S.map.flyTo.bind(S.map);
    S.map.flyTo = (...a) => { arriving = true; return fly(...a); };
    S.map.on('style.load', sync);
    const inf = document.getElementById('info'); if (inf && window.MutationObserver) new MutationObserver(place).observe(inf, { childList: true, characterData: true, subtree: true });
    addEventListener('resize', place); setInterval(place, 1000); // captions come and go (the 8 s note); cheap
    addEventListener('keydown', e => { if (e.key === 'Escape' && open) setOpen(false); });
    S.map.on('idle', () => { for (const [k, t] of tiles) if (t.H && (Math.abs(terrainAt(t.anchor.lon, t.anchor.lat) - t.gz) > 0.01 || Math.abs(elevNow() - (t.E || 0)) > 0.01)) draw(k); });
    S.map.on('moveend', () => { if (arriving) { arriving = false; arrive('find or go'); } });
    for (const [id, w] of [['walk', 'Walk'], ['drone', 'Drone'], ['here', 'Build here']]) {
      const el = document.getElementById(id); if (el) el.addEventListener('click', () => setTimeout(() => arrive(w), 1200));
    }
    show();
    window.__lidarStream = {
      arrive, tiles, heightAt, probe, pacer: () => pacer.state, R5: () => R5,
      // Tests and local checks only: serve a fixture instead of the EA; the gap may be shortened ONLY with a fixture.
      useFixture(fn, gapMs) { fetchImpl = fn; gapOverride = gapMs == null ? null : gapMs; pacer.state.next = 0; },
      segs: () => [...tiles.values()].flatMap(t => t.blks || []).reduce((s, b) => s + b.lines.length, 0),
      layer: () => ({ satellite: satMode(), own: sat.length, inWire: S.blocks.filter(b => b.lidarStream).length, alpha: SAT_ALPHA, onMap: !!S.map.getLayer(layer.id) }),
      line: () => { panel(); return { text: line.textContent, rect: line.getBoundingClientRect().toJSON(), open }; }, setOpen, place,
      blocks: () => [...tiles.values()].flatMap(t => t.blks || []).map(b => ({ kind: b.kind, prov: b.prov, receipt: b.receipt, lat: b.lat, lon: b.lon, n: b.lines.length })),
      receipt: () => panel().textContent  // the full receipt (shown on click)
    };
  });
})();

Grid Engine — Route Obstacles Page

A web page in GlobalGrid2050 covering motorways and A roads, and uses data from the ventus-grid-engine repository. Published at https://globalgrid2050.com/grid_engine/202609060213-route-obstacles/.

renderglobalgrid2050 / grid_engine/202609060213-route-obstacles/index.html · lines 1–254 of 254 · version 2026-09-06 02:13 · Entry point · pattern parseCrossings (shared by 2 files)

What it does
It draws motorways and A roads. Defines 7 functions or classes, including el, num, fig, refuse, bind. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage field_execution (path word 'route'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work. Domain terms in the code: motorways, A roads.
Inputs & outputs
In: form fields (user input). Out: web page.
Downstream impact
Used directly by 3 files: Homepage V090 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v090.html); Homepage V091 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v091.html); Homepage V093 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v093.html). It is itself an entry point, published at https://globalgrid2050.com/grid_engine/202609060213-route-obstacles/.
What it achieves
It parses crossings (`parseCrossings`) and is built from the num step (`num`) and the fig step (`fig`). Route Obstacles Workbench — Ventus Grid Engine. It responds to input events.
Why it matters
Loaded by the Homepage V090 page at https://globalgrid2050.com/homepage_versions/homepage_v090.html and 2 other pages.
Application
globalgrid2050 · grid_engine/202609060213-route-obstacles · page
Uses
Route Obstacles (link), GlobalGrid2050 — Grid Engine Page (link), Papers — Published Fault Level Page (link)
Used by
linked from Homepage V090 (link), linked from Homepage V091 (link), linked from Homepage V093 (link)
Produces
el, num, fig, refuse, bind, parseCrossings, render
Defines here
el, num, fig, refuse, bind, parseCrossings, render
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 grid_engine/202609060213-route-obstacles/index.html:1-254 · blob 814a9e4327d7a8365dc783e77e3cafd3406fea21 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
<!DOCTYPE html>
<html lang="en-GB">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Route Obstacles Workbench — Ventus Grid Engine</title>
<style>
:root{--bg:#000;--panel:#0b0e14;--line:#2f343d;--soft:#222;--text:#fff;
  --muted:#a6adbb;--accent:#00ffff;--ok:#00ff88;--warn:#ffae00;--no:#ff5c5c}
*{box-sizing:border-box;margin:0;padding:0;font-family:'Courier New',ui-monospace,monospace}
html,body{background:var(--bg);color:var(--text)}
body{font-size:14px;line-height:1.55;padding:0 0 48px}
.wrap{max-width:960px;margin:0 auto;padding:0 14px}
header{border-bottom:1px solid var(--soft);padding:18px 0 14px;margin-bottom:16px}
h1{font-size:17px;letter-spacing:2px;color:var(--accent)}
.sub{color:var(--muted);font-size:11px;margin-top:6px}
.stamp{color:#7f8996;font-size:10px;margin-top:8px;overflow-wrap:anywhere}
.status{border:1px solid var(--line);background:var(--panel);padding:9px 11px;
  margin-bottom:16px;font-size:11px}
.status.live{border-color:#167d4d;color:var(--ok)}
.status.dead{border-color:#7d1616;color:var(--no)}
section{border:1px solid var(--soft);background:var(--panel);margin-bottom:16px}
h2{font-size:12px;letter-spacing:1.4px;color:var(--accent);padding:11px 13px;
  border-bottom:1px solid var(--soft)}
.body{padding:13px}
.lede{color:var(--muted);font-size:11.5px;line-height:1.65;margin-bottom:13px}
label{display:block;color:var(--muted);font-size:10px;letter-spacing:.6px;
  text-transform:uppercase;margin:0 0 5px}
.field{margin-bottom:13px}
input[type=number],input[type=text]{width:100%;background:#000;border:1px solid var(--line);
  color:var(--text);padding:11px 10px;font-size:16px;font-weight:700}
input:focus{outline:none;border-color:var(--accent)}
input[type=range]{width:100%;accent-color:var(--accent);height:32px}
.rangerow{display:flex;justify-content:space-between;align-items:baseline;gap:10px}
.rangeval{color:var(--accent);font-weight:700;font-size:15px;white-space:nowrap}
.out{border:1px solid var(--line);background:#06080b;padding:11px;margin-top:11px}
.figure{display:flex;align-items:baseline;gap:8px;flex-wrap:wrap}
.figure .n{font-size:26px;font-weight:700;color:var(--ok);line-height:1.1}
.figure .n.over{color:var(--no)}
.figure .u{font-size:12px;color:var(--muted)}
.figure .q{font-size:10px;color:#7f8996;text-transform:uppercase;letter-spacing:.8px;
  flex:1 0 100%;margin-bottom:3px}
.basis{color:#8e98a5;font-size:10.5px;line-height:1.65;margin-top:9px;
  border-top:1px dashed #252a31;padding-top:8px}
.scroller{overflow-x:auto;-webkit-overflow-scrolling:touch}
table{width:100%;border-collapse:collapse;font-size:11px}
th{color:var(--accent);text-align:left;padding:7px 6px;border-bottom:1px solid var(--line);
  font-size:10px;letter-spacing:.5px}
td{padding:7px 6px;border-bottom:1px solid #1a1e25;color:var(--muted)}
td.n{color:var(--text);font-weight:700;text-align:right;white-space:nowrap}
.refuse{border:1px solid #5c2020;background:#120708}
.refuse h2{color:#ff8f8f;border-bottom-color:#5c2020}
.refuse dt{color:#ff8f8f;font-size:11px;font-weight:700;margin-top:11px}
.refuse dt:first-child{margin-top:0}
.refuse dd{color:#c9a9a9;font-size:10.5px;line-height:1.65;margin-top:3px}
footer{color:#69727d;font-size:10.5px;line-height:1.9;padding-top:14px;
  border-top:1px solid var(--soft);margin-top:20px}
/* Touch targets. Measured at 393px on 2026-09-06: footer links were 11.3px
   tall, below the 24px WCAG 2.2 minimum. Inline links keep their flow but are
   given real height through padding and line-height. */
footer a,.basis a{color:#66ccff;display:inline-block;padding:5px 2px;line-height:1.5}
.nav{margin-top:14px;font-size:11px}
.nav a{color:#66ccff;display:inline-block;padding:8px 10px 8px 0}
</style>
</head>
<body>
<div class="wrap">
<header>
  <h1>ROUTE OBSTACLES WORKBENCH</h1>
  <p class="sub">What gets in the way — and when a road factor describes a road that is not there</p>
  <p class="stamp">Generation 202609060213 · engine route-obstacles.js at 9a92211</p>
</header>
<div class="status" id="engine-status">Loading the engine module…</div>
<section>
  <h2>1 · THE ROUTE, AND WHAT IT CROSSES</h2>
  <div class="body">
    <p class="lede">The straight line is the first pass and stays exactly as it is. What this adds
                   is the crossings. Enter them as <code>type</code> or <code>type x count</code>,
                   separated by commas — for example <code>motorway, railway x2, minor_road x3</code>.
                   Known types: motorway, trunk_road, minor_road, railway, navigable_river, canal,
                   watercourse, open_water, protected_habitat.</p>
    <div class="field">
      <label for="skm">Straight-line distance (km)</label>
      <input type="number" id="skm" value="10" min="0.1" max="2000" step="0.01" inputmode="decimal">
    </div>
    <div class="field">
      <label for="cross">Declared crossings</label>
      <input type="text" id="cross" value="motorway, railway x2, minor_road x3" inputmode="text">
    </div>
    <div class="field">
      <div class="rangerow"><label for="cf">Corridor factor</label>
        <span class="rangeval" id="cf-val">1.245</span></div>
      <input type="range" id="cf" min="1" max="2" step="0.005" value="1.245">
    </div>
    <div class="out" id="out-route"></div>
    
    
  </div>
</section>
<section>
  <h2>2 · THE CROSSING SCHEDULE</h2>
  <div class="body">
    <p class="lede">You do not open-cut a live motorway or a running railway. Those are trenchless
                   crossings, with launch and reception pits set back beyond the asset boundary — so
                   the bore is always longer than the obstacle is wide, and for anything narrow the
                   setback is the dominant term. A 30 m motorway with 15 m setbacks is a 60 m span,
                   not a 30 m drill.</p>
    <div class="field">
      <label for="width">Obstacle width (m)</label>
      <input type="number" id="width" value="30" min="0.5" max="2000" step="0.5" inputmode="decimal">
    </div>
    <div class="field">
      <label for="setback">Setback each side (m)</label>
      <input type="number" id="setback" value="15" min="0.5" max="500" step="0.5" inputmode="decimal">
    </div>
    <div class="field">
      <label for="depth">Bore depth (m, 0 for none)</label>
      <input type="number" id="depth" value="0" min="0" max="100" step="0.5" inputmode="decimal">
    </div>
    
    <div class="scroller"><table id="cross-table"><thead><tr><th>Crossing</th><th style="text-align:right">Method</th><th>Why</th></tr></thead><tbody></tbody></table></div>
    <p class="basis">Widths, setbacks and cover are the asset owner's requirements and differ between
                   owners — Network Rail and a highways authority do not publish the same numbers — so
                   they are inputs here and never constants. A crossing declared without a width is
                   counted and named, not silently costed at zero.</p>
  </div>
</section>
<section>
  <h2>3 · THE IRISH SEA TEST</h2>
  <div class="body">
    <p class="lede">Add <code>open_water</code> to the crossings above and the estimate becomes
                   <em>null</em>, not a number. This is the check a scalar corridor function cannot
                   make: <code>forCable()</code> receives one kilometre and never sees the
                   coordinates, so South Antrim to the Western HVDC converter — 142.21 km, almost all
                   of it sea — was printed as a 177.05 km highway corridor. A road route that does not
                   exist, stated with the confidence of a calibrated number. The straight line is kept
                   either way, because it is a real measurement.</p>

    <div class="out" id="out-sea"></div>
    
    
  </div>
</section>
<section class="refuse">
  <h2>WHAT THIS WORKBENCH WILL NOT COMPUTE</h2>
  <div class="body">
    <p class="lede" style="color:#c9a9a9">These are not features missing from a later
      version. The engine proof asserts that no function of these names exists, so
      their absence is a tested property rather than an oversight.</p>
    <dl id="refusals"></dl>
  </div>
</section>
<footer>
  <p>Every figure above is computed by
     <a href="https://ventusltd.github.io/ventus-grid-engine/engine/route-obstacles.js">route-obstacles.js</a>
     in the Ventus Grid Engine, imported at runtime and proven by 44 checks.
     This page holds no copy of the mathematics: if the engine cannot be reached it
     shows no numbers rather than a stale answer.</p>
  <p class="nav">
     <a href="../">All workbenches</a>
     <a href="/papers/202609060203-electrification/">Electrification paper</a>
     <a href="/papers/202609060045-published-fault-level/">Fault-level paper</a>
     <a href="/">GlobalGrid2050</a></p>
  <p style="margin-top:6px">Scenario arithmetic is not evidence of connection headroom.
     A national load factor cannot establish utilisation at any particular transformer.</p>
</footer>
</div>
<script type="module">
const ENGINE = 'https://ventusltd.github.io/ventus-grid-engine/engine/route-obstacles.js';
const statusEl = document.getElementById('engine-status');
let E = null;

const el = id => document.getElementById(id);
const num = id => Number(el(id).value);

function fig(target, r, decimals = 1, over = false) {
  el(target).innerHTML =
    '<div class="figure">' +
      '<span class="q">' + r.quantity.replace(/_/g, ' ') + '</span>' +
      '<span class="n' + (over ? ' over' : '') + '">' +
        r.value.toLocaleString('en-GB', { minimumFractionDigits: decimals, maximumFractionDigits: decimals }) +
      '</span><span class="u">' + r.unit + '</span></div>' +
    '<p class="basis">' + r.basis + '</p>';
}

function refuse(target, message) {
  el(target).innerHTML = '<p class="basis" style="color:#ffae00;border:0;padding:0;margin:0">'
    + 'Engine refused this input: ' + message + '</p>';
}


function bind() { ['skm','cross','cf','width','setback','depth'].forEach(id => el(id).addEventListener('input', render)); }

function parseCrossings(raw, widthM, setbackM, depthM) {
  return raw.split(',').map(s => s.trim()).filter(Boolean).map(tok => {
    const m = tok.match(/^([a-z_]+)(?:\s*[x*]\s*(\d+))?$/i);
    if (!m) throw new Error('cannot read crossing "' + tok + '" — use type or type x count');
    const c = { type: m[1].toLowerCase(), count: m[2] ? parseInt(m[2], 10) : 1 };
    if (widthM > 0 && setbackM > 0) { c.widthM = widthM; c.setbackM = setbackM; if (depthM > 0) c.depthM = depthM; }
    return c;
  });
}

function render() {
  el('cf-val').textContent = num('cf').toFixed(3);
  const tb = document.querySelector('#cross-table tbody');
  let crossings;
  try { crossings = parseCrossings(el('cross').value, num('width'), num('setback'), num('depth')); }
  catch (err) { refuse('out-route', err.message); tb.innerHTML = ''; return; }

  try {
    const r = E.routeEstimate({ straightLineKm: num('skm'), crossings, corridorFactor: num('cf') });
    el('out-route').innerHTML = r.value === null
      ? '<div class="figure"><span class="q">route estimate</span><span class="n over">NO ESTIMATE</span></div>'
        + '<p class="basis">' + r.basis + '</p>'
      : '<div class="figure"><span class="q">route estimate</span><span class="n">' +
        r.value.toFixed(2) + '</span><span class="u">km</span></div><p class="basis">' + r.basis + '</p>';

    tb.innerHTML = r.schedule.items.map(i =>
      '<tr><td>' + i.label + (i.count > 1 ? ' x' + i.count : '') + '</td>' +
      '<td class="n" style="color:' + (i.trenchless ? '#ffae00' : '#00ff88') + '">' + i.method + '</td>' +
      '<td style="font-size:10px">' + i.why + '</td></tr>').join('')
      || '<tr><td colspan="3">No crossings declared.</td></tr>';

    const sea = E.routeEstimate({ straightLineKm: num('skm'),
      crossings: crossings.concat([{ type: 'open_water' }]), corridorFactor: num('cf') });
    el('out-sea').innerHTML =
      '<div class="figure"><span class="q">the same route, with open water added</span>' +
      '<span class="n over">' + (sea.value === null ? 'NO ESTIMATE' : sea.value.toFixed(2)) + '</span></div>' +
      '<p class="basis">' + sea.basis + '</p>';
  } catch (err) { refuse('out-route', err.message); tb.innerHTML = ''; }
}

try {
  E = await import(ENGINE);
  if (E.schema !== 'ventus-grid-engine.route-obstacles.v1') throw new Error('unexpected schema ' + E.schema);
  statusEl.className = 'status live';
  statusEl.textContent = 'ENGINE LIVE — ' + E.schema +
    ' · every figure below is computed by the engine module, not by this page.';
  el('refusals').innerHTML = Object.entries(E.NOT_COMPUTED).map(([k, v]) =>
    '<dt>' + k.replace(/([A-Z])/g, ' $1').toUpperCase() + '</dt><dd>' + v + '</dd>').join('');
  bind();
  render();
} catch (err) {
  statusEl.className = 'status dead';
  statusEl.textContent = 'ENGINE UNREACHABLE — ' + err.message +
    '. Nothing on this page is computed; there is deliberately no local copy to fall back to.';
  document.querySelectorAll('.out').forEach(o => {
    o.innerHTML = '<p class="basis" style="color:#ff8f8f;border:0;padding:0;margin:0">'
      + 'No figure: the engine did not load.</p>'; });
}
</script>
</body>
</html>

Whole Site Route View

A JavaScript file in the drawing folder of GlobalGrid2050 that draws Kuiper proposed site routes. Served with the page at https://globalgrid2050.com/kuiper-grid/drawing/.

renderglobalgrid2050 / kuiper-grid/drawing/whole-site-route-view.js · lines 1–48 of 48 · Entry point · pattern signature (shared by 2 files)

What it does
It draws Kuiper proposed site routes. Defines 8 functions or classes, including syncScope, nativeSite, signature, invalidate, requireCurrent. Side effects: changes the web page (DOM); reads or writes files.
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: form fields (user input). Out: JSON file kuiper-proposed-site-routes.json; downloaded file kuiper-proposed-site-routes.json; canvas drawing.
Downstream impact
Used directly by 1 file: Kuiper Grid — Drawing Page (globalgrid2050, https://globalgrid2050.com/kuiper-grid/drawing/). Reached from 109 other entry points, including GlobalGrid2050 Historical Builds (globalgrid2050, https://globalgrid2050.com/historical_builds.html); GlobalGrid2050 Homepage Before Four Nests (globalgrid2050, https://globalgrid2050.com/homepage-before-four-nests-20260925.html); GlobalGrid2050 — Compute Page (globalgrid2050, https://globalgrid2050.com/compute/). It is itself an entry point, published at https://globalgrid2050.com/kuiper-grid/drawing/.
What it achieves
It syncs scope (`syncScope`) and is built from the native site helper (`nativeSite`) and the invalidate step (`invalidate`). Defines `syncScope`, `nativeSite`, `signature` and 5 more. It responds to input and click events.
Why it matters
Loaded by the Drawing page at https://globalgrid2050.com/kuiper-grid/drawing/.
Application
globalgrid2050 · kuiper-grid/drawing · script
Uses
none found
Used by
loaded by Kuiper Grid — Drawing Page (script src)
Produces
syncScope, nativeSite, signature, invalidate, requireCurrent, sceneData, open, attempt
Defines here
syncScope, nativeSite, signature, invalidate, requireCurrent, sceneData, open, attempt
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/drawing/whole-site-route-view.js:1-48 · blob 369dc026beeaf888e5dbe6a45b61a2e7bc710515 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: agent_infra · users: ai_agent · canonical: production_core
'use strict';
(function boot(){
 if(!window.__arrayLab?.engineReady||!window.KuiperWholeSiteRoutes){setTimeout(boot,200);return;}
 const w=document.getElementById('kuiper-frame').contentWindow;let site=null,map=null,builtSignature=null,cameraTimer=null,activeStation=null;
 const panel=document.createElement('details');panel.id='whole-site-routes';panel.style.cssText='padding:16px;border-top:1px solid #35475a';panel.innerHTML='<summary>Whole-site roads &amp; collection routes</summary><p class="note">Uses the current power-block proposal and its exact inverter/station IDs. Positions are an entered grid of equipment/road envelopes. PV fields and land boundaries are n  … [line shortened here: 1,550 characters; full line on GitHub]
 document.querySelector('main').append(panel);const q=id=>panel.querySelector('#'+id);
 const scopeStyle=document.createElement('style');scopeStyle.textContent='body[data-whole-site-view="true"] main>.summary,body[data-whole-site-view="true"] main>.detail,body[data-whole-site-view="true"] main>.toolbar,body[data-whole-site-view="true"] main>.legend{display:none!important}';document.head.append(scopeStyle);
 const scopeNote=document.createElement('p');scopeNote.id='ws-view-scope';scopeNote.className='note';scopeNote.hidden=true;scopeNote.style.padding='0 17px';scopeNote.textContent='Whole-site road and station envelopes. Current-table connection metrics are hidden in this view. No module-field fit or electrical solution is implied.';document.querySelector('main>.summary').before(scopeNote);const retu  … [line shortened here: 665 characters; full line on GitHub]
 function syncScope(){const active=nativeSite();document.body.dataset.wholeSiteView=String(active);scopeNote.hidden=!active;}
 const frame=document.getElementById('kuiper-frame'),stale=document.createElement('div');
 stale.id='ws-stale-overlay';stale.setAttribute('role','status');stale.hidden=true;
 stale.style.cssText='position:absolute;inset:0;z-index:20;background:#101820;color:#e8f1f4;padding:32px;box-sizing:border-box';
 stale.textContent='Whole-site route drawing is out of date. Rebuild the current proposal routes before inspecting this view.';
 frame.parentElement.append(stale);
 function nativeSite(){return w.eval('lastFire?.name')==='whole-site-routes';}
 function signature(){return JSON.stringify([window.__powerBlockPlanner?.read(),q('ws-cols').value,q('ws-x').value,q('ws-y').value]);}
 function invalidate(message='Proposal or spacing changed. Rebuild site routes.'){
  if(nativeSite())stale.hidden=false;
  site=null;map=null;builtSignature=null;activeStation=null;clearTimeout(cameraTimer);cameraTimer=null;
  q('ws-station').replaceChildren();for(const id of ['ws-overview','ws-open','ws-export'])q(id).disabled=true;
  q('ws-state').textContent=message;
 }
 function requireCurrent(){if(site&&signature()!==builtSignature)invalidate();if(!site)throw Error('Build current site routes first.');return site;}
 for(const id of ['ws-cols','ws-x','ws-y'])q(id).addEventListener('input',()=>invalidate());
 const planner=document.getElementById('power-block-planner');
 planner?.addEventListener('input',e=>{if(['pb-dc','pb-wp','pb-series','pb-ratio','pb-inv','pb-per'].includes(e.target.id))invalidate();});
 planner?.addEventListener('click',e=>{if(['pb-build','pb-example','pb-copy'].includes(e.target.closest('button')?.id))invalidate();});
 invalidate('Build a power-block proposal, then draw site routes.');
 function sceneData(){
  if(!activeStation)return site.overview;
  const r=site.materializeStation(activeStation),glyph=(id,xyz,size)=>({id,inverterCount:null,envelope:{min:[xyz[0]-size,xyz[1]-size,xyz[2]],max:[xyz[0]+size,xyz[1]+size,xyz[2]]}});
  return {stations:[glyph(r.stationId,r.stationXYZ,3),...r.inverters.map(i=>glyph(i.id,i.xyz,1.5))],roads:[{...r.road,colour:'#8a97a3'},...r.feeders.map(f=>({id:f.id,points:f.points,colour:'#55daca'}))],totals:{feederCircuits:r.stationInverters,totalLvFeederRouteM:r.totalFeederRouteM,uniqueLvTrenchM:r.uniqueTrenchM,roadCentrelineM:r.road.lengthM}};
 }
 function drawing(){requireCurrent();const o=sceneData(),pts=o.stations.flatMap(s=>[s.envelope.min,s.envelope.max]).concat(o.roads.flatMap(r=>r.points));const xs=pts.map(p=>p[0]),ys=pts.map(p=>p[1]),x0=Math.min(...xs),x1=Math.max(...xs),y0=Math.min(...ys),y1=Math.max(...ys),scale=1.6/Math.max(x1-x0,y1-y0,1),cx=(x0+x1)/2,cy=(y0+y1)/2;map=p=>[(p[0]-cx)*scale,(p[1]-cy)*scale];const shapes=[],marks=[]  … [line shortened here: 401 characters; full line on GitHub]
  for(const road of o.roads)shapes.push({role:'lead',order:0,pot:0,plus:false,node:road.id,pts:road.points.map(map),weight:2});
  for(const s of o.stations){const a=map(s.envelope.min),b=map(s.envelope.max);shapes.push({role:'inverter',order:0,pot:0,node:s.id,pts:[[a[0],a[1]],[b[0],a[1]],[b[0],b[1]],[a[0],b[1]],[a[0],a[1]]]});marks.push({x:(a[0]+b[0])/2,y:(a[1]+b[1])/2,text:s.id.split('/').at(-1)+(s.inverterCount===null?'':' · '+s.inverterCount),colour:'#caf2ff',size:10,minPx:0,mid:true,rank:0});}
  const a=map([x0,y0]),b=map([x1,y1]),g={c:{view:'macro'},N:o.stations.length,pitch:1,short:[],links:[],rows:1,cols:1,rowY:[0],order:[],bothNear:true,ret:0,row:2,lead_m:0,field_m:0,ohm:0};g.__draw={freeCamera:true,kind:'string',shapes,marks,words:[],conns:[],terminals:[],wiring:true,crossings:[],perM:scale,open:true,g,firstModuleX:0,volts:0,volts_open:0,bounds:{x0:a[0]-.08,y0:a[1]-.08,x1:b[0]+.08,  … [line shortened here: 606 characters; full line on GitHub]
 }
 w.FIRE.register('whole-site-routes','WHOLE SITE ROUTES',drawing,[]);w.FIRE_SLD_KIND['whole-site-routes']='string';
 function show(){requireCurrent();const result=w.fireCommand('fire whole-site-routes {}',null);if(!result?.ran||result.name!=='whole-site-routes')throw Error(result?.error||'Native whole-site drawing did not run.');stale.hidden=true;clearTimeout(cameraTimer);cameraTimer=setTimeout(()=>{if(!site||signature()!==builtSignature){invalidate();return;}w.eval('isoAnim=null;bodyAnim=null;if(body&&body.sld  … [line shortened here: 481 characters; full line on GitHub]
 function open(id){requireCurrent();const r=site.materializeStation(id);activeStation=id;show();q('ws-state').textContent=id+' · '+r.stationInverters+' independent feeder circuits · '+r.totalFeederRouteM+' m circuit routes · '+r.uniqueTrenchM+' m unique trench. Teal: proposed feeders; grey: access road. Small boxes are enlarged symbols, not equipment dimensions.';return r;}
 function attempt(fn){try{return fn();}catch(e){invalidate(e.message||String(e));return null;}}
 q('ws-build').onclick=()=>{invalidate('Building current routes.');return attempt(()=>{const proposal=window.__powerBlockPlanner?.read();if(!proposal)throw Error('Build a power-block proposal in the sidebar first.');site=KuiperWholeSiteRoutes.build(proposal,{stationColumns:Number(q('ws-cols').value),horizontalM:Number(q('ws-x').value),verticalM:Number(q('ws-y').value),stationLocal:{lateralM:30,row  … [line shortened here: 984 characters; full line on GitHub]
 q('ws-open').onclick=()=>attempt(()=>open(q('ws-station').value));q('ws-overview').onclick=()=>attempt(()=>{activeStation=null;show();q('ws-state').textContent=site.overview.stationCount+' proposed stations. Amber lines are roads; module fields are not allocated.';});q('ws-export').onclick=()=>attempt(()=>{requireCurrent();const url=URL.createObjectURL(new Blob([JSON.stringify(site.overview,null,  … [line shortened here: 578 characters; full line on GitHub]
 w.__wafer?.onDraw?.add(()=>{syncScope();if(!nativeSite()&&w.eval('lastFire?.ran')===true)stale.hidden=true;if(site&&signature()!==builtSignature)invalidate();if(!site||!map||w.eval('lastFire?.name')!=='whole-site-routes'||w.eval('!!bodyAnim'))return;const c=w.document.getElementById('sldshapes'),ctx=c?.getContext('2d');if(!ctx)return;const dpr=Math.min(3,w.devicePixelRatio||1),b=w.shapeBand(true)  … [line shortened here: 788 characters; full line on GitHub]

 window.__wholeSiteRouteView={get activeStation(){return activeStation;},get site(){if(site&&signature()!==builtSignature)invalidate();return site;},open,show};
})();

Whole Site Routes

A JavaScript module in the drawing folder of GlobalGrid2050 that works with cables. Served with the page at https://globalgrid2050.com/kuiper-grid/drawing/.

transformglobalgrid2050 / kuiper-grid/drawing/whole-site-routes.js · lines 1–57 of 57 · Entry point · pattern length (shared by 4 files)

What it does
It calculates cables. Defines 6 functions or classes, including clone, finite, length, roadUnion, build.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). Domain terms in the code: cables. README: "Whole-site route overview: build a power-block proposal, then open Whole-site roads & collection routes below the canvas."
Downstream impact
Used directly by 1 file: Kuiper Grid — Drawing Page (globalgrid2050, https://globalgrid2050.com/kuiper-grid/drawing/). Reached from 109 other entry points, including GlobalGrid2050 Historical Builds (globalgrid2050, https://globalgrid2050.com/historical_builds.html); GlobalGrid2050 Homepage Before Four Nests (globalgrid2050, https://globalgrid2050.com/homepage-before-four-nests-20260925.html); GlobalGrid2050 — Compute Page (globalgrid2050, https://globalgrid2050.com/compute/). It is itself an entry point, published at https://globalgrid2050.com/kuiper-grid/drawing/.
What it achieves
It is built from the clone step (`clone`), the finite step (`finite`) and the length step (`length`). Generic whole-site collection geometry. No project boundary or MV circuit inference.
Why it matters
Loaded by the Drawing page at https://globalgrid2050.com/kuiper-grid/drawing/.
Application
globalgrid2050 · kuiper-grid/drawing · JavaScript module
Uses
none found
Used by
loaded by Kuiper Grid — Drawing Page (script src)
Produces
clone, finite, length, roadUnion, build, locateInverter
Defines here
clone, finite, length, roadUnion, build, locateInverter
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/drawing/whole-site-routes.js:1-57 · blob 1b309d264f453d69266ce8ca750c53410d831fb7 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: agent_infra · users: ai_agent · canonical: production_core
/* Generic whole-site collection geometry. No project boundary or MV circuit inference. */
(function(root){'use strict';
const clone=x=>JSON.parse(JSON.stringify(x));
function finite(v,name,min,max,integer=false){if(typeof v!=='number'||!Number.isFinite(v)||v<min||v>max||(integer&&!Number.isInteger(v)))throw Error(name+' is outside the supported range');return v;}
function length(points){let n=0;for(let i=1;i<points.length;i++)n+=Math.hypot(...points[i].map((v,j)=>v-points[i-1][j]));return n;}
// All geometry lies on one explicitly assumed ground layer. Merge collinear
// intervals, then split every resulting interval at perpendicular crossings.
function roadUnion(roads){
 const groups=new Map();
 for(const road of roads)for(let i=1;i<road.points.length;i++){
  const a=road.points[i-1],b=road.points[i];for(const p of [a,b])if(!Array.isArray(p)||p.length!==3||p.some(v=>typeof v!=='number'||!Number.isFinite(v)))throw Error('Finite XYZ road points required');if(a[2]!==0||b[2]!==0)throw Error('Only the assumed ground road layer is supported');
  if(a[0]!==b[0]&&a[1]!==b[1])throw Error('Road segments must be axis aligned');
  const h=a[1]===b[1],lo=Math.min(a[h?0:1],b[h?0:1]),hi=Math.max(a[h?0:1],b[h?0:1]);if(lo===hi)continue;
  const fixed=a[h?1:0],key=(h?'h:':'v:')+fixed;if(!groups.has(key))groups.set(key,{horizontal:h,fixed,intervals:[]});groups.get(key).intervals.push({lo,hi});
 }
 const merged=[];
 for(const group of groups.values()){group.intervals.sort((a,b)=>a.lo-b.lo);let active=null;for(const item of group.intervals){if(!active||item.lo>active.hi){active={horizontal:group.horizontal,fixed:group.fixed,lo:item.lo,hi:item.hi};merged.push(active);}else active.hi=Math.max(active.hi,item.hi);}}
 const h=merged.filter(s=>s.horizontal),v=merged.filter(s=>!s.horizontal);for(const s of merged)s.cuts=new Set([s.lo,s.hi]);
 // Preserve input endpoints even where merging removed an intermediate vertex.
 for(const group of groups.values())for(const s of merged){if(s.horizontal!==group.horizontal||s.fixed!==group.fixed)continue;for(const i of group.intervals)for(const x of [i.lo,i.hi])if(x>=s.lo&&x<=s.hi)s.cuts.add(x);}
 for(const a of h)for(const b of v)if(b.fixed>=a.lo&&b.fixed<=a.hi&&a.fixed>=b.lo&&a.fixed<=b.hi){a.cuts.add(b.fixed);b.cuts.add(a.fixed);}
 const segments=[];for(const s of merged){const cuts=[...s.cuts].sort((a,b)=>a-b);for(let i=1;i<cuts.length;i++)segments.push({id:'ROAD-UNION-'+String(segments.length+1).padStart(6,'0'),layer:'assumed-ground',points:s.horizontal?[[cuts[i-1],s.fixed,0],[cuts[i],s.fixed,0]]:[[s.fixed,cuts[i-1],0],[s.fixed,cuts[i],0]],lengthM:cuts[i]-cuts[i-1]});}
 return{segments,lengthM:segments.reduce((a,s)=>a+s.lengthM,0),meaning:'Unique road centreline length on one assumed ground layer, not surface area; geometric crossings are not electrical junctions.'};
}
function build(proposal,settings){
 const blocks=root.KuiperPowerBlocks;if(!blocks)throw Error('Load power-block-planner.js first');
 if(!proposal||proposal.schema!==blocks.schema||!settings||typeof settings!=='object')throw Error('Proposal and explicit route settings required');
 const canonical=blocks.build(proposal.inputs);
 // Keep a private canonical copy; reject changed counts, IDs or membership.
 for(const key of ['proposalId','summary','inverters','stations'])if(JSON.stringify(proposal[key])!==JSON.stringify(canonical[key]))throw Error('Proposal '+key+' differs from its validated inputs');
 const cols=finite(settings.stationColumns,'stationColumns',1,2000,true),dx=finite(settings.horizontalM,'horizontalM',1,100000),dy=finite(settings.verticalM,'verticalM',1,100000);
 const local=settings.stationLocal;if(!local||typeof local!=='object')throw Error('Explicit stationLocal route options required');
 for(const k of ['lateralM','rowPitchM','roadOffsetM'])finite(local[k],k,5,1000);
 const options={lateralM:local.lateralM,rowPitchM:local.rowPitchM,roadOffsetM:local.roadOffsetM};
 const l=options.lateralM,p=options.rowPitchM,o=options.roadOffsetM,maxCount=Math.max(...canonical.stations.map(s=>s.inverterCount));
 const width=2*l+o,height=Math.ceil(maxCount/2)*p+o;
 if(dx<=width||dy<=height)throw Error('Spacing must exceed station route/road envelope width '+width+' m and height '+height+' m. Module-field fit is not evaluated.');
 const stationIndex=new Map(),inverterIndex=new Map(),roads=[],addresses=[];let lvCircuits=0,lvTrench=0;
 for(const s of canonical.stations){
  const col=s.index%cols,row=Math.floor(s.index/cols),x=col*dx,y=row*dy,n=s.inverterCount,rows=Math.ceil(n/2),k=Math.floor(n/2),rowSum=n%2?(k+1)**2:k*(k+1);
  const address={id:s.id,index:s.index,row,column:col,xyz:[x,y,0],inverterIds:s.inverterIds.slice(),inverterCount:n,partial:s.isPartial,envelope:{min:[x-l,y,0],max:[x+l+o,y+rows*p+o,0]},totalFeederRouteM:n*l+rowSum*p,uniqueLvTrenchM:n*l+rows*p};
  addresses.push(address);stationIndex.set(s.id,address);lvCircuits+=address.totalFeederRouteM;lvTrench+=address.uniqueLvTrenchM;
  s.inverterIds.forEach((id,i)=>inverterIndex.set(id,{id,stationId:s.id,indexWithinStation:i,xyz:[x+(i%2?l:-l),y+(Math.floor(i/2)+1)*p,0]}));
  roads.push({id:s.id+'/ROAD',kind:'station-access',stationId:s.id,layer:'assumed-ground',points:[[x,y,0],[x+l+o,y,0],[x+l+o,y+rows*p+o,0]],widthM:4});
 }
 const rowCount=Math.ceil(addresses.length/cols),spineX=-l-o,entry=[spineX,-o,0],corridors=[];
 const spine={id:canonical.proposalId+'/ACCESS-SPINE',kind:'interstation-access',layer:'assumed-ground',points:[entry,[spineX,(rowCount-1)*dy,0]],widthM:4};roads.push(spine);
 for(let row=0;row<rowCount;row++){const inRow=addresses.filter(s=>s.row===row),last=inRow.at(-1);roads.push({id:canonical.proposalId+'/ACCESS-ROW-'+String(row+1).padStart(6,'0'),kind:'interstation-access',layer:'assumed-ground',points:[[spineX,row*dy,0],[last.xyz[0],row*dy,0]],widthM:4});}
 for(const road of roads.filter(r=>r.kind==='interstation-access'))corridors.push({id:road.id.replace('/ACCESS-','/UNASSIGNED-CORRIDOR-'),points:clone(road.points),assignment:'unassigned proposed corridor; no cable circuit',circuitId:null,voltageKv:null,excavationIncluded:false});
 const union=roadUnion(roads);
 const overview={schema:'kuiper.whole-site-routes/1',revision:1,proposalId:canonical.proposalId,units:'m',settings:{stationColumns:cols,horizontalM:dx,verticalM:dy,stationLocal:options},geometryBasis:'generic provisional station collection layout; no project boundary or module-field layout',entry,stationEnvelopeMaximum:{widthM:width,heightM:height},stations:addresses,stationCount:addresses.length,  … [line shortened here: 1,484 characters; full line on GitHub]
 function materializeStation(id){const address=stationIndex.get(id);if(!address)throw Error('Unknown proposal station');const r=blocks.collection(canonical,id,options),at=p=>p.map((v,i)=>v+address.xyz[i]);r.stationXYZ=at(r.stationXYZ);r.inverters.forEach(x=>{x.xyz=at(x.xyz);});for(const list of [r.feeders,r.segments])list.forEach(x=>{x.points=x.points.map(at);});r.road.points=r.road.points.map(at)  … [line shortened here: 534 characters; full line on GitHub]
 function locateInverter(id){const found=inverterIndex.get(id);if(!found)throw Error('Unknown proposal inverter');return clone(found);}
 return Object.freeze({overview:clone(overview),materializeStation,locateInverter});
}
root.KuiperWholeSiteRoutes=Object.freeze({build,roadUnion});if(typeof module!=='undefined')module.exports=root.KuiperWholeSiteRoutes;
})(typeof window!=='undefined'?window:globalThis);