GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / globalgrid2050 / energy-transition-simulator/202609280014/mod

Overlay and 2 more files

A map page in GlobalGrid2050 that maps grid substations, DEM and solar, using OSTN15 and Helmert, and uses data from OpenStreetMap (Overpass) and the GridAtlas repository. Published at https://globalgrid2050.com/energy-transition-simulator/202609280014/overlay.html.

601 lines of JavaScript and HTML from globalgrid2050, in 3 files. Topic: Electricity markets and data pipelines. Section 851 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. Perf render · globalgrid2050 / energy-transition-simulator/202609280014/mod/perf.js lines 1–136
  2. Pylons Real render · globalgrid2050 / energy-transition-simulator/202609280014/mod/pylons-real.js lines 1–165
  3. Overlay geodesy · globalgrid2050 / energy-transition-simulator/202609280014/overlay.html lines 1–300

Perf

A JavaScript file in GlobalGrid2050 that extracts planes (`extractPlanes`) and calculates planar distances.

renderglobalgrid2050 / energy-transition-simulator/202609280014/mod/perf.js · lines 1–136 of 136 · version 2026-09-28 00:14 · Not reached from any entry point (candidate for review) · pattern extractPlanes (shared by 2 files)

What it does
It draws its content. Defines 10 functions or classes, including mx, my, mz, attach, bumpTerrain. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
What it achieves
It extracts planes (`extractPlanes`) and is built from the attach step (`attach`) and the bump terrain helper (`bumpTerrain`). The wire layer, made light (plain script; attaches to window.SIM).
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · energy-transition-simulator/202609280014/mod · script
Uses
none found
Used by
none found
Produces
mx, my, mz, attach, bumpTerrain, ensurePlaced, entryFor, extractPlanes, row, visible
Defines here
mx, my, mz, attach, bumpTerrain, ensurePlaced, entryFor, extractPlanes, row, visible
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/202609280014/mod/perf.js:1-136 · blob b2f39b27ce12aee46ac64b49f46c0e023217e13d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
// mod/perf.js - the wire layer, made light (plain script; attaches to window.SIM).
// What it changes, and only in the wire layer's render:
//  1. One GPU buffer per block, uploaded ONCE (STATIC_DRAW) and kept until the block changes. A block counts as
//     changed when its Float32Array `buf` is a different object or length, or when its `rev` number changes
//     (a module that edits b.buf in place sets b.rev++). Buffers of removed blocks are deleted.
//  2. The anchor's Mercator point and ground height are cached per block, not recomputed every frame. Heights are
//     re-read after terrain tiles arrive (map 'idle' / 'terrain'), at most 300 queries per frame.
//  3. Blocks outside the view are skipped (a bounding sphere against the six frustum planes).
//  4. Shader locations are looked up once per program.
// Blocks that arrive as plain { lon, lat, lines } (no anchor/buf) are placed with place-frame.mjs, the same way
// overlay.html places its own, so any module can hand over bare metres.
// LEAD NOTES (overlay.html): (a) add 'perf' to mod/index.json; nothing else is required. Better still, fold this
// render into `wire` itself and drop the per-frame bufferData/getAttribLocation/getUniformLocation/queryTerrainElevation.
// (b) A module that edits b.buf in place must bump b.rev (or call SIM.perf.touch(b)); a new buf object is detected.
// (c) Phone size (390 px): #here-readout and #pf-readout sit over the 2nd/3rd button rows and intercept taps on
// "Rows from satellite"; #info covers the map attribution. (d) Measured 27 Sept, (local path)
(function () {
  'use strict';
  const MOD_URL = (document.currentScript && document.currentScript.src) || location.href;
  const R = 6371008.8, CIRC = 2 * Math.PI * R;                // MapLibre 4.7.1 sphere, as place-frame.mjs
  const mx = lon => (180 + lon) / 360;
  const my = lat => (180 - (180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + lat * Math.PI / 360)))) / 360;
  const mz = (alt, lat) => alt / (CIRC * Math.cos(lat * Math.PI / 180));
  const MAX_TERRAIN_QUERIES = 300;

  let PF = null;
  import(new URL('../place-frame.mjs', MOD_URL).href).then(m => { PF = m; if (window.SIM) SIM.repaint(); }).catch(() => {});

  function attach() {
    const SIM = window.SIM;
    if (!SIM || !SIM.wire || !SIM.map) return false;
    const map = SIM.map, wire = SIM.wire, blocks = SIM.blocks;
    if (wire.__perf) return true;
    const cache = new Map();            // block -> { gl, buf, src, len, rev, n, ox, oy, oz, gz, r, lat, lon }
    const progInfo = new WeakMap();     // program -> { loc, u }
    let terrainEpoch = 1;
    const stats = { frames: 0, uploads: 0, uploadBytes: 0, draws: 0, culled: 0, lastMs: 0, sumMs: 0, deleted: 0 };
    const mat = new Float32Array(16), planes = new Float64Array(24);

    const bumpTerrain = () => { terrainEpoch++; map.triggerRepaint(); };
    // Re-read heights only when new terrain tiles have arrived (a flag set by the DEM source), on the next 'idle'.
    let demDirty = false;
    map.on('sourcedata', ev => { if (ev.tile && ev.source && ev.source.type === 'raster-dem') demDirty = true; });
    map.on('idle', () => { if (demDirty) { demDirty = false; bumpTerrain(); } });
    map.on('terrain', bumpTerrain);

    // Bring a bare { lon, lat, lines } block up to the overlay's shape (anchor + anchor-relative Mercator buf).
    function ensurePlaced(b) {
      if (b.anchor && b.buf) return true;
      if (!PF || !b.lines) return false;
      const anchor = PF.placeKey(b.lat, b.lon), off = PF.toLocal(anchor, b.lat, b.lon, 0);
      const L = (off.x || off.y) ? b.lines.map(([a, c, d, e, f, g]) => [a + off.x, c + off.y, d, e + off.x, f + off.y, g]) : b.lines;
      b.anchor = anchor; b.buf = PF.wireBuffer(anchor, L);
      return true;
    }

    function entryFor(gl, b) {
      let e = cache.get(b);
      const v = b.buf, rev = b.rev || 0;
      if (e && e.gl === gl && e.src === v && e.len === v.length && e.rev === rev) return e;
      if (!e || e.gl !== gl) { e = { gl, buf: gl.createBuffer(), gzEpoch: 0 }; cache.set(b, e); }
      gl.bindBuffer(gl.ARRAY_BUFFER, e.buf);
      gl.bufferData(gl.ARRAY_BUFFER, v, gl.STATIC_DRAW);
      stats.uploads++; stats.uploadBytes += v.byteLength;
      e.src = v; e.len = v.length; e.rev = rev; e.n = v.length / 3;
      // Bounding sphere radius in Mercator units (vertices are already anchor-relative).
      let r2 = 0; for (let i = 0; i < v.length; i += 3) { const d = v[i] * v[i] + v[i + 1] * v[i + 1] + v[i + 2] * v[i + 2]; if (d > r2) r2 = d; }
      const a = b.anchor; e.lat = a.lat; e.lon = a.lon; e.ox = mx(a.lon); e.oy = my(a.lat);
      e.r = Math.sqrt(r2) + mz(80, a.lat);           // + 80 m of slack for terrain height
      e.gzEpoch = 0;
      return e;
    }

    // Frustum planes from the column-major view-projection matrix (Gribb and Hartmann).
    function extractPlanes(m) {
      const row = i => [m[i], m[4 + i], m[8 + i], m[12 + i]];
      const r0 = row(0), r1 = row(1), r2 = row(2), r3 = row(3);
      const P = [[0, 1], [0, -1], [1, 1], [1, -1], [2, 1], [2, -1]];
      const rows = [r0, r1, r2];
      for (let k = 0; k < 6; k++) {
        const s = P[k][1], rr = rows[P[k][0]];
        let a = r3[0] + s * rr[0], b = r3[1] + s * rr[1], c = r3[2] + s * rr[2], d = r3[3] + s * rr[3];
        const n = Math.hypot(a, b, c) || 1;
        planes[4 * k] = a / n; planes[4 * k + 1] = b / n; planes[4 * k + 2] = c / n; planes[4 * k + 3] = d / n;
      }
    }
    const visible = (x, y, z, r) => {
      for (let k = 0; k < 6; k++) if (planes[4 * k] * x + planes[4 * k + 1] * y + planes[4 * k + 2] * z + planes[4 * k + 3] < -r) return false;
      return true;
    };

    wire.render = function (gl, args) {
      const t0 = performance.now();
      const m = (args && args.defaultProjectionData && args.defaultProjectionData.mainMatrix) || args;
      const pr = this.pr; if (!pr) return;
      let pi = progInfo.get(pr);
      if (!pi) { pi = { loc: gl.getAttribLocation(pr, 'p'), u: gl.getUniformLocation(pr, 'u') }; progInfo.set(pr, pi); }
      gl.useProgram(pr); gl.enableVertexAttribArray(pi.loc);
      extractPlanes(m);
      const hasTerrain = !!(map.getTerrain && map.getTerrain() && map.queryTerrainElevation);
      let q = 0, draws = 0, culled = 0;
      for (let i = 0; i < blocks.length; i++) {
        const b = blocks[i];
        if (!ensurePlaced(b) || !b.buf.length) continue;
        const e = entryFor(gl, b); e.seen = stats.frames;
        if (e.gzEpoch !== terrainEpoch && q < MAX_TERRAIN_QUERIES) {
          e.gz = hasTerrain ? (map.queryTerrainElevation([e.lon, e.lat]) || 0) : 0; e.gzEpoch = terrainEpoch; q++;
          e.oz = mz(e.gz, e.lat);
        }
        const ox = e.ox, oy = e.oy, oz = e.oz || 0;
        if (!visible(ox, oy, oz, e.r)) { culled++; continue; }
        for (let k = 0; k < 4; k++) { mat[k] = m[k]; mat[4 + k] = m[4 + k]; mat[8 + k] = m[8 + k]; mat[12 + k] = m[k] * ox + m[4 + k] * oy + m[8 + k] * oz + m[12 + k]; }
        gl.bindBuffer(gl.ARRAY_BUFFER, e.buf);
        gl.vertexAttribPointer(pi.loc, 3, gl.FLOAT, false, 0, 0);
        gl.uniformMatrix4fv(pi.u, false, mat);
        gl.drawArrays(gl.LINES, 0, e.n); draws++;
      }
      if (q >= MAX_TERRAIN_QUERIES) map.triggerRepaint();   // more heights still to read next frame
      // Sweep buffers of removed blocks (cheap: only when the cache outgrows the list, or every 2 s).
      if (cache.size > blocks.length || stats.frames % 120 === 0) {
        for (const [b, e] of cache) if (e.seen !== stats.frames) { e.gl.deleteBuffer(e.buf); cache.delete(b); stats.deleted++; }
      }
      stats.frames++; stats.draws = draws; stats.culled = culled;
      const dt = performance.now() - t0; stats.lastMs = dt; stats.sumMs += dt;
    };
    wire.__perf = true;
    SIM.perf = {
      stats: () => Object.assign({ buffers: cache.size, blocks: blocks.length, meanRenderMs: stats.frames ? stats.sumMs / stats.frames : 0 }, stats),
      reset: () => { stats.frames = 0; stats.uploads = 0; stats.uploadBytes = 0; stats.sumMs = 0; stats.deleted = 0; },
      touch: b => { b.rev = (b.rev || 0) + 1; map.triggerRepaint(); }          // call after editing b.buf in place
    };
    map.triggerRepaint();
    return true;
  }
  if (!attach()) { let n = 0; const t = setInterval(() => { if (attach() || ++n > 100) clearInterval(t); }, 100); }
})();

