In this section
- Plan View render · energy-transition-simulator / prototype/mod/plan-view.js lines 1–421
- Plant render · energy-transition-simulator / prototype/mod/plant.js lines 1–153
Plan View
A JavaScript file in the prototype folder of Energy Transition Simulator that maps plan wire, substations and LiDAR terrain. It hides wire (`hideWire`) and applies plan (`applyPlan`).
renderenergy-transition-simulator / prototype/mod/plan-view.js · lines 1–421 of 421 · Not reached from any entry point (candidate for review) · pattern applyPlan (shared by 2 files)
- What it does
- It maps plan wire, substations and LiDAR terrain. Defines 40 functions or classes, including wait, skip, isRow, kindOf, provOf. Side effects: changes the web page (DOM); makes network requests.
- 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: substations, LiDAR terrain.
- Inputs & outputs
- Out: SVG drawing.
- What it achieves
- Plan: the massive plan in 2D, the close-up in 3D. It responds to keydown and click 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
- mentioned in Standalone (comment link)
- Produces
- wait, skip, isRow, kindOf, provOf, labelOf, drawing, hull, sigOf, keep, liveLayers, hideWire
- Defines here
- wait, skip, isRow, kindOf, provOf, labelOf, drawing, hull, sigOf, keep, liveLayers, hideWire, applyPlan, add, dimAt, fadeTo, clearPlan, kvText, relabel, take, flush, place, scale, morph, ease, morphUp, morphDown, frame, after, on
- 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/plan-view.js:1-421 · blob 0c4adedcf265d76ad9f1fe0cff87ab1748b77a88 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: experimental · users: none · canonical: unreached_review
// mod/plan-view.js - Plan: the massive plan in 2D, the close-up in 3D.
// View > Plan, the key P, or type "plan" (Enter) in any box. Plan puts the camera north-up and flat (pitch 0,
// bearing 0), dims the imagery to 35 % brightness, and redraws what is already on the map as a thin 2D line drawing: every
// wire block projected from its own buffer (the exact vertices the 3D wire draws, heights dropped), the mapped
// grid lines by voltage, substations as rings, and any AC trench and bund layers left exactly as their module drew
// them. Labels come only from objects already on the map, in their provenance style: solid = measured,
// dashed = documented, ghost = estimated (designs are ghost and say "imagined"). A scale bar and a north arrow sit
// top left; the grid-reference line (#where) is untouched.
// Zoom into the wireframe (the MORPH, with mod/morph.js): in plan, zooming in past z17.5 animates the wire world from
// the flat drawing to 3D over 1.2 s on a cubic in-out curve: the pitch eases 0 -> 60 while every height scales 0 -> 1
// (towers rise, conductors sag into place, the ground wire lifts, trench ducts sink to depth); the plan lines, labels
// and dimming fade out, never jump; the wire itself fades IN over the first 30 % (mod/morph.js fadeIn), so the first morph
// frame is the plan frame. At the end 3D is exactly today's 3D (scale 1, nothing wrapped). Zooming back out
// past z16.5 is the reverse. Entering plan from deeper than z17.5 first eases out to z16.5 flat so the zoom-in morph
// can happen. P off morphs up too (to the pitch plan was entered from, or 60). Without mod/morph.js the old 0.6 s ease runs.
// Walk, Drone, Map (or keys 1 2 3) and any find / go (a flyTo) leave plan at once: plan off, its look and legend cleared,
// no camera move of plan's own. The 3D wire itself is never restyled: in plan it is hidden, in 3D it is shown as it was.
// At a register asset, plan shows something by default: the scanner rows, the procedural fill and the AC trench model
// (when that module has a document for the asset in view) are switched on through their own buttons, once; their
// camera moves are swallowed while they load, so plan stays flat where it was. Labels: ONE per object class (text).
// Look carried over from the Kuiper drawing look (its published stage tokens: background #090c13, ink #d5dcea,
// dim #7d8799, cyan #2ee6e6, warm #e8b36a, row strokes #8ba6bb at 0.55 to 1.5 px). Values only; no code copied.
// Plain script; attaches to window.SIM. Test hook: SIM.plan = { on(), off(), toggle(), state() }.
(function () {
'use strict';
const K = { bg: 'rgba(9,12,19,.78)', ink: '#d5dcea', dim: '#7d8799', row: '#8ba6bb', obj: '#d5dcea', hot: '#e8b36a',
kv: { '400': '#2ee6e6', '275': '#e8b36a', '132': '#9fd8a8' } };
const IN = 17.5, OUT = 16.5, EASE = 600, MORPH = 1200, DIM = 0.35, PITCH3D = 60;
const PROV = ['measured', 'documented', 'estimated'];
const st = { left: [], kinds: {}, on: false, in3d: false, easing: false, morphing: false, saved: {}, prev: null, eases: [], morphs: [], labels: 0, lines: 0, sig: '', auto: null, autoBusy: false, fade: 1, pass: false };
const PLAN_LINE = ['plan-measured', 'plan-documented', 'plan-estimated', 'plan-g400', 'plan-g275', 'plan-g132'], PLAN_OP = { 'plan-measured': 1, 'plan-documented': 0.9, 'plan-estimated': 0.5, 'plan-g400': 0.9, 'plan-g275': 0.9, 'plan-g132': 0.9 };
let SIM, map, hud, labelsEl, btn, labelList = [];
function wait(n) { const S = window.SIM; if (S && S.map && (S.PF || window.__pf)) init(S); else if (n < 400) setTimeout(() => wait(n + 1), 50); }
// ---- which blocks are what: read from the tags the other mods already set ----
const skip = b => b.substationLabel !== undefined || b.pulse || b.ground || !b.buf || !b.anchor;
const isRow = b => !b.registerPoint && !!(b.sat || b.rowsGeometry || b.scannerRows || b.gpuRows || b.registerPoint === undefined && b.plant === false);
// What each projected block is, from its own module's tag (counted in state().kinds, so a check can say what plan drew).
const kindOf = b => b.scannerRows ? (b.registerPoint ? 'register-point' : 'scanner-rows') : b.gpuRows ? 'gpu-rows' : b.rowsGeometry ? 'rows-geometry'
: b.procedural ? 'procedural' : b.pylonsReal ? 'pylons' : b.substation !== undefined ? 'substation' : b.lidarStream ? 'lidar-stream'
: b.trench || b.kind === 'trench' ? 'trench' : b.plant ? 'plant' : 'other';
// Only the overlay's 3D wire and its look are hidden in plan. Other modules' own layers (procedural ghost, lidar-stream
// tiles over imagery, trench-measure) stay exactly as their module draws them: at pitch 0 they are seen from above.
const HIDE = new Set(['wire', 'wire-look-grid', 'lidar-stream-sat']); // the streamed ground mesh would cover the 2D drawing (W-ui-plan, 01:55)
function provOf(b) {
const p = typeof b.prov === 'string' ? b.prov : '';
if (b.registerPoint) return 'documented';
if (/measur/i.test(p) || b.lidar || b.lidarStream) return 'measured';
if (b.est || b.procedural || b.sat || b.gpuRows || b.scannerRows || b.designPlant || b.built || /estimat|assum|derived/i.test(p)) return 'estimated';
return 'documented';
}
function labelOf(b) {
if (b.designPlant) return 'design ' + b.designPlant + ' (imagined)';
if (b.built) return 'block (imagined)';
if (b.scannerRows && b.registerPoint) return b.scannerRows + ' register point';
if (b.scannerRows) return 'rows, scanner (estimated)';
if (b.procedural) return 'procedural ' + b.procedural + ' (estimated)';
if (b.gpuRows) return 'rows, GPU (estimated)';
if (b.rowsGeometry) return 'rows (estimated)';
if (b.substation !== undefined) return ''; // substations are labelled from their mapped points
if (b.bund) return 'bund ' + b.bund;
if (b.trench || b.kind === 'trench') return 'trench';
if (b.plant) return 'solar plant outline (mapped)';
return '';
}
// ---- the 2D drawing: each block's own buffer, anchor-relative Mercator, heights dropped ----
function drawing() {
const PF = SIM.PF || window.__pf.PF, feats = [], marks = [], kinds = {};
let n = 0;
for (const b of SIM.blocks) {
if (skip(b)) continue;
const kd = kindOf(b); kinds[kd] = (kinds[kd] || 0) + 1;
const o = PF.toMercator(b.anchor.lat, b.anchor.lon, 0), v = b.buf, segs = [];
let x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9;
for (let k = 0; k + 5 < v.length; k += 6) {
const ax = v[k], ay = v[k + 1], bx = v[k + 3], by = v[k + 4];
if (Math.abs(ax - bx) < 1e-10 && Math.abs(ay - by) < 1e-10) continue; // a vertical: a point in plan
const A = [PF.lngFromMercatorX(o.x + ax), PF.latFromMercatorY(o.y + ay)], B = [PF.lngFromMercatorX(o.x + bx), PF.latFromMercatorY(o.y + by)];
segs.push([A, B]); x0 = Math.min(x0, A[0], B[0]); x1 = Math.max(x1, A[0], B[0]); y0 = Math.min(y0, A[1], B[1]); y1 = Math.max(y1, A[1], B[1]);
}
if (!segs.length) continue;
n += segs.length;
const prov = provOf(b);
if (isRow(b)) {
// Rows as block outlines: the convex hull of the row ends (derived from the rows, nothing added) at plan scale;
// the row lines themselves (pieces of 5 m or more; shorter ones are table ends and legs seen from above) from z15.5.
const pts = []; for (const [A, B] of segs) pts.push(A, B);
feats.push({ type: 'Feature', properties: { cls: 'row', prov, hull: 1 }, geometry: { type: 'LineString', coordinates: hull(pts) } });
const k = Math.cos(b.anchor.lat * Math.PI / 180), long = segs.filter(([A, B]) => Math.hypot((B[0] - A[0]) * k, B[1] - A[1]) * 111320 >= 5);
if (long.length) feats.push({ type: 'Feature', properties: { cls: 'row', prov, hull: 0 }, geometry: { type: 'MultiLineString', coordinates: long } });
} else feats.push({ type: 'Feature', properties: { cls: 'obj', prov, hull: 0 }, geometry: { type: 'MultiLineString', coordinates: segs } });
const t = labelOf(b); if (t) marks.push({ t, prov, at: [(x0 + x1) / 2, (y0 + y1) / 2] });
}
st.lines = n; st.kinds = kinds;
return { fc: { type: 'FeatureCollection', features: feats }, marks };
}
function hull(P) { // monotone chain, closed ring
const p = P.slice().sort((a, b) => a[0] - b[0] || a[1] - b[1]), cr = (o, a, b) => (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);
const lo = [], up = [];
for (const q of p) { while (lo.length > 1 && cr(lo[lo.length - 2], lo[lo.length - 1], q) <= 0) lo.pop(); lo.push(q); }
for (let i = p.length - 1; i >= 0; i--) { const q = p[i]; while (up.length > 1 && cr(up[up.length - 2], up[up.length - 1], q) <= 0) up.pop(); up.push(q); }
const r = lo.slice(0, -1).concat(up.slice(0, -1)); r.push(r[0]); return r;
}
const sigOf = () => SIM.blocks.length + ':' + SIM.blocks.reduce((s, b) => s + (b.buf ? b.buf.length : 0), 0);
// ---- plan look on / off (layers only; the 3D wire is hidden, never changed) ----
function keep(id, what, val) { const k = id + '|' + what; if (!(k in st.saved)) st.saved[k] = val; }
const liveLayers = () => (map.getLayersOrder ? map.getLayersOrder() : (map.style && map.style._order) || []).map(id => map.getLayer(id)).filter(Boolean);
// The wire and the mapped lines: hidden in plan (the 2D drawing stands in). hideWire(false) shows the wire again for
// the morph (it fades in); the mapped lines and substations stay hidden behind their plan twins until clearPlan
// restores everything at the end (their twins fade out on the same curve, so nothing is drawn twice at full).
function hideWire(hide) {
for (const L of liveLayers()) {
const wire = L.type === 'custom' && HIDE.has(L.id), mapped = /^g(400|275|132)$/.test(L.id) || L.id === 'subs';
if (!wire && !mapped) continue;
if (hide) { keep(L.id, 'v', map.getLayoutProperty(L.id, 'visibility') || 'visible'); map.setLayoutProperty(L.id, 'visibility', 'none'); }
else if (wire && (L.id + '|v') in st.saved) map.setLayoutProperty(L.id, 'visibility', st.saved[L.id + '|v']);
}
map.triggerRepaint();
}
// fade: 1 = the plan look in full; 0 = plan lines, labels and dimming all off (the far end of the morph). No transitions:
// the morph sets every value per frame itself.
function applyPlan(fade) {
if (!map.getStyle()) return; st.fade = fade == null ? 1 : fade;
// Custom layers (the 3D wire) are left out of getStyle().layers, so walk the live layer order instead.
for (const L of liveLayers()) {
if (L.id.startsWith('plan-')) continue;
// Dim by brightness, not opacity: a parent and child tile drawn together at 35 % alpha would add up to a light patch.
if (L.type === 'raster') { keep(L.id, 'o', map.getPaintProperty(L.id, 'raster-brightness-max') ?? 1); keep(L.id, 't', map.getPaintProperty(L.id, 'raster-brightness-max-transition')); map.setPaintProperty(L.id, 'raster-brightness-max-transition', { duration: 0, delay: 0 }); map.setPaintProperty(L.id, 'raster-brightness-max', dimAt(st.fade)); }
}
if (st.fade >= 1) hideWire(true);
const d = drawing(); st.sig = sigOf(); st.marks = d.marks;
if (map.getSource('plan-wire')) map.getSource('plan-wire').setData(d.fc); else map.addSource('plan-wire', { type: 'geojson', data: d.fc });
const col = ['match', ['get', 'cls'], 'row', K.row, K.obj];
const add = (id, spec) => { if (!map.getLayer(id)) map.addLayer(Object.assign({ id }, spec)); };
add('plan-estimated', { type: 'line', source: 'plan-wire', filter: ['all', ['==', ['get', 'prov'], 'estimated'], ['any', ['==', ['get', 'cls'], 'obj'], ['==', ['get', 'hull'], 1], ['>=', ['zoom'], 15.5]]], paint: { 'line-color': col, 'line-width': 0.7, 'line-opacity': 0.5 } });
add('plan-documented', { type: 'line', source: 'plan-wire', filter: ['all', ['==', ['get', 'prov'], 'documented'], ['any', ['==', ['get', 'cls'], 'obj'], ['==', ['get', 'hull'], 1], ['>=', ['zoom'], 15.5]]], paint: { 'line-color': col, 'line-width': 0.9, 'line-opacity': 0.9, 'line-dasharray': [4, 2] } });
add('plan-measured', { type: 'line', source: 'plan-wire', filter: ['all', ['==', ['get', 'prov'], 'measured'], ['any', ['==', ['get', 'cls'], 'obj'], ['==', ['get', 'hull'], 1], ['>=', ['zoom'], 15.5]]], paint: { 'line-color': col, 'line-width': 1, 'line-opacity': 1 } });
for (const kv of ['132', '275', '400']) { // the mapped lines, thin, dashed = documented (GridAtlas)
if (!map.getSource('g' + kv)) continue;
const on = st.saved['g' + kv + '|v'] !== 'none';
add('plan-g' + kv, { type: 'line', source: 'g' + kv, layout: { visibility: on ? 'visible' : 'none' }, paint: { 'line-color': K.kv[kv], 'line-width': kv === '400' ? 1.3 : 1, 'line-opacity': 0.9, 'line-dasharray': [6, 2] } });
}
if (map.getSource('subs')) add('plan-subs', { type: 'circle', source: 'subs', paint: { 'circle-radius': 3.5, 'circle-color': 'rgba(0,0,0,0)', 'circle-stroke-color': K.hot, 'circle-stroke-width': 1 } });
for (const id of PLAN_LINE.concat('plan-subs')) if (map.getLayer(id)) { const k = id === 'plan-subs' ? 'circle-stroke-opacity' : 'line-opacity'; map.setPaintProperty(id, k + '-transition', { duration: 0, delay: 0 }); }
hud.hidden = false; labelsEl.hidden = false; relabel(); scale(); fadeTo(st.fade);
}
const dimAt = f => 1 - (1 - DIM) * f; // brightness at plan-fade f: DIM at 1, undimmed at 0
// One morph frame's look: plan lines, labels, HUD and dimming at fade f (1 = flat plan, 0 = 3D).
function fadeTo(f) {
st.fade = f;
for (const id of PLAN_LINE) if (map.getLayer(id)) map.setPaintProperty(id, 'line-opacity', PLAN_OP[id] * f);
if (map.getLayer('plan-subs')) map.setPaintProperty('plan-subs', 'circle-stroke-opacity', f);
for (const k of Object.keys(st.saved)) { const [id, what] = k.split('|'); if (what === 'o' && map.getLayer(id)) map.setPaintProperty(id, 'raster-brightness-max', dimAt(f)); }
if (labelsEl) labelsEl.style.opacity = f.toFixed(3); if (hud) hud.style.opacity = f.toFixed(3);
}
function clearPlan() {
for (const id of ['plan-measured', 'plan-documented', 'plan-estimated', 'plan-g400', 'plan-g275', 'plan-g132', 'plan-subs']) if (map.getLayer(id)) map.removeLayer(id);
if (map.getSource('plan-wire')) map.removeSource('plan-wire');
for (const k of Object.keys(st.saved)) {
const [id, what] = k.split('|'); if (!map.getLayer(id)) continue;
if (what === 'o') map.setPaintProperty(id, 'raster-brightness-max', st.saved[k]);
else if (what === 't') map.setPaintProperty(id, 'raster-brightness-max-transition', st.saved[k]); // the layer's own transition back (after its brightness, still instant)
else map.setLayoutProperty(id, 'visibility', st.saved[k]);
}
st.saved = {}; hud.hidden = true; labelsEl.hidden = true; labelsEl.textContent = ''; labelList = []; st.fade = 1;
labelsEl.style.opacity = ''; hud.style.opacity = '';
map.triggerRepaint();
}
// ---- labels: only from objects on the map; border = provenance ----
const BORDER = { measured: '1px solid', documented: '1px dashed', estimated: '1px dotted' };
function kvText(v) {
const l = String(v || '').split(/[;,]/).map(s => Math.round(+s / 1000)).filter(x => x > 0).sort((a, b) => b - a);
return l.length ? Array.from(new Set(l)).join('/') + ' kV' : '';
}
function relabel() {
if (!st.on || st.in3d) return;
const b = map.getBounds(), z = map.getZoom(), W = map.getCanvas().clientWidth, cell = 150, used = new Set(), out = [];
const c0 = map.getCenter(), cls = new Map();
// ONE label per object class (its text), at the member nearest the view centre, with the count of members in view.
const take = (t, at, prov, color) => {
if (!b.contains(at)) return; const d = (at[0] - c0.lng) ** 2 + (at[1] - c0.lat) ** 2, e = cls.get(t);
if (!e) cls.set(t, { t, at, prov, color, d, n: 1 }); else { e.n++; if (d < e.d) { e.d = d; e.at = at; } }
};
const flush = () => {
for (const e of Array.from(cls.values()).sort((a, b) => a.d - b.d)) {
const p = map.project(e.at), key = Math.floor(p.x / cell) + ',' + Math.floor(p.y / cell);
if (used.has(key) || out.length >= 60) continue; used.add(key); out.push({ t: e.n > 1 ? e.t + ' x' + e.n : e.t, at: e.at, prov: e.prov, color: e.color, n: e.n });
}
cls.clear();
};
for (const m of st.marks || []) take(m.t, m.at, m.prov, m.t.startsWith('rows') ? K.row : K.ink);
if (map.getSource('act-bunds')) for (const f of map.querySourceFeatures('act-bunds')) { // AC trench module, if present
const r = f.geometry.coordinates[0]; if (!r) continue; let x = 0, y = 0; for (const c of r) { x += c[0]; y += c[1]; }
take('bund (model)', [x / r.length, y / r.length], 'estimated', K.ink);
}
if (map.getSource('act-trench')) { const f = map.querySourceFeatures('act-trench')[0]; if (f) { const c = f.geometry.type === 'LineString' ? f.geometry.coordinates : (f.geometry.coordinates[0] || []); if (c.length) take('AC trench (model)', c[Math.floor(c.length / 2)], 'estimated', K.hot); } }
if (z >= 11 && map.getSource('subs')) for (const f of map.querySourceFeatures('subs')) {
if (f.geometry.type !== 'Point') continue; const t = kvText(f.properties.voltage);
take('substation' + (t ? ' ' + t : ''), f.geometry.coordinates, 'documented', K.hot);
}
for (const kv of ['400', '275', '132']) {
if (!map.getLayer('plan-g' + kv) || map.getLayoutProperty('plan-g' + kv, 'visibility') === 'none') continue;
for (const f of map.querySourceFeatures('g' + kv)) {
const lines = f.geometry.type === 'LineString' ? [f.geometry.coordinates] : f.geometry.coordinates;
for (const l of lines) { const inV = l.filter(c => b.contains(c)); if (inV.length) take(kv + ' kV line', inV[Math.floor(inV.length / 2)], 'documented', K.kv[kv]); }
}
}
flush();
labelsEl.textContent = ''; labelList = out;
for (const L of out) {
const d = document.createElement('div'); d.className = 'plan-label'; d.textContent = L.t;
d.style.cssText = `position:absolute;left:0;top:0;white-space:nowrap;font:10px/1.3 ui-monospace,Consolas,monospace;color:${L.color};` +
`background:${K.bg};border:${BORDER[L.prov]} ${L.color};opacity:${L.prov === 'estimated' ? 0.7 : 1};padding:0 4px;border-radius:2px;`;
d.dataset.prov = L.prov; labelsEl.appendChild(d); L.el = d;
}
st.labels = out.length; place(); void W;
}
function place() { for (const L of labelList) { const p = map.project(L.at); L.el.style.transform = `translate(${Math.round(p.x + 6)}px,${Math.round(p.y - 16)}px)`; } }
// ---- scale bar and north arrow ----
function scale() {
if (hud.hidden) return;
const c = map.getCenter(), mpp = 40075016.686 * Math.cos(c.lat * Math.PI / 180) / (512 * 2 ** map.getZoom());
const max = 120 * mpp, e = 10 ** Math.floor(Math.log10(max)), m = [5, 2, 1].map(k => k * e).find(v => v <= max) || e, px = m / mpp;
const txt = m >= 1000 ? (m / 1000) + ' km' : m + ' m';
hud.querySelector('.plan-bar').setAttribute('width', px.toFixed(1));
hud.querySelector('.plan-bar-mid').setAttribute('x1', (px / 2).toFixed(1)); hud.querySelector('.plan-bar-mid').setAttribute('x2', (px / 2).toFixed(1));
hud.querySelector('.plan-bar-end').setAttribute('x1', px.toFixed(1)); hud.querySelector('.plan-bar-end').setAttribute('x2', px.toFixed(1));
hud.querySelector('.plan-scale-t').textContent = txt;
hud.querySelector('.plan-north').style.transform = `rotate(${-map.getBearing()}deg)`;
hud.dataset.metres = m; hud.dataset.px = px.toFixed(1);
}
// ---- modes ----
const morph = () => { const M = SIM.morph || null; if (M && M.fadeIn && !M.state().fade.length) M.fadeIn(Array.from(HIDE)); return M; }; // the layers plan hides fade in with the morph
function ease(pitch, why, extra, ms) {
st.easing = true; const t0 = performance.now(); st.eases.push({ why, pitch, from: map.getPitch(), t: Math.round(t0) });
easeRaw(Object.assign({ pitch, bearing: 0, duration: ms || EASE, easing: morph() ? morph().ease : undefined }, extra || {}));
map.once('moveend', () => { st.easing = false; st.eases[st.eases.length - 1].ms = Math.round(performance.now() - t0); after(); });
}
// THE MORPH. up: flat plan -> 3D (heights 0 -> 1, pitch -> `pitch`, plan look fades out). down: 3D -> flat plan
// (the reverse; `cam` may add a zoom, e.g. the ease-out to z16.5). Both run MORPH ms on the cubic curve; the camera
// ease and the height animation share the curve and the clock. done(full) runs at the end (full = false if cut short).
function morphUp(pitch, why, done) {
const M = morph(); if (!M) { clearPlan(); ease(pitch, why); done && done(true); return; }
st.morphing = true; st.easing = true; const t0 = performance.now(), rec = { why, dir: 'up', pitch, t: Math.round(t0), frames: 0 };
st.morphs.push(rec); hideWire(false); M.set(0);
ease(pitch, why, {}, MORPH);
M.animate(1, MORPH, e => { rec.frames++; fadeTo(1 - e); }).then(full => {
rec.ms = Math.round(performance.now() - t0); rec.full = full; st.morphing = false;
if (full) { clearPlan(); M.set(1); }
done && done(full);
});
}
function morphDown(why, cam, done) {
const M = morph(); if (!M) { applyPlan(1); ease(0, why, cam); done && done(true); return; }
st.morphing = true; st.easing = true; const t0 = performance.now(), rec = { why, dir: 'down', t: Math.round(t0), frames: 0 };
st.morphs.push(rec); applyPlan(0); hideWire(false); M.set(1);
ease(0, why, cam || {}, MORPH);
M.animate(0, MORPH, e => { rec.frames++; fadeTo(e); }).then(full => {
rec.ms = Math.round(performance.now() - t0); rec.full = full; st.morphing = false;
if (full) { fadeTo(1); if (st.on && !st.in3d) { hideWire(true); after(); } M.set(1); }
done && done(full);
});
}
// A frame of the morph, held still, for pictures and checks: e = 0 the flat plan, 1 the 3D; the pitch follows.
function frame(e, pitch) {
const M = morph(); if (!M || !st.on) return false; e = Math.max(0, Math.min(1, +e || 0));
if (!map.getLayer('plan-measured')) applyPlan(1 - e);
hideWire(false); M.set(e); fadeTo(1 - e); jumpRaw({ pitch: (pitch == null ? PITCH3D : pitch) * e, bearing: 0 }); return true; // wire shown (at e = 0 it is faded to nothing)
}
// After the ease, touch the dim once more: with terrain on, a tile rendered to texture mid-ease can keep its
// earlier look (seen as one lighter square); a fresh paint value makes every tile redraw.
function after() {
if (!st.on || st.in3d) return;
for (const k of Object.keys(st.saved)) { const [id, what] = k.split('|'); if (what === 'o' && map.getLayer(id)) map.setPaintProperty(id, 'raster-brightness-max', map.getPaintProperty(id, 'raster-brightness-max') === DIM ? DIM + 0.001 : DIM); }
relabel(); scale();
}
function on() {
if (st.on) return; st.on = true; st.in3d = false; st.prev = { pitch: map.getPitch(), bearing: map.getBearing(), zoom: map.getZoom() };
mark(true);
// From deeper than the 3D threshold, ease out to z16.5 flat as the world flattens, so the zoom-in morph can happen.
const deep = map.getZoom() > IN;
morphDown('plan', deep ? { zoom: OUT } : {}, () => autoShow());
SIM.info && SIM.info('Plan: north-up 2D drawing of what is on the map. Solid = measured, dashed = documented, dotted/ghost = estimated. Zoom in past z17.5 for the 3D wire; P or View > Plan to leave.');
}
function off() {
if (!st.on) return; st.on = false; mark(false);
if (morph()) morph().cancel();
if (st.in3d) { clearPlan(); st.in3d = false; morph() && morph().set(1); return; }
// P off from the flat plan: the wire world rises to 3D, at the pitch plan was entered from (or 60 if that was flat).
const pitch = st.prev && st.prev.pitch >= 30 ? st.prev.pitch : PITCH3D;
morphUp(pitch, 'plan-off', () => { st.in3d = false; });
}
// One frame later, so the zoom's own moveend has passed before the ease listens for its end.
// (If plan was left in that frame, e.g. by Walk, the morph is dropped: the mode's own camera wins.)
function to3d() { st.in3d = true; st.easing = true; requestAnimationFrame(() => st.on ? morphUp(PITCH3D, 'zoom-in') : (st.easing = false)); }
function toPlan() { st.in3d = false; st.easing = true; requestAnimationFrame(() => st.on ? morphDown('zoom-out') : (st.easing = false)); }
// Walk, Drone, Map (buttons, View menu, keys 1 2 3) and find / go leave plan cleanly: plan off, its look cleared, the
// morph cut and every height back to 1, and NO camera move of plan's own, so the mode's pitch, zoom, speed and the
// current bearing are exactly what the mode (or the go) sets.
function leave(why) {
if (!st.on) return; st.on = false; st.in3d = false; st.easing = false; st.morphing = false; mark(false);
if (morph()) { morph().cancel(); morph().set(1); } clearPlan();
st.pass = true; setTimeout(() => { st.pass = false; }, 0); // the mode's own camera move follows synchronously: let it through the swallow
st.left.push({ why, t: Math.round(performance.now()) });
}
// Something by default at a register asset (once per module): the scanner rows, the procedural fill and the AC trench
// model when it has a document for a register point in view. Their own buttons are pressed, so their own labels,
// captions and checks apply; camera moves they make while loading are swallowed (plan stays flat where it is).
async function autoShow() {
if (!st.on || st.in3d || st.autoBusy) return; st.autoBusy = true; const did = st.auto = st.auto || { scanner: false, procedural: false, trenches: false, tried: 0 }; did.tried++;
// After every await: if plan was left meanwhile (Walk, Drone, Map, go), press no further button.
try {
run: {
const S = SIM, PF = S.PF || (window.__pf && window.__pf.PF);
if (S.scannerRows && !did.scanner && !S.blocks.some(b => b.scannerRows)) { did.scanner = true; await S.scannerRows.run(); }
if (!st.on || st.in3d) break run;
const pb = document.getElementById('procedural');
if (pb && !did.procedural && !pb.classList.contains('on')) { did.procedural = true; pb.click(); }
const A = window.__acTrenches;
if (A && !did.trenches && !A.state().on && PF) {
const b = map.getBounds(), reg = S.blocks.find(x => x.scannerRows && x.registerPoint && b.contains([x.lon, x.lat]));
const id = reg && String(reg.scannerRows).replace(/\D/g, '');
if (id) {
const r = await fetch('mod/ac-trenches-' + id + '.json', { method: 'HEAD' }).catch(() => null);
if (!st.on || st.in3d) break run;
if (r && r.ok) { did.trenches = true; await A.toggle(); }
}
}
}
} catch (e) { console.warn('plan autoShow', e); }
st.autoBusy = false;
if (st.on && !st.in3d && !st.morphing) { if (map.getPitch() !== 0 || map.getBearing() !== 0) jumpRaw({ pitch: 0, bearing: 0 }); refresh(true); }
}
const toggle = () => (st.on ? off() : on());
function mark(v) { if (btn) { btn.classList.toggle('on', v); btn.setAttribute('aria-pressed', String(v)); } }
let easeRaw = o => map.easeTo(o), jumpRaw = o => map.jumpTo(o), refresh = () => {};
function init(S) {
if (SIM) return; SIM = S; map = S.map;
// Plan's own camera calls go straight through; while plan switches modules on (autoBusy), their framing moves (a zoom)
// are swallowed until autoShow has finished, even after plan was left, except the one synchronous move of the mode
// (Walk, Drone, Map) that made it leave (st.pass, set by leave() for the current task).
const e0 = map.easeTo.bind(map), j0 = map.jumpTo.bind(map), f0 = map.flyTo.bind(map);
easeRaw = o => e0(o); jumpRaw = o => j0(o);
const framing = a => st.autoBusy && !st.pass && a[0] && a[0].zoom != null; // a module framing its asset (has a zoom); Walk keys never set zoom
map.easeTo = (...a) => (framing(a) ? map : e0(...a));
map.jumpTo = (...a) => (framing(a) ? map : j0(...a));
map.flyTo = (...a) => { if (st.on) leave('go'); return f0(...a); }; // find / go, addresses, a substation click
hud = document.createElement('div'); hud.id = 'plan-hud'; hud.hidden = true;
hud.style.cssText = `position:fixed;left:10px;top:calc(var(--btn, 30px) + 10px);z-index:6;pointer-events:none;color:${K.ink};` +
`font:10px/1.3 ui-monospace,Consolas,monospace;background:${K.bg};border:1px solid #1a2030;border-radius:4px;padding:6px 8px;`;
hud.innerHTML = '<div style="display:flex;align-items:center;gap:10px">'
+ '<svg class="plan-north" width="18" height="26" viewBox="0 0 18 26" aria-label="North"><path d="M9 2 L15 20 L9 16 L3 20 Z" fill="none" stroke="' + K.ink + '" stroke-width="1"/><path d="M9 2 L9 16 L3 20 Z" fill="' + K.ink + '"/><text x="9" y="26" fill="' + K.ink + '" font-size="7" text-anchor="middle">N</text></svg>'
+ '<svg width="130" height="22" aria-label="Scale bar"><g transform="translate(2,4)"><rect class="plan-bar" x="0" y="6" width="100" height="3" fill="none" stroke="' + K.ink + '" stroke-width="1"/>'
+ '<line x1="0" x2="0" y1="3" y2="12" stroke="' + K.ink + '"/><line class="plan-bar-mid" x1="50" x2="50" y1="6" y2="12" stroke="' + K.ink + '"/><line class="plan-bar-end" x1="100" x2="100" y1="3" y2="12" stroke="' + K.ink + '"/></g></svg>'
+ '<span class="plan-scale-t"></span></div>'
+ '<div style="color:' + K.dim + ';margin-top:3px">PLAN · north up · <span style="border-bottom:1px solid">measured</span> <span style="border-bottom:1px dashed">documented</span> <span style="border-bottom:1px dotted;opacity:.7">estimated</span></div>';
document.body.appendChild(hud);
labelsEl = document.createElement('div'); labelsEl.id = 'plan-labels'; labelsEl.hidden = true;
labelsEl.style.cssText = 'position:fixed;inset:0;z-index:4;pointer-events:none;overflow:hidden';
document.body.appendChild(labelsEl);
map.on('move', () => { if (st.on && !st.in3d) { place(); scale(); } });
// Blocks other mods add after a move (substation fences, towers) join the drawing at the next moveend or idle.
refresh = force => {
if (!st.on || st.in3d || st.easing) return; const changed = sigOf() !== st.sig;
if (changed) { const d = drawing(); st.sig = sigOf(); st.marks = d.marks; const s = map.getSource('plan-wire'); if (s) s.setData(d.fc); }
if (st.fade >= 1 && !st.morphing) hideWire(true); // a wire layer added since plan came on (the streamed ground arriving) is hidden too
if (changed || force) relabel();
};
map.on('moveend', () => refresh(true)); map.on('idle', () => refresh(false));
// Crossings only: in plan, a zoom that ENDS deeper than z17.5 after starting shallower eases into 3D, and back.
map.on('zoomstart', () => { if (!st.easing) st.z0 = map.getZoom(); });
map.on('zoomend', () => {
if (!st.on || st.easing || st.morphing) return; const z = map.getZoom(), z0 = st.z0 ?? z;
if (!st.in3d && z > IN && z0 <= IN) to3d(); else if (st.in3d && z < OUT && z0 >= OUT) toPlan();
});
map.on('style.load', () => setTimeout(() => { if (st.on && !st.in3d) { st.saved = {}; applyPlan(); } }, 150));
addEventListener('keydown', e => {
if (e.ctrlKey || e.metaKey || e.altKey) return;
const t = e.target, typing = t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable);
if (typing) {
if (e.key !== 'Enter') return; const v = String(t.value || '').trim().toLowerCase();
if (!/^plan( on| off)?$/.test(v)) return;
e.preventDefault(); e.stopImmediatePropagation(); t.value = '';
if (v === 'plan on') on(); else if (v === 'plan off') off(); else toggle(); return;
}
if (e.key === 'p' || e.key === 'P') toggle();
else if ((e.key === '1' || e.key === '2' || e.key === '3') && !(window.walkFps && window.walkFps.state().on)) leave('key ' + e.key);
}, true);
// Clicks reach #walk / #drone / #map2d from the bar and from the View menu (its items click them); capture phase,
// so plan is off before the page's setMode starts its ease.
document.addEventListener('click', e => { const t = e.target && e.target.closest && e.target.closest('#walk,#drone,#map2d'); if (t) leave(t.id); }, true);
// View > Plan: once the menu bar is up, the item sits after Map (3); without a menu bar it is a plain button.
(function menu(n) {
const slot = document.querySelector('.gm-panel[data-menu="View"] .gm-slot[data-key="map-item"]');
if (!slot && n < 200) return setTimeout(() => menu(n + 1), 100);
btn = document.createElement('button'); btn.id = 'plan-view'; btn.textContent = 'Plan (P)'; btn.setAttribute('aria-pressed', 'false');
btn.addEventListener('click', () => { toggle(); if (SIM.menu) SIM.menu.close(); });
if (slot) { const s = document.createElement('div'); s.className = 'gm-slot'; s.dataset.key = 'plan'; s.appendChild(btn); slot.after(s); }
else if (S.addButton) { const b = S.addButton('Plan (P)', toggle); btn = b; b.id = 'plan-view'; }
mark(st.on);
})(0);
SIM.plan = { on, off, toggle, frame, autoShow,
state: () => ({ on: st.on, in3d: st.in3d, easing: st.easing, morphing: st.morphing, morphs: st.morphs.slice(), fade: +st.fade.toFixed(3), auto: st.auto && Object.assign({}, st.auto), autoBusy: st.autoBusy,
morphT: SIM.morph ? SIM.morph.state().t : null, morphActive: SIM.morph ? SIM.morph.state().active : null, pass: st.pass,
pitch: +map.getPitch().toFixed(2), bearing: +map.getBearing().toFixed(2), zoom: +map.getZoom().toFixed(2),
scaleBar: !!(hud && !hud.hidden && hud.querySelector('.plan-bar')), scaleM: hud ? +hud.dataset.metres || 0 : 0, scalePx: hud ? +hud.dataset.px || 0 : 0,
labels: st.labels, kinds: Object.assign({}, st.kinds), left: st.left.slice(), labelProv: labelList.map(l => l.prov), lines: st.lines, eases: st.eases.slice(),
dimmed: Object.keys(st.saved).filter(k => k.endsWith('|o')).length, hidden: Object.keys(st.saved).filter(k => k.endsWith('|v')).map(k => k.split('|')[0]) }),
thresholds: { in: IN, out: OUT, easeMs: EASE, morphMs: MORPH, pitch3d: PITCH3D, dim: DIM }, provenance: PROV };
}
wait(0); // last, so every const above exists
})();Plant
A JavaScript file in the prototype folder of Energy Transition Simulator that draws cables and trench sections. It adds lines (`addLines`) and groups lines (`groupLines`).
renderenergy-transition-simulator / prototype/mod/plant.js · lines 1–153 of 153 · Not reached from any entry point (candidate for review) · pattern numbers (shared by 2 files)
- What it does
- It draws cables and trench sections. Defines 16 functions or classes, including E, start, mount, $, addLines. Side effects: changes the web page (DOM); makes network requests.
- 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, 33kV.
- Inputs & outputs
- In: JSON file cables.json; JSON file trench-sections.json; form fields (user input). Voltage levels named: 33kV.
- What it achieves
- The morning engine's own plant generator on the map. Its code works with 33 kV. It responds to 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
- mentioned in Standalone (comment link)
- Produces
- E, start, mount, $, addLines, clearDrawn, plantLines, at, seg, path, cube, groupLines
- Defines here
- E, start, mount, $, addLines, clearDrawn, plantLines, at, seg, path, cube, groupLines, f, newSession, numbers, run
- 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/plant.js:1-153 · blob 6e0557ffdfe07193c6e88455ac53f31a56f77cee · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: experimental · users: none · canonical: unreached_review
// plant.js: the morning engine's own plant generator on the map. A "Design" box takes the same typed commands as the
// engine (plant 50mw, plant 50mw south, block 10mva, pitch 6, tilt 25, clear ...). Every command runs through the engine's
// own session (engine/cmd-model.mjs, copied unchanged from v12 with its commit in each header); the layout is the
// engine's layoutPlant (engine/plant-layout.mjs) and the block is its buildBlock (engine/block-build.mjs).
// This file is only the thin adapter: it gives the session a boundary (open land centred on the map centre, sized by
// the engine's own open-land rule), runs the pure functions in local metres (east, north) and draws their lines as
// window.SIM wireframe blocks anchored at that lon/lat, so the drawing stays fixed in real coordinates.
// Assumption, labelled on screen: the ground is taken as flat (height 0 at the anchor); no measured ground is read here.
// Generic, editable parameters only: the engine defaults, changed by what is typed.
(function () {
const here = document.currentScript && document.currentScript.src ? document.currentScript.src : location.href;
const E = n => new URL('engine/' + n, here).href;
function start(SIM, PF) {
Promise.all([import(E('cmd-model.mjs')), import(E('plant-layout.mjs')), import(E('block-build.mjs')),
fetch(E('data/cables.json')).then(r => r.json()), fetch(E('data/trench-sections.json')).then(r => r.json()).then(j => j.sections || [])])
.then(([CM, PL, BB, catalogue, sections]) => mount(SIM, PF, CM, PL, BB, catalogue, sections))
.catch(e => SIM.info('Design: the engine did not load (' + e.message + ')'));
}
function mount(SIM, PF, CM, PL, BB, catalogue, sections) {
const map = SIM.map;
let anchor = null, session = null, lastLayout = null, lastBlock = null;
// ---- panel ----
const css = document.createElement('style');
css.textContent = `#design-box{position:absolute;right:8px;top:52px;z-index:4;width:340px;max-width:calc(100vw - 32px);
font:11px/1.45 ui-monospace,SFMono-Regular,Consolas,monospace;color:#d0d4d8;background:rgba(0,0,0,.78);
border:1px solid rgba(208,212,216,.25);border-radius:4px;padding:6px 8px}
#design-box input{width:100%;box-sizing:border-box;font:inherit;color:#fff;background:#000;border:1px solid #445;padding:4px 6px}
#design-box .k{color:#8a9096}#design-box .n{color:#fff}#design-box .w{color:#ffb020}#design-box pre{margin:4px 0 0;white-space:pre-wrap}`;
document.head.appendChild(css);
const box = document.createElement('div'); box.id = 'design-box';
box.innerHTML = '<div class="k">Design (type as in the engine: plant 50mw south, block 10mva, pitch 6, tilt 25, clear)</div>'
+ '<input id="design-cmd" spellcheck="false" autocomplete="off" placeholder="plant 50mw"><pre id="design-echo"></pre><pre id="design-nums"></pre>';
document.body.appendChild(box);
const $ = id => document.getElementById(id);
// ---- drawing: engine lines (local metres east, north, up) into SIM blocks at the anchor ----
function addLines(lines, tag) {
if (!lines.length) return;
const a = PF.placeKey(anchor.lat, anchor.lon), off = PF.toLocal(a, anchor.lat, anchor.lon, 0);
for (let i = 0; i < lines.length; i += 20000) { // chunks keep each buffer moderate
const L = lines.slice(i, i + 20000).map(([x0, y0, z0, x1, y1, z1]) => [x0 + off.x, y0 + off.y, z0, x1 + off.x, y1 + off.y, z1]);
SIM.addBlock({ lon: anchor.lon, lat: anchor.lat, anchor: a, lines: L, buf: PF.wireBuffer(a, L), designPlant: tag });
}
}
const clearDrawn = tag => SIM.removeWhere(b => b.designPlant && (!tag || b.designPlant === tag));
function plantLines(r) {
const F = r.frame, T = r.table, P = r.params, out = [];
const at = (u, v, z) => { const [e, n] = F.en(u, v); return [e, n, z]; };
const seg = (a, b) => out.push([...a, ...b]);
const path = (pts, z) => { for (let i = 1; i < pts.length; i++) seg(at(...pts[i - 1], z), at(...pts[i], z)); };
for (const f of r.fields || [r.boundary]) path([...f, f[0]], 1.5); // fence
const lo = P.lowEdgeM, hi = lo + T.rise, t = r.tables;
for (let q = 0; q < t.length; q += 6) { // tables (flat ground)
const ua = t[q], va = t[q + 1], ub = ua + (r.tableLen?.[q / 6] ?? T.lenU), vb = va + T.depth;
if (T.south) { const A = at(ua, va, lo), B = at(ub, va, lo), C = at(ub, vb, hi), D = at(ua, vb, hi); seg(A, B); seg(B, C); seg(C, D); seg(D, A); }
else if (T.tracker) { const z = 1.5, vm = (va + vb) / 2; seg(at(ua, va, z), at(ub, va, z)); seg(at(ub, va, z), at(ub, vb, z)); seg(at(ub, vb, z), at(ua, vb, z)); seg(at(ua, vb, z), at(ua, va, z)); seg(at(ua, vm, z), at(ub, vm, z)); }
else { const vm = (va + vb) / 2, A = at(ua, va, lo), B = at(ub, va, lo), C = at(ub, vb, lo), D = at(ua, vb, lo), M = at(ua, vm, hi), N = at(ub, vm, hi);
seg(A, B); seg(D, C); seg(M, N); seg(A, M); seg(M, D); seg(B, N); seg(N, C); }
}
const sp = r.spine; // roads
for (const d of [-P.spineWidthM / 2, P.spineWidthM / 2]) path([[sp.u + d, sp.v0], [sp.u + d, sp.v1]], 0.05);
for (const tr of r.trackRoads) for (const d of [-P.trackWidthM / 2, P.trackWidthM / 2]) path([[tr.u0, tr.v + d], [tr.u1, tr.v + d]], 0.05);
if (r.access) for (const d of [-P.trackWidthM / 2, P.trackWidthM / 2]) path([[r.access.u0, r.access.v + d], [r.access.u1, r.access.v + d]], 0.05);
const cube = (u, v, w, dp, h) => { const c = [[u - w / 2, v - dp / 2], [u + w / 2, v - dp / 2], [u + w / 2, v + dp / 2], [u - w / 2, v + dp / 2]];
for (let i = 0; i < 4; i++) { const a = c[i], b = c[(i + 1) % 4]; seg(at(...a, 0), at(...b, 0)); seg(at(...a, h), at(...b, h)); seg(at(...a, 0), at(...a, h)); } };
for (const s of r.stations) cube(s.u, s.v, 12, 3, 3); // stations (skid boxes)
const cm = r.compound; cube(cm.u, cm.v, cm.w, cm.d, 2.4); // compound fence
return out;
}
function groupLines(groups) { // buildBlock groups: base + relative xyz pairs
const out = [];
for (const G of Object.values(groups)) { const b = G.base, v = G.v;
for (let i = 0; i + 5 < v.length; i += 6) out.push([b[0] + v[i], b[1] + v[i + 1], b[2] + v[i + 2], b[0] + v[i + 3], b[1] + v[i + 4], b[2] + v[i + 5]]); }
return out;
}
// ---- the engine interface the session calls (cmd-model.mjs createSession) ----
const f = (x, d = 1) => (Number.isFinite(x) ? x.toLocaleString('en-GB', { minimumFractionDigits: d, maximumFractionDigits: d }) : '-');
const engine = {
drawnBoundary: () => null,
setBoundary: () => {},
async openLand(input) { // plant-ui.mjs useOpenLand's square, centred on the anchor (0, 0)
const ld = { ...PL.LAYOUT_DEFAULTS, ...(input.options || {}) };
const T = PL.tableGeometry(input.layout, ld, CM.derive({ ...CM.DEFAULTS, mw: input.mw, layout: input.layout }, { catalogue }).tpl);
const tpl = CM.derive({ ...CM.DEFAULTS, mw: input.mw, layout: input.layout }, { catalogue }).tpl;
const side = Math.sqrt(Math.ceil(tpl.counts.strings / 2) * T.pitch * (T.lenU + PL.LAYOUT_DEFAULTS.tableGapM) * 1.5) + 2 * input.fenceSetbackM, h = side / 2;
return [[-h, -h], [h, -h], [h, h], [-h, h]];
},
async layout(input) {
const t0 = performance.now();
const r = PL.layoutPlant({ boundary: session.state().boundary, targetMW: input.mw, layout: input.layout, template: input.template, piles: false,
groundAt: () => 0, grid: null, water: [], ohl: null,
options: { ...(input.options || {}), slopeLimitPct: input.slopeLimitPct, fenceSetbackM: input.fenceSetbackM } });
r.seconds = (performance.now() - t0) / 1000; lastLayout = r;
clearDrawn('plant'); addLines(plantLines(r), 'plant');
return CM.summarize(r); // the engine's own summary (cmd-model.mjs)
},
clearPlant() { clearDrawn('plant'); lastLayout = null; },
async block({ stations, pocKv, at, trench, modulesPerString }) {
const s0 = lastLayout?.stations?.[0], p = at ? [at.e, at.n] : s0 ? lastLayout.frame.en(s0.u + 20, s0.v + 10) : [0, 0];
const b = BB.buildBlock({ anchor: p, ground: () => 0, stations, pocKv: pocKv || 400, trench, ...(modulesPerString ? { modulesPerString } : {}) });
lastBlock = b; clearDrawn('block'); addLines(groupLines(b.groups), 'block');
return { text: `Block of ${stations} station(s): ${f(b.summary.blockKwp / 1000, 2)} MWp DC, ${b.summary.inventory.installedModules.toLocaleString('en-GB')} modules`, at: { e: p[0], n: p[1] } };
},
clearBlock() { clearDrawn('block'); lastBlock = null; },
piles: async () => 'Piles are not drawn on the map in this module.',
show: () => 'show is not in this module.', go: () => 'go is not in this module.',
constraints: () => [], avoid: () => []
};
const newSession = () => { session = CM.createSession({ engine, env: { latDeg: anchor?.lat ?? 52, catalogue, sections } }); };
function numbers() {
const r = lastLayout, rows = [];
if (r) {
const area = Math.abs((r.fields || [r.boundary]).reduce((t, p) => t + PL.polyArea(p), 0)) / 1e4, d = session.derived();
rows.push(['Asked', `${r.asked.mw} MW export, ${f(r.asked.mwp)} MWp DC`],
['Achieved', `${r.built.mw} MW export, ${f(r.built.mwp)} MWp DC${r.fits ? '' : ' (does not all fit)'}`],
['Tables', `${r.built.tables.toLocaleString('en-GB')} tables of ${r.table.modules} modules each, ${{ south: 'south-facing', tracker: 'single-axis tracker rows' }[r.layout] || 'east-west'}, ${r.packing} packing`],
['Rows', `${r.rows} rows between tracks, runs of ${r.perRun} tables`],
['Row pitch', `${f(d.T.pitch, 2)} m${d.gcr ? `, GCR ${f(d.gcr, 2)}` : ''}, tilt ${f(r.layout === 'south' ? d.st.tilt : d.st.tiltEw, 0)} deg`],
['Area', `${f(area)} ha inside the fence, ${f(d.lay?.rowsHa)} ha under rows`],
['Stations', String(r.built.stations)], ['33 kV feeders', String(r.built.feeders)],
['Roads', `${f(r.built.roadM / 1000, 2)} km`], ['Worked out in', `${f(r.seconds, 2)} s`]);
r.notes.forEach((n, i) => rows.push([i ? '' : 'Notes', n]));
}
if (lastBlock) rows.push(['Block', `${f(lastBlock.summary.blockKwp / 1000, 2)} MWp DC, ${lastBlock.summary.inventory.installedModules.toLocaleString('en-GB')} modules`]);
rows.push(['', PL.LABEL + ' Ground taken as flat here (not measured).']);
$('design-nums').textContent = rows.map(([k, v]) => (k ? k.padEnd(14) : ' '.repeat(14)) + v).join('\n');
}
async function run(line) {
line = String(line || '').trim(); if (!line) return;
if (/^clear$/i.test(line)) { clearDrawn(); anchor = null; session = null; lastLayout = null; lastBlock = null; $('design-echo').textContent = 'Cleared.'; $('design-nums').textContent = ''; return; }
if (!session) { const c = map.getCenter(); anchor = { lon: c.lng, lat: c.lat }; newSession(); } // origin at the map centre, then fixed
$('design-echo').textContent = 'Working: ' + line;
await new Promise(r => setTimeout(r, 0));
let res;
try { res = await session.exec(line); } catch (e) { res = { ok: false, text: e.message }; }
$('design-echo').textContent = (res.ok ? '' : 'Refused: ') + (res.text || line);
numbers();
SIM.info(lastLayout ? `Design: ${lastLayout.built.mw} MW, ${lastLayout.built.tables.toLocaleString('en-GB')} tables. ${PL.LABEL}` : 'Design: ' + (res.text || ''));
window.__design = { last: res, layout: lastLayout ? { asked: lastLayout.asked, built: lastLayout.built, rows: lastLayout.rows, pitch: lastLayout.table.pitch } : null, anchor };
}
$('design-cmd').addEventListener('keydown', e => { if (e.key === 'Enter') { const v = e.target.value; e.target.value = ''; run(v); } });
window.__designRun = run;
}
(function wait() { if (window.SIM && window.__pf && window.__pf.PF) start(window.SIM, window.__pf.PF); else setTimeout(wait, 100); })();
})();