GLOBALGRID2050 / EXPLORE CODE

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

Pack Check and 3 more files

A JavaScript module in the world folder of GlobalGrid2050 that imports refusal (`importRefusal`) and creates bus (`createBus`), using SHA-256. It validates pack (`validatePack`), imports refusal (`importRefusal`) and imports text (`importText`).

661 lines of JavaScript from globalgrid2050, in 4 files. Topic: Solar and storage design. Section 189 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. Pack Check ingest · globalgrid2050 / solar-design-studio/202609271853-site-world/world/pack-check.mjs lines 1–254
  2. Pack Loader ingest · globalgrid2050 / solar-design-studio/202609271853-site-world/world/pack-loader.mjs lines 1–240
  3. Packs Mount render · globalgrid2050 / solar-design-studio/202609271853-site-world/world/packs-mount.mjs lines 1–112
  4. Pick transform · globalgrid2050 / solar-design-studio/202609271853-site-world/world/pick.mjs lines 1–55

Pack Check

A JavaScript module in the world folder of GlobalGrid2050 that imports refusal (`importRefusal`) and creates bus (`createBus`), using SHA-256. It validates pack (`validatePack`), imports refusal (`importRefusal`) and imports text (`importText`).

ingestglobalgrid2050 / solar-design-studio/202609271853-site-world/world/pack-check.mjs · lines 1–254 of 254 · version 2026-09-27 18:53 · Not reached from any entry point (candidate for review) · pattern scoped (shared by 2 files)

What it does
It fetches data. Defines 19 functions or classes, including isObj, str, safePath, validatePack, need. 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.
Inputs & outputs
In: JSON file pack.json.
Downstream impact
Used directly by 1 file: Pack Loader (globalgrid2050).
What it achieves
The checks and parts of the layer pack loader (contract world.pack.v1): validation of `pack.json`, the API, import and shape refusals, hashing and importing, the event bus, fixed steps and reading a pack folder.
Why it matters
Imported by Pack Loader.
Application
globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
Uses
none found
Used by
imported by Pack Loader (import)
Produces
CONTRACT, API, KINDS, HOOKS, FIXED_DT, MAX_SUBSTEPS, OVER_BUDGET_FRAMES, LIMITS, TOP_KEYS, WORLD_EVENTS, HEX, isObj
Defines here
isObj, str, safePath, validatePack, need, apiRefusal, importRefusal, normalise, sha256Text, importText, createBus, on, emit, scoped, deepFreeze, advance, getText, readPack, shapeRefusal
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/202609271853-site-world/world/pack-check.mjs:1-254 · blob 1cba02a1fedbe0499f1d34c0a19328408614b460 · 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
// pack-check.mjs: the checks and parts of the layer pack loader (contract world.pack.v1): validation of pack.json,
// the api, import and shape refusals, hashing and importing, the event bus, fixed steps and reading a pack folder.
// Split from the pack loader (Apache-2.0, the packs' own _loader) only to keep each world file under 400 lines;
// pack-loader.mjs re-exports all of it, so code and tests import the loader as before. No logic is changed.

export const CONTRACT = 'world.pack.v1';
export const API = Object.freeze({ major: 1, minor: 0 });
export const KINDS = Object.freeze(['layer', 'body', 'vehicle', 'lens', 'sim']);
export const HOOKS = Object.freeze(['init', 'lines', 'solids', 'heightAt', 'step', 'active', 'commands', 'hud', 'setEnabled', 'dispose']);
export const FIXED_DT = 1 / 60;          // seconds per simulation step
export const MAX_SUBSTEPS = 8;           // a slow frame never runs more than this many steps (the rest is dropped and counted)
export const OVER_BUDGET_FRAMES = 30;    // consecutive frames over budget before a pack is switched off
export const LIMITS = Object.freeze({ maxVertices: 2000000, maxMsPerFrame: 8, hudLines: 4, hudChars: 80 });
export const TOP_KEYS = Object.freeze(['$schema', 'contract', 'id', 'version', 'kind', 'title', 'description', 'entry', 'sha256', 'requires', 'provides', 'budget', 'licence', 'illustrative', 'data']);
export const WORLD_EVENTS =Object.freeze(['world/pose', 'world/origin', 'world/toggle', 'world/ground']);

const ID = /^[a-z][a-z0-9-]{1,39}$/;
const SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?$/;
export const HEX = /^[0-9a-f]{64}$/;
const API_RE = /^(0|[1-9]\d*)\.(0|[1-9]\d*)$/;
const VERB = /^[a-z][a-z0-9-]{0,23}$/;
const EVENT = /^[a-z][a-z0-9-]*\/[a-z][a-z0-9-]*$/;
const KEY = /^(?:[a-z0-9]|Key[A-Z]|Digit[0-9]|F(?:[1-9]|1[0-2])|Arrow(?:Up|Down|Left|Right)|Space|Shift\+[a-z0-9])$/;

// ---------------------------------------------------------------- validation

export const isObj = v => v !== null && typeof v === 'object' && !Array.isArray(v);
export const str = (v, max = 200) => typeof v === 'string' && v.length > 0 && v.length <= max;
// A path inside the pack: relative, forward slashes, no parent steps, no drive letters, no scheme.
export const safePath = p => str(p, 200) && !/^[/\\]|\\|^[a-z][a-z0-9+.-]*:|(^|\/)\.\.(\/|$)|^~/i.test(p);

