In this section
- Block Build transform · globalgrid2050 / solar-design-studio/202609270220-site-world-v3/world/block-build.mjs lines 1–257
- Block MV transform · globalgrid2050 / solar-design-studio/202609270220-site-world-v3/world/block-mv.mjs lines 1–112
- Block Sequence transform · globalgrid2050 / solar-design-studio/202609270220-site-world-v3/world/block-sequence.mjs lines 1–89
- Design Ground render · globalgrid2050 / solar-design-studio/202609270220-site-world-v3/world/design-ground.mjs lines 1–45
- Design Options interaction · globalgrid2050 / solar-design-studio/202609270220-site-world-v3/world/design-options.mjs lines 1–102
Block Build
A JavaScript module in the world folder of GlobalGrid2050 that works with transformers, cables, 33kV and overhead lines (OHL).
transformglobalgrid2050 / solar-design-studio/202609270220-site-world-v3/world/block-build.mjs · lines 1–257 of 257 · version 2026-09-27 02:20 · Not reached from any entry point (candidate for review) · pattern overheadClearance (shared by 4 files)
- What it does
- It calculates transformers, cables, 33kV and overhead lines (OHL). Defines 26 functions or classes, including group, put, seg, poly, mark.
- 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: transformers, cables, 33kV, overhead lines (OHL), 1.5kV.
- Inputs & outputs
- Voltage levels named: 33kV, 1.5kV.
- Downstream impact
- Used directly by 1 file: Block UI (globalgrid2050).
- What it achieves
- It builds block (`buildBlock`) and is built from the group step (`group`) and the put step (`put`). The owner's 10MVA solar block (`station.mjs`, ported from his explorer) placed on the measured ground, with the 33kV rings to the grid (`block-mv.mjs`), as line groups ordered for the build sequence. Its code works with 33 kV, 1.5 kV and 10 MVA.
- Why it matters
- Imported by Block UI.
- Application
- globalgrid2050 · solar-design-studio/202609270220-site-world-v3/world · JavaScript module
- Uses
- Station (import), Block MV (import), Cable Rating (import), MV Network (import)
- Used by
- imported by Block UI (import)
- Produces
- padEarthworks, buildBlock, overheadClearance, blockCounts
- Defines here
- group, put, seg, poly, mark, box, median, padEarthworks, buildBlock, g, zLocal, baseOf, onTable, at, edge, at, padOf, buried, lift, odMv, overheadClearance, blockCounts, inside, blockTrenches, sec, acSec
- 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/202609270220-site-world-v3/world/block-build.mjs:1-257 · blob 24892f1cc1d95a8d70a857571279acc7f8b638f3 · 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
// block-build.mjs: the owner's 10 MVA solar block (station.mjs, ported from his explorer) placed on the measured
// ground, with the 33 kV rings to the grid (block-mv.mjs), as line groups ordered for the build sequence.
//
// Station 1 is drawn in full: 23 paired tables whose frames follow the ground (the frame height is the ground
// averaged across the table at every pile line, so it rides the terrain gently), piles from the frame down to the
// ground measured at each pile, every string's 30 modules in series, 28 pole inverters, the 1,344 DC home cables and
// 84 AC phase cables along his routes, lowered into the trenches at his depths, and the two 5 MVA transformers on a
// levelled pad. Stations 2 to N are the same block, drawn as table outlines, pad and transformers.
// Positions are national-grid metres (e, n, height); each group keeps them relative to its own base point.
// marks[i] is the vertex count once item i is drawn, so the sequence shows a prefix without copying anything.
// Pure: no DOM. ground(e, n) is the measured ground (NaN where none); fallback(e, n) answers there instead.
import { station, tableShape, tableOrigin, dcHomeRoutes, STATION_DEFAULTS as SD } from './station.mjs';
import { mvChain } from './block-mv.mjs';
import { build as cableBuild } from './cable-rating.mjs';
import { EQUIPMENT } from './mv-network.mjs';
const PILE_LINES = 19; // pile lines along a table, every 5 modules
const PAD_MARGIN = 12; // station pad: 12 m round the transformers (the explorer's compound)
function group() { return { base: null, v: [], marks: [] }; }
const put = (G, p) => { if (!G.base) G.base = [p[0], p[1], p[2]]; G.v.push(p[0] - G.base[0], p[1] - G.base[1], p[2] - G.base[2]); };
const seg = (G, a, b) => { put(G, a); put(G, b); };
const poly = (G, pts) => { for (let i = 1; i < pts.length; i++) seg(G, pts[i - 1], pts[i]); };
const mark = G => G.marks.push(G.v.length / 3);
const box = (G, [x, y, z], w, d, h) => {
const c = [[x - w / 2, y - d / 2], [x + w / 2, y - d / 2], [x + w / 2, y + d / 2], [x - w / 2, y + d / 2]];
for (let i = 0; i < 4; i++) { const a = c[i], b = c[(i + 1) % 4]; seg(G, [...a, z], [...b, z]); seg(G, [...a, z + h], [...b, z + h]); seg(G, [...a, z], [...a, z + h]); }
};
const median = a => { const s = a.filter(Number.isFinite).sort((p, q) => p - q); return s.length ? s[Math.floor(s.length / 2)] : NaN; };
/** Level pad over a rectangle: the median ground, and cut and fill on a 1 m grid (bank m3). */
export function padEarthworks(g, e0, n0, e1, n1, level = null) {
const hs = [];
for (let n = n0 + 0.5; n < n1; n += 1) for (let e = e0 + 0.5; e < e1; e += 1) hs.push(g(e, n));
const z = level ?? median(hs);
let cut = 0, fill = 0, unmeasured = 0;
for (const h of hs) { if (!Number.isFinite(h)) { unmeasured++; continue; } if (h > z) cut += h - z; else fill += z - h; }
return { level: z, cut, fill, unmeasured, area: (e1 - e0) * (n1 - n0) };
}
/**
* buildBlock({ anchor: [e, n], ground, fallback, stations, pocKv, towers, gpuPads }) -> { groups, cables, trenches, summary }
* towers: [{ e, n, kv }] grid towers to connect to; gpuPads: [{ poly: [[e, n]...], level, cut, fill }] optional.
*/
export function buildBlock({ anchor, ground, fallback = () => NaN, stations = 4, pocKv = 400, towers = [], gpuPads = [] }) {
const [E, N] = anchor;
let unmeasured = 0;
const g = (e, n) => { const h = ground(e, n); if (Number.isFinite(h)) return h; unmeasured++; const f = fallback(e, n); return Number.isFinite(f) ? f : 0; };
const s = SD, st = station(null, { corners: false }), T = tableShape(s), t = s.tilt * Math.PI / 180;
const mv = mvChain({ stations, stationMVA: st.inventory.aggregateInverterMVA, pocKv });
const G = {}; for (const k of ['outline', 'tables', 'strings', 'inverters', 'station', 'others', 'rmu', 'grid', 'open']) G[k] = group();
// ---- tables: frame height per pile line from the ground across the table, piles to the ground at each pile ----
const zLocal = x => { const d = Math.abs(x) - T.halfRidgeGap; return s.height + Math.max(0, T.depth - d) * Math.tan(t); };
const frames = [], piles = { count: 0, min: Infinity, max: -Infinity }, lowEdge = { min: Infinity };
for (let n = 0; n < s.tables; n++) {
const [x0, y0] = tableOrigin(n, s), ys = Array.from({ length: PILE_LINES }, (_, k) => y0 + k * T.span / (PILE_LINES - 1));
// The frame sits on the highest ground under either low edge or the ridge, so the lowest module edge keeps its
// height at every pile line; smoothing may only raise it, never drop an edge towards the ground.
const edge = T.halfRidgeGap + T.depth, raw = ys.map(y => Math.max(g(E + x0 - edge, N + y), g(E + x0 + edge, N + y), g(E + x0, N + y)));
const sm = raw.map((_, k) => Math.max(raw[k], (raw[Math.max(0, k - 1)] + raw[k] + raw[Math.min(raw.length - 1, k + 1)]) / 3));
frames.push({ x0, y0, ys, sm });
}
const baseOf = (n, y) => {
const F = frames[n], u = Math.min(Math.max((y - F.y0) / T.span, 0), 1) * (PILE_LINES - 1), k = Math.min(PILE_LINES - 2, Math.floor(u));
return F.sm[k] + (F.sm[k + 1] - F.sm[k]) * (u - k);
};
const onTable = (n, x, y) => [E + x, N + y, baseOf(n, y) + zLocal(x - frames[n].x0)];
frames.forEach((F, n) => {
const at = (x, y, z) => [E + F.x0 + x, N + y, baseOf(n, y) + z];
for (const side of [-1, 1]) {
const edge = (off, dz) => F.ys.map(y => at(side * off, y, dz)), g2 = T.halfRidgeGap;
for (let r = 0; r <= s.rows; r++) { // outer low edge, row joints, ridge edge
const v = r * (s.moduleLength + s.moduleGap) - (r ? s.moduleGap / 2 : 0), off = g2 + T.depth - v * Math.cos(t);
poly(G.tables, edge(off, s.height + v * Math.sin(t)));
}
for (let c = 0; c <= s.columns; c++) { // module joints across the face
const y = F.y0 + Math.min(T.span, c * (s.moduleWidth + s.moduleGap));
seg(G.tables, at(side * (g2 + T.depth), y, s.height), at(side * g2, y, T.ridge));
}
for (const k of [0.2, 0.8]) for (const y of F.ys) { // piles: rear (tall) and front (short) posts
const x = side * (g2 + T.depth * k), top = at(x, y, zLocal(x) - 0.12), gz = g(top[0], top[1]);
seg(G.tables, [top[0], top[1], gz], top);
piles.count++; piles.min = Math.min(piles.min, top[2] - gz); piles.max = Math.max(piles.max, top[2] - gz);
}
for (const y of F.ys) { const p = at(side * (g2 + T.depth), y, s.height); lowEdge.min = Math.min(lowEdge.min, p[2] - g(p[0], p[1])); }
}
mark(G.tables);
});
// ---- strings: 30 modules in series through their terminals, in build order (table by table) ----
for (const x of st.strings) { poly(G.strings, x.modules.map(m => onTable(x.table, m.terminal[0], m.terminal[1]))); mark(G.strings); }
// ---- inverters on poles: box, pole to the ground ----
const invBase = st.inverters.map(i => g(E + i.point[0], N + i.point[1]));
st.inverters.forEach((inv, i) => {
const [x, y, z] = inv.point, b = invBase[i];
box(G.inverters, [E + x, N + y, b + z - 1], 1, 0.5, 1); seg(G.inverters, [E + x, N + y + 0.3, b], [E + x, N + y + 0.3, b + z]); mark(G.inverters);
});
// ---- station pads (level, cut and fill), transformers and RMUs; stations 2..N as outlines ----
const txs = s.transformers, px0 = Math.min(...txs.map(p => p[0])) - PAD_MARGIN, px1 = Math.max(...txs.map(p => p[0])) + PAD_MARGIN;
const py0 = Math.min(...txs.map(p => p[1])) - PAD_MARGIN, py1 = Math.max(...txs.map(p => p[1])) + PAD_MARGIN;
const pads = mv.stations.map(S => {
const [ox, oy] = S.offset, pad = padEarthworks(g, E + ox + px0, N + oy + py0, E + ox + px1, N + oy + py1);
const L = S.index ? G.others : G.station, z = pad.level;
const q = [[px0, py0], [px1, py0], [px1, py1], [px0, py1]].map(([x, y]) => [E + ox + x, N + oy + y, z]);
for (let i = 0; i < 4; i++) { seg(L, q[i], q[(i + 1) % 4]); seg(L, [q[i][0], q[i][1], z + 2.4], [q[(i + 1) % 4][0], q[(i + 1) % 4][1], z + 2.4]); }
for (const p of txs) box(L, [E + ox + p[0], N + oy + p[1], z], 4, 4, 3);
box(G.rmu, [E + S.rmu[0], N + S.rmu[1], z], EQUIPMENT.rmu.w, EQUIPMENT.rmu.d, EQUIPMENT.rmu.h); mark(G.rmu);
if (S.index) for (const F of frames) for (const side of [-1, 1]) {
const a = [F.x0 + side * (T.halfRidgeGap + T.depth), F.x0 + side * T.halfRidgeGap], yy = [F.y0, F.y0 + T.span / 2, F.y0 + T.span];
const at = (x, y, h) => [E + ox + x, N + oy + y, g(E + ox + x, N + oy + y) + h];
poly(L, yy.map(y => at(a[0], y, s.height))); poly(L, yy.map(y => at(a[1], y, T.ridge)));
seg(L, at(a[0], yy[0], s.height), at(a[1], yy[0], T.ridge)); seg(L, at(a[0], yy[2], s.height), at(a[1], yy[2], T.ridge));
}
if (!S.index) mark(G.station);
return { id: S.id, ...pad };
});
const padOf = S => pads[S.index].level;
// ---- cables: his routes, lifted onto the tables, into the trench (depth below the ground) and up the poles ----
// Along a trench the cable follows the ground at its depth: a point every 5 m.
const buried = (a, b) => { const k = Math.max(1, Math.ceil(Math.hypot(b[0] - a[0], b[1] - a[1]) / 5)), out = [];
for (let j = 1; j < k; j++) { const x = a[0] + (b[0] - a[0]) * j / k, y = a[1] + (b[1] - a[1]) * j / k; out.push([E + x, N + y, g(E + x, N + y) + a[2]]); }
return out; };
const lift = (pts, table, inv, endZ) => pts.flatMap((p, i) => {
const pre = i && p[2] < 0 && pts[i - 1][2] < 0 ? buried(pts[i - 1], p) : [];
if (p[2] < 0) return [...pre, [E + p[0], N + p[1], g(E + p[0], N + p[1]) + p[2]]];
if (inv != null && (i >= pts.length - 2 || Math.hypot(p[0] - st.inverters[inv].point[0], p[1] - st.inverters[inv].point[1]) < 0.8))
return [[E + p[0], N + p[1], invBase[inv] + p[2]]];
if (table != null) return [[E + p[0], N + p[1], baseOf(table, p[1]) + p[2]]];
return [[E + p[0], N + p[1], endZ + p[2]]];
});
const byIndex = new Map(st.strings.map(x => [x.index, x]));
const dc = dcHomeRoutes(st.strings, st.inverters.map(i => i.point)).map(r => ({ id: r.id, inverter: r.inverter,
points: lift(r.points, byIndex.get(r.string).table, r.inverter) }));
const ac = st.acCables.map((c, i) => { const inv = Math.floor(i / 3), p = c.points, first = [E + p[0][0], N + p[0][1], invBase[inv] + p[0][2]];
return { id: c.id, inverter: inv, points: [first, ...lift(p.slice(1), null, null, padOf(mv.stations[0]))] }; });
const odMv = a => cableBuild(a).od;
const mvCables = mv.circuits.map(cc => {
const pts = [];
for (let i = 1; i < cc.plan.length; i++) {
const [a, b] = [cc.plan[i - 1], cc.plan[i]], k = Math.max(1, Math.ceil(Math.hypot(b[0] - a[0], b[1] - a[1]) / 10));
for (let j = i === 1 ? 0 : 1; j <= k; j++) { const x = a[0] + (b[0] - a[0]) * j / k, y = a[1] + (b[1] - a[1]) * j / k; pts.push([E + x, N + y, g(E + x, N + y) - 0.85]); }
}
return { id: cc.id, ring: cc.ring, normallyOpen: cc.normallyOpen, areaMm2: cc.areaMm2, points: pts };
});
// Normally-open points: a ring on the RMU switch that is left open.
for (const r of mv.rings) { const S = mv.stations.find(x => x.id === r.openAt), z = padOf(S) + EQUIPMENT.rmu.h;
for (const h of [2.5, 4]) box(G.open, [E + S.rmu[0], N + S.rmu[1], z + h - 0.75], 0.8, 0.8, 0.75); mark(G.open); }
// ---- substation compound: switchroom, grid transformer(s) in bunds, connection structure, and the line tee ----
const C = mv.compound, cE = E + C.x, cN = N + C.y;
const gpu = gpuPads.find(p => inside(p.poly, cE, cN));
const cpad = padEarthworks(g, cE - C.w / 2, cN - C.d / 2, cE + C.w / 2, cN + C.d / 2, gpu ? gpu.level : null);
if (gpu) Object.assign(cpad, { cut: gpu.cut, fill: gpu.fill, source: 'GPU pad run (read-only)' });
const cz = cpad.level, fence = [[-1, -1], [1, -1], [1, 1], [-1, 1]].map(([a, b]) => [cE + a * C.w / 2, cN + b * C.d / 2, cz]);
for (let i = 0; i < 4; i++) { seg(G.grid, fence[i], fence[(i + 1) % 4]); seg(G.grid, [...fence[i].slice(0, 2), cz + 2.4], [...fence[(i + 1) % 4].slice(0, 2), cz + 2.4]); }
const sw = EQUIPMENT.switchboard; box(G.grid, [E + mv.board[0], N + mv.board[1], cz], sw.d, sw.w, sw.h);
const gt = EQUIPMENT['grid-transformer'];
for (const [x, y] of mv.grid.at) { box(G.grid, [E + x, N + y, cz], gt.w, gt.d, gt.h); box(G.grid, [E + x, N + y, cz], gt.bund.w, gt.bund.d, gt.bund.h); }
const P = [E + mv.poc.at[0], N + mv.poc.at[1]], poc = EQUIPMENT.poc; box(G.grid, [...P, cz], poc.w, poc.d, poc.h);
for (const [x, y] of mv.grid.at) seg(G.grid, [E + x + gt.w / 2, N + y, cz + gt.h - 1], [P[0], P[1], cz + poc.h]);
const line = towers.filter(w => w.kv >= pocKv).map(w => ({ ...w, d: Math.hypot(w.e - P[0], w.n - P[1]) })).sort((a, b) => a.d - b.d)[0] || null;
if (line && line.d <= 3000) for (const o of [-3, 0, 3]) seg(G.grid, [P[0] + o, P[1], cz + poc.h], [line.e + o, line.n, g(line.e, line.n) + 28]);
mark(G.grid);
// ---- outline of the whole plant (pegged out before the build starts) ----
const W = Math.max(...frames.map(F => F.x0)) + T.depth + 1, H = Math.max(...frames.map(F => F.y0)) + T.span + 1;
for (const S of mv.stations) {
const [ox, oy] = S.offset, q = [[-T.depth - 1, -3], [W, -3], [W, H], [-T.depth - 1, H]].map(([x, y]) => [E + ox + x, N + oy + y]);
for (let i = 0; i < 4; i++) { const a = q[i], b = q[(i + 1) % 4]; seg(G.outline, [...a, g(...a) + 0.3], [...b, g(...b) + 0.3]); }
}
mark(G.outline);
const ohl = overheadClearance(anchor, mv.stations, towers);
const trenches = blockTrenches(st, mv, E, N, odMv);
const groups = {};
for (const [k, L] of Object.entries(G)) groups[k] = { base: L.base || [E, N, 0], v: new Float32Array(L.v), marks: L.marks };
const inv = st.inventory;
return { groups, cables: { dc, ac, mv: mvCables }, trenches, mv, station: st, pads, compoundPad: cpad, connection: line,
summary: { inventory: inv, blockKwp: inv.installedModules * s.moduleW / 1000, piles: { ...piles }, lowEdgeMin: lowEdge.min,
unmeasured, pads, compoundPad: cpad, connection: line ? { kv: line.kv, distanceM: line.d } : null, overhead: ohl } };
}
/**
* Overhead lines over the field: the closest any table corner of any station comes to a span (consecutive towers
* of one voltage, under 600 m apart). stations: mvChain(...).stations or a count. Null when no span is loaded.
*/
export function overheadClearance([E, N], stations, towers) {
const T = tableShape(SD), list = typeof stations === 'number' ? mvChain({ stations }).stations : stations;
const spans = towers.slice(1).map((w, i) => [towers[i], w]).filter(([a, b]) => a.kv === b.kv && Math.hypot(b.e - a.e, b.n - a.n) < 600);
let best = null;
for (const S of list) for (let n = 0; n < SD.tables; n++) for (const [x, y] of [[-1, 0], [1, 0], [-1, 1], [1, 1]]) {
const [x0, y0] = tableOrigin(n, SD), pe = E + S.offset[0] + x0 + x * (T.depth + T.halfRidgeGap), pn = N + S.offset[1] + y0 + y * T.span;
for (const [a, b] of spans) {
const dx = b.e - a.e, dy = b.n - a.n, k = Math.min(1, Math.max(0, ((pe - a.e) * dx + (pn - a.n) * dy) / (dx * dx + dy * dy)));
const d = Math.hypot(pe - a.e - k * dx, pn - a.n - k * dy);
if (!best || d < best.distanceM) best = { kv: a.kv, distanceM: d };
}
}
return best;
}
/** The counts readout for one block, as the owner's explorer states them, plus the MV chain. */
export function blockCounts(b) {
const i = b.summary.inventory;
return { tables: i.tables, tableKwp: i.tableKwp, blockKwp: b.summary.blockKwp, strings: i.totalStrings, connectedStrings: i.connectedStrings,
spareStrings: i.spareStrings, inverters: i.inverters, stringsPerInverter: [...new Set(i.stringsPerInverter)], inverterKVA: i.inverterKVA,
transformers: i.transformers, transformerMVA: i.transformerMVA, stationMVA: i.aggregateTransformerMVA, acPhaseCables: i.acPhaseCables,
dcHomeCables: i.dcHomeCables, dcRoutes: b.cables.dc.length, acRoutes: b.cables.ac.length, stations: b.mv.stations.length,
rings: b.mv.rings.length, gridTransformers: b.mv.grid.units, gridMVA: b.mv.grid.mva, pocKv: b.mv.poc.kv };
}
const inside = (poly, x, y) => {
let c = false;
for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
const [xi, yi] = poly[i], [xj, yj] = poly[j];
if ((yi > y) !== (yj > y) && x < (xj - xi) * (y - yi) / (yj - yi) + xi) c = !c;
}
return c;
};
// Trenches for the ground and the cross-sections: stage, plan path (e, n) and a section in trench-sections.json form.
function blockTrenches(st, mv, E, N, odMv) {
const out = [], P = (x, y) => ({ e: E + x, n: N + y }), s = SD;
const sec = (id, label, o) => ({ id, voltage_class: label, status: 'owner prototype geometry', bedding: { thickness_mm: 75 }, ...o });
// DC: along each table row's end (y - 1), the owner's 0.6 m cable depth, catalogue DC section; a 2 m stub at each pole.
const rows = new Map();
for (const i of st.inverters) { const y = i.point[1]; rows.set(y, [...(rows.get(y) || []), i.point[0]]); }
const span = tableShape(s).span, dcSec = sec('dc-block', 'DC string home runs (1.5 kV DC)', { formation: 'ducts side by side, one layer',
circuits: 1, trench_width_m: 0.55, trench_depth_m: 0.77, duct_od_mm: 90, phase_spacing_mm: 90, marker: { type: 'warning tape', depth_m: 0.45 } });
for (const [y, xs] of rows) {
const n = Math.round((y + 1) / (span + s.aisleGap)) * 4, xl = tableOrigin(n, s)[0] - tableShape(s).depth, xr = tableOrigin(Math.min(s.tables - 1, n + 3), s)[0] + tableShape(s).depth;
out.push({ stage: 'dc', path: [P(xl, y), P(xr, y)], section: dcSec, cableOdMm: 6 });
for (const x of xs) out.push({ stage: 'dc', path: [P(x, y - 2.4), P(x, y - 0.2)], section: { ...dcSec, trench_width_m: 0.45 }, cableOdMm: 6 });
}
// AC: each inverter row's branch east to the collector 15 m west of the transformers, then the collector and in.
const acSec = c => sec('ac-block', 'LV AC 800 V, 400 mm2 Al trefoils', { formation: 'trefoil, direct buried', circuits: c,
trench_width_m: Math.max(0.35, 0.1 + 0.25 * c), trench_depth_m: s.acDepth, phase_spacing_mm: 37.4, circuit_spacing_mm: 250,
marker: { type: 'warning tape', depth_m: 0.6 } });
const tx = s.transformers, cx = tx[0][0] - s.collectorOffset;
for (const [y, xs] of rows) out.push({ stage: 'ac', path: [P(Math.min(...xs), y), P(cx, y)], section: acSec(xs.length), cableOdMm: 37.4 });
tx.forEach((t, k) => {
const mine = st.inverters.filter(i => i.transformer === k + 1).map(i => i.point[1]), lo = Math.min(...mine, t[1]), hi = Math.max(...mine, t[1]);
out.push({ stage: 'ac', path: [P(cx, lo), P(cx, hi)], section: acSec(mine.length), cableOdMm: 37.4 },
{ stage: 'ac', path: [P(cx, t[1]), P(t[0], t[1])], section: acSec(mine.length), cableOdMm: 37.4 });
});
// MV: the ring trenches, circuits 450 mm apart (the two-circuit 33 kV section), 0.91 m deep.
const od = odMv(mv.rings[0].areaMm2);
for (const tr of mv.trenches) out.push({ stage: 'mv', path: tr.plan.map(([x, y]) => P(x, y)), cableOdMm: od,
section: sec('33kv-ring', '33 kV AC ring', { formation: 'trefoil, direct buried', circuits: tr.circuits, trench_width_m: tr.width,
trench_depth_m: 0.91, phase_spacing_mm: 45, circuit_spacing_mm: 450, marker: { type: 'protection tile over each trefoil', depth_m: 0.65 } }) });
return out;
}Block MV
A JavaScript module in the world folder of GlobalGrid2050 that works with solar, transformers and cables, using IEC 60287 and IEC 60949.
transformglobalgrid2050 / solar-design-studio/202609270220-site-world-v3/world/block-mv.mjs · lines 1–112 of 112 · version 2026-09-27 02:20 · Not reached from any entry point (candidate for review) · pattern dropWith (shared by 4 files)
- What it does
- It calculates solar, transformers and cables. Defines 9 functions or classes, including mvChain, colX, up, path, dropWith.
- 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, transformers, cables, 400kV, 33kV.
- Inputs & outputs
- Voltage levels named: 400kV, 33kV.
- Downstream impact
- Used directly by 2 files: Block Build (globalgrid2050); Block UI (globalgrid2050).
- What it achieves
- It is built from the MV chain helper (`mvChain`), the col x helper (`colX`) and the path step (`path`). Stations of the solar block chained on 33kV rings to the MV board, the grid transformer(s) and the connection, laid out and sized from the load. Its code works with 33 kV and 400 kV.
- Why it matters
- Imported by Block Build and Block UI.
- Application
- globalgrid2050 · solar-design-studio/202609270220-site-world-v3/world · JavaScript module
- Uses
- Cable Rating (import), Plant Template (import), Plant Feeders (import)
- Used by
- imported by Block Build (import), imported by Block UI (import)
- Produces
- MV_LAYOUT, mvChain
- Defines here
- mvChain, colX, up, path, dropWith, side, lineOf, off, xy
- 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/202609270220-site-world-v3/world/block-mv.mjs:1-112 · blob fa1dbeee6ee2da8f4cc5a1a1e9a41c2cac4746d5 · 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
// block-mv.mjs: stations of the solar block chained on 33 kV rings to the MV board, the grid transformer(s) and the
// connection, laid out and sized from the load. Plant frame: metres east (x) and north (y) of station 1's own
// origin (station.mjs coordinates), heading 0.
//
// Layout: stations in columns of up to `rows` (2 by default) and up to 5 across; a spine trench runs along the south
// edge to the substation compound east of the field, and a feeder trench runs north up the east side of each
// column, beside a track, past each station's ring main unit (RMU) in its transformer compound. Every ring leaves
// one board section, loops through its RMUs and returns to the board, with one normally-open point in the middle
// so each half runs radially. Circuits sharing a stretch share a trench, trefoils 450 mm apart (as the two-circuit
// section in data/trench-sections.json), so the trench widens with the circuits in it.
// Sizing (plant-template.mjs rules): stations per ring from the feeder limit; every segment carries the whole ring
// load when the open point is moved to one end (IEC 60287 rating, cable-rating.mjs), not below the fault minimum
// (adiabatic, IEC 60949); upsized until the normal-running drop is within 0.5 %; grid transformers from the packed
// load (gridChoice). Illustrative, not a design for any site.
import { sizeFor, dropPercent, SIZES } from './cable-rating.mjs';
import { gridChoice, faultMinArea, TEMPLATE_DEFAULTS } from './plant-template.mjs';
import { coverage } from './plant-feeders.mjs';
export const MV_LAYOUT = Object.freeze({ pitchX: 200, pitchY: 800, maxCols: 5, rows: 2, rmu: [162, 332.5], columnX: 172, spineY: -20,
laneM: 0.45, compound: { w: 90, d: 60, gap: 25 } });
// Load per station: the block's inverters at their rating (MVA).
export function mvChain({ stations = 4, stationMVA = 9.856, pocKv = 400, layout = MV_LAYOUT, ...opts } = {}) {
const p = { ...TEMPLATE_DEFAULTS, ...opts }, L = layout, n = Math.round(stations);
if (!(n >= 1 && n <= 10)) throw Error('solar block: 1 to 10 stations');
if (![132, 275, 400].includes(pocKv)) throw Error('solar block: connection at 132, 275 or 400 kV');
const rows = n <= 3 ? 1 : Math.min(L.rows, Math.ceil(n / L.maxCols)), cols = Math.ceil(n / rows);
const st = Array.from({ length: n }, (_, s) => {
const col = Math.floor(s / rows), row = s % rows, off = [col * L.pitchX, row * L.pitchY];
return { id: `S${s + 1}`, index: s, col, row, offset: off, rmu: [off[0] + L.rmu[0], off[1] + L.rmu[1]], mva: stationMVA };
});
const fieldE = (cols - 1) * L.pitchX + L.columnX + 8;
const c = { x: fieldE + L.compound.gap + L.compound.w / 2, y: L.spineY - 5, w: L.compound.w, d: L.compound.d };
const board = [c.x - c.w / 2 + 12, c.y], gt0 = [c.x + 4, c.y + 12], poc = [c.x + c.w / 2 - 10, c.y];
// Network lines: 's' the spine (coordinate x), 'c<col>' a column (coordinate y), 'r<s>' a station's stub (x).
const colX = col => col * L.pitchX + L.columnX;
const up = s => [{ key: 'c' + s.col, a: L.spineY, b: s.rmu[1] }, { key: 'r' + s.index, a: colX(s.col), b: s.rmu[0] }];
const path = (A, B) => { // A, B: 'board' or a station
if (A === 'board') return [{ key: 's', a: board[0], b: colX(B.col) }, ...up(B)];
if (B === 'board') return path('board', A).map(q => ({ ...q, a: q.b, b: q.a })).reverse();
const out = [{ key: 'r' + A.index, a: A.rmu[0], b: colX(A.col) }];
if (A.col === B.col) out.push({ key: 'c' + A.col, a: A.rmu[1], b: B.rmu[1] });
else out.push({ key: 'c' + A.col, a: A.rmu[1], b: L.spineY }, { key: 's', a: colX(A.col), b: colX(B.col) }, { key: 'c' + B.col, a: L.spineY, b: B.rmu[1] });
out.push({ key: 'r' + B.index, a: colX(B.col), b: B.rmu[0] });
return out;
};
// Rings: as many stations as the feeder limit allows (at most 4), in column order.
const per = Math.max(1, Math.min(p.stationsPerFeederMax, Math.floor(p.feederLimitMVA / stationMVA)));
const nRings = Math.ceil(n / per), rings = [];
const opt = { soilKmW: p.soilKmW, kv: 33, pf: p.powerFactor }, minArea = faultMinArea(p.faultKA, p.faultS);
for (let k = 0, s0 = 0; k < nRings; k++) {
const m = Math.floor(n / nRings) + (k < n % nRings ? 1 : 0), chain = st.slice(s0, s0 + m); s0 += m;
const ends = ['board', ...chain, 'board'], hops = [];
for (let h = 0; h + 1 < ends.length; h++) {
const parts = path(ends[h], ends[h + 1]).filter(q => Math.abs(q.b - q.a) > 1e-9);
hops.push({ from: ends[h] === 'board' ? 'board' : ends[h].id, to: ends[h + 1] === 'board' ? 'board' : ends[h + 1].id, parts,
lengthM: parts.reduce((t, q) => t + Math.abs(q.b - q.a), 0) });
}
const open = Math.ceil(m / 2); // the hop left open: the middle of the ring
const load = chain.reduce((t, s) => t + s.mva, 0);
const pick = sizeFor(load / p.maxUtilisation, { ...opt, minArea });
let area = pick ? pick.area : SIZES.at(-1);
// Normal running: stations before the open hop from leg A, the rest from leg B (each half radial).
const dropWith = a => {
const side = (hs, sts) => hs.reduce((t, h, i) => t + dropPercent(a, h.lengthM, sts.slice(i).reduce((u, s) => u + s.mva, 0), opt), 0);
const A = side(hops.slice(0, open), chain.slice(0, open)), B = side(hops.slice(open + 1).reverse(), chain.slice(open).reverse());
const outage = side(hops.slice(0, m), chain); // leg B out: the whole ring from leg A
return { normal: Math.max(A, B), outage };
};
while (dropWith(area).normal > p.vdropLimitPct && area < SIZES.at(-1)) area = SIZES[SIZES.indexOf(area) + 1];
const d = dropWith(area);
rings.push({ id: `F${k + 1}`, stations: chain.map(s => s.id), hops, open, openAt: hops[open].to === 'board' ? hops[open].from : hops[open].to,
loadMVA: load, areaMm2: area, carries: pick ? pick.amps : null, dropPct: d.normal, outageDropPct: d.outage });
}
// Board sections: at most 6 ways each, one per grid transformer at least; the two ends of a ring on different sections.
const exportMW = n * stationMVA * p.powerFactor;
const grid = gridChoice(exportMW, exportMW * p.gridFactor, null, rings.map(r => ({ loadMVA: r.loadMVA })));
const sections = Math.max(1, grid.units, Math.ceil(2 * rings.length / p.feedersPerBoardMax));
rings.forEach((r, k) => { r.boardA = `MVB${(k % sections) + 1}`; r.boardB = `MVB${((k + (sections > 1 ? 1 : 0)) % sections) + 1}`; });
// Circuits: each hop is one three-core circuit; lanes on each line in the order circuits first use it.
const lanes = new Map(), laneOf = (key, id) => { if (!lanes.has(key)) lanes.set(key, []); const l = lanes.get(key); if (!l.includes(id)) l.push(id); return l.indexOf(id); };
const circuits = rings.flatMap(r => r.hops.map((h, i) => ({ id: `${r.id}-${i + 1}`, ring: r.id, from: h.from, to: h.to, parts: h.parts,
lengthM: h.lengthM, areaMm2: r.areaMm2, normallyOpen: i === r.open })));
for (const cc of circuits) for (const q of cc.parts) q.lane = laneOf(q.key, cc.id);
const lineOf = key => (key === 's' ? { along: 'x', at: L.spineY } : key[0] === 'c' ? { along: 'y', at: colX(Number(key.slice(1))) }
: { along: 'x', at: st[Number(key.slice(1))].rmu[1] });
const off = (key, lane) => (lane - ((lanes.get(key).length - 1) / 2)) * L.laneM;
const xy = (key, v, lane) => { const g = lineOf(key), o = off(key, lane); return g.along === 'x' ? [v, g.at + o] : [g.at + o, v]; };
for (const cc of circuits) cc.plan = cc.parts.flatMap(q => [xy(q.key, q.a, q.lane), xy(q.key, q.b, q.lane)])
.filter((pt, i, a) => !i || Math.hypot(pt[0] - a[i - 1][0], pt[1] - a[i - 1][1]) > 1e-6);
const trenches = [];
for (const key of lanes.keys()) {
const list = circuits.flatMap(cc => cc.parts.filter(q => q.key === key).map(q => ({ a: Math.min(q.a, q.b), b: Math.max(q.a, q.b), lane: q.lane })));
for (const s of coverage(list)) {
const inside = list.filter(q => q.a < s.b - 1e-9 && q.b > s.a + 1e-9).map(q => off(key, q.lane));
const lo = Math.min(...inside), hi = Math.max(...inside), w = hi - lo + L.laneM, mid = (lo + hi) / 2, g = lineOf(key);
const plan = g.along === 'x' ? [[s.a, g.at + mid], [s.b, g.at + mid]] : [[g.at + mid, s.a], [g.at + mid, s.b]];
trenches.push({ key, circuits: s.c, width: Math.max(0.45, w), plan, lengthM: s.b - s.a });
}
}
const trenchM = trenches.reduce((t, x) => t + x.lengthM, 0);
const cableM = circuits.reduce((t, cc) => t + 3 * (cc.lengthM * 1.03 + 10), 0);
return { stations: st, rows, cols, rings, circuits, trenches, trenchM, cableM, compound: c, board, sections,
grid: { units: grid.units, mva: grid.mva, smallest: grid.smallest, at: Array.from({ length: grid.units }, (_, g) => [gt0[0] + g * 16, gt0[1]]) },
poc: { kv: pocKv, at: poc }, exportMW, perRing: per, minAreaMm2: minArea,
note: 'Illustrative, not a design for any site: ring sizes from generic rating rules, routes along assumed tracks.' };
}Block Sequence
A JavaScript module in the world folder of GlobalGrid2050 that works with cables, transformers and solar.
transformglobalgrid2050 / solar-design-studio/202609270220-site-world-v3/world/block-sequence.mjs · lines 1–89 of 89 · version 2026-09-27 02:20 · Not reached from any entry point (candidate for review) · pattern partial (shared by 2 files)
- What it does
- It calculates cables, transformers and solar. Defines 7 functions or classes, including clamp01, progress, stageAt, reveal, partial.
- 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, transformers, solar, 33kV.
- Inputs & outputs
- Voltage levels named: 33kV.
- Downstream impact
- Used directly by 2 files: Block UI (globalgrid2050); Block UI (globalgrid2050).
- What it achieves
- It creates clock (`createClock`) and is built from the clamp01 step (`clamp01`) and the progress step (`progress`). The order a solar block is built in, as a clock the page can play, pause and step. Its code works with 33 kV.
- Why it matters
- Imported by Block UI.
- Application
- globalgrid2050 · solar-design-studio/202609270220-site-world-v3/world · JavaScript module
- Uses
- none found
- Used by
- imported by Block UI (import), imported by Block UI (import), mentioned in Standalone (comment link)
- Produces
- STAGES, TOTAL, STARTS, progress, stageAt, reveal, partial, createClock
- Defines here
- clamp01, progress, stageAt, reveal, partial, createClock, t
- 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/202609270220-site-world-v3/world/block-sequence.mjs:1-89 · blob a4f7e4dc709a56867e4b24dc7b341b0952bdfca6 · 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
// block-sequence.mjs: the order a solar block is built in, as a clock the page can play, pause and step.
//
// Stages run one after another; each has a length in seconds at normal speed. progress(t) says, for a time t, how
// far every stage has got (0 before it starts, 1 once done), so drawing is a pure function of t: pausing freezes t
// and nothing is redrawn. The clock never runs a timer of its own; the page asks it for t while it is playing
// and draws at its own capped rate (30 fps), and asks nothing while it is paused (0 fps).
// Pure: no imports, no DOM.
export const STAGES = Object.freeze([
{ id: 'trenches', label: 'Trenches dug (DC and AC)', seconds: 3 },
{ id: 'tables', label: 'Piles driven, tables built', seconds: 6 },
{ id: 'strings', label: 'Modules strung: 30 in series, 24 strings per inverter', seconds: 5 },
{ id: 'inverters', label: 'Inverters mounted on their poles', seconds: 3 },
{ id: 'dc', label: 'DC home cables pulled along the trenches', seconds: 6 },
{ id: 'ac', label: 'AC phase cables pulled to the transformers', seconds: 4 },
{ id: 'station', label: 'Station transformers set; station energised', seconds: 2 },
{ id: 'mv', label: '33 kV ring cables pulled, ring main units joined', seconds: 5 },
{ id: 'grid', label: 'MV board, grid transformer and connection energised', seconds: 3 }
]);
export const TOTAL = STAGES.reduce((t, s) => t + s.seconds, 0);
// Start time of each stage.
export const STARTS = Object.freeze(STAGES.reduce((a, s, i) => (a.push(i ? a[i - 1] + STAGES[i - 1].seconds : 0), a), []));
const clamp01 = x => Math.min(1, Math.max(0, x));
/** progress(t) -> { stageId: 0..1 } for every stage. */
export function progress(t) {
const out = {};
STAGES.forEach((s, i) => { out[s.id] = clamp01((t - STARTS[i]) / s.seconds); });
return out;
}
/** The stage running at t (the last one once everything is built). */
export function stageAt(t) {
for (let i = 0; i < STAGES.length; i++) if (t < STARTS[i] + STAGES[i].seconds) return { index: i, ...STAGES[i] };
return { index: STAGES.length - 1, ...STAGES.at(-1), done: true };
}
/** Of n items revealed in order over a stage at fraction f: how many are complete, and how far the next one is. */
export function reveal(n, f) {
const x = clamp01(f) * n, whole = Math.min(n, Math.floor(x + 1e-9));
return { whole, part: whole < n ? x - whole : 0 };
}
/** The first fraction f (0..1) of a polyline [[x, y, z], ...] by length: the cable pulled in so far. */
export function partial(points, f) {
if (f >= 1) return points;
if (f <= 0 || points.length < 2) return [points[0]];
let total = 0;
const seg = [];
for (let i = 1; i < points.length; i++) {
const a = points[i - 1], b = points[i], l = Math.hypot(b[0] - a[0], b[1] - a[1], b[2] - a[2]);
seg.push(l); total += l;
}
let want = f * total;
const out = [points[0]];
for (let i = 1; i < points.length; i++) {
const a = points[i - 1], b = points[i], l = seg[i - 1];
if (want >= l) { out.push(b); want -= l; continue; }
const k = l > 0 ? want / l : 0;
out.push([a[0] + (b[0] - a[0]) * k, a[1] + (b[1] - a[1]) * k, a[2] + (b[2] - a[2]) * k]);
break;
}
return out;
}
/**
* createClock({ now }) -> { t(), playing(), play(), pause(), step(), reset(), finish() }
* t() is seconds of build time; it moves only while playing. step() pauses and jumps to the next stage boundary.
*/
export function createClock({ now = () => performance.now(), speed = 1 } = {}) {
let base = TOTAL, since = null; // placed blocks start complete; Play from the end starts again
const t = () => (since === null ? base : Math.min(TOTAL, base + (now() - since) / 1000 * speed));
const clock = {
t,
playing: () => since !== null && t() < TOTAL,
play() { if (t() >= TOTAL) base = 0; since = now(); return clock; },
pause() { base = t(); since = null; return clock; },
step() {
const cur = t() >= TOTAL ? 0 : t();
base = STARTS.find(s => s > cur + 1e-6) ?? TOTAL; since = null; return clock;
},
reset() { base = 0; since = null; return clock; },
finish() { base = TOTAL; since = null; return clock; }
};
return clock;
}Design Ground
A JavaScript module in the world folder of GlobalGrid2050 that draws profile (`drawProfile`), covering LiDAR terrain.
renderglobalgrid2050 / solar-design-studio/202609270220-site-world-v3/world/design-ground.mjs · lines 1–45 of 45 · version 2026-09-27 02:20 · Not reached from any entry point (candidate for review) · pattern drawProfile (shared by 2 files)
- What it does
- Defines 6 functions or classes, including groundShareOf, groundRowOf, drawProfile, X, line. 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: LiDAR terrain.
- Downstream impact
- Used directly by 2 files: Design UI (globalgrid2050); Design UI (globalgrid2050).
- What it achieves
- It draws profile (`drawProfile`) and is built from the ground share of helper (`groundShareOf`) and the ground row of helper (`groundRowOf`). What the ground under a route is: measured LiDAR, or a flat plane where none is loaded, said so plainly (code review 2, phone review 1).
- Why it matters
- Imported by Design UI.
- Application
- globalgrid2050 · solar-design-studio/202609270220-site-world-v3/world · JavaScript module
- Uses
- Snap (import), Boq Assumptions (import), Measure Format (import)
- Used by
- imported by Design UI (import), imported by Design UI (import)
- Produces
- groundShareOf, groundRowOf, drawProfile
- Defines here
- groundShareOf, groundRowOf, drawProfile, X, line, text
- 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/202609270220-site-world-v3/world/design-ground.mjs:1-45 · blob 6ce3cd7539c48b794c7c8769ec482ebbd2a7c005 · 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
// What the ground under a route is: measured LiDAR, or a flat plane where none is loaded, said so plainly
// (code review 2, phone review 1). Never labels a flat stand-in as LiDAR. The Design panel's readout rows (pure) and its level profile.
import { measuredShare } from './snap.mjs';
import { BASIS } from './boq-assumptions.mjs';
import { formatNumber, formatLength } from './measure-format.mjs';
const SVG = 'http://www.w3.org/2000/svg';
// pts: [[x, y], ...] local metres. measuredAt(x, y) -> measured ground or NaN (null: no measure known, all taken as measured).
export function groundShareOf(pts, measuredAt) {
if (!measuredAt || pts.length < 1) return { all: true, none: false, m: null };
const m = pts.length > 1 ? measuredShare(pts, measuredAt) : { total: 1, known: Number.isFinite(measuredAt(pts[0][0], pts[0][1])) ? 1 : 0 };
return { all: m.known >= m.total - 0.5, none: m.known <= 0.5 && m.total > 0, m };
}
// ['Ground', words, warn?] for the readout.
export function groundRowOf(pts, measuredAt) {
const g = groundShareOf(pts, measuredAt);
if (g.all) return ['Ground', `${BASIS.ground} · ${BASIS.datum}`];
if (g.none) return ['Ground', 'flat ground assumed: no LiDAR loaded here, so levels, volumes and gradients are not measured', true];
return ['Ground', `${BASIS.ground} on ${formatLength(g.m.known)} of ${formatLength(g.m.total)}; flat ground assumed beyond`, true];
}
// The level profile along the route (world.html #design-profile): ground level solid, trench floor dashed.
export function drawProfile(doc, m) {
const box = doc.getElementById('design-profile-box'), svg = doc.getElementById('design-profile');
box.hidden = !m;
if (!m) return;
const W = 300, H = 90, L = 4, R = 296, T = 14, B = 76, pr = m.profile;
const lo = pr.min - m.depth, hi = Math.max(pr.max, lo + 0.5), len = Math.max(pr.length2d, 1e-6);
const X = s => L + (s / len) * (R - L), Y = z => B - ((z - lo) / (hi - lo)) * (B - T);
const line = (dz, cls) => {
const el = doc.createElementNS(SVG, 'polyline');
el.setAttribute('points', pr.pairs.map(([s, z]) => `${X(s).toFixed(1)},${Y(z - dz).toFixed(1)}`).join(' '));
el.setAttribute('class', cls); return el;
};
const text = (x, y, s, anchor = 'start') => {
const el = doc.createElementNS(SVG, 'text');
Object.entries({ x, y, 'text-anchor': anchor }).forEach(([k, v]) => el.setAttribute(k, v));
el.textContent = s; return el;
};
svg.setAttribute('viewBox', `0 0 ${W} ${H}`);
svg.replaceChildren(line(0, 'ground'), line(m.depth, 'floor'), text(L, 10, `${formatNumber(hi, 1)} m`),
text(L, H - 2, `${formatNumber(lo, 1)} m`), text(R, H - 2, formatLength(pr.length2d), 'end'));
}Design Options
A JavaScript module in the world folder of GlobalGrid2050 that fetches spec example and cables. It creates options (`createOptions`), sets source (`setSource`) and loads example (`loadExample`).
interactionglobalgrid2050 / solar-design-studio/202609270220-site-world-v3/world/design-options.mjs · lines 1–102 of 102 · version 2026-09-27 02:20 · Not reached from any entry point (candidate for review) · pattern readFile (shared by 2 files)
- What it does
- It fetches spec example and cables. Defines 9 functions or classes, including createOptions, $, say, setSource, loadExample. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: cables.
- Inputs & outputs
- In: JSON file spec-example.json.
- Downstream impact
- Used directly by 2 files: Design Sections (globalgrid2050); Design Sections (globalgrid2050).
- What it achieves
- The Options part of the Design panel (`world.html` #design-options). It reads `./world/data/spec-example.json`. It responds to change and click events.
- Why it matters
- Imported by Design Sections.
- Application
- globalgrid2050 · solar-design-studio/202609270220-site-world-v3/world · JavaScript module
- Uses
- Spec Rules (import), Plant Template (import), MV Network (import)
- Used by
- imported by Design Sections (dynamic import), imported by Design Sections (dynamic import), mentioned in Standalone (comment link)
- Produces
- createOptions
- Defines here
- createOptions, $, say, setSource, loadExample, readFile, place, batch, batches
- 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/202609270220-site-world-v3/world/design-options.mjs:1-102 · blob 6e4e4dd59a19d34a4f4b89a7640a5c269aa860b7 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
// design-options.mjs: the Options part of the Design panel (world.html #design-options).
// Specification Network operator spec, the made-up example, or a project specification from a local file.
// A local file is read in the browser and kept in memory only; it is never sent anywhere.
// Ground Normal ground, or Alluvium / soft wet ground (support or batter, dewatering, spoil handling).
// MV network a generic plant block diagram (plant-template.mjs) placed on the ground where you stand,
// optionally following a route file in drawing coordinates, drawn as equipment outlines and cables.
// The trench tool asks spec() and ground() when it builds a trench; batches() draws the placed network.
import { OPERATOR_SPEC, readSpec, GROUNDS } from './spec-rules.mjs';
import { plantTemplate } from './plant-template.mjs';
import { placeNetwork, readRoutes, solidLines, cableLines } from './mv-network.mjs';
const COLOUR = { equipment: [0.85, 0.88, 0.95, 1], mv: [1, 0.55, 0.25, 1], hv: [1, 0.3, 0.75, 1], open: [0.6, 0.6, 0.6, 1] };
// deps: { doc, viewer() -> { pos, yaw }, heightAt(x, y), redraw(), onChange() }
export function createOptions({ doc, viewer, heightAt, redraw, onChange = () => {} }) {
const $ = id => doc.getElementById(id);
const state = { spec: OPERATOR_SPEC, project: null, ground: 'normal', routes: null, net: null, version: 0 };
const say = (msg, warn = false) => { const el = $('spec-status'); el.textContent = msg; el.className = warn ? 'warn' : ''; };
function setSource(v) {
if (v === 'operator') { state.spec = OPERATOR_SPEC; say('Operator sections, general practice ground rules.'); }
else if (v === 'project') {
if (state.project) { state.spec = state.project; say(`${state.project.label} (local file, in memory only)`); }
else { $('spec-file').click(); return; } // choose a file; change fires on load
} else if (v === 'example') loadExample();
onChange();
}
async function loadExample() {
try {
const r = await fetch('./world/data/spec-example.json', { cache: 'no-cache' });
state.spec = readSpec(await r.json()); say(`${state.spec.label}: every value is made up.`);
} catch (e) { state.spec = OPERATOR_SPEC; $('spec-source').value = 'operator'; say('Example could not be read: ' + e.message, true); }
onChange();
}
async function readFile(input, parse) {
const f = input.files && input.files[0];
if (!f) return null;
const json = JSON.parse(await f.text());
input.value = ''; // the same file can be chosen again
return parse(json);
}
$('spec-source').addEventListener('change', e => setSource(e.target.value));
$('spec-file').addEventListener('change', async e => {
try {
state.project = await readFile(e.target, readSpec);
if (!state.project) return;
state.spec = state.project; $('spec-source').value = 'project';
say(`${state.project.label} (local file, in memory only)`);
} catch (err) { state.spec = OPERATOR_SPEC; $('spec-source').value = 'operator'; say('Specification not used: ' + err.message, true); }
onChange();
});
$('ground-condition').replaceChildren(...GROUNDS.map(([id, label]) => new Option(label, id)));
$('ground-condition').addEventListener('change', e => { state.ground = e.target.value; onChange(); });
// ---- MV network ----
$('mv-routes-file').addEventListener('change', async e => {
try { state.routes = await readFile(e.target, readRoutes); say(`Route file read: ${state.routes.nodes.size} nodes, drawing units.`); }
catch (err) { state.routes = null; say('Route file not used: ' + err.message, true); }
});
function place() {
const mw = Number($('mv-mw').value), scale = Number($('mv-scale').value) || 1, v = viewer();
try {
const diagram = plantTemplate({ targetMW: mw });
const net = placeNetwork(diagram, { routes: state.routes, at: [v.pos[0], v.pos[1]], heading: v.yaw || 0,
metresPerUnit: scale, groundAt: heightAt });
state.net = { diagram, ...net }; state.version++;
const c = diagram.counts, fail = diagram.checks.filter(k => !k.ok).map(k => k.name);
say(`MV network placed: ${c.stations} stations, ${c.feeders} feeders, ${c.boardSections} board sections, `
+ `${c.gridTransformers} grid transformers, ${diagram.ratings.pocKv} kV connection`
+ `${fail.length ? '. Outside limits: ' + fail.join(', ') : '; every level within its limit'}${net.missing.length ? `; ${net.missing.length} nodes not in the route file` : ''}.`,
fail.length > 0);
} catch (err) { say(err.message, true); }
redraw();
}
$('mv-place').addEventListener('click', place);
$('mv-clear').addEventListener('click', () => { state.net = null; state.version++; say('MV network cleared.'); redraw(); });
function batch(key, pos, color) {
if (!pos || pos.length < 6) return null;
const o = [pos[0], pos[1], pos[2]], out = new Float32Array(pos.length);
for (let i = 0; i < pos.length; i++) out[i] = pos[i] - o[i % 3];
return { key, version: state.version, positions: out, color, origin: o };
}
function batches() {
const n = state.net;
if (!n) return [];
const open = n.cables.filter(c => c.normallyOpen), live = n.cables.filter(c => !c.normallyOpen);
return [batch('mv-equipment', solidLines(n.equipment.flatMap(e => e.solids)), COLOUR.equipment),
batch('mv-cables', cableLines(live.filter(c => c.kv < 100)), COLOUR.mv),
batch('mv-hv', cableLines(live.filter(c => c.kv >= 100)), COLOUR.hv),
batch('mv-open', cableLines(open), COLOUR.open)].filter(Boolean);
}
say('Operator sections, general practice ground rules.');
return {
spec: () => state.spec, ground: () => state.ground, batches,
snapshot: () => ({ spec: state.spec.label, source: state.spec.source, ground: state.ground,
network: state.net ? { counts: state.net.diagram.counts, ratings: state.net.diagram.ratings, ok: state.net.diagram.ok,
equipment: state.net.equipment.length, cables: state.net.cables.length } : null })
};
}