GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / energy-transition-simulator / prototype

Overlay and 3 more files

A map page in the prototype folder of Energy Transition Simulator that maps grid substations, using OSTN15 and Helmert and uses data from OpenStreetMap (Overpass) and the GridAtlas repository.

675 lines of JavaScript and HTML from energy-transition-simulator, in 4 files. Topic: Electricity markets and data pipelines. Section 764 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. Overlay geodesy · energy-transition-simulator / prototype/overlay.html lines 1–301
  2. Place Frame geodesy · energy-transition-simulator / prototype/place-frame.mjs lines 1–209
  3. Place Frame Samples storage · energy-transition-simulator / prototype/place-frame.samples.mjs lines 1–42
  4. Place Frame Test test · energy-transition-simulator / prototype/place-frame.test.mjs lines 1–123

Overlay

A map page in the prototype folder of Energy Transition Simulator that maps grid substations, using OSTN15 and Helmert and uses data from OpenStreetMap (Overpass) and the GridAtlas repository.

Set aside from the main view: 99% of its lines are the same as energy-transition-simulator/202609280014/overlay.html (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 98% of lines shared with Overlay; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9885 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 energy-transition-simulator/202609280014/overlay.html:1-300 8544e510dfc617181d662659c177c5ef9c7d5e83
  • sha256 2169b293283b83fa36713e3b49976bd3bbf919c737822cfe2f84327c45df1e9b
  • target sha256 c527a03778bf14c72675ba1ac6db04aa1397f376277b6afc6cff835d3eb8c24e
  • group of 2 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

geodesyenergy-transition-simulator / prototype/overlay.html · lines 1–301 of 301 · 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 experimental (path word 'prototype'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. 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
It is itself an entry point (page); no other file was found loading it.
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
No other file in the estate was found to import it; it is an entry point.
Application
energy-transition-simulator · prototype · 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
mentioned in Standalone (comment link)
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
energy-transition-simulator@a165ce6d56cb22271828874d68d570e8fa5e428a prototype/overlay.html:1-301 · blob 0790df60280d37f2802acbdc1d7fa4223c21c108 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, network · domain stage: experimental · users: none · canonical: duplicate_candidate
<!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; uniform float u_zscale; attribute vec3 p; void main(){ gl_Position = u * vec4(p.xy, p.z * u_zscale, 1.0); }`;   // u_zscale (default 1.0): the block heights, so the wire world can be flattened and raised (mod/morph.js)
    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);
    { const zl = gl.getUniformLocation(this.pr, 'u_zscale'); if (zl) gl.uniform1f(zl, 1.0); }   // u_zscale: 1.0 = today's 3D; mod/morph.js lowers it per frame while it animates
    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>

Place Frame

A JavaScript module in the prototype folder of Energy Transition Simulator that steps lon, converts to local and mercator and calculates great-circle distances and planar distances, using OSTN15 and Helmert.

geodesyenergy-transition-simulator / prototype/place-frame.mjs · lines 1–209 of 209 · Entry point · pattern circumferenceAtLatitude (shared by 2 files)

What it does
It calculates its inputs. Defines 31 functions or classes, including ecef, geodetic, axes, dot, frame.
Why it exists in the grid workflow
Domain stage experimental (path word 'prototype'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326, ETRS89 / EPSG:4258.
Downstream impact
Used directly by 5 files: Overlay (energy-transition-simulator); Place Frame Samples (energy-transition-simulator); Place Frame Test (energy-transition-simulator); Coords Reference (energy-transition-simulator); and 1 more. Reached from 23 other entry points, including Energy Transition Simulator — Latest Page (globalgrid2050, https://globalgrid2050.com/energy-transition-simulator/latest/); 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/).
What it achieves
It places key (`placeKey`), wires map (`wireToMap`) and maps wire (`mapToWire`). The one coordinate system between GridAtlas (the MapLibre map) and the 3D wireframe.
Why it matters
Loaded by the Overlay map page and 1 other page. Also imported by Place Frame Samples. Checked by 2 tests, including Place Frame Test.
Application
energy-transition-simulator · prototype · JavaScript module
Uses
.../world/bng.mjs
Used by
imported by Overlay (import), imported by Place Frame Samples (import), imported by Place Frame Test (import), imported by Coords Reference (import), imported by Overlay (import)
Produces
WGS84, ecef, geodetic, STEP_LAT, LAT_LIMIT, anchorFromKey, placeKey, enu, fromEnu, toLocal, fromLocal, MAPLIBRE_EARTH_RADIUS
Defines here
ecef, geodetic, axes, dot, frame, stepLon, anchorFromKey, placeKey, enu, fromEnu, toLocal, fromLocal, mercatorX, mercatorY, lngFromMercatorX, latFromMercatorY, circumferenceAtLatitude, mercatorZ, mercatorScale, meterInMercator, toMercator, fromMercator, wireToMap, mapToWire, wireBuffer, useWorld, needWorld, toBng, fromBng, wireToBng
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
energy-transition-simulator@a165ce6d56cb22271828874d68d570e8fa5e428a prototype/place-frame.mjs:1-209 · blob 13c72675a0caa3b218026175fc6d98e301848119 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: experimental · users: none · canonical: unknown
// place-frame.mjs: the one coordinate system between GridAtlas (the MapLibre map) and the 3D wireframe.
// Dependency-free, pure functions, no DOM. Every wireframe object is authored in metres around an anchor
// (a place key on a 100 m lattice); this file turns those metres into the Mercator vertices the overlay's
// custom layer draws, and turns map positions back into metres.
//
// WHAT IS EXACT, AND WHAT IS A CONVENTION
//   - Horizontal: exact WGS84 ellipsoid. A local point (x, y) is a point on the anchor's tangent plane
//     (x east, y north, through ECEF); its latitude and longitude are the foot of the ellipsoid normal
//     through it. So nothing is scaled by a sphere: the old overlay path (metres times
//     meterInMercatorCoordinateUnits) uses MapLibre's sphere of 6,371,008.8 m and ignores the ellipsoid,
//     which puts the far corner of a 200 m block a few decimetres off (the tests print the figure).
//   - Vertical: z is height above the ellipsoid at that point (the plane's curvature bump is dropped, so
//     z = 0 drapes on the map). In Mercator units z follows MapLibre's mercatorZfromAltitude, because the
//     map's own camera and extrusions use that convention; it is the map's rule, not the earth's.
//   - enu()/fromEnu() give the pure 3D ENU frame for anyone who needs it (no draping).
//   - toMercator/fromMercator/mercatorScale/mercatorZ copy MapLibre GL JS 4.7.1 (mercator_coordinate.ts)
//     term for term, so they match what the map does, not what the earth is.
// Agreement between these functions proves they are consistent with each other, never that the map
// imagery or grid layers are right on the ground.

// ---- WGS84 ----
export const WGS84 = { a: 6378137.0, f: 1 / 298.257223563 };
const A = WGS84.a, F = WGS84.f, E2 = F * (2 - F), RAD = Math.PI / 180;

/** Geodetic (degrees, metres) -> ECEF [X, Y, Z] in metres. */
export function ecef(lat, lon, h = 0) {
  const p = lat * RAD, l = lon * RAD, s = Math.sin(p), c = Math.cos(p);
  const N = A / Math.sqrt(1 - E2 * s * s);
  return [(N + h) * c * Math.cos(l), (N + h) * c * Math.sin(l), (N * (1 - E2) + h) * s];
}

/** ECEF -> { lat, lon, h } (degrees, metres). Fixed-point iteration, converged to 1e-15 rad. */
export function geodetic(X, Y, Z) {
  const p = Math.hypot(X, Y);
  let lat = Math.atan2(Z, p * (1 - E2)), h = 0;
  for (let k = 0; k < 20; k++) {
    const s = Math.sin(lat), N = A / Math.sqrt(1 - E2 * s * s);
    h = Math.abs(Math.cos(lat)) > 1e-9 ? p / Math.cos(lat) - N : Math.abs(Z) - N * (1 - E2);
    const next = Math.atan2(Z, p * (1 - E2 * N / (N + h)));
    const done = Math.abs(next - lat) < 1e-15;
    lat = next;
    if (done) break;
  }
  const s = Math.sin(lat), N = A / Math.sqrt(1 - E2 * s * s);
  h = Math.abs(Math.cos(lat)) > 1e-9 ? p / Math.cos(lat) - N : Math.abs(Z) - N * (1 - E2);
  return { lat: lat / RAD, lon: Math.atan2(Y, X) / RAD, h };
}

// Unit vectors of the local frame at (lat, lon): east, north, up (up is the ellipsoid normal).
function axes(lat, lon) {
  const p = lat * RAD, l = lon * RAD, sp = Math.sin(p), cp = Math.cos(p), sl = Math.sin(l), cl = Math.cos(l);
  return { e: [-sl, cl, 0], n: [-sp * cl, -sp * sl, cp], u: [cp * cl, cp * sl, sp] };
}
const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];

// An anchor's frame, computed from its lat/lon (never stored in data; cached per object only).
const FRAMES = new WeakMap();
function frame(anchor) {
  let f = FRAMES.get(anchor);
  if (!f) { f = { o: ecef(anchor.lat, anchor.lon, 0), ...axes(anchor.lat, anchor.lon) }; FRAMES.set(anchor, f); }
  return f;
}

// ---- the place key: a 100 m lattice ----
// Rows: latitude = j * STEP_LAT, with STEP_LAT = 100 / 111320 degrees (the overlay's constant, so row j is
// the overlay's own rounding). On the ellipsoid a row step is 99.3 m at the equator to 100.1 m at 61 N.
// Columns: along each row, exactly 100 m of parallel arc on WGS84 at the row's latitude:
// STEP_LON(j) = 100 / (N(lat_j) cos(lat_j)) radians. So a key is two integers; its anchor is computed.
export const STEP_LAT = 100 / 111320;
export const LAT_LIMIT = 85.0511287798066; // MapLibre's Mercator edge
function stepLon(latRow) {
  const s = Math.sin(latRow * RAD), N = A / Math.sqrt(1 - E2 * s * s);
  return 100 / (N * Math.cos(latRow * RAD)) / RAD;
}

/** The anchor for key 'pf:j:i' (or { j, i }): { key, j, i, lat, lon }. */
export function anchorFromKey(key) {
  let j, i;
  if (typeof key === 'string') {
    const m = /^pf:(-?\d+):(-?\d+)$/.exec(key);
    if (!m) throw new Error(`not a place key: ${key}`);
    j = Number(m[1]); i = Number(m[2]);
  } else ({ j, i } = key);
  const lat = j * STEP_LAT, lon = i * stepLon(lat);
  return { key: `pf:${j}:${i}`, j, i, lat, lon };
}

/** The anchor nearest (lat, lon) on the 100 m lattice. */
export function placeKey(lat, lon) {
  if (!(Math.abs(lat) < LAT_LIMIT) || !Number.isFinite(lon)) throw new Error(`no place key at ${lat}, ${lon}`);
  const w = ((lon + 180) % 360 + 360) % 360 - 180; // longitude in [-180, 180)
  const j = Math.round(lat / STEP_LAT);
  return anchorFromKey({ j, i: Math.round(w / stepLon(j * STEP_LAT)) });
}

// ---- local metres <-> WGS84 ----

/** Pure ENU: WGS84 (lat, lon, h) -> { x, y, z } in the anchor's east-north-up frame, via ECEF. */
export function enu(anchor, lat, lon, h = 0) {
  const f = frame(anchor), g = ecef(lat, lon, h), d = [g[0] - f.o[0], g[1] - f.o[1], g[2] - f.o[2]];
  return { x: dot(f.e, d), y: dot(f.n, d), z: dot(f.u, d) };
}

/** Pure ENU inverse: { lat, lon, h }. */
export function fromEnu(anchor, x, y, z = 0) {
  const f = frame(anchor), P = [0, 1, 2].map(k => f.o[k] + x * f.e[k] + y * f.n[k] + z * f.u[k]);
  return geodetic(P[0], P[1], P[2]);
}

/** Wireframe metres from WGS84: (x, y) where the ellipsoid normal through (lat, lon) meets the anchor's
 *  tangent plane; z = h, height above the ellipsoid. Exact inverse of fromLocal. */
export function toLocal(anchor, lat, lon, h = 0) {
  const f = frame(anchor), g = ecef(lat, lon, 0), nrm = axes(lat, lon).u;
  const d = [g[0] - f.o[0], g[1] - f.o[1], g[2] - f.o[2]];
  const t = -dot(f.u, d) / dot(f.u, nrm); // along the normal to the plane
  const P = [d[0] + t * nrm[0], d[1] + t * nrm[1], d[2] + t * nrm[2]];
  return { x: dot(f.e, P), y: dot(f.n, P), z: h };
}

/** WGS84 { lat, lon, h } of wireframe metres (x, y on the tangent plane, z above the ellipsoid). */
export function fromLocal(anchor, x, y, z = 0) {
  const g = fromEnu(anchor, x, y, 0);
  return { lat: g.lat, lon: g.lon, h: z, planeHeight: g.h };
}

// ---- MapLibre's Mercator (maplibre-gl 4.7.1, copied term for term) ----
export const MAPLIBRE_EARTH_RADIUS = 6371008.8;
const CIRC = 2 * Math.PI * MAPLIBRE_EARTH_RADIUS;
export const mercatorX = lng => (180 + lng) / 360;
export const mercatorY = lat => (180 - (180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + lat * Math.PI / 360)))) / 360;
export const lngFromMercatorX = x => x * 360 - 180;
export const latFromMercatorY = y => 360 / Math.PI * Math.atan(Math.exp((180 - y * 360) * Math.PI / 180)) - 90;
export const circumferenceAtLatitude = lat => CIRC * Math.cos(lat * Math.PI / 180);
export const mercatorZ = (alt, lat) => alt / circumferenceAtLatitude(lat);
/** MapLibre's mercatorScale(lat) = 1 / cos(lat). */
export const mercatorScale = lat => 1 / Math.cos(lat * Math.PI / 180);
/** MapLibre's MercatorCoordinate.meterInMercatorCoordinateUnits() at latitude lat (sphere, 6,371,008.8 m). */
export const meterInMercator = lat => 1 / CIRC * mercatorScale(latFromMercatorY(mercatorY(lat)));

/** = MercatorCoordinate.fromLngLat([lon, lat], alt): { x, y, z }. */
export function toMercator(lat, lon, alt = 0) {
  return { x: mercatorX(lon), y: mercatorY(lat), z: mercatorZ(alt, lat) };
}
/** Inverse: { lat, lon, alt }. */
export function fromMercator(x, y, z = 0) {
  const lat = latFromMercatorY(y);
  return { lat, lon: lngFromMercatorX(x), alt: z * circumferenceAtLatitude(lat) };
}

// ---- wireframe <-> map ----

/** The Mercator vertex for wireframe metres (x, y, z) around anchor: { x, y, z } for the custom layer, plus
 *  dx, dy, dz relative to the anchor's own Mercator point. Upload dx/dy/dz as float32 and put the anchor in
 *  the matrix: absolute float32 Mercator near 0.3 has a step of 3e-8, about 1.2 m on the ground. */
export function wireToMap(anchor, x, y, z = 0) {
  const g = fromLocal(anchor, x, y, z), m = toMercator(g.lat, g.lon, z), o = toMercator(anchor.lat, anchor.lon, 0);
  return { x: m.x, y: m.y, z: m.z, dx: m.x - o.x, dy: m.y - o.y, dz: m.z };
}

/** Inverse of wireToMap: Mercator (x, y, z) -> wireframe metres { x, y, z } around anchor. */
export function mapToWire(anchor, mx, my, mz = 0) {
  const g = fromMercator(mx, my, mz);
  return toLocal(anchor, g.lat, g.lon, g.alt);
}

/** A whole line list [[x0,y0,z0,x1,y1,z1], ...] -> Float32Array of anchor-relative Mercator vertices. */
export function wireBuffer(anchor, lines) {
  const out = new Float32Array(lines.length * 6);
  lines.forEach((L, k) => {
    for (let v = 0; v < 2; v++) {
      const w = wireToMap(anchor, L[3 * v], L[3 * v + 1], L[3 * v + 2]);
      out.set([w.dx, w.dy, w.dz], 6 * k + 3 * v);
    }
  });
  return out;
}

// ---- Inside GB: the world's National Grid ----
// Injected, so this file stays dependency-free and the world's own code is the one that runs:
//   useWorld(await import('.../world/bng.mjs'), { blocks, etrsToBng, bngToEtrs })   // second argument optional
// With OSTN15 blocks loaded for the place, toBng/fromBng use OSTN15 (the OS definitive transformation, about
// 0.1 m) and report the Helmert gap; elsewhere they return the Helmert answer, flagged. GPS/WGS84 is taken as
// ETRS89 here: the two part by about 0.9 m by 2026 (plate motion), which is a stated, known error.
let WORLD = null;
export function useWorld(bng, ostn = null) {
  if (!bng || typeof bng.wgs84ToBng !== 'function' || typeof bng.bngToWgs84 !== 'function') throw new Error('useWorld needs the world bng.mjs');
  WORLD = { bng, ostn };
}
const needWorld = () => { if (!WORLD) throw new Error('call useWorld(bng) first'); return WORLD; };

/** WGS84 -> National Grid { e, n, engine, helmert, gapToOstn15 } (gap in metres, null if no OSTN15 here). */
export function toBng(lat, lon) {
  const W = needWorld(), h = W.bng.wgs84ToBng(lat, lon);
  const o = W.ostn ? W.ostn.etrsToBng(W.ostn.blocks, lat, lon) : null;
  if (o) return { e: o.e, n: o.n, engine: 'OSTN15', helmert: h, gapToOstn15: Math.hypot(h.e - o.e, h.n - o.n) };
  return { e: h.e, n: h.n, engine: 'Helmert', helmert: h, gapToOstn15: null };
}

/** National Grid -> WGS84 { lat, lon, engine }. */
export function fromBng(e, n) {
  const W = needWorld(), o = W.ostn ? W.ostn.bngToEtrs(W.ostn.blocks, e, n) : null;
  if (o) return { lat: o.lat, lon: o.lon, engine: 'OSTN15' };
  const h = W.bng.bngToWgs84(e, n);
  return { lat: h.lat, lon: h.lon, engine: 'Helmert' };
}

/** Wireframe metres -> National Grid, and back: the two places tied by the same key must agree. */
export const wireToBng = (anchor, x, y) => { const g = fromLocal(anchor, x, y, 0); return toBng(g.lat, g.lon); };
export const bngToWire = (anchor, e, n) => { const g = fromBng(e, n); return toLocal(anchor, g.lat, g.lon, 0); };

Place Frame Samples

A JavaScript module in the prototype folder of Energy Transition Simulator covering JS samples, using Helmert and OSTN15. It is built from the rnd step (`rnd`).

storageenergy-transition-simulator / prototype/place-frame.samples.mjs · lines 1–42 of 42 · Not reached from any entry point (candidate for review)

What it does
Defines rnd. Uses libraries node:fs, node:path, node:url. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage experimental (path word 'prototype'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: JSON file js-samples.json; command-line arguments. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326.
What it achieves
Deterministic (mulberry32, seed ). 6,000 points at GB latitudes 49-61 N, 4,000 worldwide within +-80.
Why it matters
No other file in the estate was found to import it.
Application
energy-transition-simulator · prototype · JavaScript module
Uses
Place Frame (import), Bng (dynamic import), node:fs, node:path, node:url
Used by
none found
Produces
rnd
Defines here
rnd
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
energy-transition-simulator@a165ce6d56cb22271828874d68d570e8fa5e428a prototype/place-frame.samples.mjs:1-42 · blob d6030c87f2652e46a8aa53dba269559fc69a9002 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: experimental · users: none · canonical: unreached_review
// node place-frame.samples.mjs [out.json]  -> 10,000 sample conversions for the GPU (CuPy) parity proof.
// Deterministic (mulberry32, seed 20260927). 6,000 points at GB latitudes 49-61 N, 4,000 worldwide within +-80.
// Each point is a base place, its placeKey anchor, and a point up to about +-5 km from it with a height.
import { writeFileSync, mkdirSync } from 'node:fs';
import { dirname } from 'node:path';
import { pathToFileURL } from 'node:url';
import * as P from './place-frame.mjs';

const out = process.argv[2] || 'js-samples.json';
let s = 20260927 >>> 0;
const rnd = () => { s = (s + 0x6D2B79F5) >>> 0; let t = s; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
// WORLD_DIR points at the v12 world when the operator has it; otherwise the unchanged copy in mod/engine is used.
const bng = process.env.WORLD_DIR ? await import(pathToFileURL(process.env.WORLD_DIR + '/bng.mjs').href) : await import('./mod/engine/bng.mjs');

const COLS = ['lat', 'lon', 'h', 'key_j', 'key_i', 'anchor_lat', 'anchor_lon',
  'local_x', 'local_y', 'local_z', 'enu_x', 'enu_y', 'enu_z', 'back_lat', 'back_lon',
  'merc_x', 'merc_y', 'merc_z', 'wire_dx', 'wire_dy', 'mercator_scale', 'meter_in_mercator',
  'bng_helmert_e', 'bng_helmert_n'];
const rows = [];
for (let k = 0; k < 10000; k++) {
  const gb = k < 6000;
  const blat = gb ? 49 + 12 * rnd() : -80 + 160 * rnd(), blon = gb ? -8 + 10 * rnd() : -180 + 360 * rnd();
  const a = P.placeKey(blat, blon);
  const lat = blat + (rnd() - 0.5) * 0.09, lon = blon + (rnd() - 0.5) * 0.09 / Math.cos(blat * Math.PI / 180);
  const h = rnd() * 50;
  const l = P.toLocal(a, lat, lon, h), e = P.enu(a, lat, lon, h), b = P.fromLocal(a, l.x, l.y, l.z);
  const m = P.toMercator(lat, lon, h), w = P.wireToMap(a, l.x, l.y, l.z);
  const g = gb ? bng.wgs84ToBng(lat, lon) : { e: null, n: null };
  rows.push([lat, lon, h, a.j, a.i, a.lat, a.lon, l.x, l.y, l.z, e.x, e.y, e.z, b.lat, b.lon,
    m.x, m.y, m.z, w.dx, w.dy, P.mercatorScale(lat), P.meterInMercator(lat), g.e, g.n]);
}
mkdirSync(dirname(out), { recursive: true });
writeFileSync(out, JSON.stringify({
  engine: 'JavaScript (node ' + process.version + '), float64, place-frame.mjs',
  wgs84: P.WGS84, maplibre_earth_radius: P.MAPLIBRE_EARTH_RADIUS, step_lat_deg: P.STEP_LAT,
  lattice: 'row lat = j*step_lat_deg; col lon = i * (100 / (N(lat_j) cos lat_j)) rad, N on WGS84',
  local: 'toLocal: (x,y) where the ellipsoid normal through (lat,lon) meets the anchor tangent plane; z = h',
  enu: 'pure ECEF east-north-up of (lat,lon,h) about the anchor at h=0',
  bng: 'Helmert via world bng.mjs (wgs84ToBng), GB rows only; not OSTN15 (median 1.8 m, max 4.7 m gap)',
  columns: COLS, rows,
}));
console.log(`wrote ${rows.length} samples to ${out}`);

Place Frame Test

A test in the prototype folder of Energy Transition Simulator that checks Place Frame, using OSTN15 and SHA-256.

testenergy-transition-simulator / prototype/place-frame.test.mjs · lines 1–123 of 123 · Not reached from any entry point (candidate for review)

What it does
It tests its inputs. Defines gap, roundTrips. Uses libraries node:test, node:assert/strict, node:fs, node:crypto, node:url. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage experimental (path word 'prototype'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: JSON file ostn15.json. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
What it achieves
It is built from the gap step (`gap`) and the round trips helper (`roundTrips`). Round trips to 1 mm at 20 points from 49 to 61 N and 5 overseas; MapLibre parity; the 100 m lattice; the world's `bng.mjs` and OSTN15 (read-only, from `WORLD_DIR`, else the copy in mod/engine).
Why it matters
Guards the behaviour of Place Frame.
Application
energy-transition-simulator · prototype · test
Uses
Place Frame (import), node:test, node:assert/strict, node:fs, node:crypto, node:url
Used by
none found
Produces
gap, roundTrips
Defines here
gap, roundTrips
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
energy-transition-simulator@a165ce6d56cb22271828874d68d570e8fa5e428a prototype/place-frame.test.mjs:1-123 · blob 5c4279f3db020d1cee307fde5c1a35315117eacf · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: experimental · users: none · canonical: unreached_review
// node --test place-frame.test.mjs
// Round trips to 1 mm at 20 points from 49 to 61 N and 5 overseas; MapLibre parity; the 100 m lattice;
// the world's bng.mjs and OSTN15 (read-only, from WORLD_DIR, else the copy in mod/engine). Consistency, not truth: the OSTN15
// gap is printed alongside every GB result.
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync, existsSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { pathToFileURL, fileURLToPath } from 'node:url';
import * as P from './place-frame.mjs';

const WORLD = process.env.WORLD_DIR || fileURLToPath(new URL('./mod/engine', import.meta.url));
const mm = 1e-3;
const gap = (a, b) => { const p = P.ecef(a.lat, a.lon, 0), q = P.ecef(b.lat, b.lon, 0); return Math.hypot(p[0] - q[0], p[1] - q[1], p[2] - q[2]); };

// 20 GB-latitude points, 49 to 61 N, spread -8 to +2 E; 5 overseas.
const GB = Array.from({ length: 20 }, (_, k) => [49 + 12 * k / 19, -8 + 10 * ((k * 7) % 20) / 19]);
const OVERSEAS = [[-33.92, 18.42], [40.42, -3.70], [35.68, 139.77], [-37.81, 144.96], [19.43, -99.13]];
const OFFSETS = [[0, 0], [100, -60], [-250, 180], [600, 600], [-1000, 400], [2000, -1500], [5000, 5000]];

function roundTrips(lat, lon) {
  const a = P.placeKey(lat, lon);
  let worst = { local: 0, latlon: 0, enu: 0, wire: 0, wirePlace: 0 };
  for (const [x, y] of OFFSETS) for (const z of [0, 2.5, 30]) {
    const g = P.fromLocal(a, x, y, z), b = P.toLocal(a, g.lat, g.lon, g.h);
    worst.local = Math.max(worst.local, Math.hypot(b.x - x, b.y - y, b.z - z));
    const q = P.fromEnu(a, x, y, z), r = P.enu(a, q.lat, q.lon, q.h);
    worst.enu = Math.max(worst.enu, Math.hypot(r.x - x, r.y - y, r.z - z));
    const m = P.wireToMap(a, x, y, z), w = P.mapToWire(a, m.x, m.y, m.z);
    worst.wire = Math.max(worst.wire, Math.hypot(w.x - x, w.y - y, w.z - z));
    // the map vertex must sit on the same ground point as the local one
    const back = P.fromMercator(m.x, m.y);
    worst.wirePlace = Math.max(worst.wirePlace, gap(back, g));
  }
  // lat/lon -> local -> lat/lon for a point 1.2 km away
  const pt = { lat: lat + 0.009, lon: lon - 0.012 }, l = P.toLocal(a, pt.lat, pt.lon), g2 = P.fromLocal(a, l.x, l.y);
  worst.latlon = gap(pt, g2);
  return worst;
}

for (const [name, pts] of [['GB latitudes 49-61 N (20 points)', GB], ['overseas (5 points)', OVERSEAS]]) {
  test(`round trips within 1 mm: ${name}`, () => {
    let all = { local: 0, latlon: 0, enu: 0, wire: 0, wirePlace: 0 };
    for (const [lat, lon] of pts) {
      const w = roundTrips(lat, lon);
      for (const k in all) all[k] = Math.max(all[k], w[k]);
    }
    console.log(`  ${name} worst (m): ` + Object.entries(all).map(([k, v]) => `${k} ${v.toExponential(2)}`).join(', '));
    for (const k in all) assert.ok(all[k] < mm, `${k} ${all[k]} m`);
  });
}

test('MapLibre 4.7.1 Mercator parity (known values)', () => {
  const c = P.toMercator(0, 0);
  assert.equal(c.x, 0.5); assert.ok(Math.abs(c.y - 0.5) < 1e-15);
  assert.ok(Math.abs(P.toMercator(P.LAT_LIMIT, 180).y) < 1e-12);
  assert.equal(P.toMercator(0, 180).x, 1);
  assert.ok(Math.abs(P.mercatorScale(60) - 2) < 1e-12);
  assert.ok(Math.abs(P.mercatorZ(1, 0) * 2 * Math.PI * 6371008.8 - 1) < 1e-12);
  for (const lat of [-60, -10, 0, 33.3, 51.215, 61]) {
    const m = P.toMercator(lat, -1.78, 12), b = P.fromMercator(m.x, m.y, m.z);
    assert.ok(Math.abs(b.lat - lat) < 1e-12 && Math.abs(b.lon + 1.78) < 1e-12 && Math.abs(b.alt - 12) < 1e-9);
  }
});

test('place keys: stable 100 m lattice, anchor computed from the key', () => {
  for (const [lat, lon] of [...GB, ...OVERSEAS]) {
    const a = P.placeKey(lat, lon);
    assert.deepEqual(P.anchorFromKey(a.key), a);
    const d = P.toLocal(a, lat, lon); // the point is inside its cell
    assert.ok(Math.abs(d.x) <= 50.001 && Math.abs(d.y) <= 50.6, `${a.key} ${d.x} ${d.y}`);
    const e = P.anchorFromKey({ j: a.j, i: a.i + 1 }), n = P.anchorFromKey({ j: a.j + 1, i: a.i });
    const de = gap(a, e), dn = gap(a, { lat: n.lat, lon: a.lon }); // row step along the meridian
    assert.ok(Math.abs(de - 100) < 1e-3, `east step ${de}`); // 100 m of parallel arc; chord differs < 1 um
    assert.ok(dn > 99.2 && dn < 100.2, `north step ${dn}`);
    // any point in the cell keys to the same anchor: identity never moves with the viewer
    const g = P.fromLocal(a, 30, -30); assert.equal(P.placeKey(g.lat, g.lon).key, a.key);
  }
});

test('the old overlay path against the exact one (information)', () => {
  // overlay.html: o = fromLngLat(anchor); vertex = o + metres * meterInMercatorCoordinateUnits (sphere, no ellipsoid)
  const a = P.placeKey(51.215, -1.78);
  let worst = 0;
  for (const [x, y] of [[100, 60], [-100, -60], [130, 10], [300, 300], [1000, 1000]]) {
    const o = P.toMercator(a.lat, a.lon), s = P.meterInMercator(a.lat), old = { x: o.x + x * s, y: o.y - y * s };
    const ex = P.fromMercator(old.x, old.y), l = P.toLocal(a, ex.lat, ex.lon);
    const err = Math.hypot(l.x - x, l.y - y); worst = Math.max(worst, err);
    console.log(`  old overlay vertex at (${x}, ${y}) m lands ${(err * 100).toFixed(1)} cm from the exact point`);
  }
  assert.ok(worst > 0.01); // the old path is measurably off; the fix is wireToMap
});

test('GB: world bng.mjs round trips; OSTN15 where the data is present; gap to OSTN15 stated', async () => {
  const bng = await import(pathToFileURL(`${WORLD}/bng.mjs`).href);
  const os = existsSync(`${WORLD}/ostn15.mjs`) ? await import(pathToFileURL(`${WORLD}/ostn15.mjs`).href) : null; // OSTN15 lives in the world, not in this copy
  const dir = `${WORLD}/data/ostn15`, blocks = new Map();
  if (os && existsSync(`${dir}/ostn15.json`)) {
    const raw = readFileSync(`${dir}/ostn15.json`);
    assert.equal(createHash('sha256').update(raw).digest('hex'), os.INDEX_SHA256);
    for (const r of JSON.parse(raw).blocks || []) {
      const buf = readFileSync(`${dir}/${r.file}`);
      assert.equal(createHash('sha256').update(buf).digest('hex'), r.sha256, r.file);
      blocks.set(`${r.lat0}_${r.lon0}`, os.decodeBlock(new Uint8Array(buf)));
    }
  }
  P.useWorld(bng, blocks.size ? { blocks, etrsToBng: os.etrsToBng, bngToEtrs: os.bngToEtrs } : null);
  let rt = 0, rtWire = 0, n15 = 0; const gaps = [];
  for (const [lat, lon] of GB.filter(([la, lo]) => la < 60.9 && lo > -7.9 && lo < 1.8)) {
    const b = P.toBng(lat, lon), g = P.fromBng(b.e, b.n);
    rt = Math.max(rt, gap({ lat, lon }, g));
    if (b.engine === 'OSTN15') { n15++; gaps.push(b.gapToOstn15); }
    const a = P.placeKey(lat, lon), w = P.wireToBng(a, 150, -80), back = P.bngToWire(a, w.e, w.n);
    rtWire = Math.max(rtWire, Math.hypot(back.x - 150, back.y + 80));
  }
  gaps.sort((x, y) => x - y);
  console.log(`  GB round trip worst ${rt.toExponential(2)} m, wire->BNG->wire ${rtWire.toExponential(2)} m; ` +
    `OSTN15 blocks ${blocks.size}, points on OSTN15 ${n15}; Helmert gap to OSTN15 median ${(gaps[gaps.length >> 1] ?? NaN).toFixed(2)} m, max ${(gaps.at(-1) ?? NaN).toFixed(2)} m`);
  assert.ok(rt < mm && rtWire < mm);
  P.useWorld(bng); // Helmert-only round trip too
  const h = P.toBng(52.5, -1.5), hg = P.fromBng(h.e, h.n);
  assert.equal(h.engine, 'Helmert'); assert.ok(gap({ lat: 52.5, lon: -1.5 }, hg) < mm);
});