// Every problem with a pack.json, in words; an empty list means it meets the contract.
export function validatePack(p) {
  const bad = [];
  const need = (ok, why) => { if (!ok) bad.push(why); };
  if (!isObj(p)) return ['pack.json is not an object'];
  need(p.contract === CONTRACT, `contract must be "${CONTRACT}"`);
  for (const k of Object.keys(p)) need(TOP_KEYS.includes(k), `${k} is not a pack.json field (a new field needs a new contract minor)`);
  if (p.description !== undefined) need(typeof p.description === 'string' && p.description.length <= 400, 'description must be at most 400 characters');
  need(typeof p.id === 'string' && ID.test(p.id), 'id must be 2-40 characters: lower-case letters, digits, hyphens, starting with a letter');
  need(typeof p.version === 'string' && SEMVER.test(p.version), 'version must be semantic (1.2.3)');
  need(KINDS.includes(p.kind), `kind must be one of ${KINDS.join(', ')}`);
  need(str(p.title, 60), 'title must be 1-60 characters');
  need(safePath(p.entry) && /\.mjs$/.test(p.entry), 'entry must be a relative .mjs path inside the pack');
  need(typeof p.sha256 === 'string' && HEX.test(p.sha256), 'sha256 must be 64 lower-case hex characters (the entry, normalised)');
  need(typeof p.licence === 'string' && /^[A-Za-z0-9.+-]{2,40}$/.test(p.licence), 'licence must be an SPDX identifier');
  need(typeof p.illustrative === 'boolean', 'illustrative must be true or false');
  if (p.kind === 'sim') need(p.illustrative === true, 'a sim pack must be labelled illustrative');

  const r = p.requires;
  if (!isObj(r)) bad.push('requires must be an object');
  else {
    need(typeof r.api === 'string' && API_RE.test(r.api), 'requires.api must be "major.minor"');
    if (r.lib !== undefined) need(Number.isInteger(r.lib) && r.lib > 0, 'requires.lib must be a positive integer');
    if (r.packs !== undefined) {
      if (!isObj(r.packs)) bad.push('requires.packs must map pack ids to major versions');
      else for (const [k, v] of Object.entries(r.packs)) need(ID.test(k) && Number.isInteger(v) && v >= 0, `requires.packs.${k} must be a major version number`);
    }
  }

  const b = p.budget;
  if (!isObj(b)) bad.push('budget must be an object');
  else {
    need(Number.isInteger(b.maxVertices) && b.maxVertices >= 0 && b.maxVertices <= LIMITS.maxVertices, `budget.maxVertices must be an integer 0-${LIMITS.maxVertices}`);
    need(typeof b.maxMsPerFrame === 'number' && b.maxMsPerFrame > 0 && b.maxMsPerFrame <= LIMITS.maxMsPerFrame, `budget.maxMsPerFrame must be above 0 and at most ${LIMITS.maxMsPerFrame}`);
    need(typeof b.lazy === 'boolean', 'budget.lazy must be true or false');
  }

  const v = p.provides;
  if (!isObj(v)) bad.push('provides must be an object');
  else {
    const verbs = new Set();
    for (const [i, c] of (Array.isArray(v.commands) ? v.commands : []).entries()) {
      if (!isObj(c) || !VERB.test(c.verb ?? '')) { bad.push(`provides.commands[${i}].verb must be a lower-case word`); continue; }
      need(!verbs.has(c.verb), `provides.commands: ${c.verb} is listed twice`);
      verbs.add(c.verb);
      need(str(c.usage, 120) && c.usage.split(/\s+/)[0] === c.verb, `provides.commands.${c.verb}.usage must start with the verb`);
      need(str(c.words, 200), `provides.commands.${c.verb}.words must be plain search words`);
    }
    if (v.commands !== undefined) need(Array.isArray(v.commands), 'provides.commands must be a list');
    for (const [i, h] of (Array.isArray(v.hud) ? v.hud : []).entries()) need(isObj(h) && VERB.test(h.id ?? '') && str(h.label, 40), `provides.hud[${i}] needs an id and a label`);
    if (v.hud !== undefined) need(Array.isArray(v.hud) && v.hud.length <= LIMITS.hudLines, `provides.hud must be a list of at most ${LIMITS.hudLines}`);
    if (v.toggle !== undefined) {
      need(isObj(v.toggle) && str(v.toggle.label, 40), 'provides.toggle.label must be 1-40 characters');
      if (isObj(v.toggle)) {
        need(typeof v.toggle.on === 'boolean', 'provides.toggle.on must say whether the pack starts on');
        if (v.toggle.group !== undefined) need(str(v.toggle.group, 40), 'provides.toggle.group must be 1-40 characters');
      }
    }
    for (const [i, k] of (Array.isArray(v.keys) ? v.keys : []).entries()) {
      if (!isObj(k)) { bad.push(`provides.keys[${i}] must be an object`); continue; }
      need(typeof k.key === 'string' && KEY.test(k.key), `provides.keys[${i}].key must be a single key name (a, KeyB, Digit3, F2, ArrowUp, Space, Shift+j)`);
      need(str(k.command, 120) && verbs.has(k.command.split(/\s+/)[0]), `provides.keys[${i}].command must run one of this pack's commands`);
      need(str(k.summary, 80), `provides.keys[${i}].summary must say what the key does`);
    }
    if (v.keys !== undefined) need(Array.isArray(v.keys), 'provides.keys must be a list');
    const ev = v.events;
    if (ev !== undefined) {
      if (!isObj(ev)) bad.push('provides.events must be an object');
      else {
        for (const e of ev.emits ?? []) need(EVENT.test(e) && typeof p.id === 'string' && e.startsWith(p.id + '/'), `provides.events.emits: ${e} must be "${p.id}/<topic>"`);
        for (const e of ev.listens ?? []) need(EVENT.test(e), `provides.events.listens: ${e} must be "<pack>/<topic>"`);
      }
    }
  }

  if (p.data !== undefined) {
    if (!Array.isArray(p.data)) bad.push('data must be a list');
    else for (const [i, d] of p.data.entries()) {
      need(isObj(d) && safePath(d.path), `data[${i}].path must be a relative path inside the pack`);
      need(isObj(d) && typeof d.sha256 === 'string' && HEX.test(d.sha256), `data[${i}].sha256 must be 64 hex characters`);
      need(isObj(d) && str(d.licence, 60), `data[${i}].licence must name the data's licence`);
      need(isObj(d) && str(d.source, 200), `data[${i}].source must say where the data came from`);
    }
  }
  return bad;
}

// Why a pack needing api "M.m" cannot run on a world offering `world` ({ major, minor }); null when it can.
export function apiRefusal(need, world = API) {
  const m = API_RE.exec(String(need ?? ''));
  if (!m) return `it asks for api "${need}", which is not "major.minor"`;
  const [maj, min] = [Number(m[1]), Number(m[2])];
  if (maj !== world.major) return `it needs pack api ${maj}.x, this world offers ${world.major}.${world.minor}`;
  if (min > world.minor) return `it needs pack api ${maj}.${min}, this world offers ${world.major}.${world.minor}`;
  return null;
}