Pylons Real

A JavaScript file in GlobalGrid2050 using data from the GridAtlas repository. It makes block (`makeBlock`) and adds layer (`addLayer`).

renderglobalgrid2050 / energy-transition-simulator/202609280014/mod/pylons-real.js · lines 1–165 of 165 · version 2026-09-28 00:14 · Not reached from any entry point (candidate for review) · pattern makeBlock (shared by 2 files)

What it does
It maps its content. Defines 16 functions or classes, including ready, start, kx, dist, towersOf. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
Inputs & outputs
In: data source: gridatlas data. Coordinate systems named: WGS84 / EPSG:4326.
What it achieves
Lattice pylons and sagging conductors on the real GridAtlas lines.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · energy-transition-simulator/202609280014/mod · script
Uses
none found
Used by
none found
Produces
ready, start, kx, dist, towersOf, lattice, half, sq, attach, elev, makeBlock, X
Defines here
ready, start, kx, dist, towersOf, lattice, half, sq, attach, elev, makeBlock, X, refresh, regrade, sh, addLayer
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/202609280014/mod/pylons-real.js:1-165 · blob 1e3d149d96d459e8185c08fc9b8d38f7f6d10480 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
// mod/pylons-real.js - lattice pylons and sagging conductors on the real GridAtlas lines.
// Plain script. Attaches to window.SIM ({ map, ... }) and uses the overlay's place frame (window.__pf.PF), so every
// tower is authored in metres around a 100 m place key and lands on its exact WGS84 position.
// What is real: tower positions = GridAtlas line vertices (lines from OpenStreetMap), with vertices closer than
// MERGE_M merged. What is estimated: towers inserted on long straight runs (typical span), tower shape and height,
// arm lengths, insulator length and conductor sag, all by voltage class. Drawn in its own custom layer:
// one GPU buffer per tower block, uploaded once, reused every frame; hidden below zoom MIN_Z.
(function () {
  'use strict';
  const MIN_Z = 14, MAX_TOWERS = 260, MERGE_M = 60, SEG = 12;
  const GA = 'https://ventusltd.github.io/gridatlas/atlas/releases/202608300453-atlas-v9/data';
  // Estimated geometry by voltage class (GB double-circuit lattice types, typical values, not surveyed):
  // H tower height, base half-width, arm heights (fractions of H, bottom to top), arm half-lengths (m),
  // suspension insulator length (m), typical span (m), catenary parameter a = T/w (m), conductor colour.
  const KV = {
    '400': { H: 50, base: 6.0, armZ: [0.62, 0.77, 0.92], arm: [10.5, 12.0, 9.0], ins: 4.5, span: 360, a: 1500, col: [0.25, 0.5, 1.0] },
    '275': { H: 46, base: 5.5, armZ: [0.62, 0.77, 0.92], arm: [9.5, 11.0, 8.2], ins: 3.4, span: 340, a: 1400, col: [1.0, 0.3, 0.3] },
    '132': { H: 27, base: 3.2, armZ: [0.60, 0.76, 0.92], arm: [4.6, 5.3, 4.1], ins: 1.8, span: 280, a: 1100, col: [0.2, 0.9, 0.4] }
  };
  const TOWER_COL = [0.82, 0.86, 0.9];

  let SIM, map, PF, on = true, btn = null;
  const lines = { };                     // kv -> [{ bbox, coords }]
  const runs = new Map();                // `${kv}:${lineIndex}` -> tower list (built lazily, cached)
  const live = new Map();                // tower id -> block { anchor, lon, lat, gz, buf, nTower, nWire, col }
  let gl = null, prog = null, loc = {}, pending = 0, regrades = 0;

  const ready = () => { SIM = window.SIM; PF = window.__pf && window.__pf.PF; return SIM && SIM.map && PF; };
  (function wait(n) { if (ready()) start(); else if (n < 200) setTimeout(() => wait(n + 1), 100); })(0);

  function start() {
    map = SIM.map;
    if (SIM.addButton) { btn = SIM.addButton('Pylons (real)', () => { on = !on; btn.classList.toggle('on', on); refresh(); }); btn.classList.add('on'); }
    Promise.all(Object.keys(KV).map(kv => fetch(`${GA}/grid_${kv}kv.geojson`).then(r => r.json()).then(j => {
      const L = [];
      for (const f of j.features || []) { const g = f.geometry; if (!g) continue;
        for (const c of g.type === 'LineString' ? [g.coordinates] : g.type === 'MultiLineString' ? g.coordinates : []) {
          let w = 180, s = 90, e = -180, n = -90; for (const [x, y] of c) { if (x < w) w = x; if (x > e) e = x; if (y < s) s = y; if (y > n) n = y; }
          L.push({ bbox: [w, s, e, n], coords: c }); } }   // properties (names) are never read or shown
      lines[kv] = L;
    }).catch(() => { lines[kv] = []; }))).then(() => { addLayer(); refresh(); });
    map.on('moveend', refresh);
    map.on('style.load', () => setTimeout(() => { addLayer(); refresh(); }, 50));
    map.on('idle', () => { if (pending && regrades < 6) { pending = 0; regrades++; regrade(); } });
  }

  // ---- towers along one GridAtlas line: exact vertices, close ones merged, long runs filled at the typical span ----
  const kx = lat => 111320 * Math.cos(lat * Math.PI / 180);
  const dist = (a, b) => Math.hypot((b[0] - a[0]) * kx((a[1] + b[1]) / 2), (b[1] - a[1]) * 111320);
  function towersOf(kv, li) {
    const id = kv + ':' + li; if (runs.has(id)) return runs.get(id);
    const c = lines[kv][li].coords, P = [];
    for (const p of c) { if (!P.length || dist(P[P.length - 1].p, p) >= MERGE_M) P.push({ p, est: false }); }
    if (P.length > 1 && dist(P[P.length - 1].p, c[c.length - 1]) > 1) P[P.length - 1] = { p: c[c.length - 1], est: false };
    const T = [];
    for (let i = 0; i < P.length; i++) {
      T.push(P[i]);
      if (i + 1 < P.length) { const d = dist(P[i].p, P[i + 1].p), n = Math.round(d / KV[kv].span) - 1;
        for (let k = 1; k <= n; k++) { const t = k / (n + 1), a = P[i].p, b = P[i + 1].p; T.push({ p: [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t], est: true }); } }
    }
    const out = T.map((t, i) => ({ id: `${id}:${i}`, kv, lon: t.p[0], lat: t.p[1], est: t.est }));
    for (let i = 0; i < out.length; i++) {           // along-line direction in local metres (bisector at angle towers)
      const t = out[i], dir = [0, 0];
      for (const j of [i - 1, i + 1]) { const o = out[j]; if (!o) continue; const s = j < i ? 1 : -1;
        const dx = (t.lon - o.lon) * kx(t.lat) * s, dy = (t.lat - o.lat) * 111320 * s, l = Math.hypot(dx, dy) || 1; dir[0] += dx / l; dir[1] += dy / l; }
      const l = Math.hypot(dir[0], dir[1]) || 1; t.u = [dir[0] / l, dir[1] / l]; t.next = out[i + 1] || null;
    }
    runs.set(id, out); return out;
  }

  // ---- geometry in tower-frame metres: (along, left, up) ----
  function lattice(g) {
    const L = [], H = g.H, b = g.base, zw = g.armZ[0] * H - 2, w = b * 0.32, zt = g.armZ[2] * H + 1, wt = w * 0.8;
    const half = z => z <= zw ? b + (w - b) * z / zw : w + (wt - w) * (z - zw) / (zt - zw);
    const lv = [0, zw * 0.3, zw * 0.58, zw * 0.8, zw, ...g.armZ.map(f => f * H), zt];
    const sq = (z) => { const h = half(z); return [[-h, -h, z], [h, -h, z], [h, h, z], [-h, h, z]]; };
    for (let k = 0; k < lv.length; k++) {
      const A = sq(lv[k]);
      for (let i = 0; i < 4; i++) { const j = (i + 1) % 4; if (k > 0) L.push([...A[i], ...A[j]]); }
      if (k + 1 < lv.length) { const B = sq(lv[k + 1]);
        for (let i = 0; i < 4; i++) { const j = (i + 1) % 4; L.push([...A[i], ...B[i]]);
          if (lv[k] < zw) L.push([...A[i], ...B[j]], [...A[j], ...B[i]]); else L.push([...A[i], ...B[j]]); } }
    }
    const top = sq(zt); for (const p of top) L.push([...p, 0, 0, H]);          // earth-wire peak
    g.armZ.forEach((f, k) => { const z = f * H, h = half(z), a = g.arm[k];     // crossarms: two chords to the tip, both sides
      for (const s of [-1, 1]) { const tip = [0, s * a, z];
        L.push([-h, s * h, z, ...tip], [h, s * h, z, ...tip], [-h, s * h, z - 2.2, ...tip], [h, s * h, z - 2.2, ...tip], [...tip, 0, s * a, z - g.ins]); } });
    return L;
  }
  const attach = g => { const P = []; g.armZ.forEach((f, k) => { for (const s of [-1, 1]) P.push([s * g.arm[k], f * g.H - g.ins]); }); P.push([0, g.H]); return P; };

  function elev(lon, lat) { const e = map.queryTerrainElevation ? map.queryTerrainElevation([lon, lat]) : 0; if (e == null) pending = 1; return e || 0; }

  function makeBlock(t) {
    const g = KV[t.kv], an = PF.placeKey(t.lat, t.lon), o = PF.toLocal(an, t.lat, t.lon, 0);
    const u = t.u, v = [-u[1], u[0]], gz = elev(t.lon, t.lat);
    const X = (a, l, z, base = o, uu = u, vv = v, dz = 0) => [base.x + uu[0] * a + vv[0] * l, base.y + uu[1] * a + vv[1] * l, z + dz];
    const T = lattice(g).map(s => [...X(s[0], s[1], s[2]), ...X(s[3], s[4], s[5])]);
    const W = [];
    if (t.next) {                                    // conductors to the next tower: 3 phases per side + earth wire
      const n = t.next, q = PF.toLocal(an, n.lat, n.lon, 0), nv = [-n.u[1], n.u[0]], dz = elev(n.lon, n.lat) - gz;
      const span = Math.hypot(q.x - o.x, q.y - o.y), sag = span * span / (8 * g.a);
      for (const [l, z] of attach(g)) {
        const A = X(0, l, z), B = X(0, l, z, q, n.u, nv, dz); let prev = A;
        for (let k = 1; k <= SEG; k++) { const s = k / SEG, p = [A[0] + (B[0] - A[0]) * s, A[1] + (B[1] - A[1]) * s, A[2] + (B[2] - A[2]) * s - 4 * sag * s * (1 - s) * (l ? 1 : 0.7)];
          W.push([...prev, ...p]); prev = p; }
      }
    }
    const data = PF.wireBuffer(an, T.concat(W)), buf = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, buf); gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);   // once
    return { pylonsReal: true, lon: t.lon, lat: t.lat, anchor: an, gz, buf, nTower: T.length * 2, nWire: W.length * 2, col: g.col, t };
  }

  function refresh() {
    if (!map || !gl) return;
    const want = new Set();
    if (on && map.getZoom() >= MIN_Z) {
      const b = map.getBounds(), c = map.getCenter(), mx = (b.getEast() - b.getWest()) * 0.25, my = (b.getNorth() - b.getSouth()) * 0.25;
      const W = b.getWest() - mx, E = b.getEast() + mx, S = b.getSouth() - my, N = b.getNorth() + my, cand = [];
      for (const kv of Object.keys(lines)) lines[kv].forEach((ln, li) => {
        const [w, s, e, n] = ln.bbox; if (e < W || w > E || n < S || s > N) return;
        for (const t of towersOf(kv, li)) if (t.lon >= W && t.lon <= E && t.lat >= S && t.lat <= N) cand.push([dist([c.lng, c.lat], [t.lon, t.lat]), t]);
      });
      cand.sort((a, b) => a[0] - b[0]);
      for (const [, t] of cand.slice(0, MAX_TOWERS)) want.add(t.id), live.has(t.id) || live.set(t.id, makeBlock(t));
    }
    for (const [id, bk] of live) if (!want.has(id)) { gl.deleteBuffer(bk.buf); live.delete(id); }
    if (SIM.info && on && live.size) SIM.info(`Pylons: ${live.size} at GridAtlas line vertices (© OpenStreetMap). Heights, arms, sag and infill towers are estimates.`);
    map.triggerRepaint();
  }
  // Terrain arrives after the first build: re-grade the blocks built on missing heights (their spans too).
  function regrade() { for (const [id, bk] of live) { gl.deleteBuffer(bk.buf); live.delete(id); } refresh(); }

  const layer = {
    id: 'pylons-real', type: 'custom', renderingMode: '3d',
    onAdd(m, g) {
      if (gl === g && prog) return; gl = g; live.clear();
      const sh = (t, s) => { const o = g.createShader(t); g.shaderSource(o, s); g.compileShader(o); return o; };
      prog = g.createProgram();
      g.attachShader(prog, sh(g.VERTEX_SHADER, 'uniform mat4 u; attribute vec3 p; void main(){ gl_Position = u * vec4(p, 1.0); }'));
      g.attachShader(prog, sh(g.FRAGMENT_SHADER, 'precision mediump float; uniform vec3 c; void main(){ gl_FragColor = vec4(c, 1.0); }'));
      g.linkProgram(prog); loc = { p: g.getAttribLocation(prog, 'p'), u: g.getUniformLocation(prog, 'u'), c: g.getUniformLocation(prog, 'c') };
    },
    render(g, args) {
      if (!on || map.getZoom() < MIN_Z || !live.size) return;
      const m = (args && args.defaultProjectionData && args.defaultProjectionData.mainMatrix) || args, M = new Float32Array(16);
      g.useProgram(prog); g.enableVertexAttribArray(loc.p);
      for (const bk of live.values()) {
        const a = bk.anchor, o = PF.toMercator(a.lat, a.lon, bk.gz);
        for (let k = 0; k < 16; k++) M[k] = m[k];
        for (let k = 0; k < 4; k++) M[12 + k] = m[k] * o.x + m[4 + k] * o.y + m[8 + k] * o.z + m[12 + k];
        g.uniformMatrix4fv(loc.u, false, M);
        g.bindBuffer(g.ARRAY_BUFFER, bk.buf); g.vertexAttribPointer(loc.p, 3, g.FLOAT, false, 0, 0);
        g.uniform3fv(loc.c, TOWER_COL); g.drawArrays(g.LINES, 0, bk.nTower);
        if (bk.nWire) { g.uniform3fv(loc.c, bk.col); g.drawArrays(g.LINES, bk.nTower, bk.nWire); }
      }
    }
  };
  function addLayer() {
    if (!map.isStyleLoaded()) { map.once('idle', () => { addLayer(); refresh(); }); return; }
    try { if (!map.getLayer('pylons-real')) map.addLayer(layer); } catch (e) { map.once('idle', () => { addLayer(); refresh(); }); }
  }

  window.__pylonsReal = { live, refresh, count: () => live.size, towersOf, KV };
})();

