In this section
- Phases render · globalgrid2050 / solar-design-studio/202609270439-site-world/world/phases.mjs lines 1–215
- Raycast render · globalgrid2050 / solar-design-studio/202609270439-site-world/world/raycast.mjs lines 1–326
Phases
A JavaScript module in the world folder of GlobalGrid2050 that compiles plan (`compilePlan`), validates plan (`validatePlan`) and creates timeline (`createTimeline`), covering cables.
renderglobalgrid2050 / solar-design-studio/202609270439-site-world/world/phases.mjs · lines 1–215 of 215 · version 2026-09-27 04:39 · Not reached from any entry point (candidate for review) · pattern createTimeline (shared by 2 files)
- What it does
- It lists and searches cables. Defines 20 functions or classes, including rank, list, issue, readItems, skip. Side effects: changes the web page (DOM).
- 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: cables.
- Downstream impact
- Used directly by 1 file: Project UI (globalgrid2050).
- What it achieves
- It compiles plan (`compilePlan`), validates plan (`validatePlan`) and creates timeline (`createTimeline`). Construction sequence over the design document.
- Why it matters
- Imported by Project UI.
- Application
- globalgrid2050 · solar-design-studio/202609270439-site-world/world · JavaScript module
- Uses
- none found
- Used by
- imported by Project UI (import)
- Produces
- STATES, LIFECYCLES, KINDS, DEFAULT_PHASES, compilePlan, validatePlan, createTimeline
- Defines here
- rank, list, issue, readItems, skip, wholeSteps, expand, rules, at, kindOf, reached, need, roadsFor, compilePlan, validatePlan, createTimeline, clamp, phaseAt, stateAt, label
- 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/phases.mjs:1-215 · blob a684c87c58d53b8635aa757f05b4598bdd348ee0 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
// phases.mjs: construction sequence over the design document.
// Pure logic: no imports, no DOM. Items are the things that get built (roads,
// pads, trenches, cables, fences, HDD bores, piles, equipment, deliveries);
// phases are named, ordered groups of tasks that move items through their
// lifecycle. A timeline turns a slider step into the state of every item, and
// validation flags orders that cannot happen on site (a cable laid before its
// trench is dug, a trench backfilled over an empty bed, a delivery with no road).
//
// Time is measured in abstract steps. A phase's `steps` is a user input (default
// 1) and means "slider units", not days: nothing here asserts how long any
// activity takes.
export const STATES = Object.freeze(['planned', 'dug', 'laid', 'backfilled', 'complete']);
// Lifecycle per kind: the states an item passes through, in order.
export const LIFECYCLES = Object.freeze({
road: ['planned', 'complete'],
pad: ['planned', 'complete'],
fence: ['planned', 'complete'],
pile: ['planned', 'complete'],
delivery: ['planned', 'complete'],
equipment: ['planned', 'complete'],
trench: ['planned', 'dug', 'backfilled', 'complete'],
hdd: ['planned', 'dug', 'complete'],
cable: ['planned', 'laid', 'complete']
});
export const KINDS = Object.freeze(Object.keys(LIFECYCLES));
// Default sequence. Names and order are a generic template, not a programme;
// `steps` are placeholders for the user to replace.
export const DEFAULT_PHASES = Object.freeze([
{ id: 'access', name: 'Access roads', tasks: [{ kind: 'road', to: 'complete' }] },
{ id: 'fencing', name: 'Security fencing', tasks: [{ kind: 'fence', to: 'complete' }] },
{ id: 'piling', name: 'Piling', tasks: [{ kind: 'pile', to: 'complete' }] },
{ id: 'pads', name: 'Pads and foundations', tasks: [{ kind: 'pad', to: 'complete' }] },
{ id: 'deliveries', name: 'Deliveries', tasks: [{ kind: 'delivery', to: 'complete' }] },
{ id: 'setting', name: 'Equipment setting', tasks: [{ kind: 'equipment', to: 'complete' }] },
{ id: 'trenching', name: 'Trenching and drilling', tasks: [{ kind: 'trench', to: 'dug' }, { kind: 'hdd', to: 'dug' }, { kind: 'hdd', to: 'complete' }] },
{ id: 'cabling', name: 'Cable laying', tasks: [{ kind: 'cable', to: 'laid' }] },
{ id: 'backfill', name: 'Backfill', tasks: [{ kind: 'trench', to: 'backfilled' }] },
{ id: 'reinstate', name: 'Reinstatement and testing', tasks: [{ kind: 'trench', to: 'complete' }, { kind: 'cable', to: 'complete' }] }
].map((p, i) => Object.freeze({ ...p, order: i + 1, steps: 1, tasks: Object.freeze(p.tasks.map(t => Object.freeze(t))) })));
const rank = (kind, state) => (LIFECYCLES[kind] || []).indexOf(state);
const list = v => (v == null ? [] : Array.isArray(v) ? v : [v]);
function issue(severity, code, message, extra = {}) {
return { severity, code, message, ...extra };
}
// Normalise items; flag bad kinds and duplicate ids. A reference to an item that is missing (or of the wrong kind)
// is dropped from the item and noted as a warning: the rest of the sequence still runs, and no rule ever follows it.
function readItems(items, issues) {
const byId = new Map();
for (const raw of list(items)) {
if (!raw || typeof raw.id !== 'string' || !raw.id) { issues.push(issue('error', 'BAD_ITEM', 'An item has no string id.')); continue; }
if (!LIFECYCLES[raw.kind]) { issues.push(issue('error', 'UNKNOWN_KIND', `Item ${raw.id} has unknown kind "${raw.kind}".`, { item: raw.id })); continue; }
if (byId.has(raw.id)) { issues.push(issue('error', 'DUPLICATE_ID', `Item id ${raw.id} is used twice.`, { item: raw.id })); continue; }
byId.set(raw.id, { ...raw, via: list(raw.via), after: list(raw.after) });
}
const skip = (it, what) => issues.push(issue('warning', 'BAD_REF', `Item ${it.id} names ${what}; that link is skipped.`, { item: it.id }));
for (const it of byId.values()) {
for (const key of ['trench', 'hdd', 'pad']) {
if (it[key] == null) continue;
if (byId.get(it[key])?.kind !== key) { skip(it, `${key} "${it[key]}", which is not a ${key} in this design`); delete it[key]; }
}
it.via = it.via.filter(r => byId.get(r)?.kind === 'road' || (skip(it, `via "${r}", which is not a road in this design`), false));
it.after = it.after.map(a => (typeof a === 'string' ? { item: a } : a)).filter(a => {
const t = byId.get(a?.item);
if (t && rank(t.kind, a.state || 'complete') >= 0) return true;
skip(it, `a wait on "${a?.item}" reaching "${a?.state || 'complete'}", which does not exist`);
return false;
});
}
return byId;
}
// Steps are slider units, so they are whole numbers; anything else is reported and rounded (at least 1).
function wholeSteps(p, idx, issues) {
if (p.steps === undefined) return 1;
if (Number.isInteger(p.steps) && p.steps > 0) return p.steps;
issues.push(issue('error', 'BAD_STEPS', `Phase "${p.name || idx + 1}" has ${p.steps} steps; steps are whole numbers from 1.`, { phase: p.id }));
return Math.max(1, Math.round(Number(p.steps)) || 1);
}
// Expand each phase's tasks to one operation per item, in sequence order.
function expand(phases, byId, issues) {
const sorted = list(phases).map((p, i) => ({ p, i }))
.sort((a, b) => (a.p.order ?? a.i) - (b.p.order ?? b.i) || a.i - b.i)
.map(({ p }, idx) => ({ id: p.id ?? `phase-${idx + 1}`, name: p.name || `Phase ${idx + 1}`, order: p.order ?? idx + 1,
steps: wholeSteps(p, idx, issues), tasks: list(p.tasks) }));
const ops = [];
sorted.forEach((ph, pi) => {
for (const t of ph.tasks) {
const ids = t.item != null ? list(t.item) : [...byId.values()].filter(it => it.kind === t.kind).map(it => it.id);
for (const id of ids) {
const it = byId.get(id);
if (!it) { issues.push(issue('error', 'UNKNOWN_ITEM', `Phase "${ph.name}" moves unknown item "${id}".`, { phase: ph.id, item: id })); continue; }
if (rank(it.kind, t.to) < 1) {
const msg = `Phase "${ph.name}" moves ${it.kind} ${id} to "${t.to}", which a ${it.kind} never reaches.`;
issues.push(issue('error', 'BAD_STATE', msg, { phase: ph.id, item: id }));
continue;
}
ops.push({ phase: pi, item: id, to: t.to });
}
}
});
return { phases: sorted, ops };
}
// Physical rules checked when `op` is applied to the current `state` map.
function rules(op, it, byId, state, allRoads) {
const out = [];
const at = id => state.get(id);
const kindOf = id => byId.get(id).kind;
const reached = (id, s) => rank(kindOf(id), at(id)) >= rank(kindOf(id), s);
// A missing item is already reported as BAD_REF by readItems; the rule is skipped, never a TypeError.
const need = (id, s, code, why) => { if (byId.has(id) && !reached(id, s)) out.push([code, `${why} (${id} is ${at(id)}).`]); };
const roadsFor = x => (x.via.length ? x.via : allRoads);
if (it.kind === 'cable' && op.to === 'laid') {
if (it.trench) {
need(it.trench, 'dug', 'CABLE_BEFORE_TRENCH', `Cable ${it.id} is laid before trench ${it.trench} is dug`);
if (byId.has(it.trench) && rank('trench', at(it.trench)) >= rank('trench', 'backfilled')) out.push(['CABLE_AFTER_BACKFILL', `Cable ${it.id} is laid after trench ${it.trench} was backfilled.`]);
}
if (it.hdd) need(it.hdd, 'dug', 'CABLE_BEFORE_BORE', `Cable ${it.id} is pulled before bore ${it.hdd} is drilled`);
}
if (it.kind === 'trench' && op.to === 'backfilled') {
for (const c of byId.values()) if (c.kind === 'cable' && c.trench === it.id) need(c.id, 'laid', 'BACKFILL_BEFORE_CABLE', `Trench ${it.id} is backfilled before cable ${c.id} is laid`);
}
if ((it.kind === 'equipment' || it.kind === 'delivery') && op.to === 'complete') {
for (const r of roadsFor(it)) need(r, 'complete', 'DELIVERY_BEFORE_ROAD', `${it.kind === 'delivery' ? 'Delivery' : 'Equipment'} ${it.id} arrives before road ${r} is built`);
}
if (it.kind === 'equipment' && op.to === 'complete' && it.pad) need(it.pad, 'complete', 'EQUIPMENT_BEFORE_PAD', `Equipment ${it.id} is set before pad ${it.pad} is complete`);
if (it.kind === 'pad' && op.to === 'complete') {
for (const r of roadsFor(it)) need(r, 'complete', 'PAD_BEFORE_ROAD', `Pad ${it.id} is built before road ${r} gives access`);
}
for (const a of it.after) if (byId.has(a.item)) need(a.item, a.state || 'complete', 'WAITS_ON', `${it.id} moves before ${a.item} reaches ${a.state || 'complete'}`);
return out;
}
// Compile items + phases into a checked sequence.
// Returns { items: Map, phases, ops, issues, ok, totalSteps }.
export function compilePlan(items, phases = DEFAULT_PHASES) {
const issues = [];
const byId = readItems(items, issues);
const { phases: ph, ops } = expand(phases, byId, issues);
const allRoads = [...byId.values()].filter(i => i.kind === 'road').map(i => i.id);
const state = new Map([...byId.keys()].map(id => [id, 'planned']));
for (const op of ops) {
const it = byId.get(op.item), from = state.get(op.item);
const where = { phase: ph[op.phase].id, item: op.item };
const lc = LIFECYCLES[it.kind], r0 = lc.indexOf(from), r1 = lc.indexOf(op.to);
if (r1 <= r0) { issues.push(issue('error', 'STATE_REGRESSION', `${it.id} is moved to ${op.to} but is already ${from}.`, where)); op.skip = true; continue; }
if (r1 > r0 + 1) issues.push(issue('error', 'SKIPPED_STATE', `${it.id} jumps from ${from} to ${op.to}, skipping ${lc.slice(r0 + 1, r1).join(', ')}.`, where));
for (const [code, message] of rules(op, it, byId, state, allRoads)) issues.push(issue('error', code, message, where));
op.from = from;
state.set(op.item, op.to);
}
for (const [id, s] of state) if (s !== 'complete') issues.push(issue('warning', 'INCOMPLETE', `${id} ends the sequence ${s}, not complete.`, { item: id }));
const totalSteps = ph.reduce((n, p) => n + p.steps, 0);
return { items: byId, phases: ph, ops: ops.filter(o => !o.skip), issues, ok: !issues.some(i => i.severity === 'error'), totalSteps };
}
export function validatePlan(items, phases = DEFAULT_PHASES) {
const { ok, issues } = compilePlan(items, phases);
return { ok, errors: issues.filter(i => i.severity === 'error'), warnings: issues.filter(i => i.severity === 'warning') };
}
// Timeline over a compiled plan. Step 0 is before any work; step totalSteps is
// the end. Inside a phase spanning several steps its operations complete in
// listed order, spread evenly across the span.
export function createTimeline(items, phases = DEFAULT_PHASES) {
const plan = compilePlan(items, phases);
const starts = [];
let acc = 0;
for (const p of plan.phases) { starts.push(acc); acc += p.steps; }
const opsBy = plan.phases.map((_, i) => plan.ops.filter(o => o.phase === i));
const clamp = s => Math.min(plan.totalSteps, Math.max(0, Number.isFinite(+s) ? +s : 0));
function phaseAt(step) {
const s = clamp(step);
for (let i = 0; i < plan.phases.length; i++) {
if (s < starts[i] + plan.phases[i].steps) return { index: i, ...plan.phases[i], start: starts[i], fraction: (s - starts[i]) / plan.phases[i].steps };
}
return null; // finished
}
function stateAt(step) {
const s = clamp(step);
const state = new Map([...plan.items.keys()].map(id => [id, 'planned']));
const active = new Map();
plan.phases.forEach((p, i) => {
const done = s >= starts[i] + p.steps ? opsBy[i].length : Math.floor(Math.max(0, s - starts[i]) / p.steps * opsBy[i].length + 1e-9);
opsBy[i].forEach((o, k) => {
if (k < done) state.set(o.item, o.to);
else if (s >= starts[i] && !active.has(o.item)) active.set(o.item, o.to);
});
});
const out = [...plan.items.values()].map(it => ({
id: it.id, kind: it.kind, state: state.get(it.id), exists: state.get(it.id) !== 'planned',
next: active.get(it.id) || null
}));
const counts = Object.fromEntries(STATES.map(st => [st, out.filter(o => o.state === st).length]));
return { step: s, phase: phaseAt(s), items: out, counts };
}
function label(step) {
const s = clamp(step), p = phaseAt(s);
if (s === 0) return `Step 0 of ${plan.totalSteps}: nothing started`;
if (!p) return `Step ${s} of ${plan.totalSteps}: sequence finished`;
return `Step ${s} of ${plan.totalSteps}: ${p.name} (phase ${p.index + 1} of ${plan.phases.length})`;
}
return { plan, totalSteps: plan.totalSteps, phaseAt, stateAt, label, clamp };
}Raycast
A JavaScript module in the world folder of GlobalGrid2050 that builds pyramid (`buildPyramid`), calculates planar distances and renders with WebGL. It builds pyramid (`buildPyramid`) and creates raycaster (`createRaycaster`).
renderglobalgrid2050 / solar-design-studio/202609270439-site-world/world/raycast.mjs · lines 1–326 of 326 · version 2026-09-27 04:39 · pattern createRaycaster (shared by 2 files)
- What it does
- It draws its content. Defines 14 functions or classes, including buildPyramid, basis, sunVector, createRaycaster, sh. Side effects: changes the web page (DOM).
- 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
- Out: WebGL/WebGPU drawing.
- Downstream impact
- Used directly by 1 file: Substrate (globalgrid2050). Reached from 1 other entry point, including Solar Design Studio — Site World Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609271853-site-world/).
- What it achieves
- Solid ground on the viewer's own GPU: a WebGL2 ray cast through the height field, drawn behind the lines.
- Why it matters
- Imported by Substrate.
- Application
- globalgrid2050 · solar-design-studio/202609270439-site-world/world · JavaScript module
- Uses
- none found
- Used by
- imported by Substrate (dynamic import)
- Produces
- DEFAULTS, NO_GROUND, buildPyramid, basis, sunVector, createRaycaster, gatherGrid, mountRaycast
- Defines here
- buildPyramid, basis, sunVector, createRaycaster, sh, tex, upload, setup, gatherGrid, slice, mountRaycast, gather, stale, backdrop
- 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/raycast.mjs:1-326 · blob f4231100f70425c6101ac754a5f9d6be62a92e4e · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
// Solid ground on the viewer's own GPU: a WebGL2 ray cast through the height field, drawn behind the lines.
// OPTIONAL and OFF by default. substrate.mjs imports this module only when "Solid ground (GPU)" is first switched
// on, so the first frame never waits for it. Where WebGL2 is missing (or its context fails) mountRaycast returns
// null and the world carries on in WebGL1 exactly as before. It draws only inside the substrate's own frames, so
// a still view stays at 0 fps; a new ground grid is gathered in slices between frames and asks for one frame.
//
// The method is the "positron" of the GPU night render pair (gw-lidar src/render_pair.py): a maximum-mipmap
// traversal (Tevs, Ihrke and Seidel 2008), 16 samples and 30 bisections in the 1-cell step, bilinear ground in
// lerp form. Its CuPy twin and its exact-quadratic partner are the witness; tests/raycast-vector.json holds a
// case computed there, tests/raycast.test.mjs checks the pure parts and tests/raycast-browser.cjs the shader.
// What it adds to the wireframe: the TRUE horizon (ground that is not measured is not drawn: a ray that finds no
// measured ground is sky, never a guessed plateau), sun shadows (one shadow ray per pixel, toward the sun of the
// sun control) and, when a target is set, a sightline tint (ground from which a person 1.7 m tall sees it).
// Local east (x), north (y), up (z) metres, the camera of camera.mjs / pick.mjs (yaw 0 north, pitch up +).
export const DEFAULTS = Object.freeze({ nodes: 1025, spacing: 2, farNodes: 1025, farSpacing: 8, scale: 0.5, sliceMs: 6, person: 1.7 });
export const NO_GROUND = -1e4; // a node with no measured height: far below anything, so rays pass
const K = 16, BIS = 30, PROBE = 1e-3;
// Maximum-mipmap levels of a node grid (n = 2^k + 1 nodes a side): level 0 holds the highest of each cell's four
// nodes, level L the highest of each 2x2 block of level L-1. Pure.
export function buildPyramid(h, n) {
const c = n - 1;
if (c & (c - 1)) throw Error('buildPyramid needs 2^k + 1 nodes a side');
let lv = new Float32Array(c * c);
for (let j = 0; j < c; j++) for (let i = 0; i < c; i++)
lv[j * c + i] = Math.max(h[j * n + i], h[j * n + i + 1], h[(j + 1) * n + i], h[(j + 1) * n + i + 1]);
const levels = [lv];
for (let m = c / 2; m >= 1; m /= 2) {
const p = levels[levels.length - 1], w = m * 2, nx = new Float32Array(m * m);
for (let j = 0; j < m; j++) for (let i = 0; i < m; i++)
nx[j * m + i] = Math.max(p[2 * j * w + 2 * i], p[2 * j * w + 2 * i + 1], p[(2 * j + 1) * w + 2 * i], p[(2 * j + 1) * w + 2 * i + 1]);
levels.push(nx);
}
return levels;
}
// Camera basis of camera.mjs view(): forward, right, up. Pure.
export function basis(yaw, pitch) {
const c = Math.cos(pitch), f = [Math.sin(yaw) * c, Math.cos(yaw) * c, Math.sin(pitch)], r = [Math.cos(yaw), -Math.sin(yaw), 0];
return { f, r, 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]] };
}
// Unit vector toward the sun from grid azimuth and elevation (degrees), as sun-mode.mjs reports them. Pure.
export function sunVector({ azimuth, elevation }) {
const a = azimuth * Math.PI / 180, e = elevation * Math.PI / 180;
return [Math.sin(a) * Math.cos(e), Math.cos(a) * Math.cos(e), Math.sin(e)];
}
const VS = `#version 300 es
in vec2 p; void main() { gl_Position = vec4(p, 0.0, 1.0); }`;
const FS = `#version 300 es
precision highp float; precision highp int; precision highp sampler2D;
uniform sampler2D uH, uP, uH1, uP1; uniform int n, top, n1, top1, useFar, mode, useSun, useTarget; uniform vec2 size, g0, g01;
uniform float sp, sp1, tanHalf, aspect, person; uniform vec3 eye, cf, cr, cu, sun, target, bg, light;
out vec4 o;
const int K = ${K}, BIS = ${BIS}, MAX_ITER = 60000; const float PROBE = ${PROBE}, INF = 1e30;
float hz(sampler2D H, int i, int j) { return texelFetch(H, ivec2(i, j), 0).r - eye.z; }
float lerpH(sampler2D H, int ci, int cj, float u, float v) {
float s0 = hz(H, ci, cj) * (1.0 - u) + hz(H, ci + 1, cj) * u, s1 = hz(H, ci, cj + 1) * (1.0 - u) + hz(H, ci + 1, cj + 1) * u;
return s0 * (1.0 - v) + s1 * v; }
float cl(float x) { return min(max(x, 0.0), 1.0); }
// 1 when a corner of the cell has no measured ground: the steep wall down to NO_GROUND there is what draws the stair-step
// silhouette of the 8 m far tiles against the sky, so the colour pass fades such cells into the sky (hits are unchanged)
float rim(sampler2D H, int ci, int cj) {
return min(min(texelFetch(H, ivec2(ci, cj), 0).r, texelFetch(H, ivec2(ci + 1, cj), 0).r),
min(texelFetch(H, ivec2(ci, cj + 1), 0).r, texelFetch(H, ivec2(ci + 1, cj + 1), 0).r)) < ${NO_GROUND / 2}.0 ? 1.0 : 0.0; }
// the positron on one grid, in its cells: origin o (local x, y metres; z metres above the eye), unit d, to tfar
float trace(sampler2D H, sampler2D P, int n, int top, float sp, vec2 g0, vec3 o, vec3 d, float tfar, out int hci, out int hcj) {
float ex = (o.x - g0.x) / sp, ey = (o.y - g0.y) / sp, oz = o.z;
float dx = d.x / sp, dy = d.y / sp, dz = d.z, X1 = float(n - 1);
float tx = dx > 0.0 ? (X1 - ex) / dx : (dx < 0.0 ? -ex / dx : INF);
float ty = dy > 0.0 ? (X1 - ey) / dy : (dy < 0.0 ? -ey / dy : INF);
float tExit = min(tfar, min(tx, ty)), t = 0.0; int L = top; hci = 0; hcj = 0;
if (ex < 0.0 || ey < 0.0 || ex > X1 || ey > X1) return INF;
for (int it = 0; it < MAX_ITER; it++) {
if (!(t < tExit)) break;
float te = t + PROBE, qx = ex + dx * te, qy = ey + dy * te;
int sz = 1 << L, w = (n - 1) >> L;
int ci = int(floor(qx / float(sz))), cj = int(floor(qy / float(sz)));
if (dx < 0.0 && float(ci * sz) == qx) ci -= 1;
if (dy < 0.0 && float(cj * sz) == qy) cj -= 1;
ci = clamp(ci, 0, w - 1); cj = clamp(cj, 0, w - 1);
float x0 = float(ci * sz), y0 = float(cj * sz);
float cx = dx > 0.0 ? (x0 + float(sz) - ex) / dx : (dx < 0.0 ? (x0 - ex) / dx : INF);
float cy = dy > 0.0 ? (y0 + float(sz) - ey) / dy : (dy < 0.0 ? (y0 - ey) / dy : INF);
float tc = min(min(cx, cy), tExit);
if (tc <= t) tc = t + PROBE;
if (min(oz + dz * t, oz + dz * tc) > texelFetch(P, ivec2(ci, cj), L).r - eye.z) { t = tc; if (L < top) L++; continue; }
if (L > 0) { L--; continue; }
float fx = float(ci), fy = float(cj), lo = t, hi = -1.0;
if ((oz + dz * t) - lerpH(H, ci, cj, cl(ex + dx * t - fx), cl(ey + dy * t - fy)) <= 0.0) hi = t;
else {
for (int k = 1; k <= K; k++) {
float tq = t + (tc - t) * (float(k) / float(K));
if ((oz + dz * tq) - lerpH(H, ci, cj, cl(ex + dx * tq - fx), cl(ey + dy * tq - fy)) <= 0.0) { hi = tq; break; }
lo = tq;
}
if (hi >= 0.0) for (int b = 0; b < BIS; b++) {
float m = 0.5 * (lo + hi);
if ((oz + dz * m) - lerpH(H, ci, cj, cl(ex + dx * m - fx), cl(ey + dy * m - fy)) <= 0.0) hi = m; else lo = m;
}
}
if (hi >= 0.0) { hci = ci; hcj = cj; return hi; }
t = tc; if (L < top) L++;
}
return INF;
}
// near grid first; a ray that leaves it without a hit carries on in the far grid from where it left
float castAll(vec3 o, vec3 d, float tfar, out int which, out int ci, out int cj) {
which = 0; float t = trace(uH, uP, n, top, sp, g0, o, d, tfar, ci, cj);
if (t < INF || useFar == 0) return t;
vec2 lo = g0, hi = g0 + sp * float(n - 1); float tn = 0.0;
if (all(greaterThanEqual(o.xy, lo)) && all(lessThanEqual(o.xy, hi))) {
float ax = d.x > 0.0 ? (hi.x - o.x) / d.x : (d.x < 0.0 ? (lo.x - o.x) / d.x : INF);
float ay = d.y > 0.0 ? (hi.y - o.y) / d.y : (d.y < 0.0 ? (lo.y - o.y) / d.y : INF);
tn = min(ax, ay);
}
if (!(tn < tfar)) return INF;
which = 1; t = trace(uH1, uP1, n1, top1, sp1, g01, o + d * tn, d, tfar - tn, ci, cj);
return t < INF ? tn + t : INF;
}
vec3 normalAt(int which, int ci, int cj, vec3 P) { // central differences in the hit cell of the grid it was found in
float s = which == 0 ? sp : sp1; vec2 g = which == 0 ? g0 : g01;
float uh = cl((P.x - g.x) / s - float(ci)), vh = cl((P.y - g.y) / s - float(cj));
const float h = 0.015625;
float ua = min(max(uh, h), 1.0 - h), va = min(max(vh, h), 1.0 - h), gx, gy;
if (which == 0) { gx = lerpH(uH, ci, cj, ua + h, vh) - lerpH(uH, ci, cj, ua - h, vh); gy = lerpH(uH, ci, cj, uh, va + h) - lerpH(uH, ci, cj, uh, va - h); }
else { gx = lerpH(uH1, ci, cj, ua + h, vh) - lerpH(uH1, ci, cj, ua - h, vh); gy = lerpH(uH1, ci, cj, uh, va + h) - lerpH(uH1, ci, cj, uh, va - h); }
return normalize(vec3(-gx / (2.0 * h * s), -gy / (2.0 * h * s), 1.0));
}
void main() {
vec2 ndc = 2.0 * gl_FragCoord.xy / size - 1.0; // pixel centres, as pick.mjs rayFromScreen
vec3 d = normalize(cf + cr * (ndc.x * tanHalf * aspect) + cu * (ndc.y * tanHalf));
int which, ci, cj, w2, si, sj;
float T = castAll(vec3(eye.xy, 0.0), d, INF, which, ci, cj), shadow = -1.0, seen = -1.0, lam = 0.0;
if (T < INF) {
vec3 P = vec3(eye.xy, 0.0) + d * T, nrm = normalAt(which, ci, cj, P); // local x, y; z above the eye
if (useSun == 1) {
shadow = castAll(P + nrm * 0.1, sun, INF, w2, si, sj) < INF ? 1.0 : 0.0;
lam = max(dot(nrm, sun), 0.0);
} else lam = 0.25 + 0.75 * max(dot(nrm, light), 0.0); // no sun control on: a plain hillshade light
if (useTarget == 1) {
vec3 a = P + vec3(0.0, 0.0, person), v = vec3(target.xy, target.z - eye.z) - a; float L = length(v);
seen = castAll(a, v / L, max(L - 1.0, 0.01), w2, si, sj) < INF ? 0.0 : 1.0;
}
}
if (mode == 1) { o = vec4(T, shadow, seen, lam); return; }
if (!(T < INF)) { o = vec4(bg, 1.0); return; }
vec3 c = vec3(0.30, 0.37, 0.27) * (0.30 + 0.75 * (shadow > 0.5 ? 0.0 : lam));
if (shadow > 0.5) c *= vec3(0.9, 0.95, 1.15);
if (seen > 0.5) c = mix(c, vec3(0.2, 0.75, 0.85), 0.35);
// horizon: distance haze as before, plus a fade over the last 30 % of the far grid's reach and on cells at the rim
// of the measured ground, so the far ring meets the sky softly instead of in 8 m steps (colour only; mode 1 is exact)
float R1 = sp1 * float(n1 - 1) * 0.5, edge = which == 0 ? rim(uH, ci, cj) : rim(uH1, ci, cj);
float fade = max(min(T / 3000.0, 0.8), max(which == 1 ? smoothstep(0.7 * R1, R1, T) : 0.0, 0.85 * edge));
o = vec4(mix(c, bg, fade), 1.0);
}`;
// The ray caster on a WebGL2 context: upload a grid, render a pose to the canvas or read back distances.
export function createRaycaster(gl) {
if (!gl.getExtension('EXT_color_buffer_float')) throw Error('EXT_color_buffer_float is missing');
const sh = (t, s) => { const x = gl.createShader(t); gl.shaderSource(x, s); gl.compileShader(x);
if (!gl.getShaderParameter(x, gl.COMPILE_STATUS)) throw Error(gl.getShaderInfoLog(x)); return x; };
const prog = gl.createProgram();
gl.attachShader(prog, sh(gl.VERTEX_SHADER, VS)); gl.attachShader(prog, sh(gl.FRAGMENT_SHADER, FS)); gl.linkProgram(prog);
if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) throw Error(gl.getProgramInfoLog(prog));
const U = {}; for (const k of ['uH', 'uP', 'uH1', 'uP1', 'n', 'top', 'n1', 'top1', 'useFar', 'mode', 'useSun', 'useTarget', 'size', 'g0', 'g01',
'sp', 'sp1', 'tanHalf', 'aspect', 'person', 'eye', 'cf', 'cr', 'cu', 'sun', 'target', 'bg', 'light']) U[k] = gl.getUniformLocation(prog, k);
const vao = gl.createVertexArray(); gl.bindVertexArray(vao);
const buf = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buf);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);
const pl = gl.getAttribLocation(prog, 'p'); gl.enableVertexAttribArray(pl); gl.vertexAttribPointer(pl, 2, gl.FLOAT, false, 0, 0);
const grids = [null, null], texs = [[null, null], [null, null]]; let dataFb = null, dataTex = null, dataSize = [0, 0];
const tex = () => { const t = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, t);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); return t; };
// g: { h: Float32Array n*n (rows south to north), n, spacing, x0, y0 } local metres; level 0 near, 1 far (or null)
function upload(g, level = 0) {
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
for (const t of texs[level]) if (t) gl.deleteTexture(t);
if (!g) { grids[level] = null; texs[level] = [null, null]; return; }
gl.activeTexture(gl.TEXTURE0); const texH = tex(); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texStorage2D(gl.TEXTURE_2D, 1, gl.R32F, g.n, g.n); gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, g.n, g.n, gl.RED, gl.FLOAT, g.h);
const levels = buildPyramid(g.h, g.n), c = g.n - 1;
gl.activeTexture(gl.TEXTURE1); const texP = tex(); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST_MIPMAP_NEAREST);
gl.texStorage2D(gl.TEXTURE_2D, levels.length, gl.R32F, c, c);
levels.forEach((lv, l) => gl.texSubImage2D(gl.TEXTURE_2D, l, 0, 0, c >> l, c >> l, gl.RED, gl.FLOAT, lv));
grids[level] = { ...g, top: levels.length - 1 }; texs[level] = [texH, texP];
}
// p: { eye: [x, y, z], yaw, pitch, fovy, width, height, sun?: [x, y, z], target?: [x, y, z], bg?: [r, g, b] }
function setup(p, mode) {
const b = basis(p.yaw, p.pitch);
gl.useProgram(prog); gl.bindVertexArray(vao);
const g = grids[0], f = grids[1] || grids[0], tf = grids[1] ? texs[1] : texs[0];
[texs[0][0], texs[0][1], tf[0], tf[1]].forEach((t, k) => { gl.activeTexture(gl.TEXTURE0 + k); gl.bindTexture(gl.TEXTURE_2D, t); });
gl.uniform1i(U.uH, 0); gl.uniform1i(U.uP, 1); gl.uniform1i(U.uH1, 2); gl.uniform1i(U.uP1, 3);
gl.uniform1i(U.n, g.n); gl.uniform1i(U.top, g.top); gl.uniform1i(U.n1, f.n); gl.uniform1i(U.top1, f.top);
gl.uniform1i(U.useFar, grids[1] ? 1 : 0); gl.uniform1i(U.mode, mode);
gl.uniform2f(U.g01, f.x0, f.y0); gl.uniform1f(U.sp1, f.spacing);
gl.uniform1i(U.useSun, p.sun ? 1 : 0); gl.uniform1i(U.useTarget, p.target ? 1 : 0);
gl.uniform2f(U.size, p.width, p.height); gl.uniform2f(U.g0, g.x0, g.y0); gl.uniform1f(U.sp, g.spacing);
gl.uniform1f(U.tanHalf, Math.tan(p.fovy / 2)); gl.uniform1f(U.aspect, p.width / p.height); gl.uniform1f(U.person, p.person ?? DEFAULTS.person);
gl.uniform3fv(U.eye, p.eye); gl.uniform3fv(U.cf, b.f); gl.uniform3fv(U.cr, b.r); gl.uniform3fv(U.cu, b.u);
gl.uniform3fv(U.sun, p.sun || [0, 0, 1]); gl.uniform3fv(U.target, p.target || [0, 0, 0]); gl.uniform3fv(U.bg, p.bg || [0.04, 0.04, 0.04]);
gl.uniform3fv(U.light, sunVector({ azimuth: 315, elevation: 45 }));
gl.viewport(0, 0, p.width, p.height); gl.disable(gl.DEPTH_TEST); gl.disable(gl.BLEND);
}
return {
ready: () => !!grids[0], grid: (level = 0) => grids[level], upload,
render(p) { if (!grids[0]) return false; gl.bindFramebuffer(gl.FRAMEBUFFER, null); setup(p, 0); gl.drawArrays(gl.TRIANGLES, 0, 3); return true; },
// Per pixel, rows from the TOP: [distance (1e30 sky), shadow (1, 0, -1 no ground), seen (1, 0, -1), sun term].
readData(p) {
if (!grids[0]) return null;
if (!dataFb || dataSize[0] !== p.width || dataSize[1] !== p.height) {
if (dataTex) gl.deleteTexture(dataTex);
gl.activeTexture(gl.TEXTURE4); dataTex = tex(); gl.texStorage2D(gl.TEXTURE_2D, 1, gl.RGBA32F, p.width, p.height);
dataFb = dataFb || gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, dataFb);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, dataTex, 0); dataSize = [p.width, p.height];
}
gl.bindFramebuffer(gl.FRAMEBUFFER, dataFb); setup(p, 1); gl.drawArrays(gl.TRIANGLES, 0, 3);
const raw = new Float32Array(p.width * p.height * 4), out = new Float32Array(raw.length);
gl.readPixels(0, 0, p.width, p.height, gl.RGBA, gl.FLOAT, raw); gl.bindFramebuffer(gl.FRAMEBUFFER, null);
const row = p.width * 4;
for (let y = 0; y < p.height; y++) out.set(raw.subarray((p.height - 1 - y) * row, (p.height - y) * row), y * row);
return out;
}
};
}
// Gathers the measured ground around (cx, cy) into a node grid, a few rows per slice, then calls done(grid).
// Unmeasured nodes get NO_GROUND. Returns a cancel function.
export function gatherGrid(measuredAt, cx, cy, { nodes = DEFAULTS.nodes, spacing = DEFAULTS.spacing, sliceMs = DEFAULTS.sliceMs } = {}, done, later = f => setTimeout(f, 0)) {
const half = (nodes - 1) / 2 * spacing, x0 = Math.round((cx - half) / spacing) * spacing, y0 = Math.round((cy - half) / spacing) * spacing;
const h = new Float32Array(nodes * nodes); let j = 0, cancelled = false, measured = 0;
const slice = () => {
if (cancelled) return;
const t0 = performance.now();
do { // at least one row a slice, however small the budget
for (let i = 0; i < nodes; i++) { const v = measuredAt(x0 + i * spacing, y0 + j * spacing); if (Number.isFinite(v)) { h[j * nodes + i] = v; measured++; } else h[j * nodes + i] = NO_GROUND; }
j++;
} while (j < nodes && performance.now() - t0 < sliceMs);
if (j < nodes) later(slice); else done({ h, n: nodes, spacing, x0, y0, measured });
};
later(slice);
return () => { cancelled = true; };
}
// The optional layer. w: { lines, canvas, state, FOV, measuredAt, groundVersion, origin, sun, invalidate, doc }.
// Returns null (and the caller hides the switch) where WebGL2 cannot run it.
export function mountRaycast(w, opts = {}) {
const o = { ...DEFAULTS, ...opts }, doc = w.doc || document;
let gl2 = null, rc = null;
const off = doc.createElement('canvas');
try { gl2 = off.getContext('webgl2', { antialias: false, depth: false, alpha: false }); if (gl2) rc = createRaycaster(gl2); } catch { rc = null; }
if (!rc) return null;
let on = false, cancel = null, built = null, target = null, lastGv = -1, lastMs = 0, frames = 0, gatherMs = 0;
const gl1 = w.lines.context(), T1 = gl1.createTexture(), B1 = gl1.createBuffer();
gl1.bindTexture(gl1.TEXTURE_2D, T1);
for (const [k, v] of [[gl1.TEXTURE_MIN_FILTER, gl1.LINEAR], [gl1.TEXTURE_MAG_FILTER, gl1.LINEAR],
[gl1.TEXTURE_WRAP_S, gl1.CLAMP_TO_EDGE], [gl1.TEXTURE_WRAP_T, gl1.CLAMP_TO_EDGE]]) gl1.texParameteri(gl1.TEXTURE_2D, k, v);
gl1.bindBuffer(gl1.ARRAY_BUFFER, B1); gl1.bufferData(gl1.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl1.STATIC_DRAW);
const q = gl1.createProgram();
for (const [t, s] of [[gl1.VERTEX_SHADER, 'attribute vec2 p; varying vec2 v; void main() { v = p * 0.5 + 0.5; gl_Position = vec4(p, 0.0, 1.0); }'],
[gl1.FRAGMENT_SHADER, 'precision mediump float; uniform sampler2D t; varying vec2 v; void main() { gl_FragColor = texture2D(t, v); }']]) {
const s1 = gl1.createShader(t); gl1.shaderSource(s1, s); gl1.compileShader(s1); gl1.attachShader(q, s1);
}
gl1.linkProgram(q);
const qp = gl1.getAttribLocation(q, 'p'), qt = gl1.getUniformLocation(q, 't');
// Grids are anchored in national-grid metres, so an origin move does not shift the ground under the viewer.
// The near grid (1025 nodes at 2 m) comes first and is drawn at once; the far grid (1025 at 8 m, where the
// far-ring tiles give ground past the 1 m tiles) follows. A far node with no measured ground stays NO_GROUND.
let farBuilt = null;
function gather() {
const s = w.state(), og = w.origin(); cancel?.(); const t0 = performance.now();
cancel = gatherGrid(w.measuredAt, s.pos[0], s.pos[1], o, g => {
gatherMs = performance.now() - t0; lastMs = performance.now();
rc.upload(g, 0); built = { e0: g.x0 + og.e, n0: g.y0 + og.n, measured: g.measured, cx: s.pos[0] + og.e, cy: s.pos[1] + og.n };
w.invalidate({ ground: false });
cancel = gatherGrid(w.measuredAt, s.pos[0], s.pos[1], { ...o, nodes: o.farNodes, spacing: o.farSpacing }, f => {
cancel = null;
// a far grid that measured nothing past the near one adds nothing: leave the far grid off
const beyond = f.measured > g.measured / ((o.farSpacing / o.spacing) ** 2) * 1.05;
rc.upload(beyond ? f : null, 1); farBuilt = beyond ? { e0: f.x0 + og.e, n0: f.y0 + og.n, measured: f.measured } : null;
w.invalidate({ ground: false });
});
});
}
function stale() {
if (!built) return !cancel;
const s = w.state(), og = w.origin(), reach = (o.nodes - 1) * o.spacing / 4;
if (Math.hypot(s.pos[0] + og.e - built.cx, s.pos[1] + og.n - built.cy) > reach) return true;
return w.groundVersion() !== lastGv && performance.now() - lastMs > 1500;
}
// Called by lines.draw right after it clears: ray cast into the WebGL2 canvas, then paint it as the backdrop.
function backdrop(gl, width, height) {
if (!on) return;
if (stale() && !cancel) { lastGv = w.groundVersion(); gather(); }
if (!rc.ready() || !built) return;
const s = w.state(), og = w.origin(), sunNow = w.sun?.();
rc.grid(0).x0 = built.e0 - og.e; rc.grid(0).y0 = built.n0 - og.n;
if (farBuilt && rc.grid(1)) { rc.grid(1).x0 = farBuilt.e0 - og.e; rc.grid(1).y0 = farBuilt.n0 - og.n; }
const W = Math.max(1, Math.round(width * o.scale)), H = Math.max(1, Math.round(height * o.scale));
if (off.width !== W || off.height !== H) { off.width = W; off.height = H; }
rc.render({ eye: s.pos, yaw: s.yaw, pitch: s.pitch, fovy: w.FOV, width: W, height: H,
sun: sunNow && sunNow.elevation > 0 ? sunVector(sunNow) : null, target: target ? [target[0] - w.origin().e, target[1] - w.origin().n, target[2]] : null });
gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, T1);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true); // a canvas's top row is the texture's last
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, off); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
gl.useProgram(q); gl.bindBuffer(gl.ARRAY_BUFFER, B1); gl.enableVertexAttribArray(qp); gl.vertexAttribPointer(qp, 2, gl.FLOAT, false, 0, 0);
gl.uniform1i(qt, 0);
gl.disable(gl.DEPTH_TEST); gl.disable(gl.BLEND); gl.depthMask(false);
gl.drawArrays(gl.TRIANGLES, 0, 3);
gl.enable(gl.BLEND); gl.depthMask(true);
frames++;
}
return {
set(v) { on = !!v; w.lines.setBackdrop(on ? backdrop : null); if (!on) { cancel?.(); cancel = null; } w.invalidate({ ground: false }); },
on: () => on,
// A point in national-grid metres (e, n, height m) to test sightlines to; null clears it.
setTarget(t) { target = t; w.invalidate({ ground: false }); },
readData: p => rc.readData(p), grid: () => rc.grid(),
debug: () => ({ on, ready: rc.ready(), gathering: !!cancel, frames, gatherMs: Math.round(gatherMs), measured: built?.measured ?? 0,
far: farBuilt ? { measured: farBuilt.measured, nodes: o.farNodes, spacing: o.farSpacing } : null,
nodes: o.nodes, spacing: o.spacing, scale: o.scale, sun: !!w.sun?.(), target })
};
}