In this section
- Offset transform · globalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/offset.mjs lines 1–224
- Origin transform · globalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/origin.mjs lines 1–31
- Phases Slider render · globalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/phases-slider.mjs lines 1–46
- Phases render · globalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/phases.mjs lines 1–213
- Pick transform · globalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/pick.mjs lines 1–52
Offset
A JavaScript module in the world folder of GlobalGrid2050 that cleans path (`cleanPath`), makes grid (`makeGrid`) and calculates planar distances. It cleans path (`cleanPath`) and makes grid (`makeGrid`).
transformglobalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/offset.mjs · lines 1–224 of 224 · version 2026-09-27 00:05 · pattern ringArea (shared by 2 files)
- What it does
- It calculates its inputs. Defines 18 functions or classes, including cross, isPt, ringArea, pointInRing, cleanPath.
- 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 3 files: Clash (globalgrid2050); Buffers (globalgrid2050); Overhead Line (OHL) Zones (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
- Offsetting of points, polylines and polygons: the zone of all ground within d metres of a feature.
- Why it matters
- Imported by Clash, Buffers and Overhead Line (OHL) Zones.
- Application
- globalgrid2050 · solar-design-studio/202609270005-site-world-v3/world · JavaScript module
- Uses
- none found
- Used by
- imported by Clash (import), imported by Buffers (import), imported by Overhead Line (OHL) Zones (import), mentioned in Standalone (comment link)
- Produces
- ARC_SEGMENTS, ANGLE_PHASE, ringArea, pointInRing, cleanPath, pieces, unionRings, offset, offsetUnion
- Defines here
- cross, isPt, ringArea, pointInRing, cleanPath, piece, disc, rect, pieces, locate, makeGrid, range, segHit, unionRings, k, chain, offset, offsetUnion
- 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/202609270005-site-world-v3/world/offset.mjs:1-224 · blob a18058128f27a72362cf01e05d2438e2bff97dc5 · 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
// Offsetting of points, polylines and polygons: the zone of all ground within d metres of a feature.
// Pure: no imports, no DOM. Coordinates are local metres (x east, y north); any consistent plane works.
//
// Method: the zone is the union of convex pieces, one disc at every vertex and one rectangle along every
// segment (plus the polygon itself for an area). Every piece edge is split where it crosses an edge of another
// piece; a split piece is kept when its midpoint lies strictly inside no other piece. The kept pieces are then
// chained into rings. This never forms an offset by moving edges and mitring corners, so concave corners,
// notches narrower than 2d, hairpins, self-crossing lines and holes all come out right with no special cases.
//
// Discs are regular polygons circumscribed about the true circle (every edge touches it), so the drawn zone
// always contains the exact zone and is at most d * (1 / cos(pi / segments) - 1) larger: 0.48 % of d at 32.
// The arc vertices sit on one grid of angles rotated by ANGLE_PHASE, so two discs never share an edge by
// chance and square, axis-aligned input never lines up with an arc edge. Rings: outer anticlockwise, holes clockwise.
export const ARC_SEGMENTS = 32;
export const ANGLE_PHASE = 0.1234567;
const EPS = 1e-9;
const cross = (ax, ay, bx, by) => ax * by - ay * bx;
const isPt = p => Array.isArray(p) && Number.isFinite(p[0]) && Number.isFinite(p[1]);
// Pure: signed area of a ring (anticlockwise positive). The ring is not closed by repeating its first point.
export function ringArea(ring) {
let s = 0;
for (let i = 0, n = ring.length; i < n; i++) { const a = ring[i], b = ring[(i + 1) % n]; s += a[0] * b[1] - b[0] * a[1]; }
return s / 2;
}
// Pure: even-odd point in ring.
export function pointInRing(ring, x, y) {
let inside = false;
for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
const [xi, yi] = ring[i], [xj, yj] = ring[j];
if ((yi > y) !== (yj > y) && x < (xj - xi) * (y - yi) / (yj - yi) + xi) inside = !inside;
}
return inside;
}
// Pure: drops non-finite and repeated points and straight-through middle points. A closed ring loses a repeated
// closing point. A doubling-back point (a spike) is kept: it is a real turn.
export function cleanPath(pts, closed = false) {
let p = (Array.isArray(pts) ? pts : []).filter(isPt).map(q => [+q[0], +q[1]]);
p = p.filter((q, i) => i === 0 || Math.hypot(q[0] - p[i - 1][0], q[1] - p[i - 1][1]) > EPS);
if (closed && p.length > 1 && Math.hypot(p[0][0] - p[p.length - 1][0], p[0][1] - p[p.length - 1][1]) <= EPS) p.pop();
let changed = true;
while (changed && p.length > 2) {
changed = false;
const n = p.length;
for (let i = closed ? 0 : 1; i < (closed ? n : n - 1); i++) {
const a = p[(i - 1 + n) % n], b = p[i], c = p[(i + 1) % n];
const ux = b[0] - a[0], uy = b[1] - a[1], vx = c[0] - b[0], vy = c[1] - b[1];
const lu = Math.hypot(ux, uy), lv = Math.hypot(vx, vy);
if (Math.abs(cross(ux, uy, vx, vy)) <= EPS * lu * lv && ux * vx + uy * vy > 0) { p.splice(i, 1); changed = true; break; }
}
}
return p;
}
// Convex anticlockwise piece: { pts, box, id }. Region: a non-convex area polygon, tested even-odd.
function piece(pts, id) {
const xs = pts.map(p => p[0]), ys = pts.map(p => p[1]);
return { pts, id, box: [Math.min(...xs), Math.min(...ys), Math.max(...xs), Math.max(...ys)] };
}
function disc(c, d, n) {
const R = d / Math.cos(Math.PI / n), out = [];
for (let k = 0; k < n; k++) { const a = ANGLE_PHASE + (2 * Math.PI * k) / n; out.push([c[0] + R * Math.cos(a), c[1] + R * Math.sin(a)]); }
return out;
}
function rect(a, b, d) {
const L = Math.hypot(b[0] - a[0], b[1] - a[1]), nx = -(b[1] - a[1]) / L * d, ny = (b[0] - a[0]) / L * d;
return [[a[0] - nx, a[1] - ny], [b[0] - nx, b[1] - ny], [b[0] + nx, b[1] + ny], [a[0] + nx, a[1] + ny]];
}
// Pure: the convex pieces and area regions whose union is the zone of the given parts.
// part: { pts, closed?: bool, area?: bool, d } (area implies closed; a single point is a disc).
export function pieces(parts, { segments = ARC_SEGMENTS } = {}) {
const out = [], areas = [];
for (const part of parts) {
const d = +part.d, closed = !!(part.closed || part.area);
if (!(d > 0)) continue;
const p = cleanPath(part.pts, closed);
if (!p.length) continue;
for (const v of p) out.push(piece(disc(v, d, segments), out.length));
const m = closed && p.length > 2 ? p.length : p.length - 1;
for (let i = 0; i < m; i++) out.push(piece(rect(p[i], p[(i + 1) % p.length], d), out.length));
if (part.area && p.length > 2) areas.push(ringArea(p) >= 0 ? p : p.slice().reverse());
}
return { pieces: out, areas };
}
// Where is (x, y) against a convex anticlockwise piece? 1 strictly inside, 0 outside, or the edge it lies on.
function locate(pc, x, y) {
const P = pc.pts, n = P.length;
if (x < pc.box[0] - EPS || x > pc.box[2] + EPS || y < pc.box[1] - EPS || y > pc.box[3] + EPS) return 0;
let on = null;
for (let i = 0; i < n; i++) {
const a = P[i], b = P[(i + 1) % n], L = Math.hypot(b[0] - a[0], b[1] - a[1]);
const sd = cross(b[0] - a[0], b[1] - a[1], x - a[0], y - a[1]) / L;
if (sd < -EPS) return 0;
if (sd <= EPS) on = [(b[0] - a[0]) / L, (b[1] - a[1]) / L];
}
return on || 1;
}
// A uniform grid over boxes, so each lookup meets only nearby edges and pieces.
function makeGrid(h) {
const cells = new Map(), key = (i, j) => i * 1e6 + j;
const range = (lo, hi) => [Math.floor(lo / h), Math.floor(hi / h)];
return {
h, cells,
add(box, v) {
const [i0, i1] = range(box[0], box[2]), [j0, j1] = range(box[1], box[3]);
for (let i = i0; i <= i1; i++) for (let j = j0; j <= j1; j++) {
const k = key(i, j); let c = cells.get(k); if (!c) cells.set(k, c = []); c.push(v);
}
},
at(x, y) { return cells.get(key(Math.floor(x / h), Math.floor(y / h))) || []; },
cellOf(x, y) { return key(Math.floor(x / h), Math.floor(y / h)); }
};
}
function segHit(e, f) {
const rx = e.b[0] - e.a[0], ry = e.b[1] - e.a[1], sx = f.b[0] - f.a[0], sy = f.b[1] - f.a[1];
const den = cross(rx, ry, sx, sy);
if (Math.abs(den) < EPS * Math.hypot(rx, ry) * Math.hypot(sx, sy)) return null; // parallel: no single crossing
const qx = f.a[0] - e.a[0], qy = f.a[1] - e.a[1], t = cross(qx, qy, sx, sy) / den, u = cross(qx, qy, rx, ry) / den;
if (t < -EPS || t > 1 + EPS || u < -EPS || u > 1 + EPS) return null;
return { t: Math.min(1, Math.max(0, t)), u: Math.min(1, Math.max(0, u)), p: [e.a[0] + rx * t, e.a[1] + ry * t] };
}
// Pure: the boundary of the union of convex pieces (and area regions), as rings. With inside (a ring), the
// result is instead that ring minus the union: an inward offset.
export function unionRings({ pieces: pcs, areas = [] }, { inside = null } = {}) {
if (!pcs.length) return [];
// Grid cell: the median piece size, so long rectangles span several cells but discs sit in one or two.
const sizes = pcs.map(pc => Math.max(pc.box[2] - pc.box[0], pc.box[3] - pc.box[1])).sort((a, b) => a - b);
const span = sizes[sizes.length >> 1];
const edges = [];
for (const pc of pcs) pc.pts.forEach((a, i) => {
const b = pc.pts[(i + 1) % pc.pts.length];
edges.push({ a, b, id: pc.id, cuts: [], box: [Math.min(a[0], b[0]), Math.min(a[1], b[1]), Math.max(a[0], b[0]), Math.max(a[1], b[1])] });
});
const eg = makeGrid(Math.max(span, 1e-6)), pg = makeGrid(Math.max(span, 1e-6));
edges.forEach((e, i) => eg.add(e.box, i));
pcs.forEach(pc => pg.add(pc.box, pc.id));
// Split every edge where it crosses an edge of another piece. Each crossing is recorded once: in the cell
// that holds the crossing point, which is the same point object on both edges.
for (const [cell, list] of eg.cells) {
for (let x = 0; x < list.length; x++) for (let y = x + 1; y < list.length; y++) {
const e = edges[list[x]], f = edges[list[y]];
if (e.id === f.id || e.box[0] > f.box[2] || f.box[0] > e.box[2] || e.box[1] > f.box[3] || f.box[1] > e.box[3]) continue;
const hit = segHit(e, f);
if (!hit || eg.cellOf(hit.p[0], hit.p[1]) !== cell) continue;
e.cuts.push([hit.t, hit.p]); f.cuts.push([hit.u, hit.p]);
}
}
const kept = [];
for (const e of edges) {
const cuts = e.cuts.sort((p, q) => p[0] - q[0]), pts = [e.a, ...cuts.map(c => c[1]), e.b];
const dx = e.b[0] - e.a[0], dy = e.b[1] - e.a[1], L = Math.hypot(dx, dy);
for (let i = 0; i < pts.length - 1; i++) {
const p = pts[i], q = pts[i + 1];
if (Math.hypot(q[0] - p[0], q[1] - p[1]) <= EPS) continue;
const mx = (p[0] + q[0]) / 2, my = (p[1] + q[1]) / 2;
let covered = areas.some(r => pointInRing(r, mx, my));
for (const id of covered ? [] : pg.at(mx, my)) {
if (id === e.id) continue;
const w = locate(pcs[id], mx, my);
// On another piece's edge: running the same way, the lower id keeps it; running the other way, the
// two pieces meet there and it is interior to the union.
if (w === 1 || (w && (w[0] * dx + w[1] * dy < 0 || id < e.id))) { covered = true; break; }
}
if (covered) continue;
if (inside) { if (pointInRing(inside, mx, my)) kept.push([q, p]); }
else kept.push([p, q]);
}
}
return chain(kept);
}
const k = p => p[0] + ',' + p[1];
// Pure: joins directed pieces [start, end] into closed rings. An open chain (a numerical dead end) is dropped.
function chain(segs) {
const from = new Map();
segs.forEach((s, i) => { const key = k(s[0]); if (!from.has(key)) from.set(key, []); from.get(key).push(i); });
const used = new Uint8Array(segs.length), rings = [];
for (let s = 0; s < segs.length; s++) {
if (used[s]) continue;
const ring = [], startKey = k(segs[s][0]);
let i = s, ok = false;
while (i !== undefined) {
used[i] = 1; ring.push(segs[i][0]);
const endKey = k(segs[i][1]);
if (endKey === startKey) { ok = true; break; }
i = (from.get(endKey) || []).find(j => !used[j]);
}
if (ok && ring.length >= 3) rings.push(cleanPath(ring, true));
}
return rings.filter(r => r.length >= 3 && Math.abs(ringArea(r)) > EPS);
}
// Pure: the zone within d of a polyline (closed: false), a closed outline (closed: true, the band either side)
// or an area (area: true, the polygon and all within d of it). A single point gives a disc.
// d < 0 with area: true shrinks the polygon instead (an inward setback). Returns { rings, area }.
export function offset(pts, d, { closed = false, area = false, segments = ARC_SEGMENTS } = {}) {
let rings;
if (d < 0) {
if (!area) throw Error('offset: a negative distance needs an area');
const ring = cleanPath(pts, true), r = ringArea(ring) >= 0 ? ring : ring.slice().reverse();
rings = unionRings(pieces([{ pts: r, closed: true, d: -d }], { segments }), { inside: r });
} else {
rings = unionRings(pieces([{ pts, closed, area, d }], { segments }));
}
return { rings, area: rings.reduce((s, r) => s + ringArea(r), 0) };
}
// Pure: the union of several parts, each with its own distance d. Returns { rings, area }.
export function offsetUnion(parts, { segments = ARC_SEGMENTS } = {}) {
const rings = unionRings(pieces(parts, { segments }));
return { rings, area: rings.reduce((s, r) => s + ringArea(r), 0) };
}Origin
A JavaScript module in the world folder of GlobalGrid2050 that converts to local (`toLocal`) and bng (`toBng`).
transformglobalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/origin.mjs · lines 1–31 of 31 · version 2026-09-27 00:05 · Entry point · pattern toBng (shared by 3 files)
- What it does
- It calculates its inputs. Defines toLocal, toBng, rebaseIfNeeded.
- 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
- Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
- Downstream impact
- Used directly by 24 files: Links (globalgrid2050); Plan Wire (globalgrid2050); Tour (globalgrid2050); Design Earthworks (globalgrid2050); and 20 more. Reached from 2 other entry points, including Graphics Engines Open Source — Versions Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/versions/); Versions — Site World Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/versions/202609262227-site-world/).
- What it achieves
- It is built from the to local helper (`toLocal`), the to bng helper (`toBng`) and the rebase if needed helper (`rebaseIfNeeded`). The world is drawn in local `east/north/up` metres around an origin held in float64 British National Grid metres ({ e, n, id }).
- Why it matters
- Loaded by the Site World V3 page at https://globalgrid2050.com/solar-design-studio/202609270402-site-world-v3/ and 1 other page. Also imported by 22 files, including Links, Plan Wire and Tour, from Graphics Engines Open Source.
- Application
- globalgrid2050 · solar-design-studio/202609270005-site-world-v3/world · JavaScript module
- Uses
- none found
- Used by
- imported by Links (import), imported by Plan Wire (import), imported by Tour (import), imported by Design Earthworks (import), imported by Design UI (import), imported by Plant UI (import), imported by Block UI (import), imported by First Showing (import), and 16 more, mentioned in Standalone (comment link)
- Produces
- toLocal, toBng, rebaseIfNeeded
- Defines here
- toLocal, toBng, rebaseIfNeeded
- 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/202609270005-site-world-v3/world/origin.mjs:1-31 · blob 633f6fc00c91b6508b10af44932649b2fd0799f7 · 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
// The site origin. The world is drawn in local east/north/up metres around an origin held in
// float64 British National Grid metres ({ e, n, id }). Float32 drawing error passes 0.1 px about
// 200 m from the origin and 0.5 px about 1 km out, so when the viewer strays too far we move the
// origin to them rather than let the numbers on the GPU grow. Pure: no imports, no DOM.
// Local metres from grid metres, in float64. Returns [x, y].
export function toLocal(origin, e, n) {
return [e - origin.e, n - origin.n];
}
// Grid metres from local metres, in float64. Returns { e, n }.
export function toBng(origin, x, y) {
return { e: origin.e + x, n: origin.n + y };
}
// If the viewer at local pos [x, y, ...] is more than `limit` metres from the origin on either
// axis, return a new origin snapped to whole `tile` metres of the national grid, nearest the
// viewer, with the local shift [dx, dy] to subtract from every local position. Otherwise null.
// Snapping to the nearest tile corner leaves the viewer at most tile / 2 from the new origin,
// so tile / 2 must be below the limit or we would rebase on every step.
export function rebaseIfNeeded(origin, pos, { limit = 600, tile = 1000 } = {}) {
if (!(tile > 0) || !(limit > tile / 2)) throw new Error('rebase needs tile > 0 and limit > tile / 2');
const [x, y] = pos;
if (!Number.isFinite(x) || !Number.isFinite(y)) return null; // never rebase onto a broken position
if (Math.abs(x) <= limit && Math.abs(y) <= limit) return null;
const e = Math.round((origin.e + x) / tile) * tile;
const n = Math.round((origin.n + y) / tile) * tile;
const dx = e - origin.e, dy = n - origin.n;
if (dx === 0 && dy === 0) return null; // already on the nearest corner; nothing to gain
return { e, n, shift: [dx, dy] };
}Phases Slider
A JavaScript module in the world folder of GlobalGrid2050 that creates phase slider (`createPhaseSlider`).
renderglobalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/phases-slider.mjs · lines 1–46 of 46 · version 2026-09-27 00:05 · Not reached from any entry point (candidate for review) · pattern sliderModel (shared by 2 files)
- What it does
- It draws its content. Defines sliderModel, createPhaseSlider, set. 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.
- Downstream impact
- Used directly by 2 files: Project UI (globalgrid2050); Project UI (globalgrid2050).
- What it achieves
- It creates phase slider (`createPhaseSlider`) and is built from the slider model helper (`sliderModel`) and the set step (`set`). A small range slider over a `phases.mjs` timeline. It responds to input events.
- Why it matters
- Imported by Project UI.
- Application
- globalgrid2050 · solar-design-studio/202609270005-site-world-v3/world · JavaScript module
- Uses
- none found
- Used by
- imported by Project UI (import), imported by Project UI (import), mentioned in Standalone (comment link)
- Produces
- sliderModel, createPhaseSlider
- Defines here
- sliderModel, createPhaseSlider, set
- 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/202609270005-site-world-v3/world/phases-slider.mjs:1-46 · blob 4c61229925dc0f8ca878c5e0565049157baf2cea · 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-slider.mjs: a small range slider over a phases.mjs timeline.
// The model (sliderModel) is pure; createPhaseSlider draws it into a container
// using the container's own document, so tests can pass a stub.
// timeline: createTimeline(...). Returns what the slider shows at `step`.
export function sliderModel(timeline, step) {
const s = timeline.clamp(Math.round(Number(step) || 0));
const snap = timeline.stateAt(s);
const ticks = [];
let acc = 0;
for (const p of timeline.plan.phases) { ticks.push({ step: acc, name: p.name }); acc += p.steps; }
return {
min: 0, max: timeline.totalSteps, value: s, label: timeline.label(s), ticks, counts: snap.counts,
summary: `${snap.counts.complete} complete, ${snap.items.length - snap.counts.planned - snap.counts.complete} in progress, ${snap.counts.planned} planned`
};
}
// container: an element; onStep(stateAt result) is called on every change.
export function createPhaseSlider(container, timeline, onStep = () => {}) {
const doc = container.ownerDocument;
const wrap = doc.createElement('div');
wrap.className = 'phase-slider';
const input = doc.createElement('input');
input.type = 'range';
input.min = '0';
input.max = String(timeline.totalSteps);
input.step = '1';
input.setAttribute('aria-label', 'Construction step');
const caption = doc.createElement('div');
caption.className = 'phase-slider-label';
caption.setAttribute('aria-live', 'polite');
wrap.appendChild(input);
wrap.appendChild(caption);
container.appendChild(wrap);
function set(step) {
const m = sliderModel(timeline, step);
input.value = String(m.value);
caption.textContent = `${m.label}. ${m.summary}.`;
onStep(timeline.stateAt(m.value));
return m;
}
input.addEventListener('input', () => set(input.value));
set(0);
return { set, element: wrap, destroy: () => wrap.remove() };
}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/202609270005-site-world-v3/world/phases.mjs · lines 1–213 of 213 · version 2026-09-27 00:05 · 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, ref. 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/202609270005-site-world-v3/world · JavaScript module
- Uses
- none found
- Used by
- imported by Project UI (import), mentioned in Standalone (comment link)
- Produces
- STATES, LIFECYCLES, KINDS, DEFAULT_PHASES, compilePlan, validatePlan, createTimeline
- Defines here
- rank, list, issue, readItems, ref, 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/202609270005-site-world-v3/world/phases.mjs:1-213 · blob a93f88a4dabdbb96b39cf1150efd11d528fd65e4 · 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, duplicate ids and dangling references.
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 ref = (it, key, kind) => {
if (it[key] == null) return;
const t = byId.get(it[key]);
if (!t || t.kind !== kind) issues.push(issue('error', 'BAD_REF', `Item ${it.id} names ${key} "${it[key]}", which is not a ${kind}.`, { item: it.id }));
};
for (const it of byId.values()) {
ref(it, 'trench', 'trench'); ref(it, 'hdd', 'hdd'); ref(it, 'pad', 'pad');
for (const r of it.via) if (byId.get(r)?.kind !== 'road') issues.push(issue('error', 'BAD_REF', `Item ${it.id} names via "${r}", which is not a road.`, { item: it.id }));
for (const a of it.after) {
const t = byId.get(a?.item);
if (!t || rank(t.kind, a.state || 'complete') < 0) issues.push(issue('error', 'BAD_REF', `Item ${it.id} waits on "${a?.item}" reaching "${a?.state}", which does not exist.`, { item: it.id }));
}
}
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 };
}Pick
A JavaScript module in the world folder of GlobalGrid2050 that snaps to grid (`snapToGrid`) and calculates planar distances. It picks ground (`pickGround`) and snaps grid (`snapToGrid`).
transformglobalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/pick.mjs · lines 1–52 of 52 · version 2026-09-27 00:05 · pattern rayFromScreen (shared by 2 files)
- What it does
- It calculates its inputs. Defines rayFromScreen, pickGround, below, snapToGrid, snap.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
- Downstream impact
- Used directly by 2 files: Design UI (globalgrid2050); Design UI (graphics-engines-open-source). Reached from 3 other entry points, including Graphics Engines Open Source — Versions Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/versions/); Versions — Site World Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/versions/202609262227-site-world/); Substrate (graphics-engines-open-source).
- What it achieves
- Picking: which point on the ground is under a pixel.
- Why it matters
- Imported by Design UI, from Graphics Engines Open Source.
- Application
- globalgrid2050 · solar-design-studio/202609270005-site-world-v3/world · JavaScript module
- Uses
- none found
- Used by
- imported by Design UI (import), imported by Design UI (import), mentioned in Standalone (comment link)
- Produces
- rayFromScreen, pickGround, snapToGrid
- Defines here
- rayFromScreen, pickGround, below, snapToGrid, snap
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609270005-site-world-v3/world/pick.mjs:1-52 · blob 60448f77cf04f86749fe0724f98bd548f71dd2af · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
// Picking: which point on the ground is under a pixel. Pure: no imports, no DOM, no WebGL.
// Conventions match camera.mjs: local east (x), north (y), up (z), metres; yaw 0 looks north (+y),
// yaw +π/2 looks east (+x); pitch up is positive. The view is built at the eye (eye-relative drawing),
// so the ray starts at the eye in local metres. Pixels: (0, 0) is the top-left corner of the canvas,
// px grows right and py grows down, as in DOM mouse events (use offsetX / offsetY scaled to canvas size).
// A ray through the centre of pixel position (px, py) on a width x height canvas. fovy in radians.
// Returns { origin: [x, y, z], dir: [x, y, z] } with dir of unit length.
export function rayFromScreen(px, py, width, height, eye, yaw, pitch, fovy) {
const c = Math.cos(pitch);
const f = [Math.sin(yaw) * c, Math.cos(yaw) * c, Math.sin(pitch)]; // camera.mjs direction()
const r = [Math.cos(yaw), -Math.sin(yaw), 0]; // camera.mjs view() right
const u = [r[1] * f[2] - r[2] * f[1], r[2] * f[0] - r[0] * f[2], r[0] * f[1] - r[1] * f[0]]; // r x f
const t = Math.tan(fovy / 2), aspect = width / height;
const nx = (2 * px) / width - 1, ny = 1 - (2 * py) / height; // normalised device coordinates
const a = nx * t * aspect, b = ny * t;
const d = [f[0] + r[0] * a + u[0] * b, f[1] + r[1] * a + u[1] * b, f[2] + r[2] * a + u[2] * b];
const len = Math.hypot(d[0], d[1], d[2]);
return { origin: [eye[0], eye[1], eye[2]], dir: [d[0] / len, d[1] / len, d[2] / len] };
}
// First point where the ray meets the ground, or null if it meets none within maxDistance metres.
// groundAt(x, y) -> ground height in metres. The ray is marched in steps of `step` metres; the first
// step that ends at or below the ground is bisected until the bracket is under 1 cm along the ray.
// Returns [x, y, groundAt(x, y)] so the point sits on the ground. A ray that starts below ground: null.
export function pickGround(ray, groundAt, { maxDistance = 2000, step = 0.5 } = {}) {
const { origin: o, dir: d } = ray;
if (!(step > 0) || !(maxDistance > 0)) return null;
const below = t => o[2] + d[2] * t <= groundAt(o[0] + d[0] * t, o[1] + d[1] * t);
if (below(0)) return null;
let lo = 0, hi = -1;
for (let t = step; ; t += step) {
const s = Math.min(t, maxDistance);
if (below(s)) { hi = s; break; }
lo = s;
if (s >= maxDistance) return null;
}
while (hi - lo > 0.01) {
const mid = (lo + hi) / 2;
if (below(mid)) hi = mid; else lo = mid;
}
const t = (lo + hi) / 2, x = o[0] + d[0] * t, y = o[1] + d[1] * t;
return [x, y, groundAt(x, y)];
}
// Snaps a point's x and y to the nearest multiple of spacing metres; z is kept as given
// (re-read the ground height afterwards if the snapped point must sit on the ground).
export function snapToGrid(point, spacing) {
if (!(spacing > 0)) return [point[0], point[1], point[2]];
const snap = v => Math.round(v / spacing) * spacing + 0; // + 0 turns -0 into 0
return [snap(point[0]), snap(point[1]), point[2]];
}