GLOBALGRID2050 / EXPLORE CODE

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

Bng and 4 more files

A JavaScript module in the world folder of Energy Transition Simulator that converts to cartesian (`toCartesian`), parses grid ref (`parseGridRef`) and calculates planar distances and angles, using Helmert and OSTN15.

650 lines of JavaScript from energy-transition-simulator, in 5 files. Topic: Electricity markets and data pipelines. Section 765 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. Bng geodesy · energy-transition-simulator / prototype/world/bng.mjs lines 1–212
  2. Fade transform · energy-transition-simulator / prototype/world/fade.mjs lines 1–14
  3. Ground Grid render · energy-transition-simulator / prototype/world/layers/ground-grid.mjs lines 1–165
  4. Lines render · energy-transition-simulator / prototype/world/lines.mjs lines 1–166
  5. OSTN15 ingest · energy-transition-simulator / prototype/world/ostn15.mjs lines 1–93

Bng

A JavaScript module in the world folder of Energy Transition Simulator that converts to cartesian (`toCartesian`), parses grid ref (`parseGridRef`) and calculates planar distances and angles, using Helmert and OSTN15.

geodesyenergy-transition-simulator / prototype/world/bng.mjs · lines 1–212 of 212 · Entry point · pattern fromCartesian (shared by 3 files)

What it does
It calculates its inputs. Defines 14 functions or classes, including invert3, apply, toCartesian, fromCartesian, meridional.
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.
Downstream impact
Used directly by 20 files: Links (globalgrid2050); Print Layout (globalgrid2050); Sun UI (globalgrid2050); Sun Mode (globalgrid2050); and 16 more. Reached from 25 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 parses grid ref (`parseGridRef`) and is built from the invert3 step (`invert3`) and the apply step (`apply`). `bngToWgs84` mirrors `osgb36_to_wgs84` in GlobalGrid2050 `uk_renewables_pipeline/v9.7/scripts/data/build_v7_2_spine.py` term for term (one deliberate difference: the meridian-arc loop, see `tmInverse`).
Why it matters
Loaded by the Site World V3 page in GlobalGrid2050 at https://globalgrid2050.com/solar-design-studio/202609270402-site-world-v3/ and 3 other pages. Also imported by 15 files, including Links, Print Layout and Sun UI, from GlobalGrid2050 and Graphics Engines Open Source. Checked by Coords Reference.
Application
energy-transition-simulator · prototype/world · JavaScript module
Uses
none found
Used by
imported by Links (import), imported by Print Layout (import), imported by Sun UI (import), imported by Sun Mode (import), imported by First Showing (import), preloaded by Solar Design Studio — Site World V3 Page (modulepreload), imported by Find Mount (import), imported by Substrate (import), and 12 more, mentioned in Standalone (comment link)
Produces
tmForward, tmInverse, bngToWgs84, wgs84ToBng, parseGridRef, gridRef
Defines here
invert3, apply, toCartesian, fromCartesian, meridional, tmForward, tmInverse, offset, bngToWgs84, wgs84ToBng, parseGridRef, pad, gridRef, fmt
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/world/bng.mjs:1-212 · blob b7164628503b1e80df26257dc62ecebfa77a4d34 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: experimental · users: none · canonical: unknown
// British National Grid <-> WGS84, pure functions, no imports, no DOM.
//
// WHAT THIS IS
//   bngToWgs84 mirrors osgb36_to_wgs84() in globalgrid2050
//   uk_renewables_pipeline/v9.7/scripts/data/build_v7_2_spine.py term for term (one
//   deliberate difference: the meridian-arc loop, see tmInverse):
//   Transverse Mercator inverse on Airy 1830 with the OS National Grid constants
//   (F0 0.9996012717, true origin 49N 2W, false origin E 400000 N -100000), then a
//   7-parameter Helmert OSGB36 -> WGS84 with heights taken as zero on Airy.
//   wgs84ToBng is its exact algebraic inverse: the Helmert matrix inverted (not the
//   usual sign-flipped approximation, which is out by about 1 cm) and the WGS84 height
//   chosen so the Airy height is zero, then the TM forward series, then one fixed-point
//   step against tmInverse (the OS forward and inverse series are truncations and part
//   by up to 2 mm 400 km from the central meridian). So a round trip through both
//   functions closes to well under a millimetre anywhere on the grid.
//
// HOW ACCURATE IT IS, AND IS NOT
//   Closing a round trip proves consistency, not truth. The Helmert transformation is
//   accurate to about 3.5 m against the real National Grid (Ordnance Survey, "A guide to
//   coordinate systems in Great Britain", section 6.6; the OS says 3-5 m and does not
//   recommend it where better is needed). The definitive transformation is OSTN15, a
//   grid of offsets not held here. Where a site has a known OSTN15 offset it can be
//   passed as { de, dn } in metres: wgs84ToBng adds it to the result and bngToWgs84
//   removes it before converting, so the pair stays inverses of each other.
//
// Sources: Ordnance Survey, "A guide to coordinate systems in Great Britain" (v3.6),
//   Annex B (Helmert), Annex C (Transverse Mercator), Annex C.1 worked example.

const AIRY_A = 6377563.396, AIRY_B = 6356256.909;
const WGS_A = 6378137.0, WGS_B = 6356752.3141;
const F0 = 0.9996012717;
const LAT0 = 49 * Math.PI / 180, LON0 = -2 * Math.PI / 180;
const E0 = 400000, N0 = -100000;
const AIRY_E2 = 1 - (AIRY_B * AIRY_B) / (AIRY_A * AIRY_A);
const WGS_E2 = 1 - (WGS_B * WGS_B) / (WGS_A * WGS_A);
const N_ = (AIRY_A - AIRY_B) / (AIRY_A + AIRY_B);
const RAD = Math.PI / 180, SEC = RAD / 3600;

// OSGB36 -> WGS84, exactly as the Python: x2 = t + M x1
const T = [446.448, -125.157, 542.060];
const RX = 0.1502 * SEC, RY = 0.2470 * SEC, RZ = 0.8421 * SEC;
const S = 1 - 20.4894e-6;
const M = [[S, -RZ, RY], [RZ, S, -RX], [-RY, RX, S]];

function invert3(m) {
  const [[a, b, c], [d, e, f], [g, h, i]] = m;
  const A = e * i - f * h, B = -(d * i - f * g), C = d * h - e * g;
  const det = a * A + b * B + c * C;
  return [
    [A / det, -(b * i - c * h) / det, (b * f - c * e) / det],
    [B / det, (a * i - c * g) / det, -(a * f - c * d) / det],
    [C / det, -(a * h - b * g) / det, (a * e - b * d) / det],
  ];
}
const MI = invert3(M);

