GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Solar and storage design / globalgrid2050 / solar-design-studio/202609270402-site-world-v3/world

Substrate and 1 more file

A JavaScript module in the world folder of GlobalGrid2050 that sets origin (`setOrigin`), writes readout (`writeReadout`), opens panel (`openPanel`) and calculates planar distances (units: kV).

476 lines of JavaScript from globalgrid2050, in 2 files. Topic: Solar and storage design. Section 152 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. Substrate geodesy · globalgrid2050 / solar-design-studio/202609270402-site-world-v3/world/substrate.mjs lines 1–387
  2. Block Export ingest · globalgrid2050 / solar-design-studio/202609270439-site-world/world/block-export.mjs lines 1–89

Substrate

A JavaScript module in the world folder of GlobalGrid2050 that sets origin (`setOrigin`), writes readout (`writeReadout`), opens panel (`openPanel`) and calculates planar distances (units: kV).

geodesyglobalgrid2050 / solar-design-studio/202609270402-site-world-v3/world/substrate.mjs · lines 1–387 of 387 · version 2026-09-27 04:02 · Entry point · pattern groundSource (shared by 2 files)

What it does
It draws attribution, overhead lines (OHL), LiDAR terrain and substations. Defines 28 functions or classes, including $, fadeAt, tourPlaying, live, shown. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: overhead lines (OHL), LiDAR terrain, substations.
Inputs & outputs
In: JSON file attribution.json. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
Downstream impact
Used directly by 1 file: Solar Design Studio — Site World V3 Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609270402-site-world-v3/).
What it achieves
It sets origin (`setOrigin`), writes readout (`writeReadout`) and opens panel (`openPanel`). The substrate: an empty world you can move around in. It reads `./world/data/attribution.json`. It responds to click, resize and close events.
Why it matters
Loaded by the Site World V3 page at https://globalgrid2050.com/solar-design-studio/202609270402-site-world-v3/.
Application
globalgrid2050 · solar-design-studio/202609270402-site-world-v3/world · JavaScript module
VEDIC
HEIGHT (GG2050-VEDIC-000011): Solar Design Studio / LiDAR · Mathematics / Raster sampling. bng_easting_m, bng_northing_m → height_receipt_or_null
Uses
Links (import), Camera (import), Views (import), Frame Gate (import), Device Budget (import), Lines (import), Input (import), Layers (import), and 10 more
Used by
preloaded by Solar Design Studio — Site World V3 Page (modulepreload)
Produces
$, fadeAt, tourPlaying, live, shown, guarded, baseHeight, measuredAt, known, groundSource, heightAt, solids
Defines here
$, fadeAt, tourPlaying, live, shown, guarded, baseHeight, measuredAt, known, groundSource, heightAt, solids, invalidate, gridAssets, setOrigin, playing, target, moving, flyTo, draw, collect, chooseView, writeReadout, openPanel, writeCredits, skip, nearestSub, panelOpen
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609270402-site-world-v3/world/substrate.mjs:1-387 · blob 328a292d74e8a04afbbd6771893101ff9e263543 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
// The substrate: an empty world you can move around in. It owns the loop, the camera and the views;
// everything you see comes from layers listed in manifest.json, plus the design being drawn (trenches and cables).
// Positions are local metres from the site origin, which is held in float64 British National Grid metres
// (0, 0 until a site is chosen). setOrigin moves the origin and shifts the viewer so they stay put in the world;
// walking more than 600 m from the origin moves it to the nearest whole kilometre (origin.mjs).
// The design is kept in memory in national-grid metres, so it survives every move of the origin.

import { gridAtlasUrl } from './links.mjs';
import { perspective, view, multiply } from './camera.mjs';
import { VIEWS, fpsOf, step, look, setView, toggle, blocked, AERIAL_MIN_CLEARANCE } from './views.mjs';
import { createFrameGate } from './frame-gate.mjs';
import { initialBudget, adjust } from './device-budget.mjs';
import { createLines } from './lines.mjs';
import { attachInput } from './input.mjs';
import { loadLayers, statusLine } from './layers.mjs';
import { rebaseIfNeeded, toBng, toLocal } from './origin.mjs';
import { arrive } from './arrival.mjs';
import { gridRef } from './bng.mjs';
import { aboutList } from './attribution.mjs';
import { siteFromUrl } from './sites-ui.mjs';
import { sourceKeysFor, OPTIONAL_LAYERS } from './layers-panel.mjs';
import { createLiveTerrain } from './wcs-terrain.mjs';
import { attachLift, TAP_M } from './lift.mjs';
import { fadeFor, farPlane, FADE_M } from './fade.mjs';
// Design, Find, the project tools (file, print, tour, phases), the plan inset, the headset view and the layer
// panels load just after the first frame, not before it (review E, win 2): see "after the first frame" below.
const TOOLS = ['./design-ui.mjs', './find-mount.mjs', './plan-wire.mjs', './project-ui.mjs', './xr.mjs', './layers-ui.mjs',
  './sun-ui.mjs', './buffers-ui.mjs', './ground-readout.mjs', './sun-mode.mjs', './first-showing.mjs', './ohl-ui.mjs', './help.mjs'];

