In this section
- Menu Bar render · energy-transition-simulator / prototype/mod/menu-bar.js lines 1–294
- Menu Style render · energy-transition-simulator / prototype/mod/menu-style.js lines 1–49
- Morph render · energy-transition-simulator / prototype/mod/morph.js lines 1–122
- Perf render · energy-transition-simulator / prototype/mod/perf.js lines 1–136
Menu Bar
A JavaScript file in the prototype folder of Energy Transition Simulator that opens name (`openName`), sets kV (`setKv`) and refreshes about (`refreshAbout`), covering substations, 275kV and LiDAR terrain.
renderenergy-transition-simulator / prototype/mod/menu-bar.js · lines 1–294 of 294 · Not reached from any entry point (candidate for review) · pattern creditText (shared by 2 files)
- What it does
- It draws substations, 275kV and LiDAR terrain. Defines 20 functions or classes, including wait, init, openName, close, open. Side effects: changes the web page (DOM); reads or writes files; 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, 275kV, LiDAR terrain, 400kV, 132kV.
- Inputs & outputs
- In: JSON file index.json. Voltage levels named: 400kV, 275kV, 132kV.
- What it achieves
- It opens name (`openName`), sets kV (`setKv`) and refreshes about (`refreshAbout`). One menu bar instead of a toolbar: File, Edit, View, Scope, Grid, About, with Walk, Drone and Map at the right end. Its code works with 275 kV, 132 kV and 400 kV. It reads `mod/index.json`. It responds to click, mouseenter and keydown events.
- Why it matters
- No other file in the estate was found to import it.
- Application
- energy-transition-simulator · prototype/mod · script
- Uses
- none found
- Used by
- mentioned in Standalone (comment link)
- Produces
- wait, init, openName, close, open, labelOf, entryFor, place, defaultLabel, item, click, setKv
- Defines here
- wait, init, openName, close, open, labelOf, entryFor, place, defaultLabel, item, click, setKv, refreshAbout, PF, gridRef, pad, writeWhere, soon, creditText, writeStrip
- 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/menu-bar.js:1-294 · blob a90c983a6991e7bbc1ab2b8fb828fd3a15833edf · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: experimental · users: none · canonical: unreached_review
// mod/menu-bar.js - one menu bar instead of a toolbar: File, Edit, View, Scope, Grid, About, with Walk, Drone and
// Map at the right end. Plain script; load it LAST in mod/index.json (menu-style.js first).
// Nothing is cloned: every existing button, input and readout is MOVED (appendChild) into its menu, so its handler,
// its .on state and the label text the mods write ("Pylons (37)", "to 275 kV") keep working on the same element.
// Late buttons (SIM.addButton, or anything a mod appends to #bar) are routed by label; a label that matches nothing
// lands under Scope > More with a console note, so no control is ever lost.
// Menu idiom from GridAtlas menu-bar.js (six titles, closed at rest, one panel open at a time, Escape and an outside
// click close, arrow keys move across titles); colours from the site-world release tokens (menu-style.js).
// Test hook: SIM.menu = { controls(), open(name), close(), openName(), titles }.
(function () {
'use strict';
const TITLES = ['File', 'Edit', 'View', 'Scope', 'Grid', 'About'];
// The routing table: [menu, key, how to find it]. `id` = element id in the page; `re` = label at the moment it
// arrives; `sel` = a CSS selector. The 22 controls of 28 Sept are marked core: true.
const TABLE = [
['File', 'here', { id: 'here', core: true, label: 'Build block here' }],
['File', 'connect', { re: /^Connect here/, core: true }],
['File', 'design-box', { id: 'design-box', box: true }],
['File', 'clear-design', { make: 'Clear design' }],
['File', 'export', { make: 'Export view as image (not built yet)', disabled: true }],
['Edit', 'kv', { re: /^to \d+ kV$/, core: true }],
['Edit', 'mw', { re: /^\d+ MW$/, core: true }],
['Edit', 'route', { re: /^(Road route|Straight)$/, core: true }],
['Edit', 'sub-input', { sel: 'input[placeholder^="go substation"]', core: true }],
['Edit', 'fg', { id: 'fg', box: true }],
['View', 'walk-item', { make: 'Walk (1)', proxy: 'walk' }],
['View', 'drone-item', { make: 'Drone (2)', proxy: 'drone' }],
['View', 'map-item', { make: 'Map (3)', proxy: 'map2d' }],
['View', 'fps', { id: 'walk-fps', core: true, label: 'First person' }],
['View', 'tilt', { id: 'tilt', core: true }],
['View', 'north', { make: 'Reset north' }],
['View', 'zin', { make: 'Zoom in' }],
['View', 'zout', { make: 'Zoom out' }],
['View', 'spd', { id: 'spd', box: true }],
['Scope', 'sat', { id: 'sat', core: true }],
['Scope', 'dark', { id: 'dark', core: true }],
['Scope', 'wire', { id: 'wire', core: true }],
['Scope', 'survey', { id: 'survey', core: true, label: 'Survey grid' }],
['Scope', 'lidar', { re: /^LiDAR/, core: true }],
['Scope', 'rows', { id: 'rows', core: true }],
['Scope', 'detect', { id: 'detect', core: true }],
['Scope', 'gpu-rows', { re: /^GPU rows/, core: true }],
['Scope', 'scanner-rows', { re: /^Scanner rows/ }],
['Scope', 'farm-assess', { re: /^Assess land/ }],
['Scope', 'stream', { re: /stream/i }],
['Scope', 'procedural', { re: /procedural|generate/i }],
['Scope', 'more', { more: true }],
['Grid', 'pylons', { id: 'pylons', core: true }],
['Grid', 'pylons-real', { re: /^Pylons \((mapped|real)/, core: true }],
['Grid', 'substations', { re: /^Substations/, core: true }],
['Grid', 'g400', { make: '400 kV lines', kv: '400' }],
['Grid', 'g275', { make: '275 kV lines', kv: '275' }],
['Grid', 'g132', { make: '132 kV lines', kv: '132' }],
['Grid', 'trench', { re: /^Trench/ }],
['Grid', 'completion', { re: /complet/i }],
['Grid', 'pf-readout', { id: 'pf-readout', box: true }],
['Grid', 'coords-hud', { id: 'coords-hud', box: true }],
['About', 'controls', { make: 'Controls and keys' }],
['About', 'credits', { make: 'Credits' }],
['About', 'modules', { make: 'Modules loaded' }]
];
const VIEWS = ['walk', 'drone', 'map2d'];
function wait(n) { if (window.SIM && window.SIM.map && document.getElementById('bar')) init(); else if (n < 400) setTimeout(() => wait(n + 1), 50); }
wait(0);
function init() {
if (document.getElementById('sim-menu')) return;
const SIM = window.SIM, map = SIM.map, bar = document.getElementById('bar');
const css = document.createElement('style'); css.id = 'menu-bar-style';
css.textContent = `
#sim-menu { position: fixed; top: 0; left: 0; right: 0; height: var(--btn, 30px); z-index: 20; display: flex; align-items: stretch;
background: var(--panel); border-bottom: 1px solid var(--edge); font: 12px system-ui, sans-serif; }
#sim-menu .gm-titles { display: flex; align-items: stretch; }
#sim-menu .gm-title { background: transparent; border: 0; border-bottom: 1px solid transparent; border-radius: 0; color: var(--dim);
padding: 0 9px; min-height: 0; height: 100%; }
#sim-menu .gm-title:hover, #sim-menu .gm-title[aria-expanded="true"] { color: #fff; border-bottom-color: var(--line); background: transparent; }
#sim-menu .gm-views { margin-left: auto; display: flex; align-items: stretch; }
#sim-menu .gm-views button { border: 0; border-bottom: 1px solid transparent; border-radius: 0; background: transparent; min-height: 0; height: 100%; padding: 0 9px; }
#sim-menu .gm-views button.on { color: #fff; border-bottom-color: var(--line); }
.gm-panel { position: fixed; top: calc(var(--btn, 30px) + 2px); min-width: 220px; width: max-content; max-width: min(340px, calc(100vw - 16px));
max-height: calc(100vh - 90px); overflow: auto; z-index: 21; background: var(--panel); border: 1px solid var(--edge); border-radius: 6px; padding: 6px; box-sizing: border-box; }
.gm-panel[hidden] { display: none; }
.gm-panel h2 { margin: 6px 6px 4px; }
.gm-panel button { display: block; width: 100%; text-align: left; background: transparent; border: 1px solid transparent; min-height: 28px; padding: 4px 8px 4px 22px; position: relative; }
.gm-panel button:hover { color: var(--text); border-color: var(--edge); }
.gm-panel button.on, .gm-panel button[aria-pressed="true"] { color: #fff; border-color: transparent; }
.gm-panel button.on::before, .gm-panel button[aria-pressed="true"]::before { content: '\\2713'; position: absolute; left: 7px; color: var(--line); }
.gm-panel button[disabled] { opacity: .45; cursor: default; }
.gm-panel input { display: block; width: 100%; margin: 4px 0; }
.gm-panel #fg, .gm-panel #design-box, .gm-panel #pf-readout, .gm-panel #coords-hud, .gm-panel #spd {
display: block !important; position: static !important; inset: auto !important; max-width: none !important; width: auto !important;
background: transparent !important; border: 0 !important; padding: 4px 8px !important; margin: 0 !important; color: var(--text) !important;
font: 11px/1.45 ui-monospace, Consolas, monospace !important; pointer-events: auto !important; box-shadow: none !important; }
.gm-panel #fg { align-items: stretch !important; }
.gm-panel .gm-sep { border-top: 1px solid var(--edge); margin: 6px 4px; }
.gm-panel .gm-note { color: var(--dim); padding: 4px 8px; white-space: pre-wrap; font-size: 11px; }
#where { position: fixed; left: 10px; bottom: calc(var(--foot, 20px) + 8px); z-index: 5; color: var(--dim); pointer-events: none;
font: 12px system-ui, sans-serif; font-variant-numeric: tabular-nums; text-shadow: 0 0 3px #000, 0 0 1px #000; white-space: nowrap; max-width: calc(100vw - 110px); overflow: hidden; text-overflow: ellipsis; }
#attribution { position: fixed; left: 0; right: 0; bottom: 0; height: var(--foot, 20px); z-index: 5; box-sizing: border-box; padding: 3px 10px 4px;
font-size: 10px; line-height: 13px; color: var(--dim); background: rgba(10, 10, 10, .72); pointer-events: none; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
#sim-note { position: fixed; left: 10px; bottom: calc(var(--foot, 20px) + 28px); z-index: 5; max-width: min(560px, calc(100vw - 110px)); color: var(--text);
font: 12px/1.45 system-ui, sans-serif; text-shadow: 0 0 3px #000, 0 0 1px #000; pointer-events: none; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
#sim-note[hidden] { display: none; }
#help-toggle { position: fixed; right: 10px; bottom: calc(var(--foot, 20px) + 6px); z-index: 6; min-height: 28px; padding: 0 10px; }
#help { right: 10px; bottom: calc(var(--foot, 20px) + 40px); width: min(340px, calc(100vw - 36px)); z-index: 21; }
#help #info { display: block !important; position: static !important; background: transparent !important; padding: 0 !important; color: var(--text) !important; font: 12px/1.45 system-ui, sans-serif !important; }
@media (max-width: 480px) {
#sim-menu .gm-title { padding: 0 6px; font-size: 11px; }
#sim-menu .gm-views button { padding: 0 6px; font-size: 11px; }
}`;
document.head.appendChild(css);
// ---- the bar, the six titles and panels ----
const nav = document.createElement('nav'); nav.id = 'sim-menu'; nav.setAttribute('aria-label', 'Menu');
const titlesEl = document.createElement('div'); titlesEl.className = 'gm-titles'; titlesEl.setAttribute('role', 'menubar');
const views = document.createElement('span'); views.className = 'gm-views';
nav.append(titlesEl, views); document.body.appendChild(nav);
const menus = {};
let hoverAt = -1e9;
for (const t of TITLES) {
const b = document.createElement('button'); b.className = 'gm-title'; b.textContent = t; b.dataset.menu = t;
b.setAttribute('aria-haspopup', 'menu'); b.setAttribute('aria-expanded', 'false'); b.setAttribute('role', 'menuitem');
const p = document.createElement('div'); p.className = 'gm-panel'; p.hidden = true; p.dataset.menu = t; p.setAttribute('role', 'menu');
titlesEl.appendChild(b); document.body.appendChild(p); menus[t] = { title: b, panel: p };
// A hover that opened this menu a moment ago must not be undone by the click that follows it.
b.addEventListener('click', e => { e.stopPropagation(); if (openName() === t && performance.now() - hoverAt > 400) close(); else open(t); });
b.addEventListener('mouseenter', () => { if (openName() && openName() !== t) { open(t); hoverAt = performance.now(); } });
b.addEventListener('keydown', e => {
const i = TITLES.indexOf(t);
if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') { e.preventDefault(); const n = TITLES[(i + (e.key === 'ArrowRight' ? 1 : TITLES.length - 1)) % TITLES.length]; menus[n].title.focus(); if (openName()) open(n); }
if (e.key === 'ArrowDown') { e.preventDefault(); open(t); }
});
}
// One slot per table row, in table order, so a late control still lands in its place.
const slots = {}, found = {};
let lastMenu = '';
for (const [m, key, spec] of TABLE) {
const p = menus[m].panel;
if (spec.box && lastMenu === m) { const s = document.createElement('div'); s.className = 'gm-sep'; p.appendChild(s); }
const s = document.createElement('div'); s.className = 'gm-slot'; s.dataset.key = key; p.appendChild(s); slots[key] = s; lastMenu = m;
if (spec.more) { const h = document.createElement('h2'); h.textContent = 'More'; h.hidden = true; s.appendChild(h); }
}
// ---- help panel and the Controls chip (bottom right) ----
const help = document.createElement('div'); help.id = 'help'; help.className = 'panel gm-panel'; help.hidden = true; help.dataset.menu = 'Help';
help.innerHTML = '<h2>Controls</h2>'; document.body.appendChild(help);
const info = document.getElementById('info'); if (info) help.appendChild(info);
const hb = document.createElement('button'); hb.id = 'help-toggle'; hb.textContent = 'Controls'; hb.setAttribute('aria-expanded', 'false');
hb.addEventListener('click', e => { e.stopPropagation(); openName() === 'Help' ? close() : open('Help'); });
document.body.appendChild(hb);
// SIM.info(t) still writes into #info; the newest message also shows for 8 s as one dim note above #where.
const note = document.createElement('div'); note.id = 'sim-note'; note.hidden = true; document.body.appendChild(note);
let noteT = 0;
if (info) new MutationObserver(() => { note.textContent = info.textContent; note.hidden = false; clearTimeout(noteT); noteT = setTimeout(() => { note.hidden = true; }, 8000); })
.observe(info, { childList: true, characterData: true, subtree: true });
// ---- open / close: one panel at a time ----
function openName() { for (const t of TITLES) if (!menus[t].panel.hidden) return t; return help.hidden ? '' : 'Help'; }
function close() {
for (const t of TITLES) { menus[t].panel.hidden = true; menus[t].title.setAttribute('aria-expanded', 'false'); }
help.hidden = true; hb.setAttribute('aria-expanded', 'false');
}
function open(t) {
close();
if (t === 'Help') { help.hidden = false; hb.setAttribute('aria-expanded', 'true'); return; }
const { title, panel } = menus[t]; panel.hidden = false; title.setAttribute('aria-expanded', 'true');
const r = title.getBoundingClientRect(), w = panel.offsetWidth;
panel.style.left = Math.max(8, Math.min(r.left, innerWidth - w - 8)) + 'px';
if (t === 'About') refreshAbout();
}
document.addEventListener('keydown', e => { if (e.key === 'Escape' && openName()) { close(); e.stopPropagation(); } }, true);
document.addEventListener('pointerdown', e => {
if (!openName()) return;
if (e.target.closest && (e.target.closest('.gm-panel') || e.target.closest('#sim-menu') || e.target.closest('#help-toggle'))) return;
close();
}, true);
// ---- routing: move each control to its slot ----
const labelOf = el => (el.textContent || '').trim();
function entryFor(el) {
for (const [m, key, spec] of TABLE) {
if (found[key] || spec.make || spec.more) continue;
if (spec.id && el.id === spec.id) return [m, key, spec];
}
for (const [m, key, spec] of TABLE) {
if (found[key] || spec.make || spec.more || spec.id) continue;
if (spec.sel && el.matches && el.matches(spec.sel)) return [m, key, spec];
if (spec.re && el.tagName === 'BUTTON' && spec.re.test(labelOf(el))) return [m, key, spec];
}
return null;
}
function place(el) {
if (!el || el.nodeType !== 1 || el.closest('.gm-panel') || el.closest('#sim-menu')) return;
if (VIEWS.includes(el.id)) { views.appendChild(el); return; }
if (el.id === 'spd' && !slots.spd.firstChild) { slots.spd.appendChild(el); found.spd = el; return; }
const hit = entryFor(el);
if (hit) {
const [, key, spec] = hit; found[key] = el; slots[key].appendChild(el);
if (spec.label && el.tagName === 'BUTTON' && !el.dataset.menuLabel) { el.dataset.menuLabel = spec.label; if (labelOf(el) === defaultLabel(el)) el.textContent = spec.label; }
return;
}
if (el.tagName === 'BUTTON' || el.tagName === 'INPUT') {
slots.more.firstChild.hidden = false; slots.more.appendChild(el);
console.warn('[menu-bar] no menu for "' + (labelOf(el) || el.placeholder || el.id) + '": placed under Scope > More');
}
}
// Only static labels are renamed (so "Pylons (37)" and "Loading rows..." still show as the mods write them).
const defaultLabel = el => ({ here: 'Build here', survey: 'Survey', 'walk-fps': 'FPS' })[el.id] || labelOf(el);
for (const el of Array.from(bar.children)) place(el);
for (const id of ['fg', 'design-box', 'pf-readout', 'coords-hud']) { const el = document.getElementById(id); if (el) place(el); }
// Anything appended later to #bar or the body (walk-fps inserts after #map2d; find-go and plant append boxes).
new MutationObserver(ms => { for (const m of ms) for (const n of m.addedNodes) if (n.nodeType === 1 && (m.target === bar || ['fg', 'design-box', 'pf-readout', 'coords-hud'].includes(n.id) || (VIEWS.includes(n.id)))) place(n); })
.observe(bar, { childList: true });
new MutationObserver(ms => { for (const m of ms) for (const n of m.addedNodes) if (n.nodeType === 1 && ['fg', 'design-box', 'coords-hud'].includes(n.id)) place(n); })
.observe(document.body, { childList: true });
// SIM.addButton: same button, same #bar append (so the observer above routes it), returned to the mod as before.
const add = SIM.addButton;
if (add && !add.__menu) { SIM.addButton = function (label, fn) { const b = add.call(SIM, label, fn); place(b); return b; }; SIM.addButton.__menu = true; }
// ---- the menu's own items ----
const item = (key, label, fn, disabled) => { const b = document.createElement('button'); b.textContent = label; b.dataset.key = key; if (disabled) b.disabled = true; else b.addEventListener('click', fn); slots[key].appendChild(b); found[key] = b; return b; };
const click = id => { const el = document.getElementById(id); if (el) el.click(); };
for (const [, key, spec] of TABLE) {
if (!spec.make) continue;
if (spec.proxy) item(key, spec.make, () => { click(spec.proxy); close(); });
else if (spec.kv) { const b = item(key, spec.make, () => { const on = !b.classList.contains('on'); b.classList.toggle('on', on); setKv(spec.kv, on); }); b.classList.add('on'); }
else if (spec.disabled) item(key, spec.make, null, true);
}
const setKv = (kv, on) => { if (map.getLayer('g' + kv)) map.setLayoutProperty('g' + kv, 'visibility', on ? 'visible' : 'none'); };
map.on('style.load', () => setTimeout(() => { for (const kv of ['400', '275', '132']) { const b = found['g' + kv]; if (b && !b.classList.contains('on')) setKv(kv, false); } }, 50));
slots['clear-design'].appendChild(Object.assign(document.createElement('button'), { textContent: 'Clear design', onclick: () => {
const i = document.getElementById('design-cmd'); if (!i) return; i.value = 'clear';
i.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })); i.dispatchEvent(new Event('change', { bubbles: true })); } }));
found['clear-design'] = slots['clear-design'].firstChild;
item('north', 'Reset north', () => map.easeTo({ bearing: 0, duration: 600 }));
item('zin', 'Zoom in', () => map.zoomIn());
item('zout', 'Zoom out', () => map.zoomOut());
item('controls', 'Controls and keys', () => open('Help'));
const credits = document.createElement('div'); credits.className = 'gm-note'; slots.credits.appendChild(credits);
const mods = document.createElement('div'); mods.className = 'gm-note'; slots.modules.appendChild(mods);
item('credits', 'Credits', () => { credits.textContent = creditText().join('\n'); });
item('modules', 'Modules loaded', () => {
fetch('mod/index.json').then(r => r.json()).then(l => { mods.textContent = l.join(', '); }).catch(() => { mods.textContent = 'mod/index.json not readable'; });
});
// Move the note under its button.
slots.credits.appendChild(credits); slots.modules.appendChild(mods);
function refreshAbout() { credits.textContent = ''; mods.textContent = ''; }
// ---- #where: one line, grid reference first ----
const where = document.createElement('div'); where.id = 'where'; document.body.appendChild(where);
const PF = () => SIM.PF || (window.__pf && window.__pf.PF);
function gridRef(e, n) {
const e1 = Math.floor(e / 1e5), n1 = Math.floor(n / 1e5);
if (e1 < 0 || e1 > 6 || n1 < 0 || n1 > 12) return '';
let l1 = (19 - n1) - (19 - n1) % 5 + Math.floor((e1 + 10) / 5), l2 = (19 - n1) * 5 % 25 + e1 % 5;
if (l1 > 7) l1++; if (l2 > 7) l2++;
const pad = v => String(Math.floor((v % 1e5) / 10)).padStart(4, '0');
return String.fromCharCode(65 + l1, 65 + l2) + ' ' + pad(e) + ' ' + pad(n);
}
let pending = false;
function writeWhere() {
pending = false;
const c = map.getCenter(), pf = PF(); let ref = '';
if (pf && c.lat > 49 && c.lat < 61.5 && c.lng > -9 && c.lng < 2.5) { try { const t = pf.toBng(c.lat, c.lng); ref = gridRef(t.e, t.n); } catch (e) { ref = ''; } }
const h = map.queryTerrainElevation ? map.queryTerrainElevation([c.lng, c.lat]) : null;
const parts = [ref, c.lat.toFixed(6) + ', ' + c.lng.toFixed(6), Number.isFinite(h) && h !== null ? Math.round(h) + ' m' : '', 'heading ' + Math.round((map.getBearing() + 360) % 360) + '°'];
where.textContent = parts.filter(Boolean).join(' · ');
}
const soon = () => { if (!pending) { pending = true; requestAnimationFrame(writeWhere); } };
map.on('move', soon); map.on('idle', soon); soon();
// ---- attribution strip: the credits of what is on screen ----
const strip = document.createElement('div'); strip.id = 'attribution'; document.body.appendChild(strip);
function creditText() {
const out = [], st = map.getStyle ? map.getStyle() : null;
if (st && st.sources) for (const k of Object.keys(st.sources)) { const a = st.sources[k].attribution; if (a) out.push(String(a).replace(/<[^>]*>/g, '').trim()); }
out.push('Grid lines and substations: GridAtlas');
return Array.from(new Set(out.filter(Boolean)));
}
const writeStrip = () => { strip.textContent = creditText().join(' · '); };
map.on('style.load', () => setTimeout(writeStrip, 100)); map.on('sourcedata', e => { if (e.sourceDataType === 'metadata') writeStrip(); });
writeStrip();
SIM.menu = {
titles: TITLES.slice(), open, close, openName,
// The 22 controls of 28 Sept: 19 in the six menus, plus Walk, Drone and Map at the bar's right end.
controls: () => TABLE.filter(r => r[2].core).map(([m, key]) => {
const el = found[key]; return { key, menu: m, found: !!el, inMenu: !!(el && menus[m].panel.contains(el)), label: el ? (labelOf(el) || el.placeholder || '') : '' };
}).concat(VIEWS.map(id => { const el = document.getElementById(id); return { key: id, menu: 'View', found: !!el, inMenu: !!(el && views.contains(el)), label: el ? labelOf(el) : '' }; })),
element: key => found[key] || (VIEWS.includes(key) ? document.getElementById(key) : null)
};
}
})();Menu Style
A JavaScript file in the prototype folder of Energy Transition Simulator.
renderenergy-transition-simulator / prototype/mod/menu-style.js · lines 1–49 of 49 · Not reached from any entry point (candidate for review)
- What it does
- It draws its content. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage experimental (path word 'prototype'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
- What it achieves
- The site world's look for the overlay: black page, dim text, hairline edges, no blue buttons.
- Why it matters
- No other file in the estate was found to import it.
- Application
- energy-transition-simulator · prototype/mod · script
- Uses
- none found
- Used by
- none found
- Produces
- none declared
- Defines here
- none
- 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/menu-style.js:1-49 · blob 199fadeaf189f3d5a75575d788c3fbc952a10e54 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: experimental · users: none · canonical: unreached_review
// mod/menu-style.js - the site world's look for the overlay: black page, dim text, hairline edges, no blue buttons.
// Plain script, no dependencies. Load it FIRST in mod/index.json (menu-bar.js last).
// Tokens are copied from the morning site-world release (solar-design-studio/202609270524-site-world, index.html
// lines 23-33, 59-62, 67, 153-160). The menu geometry (six titles, one panel at a time) follows GridAtlas menu-bar.js.
// It only adds CSS: every element it hides (#bar, #info, #spd, the readouts, the mod boxes) still exists and still
// receives the text the mods write; menu-bar.js moves them into menus and panels.
(function () {
'use strict';
if (document.getElementById('menu-style')) return;
const css = document.createElement('style');
css.id = 'menu-style';
css.textContent = `
:root { --bg: #0a0a0a; --line: #9cdbff; --text: #cfe9ff; --dim: #6f8ea6;
--panel: rgba(10, 10, 10, 0.86); --edge: #1c2c3a; --foot: 20px; --btn: 30px; --warn: #ffb27a; --bad: #ff8a7a; }
html, body, #map { background: var(--bg); color: var(--text); }
body { font: 12px/1.45 system-ui, sans-serif; }
/* Hidden at rest; still written to by the page and the mods. */
#bar, #info, #spd, #pf-readout, #here-readout, #coords-hud, #fg, #design-box { display: none !important; }
#fg input, #design-box input { font: 12px ui-monospace, Consolas, monospace !important; width: 100% !important; min-height: 28px !important;
padding: 5px 8px !important; border-radius: 4px !important; border: 1px solid var(--edge) !important; background: #050505 !important; color: var(--text) !important; }
.maplibregl-ctrl-top-right { display: none; }
.maplibregl-ctrl-bottom-right, .maplibregl-ctrl-bottom-left { display: none; }
/* Every button in the page: the five-dash-button look, never a filled blue block. */
button { font: 12px system-ui, sans-serif; background: var(--panel); color: var(--dim); border: 1px solid var(--edge);
border-radius: 4px; padding: 5px 9px; min-height: var(--btn); cursor: pointer; }
button:hover { color: var(--text); }
button.on, button[aria-pressed="true"], button[aria-expanded="true"] { color: #fff; border-color: var(--line); background: var(--panel); }
input { font: 12px system-ui, sans-serif; background: #050505; color: var(--text); border: 1px solid var(--edge);
border-radius: 4px; padding: 5px 8px; min-height: 28px; box-sizing: border-box; }
input:focus { outline: none; border-color: var(--line); }
.panel { position: fixed; background: var(--panel); border: 1px solid var(--edge); border-radius: 6px; padding: 10px 12px; overflow: auto; }
h2 { font-size: 11px; font-weight: 600; letter-spacing: 0.04em; color: var(--dim); text-transform: uppercase; margin: 0 0 6px; }
/* The touch joystick, restyled (site world #pad). Mouse users never see it. */
#joy { left: 24px !important; right: auto !important; bottom: 56px !important; border: 1px solid var(--edge) !important;
background: rgba(156, 219, 255, 0.04) !important; }
#knob { width: 48px !important; height: 48px !important; left: 36px; top: 36px; border: 1px solid var(--line);
background: rgba(156, 219, 255, 0.12) !important; }
@media (pointer: fine) { #joy { display: none !important; } }
@media (pointer: coarse) { #joy { bottom: 88px !important; } } /* clear of the note, #where and the strip */
/* Mod-drawn boxes that stay free-floating (trench panel, walk HUD, farm labels): the same panel tokens. */
#trench-panel { background: var(--panel) !important; border: 1px solid var(--edge) !important; color: var(--text) !important; }
`;
document.head.appendChild(css);
})();Morph
A JavaScript file in the prototype folder of Energy Transition Simulator. It is built from the fresh step (`fresh`), the ease step (`ease`) and the wait step (`wait`).
renderenergy-transition-simulator / prototype/mod/morph.js · lines 1–122 of 122 · Not reached from any entry point (candidate for review) · pattern animate (shared by 7 files)
- What it does
- It draws its content. Defines 20 functions or classes, including fresh, ease, wait, count, scaled. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage experimental (path word 'prototype'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
- What it achieves
- The wire world flattened and raised: one number t in [0, 1] that scales every height. t = 0 is the flat drawing (towers are points, conductors lie on the ground, ducts rise to the surface).
- Why it matters
- No other file in the estate was found to import it.
- Application
- energy-transition-simulator · prototype/mod · script
- Uses
- none found
- Used by
- none found
- Produces
- fresh, ease, wait, count, scaled, fading, own, cAlpha, arm, alpha, wrap, w
- Defines here
- fresh, ease, wait, count, scaled, fading, own, cAlpha, arm, alpha, wrap, w, wrapAll, release, set, cancel, fadeIn, animate, step, init
- 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/morph.js:1-122 · blob d087550bf42a1b2163f165a0625be48b7466423c · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: experimental · users: none · canonical: unreached_review
// mod/morph.js - the wire world flattened and raised: one number t in [0, 1] that scales every height.
// t = 0 is the flat drawing (towers are points, conductors lie on the ground, ducts rise to the surface); t = 1 is
// today's 3D exactly (nothing scaled). plan-view.js drives it: zoom in past the plan threshold and t eases 0 -> 1
// over MS with a cubic in-out curve while the pitch eases 0 -> 60; zoom out and the reverse happens.
// How: every custom layer keeps its own shader ("u * vec4(p, 1)", p anchor-relative, the anchor folded into u at
// its ground height). Scaling the third column of u by t scales p.z, so every block flattens onto its own ground.
// While t < 1 this module wraps each custom layer's render() (through a Proxy in place of the style layer's
// `implementation`, so a module that re-wraps the raw layer object's render, as wire-look does for 15 s after load,
// never sees the wrap: two wraps of one render would call each other for ever) and, for that call only, replaces gl.uniformMatrix4fv
// with one that (a) sets the layer's own u_zscale uniform when its program has one (the overlay's wire layer), or
// (b) scales column 2 of the matrix. At t = 1 the wrap returns to the layer's render at once: no cost, no change.
// The layers plan HIDES (the wire, its grid, the streamed ground) would pop in at full strength at t = 0, so for the ids
// in fadeIn(ids) the wrap also fades them: over the first FADE of t (30 %) every draw call of such a layer blends
// CONSTANT_ALPHA / ONE_MINUS_CONSTANT_ALPHA with alpha t / FADE (a plain mix of the layer over what is behind it), the
// layer's own blendFunc / enable(BLEND) recorded, not applied, until the call returns, and depth writes off (a faded
// line that wrote depth would still cut the draped terrain behind it to black; they stay off until t = 1, so the cut
// fringes of today's 3D return with everything else at the end, not mid-morph). Exact for opaque and premultiplied
// (ONE, ONE_MINUS_SRC_ALPHA) lines. A layer that blends SRC_ALPHA with one uniform colour `c` (the streamed ground) is
// mixed to c's alpha instead, which is its own result exactly at the end of the fade; one without such a uniform is
// left as it draws itself (a mix to 1 would end opaque).
// Nothing here edits another module's file; the wrap is runtime only and removable (SIM.morph.release()).
// Test hook: SIM.morph = { set(t), animate(to, ms, onFrame) -> Promise, cancel(), fadeIn(ids), state(), ease(x), release() }.
// state().frame counts the matrix calls since the last set() (this frame); state().totals counts them since load.
(function () {
'use strict';
const MS = 1200, FADE = 0.3;
const fresh = t => ({ t, calls: 0, uniform: 0, matrix: 0, faded: 0 });
const st = { t: 1, active: false, wrapped: [], frame: fresh(1), totals: fresh(1), anim: null, frames: 0, fade: new Set() };
let map;
const ease = x => x < 0.5 ? 4 * x * x * x : 1 - Math.pow(-2 * x + 2, 3) / 2; // cubic in-out
function wait(n) { const S = window.SIM; if (S && S.map) init(S); else if (n < 400) setTimeout(() => wait(n + 1), 50); }
// The per-call interceptor: called in place of gl.uniformMatrix4fv while a wrapped layer renders at t < 1.
const count = k => { st.frame[k]++; st.totals[k]++; };
function scaled(gl, orig, loc, tr, m) {
count('calls');
const pr = gl.getParameter(gl.CURRENT_PROGRAM), zl = pr ? gl.getUniformLocation(pr, 'u_zscale') : null;
if (zl) { count('uniform'); gl.uniform1f(zl, st.t); return orig.call(gl, loc, tr, m); }
count('matrix');
const r = new Float32Array(m); // column-major mat4: column 2 = indices 8..11
if (tr) { r[2] *= st.t; r[6] *= st.t; r[10] *= st.t; r[14] *= st.t; } else { r[8] *= st.t; r[9] *= st.t; r[10] *= st.t; r[11] *= st.t; }
return orig.call(gl, loc, tr, r);
}
// The fade-in for one render call: the layer's blend calls are recorded, and at each of its draw calls the mix
// CONSTANT_ALPHA / ONE_MINUS_CONSTANT_ALPHA at alpha a is set instead (or the layer's own SRC_ALPHA blend, untouched).
// Returns the function that puts the GL methods back.
function fading(gl, a) {
const o = { enable: gl.enable, disable: gl.disable, blendFunc: gl.blendFunc, blendFuncSeparate: gl.blendFuncSeparate, drawArrays: gl.drawArrays, drawElements: gl.drawElements, depthMask: gl.depthMask };
const want = { on: gl.getParameter(gl.BLEND), s: gl.getParameter(gl.BLEND_SRC_RGB), d: gl.getParameter(gl.BLEND_DST_RGB), sa: gl.getParameter(gl.BLEND_SRC_ALPHA), da: gl.getParameter(gl.BLEND_DST_ALPHA), dm: gl.getParameter(gl.DEPTH_WRITEMASK) };
const own = () => want.on && want.s === gl.SRC_ALPHA; // a translucent layer (SRC_ALPHA)
const cAlpha = () => { try { const pr = gl.getParameter(gl.CURRENT_PROGRAM), l = pr && gl.getUniformLocation(pr, 'c'), v = l && gl.getUniform(pr, l); return v && v.length === 4 ? v[3] : null; } catch (e) { return null; } };
const arm = () => {
o.enable.call(gl, gl.BLEND); o.depthMask.call(gl, false);
const sa = own() ? cAlpha() : 1;
if (sa == null) o.blendFuncSeparate.call(gl, want.s, want.d, want.sa, want.da); // alpha unknown: its own blend
else { gl.blendColor(0, 0, 0, a * sa); o.blendFuncSeparate.call(gl, gl.CONSTANT_ALPHA, gl.ONE_MINUS_CONSTANT_ALPHA, gl.ZERO, gl.ONE); count('faded'); }
};
gl.enable = c => (c === gl.BLEND ? (want.on = true) : o.enable.call(gl, c));
gl.disable = c => (c === gl.BLEND ? (want.on = false) : o.disable.call(gl, c));
gl.blendFunc = (s, d) => { want.s = want.sa = s; want.d = want.da = d; };
gl.blendFuncSeparate = (s, d, sa, da) => { want.s = s; want.d = d; want.sa = sa; want.da = da; };
gl.depthMask = v => { want.dm = !!v; };
gl.drawArrays = (...x) => { arm(); return o.drawArrays.apply(gl, x); };
gl.drawElements = (...x) => { arm(); return o.drawElements.apply(gl, x); };
return () => {
Object.assign(gl, o);
(want.on ? gl.enable : gl.disable).call(gl, gl.BLEND); gl.blendFuncSeparate(want.s, want.d, want.sa, want.da); gl.depthMask(want.dm); // as the layer left it
};
}
const alpha = () => Math.max(0, Math.min(1, st.t / FADE));
function wrap(id) {
const L = map.getLayer(id); const impl = L && L.implementation; if (!impl || impl.__morphProxy || typeof impl.render !== 'function') return false;
// The layer's CURRENT render, read at each call (another module may wrap it later), with the raw object as `this`.
const w = function (gl, args) {
if (st.t >= 1 || !st.active) return impl.render.call(impl, gl, args);
const orig = gl.uniformMatrix4fv; gl.uniformMatrix4fv = (loc, tr, m) => scaled(gl, orig, loc, tr, m);
const undo = st.fade.has(id) ? fading(gl, alpha()) : null; // for the whole morph: depth writes stay off until t = 1
try { return impl.render.call(impl, gl, args); } finally { gl.uniformMatrix4fv = orig; undo && undo(); }
};
const proxy = new Proxy(impl, { get: (t, k) => (k === 'render' ? w : k === '__morphProxy' ? true : k === '__morphRaw' ? t : Reflect.get(t, k)), set: (t, k, v) => Reflect.set(t, k, v) });
L.implementation = proxy; st.wrapped.push(id); return true;
}
// Every custom layer in the live order (the overlay's wire, the procedural ghost, the trench wires, the streamed
// ground, the survey grid). Other modules may wrap the same render later (wire-look does); the interceptor works from
// inside, whichever order the wraps ended up in, because it reads the program that is current at the call.
function wrapAll() {
const ids = map.getLayersOrder ? map.getLayersOrder() : (map.style && map.style._order) || [];
for (const id of ids) { const L = map.getLayer(id); if (L && L.type === 'custom') wrap(id); }
}
function release() { for (const id of st.wrapped) { const L = map.getLayer(id), impl = L && L.implementation; if (impl && impl.__morphProxy) L.implementation = impl.__morphRaw; } st.wrapped = []; st.active = false; }
function set(t) {
t = Math.max(0, Math.min(1, +t || 0)); st.t = t; st.frame = fresh(t); st.totals.t = t;
if (t < 1) { st.active = true; wrapAll(); } else st.active = false;
st.frames++; map.triggerRepaint();
}
function cancel() { if (st.anim) { cancelAnimationFrame(st.anim.raf); const a = st.anim; st.anim = null; a.resolve(false); } }
// The layers whose appearance fades in over the first FADE of t (plan names the ones it hides in the flat drawing).
function fadeIn(ids) { st.fade = new Set(ids || []); }
// Eases t from its current value to `to` over ms with the cubic; onFrame(e, t) each frame (e = eased progress 0..1).
function animate(to, ms, onFrame) {
cancel(); const from = st.t, t0 = performance.now(), D = ms == null ? MS : ms;
return new Promise(resolve => {
const a = { resolve, raf: 0, from, to, t0 };
st.anim = a;
const step = () => {
if (st.anim !== a) return;
const x = Math.min(1, (performance.now() - t0) / D), e = ease(x);
set(from + (to - from) * e); try { onFrame && onFrame(e, st.t, x); } catch (err) { console.warn('morph frame', err); }
if (x < 1) a.raf = requestAnimationFrame(step); else { st.anim = null; resolve(true); }
};
a.raf = requestAnimationFrame(step);
});
}
function init(S) {
if (S.morph) return; map = S.map;
map.on('style.load', () => { st.wrapped = []; if (st.active) setTimeout(wrapAll, 100); });
S.morph = { set, animate, cancel, release, ease, fadeIn, MS, FADE,
state: () => ({ t: +st.t.toFixed(4), active: st.active, animating: !!st.anim, wrapped: st.wrapped.slice(), frame: Object.assign({}, st.frame), totals: Object.assign({}, st.totals), frames: st.frames, alpha: +alpha().toFixed(3), fade: Array.from(st.fade) }) };
}
wait(0);
})();Perf
A JavaScript file in the prototype folder of Energy Transition Simulator that extracts planes (`extractPlanes`) and calculates planar distances.
Set aside from the main view: 98% of its lines are the same as energy-transition-simulator/202609280014/mod/perf.js (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 98% of lines shared with Perf; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.9828 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 energy-transition-simulator/202609280014/mod/perf.js:1-136 b2f39b27ce12aee46ac64b49f46c0e023217e13d
- sha256 4593aee148d08958e4c6d307d13e251c0d1cf8c6526a029991f3704973409388
- target sha256 5827d44771822d79e91ad6f9b5d8656f936e9d1b8def9ce3b31e3058cc921ae6
- group of 2 (identity.json near-copy edges >= 0.9)
- canonical rule: reachable, newest stamp, core repo, most lines
renderenergy-transition-simulator / prototype/mod/perf.js · lines 1–136 of 136 · Not reached from any entry point (candidate for review) · pattern extractPlanes (shared by 2 files)
- What it does
- It draws its content. Defines 10 functions or classes, including mx, my, mz, attach, bumpTerrain. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain stage experimental (path word 'prototype'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
- What it achieves
- It extracts planes (`extractPlanes`) and is built from the attach step (`attach`) and the bump terrain helper (`bumpTerrain`). The wire layer, made light (plain script; attaches to window.SIM).
- Why it matters
- No other file in the estate was found to import it.
- Application
- energy-transition-simulator · prototype/mod · script
- Uses
- none found
- Used by
- none found
- Produces
- mx, my, mz, attach, bumpTerrain, ensurePlaced, entryFor, extractPlanes, row, visible
- Defines here
- mx, my, mz, attach, bumpTerrain, ensurePlaced, entryFor, extractPlanes, row, visible
- 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/perf.js:1-136 · blob 0b577126ae9fcbede0d1b3035d26a95806b5892f · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: experimental · users: none · canonical: duplicate_candidate
// mod/perf.js - the wire layer, made light (plain script; attaches to window.SIM).
// What it changes, and only in the wire layer's render:
// 1. One GPU buffer per block, uploaded ONCE (STATIC_DRAW) and kept until the block changes. A block counts as
// changed when its Float32Array `buf` is a different object or length, or when its `rev` number changes
// (a module that edits b.buf in place sets b.rev++). Buffers of removed blocks are deleted.
// 2. The anchor's Mercator point and ground height are cached per block, not recomputed every frame. Heights are
// re-read after terrain tiles arrive (map 'idle' / 'terrain'), at most 300 queries per frame.
// 3. Blocks outside the view are skipped (a bounding sphere against the six frustum planes).
// 4. Shader locations are looked up once per program.
// Blocks that arrive as plain { lon, lat, lines } (no anchor/buf) are placed with place-frame.mjs, the same way
// overlay.html places its own, so any module can hand over bare metres.
// LEAD NOTES (overlay.html): (a) add 'perf' to mod/index.json; nothing else is required. Better still, fold this
// render into `wire` itself and drop the per-frame bufferData/getAttribLocation/getUniformLocation/queryTerrainElevation.
// (b) A module that edits b.buf in place must bump b.rev (or call SIM.perf.touch(b)); a new buf object is detected.
// (c) Phone size (390 px): #here-readout and #pf-readout sit over the 2nd/3rd button rows and intercept taps on
// "Rows from satellite"; #info covers the map attribution. (d) Measured 27 Sept; the measurement file is kept off the public repo.
(function () {
'use strict';
const MOD_URL = (document.currentScript && document.currentScript.src) || location.href;
const R = 6371008.8, CIRC = 2 * Math.PI * R; // MapLibre 4.7.1 sphere, as place-frame.mjs
const mx = lon => (180 + lon) / 360;
const my = lat => (180 - (180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + lat * Math.PI / 360)))) / 360;
const mz = (alt, lat) => alt / (CIRC * Math.cos(lat * Math.PI / 180));
const MAX_TERRAIN_QUERIES = 300;
let PF = null;
import(new URL('../place-frame.mjs', MOD_URL).href).then(m => { PF = m; if (window.SIM) SIM.repaint(); }).catch(() => {});
function attach() {
const SIM = window.SIM;
if (!SIM || !SIM.wire || !SIM.map) return false;
const map = SIM.map, wire = SIM.wire, blocks = SIM.blocks;
if (wire.__perf) return true;
const cache = new Map(); // block -> { gl, buf, src, len, rev, n, ox, oy, oz, gz, r, lat, lon }
const progInfo = new WeakMap(); // program -> { loc, u }
let terrainEpoch = 1;
const stats = { frames: 0, uploads: 0, uploadBytes: 0, draws: 0, culled: 0, lastMs: 0, sumMs: 0, deleted: 0 };
const mat = new Float32Array(16), planes = new Float64Array(24);
const bumpTerrain = () => { terrainEpoch++; map.triggerRepaint(); };
// Re-read heights only when new terrain tiles have arrived (a flag set by the DEM source), on the next 'idle'.
let demDirty = false;
map.on('sourcedata', ev => { if (ev.tile && ev.source && ev.source.type === 'raster-dem') demDirty = true; });
map.on('idle', () => { if (demDirty) { demDirty = false; bumpTerrain(); } });
map.on('terrain', bumpTerrain);
// Bring a bare { lon, lat, lines } block up to the overlay's shape (anchor + anchor-relative Mercator buf).
function ensurePlaced(b) {
if (b.anchor && b.buf) return true;
if (!PF || !b.lines) return false;
const anchor = PF.placeKey(b.lat, b.lon), off = PF.toLocal(anchor, b.lat, b.lon, 0);
const L = (off.x || off.y) ? b.lines.map(([a, c, d, e, f, g]) => [a + off.x, c + off.y, d, e + off.x, f + off.y, g]) : b.lines;
b.anchor = anchor; b.buf = PF.wireBuffer(anchor, L);
return true;
}
function entryFor(gl, b) {
let e = cache.get(b);
const v = b.buf, rev = b.rev || 0;
if (e && e.gl === gl && e.src === v && e.len === v.length && e.rev === rev) return e;
if (!e || e.gl !== gl) { e = { gl, buf: gl.createBuffer(), gzEpoch: 0 }; cache.set(b, e); }
gl.bindBuffer(gl.ARRAY_BUFFER, e.buf);
gl.bufferData(gl.ARRAY_BUFFER, v, gl.STATIC_DRAW);
stats.uploads++; stats.uploadBytes += v.byteLength;
e.src = v; e.len = v.length; e.rev = rev; e.n = v.length / 3;
// Bounding sphere radius in Mercator units (vertices are already anchor-relative).
let r2 = 0; for (let i = 0; i < v.length; i += 3) { const d = v[i] * v[i] + v[i + 1] * v[i + 1] + v[i + 2] * v[i + 2]; if (d > r2) r2 = d; }
const a = b.anchor; e.lat = a.lat; e.lon = a.lon; e.ox = mx(a.lon); e.oy = my(a.lat);
e.r = Math.sqrt(r2) + mz(80, a.lat); // + 80 m of slack for terrain height
e.gzEpoch = 0;
return e;
}
// Frustum planes from the column-major view-projection matrix (Gribb and Hartmann).
function extractPlanes(m) {
const row = i => [m[i], m[4 + i], m[8 + i], m[12 + i]];
const r0 = row(0), r1 = row(1), r2 = row(2), r3 = row(3);
const P = [[0, 1], [0, -1], [1, 1], [1, -1], [2, 1], [2, -1]];
const rows = [r0, r1, r2];
for (let k = 0; k < 6; k++) {
const s = P[k][1], rr = rows[P[k][0]];
let a = r3[0] + s * rr[0], b = r3[1] + s * rr[1], c = r3[2] + s * rr[2], d = r3[3] + s * rr[3];
const n = Math.hypot(a, b, c) || 1;
planes[4 * k] = a / n; planes[4 * k + 1] = b / n; planes[4 * k + 2] = c / n; planes[4 * k + 3] = d / n;
}
}
const visible = (x, y, z, r) => {
for (let k = 0; k < 6; k++) if (planes[4 * k] * x + planes[4 * k + 1] * y + planes[4 * k + 2] * z + planes[4 * k + 3] < -r) return false;
return true;
};
wire.render = function (gl, args) {
const t0 = performance.now();
const m = (args && args.defaultProjectionData && args.defaultProjectionData.mainMatrix) || args;
const pr = this.pr; if (!pr) return;
let pi = progInfo.get(pr);
if (!pi) { pi = { loc: gl.getAttribLocation(pr, 'p'), u: gl.getUniformLocation(pr, 'u') }; progInfo.set(pr, pi); }
gl.useProgram(pr); gl.enableVertexAttribArray(pi.loc);
extractPlanes(m);
const hasTerrain = !!(map.getTerrain && map.getTerrain() && map.queryTerrainElevation);
let q = 0, draws = 0, culled = 0;
for (let i = 0; i < blocks.length; i++) {
const b = blocks[i];
if (!ensurePlaced(b) || !b.buf.length) continue;
const e = entryFor(gl, b); e.seen = stats.frames;
if (e.gzEpoch !== terrainEpoch && q < MAX_TERRAIN_QUERIES) {
e.gz = hasTerrain ? (map.queryTerrainElevation([e.lon, e.lat]) || 0) : 0; e.gzEpoch = terrainEpoch; q++;
e.oz = mz(e.gz, e.lat);
}
const ox = e.ox, oy = e.oy, oz = e.oz || 0;
if (!visible(ox, oy, oz, e.r)) { culled++; continue; }
for (let k = 0; k < 4; k++) { mat[k] = m[k]; mat[4 + k] = m[4 + k]; mat[8 + k] = m[8 + k]; mat[12 + k] = m[k] * ox + m[4 + k] * oy + m[8 + k] * oz + m[12 + k]; }
gl.bindBuffer(gl.ARRAY_BUFFER, e.buf);
gl.vertexAttribPointer(pi.loc, 3, gl.FLOAT, false, 0, 0);
gl.uniformMatrix4fv(pi.u, false, mat);
gl.drawArrays(gl.LINES, 0, e.n); draws++;
}
if (q >= MAX_TERRAIN_QUERIES) map.triggerRepaint(); // more heights still to read next frame
// Sweep buffers of removed blocks (cheap: only when the cache outgrows the list, or every 2 s).
if (cache.size > blocks.length || stats.frames % 120 === 0) {
for (const [b, e] of cache) if (e.seen !== stats.frames) { e.gl.deleteBuffer(e.buf); cache.delete(b); stats.deleted++; }
}
stats.frames++; stats.draws = draws; stats.culled = culled;
const dt = performance.now() - t0; stats.lastMs = dt; stats.sumMs += dt;
};
wire.__perf = true;
SIM.perf = {
stats: () => Object.assign({ buffers: cache.size, blocks: blocks.length, meanRenderMs: stats.frames ? stats.sumMs / stats.frames : 0 }, stats),
reset: () => { stats.frames = 0; stats.uploads = 0; stats.uploadBytes = 0; stats.sumMs = 0; stats.deleted = 0; },
touch: b => { b.rev = (b.rev || 0) + 1; map.triggerRepaint(); } // call after editing b.buf in place
};
map.triggerRepaint();
return true;
}
if (!attach()) { let n = 0; const t = setInterval(() => { if (attach() || ++n > 100) clearInterval(t); }, 100); }
})();