const apply = (m, v) => [
  m[0][0] * v[0] + m[0][1] * v[1] + m[0][2] * v[2],
  m[1][0] * v[0] + m[1][1] * v[1] + m[1][2] * v[2],
  m[2][0] * v[0] + m[2][1] * v[1] + m[2][2] * v[2],
];

function toCartesian(lat, lon, h, a, e2) {
  const s = Math.sin(lat), c = Math.cos(lat);
  const nu = a / Math.sqrt(1 - e2 * s * s);
  return [(nu + h) * c * Math.cos(lon), (nu + h) * c * Math.sin(lon), (nu * (1 - e2) + h) * s];
}

// Cartesian -> geodetic, the same fixed-point iteration as the Python (12 steps max).
function fromCartesian(x, y, z, a, e2) {
  const p = Math.hypot(x, y);
  let lat = Math.atan2(z, p * (1 - e2));
  for (let k = 0; k < 12; k++) {
    const nu = a / Math.sqrt(1 - e2 * Math.sin(lat) ** 2);
    const next = Math.atan2(z + e2 * nu * Math.sin(lat), p);
    const done = Math.abs(next - lat) < 1e-12;
    lat = next;
    if (done) break;
  }
  const nu = a / Math.sqrt(1 - e2 * Math.sin(lat) ** 2);
  const h = Math.abs(Math.cos(lat)) > 1e-9 ? p / Math.cos(lat) - nu : Math.abs(z) - nu * (1 - e2);
  return { lat, lon: Math.atan2(y, x), h };
}

function meridional(lat) {
  const n = N_, dl = lat - LAT0, sl = lat + LAT0;
  const ma = (1 + n + 5 / 4 * n ** 2 + 5 / 4 * n ** 3) * dl;
  const mb = (3 * n + 3 * n ** 2 + 21 / 8 * n ** 3) * Math.sin(dl) * Math.cos(sl);
  const mc = (15 / 8 * n ** 2 + 15 / 8 * n ** 3) * Math.sin(2 * dl) * Math.cos(2 * sl);
  const md = 35 / 24 * n ** 3 * Math.sin(3 * dl) * Math.cos(3 * sl);
  return AIRY_B * F0 * (ma - mb + mc - md);
}

/** OSGB36 latitude/longitude (radians, Airy 1830) -> National Grid { e, n }. OS Annex C. */
export function tmForward(lat, lon) {
  const s = Math.sin(lat), c = Math.cos(lat), t = Math.tan(lat);
  const nu = AIRY_A * F0 / Math.sqrt(1 - AIRY_E2 * s * s);
  const rho = AIRY_A * F0 * (1 - AIRY_E2) / (1 - AIRY_E2 * s * s) ** 1.5;
  const eta2 = nu / rho - 1;
  const I = meridional(lat) + N0;
  const II = nu / 2 * s * c;
  const III = nu / 24 * s * c ** 3 * (5 - t ** 2 + 9 * eta2);
  const IIIA = nu / 720 * s * c ** 5 * (61 - 58 * t ** 2 + t ** 4);
  const IV = nu * c;
  const V = nu / 6 * c ** 3 * (nu / rho - t ** 2);
  const VI = nu / 120 * c ** 5 * (5 - 18 * t ** 2 + t ** 4 + 14 * eta2 - 58 * t ** 2 * eta2);
  const dl = lon - LON0;
  return {
    e: E0 + IV * dl + V * dl ** 3 + VI * dl ** 5,
    n: I + II * dl ** 2 + III * dl ** 4 + IIIA * dl ** 6,
  };
}

/** National Grid (e, n) -> OSGB36 { lat, lon } in radians on Airy 1830. Mirrors the Python. */
export function tmInverse(easting, northing) {
  let lat = LAT0, m = 0;
  // OS Annex C.6 repeats while |N - N0 - M| >= 0.01 mm. The Python tests the signed value,
  // so north of about 55N, where a step overshoots, it stops early: 3-11 cm out in Scotland
  // and up to 46 m north of N 1,210,000. Here the absolute value, as the OS writes it.
  for (let k = 0; k < 100 && Math.abs(northing - N0 - m) >= 0.00001; k++) {
    lat += (northing - N0 - m) / (AIRY_A * F0);
    m = meridional(lat);
  }
  const s = Math.sin(lat), c = Math.cos(lat), t = Math.tan(lat);
  const nu = AIRY_A * F0 / Math.sqrt(1 - AIRY_E2 * s * s);
  const rho = AIRY_A * F0 * (1 - AIRY_E2) / (1 - AIRY_E2 * s * s) ** 1.5;
  const eta2 = nu / rho - 1;
  const de = easting - E0;
  const VII = t / (2 * rho * nu);
  const VIII = t / (24 * rho * nu ** 3) * (5 + 3 * t ** 2 + eta2 - 9 * t ** 2 * eta2);
  const IX = t / (720 * rho * nu ** 5) * (61 + 90 * t ** 2 + 45 * t ** 4);
  const X = 1 / (c * nu);
  const XI = 1 / (c * 6 * nu ** 3) * (nu / rho + 2 * t ** 2);
  const XII = 1 / (c * 120 * nu ** 5) * (5 + 28 * t ** 2 + 24 * t ** 4);
  const XIIA = 1 / (c * 5040 * nu ** 7) * (61 + 662 * t ** 2 + 1320 * t ** 4 + 720 * t ** 6);
  return {
    lat: lat - VII * de ** 2 + VIII * de ** 4 - IX * de ** 6,
    lon: LON0 + X * de - XI * de ** 3 + XII * de ** 5 - XIIA * de ** 7,
  };
}

const offset = (o) => ({ de: (o && Number.isFinite(o.de)) ? o.de : 0, dn: (o && Number.isFinite(o.dn)) ? o.dn : 0 });

/** National Grid easting/northing (m) -> WGS84 { lat, lon } in degrees. */
export function bngToWgs84(e, n, ostn) {
  const { de, dn } = offset(ostn);
  const g = tmInverse(e - de, n - dn);
  const p = toCartesian(g.lat, g.lon, 0, AIRY_A, AIRY_E2);
  const q = apply(M, p);
  const w = fromCartesian(q[0] + T[0], q[1] + T[1], q[2] + T[2], WGS_A, WGS_E2);
  return { lat: w.lat / RAD, lon: w.lon / RAD };
}