Overlay

A map page in GlobalGrid2050 that maps grid substations, DEM and solar, using OSTN15 and Helmert, and uses data from OpenStreetMap (Overpass) and the GridAtlas repository. Published at https://globalgrid2050.com/energy-transition-simulator/202609280014/overlay.html.

geodesyglobalgrid2050 / energy-transition-simulator/202609280014/overlay.html · lines 1–300 of 300 · version 2026-09-28 00:14 · Entry point · pattern buildPylons (shared by 2 files)

What it does
It maps grid substations, DEM, solar and LiDAR terrain. Defines 24 functions or classes, including placed, withAnchor, addGrid, block, c. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: solar, LiDAR terrain.
Inputs & outputs
In: data source: OpenStreetMap (Overpass); data source: gridatlas data; JSON file style.json; GeoJSON file grid_substations.geojson; JSON file index.json. Out: web page; interactive map; canvas drawing. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326.
Downstream impact
Used directly by 7 files: SatNav — Scope Page (satnav, https://ventusltd.github.io/satnav/scope/); GlobalGrid2050 — Energy Transition Simulator Page (globalgrid2050, https://globalgrid2050.com/energy-transition-simulator/202609280014/); GlobalGrid2050 — Energy Transition Simulator Page (globalgrid2050, https://globalgrid2050.com/energy-transition-simulator/); Energy Transition Simulator — Latest Page (globalgrid2050, https://globalgrid2050.com/energy-transition-simulator/latest/); and 3 more. Reached from 16 other entry points, including Kuiper Belt — See Through Page (kuiper-belt, https://ventusltd.github.io/kuiper-belt/see-through/202610050513/); Lesson (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050609/lesson.html); Menu (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050354/menu.html). It is itself an entry point, published at https://globalgrid2050.com/energy-transition-simulator/202609280014/overlay.html.
What it achieves
It adds grid (`addGrid`), sets mode (`setMode`) and loads rows (`loadRows`). Defines `placed`, `withAnchor`, `addGrid` and 17 more. It reads `mod/index.json`. It responds to keydown, keyup and pointerdown events.
Why it matters
Loaded by the Scope page in SatNav at https://ventusltd.github.io/satnav/scope/ and 3 other pages. Also imported by Descent, from Kuiper Belt. Checked by Test Grid Explorer Entry.
Application
globalgrid2050 · energy-transition-simulator/202609280014 · page
Uses
Place Frame (import), Bng (import), OSTN15 (import), https://cdn.jsdelivr.net/npm/maplibre-gl@4.7.1/dist/maplibre-gl.css, https://cdn.jsdelivr.net/npm/maplibre-gl@4.7.1/dist/maplibre-gl.js
Used by
linked from SatNav — Scope Page (link), linked from GlobalGrid2050 — Energy Transition Simulator Page (link), linked from GlobalGrid2050 — Energy Transition Simulator Page (link), linked from Energy Transition Simulator — Latest Page (link), named by URL in Descent (estate URL), named by URL in Descent (estate URL), named by URL in Test Grid Explorer Entry (estate URL)
Produces
placed, withAnchor, addGrid, block, c, sh, ground, setMode, joyAt, tick, loadRows, h
Defines here
placed, withAnchor, addGrid, block, c, sh, ground, setMode, joyAt, tick, loadRows, h, tower, buildPylons, readout, pfLine, pfReadout, render, lonLatToTile, tileToLonLat, loadImg, detectRows, dark, on
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/202609280014/overlay.html:1-300 · blob 8544e510dfc617181d662659c177c5ef9c7d5e83 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Simulator overlay</title>
<link href="https://cdn.jsdelivr.net/npm/maplibre-gl@4.7.1/dist/maplibre-gl.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/maplibre-gl@4.7.1/dist/maplibre-gl.js"></script>
<style>
  html,body,#map{margin:0;height:100%;background:#000}
  #bar{position:absolute;left:8px;top:8px;z-index:2;display:flex;gap:6px;flex-wrap:wrap}
  #bar button{font:14px sans-serif;padding:10px 12px;border-radius:6px;border:1px solid #456;background:#0b1220;color:#dfe;min-height:44px}
  #bar button.on{background:#1d4ed8}
  #info{position:absolute;left:8px;bottom:28px;z-index:2;font:13px sans-serif;color:#dfe;background:rgba(0,0,0,.6);padding:6px 8px;border-radius:6px}
  #joy{position:absolute;right:24px;bottom:40px;z-index:3;width:120px;height:120px;border-radius:50%;background:rgba(255,255,255,.08);border:1px solid rgba(255,255,255,.3);touch-action:none}
  #knob{position:absolute;left:40px;top:40px;width:40px;height:40px;border-radius:50%;background:rgba(160,220,255,.6)}
</style></head><body>
<div id="map"></div>
<div id="bar"><button id="sat" class="on">Satellite</button><button id="dark">Dark</button><button id="wire">Wire</button><button id="tilt">3D tilt</button><button id="here">Build here</button><button id="survey">Survey</button><button id="rows">Solar rows</button><button id="detect">Rows from satellite</button><button id="pylons">Pylons</button><button id="walk">Walk</button><button id="drone">Dr  … [line shortened here: 589 characters; full line on GitHub]
<div id="joy"><div id="knob"></div></div><div id="here-readout" style="position:absolute;right:8px;top:62px;z-index:2;font:13px monospace;color:#dfe;background:rgba(0,0,0,.65);padding:6px 8px;border-radius:6px"></div><div id="pf-readout" style="position:absolute;right:8px;top:100px;z-index:2;font:12px monospace;color:#dfe;background:rgba(0,0,0,.7);padding:6px 8px;border-radius:6px;white-space:pre"  … [line shortened here: 777 characters; full line on GitHub]
<script type="module">
// ONE coordinate system: every wireframe object is authored in metres around a place key (100 m lattice) and
// turned into Mercator by place-frame.mjs (WGS84 ellipsoid). Inside GB the world's own bng.mjs + OSTN15 give the grid ref.
import * as PF from './place-frame.mjs';
import * as BNG from './world/bng.mjs';
import { createOstn15, etrsToBng, bngToEtrs } from './world/ostn15.mjs';
const OSTN = createOstn15();
PF.useWorld(BNG, { blocks: OSTN.blocks, etrsToBng, bngToEtrs });
// Place lines (metres around lon/lat) on the lattice: anchor = placeKey(centre); the lines shift by the centre's
// metres from the anchor, so the object lands where asked and the key is the anchor. pre=true: lines already around the anchor.
function placed(lon, lat, lines, extra = {}, pre = false) {
  const anchor = PF.placeKey(lat, lon), off = pre ? { x: 0, y: 0 } : PF.toLocal(anchor, lat, lon, 0);
  const L = off.x || off.y ? lines.map(([a, b, c, d, e, f]) => [a + off.x, b + off.y, c, d + off.x, e + off.y, f]) : lines;
  return { lon, lat, anchor, lines: L, buf: PF.wireBuffer(anchor, L), ...extra };
}
// Anchor-relative float32 vertices; the anchor's Mercator point (float64) goes into the matrix: m * T(o).
function withAnchor(m, o) {
  const r = Array.from(m);
  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];
  return new Float32Array(r);
}
// Proof: GridAtlas is the ground (its satellite and dark basemaps, its grid layers), and the 3D wireframe is drawn
// INSIDE the map's own camera as a custom WebGL layer, so it stays fixed to real coordinates when the map
// pans, zooms, tilts or rotates. Positions are in metres around a local origin, turned into Mercator units
// with the map's own scale at that latitude.
const SAT = { type: 'raster', tiles: ['https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}'], tileSize: 256, maxzoom: 17, attribution: 'Imagery: Esri, Maxar, Earthstar Geographics · Rows © OpenStreetMap contributors, ODbL' };
const GA = 'https://ventusltd.github.io/gridatlas/atlas/releases/202608300453-atlas-v9/data';
const FADE = { 'raster-opacity': 1 };
const DEM = { type: 'raster-dem', tiles: ['https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png'], tileSize: 256, encoding: 'terrarium', maxzoom: 15, attribution: 'Terrain: AWS Terrain Tiles (open)' };
const DARK = 'https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json';
const q = new URLSearchParams(location.search);
const start = [Number(q.get('lon') ?? -1.78), Number(q.get('lat') ?? 51.215)];
const map = new maplibregl.Map({ container: 'map', center: start, zoom: 15, pitch: 55, bearing: -20, maxPitch: 85, maxZoom: 20,
  style: { version: 8, sources: { sat: SAT }, layers: [{ id: 'sat', type: 'raster', source: 'sat', paint: FADE }] }, antialias: true });