const $ = id => document.getElementById(id);
const canvas = $('view'), where = $('where-line'), status = $('status');
// Layer diagnostics sit behind a closed "Layer details" in Controls; ?debug=1 opens them.
if (new URLSearchParams(location.search).get('debug') === '1') $('layer-details').open = true;
const fadeAt = () => fadeFor(state.view, state.pos[2] - heightAt(state.pos[0], state.pos[1]), layersUi?.rangeM() || 0); // fade.mjs
const FOV = 70 * Math.PI / 180, MAX_DT = 0.1, ARRIVAL_FPS = 30, ARRIVAL = { height: 80, seconds: 3 };
const JUMP_M = 3000;      // further than this, Find moves the origin and drops in from above instead of flying across
const SITE_HALF_M = 1024; // half the staged site's side: terrain tiles exist within this of its centre
const OBLIQUE = { pitch: -35 * Math.PI / 180, back: 150 }; // arriving at a found place: 35 degrees down from 150 m out

let state = { view: 'standing', pos: [0, -25, 0], yaw: 0, pitch: -0.12 };
let budget = initialBudget(devicePixelRatio);
let loaded = { generation: '', layers: [] }, vertices = 0;
let origin = { e: 0, n: 0, id: 0 };
let groundVersion = 0; // bumped whenever a layer says new ground has arrived, or the origin moves
let lastGround = 0;    // the last ground height found near the viewer; used where no layer knows the height
let arrival = null;    // { pose, t0 } while the drone flies itself somewhere
const GROUND_MEMORY_M = 20;
// Extensions (plan inset, project tools) run before and after each drawn frame; lastBatches is what the frame drew.
const hooks = { before: new Set(), after: new Set(), design: new Set() };
let lastBatches = [];
let sunMode = null, first = null; // after the first frame: sun-mode.mjs (plays at up to 30 fps), first-showing.mjs (cards, pin)
let tourPlaying = () => false; // set once the project tools are mounted: a playing tour draws at 30 fps

const live = () => loaded.layers.filter(l => l.layer);
let layersUi = null, groundReadout = null, ohl = null; // the Layers panel (dash button, layers-ui.mjs): an optional layer switched off is hidden
const shown = () => live().filter(l => !l.hidden);
// A layer that throws is switched off and named; it never takes the rest of the world down with it.
const guarded = (l, fn, fallback) => {
  try { return fn(); } catch (e) { l.layer = null; l.status = 'failed and switched off: ' + e.message; return fallback; }
};
// The ground the layers know, before any design cuts it.
const baseHeight = (x, y) => {
  for (const l of live()) {
    if (typeof l.layer.heightAt !== 'function') continue;
    const h = guarded(l, () => l.layer.heightAt(x, y), NaN);
    if (Number.isFinite(h)) {
      if (Math.hypot(x - state.pos[0], y - state.pos[1]) <= GROUND_MEMORY_M) lastGround = h;
      return h;
    }
  }
  return lastGround; // the empty world is flat at 0 m; past the edge of known ground, keep the last height
};
// Ground actually measured by a layer at (x, y), or NaN: engineering checks use this, never a guess.
const measuredAt = (x, y) => {
  for (const l of live()) if (typeof l.layer.heightAt === 'function') { const h = guarded(l, () => l.layer.heightAt(x, y), NaN); if (Number.isFinite(h)) return h; }
  return NaN;
};
// Whether a layer measured the ground at (x, y): off it, layers leave out what would stand there (water and roads
// past the LiDAR, tester 7).
const known = (x, y) => Number.isFinite(measuredAt(x, y));
// Which layer the ground at (x, y) comes from, in words for the readout.
const GROUND_WORDS = { terrain: 'LiDAR', 'terrain-live': 'live EA LiDAR' }; // the Controls status spells out LIVE_LABEL
const groundSource = (x, y) => {
  for (const l of live()) {
    if (typeof l.layer.heightAt !== 'function') continue;
    if (Number.isFinite(guarded(l, () => l.layer.heightAt(x, y), NaN))) return l.id;
  }
  return null;
};
// The ground everyone stands on: the layers' ground with every finished trench cut into it (design-ui.mjs).
const heightAt = (x, y) => design.heightAt(x, y);
// Solids are what a person or drone cannot pass through; layers declare them as boxes in local metres.
const solids = () => shown().flatMap(l => (typeof l.layer.solids === 'function' ? guarded(l, () => l.layer.solids({ pos: state.pos }), []) : []));

const lines = createLines(canvas, { onRestore: () => gate.invalidate() });
const gate = createFrameGate(draw);
// A layer asks for a redraw; { ground: true } (the default) also says new ground has arrived.
const invalidate = ({ ground = true } = {}) => { if (ground) groundVersion++; gate.invalidate(); };

// Grid equipment the design measures its routes against: substations and towers from the grid layer, if loaded.
function gridAssets() {
  const model = live().find(l => l.id === 'grid')?.layer?.debug?.()?.model;
  if (!model) return [];
  const subs = (model.substations || []).map(s => ({ kind: 'substation', label: `${s.cls} substation`, e: s.e, n: s.n,
    kv: s.kv ?? null, tier: s.tier ?? null, id: s.id })); // no operator: the screen shows the network tier only
  const towers = (model.lines || []).flatMap(l => l.towers.map(t => ({ kind: 'tower', label: `${l.cls} pylon`, e: t.e, n: t.n,
    kv: l.kv ?? null, id: t.id })));
  return [...subs, ...towers];
}
// Until design-ui.mjs arrives (just after the first frame) the ground is the layers' own and nothing is designed.
let design = Object.freeze({ heightAt: (x, y) => baseHeight(x, y), batches: () => [], pickAt() {}, shift() {}, putDown() {},
  snapshot: () => ({ tool: null, trenches: [], cables: [], works: [], draft: [], readout: null }), lastFinished: () => null, replace() {}, animating: () => false });