/** WGS84 { lat, lon } in degrees -> National Grid { e, n } in metres. Exact inverse of bngToWgs84. */
export function wgs84ToBng(lat, lon, ostn) {
  const { de, dn } = offset(ostn);
  const la = lat * RAD, lo = lon * RAD;
  let h = 0, g = null;
  // bngToWgs84 puts the point at height zero on Airy; find the WGS84 height that does too.
  for (let k = 0; k < 4; k++) {
    const w = toCartesian(la, lo, h, WGS_A, WGS_E2);
    const p = apply(MI, [w[0] - T[0], w[1] - T[1], w[2] - T[2]]);
    g = fromCartesian(p[0], p[1], p[2], AIRY_A, AIRY_E2);
    if (Math.abs(g.h) < 1e-6) break;
    h -= g.h;
  }
  const r0 = tmForward(g.lat, g.lon);
  let r = r0;
  for (let k = 0; k < 3; k++) { // make it the inverse of tmInverse, not just the OS series
    const back = tmInverse(r.e, r.n), b = tmForward(back.lat, back.lon);
    r = { e: r.e + (r0.e - b.e), n: r.n + (r0.n - b.n) };
  }
  return { e: r.e + de, n: r.n + dn };
}

// ---- grid references: two letters for the 100 km square, then digits ----

const LETTERS = 'ABCDEFGHJKLMNOPQRSTUVWXYZ'; // 25 letters, no I

/** 'TQ 30 80' / 'TQ3080' / 'tq 3000 8000' -> { e, n } of the square's south-west corner. */
export function parseGridRef(ref) {
  const s = String(ref ?? '').toUpperCase().replace(/[\s,]+/g, ' ').trim();
  const m = /^([A-HJ-Z])([A-HJ-Z])\s*(\d*)\s*(\d*)$/.exec(s);
  if (!m) throw new Error(`not a grid reference: ${ref}`);
  const l1 = LETTERS.indexOf(m[1]), l2 = LETTERS.indexOf(m[2]);
  const e100 = ((l1 - 2) % 5) * 5 + (l2 % 5);
  const n100 = (19 - Math.floor(l1 / 5) * 5) - Math.floor(l2 / 5);
  let de = m[3], dn = m[4];
  if (!dn) { // run together: split in half
    if (de.length % 2) throw new Error(`odd number of digits: ${ref}`);
    dn = de.slice(de.length / 2); de = de.slice(0, de.length / 2);
  }
  if (de.length !== dn.length || de.length > 5) throw new Error(`unbalanced digits: ${ref}`);
  const pad = (d) => (d ? Number((d + '00000').slice(0, 5)) : 0);
  const e = e100 * 100000 + pad(de), n = n100 * 100000 + pad(dn);
  if (e100 < 0 || e100 > 6 || n100 < 0 || n100 > 12) throw new Error(`square outside the grid: ${ref}`);
  return { e, n };
}

/** { e, n } -> 'TQ 30 80' with `digits` digits in all (0, 2, 4, ... 10). Truncates, as the OS does. */
export function gridRef(e, n, digits = 10) {
  if (!(digits >= 0 && digits <= 10 && digits % 2 === 0)) throw new Error(`digits must be 0..10 and even: ${digits}`);
  if (!(e >= 0 && e < 700000 && n >= 0 && n < 1300000)) throw new Error(`outside the grid: ${e}, ${n}`);
  const e100 = Math.floor(e / 100000), n100 = Math.floor(n / 100000);
  const l1 = (19 - n100) - ((19 - n100) % 5) + Math.floor((e100 + 10) / 5);
  const l2 = ((19 - n100) * 5) % 25 + (e100 % 5);
  const sq = LETTERS[l1] + LETTERS[l2];
  if (digits === 0) return sq;
  const k = digits / 2, div = 10 ** (5 - k);
  const fmt = (v) => String(Math.floor((v % 100000) / div)).padStart(k, '0');
  return `${sq} ${fmt(e)} ${fmt(n)}`;
}

Fade

A JavaScript module in the world folder of Energy Transition Simulator that works with far plane (`farPlane`).

transformenergy-transition-simulator / prototype/world/fade.mjs · lines 1–14 of 14 · Not reached from any entry point (candidate for review) · pattern farPlane (shared by 3 files)

What it does
It calculates its inputs. Defines fadeFor, farPlane.
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.
What it achieves
It is built from the fade for helper (`fadeFor`) and the far plane helper (`farPlane`). Carried over unchanged from the site-world release `solar-design-studio/202609270524-site-world/world/fade.mjs` (published 27 Sept 2026, copied 28 Sept 2026).
Why it matters
No other file in the estate was found to import it.
Application
energy-transition-simulator · prototype/world · JavaScript module
Uses
none found
Used by
none found
Produces
FADE_M, fadeFor, farPlane
Defines here
fadeFor, farPlane
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/world/fade.mjs:1-14 · blob b5adeb934df154ecb5db51f668f6b393578d2b93 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: experimental · users: none · canonical: duplicate_candidate
// Carried over unchanged from the site-world release solar-design-studio/202609270524-site-world/world/fade.mjs
// (published 27 Sept 2026, copied 28 Sept 2026). Do not edit here: change the release line and carry it again.
// How far the world is drawn before it fades out, and the far plane that follows it. Pure.
export const FADE_M = 450, FAR_M = 5000, MILE_M = 1609.344;

// view: 'standing' | 'aerial'; above: eye height above the ground (m); rangeM: the wider-area roads and rail range
// when that layer is on, else 0. The fade grows 2.5 m per metre up, to 4 km (phone review: a high drone still sees the
// ground below). With the wider area on, a drone sees 30 m per metre up, never past the chosen range.
export function fadeFor(view, above, rangeM = 0) {
  const h = Math.max(0, Number.isFinite(above) ? above : 0), base = Math.min(4000, FADE_M + h * 2.5);
  return view === 'aerial' && rangeM > 0 ? Math.max(base, Math.min(Math.max(FADE_M, 30 * h), rangeM)) : base;
}

export const farPlane = fade => Math.max(FAR_M, fade * 1.1);

Ground Grid

A JavaScript module in the layers folder of Energy Transition Simulator that works with height store (`heightStore`) and origin mark (`originMark`).

Set aside from the main view: 92% of its lines are the same as solar-design-studio/202609271740-site-world/world/layers/ground-grid.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 91% of lines shared with Ground Grid; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9191 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271740-site-world/world/layers/ground-grid.mjs:1-158 ccb2f775cb9dcf7a424e23e6370d8242611c2f16
  • sha256 c2500d0c8e4e445fd7cd9714bdda4889bd35e0b3476c9aecfcc0bb3625ae979b
  • target sha256 0556afb378177d8a8647776f2c70406a658f0ca1013b382d969dbf9712eb8d46
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

renderenergy-transition-simulator / prototype/world/layers/ground-grid.mjs · lines 1–165 of 165 · Not reached from any entry point (candidate for review) · pattern originMark (shared by 2 files)

