In this section
- Search UI interaction · globalgrid2050 / solar-design-studio/202609270220-site-world-v3/world/search-ui.mjs lines 1–332
- Spec Rules test · globalgrid2050 / solar-design-studio/202609270220-site-world-v3/world/spec-rules.mjs lines 1–104
- Station transform · globalgrid2050 / solar-design-studio/202609270220-site-world-v3/world/station.mjs lines 1–260
Search UI
A JavaScript module in the world folder of GlobalGrid2050 that formats capacity and technology and converts to rows, covering postcodes, the Renewable Energy Planning Database (REPD) register, wind and solar.
interactionglobalgrid2050 / solar-design-studio/202609270220-site-world-v3/world/search-ui.mjs · lines 1–332 of 332 · version 2026-09-27 02:20 · pattern createSearchPanel (shared by 2 files)
- What it does
- It draws postcodes, the REPD register, wind and solar. Defines 29 functions or classes, including creditsFor, formatCapacity, trim, formatTechnology, toRows. 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: postcodes, the REPD register, wind, solar.
- Downstream impact
- Used directly by 2 files: Find Mount (globalgrid2050); Substrate (graphics-engines-open-source). Reached from 2 other entry points, including Graphics Engines Open Source — Versions Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/versions/); Versions — Site World Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/versions/202609262227-site-world/).
- What it achieves
- It formats capacity (`formatCapacity`), formats technology (`formatTechnology`) and merges rows (`mergeRows`). Search panel: "Find a place". A small box over the world that finds a town or village (OS Open Names through postcodes.io, see `places.mjs`), a REPD project, a UK postcode (postcodes.io, see `postcodes.mjs`) or a typed "lat, lon". Its code works with 1.2 GW, 49.9 MW and 650 kW. It responds to pointerdown, click and input events.
- Why it matters
- Imported by Find Mount and Substrate, from Graphics Engines Open Source.
- Application
- globalgrid2050 · solar-design-studio/202609270220-site-world-v3/world · JavaScript module
- Uses
- Search (import), Postcodes (import), Places (import)
- Used by
- imported by Find Mount (import), imported by Substrate (import), mentioned in Standalone (comment link)
- Produces
- REPD_CREDIT, NO_TERRAIN, LIVE_TERRAIN, creditsFor, formatCapacity, formatTechnology, toRows, summaryText, moveSelection, rowForEnter, debounce, arrivalNote
- Defines here
- creditsFor, formatCapacity, trim, formatTechnology, toRows, summaryText, moveSelection, rowForEnter, debounce, d, arrivalNote, mergeRows, statusLine, sourcesShown, runQuery, createSearchPanel, el, showCredits, ensureIndex, highlight, choose, render, paint, settle, ask, show, parseLike, openPanel, close
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609270220-site-world-v3/world/search-ui.mjs:1-332 · blob 5be962c628d66b01f1d473f1c6c070d08ee74c9b · 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
// Search panel: "Find a place". A small box over the world that finds a town or village (OS Open Names through
// postcodes.io, see places.mjs), a REPD project, a UK postcode (postcodes.io, see postcodes.mjs) or a typed "lat, lon",
// and hands the chosen point to the caller. The logic is pure functions at the top,
// tested without a DOM; createSearchPanel at the bottom only wires them to elements.
// The project index is large, so it is loaded the first time the panel is opened, never before.
import { search } from './search.mjs';
import { looksLikePostcode, createPostcodeLookup, POSTCODES_CREDIT } from './postcodes.mjs';
import { looksLikePlace, createPlaceLookup, PLACES_CREDIT } from './places.mjs';
// The on-screen credit for the search layer, as worded in data/attribution.json (sources.repd.line).
// tests/search-ui.test.mjs checks this copy against the file, so the two cannot drift apart.
export const REPD_CREDIT = Object.freeze({
id: 'repd',
text: 'Contains public sector information licensed under the Open Government Licence v3.0. Source: DESNZ Renewable Energy Planning Database, via GridAtlas.',
link: 'https://www.gov.uk/government/publications/renewable-energy-planning-database-monthly-extract'
});
// What the panel says after a jump, when the place has no staged ground.
export const NO_TERRAIN = 'No terrain tiles here yet. The ground is shown flat until terrain is fetched for this place.';
// What it says when the ground will come live from the Environment Agency service (wcs-terrain.mjs).
export const LIVE_TERRAIN = 'Fetching the ground live from the Environment Agency LiDAR service; it shows flat until it arrives.';
const TECH = {
solar: 'Solar', wind: 'Wind', bess: 'Battery storage', battery: 'Battery storage', hydro: 'Hydro',
biomass: 'Biomass', 'energy from waste': 'Energy from waste', efw: 'Energy from waste', 'anaerobic digestion': 'Anaerobic digestion',
'offshore wind': 'Offshore wind', 'onshore wind': 'Onshore wind', tidal: 'Tidal', geothermal: 'Geothermal', 'landfill gas': 'Landfill gas'
};
// The credit lines for the given attribution.json object: every on-screen source under the "search" (REPD),
// "postcodes" and "names" (OS Open Names) layers, de-duplicated, {year} filled in as attribution.mjs does.
// Falls back to the built-in lines without the file.
export function creditsFor(attribution, layers = ['search', 'postcodes', 'names'], year = new Date().getUTCFullYear()) {
const ids = [layers].flat().flatMap((l) => attribution?.layers?.[l] ?? []);
if (!attribution?.layers) return [REPD_CREDIT, POSTCODES_CREDIT, PLACES_CREDIT];
const out = [];
for (const id of new Set(ids)) {
const s = attribution.sources?.[id];
if (s && s.on_screen !== false && s.line) out.push({ id, text: s.line.replaceAll('{year}', String(s.year ?? year)), link: s.link ?? null });
}
return out;
}
// "49.9 MW", "650 kW", "1.2 GW"; empty when the capacity is unknown.
export function formatCapacity(mw) {
if (mw == null || mw === '' || !Number.isFinite(Number(mw))) return '';
const v = Number(mw);
if (v >= 1000) return `${trim(v / 1000)} GW`;
if (v > 0 && v < 1) return `${trim(v * 1000)} kW`;
return `${trim(v)} MW`;
}
const trim = (v) => String(Number(v.toFixed(v >= 100 ? 0 : v >= 10 ? 1 : 2)));
export function formatTechnology(t) {
if (t == null || t === '') return '';
const k = String(t).trim().toLowerCase();
return TECH[k] ?? k.charAt(0).toUpperCase() + k.slice(1);
}
// search() output to display rows. Each row: { key, title, detail, choice: { lat, lon, label } }.
// A coordinate query gives one row. Projects without a usable point are left out.
export function toRows(result) {
if (!result) return [];
if (result.kind === 'coords') {
const label = `${result.lat.toFixed(5)}, ${result.lon.toFixed(5)}`;
return [{ key: 'coords', title: label, detail: 'Latitude, longitude', choice: { lat: result.lat, lon: result.lon, label } }];
}
return (result.results ?? [])
.filter((r) => r.lat != null && r.lon != null && r.lat !== '' && r.lon !== '' && Number.isFinite(Number(r.lat)) && Number.isFinite(Number(r.lon)))
.map((r) => {
const title = r.name ? String(r.name) : `REPD ${r.repd_ref}`;
const detail = [`REPD ${r.repd_ref}`, formatCapacity(r.capacity_mw), formatTechnology(r.technology), r.county ?? ''].filter(Boolean).join(' · ');
return { key: `repd-${r.repd_ref}`, source: 'repd', title, detail, rank: r.score, choice: { lat: Number(r.lat), lon: Number(r.lon), label: title, ref: r.repd_ref } };
});
}
// "12 of 340 projects", "1 project", "No projects match", "" (no query).
export function summaryText(result, shown) {
if (!result) return '';
if (result.kind === 'coords') return 'Go to this point';
if (!result.total) return 'No projects match';
const noun = result.total === 1 ? 'project' : 'projects';
return shown < result.total ? `${shown} of ${result.total} ${noun}` : `${result.total} ${noun}`;
}
// Arrow keys move the highlighted row, wrapping; Home and End jump. -1 means nothing highlighted.
// Returns the new index, or null when the key is not a selection key.
export function moveSelection(index, count, key) {
if (count <= 0) return key === 'ArrowDown' || key === 'ArrowUp' || key === 'Home' || key === 'End' ? -1 : null;
switch (key) {
case 'ArrowDown': return index < 0 || index >= count - 1 ? 0 : index + 1;
case 'ArrowUp': return index <= 0 ? count - 1 : index - 1;
case 'Home': return 0;
case 'End': return count - 1;
default: return null;
}
}
// Which row Enter chooses: the highlighted one, or the first when nothing is highlighted.
export function rowForEnter(rows, index) {
if (!rows.length) return null;
return rows[index >= 0 && index < rows.length ? index : 0];
}
// Trailing-edge debounce. Clock functions are injectable so tests need no real time.
export function debounce(fn, ms, clock = { set: (f, t) => setTimeout(f, t), clear: id => clearTimeout(id) }) { // bound: a bare setTimeout called as clock.set throws 'Illegal invocation' in browsers
let id = null;
const d = (...args) => {
if (id !== null) clock.clear(id);
id = clock.set(() => { id = null; fn(...args); }, ms);
};
d.cancel = () => { if (id !== null) clock.clear(id); id = null; };
d.flush = (...args) => { d.cancel(); fn(...args); };
return d;
}
// The note to show after choosing a place. hasTerrain(lat, lon) is the caller's answer to
// "is ground staged here?"; without it we cannot know, so we say so plainly. live: ground elsewhere
// is fetched from the EA service, so say that instead of "flat".
export function arrivalNote(choice, hasTerrain, live = false) {
const known = typeof hasTerrain === 'function' ? Boolean(hasTerrain(choice.lat, choice.lon)) : false;
return known ? '' : live ? LIVE_TERRAIN : NO_TERRAIN;
}
// Postcode rows first (an exact postcode is what was meant), then places and projects by their ranks
// (places.mjs PLACE_SCORE against search.mjs SCORE): an exact town name above every project, a town that starts
// with the text above projects that only start with it. Ties keep places first, and each list keeps its own order. Pure.
export function mergeRows(postcodeRows, projectRows, placeRows = []) {
const rest = [...(placeRows || []).map((r) => ({ r, k: r.score ?? 0 })), ...(projectRows || []).map((r) => ({ r, k: r.rank ?? 0 }))];
return [...(postcodeRows || []), ...rest.map((x, i) => ({ ...x, i })).sort((a, b) => b.k - a.k || a.i - b.i).map((x) => x.r)];
}
// The status line: what each source found, or that it is still looking. Counts of null mean "still waiting";
// projects is runQuery's summary, or null while the project list is not loaded. Pure.
export function statusLine({ postcodes = undefined, places = undefined, projects = null, projectRows = 0 } = {}) {
const parts = [];
if (postcodes === null) parts.push('Looking up postcode...');
else if (postcodes !== undefined) parts.push(postcodes ? `${postcodes} ${postcodes === 1 ? 'postcode' : 'postcodes'}` : 'No postcode matches');
if (places === null) parts.push('Looking up places...');
else if (places) parts.push(`${places} ${places === 1 ? 'place' : 'places'}`);
if (projects && (projectRows > 0 || !parts.length)) parts.push(projects);
return parts.join(' · ');
}
// Which credits to show: those of the sources that have rows on screen.
export const sourcesShown = rows => new Set(rows.map(r => r.source).filter(Boolean));
// One lookup: query text in, everything the list needs out. Pure.
export function runQuery(index, text, limit = 12) {
const q = String(text ?? '').trim();
if (!q) return { rows: [], summary: '', credits: false };
const result = search(index, q, limit);
const rows = toRows(result);
return { rows, summary: summaryText(result, rows.length), credits: result.kind === 'projects' && rows.length > 0, result };
}
// ---- DOM wiring ----------------------------------------------------------------------------
// Uses world.html's colour tokens, with fallbacks. Rows are 44 px tall for touch.
const STYLE = `
.find-panel { position: fixed; top: 46px; right: 8px; width: min(360px, calc(100vw - 16px)); box-sizing: border-box;
background: var(--panel, rgba(10,10,10,.9)); border: 1px solid var(--edge, #1c2c3a); border-radius: 6px; padding: 8px 10px; z-index: 5;
display: flex; flex-direction: column; }
.find-panel > * { flex: none; }
.find-panel[hidden] { display: none; }
.find-panel label { display: block; color: var(--dim, #6f8ea6); margin-bottom: 4px; }
.find-panel input { width: 100%; box-sizing: border-box; height: 34px; padding: 0 8px; font: inherit; font-size: 16px;
color: var(--text, #cfe9ff); background: #000; border: 1px solid var(--edge, #1c2c3a); border-radius: 4px; }
.find-panel input:focus { outline: none; border-color: var(--line, #9cdbff); }
.find-status { color: var(--dim, #6f8ea6); font-size: 11px; min-height: 16px; margin: 4px 0; }
.find-list { list-style: none; margin: 0; padding: 0; max-height: min(50vh, 400px); overflow-y: auto; }
.find-panel > .find-list { flex: 0 1 auto; min-height: 44px; } /* on a short panel the list scrolls; the credits stay in view */
.find-row { min-height: 44px; box-sizing: border-box; padding: 5px 6px; border-radius: 4px; cursor: pointer;
display: flex; flex-direction: column; justify-content: center; }
.find-row[aria-selected="true"], .find-row:hover { background: rgba(156, 219, 255, 0.10); }
.find-name { color: var(--text, #cfe9ff); } .find-detail { color: var(--dim, #6f8ea6); font-size: 11px; }
.find-credit { margin: 6px 0 0; font-size: 10px; line-height: 1.3; } .find-credit[hidden] { display: none; }
.find-credit a { color: var(--dim, #6f8ea6); display: block; margin-top: 3px; } .find-credit a[hidden] { display: none; } /* one credit per line */
`;
// container: element the panel is built inside. loadIndex(): Promise of the projects.json object,
// called once, on first open. onChoose({ lat, lon, label }): the caller moves the world there.
// Options: attribution (the attribution.json object; defaults to the REPD and postcode lines), hasTerrain(lat, lon),
// liveTerrain (ground elsewhere comes from the EA service), postcodes (a lookup from createPostcodeLookup;
// false for none), places (a lookup from createPlaceLookup; false for none), limit (rows shown), delay (debounce ms). Returns { open, close, toggle, isOpen, element, destroy }.
let panelCount = 0;
export function createSearchPanel(container, { loadIndex, onChoose, attribution = null, hasTerrain = null, liveTerrain = false,
postcodes = createPostcodeLookup(), places = createPlaceLookup(), limit = 12, delay = 120 } = {}) {
if (typeof loadIndex !== 'function') throw Error('createSearchPanel needs loadIndex');
if (typeof onChoose !== 'function') throw Error('createSearchPanel needs onChoose');
const doc = container.ownerDocument;
const el = (tag, props = {}, attrs = {}) => {
const e = doc.createElement(tag);
Object.assign(e, props);
for (const [k, v] of Object.entries(attrs)) e.setAttribute(k, v);
return e;
};
const uid = `find-${++panelCount}`; // a counter, not a random draw: ids stay the same on every run
if (doc.head && !doc.getElementById?.('find-panel-style')) doc.head.appendChild(el('style', { id: 'find-panel-style', textContent: STYLE }));
const root = el('section', { className: 'find-panel', hidden: true }, { 'aria-label': 'Find a place' });
const label = el('label', { textContent: 'Find a place', htmlFor: `${uid}-q` });
const input = el('input', { type: 'search', id: `${uid}-q`, autocomplete: 'off', spellcheck: false,
placeholder: 'Town, postcode, project or lat, lon' },
{ role: 'combobox', 'aria-autocomplete': 'list', 'aria-expanded': 'false', 'aria-controls': `${uid}-list`, enterkeyhint: 'go' });
const status = el('div', { className: 'find-status' }, { role: 'status', 'aria-live': 'polite' });
const list = el('ul', { id: `${uid}-list`, className: 'find-list' }, { role: 'listbox', 'aria-label': 'Places found' });
const credit = el('p', { className: 'find-credit', hidden: true });
for (const c of creditsFor(attribution)) {
const a = el('a', { textContent: c.text, href: c.link ?? '#', target: '_blank', rel: 'noopener' }, { 'data-source': c.id ?? '' });
credit.appendChild(a);
}
// Only the credits of sources with rows on screen are shown; the small print hides when there are none.
const showCredits = (ids) => {
for (const a of credit.childNodes) a.hidden = !ids.has(a.getAttribute('data-source'));
credit.hidden = ids.size === 0;
};
root.append(label, input, status, list, credit);
container.appendChild(root);
let index = null, loading = null, rows = [], sel = -1, open = false, shown = null; // shown: the text the list was built for
let pending = null, enterWhenReady = false; // pending: the text a postcode or place lookup is running for
const ensureIndex = () => {
if (index || loading) return loading;
status.textContent = 'Loading project list...';
loading = Promise.resolve().then(loadIndex).then((ix) => {
index = ix; status.textContent = '';
if (input.value.trim()) render(input.value);
}, (e) => {
loading = null; status.textContent = `Project list could not be loaded: ${e?.message ?? e}`;
});
return loading;
};
const highlight = (i) => {
sel = i;
list.childNodes.forEach((li, k) => li.setAttribute('aria-selected', String(k === sel)));
if (sel >= 0) { input.setAttribute('aria-activedescendant', `${uid}-o${sel}`); list.childNodes[sel]?.scrollIntoView?.({ block: 'nearest' }); }
else input.removeAttribute('aria-activedescendant');
};
const choose = (row) => {
if (!row) return;
status.textContent = arrivalNote(row.choice, hasTerrain, liveTerrain) || `Going to ${row.choice.label}`;
list.replaceChildren(); rows = []; shown = null; pending = null; enterWhenReady = false;
showCredits(new Set()); input.setAttribute('aria-expanded', 'false');
onChoose({ ...row.choice });
};
function render(text) {
const pc = Boolean(postcodes) && looksLikePostcode(text), pl = Boolean(places) && looksLikePlace(text);
const point = parseLike(text);
if (!index && !point) ensureIndex();
if (!index && !point && !pc && !pl) return;
const out = index || point ? runQuery(index, text, limit) : { rows: [], summary: '', result: null };
const projects = out.result?.kind === 'projects' ? out.summary : null;
shown = text;
// Each answer: undefined when not asked, null while waiting, else the rows.
const got = { postcodes: pc ? null : undefined, places: pl ? null : undefined };
const paint = () => {
show(mergeRows(got.postcodes, out.rows, got.places), point ? out.summary : statusLine({
postcodes: got.postcodes === null ? null : got.postcodes?.length, places: got.places === null ? null : got.places?.length,
projects, projectRows: out.rows.length }));
};
paint();
pending = pc || pl ? text : null;
const settle = () => {
if (got.postcodes === null || got.places === null) return;
pending = null;
if (enterWhenReady) { enterWhenReady = false; choose(rowForEnter(rows, sel)); }
};
const ask = (key, lookup, noun) => lookup(text).then((found) => {
if (found === null || shown !== text) return; // a newer query took over
got[key] = found; paint(); settle();
}, (e) => {
if (shown !== text) return;
got[key] = []; paint(); settle();
status.textContent = [`${noun} lookup failed: ${e?.message ?? e}`, status.textContent].filter(Boolean).join(' · ');
});
if (pc) ask('postcodes', postcodes, 'Postcode');
if (pl) ask('places', places, 'Place');
}
function show(next, summary) {
rows = next;
list.replaceChildren(...rows.map((r, i) => {
const li = el('li', { id: `${uid}-o${i}`, className: 'find-row' }, { role: 'option', 'aria-selected': 'false' });
li.append(el('span', { className: 'find-name', textContent: r.title }), el('span', { className: 'find-detail', textContent: r.detail }));
li.addEventListener('pointerdown', (e) => e.preventDefault()); // keep focus in the box
li.addEventListener('click', () => choose(r));
return li;
}));
status.textContent = summary;
showCredits(sourcesShown(rows));
input.setAttribute('aria-expanded', String(rows.length > 0));
highlight(-1);
}
const parseLike = (text) => runQuery(null, text).rows.length > 0; // a typed point needs no index
const later = debounce(render, delay);
input.addEventListener('input', () => later(input.value));
input.addEventListener('keydown', (e) => {
if (e.key === 'Escape') { e.preventDefault(); close(); return; }
if (e.key === 'Enter') {
e.preventDefault();
if (input.value !== shown) later.flush(input.value); else later.cancel();
if (pending === input.value && sel < 0) { enterWhenReady = true; return; } // the postcode answer is on its way
choose(rowForEnter(rows, sel)); return;
}
const next = moveSelection(sel, rows.length, e.key);
if (next !== null) { e.preventDefault(); highlight(next); }
});
function openPanel() {
if (open) return;
open = true; root.hidden = false; ensureIndex(); input.focus?.(); input.select?.();
}
function close() { open = false; root.hidden = true; later.cancel(); }
return {
element: root,
open: openPanel,
close,
toggle: () => (open ? close() : openPanel()),
isOpen: () => open,
destroy: () => { close(); root.remove(); }
};
}
export default createSearchPanel;Spec Rules
A JavaScript module in the world folder of GlobalGrid2050 that tests cables. It reads spec (`readSpec`) and applies ground (`applyGround`).
testglobalgrid2050 / solar-design-studio/202609270220-site-world-v3/world/spec-rules.mjs · lines 1–104 of 104 · version 2026-09-27 02:20
- What it does
- It tests cables. Defines num, txt, readSpec, applyGround, looseSpoil.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: cables.
- Downstream impact
- Used directly by 4 files: Design Options (globalgrid2050); Design Sections (globalgrid2050); Xray (globalgrid2050); Design Sections (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
- Which specification a trench is built to, and what the ground does to it.
- Why it matters
- Imported by 4 files, including Design Options, Design Sections and Xray.
- Application
- globalgrid2050 · solar-design-studio/202609270220-site-world-v3/world · JavaScript module
- Uses
- none found
- Used by
- imported by Design Options (import), imported by Design Sections (import), imported by Xray (import), imported by Design Sections (import)
- Produces
- SCHEMA, OPERATOR_SPEC, readSpec, GROUNDS, applyGround, looseSpoil
- Defines here
- num, txt, readSpec, applyGround, looseSpoil
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609270220-site-world-v3/world/spec-rules.mjs:1-104 · blob b4bba11f5f3bee81364637caea7cb7104cb4f528 · 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
// spec-rules.mjs: which specification a trench is built to, and what the ground does to it.
//
// Two specifications:
// 'operator' the network operator sections in data/trench-sections.json, with the good-practice
// ground rules below (our own summary of common UK practice, not any one document).
// 'project' a project specification the user loads from a local file at run time (schema spec-rules.v1).
// It is held in memory only: never uploaded, never stored, never written into the page.
// The repo ships only data/spec-example.json, a made-up file clearly labelled "example".
//
// Ground conditions change the trench: an alluvium / soft wet ground option adds support or a batter,
// a formation over-dig with granular fill, a wider working width, a dewatering note and spoil handling.
// Pure: no imports, no DOM.
export const SCHEMA = 'spec-rules.v1';
// Good practice when no project specification is loaded (general UK practice, rounded):
// tape 200 mm above the cable; backfill compacted in 150 mm layers; 150 mm concrete round ducts under roads;
// signal cables 600 mm from MV/HV and 300 mm from LV; soil stripped and stored by the Defra soil code
// (topsoil apart from subsoil); watercourse stand-off 10 m by default (drainage-board byelaw strips are
// typically 8-9 m; the regulator sets the figure).
// The alluvium numbers are assumed general practice for soft wet ground, not from any document: support below
// 1.2 m (entry depth), a 1 : 1 batter above it, 1 m working strip each side, 150 mm formation over-dig,
// 1.3 bulking for wet clayey spoil.
export const OPERATOR_SPEC = Object.freeze({
schema: SCHEMA, label: 'Network operator spec', source: 'operator',
note: 'Operator trench sections (typical UK practice, confirm with the DNO/TO spec); ground rules are general practice.',
marker: { tape_above_service_m: 0.2 },
backfill: { layer_mm: 150 },
ducts: { road_concrete_surround_mm: 150, dc_mains_ducted: true },
separation: { signal_from_mv_mm: 600, signal_from_lv_mm: 300 },
spoil: { topsoil_separate: true },
standoff: { watercourse_m: 10 },
ground: {
normal: { label: 'Normal ground' },
alluvium: {
label: 'Alluvium / soft wet ground',
basis: 'General practice for soft, wet, low-strength ground with a high water table.',
support_below_m: 1.2, batter_h_per_v: 1.0, working_extra_m: 1.0, overdig_m: 0.15,
formation: 'granular sub-base on geotextile', bulking: 1.3,
dewatering: 'sump pumping through a settlement tank or silt bag; never straight into a ditch or drain',
spoil: 'wet spoil kept away from ditch edges, stockpiles low and covered, topsoil and subsoil apart',
ducts_preferred: true
}
}
});
const num = (v, lo, hi) => typeof v === 'number' && Number.isFinite(v) && v >= lo && v <= hi;
const txt = v => typeof v === 'string' && v.length > 0 && v.length <= 400;
/**
* readSpec(json) -> a normalised specification, or throws with a plain reason.
* Accepts the rules object itself or a wrapper with the rules under `tool` (a private file may carry both).
* Missing groups fall back to the operator spec, so a project file only says what it changes.
*/
export function readSpec(json) {
const doc = json && typeof json === 'object' && json.tool && typeof json.tool === 'object' ? json.tool : json;
if (!doc || typeof doc !== 'object') throw new Error('specification: not a JSON object');
if (doc.schema !== SCHEMA) throw new Error(`specification: schema must be "${SCHEMA}"`);
const out = { schema: SCHEMA, source: 'project', label: txt(doc.label) ? doc.label.slice(0, 80) : 'Project specification',
note: txt(doc.note) ? doc.note : '' };
for (const k of ['marker', 'backfill', 'ducts', 'separation', 'spoil', 'standoff']) out[k] = { ...OPERATOR_SPEC[k], ...(doc[k] || {}) };
if (!num(out.marker.tape_above_service_m, 0.05, 1)) throw new Error('specification: marker.tape_above_service_m must be 0.05 to 1 m');
if (!num(out.backfill.layer_mm, 50, 500)) throw new Error('specification: backfill.layer_mm must be 50 to 500');
out.ground = { normal: { label: 'Normal ground' } };
const g = { ...OPERATOR_SPEC.ground.alluvium, ...((doc.ground || {}).alluvium || {}) };
if (!num(g.support_below_m, 0.5, 3)) throw new Error('specification: ground.alluvium.support_below_m must be 0.5 to 3 m');
if (!num(g.batter_h_per_v, 0, 3)) throw new Error('specification: ground.alluvium.batter_h_per_v must be 0 to 3');
if (!num(g.working_extra_m, 0, 5)) throw new Error('specification: ground.alluvium.working_extra_m must be 0 to 5 m');
if (!num(g.overdig_m, 0, 1)) throw new Error('specification: ground.alluvium.overdig_m must be 0 to 1 m');
if (!num(g.bulking, 1, 2)) throw new Error('specification: ground.alluvium.bulking must be 1 to 2');
out.ground.alluvium = g;
return out;
}
export const GROUNDS = Object.freeze([['normal', 'Normal ground'], ['alluvium', 'Alluvium / soft wet ground']]);
/**
* applyGround(section, spec, groundId) -> the trench as it will be dug.
* section: a row of trench-sections.json (trench_width_m, trench_depth_m, ...).
* Returns { width, depth, benchSlope, cableDepth, support, workingWidth, overdig, bulking, notes, groundLabel, specLabel }.
* width, depth, benchSlope feed createTrench(); cableDepth is where the cables sit (the section's own depth).
*/
export function applyGround(section, spec = OPERATOR_SPEC, groundId = 'normal') {
const s = spec || OPERATOR_SPEC, w = section.trench_width_m, d = section.trench_depth_m;
const base = { width: w, depth: d, benchSlope: 0, cableDepth: d, overdig: 0, bulking: 1, support: 'none',
workingWidth: w + 1.0, groundLabel: 'Normal ground', specLabel: s.label, notes: [] };
base.notes.push(`Backfill in ${s.backfill.layer_mm} mm layers; tape ${s.marker.tape_above_service_m} m above the service`);
if (d > 1.2) { base.support = 'trench support (boxes or sheets)'; base.notes.push('Deeper than 1.2 m: support before anyone enters'); }
if (groundId !== 'alluvium') return base;
const g = s.ground.alluvium, depth = d + g.overdig_m;
const supported = depth > g.support_below_m || g.batter_h_per_v === 0;
const topWidth = supported ? w : w + 2 * g.batter_h_per_v * depth;
return {
width: w, depth, benchSlope: supported ? 0 : g.batter_h_per_v, cableDepth: d, overdig: g.overdig_m, bulking: g.bulking,
support: supported ? 'trench boxes or sheet support, walls vertical' : `battered sides ${g.batter_h_per_v} : 1 (horizontal : vertical)`,
workingWidth: topWidth + 2 * g.working_extra_m, groundLabel: g.label, specLabel: s.label,
notes: [...base.notes.slice(0, 1),
`Over-dig ${Math.round(g.overdig_m * 1000)} mm, ${g.formation}`,
`Dewatering: ${g.dewatering}`, `Spoil: ${g.spoil}`, `Keep ${s.standoff.watercourse_m} m from watercourses`, ...(g.ducts_preferred ? ['Ducts preferred over direct lay in soft ground'] : [])]
};
}
// Loose volume of spoil once dug: bank volume times the bulking factor.
export const looseSpoil = (bankM3, eff) => bankM3 * (eff?.bulking || 1);Station
A JavaScript module in the world folder of GlobalGrid2050 that works with transformers, cables and solar.
transformglobalgrid2050 / solar-design-studio/202609270220-site-world-v3/world/station.mjs · lines 1–260 of 260 · version 2026-09-27 02:20 · pattern stationInventory (shared by 3 files)
- What it does
- It calculates transformers, cables and solar. Defines 20 functions or classes, including cfg, tableShape, tableOrigin, stringsPerTable, tableStrings.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: transformers, cables, solar.
- Downstream impact
- Used directly by 11 files: Cmd Trench (globalgrid2050); Block Trenches (globalgrid2050); Block Build (globalgrid2050); MV Network (globalgrid2050); and 7 more. 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 cfg step (`cfg`), the table shape helper (`tableShape`) and the table origin helper (`tableOrigin`). Solar station library: paired tables, pole inverters, DC home cables in ducts, AC trenches, 2 x 5MVA. Its code works with 5 MVA.
- Why it matters
- Imported by 11 files, including Cmd Trench, Block Trenches and Block Build, from Energy Transition Simulator.
- Application
- globalgrid2050 · solar-design-studio/202609270220-site-world-v3/world · JavaScript module
- Uses
- none found
- Used by
- imported by Cmd Trench (import), imported by Block Trenches (import), imported by Block Build (import), imported by MV Network (import), imported by Block Build (import), imported by Earth Draw (import), imported by Earth Study (import), imported by Module View (import), and 3 more
- Produces
- STATION_DEFAULTS, tableShape, tableOrigin, stringsPerTable, tableStrings, dcOrder, seriesLinks, inverterSite, dcDucts, dcHomeRoutes, acRoute, acTrenches
- Defines here
- cfg, tableShape, tableOrigin, stringsPerTable, tableStrings, p, dcOrder, seriesLinks, inverterSite, dcDucts, dcHomeRoutes, acRoute, acTrenches, compoundBox, stationSolids, stationInventory, placer, point, box, station
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609270220-site-world-v3/world/station.mjs:1-260 · blob de97067e14359e65a6bd855026887ddfe01fc199 · 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
// Solar station library: paired tables, pole inverters, DC home cables in ducts, AC trenches, 2 x 5 MVA.
// The world draws it through block-build.mjs (Design > Solar block): placed on the measured ground, built in sequence.
//
// Source: graphics-engines-open-source, web/explore.mjs at commit 826c0df4e94b46d9b96c5fb9bfcffab52851f03a
// (branch improve/20260926, 26 Sept 2026; the explorer file there equals the working tree). Lifted lines:
// L82 dcLayout / blockLayout defaults L87 stationTableOrigin L88 defaultInverterSite
// L92 blockPosition L93 blockStrings (stationMode branch: index < 672, 24 per inverter)
// L95 dcOrder (sequential / leapfrog) L96 ridgeHeight L97 dcDucts (4 per inverter)
// L101 drawPoleInverter (box and pole) L100 drawTransformer (4 x 4 x 3 m, 12 x 10 m pad)
// L118 acLayout (28 inverters, 14 per transformer, trefoil, 0.9 m) L120-121 collectorX / acRoute, L123 acTrenches
// L127-128 compoundBox / drawCompound (12 m margin, 2.4 m fence) L143 stationInventory
// L8 stationTransformers [[155,320,1.5],[155,345,1.5]]
// The same functions sit at L68-74 and L106-108 on origin/main 037e2f79a1493a3ef422807b274c6c22ef7dc9a7.
//
// Pure functions, no globals. Geometry is local east/north/up metres. station() places it relative to a
// placement point and a heading (radians, compass: 0 = the station's +y points north, pi/2 = east).
// Labels are the source's own: equipment positions, cable routes and duct size are assumed/illustrative,
// not surveyed, and no isolators are modelled.
const RAD = Math.PI / 180;
export const STATION_DEFAULTS = Object.freeze({
// startStation() settings (explorer L142)
height: 1.2, tilt: 10, tables: 23, columns: 90, rows: 5, moduleWidth: 1.303, moduleLength: 2.384, moduleGap: 0.02,
// blockLayout (L82)
rowGap: 8, aisleGap: 10, ridgeGap: 0.5,
// electrical (L80, L143)
moduleW: 660, modulesPerString: 30, stringsPerInverter: 24, inverters: 28, invertersPerTransformer: 14,
inverterKVA: 352, transformerMVA: 5, transformers: [[155, 320, 1.5], [155, 345, 1.5]],
// dcLayout (L82); duct diameter is flagged as assumed by the source (dcWiring: ductDiameterAssumed)
wiring: 'sequential', dcDepth: 0.6, ductDiameter: 0.09, ductsPerInverter: 4, ductSpacing: 0.12,
// acLayout (L118); cable 400 mm2 Al, 800 V (acRoute labels)
acDepth: 0.9, formation: 'trefoil', acDiameter: 0.0374, acAreaMm2: 400, acVolts: 800, collectorOffset: 15,
// world-only: the underside of a table solid. Assumed, not from the source: the lowest module edge sits
// at `height`; purlins and rails are taken to hang 0.3 m below it. A drone flies under, a walker does not.
tableUnderside: 0.9
});
const cfg = p => ({ ...STATION_DEFAULTS, ...(p || {}) });
// Table cross-section: the run of one face up the slope, its plan depth, span along y, ridge height.
export function tableShape(params) {
const s = cfg(params), run = s.rows * (s.moduleLength + s.moduleGap) - s.moduleGap;
return {
run, depth: run * Math.cos(s.tilt * RAD), span: s.columns * (s.moduleWidth + s.moduleGap) - s.moduleGap,
ridge: s.height + run * Math.sin(s.tilt * RAD), halfRidgeGap: s.ridgeGap / 2
};
}
// blockPosition / stationTableOrigin (L87, L92): four paired tables across, then the next aisle.
export function tableOrigin(n, params) {
const s = cfg(params), { depth, span } = tableShape(s);
return [(n % 4) * (2 * depth + s.ridgeGap + s.rowGap), Math.floor(n / 4) * (span + s.aisleGap)];
}
export const stringsPerTable = params => { const s = cfg(params); return 2 * s.rows * Math.ceil(s.columns / s.modulesPerString); };
// blockStrings (L93), station branch: every face-row is cut into 30-module strings; the first
// inverters x stringsPerInverter strings in build order are connected, the rest are spare (assigned elsewhere).
export function tableStrings(params, { corners = true } = {}) {
const s = cfg(params), t = s.tilt * RAD, { depth, halfRidgeGap: g } = tableShape(s), out = [];
const connectedLimit = s.inverters * s.stringsPerInverter, groups = Math.ceil(s.columns / s.modulesPerString);
for (let n = 0; n < s.tables; n++) {
const [x, y] = tableOrigin(n, s);
for (const side of [-1, 1]) for (let r = 0; r < s.rows; r++) for (let group = 0; group < groups; group++) {
const modules = [];
for (let c = group * s.modulesPerString; c < Math.min(s.columns, (group + 1) * s.modulesPerString); c++) {
const v = (side === 1 ? s.rows - 1 - r : r) * (s.moduleLength + s.moduleGap), u = c * (s.moduleWidth + s.moduleGap);
const p = (dv, du) => [x + side * (g + depth - (v + dv) * Math.cos(t)), y + u + du, s.height + (v + dv) * Math.sin(t)];
const m = { terminal: p(s.moduleLength / 2, s.moduleWidth / 2), minus: p(s.moduleLength / 2, s.moduleWidth / 2 - 0.42), plus: p(s.moduleLength / 2, s.moduleWidth / 2 + 0.42) };
if (corners) m.corners = [p(0, 0), p(s.moduleLength, 0), p(s.moduleLength, s.moduleWidth), p(0, s.moduleWidth)];
modules.push(m);
}
const index = out.length, connected = index < connectedLimit;
out.push({ index, table: n, side, row: r, group, connected, inverter: connected ? Math.floor(index / s.stringsPerInverter) : null, modules });
}
}
return out;
}
// dcOrder (L95): the order modules are linked in series. Leapfrog runs out on evens, back on odds.
export function dcOrder(n, wiring = 'sequential') {
if (wiring === 'sequential') return Array.from({ length: n }, (_, i) => i);
const a = [];
for (let i = 0; i < n; i += 2) a.push(i);
for (let i = n % 2 ? n - 2 : n - 1; i >= 1; i -= 2) a.push(i);
return a;
}
// Series links of one string as polylines (module + to next module -, dropped 8 cm onto a rail; L94).
export function seriesLinks(string, wiring = 'sequential') {
const order = dcOrder(string.modules.length, wiring), links = [];
for (let i = 1; i < order.length; i++) {
const a = string.modules[order[i - 1]].plus, b = string.modules[order[i]].minus, dx = order[i] > order[i - 1] ? 0.05 : -0.05;
links.push([a, [a[0] + dx, a[1], a[2] - 0.08], [b[0] + dx, b[1], b[2] - 0.08], b]);
}
return links;
}
// defaultInverterSite (L88): one pole per 24 strings, at the end (y - 1 m) of the table that feeds it;
// shifted 1.2 m when the inverter's first string starts 24 strings into a 30-string table. Top at ridge height.
export function inverterSite(k, params) {
const s = cfg(params), spt = stringsPerTable(s), first = k * s.stringsPerInverter;
const [x, y] = tableOrigin(Math.floor(first / spt), s);
return [x + (first % spt === s.stringsPerInverter ? 1.2 : 0), y - 1, tableShape(s).ridge];
}
// dcDucts (L97): four ducts per inverter, 0.12 m apart, 2 m run at DC depth then up the pole to top - 0.9 m.
// Each duct carries up to 6 strings, a + and a - home cable each (dcWiring: L112 of origin/main).
export function dcDucts(sites, params) {
const s = cfg(params), per = Math.ceil(s.stringsPerInverter / s.ductsPerInverter);
return sites.flatMap((p, i) => Array.from({ length: s.ductsPerInverter }, (_, d) => {
const x = p[0] + (d - (s.ductsPerInverter - 1) / 2) * s.ductSpacing, strings = Math.min(per, Math.max(0, s.stringsPerInverter - d * per));
return { inverter: i + 1, duct: d + 1, diameter: s.ductDiameter, diameterAssumed: true, strings, positiveCables: strings, negativeCables: strings,
points: [[x, p[1] - 2, -s.dcDepth], [x, p[1], -s.dcDepth], [x, p[1], p[2] - 0.9]] };
}));
}
// updateBlockRoutes (explorer, station branch): each connected string's two home cables, in string order. From the
// end module's terminal onto the rail (8 cm down), along the rail to the table end (y - 1), down to DC depth, along
// to the inverter's duct (6 strings a duct, 4 ducts), 2 m past the pole and back, up the pole to top - 0.9 m.
export function dcHomeRoutes(strings, sites, params) {
const s = cfg(params), count = new Map(), out = [];
strings.filter(x => x.connected).forEach((string, i) => {
const slot = count.get(string.inverter) || 0;
count.set(string.inverter, slot + 1);
if (slot >= s.stringsPerInverter || string.modules.length > s.modulesPerString) throw Error('too many strings for one inverter');
const order = dcOrder(string.modules.length, s.wiring), dest = sites[string.inverter], duct = Math.floor(slot / 6);
const [, ty] = tableOrigin(string.table, s), ductX = dest[0] + (duct - 1.5) * s.ductSpacing, d = s.dcDepth;
for (const end of [0, 1]) {
const p = end ? string.modules[order.at(-1)].plus : string.modules[order[0]].minus;
const offset = ((slot % 6) * 2 + end - 5.5) * 0.004, railZ = p[2] - 0.08, x = ductX + offset, y = dest[1];
const points = [p, [p[0] + offset, p[1], railZ], [p[0] + offset, ty - 1, railZ], [p[0] + offset, ty - 1, -d], [x, ty - 1, -d],
[x, y - 2, -d], [x, y, -d], [x, y, dest[2] - 0.9], [dest[0], y, dest[2] - 0.9]]
.filter((q, j, a) => !j || Math.hypot(q[0] - a[j - 1][0], q[1] - a[j - 1][1], q[2] - a[j - 1][2]) > 1e-8);
out.push({ id: `S${String(i + 1).padStart(2, '0')}-${end ? 'POS' : 'NEG'}`, string: string.index, inverter: string.inverter, slot,
duct: duct + 1, polarity: end ? '+' : '-', points });
}
});
return out;
}
// collectorX / acRoute (L120-121): down the pole, east in a branch trench to the collector 15 m west of the
// transformer, along the main trench, then in. Three phases, trefoil or flat.
export function acRoute(p, t, id, label, params) {
const s = cfg(params), d = s.acDiameter, cx = t[0] - s.collectorOffset;
return [0, 1, 2].map(phase => {
const o = s.formation === 'flat' ? (phase - 1) * d : phase === 0 ? -d / 2 : phase === 1 ? d / 2 : 0;
const z = -s.acDepth + 0.05 + d / 2 + (s.formation === 'trefoil' && phase === 2 ? Math.sqrt(3) * d / 2 : 0);
const points = [[p[0] + o, p[1], p[2] - 0.9], [p[0] + o, p[1], z], [cx + o, p[1], z], [cx + o, t[1], z], [t[0] + o, t[1], z], [t[0] + o, t[1], 1]]
.filter((q, j, a) => !j || Math.hypot(q[0] - a[j - 1][0], q[1] - a[j - 1][1], q[2] - a[j - 1][2]) > 1e-8);
return { id: `${id}-L${phase + 1}`, label, areaMm2: s.acAreaMm2, volts: s.acVolts, points };
});
}
// acTrenches (L123): branch 0.35 m wide, main 2.6 m wide, depth acDepth.
export function acTrenches(sites, transformers, params) {
const s = cfg(params), out = [];
sites.forEach((p, i) => {
const t = transformers[Math.floor(i / s.invertersPerTransformer)], cx = t[0] - s.collectorOffset;
out.push({ from: [p[0], p[1]], to: [cx, p[1]], width: 0.35, depth: s.acDepth, kind: 'branch' },
{ from: [cx, p[1]], to: [cx, t[1]], width: 2.6, depth: s.acDepth, kind: 'main' },
{ from: [cx, t[1]], to: [t[0], t[1]], width: 2.6, depth: s.acDepth, kind: 'main' });
});
return out;
}
// compoundBox (L127): 12 m round the transformers; drawCompound fence 2.4 m high.
export function compoundBox(transformers) {
const xs = transformers.map(p => p[0]), ys = transformers.map(p => p[1]);
return [Math.min(...xs) - 12, Math.min(...ys) - 12, Math.max(...xs) + 12, Math.max(...ys) + 12];
}
// Solids in station-local metres, before placement: { min, max, kind, id }.
export function stationSolids(params, sites, transformers) {
const s = cfg(params), { depth, span, ridge, halfRidgeGap: g } = tableShape(s), out = [];
for (let n = 0; n < s.tables; n++) {
const [x, y] = tableOrigin(n, s);
out.push({ kind: 'table', id: n + 1, min: [x - g - depth, y, s.tableUnderside], max: [x + g + depth, y + span, ridge + 0.05] });
}
sites.forEach((p, i) => {
out.push({ kind: 'inverter', id: i + 1, min: [p[0] - 0.5, p[1] - 0.25, p[2] - 1], max: [p[0] + 0.5, p[1] + 0.25, p[2]] },
{ kind: 'pole', id: i + 1, min: [p[0] - 0.06, p[1] + 0.24, 0], max: [p[0] + 0.06, p[1] + 0.36, p[2]] });
});
transformers.forEach((p, i) => out.push({ kind: 'transformer', id: i + 1, min: [p[0] - 2, p[1] - 2, 0], max: [p[0] + 2, p[1] + 2, 3] }));
const [x0, y0, x1, y1] = compoundBox(transformers), w = 0.05, h = 2.4;
out.push({ kind: 'fence', id: 1, min: [x0, y0 - w, 0], max: [x1, y0 + w, h] }, { kind: 'fence', id: 2, min: [x0, y1 - w, 0], max: [x1, y1 + w, h] },
{ kind: 'fence', id: 3, min: [x0 - w, y0, 0], max: [x0 + w, y1, h] }, { kind: 'fence', id: 4, min: [x1 - w, y0, 0], max: [x1 + w, y1, h] });
return out;
}
// stationInventory (L143), computed rather than typed, so it moves with the parameters.
export function stationInventory(params, strings = tableStrings(params, { corners: false })) {
const s = cfg(params), connected = strings.filter(x => x.connected), tableModules = s.rows * s.columns * 2;
const connectedModules = connected.reduce((n, x) => n + x.modules.length, 0);
const perInverter = Array.from({ length: s.inverters }, (_, i) => connected.filter(x => x.inverter === i).length);
return {
illustrative: true, tables: s.tables, modulesPerTable: tableModules, stringsPerTable: stringsPerTable(s),
tableKwp: tableModules * s.moduleW / 1000, installedModules: strings.reduce((n, x) => n + x.modules.length, 0),
connectedModules, totalStrings: strings.length, connectedStrings: connected.length, spareStrings: strings.length - connected.length,
modulesPerString: s.modulesPerString, stringKwp: s.modulesPerString * s.moduleW / 1000,
maxInverterDCKwp: s.stringsPerInverter * s.modulesPerString * s.moduleW / 1000, connectedDCKwp: connectedModules * s.moduleW / 1000,
seriesLinks: connected.reduce((n, x) => n + x.modules.length - 1, 0),
inverters: s.inverters, stringsPerInverter: perInverter, inverterKVA: s.inverterKVA, aggregateInverterMVA: s.inverters * s.inverterKVA / 1000,
dcHomeCables: connected.length * 2, ductsPerInverter: s.ductsPerInverter, ducts: s.inverters * s.ductsPerInverter,
acPhaseCables: s.inverters * 3, acAreaMm2: s.acAreaMm2, invertersPerTransformer: s.invertersPerTransformer,
transformers: s.transformers.length, transformerMVA: s.transformerMVA, aggregateTransformerMVA: s.transformers.length * s.transformerMVA,
wiring: s.wiring, dcDepth: s.dcDepth, ductDiameter: s.ductDiameter, ductDiameterAssumed: true, acDepth: s.acDepth, formation: s.formation
};
}
// Placement: rotate station-local (x, y) by the compass heading, then add the placement point.
export function placer(at = [0, 0, 0], heading = 0) {
const c = Math.cos(heading), s = Math.sin(heading), z0 = at[2] || 0;
const point = ([x, y, z = 0]) => [at[0] + x * c + y * s, at[1] - x * s + y * c, z0 + z];
const box = b => {
const q = [[b.min[0], b.min[1]], [b.max[0], b.min[1]], [b.max[0], b.max[1]], [b.min[0], b.max[1]]].map(([x, y]) => point([x, y, 0]));
const xs = q.map(p => p[0]), ys = q.map(p => p[1]);
return { ...b, min: [Math.min(...xs), Math.min(...ys), z0 + b.min[2]], max: [Math.max(...xs), Math.max(...ys), z0 + b.max[2]], quad: q.map(p => [p[0], p[1]]) };
};
return { point, box };
}
// The whole station, placed. opts.corners = false skips the 4 corners of each of the 20,700 modules.
export function station(params, { at = [0, 0, 0], heading = 0, corners = true } = {}) {
const s = cfg(params), P = placer(at, heading), pts = a => a.map(P.point);
const localSites = Array.from({ length: s.inverters }, (_, k) => inverterSite(k, s));
const localTx = s.transformers.map(p => [...p]);
const strings = tableStrings(s, { corners });
const inventory = stationInventory(s, strings);
const { depth, span, ridge, halfRidgeGap: g } = tableShape(s);
const tables = Array.from({ length: s.tables }, (_, n) => {
const [x, y] = tableOrigin(n, s);
return { id: n + 1, faces: [-1, 1].map(side => pts([[x + side * (g + depth), y, s.height], [x + side * g, y, ridge],
[x + side * g, y + span, ridge], [x + side * (g + depth), y + span, s.height]])) };
});
const placedStrings = strings.map(x => ({ ...x, modules: x.modules.map(m => {
const o = { terminal: P.point(m.terminal), minus: P.point(m.minus), plus: P.point(m.plus) };
if (m.corners) o.corners = pts(m.corners);
return o;
}) }));
const acCables = localSites.flatMap((p, i) => {
const t = localTx[Math.floor(i / s.invertersPerTransformer)];
return acRoute(p, t, `ST-INV-${i + 1}`, `Inverter ${i + 1} to transformer ${Math.floor(i / s.invertersPerTransformer) + 1}; ${s.acAreaMm2} mm2 Al; ${s.acVolts} V; illustrative`, s)
.map(c => ({ ...c, points: pts(c.points) }));
});
return {
note: 'Illustrative station geometry: equipment positions, cable routes and duct size assumed, not surveyed; no isolators modelled.',
at: [...at], heading, params: s, tables, strings: placedStrings,
inverters: localSites.map((p, i) => ({ id: i + 1, point: P.point(p), transformer: Math.floor(i / s.invertersPerTransformer) + 1,
kva: s.inverterKVA, label: 'pole-mounted; port positions illustrative' })),
transformers: localTx.map((p, i) => ({ id: i + 1, point: P.point(p), mva: s.transformerMVA })),
compound: (([x0, y0, x1, y1]) => pts([[x0, y0], [x1, y0], [x1, y1], [x0, y1]]))(compoundBox(localTx)),
ducts: dcDucts(localSites, s).map(d => ({ ...d, points: pts(d.points) })),
acCables,
acTrenches: acTrenches(localSites, localTx, s).map(t => ({ ...t, from: P.point(t.from).slice(0, 2), to: P.point(t.to).slice(0, 2) })),
solids: stationSolids(s, localSites, localTx).map(P.box),
inventory
};
}