// ---- moving -----------------------------------------------------------------------------------------
// Moves the site origin to (e, n) national-grid metres. The viewer and the route being drawn are shifted by the
// same amount the other way, so they stay in the same place in the world; layers read it via api.origin().
function setOrigin(e, n) {
  if (!Number.isFinite(e) || !Number.isFinite(n)) throw Error('setOrigin needs finite easting and northing');
  const dx = e - origin.e, dy = n - origin.n;
  state = { ...state, pos: [state.pos[0] - dx, state.pos[1] - dy, state.pos[2]] };
  origin = { e, n, id: origin.id + 1 };
  design.shift(dx, dy);
  invalidate();
  return { ...origin };
}

// Sun play and the solar block's build sequence (Design) both ask for frames at their own rate; paused, nothing.
const playing = () => !!sunMode?.playing() || design.animating();
const target = () => (arrival ? ARRIVAL_FPS : !input.active() && playing() ? (sunMode?.playing() ? sunMode.PLAY_FPS : ARRIVAL_FPS) : fpsOf(VIEWS[state.view], input.get().slow));
const moving = () => input.active() || !!arrival || playing();
const input = attachInput(canvas, $('pad'), {
  onChange: () => { if (input.active()) arrival = null; gate.setMoving(moving(), target()); gate.invalidate(); },
  onLook: (dy, dp) => { arrival = null; state = look(state, dy, dp); gate.invalidate(); },
  onView: v => chooseView(toggle(state.view, v)),
  onClick: (x, y) => design.pickAt(x, y)
});

// Flies the drone smoothly to hover above local [x, y], looking down; any movement key takes over.
function flyTo(x, y, opts = {}) {
  if (state.view !== 'aerial') chooseView('aerial', { arrive: false });
  if (Math.hypot(x - state.pos[0], y - state.pos[1]) > JUMP_M) { // a far place: move the origin there, drop in from above
    const p = toBng(origin, x, y);
    setOrigin(Math.round(p.e / 1000) * 1000, Math.round(p.n / 1000) * 1000);
    [x, y] = toLocal(origin, p.e, p.n);
    state = { ...state, pos: [x, y, heightAt(x, y) + 400] };
  }
  // back: stand off this far behind the point (along the current heading), so a pitch above straight down still sees it.
  const { back = 0, ...rest } = opts, yaw = rest.yaw ?? state.yaw, g = heightAt(x, y);
  const at = [x - back * Math.sin(yaw), y - back * Math.cos(yaw), g];
  const height = back && rest.pitch ? back * Math.tan(-rest.pitch) : (rest.height ?? ARRIVAL.height);
  arrival = { pose: arrive(state, at, { ...ARRIVAL, ...rest, yaw, height }), t0: performance.now() };
  gate.setMoving(true, ARRIVAL_FPS);
}

function draw(now, intervalMs) {
  for (const f of hooks.before) f(now);
  sunMode?.advance(intervalMs);
  if (arrival) {
    const t = (now - arrival.t0) / 1000;
    state = { ...state, ...arrival.pose(t) };
    if (arrival.pose.done(t)) { arrival = null; gate.setMoving(moving(), target()); }
  } else if (input.active()) {
    const i = input.get(), dt = Math.min(intervalMs / 1000, MAX_DT);
    if (i.turn) state = look(state, i.turn * dt, 0);
    state = step(state, i, dt, heightAt, solids());
    budget = adjust(budget, intervalMs, 1000 / target());
  }
  const r = arrival ? null : rebaseIfNeeded(origin, state.pos);
  if (r) setOrigin(r.e, r.n);
  // Ground can arrive after the viewer does (tiles stream in): a walker's eye follows it, a drone keeps clear.
  const v = VIEWS[state.view], g = heightAt(state.pos[0], state.pos[1]);
  if (v.eye !== null && Math.abs(state.pos[2] - (g + v.eye)) > 1e-6) state = { ...state, pos: [state.pos[0], state.pos[1], g + v.eye] };
  if (v.eye === null && state.pos[2] < g + AERIAL_MIN_CLEARANCE) state = { ...state, pos: [state.pos[0], state.pos[1], g + AERIAL_MIN_CLEARANCE] };
  lines.resize(budget.scale);
  // The view is built at the eye; lines.draw moves each batch by (its origin - eye) in doubles.
  const fade = fadeAt(), mat = multiply(perspective(FOV, canvas.width / canvas.height, 0.05, farPlane(fade)), view([0, 0, 0], state.yaw, state.pitch));
  lastBatches = collect(state.pos);
  vertices = lines.draw(mat, state.pos, fade, lastBatches);
  writeReadout();
  groundReadout?.update();
  sunMode?.afterDraw({ pos: state.pos, heightAt, groundVersion });
  for (const f of hooks.after) f(now);
}

