In this section
- Engine Lock render · energy-transition-simulator / prototype/mod/engine-lock.js lines 1–305
- Block Build transform · energy-transition-simulator / prototype/mod/engine/block-build.mjs lines 1–255
- Block MV transform · energy-transition-simulator / prototype/mod/engine/block-mv.mjs lines 1–139
Engine Lock
A JavaScript file in the prototype folder of Energy Transition Simulator that maps cables, LiDAR terrain and transformers, using OSTN15. It rebuilds same (`rebuildSame`) and stops ride (`stopRide`).
renderenergy-transition-simulator / prototype/mod/engine-lock.js · lines 1–305 of 305 · Not reached from any entry point (candidate for review) · pattern footprints (shared by 2 files)
- What it does
- It maps cables, LiDAR terrain and transformers. Defines 48 functions or classes, including ENGINE, PF, stream, clamp, lerp. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage experimental (path word 'prototype'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: cables, LiDAR terrain, transformers, 33kV.
- Inputs & outputs
- Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid). Voltage levels named: 33kV.
- What it achieves
- The site-world 10MVA block, imported BY URL from its immutable site-world release (never copied), locked to real coordinates first and animated second. Its code works with 10 MVA and 33 kV. It responds to click and keydown events.
- Why it matters
- No other file in the estate was found to import it.
- Application
- energy-transition-simulator · prototype/mod · script
- Uses
- none found
- Used by
- none found
- Produces
- ENGINE, PF, stream, clamp, lerp, routeAt, cableCamera, route, load, exag, elevNow, rawAt
- Defines here
- ENGINE, PF, stream, clamp, lerp, routeAt, cableCamera, route, load, exag, elevNow, rawAt, demAt, grounds, ground, fallback, rot, build, ground, toV, pack, ll, tilesTouched, tileState, arriveAt, reground, tick, viewTile, rebuildSame, freeBuffers
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- energy-transition-simulator@a165ce6d56cb22271828874d68d570e8fa5e428a prototype/mod/engine-lock.js:1-305 · blob 9f74eba2fadbba8e7ceba0253688d073a1b59b73 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: experimental · users: none · canonical: unreached_review
// mod/engine-lock.js - the site-world 10 MVA block, imported BY URL from its immutable site-world release (never copied),
// locked to real coordinates first and animated second.
// LOCK: the anchor is a British National Grid point converted through the overlay's own OSTN15 path (place-frame
// PF.fromBng / toBng); ground(e, n) is the streamed EA LiDAR DTM (window.__lidarStream.heightAt, measured, rule R5);
// the fallback is the map terrain, counted and labelled "estimated". No second conversion exists in this file.
// BUILD: File > "Build here (animated)" places the block at the view centre and plays the engine's own build sequence
// (marks[] prefixes: outline, 23 tables, strings, inverters, DC home cables, AC phase cables, pad, RMU, 33 kV rings,
// grid) over about 20 s, then the cable-flow pulses. View > "Walk a cable" rides one AC cable at eye height.
// PROVENANCE, three line styles never mixed, cut in the fragment shader (no extra geometry): SOLID = measured
// (the ground contact: outline pegs and pile feet on measured ground), DASHED = documented (the library's cable
// routes and trench depths), GHOST dotted = the engine's assumed equipment (tables, strings, inverters, station, grid).
// With any estimated ground under the block, the ground contact is drawn ghost, not solid.
// LOCK BEFORE ANIMATING: the block is built at once on whatever ground is in, then RE-GROUNDED: every R5 tile the rotated
// block's bounding box touches is asked to arrive (one at a time, the stream's own 40 s gap), and when any of them turns
// measured the block is rebuilt at the same E, N and bearing without replaying the sequence; the caption follows.
// Static VBOs: every group is uploaded once; the sequence is a growing draw count, the pulses are one small dynamic buffer.
// Lifted (they cannot be imported: the explorer's script is DOM-bound): routeAt and the 'cable' camera from
// Ventusltd/graphics-engines-open-source web/explore.mjs at commit 79e0bd8 (lines 22 and 41).
// Plain script; attaches to window.SIM. Test hook: SIM.engineLock = { build, state, footprints, walkCable, stop, sequence }.
(function () {
'use strict';
const RELEASES = ['202609270524', '202609271853'];
const ENGINE = s => `https://globalgrid2050.com/solar-design-studio/${s}-site-world/world/block-build.mjs`;
const EYE = 1.7, RIDE_MPS = 4, SEQ_MS = 20000;
const STYLE = { solid: 0, dashed: 1, ghost: 2 };
// group -> [colour rgba, style, seconds of the sequence]; the order IS the build sequence
const PLAN = [
['outline', [0.55, 0.9, 1.0, 1.0], 'solid', 1.0], ['tables', [0.61, 0.86, 1.0, 0.95], 'ghost', 6.0], ['strings', [1.0, 0.86, 0.35, 0.8], 'ghost', 3.0],
['inverters', [1.0, 0.55, 0.2, 1.0], 'ghost', 1.0], ['dc', [1.0, 0.86, 0.35, 0.75], 'dashed', 3.0], ['ac', [0.75, 0.8, 0.86, 0.95], 'dashed', 2.0],
['station', [0.95, 0.97, 1.0, 1.0], 'ghost', 1.0], ['rmu', [0.95, 0.97, 1.0, 1.0], 'ghost', 0.5], ['mv', [1.0, 0.3, 0.3, 0.9], 'dashed', 1.5],
['grid', [0.95, 0.97, 1.0, 1.0], 'ghost', 1.0], ['others', [0.61, 0.86, 1.0, 0.5], 'ghost', 0.0], ['open', [1.0, 0.3, 0.3, 0.9], 'ghost', 0.0]
];
const PF = () => window.SIM && (window.SIM.PF || (window.__pf && window.__pf.PF));
const stream = () => window.__lidarStream;
let engine = null, stn = null, source = null, loadErr = null, built = null, seq = null, ride = null, cap = null, layerAdded = false, rg = null;
// ---- lifted from web/explore.mjs @ 79e0bd8 line 22: point at distance d along a route r = { points, lengths, length } ----
const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
const lerp = (a, b, t) => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t];
function routeAt(r, d) { d = clamp(d, 0, r.length); let i = 1; while (i < r.lengths.length - 1 && r.lengths[i] < d) i++; return lerp(r.points[i - 1], r.points[i], (d - r.lengths[i - 1]) / (r.lengths[i] - r.lengths[i - 1])); }
// ---- lifted from web/explore.mjs @ 79e0bd8 line 41, mode 'cable': eye 1.7 m over the cable, looking 0.5 m ahead ----
function cableCamera(r, distance, reverse = 1) {
const p = routeAt(r, distance), q = routeAt(r, clamp(distance + reverse * 0.5, 0, r.length)); let f = [q[0] - p[0], q[1] - p[1], q[2] - p[2]];
if (Math.hypot(f[0], f[1], f[2]) < 0.001) { let i = 1; while (i < r.lengths.length - 1 && r.lengths[i] <= distance) i++; const a = r.points[i - 1], b = r.points[i]; f = [(b[0] - a[0]) * reverse, (b[1] - a[1]) * reverse, (b[2] - a[2]) * reverse]; }
return { position: [p[0], p[1], p[2] + EYE], forward: f };
}
const route = pts => { const lengths = [0]; for (let i = 1; i < pts.length; i++) lengths.push(lengths[i - 1] + Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1], pts[i][2] - pts[i - 1][2])); return { points: pts, lengths, length: lengths[lengths.length - 1] }; };
// ---- the engine, by URL (first the 0524 release, then 1853 if a same-folder import fails cross-origin) ----
async function load() {
if (engine) return engine;
for (const rel of RELEASES) {
try { engine = await import(ENGINE(rel)); stn = await import(new URL('./station.mjs', ENGINE(rel)).href); source = ENGINE(rel); return engine; }
catch (e) { loadErr = `${rel}: ${e && e.message || e}`; console.warn('[engine-lock] import failed', ENGINE(rel), e); }
}
throw new Error('engine import failed: ' + loadErr);
}
// ---- ground: measured DTM first (R5 stream), map terrain as the labelled fallback ----
const exag = () => { const m = window.SIM.map, t = m.getTerrain && m.getTerrain(); return (t && t.exaggeration) || 1; };
const elevNow = () => (window.SIM.map.transform && window.SIM.map.transform.elevation) || 0;
const rawAt = (lon, lat) => { const m = window.SIM.map; try { const v = m.queryTerrainElevation && m.queryTerrainElevation([lon, lat]); return v == null || !isFinite(v) ? 0 : v; } catch (e) { return 0; } };
const demAt = (lon, lat) => (rawAt(lon, lat) + elevNow()) / exag();
function grounds() {
const P = PF(), st = stream(), used = { measured: 0, estimated: 0, receipt: null };
const ground = (e, n) => { if (!st || !st.heightAt) return NaN; const h = st.heightAt(e, n); if (h && Number.isFinite(h.h)) { used.measured++; used.receipt = used.receipt || h.receipt; return h.h; } return NaN; };
const fallback = (e, n) => { used.estimated++; const g = P.fromBng(e, n); return demAt(g.lon, g.lat); };
return { ground, fallback, used };
}
// ---- rotation: the engine's tables run north; bearing turns the block's north axis clockwise by `bearingDeg` ----
const rot = (E, N, a) => { const c = Math.cos(a), s = Math.sin(a); return { fwd: (x, y) => [E + x * c + y * s, N - x * s + y * c], inv: (e, n) => [(e - E) * c - (n - N) * s, (e - E) * s + (n - N) * c] }; };
/** build({ e, n } | { lon, lat } | nothing = view centre; bearingDeg (default 0 = north); at: 'anchor' | 'pad' (the pad centre lands on e, n)). */
async function build(o = {}) {
const S = window.SIM, P = PF(), eng = await load();
let e = o.e, n = o.n;
if (e == null) { const c = o.lon != null ? { lng: o.lon, lat: o.lat } : S.map.getCenter(); const g = P.toBng(c.lat, c.lng); e = g.e; n = g.n; }
const bearing = (o.bearingDeg || 0) * Math.PI / 180, regroundOf = o.regroundOf || null;
// at: 'pad': the engine's station pad centre (mid of the transformers, station.mjs STATION_DEFAULTS) lands on (e, n)
const R0 = rot(e, n, bearing);
let E = e, N = n;
if (o.at === 'pad') { const pc = padCentre(); const q = R0.fwd(-pc[0], -pc[1]); E = q[0]; N = q[1]; }
const R = rot(E, N, bearing), G = grounds();
const ground = (x, y) => { const q = R.fwd(x - E, y - N); return G.ground(q[0], q[1]); }, fallback = (x, y) => { const q = R.fwd(x - E, y - N); return G.fallback(q[0], q[1]); };
const t0 = performance.now();
const b = eng.buildBlock({ anchor: [E, N], ground, fallback, stations: o.stations || 1, pocKv: o.pocKv || 132, towers: [] });
const tBuild = performance.now() - t0;
// ---- into the map: every vertex e,n -> (rotated) -> PF.fromBng (OSTN15) -> Mercator about the anchor ----
const an = P.fromBng(E, N), anchor = P.placeKey(an.lat, an.lon), o0 = P.toMercator(anchor.lat, anchor.lon, 0), base = rawAt(anchor.lon, anchor.lat) + elevNow();
const mz = P.toMercator(anchor.lat, anchor.lon, 1).z - o0.z; // metres -> Mercator z at the anchor
const groups = [], counts = {};
const bb = { e0: Infinity, n0: Infinity, e1: -Infinity, n1: -Infinity };
const toV = (x, y, h) => { const q = R.fwd(x - E, y - N), g = P.fromBng(q[0], q[1]), m = P.toMercator(g.lat, g.lon, 0); if (q[0] < bb.e0) bb.e0 = q[0]; if (q[0] > bb.e1) bb.e1 = q[0]; if (q[1] < bb.n0) bb.n0 = q[1]; if (q[1] > bb.n1) bb.n1 = q[1]; return [m.x - o0.x, m.y - o0.y, (h - base) * mz]; };
const pack = (verts) => { const out = new Float32Array(verts.length * 4); for (let k = 0; k < verts.length; k += 2) { const a = verts[k], c = verts[k + 1], L = Math.hypot((c[0] - a[0]) / mz, (c[1] - a[1]) / mz, (c[2] - a[2]) / mz); out.set([a[0], a[1], a[2], 0], 4 * k); out.set([c[0], c[1], c[2], L], 4 * k + 4); } return out; };
const unmeasured = b.summary.unmeasured || 0;
for (const [key, color, style, secs] of PLAN) {
let verts = [], marks = [];
if (b.groups[key]) { const g = b.groups[key], v = g.v, bs = g.base; for (let k = 0; k < v.length; k += 3) verts.push(toV(bs[0] + v[k], bs[1] + v[k + 1], bs[2] + v[k + 2])); marks = g.marks.slice(); }
else if (b.cables[key]) { for (const c of b.cables[key]) { for (let i = 1; i < c.points.length; i++) verts.push(toV(...c.points[i - 1]), toV(...c.points[i])); marks.push(verts.length); } }
if (!verts.length) continue;
if (marks.length === 0 || marks[marks.length - 1] < verts.length) marks.push(verts.length);
const st = key === 'outline' && unmeasured > 0 ? 'ghost' : style;
groups.push({ key, color, style: STYLE[st], styleName: st, secs, data: pack(verts), n: verts.length, marks, draw: 0, glbuf: null });
counts[key] = verts.length / 2;
}
// walk-fps collision: the table frames as plain local lines (x, y east/north metres about the anchor, z above the anchor ground)
const lines = []; { const g = b.groups.tables, v = g.v, bs = g.base; for (let k = 0; k + 5 < v.length; k += 6) { const a = P.toLocal(anchor, ...ll(P, R, E, N, bs[0] + v[k], bs[1] + v[k + 1]), 0), c = P.toLocal(anchor, ...ll(P, R, E, N, bs[0] + v[k + 3], bs[1] + v[k + 4]), 0); lines.push([a.x, a.y, bs[2] + v[k + 2] - base, c.x, c.y, bs[2] + v[k + 5] - base]); } }
if (built) { S.removeWhere(x => x.engineLock); freeBuffers(); }
S.addBlock({ lon: anchor.lon, lat: anchor.lat, anchor, lines, buf: new Float32Array(0), engineLock: true, prov: unmeasured ? 'estimated' : 'measured' });
const routes = { ac: b.cables.ac.map(c => ({ id: c.id, r: route(c.points.map(p => { const q = R.fwd(p[0] - E, p[1] - N); return [q[0], q[1], p[2]]; })) })),
dc: b.cables.dc.map(c => route(c.points.map(p => { const q = R.fwd(p[0] - E, p[1] - N); return [q[0], q[1], p[2]]; }))),
mv: b.cables.mv.map(c => route(c.points.map(p => { const q = R.fwd(p[0] - E, p[1] - N); return [q[0], q[1], p[2]]; }))) };
built = { E, N, bearingDeg: o.bearingDeg || 0, anchor, base, mz, o0, groups, counts, routes, block: b, unmeasured, used: G.used, tBuild, pulse: null, pulseOn: false, dz: 0,
bbox: bb, tiles: tilesTouched(bb), at: o.at || 'anchor', rebuilt: regroundOf ? regroundOf.rebuilt + 1 : 0, opts: { stations: o.stations, pocKv: o.pocKv } };
ensureLayer(); S.repaint();
if (regroundOf && seq && !seq.done) { /* the running sequence keeps its place: step() sets every draw next frame */ }
else if (o.animate !== false && !regroundOf) sequence(); else { for (const g of groups) g.draw = g.n; built.pulseOn = true; }
caption(); if (!regroundOf) reground(); return state();
}
const ll = (P, R, E, N, e, n) => { const q = R.fwd(e - E, n - N), g = P.fromBng(q[0], q[1]); return [g.lat, g.lon]; };
// ---- re-grounding: the R5 tiles the block's bounding box touches, arrivals stepped one at a time, rebuild when measured ----
function tilesTouched(bb) {
const st = stream(), R5 = st && st.R5 && st.R5(); if (!R5 || !isFinite(bb.e0)) return [];
const out = new Map(); const T = R5.TILE_M || 2048;
for (let e = Math.floor(bb.e0 / T) * T; e <= bb.e1; e += T) for (let n = Math.floor(bb.n0 / T) * T; n <= bb.n1; n += T) { const t = R5.tileOf(e + 1, n + 1); out.set(t.key, t); }
return [...out.values()];
}
const tileState = t => { const st = stream(), x = st && st.tiles && st.tiles.get(t.key), r = x && x.dtm; return !x ? 'unasked' : !r ? 'asked' : r.pending ? 'pending' : r.none ? 'none' : r.failed ? 'failed' : 'measured'; };
// lidar-stream's arrive(why) reads the view centre only; until it takes {e, n}, the centre is answered for that one
// synchronous call and restored at once. The view never moves. (Request to the lidar-stream module: arrive(why, {e, n}).)
function arriveAt(t, why) {
const st = stream(), S = window.SIM, P = PF(); if (!st || !st.arrive) return null;
const g = P.fromBng(t.e0 + 1024, t.n0 + 1024), orig = S.map.getCenter;
S.map.getCenter = () => ({ lng: g.lon, lat: g.lat });
try { return st.arrive(why); } catch (e) { return null; } finally { S.map.getCenter = orig; }
}
function reground() {
if (rg) { clearInterval(rg.timer); rg = null; }
if (!built || !stream()) return;
const home = built.tiles.find(t => t.key === viewTile()) || null;
rg = { asked: new Set(), timer: 0, done: false, was: Object.fromEntries(built.tiles.map(t => [t.key, tileState(t)])), homeRestored: false };
const tick = () => {
if (!built || !stream()) { clearInterval(rg.timer); rg = null; return; }
const states = Object.fromEntries(built.tiles.map(t => [t.key, tileState(t)]));
// any tile newly measured since the last build: rebuild at the same E, N and bearing, the sequence keeps its place
if (built.unmeasured > 0 && built.tiles.some(t => states[t.key] === 'measured' && rg.was[t.key] !== 'measured')) {
rg.was = states; rebuildSame().catch(e => console.warn('[engine-lock] reground rebuild failed', e)); return;
}
rg.was = states;
const open = built.tiles.filter(t => ['unasked', 'asked', 'pending'].includes(states[t.key]));
if (!open.length) { // every touched tile resolved: give the stream back its own view-centre tile, then stop
if (home && !rg.homeRestored && stream().arrive && built.tiles.length > 1) { rg.homeRestored = true; try { stream().arrive('Build here (re-grounded)'); } catch (e) { /* stream off */ } }
clearInterval(rg.timer); rg.done = true; caption(); return;
}
const busy = open.some(t => states[t.key] !== 'unasked'); // one arrival at a time: the stream paces the gap
if (!busy) { const next = open.find(t => states[t.key] === 'unasked'); if (next && !rg.asked.has(next.key)) { rg.asked.add(next.key); arriveAt(next, 'Build here (neighbour tile)'); } }
if (built.unmeasured > 0) caption();
};
rg.timer = setInterval(tick, 1000); tick();
}
const viewTile = () => { const st = stream(), R5 = st && st.R5 && st.R5(), P = PF(); if (!R5) return null; const c = window.SIM.map.getCenter(), g = P.toBng(c.lat, c.lng); return R5.tileOf(g.e, g.n).key; };
async function rebuildSame() { if (!built) return null; const b = built, fp = b.at === 'pad' ? footprints() : null; return build({ e: fp ? fp.pad.e : b.E, n: fp ? fp.pad.n : b.N, at: b.at, bearingDeg: b.bearingDeg, stations: b.opts.stations, pocKv: b.opts.pocKv, animate: false, regroundOf: b }); }
function freeBuffers() { const gl = layer.gl; if (!gl || !built) return; for (const g of built.groups) if (g.glbuf) { try { gl.deleteBuffer(g.glbuf); } catch (e) { /* context lost */ } g.glbuf = null; } }
function padCentre() { const s = stn && stn.STATION_DEFAULTS; if (s && s.transformers) { const xs = s.transformers.map(p => p[0]), ys = s.transformers.map(p => p[1]); return [(Math.min(...xs) + Math.max(...xs)) / 2, (Math.min(...ys) + Math.max(...ys)) / 2]; } return [155, 332.5]; }
// ---- the build sequence: marks[] prefixes over about 20 s, group by group; then the pulses ----
function sequence(ms = SEQ_MS) {
if (!built) return; if (seq) cancelAnimationFrame(seq.raf);
const total = built.groups.reduce((s, g) => s + g.secs, 0) || 1, t0 = performance.now();
for (const g of built.groups) g.draw = 0; built.pulseOn = false;
const step = now => {
const t = Math.min(1, (now - t0) / ms); let acc = 0, label = '';
for (const g of built.groups) {
const f0 = acc / total, f1 = (acc + g.secs) / total; acc += g.secs;
if (g.secs === 0) { g.draw = t >= 1 ? g.n : 0; continue; }
const f = clamp((t - f0) / (f1 - f0), 0, 1), i = Math.min(g.marks.length, Math.floor(f * g.marks.length + 1e-9));
g.draw = f >= 1 ? g.n : i > 0 ? g.marks[i - 1] : 0; if (f > 0 && f < 1) label = `${g.key} ${i} of ${g.marks.length}`;
}
seq.t = t; window.SIM.repaint(); if (label) caption(`building: ${label} (${Math.round(t * 100)} %)${groundNote()}`);
if (t < 1) seq.raf = requestAnimationFrame(step); else { seq.done = true; built.pulseOn = true; caption(); }
};
seq = { t: 0, done: false, raf: requestAnimationFrame(step) };
}
// ---- own layer: static VBOs, style cut in the fragment shader by distance along the segment (metres) ----
const layer = {
id: 'engine-lock-wire', type: 'custom', renderingMode: '3d',
onAdd(m, gl) {
const vs = 'uniform mat4 u; uniform float u_dz; attribute vec4 p; varying float v_d; void main(){ gl_Position = u * vec4(p.xy, p.z + u_dz, 1.0); v_d = p.w; }';
const fs = 'precision mediump float; uniform vec4 c; uniform int s; varying float v_d; void main(){ if (s == 1 && fract(v_d / 2.0) > 0.7) discard; if (s == 2 && fract(v_d / 0.6) > 0.35) discard; gl_FragColor = c; }';
const sh = (t, src) => { const o = gl.createShader(t); gl.shaderSource(o, src); gl.compileShader(o); return o; };
this.pr = gl.createProgram(); gl.attachShader(this.pr, sh(gl.VERTEX_SHADER, vs)); gl.attachShader(this.pr, sh(gl.FRAGMENT_SHADER, fs)); gl.linkProgram(this.pr);
this.loc = { p: gl.getAttribLocation(this.pr, 'p'), u: gl.getUniformLocation(this.pr, 'u'), dz: gl.getUniformLocation(this.pr, 'u_dz'), c: gl.getUniformLocation(this.pr, 'c'), s: gl.getUniformLocation(this.pr, 's') };
this.pulseBuf = gl.createBuffer(); this.gl = gl; if (built) for (const g of built.groups) g.glbuf = null;
},
render(gl, args) {
if (!built) return; const S = window.SIM, P = PF(), m = args.defaultProjectionData?.mainMatrix || args, a = built.anchor;
const o = P.toMercator(a.lat, a.lon, rawAt(a.lon, a.lat)), r = Array.from(m);
for (let k = 0; k < 4; k++) r[12 + k] = m[k] * o.x + m[4 + k] * o.y + m[8 + k] * o.z + m[12 + k];
const dz = (built.base - (rawAt(a.lon, a.lat) + elevNow())) * built.mz; // terrain tiles loading after the build: keep the vertices at their own heights
gl.useProgram(this.pr); gl.enable(gl.DEPTH_TEST); gl.enable(gl.BLEND); gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
gl.uniformMatrix4fv(this.loc.u, false, new Float32Array(r)); gl.uniform1f(this.loc.dz, dz);
for (const g of built.groups) {
if (!g.draw) continue;
if (!g.glbuf) { g.glbuf = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, g.glbuf); gl.bufferData(gl.ARRAY_BUFFER, g.data, gl.STATIC_DRAW); }
gl.bindBuffer(gl.ARRAY_BUFFER, g.glbuf); gl.enableVertexAttribArray(this.loc.p); gl.vertexAttribPointer(this.loc.p, 4, gl.FLOAT, false, 16, 0);
gl.uniform4fv(this.loc.c, g.color); gl.uniform1i(this.loc.s, g.style); gl.drawArrays(gl.LINES, 0, g.draw);
}
if (built.pulseOn) {
const pulse = pulses(performance.now()); built.pulse = pulse.length / 8;
gl.bindBuffer(gl.ARRAY_BUFFER, this.pulseBuf); gl.bufferData(gl.ARRAY_BUFFER, pulse, gl.DYNAMIC_DRAW);
gl.enableVertexAttribArray(this.loc.p); gl.vertexAttribPointer(this.loc.p, 4, gl.FLOAT, false, 16, 0);
gl.disable(gl.DEPTH_TEST); gl.uniform4fv(this.loc.c, [1.0, 1.0, 0.6, 1.0]); gl.uniform1i(this.loc.s, 0); gl.drawArrays(gl.LINES, 0, pulse.length / 4);
S.repaint();
}
}
};
// cable-flow pulses (web/explore.mjs @ 79e0bd8 line 42, inverterMode): one 0.6 m bright dash per route, phase by route index
function pulses(now) {
const P = PF(), o0 = built.o0, mz = built.mz, all = [...built.routes.dc, ...built.routes.ac.map(x => x.r), ...built.routes.mv], out = new Float32Array(all.length * 8);
all.forEach((r, i) => {
const f = (now / 6000 + i * 0.037) % 1, d = (i % 2 ? 1 - f : f) * r.length, a = routeAt(r, d), b = routeAt(r, Math.min(r.length, d + 0.6));
const ga = P.fromBng(a[0], a[1]), gb = P.fromBng(b[0], b[1]), ma = P.toMercator(ga.lat, ga.lon, 0), mb = P.toMercator(gb.lat, gb.lon, 0);
out.set([ma.x - o0.x, ma.y - o0.y, (a[2] - built.base) * mz, 0, mb.x - o0.x, mb.y - o0.y, (b[2] - built.base) * mz, 0.6], 8 * i);
});
return out;
}
function ensureLayer() { const map = window.SIM.map; if (!map.getLayer(layer.id)) { try { map.addLayer(layer); layerAdded = true; } catch (e) { /* style not ready */ } } }
// ---- walk a cable: eye height along a selected AC phase cable, driving walk-fps (or the map camera) ----
function walkCable(i, reverse = 1) {
if (!built) return null; const P = PF(), S = window.SIM, n = built.routes.ac.length; if (!n) return null;
if (i == null) { const c = S.map.getCenter(), g = P.toBng(c.lat, c.lng); let best = 0, bd = Infinity; built.routes.ac.forEach((x, k) => { const p = x.r.points[0], d = Math.hypot(p[0] - g.e, p[1] - g.n); if (d < bd) { bd = d; best = k; } }); i = best; }
i = ((i % n) + n) % n; stopRide(); const r = built.routes.ac[i].r;
if (window.walkFps) { try { if (!window.walkFps.state().on) window.walkFps.enter(); } catch (e) { /* walk-fps not ready */ } }
const t0 = performance.now(); ride = { i, id: built.routes.ac[i].id, d: reverse > 0 ? 0 : r.length, raf: 0, reverse, done: false, r };
const step = now => {
const dt = Math.min(0.05, (now - (ride.last || now)) / 1000); ride.last = now; ride.d = clamp(ride.d + reverse * RIDE_MPS * dt, 0, r.length);
const cam = cableCamera(r, ride.d, reverse), g = P.fromBng(cam.position[0], cam.position[1]), yaw = Math.atan2(cam.forward[0], cam.forward[1]) * 180 / Math.PI;
if (window.walkFps && window.walkFps.state().on) window.walkFps.set({ lon: g.lon, lat: g.lat, yaw, pitch: 84 });
else S.map.jumpTo({ center: [g.lon, g.lat], zoom: 20.5, bearing: yaw, pitch: 80 });
ride.lon = g.lon; ride.lat = g.lat; ride.yaw = yaw; ride.z = cam.position[2];
caption(`walking AC cable ${ride.id}: ${ride.d.toFixed(1)} of ${r.length.toFixed(1)} m, eye ${EYE} m over the cable (route and trench depth documented, drawn dashed)`);
if ((reverse > 0 && ride.d < r.length) || (reverse < 0 && ride.d > 0)) ride.raf = requestAnimationFrame(step); else { ride.done = true; caption(`end of AC cable ${ride.id} (${r.length.toFixed(1)} m in ${((now - t0) / 1000).toFixed(1)} s)`); }
};
ride.raf = requestAnimationFrame(step); return { i, id: ride.id, length: r.length };
}
function stopRide() { if (ride && ride.raf) cancelAnimationFrame(ride.raf); ride = null; }
function stop() { stopRide(); if (seq) cancelAnimationFrame(seq.raf); seq = null; if (rg) { clearInterval(rg.timer); rg = null; } if (built) { window.SIM.removeWhere(x => x.engineLock); freeBuffers(); built = null; } caption(''); window.SIM.repaint(); }
// ---- captions: measured / estimated ground, counts, source ----
// the ground state in a few words while the sequence plays (F3 wording: never "no measured LiDAR here yet" once a tile is in)
function groundNote() {
if (!built) return ''; const u = built.used;
if (!u.estimated) return built.rebuilt ? ' · ground measured, re-grounded' : '';
if (u.measured) return ` · ${u.estimated} of ${u.measured + u.estimated} samples estimated (outside the streamed tile)`;
return rg && !rg.done ? ' · waiting for measured ground (R5 gap)' : ' · ground estimated (measured ground not streamed here)';
}
function caption(t) {
if (!cap) { cap = document.createElement('div'); cap.id = 'engine-lock-caption'; cap.style.cssText = 'position:absolute;left:50%;transform:translateX(-50%);top:58px;z-index:7;background:rgba(0,0,0,.75);color:#fff;font:12px sans-serif;padding:4px 10px;border-radius:4px;max-width:92vw;pointer-events:none'; document.body.appendChild(cap); }
if (t == null && built) {
const u = built.used, tot = u.measured + u.estimated, c = built.counts, s = built.block.summary;
t = `10 MVA block (the site-world engine, by URL, release ${(source || '').match(/(\d{12})/)?.[1] || '?'}) at E ${built.E.toFixed(1)} N ${built.N.toFixed(1)}, rows ${built.bearingDeg.toFixed(2)}° from grid north. ` +
(!u.estimated ? `ground: ${tot} samples MEASURED (EA LiDAR 1 m, receipt ${u.receipt || '?'}), solid${built.rebuilt ? ', re-grounded after the tile arrived' : ''}. `
: u.measured ? `ground: ${u.estimated} of ${tot} samples estimated (outside the streamed tile), ${u.measured} measured (receipt ${u.receipt || '?'}): ground contact drawn ghost${rg && !rg.done ? '; neighbour tile streaming (R5 gap)' : ''}. `
: `ground: all ${tot} samples ESTIMATED from the map terrain, ground contact drawn ghost: ${rg && !rg.done ? 'waiting for measured ground (R5 gap)' : 'measured ground not streamed here'}. `) +
`equipment ghost (assumed design), cables dashed (documented routes): ${c.tables / 2 | 0} table segments, ${(built.routes.dc.length)} DC and ${built.routes.ac.length} AC cables, piles ${s.piles.min.toFixed(1)} to ${s.piles.max.toFixed(1)} m` + (built.pulseOn ? ', cable flow pulsing' : '');
}
cap.textContent = t || ''; cap.style.display = t ? 'block' : 'none';
}
// ---- footprints for the lock test: every table face as a BNG rectangle with its OSTN15 lon/lat corners ----
function footprints() {
if (!built) return null; const P = PF(), b = built.block, eng = stn, s = eng.STATION_DEFAULTS, T = eng.tableShape ? eng.tableShape(s) : null;
const R = rot(built.E, built.N, built.bearingDeg * Math.PI / 180), out = [];
const corner = (x, y) => { const q = R.fwd(x, y), g = P.fromBng(q[0], q[1]); return { e: q[0], n: q[1], lat: g.lat, lon: g.lon }; };
if (T && eng.tableOrigin) for (let k = 0; k < s.tables; k++) { const [x0, y0] = eng.tableOrigin(k, s); for (const side of [-1, 1]) { const xa = x0 + side * T.halfRidgeGap, xb = x0 + side * (T.halfRidgeGap + T.depth); out.push({ table: k, side, corners: [corner(xa, y0), corner(xb, y0), corner(xb, y0 + T.span), corner(xa, y0 + T.span)] }); } }
const pc = padCentre(), pq = R.fwd(pc[0], pc[1]), pg = P.fromBng(pq[0], pq[1]), st = stream(), h = st && st.heightAt ? st.heightAt(pq[0], pq[1]) : null;
return { anchor: { e: built.E, n: built.N, lat: built.anchor.lat, lon: built.anchor.lon }, bearingDeg: built.bearingDeg, tables: out, table: T, source,
pad: { e: pq[0], n: pq[1], lat: pg.lat, lon: pg.lon, levelEngine: b.pads[0] && b.pads[0].level, measured: h && h.h, receipt: h && h.receipt, mapTerrain: demAt(pg.lon, pg.lat), cut: b.pads[0] && b.pads[0].cut, fill: b.pads[0] && b.pads[0].fill, unmeasuredPad: b.pads[0] && b.pads[0].unmeasured },
ground: built.used, unmeasured: built.unmeasured, pf: P.toBng(pg.lat, pg.lon) };
}
function state() {
return { source, loadErr, built: !!built, E: built && built.E, N: built && built.N, bearingDeg: built && built.bearingDeg, counts: built && built.counts, unmeasured: built && built.unmeasured, used: built && built.used,
tBuildMs: built && built.tBuild, seq: seq && { t: seq.t, done: seq.done }, pulse: built && built.pulseOn ? built.pulse : 0, ride: ride && { i: ride.i, id: ride.id, d: ride.d, done: ride.done, lon: ride.lon, lat: ride.lat, yaw: ride.yaw },
routes: built && { dc: built.routes.dc.length, ac: built.routes.ac.length, mv: built.routes.mv.length }, layer: !!(window.SIM.map.getLayer && window.SIM.map.getLayer(layer.id)),
styles: built && Object.fromEntries(built.groups.map(g => [g.key, g.styleName])),
tiles: built && built.tiles.map(t => ({ key: t.key, state: tileState(t) })), regrounding: !!(rg && !rg.done), rebuilt: built && built.rebuilt, bbox: built && built.bbox };
}
// ---- menu: File > Build here (animated), View > Walk a cable (into the menu panels; Scope > More if the bar has no menu) ----
function menu() {
const S = window.SIM, mk = (label, fn, title) => { const b = document.createElement('button'); b.textContent = label; b.title = title; b.addEventListener('click', fn); return b; };
const b1 = mk('Build here (animated)', () => { const st = stream(); if (st && st.arrive) try { st.arrive('Build here (animated)'); } catch (e) { /* stream off */ } build().catch(e => caption('engine: ' + (e.message || e))); }, 'The site-world 10 MVA block at the view centre on the measured ground, built over 20 s, then the cable flow');
const b2 = mk('Walk a cable', () => { if (!built) { caption('build a block first (File > Build here (animated))'); return; } if (ride && !ride.done) stopRide(); else walkCable(ride ? ride.i + 1 : null); }, 'Ride an AC phase cable at eye height (again: the next cable)');
const panel = t => document.querySelector(`.gm-panel[data-menu="${t}"]`);
if (panel('File') && panel('View')) { panel('File').appendChild(b1); panel('View').appendChild(b2); }
else { S.addButton(b1.textContent, () => b1.click()); S.addButton(b2.textContent, () => b2.click()); }
S.map.on('style.load', () => setTimeout(() => { if (built) { for (const g of built.groups) g.glbuf = null; ensureLayer(); } }, 80));
document.addEventListener('keydown', e => { if (e.key === 'Escape' && ride) stopRide(); });
}
function wait(n) { if (window.SIM && window.SIM.map && PF() && (document.getElementById('sim-menu') || n > 60)) { menu(); window.SIM.engineLock = { build, state, footprints, walkCable, stop, sequence, load, routeAt, cableCamera, releases: RELEASES }; } else if (n < 400) setTimeout(() => wait(n + 1), 50); }
wait(0);
})();Block Build
A JavaScript module in the engine folder of Energy Transition Simulator that works with cables, transformers, overhead lines (OHL) and substations.
Set aside from the main view: 99% of its lines are the same as energy-transition-simulator/202609280014/mod/engine/block-build.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 99% of lines shared with Block Build; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.9905 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 energy-transition-simulator/202609280014/mod/engine/block-build.mjs:1-255 c7a3ec963c02f85ebf017a6c1b0d2f41f50a86ae
- sha256 5b7e718361566835584bb7c74a99c8f159440da0f2fe9d24b38bf0ffc43e17e9
- target sha256 6b97468bff7254b4636652419cae690165c1fd58ad0bc28e59d72d22719d6d3b
- group of 3 (identity.json near-copy edges >= 0.9)
- canonical rule: reachable, newest stamp, core repo, most lines
transformenergy-transition-simulator / prototype/mod/engine/block-build.mjs · lines 1–255 of 255 · Not reached from any entry point (candidate for review) · pattern pileTotals (shared by 3 files)
- What it does
- It calculates cables, transformers, overhead lines (OHL) and substations. Defines 25 functions or classes, including group, put, seg, poly, mark.
- Why it exists in the grid workflow
- Domain stage experimental (path word 'prototype'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: cables, transformers, overhead lines (OHL), substations, 33kV.
- Inputs & outputs
- Voltage levels named: 33kV.
- 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 10 MVA, 33 kV and 5 MVA.
- Why it matters
- No other file in the estate was found to import it.
- Application
- energy-transition-simulator · prototype/mod/engine · JavaScript module
- Uses
- Station (import), Block MV (import), Cable Rating (import), MV Network (import), Piles (import), Pile Rules (import), Block Trenches (import)
- Used by
- mentioned in Standalone (comment link)
- Produces
- padEarthworks, buildBlock, overheadClearance, blockCounts
- Defines here
- group, put, seg, poly, mark, box, median, pileTotals, padEarthworks, buildBlock, g, zLocal, baseOf, onTable, gq, at, edge, at, padOf, buried, lift, odMv, overheadClearance, blockCounts, inside
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- energy-transition-simulator@a165ce6d56cb22271828874d68d570e8fa5e428a prototype/mod/engine/block-build.mjs:1-255 · blob e370d93df21445a1f9995ef6d32be798e6a4468b · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: experimental · users: none · canonical: duplicate_candidate
// COPIED UNCHANGED from the v12 world (web/world/block-build.mjs) at v12 commit 3adcee9 (file last changed 604729d). Modular star family: public #146332 padEarthworks.
// Do not edit here: change the source and re-copy. Everything below this header is byte-identical to the source.
// 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';
import { planPiles } from './piles.mjs';
import { PILE_RULES as PR, revealBand } from './pile-rules.mjs';
import { blockTrenches, BLOCK_DC_ISC_A } from './block-trenches.mjs';
export { BLOCK_DC_ISC_A };
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; };
// The block's pile totals for the readout and the bill (embedment provisional).
const pileTotals = P => ({ revealAdjust: P.summary.revealAdjust, outsideBand: P.summary.revealHigh + P.summary.revealLow,
twistTables: P.summary.twistTables, gradingTables: P.summary.tablesNeedingGrading, cutM3: P.summary.cutM3, fillM3: P.summary.fillM3,
totalPileLengthM: P.summary.totalPileLengthM, embeddedM: P.piles.reduce((t, p) => t + p.embed, 0), embedM: P.assumed.embedMin,
revealAdjustM: P.assumed.revealAdjust, twistTolDeg: P.assumed.twistTolDeg });
/** 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, trench }) -> { groups, cables, trenches, summary }
* towers: [{ e, n, kv }] grid towers to connect to; gpuPads: [{ poly: [[e, n]...], level, cut, fill }] optional.
* trench: { soilKmW, load, split: { dc, branch, collector, mv }, cover: { dc, lv, mv }, drumM, ring } for sizing the trenches by rating
* (block-trenches.mjs); defaults when left out.
*/
export function buildBlock({ anchor, ground, fallback = () => NaN, stations = 4, pocKv = 400, towers = [], gpuPads = [], topology = 'radial',
connection = 'cable', modulesPerString = SD.modulesPerString, trench = {} }) {
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; };
// Modules in series are the owner's to change: each table row keeps its three strings, so the table is 3 strings long.
const mps = Math.round(modulesPerString) || SD.modulesPerString, s = { ...SD, modulesPerString: mps, columns: mps * SD.columns / SD.modulesPerString };
const st = station(s, { corners: false }), T = tableShape(s), t = s.tilt * Math.PI / 180;
const mv = mvChain({ stations, stationMVA: st.inventory.aggregateInverterMVA, pocKv, topology });
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)];
// Piles, automatic, on the shared rules (pile-rules.mjs): each post line under the owner's frame, its tops where the
// frame puts them, checked for reveal (band and head adjustment), grading, embedment and twist by piles.mjs.
const gq = (e, n) => { const h = ground(e, n); if (Number.isFinite(h)) return h; const f = fallback(e, n); return Number.isFinite(f) ? f : 0; };
const pileRows = [];
frames.forEach((F, n) => { for (const side of [-1, 1]) [0.2, 0.8].forEach((k, j) => {
const x = side * (T.halfRidgeGap + T.depth * k), top = y => baseOf(n, y) + zLocal(x) - 0.12, id = `${n}:${side}:${j}`;
pileRows.push({ id, line: [[E + F.x0 + x, N + F.ys[0]], [E + F.x0 + x, N + F.ys[PILE_LINES - 1]]], tops: F.ys.map(top),
reveal: revealBand(zLocal(x) - 0.12), ...(j ? {} : { pair: { with: `${n}:${side}:1`, depth: T.depth * 0.6 } }) });
}); });
const plan = planPiles({ rows: pileRows, groundAt: gq, system: 'fixed', tableLength: T.span, tableGap: 0, pileSpacing: T.span / (PILE_LINES - 1) * (1 - 1e-12),
embedMin: PR.embedM, embedToReveal: PR.embedToReveal, gradingWidth: PR.gradingWidthM, revealAdjust: PR.revealAdjustM, twistTolDeg: PR.twistTolDeg, limits: { along: 'ns' } });
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 j of [0, 1]) for (const p of plan.rows.find(r => r.id === `${n}:${side}:${j}`).tables[0].piles) { // front, rear posts
g(p.x, p.y); seg(G.tables, [p.x, p.y, Math.min(p.ground, p.finishedGround)], [p.x, p.y, p.top]);
piles.count++; piles.min = Math.min(piles.min, p.reveal); piles.max = Math.max(piles.max, p.reveal);
}
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), s).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.filter(x => x.openAt)) { 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 (line tee as an option) ----
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);
// The HV connection runs as a fully ducted cable: down from the transformer, buried, and up the connection structure.
for (const [x, y] of mv.grid.at) poly(G.grid, [[E + x + gt.w / 2, N + y, cz + gt.h - 1], [E + x + gt.w / 2, N + y, cz - 1.1], [P[0], P[1], cz - 1.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;
// The default landing is a ducted HV cable to the substation's bay (drawn by the single-line diagram, sld-symbols.mjs);
// the overhead tee into the nearest tower is an option, off by default.
if (connection === 'ohl-tee' && 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 works = blockTrenches(st, mv, E, N, odMv, trench, s), trenches = works.items;
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, trenchPlan: works.plan, mv, station: st, pads, compoundPad: cpad, connection: line, onTable, // onTable: module detail
summary: { inventory: inv, blockKwp: inv.installedModules * s.moduleW / 1000, piles: { ...piles, ...pileTotals(plan) }, 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;
};Block MV
A JavaScript module in the engine folder of Energy Transition Simulator that works with transformers, solar and cables, using IEC 60287 and IEC 60949.
Set aside from the main view: 98% of its lines are the same as solar-design-studio/202609271552-site-world/world/block-mv.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 98% of lines shared with Block MV; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.9833 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271552-site-world/world/block-mv.mjs:1-137 6284ee02b77ded0ed6310420eede0bfcc7655201
- sha256 4fd4d5658c4f9b473c91e769a5540c96b9b9139499bbd9f423b05daaeade8198
- target sha256 77dbdded292674617c48d7542de515b7f59b3f735fd54af1f6638dcd857f0232
- group of 3 (identity.json near-copy edges >= 0.9)
- canonical rule: reachable, newest stamp, core repo, most lines
transformenergy-transition-simulator / prototype/mod/engine/block-mv.mjs · lines 1–139 of 139 · Not reached from any entry point (candidate for review) · pattern dropWith (shared by 4 files)
- What it does
- It calculates transformers, solar and cables. Defines 12 functions or classes, including mvChain, colX, up, path, groupOf.
- Why it exists in the grid workflow
- Domain stage experimental (path word 'prototype'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: transformers, solar, cables, 400kV, 33kV.
- Inputs & outputs
- Voltage levels named: 400kV, 33kV.
- Downstream impact
- Used directly by 2 files: Cmd Trench (energy-transition-simulator); Block Build (energy-transition-simulator).
- 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 feeders 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 Cmd Trench and Block Build.
- Application
- energy-transition-simulator · prototype/mod/engine · JavaScript module
- Uses
- Cable Rating (import), Plant Template (import), Plant Feeders (import), Single-Line Diagram (SLD) Rules (import)
- Used by
- imported by Cmd Trench (import), imported by Block Build (import)
- Produces
- MV_LAYOUT, mvChain
- Defines here
- mvChain, colX, up, path, groupOf, size, drop, 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
- energy-transition-simulator@a165ce6d56cb22271828874d68d570e8fa5e428a prototype/mod/engine/block-mv.mjs:1-139 · blob 166e6b6341f26d29c184b1ded4dbbc343e09e70a · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: experimental · users: none · canonical: duplicate_candidate
// COPIED UNCHANGED from the v12 world (web/world/block-mv.mjs) at v12 commit 3adcee9 (file last changed 256ecf8). Modular star family: public #146351 mvChain.
// Do not edit here: change the source and re-copy. Everything below this header is byte-identical to the source.
// block-mv.mjs: stations of the solar block chained on 33 kV feeders 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. By default each
// feeder is a radial chain: it leaves one board section and runs station to station. With topology 'ring' it 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, and each hop is rated with the group factor of the circuits it shares a line with.
// Sizing (plant-template.mjs rules): stations per feeder from the feeder limit; radial segments from the load they
// carry; a ring's segments carry 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';
import { groupFactor } from './sld-rules.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, topology = 'radial', 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;
};
// Feeders: as many stations as the feeder limit allows (at most 4), in column order. Radial chains by default
// (board, then station to station); topology 'ring' returns each chain to the board with one normally-open hop.
const per = Math.max(1, Math.min(p.stationsPerFeederMax, Math.floor(p.feederLimitMVA / stationMVA)));
const nRings = Math.ceil(n / per), rings = [], ring = topology === 'ring';
const opt = { soilKmW: p.soilKmW, kv: 33, pf: p.powerFactor }, minArea = faultMinArea(p.faultKA, p.faultS);
const plans = [];
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, ...(ring ? ['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) });
}
plans.push({ chain, hops, m });
}
// Shared-trench heating: a hop is rated with the group factor of the most circuits it shares a line with.
const onLine = new Map();
for (const { hops } of plans) for (const h of hops) for (const key of new Set(h.parts.map(q => q.key))) onLine.set(key, (onLine.get(key) || 0) + 1);
const groupOf = h => groupFactor(Math.max(1, ...h.parts.map(q => onLine.get(q.key) || 1)));
plans.forEach(({ chain, hops, m }, k) => {
const load = chain.reduce((t, s) => t + s.mva, 0);
const size = (mva, h) => (sizeFor(mva / p.maxUtilisation, { ...opt, minArea, groupFactor: groupOf(h) }) || { area: SIZES.at(-1) });
if (!ring) { // radial: each segment sized from the load it carries
hops.forEach((h, i) => { h.loadMVA = chain.slice(i).reduce((u, s) => u + s.mva, 0); h.areaMm2 = size(h.loadMVA, h).area; h.group = groupOf(h); });
const drop = () => hops.reduce((t, h) => t + dropPercent(h.areaMm2, h.lengthM, h.loadMVA, opt), 0);
for (let guard = 0; drop() > p.vdropLimitPct && guard < 60; guard++) {
const can = hops.filter(h => h.areaMm2 < SIZES.at(-1)).sort((a, b) => b.loadMVA * b.lengthM - a.loadMVA * a.lengthM)[0];
if (!can) break;
can.areaMm2 = SIZES[SIZES.indexOf(can.areaMm2) + 1];
}
rings.push({ id: `F${k + 1}`, topology: 'radial', stations: chain.map(s => s.id), hops, open: -1, openAt: null, loadMVA: load,
areaMm2: Math.max(...hops.map(h => h.areaMm2)), carries: null, dropPct: drop(), outageDropPct: null });
return;
}
const open = Math.ceil(m / 2); // the hop left open: the middle of the ring
const pick = size(load, hops.reduce((a, b) => (groupOf(b) < groupOf(a) ? b : a)));
let area = pick.area;
// 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);
for (const h of hops) { h.areaMm2 = area; h.group = groupOf(h); }
rings.push({ id: `F${k + 1}`, topology: 'ring', 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.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 = r.topology === 'ring' ? `MVB${((k + (sections > 1 ? 1 : 0)) % sections) + 1}` : r.boardA; });
// 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: h.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.' };
}