What it does
Defines 7 functions or classes, including later, grid, wrap, slotOf, heightStore.
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.
What it achieves
It is built from the later step (`later`), the grid step (`grid`) and the wrap step (`wrap`). Carried over unchanged from the site-world release `solar-design-studio/202609270524-site-world/world/layers/ground-grid.mjs` (published 27 Sept 2026, copied 28 Sept 2026).
Why it matters
No other file in the estate was found to import it.
Application
energy-transition-simulator · prototype/world/layers · JavaScript module
Uses
none found
Used by
none found
Produces
DETAIL, REACH, grid
Defines here
later, grid, wrap, slotOf, heightStore, originMark, finite
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/world/layers/ground-grid.mjs:1-165 · blob 012e4770cb0d36f5a3cff321fbaa1951536c0a28 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: none found · domain stage: experimental · users: none · canonical: duplicate_candidate
// Carried over unchanged from the site-world release solar-design-studio/202609270524-site-world/world/layers/ground-grid.mjs
// (published 27 Sept 2026, copied 28 Sept 2026). Do not edit here: change the release line and carry it again.
// Layer: ground grid. A 1 m grid near the viewer and a 10 m grid to the horizon, draped on whatever
// ground the world has (flat until a terrain layer supplies heightAt). The grid follows the viewer in
// 10 m steps, so it looks endless but only ever holds a few thousand lines.
// Within 100 m of the viewer every segment is split to 2 m or less, so the grid follows real banks and
// ditches rather than bridging them. Batches carry an origin at the centre of the viewer's 10 m cell and
// positions relative to it, so they stay sharp on the GPU. The grid is rebuilt on a new cell or new ground.
//
// Cost: every grid point is a heightAt call, and real terrain makes those dear (about 45,000 per rebuild
// before, when each segment asked for both ends). Now each point is asked for once: heights are kept in
// a store for one ground (one heightAt and groundVersion), so stepping into a new 10 m cell only asks for
// the strip of points that came into view. New ground starts a new store and nothing old is trusted: the
// first frame asks again for everything within 50 m (the 1 m grid and the nearest banks and ditches), and
// the next few frames widen that to 150 m, 300 m and the horizon. Until a far point is asked again it is
// drawn at its height on the previous ground, so a new tile never stalls a walk for a whole rebuild.
//
// Measured ground only (v05, phantom plateau): past the loaded terrain tiles the world's heightAt keeps the
// last height it knew, and a grid drawn there is a flat plateau that is not on the ground (up to 59 px of false
// horizon over a valley, GPU ray-cast check). When the page says which ground is measured (ctx.known) and the
// viewer stands on measured ground, a segment is drawn only if both its ends are measured: the grid ends at the
// loaded edge. With no measured ground under the viewer (the empty world) the flat grid is the only ground.

const MINOR = { spacing: 1, radius: 30, color: [156 / 255, 219 / 255, 1, 0.16] };  // #9cdbff
const MAJOR = { spacing: 10, radius: 400, color: [156 / 255, 219 / 255, 1, 0.42] };
const ORIGIN = { color: [1, 1, 1, 0.9], arm: 5 };
const FOLLOW = 10;
export const DETAIL = { radius: 100, step: 2 }; // near the viewer, no segment is longer than 2 m
export const REACH = [50, 150, 300, Infinity];  // metres asked again on the frames after new ground
let cached = { version: null, batches: [] };
let store = null, api = null;

export default {
  id: 'ground-grid',
  init(a) { api = a; },
  // ctx: { pos, heightAt, known?(x, y) -> measured ground there, groundVersion?, origin? }
  lines({ pos, heightAt, known = null, groundVersion = 0 }) {
    const cx = Math.floor(pos[0] / FOLLOW) * FOLLOW, cy = Math.floor(pos[1] / FOLLOW) * FOLLOW;
    const clip = typeof known === 'function' && !!known(cx + FOLLOW / 2, cy + FOLLOW / 2) ? known : null;
    const version = cx + ',' + cy + '@' + groundVersion + (clip ? '/m' : ''), same = cached.version === version && cached.heightAt === heightAt;
    if (same && cached.pass === store.pass) return cached.batches; // new cell, new ground or a wider reach only
    if (!store || !store.fits(heightAt, groundVersion, clip)) store = heightStore(heightAt, groundVersion, cx, cy, api ? store : null, clip);
    const mx = cx + FOLLOW / 2, my = cy + FOLLOW / 2, sample = store.begin(mx, my), mz = sample(mx, my);
    const origin = [mx, my, mz], opts = { origin, near: [mx, my], sample, known: clip && store.knownAt };
    const step = store.pass ? '#' + store.pass : '', tag = version + step;
    const minor = same && cached.minorWhole ? cached.batches[0]
      : { key: 'ground-grid/minor', version: tag, origin, color: MINOR.color, positions: grid(cx, cy, MINOR, heightAt, opts) };
    const minorWhole = !store.partial;
    const major = { key: 'ground-grid/major', version: tag, origin, color: MAJOR.color, positions: grid(cx, cy, MAJOR, heightAt, opts) };
    const mark = { key: 'ground-grid/origin', version: 'origin@' + groundVersion + step, color: ORIGIN.color, positions: originMark(sample, mz) };
    cached = { version, heightAt, pass: store.pass, minorWhole, batches: [minor, major, mark] };
    if (store.partial) later(store); // after this frame: widen the reach and ask for another frame
    return cached.batches;
  }
};

// Only with a live page (init gave an api to ask for frames) does new ground arrive in steps; without
// one, every rebuild asks for every point it lacks.
function later(s) {
  setTimeout(() => { if (s === store && s.partial) { s.widen(); api.invalidate({ ground: false }); } }, 0);
}