// What the layers and the design draw around a position; the flat screen and the headset view both draw from this.
function collect(pos) {
  const ctx = { pos, heightAt, measuredAt, known, groundVersion, origin: { ...origin }, sun: sunMode?.sun(), view: state.view }; // view: imagery shows in Drone and Map, never Walk
  const batches = shown().flatMap(l => (typeof l.layer.lines === 'function' ? guarded(l, () => l.layer.lines(ctx), []) : []));
  return (sunMode ? sunMode.decorate(batches, ctx) : batches).concat(design.batches(), first?.batches() || []);
}

function chooseView(v, { arrive: fly = true } = {}) {
  const next = setView(state, v, heightAt);
  if (blocked(next.pos, VIEWS[v].body, solids())) return; // e.g. no standing up under a table
  const from = state.view;
  state = next; arrival = null;
  for (const b of document.querySelectorAll('[data-view]')) b.setAttribute('aria-pressed', String(b.dataset.view === v));
  $('lift').hidden = v !== 'aerial';
  if (v !== 'aerial') input.setLift(0);
  if (fly && v === 'aerial' && from !== 'aerial') flyTo(state.pos[0], state.pos[1]);
  gate.setMoving(moving(), target());
  gate.invalidate();
}

function writeReadout() {
  const [x, y, z] = state.pos, g = heightAt(x, y), v = VIEWS[state.view], p = toBng(origin, x, y);
  // On screen: a grid reference and the ground (its height above sea level where measured); exact numbers in Layer details.
  let ref = '';
  try { ref = gridRef(p.e, p.n, 8) + ' · '; } catch { /* off the national grid */ }
  const src = groundSource(x, y), known = Number.isFinite(measuredAt(x, y)), up = v.eye === null ? ` · ${Math.round(z - g)} m up` : '';
  where.textContent = `${ref}${known ? `ground ${Math.round(g)} m above sea level` : src ? GROUND_WORDS[src] || src : 'flat, no LiDAR yet'}${up}`;
  $('where-detail').textContent = `${v.label} · ${src ? GROUND_WORDS[src] || src : 'flat, no LiDAR yet'} · easting ${p.e.toFixed(1)} m, ` +
    `northing ${p.n.toFixed(1)} m · eye ${(z - g).toFixed(2)} m above the ground${known ? ` · ground ${g.toFixed(2)} m above sea level` : ''}`;
  // When still, no frame is drawn, so the rate is 0 whatever the last second's counter still holds.
  status.textContent = `${moving() || tourPlaying() ? gate.fps() : 0} fps now (moving ${v.fps}, precise ${v.slowFps}, still 0) · ${budget.scale}× resolution · ` +
    `${vertices / 2} lines · ${loaded.layers.map(l => `${l.id}: ${statusLine(l)}`).join('; ') || 'no layers'}`;
}

// ---- page controls ----------------------------------------------------------------------------------
for (const b of document.querySelectorAll('[data-view]')) b.addEventListener('click', () => { chooseView(b.dataset.view); canvas.focus(); });
// One panel at a time: Find, Design, Layers and Controls share the space under the dash on a phone.
let search = null;
const panels = { 'help-toggle': 'help', 'design-toggle': 'design', 'find-toggle': 'find', 'layers-toggle': 'layers' };
// GridAtlas opens at the spot you are standing on (latitude, longitude and zoom only; no project reference).
$('to-gridatlas').addEventListener('click', () => {
  const url = gridAtlasUrl({ origin, pos: state.pos });
  if (url) open(url, '_blank', 'noopener');
});
function openPanel(btn, open) {
  if (btn === 'find-toggle') { if (search) (open ? search.open() : search.close()); }
  else $(panels[btn]).hidden = !open;
  $(btn).setAttribute('aria-expanded', String(open));
  if (btn === 'design-toggle' && !open) design.putDown(); // closing Design puts the tool down
  const shown = Object.keys(panels).find(b => $(b).getAttribute('aria-expanded') === 'true');
  if (shown) document.body.dataset.panel = panels[shown]; else delete document.body.dataset.panel;
  if (btn === 'find-toggle' && open) first?.dismissStart();
}
for (const btn of Object.keys(panels)) {
  $(btn).addEventListener('click', () => {
    const open = $(btn).getAttribute('aria-expanded') !== 'true';
    for (const o of Object.keys(panels)) if (o !== btn && $(o).getAttribute('aria-expanded') === 'true') openPanel(o, false);
    openPanel(btn, open);
  });
}
// Up and Down: hold to climb or sink; a quick tap moves the drone 10 m (lift.mjs).
attachLift(document.querySelectorAll('[data-lift]'), { setLift: d => input.setLift(d), tap: d => {
  if (state.view !== 'aerial') return;
  const [x, y, z] = state.pos, floor = heightAt(x, y) + AERIAL_MIN_CLEARANCE;
  state = { ...state, pos: [x, y, Math.max(floor, z + d * TAP_M)] }; gate.invalidate();
} });
addEventListener('resize', () => gate.invalidate());
setInterval(() => { if (!moving() && !tourPlaying()) { writeReadout(); groundReadout?.update(); } layersUi?.refresh(); ohl?.update(); }, 1000); // text only: no frame is drawn

// The full credit lines under Controls, for exactly the data on screen; the footer line is written by layers-ui.mjs.
let attribution = null;
function writeCredits() {
  if (!attribution) return;
  $('credits').replaceChildren(...aboutList(sourceKeysFor(shown().map(l => l.id)), attribution).map(c => {
    const li = document.createElement('li'), a = document.createElement('a');
    a.href = c.link || c.licence_url || '#'; a.target = '_blank'; a.rel = 'noopener';
    a.textContent = `${c.line} (${c.licence})`; li.append(a); return li;
  }));
}