map.addControl(new maplibregl.NavigationControl({ visualizePitch: true }));

const GRID = [['400', '#0054ff', 3], ['275', '#ff0000', 2.5], ['132', '#00b050', 2]];
function addGrid() {
  for (const [kv, color, w] of GRID) {
    if (map.getSource('g' + kv)) continue;
    map.addSource('g' + kv, { type: 'geojson', data: `${GA}/grid_${kv}kv.geojson` });
    map.addLayer({ id: 'g' + kv, type: 'line', source: 'g' + kv, paint: { 'line-color': color, 'line-width': w, 'line-opacity': 0.9 } });
  }
  if (!map.getSource('subs')) {
    map.addSource('subs', { type: 'geojson', data: `${GA}/grid_substations.geojson` });
    map.addLayer({ id: 'subs', type: 'circle', source: 'subs', paint: { 'circle-radius': 5, 'circle-color': '#ffd400', 'circle-stroke-color': '#000', 'circle-stroke-width': 1 } });
  }
  if (!map.getLayer('wire')) map.addLayer(wire);
}

// The 3D wireframe layer: blocks of lines, each in local metres around its own lon/lat anchor.
const blocks = [];
function block(lon, lat) {
  // A 200 m x 120 m solar block: table rows every 10 m, 2.5 m tall at the back, plus a compound cube.
  const L = [], row = (x0, x1, y, h) => { L.push([x0, y, 0, x1, y, 0], [x0, y, 0, x0, y + 4, h], [x1, y, 0, x1, y + 4, h], [x0, y + 4, h, x1, y + 4, h]); };
  for (let y = -60; y <= 56; y += 10) row(-100, 100, y, 2.5);
  const c = (x, y, s, h) => { const p = [[x, y], [x + s, y], [x + s, y + s], [x, y + s]]; for (let i = 0; i < 4; i++) { const a = p[i], b = p[(i + 1) % 4]; L.push([a[0], a[1], 0, b[0], b[1], 0], [a[0], a[1], h, b[0], b[1], h], [a[0], a[1], 0, a[0], a[1], h]); } };
  c(110, -10, 20, 6);
  const b = placed(lon, lat, L, { built: true }); blocks.push(b); lastBuilt = b; pfReadout();
  map.triggerRepaint(); return b;
}
const wire = {
  id: 'wire', type: 'custom', renderingMode: '3d',
  onAdd(m, gl) {
    const vs = `uniform mat4 u; attribute vec3 p; void main(){ gl_Position = u * vec4(p, 1.0); }`;
    const fs = `precision mediump float; void main(){ gl_FragColor = vec4(0.55, 0.9, 1.0, 1.0); }`;
    const sh = (t, s) => { const o = gl.createShader(t); gl.shaderSource(o, s); gl.compileShader(o); return o; };
    this.pr = gl.createProgram(); gl.attachShader(this.pr, sh(gl.VERTEX_SHADER, vs)); gl.attachShader(this.pr, sh(gl.FRAGMENT_SHADER, fs)); gl.linkProgram(this.pr);
    this.buf = gl.createBuffer();
  },
  render(gl, args) {
    const m = args.defaultProjectionData?.mainMatrix || args;
    gl.useProgram(this.pr);
    for (const b of blocks) {
      const a = b.anchor, gz = (map.queryTerrainElevation && map.queryTerrainElevation([a.lon, a.lat])) || 0;
      const o = PF.toMercator(a.lat, a.lon, gz), v = b.buf;
      gl.bindBuffer(gl.ARRAY_BUFFER, this.buf); gl.bufferData(gl.ARRAY_BUFFER, v, gl.DYNAMIC_DRAW);
      const loc = gl.getAttribLocation(this.pr, 'p'); gl.enableVertexAttribArray(loc); gl.vertexAttribPointer(loc, 3, gl.FLOAT, false, 0, 0);
      gl.uniformMatrix4fv(gl.getUniformLocation(this.pr, 'u'), false, withAnchor(m, o));
      gl.drawArrays(gl.LINES, 0, v.length / 3);
    }
  }
};
// Zoomed in: a wireframe ground of 10 m squares, 600 m across, anchored at a fixed 100 m national-style
// lattice so it never swims as you move (drawn in real metres; LiDAR heights plug in here next).
let groundKey = '', survey = false;
function ground() {
  const z = map.getZoom(); const i = blocks.findIndex(b => b.ground);
  if (!survey || z < 16.5) { if (i >= 0) { blocks.splice(i, 1); groundKey = ''; map.triggerRepaint(); } return; }
  const c = map.getCenter(), an = PF.placeKey(c.lat, c.lng), key = an.key; if (key === groundKey) return; groundKey = key;
  const L = []; for (let k = -300; k <= 300; k += 10) { L.push([-300, k, 0.2, 300, k, 0.2], [k, -300, 0.2, k, 300, 0.2]); }
  if (i >= 0) blocks.splice(i, 1); blocks.unshift(placed(an.lon, an.lat, L, { ground: true }, true)); map.triggerRepaint();
}