// Lines of the grid centred on (cx, cy). Positions are relative to opts.origin ([0, 0, 0] by default).
// Segments whose midpoint lies within DETAIL.radius of opts.near are split to DETAIL.step or less.
// opts.sample(x, y, guess), if given, is used in place of heightAt and must return a finite height; guess is
// the height of the point before it on the line (the origin's for the first), for a sampler that may guess.
// opts.known(x, y), if given, says where ground is measured: a segment is left out unless both its ends are.
export function grid(cx, cy, { spacing, radius }, heightAt, { origin = [0, 0, 0], near = null, sample = null, known = null } = {}) {
  const h = sample || ((x, y) => finite(heightAt(x, y)));
  const n = Math.round(radius / spacing), pieces = spacing > DETAIL.step ? Math.ceil(spacing / DETAIL.step) : 1;
  const [ox, oy, oz] = origin, r2 = DETAIL.radius * DETAIL.radius;
  // How many pieces the segment from b0 to b0 + spacing along a line at offset a is cut into.
  const split = pieces > 1 && near
    ? (ax, ay, bx, by) => { const dx = (ax + bx) / 2 - near[0], dy = (ay + by) / 2 - near[1]; return dx * dx + dy * dy <= r2 ? pieces : 1; }
    : () => 1;
  let count = 0;
  for (let i = -n; i <= n; i++) {
    const a = i * spacing;
    for (let j = -n; j < n; j++) {
      const b0 = j * spacing, b1 = b0 + spacing;
      count += split(cx + a, cy + b0, cx + a, cy + b1) + split(cx + b0, cy + a, cx + b1, cy + a);
    }
  }
  const out = new Float32Array(count * 6);
  let w = 0;
  for (let i = -n; i <= n; i++) {
    const a = i * spacing;
    for (let dir = 0; dir < 2; dir++) { // 0: north-south line at x = cx + a; 1: east-west line at y = cy + a
      let px = dir ? cx - n * spacing : cx + a, py = dir ? cy + a : cy - n * spacing, pz = h(px, py, oz);
      let pk = !known || !!known(px, py);
      for (let j = -n; j < n; j++) {
        const b0 = j * spacing, b1 = b0 + spacing;
        const x0 = dir ? cx + b0 : cx + a, y0 = dir ? cy + a : cy + b0, x1 = dir ? cx + b1 : cx + a, y1 = dir ? cy + a : cy + b1;
        const k = split(x0, y0, x1, y1);
        for (let p = 0; p < k; p++) {
          const qx = x0 + (x1 - x0) * (p + 1) / k, qy = y0 + (y1 - y0) * (p + 1) / k, qz = h(qx, qy, pz); // whole metres stay whole
          const qk = !known || !!known(qx, qy);
          if (pk && qk) {
            out[w++] = px - ox; out[w++] = py - oy; out[w++] = pz - oz;
            out[w++] = qx - ox; out[w++] = qy - oy; out[w++] = qz - oz;
          }
          px = qx; py = qy; pz = qz; pk = qk;
        }
      }
    }
  }
  return w < out.length ? out.slice(0, w) : out;
}

// Heights asked for once per ground, kept in fixed typed arrays that wrap around as the viewer walks
// (no Map, nothing to trim). A whole-metre point on a 10 m line has a slot in one of two line planes;
// any other whole-metre point near the viewer has one in the inner plane; each slot remembers which point
// and which ground it holds. Other points go straight to heightAt. A store serves one heightAt and one
// groundVersion (and one known, whose answers it keeps beside the heights). When the store before it had the same heightAt, a new store asks only within its reach
// of the centre and answers further points from older ground (or the guess), marking itself partial.
const LINES = 2 * Math.ceil(MAJOR.radius / MAJOR.spacing) + 4, ALONG = 2 * MAJOR.radius + 4 * FOLLOW, INNER = 2 * MINOR.radius + 12;
let slots = null, generation = 0;
const wrap = (v, m) => ((v % m) + m) % m;
function slotOf(x, y) {
  if ((x | 0) !== x || (y | 0) !== y) return -1;
  if (x % MAJOR.spacing === 0) return wrap(x / MAJOR.spacing, LINES) * ALONG + wrap(y, ALONG);
  if (y % MAJOR.spacing === 0) return (LINES + wrap(y / MAJOR.spacing, LINES)) * ALONG + wrap(x, ALONG);
  return 2 * LINES * ALONG + wrap(x, INNER) * INNER + wrap(y, INNER);
}
function heightStore(heightAt, groundVersion, cx, cy, before, known = null) {
  if (!slots) {
    const n = 2 * LINES * ALONG + INNER * INNER;
    slots = { z: new Float64Array(n), x: new Int32Array(n).fill(-0x80000000), y: new Int32Array(n), gen: new Uint32Array(n), k: new Uint8Array(n) };
  }
  const { z, x: sx, y: sy, gen, k: kn } = slots, g = ++generation;
  const guessing = !!before && before.heightAt === heightAt;
  let pass = guessing ? 0 : REACH.length - 1, reach2 = REACH[pass] ** 2, mx = 0, my = 0;
  const self = {
    heightAt, partial: false,
    get pass() { return pass; },
    sample(x, y, guess = 0) {
      const k = slotOf(x, y);
      if (k < 0) return finite(heightAt(x, y));
      const held = sx[k] === x && sy[k] === y;
      if (held && gen[k] === g) return z[k];
      if ((x - mx) ** 2 + (y - my) ** 2 > reach2) { self.partial = true; return held ? z[k] : guess; } // older ground
      const h = finite(heightAt(x, y));
      z[k] = h; sx[k] = x; sy[k] = y; gen[k] = g; kn[k] = known && known(x, y) ? 1 : 0;
      return h;
    },
    // Whether (x, y) is measured, for a point sample has just answered: a slot keeps the answer with its height;
    // a far point answered from older ground is taken as unmeasured until it is asked again.
    knownAt(x, y) {
      const k = slotOf(x, y);
      if (k < 0) return !!known(x, y);
      return sx[k] === x && sy[k] === y && gen[k] === g ? kn[k] === 1 : false;
    },
    begin(x, y) { mx = x; my = y; self.partial = false; return self.sample; },
    widen() { pass = Math.min(pass + 1, REACH.length - 1); reach2 = REACH[pass] ** 2; },
    fits: (f, gv, kf = null) => f === heightAt && gv === groundVersion && kf === known && g === generation
  };
  return self;
}

function originMark(sample, guess) {
  const a = ORIGIN.arm, h = sample(0, 0, guess);
  return new Float32Array([-a, 0, h, a, 0, h, 0, -a, h, 0, a, h, 0, 0, h, 0, 0, h + 2 * a]);
}

const finite = h => (Number.isFinite(h) ? h : 0);

Lines

A JavaScript module in the world folder of Energy Transition Simulator that splits batches (`splitBatches`), calculates planar distances and renders with WebGL.

Set aside from the main view: 99% of its lines are the same as solar-design-studio/202609270402-site-world-v3/world/lines.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 98% of lines shared with Lines; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9851 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609270402-site-world-v3/world/lines.mjs:1-164 f947588fc0a665b0c3789dd6b6700f686794c244
  • sha256 6ca31abde7c06f8a0505ce510bddeb7a27ea1d60c622b56b82956b4358c2878e
  • target sha256 a2d07cb7b43896d8dd5b5c3e1ce58374e1793d8e269958fb5b8332414edb61c9
  • group of 2 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

renderenergy-transition-simulator / prototype/world/lines.mjs · lines 1–166 of 166 · Not reached from any entry point (candidate for review) · pattern occluderFollower (shared by 4 files)