try {
  // Optional layers that start off load on first switch-on (review E); the sun and buffer controls need theirs now.
  loaded = await loadLayers('./world/manifest.json', { invalidate, origin: () => origin, site: await siteFromUrl(), started: item => item.layer?.mountControls?.(document.body),
    deferred: OPTIONAL_LAYERS.map(l => l.id).filter(id => !['grid', 'shade', 'buffers'].includes(id)), first: ['terrain', 'ground-grid'] }); // the ground first
} catch (e) {
  loaded = { generation: '', layers: [{ id: 'manifest', status: 'failed: ' + e.message }] };
}
// Live ground from the EA service wherever the staged tiles do not reach. It comes after the staged terrain
// layer, so staged, hash-checked tiles always win where both exist; boxes inside a staged site are not fetched.
{
  const staged = loaded.layers.find(l => l.id === 'terrain');
  const skip = (e0, n0, size) => {
    if (!staged?.layer || staged.layer.debug?.().indexState === 'failed' || !loaded.site) return false;
    const { centre_e: ce, centre_n: cn } = loaded.site;
    return e0 >= ce - SITE_HALF_M && n0 >= cn - SITE_HALF_M && e0 + size <= ce + SITE_HALF_M && n0 + size <= cn + SITE_HALF_M;
  };
  const layer = createLiveTerrain({ origin: () => origin, invalidate: () => invalidate(), skip });
  let failed = null; // set by guarded() if the layer throws; otherwise the status is the layer's own, live
  loaded.layers.push({ id: layer.id, layer, set status(t) { failed = t; },
    get status() { return failed || 'not hash-checked'; } }); // the Controls line adds the layer's own words in brackets
}
// A site places the world: its centre becomes the origin, so the viewer starts in the middle of the land.
if (loaded.site) origin = { e: loaded.site.centre_e, n: loaded.site.centre_n, id: origin.id + 1 };
chooseView('standing');

// ---- after the first frame ----------------------------------------------------------------------------
await new Promise(r => requestAnimationFrame(() => setTimeout(r, 0)));
const nearestSub = async (e, n) => live().find(l => l.id === 'grid')?.layer?.nearestSubstation?.(e, n) ?? null; // national index
const [{ createDesign }, { mountFind }, { mountPlan }, { mountProject }, { attachHeadset }, { mountLayersUi },
  { mountSunControl }, { mountBuffers }, { mountGroundReadout }, { attachSunMode }, { mountFirstShowing }, { attachOhl }] = await Promise.all(TOOLS.map(p => import(p)));
await loaded.rest; // grid, shade and buffers start just after the first frame; their controls need them
design = createDesign({ doc: document, canvas, fov: FOV, baseHeight, origin: () => origin, viewer: () => state, extraItems: () => ohl?.layer.boqItems() ?? [],
  invalidate, redraw: () => gate.invalidate(), assets: gridAssets, measuredAt, nearest: nearestSub, onChange: () => hooks.design.forEach(f => f()),
  animate: () => gate.setMoving(moving(), target()) });
design.setGroundVersion(() => groundVersion);
await design.loadCatalogue();
invalidate(); // the ground now comes through the design (trenches, roads and pads cut into it)
try { attribution = await (await fetch('./world/data/attribution.json', { cache: 'no-cache' })).json(); } catch { /* the fixed footer stays */ }
// Layers panel, from the dash's Layers button; GridAtlas sits in its header. Grid starts on; the rest start off.
const shade = loaded.layers.find(l => l.id === 'shade' && l.layer); let sunUi = null; // the shadow's date and time (sun-ui.mjs)
ohl = attachOhl(loaded.layers, { design: () => design.snapshot(), origin: () => origin, measuredAt, invalidate: () => gate.invalidate() }); // overhead line zones, on whenever the grid is
const buffers = mountBuffers({ layer: loaded.layers.find(l => l.id === 'buffers' && l.layer)?.layer, origin: () => origin, design: () => design.snapshot() });
try {
  layersUi = mountLayersUi({ items: loaded.layers, host: $('layers-slot'), footer: $('attribution'), attribution,
    invalidate: () => gate.invalidate(),
    onChange: ids => { sunUi?.show(ids.includes('shade') && !sunMode?.on()); buffers?.refresh(ids.includes('buffers')); writeCredits();
      ohl?.onChange(ids, () => layersUi?.panel); groundReadout?.reset(); groundReadout?.update(); } });
} catch (e) { console.warn('layers panel: not wired: ' + e.message); }
if (buffers) setInterval(() => buffers.refresh(layersUi?.panel.isOn('buffers')), 1000); // origin moves, new drawn items
ohl.mount($('layers-slot'), () => layersUi?.panel);
try { sunUi = mountSunControl($('layers-slot'), { layer: shade?.layer, site: loaded.site }); sunUi?.show(!!layersUi?.panel.isOn('shade')); }
catch (e) { console.warn('sun control: ' + e.message); }
// Sun mode (Sun switch in Layers): switches the terrain shadow on through the panel, shows its time bar, lights the grid.
try {
  sunMode = attachSunMode({ pos: () => state.pos, heightAt, origin: () => origin, site: () => loaded.site,
    layer: id => live().find(l => l.id === id)?.layer || null, base: new URL('./world/', location.href).href,
    setShade: on => { if (layersUi && layersUi.panel.isOn('shade') !== on) layersUi.panel.set('shade', on); },
    onToggle: on => sunUi?.show(!on && !!layersUi?.panel.isOn('shade')), redraw: () => gate.invalidate(),
    onPlay: () => { gate.setMoving(moving(), target()); gate.invalidate(); } });
} catch (e) { console.warn('sun mode: ' + e.message); }
// Escape inside the list closes the Layers panel and hands focus back to its dash button.
layersUi?.panel.element.addEventListener('close', () => { openPanel('layers-toggle', false); $('layers-toggle').focus(); });
// Ground readout: under the walker's feet, and along the last finished trench or cable (Design panel).
const panelOpen = () => Object.keys(panels).some(b => $(b).getAttribute('aria-expanded') === 'true');
groundReadout = mountGroundReadout({ doc: document, layer: () => live().find(l => l.id === 'ground')?.layer || null,
  on: () => !!layersUi?.panel.isOn('ground'), feet: $('ground-feet'), box: $('ground-readout'), finished: design.lastFinished,
  here: () => toBng(origin, state.pos[0], state.pos[1]), walking: () => state.view === 'standing' && !panelOpen() });