// ---- Walk and fly over the real map: fast, virtual movement (owner). ----
const MODES = { walk: { pitch: 80, zoom: 18.5, speed: 10 }, drone: { pitch: 60, zoom: 16.5, speed: 60 }, map: { pitch: 0, zoom: 14, speed: 300 } };
let mode = 'map', boost = 1; const keys = new Set(), joy = { x: 0, y: 0 };
function setMode(m) { mode = m; const c = MODES[m]; map.easeTo({ pitch: c.pitch, zoom: c.zoom, duration: 900 });
  for (const b of ['walk', 'drone', 'map2d']) document.getElementById(b).classList.toggle('on', b === (m === 'map' ? 'map2d' : m)); }
document.getElementById('walk').onclick = () => setMode('walk');
document.getElementById('drone').onclick = () => setMode('drone');
document.getElementById('map2d').onclick = () => setMode('map');
addEventListener('keydown', e => { if (e.target.tagName === 'INPUT') return; keys.add(e.key.toLowerCase()); if (e.key === 'Shift') boost = 3;
  if (e.key === '1') setMode('walk'); if (e.key === '2') setMode('drone'); if (e.key === '3') setMode('map'); });
addEventListener('keyup', e => { keys.delete(e.key.toLowerCase()); if (e.key === 'Shift') boost = 1; });
const joyEl = document.getElementById('joy'), knob = document.getElementById('knob');
function joyAt(e) { const r = joyEl.getBoundingClientRect(); let x = (e.clientX - r.left - 60) / 50, y = (e.clientY - r.top - 60) / 50; const d = Math.hypot(x, y); if (d > 1) { x /= d; y /= d; }
  joy.x = x; joy.y = y; knob.style.left = (40 + x * 40) + 'px'; knob.style.top = (40 + y * 40) + 'px'; }