What it does
It draws its content. Defines 8 functions or classes, including offsetOf, splitBatches, occluderMesh, put, occluderFollower. Side effects: changes the web page (DOM).
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
Out: WebGL/WebGPU drawing.
What it achieves
It splits batches (`splitBatches`) and is built from the offset of helper (`offsetOf`) and the occluder mesh helper (`occluderMesh`). Carried over unchanged from the site-world release `solar-design-studio/202609270524-site-world/world/lines.mjs` (published 27 Sept 2026, copied 28 Sept 2026). It responds to webglcontextlost and webglcontextrestored events.
Why it matters
No other file in the estate was found to import it.
Application
energy-transition-simulator · prototype/world · JavaScript module
Uses
none found
Used by
none found
Produces
offsetOf, BACKGROUND, splitBatches, occluderMesh, occluderFollower, createLines
Defines here
offsetOf, splitBatches, occluderMesh, put, occluderFollower, createLines, init, bind
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/world/lines.mjs:1-166 · blob dc2320d1ec07f88399c44ff4817d9dbfe597b0b5 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: experimental · users: none · canonical: duplicate_candidate
// Carried over unchanged from the site-world release solar-design-studio/202609270524-site-world/world/lines.mjs
// (published 27 Sept 2026, copied 28 Sept 2026). Do not edit here: change the release line and carry it again.
// Line renderer: raw WebGL 1, flat colour, lines fade with distance. No textures, no sky, no lighting.
// Survives a lost WebGL context: every buffer is rebuilt from the layers' own data on restore.
// Drawing is relative to the eye: the matrix is built with the eye at [0, 0, 0], and each batch is moved by
// u_off = (batch origin - eye), worked out in JavaScript doubles. A batch with an origin keeps its
// positions small, so 32-bit floats stay sharp however far the viewer walks from the site origin.
// Occlusion: batches marked { occluder: true, triangles } (a coarse ground mesh) are drawn first into the
// depth buffer only; then every line batch is depth tested against them, so lines behind a hill are hidden.
// Lines never write depth, so they never hide each other; only occluders hide anything.

const VS = `attribute vec3 a_p; uniform mat4 u_m; uniform vec3 u_off; uniform float u_fade; varying float v_a;
void main() { vec3 p = a_p + u_off; gl_Position = u_m * vec4(p, 1.0); v_a = clamp(1.0 - length(p) / u_fade, 0.0, 1.0); }`;
const ZERO = [0, 0, 0];

// The offset from the eye to a batch's origin, in doubles; only the small result goes to the GPU.
export const offsetOf = (origin, eye) => {
  const o = origin || ZERO;
  return [o[0] - eye[0], o[1] - eye[1], o[2] - eye[2]];
};
const FS = `precision mediump float; uniform vec4 u_c; varying float v_a;
void main() { gl_FragColor = vec4(u_c.rgb, u_c.a * v_a); }`;

export const BACKGROUND = [10 / 255, 10 / 255, 10 / 255, 1]; // #0a0a0a

// Occluders first (depth only), then lines; order within each group is kept.
export const splitBatches = batches => {
  const occluders = [], lines = [];
  for (const b of batches) (b.occluder ? occluders : lines).push(b);
  return { occluders, lines };
};

// A coarse ground mesh around (x, y) for occlusion, as an occluder batch. Pure: it only calls heightAt.
// The centre snaps to the cell grid so the mesh does not swim as the viewer moves; positions are relative
// to that centre (the batch origin), so they stay small. sink lowers the mesh so lines lying on finer
// ground than these cells are not buried where the coarse surface cuts above the true one.
// Cells with a corner that has no finite height are left out (nothing is hidden there).
export function occluderMesh(heightAt, x, y, { cell = 8, radius = 400, sink = 0.5, key = 'occluder', version } = {}) {
  if (!(cell > 0) || !(radius > 0)) throw Error('occluderMesh needs a positive cell and radius');
  const cx = Math.round(x / cell) * cell, cy = Math.round(y / cell) * cell;
  const n = Math.ceil(radius / cell), side = 2 * n + 1;
  const h = new Float64Array(side * side);
  for (let j = 0; j < side; j++) for (let i = 0; i < side; i++) {
    const v = heightAt(cx + (i - n) * cell, cy + (j - n) * cell);
    h[j * side + i] = Number.isFinite(v) ? v - sink : NaN;
  }
  const out = new Float32Array((side - 1) * (side - 1) * 18);
  let k = 0;
  const put = (i, j) => { out[k++] = (i - n) * cell; out[k++] = (j - n) * cell; out[k++] = h[j * side + i]; };
  for (let j = 0; j < side - 1; j++) for (let i = 0; i < side - 1; i++) {
    const a = h[j * side + i], b = h[j * side + i + 1], c = h[(j + 1) * side + i], d = h[(j + 1) * side + i + 1];
    if (!Number.isFinite(a + b + c + d)) continue;
    put(i, j); put(i + 1, j); put(i + 1, j + 1);
    put(i, j); put(i + 1, j + 1); put(i, j + 1);
  }
  return { key, version: version ?? `${cx},${cy},${cell},${radius},${sink}`, occluder: true,
    triangles: out.subarray(0, k), origin: [cx, cy, 0] };
}

// Keeps one occluder mesh and rebuilds it only when the viewer has moved `every` metres from where it was
// built, or the ground has changed (groundVersion). Returns the same batch object while nothing changed.
export function occluderFollower({ every = 64, ...opts } = {}) {
  let last = null, at = null, gv;
  return (heightAt, pos, groundVersion = 0) => {
    if (!last || gv !== groundVersion || Math.hypot(pos[0] - at[0], pos[1] - at[1]) > every) {
      at = [pos[0], pos[1]]; gv = groundVersion;
      const m = occluderMesh(heightAt, pos[0], pos[1], opts);
      last = { ...m, version: `${m.version},g${groundVersion}` };
    }
    return last;
  };
}