writeCredits();
first = mountFirstShowing({ canvas, redraw: () => gate.invalidate(), origin: () => origin, heightAt, groundVersion: () => groundVersion,
  assets: gridAssets, nearest: nearestSub, openFind: () => { if ($('find-toggle').getAttribute('aria-expanded') !== 'true') $('find-toggle').click(); } });
search = mountFind({ site: () => loaded.site, attribution, origin: () => origin, SITE_HALF_M, first: () => first, canvas,
  close: () => openPanel('find-toggle', false), flyTo: (x, y) => flyTo(x, y, OBLIQUE) }); // find-mount.mjs

// What extensions may read and change. The design stays in national-grid metres; replace swaps it whole.
const api = {
  canvas, gate, hooks, live, guarded, heightAt, invalidate, FOV, FADE_M, VIEWS, flyTo,
  state: () => state, origin: () => ({ ...origin }), site: () => loaded.site || null, generation: () => loaded.generation,
  batches: () => lastBatches, redraw: () => draw(performance.now(), 0), moving: () => input.active(), attribution: () => attribution,
  setPose(p) { arrival = null; state = { ...state, ...p }; gate.invalidate(); },
  setView: v => { if (state.view !== v) chooseView(v, { arrive: false }); },
  resumeGate: () => gate.setMoving(moving(), target()), // after a tour pauses, the walk carries on at its own rate
  design: () => design.snapshot(), replaceDesign: d => design.replace(d)
};
const plan = mountPlan(api);
const project = mountProject(api);
tourPlaying = project.playing;
// Headset view (in Controls): hidden where the browser cannot run it; on leaving, the flat screen carries on from there.
attachHeadset($('headset'), {
  lines, heightAt, solids, collect, fade: FADE_M, state: () => state,
  leave: next => { state = { ...state, ...next }; chooseView(state.view, { arrive: false }); }
});

// Solid ground (GPU), in Controls: a WebGL2 ray cast behind the lines (raycast.mjs). Shown only where WebGL2 exists,
// off by default, and the module is not even fetched until the first switch-on, so the first frame never waits for
// it. If WebGL2 then fails, the switch hides itself and the world stays as it was.
let raycast = null;
if (typeof WebGL2RenderingContext !== 'undefined' && $('raycast')) {
  const b = $('raycast'); b.hidden = false;
  b.addEventListener('click', async () => {
    try {
      if (!raycast) raycast = (await import('./raycast.mjs')).mountRaycast({ lines, canvas, FOV, measuredAt, invalidate, doc: document,
        state: () => state, groundVersion: () => groundVersion, origin: () => ({ ...origin }), sun: () => sunMode?.sun() });
    } catch (e) { console.warn('solid ground: ' + e.message); raycast = null; }
    if (!raycast) { b.hidden = true; return; }
    const on = !raycast.on(); raycast.set(on); b.setAttribute('aria-pressed', String(on));
  });
}

// For tests and the console. Read-only views of the live state, and the origin and arrival hooks.
window.world = Object.freeze({
  raycast: () => raycast?.debug() ?? null, raycastApi: () => raycast,
  origin: () => ({ ...origin }), groundVersion: () => groundVersion, setOrigin, heightAt, measuredAt, groundSource,
  liveTerrain: () => live().find(l => l.id === 'terrain-live')?.layer.debug() ?? null,
  state: () => state, budget: () => budget, fps: () => gate.fps(), generation: () => loaded.generation,
  layers: () => loaded.layers.map(({ id, status, layer }) => ({ id, status, detail: layer?.status ?? null })), // detail: the layer's own word
  // Flies the drone to national-grid (e, n): the arrival is smooth and capped at 30 fps.
  flyTo: (e, n, opts) => { const [x, y] = toLocal(origin, e, n); flyTo(x, y, opts); },
  plan, project, ohl: () => ohl?.layer.debug() ?? null, layerDebug: id => live().find(l => l.id === id)?.layer?.debug?.() ?? null, setRange: mi => layersUi?.range?.set(mi),
  layersOn: () => layersUi?.panel.onIds() || [], setLayer: (id, on) => layersUi?.panel.set(id, on),
  sun: () => sunMode?.debug() ?? null, place: () => first?.place() ?? null, // the place last found and pinned
  design: () => design.snapshot(), // the design in memory, in national-grid metres (export and import come later)
  plant: design.plantApi, block: design.blockApi // Design > Plant layout and Solar block (design-sections.mjs)
});

