In this section
- Test Export test · data-grid-gb / repd_columnar/tests/test_export.py lines 1–174
- Addresses geodesy · energy-transition-simulator / prototype/mod/addresses.js lines 1–151
- Connect Here interaction · energy-transition-simulator / prototype/mod/connect-here.js lines 1–177
- Coords Readout geodesy · energy-transition-simulator / prototype/mod/coords-readout.js lines 1–133
Test Export
A test in the tests folder of Data Grid GB that checks Export, using SHA-256. It exports tests (`ExportTests`) and sets up (`setUp`).
testdata-grid-gb / repd_columnar/tests/test_export.py · lines 1–174 of 174 · Entry point · pattern synthetic (shared by 7 files)
- What it does
- It tests its inputs. Defines 14 functions or classes, including synthetic, ExportTests, setUp, test_all_fields_dates_null_capacity_nested_unicode_and_order_roundtrip, test_changed_byte_pin_refuses_before_output_write. Uses libraries copy, datetime, json, os, pathlib. Side effects: reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'repd'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
- Inputs & outputs
- In: JSON file v939-source.json; JSON file part-001.json; JSON file build_manifest.json; JSON file raw-descriptor.json; Parquet file repd.parquet; JSON file filtered.json; JSON file solar1000-manifest.json; JSON file measurements.json.
- Downstream impact
- Used directly by 1 file: Renewable Energy Planning Database (REPD) Columnar Workflow (data-grid-gb).
- What it achieves
- Offline prototype checks. Real integration uses an explicit pinned local checkout.
- Why it matters
- Run by Renewable Energy Planning Database (REPD) Columnar Workflow.
- Application
- data-grid-gb · repd_columnar/tests · test
- Uses
- Export (import), copy, datetime, json, os, pathlib, tempfile, unittest, unittest.mock
- Used by
- run by Renewable Energy Planning Database (REPD) Columnar Workflow (workflow run)
- Produces
- synthetic, ExportTests, PinnedSourceTests
- Defines here
- synthetic, ExportTests, setUp, test_all_fields_dates_null_capacity_nested_unicode_and_order_roundtrip, test_changed_byte_pin_refuses_before_output_write, test_unknown_capacity_is_never_zero_imputed, test_duplicate_identity_and_invalid_day_are_refused, test_population_mismatch_and_solar_order_are_refused, test_existing_or_inside_source_output_is_refused, test_another_git_worktree_output_is_refused, test_filters_are_bounded_and_parameterized, test_source_path_and_mutable_ref_are_refused, PinnedSourceTests, test_full_7775_record_source_roundtrip
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- data-grid-gb@4a9cef6c7c791f76d416c8b2fbafac8265f7a263 repd_columnar/tests/test_export.py:1-174 · blob e249355dea975e2031ccbd9f89463ecebac828bd · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
"""Offline prototype checks. Real integration uses an explicit pinned local checkout."""
import copy
import datetime
import json
import os
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
import duckdb
from repd_columnar.export import DATES, HERE, encoded, export_product, filters, git_blob, load_source, projection, sha
PIN = json.loads((HERE / "pins/v939-source.json").read_bytes())
def synthetic():
rows = []
for i in range(1001):
r = {"repd_ref": str(i + 1000), "gg_project_id": "GG2050-REPD-" + str(i + 1000),
"technology": "solar" if i < 1000 else "bess", "capacity_mw": None if i == 0 else float(i + 1),
"capacity_known": i != 0, "name": 'Synthetic, "Unicode" café\nrow ' + str(i),
"relationships": [{"repd_ref": "999999", "source_field": "fixture"}], "source_row": i + 1,
"first_seen": None if i == 0 else "2024-01-01T00:00:00Z",
"last_seen": None if i == 0 else "2024-02-01T00:00:00Z"}
r.update({d: "2025-01-02" if i % 2 else None for d in DATES})
rows.append(r)
base = "uk_renewables_pipeline/209901010000"
parts = [{"path": "data/v9.1/projects/part-001.json", "record_count": len(rows), "sha256": sha(encoded({"record_count": len(rows), "projects": rows}))}]
manifest = {"project_count": 1001, "solar_count": 1000, "source_record_count": 2000,
"project_partitions": parts, "source_identity_sha256": "d" * 64}
solar = {"ids": [str(i + 1000) for i in range(1000)], "record_count": 1001, "solar_count": 1000, "selection_count": 1000}
blobs = {base + "/data/v9.1/build_manifest.json": encoded(manifest), base + "/solar1000/manifest.json": encoded(solar),
"raw-descriptor.json": encoded({"expected": {"csv_sha256": "b" * 64, "xlsx_sha256": "c" * 64}}),
base + "/data/v9.1/projects/part-001.json": encoded({"record_count": len(rows), "projects": rows})}
pin = {"schema": "data-grid-gb.repd-columnar-input.v1", "source_commit": "a" * 40, "edition_path": base,
"expected_rows": 1001, "expected_solar": 1000, "original_source_population": 2000,
"solar1000_manifest_sha256": sha(blobs[base + "/solar1000/manifest.json"]),
"raw_descriptor_path": "raw-descriptor.json",
"raw_dataset_hashes": {"csv_sha256": "b" * 64, "xlsx_sha256": "c" * 64},
"files": [{"path": p, "bytes": len(b), "sha256": sha(b)} for p, b in blobs.items()]}
return rows, blobs, pin
class ExportTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.root = Path(self.tmp.name)
self.source = self.root / "source"
self.source.mkdir()
self.rows, self.blobs, self.pin = synthetic()
self.mock = patch("repd_columnar.export.git_blob", side_effect=lambda root, ref, path: self.blobs[path])
self.mock.start()
self.addCleanup(self.mock.stop)
self.addCleanup(self.tmp.cleanup)
def test_all_fields_dates_null_capacity_nested_unicode_and_order_roundtrip(self):
out = self.root / "result"
m = export_product(self.source, out, self.pin, limit=17, submitted_year="missing")
self.assertEqual(m["full_row_and_typed_field_readback"], "PASS")
with duckdb.connect() as db:
data = db.execute("SELECT source_ordinal,repd_ref,capacity_mw,planning_application_submitted,record_json FROM read_parquet(?) ORDER BY source_ordinal", [str(out / "repd.parquet")]).fetchall()
self.assertIsNone(data[0][2])
self.assertIsNone(data[0][3])
self.assertEqual(data[1][3], datetime.date(2025, 1, 2))
self.assertEqual([json.loads(r[-1]) for r in data], self.rows)
filtered = json.loads((out / "filtered.json").read_bytes())
self.assertEqual(filtered["rows"], self.rows[::2][:17])
self.assertEqual(filtered["matching_count"], 501)
self.assertNotEqual(m["source_package_sha256"], m["raw_dataset_hashes"]["csv_sha256"])
self.assertIsNone(filtered["rows"][0]["first_seen"])
self.assertEqual(sha((out / "solar1000-manifest.json").read_bytes()), self.pin["solar1000_manifest_sha256"])
measurements = json.loads((out / "measurements.json").read_bytes())
self.assertEqual(len(measurements["samples"]), 6)
self.assertEqual(measurements["same_selection"], "PASS")
def test_changed_byte_pin_refuses_before_output_write(self):
pin = copy.deepcopy(self.pin)
pin["files"][0]["sha256"] = "0" * 64
out = self.root / "must-not-exist"
with self.assertRaisesRegex(ValueError, "pin mismatch"):
export_product(self.source, out, pin)
self.assertFalse(out.exists())
p = copy.deepcopy(self.pin)
p["raw_dataset_hashes"]["csv_sha256"] = "f" * 64
with self.assertRaisesRegex(ValueError, "raw dataset hashes"):
load_source(self.source, p)
def test_unknown_capacity_is_never_zero_imputed(self):
self.rows[0]["capacity_mw"] = 0
path = self.pin["edition_path"] + "/data/v9.1/projects/part-001.json"
self.blobs[path] = encoded({"record_count": len(self.rows), "projects": self.rows})
part_hash = sha(self.blobs[path])
manifest_path = self.pin["edition_path"] + "/data/v9.1/build_manifest.json"
manifest = json.loads(self.blobs[manifest_path])
manifest["project_partitions"][0]["sha256"] = part_hash
self.blobs[manifest_path] = encoded(manifest)
for f in self.pin["files"]:
f.update(bytes=len(self.blobs[f["path"]]), sha256=sha(self.blobs[f["path"]]))
with self.assertRaisesRegex(ValueError, "unknown capacity"):
load_source(self.source, self.pin)
def test_duplicate_identity_and_invalid_day_are_refused(self):
for mutate in [lambda r: r[1].update(repd_ref=r[0]["repd_ref"]),
lambda r: r[1].update(planning_application_submitted="2025-99-01")]:
rows, blobs, pin = synthetic()
mutate(rows)
path = pin["edition_path"] + "/data/v9.1/projects/part-001.json"
blobs[path] = encoded({"record_count": len(rows), "projects": rows})
manifest_path = pin["edition_path"] + "/data/v9.1/build_manifest.json"
manifest = json.loads(blobs[manifest_path]);manifest["project_partitions"][0]["sha256"] = sha(blobs[path]);blobs[manifest_path] = encoded(manifest)
for f in pin["files"]:
f.update(bytes=len(blobs[f["path"]]), sha256=sha(blobs[f["path"]]))
with patch("repd_columnar.export.git_blob", side_effect=lambda root, ref, path: blobs[path]):
with self.assertRaises(ValueError):
load_source(self.source, pin)
def test_population_mismatch_and_solar_order_are_refused(self):
for field, value in [("expected_rows", 7680), ("expected_solar", 3599), ("original_source_population", 14966)]:
p = copy.deepcopy(self.pin)
p[field] = value
with self.assertRaises(ValueError):
load_source(self.source, p)
path = self.pin["edition_path"] + "/solar1000/manifest.json"
solar = json.loads(self.blobs[path]);solar["ids"].reverse();self.blobs[path] = encoded(solar)
self.pin["solar1000_manifest_sha256"] = sha(self.blobs[path])
for f in self.pin["files"]:
f.update(bytes=len(self.blobs[f["path"]]), sha256=sha(self.blobs[f["path"]]))
with self.assertRaisesRegex(ValueError, "ordered selection"):
load_source(self.source, self.pin)
def test_existing_or_inside_source_output_is_refused(self):
existing = self.root / "existing";existing.mkdir();(existing / "keep").write_text("do not replace")
for out in [existing, self.source / "derived", HERE / "output", self.root / "x/../escape"]:
with self.assertRaises(ValueError):
export_product(self.source, out, self.pin)
self.assertEqual((existing / "keep").read_text(), "do not replace")
def test_another_git_worktree_output_is_refused(self):
with patch("repd_columnar.export.subprocess.run") as run:
run.return_value.returncode = 0;run.return_value.stdout = "true\n"
with self.assertRaisesRegex(ValueError, "every Git"):
export_product(self.source, self.root / "other-repo/output", self.pin)
def test_filters_are_bounded_and_parameterized(self):
for query in [{"submitted_year": "2025 OR 1=1"}, {"technology": "solar';drop table repd;--"}, {"operational_year": "0000"}]:
with self.assertRaises(ValueError):
filters(**query)
clause, args = filters(technology="solar", submitted_year="2025", updated_year="missing")
self.assertEqual(args, ["solar", 2025]);self.assertIn("IS NULL", clause)
with self.assertRaises(ValueError):
export_product(self.source, self.root / "bad-limit", self.pin, limit=1001)
def test_source_path_and_mutable_ref_are_refused(self):
self.mock.stop()
for ref, path in [("main", "okay.json"), ("a" * 40, "../outside.json"), ("a" * 40, "C:/secret")]:
with self.assertRaises(ValueError):
git_blob(self.source, ref, path)
@unittest.skipUnless(os.environ.get("REPD_SOURCE_ROOT"), "Set REPD_SOURCE_ROOT for actual pinned integration")
class PinnedSourceTests(unittest.TestCase):
def test_full_7775_record_source_roundtrip(self):
with tempfile.TemporaryDirectory() as folder:
out = Path(folder) / "actual-output"
m = export_product(Path(os.environ["REPD_SOURCE_ROOT"]), out, PIN, limit=100, technology="solar", submitted_year="missing")
self.assertEqual((m["rows"], m["solar_rows"]), (7775, 3604))
self.assertEqual(m["solar1000_manifest_sha256"], "c625edbb9c471a1e9a9034a1afe99881fbfabb1fcadcf0623355931f5b6aed1f")
self.assertEqual(projection(out / "repd.parquet", limit=1000, operational_year="missing")["matching_count"], 5531)
if __name__ == "__main__":
unittest.main()Addresses
A JavaScript file in the prototype folder of Energy Transition Simulator that fetches postcodes, using OSTN15 and Helmert from postcodes.io.
geodesyenergy-transition-simulator / prototype/mod/addresses.js · lines 1–151 of 151 · Not reached from any entry point (candidate for review) · pattern lookupPostcode (shared by 2 files)
- What it does
- It fetches postcodes. Defines 10 functions or classes, including onGrid, classify, gridToLatLon, lookupPostcode, metres. Side effects: changes the web page (DOM); makes network requests; uses storage (browser storage, DuckDB or Parquet).
- 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: postcodes.
- Inputs & outputs
- In: data source: postcodes.io; browser storage (getItem). Out: browser storage (setItem). Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326.
- What it achieves
- It looks up postcode (`lookupPostcode`) and is built from the on grid helper (`onGrid`) and the classify step (`classify`). Type a UK postcode, a National Grid reference, an easting/northing pair or a lat, lon into the find box ("go SW1A 1AA", "go TQ 30624 78388", "go 530624 178388", "go 51.5, -0.12") and fly to the right spot. It responds to keydown events.
- Why it matters
- No other file in the estate was found to import it.
- Application
- energy-transition-simulator · prototype/mod · script
- Uses
- none found
- Used by
- mentioned in Standalone (comment link)
- Produces
- onGrid, classify, gridToLatLon, lookupPostcode, metres, marker, land, ref10, conv, go
- Defines here
- onGrid, classify, gridToLatLon, lookupPostcode, metres, marker, land, ref10, conv, go
- 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/mod/addresses.js:1-151 · blob 89c710ff875034cb6b98425e9ab799796f71deaf · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, network, storage · domain stage: experimental · users: none · canonical: duplicate_candidate
// addresses: type a UK postcode, a National Grid reference, an easting/northing pair or a lat, lon into the find box
// ("go SW1A 1AA", "go TQ 30624 78388", "go 530624 178388", "go 51.5, -0.12") and fly to the right spot.
//
// ONE conversion: every grid position (grid reference, E/N, and a postcode's published grid reference) becomes
// latitude and longitude through world/ostn15.mjs (OSTN15, the OS definitive transformation, about 0.1 m) where its
// block is held (England and Wales); elsewhere the Helmert answer from world/bng.mjs is used and the label says so.
// The typed grammar follows the site world's links.mjs parseAddress (latlon, en, gridref = the square's centre,
// postcode), which lives in another repo; its kinds were checked to agree on every test input (round-1 note).
//
// Postcodes: the open postcodes.io API (ONS Postcode Directory), at most one request per second, each answer cached
// for the page (and in this browser when storage allows). We land on the published grid reference (eastings,
// northings, 1 m) through OSTN15 and report the gap to the lat/lon postcodes.io publishes. A postcode centroid is a
// point inside the postcode's delivery points, not a building: labelled "published centroid".
//
// Provenance in every label: gridref / E,N / lat,lon = typed (exact); postcode = published centroid (ONSPD).
// Plain script: attaches to window.SIM; intercepts the find box (#fg-in) for these kinds only, before find-go.
(function () {
'use strict';
const here = document.currentScript && document.currentScript.src ? document.currentScript.src : location.href;
const base = new URL('../', here);
const API = 'https://api.postcodes.io/postcodes/';
const CREDIT_PC = 'Postcode: postcodes.io (ONS Postcode Directory; contains OS data © Crown copyright and database right, Royal Mail data © Royal Mail, OGL v3).';
// ---- grammar (after links.mjs parseAddress) ----
const LATLON = /^(-?\d{1,2}(?:\.\d+)?)\s*°?\s*([NS])?\s*[,\s]\s*(-?\d{1,3}(?:\.\d+)?)\s*°?\s*([EW])?$/i;
const EN = /^(\d{4,6}(?:\.\d+)?)\s*[,\s]\s*(\d{4,7}(?:\.\d+)?)$/;
const POSTCODE = /^[A-Z]{1,2}\d[A-Z\d]?\s*\d[A-Z]{2}$/i;
const GRIDREF = /^[A-HJ-Z]{2}\s*[\d\s]*$/i;
const onGrid = (e, n) => Number.isFinite(e) && Number.isFinite(n) && e >= 0 && e < 700000 && n >= 0 && n < 1300000;
let BNG = null, OSTN = null;
const ready = Promise.all([
import(new URL('world/bng.mjs', base).href).then(m => { BNG = m; }),
import(new URL('world/ostn15.mjs', base).href).then(m => { OSTN = m.createOstn15(); })
]);
// Pure after `ready`: text -> { kind, e?, n?, lat?, lon?, query?, digits? } or null (not an address: find-go keeps it).
function classify(raw) {
const t = String(raw ?? '').trim().replace(/^go\s+/i, '').replace(/\s+/g, ' ');
if (!t) return null;
const ll = LATLON.exec(t);
if (ll) {
let lat = +ll[1], lon = +ll[3];
if (ll[2] && /s/i.test(ll[2])) lat = -Math.abs(lat);
if (ll[4] && /w/i.test(ll[4])) lon = -Math.abs(lon);
if (Math.abs(lat) <= 90 && Math.abs(lon) <= 180) return { kind: 'latlon', lat, lon };
}
const en = EN.exec(t);
if (en && onGrid(+en[1], +en[2])) return { kind: 'en', e: +en[1], n: +en[2] };
if (GRIDREF.test(t)) {
try {
const g = BNG.parseGridRef(t), digits = t.replace(/\D/g, '').length, half = digits ? 10 ** (5 - digits / 2) / 2 : 50000;
return { kind: 'gridref', e: g.e + half, n: g.n + half, digits, text: t.toUpperCase() };
} catch (e) { /* not a grid reference after all */ }
}
if (POSTCODE.test(t)) return { kind: 'postcode', query: t.toUpperCase().replace(/^(\S+?)\s*(\d[A-Z]{2})$/, '$1 $2') };
return null;
}
// National Grid -> lat/lon, through OSTN15 when its block is held (loaded here, hash-checked), else Helmert.
async function gridToLatLon(e, n) {
await OSTN.needBng(e, n);
return OSTN.toLatLon(e, n); // { lat, lon, ostn15 }
}
// ---- postcodes.io: one request per second at most, cached ----
const cache = new Map(); let nextSlot = 0;
const store = { get(k) { try { return JSON.parse(localStorage.getItem('pc:' + k)); } catch (e) { return null; } },
set(k, v) { try { localStorage.setItem('pc:' + k, JSON.stringify(v)); } catch (e) { /* no storage: page cache only */ } } };
async function lookupPostcode(pc) {
const key = pc.replace(/\s/g, '');
if (cache.has(key)) return cache.get(key);
const kept = store.get(key); if (kept) { cache.set(key, kept); return kept; }
const wait = Math.max(0, nextSlot - Date.now()); nextSlot = Date.now() + wait + 1000;
if (wait) await new Promise(r => setTimeout(r, wait));
const res = await fetch(API + encodeURIComponent(key));
if (res.status === 404) { const miss = { missing: true }; cache.set(key, miss); return miss; }
if (!res.ok) throw new Error('postcodes.io HTTP ' + res.status);
const r = (await res.json()).result;
const v = { postcode: r.postcode, e: r.eastings, n: r.northings, lat: r.latitude, lon: r.longitude, country: r.country };
cache.set(key, v); store.set(key, v);
return v;
}
// metres between two lat/lon (local flat earth; fine at these distances)
const metres = (a, b) => { const k = Math.cos((a.lat + b.lat) * Math.PI / 360); return Math.hypot((a.lat - b.lat) * 111320, (a.lon - b.lon) * 111320 * k); };
// Marker: a 6 m ring and a 30 m ring at ground, and a 40 m mast, around the landing point.
function marker(lon, lat) {
const L = [], ring = (r, n) => { for (let i = 0; i < n; i++) { const a = 2 * Math.PI * i / n, b = 2 * Math.PI * (i + 1) / n;
L.push([r * Math.cos(a), r * Math.sin(a), 0.5, r * Math.cos(b), r * Math.sin(b), 0.5]); } };
L.push([0, 0, 0, 0, 0, 40], [-8, 0, 0.5, 8, 0, 0.5], [0, -8, 0.5, 0, 8, 0.5]); ring(6, 24); ring(30, 48);
return { lon, lat, lines: L, find: true, address: true };
}
function land(S, lat, lon, text, zoom) {
S.removeWhere(b => b.find);
const b = marker(lon, lat), PF = S.PF || (window.__pf && window.__pf.PF);
if (PF) { const an = PF.placeKey(lat, lon), off = PF.toLocal(an, lat, lon, 0);
b.lines = b.lines.map(([a, c, d, e, f, g]) => [a + off.x, c + off.y, d, e + off.x, f + off.y, g]); b.anchor = an; b.buf = PF.wireBuffer(an, b.lines); }
S.addBlock(b); S.repaint();
S.map.flyTo({ center: [lon, lat], zoom, pitch: 50, bearing: S.map.getBearing(), curve: 1.6, speed: 1.2, essential: true });
S.info(text);
last = { lat, lon, text };
}
let last = null;
const ref10 = (e, n) => { try { return BNG.gridRef(e, n, 10); } catch (x) { return '—'; } };
const conv = o => o.ostn15 ? 'OSTN15' : 'Helmert (±5 m, no OSTN15 block here)';
// text -> '' when landed, a message when not, or null when it is not an address (find-go should take it).
async function go(S, raw) {
await ready;
const a = classify(raw); if (!a) return null;
if (a.kind === 'latlon') {
await OSTN.need(a.lat, a.lon); const g = OSTN.toBng(a.lat, a.lon);
const bng = onGrid(g.e, g.n) && a.lat > 49 && a.lat < 61.5 ? ` · BNG ${ref10(g.e, g.n)} (${conv(g)})` : ' · outside the National Grid';
land(S, a.lat, a.lon, `${a.lat.toFixed(6)}, ${a.lon.toFixed(6)} · typed (exact, WGS84)${bng}.`, 17);
return '';
}
if (a.kind === 'en' || a.kind === 'gridref') {
const p = await gridToLatLon(a.e, a.n);
const what = a.kind === 'en' ? `E ${a.e} N ${a.n} · typed (exact)` : `${a.text} · typed grid reference; centre of its ${a.digits ? 10 ** (5 - a.digits / 2) : 100000} m square (E ${a.e} N ${a.n})`;
land(S, p.lat, p.lon, `${what} · ${p.lat.toFixed(7)}, ${p.lon.toFixed(7)} by ${conv(p)}.`, a.digits && a.digits <= 4 ? 13 : 17);
return '';
}
// postcode
const r = await lookupPostcode(a.query);
if (r.missing) return `${a.query}: not a live postcode on postcodes.io.`;
const p = await gridToLatLon(r.e, r.n), gap = metres(p, { lat: r.lat, lon: r.lon });
land(S, p.lat, p.lon, `${r.postcode} · published centroid (ONSPD grid ref E ${r.e} N ${r.n}, 1 m) · ${p.lat.toFixed(6)}, ${p.lon.toFixed(6)} by ${conv(p)}`
+ ` · ${gap.toFixed(1)} m from the lat/lon postcodes.io publishes · a centroid, not a building. ${CREDIT_PC}`, 17);
return '';
}
(function wait(n) {
if (!(window.SIM && window.SIM.map)) { if (n < 400) setTimeout(() => wait(n + 1), 50); return; }
const S = window.SIM;
// Take the find box's Enter for addresses only; everything else carries on to find-go untouched.
// Decided synchronously (capture phase, before find-go's own listener): until the converters load, find-go keeps it.
addEventListener('keydown', async e => {
const inp = e.target; if (!inp || inp.id !== 'fg-in' || e.key !== 'Enter' || !inp.value.trim()) return;
if (!BNG || !OSTN || !classify(inp.value)) return;
e.stopImmediatePropagation(); e.preventDefault();
const msg = document.getElementById('fg-msg'); if (msg) msg.textContent = '...';
let t; try { t = await go(S, inp.value); } catch (err) { t = 'Could not resolve: ' + err.message; }
if (msg) msg.textContent = t || ''; inp.blur();
}, true);
(function hint(k) { const i = document.getElementById('fg-in'); if (i) i.placeholder = 'go SW1A 1AA · go TQ 30 80 · go solar'; else if (k < 100) setTimeout(() => hint(k + 1), 100); })(0);
S.addresses = { go: t => go(S, t), classify: t => ready.then(() => classify(t)), gridToLatLon: (e, n) => ready.then(() => gridToLatLon(e, n)), last: () => last };
const q = new URLSearchParams(location.search).get('addr'); if (q) go(S, q);
})(0);
})();Connect Here
A JavaScript file in the prototype folder of Energy Transition Simulator that draws grid substations and cables, and uses data from the GridAtlas repository.
interactionenergy-transition-simulator / prototype/mod/connect-here.js · lines 1–177 of 177 · Not reached from any entry point (candidate for review) · pattern startPulse (shared by 2 files)
- What it does
- It draws grid substations and cables. Defines 16 functions or classes, including ready, init, btn, hav, segLen. 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: cables.
- Inputs & outputs
- In: data source: gridatlas data; GeoJSON file grid_substations.geojson. Coordinate systems named: WGS84 / EPSG:4326.
- What it achieves
- It starts pulse (`startPulse`) and is built from the ready step (`ready`) and the init step (`init`). From the map centre, find the nearest GridAtlas substation point at a chosen voltage, draw a wireframe cable route to it in real coordinates (straight, or snapped to roads via the public OSRM router on OpenStreetMap data).
- Why it matters
- No other file in the estate was found to import it.
- Application
- energy-transition-simulator · prototype/mod · script
- Uses
- none found
- Used by
- none found
- Produces
- ready, init, btn, hav, segLen, densify, chunk, boxBlock, pulseBlock, subs, roadPath, run
- Defines here
- ready, init, btn, hav, segLen, densify, chunk, boxBlock, pulseBlock, subs, roadPath, run, elec, fit, clear, startPulse
- 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/mod/connect-here.js:1-177 · blob 62a60a5afd24705512c8d5b543349bd72c56987e · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: experimental · users: none · canonical: unreached_review
// connect-here: from the map centre, find the nearest GridAtlas substation point at a chosen voltage, draw a
// wireframe cable route to it in real coordinates (straight, or snapped to roads via the public OSRM router on
// OpenStreetMap data), and show the route length and an ILLUSTRATIVE voltage drop.
// Plain script. Attaches to window.SIM { map, blocks, addBlock, removeWhere, repaint, info, addButton? }
// and uses the page's place frame (window.__pf.PF or SIM.PF) so every vertex goes through the same WGS84 ->
// tangent-plane -> Mercator path as the rest of the wireframe.
//
// Coordinates: the route is cut into chunks of at most 150 m of path. Each chunk is its own block, anchored on
// the 100 m place lattice at the chunk start, its vertices in tangent-plane metres (PF.toLocal) and packed once
// into a Float32 buffer (PF.wireBuffer). So the cable follows the terrain chunk by chunk and never loses float
// precision, however long the route. The travelling pulse is one small block whose anchor moves; its buffer is
// never rebuilt.
//
// Voltage drop: the formula of the isolated star-join code (electrical.mjs, equations V10-R-001 R = R'.L.k and
// V10-V-001 dV = I.R), applied per phase with k = sqrt(3) for a balanced three-phase line-to-line drop.
// Resistive only (reactance ignored). Conductor data are typical round figures, NOT a design.
(function () {
'use strict';
const GA = 'https://ventusltd.github.io/gridatlas/atlas/releases/202608300453-atlas-v9/data/grid_substations.geojson';
const OSRM = 'https://router.project-osrm.org/route/v1/driving/';
// Illustrative conductor per voltage: R' (ohm/km, AC at 90 C, rounded) and a buried rating (A) per circuit.
const CABLE = {
33: { name: '3 x 1c 630 mm2 Al XLPE', r: 0.064, amp: 590 },
132: { name: '3 x 1c 1000 mm2 Al XLPE', r: 0.039, amp: 900 },
275: { name: '3 x 1c 2000 mm2 Cu XLPE', r: 0.013, amp: 1500 },
400: { name: '3 x 1c 2500 mm2 Cu XLPE', r: 0.011, amp: 1800 },
};
const KV = [33, 132, 275, 400], MW = [10, 20, 50, 100, 200], PF_COS = 0.95, CHUNK = 150;
const q = new URLSearchParams(location.search);
const st = { kv: KV.includes(+q.get('ckv')) ? +q.get('ckv') : 132, mw: +q.get('cmw') > 0 ? +q.get('cmw') : 50,
road: q.get('croad') !== '0', subs: null, pulse: null, raf: 0, busy: false, last: null };
const ready = () => window.SIM && (window.SIM.PF || (window.__pf && window.__pf.PF)) && window.SIM.map;
(function wait(n) { if (ready()) init(); else if (n < 400) setTimeout(() => wait(n + 1), 50); })(0);
function init() {
const SIM = window.SIM, PF = SIM.PF || window.__pf.PF, map = SIM.map;
const btn = (label, fn) => {
if (SIM.addButton) return SIM.addButton(label, fn);
const b = document.createElement('button'); b.textContent = label; b.onclick = fn;
(document.getElementById('bar') || document.body).appendChild(b); return b;
};
const go = btn('Connect here', () => run());
const kvB = btn(`to ${st.kv} kV`, () => { st.kv = KV[(KV.indexOf(st.kv) + 1) % KV.length]; kvB.textContent = `to ${st.kv} kV`; if (st.last) run(); });
const mwB = btn(`${st.mw} MW`, () => { st.mw = MW[(MW.indexOf(st.mw) + 1) % MW.length] || 50; mwB.textContent = `${st.mw} MW`; if (st.last) run(st.last); });
const rdB = btn(st.road ? 'Road route' : 'Straight', () => { st.road = !st.road; rdB.textContent = st.road ? 'Road route' : 'Straight'; if (st.last) run(st.last); });
// ---- geometry helpers (all through the page's place frame) ----
const R_MEAN = 6371008.8, rad = d => d * Math.PI / 180;
function hav(a, b) { // [lon, lat] great-circle metres, used only to rank candidates
const dl = rad(b[1] - a[1]), dn = rad(b[0] - a[0]);
const h = Math.sin(dl / 2) ** 2 + Math.cos(rad(a[1])) * Math.cos(rad(b[1])) * Math.sin(dn / 2) ** 2;
return 2 * R_MEAN * Math.asin(Math.sqrt(h));
}
function segLen(a, b) { const an = PF.placeKey(a[1], a[0]), p = PF.toLocal(an, a[1], a[0]), r = PF.toLocal(an, b[1], b[0]); return Math.hypot(r.x - p.x, r.y - p.y); }
// Densify so no step exceeds 50 m (a straight route is a geodesic-ish line of real points, not two ends).
function densify(path) {
const out = [path[0]];
for (let i = 1; i < path.length; i++) {
const a = path[i - 1], b = path[i], n = Math.ceil(segLen(a, b) / 50);
for (let k = 1; k <= n; k++) {
if (n > 1 && k < n) { const t = k / n, an = PF.placeKey(a[1], a[0]), p = PF.toLocal(an, a[1], a[0]), r = PF.toLocal(an, b[1], b[0]);
const g = PF.fromLocal(an, p.x + (r.x - p.x) * t, p.y + (r.y - p.y) * t); out.push([g.lon, g.lat]); }
else out.push(b);
}
}
return out;
}
// Cut a lon/lat path into chunk blocks; returns { blocks, length, marks } (marks: [lon,lat] each 1 km).
function chunk(path) {
const out = []; let i = 0, total = 0, nextMark = 1000; const marks = [];
while (i < path.length - 1) {
const an = PF.placeKey(path[i][1], path[i][0]), L = []; let run = 0, prev = PF.toLocal(an, path[i][1], path[i][0]);
while (i < path.length - 1 && run < CHUNK) {
const b = path[i + 1], p = PF.toLocal(an, b[1], b[0]), d = Math.hypot(p.x - prev.x, p.y - prev.y);
for (const o of [-1.2, 0, 1.2]) { // three phases, 1.2 m apart across the route, 1.5 m above ground
const ux = d ? -(p.y - prev.y) / d * o : 0, uy = d ? (p.x - prev.x) / d * o : 0;
L.push([prev.x + ux, prev.y + uy, 1.5, p.x + ux, p.y + uy, 1.5]);
}
if (total + run + d >= nextMark) { L.push([p.x, p.y, 0, p.x, p.y, 8], [p.x - 2, p.y, 8, p.x + 2, p.y, 8]); marks.push(b); nextMark += 1000; }
run += d; prev = p; i++;
}
L.push([prev.x, prev.y, 0, prev.x, prev.y, 3]); // route marker post at each chunk end
total += run;
out.push({ lon: an.lon, lat: an.lat, anchor: an, lines: L, buf: PF.wireBuffer(an, L), connect: true });
}
return { blocks: out, length: total, marks };
}
function boxBlock(lon, lat, s, h, extra) { // a wireframe compound (substation) or a mast at the start
const an = PF.placeKey(lat, lon), c = PF.toLocal(an, lat, lon), L = [], p = [[-s, -s], [s, -s], [s, s], [-s, s]];
for (let k = 0; k < 4; k++) { const a = p[k], b = p[(k + 1) % 4];
L.push([c.x + a[0], c.y + a[1], 0, c.x + b[0], c.y + b[1], 0], [c.x + a[0], c.y + a[1], h, c.x + b[0], c.y + b[1], h], [c.x + a[0], c.y + a[1], 0, c.x + a[0], c.y + a[1], h]); }
if (extra) extra(L, c);
return { lon: an.lon, lat: an.lat, anchor: an, lines: L, buf: PF.wireBuffer(an, L), connect: true };
}
function pulseBlock(lon, lat) { // a small diamond; its buffer is built once and its anchor is moved
const an = PF.placeKey(lat, lon), s = 6, h = 4, L = [[-s, 0, h, 0, -s, h], [0, -s, h, s, 0, h], [s, 0, h, 0, s, h], [0, s, h, -s, 0, h],
[-s, 0, h, 0, 0, h + 8], [s, 0, h, 0, 0, h + 8], [0, -s, h, 0, 0, h + 8], [0, s, h, 0, 0, h + 8]];
return { lon: an.lon, lat: an.lat, anchor: { ...an }, lines: L, buf: PF.wireBuffer(an, L), connect: true, pulse: true };
}
async function subs() {
if (st.subs) return st.subs;
const j = await (await fetch(GA)).json();
st.subs = j.features.filter(f => f.geometry && f.geometry.type === 'Point').map(f => ({
c: f.geometry.coordinates, kv: String(f.properties.voltage || '').split(';').map(v => Math.round(+v / 1000)).filter(v => v > 0) }));
return st.subs;
}
async function roadPath(a, b) {
try {
const r = await fetch(`${OSRM}${a[0]},${a[1]};${b[0]},${b[1]}?overview=full&geometries=geojson`, { signal: AbortSignal.timeout(8000) });
const j = await r.json(); const g = j.routes && j.routes[0] && j.routes[0].geometry.coordinates;
return g && g.length > 1 ? [a, ...g, b] : null; // straight stubs from the site to the road and road to the point
} catch (e) { return null; }
}
async function run(from) {
if (st.busy) return; st.busy = true; go.textContent = 'Connecting...';
try {
const c = map.getCenter(), here = from || [c.lng, c.lat]; st.last = here;
const all = await subs(); let best = null, bd = Infinity;
for (const s of all) if (s.kv.includes(st.kv)) { const d = hav(here, s.c); if (d < bd) { bd = d; best = s; } }
if (!best) { SIM.info(`No ${st.kv} kV substation point in the GridAtlas data.`); return; }
const straight = densify([here, best.c]); let path = straight, how = 'straight line';
if (st.road) { const rp = await roadPath(here, best.c); if (rp) { path = densify(rp); how = 'road route (OSRM, OpenStreetMap)'; } else how = 'straight line (road router unavailable)'; }
clear();
const ch = chunk(path), straightLen = chunk(straight).length;
const mast = boxBlock(here[0], here[1], 3, 40, (L, c) => L.push([c.x, c.y, 40, c.x, c.y, 55]));
const sub = boxBlock(best.c[0], best.c[1], 30, 10, (L, c) => { for (let x = -20; x <= 20; x += 10) L.push([c.x + x, c.y - 30, 10, c.x + x, c.y + 30, 10]); L.push([c.x, c.y, 10, c.x, c.y, 25]); });
SIM.addBlock(mast); SIM.addBlock(sub);
// Animate: lay the chunks one by one from the site to the substation, then run a pulse along the cable.
const km = ch.length / 1000, e = elec(ch.length);
SIM.info(`Laying ${km.toFixed(2)} km route...`);
fit(path);
let k = 0; const per = Math.max(1, Math.ceil(ch.blocks.length / 90));
await new Promise(done => { (function lay() { for (let n = 0; n < per && k < ch.blocks.length; n++) SIM.addBlock(ch.blocks[k++]); if (k < ch.blocks.length) requestAnimationFrame(lay); else done(); })(); });
startPulse(path);
SIM.info(`Connect here (ESTIMATE, not a design): nearest ${st.kv} kV substation point ${(straightLen / 1000).toFixed(2)} km straight; ` +
`cable by ${how}: ${km.toFixed(2)} km. At ${st.mw} MW, pf ${PF_COS}: ${e.I.toFixed(0)} A, ${e.n} circuit(s) of ${CABLE[st.kv].name} (R' ${CABLE[st.kv].r} ohm/km, assumed) ` +
`-> drop about ${(e.dV / 1000).toFixed(2)} kV (${e.pct.toFixed(2)} %), loss about ${(e.loss / 1e6).toFixed(2)} MW. Resistive only, reactance ignored. ` +
`Data: GridAtlas substation points${st.road ? '; route © OpenStreetMap contributors via OSRM' : ''}.`);
window.__connect = { here, sub: best.c, kv: st.kv, mw: st.mw, how, straight_m: straightLen, route_m: ch.length, blocks: ch.blocks.length + 2, marks: ch.marks.length, ...e };
} catch (err) { SIM.info('Connect here failed: ' + err.message); }
finally { st.busy = false; go.textContent = 'Connect here'; }
}
// dV (line-to-line) = I . R, R = R' . L . sqrt(3) / n (n parallel circuits); loss = 3 I^2 R' L / n.
function elec(len) {
const cab = CABLE[st.kv], V = st.kv * 1000, I = st.mw * 1e6 / (Math.sqrt(3) * V * PF_COS);
const n = Math.max(1, Math.ceil(I / cab.amp)), Rph = cab.r * len / 1000 / n;
const dV = I * Rph * Math.sqrt(3);
return { I, n, dV, pct: 100 * dV / V, loss: 3 * I * I * Rph };
}
function fit(path) {
let w = 180, s = 90, e = -180, nn = -90; for (const [x, y] of path) { w = Math.min(w, x); e = Math.max(e, x); s = Math.min(s, y); nn = Math.max(nn, y); }
const H = map.getContainer().clientHeight, W = map.getContainer().clientWidth;
map.fitBounds([[w, s], [e, nn]], { padding: { top: Math.round(H * 0.3), bottom: Math.round(H * 0.2), left: Math.round(W * 0.1), right: Math.round(W * 0.1) }, pitch: 45, duration: 1200, maxZoom: 16 });
}
function clear() { cancelAnimationFrame(st.raf); st.pulse = null; SIM.removeWhere(b => b.connect); }
function startPulse(path) {
// Cumulative distances along the path, then move one prebuilt block's anchor along it for 15 s.
const cum = [0]; for (let i = 1; i < path.length; i++) cum.push(cum[i - 1] + segLen(path[i - 1], path[i]));
const total = cum[cum.length - 1], p = pulseBlock(path[0][0], path[0][1]); st.pulse = p; SIM.addBlock(p);
const speed = Math.max(300, total / 6), t0 = performance.now();
(function step(t) {
if (st.pulse !== p) return;
const s = ((t - t0) / 1000 * speed) % total; let i = 1; while (i < cum.length - 1 && cum[i] < s) i++;
const f = (s - cum[i - 1]) / Math.max(1e-9, cum[i] - cum[i - 1]), a = path[i - 1], b = path[i];
p.anchor = { ...p.anchor, lon: a[0] + (b[0] - a[0]) * f, lat: a[1] + (b[1] - a[1]) * f };
SIM.repaint();
if (t - t0 < 15000) st.raf = requestAnimationFrame(step);
else { p.anchor = { ...p.anchor, lon: path[path.length - 1][0], lat: path[path.length - 1][1] }; SIM.repaint(); }
})(t0);
}
window.__connectRun = run;
if (q.get('connect') === '1') setTimeout(() => run(), 1500);
}
})();Coords Readout
A JavaScript file in the prototype folder of Energy Transition Simulator that loads tile (`loadTile`) and draws on a canvas, covering LiDAR terrain, using OSTN15 and Helmert.
geodesyenergy-transition-simulator / prototype/mod/coords-readout.js · lines 1–133 of 133 · Not reached from any entry point (candidate for review) · pattern tileFor (shared by 2 files)
- What it does
- It draws LiDAR terrain. Defines 12 functions or classes, including start, place, tileFor, loadTile, heightAt. 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. Domain terms in the code: LiDAR terrain.
- Inputs & outputs
- Out: canvas drawing. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326.
- What it achieves
- It loads tile (`loadTile`) and is built from the start step (`start`) and the place step (`place`). An always-visible coordinate HUD in the morning engine's style (small monospace, grey on black, red for the rule line). It responds to resize and click events.
- Why it matters
- No other file in the estate was found to import it.
- Application
- energy-transition-simulator · prototype/mod · script
- VEDIC
- HEIGHT (GG2050-VEDIC-000011): Solar Design Studio / LiDAR · Mathematics / Raster sampling. bng_easting_m, bng_northing_m → height_receipt_or_null
- Uses
- none found
- Used by
- none found
- Produces
- start, place, tileFor, loadTile, heightAt, h, surveyOn, lidarCached, inGB, esc, render, kick
- Defines here
- start, place, tileFor, loadTile, heightAt, h, surveyOn, lidarCached, inGB, esc, render, kick
- 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/mod/coords-readout.js:1-133 · blob e4caf9a0d89f4e4977368a585d96101abfe5acca · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: experimental · users: none · canonical: unreached_review
// coords-readout: an always-visible coordinate HUD in the morning engine's style (small monospace, grey on black,
// red for the rule line). It reads the map centre (where Walk and Drone stand) and shows:
// BNG the 10-figure National Grid reference, from the world's own bng.mjs, corrected by OSTN15 where the
// block is loaded (about 0.1 m), else the Helmert answer, flagged as an estimate (about 3.5 m);
// WGS84 latitude and longitude;
// ASL height above sea level of the ground under the centre, read from the open terrain tiles (Terrarium,
// heights to mean sea level, a 30 m class model: an estimate, labelled so);
// HDG the compass heading of the view, and the tilt;
// the ground line: "Ground: satellite + open terrain", or in survey mode "LiDAR 1 m (cached)" only when a cached
// LiDAR tile is reported for this place (SIM.lidarAt(lat, lon) true); otherwise it says LiDAR is not cached here.
// Light: no WebGL, no blocks; one DOM panel updated at most once per animation frame; one terrain tile fetched per
// 600 m square (z15) and kept. Plain script: attaches to window.SIM (waits for it).
(function () {
const here = document.currentScript && document.currentScript.src ? document.currentScript.src : location.href;
const base = new URL('../', here);
const TERRAIN = 'https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png';
const TZ = 15;
function start(SIM) {
const map = SIM.map;
let BNG = null, OSTN = null;
import(new URL('world/bng.mjs', base).href).then(m => { BNG = m; kick(); }).catch(() => {});
import(new URL('world/ostn15.mjs', base).href).then(m => { OSTN = m.createOstn15(); kick(); }).catch(() => {});
// ---- panel ----
const css = document.createElement('style');
css.textContent = `#coords-hud{position:absolute;left:8px;z-index:3;pointer-events:none;max-width:calc(100vw - 32px);
font:11px/1.45 ui-monospace,SFMono-Regular,Consolas,monospace;letter-spacing:.04em;color:#d0d4d8;
background:rgba(0,0,0,.72);border:1px solid rgba(208,212,216,.25);border-radius:4px;padding:6px 9px;white-space:pre}
#coords-hud b{color:#fff;font-weight:600}#coords-hud .k{color:#8a9096}#coords-hud .r{color:#ff3b30;opacity:.85}
#coords-hud .s{color:#8a9096;font-size:9.5px}`;
document.head.appendChild(css);
const hud = document.createElement('div');
hud.id = 'coords-hud';
document.body.appendChild(hud);
const bar = document.getElementById('bar');
const place = () => { hud.style.top = ((bar ? bar.getBoundingClientRect().bottom : 8) + 6) + 'px'; };
place(); addEventListener('resize', place);
if (bar && window.ResizeObserver) new ResizeObserver(place).observe(bar); // other modules add buttons later
// ---- terrain height: own tile sampler, independent of style changes and exaggeration ----
const tiles = new Map();
function tileFor(lat, lon) {
const n = 2 ** TZ, x = (lon + 180) / 360 * n, s = Math.sin(lat * Math.PI / 180);
const y = (0.5 - Math.log((1 + s) / (1 - s)) / (4 * Math.PI)) * n;
return { tx: Math.floor(x), ty: Math.floor(y), px: (x % 1) * 256, py: (y % 1) * 256 };
}
function loadTile(tx, ty) {
const key = tx + '/' + ty;
if (tiles.has(key)) return tiles.get(key);
const rec = { data: null, failed: false };
tiles.set(key, rec);
const img = new Image();
img.crossOrigin = 'anonymous';
img.onload = () => {
try {
const c = document.createElement('canvas'); c.width = c.height = 256;
const g = c.getContext('2d', { willReadFrequently: true }); g.drawImage(img, 0, 0);
rec.data = g.getImageData(0, 0, 256, 256).data;
} catch (e) { rec.failed = true; }
kick();
};
img.onerror = () => { rec.failed = true; kick(); };
img.src = TERRAIN.replace('{z}', TZ).replace('{x}', tx).replace('{y}', ty);
return rec;
}
function heightAt(lat, lon) {
const t = tileFor(lat, lon), rec = loadTile(t.tx, t.ty);
if (rec.data) { // bilinear inside the tile
const d = rec.data, x = Math.min(254.999, Math.max(0, t.px - 0.5)), y = Math.min(254.999, Math.max(0, t.py - 0.5));
const i = Math.floor(x), j = Math.floor(y), fx = x - i, fy = y - j;
const h = (c, r) => { const k = 4 * (r * 256 + c); return d[k] * 256 + d[k + 1] + d[k + 2] / 256 - 32768; };
return { h: (1 - fx) * (1 - fy) * h(i, j) + fx * (1 - fy) * h(i + 1, j) + (1 - fx) * fy * h(i, j + 1) + fx * fy * h(i + 1, j + 1), src: 'tile' };
}
const q = map.queryTerrainElevation && map.getTerrain && map.getTerrain() ? map.queryTerrainElevation([lon, lat]) : null;
if (q != null && Number.isFinite(q)) return { h: q / ((map.getTerrain() || {}).exaggeration || 1), src: 'map' };
return { h: null, src: rec.failed ? 'failed' : 'loading' };
}
// ---- survey state: read from the page, never assumed ----
const surveyOn = () => (typeof SIM.survey === 'function' ? !!SIM.survey() : !!document.querySelector('#survey.on'));
const lidarCached = (lat, lon) => (typeof SIM.lidarAt === 'function' ? !!SIM.lidarAt(lat, lon) : false);
const inGB = (lat, lon) => lat > 49 && lat < 61.5 && lon > -9 && lon < 2.5;
const esc = s => String(s).replace(/[&<>]/g, c => ({ '&': '&', '<': '<', '>': '>' })[c]);
let lastBlock = '';
function render() {
const c = map.getCenter(), lat = c.lat, lon = c.lng;
const rows = [];
// BNG
if (!inGB(lat, lon)) rows.push(`<span class="k">BNG </span>outside GB: no National Grid`);
else if (!BNG) rows.push(`<span class="k">BNG </span>loading converter…`);
else {
const bk = Math.floor(lat) + '_' + Math.floor(lon);
if (OSTN && bk !== lastBlock) { lastBlock = bk; OSTN.need(lat, lon).then(kick); }
const t = OSTN ? OSTN.toBng(lat, lon) : Object.assign(BNG.wgs84ToBng(lat, lon), { ostn15: false });
let ref = '—';
try { ref = BNG.gridRef(t.e, t.n, 10); } catch (e) { /* off grid */ }
rows.push(`<span class="k">BNG </span><b>${esc(ref)}</b> <span class="s">E ${t.e.toFixed(1)} N ${t.n.toFixed(1)}</span>`);
rows.push(`<span class="s"> ${t.ostn15 ? 'OSTN15 (OS definitive, ~0.1 m)' : 'Helmert estimate (~3.5 m), OSTN15 not loaded'}</span>`);
}
// WGS84
const ns = lat >= 0 ? 'N' : 'S', ew = lon >= 0 ? 'E' : 'W';
rows.push(`<span class="k">WGS84 </span>${Math.abs(lat).toFixed(6)}° ${ns} ${Math.abs(lon).toFixed(6)}° ${ew}`);
// Height
const h = heightAt(lat, lon);
rows.push(`<span class="k">ASL </span>${h.h == null ? (h.src === 'failed' ? 'terrain unavailable' : 'reading terrain…') : `≈ ${h.h.toFixed(1)} m`} <span class="s">${h.h == null ? '' : 'estimate, open terrain model'}</span>`);
// Heading
const hd = (map.getBearing() % 360 + 360) % 360;
const pts = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'][Math.round(hd / 45) % 8];
rows.push(`<span class="k">HDG </span>${String(Math.round(hd)).padStart(3, '0')}° ${pts} <span class="s">tilt ${Math.round(map.getPitch())}° z${map.getZoom().toFixed(1)}</span>`);
// Ground line
const sv = surveyOn();
const gl = sv ? (lidarCached(lat, lon) ? 'LiDAR 1 m (cached)' : 'Survey grid 10 m · LiDAR 1 m not cached here') : 'Ground: satellite + open terrain';
rows.push(`<span class="r">${esc(gl)}</span>`);
rows.push(`<span class="s">Grid: OS National Grid, OSTN15</span>`, `<span class="s">Terrain: AWS Terrain Tiles (open)</span>`);
hud.innerHTML = rows.join('\n');
}
let queued = false;
function kick() { if (queued) return; queued = true; requestAnimationFrame(() => { queued = false; render(); }); }
map.on('move', kick); map.on('styledata', kick); map.on('load', kick);
document.addEventListener('click', e => { if (e.target && e.target.closest && e.target.closest('#bar')) { setTimeout(place, 0); setTimeout(kick, 50); } });
SIM.coordsReadout = { render: kick, heightAt };
kick();
}
(function wait(n) {
if (window.SIM && window.SIM.map) start(window.SIM);
else if (n < 400) setTimeout(() => wait(n + 1), 50);
})(0);
})();