export function createLines(canvas, { onRestore = () => {} } = {}) {
  let gl, prog, loc, lost = false, scale = 0, backdrop = null;
  const cache = new Map(); // batch key -> { buf, version, count }

  function init() {
    gl = canvas.getContext('webgl', { antialias: true, alpha: false, depth: true, powerPreference: 'low-power' });
    if (!gl) throw Error('WebGL is not available in this browser');
    prog = gl.createProgram();
    for (const [type, src] of [[gl.VERTEX_SHADER, VS], [gl.FRAGMENT_SHADER, FS]]) {
      const s = gl.createShader(type); gl.shaderSource(s, src); gl.compileShader(s);
      if (!gl.getShaderParameter(s, gl.COMPILE_STATUS) && !gl.isContextLost()) throw Error(gl.getShaderInfoLog(s));
      gl.attachShader(prog, s);
    }
    gl.linkProgram(prog);
    loc = { p: gl.getAttribLocation(prog, 'a_p'), m: gl.getUniformLocation(prog, 'u_m'), off: gl.getUniformLocation(prog, 'u_off'),
      fade: gl.getUniformLocation(prog, 'u_fade'), c: gl.getUniformLocation(prog, 'u_c') };
    gl.enable(gl.BLEND); gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
    gl.depthFunc(gl.LEQUAL); gl.clearDepth(1);
    cache.clear();
  }

  canvas.addEventListener('webglcontextlost', e => { e.preventDefault(); lost = true; cache.clear(); });
  canvas.addEventListener('webglcontextrestored', () => { init(); lost = false; scale = 0; onRestore(); });
  init();

  // Uploads a batch's data once per version and binds it; returns its vertex count.
  function bind(b, data) {
    let c = cache.get(b.key);
    if (!c || c.version !== b.version) {
      if (!c) c = { buf: gl.createBuffer() };
      gl.bindBuffer(gl.ARRAY_BUFFER, c.buf); gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);
      c.version = b.version; c.count = data.length / 3; cache.set(b.key, c);
    }
    gl.bindBuffer(gl.ARRAY_BUFFER, c.buf); gl.vertexAttribPointer(loc.p, 3, gl.FLOAT, false, 0, 0);
    return c.count;
  }

  return {
    lost: () => lost,
    context: () => gl, // the headset view shares this context
    setBackdrop(fn) { backdrop = typeof fn === 'function' ? fn : null; }, // painted after the clear, before occluders and lines

    // returns true when the drawing buffer changed size
    resize(nextScale) {
      const w = Math.max(1, Math.round(canvas.clientWidth * nextScale)), h = Math.max(1, Math.round(canvas.clientHeight * nextScale));
      if (canvas.width === w && canvas.height === h && scale === nextScale) return false;
      canvas.width = w; canvas.height = h; scale = nextScale;
      return true;
    },
    // matrix: projection times the view built at the eye, i.e. view([0, 0, 0], yaw, pitch).
    // eye: the viewer's position in local metres (doubles). fade: distance in metres where lines vanish.
    // batches: [{ key, version, positions: Float32Array of x,y,z pairs, color: [r,g,b,a], origin?: [x,y,z], fade?: metres }]
    //   (a batch's own fade replaces the viewer's: the imagery drape stays readable from a drone's height)
    //   and occluders: { key, version, occluder: true, triangles: Float32Array of x,y,z triples, origin? }
    // target (headset view only): { framebuffer, viewport: [x, y, w, h], clear } draws one eye into the
    //   headset's framebuffer; clear: false keeps what the first eye drew. Without it, the canvas as before.
    // Returns the number of line vertices drawn (occluder vertices are not counted).
    draw(matrix, eye, fade, batches, target) {
      if (lost) return 0;
      const { occluders, lines } = splitBatches(batches);
      gl.bindFramebuffer(gl.FRAMEBUFFER, target ? target.framebuffer : null);
      if (target) gl.viewport(...target.viewport); else gl.viewport(0, 0, canvas.width, canvas.height);
      gl.depthMask(true);
      if (!target || target.clear !== false) { gl.clearColor(...BACKGROUND); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); }
      if (backdrop && !target) backdrop(gl, canvas.width, canvas.height); // optional solid ground (raycast.mjs), flat screen only
      gl.useProgram(prog);
      gl.uniformMatrix4fv(loc.m, false, matrix); gl.uniform1f(loc.fade, fade);
      gl.enableVertexAttribArray(loc.p);
      gl.enable(gl.DEPTH_TEST);
      // Depth only: no colour, pushed slightly back so lines lying on the surface do not z-fight with it.
      gl.colorMask(false, false, false, false);
      gl.enable(gl.POLYGON_OFFSET_FILL); gl.polygonOffset(1, 4);
      for (const b of occluders) {
        const count = bind(b, b.triangles);
        gl.uniform3fv(loc.off, offsetOf(b.origin, eye));
        gl.drawArrays(gl.TRIANGLES, 0, count);
      }
      gl.disable(gl.POLYGON_OFFSET_FILL);
      gl.colorMask(true, true, true, true);
      gl.depthMask(false); // lines are tested against the ground but never hide each other
      let vertices = 0;
      for (const b of lines) {
        const count = bind(b, b.positions);
        gl.uniform3fv(loc.off, offsetOf(b.origin, eye));
        gl.uniform1f(loc.fade, b.fade > 0 ? b.fade : fade);
        gl.uniform4fv(loc.c, b.color); gl.drawArrays(gl.LINES, 0, count);
        vertices += count;
      }
      gl.depthMask(true);
      return vertices;
    }
  };
}

OSTN15

A JavaScript module in the world folder of Energy Transition Simulator that decodes block (`decodeBlock`), gets checked (`getChecked`) and loads index (`loadIndex`), using OSTN15 and Helmert.

ingestenergy-transition-simulator / prototype/world/ostn15.mjs · lines 1–93 of 93 · Entry point · pattern loadIndex (shared by 13 files)