Block Export

A JavaScript module in the world folder of GlobalGrid2050 that fetches substations, 33kV and solar, using Dijkstra and SHA-256. It loads export (`loadExport`), parses export (`parseExport`) and builds export (`buildExport`).

ingestglobalgrid2050 / solar-design-studio/202609270439-site-world/world/block-export.mjs · lines 1–89 of 89 · version 2026-09-27 04:39 · Not reached from any entry point (candidate for review) · pattern exportRows (shared by 3 files)

What it does
It fetches substations, 33kV and solar. Defines 11 functions or classes, including hex, sha256, loadExport, parseExport, buildExport. Side effects: makes network requests.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: substations, 33kV, solar.
Inputs & outputs
In: JSON file index.json. Voltage levels named: 33kV.
Downstream impact
Used directly by 1 file: Block UI (globalgrid2050).
What it achieves
Design > Solar block > Export route (GPU-checked, illustrative). Its code works with 33 kV.
Why it matters
Imported by Block UI.
Application
globalgrid2050 · solar-design-studio/202609270439-site-world/world · JavaScript module
Uses
none found
Used by
imported by Block UI (dynamic import)
Produces
EXPORT_LABEL, EXPORT_DIR, ROUTE_LIFT_M, COLORS, loadExport, parseExport, buildExport, exportRows
Defines here
hex, sha256, loadExport, parseExport, buildExport, mk, seg, near, z, exportRows, pair
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609270439-site-world/world/block-export.mjs:1-89 · blob ad94b7739321a8c2e8dbffd1b3c0bc0a2bb8fc3a · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: network · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
// block-export.mjs: Design > Solar block > Export route (GPU-checked, illustrative). The GPU study's 33 kV export route
// (gpu-night agent A, round 11 item 3): from the prototype station pad over the EA LiDAR ground to the nearest 33 kV
// substation in GridAtlas, found both ways on a 2 m grid (GPU and a CPU Dijkstra witness agree on its cost), with the
// study's HDD candidates where it crosses a road or a watercourse and the trench spoil it works out.
// ILLUSTRATIVE: nearest by distance, not a connection offer, capacity or consent; every weight, width, depth and HDD rule
// is the study's assumption. Files are staged by tools/stage-gpu-export.mjs into sites/<site>/gpu-export/ (local,
// git-ignored) with an index naming each file's SHA-256; each is checked before use. National-grid metres, heights ODN.

export const EXPORT_LABEL = 'Export route (GPU-checked, illustrative): nearest 33 kV substation by distance, not a connection offer; ' +
  'route weights, trench and HDD rules assumed.';
export const EXPORT_DIR = 'gpu-export';
export const ROUTE_LIFT_M = 0.3, HDD_POST_M = 4, TARGET_MAST_M = 15; // drawing only
export const COLORS = Object.freeze({ route: [1, 0.55, 0.25, 1], floor: [0.7, 0.6, 0.5, 0.7], hdd: [1, 0.9, 0.3, 1], bore: [1, 0.9, 0.3, 0.8], target: [0.95, 0.97, 1, 1] });

const hex = buf => [...new Uint8Array(buf)].map(b => b.toString(16).padStart(2, '0')).join('');
const sha256 = async bytes => hex(await globalThis.crypto.subtle.digest('SHA-256', bytes));

// Reads sites/<site>/gpu-export/index.json and each file it names, checked against its SHA-256. -> { route, witness? }
export async function loadExport(site, { get = (u, o) => fetch(u, o), base = './world/sites/', digest = sha256 } = {}) {
  const dir = `${base}${site}/${EXPORT_DIR}/`, r = await get(dir + 'index.json', { cache: 'no-cache' });
  if (!r.ok) throw Error(`no GPU-checked export route staged for ${site}`);
  const index = await r.json(), out = {};
  for (const f of index.files || []) {
    const res = await get(dir + f.file, { cache: 'no-cache' });
    if (!res.ok) throw Error(`${f.file}: HTTP ${res.status}`);
    const bytes = await res.arrayBuffer(), h = await digest(bytes);
    if (h !== f.sha256) throw Error(`${f.file}: hash ${h.slice(0, 12)} is not the index's ${String(f.sha256).slice(0, 12)}`);
    out[f.role] = JSON.parse(new TextDecoder().decode(bytes));
  }
  if (!out.route) throw Error('the export route index names no route');
  return out;
}

// Pure: the study's file -> what the page draws and says.
export function parseExport(j, witness = null) {
  if (j?.schema !== 'gpu-night-a.export-route/1' || !Array.isArray(j.route?.route_bng)) throw Error('not a GPU export route');
  const pts = j.route.route_bng.filter(q => Array.isArray(q) && q.length >= 3 && q.every(Number.isFinite));
  if (pts.length < 2) throw Error('the export route has fewer than two points');
  const a = j.assumed || {}, depth = Number.isFinite(a.floor_m) ? a.floor_m : 1.1;
  const hdd = (j.hdd_candidates || []).filter(h => [...(h.entry_bng || []), ...(h.exit_bng || [])].length === 4)
    .map(h => ({ entry: h.entry_bng, exit: h.exit_bng, level: h.bore_level_under_feature_m, crosses: h.crosses, drill: h.drill_length_m, chainage: h.chainage_m }));
  return { pts, depth, hdd, lengthM: j.route.length_m, straightM: j.straight_line_m, spoil: j.route.spoil_m3 || {}, gradient: j.route.max_floor_gradient_pct || {},
    crossings: j.crossings || {}, target: j.target || null, photons: j.photons || [], widthM: a.trench_width_m,
    witness: witness ? { match: !!witness.match, rel: witness.rel } : null, receipt: j.body_sha256 || null };
}

