In this section
- Tour transform · globalgrid2050 / solar-design-studio/202609270439-site-world/world/tour.mjs lines 1–291
- Block MV transform · globalgrid2050 / solar-design-studio/202609271552-site-world/world/block-mv.mjs lines 1–137
- Cmd Anim render · globalgrid2050 / solar-design-studio/202609271552-site-world/world/cmd-anim.mjs lines 1–158
Tour
A JavaScript module in the world folder of GlobalGrid2050 that creates recorder (`createRecorder`) and player (`createPlayer`), using SHA-256. It creates recorder (`createRecorder`) and creates player (`createPlayer`).
transformglobalgrid2050 / solar-design-studio/202609270439-site-world/world/tour.mjs · lines 1–291 of 291 · version 2026-09-27 04:39 · Not reached from any entry point (candidate for review) · pattern createRecorder (shared by 2 files)
- What it does
- It calculates its inputs. Defines 24 functions or classes, including fileRefusal, mm, rad, ms, turn.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
- Inputs & outputs
- Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
- Downstream impact
- Used directly by 1 file: Project UI (globalgrid2050).
- What it achieves
- Tours: record a walk or a drone flight, play it back smoothly, save it, and present it.
- Why it matters
- Imported by Project UI.
- Application
- globalgrid2050 · solar-design-studio/202609270439-site-world/world · JavaScript module
- Uses
- Origin (import)
- Used by
- imported by Project UI (import)
- Produces
- SCHEMA, PLAY_FPS, LIMITS, fileRefusal, keyframe, createRecorder, makeTour, sha256, exportTour, importTour, compile, gridPoseAt
- Defines here
- fileRefusal, mm, rad, ms, turn, keyframe, createRecorder, push, pick, makeTour, body, sha256, exportTour, importTour, compile, hermite, gridPoseAt, at, poseAt, captionAt, createPlayer, show, draw, present
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609270439-site-world/world/tour.mjs:1-291 · blob 31c2a4f473026ce5d9fa8471f410e07dc5954fb3 · 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
// Tours: record a walk or a drone flight, play it back smoothly, save it, and present it.
// Keyframes are held in British National Grid metres ({ e, n, z }), never in local metres, so a tour
// survives any origin rebase and plays the same on any machine. Playback is a pure function of the
// tour and the time: the same tour gives the same pose at the same time, every time.
// No DOM and no randomness; the caller supplies time, the origin and the frame gate.
import { toLocal, toBng } from './origin.mjs';
export const SCHEMA = 'world.tour.v1';
export const PLAY_FPS = 30;
const KINDS = ['walk', 'drone'];
// The national grid extent. Its south-west 10 km corner is open sea, so a point there is almost
// certainly local metres given by mistake and is refused too.
const GRID = { e: [0, 700000], n: [0, 1300000], sea: 10000 };
const HEX64 = /^[0-9a-f]{64}$/;
// A phone must be able to open any tour it is given, so files and their parts are capped by name.
// seconds bounds the whole tour, holds included: playback runs the gate at 30 fps, so a tour (or a seek into one)
// can never keep the page drawing for longer than this.
export const LIMITS = Object.freeze({ fileBytes: 8 * 1024 * 1024, keyframes: 100000, caption: 280, name: 200, seconds: 4 * 3600 });
// Checked on the file's size before a byte is read: an over-size file is refused with a reason, never loaded.
export function fileRefusal(size) {
if (!Number.isFinite(size) || size < 0) return 'the file size is unknown';
return size > LIMITS.fileBytes ? `the file is ${(size / 1048576).toFixed(1)} MB, over the limit of ${LIMITS.fileBytes / 1048576} MB` : '';
}
const TOP_FIELDS = ['schema', 'kind', 'name', 'keyframes', 'sha256'];
const KEY_FIELDS = ['t', 'e', 'n', 'z', 'yaw', 'pitch', 'caption', 'hold'];
// Quantise on the way in, so a saved tour reads back as the very same numbers (whole millimetres, no float noise).
const mm = x => Math.round(x * 1e3) / 1e3;
const rad = x => Math.round(x * 1e6) / 1e6;
const ms = x => Math.round(x * 1e3) / 1e3;
const TAU = 2 * Math.PI;
const turn = (from, to) => {
const d = (to - from) % TAU;
return d > Math.PI ? d - TAU : d < -Math.PI ? d + TAU : d;
};
// ---------- keyframes ----------
// One keyframe from a local pose and the origin it was taken under. Returns grid metres.
export function keyframe(t, origin, pose, { caption = '', hold = 0 } = {}) {
const g = toBng(origin, pose.pos[0], pose.pos[1]);
const k = { t: ms(t), e: mm(g.e), n: mm(g.n), z: mm(pose.pos[2]), yaw: rad(pose.yaw), pitch: rad(pose.pitch) };
if (caption) k.caption = String(caption);
if (hold > 0) k.hold = ms(hold);
return k;
}
// Recorder. sample() is called every frame with the time in seconds since recording began;
// a keyframe is kept at most every `every` seconds. mark() pins a caption (and an optional hold)
// to a keyframe taken at that moment. stop() returns the tour.
export function createRecorder({ kind = 'walk', name = '', every = 0.25 } = {}) {
if (!KINDS.includes(kind)) throw Error(`tour kind must be one of ${KINDS.join(', ')}`);
const frames = [];
let last = null;
const push = k => {
if (frames.length && k.t <= frames[frames.length - 1].t) {
if (k.caption || k.hold) Object.assign(frames[frames.length - 1], pick(k, ['caption', 'hold']));
return;
}
frames.push(k);
};
return {
sample(t, origin, pose) {
last = { t, origin: { ...origin }, pose: { pos: [...pose.pos], yaw: pose.yaw, pitch: pose.pitch } };
if (!frames.length || t - frames[frames.length - 1].t >= every) push(keyframe(t, origin, pose));
},
mark(caption, hold = 0) {
if (!last) throw Error('nothing recorded yet to caption');
push(keyframe(last.t, last.origin, last.pose, { caption, hold }));
},
count: () => frames.length,
stop() {
if (last && frames.length && last.t > frames[frames.length - 1].t) push(keyframe(last.t, last.origin, last.pose));
return makeTour({ kind, name, keyframes: frames });
}
};
}
const pick = (o, keys) => Object.fromEntries(keys.filter(k => o[k] !== undefined).map(k => [k, o[k]]));
// Build a tour in canonical form: fixed key order, times from zero, quantised values. Throws on bad input.
export function makeTour({ kind = 'walk', name = '', keyframes }) {
if (!KINDS.includes(kind)) throw Error(`tour kind must be one of ${KINDS.join(', ')}`);
if (!Array.isArray(keyframes) || keyframes.length < 2) throw Error('a tour needs at least two keyframes');
if (keyframes.length > LIMITS.keyframes) throw Error(`a tour has ${keyframes.length} keyframes, over the limit of ${LIMITS.keyframes}`);
if (String(name).length > LIMITS.name) throw Error(`the tour name is over ${LIMITS.name} characters`);
const t0 = keyframes[0].t;
const out = keyframes.map((k, i) => {
for (const f of ['t', 'e', 'n', 'z', 'yaw', 'pitch']) {
if (!Number.isFinite(k[f])) throw Error(`keyframe ${i}: ${f} is not a finite number`);
}
if ('x' in k || 'y' in k || 'pos' in k) throw Error(`keyframe ${i}: local coordinates are not accepted; use grid e and n`);
if (k.e < GRID.e[0] || k.e > GRID.e[1] || k.n < GRID.n[0] || k.n > GRID.n[1] || (k.e < GRID.sea && k.n < GRID.sea)) {
throw Error(`keyframe ${i}: ${k.e}, ${k.n} is not on the national grid (local metres?)`);
}
if (k.hold !== undefined && !(k.hold >= 0 && Number.isFinite(k.hold))) throw Error(`keyframe ${i}: hold must be zero or more`);
if (k.caption && String(k.caption).length > LIMITS.caption) throw Error(`keyframe ${i}: caption is over ${LIMITS.caption} characters`);
const c = { t: ms(k.t - t0), e: mm(k.e), n: mm(k.n), z: mm(k.z), yaw: rad(k.yaw), pitch: rad(k.pitch) };
if (k.caption) c.caption = String(k.caption);
if (k.hold > 0) c.hold = ms(k.hold);
return c;
});
for (let i = 1; i < out.length; i++) {
if (!(out[i].t > out[i - 1].t)) throw Error(`keyframe ${i}: time must increase`);
}
const seconds = out[out.length - 1].t + out.reduce((s, k) => s + (k.hold || 0), 0);
if (seconds > LIMITS.seconds) throw Error(`the tour lasts ${Math.round(seconds)} s, over the limit of ${LIMITS.seconds} s`);
return { schema: SCHEMA, kind, name: String(name), keyframes: out };
}
// ---------- JSON with a SHA-256 ----------
const body = tour => JSON.stringify({ schema: SCHEMA, kind: tour.kind, name: tour.name, keyframes: tour.keyframes });
export async function sha256(text) {
const bytes = new TextEncoder().encode(text);
const digest = await globalThis.crypto.subtle.digest('SHA-256', bytes);
return [...new Uint8Array(digest)].map(b => b.toString(16).padStart(2, '0')).join('');
}
// The hash covers the canonical body (everything but the hash itself), so re-exporting is stable.
export async function exportTour(tour) {
const t = makeTour(tour);
const sha = await sha256(body(t));
return JSON.stringify({ ...t, sha256: sha }, null, 1);
}
// Parse, check the schema and the hash, and return the tour. Throws with a plain reason on any fault.
export async function importTour(text) {
const bytes = new TextEncoder().encode(String(text)).length;
if (bytes > LIMITS.fileBytes) throw Error(`tour file is ${bytes} bytes, over the limit of ${LIMITS.fileBytes}`);
let raw;
try { raw = JSON.parse(String(text).replace(/^/, '')); } catch { throw Error('tour file is not valid JSON'); }
if (raw?.schema !== SCHEMA) throw Error(`tour file schema is not ${SCHEMA}`);
const extra = Object.keys(raw).filter(k => !TOP_FIELDS.includes(k));
if (extra.length) throw Error(`tour file has unexpected fields: ${extra.join(', ')}`);
if (!HEX64.test(String(raw.sha256 ?? '').toLowerCase())) throw Error('tour file has no valid sha256');
const t = makeTour(raw);
raw.keyframes.forEach((k, i) => {
const odd = Object.keys(k).filter(f => !KEY_FIELDS.includes(f));
if (odd.length) throw Error(`keyframe ${i} has unexpected fields: ${odd.join(', ')}`);
});
const sha = await sha256(body(t));
if (sha !== raw.sha256.toLowerCase()) throw Error('tour file sha256 does not match its contents');
return t;
}
// ---------- playback ----------
// Compile a tour into a timeline. Holds become a second keyframe in the same place; the first, last,
// captioned and held keyframes are stops, where the camera comes to rest as it does on arrival.
export function compile(tour) {
const src = tour.keyframes;
const pts = [];
let shift = 0, yaw = src[0].yaw;
src.forEach((k, i) => {
yaw = i ? yaw + turn(pts[pts.length - 1].raw, k.yaw) : k.yaw; // unwrap, so each step turns the short way
const stop = i === 0 || i === src.length - 1 || !!k.caption || k.hold > 0;
const p = { t: k.t + shift, v: [k.e, k.n, k.z, yaw, k.pitch], raw: k.yaw, stop, caption: k.caption || '', src: i };
pts.push(p);
if (k.hold > 0) { shift += k.hold; pts.push({ ...p, t: k.t + shift, caption: '', held: true }); }
});
// Tangents: zero at stops, otherwise the time-weighted Catmull-Rom slope through the neighbours.
for (let i = 0; i < pts.length; i++) {
const a = pts[i - 1], b = pts[i], c = pts[i + 1];
b.m = b.stop || !a || !c ? [0, 0, 0, 0, 0] : b.v.map((_, j) => (c.v[j] - a.v[j]) / (c.t - a.t));
}
const captions = pts.filter(p => p.caption).map(p => ({ t: p.t, text: p.caption, keyframe: p.src }));
const stops = pts.filter(p => p.stop && !p.held).map(p => p.t);
return Object.freeze({ tour, pts, captions, stops, duration: pts[pts.length - 1].t });
}
// Cubic Hermite between two points with the given tangents; u in [0, 1], h the span in seconds.
function hermite(a, b, u, h, j) {
const u2 = u * u, u3 = u2 * u;
return (2 * u3 - 3 * u2 + 1) * a.v[j] + (u3 - 2 * u2 + u) * h * a.m[j] + (-2 * u3 + 3 * u2) * b.v[j] + (u3 - u2) * h * b.m[j];
}
// The pose at time t (seconds from the start) in grid metres: { e, n, z, yaw, pitch }.
// Times before the start or after the end give the first or last pose exactly.
export function gridPoseAt(line, t) {
const p = line.pts;
const at = v => ({ e: v[0], n: v[1], z: v[2], yaw: v[3], pitch: v[4] });
if (!(t > p[0].t)) return at(p[0].v);
if (t >= line.duration) return at(p[p.length - 1].v);
let lo = 0, hi = p.length - 1; // binary search: p[lo].t <= t < p[hi].t
while (hi - lo > 1) { const mid = (lo + hi) >> 1; if (p[mid].t <= t) lo = mid; else hi = mid; }
const a = p[lo], b = p[hi], h = b.t - a.t, u = (t - a.t) / h;
return at(a.v.map((_, j) => hermite(a, b, u, h, j)));
}
// The same pose in local metres under the current origin, ready for the camera: { pos, yaw, pitch }.
export function poseAt(line, t, origin) {
const g = gridPoseAt(line, t);
const [x, y] = toLocal(origin, g.e, g.n);
return { pos: [x, y, g.z], yaw: g.yaw, pitch: g.pitch };
}
// The caption showing at time t: from its keyframe until the next captioned keyframe, or `showFor`
// seconds, whichever is sooner. Returns { text, index } or null.
export function captionAt(line, t, { showFor = 6 } = {}) {
const cs = line.captions;
for (let i = cs.length - 1; i >= 0; i--) {
if (cs[i].t <= t) {
const until = Math.min(cs[i + 1]?.t ?? Infinity, cs[i].t + showFor);
return t < until ? { text: cs[i].text, index: i } : null;
}
}
return null;
}
// ---------- player and presentation ----------
// Player. apply(pose, t) receives the local pose for each drawn frame; getOrigin() gives the current
// origin. gate is a frame gate (frame-gate.mjs): while playing it runs at 30 fps at most, and when
// paused or finished it is told to stop, so an idle tour draws nothing at all.
// The caller's draw routine calls player.frame(now); now is in milliseconds, as from the gate.
export function createPlayer(tour, { gate, getOrigin, apply = () => {}, onCaption = () => {}, onEnd = () => {}, clock = () => performance.now(), showFor = 6 } = {}) {
const line = compile(tour);
let playing = false, t = 0, startedAt = 0, shown;
const show = () => {
const c = captionAt(line, t, { showFor });
const key = c ? c.index : -1;
if (key !== shown) { shown = key; onCaption(c ? c.text : '', c); }
};
const draw = () => { apply(poseAt(line, t, getOrigin()), t); show(); };
const self = {
line,
get playing() { return playing; },
get time() { return t; },
play() {
if (playing) return;
if (t >= line.duration) t = 0;
playing = true; startedAt = clock() - t * 1000;
gate?.setMoving(true, PLAY_FPS);
},
pause() {
if (!playing) return;
t = Math.min(line.duration, (clock() - startedAt) / 1000);
playing = false;
gate?.setMoving(false);
gate?.invalidate(); // one last frame at the exact paused time, then nothing
},
toggle() { playing ? self.pause() : self.play(); },
// Jump to a time in seconds; keeps playing if it was.
seek(s) {
if (!Number.isFinite(s)) return; // a bad time is ignored, never played forever
t = Math.max(0, Math.min(line.duration, s)); // bounded by the tour, which is bounded by LIMITS.seconds
if (playing) startedAt = clock() - t * 1000;
else gate?.invalidate();
},
// Presentation steps: go to the next or previous stop (a captioned or held keyframe, or an end).
next() { const s = line.stops.find(x => x > t + 1e-9); self.seek(s ?? line.duration); },
previous() { const s = [...line.stops].reverse().find(x => x < t - 1e-9); self.seek(s ?? 0); },
// Called from the gate's draw. Works out the tour time from the clock, applies the pose.
frame(now = clock()) {
if (!Number.isFinite(now)) now = clock();
if (playing) {
t = Math.min(line.duration, (now - startedAt) / 1000);
if (t >= line.duration) { playing = false; gate?.setMoving(false); draw(); onEnd(); return; }
}
draw();
}
};
return self;
}
// Presentation mode: play a saved tour for a meeting. Takes the tour file's text, checks its hash,
// and returns a player whose captions go to captionEl (any object with textContent and hidden) or
// onCaption. Keys: space plays or pauses, right and left arrows step between stops, Escape ends.
export async function present(text, { captionEl, onCaption, onExit = () => {}, autoplay = true, ...opts } = {}) {
const tour = await importTour(text);
const player = createPlayer(tour, {
...opts,
onCaption(textNow, c) {
if (captionEl) { captionEl.textContent = textNow; captionEl.hidden = !textNow; }
onCaption?.(textNow, c);
}
});
player.key = code => {
if (code === ' ' || code === 'Space') player.toggle();
else if (code === 'ArrowRight') player.next();
else if (code === 'ArrowLeft') player.previous();
else if (code === 'Escape') { player.pause(); onExit(); }
else return false;
return true;
};
if (autoplay) player.play();
return player;
}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/202609271552-site-world/world/block-mv.mjs · lines 1–137 of 137 · version 2026-09-27 15:52 · pattern dropWith (shared by 4 files)
- What it does
- It calculates solar, transformers and cables. Defines 12 functions or classes, including mvChain, colX, up, path, groupOf.
- 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 3 files: Cmd Trench (globalgrid2050); Block Build (globalgrid2050); Block UI (globalgrid2050). Reached from 2 other entry points, including Solar Design Studio — Site World Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609271853-site-world/); Substrate (globalgrid2050).
- What it achieves
- It is built from the 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, Block Build and Block UI.
- Application
- globalgrid2050 · solar-design-studio/202609271552-site-world/world · 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), imported by Block UI (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
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609271552-site-world/world/block-mv.mjs:1-137 · blob 6284ee02b77ded0ed6310420eede0bfcc7655201 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
// 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.' };
}Cmd Anim
A JavaScript module in the world folder of GlobalGrid2050 that draws on a canvas, covering cables.
renderglobalgrid2050 / solar-design-studio/202609271552-site-world/world/cmd-anim.mjs · lines 1–158 of 158 · version 2026-09-27 15:52 · pattern frame (shared by 66 files)
- What it does
- It draws cables. Defines 10 functions or classes, including f2, createAnim, size, frame, label. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: cables.
- Inputs & outputs
- Out: canvas drawing.
- Downstream impact
- Used directly by 1 file: Cmd UI (globalgrid2050). Reached from 2 other entry points, including Solar Design Studio — Site World Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609271853-site-world/); Substrate (globalgrid2050).
- What it achieves
- It creates anim (`createAnim`) and is built from the size step (`size`) and the frame step (`frame`). Short drawn explanations beside the typed bar.
- Why it matters
- Imported by Cmd UI.
- Application
- globalgrid2050 · solar-design-studio/202609271552-site-world/world · JavaScript module
- Uses
- none found
- Used by
- imported by Cmd UI (import)
- Produces
- createAnim
- Defines here
- f2, createAnim, size, frame, label, setup, line, tiltOf, X, draw
- 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/202609271552-site-world/world/cmd-anim.mjs:1-158 · blob b9d084b2852905c27d4e5e092cd42be0d336b9e9 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
// cmd-anim.mjs: short drawn explanations beside the typed bar. Each plays once when a value it shows changes (about 1.4 s
// between the old value and the new), then stops: no frame is drawn while nothing changes (0 fps). Canvas 2D, no imports.
// tilt side view of a table: the tilt arc, and the noon sun at midwinter and midsummer with its path between them
// rows three rows at the pitch: the midwinter noon shadow on the ground, the clear gap and the ground cover ratio
// trench the cross-section with its cables (trefoil or flat), bedding and cover; the bend radius drawn as an arc at a corner
// loop one string on its table tier: the loop between + and − conductors, standard and leapfrog, with areas in m²
// d, before: cmd-model.mjs derive() records. Illustrative, not to any site.
const C = { line: '#9cdbff', text: '#cfe9ff', dim: '#6f8ea6', warn: '#ff8a7a', sun: '#ffc773', cable: '#8cffa0', std: '#ff9d5c', lf: '#8cffa0',
ground: '#56708a', fill: 'rgba(156,219,255,0.10)' };
const MS = 1400, ease = t => 1 - (1 - t) ** 3, mix = (a, b, t) => (Number.isFinite(a) ? a + (b - a) * t : b);
const f2 = v => v.toFixed(2), DEG = Math.PI / 180;
export function createAnim(canvas, { onFrame = () => {} } = {}) {
const ctx = canvas.getContext('2d');
let raf = 0, job = null;
function size() {
const r = canvas.getBoundingClientRect(), k = globalThis.devicePixelRatio || 1;
const w = Math.max(1, Math.round(r.width * k)), h = Math.max(1, Math.round(r.height * k));
if (canvas.width !== w || canvas.height !== h) { canvas.width = w; canvas.height = h; }
ctx.setTransform(k, 0, 0, k, 0, 0);
return [r.width, r.height];
}
function frame(now) {
if (!job) return;
const t = Math.min(1, (now - job.t0) / MS), [W, H] = size();
ctx.clearRect(0, 0, W, H);
DRAW[job.kind](ctx, W, H, job.a, job.b, ease(t));
onFrame(job.kind, t);
if (t < 1) raf = requestAnimationFrame(frame); else { raf = 0; job.done = true; }
}
return {
play(kind, a, b) {
if (!DRAW[kind] || !b) return false;
cancelAnimationFrame(raf);
job = { kind, a: a || b, b, t0: performance.now(), done: false };
raf = requestAnimationFrame(frame);
return true;
},
stop() { cancelAnimationFrame(raf); raf = 0; },
running: () => !!raf,
kind: () => job?.kind || null
};
}
function label(ctx, s, x, y, color = C.text, align = 'left') { ctx.fillStyle = color; ctx.textAlign = align; ctx.fillText(s, x, y); }
function setup(ctx) { ctx.font = '11px system-ui, sans-serif'; ctx.lineCap = 'round'; ctx.lineJoin = 'round'; ctx.setLineDash([]); }
function line(ctx, pts, color, w = 1.5, dash = []) {
ctx.strokeStyle = color; ctx.lineWidth = w; ctx.setLineDash(dash); ctx.beginPath();
pts.forEach(([x, y], i) => (i ? ctx.lineTo(x, y) : ctx.moveTo(x, y))); ctx.stroke(); ctx.setLineDash([]);
}
const tiltOf = d => (d.st.layout === 'south' ? d.st.tilt : d.st.tiltEw);
const DRAW = {
tilt(ctx, W, H, a, b, t) {
setup(ctx);
const gy = H - 22, tilt = mix(tiltOf(a), tiltOf(b), t) * DEG, s = b.T.slope, sc = Math.min((W * 0.42) / s, (H - 50) / (s * 0.8 + b.st.edge));
const x0 = W * 0.42, y0 = gy - b.st.edge * sc, x1 = x0 + s * sc * Math.cos(tilt), y1 = y0 - s * sc * Math.sin(tilt);
line(ctx, [[8, gy], [W - 8, gy]], C.ground);
line(ctx, [[x0, gy], [x0, y0]], C.dim, 2); line(ctx, [[x0 + (x1 - x0) * 0.7, gy], [x0 + (x1 - x0) * 0.7, y0 + (y1 - y0) * 0.7]], C.dim, 2);
line(ctx, [[x0, y0], [x1, y1]], C.line, 4);
ctx.strokeStyle = C.sun; ctx.lineWidth = 1.2; ctx.beginPath(); ctx.arc(x0, y0, 26, -tilt, 0); ctx.stroke();
line(ctx, [[x0, y0], [x0 + 34, y0]], C.dim, 1, [2, 2]);
label(ctx, `${Math.round(mix(tiltOf(a), tiltOf(b), t))}°`, x0 + 30, y0 - 4, C.sun);
// The noon sun: midwinter and midsummer, the day's path between them as an arc, rays onto the table's middle.
const cx = (x0 + x1) / 2, cy = (y0 + y1) / 2, R = Math.min(W * 0.36, H - 30);
const ew = b.sun.winter * DEG, es = b.sun.summer * DEG;
ctx.strokeStyle = C.sun; ctx.setLineDash([3, 3]); ctx.beginPath(); ctx.arc(cx, cy, R * 0.8, Math.PI + ew * 0, Math.PI + es, false); ctx.stroke(); ctx.setLineDash([]);
for (const [e, name] of [[ew, '21 Dec'], [es, '21 Jun']]) {
const sx = cx - R * 0.8 * Math.cos(e), sy = cy - R * 0.8 * Math.sin(e);
line(ctx, [[sx, sy], [cx, cy]], C.sun, 1, [4, 3]);
ctx.fillStyle = C.sun; ctx.beginPath(); ctx.arc(sx, sy, 4, 0, 2 * Math.PI); ctx.fill();
label(ctx, `${name} ${Math.round(e / DEG)}°`, sx - 4, sy - 7, C.sun, 'right');
}
label(ctx, `Panel angle ${Math.round(tiltOf(a))}° → ${Math.round(tiltOf(b))}° · noon sun from the south`, 8, 14);
label(ctx, `top edge ${f2(b.st.edge + b.T.rise)} m`, x1 + 6, y1 + 4, C.dim);
},
rows(ctx, W, H, a, b, t) {
setup(ctx);
const gy = H - 24, pitch = mix(a.T.pitch, b.T.pitch, t), depth = mix(a.T.depth, b.T.depth, t), rise = b.T.rise, edge = mix(a.st.edge, b.st.edge, t);
const span = 2 * pitch + depth + 2, sc = Math.min((W - 24) / span, (H - 52) / (edge + rise + 0.5)), X = m => 12 + m * sc, Y = m => gy - m * sc;
line(ctx, [[8, gy], [W - 8, gy]], C.ground);
const el = b.sun.winter * DEG, sh = (edge + rise) / Math.tan(el);
for (let k = 0; k < 3; k++) {
const u = k * pitch;
if (b.st.layout === 'south') {
// Shadow of the top edge, grown along the ground as t runs.
const reach = Math.min(sh, span) * t;
ctx.fillStyle = 'rgba(255,138,122,0.16)'; ctx.beginPath();
ctx.moveTo(X(u + depth), Y(edge + rise)); ctx.lineTo(X(u + depth + reach), Y(Math.max(0, edge + rise - reach * Math.tan(el))));
ctx.lineTo(X(u + depth + reach), gy); ctx.lineTo(X(u), gy); ctx.closePath(); ctx.fill();
line(ctx, [[X(u), Y(edge)], [X(u + depth), Y(edge + rise)]], C.line, 3);
} else {
line(ctx, [[X(u), Y(edge)], [X(u + depth / 2), Y(edge + rise)], [X(u + depth), Y(edge)]], C.line, 3);
}
line(ctx, [[X(u + depth * 0.2), gy], [X(u + depth * 0.2), Y(edge + rise * 0.2)]], C.dim, 1.5);
}
// Pitch and gap dimensions.
line(ctx, [[X(0), gy + 10], [X(pitch), gy + 10]], C.dim, 1); label(ctx, `pitch ${f2(pitch)} m`, X(pitch / 2), gy + 21, C.text, 'center');
const gap = pitch - depth;
line(ctx, [[X(depth), Y(-0.3)], [X(pitch), Y(-0.3)]], b.shade.shaded ? C.warn : C.cable, 2);
const gcr = b.gcr ?? depth / pitch;
label(ctx, `Row spacing · GCR ${f2(mix(a.gcr ?? gcr, gcr, t))} · clear gap ${f2(gap)} m · 21 Dec noon shadow ${f2(b.shade.shadowM)} m`, 8, 14,
b.shade.shaded ? C.warn : C.text);
// Coverage bar: the share of the ground under modules.
const bw = 70, bx = W - bw - 10;
ctx.strokeStyle = C.dim; ctx.strokeRect(bx, 22, bw, 7); ctx.fillStyle = C.line; ctx.fillRect(bx, 22, bw * Math.min(1, depth / pitch), 7);
label(ctx, `${Math.round(100 * depth / pitch)} % of the ground in plan`, bx + bw, 40, C.dim, 'right');
},
trench(ctx, W, H, a, b, t) {
setup(ctx);
const depth = mix(a.st.depth, b.st.depth, t), width = mix(a.st.width, b.st.width, t), od = b.cable?.od || 0.05;
const L = W * 0.55, sc = Math.min((L - 30) / Math.max(1.2, width + 0.6), (H - 40) / 1.6), gy = 30, cx = 14 + (L - 14) / 2;
const X = m => cx + m * sc, Y = m => gy + m * sc;
line(ctx, [[8, gy], [X(-width / 2), gy], [X(-width / 2), Y(depth)], [X(width / 2), Y(depth)], [X(width / 2), gy], [L - 4, gy]], C.line, 1.5);
ctx.fillStyle = 'rgba(255,199,115,0.18)'; ctx.fillRect(X(-width / 2), Y(depth - 0.075 - b.trench.height), width * sc, (0.075 + b.trench.height) * sc);
ctx.fillStyle = C.cable;
for (const [u, v] of b.trench.centres) { ctx.beginPath(); ctx.arc(X(u), Y(depth - 0.075 - v), Math.max(2, od / 2 * sc), 0, 2 * Math.PI); ctx.fill(); }
const cover = depth - 0.075 - b.trench.height;
line(ctx, [[X(-width / 2) + 2, Y(cover - 0.1)], [X(width / 2) - 2, Y(cover - 0.1)]], C.sun, 1, [4, 3]);
line(ctx, [[X(width / 2) + 8, gy], [X(width / 2) + 8, Y(cover)]], cover < 0.91 ? C.warn : C.dim, 1);
label(ctx, `cover ${f2(cover)} m`, X(width / 2) + 12, Y(cover / 2), cover < 0.91 ? C.warn : C.text);
label(ctx, `depth ${f2(depth)} m · width ${f2(width)} m`, cx, Y(depth) + 14, C.text, 'center');
label(ctx, `${b.st.formation}, ${b.st.size} mm² ${b.st.metal === 'cu' ? 'Cu' : 'Al'}, OD ${(od * 1000).toFixed(1)} mm · tape dashed`, 8, 14);
// Plan of a corner: the trench turns 90°; the cable follows an arc of the bend radius (installation), swept as t runs.
const R = b.bend?.installM || 1, px = L + 18, py = H - 16, s2 = Math.min((W - px - 14) / (R + 1.2), (H - 46) / (R + 1.2));
const tw = Math.max(width * s2, 8), ox = px, oy = py;
ctx.fillStyle = C.fill;
ctx.fillRect(ox, oy - (R + 1) * s2, tw, (R + 1) * s2); ctx.fillRect(ox, oy - (R + 1) * s2, (R + 1.2) * s2, tw);
ctx.strokeStyle = C.cable; ctx.lineWidth = 2; ctx.beginPath();
const acx = ox + tw / 2 + R * s2, acy = oy - (R + 1) * s2 + tw / 2 + R * s2;
ctx.arc(acx, acy, R * s2, Math.PI, Math.PI + (Math.PI / 2) * t); ctx.stroke();
line(ctx, [[acx, acy], [acx - R * s2 * Math.cos(Math.PI / 4), acy - R * s2 * Math.sin(Math.PI / 4)]], C.dim, 1, [2, 2]);
label(ctx, `bend R ${f2(R)} m`, px, 14 + 14, C.cable);
label(ctx, `(${b.bend?.installX ?? '–'} × OD, pulling)`, px, 14 + 28, C.dim);
},
loop(ctx, W, H, a, b, t) {
setup(ctx);
const L = b.loops, len = L.lengthM, sx = (W - 24) / len, sy = Math.min((H - 64) / 2.4, sx * 3), X = m => 12 + m * sx, Y = m => H - 30 - m * sy;
for (let i = 0; i < b.mps; i++) { ctx.strokeStyle = 'rgba(111,142,166,0.5)'; ctx.lineWidth = 1; ctx.strokeRect(X(i * 1.154), Y(2.384), 1.134 * sx, 2.384 * sy); }
const draw = (poly, color, alpha, k) => {
const n = Math.max(2, Math.round(poly.length * k));
ctx.fillStyle = color.replace(')', `,${alpha})`).replace('rgb', 'rgba');
if (k >= 1) { ctx.beginPath(); poly.forEach(([x, y], i) => (i ? ctx.lineTo(X(x), Y(y)) : ctx.moveTo(X(x), Y(y)))); ctx.closePath(); ctx.fill(); }
line(ctx, poly.slice(0, n).map(([x, y]) => [X(x), Y(y)]), color, 1.6);
};
const t1 = Math.min(1, t * 2), t2 = Math.max(0, t * 2 - 1);
draw(L.standard.poly, 'rgb(255,157,92)', 0.22, t1);
if (t2 > 0) draw(L.leapfrog.poly, 'rgb(140,255,160)', 0.35, t2);
label(ctx, `Loop between + and − of one ${b.mps}-module string (height drawn ×${(sy / sx).toFixed(1)})`, 8, 14);
label(ctx, `standard ${L.standard.area.toFixed(1)} m²`, 8, 30, b.st.wiring === 'standard' ? C.std : C.dim);
label(ctx, `leapfrog ${L.leapfrog.area.toFixed(1)} m²`, 150, 30, b.st.wiring === 'leapfrog' ? C.lf : C.dim);
label(ctx, `routes on the table assumed`, W - 8, 30, C.dim, 'right');
}
};