joyEl.addEventListener('pointerdown', e => { joyEl.setPointerCapture(e.pointerId); joyAt(e); });
joyEl.addEventListener('pointermove', e => { if (e.buttons) joyAt(e); });
joyEl.addEventListener('pointerup', () => { joy.x = joy.y = 0; knob.style.left = knob.style.top = '40px'; });
let last = performance.now();
function tick(t) {
  const dt = Math.min(0.1, (t - last) / 1000); last = t;
  const f = (keys.has('w') || keys.has('arrowup') ? 1 : 0) - (keys.has('s') || keys.has('arrowdown') ? 1 : 0) - joy.y;
  const r = (keys.has('d') ? 1 : 0) - (keys.has('a') ? 1 : 0);
  const turn = (keys.has('e') || keys.has('arrowright') ? 1 : 0) - (keys.has('q') || keys.has('arrowleft') ? 1 : 0) + joy.x;
  const tilt = (keys.has('r') ? 1 : 0) - (keys.has('f') ? 1 : 0);
  if (f || r || turn || tilt) {
    const sp = MODES[mode].speed * boost, b = map.getBearing() * Math.PI / 180, c = map.getCenter();
    const dn = (f * Math.cos(b) - r * Math.sin(b)) * sp * dt, de = (f * Math.sin(b) + r * Math.cos(b)) * sp * dt;
    const lat = c.lat + dn / 111320, lng = c.lng + de / (111320 * Math.cos(c.lat * Math.PI / 180));
    map.jumpTo({ center: [lng, lat], bearing: map.getBearing() + turn * 60 * dt, pitch: Math.max(0, Math.min(85, map.getPitch() + tilt * 30 * dt)) });
  }
  document.getElementById('spd').textContent = `${mode} · ${Math.round(MODES[mode].speed * boost)} m/s · ${(MODES[mode].speed * boost * 3.6).toFixed(0)} km/h`;
  requestAnimationFrame(tick);
}
requestAnimationFrame(tick);