// Pure: line groups { key, base, v } relative to each base. ground(e, n): measured height or NaN (for HDD ends and the
// substation, which the route file does not give heights for; off measured ground the nearest route point's is used).
export function buildExport(p, ground = () => NaN) {
  const mk = key => ({ key, base: null, v: [] });
  const seg = (G, a, b) => { G.base ||= a; for (const q of [a, b]) G.v.push(q[0] - G.base[0], q[1] - G.base[1], q[2] - G.base[2]); };
  const near = (e, n) => { let best = p.pts[0], d = Infinity; for (const q of p.pts) { const k = (q[0] - e) ** 2 + (q[1] - n) ** 2; if (k < d) { d = k; best = q; } } return best[2]; };
  const z = (e, n) => { const h = ground(e, n); return Number.isFinite(h) ? h : near(e, n); };
  const route = mk('route'), floor = mk('floor'), hdd = mk('hdd'), bore = mk('bore'), target = mk('target');
  for (let i = 1; i < p.pts.length; i++) {
    const A = p.pts[i - 1], B = p.pts[i];
    seg(route, [A[0], A[1], A[2] + ROUTE_LIFT_M], [B[0], B[1], B[2] + ROUTE_LIFT_M]);
    seg(floor, [A[0], A[1], A[2] - p.depth], [B[0], B[1], B[2] - p.depth]); // the trench floor: what the spoil comes out of
  }
  for (const h of p.hdd) {
    const ea = [h.entry[0], h.entry[1], z(...h.entry)], ex = [h.exit[0], h.exit[1], z(...h.exit)];
    for (const q of [ea, ex]) seg(hdd, q, [q[0], q[1], q[2] + HDD_POST_M]);
    const low = Number.isFinite(h.level) ? h.level : Math.min(ea[2], ex[2]) - 2, mid = [(ea[0] + ex[0]) / 2, (ea[1] + ex[1]) / 2, low];
    seg(bore, ea, mid); seg(bore, mid, ex);
  }
  if (p.target && Number.isFinite(p.target.e) && Number.isFinite(p.target.n)) {
    const g = z(p.target.e, p.target.n), s = TARGET_MAST_M / 6, t = [p.target.e, p.target.n, g];
    seg(target, t, [t[0], t[1], g + TARGET_MAST_M]);
    const P = [[t[0] + s, t[1], g + TARGET_MAST_M], [t[0], t[1] + s, g + TARGET_MAST_M + s], [t[0] - s, t[1], g + TARGET_MAST_M], [t[0], t[1] - s, g + TARGET_MAST_M - s]];
    for (let k = 0; k < 4; k++) seg(target, P[k], P[(k + 1) % 4]);
  }
  return [route, floor, hdd, bore, target].filter(G => G.base).map(G => ({ ...G, v: new Float32Array(G.v) }));
}

// Pure: the readout rows [label, text].
export function exportRows(p, fmt = { n0: x => String(Math.round(x)), len: m => `${Math.round(m)} m` }) {
  const c = p.crossings, other = o => (Number.isFinite(o.positron) && fmt.n0(o.positron) !== fmt.n0(o.electron) ? ` (checked pair ${fmt.n0(o.positron)})` : '');
  const pair = o => (o && Number.isFinite(o.electron) ? `${fmt.n0(o.electron)}${other(o)}` : 'not given');
  return [
    ['To', p.target ? `${p.target.voltage_kv ?? 33} kV substation at ${fmt.n0(p.target.e)} E, ${fmt.n0(p.target.n)} N (GridAtlas, OpenStreetMap)` : 'not given'],
    ['Route', `${fmt.len(p.lengthM)} over the ground · ${fmt.len(p.straightM)} straight line`],
    ['Trench', `floor ${p.depth} m down${p.widthM ? ` · ${p.widthM} m wide` : ''} (assumed) · steepest floor ${pair(p.gradient)} %`],
    ['Spoil', `${pair(p.spoil)} m³ (bank volume, estimate)`],
    ['Crossings', `roads ${pair(c.road)} · watercourses ${pair(c.watercourse)} · rail ${pair(c.rail)}`],
    ['HDD candidates', `${p.hdd.length} (drawn yellow: entry and exit posts, bore under the feature) · ${fmt.len(p.hdd.reduce((s, h) => s + (h.drill || 0), 0))} drilled`],
    ['Checked', p.witness ? (p.witness.match ? 'GPU route cost matches the CPU witness' : 'GPU and CPU witness disagree') +
      (p.photons.length ? ` · ${p.photons.length} counted disagreements (${p.photons.join(', ')})` : '') : 'no witness staged'],
    ['Basis', EXPORT_LABEL + (p.receipt ? ` Receipt ${p.receipt.slice(0, 12)}.` : '')]];
}