// Why an entry's text is not self-contained (it runs from a blob URL, so it cannot import); null when it is.
export function importRefusal(text) {
  if (/^\s*import\s*[\w{*'"]/m.test(text)) return 'the entry has an import statement; a pack entry must be self-contained';
  if (/^\s*export\s+(?:\*|\{[^}]*\})\s*from\s/m.test(text)) return 'the entry re-exports from another file; a pack entry must be self-contained';
  if (/\bimport\s*\(/.test(text)) return 'the entry calls import(); a pack entry must be self-contained';
  return null;
}

// ---------------------------------------------------------------- hashing and importing

// Same rule as the world's layer loader: a byte-order mark and CRLF line endings are normalised in code only.
export const normalise = text => text.replace(/^/, '').replace(/\r\n/g, '\n');

export async function sha256Text(text, subtle = globalThis.crypto?.subtle) {
  if (!subtle) return null;
  const d = await subtle.digest('SHA-256', new TextEncoder().encode(text));
  return [...new Uint8Array(d)].map(b => b.toString(16).padStart(2, '0')).join('');
}

// Imports checked module text. In a browser a blob URL (as the world's layers); in Node a data URL.
// Each call yields a fresh module instance, so a pack's module-level state is its own. Node would cache a data URL
// of the same text as one module, so each import there gets a numbered trailing comment (after the hash check).
let instances = 0;
export async function importText(text) {
  const node = typeof process !== 'undefined' && !!process.versions?.node;
  if (!node && typeof Blob === 'function' && URL.createObjectURL) {
    const u = URL.createObjectURL(new Blob([text], { type: 'text/javascript' }));
    try { return await import(u); } finally { URL.revokeObjectURL(u); }
  }
  const t = `${text}\n// pack instance ${++instances}\n`;
  const b64 = typeof Buffer === 'function' ? Buffer.from(t, 'utf8').toString('base64')
    : btoa(String.fromCharCode(...new TextEncoder().encode(t)));
  return import('data:text/javascript;base64,' + b64);
}

// ---------------------------------------------------------------- events

// One bus per world. Names are "<source>/<topic>". A pack emits only under its own id and only what it declared;
// it hears world/* and whatever it declared under listens. Payloads are cloned (data only, no functions), and a
// listener that throws is reported, never allowed to stop the others. Delivery is synchronous, in subscription order.
export function createBus({ onError = () => {}, clone = globalThis.structuredClone, maxDepth = 16 } = {}) {
  const subs = new Map();
  let depth = 0;
  const on = (name, fn) => {
    if (!subs.has(name)) subs.set(name, []);
    const list = subs.get(name), rec = { fn };
    list.push(rec);
    return () => { const i = list.indexOf(rec); if (i >= 0) list.splice(i, 1); };
  };
  const emit = (name, payload) => {
    if (depth >= maxDepth) { onError(name, Error(`events nested deeper than ${maxDepth}: ${name} dropped`)); return 0; }
    const list = subs.get(name);
    if (!list?.length) return 0;
    const data = payload === undefined ? undefined : clone ? clone(payload) : JSON.parse(JSON.stringify(payload));
    if (data && typeof data === 'object') deepFreeze(data);
    depth++;
    let n = 0;
    try { for (const rec of [...list]) { try { rec.fn(data, name); n++; } catch (e) { onError(name, e); } } } finally { depth--; }
    return n;
  };
  const scoped = (id, declared = {}) => {
    const emits = new Set(declared.emits || []), listens = new Set(declared.listens || []), offs = [];
    return Object.freeze({
      on(name, fn) {
        if (typeof fn !== 'function') throw TypeError('events.on needs a function');
        if (!name.startsWith('world/') && !listens.has(name)) throw Error(`${id} did not declare that it listens to ${name}`);
        const off = on(name, fn); offs.push(off); return off;
      },
      emit(topic, payload) {
        const name = `${id}/${topic}`;
        if (!emits.has(name)) throw Error(`${id} did not declare that it emits ${name}`);
        return emit(name, payload);
      },
      offAll() { while (offs.length) offs.pop()(); }
    });
  };
  return Object.freeze({ on, emit, scoped });
}

function deepFreeze(o) {
  if (ArrayBuffer.isView(o)) return o; // typed arrays cannot be frozen; they are copies, so a listener's change stays its own
  Object.freeze(o);
  for (const v of Object.values(o)) if (v && typeof v === 'object' && !Object.isFrozen(v)) deepFreeze(v);
  return o;
}

// ---------------------------------------------------------------- fixed step

// Whole steps due after real time `dt` with carry `acc`: { steps, acc, dropped }. Pure and deterministic.
export function advance(acc, dt, fixed = FIXED_DT, max = MAX_SUBSTEPS) {
  const t = acc + (Number.isFinite(dt) && dt > 0 ? dt : 0);
  let steps = Math.floor(t / fixed + 1e-9);
  let rest = Math.max(0, t - steps * fixed);
  let dropped = 0;
  if (steps > max) { dropped = steps - max; steps = max; rest = 0; }
  return { steps, acc: rest, dropped };
}

// ---------------------------------------------------------------- reading a pack

export async function getText(fetchImpl, url) {
  const res = await fetchImpl(url, { cache: 'no-cache' });
  if (!res.ok) throw Error(`${url}: HTTP ${res.status}`);
  return res.text();
}

// Reads and validates <from>pack.json. `from` is a folder URL (a trailing slash is added) resolved against `base`.
export async function readPack(from, { base, fetchImpl = (u, o) => fetch(u, o) } = {}) {
  const folder = new URL(String(from).replace(/\/?$/, '/'), base).href;
  let pack;
  try { pack = JSON.parse(await getText(fetchImpl, new URL('pack.json', folder).href)); }
  catch (e) { return { folder, pack: null, problems: ['pack.json could not be read: ' + e.message] }; }
  return { folder, pack, problems: validatePack(pack) };
}

// Why a module's default export cannot run as this pack; null when it can.
export function shapeRefusal(mod, pack) {
  if (!isObj(mod) && typeof mod !== 'object') return 'the entry has no default export object';
  if (!mod) return 'the entry has no default export object';
  for (const h of HOOKS) if (h in mod && typeof mod[h] !== 'function') return `${h} must be a function`;
  if (mod.id !== undefined && mod.id !== pack.id) return `the entry says id ${mod.id}, pack.json says ${pack.id}`;
  if (typeof mod.step === 'function' && pack.illustrative !== true) return 'the entry simulates (step) but pack.json does not label it illustrative';
  if (typeof mod.heightAt === 'function' && pack.kind !== 'layer') return 'only a layer pack may offer ground (heightAt)';
  if (!HOOKS.some(h => typeof mod[h] === 'function')) return 'the entry offers none of the hooks';
  return null;
}

Pack Loader

A JavaScript module in the world folder of GlobalGrid2050 that creates pack host (`createPackHost`), using SHA-256.

ingestglobalgrid2050 / solar-design-studio/202609271853-site-world/world/pack-loader.mjs · lines 1–240 of 240 · version 2026-09-27 18:53 · Not reached from any entry point (candidate for review) · pattern active (shared by 2 files)

What it does
It fetches data. Defines 18 functions or classes, including createPackHost, off, guard, add, refuse. 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.
Downstream impact
Used directly by 1 file: Packs Mount (globalgrid2050).
What it achieves
It creates pack host (`createPackHost`) and is built from the off step (`off`) and the guard step (`guard`). Loads layer packs into a world, contract world.pack.v1 (see `CONTRACT.md` beside this folder).
Why it matters
Imported by Packs Mount.
Application
globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
Uses
Pack Check (import)
Used by
imported by Packs Mount (import)
Produces
createPackHost
Defines here
createPackHost, off, guard, add, refuse, load, setOn, toggle, live, frame, step, active, command, key, panel, help, dispose, disposeAll
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/202609271853-site-world/world/pack-loader.mjs:1-240 · blob bda545bd56e11bc0d1cd340c49c1c624137af425 · 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
// pack-loader.mjs: loads layer packs into a world, contract world.pack.v1 (see CONTRACT.md beside this folder).
// Dependency-free ES module; runs in a browser page and in Node 20+ (tests). No globals are read or written
// except fetch, crypto.subtle, URL, Blob and structuredClone, all of which can be passed in.
//
// A pack is a folder (served from the world's own site or from another URL) holding pack.json and one
// self-contained entry module. The world pins each pack in its manifest with the entry's SHA-256; that pin is
// the trust. The hash inside pack.json is only a consistency check between the pack and its own description.
//
//   manifest.packs: [{ id, from, version, sha256, config?, on? }]
//
// const host = createPackHost({ api, reserved, clock, importText, fetchImpl });
// await host.add(pin)            reads pack.json, validates it, checks the pin; loads now unless budget.lazy
// host.toggle(id, on)            switches a pack on or off; a lazy pack is fetched, checked and started on first use
// host.frame(ctx)                -> { lines, solids, hud } from every pack that is on, within its budget
// host.step(realDt, ctx)         fixed-step simulation: whole FIXED_DT steps, at most MAX_SUBSTEPS per call
// host.active()                  true while any pack asks for frames (the world draws 0 fps when this is false)
// host.command(line, io)         runs a pack command typed on the command line (loads a lazy pack first)
// host.key(key, io)              runs the command a pack bound to a key
// host.panel()                   rows for the Layers panel: { id, label, group, on, status, illustrative }
// host.help()                    every pack command with its usage and plain words
// host.dispose(id) / disposeAll()

// Split for the world: the checks and parts are in pack-check.mjs (re-exported here); the host is below.

import { API, FIXED_DT, MAX_SUBSTEPS, OVER_BUDGET_FRAMES, LIMITS, HEX, isObj, str, getText, readPack, apiRefusal, importRefusal,
  normalise, sha256Text, importText, createBus, advance, shapeRefusal } from './pack-check.mjs';
export * from './pack-check.mjs'; // the checks and parts live there (split only for the 400-line rule)

// ---------------------------------------------------------------- the host

// api: the world's layer api (base, fetchVerified, fetchJSON, invalidate, origin, lib, ...).
// reserved: verbs the world's own command line already uses. worldApi: { major, minor } this world offers.
// libVersion: the shared library version the world serves (null when it serves none).
export function createPackHost({
  api = {}, base = api.base, reserved = [], worldApi = API, libVersion = api.lib?.version ?? null,
  fetchImpl = (u, o) => fetch(u, o), importer = importText, subtle = globalThis.crypto?.subtle,
  clock = () => (globalThis.performance?.now?.() ?? Date.now()), onError = () => {}, fixedDt = FIXED_DT
} = {}) {
  const items = new Map(), verbs = new Map(), keys = new Map();
  const bus = createBus({ onError: (name, e) => onError(`event ${name}: ${e?.message || e}`) });
  const taken = new Set(reserved);
  let acc = 0, stats = { steps: 0, dropped: 0 };

  const off = (item, why) => {
    const was = item.module;
    item.on = false; item.module = null; item.status = why;
    try { was?.dispose?.(); } catch { /* already failing; the status says why */ }
    item.events?.offAll();
    api.invalidate?.({ ground: false });
  };
  const guard = (item, hook, fn) => {
    try { return fn(); } catch (e) { off(item, `switched off: ${hook}() threw: ${e?.message || e}`); onError(`${item.id}.${hook}: ${e?.message || e}`); return undefined; }
  };

  async function add(pin) {
    if (!isObj(pin) || !str(pin.from) || !HEX.test(pin.sha256 ?? '')) throw Error('a pack pin needs { from, sha256 } (the entry hash)');
    const { folder, pack, problems } = await readPack(pin.from, { base, fetchImpl });
    const id = pack?.id ?? pin.id ?? pin.from;
    const item = { id, folder, pack, pin, on: false, module: null, status: 'loading', loading: null, over: 0, events: null, overs: { vertices: 0, ms: 0 } };
    // A refused pack stays listed (the Layers panel names it and says why) but never replaces one already loaded.
    const refuse = why => { item.status = 'refused: ' + why; items.set(items.has(id) ? `${id}#refused-${items.size}` : id, item); return item; };
    if (problems.length) return refuse(problems.join('; '));
    if (items.has(id)) return refuse(`a pack with id ${id} is already loaded`);
    if (pin.id && pin.id !== pack.id) return refuse(`the world pinned id ${pin.id}, pack.json says ${pack.id}`);
    if (pin.version && pin.version !== pack.version) return refuse(`the world pinned version ${pin.version}, pack.json says ${pack.version}`);
    if (pin.sha256 !== pack.sha256) return refuse(`pack.json gives entry hash ${pack.sha256.slice(0, 12)}, the world pinned ${pin.sha256.slice(0, 12)}`);
    const api_ = apiRefusal(pack.requires.api, worldApi);
    if (api_) return refuse(api_);
    if (pack.requires.lib !== undefined && pack.requires.lib !== libVersion) return refuse(`it needs lib version ${pack.requires.lib}, the world serves ${libVersion ?? 'none'}`);
    for (const c of pack.provides.commands ?? []) if (taken.has(c.verb)) return refuse(`command ${c.verb} is already taken by ${verbs.get(c.verb) ?? 'the world'}`);
    for (const k of pack.provides.keys ?? []) if (keys.has(k.key)) return refuse(`key ${k.key} is already bound by ${keys.get(k.key).id}`);
    for (const c of pack.provides.commands ?? []) { taken.add(c.verb); verbs.set(c.verb, id); }
    for (const k of pack.provides.keys ?? []) keys.set(k.key, { id, command: k.command });
    items.set(id, item);
    const startOn = pin.on ?? pack.provides.toggle?.on ?? !pack.provides.toggle;
    if (pack.budget.lazy && !startOn) { item.status = 'ready: loads when switched on'; return item; }
    await load(id);
    if (item.module && startOn) setOn(item, true);
    return item;
  }

  function load(id) {
    const item = items.get(id);
    if (!item) return Promise.reject(Error(`no pack ${id}`));
    if (item.module || /^refused|^failed|^switched off/.test(item.status)) return Promise.resolve(item);
    return (item.loading ||= (async () => {
      const { pack, pin } = item;
      for (const [dep, major] of Object.entries(pack.requires.packs ?? {})) {
        const d = items.get(dep);
        if (!d || !d.pack || /^refused/.test(d.status)) { item.status = `refused: it needs pack ${dep} ${major}.x, which this world has not loaded`; return item; }
        if (Number(d.pack.version.split('.')[0]) !== major) { item.status = `refused: it needs pack ${dep} ${major}.x, the world has ${d.pack.version}`; return item; }
      }
      item.status = 'loading now';
      let text;
      try { text = normalise(await getText(fetchImpl, new URL(pack.entry, item.folder).href)); }
      catch (e) { item.status = 'failed: ' + e.message; return item; }
      const hash = await sha256Text(text, subtle);
      if (!hash) { item.status = 'refused: this browser cannot check hashes here (needs https)'; return item; }
      if (hash !== pin.sha256) { item.status = `refused: entry hash ${hash.slice(0, 12)} is not the pinned ${pin.sha256.slice(0, 12)}`; return item; }
      const imp = importRefusal(text);
      if (imp) { item.status = 'refused: ' + imp; return item; }
      let mod;
      try { mod = (await importer(text)).default; } catch (e) { item.status = 'failed: the entry did not import: ' + e.message; return item; }
      const shape = shapeRefusal(mod, pack);
      if (shape) { item.status = 'refused: ' + shape; return item; }
      item.events = bus.scoped(pack.id, pack.provides.events ?? {});
      const packApi = Object.freeze({
        ...api,
        config: pin.config ?? null,
        pack: Object.freeze({ id: pack.id, version: pack.version, kind: pack.kind, illustrative: pack.illustrative }),
        packApi: Object.freeze({ ...worldApi }),
        fixedDt,
        events: item.events,
        log: text => onError(`${pack.id}: ${String(text).slice(0, 200)}`)
      });
      item.module = mod;
      item.status = 'loaded, hash matches';
      try {
        const r = mod.init?.(packApi);
        if (r && typeof r.then === 'function') await r;
      } catch (e) { off(item, 'failed to start and switched off: ' + (e?.message || e)); return item; }
      if (item.module && typeof mod.commands === 'function') {
        const run = guard(item, 'commands', () => mod.commands()) ?? [];
        const want = new Set((pack.provides.commands ?? []).map(c => c.verb));
        const got = new Set(Array.isArray(run) ? run.filter(c => c && typeof c.run === 'function').map(c => c.verb) : []);
        const miss = [...want].filter(v => !got.has(v)), extra = [...got].filter(v => !want.has(v));
        const why = [miss.length ? 'missing ' + miss.join(', ') : '', extra.length ? 'undeclared ' + extra.join(', ') : ''].filter(Boolean).join('; ');
        if (miss.length || extra.length) { off(item, `refused: commands() does not match pack.json (${why})`); return item; }
        item.run = new Map(run.map(c => [c.verb, c.run]));
      } else if ((pack.provides.commands ?? []).length) { off(item, 'refused: pack.json lists commands but the entry has no commands()'); return item; }
      api.invalidate?.({ ground: typeof mod.heightAt === 'function' });
      return item;
    })().finally(() => { item.loading = null; }));
  }

  function setOn(item, on) {
    if (!item.module) return;
    item.on = !!on;
    if (typeof item.module.setEnabled === 'function') guard(item, 'setEnabled', () => item.module.setEnabled(item.on));
    bus.emit('world/toggle', { id: item.id, on: item.on });
    api.invalidate?.({ ground: typeof item.module?.heightAt === 'function' });
  }

  async function toggle(id, on) {
    const item = items.get(id);
    if (!item) throw Error(`no pack ${id}`);
    if (on && !item.module) await load(id);
    if (!item.module) return item;
    setOn(item, on);
    return item;
  }

  const live = () => [...items.values()].filter(i => i.on && i.module);

  function frame(ctx = {}) {
    const lines = [], solids = [], hud = [];
    for (const item of live()) {
      const { module: m, pack } = item, t0 = clock();
      const ls = typeof m.lines === 'function' ? guard(item, 'lines', () => m.lines(ctx)) : [];
      if (!item.module) continue;
      const sd = typeof m.solids === 'function' ? guard(item, 'solids', () => m.solids(ctx)) : [];
      if (!item.module) continue;
      const hd = typeof m.hud === 'function' ? guard(item, 'hud', () => m.hud(ctx)) : [];
      if (!item.module) continue;
      const ms = clock() - t0 + (item.stepMs || 0);
      item.stepMs = 0;
      let verts = 0;
      for (const b of Array.isArray(ls) ? ls : []) verts += (b?.positions?.length || 0) / 3;
      const overV = verts > pack.budget.maxVertices, overT = ms > pack.budget.maxMsPerFrame;
      item.over = overV || overT ? item.over + 1 : 0;
      item.last = { vertices: verts, ms };
      if (item.over >= OVER_BUDGET_FRAMES) {
        off(item, `switched off: over budget for ${OVER_BUDGET_FRAMES} frames (${Math.round(verts)} vertices, max ${pack.budget.maxVertices}; ${ms.toFixed(2)} ms, max ${pack.budget.maxMsPerFrame})`);
        continue;
      }
      if (overV) continue; // this frame's lines are left out; the pack keeps running until the limit above
      for (const b of Array.isArray(ls) ? ls : []) if (b && b.positions) lines.push({ ...b, key: `${pack.id}/${b.key ?? 'lines'}` });
      for (const s of Array.isArray(sd) ? sd : []) if (s && s.min && s.max) solids.push(s);
      const tag = pack.illustrative ? ' (illustrative)' : '';
      for (const h of (Array.isArray(hd) ? hd : []).slice(0, LIMITS.hudLines)) {
        if (h && typeof h.text === 'string') hud.push({ id: `${pack.id}/${h.id ?? 'hud'}`, text: (h.text.slice(0, LIMITS.hudChars) + tag) });
      }
    }
    return { lines, solids, hud };
  }

  function step(realDt, ctx = {}) {
    const r = advance(acc, realDt, fixedDt, MAX_SUBSTEPS);
    acc = r.acc; stats.steps += r.steps; stats.dropped += r.dropped;
    if (!r.steps) return r;
    for (const item of live()) {
      if (typeof item.module.step !== 'function') continue;
      const t0 = clock();
      for (let i = 0; i < r.steps && item.module; i++) guard(item, 'step', () => item.module.step(fixedDt, ctx));
      item.stepMs = (item.stepMs || 0) + clock() - t0;
    }
    return r;
  }

  const active = () => live().some(i => typeof i.module.active === 'function' && guard(i, 'active', () => !!i.module.active()));

  async function command(line, io = { say: () => {} }) {
    const w = String(line).trim().split(/\s+/), verb = w[0]?.toLowerCase();
    const id = verbs.get(verb);
    if (!id) return { ok: false, text: `no pack offers ${verb}` };
    const item = items.get(id);
    if (!item.module) await load(id);
    if (!item.module) return { ok: false, text: `${id}: ${item.status}` };
    if (!item.on) setOn(item, true);
    try {
      const out = await item.run.get(verb)(w.slice(1), io);
      api.invalidate?.({ ground: false });
      return { ok: true, text: typeof out === 'string' ? out : '' };
    } catch (e) { return { ok: false, text: `${verb}: ${e?.message || e}` }; }
  }

  const key = (k, io) => { const b = keys.get(k); return b ? command(b.command, io) : Promise.resolve(null); };

  const panel = () => [...items.values()].map(i => ({
    id: i.id, label: i.pack?.provides.toggle?.label ?? i.pack?.title ?? i.id, group: i.pack?.provides.toggle?.group ?? 'Packs',
    on: i.on, status: i.status, illustrative: !!i.pack?.illustrative, kind: i.pack?.kind ?? null
  }));

  const help = () => [...items.values()].flatMap(i => (i.pack?.provides.commands ?? []).map(c => ({ ...c, pack: i.id })));

  function dispose(id) {
    const item = items.get(id);
    if (!item) return;
    if (item.module) off(item, 'disposed');
    for (const [v, owner] of verbs) if (owner === id) { verbs.delete(v); taken.delete(v); }
    for (const [k, b] of keys) if (b.id === id) keys.delete(k);
    items.delete(id);
  }
  const disposeAll = () => { for (const id of [...items.keys()].reverse()) dispose(id); };

  return Object.freeze({
    add, load, toggle, frame, step, active, command, key, panel, help, dispose, disposeAll,
    bus, get: id => items.get(id), stats: () => ({ ...stats, acc })
  });
}

Packs Mount

A JavaScript module in the world folder of GlobalGrid2050 that shows hud (`showHud`), using SHA-256.

renderglobalgrid2050 / solar-design-studio/202609271853-site-world/world/packs-mount.mjs · lines 1–112 of 112 · version 2026-09-27 18:53 · Not reached from any entry point (candidate for review) · pattern keyName (shared by 2 files)

What it does
It draws its content. Defines 12 functions or classes, including packKeyAllowed, typing, packCtx, keyName, mountPacks. Side effects: changes the web page (DOM); 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.
What it achieves
It shows hud (`showHud`) and is built from the pack key allowed helper (`packKeyAllowed`) and the typing step (`typing`). Layer packs in the world (contract world.pack.v1; `pack-loader.mjs`). It responds to keydown and click events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
Uses
Pack Loader (import), Layers (import), Cmd Grammar (import)
Used by
none found
Produces
packKeyAllowed, packCtx, keyName, mountPacks
Defines here
packKeyAllowed, typing, packCtx, keyName, mountPacks, kick, bound, showHud, render, panelRoot, attach, watch
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/202609271853-site-world/world/packs-mount.mjs:1-112 · blob 3bdc220be2cd1b5ba9514c7710c2c0bc26221364 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
// Layer packs in the world (contract world.pack.v1; pack-loader.mjs). The manifest pins each installed pack by its
// entry's SHA-256 (tools/world-manifest.mjs from web/packs/pins.json); the pin is the trust. A pack is listed in the
// Layers panel under "Packs" and fetched only when it is switched on, one of its commands is typed or its key is pressed.
// Each drawn frame: fixed steps (at most 8), then its lines, solids and HUD lines. It asks for frames only while a pack
// says it is active, so a still world stays at 0 fps. Mounted after the first frame (extensions.mjs).

import { createPackHost } from './pack-loader.mjs';
import { makeApi } from './layers.mjs';
import { COMMANDS } from './cmd-grammar.mjs';

const WORLD_VERBS = ['build', 'buggy']; // typed words the world's extensions answer (build-mount.mjs, buggy-mount.mjs)
// Keys: the world keeps every plain key (Space jumps, letters walk, fly and open panels) and Shift with its movement letters
// (Shift is the slow walk); a pack's other Shift keys are its own. A pack's plain-key binding is still there by typing.
export const packKeyAllowed = k => /^Shift\+[a-z0-9]$/.test(k) && !/^Shift\+[wasdqe]$/.test(k);
const typing = t => t instanceof HTMLInputElement || t instanceof HTMLTextAreaElement || t instanceof HTMLSelectElement || t?.isContentEditable;

/** The frame context a pack sees: local metres, a look direction, the world's ground. */
export function packCtx(state, heightAt, groundVersion) {
  const { yaw = 0, pitch = 0 } = state, c = Math.cos(pitch);
  return { pos: [...state.pos], dir: [Math.sin(yaw) * c, Math.cos(yaw) * c, Math.sin(pitch)], heightAt, groundVersion };
}

/** The key name a pack binds ("Shift+n", "KeyB", "x") for a keyboard event. */
export const keyName = e => (e.shiftKey && e.key && e.key.length === 1 ? `Shift+${e.key.toLowerCase()}` : e.code || String(e.key || '').toLowerCase());

// deps: { api (the substrate's extension api), world (window.world), doc, manifestUrl, fetchImpl }
export async function mountPacks({ api, world = globalThis.window?.world, doc = document, manifestUrl = new URL('./manifest.json', import.meta.url).href,
  fetchImpl } = {}) {
  const get = fetchImpl || ((u, o) => fetch(u, o));
  const manifest = await (await get(manifestUrl, { cache: 'no-cache' })).json();
  const pins = Array.isArray(manifest.packs) ? manifest.packs : [];
  const base = new URL('./', manifestUrl).href;
  const layerApi = makeApi(base, { invalidate: o => api.invalidate(o), origin: () => ({ id: 0, ...api.origin() }), fetchImpl });
  const log = [];
  const host = createPackHost({ api: layerApi, base, reserved: [...COMMANDS.map(c => c.verb), ...WORLD_VERBS], fetchImpl,
    onError: t => { log.push(t); if (log.length > 50) log.shift(); console.warn('pack: ' + t); } });
  for (const pin of pins) await host.add(pin).catch(e => log.push(`pin ${pin.id}: ${e.message}`));

  let out = { lines: [], solids: [], hud: [] }, last = null, asked = false, pose = '', originKey = '';
  const kick = () => { // frames while a pack is active (a playing sun), then back to the walk's own rate: 0 fps when still
    const on = host.active();
    if (on && !asked) { asked = true; api.gate.setMoving(true, 30); } else if (!on && asked) { asked = false; api.resumeGate(); }
    api.gate.invalidate();
  };
  api.hooks.before.add(now => {
    const ctx = packCtx(api.state(), api.heightAt, world?.groundVersion?.() ?? 0), o = api.origin();
    const ok = `${o.e},${o.n}`;
    if (ok !== originKey) { originKey = ok; host.bus.emit('world/origin', { e: o.e, n: o.n, id: 0 }); }
    const pk = ctx.pos.map(v => v.toFixed(2)).join(',');
    if (pk !== pose) { pose = pk; host.bus.emit('world/pose', { pos: ctx.pos, dir: ctx.dir }); }
    host.step(last == null ? 0 : Math.min(0.25, (now - last) / 1000), ctx); last = asked ? now : null;
    out = host.frame(ctx);
    showHud(out.hud);
    if (asked !== host.active()) queueMicrotask(kick);
  });
  api.hooks.batches.add(() => out.lines);
  (api.hooks.solids ||= new Set()).add(() => out.solids);
  // Typed commands: a verb a pack offers goes to the pack (a lazy pack loads first); anything else is not ours.
  (api.hooks.commands ||= new Set()).add(line => {
    const verb = String(line).trim().split(/\s+/)[0]?.toLowerCase();
    if (!host.help().some(c => c.verb === verb)) return null;
    return host.command(line).then(r => { render(); kick(); return { ...r, line }; });
  });
  const bound = () => new Set(host.panel().flatMap(p => host.get(p.id)?.pack?.provides.keys?.map(k => k.key) || []));
  doc.addEventListener('keydown', e => {
    if (typing(e.target) || e.ctrlKey || e.metaKey || e.altKey) return;
    const k = keyName(e);
    if (!packKeyAllowed(k) || !bound().has(k)) return;
    e.preventDefault();
    host.key(k).then(() => { render(); kick(); });
  });

  // HUD: a small quiet box, only while a pack that is on has something to say (illustrative packs say so).
  const hud = doc.createElement('div');
  hud.id = 'pack-hud'; hud.hidden = true; hud.setAttribute('aria-live', 'polite');
  hud.style.cssText = 'position:fixed;left:8px;bottom:64px;max-width:min(360px,calc(100vw - 16px));padding:4px 8px;border-radius:4px;'
    + 'background:rgba(10,10,10,0.72);color:#cfe9ff;font:11px/1.45 system-ui,sans-serif;pointer-events:none;white-space:pre-line;z-index:3';
  doc.body.appendChild(hud);
  let hudText = '';
  function showHud(lines) {
    const t = lines.map(h => h.text).join('\n');
    if (t === hudText) return;
    hudText = t; hud.textContent = t; hud.hidden = !t;
  }

  // The Layers panel: a "Packs" group in the same switches as the world's layers, kept after each redraw of the panel.
  const group = doc.createElement('fieldset');
  group.id = 'lp-packs';
  function render() {
    const lg = doc.createElement('legend'); lg.textContent = 'Packs';
    const rows = host.panel().map(p => {
      const row = doc.createElement('div'), b = doc.createElement('button'), name = doc.createElement('span'), tr = doc.createElement('span');
      row.className = 'row'; b.type = 'button'; b.setAttribute('role', 'switch'); b.dataset.pack = p.id;
      b.setAttribute('aria-checked', String(p.on)); if (/^refused|^failed/.test(p.status)) b.setAttribute('aria-disabled', 'true');
      name.textContent = p.label + (p.illustrative ? ', illustrative' : ''); tr.className = 'track';
      b.append(name, tr);
      b.addEventListener('click', () => { if (b.getAttribute('aria-disabled') !== 'true') host.toggle(p.id, !p.on).then(() => { render(); kick(); }); });
      const st = doc.createElement('p'); st.className = 'status'; st.textContent = p.status;
      row.append(b, st);
      return row;
    });
    group.replaceChildren(lg, ...rows);
    attach();
  }
  const panelRoot = () => doc.querySelector('#layers .lp') || doc.querySelector('.lp');
  function attach() { const r = panelRoot(); if (r && group.parentNode !== r) r.appendChild(group); }
  const watch = () => { const r = panelRoot(); if (!r) return false; new MutationObserver(attach).observe(r, { childList: true }); attach(); return true; };
  if (!watch()) { const t = setInterval(() => { if (watch()) clearInterval(t); }, 500); setTimeout(() => clearInterval(t), 30000); }
  render();

  return { host, panel: () => host.panel(), hud: () => hudText, log: () => log.slice(), frame: () => ({ lines: out.lines.length, solids: out.solids.length }) };
}

Pick

A JavaScript module in the world folder of GlobalGrid2050 that snaps to grid (`snapToGrid`) and calculates planar distances. It picks ground (`pickGround`) and snaps grid (`snapToGrid`).

transformglobalgrid2050 / solar-design-studio/202609271853-site-world/world/pick.mjs · lines 1–55 of 55 · version 2026-09-27 18:53 · pattern rayFromScreen (shared by 2 files)

What it does
It calculates its inputs. Defines rayFromScreen, pickGround, below, snapToGrid, snap.
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.
Downstream impact
Used directly by 4 files: Module Mount (globalgrid2050); Single-Line Diagram (SLD) Mount (globalgrid2050); Build UI (globalgrid2050); Design UI (globalgrid2050). Reached from 2 other entry points, including Solar Design Studio — Site World Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609271853-site-world/); Substrate (globalgrid2050).
What it achieves
Picking: which point on the ground is under a pixel.
Why it matters
Imported by 4 files, including Module Mount, Single-Line Diagram (SLD) Mount and Build UI.
Application
globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
Uses
none found
Used by
imported by Module Mount (import), imported by Single-Line Diagram (SLD) Mount (import), imported by Build UI (import), imported by Design UI (import)
Produces
rayFromScreen, CURV, pickGround, snapToGrid
Defines here
rayFromScreen, pickGround, below, snapToGrid, snap
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/202609271853-site-world/world/pick.mjs:1-55 · blob d3f03feaf5c70c57868973263a8d400ba89f848e · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
// Picking: which point on the ground is under a pixel. Pure: no imports, no DOM, no WebGL.
// Conventions match camera.mjs: local east (x), north (y), up (z), metres; yaw 0 looks north (+y),
// yaw +π/2 looks east (+x); pitch up is positive. The view is built at the eye (eye-relative drawing),
// so the ray starts at the eye in local metres. Pixels: (0, 0) is the top-left corner of the canvas,
// px grows right and py grows down, as in DOM mouse events (use offsetX / offsetY scaled to canvas size).

// A ray through the centre of pixel position (px, py) on a width x height canvas. fovy in radians.
// Returns { origin: [x, y, z], dir: [x, y, z] } with dir of unit length.
export function rayFromScreen(px, py, width, height, eye, yaw, pitch, fovy) {
  const c = Math.cos(pitch);
  const f = [Math.sin(yaw) * c, Math.cos(yaw) * c, Math.sin(pitch)];   // camera.mjs direction()
  const r = [Math.cos(yaw), -Math.sin(yaw), 0];                         // camera.mjs view() right
  const u = [r[1] * f[2] - r[2] * f[1], r[2] * f[0] - r[0] * f[2], r[0] * f[1] - r[1] * f[0]]; // r x f
  const t = Math.tan(fovy / 2), aspect = width / height;
  const nx = (2 * px) / width - 1, ny = 1 - (2 * py) / height;          // normalised device coordinates
  const a = nx * t * aspect, b = ny * t;
  const d = [f[0] + r[0] * a + u[0] * b, f[1] + r[1] * a + u[1] * b, f[2] + r[2] * a + u[2] * b];
  const len = Math.hypot(d[0], d[1], d[2]);
  return { origin: [eye[0], eye[1], eye[2]], dir: [d[0] / len, d[1] / len, d[2] / len] };
}

// First point where the ray meets the ground, or null if it meets none within maxDistance metres.
// groundAt(x, y) -> ground height in metres. The ray is marched in steps of `step` metres; the first
// step that ends at or below the ground is bisected until the bracket is under 1 cm along the ray.
// Returns [x, y, groundAt(x, y)] so the point sits on the ground. A ray that starts below ground: null.
// curv: the renderer draws ground h metres from the eye CURV * h^2 lower (earth curvature with refraction, lines.mjs and
// accuracy.mjs), so the ray is tested against the ground as drawn; without it a far pick lands short (about 280 m at 2 km).
export const CURV = (1 - 0.13) / (2 * 6378137);
export function pickGround(ray, groundAt, { maxDistance = 2000, step = 0.5, curv = CURV } = {}) {
  const { origin: o, dir: d } = ray, h2 = d[0] * d[0] + d[1] * d[1];
  if (!(step > 0) || !(maxDistance > 0)) return null;
  const below = t => o[2] + d[2] * t <= groundAt(o[0] + d[0] * t, o[1] + d[1] * t) - curv * h2 * t * t;
  if (below(0)) return null;
  let lo = 0, hi = -1;
  for (let t = step; ; t += step) {
    const s = Math.min(t, maxDistance);
    if (below(s)) { hi = s; break; }
    lo = s;
    if (s >= maxDistance) return null;
  }
  while (hi - lo > 0.01) {
    const mid = (lo + hi) / 2;
    if (below(mid)) hi = mid; else lo = mid;
  }
  const t = (lo + hi) / 2, x = o[0] + d[0] * t, y = o[1] + d[1] * t;
  return [x, y, groundAt(x, y)];
}

// Snaps a point's x and y to the nearest multiple of spacing metres; z is kept as given
// (re-read the ground height afterwards if the snapped point must sit on the ground).
export function snapToGrid(point, spacing) {
  if (!(spacing > 0)) return [point[0], point[1], point[2]];
  const snap = v => Math.round(v / spacing) * spacing + 0; // + 0 turns -0 into 0
  return [snap(point[0]), snap(point[1]), point[2]];
}