In this section
- Plant UI interaction · globalgrid2050 / solar-design-studio/202609271853-site-world/world/plant-ui.mjs lines 1–342
- Procedural Detail transform · globalgrid2050 / solar-design-studio/202609271853-site-world/world/procedural-detail.mjs lines 1–114
- Procedural Key ingest · globalgrid2050 / solar-design-studio/202609271853-site-world/world/procedural-key.mjs lines 1–82
- Senses Mount interaction · globalgrid2050 / solar-design-studio/202609271853-site-world/world/senses-mount.mjs lines 1–84
- Site Checks transform · globalgrid2050 / solar-design-studio/202609271853-site-world/world/site-checks.mjs lines 1–48
Plant UI
A JavaScript module in the world folder of GlobalGrid2050 that draws ground (`drawGround`), sets boundary (`setBoundary`), builds lines (`buildLines`) and calculates planar distances (units: MW, kV).
interactionglobalgrid2050 / solar-design-studio/202609271853-site-world/world/plant-ui.mjs · lines 1–342 of 342 · version 2026-09-27 18:53 · Not reached from any entry point (candidate for review) · pattern clearLayout (shared by 2 files)
- What it does
- It draws overhead lines (OHL), substations and transformers. Defines 29 functions or classes, including PAUSE, createPlant, $, say, measured. 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: overhead lines (OHL), substations, transformers, 33kV.
- Inputs & outputs
- Voltage levels named: 33kV.
- Downstream impact
- Used directly by 1 file: Design Sections (globalgrid2050).
- What it achieves
- It creates plant (`createPlant`), draws ground (`drawGround`) and sets boundary (`setBoundary`). Design > Plant layout. The user draws a boundary (the Boundary tool, or the open land around them), picks a capacity and a layout, and the plant is laid out on the measured ground (`plant-layout.mjs`), in slices between frames. Its code works with 33 kV and 500 MW. It responds to click events.
- Why it matters
- Imported by Design Sections.
- Application
- globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
- Uses
- Origin (import), Plant Layout (import), Plant Template (import), MV Network (import), Plant Ground (import), Measure Format (import), Plant Piles (import), Pile Rules (import), and 5 more
- Used by
- imported by Design Sections (dynamic import)
- Produces
- createPlant
- Defines here
- PAUSE, createPlant, $, say, measured, drawGround, formParams, withForm, setBoundary, useOpenLand, run, drawPlant, buildLines, make, put, seg, at, path, c, place, batches, pilesAuto, n0, pileReadout, r0, pileSnapshot, boqItems, showReport, clearLayout
- 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/plant-ui.mjs:1-342 · blob a5a1ff7c80435e2a390b1f0fb6ac14f93e8b6731 · 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
// plant-ui.mjs: Design > Plant layout. The user draws a boundary (the Boundary tool, or the open land around them),
// picks a capacity and a layout, and the plant is laid out on the measured ground (plant-layout.mjs), in slices
// between frames. It is drawn as quiet lines: fence, tables, roads, stations, the compound and the MV trenches.
// Every table is piled automatically (plant-piles.mjs) and drawn on its piles at their fitted heights; piles that need
// grading are drawn warm. Nobody places a pile.
// Everything is held in national-grid metres; each batch keeps its positions relative to its own base point, so
// a move of the site origin only moves the base (no rebuild, no upload).
import { toBng, toLocal } from './origin.mjs';
import { layoutPlantAsync, LAYOUTS, LABEL, tableGeometry, LAYOUT_DEFAULTS } from './plant-layout.mjs';
import { plantTemplate } from './plant-template.mjs';
import { equipmentSolids, solidLines } from './mv-network.mjs';
import { createSiteGround } from './plant-ground.mjs';
import { formatNumber, formatLength, formatVolume } from './measure-format.mjs';
import { pilesForLayout, pileBoqItems, STRIDE } from './plant-piles.mjs';
import { trackerHub } from './pile-rules.mjs';
import { trenchRows } from './plant-feeders.mjs';
import { centralItems, itemSolids } from './plant-central.mjs';
import { packPlant, packSize } from './plant-pack.mjs';
import { createLod } from './plant-lod.mjs';
import { plantView, blockView, boxOfPoints } from './nav-flight.mjs';
const COLOUR = { fence: [0.8, 0.8, 0.8, 0.7], tables: [0.6, 0.67, 0.78, 0.55], roads: [0.78, 0.74, 0.62, 0.6],
equipment: [0.85, 0.88, 0.95, 1], mv: [1, 0.55, 0.25, 0.9], piles: [0.95, 0.9, 0.55, 1], pileWarn: [1, 0.45, 0.35, 1] };
const LOD_TABLES = 5000; // above this many tables the plant is drawn by distance (plant-lod.mjs), never as one batch
const LOD_COLOUR = { outline: COLOUR.fence, blocks: [0.6, 0.67, 0.78, 0.8], stations: COLOUR.equipment, runs: COLOUR.tables, tables: COLOUR.tables,
detail: [0.7, 0.78, 0.9, 0.7] };
const PILES_DRAWN_MAX = 200000; // above this many piles none are drawn, never a scatter of flagged ones (the counts cover all)
const PAUSE = () => new Promise(r => setTimeout(r, 0));
// deps: { doc, origin(), viewer(), measuredAt(x, y) local, heightAt(x, y) local, assets() -> [{ kind, e, n }], redraw(),
// nearest(e, n) -> Promise<{ e, n } | null> the nearest substation in the national index }
export function createPlant({ doc, origin, viewer, measuredAt, heightAt, assets = () => [], nearest = null, redraw, release = () => false, ohlZones = () => null }) {
const $ = id => doc.getElementById(id);
const ground = createSiteGround();
const state = { boundary: null, result: null, draw: null, running: false, version: 0, summary: null, rows: null, pack: null, lod: null };
const say = (msg, warn = false) => { const el = $('plant-status'); el.textContent = msg; el.className = warn ? 'warn' : ''; };
const measured = fn => (e, n) => {
const h = fn(e, n);
if (Number.isFinite(h)) return h;
const [x, y] = toLocal(origin(), e, n);
return measuredAt(x, y);
};
let sample = ground.heightAt;
const drawGround = (e, n) => { const h = measured(sample)(e, n); if (Number.isFinite(h)) return h; const [x, y] = toLocal(origin(), e, n); return heightAt(x, y); };
$('plant-layout').replaceChildren(...LAYOUTS.map(([id, label]) => new Option(label, id)));
ground.start().then(() => {
// Presets only on open-land sites; elsewhere the capacity is typed.
$('plant-presets').hidden = !/^open-land-/.test(ground.site()?.name || '');
}).catch(() => {});
for (const b of doc.querySelectorAll('#plant-presets [data-mw]')) b.addEventListener('click', () => { $('plant-mw').value = b.dataset.mw; });
// The form's values as parameters: the buttons pass these, the typed bar passes its own (and the form then shows them).
const formParams = () => ({ mw: Number($('plant-mw').value), layout: $('plant-layout').value,
slopeLimitPct: Number($('plant-slope').value) || 15, fenceSetbackM: Number($('plant-fence').value) || 8 });
const withForm = (q = {}) => {
const P = { ...formParams(), ...q };
for (const [id, k] of [['plant-mw', 'mw'], ['plant-layout', 'layout'], ['plant-slope', 'slopeLimitPct'], ['plant-fence', 'fenceSetbackM']]) if (k in q) $(id).value = String(q[k]);
return P;
};
function setBoundary(path) {
if (path.length < 3) { say('A boundary needs at least three corners.', true); return false; }
state.boundary = path.map(p => [p.e, p.n]); clearLayout(false);
say(`Boundary set: ${path.length} corners. Choose a capacity and press Lay out.`);
return true;
}
// The open land around the viewer: a square big enough for the capacity asked (room for roads, setbacks and overhead line
// zones), kept on the measured tiles.
async function useOpenLand(params = {}) {
await ground.start().catch(() => {});
const P = withForm(params), mw = P.mw, v = viewer(), c = params.at || toBng(origin(), v.pos[0], v.pos[1]);
const tpl = plantTemplate({ ...(P.template || {}), targetMW: Math.min(5000, Math.max(1, mw || 1)) });
const T = tableGeometry(P.layout, { ...LAYOUT_DEFAULTS, ...(P.options || {}) }, tpl);
const side = Math.sqrt(Math.ceil(tpl.counts.strings / 2) * T.pitch * (T.lenU + LAYOUT_DEFAULTS.tableGapM) * 1.5) + 2 * P.fenceSetbackM;
const fine = ground.extent(), wide = fine && side > Math.min(fine.e1 - fine.e0, fine.n1 - fine.n0);
// Larger than the 1 m tiles (500 MW is about 3.3 km square): centred on the measured site, out onto the far ring.
const x = wide ? ground.extent({ ring: true }) : fine, m = wide && !params.at ? { e: (fine.e0 + fine.e1) / 2, n: (fine.n0 + fine.n1) / 2 } : c;
let [e0, n0, e1, n1] = [m.e - side / 2, m.n - side / 2, m.e + side / 2, m.n + side / 2];
if (x) { e0 = Math.max(e0, x.e0 + 1); n0 = Math.max(n0, x.n0 + 1); e1 = Math.min(e1, x.e1 - 1); n1 = Math.min(n1, x.n1 - 1); }
setBoundary([{ e: e0, n: n0 }, { e: e1, n: n0 }, { e: e1, n: n1 }, { e: e0, n: n1 }]);
say(`Open land ${wide ? 'on this site' : 'around you'}: ${formatLength(e1 - e0)} × ${formatLength(n1 - n0)}${x ? ', kept on the measured tiles' : ''}`
+ `${wide ? ' (beyond the 1 m tiles, the 8 m far ring)' : ''}. Press Lay out.`);
redraw();
return state.boundary;
}
// params (all optional; the form fills the rest): { mw, layout: 'south' | 'east-west' | 'tracker', slopeLimitPct, fenceSetbackM,
// ohlMargin, openLand: true, options: layout overrides, template: plant template overrides,
// avoid: [{ id, test(e, n) }] areas kept clear (the typed session passes its overhead line test as id 'ohl') }
async function run(params = {}) {
if (state.running) return null;
// Short names from tests and older hooks (slope, fence) map onto the form's; the rest pass through withForm.
if (params.slope != null && params.slopeLimitPct == null) params = { ...params, slopeLimitPct: params.slope };
if (params.fence != null && params.fenceSetbackM == null) params = { ...params, fenceSetbackM: params.fence };
if (params.openLand || (params.mw != null && !state.boundary)) await useOpenLand(params);
if (!state.boundary) { say('Draw a boundary, or use the open land around you, first.', true); return null; }
state.running = true; $('plant-run').disabled = true;
const t0 = performance.now();
try {
const b = state.boundary, box = { e0: Math.min(...b.map(q => q[0])), n0: Math.min(...b.map(q => q[1])),
e1: Math.max(...b.map(q => q[0])), n1: Math.max(...b.map(q => q[1])) };
say('Reading the measured ground under the boundary…');
const fine = ground.extent(), ring = !!fine && (box.e0 < fine.e0 || box.n0 < fine.n0 || box.e1 > fine.e1 || box.n1 > fine.n1);
await ground.loadFor(box, k => say(`Reading the measured ground: ${k} tiles`), { ring }).catch(() => null);
const water = await ground.water().catch(() => []); // the water layer's watercourses (OS Open Rivers), for the setback
const mid = [(box.e0 + box.e1) / 2, (box.n0 + box.n1) / 2];
// The compound faces the nearest substation: the national index (read tile by tile) where the page has it, else the
// substations loaded here. With neither, the layout says so and puts the compound on the south side.
say('Finding the nearest substation…');
const national = nearest ? await Promise.resolve().then(() => nearest(mid[0], mid[1])).catch(() => null) : null;
const sub = national || assets().filter(a => a.kind === 'substation')
.sort((p, q) => Math.hypot(p.e - mid[0], p.n - mid[1]) - Math.hypot(q.e - mid[0], q.n - mid[1]))[0];
sample = ground.sampler();
const P = withForm(params), typedAvoid = Array.isArray(params.avoid);
// The typed session passes its own overhead line test (or none: "avoid pylons off"); the forms use the zones layer.
// The survey date check reads the site's data fields (plant-ground.mjs survey); none given, nothing is said.
const r = await layoutPlantAsync({ boundary: b, targetMW: P.mw, layout: P.layout, template: P.template, avoid: P.avoid, piles: P.piles, survey: ground.survey?.(),
groundAt: measured(sample), grid: sub ? [sub.e, sub.n] : null, water, ohl: typedAvoid ? null : ohlZones(),
options: { ...(P.options || {}), slopeLimitPct: P.slopeLimitPct, fenceSetbackM: P.fenceSetbackM,
...(Number.isFinite(params.ohlMargin) ? { ohlMarginM: params.ohlMargin } : {}) } },
{ onProgress: p => say(p.phase === 'tables' ? `Laying out: ${p.candidates} positions tried, ${p.accepted} tables fit`
: p.phase === 'piles' ? `Piling every table: ${p.tables} done` : `Laying out: ${p.phase}`) });
if (ground.ringShare() > 0) r.notes.push(`${formatNumber(ground.ringShare() * 100, 0)} % of the ground heights read came from the 8 m far ring `
+ 'beyond the 1 m tiles: slopes there are coarse and hollows under 8 m are not seen. Survey before design.');
await drawPlant(r);
r.seconds = (performance.now() - t0) / 1000; r.grid = sub || null; r.waterLines = water.length;
state.result = r; state.version++;
showReport(r); redraw();
return state.summary;
} catch (e) { say(e.message, true); return null; }
finally { state.running = false; $('plant-run').disabled = false; }
}
// A large plant is packed (plant-pack.mjs) and drawn by distance (plant-lod.mjs); tables and piles leave the flat batches.
async function drawPlant(r) {
state.lod?.dispose(); state.lod = null; state.pack = null;
if (r.built.tables > LOD_TABLES) {
const pt = r.piles?.tables, pack = state.pack = packPlant(r, { surface: q => pt?.[q]?.edges || null }), [pe, pn] = pack.origin;
let asked = false;
state.lod = createLod(pack, { colours: LOD_COLOUR, release, version: state.version + 1,
onPending: () => { if (!asked) { asked = true; setTimeout(() => { asked = false; redraw(); }, 0); } },
extra: (q, v, b) => { const pr = pt?.[q]; if (pr) for (let i = 0; i < pr.n; i++) { const o = i * STRIDE; // the piles, near the eye only
v.push(pr.pa[o] - pe - b[0], pr.pa[o + 1] - pn - b[1], pr.pa[o + 4] - b[2], pr.pa[o] - pe - b[0], pr.pa[o + 1] - pn - b[1], pr.pa[o + 3] - b[2]); } } });
}
state.draw = await buildLines(r, { tables: !state.lod });
}
// ---- lines, built in slices; absolute national-grid positions kept relative to a base point per batch ----
async function buildLines(r, { tables: withTables = true } = {}) {
const F = r.frame, T = r.table, P = r.params, out = {};
const make = () => ({ base: null, v: [] });
const put = (L, e, n, z) => { if (!L.base) L.base = [e, n, z]; L.v.push(e - L.base[0], n - L.base[1], z - L.base[2]); };
const seg = (L, a, b) => { put(L, ...a); put(L, ...b); };
const at = (u, v, dz = 0) => { const [e, n] = F.en(u, v); return [e, n, drawGround(e, n) + dz]; };
const path = (L, pts, dz = 0.05, step = 10) => { // a draped line, one point every step metres
for (let i = 1; i < pts.length; i++) {
const [u0, v0] = pts[i - 1], [u1, v1] = pts[i], k = Math.max(1, Math.ceil(Math.hypot(u1 - u0, v1 - v0) / step));
for (let s = 0; s < k; s++) seg(L, at(u0 + (u1 - u0) * s / k, v0 + (v1 - v0) * s / k, dz), at(u0 + (u1 - u0) * (s + 1) / k, v0 + (v1 - v0) * (s + 1) / k, dz));
}
};
out.fence = make(); for (const f of r.fields || [r.boundary]) path(out.fence, [...f, f[0]], 1.5); // every field of the plant
out.tables = make();
const lo = P.lowEdgeM, hi = lo + T.rise, t = r.tables, pt = r.piles?.tables;
out.piles = make(); out.pileWarn = make();
const all = (r.piles?.summary.piles || 0) <= PILES_DRAWN_MAX;
let t0 = performance.now();
for (let q = 0; withTables && q < t.length; q += 6) {
const [ua, va, h0, h1, h2, h3] = t.subarray(q, q + 6), ub = ua + (r.tableLen?.[q / 6] ?? T.lenU), vb = va + T.depth, pr = pt?.[q / 6];
const c = (u, v, z) => { const [e, n] = F.en(u, v); return [e, n, z]; };
if (pr) for (let i = 0; i < pr.n; i++) { // piles, from the ground (or graded ground) to the top
const o = i * STRIDE, L = pr.pf[i] & 3 ? out.pileWarn : out.piles;
if (all) seg(L, [pr.pa[o], pr.pa[o + 1], pr.pa[o + 4]], [pr.pa[o], pr.pa[o + 1], pr.pa[o + 3]]);
}
// On its piles: the fitted module surface heights; without piles, a fixed height over the ground.
const hub = trackerHub().hub, fb = T.tracker ? [[(h0 + h3) / 2 + hub, (h1 + h2) / 2 + hub]].flatMap(x => [x, x, x]) : null;
const [Ea, Em, Eb] = pr ? pr.edges : fb || [[h0 + lo, h1 + lo], [(h0 + h3) / 2 + hi, (h1 + h2) / 2 + hi], T.south ? [h3 + hi, h2 + hi] : [h3 + lo, h2 + lo]];
if (T.tracker) { // tracker at stow: the modules flat on the tube, and the tube along the middle
const vm = (va + vb) / 2, A = c(ua, va, Ea[0]), B = c(ub, va, Ea[1]), C = c(ub, vb, Eb[1]), D = c(ua, vb, Eb[0]);
seg(out.tables, A, B); seg(out.tables, B, C); seg(out.tables, C, D); seg(out.tables, D, A); seg(out.tables, c(ua, vm, Em[0]), c(ub, vm, Em[1]));
} else if (T.south) {
const A = c(ua, va, Ea[0]), B = c(ub, va, Ea[1]), C = c(ub, vb, Eb[1]), D = c(ua, vb, Eb[0]);
seg(out.tables, A, B); seg(out.tables, B, C); seg(out.tables, C, D); seg(out.tables, D, A);
} else {
const vm = (va + vb) / 2, A = c(ua, va, Ea[0]), B = c(ub, va, Ea[1]), C = c(ub, vb, Eb[1]), D = c(ua, vb, Eb[0]);
const M = c(ua, vm, Em[0]), N = c(ub, vm, Em[1]);
seg(out.tables, A, B); seg(out.tables, D, C); seg(out.tables, M, N);
seg(out.tables, A, M); seg(out.tables, M, D); seg(out.tables, B, N); seg(out.tables, N, C);
}
if (performance.now() - t0 > 10) { await PAUSE(); t0 = performance.now(); }
}
out.roads = make();
const sp = r.spine;
for (const d of [-P.spineWidthM / 2, P.spineWidthM / 2]) path(out.roads, [[sp.u + d, sp.v0], [sp.u + d, sp.v1]]);
for (const tr of r.trackRoads) for (const d of [-P.trackWidthM / 2, P.trackWidthM / 2]) path(out.roads, [[tr.u0, tr.v + d], [tr.u1, tr.v + d]]);
if (r.access) for (const d of [-P.trackWidthM / 2, P.trackWidthM / 2]) path(out.roads, [[r.access.u0, r.access.v + d], [r.access.u1, r.access.v + d]]);
await PAUSE();
// Equipment: station skids at their pads, the compound fence, the switchroom and the grid transformers.
out.equipment = make();
const cm = r.compound, [ce, cn] = F.en(cm.u, cm.v), cz = drawGround(ce, cn), base = [ce, cn, cz];
const solids = [];
const place = (kind, u, v, id) => { const [e, n] = F.en(u, v); solids.push(...equipmentSolids(kind, [e - ce, n - cn, drawGround(e, n) - cz], 0, id)); };
for (const s of r.stations) if (!s.central) place('station', s.u, s.v, s.id);
for (const it of centralItems(r)) { const [e, n] = F.en(it.u, it.v); solids.push(...itemSolids(it.kind, [e - ce, n - cn, drawGround(e, n) - cz], it.id)); }
place('switchboard', cm.u - cm.w / 4, cm.v, 'switchroom');
const gts = r.template?.counts.gridTransformers || 0;
for (let g = 0; g < gts; g++) place('grid-transformer', cm.u + 4 + (g % 2) * 14 - 2, cm.v - cm.d / 4 + Math.floor(g / 2) * 10, 'GT' + (g + 1));
out.equipment.base = base; out.equipment.v = solidLines(solids);
path(out.fence, [[cm.u - cm.w / 2, cm.v - cm.d / 2], [cm.u + cm.w / 2, cm.v - cm.d / 2], [cm.u + cm.w / 2, cm.v + cm.d / 2],
[cm.u - cm.w / 2, cm.v + cm.d / 2], [cm.u - cm.w / 2, cm.v - cm.d / 2]], 2.4);
// MV trenches: beside the road they follow, one line per trench wall.
out.mv = make();
const off = P.trackWidthM / 2 + 1.5, sOff = P.spineWidthM / 2 + 1.5;
for (const pc of r.electrical?.pieces || []) {
const w = (pc.c > 1 ? 0.8 : 0.45) * Math.ceil(pc.c / 2) / 2;
for (const d of [-w, w]) {
if (pc.key === 's') path(out.mv, [[r.spine.u + sOff + d, pc.a], [r.spine.u + sOff + d, pc.b]], 0.02);
else if (pc.key === 'a') path(out.mv, [[pc.a, r.access.v + off + d], [pc.b, r.access.v + off + d]], 0.02);
else if (pc.key.startsWith('t')) { const v = r.tracks[Number(pc.key.slice(1))] + off + d; path(out.mv, [[pc.a, v], [pc.b, v]], 0.02); }
else path(out.mv, [[pc.u + d, pc.a + off], [pc.u + d, pc.b]], 0.02);
}
}
for (const k of Object.keys(out)) if (!(out[k].v instanceof Float32Array)) out[k].v = new Float32Array(out[k].v);
return out;
}
function batches() {
const out = [], o = origin(), d = state.draw;
if (state.boundary && !d) { // the boundary alone, before a layout
const v = [], b = state.boundary, z = (e, n) => drawGround(e, n) + 1.5;
for (let i = 0; i < b.length; i++) { const [e0, n0] = b[i], [e1, n1] = b[(i + 1) % b.length]; v.push(e0, n0, z(e0, n0), e1, n1, z(e1, n1)); }
const base = v.slice(0, 3), rel = new Float32Array(v.map((x, i) => x - base[i % 3]));
out.push({ key: 'plant-boundary', version: `${state.version}:${b.length}`, positions: rel, color: COLOUR.fence, origin: [base[0] - o.e, base[1] - o.n, base[2]] });
}
if (d && state.lod) { // a large plant: by distance from the eye
const v = viewer(), p = toBng(o, v.pos[0], v.pos[1]), [pe, pn] = state.pack.origin;
out.push(...state.lod.batches([p.e - pe, p.n - pn, v.pos[2]], b => [pe + b[0] - o.e, pn + b[1] - o.n, b[2]]));
}
if (d) for (const k of ['fence', 'tables', 'piles', 'pileWarn', 'roads', 'equipment', 'mv']) {
const L = d[k];
if (!L.base || L.v.length < 6) continue;
out.push({ key: 'plant-' + k, version: state.version, positions: L.v, color: COLOUR[k === 'fence' ? 'fence' : k], origin: [L.base[0] - o.e, L.base[1] - o.n, L.base[2]] });
}
return out;
}
// ---- piles: automatic from the tables; rerun on the laid-out plant with other rules (typed "piles auto") ----
async function pilesAuto(opts = {}) {
const r = state.result;
if (!r || state.running) return null;
const it = pilesForLayout(r, measured(sample), { posts: opts.posts, mwp: r.built.mwp, rules: opts.rules, soil: opts.soil });
let x, t0 = performance.now();
while (!(x = it.next()).done) if (performance.now() - t0 > 10) { await PAUSE(); t0 = performance.now(); }
r.piles = x.value; state.version++; await drawPlant(r);
showReport(r); redraw();
return state.summary.piles;
}
const n0 = x => formatNumber(x, 0), n2 = x => formatNumber(x, 2);
function pileReadout(pl) {
if (!pl) return [['Piles', 'none: no tables']];
const s = pl.summary, R = pl.rules, top = s.suggestions[0];
const tr = s.system === 'tracker', what = tr ? 'posts along each tracker tube' : pl.posts === 1 ? 'one post per table' : 'front and rear posts per table';
return [['Piles', `${n0(s.piles)} (${n0(s.perMWp)} per MWp), ${what}, automatic`],
['Pile metres', `${formatLength(s.totalPileLengthM)} in all; ${formatLength(s.embeddedM)} embedded (${n2(R.embedM)} m each at least; `
+ `soil assumed ${R.soilFrom ? `from ${R.soilFrom}` : `${R.soil.replace(/_/g, ' ')}, not read from the geology here`})`],
['Reveal', `${n2(Math.max(0, s.finishedP?.[0] ?? s.revealP[0]))} to ${n2(s.finishedP?.[2] ?? s.revealP[2])} m out of the ground once graded `
+ `(${tr ? 'from the tube height' : `design ${n2(r0(state.result).lowEdgeM)} m low edge plus the table rise`})`],
['Pile flags', `${n0(s.revealAdjust)} piles outside ±${n2(R.revealAdjustM)} m adjustment · ${n0(s.revealHigh + s.revealLow)} outside the band · `
+ (tr ? `${n0(s.cannotFollow)} rows the tracker cannot follow (bay to bay ${formatNumber(R.bayChangeMaxDeg, 1)}°, reveal ${n2(R.revealWindowM[0])} to ${n2(R.revealWindowM[1])} m)`
: `${n0(s.twistTables)} tables where the ground twists over ${formatNumber(R.twistTolDeg, 1)}° · ${n0(s.lowEdgeTables)} with the low edge under ${n2(R.lowEdgeClearM)} m`),
s.revealHigh + s.revealLow + s.twistTables + s.cannotFollow > 0],
['', `${n0(s.embedBelowReveal)} posts lengthened: embedded at least ${n2(R.embedToReveal ?? 0)} × their reveal (lateral load)${s.revealWarn + s.revealFail ? ` · ${n0(s.revealWarn)} more than `
+ `${n2(R.revealWarnAboveM)} m above their design height, ${n0(s.revealFail)} over ${n2(R.revealFailM)} m` : ''}`
+ `${s.unmeasured ? ` · ${n0(s.unmeasured)} tables partly on unmeasured ground` : ''}`],
['Pile tests', `${n0(s.proofTests)} production proof tests (${formatNumber(R.proofTestPct, 1)} %, spread evenly); trial piles per zone before works`
+ `${tr ? '' : ` · ground twist median ${formatNumber(s.twistP50Deg, 1)}°, largest ${formatNumber(s.twistMaxDeg, 1)}°`}`],
['Grading', s.gradingTables ? `${n0(s.gradingTables)} tables (ground as found: ${n2(s.revealP[0])} to ${n2(s.revealP[2])} m under the post tops): `
+ `${n0(s.regrade)} regrade · ${n0(s.raise)} raise · ${n0(s.drop)} drop · `
+ `cut ${formatVolume(s.cutM3)} / fill ${formatVolume(s.fillM3)} (indicative)` : 'none needed'],
...(top ? [['', `Largest patch: ${top.action}, ${top.tables.length} table${top.tables.length === 1 ? '' : 's'}, up to ${n2(top.maxDepth)} m`]] : []),
['Pile rules', R.label]];
}
const r0 = r => r?.params || { lowEdgeM: NaN };
const pileSnapshot = pl => (pl ? { ...pl.summary, suggestions: pl.summary.suggestions.length, posts: pl.posts } : null);
const boqItems = () => pileBoqItems('plant-piles', state.result?.piles?.summary, 'plant');
// ---- report ----
function showReport(r) {
const e = r.electrical, km = m => `${formatNumber(m / 1000, 2)} km`, pct = x => formatNumber(x, 2) + ' %';
const rows = [['Asked', `${r.asked.mw} MW export, ${formatNumber(r.asked.mwp, 1)} MWp DC`],
['Achieved', `${r.built.mw} MW export, ${formatNumber(r.built.mwp, 1)} MWp DC${r.fits ? '' : ' (does not all fit)'}`],
['Tables', `${r.built.tables.toLocaleString('en-GB')} tables of ${r.table.modules} modules each${r.built.halfTables ? ` (${r.built.halfTables} half tables)` : ''}, `
+ `${{ south: 'south-facing', tracker: 'single-axis tracker rows' }[r.layout] || 'east-west'}, ${r.packing || 'bands'} packing`],
...pileReadout(r.piles), ['Stations', r.stations.some(s => s.central) ? `${r.built.stations} central-inverter stations, `
+ `${r.stations.reduce((t, s) => t + (s.combiners || 0), 0).toLocaleString('en-GB')} DC combiner boxes` : String(r.built.stations)], ['33 kV feeders', String(r.built.feeders)],
['Roads', `${km(r.built.roadM)} (spine, ${r.trackRoads.length} track runs${r.access ? ', access' : ''})`]];
if (e) {
rows.push(...trenchRows(e, v => formatNumber(v, 2)).rows);
rows.push(['Worst MV drop', pct(e.worstDropPct)]);
}
const sk = r.skipped;
rows.push(['Left out', `slope ${sk.slope} · twist ${sk.twist || 0} · hollows ${sk.hollow} · water ${sk.water} · overhead line ${sk.ohl}`
+ ` · setback ${sk.setback} · not measured ${sk.unmeasured}`]);
if (r.grid) {
const [ce, cn] = r.frame.en(r.compound.u, r.compound.v), d = Math.hypot(r.grid.e - ce, r.grid.n - cn);
rows.push(['Grid', `compound ${km(d)} from the nearest ${r.grid.kv ? r.grid.kv + ' kV ' : ''}substation (straight line; the connection is not drawn)`]);
}
if (r.waterLines) rows.push(['Water', `${r.waterLines} mapped watercourses; tables kept ${r.params.waterSetbackM} m from them`]);
if (state.pack) { const k = packSize(state.pack);
rows.push(['Drawn by distance', `${k.tables.toLocaleString('en-GB')} tables packed at ${k.bytesPerTable} B each (${formatNumber(k.tableBytes / 1024, 0)} KB), `
+ `${k.blocks} blocks, ${k.cells} cells of 250 m: outline, blocks, runs, tables, then modules within 80 m`]); }
rows.push(['Worked out in', r.seconds < 0.1 ? 'under 0.1 s' : `${formatNumber(r.seconds, 1)} s`], ...r.notes.map((n, i) => [i ? '' : 'Notes', n]));
state.rows = rows;
$('plant-readout').replaceChildren(...rows.flatMap(([k, v]) => { const dt = doc.createElement('dt'), dd = doc.createElement('dd'); dt.textContent = k; dd.textContent = v; return [dt, dd]; }));
state.summary = { asked: r.asked, built: r.built, fits: r.fits, skipped: sk, seconds: r.seconds, longestSliceMs: r.longestSliceMs, slowestStep: r.slowestStep,
trenchM: e?.trenchM ?? 0, trenchByType: e?.trenchByType ?? {}, cableM: e?.cableM ?? 0, cableBySize: e?.cableBySize ?? {},
worstDropPct: e?.worstDropPct ?? null, notes: r.notes, label: LABEL, piles: pileSnapshot(r.piles) };
say(`${LABEL} ${r.fits ? 'Laid out.' : r.notes[0]}`, !r.fits);
}
function clearLayout(all = true) {
state.result = null; state.draw = null; state.summary = null; state.version++;
state.lod?.dispose(); state.lod = null; state.pack = null;
if (all) state.boundary = null;
$('plant-readout').replaceChildren(); redraw();
}
$('plant-open').addEventListener('click', () => useOpenLand());
$('plant-run').addEventListener('click', () => run());
$('plant-clear').addEventListener('click', () => { clearLayout(true); say('Layout cleared.'); });
say(LABEL);
return { setBoundary, useOpenLand, run, batches, clear: clearLayout, pilesAuto, boqItems, result: () => state.result, boundary: () => state.boundary,
version: () => state.version,
// The plant's diagonal (m) for the far fade, the pack's figures and the drawer's levels (plant-pack.mjs, plant-lod.mjs).
extentM: () => { const b = state.result && state.boundary; if (!b) return 0;
const es = b.map(q => q[0]), ns = b.map(q => q[1]); return Math.hypot(Math.max(...es) - Math.min(...es), Math.max(...ns) - Math.min(...ns)); },
pack: () => (state.pack ? packSize(state.pack) : null), lod: () => state.lod?.stats() ?? null,
// The camera that frames the whole plant (block null) or block n (from 1), as flyTo options at national-grid (e, n)
// (nav-flight.mjs: 45 degrees down for the plant, 50 for a block). Null without a packed plant or for no such block.
frame: (block = null) => { const p = state.pack, pts = p && (block == null ? p.fence : p.blocks[block - 1]?.rect); if (!pts) return null;
const v = (block == null ? plantView : blockView)(boxOfPoints(pts));
return { e: p.origin[0] + v.x, n: p.origin[1] + v.y, yaw: v.yaw, pitch: v.pitch, back: v.back, block, blocks: p.blocks.length }; },
snapshot: () => (state.summary ? JSON.parse(JSON.stringify(state.summary)) : { boundary: state.boundary ? state.boundary.length : 0, running: state.running }) };
}Procedural Detail
A JavaScript module in the world folder of GlobalGrid2050 that generates table (`generateTable`) and converts to local float32 (`toLocalFloat32`).
transformglobalgrid2050 / solar-design-studio/202609271853-site-world/world/procedural-detail.mjs · lines 1–114 of 114 · version 2026-09-27 18:53 · Not reached from any entry point (candidate for review) · pattern stringsPerTable (shared by 4 files)
- What it does
- It calculates its inputs. Defines 15 functions or classes, including plantRecord, groupsPerRow, stringsPerTable, modulesPerTable, pilesPerTable.
- 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: Keyset (globalgrid2050).
- What it achieves
- It generates table (`generateTable`) and is built from the plant record helper (`plantRecord`) and the groups per row helper (`groupsPerRow`). Procedural table detail: every module corner, string and pile of one table generated from its key.
- Why it matters
- Imported by Keyset.
- Application
- globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
- Uses
- Procedural Key (import)
- Used by
- imported by Keyset (import)
- Produces
- Q, MAGIC, RULES_VERSION, HEADER, TABLE_DEFAULTS, plantRecord, groupsPerRow, stringsPerTable, modulesPerTable, pilesPerTable, tableInts, tableBytes
- Defines here
- plantRecord, groupsPerRow, stringsPerTable, modulesPerTable, pilesPerTable, tableInts, tableBytes, fl, moduleAddress, place, generateTable, moduleCorners, pile, stringModules, toLocalFloat32
- 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/procedural-detail.mjs:1-114 · blob 7e23f1888add88ac178d292e9c1e52d677c4153f · 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: unreached_review
// Procedural table detail: every module corner, string and pile of one table generated from its key.
//
// Rule: trig is evaluated ONCE per plant (plantRecord) and carried as Q16 integers; per-detail maths is
// integer only (+ - x and floor division, exact in float64 below 2^53), so the JS page, CuPy and NumPy
// produce the same Int32 millimetre buffer bit for bit. No Math.random; randomness only where the rules
// are silent (pile embed), drawn from mulberry32(fnv1a("<seed>|<table key>|piles")).
//
// Table rules default to the owner's station table (station.mjs STATION_DEFAULTS: 5 rows x 90 columns a
// face, two faces, 1.303 x 2.384 m modules, 0.02 m gap, 10 deg, 30 modules a string, 0.5 m ridge gap,
// 1.2 m lowest edge, 0.9 m underside). Pile embed and its +-0.2 m spread are ILLUSTRATIVE, not designed.
// Illustrative - early design, no warranty; confirm with a qualified engineer.
import { tableKey, detailSeed, mulberry32, intIn, mm } from './procedural-key.mjs';
export const Q = 65536; // Q16 fixed point for the plant's trig constants
export const MAGIC = 0x31304450; // "PD01" little-endian
export const RULES_VERSION = 1;
export const HEADER = 8; // magic, rules version, modules, piles, anchor x/y/z, strings a table
export const TABLE_DEFAULTS = Object.freeze({
rows: 5, columns: 90, moduleWidth: 1.303, moduleLength: 2.384, moduleGap: 0.02, tilt: 10,
ridgeGap: 0.5, height: 1.2, underside: 0.9, modulesPerString: 30,
pileLines: 19, pileEmbed: 1.6, pileSpread: 0.2
});
// The plant record: all floats become integers here, once. headingDeg is compass (0 = table +y north).
export function plantRecord({ seed = 20260927, headingDeg = 0, table = {} } = {}) {
const t = { ...TABLE_DEFAULTS, ...table }, R = Math.PI / 180;
const L = mm(t.moduleLength), W = mm(t.moduleWidth), G = mm(t.moduleGap);
const cosT = Math.round(Math.cos(t.tilt * R) * Q), sinT = Math.round(Math.sin(t.tilt * R) * Q);
const run = t.rows * (L + G) - G;
const rec = {
seed: seed >>> 0, rulesVersion: RULES_VERSION,
rows: t.rows, columns: t.columns, L, W, G, halfGap: Math.floor(mm(t.ridgeGap) / 2),
height: mm(t.height), underside: mm(t.underside), mps: t.modulesPerString,
cosT, sinT, cosH: Math.round(Math.cos(headingDeg * R) * Q), sinH: Math.round(Math.sin(headingDeg * R) * Q),
run, depth: Math.floor(run * cosT / Q), span: t.columns * (W + G) - G,
pileLines: t.pileLines, pileEmbed: mm(t.pileEmbed), pileSpread: mm(t.pileSpread)
};
for (const [k, v] of Object.entries(rec)) if (!Number.isSafeInteger(v)) throw new RangeError(`plant record ${k} is not an integer: ${v}`);
if (rec.rows < 1 || rec.columns < 1 || rec.mps < 1 || rec.pileLines < 2) throw new RangeError('plant record: rows, columns, modules a string >= 1, pile lines >= 2');
return Object.freeze(rec);
}
export const groupsPerRow = p => Math.ceil(p.columns / p.mps);
export const stringsPerTable = p => 2 * p.rows * groupsPerRow(p);
export const modulesPerTable = p => 2 * p.rows * p.columns;
export const pilesPerTable = p => 2 * p.pileLines;
export const tableInts = p => HEADER + modulesPerTable(p) * 12 + pilesPerTable(p) * 4;
export const tableBytes = p => tableInts(p) * 4;
const fl = (a, b) => Math.floor(a / b); // exact: |a| < 2^53, b = 2^16 or a small integer
// Module n of a table (build order: face -1 then +1, row 0..rows-1, column 0..columns-1) and its string.
export function moduleAddress(p, n) {
const perFace = p.rows * p.columns, face = n < perFace ? 0 : 1, rest = n - face * perFace;
const row = fl(rest, p.columns), column = rest - row * p.columns, g = groupsPerRow(p);
return { face, side: face ? 1 : -1, row, column, string: (face * p.rows + row) * g + fl(column, p.mps), inString: column % p.mps };
}
// Rotate a local (x across, y along) mm vector by the plant heading and add the anchor.
const place = (p, ax, ay, lx, ly) => [ax + fl(lx * p.cosH + ly * p.sinH, Q), ay + fl(ly * p.cosH - lx * p.sinH, Q)];
// The detail of one table as an Int32Array in millimetres, plant-relative.
// anchor: [x, y, z] integer mm of the table's ridge-centre foot (from the plant layout, quantised once).
export function generateTable(p, addr, anchor) {
const key = tableKey(addr), seed = detailSeed(p.seed, key, 'piles');
const [ax, ay, az] = anchor.map(v => { if (!Number.isSafeInteger(v) || Math.abs(v) > 2e9) throw new RangeError(`anchor must be integer mm, got ${v}`); return v; });
const nM = modulesPerTable(p), nP = pilesPerTable(p), out = new Int32Array(tableInts(p));
out[0] = MAGIC; out[1] = p.rulesVersion; out[2] = nM; out[3] = nP; out[4] = ax; out[5] = ay; out[6] = az; out[7] = stringsPerTable(p);
const dvs = [0, p.L, p.L, 0], dus = [0, 0, p.W, p.W];
let o = HEADER;
for (let side = -1; side <= 1; side += 2) for (let r = 0; r < p.rows; r++) {
const rr = side === 1 ? p.rows - 1 - r : r, v0 = rr * (p.L + p.G);
for (let c = 0; c < p.columns; c++) {
const u0 = c * (p.W + p.G);
for (let k = 0; k < 4; k++) {
const vv = v0 + dvs[k];
const lx = side * (p.halfGap + p.depth - fl(vv * p.cosT, Q)), ly = u0 + dus[k];
const [x, y] = place(p, ax, ay, lx, ly);
out[o++] = x; out[o++] = y; out[o++] = az + p.height + fl(vv * p.sinT, Q);
}
}
}
const next = mulberry32(seed), px = p.halfGap + fl(p.depth, 2);
for (let line = 0; line < p.pileLines; line++) {
const ly = fl(line * p.span, p.pileLines - 1);
for (let side = -1; side <= 1; side += 2) {
const [x, y] = place(p, ax, ay, side * px, ly);
out[o++] = x; out[o++] = y; out[o++] = az + p.underside;
out[o++] = intIn(next(), p.pileEmbed - p.pileSpread, p.pileEmbed + p.pileSpread);
}
}
return { key, seed, buf: out, bytes: out.byteLength };
}
// Read-back helpers for the renderer and the pickers (views, no copies).
export const moduleCorners = (p, buf, n) => buf.subarray(HEADER + n * 12, HEADER + n * 12 + 12);
export function pile(p, buf, n) { const s = HEADER + modulesPerTable(p) * 12 + n * 4; return buf.subarray(s, s + 4); }
export function stringModules(p, s) {
const g = groupsPerRow(p), faceRow = fl(s, g), group = s - faceRow * g, face = fl(faceRow, p.rows), row = faceRow - face * p.rows;
const rowStart = face * p.rows * p.columns + row * p.columns, first = rowStart + group * p.mps;
return { face, row, group, first, count: Math.min(first + p.mps, rowStart + p.columns) - first };
}
// Float32 positions relative to the table anchor, in metres, for a GPU buffer (the camera stays float64).
export function toLocalFloat32(buf) {
const nM = buf[2], out = new Float32Array(nM * 12), ax = buf[4], ay = buf[5], az = buf[6];
for (let i = 0; i < nM * 4; i++) {
const s = HEADER + i * 3;
out[i * 3] = (buf[s] - ax) / 1000; out[i * 3 + 1] = (buf[s + 1] - ay) / 1000; out[i * 3 + 2] = (buf[s + 2] - az) / 1000;
}
return out;
}Procedural Key
A JavaScript module in the world folder of GlobalGrid2050 that works with fnv1a bytes (`fnv1aBytes`) and fnv1a int32 (`fnv1aInt32`).
ingestglobalgrid2050 / solar-design-studio/202609271853-site-world/world/procedural-key.mjs · lines 1–82 of 82 · version 2026-09-27 18:53 · Not reached from any entry point (candidate for review) · pattern stringKey (shared by 2 files)
- What it does
- Defines 14 functions or classes, including fnv1a, fnv1aBytes, fnv1aInt32, mulberry32, unit.
- 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: Procedural Detail (globalgrid2050).
- What it achieves
- It parses key (`parseKey`) and is built from the fnv1a step (`fnv1a`) and the fnv1a bytes helper (`fnv1aBytes`). Stable keys and the seeded draw for procedural detail (Kuiper style: computed on arrival, never stored).
- Why it matters
- Imported by Procedural Detail.
- Application
- globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
- Uses
- none found
- Used by
- imported by Procedural Detail (import)
- Produces
- fnv1a, fnv1aBytes, fnv1aInt32, mulberry32, unit, intIn, rowKey, tableKey, stringKey, moduleKey, parseKey, detailSeed
- Defines here
- fnv1a, fnv1aBytes, fnv1aInt32, mulberry32, unit, intIn, int, rowKey, tableKey, stringKey, moduleKey, parseKey, detailSeed, mm
- 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/procedural-key.mjs:1-82 · blob de5258f1b47e5c2ee7e42e001e9dc50cf0a1d7af · 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: unreached_review
// Stable keys and the seeded draw for procedural detail (Kuiper style: computed on arrival, never stored).
//
// Identity is geometric: a table is addressed by the layout's own sort tuple (track k, side s, run j,
// row r, index i; plant-layout.mjs sorts candidates by acc.k, acc.s, acc.j, acc.r, acc.i), so a key
// survives a capacity change. Hierarchy: R:k.s.j.r -> T:k.s.j.r.i -> S:<table>/n -> M:<table>/n.m
//
// The seeded draw is FNV-1a (32-bit, over the UTF-8 bytes of "<seed>|<key>|<kind>") into mulberry32.
// Everything here is integer arithmetic on uint32; no Math.random, no floats are hashed. The same
// arithmetic is re-derived in CuPy by pair_procedural_gpu.py and must hash-match.
// Pure functions, no globals, no DOM.
const FNV_OFFSET = 0x811c9dc5, FNV_PRIME = 0x01000193;
// FNV-1a over a string's UTF-8 bytes (keys are ASCII; non-ASCII is encoded, not truncated).
export function fnv1a(str, h = FNV_OFFSET) {
const bytes = new TextEncoder().encode(String(str));
return fnv1aBytes(bytes, h);
}
export function fnv1aBytes(bytes, h = FNV_OFFSET) {
h >>>= 0;
for (let i = 0; i < bytes.length; i++) { h ^= bytes[i]; h = Math.imul(h, FNV_PRIME) >>> 0; }
return h >>> 0;
}
// FNV-1a over an Int32Array's bytes, little-endian whatever the host order is.
export function fnv1aInt32(arr, h = FNV_OFFSET) {
h >>>= 0;
for (let i = 0; i < arr.length; i++) {
const v = arr[i] >>> 0;
for (let b = 0; b < 32; b += 8) { h ^= (v >>> b) & 0xff; h = Math.imul(h, FNV_PRIME) >>> 0; }
}
return h >>> 0;
}
// mulberry32 as a stream of uint32 draws (the float form is draw / 2^32; integer users take the u32).
export function mulberry32(seed) {
let a = seed >>> 0;
return function next() {
a = (a + 0x6d2b79f5) >>> 0;
let t = Math.imul(a ^ (a >>> 15), 1 | a);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return (t ^ (t >>> 14)) >>> 0;
};
}
export const unit = u32 => u32 / 4294967296;
// Seeded integer in [lo, hi] from a u32 (modulo bias < 1e-6 for ranges under 4,000; stated, not hidden).
export const intIn = (u32, lo, hi) => lo + (u32 % (hi - lo + 1));
// ---- keys ---------------------------------------------------------------------------------------
const int = (v, name) => {
if (!Number.isInteger(v) || v < 0 || v > 0xffff) throw new RangeError(`address ${name} must be an integer 0..65535, got ${v}`);
return v;
};
export function rowKey({ k, s, j, r }) { return `R:${int(k, 'k')}.${int(s, 's')}.${int(j, 'j')}.${int(r, 'r')}`; }
export function tableKey(a) { return `T:${int(a.k, 'k')}.${int(a.s, 's')}.${int(a.j, 'j')}.${int(a.r, 'r')}.${int(a.i, 'i')}`; }
export const stringKey = (tKey, n) => `S:${tKey.slice(2)}/${n}`;
export const moduleKey = (tKey, n, m) => `M:${tKey.slice(2)}/${n}.${m}`;
export function parseKey(key) {
const m = /^([RTSM]):(\d+)\.(\d+)\.(\d+)\.(\d+)(?:\.(\d+))?(?:\/(\d+)(?:\.(\d+))?)?$/.exec(String(key));
if (!m) return null;
const [, level, k, s, j, r, i, n, mod] = m;
const out = { level, k: +k, s: +s, j: +j, r: +r };
if (i !== undefined) out.i = +i;
if (n !== undefined) out.string = +n;
if (mod !== undefined) out.module = +mod;
if ((level === 'R') !== (i === undefined)) return null;
if ((level === 'S' || level === 'M') !== (n !== undefined)) return null;
if ((level === 'M') !== (mod !== undefined)) return null;
return out;
}
// The seed of one piece of detail: u32 of "<plantSeed>|<key>|<kind>".
export const detailSeed = (plantSeed, key, kind = 'detail') => fnv1a(`${plantSeed >>> 0}|${key}|${kind}`);
// Quantise metres to integer millimetres (round half away from zero; the only float step, done once
// on the plant record, never per detail).
export const mm = metres => { const v = metres * 1000; return v < 0 ? -Math.round(-v) : Math.round(v); };Senses Mount
A JavaScript module in the world folder of GlobalGrid2050 that calculates planar distances and draws SVG graphics.
interactionglobalgrid2050 / solar-design-studio/202609271853-site-world/world/senses-mount.mjs · lines 1–84 of 84 · version 2026-09-27 18:53 · Not reached from any entry point (candidate for review) · pattern typing (shared by 7 files)
- What it does
- It draws its content. Defines 10 functions or classes, including typing, mountSenses, walking, go, jump. 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: SVG drawing.
- What it achieves
- It is built from the typing step (`typing`), the mount senses helper (`mountSenses`) and the walking step (`walking`). The jump (Space in Walk) and the binoculars switch (B), mounted just after the first frame. It responds to keydown, keyup and blur 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
- Jump (import), Binoculars Mount (dynamic import)
- Used by
- none found
- Produces
- mountSenses
- Defines here
- typing, mountSenses, walking, go, jump, land, load, mark, set, toggle
- 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/senses-mount.mjs:1-84 · blob 9e2e87cf1a1daa802488df5c5568d8e21cdfbdfb · 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
// senses-mount.mjs: the jump (Space in Walk) and the binoculars switch (B), mounted just after the first frame.
// The jump (jump.mjs) is small and loads with this; the binoculars (binoculars-mount.mjs and binoculars-lens.mjs) load
// the first time they are switched on: the B key, the icon in the corner of the view (mouse screens), the Binoculars
// button under Controls (every screen; on a phone the dash keeps its five buttons), or the command line.
// Phones jump with a double tap on the centre of the move pad. Nothing here draws unless something moves.
import { createJump } from './jump.mjs';
const typing = t => t instanceof HTMLInputElement || t instanceof HTMLTextAreaElement || t instanceof HTMLSelectElement || !!t?.isContentEditable;
const GLYPH = '<svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.6">'
+ '<circle cx="6.5" cy="15" r="4"/><circle cx="17.5" cy="15" r="4"/><path d="M10.5 15h3M4 11l2-6h3l1 6M20 11l-2-6h-3l-1 6"/></svg>';
const CSS = `
#bino-corner { position: fixed; right: 10px; top: calc(50% + 64px); width: 30px; /* under the drone's Up and Down, clear of the sun bar */
height: 30px; padding: 0; display: grid;
place-items: center; background: var(--panel); color: var(--dim); border: 1px solid var(--edge); border-radius: 4px; cursor: pointer; }
#bino-corner[aria-pressed="true"] { color: #fff; border-color: var(--line); }
@media (pointer: coarse) { #bino-corner { display: none; } }
body[data-panel] #bino-corner { display: none; }`;
const PAD_TAP_MS = 350, PAD_CENTRE_PX = 20;
// deps: { api (the substrate's extension api), world (window.world), doc }
export function mountSenses({ api, world, doc = document }) {
const legs = createJump();
api.setLegs(legs);
const walking = () => api.state().view === 'standing';
const go = () => { api.resumeGate(); api.gate.invalidate(); };
// When a jump comes to rest (landed, the eye settled) the loop goes back to still: 0 fps.
let was = false;
api.hooks.after.add(() => { const b = legs.busy(); if (was && !b) api.resumeGate(); was = b; });
const jump = () => { if (!walking()) return false; legs.press(); go(); return true; };
const land = () => legs.release();
addEventListener('keydown', e => {
if (e.code !== 'Space' || e.repeat || e.ctrlKey || e.metaKey || e.altKey) return;
if (typing(e.target) || e.target instanceof HTMLButtonElement) return;
jump(); // in Drone, input.mjs already climbs on Space
});
addEventListener('keyup', e => { if (e.code === 'Space') land(); });
addEventListener('blur', land);
// Phones: a double tap on the centre of the move pad; holding the second tap jumps a little higher.
const pad = doc.getElementById('pad');
let lastTap = -Infinity;
pad?.addEventListener('pointerdown', e => {
const r = pad.getBoundingClientRect(), off = Math.hypot(e.clientX - (r.left + r.width / 2), e.clientY - (r.top + r.height / 2));
if (off > PAD_CENTRE_PX) { lastTap = -Infinity; return; }
if (e.timeStamp - lastTap <= PAD_TAP_MS) { lastTap = -Infinity; jump(); } else lastTap = e.timeStamp;
});
for (const ev of ['pointerup', 'pointercancel']) pad?.addEventListener(ev, land);
// ---- binoculars ----
let bino = null, loading = null;
const load = () => (loading ||= import('./binoculars-mount.mjs')
.then(m => (bino = m.createBinoculars({ api, world, doc, onChange: mark })))
.catch(e => { loading = null; console.warn('binoculars: ' + e.message); throw e; }));
const style = doc.createElement('style'); style.textContent = CSS; doc.head.appendChild(style);
const corner = doc.createElement('button');
corner.type = 'button'; corner.id = 'bino-corner'; corner.innerHTML = GLYPH;
corner.title = 'Binoculars (B): 7× and 10×, with a rangefinder'; corner.setAttribute('aria-label', 'Binoculars'); corner.setAttribute('aria-pressed', 'false');
doc.body.appendChild(corner);
const inControls = doc.createElement('button');
inControls.type = 'button'; inControls.id = 'bino-controls'; inControls.textContent = 'Binoculars'; inControls.setAttribute('aria-pressed', 'false');
inControls.title = 'Narrow view at 7× or 10× (wheel or pinch to step), with a rangefinder in the middle';
doc.getElementById('help-links')?.append(inControls);
function mark() { const on = String(!!bino?.on()); corner.setAttribute('aria-pressed', on); inControls.setAttribute('aria-pressed', on); }
const set = async on => { if (!on && !bino) return false; const b = bino || await load(); b.set(on); mark(); return b.on(); };
const toggle = () => set(!bino?.on()).catch(() => {});
corner.addEventListener('click', () => { toggle(); (doc.getElementById('view') || doc.body).focus?.(); });
inControls.addEventListener('click', () => { toggle(); });
addEventListener('keydown', e => {
if (e.code !== 'KeyB' || e.repeat || e.ctrlKey || e.metaKey || e.altKey || typing(e.target)) return;
e.preventDefault(); toggle();
});
// The command line's hook (cmd-run.mjs): binoculars on|off, zoom 7|10, range.
api.senses = {
async binoculars({ on, zoom, range }) {
if (range) return bino?.on() ? bino.rangeText() : (bino?.lastText() || 'Binoculars are off: type binoculars on, then range.');
if (zoom) { await set(true); bino.zoom(zoom); return `Binoculars at ${bino.mag()}×. ${bino.rangeText()}`; }
const now = await set(on);
return now ? `Binoculars on at ${bino.mag()}× (B or the corner icon to put them down). ${bino.rangeText()}` : 'Binoculars off.';
}
};
return { legs, binoculars: () => bino, set, jump, land, debug: () => ({ jump: legs.debug(), binoculars: bino?.debug() ?? null }) };
}Site Checks
A JavaScript module in the world folder of GlobalGrid2050 that works with solar.
transformglobalgrid2050 / solar-design-studio/202609271853-site-world/world/site-checks.mjs · lines 1–48 of 48 · version 2026-09-27 18:53 · pattern sourceConflict (shared by 3 files)
- What it does
- It calculates solar. Defines dayOf, surveyCheck, surveyNote, sourceConflict.
- 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: solar.
- Downstream impact
- Used directly by 1 file: Plant Layout (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
- It is built from the day of helper (`dayOf`), the survey check helper (`surveyCheck`) and the survey note helper (`surveyNote`). A date field as a sortable day number (ms since 1970); '2020', '2020-11' and '' are all read.
- Why it matters
- Imported by Plant Layout.
- Application
- globalgrid2050 · solar-design-studio/202609271853-site-world/world · JavaScript module
- Uses
- none found
- Used by
- imported by Plant Layout (import)
- Produces
- dayOf, surveyCheck, surveyNote, sourceConflict
- Defines here
- dayOf, surveyCheck, surveyNote, sourceConflict
- 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/site-checks.mjs:1-48 · blob cba873b022cda27172f65ddae61250e7e84734c6 · 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
// site-checks.mjs: two honesty checks on the data a plant is drawn from, raised as notes, never as refusals.
//
// SURVEY DATE A ground survey (LiDAR) flown before a plant was planned or built shows the land, not the plant: its
// surface has no rows, so it can never confirm what the layout draws. An open-data study of large operational UK
// solar farms found this at most of them (the public 1 m survey predated the build). When the site's data gives the
// survey date and a planning or commissioning date, a survey older than either is said: "Ground survey predates
// this layout". Dates come from a data field (a site record or the terrain index); none given, nothing is said.
// CONFLICTING SOURCES Two open sources that give one quantity (a capacity, a place) differently, beyond a tolerance,
// are flagged with both values and the size of the gap, not settled by picking one.
// Pure: no DOM, no imports.
/** A date field as a sortable day number (ms since 1970); '2020', '2020-11' and '2020-11-05' are all read. */
export function dayOf(v) {
if (v == null || v === '') return null;
if (v instanceof Date) return Number.isFinite(v.getTime()) ? v.getTime() : null;
const m = /^(\d{4})(?:-(\d{1,2}))?(?:-(\d{1,2}))?/.exec(String(v).trim());
return m ? Date.UTC(Number(m[1]), (Number(m[2]) || 1) - 1, Number(m[3]) || 1) : null;
}
/**
* surveyCheck({ groundDate, planningDate, commissionedDate }) -> { checked, predates, against, line }
* checked is false when the survey date or both plant dates are missing.
*/
export function surveyCheck(s = {}) {
const g = dayOf(s.groundDate), plan = dayOf(s.planningDate), built = dayOf(s.commissionedDate);
if (g == null || (plan == null && built == null)) return { checked: false, predates: false, against: null, line: '' };
const later = [['planning', plan, s.planningDate], ['commissioning', built, s.commissionedDate]].filter(([, d]) => d != null && g < d);
if (!later.length) return { checked: true, predates: false, against: null, line: `Ground survey ${s.groundDate} is after the plant's dates: it can show what was built.` };
const [what, , when] = later.at(-1);
return { checked: true, predates: true, against: what,
line: `Ground survey predates this layout: flown ${s.groundDate}, before ${what} (${when}). The survey shows the land, not a plant; `
+ 'rows drawn here are illustrative and no plant in the survey confirms them.' };
}
/** The note a layout carries for its survey, or '' (no dates, or a survey after the plant). */
export const surveyNote = s => { const c = surveyCheck(s || {}); return c.predates ? c.line : ''; };
/**
* sourceConflict([{ source, value }], { tolerance = 0.1, unit = '' }) -> null | { values, spread, line }
* spread: (largest - smallest) / smallest. Flagged over the tolerance; both ends named by their generic source label.
*/
export function sourceConflict(values = [], { tolerance = 0.1, unit = '' } = {}) {
const v = values.filter(x => Number.isFinite(x?.value) && x.value > 0);
if (v.length < 2) return null;
const lo = v.reduce((a, b) => (b.value < a.value ? b : a)), hi = v.reduce((a, b) => (b.value > a.value ? b : a)), spread = (hi.value - lo.value) / lo.value;
if (spread <= tolerance + 1e-12) return null;
return { values: v, spread, line: `Sources disagree: ${hi.source} gives ${hi.value}${unit ? ' ' + unit : ''}, ${lo.source} gives ${lo.value}${unit ? ' ' + unit : ''} `
+ `(${Math.round(spread * 100)} % apart). Both are kept; neither is picked.` };
}