What it does
It fetches data. Defines 11 functions or classes, including decodeBlock, blockKey, shiftAt, at, bil. Side effects: 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.
Inputs & outputs
In: JSON file ostn15.json. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326, ETRS89 / EPSG:4258.
Downstream impact
Used directly by 4 files: Find Mount (globalgrid2050); Overlay (energy-transition-simulator); Coords Reference (energy-transition-simulator); Overlay (globalgrid2050, https://globalgrid2050.com/energy-transition-simulator/202609280014/overlay.html). 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 decodes block (`decodeBlock`), gets checked (`getChecked`) and creates OSTN15 (`createOstn15`). `bng.mjs`'s Helmert is good to about 3.5 m; this is good to about 0.1 m (OS: OSTN15 reproduces the National Grid to 0.1 m r.m.s. and its NTv2 form agrees with it to a few mm at the check points)…
Why it matters
Loaded by the Overlay map page and 1 other page. Also imported by Find Mount, from GlobalGrid2050. Checked by Coords Reference.
Application
energy-transition-simulator · prototype/world · JavaScript module
Uses
Bng (import)
Used by
imported by Find Mount (import), imported by Overlay (import), imported by Coords Reference (import), imported by Overlay (import), mentioned in Standalone (comment link)
Produces
INDEX, INDEX_SHA256, decodeBlock, blockKey, shiftAt, bngToEtrs, etrsToBng, createOstn15
Defines here
decodeBlock, blockKey, shiftAt, at, bil, bngToEtrs, etrsToBng, getChecked, createOstn15, loadIndex, need
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/world/ostn15.mjs:1-93 · blob e6add8c05989f02d6e39973d779be81545864449 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: network · domain stage: experimental · users: none · canonical: unknown
// OSTN15: the Ordnance Survey's definitive ETRS89 (GPS) <-> National Grid transformation, horizontal part.
// bng.mjs's Helmert is good to about 3.5 m; this is good to about 0.1 m (OS: OSTN15 reproduces the National Grid to
// 0.1 m r.m.s. and its NTv2 form agrees with it to a few mm at the check points), where a block is loaded.
//
// Data: OSTN15_NTv2_OSGBtoETRS (OS; PROJ data uk_os_OSTN15_NTv2_OSGBtoETRS.tif, BSD 2-Clause, derived from Ordnance
// Survey work), cut into 1-degree blocks over England by tools/ostn15/cut_ostn15.py: web/world/data/ostn15/.
// Each block is fetched only when a place inside it is converted, and hash-checked against ostn15.json.
// Nodes: 1' of longitude by 0.5' of latitude, OSGB36 latitude and longitude offsets (to ETRS89) in arc-seconds,
// bilinear between nodes (the NTv2 method). Outside the loaded blocks the Helmert answer is given, marked approx.
import { tmForward, tmInverse, bngToWgs84, wgs84ToBng } from './bng.mjs';

const RAD = Math.PI / 180, UNIT = 1e-5; // offsets are stored in 1e-5 arc-second steps
export const INDEX = 'data/ostn15/ostn15.json';
export const INDEX_SHA256 = 'da7893530d19f35b0253737cc9264d6b3fc364d0711f1aba3d2a0160e9b8f74e'; // tests/ostn15.test.mjs checks it against the file

// Pure: a block file -> { lat0, lon0, cols, rows, v: Int32Array (lat, lon offsets per node) }.
export function decodeBlock(buffer) {
  const dv = new DataView(buffer instanceof ArrayBuffer ? buffer : buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength));
  const magic = String.fromCharCode(dv.getUint8(0), dv.getUint8(1), dv.getUint8(2), dv.getUint8(3));
  if (magic !== 'O15B' || dv.getUint16(4, true) !== 1) throw Error('not an OSTN15 block (O15B version 1)');
  const cols = dv.getUint16(6, true), rows = dv.getUint16(8, true);
  if (dv.byteLength !== 16 + cols * rows * 8) throw Error(`OSTN15 block is ${dv.byteLength} bytes, expected ${16 + cols * rows * 8}`);
  const v = new Int32Array(cols * rows * 2);
  for (let k = 0; k < v.length; k++) v[k] = dv.getInt32(16 + 4 * k, true);
  return { lat0: dv.getInt16(12, true), lon0: dv.getInt16(14, true), cols, rows, v };
}

export const blockKey = (lat, lon) => `${Math.floor(lat)}_${Math.floor(lon)}`;

// Pure: the offsets at an OSGB36 latitude and longitude (degrees), in arc-seconds, or null off the loaded blocks.
export function shiftAt(blocks, lat, lon) {
  const b = blocks.get(blockKey(lat, lon));
  if (!b) return null;
  const x = (lon - b.lon0) * 60, y = (lat - b.lat0) * 120;
  const i = Math.min(b.cols - 2, Math.floor(x)), j = Math.min(b.rows - 2, Math.floor(y)), fx = x - i, fy = y - j;
  const at = (c, r, k) => b.v[2 * (r * b.cols + c) + k];
  const bil = k => ((1 - fx) * (1 - fy) * at(i, j, k) + fx * (1 - fy) * at(i + 1, j, k) + (1 - fx) * fy * at(i, j + 1, k) + fx * fy * at(i + 1, j + 1, k)) * UNIT;
  return { dlat: bil(0), dlon: bil(1) };
}

// Pure: National Grid -> ETRS89 { lat, lon } (degrees), or null where no block is loaded.
export function bngToEtrs(blocks, e, n) {
  const g = tmInverse(e, n), lat = g.lat / RAD, lon = g.lon / RAD, s = shiftAt(blocks, lat, lon);
  return s ? { lat: lat + s.dlat / 3600, lon: lon + s.dlon / 3600 } : null;
}

// Pure: ETRS89 (GPS, WGS84 to a metre) -> National Grid { e, n }, or null where no block is loaded.
// The offsets are given at the OSGB36 position, so it is found by fixed-point iteration (converges in 3 to 4 steps).
export function etrsToBng(blocks, lat, lon) {
  let la = lat, lo = lon;
  for (let k = 0; k < 6; k++) {
    const s = shiftAt(blocks, la, lo);
    if (!s) return null;
    la = lat - s.dlat / 3600; lo = lon - s.dlon / 3600;
  }
  return tmForward(la * RAD, lo * RAD);
}

// Fetch a file beside this module and refuse it unless its SHA-256 is the one given.
async function getChecked(path, sha) {
  const res = await fetch(new URL(path, import.meta.url), { cache: 'no-cache' });
  if (!res.ok) throw Error(`${path}: HTTP ${res.status}`);
  const buf = await res.arrayBuffer(), d = await globalThis.crypto.subtle.digest('SHA-256', buf);
  if ([...new Uint8Array(d)].map(b => b.toString(16).padStart(2, '0')).join('') !== sha) throw Error(`${path}: hash does not match`);
  return buf;
}

// The page's converter. get(path, sha) -> ArrayBuffer, hash-checked. Sync calls use whatever blocks are loaded and
// say whether the answer is OSTN15 or the Helmert fallback; need() loads a block.
export function createOstn15({ get = getChecked, indexSha = INDEX_SHA256 } = {}) {
  const blocks = new Map(), pending = new Map();
  let index = null;
  const loadIndex = () => (index ||= get(INDEX, indexSha).then(b => JSON.parse(new TextDecoder().decode(b))));
  async function need(lat, lon) {
    const key = blockKey(lat, lon);
    if (blocks.has(key)) return true;
    if (!pending.has(key)) {
      pending.set(key, loadIndex().then(ix => {
        const row = (ix.blocks || []).find(r => `${r.lat0}_${r.lon0}` === key);
        if (!row) return false; // outside England's blocks: Helmert stays
        return get(INDEX.replace(/[^/]+$/, row.file), row.sha256).then(buf => { blocks.set(key, decodeBlock(buf)); return true; });
      }).catch(() => false));
    }
    return pending.get(key);
  }
  return {
    need,
    needBng: (e, n) => { const g = bngToWgs84(e, n); return need(g.lat, g.lon); },
    toBng(lat, lon) { const p = etrsToBng(blocks, lat, lon); return p ? { ...p, ostn15: true } : { ...wgs84ToBng(lat, lon), ostn15: false }; },
    toLatLon(e, n) { const p = bngToEtrs(blocks, e, n); return p ? { ...p, ostn15: true } : { ...bngToWgs84(e, n), ostn15: false }; },
    blocks
  };
}