// ---- Real solar rows from OpenStreetMap (ODbL), stood up as 3D wireframe tables on the map. ----
// One polite Overpass request per press, for the area in view. Each mapped panel outline becomes a table:
// its outline at 1 m, a top edge at 2.6 m on the northern side, and legs at the corners. No names shown.
const M_LAT = 111320;
async function loadRows() {
  const bt = document.getElementById('rows'); bt.textContent = 'Loading rows...';
  const b = map.getBounds(), bbox = [b.getSouth(), b.getWest(), b.getNorth(), b.getEast()].map(v => v.toFixed(5)).join(',');
  const q = `[out:json][timeout:25];(way["power"="generator"]["generator:source"="solar"](${bbox});way["generator:method"="photovoltaic"](${bbox});way["power"="plant"]["plant:source"="solar"](${bbox}););out geom 4000;`;
  try {
    const r = await fetch('https://overpass-api.de/api/interpreter', { method: 'POST', body: 'data=' + encodeURIComponent(q) });
    const j = await r.json(); let n = 0;
    for (const w of j.elements || []) {
      const g = w.geometry; if (!g || g.length < 3) continue;
      const plant = w.tags && w.tags.power === 'plant';
      const lat0 = g[0].lat, lon0 = g[0].lon, an = PF.placeKey(lat0, lon0);
      const P = g.map(p => { const q = PF.toLocal(an, p.lat, p.lon, 0); return [q.x, q.y]; });
      const L = [];
      if (plant) { for (let i = 0; i + 1 < P.length; i++) L.push([P[i][0], P[i][1], 0.3, P[i + 1][0], P[i + 1][1], 0.3]); }
      else {
        let yMax = -1e9, yMin = 1e9; for (const p of P) { yMax = Math.max(yMax, p[1]); yMin = Math.min(yMin, p[1]); }
        const h = y => 1.0 + 1.6 * (y - yMin) / Math.max(0.5, yMax - yMin);   // higher at the north (back) edge
        for (let i = 0; i + 1 < P.length; i++) { const a = P[i], c = P[i + 1]; L.push([a[0], a[1], h(a[1]), c[0], c[1], h(c[1])], [a[0], a[1], 0, a[0], a[1], h(a[1])]); }
      }
      blocks.push(placed(an.lon, an.lat, L, { plant }, true)); n++;
    }
    bt.textContent = n ? `Solar rows (${n})` : 'No rows mapped here';
    map.triggerRepaint();
  } catch (e) { bt.textContent = 'Rows: try again'; }
}
document.getElementById('rows').onclick = loadRows;


// ---- Pylons from GridAtlas's own line vertices (exact coordinates), stood up as 3D wireframe towers,
// with conductors at arm height. Heights are illustrative by voltage class. Only lines in view, zoom 14+.
const PYLON_H = { '400': 50, '275': 45, '132': 27 };
let pylonsOn = false;
function tower(h) { const L = [], b = h * 0.12, t = h * 0.03, arm = h * 0.8, w = h * 0.3;
  const legs = [[-b, -b], [b, -b], [b, b], [-b, b]], top = [[-t, -t], [t, -t], [t, t], [-t, t]];
  for (let i = 0; i < 4; i++) { L.push([legs[i][0], legs[i][1], 0, top[i][0], top[i][1], h]); const j = (i + 1) % 4; L.push([legs[i][0], legs[i][1], 0, legs[j][0], legs[j][1], 0]); }
  L.push([-w, 0, arm, w, 0, arm], [-w * 0.8, 0, arm - h * 0.15, w * 0.8, 0, arm - h * 0.15]);
  return L; }
function buildPylons() {
  for (let i = blocks.length - 1; i >= 0; i--) if (blocks[i].pylon) blocks.splice(i, 1);
  if (!pylonsOn || map.getZoom() < 14) { map.triggerRepaint(); return 0; }
  const b = map.getBounds(); let n = 0;
  for (const kv of Object.keys(PYLON_H)) {
    if (!map.getSource('g' + kv)) continue;
    const h = PYLON_H[kv], seen = new Set();
    for (const f of map.querySourceFeatures('g' + kv)) {
      const lines = f.geometry.type === 'LineString' ? [f.geometry.coordinates] : f.geometry.coordinates;
      for (const line of lines) for (let i = 0; i < line.length; i++) {
        const [lon, lat] = line[i]; if (!b.contains([lon, lat])) continue;
        const key = lon.toFixed(6) + lat.toFixed(6); if (seen.has(key)) continue; seen.add(key);
        const L = tower(h);
        if (i + 1 < line.length) { const [lon2, lat2] = line[i + 1], q = PF.toLocal(PF.placeKey(lat, lon), lat2, lon2, 0), q0 = PF.toLocal(PF.placeKey(lat, lon), lat, lon, 0);
          const dx = q.x - q0.x, dy = q.y - q0.y; if (Math.hypot(dx, dy) < 800) for (const o of [-h * 0.3, h * 0.3]) L.push([o, 0, h * 0.8, dx + o, dy, h * 0.8]); }
        blocks.push(placed(lon, lat, L, { pylon: true })); n++; if (n > 600) break;
      }
    }
  }
  map.triggerRepaint(); return n;
}
document.getElementById('pylons').onclick = e => { pylonsOn = !pylonsOn; e.target.classList.toggle('on', pylonsOn); const n = buildPylons(); e.target.textContent = pylonsOn ? `Pylons (${n})` : 'Pylons'; };
map.on('moveend', () => { if (pylonsOn) { const n = buildPylons(); document.getElementById('pylons').textContent = `Pylons (${n})`; } });
// Exact position readout: the map centre (where you stand), from GridAtlas's own coordinates.
function readout() { const c = map.getCenter(); document.getElementById('here-readout').textContent = `${c.lat.toFixed(6)}, ${c.lng.toFixed(6)}  z${map.getZoom().toFixed(1)}  heading ${Math.round((map.getBearing() + 360) % 360)}°`; }
map.on('move', readout); map.on('load', readout);
// Place-frame readout: the key, lat/lon, National Grid ref (GB) and the OSTN15 correction applied (Helmert -> OSTN15).
let lastBuilt = null;
function pfLine(tag, lat, lon) {
  const a = PF.placeKey(lat, lon); let s = `${tag} ${a.key}  ${lat.toFixed(6)}, ${lon.toFixed(6)}`;
  const t = PF.toBng(lat, lon);
  if (t.e >= 0 && t.e < 700000 && t.n >= 0 && t.n < 1300000 && lat > 49 && lat < 61.5 && lon > -9 && lon < 2.5)
    s += `
  BNG ${BNG.gridRef(t.e, t.n, 10)}  (${t.engine}${t.gapToOstn15 != null ? `, OSTN15 correction ${t.gapToOstn15.toFixed(2)} m` : ', OSTN15 not loaded'})`;
  else s += `
  outside GB: no National Grid, WGS84 place frame only`;
  return s;
}
function pfReadout() {
  const c = map.getCenter(); OSTN.need(c.lat, c.lng).then(ok => { if (ok) render(); });
  if (lastBuilt) OSTN.need(lastBuilt.lat, lastBuilt.lon);
  const render = () => { document.getElementById('pf-readout').textContent = pfLine('centre', c.lat, c.lng) + (lastBuilt ? `
` + pfLine('block ', lastBuilt.lat, lastBuilt.lon) + `
  anchor ${lastBuilt.anchor.lat.toFixed(7)}, ${lastBuilt.anchor.lon.toFixed(7)}` : ''); };
  render();
}
map.on('moveend', pfReadout); map.on('load', pfReadout);
// Test hooks (headless proof): build a block at lon/lat; read placed blocks.
window.__pf = { PF, build: (lon, lat) => { const b = block(lon, lat); return { key: b.anchor.key, lat: b.anchor.lat, lon: b.anchor.lon }; }, blocks: () => blocks.filter(b => b.built).map(b => ({ key: b.anchor.key, lon: b.lon, lat: b.lat })), map };


// ---- Procedural rows from the satellite itself (the owner's logic): read the imagery around you, find the dark
// panel pixels, and stand them up as 3D wireframe tables where they are. Estimated from satellite, not measured.
const TILE_URL = SAT.tiles[0];
function lonLatToTile(lon, lat, z) { const n = 2 ** z, r = lat * Math.PI / 180;
  return [(lon + 180) / 360 * n, (1 - Math.log(Math.tan(r) + 1 / Math.cos(r)) / Math.PI) / 2 * n]; }
function tileToLonLat(x, y, z) { const n = 2 ** z, lon = x / n * 360 - 180, lat = Math.atan(Math.sinh(Math.PI * (1 - 2 * y / n))) * 180 / Math.PI; return [lon, lat]; }
const loadImg = u => new Promise((ok, no) => { const im = new Image(); im.crossOrigin = 'anonymous'; im.onload = () => ok(im); im.onerror = no; im.src = u; });
async function detectRows() {
  const bt = document.getElementById('detect'); bt.textContent = 'Reading satellite...';
  for (let i = blocks.length - 1; i >= 0; i--) if (blocks[i].sat) blocks.splice(i, 1);
  const Z = 17, c = map.getCenter(), [tx, ty] = lonLatToTile(c.lng, c.lat, Z), x0 = Math.floor(tx) - 1, y0 = Math.floor(ty) - 1;
  const cv = document.createElement('canvas'); cv.width = cv.height = 768; const g = cv.getContext('2d', { willReadFrequently: true });
  try {
    await Promise.all([0, 1, 2].flatMap(j => [0, 1, 2].map(i => loadImg(TILE_URL.replace('{z}', Z).replace('{x}', x0 + i).replace('{y}', y0 + j)).then(im => g.drawImage(im, i * 256, j * 256)))));
  } catch (e) { bt.textContent = 'Satellite read failed'; return; }
  const d = g.getImageData(0, 0, 768, 768).data;
  const dark = (px, py) => { const k = (py * 768 + px) * 4, r = d[k], gg = d[k + 1], b = d[k + 2]; const lum = 0.3 * r + 0.59 * gg + 0.11 * b; return lum < 60 && b >= r - 6; };
  const [lon0, lat0] = tileToLonLat(x0, y0, Z), kx = 111320 * Math.cos(c.lat * Math.PI / 180);
  const mpp = (tileToLonLat(x0 + 1, y0, Z)[0] - lon0) * kx / 256;   // metres per pixel east-west
  const L = []; let n = 0; const an = PF.placeKey(c.lat, c.lng);
  for (let py = 0; py < 768; py += 3) {           // sample every third pixel row (about 2 m)
    let run = -1;
    for (let px = 0; px <= 768; px++) {
      const on = px < 768 && dark(px, py);
      if (on && run < 0) run = px;
      if (!on && run >= 0) { if (px - run >= 4) {
          const [aLon, aLat] = tileToLonLat(x0 + run / 256, y0 + py / 256, Z), [bLon, bLat] = tileToLonLat(x0 + px / 256, y0 + py / 256, Z);
          const A0 = PF.toLocal(an, aLat, aLon, 0), B0 = PF.toLocal(an, bLat, bLon, 0), ax = A0.x, ay = A0.y, bx = B0.x, by = B0.y;
          L.push([ax, ay, 2.2, bx, by, 2.2], [ax, ay, 0, ax, ay, 2.2], [bx, by, 0, bx, by, 2.2]); n++; }
        run = -1; }
    }
  }
  blocks.push(placed(an.lon, an.lat, L, { sat: true }, true)); map.triggerRepaint();
  bt.textContent = `Rows from satellite (${n})`;
  document.getElementById('info').textContent = `Rows estimated from satellite imagery (not measured): ${n} panel runs over about ${Math.round(768 * mpp)} m square around you. Walk (1) to walk between them.`;
}
document.getElementById('detect').onclick = detectRows;


// ---- Plug-in API for modules in prototype/mod/*.js (each attaches to window.SIM). ----
window.SIM = {
  map, blocks, wire,
  addBlock(b) { blocks.push(b); map.triggerRepaint(); return b; },
  removeWhere(fn) { for (let i = blocks.length - 1; i >= 0; i--) if (fn(blocks[i])) blocks.splice(i, 1); map.triggerRepaint(); },
  repaint() { map.triggerRepaint(); },
  info(t) { document.getElementById('info').textContent = t; },
  addButton(label, onclick) { const b = document.createElement('button'); b.textContent = label; b.onclick = onclick; document.getElementById('bar').appendChild(b); return b; }
};

map.on('moveend', ground); map.on('zoomend', ground);
map.on('load', () => { addGrid(); ground(); });
const on = id => { for (const b of ['sat', 'dark', 'wire']) document.getElementById(b).classList.toggle('on', b === id); };
document.getElementById('sat').onclick = () => { map.setStyle({ version: 8, sources: { sat: SAT }, layers: [{ id: 'sat', type: 'raster', source: 'sat', paint: FADE }] }); on('sat'); };
document.getElementById('dark').onclick = () => { map.setStyle(DARK); on('dark'); };
document.getElementById('wire').onclick = () => { map.setStyle({ version: 8, sources: {}, layers: [{ id: 'bg', type: 'background', paint: { 'background-color': '#0a0a0a' } }] }); on('wire'); survey = true; groundKey = ''; setTimeout(ground, 300); document.getElementById('survey').classList.add('on'); };
map.on('style.load', () => { addGrid(); if (!map.getSource('dem')) map.addSource('dem', DEM); map.setTerrain({ source: 'dem', exaggeration: 1 }); });
document.getElementById('tilt').onclick = () => map.easeTo({ pitch: map.getPitch() > 10 ? 0 : 60, duration: 800 });
document.getElementById('survey').onclick = e => { survey = !survey; e.target.classList.toggle('on', survey); groundKey = ''; ground(); };
document.getElementById('here').onclick = () => { const c = map.getCenter(); block(c.lng, c.lat); };
</script><script>fetch('mod/index.json').then(r => r.ok ? r.json() : []).then(list => { for (const n of list) { const t = document.createElement('script'); t.src = 'mod/' + n + '.js'; document.body.appendChild(t); } }).catch(() => {});</script>
</body></html>