In this section
- Wafer Development Environment — Proof K0030 Page render · globalgrid2050 / testcode/wafer-development-environment/202609192238-proof-k0030/index.html lines 2101–2157
- Testcode — Wafer Development Environment Page render · globalgrid2050 / testcode/wafer-development-environment/index.html lines 1–12
- Test Kuiper Universes Entry test · globalgrid2050-homepage / tests/test_kuiper_universes_entry.py lines 1–37
- Assemble storage · graphics-engines-open-source / assemble.py lines 1–12
- Check Scene GPU storage · graphics-engines-open-source / check_scene_gpu.py lines 1–38
- Browser test · graphics-engines-open-source / tests/browser.cjs lines 1–51
- Existing Wiring test · graphics-engines-open-source / tests/existing-wiring.cjs lines 1–42
- Explore Test test · graphics-engines-open-source / tests/explore.test.mjs lines 1–37
- Convert Connector storage · graphics-engines-open-source / tools/convert-connector.cjs lines 1–8
- GPU Watch storage · graphics-engines-open-source / tools/gpu_watch.py lines 1–130
- Explore interaction · graphics-engines-open-source / web/explore.mjs lines 1–114
- Graphics Engines Open Source — Index Page render · graphics-engines-open-source / web/index.html lines 1–14
Wafer Development Environment — Proof K0030 Page
A web page in the testcode folder of GlobalGrid2050 that draws programs, link contract, cables and solar, and uses data from the GridAtlas repository. Published at https://globalgrid2050.com/testcode/wafer-development-environment/202609192238-proof-k0030/.
renderglobalgrid2050 / testcode/wafer-development-environment/202609192238-proof-k0030/index.html · lines 2101–2157 of 2157 · version 2026-09-19 22:38 (continued from section 1497) · Entry point · pattern frameOnce (shared by 6 files)
- What it does
- It draws programs, link contract, cables and solar. Defines 105 functions or classes, including buildLink, complaints, parseLink, fmt, day. Side effects: changes the web page (DOM); makes network requests.
- Why it exists in the grid workflow
- Domain stage experimental (path word 'testcode'): 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, solar.
- Inputs & outputs
- In: data source: gridatlas data; JSON file programs.json; JSON file link-contract.json; form fields (user input). Out: web page; WebGL/WebGPU drawing.
- Downstream impact
- Used directly by 5 files: GlobalGrid2050 Homepage Before Four Nests (globalgrid2050, https://globalgrid2050.com/homepage-before-four-nests-20260925.html); Homepage Versions — Before Refresh Page (globalgrid2050, https://globalgrid2050.com/homepage_versions/20260922-before-refresh/); Homepage V123 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v123.html); Homepage V124 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v124.html); and 1 more. Reached from 83 other entry points, including GlobalGrid2050 Historical Builds (globalgrid2050, https://globalgrid2050.com/historical_builds.html); Homepage V037 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v037.html); Homepage V038 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v038.html). It is itself an entry point, published at https://globalgrid2050.com/testcode/wafer-development-environment/202609192238-proof-k0030/.
- What it achieves
- It builds link (`buildLink`), parses link (`parseLink`) and makes body (`makeBody`). Its `lightTime` function gives commit period summary or null from year, optional month and optional day (VEDIC: period). It reads `cosmos/programs.json`. It responds to error, webglcontextlost and resize events.
- Why it matters
- Loaded by the GlobalGrid2050 Homepage Before Four Nests page at https://globalgrid2050.com/homepage-before-four-nests-20260925.html and 4 other pages.
- Application
- globalgrid2050 · testcode/wafer-development-environment/202609192238-proof-k0030 · page
- VEDIC
- PERIOD (GG2050-VEDIC-000042): Kuiper / Code navigation · Computer science / Interactive visualisation. year, month_optional, day_optional, ordered_commits → commit_period_summary_or_null
- Uses
- Assemble (dynamic import), Cable Geometry Visualiser V5 (estate URL), GridAtlas — Atlas Page (estate URL), GlobalGrid2050 — Cable Geometry Page (estate URL)
- Used by
- linked from GlobalGrid2050 Homepage Before Four Nests (link), linked from Homepage Versions — Before Refresh Page (link), linked from Homepage V123 (link), linked from Homepage V124 (link), linked from Homepage V125 (link)
- Produces
- buildLink, complaints, parseLink, fmt, day, words, prog, U, tsv, appFor, narrow, resize
- Defines here
- goToKey
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/wafer-development-environment/202609192238-proof-k0030/index.html:2101-2157 · blob 49d0fcee35f69d086bc25c56b554adeccf8e53be · GitHub at these lines
- State
- achieves: code · context: readme_derived · stage: output · effects: dom, network · domain stage: experimental · users: none · canonical: production_core
if (drag && moved < 4 && iso && body && body.shown && !bodyAnim) { let bj = -1, bd = Math.max(12, bodyDotPx() + 8);
for (let j = 0; j < body.n; j++) { const x = (body.pos[2*j] - cx) * zoom + innerWidth / 2, y = innerHeight / 2 - (body.pos[2*j+1] - cy) * zoom;
const d = Math.hypot(x - e.clientX, y - e.clientY); if (d < bd) { bd = d; bj = j; } }
if (bj >= 0) { const c0 = commits[iso.idx[bj]]; show(address(c0.k0 + Math.floor((c0.k1 - c0.k0) / 2))); pointerGone(e); return; } }
if (drag && moved < 4 && N) { const [wx, wy] = toWorld(e.clientX, e.clientY), r = Math.hypot(wx, wy);
if (r*r < SPACE) { let k = zoom >= POINTS_FROM ? keyAt(wx, wy) : -1; const exact = k >= 0; if (!exact) k = Math.floor(r*r);
target = exact ? { x:keyPlace(k)[0], y:keyPlace(k)[1] } : null; show(address(k)); } }
pointerGone(e); });
addEventListener('pointercancel', pointerGone);
addEventListener('wheel', e => { const [wx, wy] = toWorld(e.clientX, e.clientY), f = e.deltaY < 0 ? 1.18 : 1/1.18;
zoom = Math.max(1e-4, Math.min(ZMAX, zoom*f)); cx = wx - (e.clientX - innerWidth/2)/zoom; cy = wy + (e.clientY - innerHeight/2)/zoom;
atHome = false; tween = null; dirty = true; }, { passive:true });
// the tap targets, so a phone can do everything the keyboard can
document.getElementById('keys').addEventListener('click', e => {
if (e.target.classList.contains('q')) { e.stopPropagation(); elFoot.classList.toggle('hints'); layout(); dirty = true; return; }
const k = e.target.getAttribute('data-k'); if (!k) return;
e.stopPropagation(); dispatchEvent(new KeyboardEvent('keydown', { key:k })); });
elTop.addEventListener('click', () => elTop.classList.toggle('open')); // the long subtitle, collapsed by default
// A LINK INSIDE THE CARD IS NOT A DISMISSAL, and neither is reading it: the card is put away with
// its own cross or with Escape, the way the wafer's card is.
card.addEventListener('click', e => {
const a = e.target.closest ? e.target.closest('a') : null;
if (a && a.hasAttribute('data-key')) { e.preventDefault(); goToKey(+a.getAttribute('data-key')); }
});
// GOING TO A KEY, from a link inside a card or from an address a reader arrived with. The camera
// flies, the dot is marked and its card opens: one way of arriving, however the reader got here.
function goToKey(k){
const a = address(k);
if (!a) return;
const p = keyPlace(k);
litK = [k, k + 1]; litCi = null; target = { x:p[0], y:p[1] };
show(a); flyTo(p[0], p[1], Math.max(zoom, 14)); dirty = true;
}
const gbox = document.getElementById('goto'), gin = document.getElementById('gotoin');
gin.addEventListener('keydown', e => { e.stopPropagation(); if (e.key === 'Escape') { gbox.style.display = 'none'; return; }
if (e.key !== 'Enter') return; gbox.style.display = 'none'; const raw = gin.value.trim(), q = raw.replace(/[ ,_]/g,'');
const mt = raw.match(/^(20\d\d)(?:-(\d\d))?(?:-(\d\d))?$/);
if (mt) { lightTime(+mt[1], mt[2] ? +mt[2] : 0, mt[3] ? +mt[3] : 0); return; }
const mnew = raw.toLowerCase().match(/^(?:show\s+)?new(?:\s+code)?(?:\s+(\d+)\s*h?)?$/);
if (mnew) { showNew(mnew[1] ? Number(mnew[1]) : 24); return; }
if (/^\d+$/.test(q)) goKey(Math.min(SPACE-1, Number(q)));
else { const r = repos.find(x => x.name.toLowerCase() === raw.toLowerCase()) || repos.find(x => x.name.toLowerCase().includes(raw.toLowerCase()));
if (r) { litRepo = r.i; target = null; card.style.display = 'none'; home(); dirty = true; } } });
addEventListener('keydown', e => { if (gbox.style.display === 'block') return;
if (e.key === 'd') { detail = !detail; dirty = true; }
else if (e.key === 'r' && N) { const j = Math.floor(Math.random()*N), c = commits[findBy('cum', j)]; goKey(c.k0 + (j - c.cum)); } // uniform over issued lines
else if (e.key === 'n' && N) showNew(24);
else if (e.key === '/') { e.preventDefault(); gbox.style.display = 'block'; gin.value = ''; gin.focus(); }
else if (e.key === 'Backspace') { e.preventDefault(); target = null; litRepo = -1; newFrom = -1; flash = 0; pulse = -1; litK = [-1,-1]; litCi = null; litPath = null; card.style.display = 'none';
// GATHERED WORK GOES HOME BEFORE THE LIGHT COMES BACK: the same rule run the other way, so a
// visitor sees that the body was made of work from all over the record and nothing else.
if (iso && body && body.shown && ASM && !(bodyAnim && bodyAnim.home)) { bodyAnim = { k:Math.max(0, body.k), t0:performance.now(), from:new Float32Array(body.pos), gap0:body.gap, phase:'move', home:true }; isoAnim = null; dirty = true; }
else { unisolate(true); home(); } } });
requestAnimationFrame(frame);
</script>
</body>
</html>Testcode — Wafer Development Environment Page
A web page in GlobalGrid2050. Published at https://globalgrid2050.com/testcode/wafer-development-environment/.
renderglobalgrid2050 / testcode/wafer-development-environment/index.html · lines 1–12 of 12 · Entry point
- 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 'testcode'): 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: 400kV, 132kV.
- Inputs & outputs
- Out: web page. Voltage levels named: 400kV, 132kV.
- Downstream impact
- Used directly by 9 files: Check Proof (kuiper-belt); Modular Join (vedic-); Review Page (vedic-); Test Modular Join (vedic-); and 5 more. Reached from 111 other entry points, including GlobalGrid2050 Historical Builds (globalgrid2050, https://globalgrid2050.com/historical_builds.html); Homepage V037 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v037.html); Homepage V038 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v038.html). It is itself an entry point, published at https://globalgrid2050.com/testcode/wafer-development-environment/.
- What it achieves
- Its code works with 132 kV and 400 kV.
- Why it matters
- Loaded by the GlobalGrid2050 Homepage Before Four Nests page at https://globalgrid2050.com/homepage-before-four-nests-20260925.html and 4 other pages. Also imported by Check Proof, Modular Join and Review Page, from Kuiper Belt and VEDIC. Checked by Test Modular Join.
- Application
- globalgrid2050 · testcode/wafer-development-environment · page
- Uses
- Wafer Development Environment — Estate Page (link), Wafer Development Environment — Block 39885 Page (link), Wafer Development Environment — Twin 39885 Page (link), Wafer Development Environment — State 39885 Page (link), Wafer Development Environment — Measure 39885 Page (link), Wafer Development Environment — GridAtlas Page (link), Wafer Development Environment — Voltage Drop Page (link), Wafer Development Environment — Diversified Demand Page (link), and 4 more
- Used by
- named by URL in Check Proof (estate URL), named by URL in Modular Join (estate URL), named by URL in Review Page (estate URL), named by URL in Test Modular Join (estate URL), linked from GlobalGrid2050 Homepage Before Four Nests (link), linked from Homepage Versions — Before Refresh Page (link), linked from Homepage V123 (link), linked from Homepage V124 (link), and 1 more
- 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
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/wafer-development-environment/index.html:1-12 · blob 1d0a2fe001c67e701908d4d236c19629024706c8 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: experimental · users: none · canonical: production_core
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Wafer Development Environment</title>
<style>body{background:#0b0e15;color:#cfe3f2;font:14px/1.5 ui-monospace,Menlo,Consolas,monospace;margin:0;padding:24px 16px;max-width:900px}h1{font-size:16px;letter-spacing:.08em;text-transform:uppercase;margin:0 0 16px}table{border-collapse:collapse;width:100%}td{padding:6px 10px;border-bottom:1px solid #1b2030;vertical-align:top}a{color:#5ec8f2;text-decoration:none}a:hover{text-decoration:underl … [line shortened here: 450 characters; full line on GitHub]
<body><h1>Wafer Development Environment</h1><table><tr><td><a href="202609170036-estate/">202609170036-estate</a></td><td>Every numbered line of the estate, under gravity</td></tr>
<tr><td><a href="202609170037-block-39885/">202609170037-block-39885</a></td><td>One line: the most-copied line in the estate</td></tr>
<tr><td><a href="202609170038-twin-39885/">202609170038-twin-39885</a></td><td>The code behind one line, in the card</td></tr>
<tr><td><a href="202609170039-state-39885/">202609170039-state-39885</a></td><td>A block's two states, HOME and AWAY</td></tr>
<tr><td><a href="202609170040-measure-39885/">202609170040-measure-39885</a></td><td>One recorded measurement</td></tr>
<tr><td><a href="202609170041-gridatlas/">202609170041-gridatlas</a></td><td>GridAtlas on the wafer</td></tr>
<tr><td><a href="202609170042-voltage-drop/">202609170042-voltage-drop</a></td><td>Voltage drop, 120 A over 250 m</td></tr>
<tr><td><a href="202609170043-diversified-demand/">202609170043-diversified-demand</a></td><td>Diversified demand, 900 units</td></tr>
<tr><td><a href="202609170044-key-to-code/">202609170044-key-to-code</a></td><td>The key-to-code check</td></tr>
<tr><td><a href="202609170045-land-gridatlas/">202609170045-land-gridatlas</a></td><td>GridAtlas pulled in; asks before entering</td></tr><tr><td><a href="202609180205-underground/">202609180205-underground</a></td><td>the Underground drawn from a typed command, on the wafer's own dust</td></tr><tr><td><a href="202609180245-real-systems/">202609180245-real-systems</a></td><td>real systems drawn fr … [line shortened here: 665 characters; full line on GitHub]Test Kuiper Universes Entry
A test in the tests folder of GlobalGrid2050 Homepage using data from the cosmic repository. It is built from the kuiper universes entry tests class (`KuiperUniversesEntryTests`).
testglobalgrid2050-homepage / tests/test_kuiper_universes_entry.py · lines 1–37 of 37 · Entry point
- What it does
- It tests its inputs. Defines KuiperUniversesEntryTests, test_kuiper_universes_under_explore_code. Uses libraries json, unittest, pathlib. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage agent_infra (path word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Inputs & outputs
- In: data source: cosmic data; JSON file homepage.json; JSON file entity-types.json.
- Downstream impact
- Used directly by 3 files: Build Homepage Release Candidate Workflow (globalgrid2050-homepage); Pages Workflow (globalgrid2050-homepage); PR Checks Workflow (globalgrid2050-homepage).
- What it achieves
- Kuiper universes is a featured sub-entry of Explore Code (section 13).
- Why it matters
- Run by Build Homepage Release Candidate Workflow, Pages Workflow and PR Checks Workflow.
- Application
- globalgrid2050-homepage · tests · test
- Uses
- json, unittest, pathlib
- Used by
- run by Build Homepage Release Candidate Workflow (workflow run), run by Pages Workflow (workflow run), run by PR Checks Workflow (workflow run)
- Produces
- KuiperUniversesEntryTests
- Defines here
- KuiperUniversesEntryTests, test_kuiper_universes_under_explore_code
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050-homepage@551a7625b02ddb7b3e6e0181cc643b8114c7fc06 tests/test_kuiper_universes_entry.py:1-37 · blob 48e04e90eeac8896ef895189bcdfd58e5a39c8e2 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unknown
"""Kuiper universes is a featured sub-entry of Explore Code (section 13)."""
import json
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
ID = "kuiper-universes"
URL = "https://ventusltd.github.io/cosmic/explore-code/kuiper/index.html"
class KuiperUniversesEntryTests(unittest.TestCase):
def test_kuiper_universes_under_explore_code(self):
d = json.loads((ROOT / "data/homepage.json").read_text(encoding="utf-8"))
m = json.loads((ROOT / "data/entity-types.json").read_text(encoding="utf-8"))
h = (ROOT / "index.html").read_text(encoding="utf-8")
by = {e["id"]: e for e in d["entities"]}
e = by[ID]
self.assertEqual(e["parent_id"], "explore-code")
self.assertTrue(e["title"].startswith("Kuiper universes"))
self.assertEqual([x["id"] for x in d["entities"] if x.get("parent_id") == "explore-code"][0], ID)
self.assertEqual(d["view"]["items"][12], {"entity_id": "explore-code", "open": False})
rel = {r["id"]: r for r in e["releases"]}[e["operative_release_id"]]
self.assertEqual(e["operative_release_id"], "20261205-kuiper-universes")
self.assertEqual(rel["url"], URL)
self.assertEqual(rel["status"], "available")
self.assertRegex(rel["source_ref"], r"^https://github\.com/Ventusltd/cosmic/commit/[0-9a-f]{40}$")
explore = by["explore-code"]
self.assertEqual(explore["operative_release_id"], "20261205-cosmic")
self.assertEqual(m["records"][ID]["type"], "catalogue")
self.assertEqual(h.count('<details id="kuiper-universes">'), 1)
self.assertIn(f'href="{URL}">Open the Kuiper universes', h)
self.assertLess(h.index('id="explore-code"'), h.index('id="kuiper-universes"'))
self.assertLess(h.index('id="kuiper-universes"'), h.index('id="catalogueArchive"'))
if __name__ == "__main__":
unittest.main()Assemble
A Python module in Graphics Engines Open Source that copies the explicitly listed original prototype files; no project data, using SHA-256.
storagegraphics-engines-open-source / assemble.py · lines 1–12 of 12 · Not reached from any entry point (candidate for review)
- What it does
- Uses libraries pathlib, hashlib, json, argparse. Side effects: reads or writes files.
- Inputs & outputs
- In: command-line arguments. Out: JSON file source-manifest.json.
- What it achieves
- No statement of purpose was found in the file, a README line naming it, or its name.
- Why it matters
- No other file in the estate was found to import it.
- Application
- graphics-engines-open-source · / · Python module
- Uses
- pathlib, hashlib, json, argparse
- 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
- graphics-engines-open-source@79e0bd8ee33844835e553fc84d552b6aa1521152 assemble.py:1-12 · blob 5ce267ee858c982a5c95d70ed744acaf7001ff95 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: unreached_review
"""Copy the explicitly listed original prototype files; no project data."""
from pathlib import Path
import hashlib,json,argparse
ROOT=Path(__file__).parent
parser=argparse.ArgumentParser();parser.add_argument('source',type=Path);SOURCE=parser.parse_args().source
files={'web/explore.html':'web/index.html','web/explore.mjs':'web/explore.mjs','web/explore.css':'web/explore.css','web/gridatlas.mjs':'web/gridatlas.mjs','web/atlas-picker.mjs':'web/atlas-picker.mjs','LICENSE-ARRAY':'LICENSE','tests/explore.test.mjs':'tests/explore.test.mjs','tests/gridatlas.test.mjs':'tests/gridatlas.test.mjs'}
manifest=[]
for src,dst in files.items():
raw=(SOURCE/src).read_bytes();p=ROOT/dst;p.parent.mkdir(parents=True,exist_ok=True);p.write_bytes(raw)
manifest.append({'source_repository':'Ventusltd/kuiper-drawing-engine','source_file':src,'destination':dst,'sha256':hashlib.sha256(raw).hexdigest(),'basis':'local working-tree prototype, not a released upstream version'})
(ROOT/'source-manifest.json').write_text(json.dumps(manifest,indent=2),encoding='utf8')
print(json.dumps({'files':len(files),'web_bytes':sum((ROOT/v).stat().st_size for v in files.values() if v.startswith('web/'))}))Check Scene GPU
A Python module in Graphics Engines Open Source covering explore geometry and GPU scene check, using SHA-256.
storagegraphics-engines-open-source / check_scene_gpu.py · lines 1–38 of 38
- What it does
- It lists and searches explore geometry and GPU scene check. Uses libraries pathlib, json, time, hashlib, argparse. Side effects: reads or writes files.
- Inputs & outputs
- In: JSON file explore-geometry.json; command-line arguments. Out: JSON file gpu-scene-check.json.
- Downstream impact
- Used directly by 1 file: GPU Watch (graphics-engines-open-source).
- What it achieves
- Compare actual renderer panel vertices and route travel with CuPy calculations.
- Why it matters
- Run by GPU Watch.
- Application
- graphics-engines-open-source · / · Python module
- Uses
- pathlib, json, time, hashlib, argparse, numpy, cupy
- Used by
- run by GPU Watch (script call)
- 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
- graphics-engines-open-source@79e0bd8ee33844835e553fc84d552b6aa1521152 check_scene_gpu.py:1-38 · blob e64d2c767ee3aa69f30083947206f13f9061aa3c · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: supporting_data
"""Compare actual renderer panel vertices and route travel with CuPy calculations."""
from pathlib import Path
import json,time,hashlib,argparse
import numpy as np
import cupy as cp
ROOT=Path(__file__).parent
parser=argparse.ArgumentParser();parser.add_argument('fixture',nargs='?',type=Path,default=ROOT/'.local'/'explore-geometry.json');fixture=parser.parse_args().fixture
raw=fixture.read_bytes();data=json.loads(raw);s=data['settings'];v=np.array(data['vertices']).reshape(-1,6)
panel=v[np.all(np.isclose(v[:,3:],[.7,.79,.88],atol=1e-12),axis=1),:3]
started=time.perf_counter();cp.cuda.Stream.null.synchronize()
nt,nr,nc=s['tables'],s['rows'],s['columns'];w,l=s['moduleWidth'],s['moduleLength'];g=.02;t=np.deg2rad(s['tilt'])
table,row,col,edge=cp.meshgrid(cp.arange(nt),cp.arange(nr),cp.arange(nc),cp.arange(8),indexing='ij')
dx=cp.array([0,w,w,w,w,0,0,0],dtype=cp.float64)[edge.ravel()]
dy=cp.array([0,0,0,l,l,l,l,0],dtype=cp.float64)[edge.ravel()]
across=int(np.ceil(np.sqrt(nt)));span=nc*(w+g)-g;run=nr*(l+g)-g
x=col.ravel()*(w+g)+dx;y=row.ravel()*(l+g)+dy
local=cp.stack([x,y,cp.zeros_like(x)],axis=1)
rotation=cp.array([[1,0,0],[0,np.cos(t),-np.sin(t)],[0,np.sin(t),np.cos(t)]])
actual=local@rotation.T
actual[:,0]+=(table.ravel()%across)*(span+5)
actual[:,1]+=(table.ravel()//across)*(run*np.cos(t)+6)
actual[:,2]+=s['height']
assert panel.shape==actual.shape,(panel.shape,actual.shape)
panel_error=float(cp.max(cp.abs(actual-cp.asarray(panel))))
assert panel_error<1e-9,panel_error
route_results=[]
for r in data['routes']:
p=np.array(r['points'],dtype=np.float64);segments=np.linalg.norm(np.diff(p,axis=0),axis=1);cum=np.r_[0,np.cumsum(segments)]
gp=cp.asarray(p);gl=cp.sqrt(cp.sum(cp.diff(gp,axis=0)**2,axis=1));gc=cp.concatenate((cp.zeros(1),cp.cumsum(gl)))
ds=np.unique(np.r_[np.linspace(0,cum[-1],65536),cum]);gd=cp.asarray(ds);idx=cp.minimum(cp.searchsorted(gc,gd,side='right')-1,len(p)-2)
fraction=(gd-gc[idx])/gl[idx];positions=gp[idx]+fraction[:,None]*(gp[idx+1]-gp[idx])
witness=np.stack([np.interp(ds,cum,p[:,k]) for k in range(3)],axis=1)
error=float(cp.max(cp.abs(positions-cp.asarray(witness))));assert error<1e-9
assert abs(float(gc[-1])-r['length'])<1e-9
route_results.append({'id':r['id'],'samples':len(ds),'length_m':float(gc[-1]),'max_error_m':error})
cp.cuda.Stream.null.synchronize()
result={'device':cp.cuda.runtime.getDeviceProperties(0)['name'].decode(),'fixture_sha256':hashlib.sha256(raw).hexdigest(),'panel_vertices':len(panel),'panel_max_error_m':panel_error,'routes':route_results,'elapsed_s':time.perf_counter()-started,'scope':'Actual renderer geometry and route interpolation agreement. Not browser raster validation, collision clearance, electrical or structural approval. … [line shortened here: 402 characters; full line on GitHub]
out=ROOT/'.local';out.mkdir(exist_ok=True);(out/'gpu-scene-check.json').write_text(json.dumps(result,indent=2),encoding='utf8');print(json.dumps(result))Browser
A JavaScript module in the tests folder of Graphics Engines Open Source that tests cases, exported routes and cables. It is built from the colours step (`colours`).
testgraphics-engines-open-source / tests/browser.cjs · lines 1–51 of 51 · Entry point
- What it does
- It tests cases, exported routes and cables. Defines colours. Uses libraries node:assert/strict, node:fs, node:path, node:http, node:zlib. Side effects: changes the web page (DOM); reads or writes files.
- Why it exists in the grid workflow
- Domain terms in the code: cables.
- Inputs & outputs
- In: JSON file routes.json. Out: JSON file cases.json; JSON file exported-routes.json; JSON file report.json; WebGL/WebGPU drawing.
- Downstream impact
- Used directly by 1 file: Pages Workflow (graphics-engines-open-source).
- What it achieves
- Real Chromium interaction test. npm install --no-save Playwright; npx Playwright install chromium.
- Why it matters
- Run by Pages Workflow.
- Application
- graphics-engines-open-source · tests · JavaScript module
- Uses
- node:assert/strict, node:fs, node:path, node:http, node:zlib
- Used by
- run by Pages Workflow (workflow run)
- Produces
- colours
- Defines here
- colours
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- graphics-engines-open-source@79e0bd8ee33844835e553fc84d552b6aa1521152 tests/browser.cjs:1-51 · blob 08b52c5f306c95afc9c4e42b0dc9eb51347fbc8c · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: unknown · users: none · canonical: unknown
// Real Chromium interaction test. npm install --no-save playwright; npx playwright install chromium
const assert=require('node:assert/strict'),fs=require('node:fs'),path=require('node:path'),http=require('node:http'),zlib=require('node:zlib');
const {chromium}=require(process.env.PLAYWRIGHT_MODULE||'playwright');
const root=path.resolve(__dirname,'../web'),out=path.resolve(__dirname,'../.local/browser');
fs.mkdirSync(out,{recursive:true});
// Decode Chromium PNG screenshots to prove that the unobstructed canvas has rendered lines.
function colours(png){
let p=8,w,h,bpp,parts=[];
while(p<png.length){const n=png.readUInt32BE(p),type=png.toString('ascii',p+4,p+8),data=png.subarray(p+8,p+8+n);p+=n+12;
if(type==='IHDR'){w=data.readUInt32BE(0);h=data.readUInt32BE(4);assert.equal(data[8],8);bpp=data[9]===6?4:data[9]===2?3:0;assert.ok(bpp);}
if(type==='IDAT')parts.push(data);
}
const raw=zlib.inflateSync(Buffer.concat(parts)),stride=w*bpp,values=new Set();let previous=Buffer.alloc(stride),offset=0;
for(let y=0;y<h;y++){const filter=raw[offset++],row=Buffer.alloc(stride);for(let x=0;x<stride;x++){
const a=x>=bpp?row[x-bpp]:0,b=previous[x],c=x>=bpp?previous[x-bpp]:0,q=a+b-c;
const pa=Math.abs(q-a),pb=Math.abs(q-b),pc=Math.abs(q-c),prediction=filter===0?0:filter===1?a:filter===2?b:filter===3?Math.floor((a+b)/2):pa<=pb&&pa<=pc?a:pb<=pc?b:c;
row[x]=(raw[offset++]+prediction)&255;
}for(let x=0;x<stride;x+=bpp)values.add(`${row[x]},${row[x+1]},${row[x+2]}`);previous=row;}
return values.size;
}
const server=http.createServer((req,res)=>{try{const name=decodeURIComponent(new URL(req.url,'http://localhost').pathname),file=path.resolve(root,'.'+(name==='/'?'/index.html':name));if(!file.startsWith(root+path.sep))throw Error('Path outside web');const data=fs.readFileSync(file);res.setHeader('Content-Type',({'.html':'text/html','.mjs':'text/javascript','.css':'text/css','.json':'application/js … [line shortened here: 520 characters; full line on GitHub]
(async()=>{let browser;const report={checks:[],errors:[]};try{
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
browser=await chromium.launch({...(process.env.PLAYWRIGHT_CHANNEL?{channel:process.env.PLAYWRIGHT_CHANNEL}:{}),headless:true,args:['--use-angle=swiftshader','--enable-unsafe-swiftshader']});
const page=await browser.newPage({viewport:{width:1280,height:900},acceptDownloads:true});
page.on('pageerror',e=>report.errors.push(e.message));
await page.goto(`http://127.0.0.1:${server.address().port}/?baseline`,{waitUntil:'networkidle'});
await page.waitForFunction(()=>window.electricalExplorer?.state.vertexCount>0);
assert.equal(await page.locator('#error').textContent(),'');
const playCases=[];const state=async()=>{const value=await page.evaluate(()=>window.electricalExplorer.state);if(value.routes.length>=48&&playCases.length<12){playCases.push({id:'case-'+String(playCases.length+1).padStart(2,'0'),settings:value.settings,routes:value.routes.map((r,i)=>({id:'route-'+(i+1),length:r.length,points:r.points}))});const folder=path.resolve(__dirname,'../.local/play-audit' … [line shortened here: 614 characters; full line on GitHub]
const clip={x:350,y:0,width:930,height:790};
const initial=await page.screenshot({path:path.join(out,'initial.png'),clip});
report.canvasColours=colours(initial);assert.ok(report.canvasColours>10,'Canvas must contain rendered geometry');report.checks.push('nonempty WebGL canvas');
await page.locator('[name=height]').fill('2.5');await page.getByRole('button',{name:'Apply geometry',exact:true}).click();assert.equal((await state()).settings.height,2.5);report.checks.push('numeric geometry applied');
for(const mode of ['walk','fly']){await page.locator('#mode').selectOption(mode);await page.locator('#scene').focus();const before=await page.screenshot({clip});await page.keyboard.down('w');await page.waitForTimeout(400);await page.keyboard.up('w');const after=await page.screenshot({clip});assert.equal((await state()).mode,mode);assert.ok(!before.equals(after),`${mode} W changes rendered view`); … [line shortened here: 440 characters; full line on GitHub]
await page.locator('#start').click();await page.keyboard.down('w');await page.waitForTimeout(400);await page.keyboard.up('w');const forward=(await state()).distance;assert.ok(forward>0);await page.keyboard.down('s');await page.waitForTimeout(180);await page.keyboard.up('s');assert.ok((await state()).distance<forward);report.checks.push('cable W/S distance');
await page.locator('#blueprint').click();assert.equal((await state()).mode,'top');assert.equal(await page.locator('aside').isVisible(),false);await page.locator('#show').click();assert.equal(await page.locator('aside').isVisible(),true);await page.locator('#hide').click();assert.equal(await page.locator('aside').isVisible(),false);assert.equal(await page.evaluate(()=>document.activeElement.id),'s … [line shortened here: 488 characters; full line on GitHub]
await page.locator('summary').filter({hasText:'Cable route files'}).click();
const routes=[{id:'browser-test',label:'Browser metric test',points:[[0,0,0],[3,4,0],[3,4,12]]}],envelope={schema:'electrical-routes/1',units:'metres',axes:'ENU',routes};
await page.locator('#route-file').setInputFiles({name:'routes.json',mimeType:'application/json',buffer:Buffer.from(JSON.stringify(envelope))});await page.waitForFunction(()=>window.electricalExplorer.state.routes[0].id==='browser-test');assert.equal((await state()).routes[0].length,17);
const downloadPromise=page.waitForEvent('download');await page.locator('#export-routes').click();const download=await downloadPromise;await download.saveAs(path.join(out,'exported-routes.json'));assert.deepEqual(JSON.parse(fs.readFileSync(path.join(out,'exported-routes.json'),'utf8')).routes,routes);report.checks.push('real file import/export and 17 m length');
await page.locator('#plantPreset').click();assert.equal((await state()).mode,'top');const inventory=await page.evaluate(()=>electricalExplorer.plantInventory);assert.equal(inventory.stationCount,10);await page.screenshot({path:path.join(out,'plant.png')});report.checks.push('100 MWp overview button');await page.locator('#show').click();await page.locator('#arrayNumber').fill('100');await page.loc … [line shortened here: 642 characters; full line on GitHub]
await page.screenshot({path:path.join(out,'final.png')});
await page.goto(`http://127.0.0.1:${server.address().port}/`,{waitUntil:'networkidle'});
await page.waitForFunction(()=>electricalExplorer.blockInventory()?.modules===900);await page.locator('#direct-ac').click();await page.waitForFunction(()=>electricalExplorer.acInventory()?.phaseCables===84);assert.equal((await state()).mode,'orbit');assert.equal(await page.locator('aside').isVisible(),false);await page.screenshot({path:path.join(out,'ac-trench-default.png')});await page.locator(' … [line shortened here: 1,757 characters; full line on GitHub]
const inv=await page.evaluate(()=>electricalExplorer.blockInventory());assert.equal(inv.modulesPerString,30);assert.ok((await page.locator('#string-stc').textContent()).includes('1377.0 V'));assert.ok((await page.locator('#string-stc').textContent()).includes('1143.0 V'));assert.equal(inv.modules,900);assert.equal(inv.totalStrings,30);assert.equal(inv.spareStrings,6);assert.equal(inv.connectedMod … [line shortened here: 1,276 characters; full line on GitHub]
await page.screenshot({path:path.join(out,'full-table-3d.png')});const projected=await page.evaluate(()=>electricalExplorer.project([10,30,2]));await page.mouse.move(600,400);await page.mouse.wheel(0,-250);await page.waitForTimeout(120);const zoomed=await page.evaluate(()=>electricalExplorer.project([10,30,2]));assert.notDeepEqual(zoomed,projected);const frameA=await page.locator('#scene').screen … [line shortened here: 3,081 characters; full line on GitHub]
await page.locator('#direct-station').click();await page.waitForFunction(()=>electricalExplorer.stationInventory()?.tables===23);const station=await page.evaluate(()=>electricalExplorer.stationInventory());assert.equal(station.installedModules,20700);assert.equal(station.connectedModules,20160);assert.equal(station.connectedStrings,672);assert.equal(station.spareStrings,18);assert.deepEqual(stati … [line shortened here: 1,589 characters; full line on GitHub]
const mobileContext=await browser.newContext({viewport:{width:390,height:844},isMobile:true,hasTouch:true});const mobile=await mobileContext.newPage();mobile.on('pageerror',e=>report.errors.push(e.message));await mobile.goto(`http://127.0.0.1:${server.address().port}/`,{waitUntil:'networkidle'});await mobile.waitForFunction(()=>electricalExplorer.blockInventory()?.modules===900);assert.ok(await m … [line shortened here: 1,806 characters; full line on GitHub]
assert.deepEqual(report.errors,[]);report.status='passed';
}catch(error){report.status='failed';report.failure=error.stack;process.exitCode=1;}finally{if(browser)await browser.close();await new Promise(resolve=>server.close(resolve));fs.writeFileSync(path.join(out,'report.json'),JSON.stringify(report,null,2));console.log(JSON.stringify(report,null,2));}})();Existing Wiring
A JavaScript module in the tests folder of Graphics Engines Open Source that tests cables. It is built from the snapshot step (`snapshot`) and the animation step (`animation`).
testgraphics-engines-open-source / tests/existing-wiring.cjs · lines 1–42 of 42 · Entry point · pattern snapshot (shared by 43 files)
- What it does
- It tests cables. Defines snapshot, animation. Uses libraries node:assert/strict, node:fs, node:path. Side effects: changes the web page (DOM); reads or writes files.
- Why it exists in the grid workflow
- Domain terms in the code: cables.
- Inputs & outputs
- Out: JSON file report.json.
- Downstream impact
- Used directly by 1 file: Existing Wiring Workflow (graphics-engines-open-source).
- What it achieves
- Browser acceptance against the existing published Ventus drawings.
- Why it matters
- Run by Existing Wiring Workflow.
- Application
- graphics-engines-open-source · tests · JavaScript module
- Uses
- Ventus — Wiring Page (estate URL), node:assert/strict, node:fs, node:path
- Used by
- run by Existing Wiring Workflow (workflow run)
- Produces
- snapshot, animation
- Defines here
- snapshot, animation
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- graphics-engines-open-source@79e0bd8ee33844835e553fc84d552b6aa1521152 tests/existing-wiring.cjs:1-42 · blob ae7c1bacf8855819cab5f1cbe19a9f92b8081721 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: unknown · users: none · canonical: unknown
// Browser acceptance against the existing published Ventus drawings.
const {chromium}=require(process.env.PLAYWRIGHT_MODULE||'playwright');
const assert=require('node:assert/strict'),fs=require('node:fs'),path=require('node:path');
const out=path.resolve(__dirname,'../.local/existing-wiring');fs.mkdirSync(out,{recursive:true});
const base=process.env.EXISTING_WIRING_BASE||'https://globalgrid2050.com/ventus/wiring/';
(async()=>{let browser;const results=[];try{
browser=await chromium.launch({headless:true,...(process.env.PLAYWRIGHT_CHANNEL?{channel:process.env.PLAYWRIGHT_CHANNEL}:{}),args:['--use-angle=swiftshader','--enable-unsafe-swiftshader']});
for(const name of ['inverter-48','inverter-station']){
const page=await browser.newPage({viewport:{width:1600,height:1100}}),result={name,url:new URL(name+'.html',base).href,errors:[],checks:[]};results.push(result);
page.on('pageerror',error=>result.errors.push(error.message));page.setDefaultTimeout(30000);
try{
const response=await page.goto(result.url,{waitUntil:'networkidle'});assert.equal(response.status(),200);
if(!await page.locator('#flow').isVisible())await page.locator(name==='inverter-48'?'#menu':'#controls').click();
if(name==='inverter-48'){
await page.waitForFunction(()=>window.__inverter48?.ready===true);
const snapshot=()=>page.evaluate(()=>({ready:__inverter48.ready,playing:__inverter48.playing,frames:__inverter48.flowFrames,stats:__inverter48.flowStats,homes:__inverter48.animatedHomeCount,visibility:document.visibilityState}));
result.initial=await snapshot();if(!result.initial.playing)await page.locator('#flow').click();
await page.waitForFunction(()=>__inverter48.flowFrames>2&&__inverter48.flowStats.homePaths>0);
const before=await snapshot(),started=Date.now();result.frameProbe={before};
try{await page.waitForFunction(previous=>__inverter48.flowFrames>previous,before.frames,{timeout:10000,polling:100});}finally{result.frameProbe.elapsedMs=Date.now()-started;result.frameProbe.after=await snapshot();}
const after=await snapshot();
assert.equal(after.playing,true);assert.ok(after.frames>before.frames);assert.equal(after.homes,48);result.running=after;
await page.screenshot({path:path.join(out,name+'-running.png')});
await page.locator('#flow').click();await page.waitForTimeout(150);const stopped=await snapshot();await page.waitForTimeout(350);const still=await snapshot();assert.equal(still.playing,false);assert.equal(still.frames,stopped.frames);result.paused=still;
await page.locator('#flow').click();await page.waitForFunction(previous=>__inverter48.flowFrames>previous,still.frames,{timeout:10000,polling:100});result.checks.push('ready; 48 animated home cables; frames advance, pause and resume');
}else{
await page.waitForFunction(()=>window.__inverterStation?.model&&document.querySelector('#drawing .power'));
result.model=await page.evaluate(()=>({inverters:__inverterStation.model.inverters.length,cables:__inverterStation.model.cables.length,sections:__inverterStation.model.sections.length}));
assert.deepEqual(result.model,{inverters:28,cables:84,sections:2});
const animation=()=>page.locator('#drawing .power').first().evaluate(e=>{const s=getComputedStyle(e);return {name:s.animationName,state:s.animationPlayState,display:s.display,offset:s.strokeDashoffset,duration:s.animationDuration};});
if(await page.locator('#drawing').evaluate(e=>e.classList.contains('paused')))await page.locator('#flow').click();
await page.waitForTimeout(100);const before=await animation();await page.waitForTimeout(350);const after=await animation();
assert.notEqual(after.name,'none');assert.notEqual(after.display,'none');assert.equal(after.state,'running');assert.notEqual(after.offset,before.offset);result.running={before,after};
await page.screenshot({path:path.join(out,name+'-running.png')});
await page.locator('#flow').click();await page.waitForTimeout(100);const stopped=await animation();await page.waitForTimeout(350);const still=await animation();assert.equal(still.display,'none');result.paused={stopped,still};
await page.locator('#flow').click();await page.waitForTimeout(100);const resumed=await animation();assert.notEqual(resumed.display,'none');await page.waitForTimeout(350);assert.notEqual((await animation()).offset,resumed.offset);result.checks.push('28 inverters / 84 phase cables; computed dash offset advances, pause hides flow, resume moves flow');
}
assert.deepEqual(result.errors,[]);result.status='passed';
}catch(error){result.status='failed';result.failure=error.stack;process.exitCode=1;}
finally{await page.screenshot({path:path.join(out,name+'.png'),fullPage:true}).catch(()=>{});await page.close();}
}
}catch(error){results.push({status:'failed',failure:error.stack});process.exitCode=1;}finally{if(browser)await browser.close();fs.writeFileSync(path.join(out,'report.json'),JSON.stringify(results,null,2));console.log(JSON.stringify(results,null,2));}})();Explore Test
A test in the tests folder of Graphics Engines Open Source that checks Explore.
testgraphics-engines-open-source / tests/explore.test.mjs · lines 1–37 of 37 · Entry point · pattern evaluate (shared by 18 files)
- What it does
- It tests cables. Defines node, evaluate. Uses libraries node:assert/strict, node:fs, node:vm. Side effects: changes the web page (DOM); reads or writes files.
- Why it exists in the grid workflow
- Domain terms in the code: cables.
- Inputs & outputs
- In: command-line arguments.
- Downstream impact
- Used directly by 2 files: Geometry Check Workflow (graphics-engines-open-source); Pages Workflow (graphics-engines-open-source).
- What it achieves
- Defines `node` and `evaluate`.
- Why it matters
- Run by Geometry Check Workflow and Pages Workflow.
- Application
- graphics-engines-open-source · tests · test
- Uses
- Explore (new URL import.meta.url), node:assert/strict, node:fs, node:vm
- Used by
- run by Geometry Check Workflow (workflow run), run by Pages Workflow (workflow run)
- Produces
- node, evaluate
- Defines here
- node, evaluate
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- graphics-engines-open-source@79e0bd8ee33844835e553fc84d552b6aa1521152 tests/explore.test.mjs:1-37 · blob 60019ed7e693b10fa9e1bd7d7a5abc093e78bb25 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: unknown · users: none · canonical: unknown
import assert from 'node:assert/strict';
import fs from 'node:fs';
import vm from 'node:vm';
const nodes=new Map();
function node(id){if(!nodes.has(id))nodes.set(id,{value:'2',checked:id==='props',clientWidth:1200,clientHeight:800,getContext:()=>null,addEventListener(){},focus(){},replaceChildren(){},setPointerCapture(){}});return nodes.get(id);}
const context=vm.createContext({document:{getElementById:node,querySelector:()=>node('aside')},window:{addEventListener(){}},console,Float32Array,Option:class{},requestAnimationFrame(){},devicePixelRatio:1});
vm.runInContext(fs.readFileSync(new URL('../web/explore.mjs',import.meta.url),'utf8'),context);
const evaluate=code=>vm.runInContext(code,context),plain=value=>JSON.parse(JSON.stringify(value));
assert.deepEqual(plain(evaluate('routeAt(routes[0],0)')),[0,0,.4]);
assert.deepEqual(plain(evaluate('routeAt(routes[0],routes[0].length)')),[18,-8,.4]);
assert.deepEqual(plain(evaluate('routeAt(routes[0],3)')),[0,-3,.4]);
assert.deepEqual(plain(evaluate('routeAt(routes[0],9)')),[6,-3,.4]);
assert.throws(()=>evaluate('validateRoutes([{id:"bad",points:[[0,0,0],[0,0,0]]}])'),/repeated/);
assert.throws(()=>evaluate('validateRoutes([{id:"bad",points:[[0,0,0],[NaN,0,0]]}])'),/finite/);
assert.throws(()=>evaluate('validateRoutes([{id:"a",points:[[0,0,0],[1,0,0]]},{id:"a",points:[[0,0,0],[1,0,0]]}])'),/unique/);
evaluate('settings.height=20;build()');
assert.ok(evaluate('vertices.some((v,i)=>i%6===2&&v>20)'),'20 m lower edge supports higher upper edge');
for(const mode of ['top','orbit','walk','fly','cable']){evaluate(`changeMode('${mode}')`);const m=evaluate('(()=>{const c=camera();return matrixMultiply(projection(1.5,mode==="top"),viewMatrix(c.position,c.target,c.up));})()');assert.ok([...m].every(Number.isFinite),mode+' camera finite');}
const top=plain(evaluate('changeMode("top");camera()'));
assert.equal(top.position[0],top.target[0]);assert.equal(top.position[1],top.target[1]);assert.ok(top.position[2]>top.target[2]);
const m=evaluate('viewMatrix([0,0,10],[0,0,0],[0,1,0])');assert.equal(m[14],-10);
evaluate('const originalRoutes=routes;routes=validateRoutes([{id:"vertical",points:[[0,0,0],[0,0,5]]}]);routeIndex=0;distance=5;changeMode("cable")');
assert.ok([...evaluate('(()=>{const c=camera();return viewMatrix(c.position,c.target)})()')].every(Number.isFinite));
for(const points of [[[0,0,0],[.25,0,0],[0,0,0],[0,1,0]],[[0,0,0],[0,0,.0001]]]){evaluate(`routes=validateRoutes([{id:'edge',points:${JSON.stringify(points)}}]);distance=0`);assert.ok(Math.abs(evaluate('(()=>{const c=camera();return Math.hypot(...sub(c.target,c.position))})()')-1)<1e-9);const basis=evaluate('(()=>{const c=camera();return viewMatrix(c.position,c.target)})()');for(let column=0;colum … [line shortened here: 490 characters; full line on GitHub]
evaluate('changeMode("fly");eye=[0,0,0];heading=0;lookPitch=Math.PI/3;keys.add("w");lastTime=0;tick(50);keys.clear()');
assert.ok(Math.abs(evaluate('eye[1]')-.05)<1e-9);
evaluate('routes=originalRoutes;settings.height=1.5;build()');
const fixture=evaluate('({settings,vertices,routes:routes.map(r=>({id:r.id,points:r.points,length:r.length})),units:"metres",stride:6,axes:"east,north,up",columns:"x,y,z,r,g,b"})');
if(process.argv[2]){fs.mkdirSync(new URL('../.local/',import.meta.url),{recursive:true});fs.writeFileSync(process.argv[2],JSON.stringify(fixture));}
evaluate('activatePlant()');
const inventory=plain(evaluate('window.electricalExplorer.plantInventory'));
assert.equal(inventory.modules,151516);assert.equal(inventory.blocks.reduce((sum,b)=>sum+b.modules,0),151516);
assert.equal(inventory.stationCount,10);assert.equal(inventory.blocks.flatMap(b=>b.station.transformers).length,20);
assert.equal(inventory.actualDCMWp,100.00056);assert.equal(inventory.aggregateTransformerMVA,100);
assert.equal(evaluate('routes.length'),10);assert.equal(evaluate('settings.rows'),5);
assert.ok(evaluate('vertices.length')<1000000,'overview remains bounded');
console.log('Explorer: routes, camera, raised geometry and 100 MWp inventory checks passed.');Convert Connector
A JavaScript module in the tools folder of Graphics Engines Open Source that calculates planar distances, using SHA-256.
storagegraphics-engines-open-source / tools/convert-connector.cjs · lines 1–8 of 8 · Not reached from any entry point (candidate for review)
- What it does
- It loads data. Uses libraries node:fs, node:crypto. Side effects: reads or writes files.
- Inputs & outputs
- In: command-line arguments.
- What it achieves
- Local-only STEP conversion. Input/output paths are supplied explicitly; no upload.
- Why it matters
- No other file in the estate was found to import it.
- Application
- graphics-engines-open-source · tools · JavaScript module
- Uses
- node:fs, node:crypto
- 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
- graphics-engines-open-source@79e0bd8ee33844835e553fc84d552b6aa1521152 tools/convert-connector.cjs:1-8 · blob 471889db4eaf2bc2b192f04f11c834afbd24f2f9 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: unreached_review
// Local-only STEP conversion. Input/output paths are supplied explicitly; no upload.
const fs=require('node:fs'),crypto=require('node:crypto');
const [input,output,importer]=process.argv.slice(2);
if(!input||!output||!importer)throw Error('Usage: node tools/convert-connector.cjs input.stp output.json importer-module');
(async()=>{const occt=await require(importer)(),raw=fs.readFileSync(input),model=occt.ReadStepFile(raw,{linearUnit:'meter',linearDeflectionType:'absolute_value',linearDeflection:.00015,angularDeflection:.3});if(!model.success)throw Error('STEP import failed');const edges=new Map(),bounds=[[Infinity,Infinity,Infinity],[-Infinity,-Infinity,-Infinity]];
for(const mesh of model.meshes){const p=mesh.attributes.position.array,idx=mesh.index.array;for(let i=0;i<idx.length;i+=3){const a=[0,1,2].map(k=>p[3*idx[i]+k]),b=[0,1,2].map(k=>p[3*idx[i+1]+k]),c=[0,1,2].map(k=>p[3*idx[i+2]+k]),u=b.map((v,k)=>v-a[k]),v=c.map((x,k)=>x-a[k]),n=[u[1]*v[2]-u[2]*v[1],u[2]*v[0]-u[0]*v[2],u[0]*v[1]-u[1]*v[0]],length=Math.hypot(...n);if(length<1e-15)continue;const normal … [line shortened here: 755 characters; full line on GitHub]
const sizes=bounds[1].map((x,i)=>x-bounds[0][i]),axis=sizes.indexOf(Math.max(...sizes)),other=[0,1,2].filter(i=>i!==axis),centre=bounds[0].map((x,i)=>(x+bounds[1][i])/2),map=p=>[p[other[0]]-centre[other[0]],p[other[1]]-centre[other[1]],p[axis]-bounds[0][axis]].map(x=>+x.toFixed(7));
const lines=[];for(const edge of edges.values()){if(edge.normals.length===1||edge.normals.some(n=>Math.abs(n.reduce((s,x,k)=>s+x*edge.normals[0][k],0))<Math.cos(Math.PI/9)))lines.push([map(edge.a),map(edge.b)]);}if(lines.length>15000)throw Error('Too many feature edges');const result={schema:'local-connector-lines/1',units:'m',sourceSHA256:crypto.createHash('sha256').update(raw).digest('hex'),scop … [line shortened here: 667 characters; full line on GitHub]GPU Watch
A Python command-line tool in the tools folder of Graphics Engines Open Source covering explore geometry, using SHA-256.
storagegraphics-engines-open-source / tools/gpu_watch.py · lines 1–130 of 130 · Entry point · pattern atomic_json (shared by 2 files)
- What it does
- Defines 6 functions or classes, including stamp, atomic_json, hashes, run_watch, save. Uses libraries pathlib, argparse, datetime, hashlib, json. Side effects: reads or writes files; starts processes.
- Inputs & outputs
- In: JSON file status.json; JSON file explore-geometry.json; command-line arguments.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- It runs watch (`run_watch`) and is built from the stamp step (`stamp`) and the atomic JSON helper (`atomic_json`). Bounded repeat checks of a fixed renderer fixture; no editing or publishing. It accepts `--fixture`, `--duration` and `--interval`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- graphics-engines-open-source · tools · Python CLI
- Uses
- Check Scene GPU (script call), pathlib, argparse, datetime, hashlib, json, os, subprocess, sys
- Used by
- none found
- Produces
- stamp, atomic_json, hashes, run_watch, main
- Defines here
- stamp, atomic_json, hashes, run_watch, save, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- graphics-engines-open-source@79e0bd8ee33844835e553fc84d552b6aa1521152 tools/gpu_watch.py:1-130 · blob af668a9a5b2af19b0f7b147f13499bc8f44240bd · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: supporting_data
"""Bounded repeat checks of a fixed renderer fixture; no editing or publishing."""
from pathlib import Path
import argparse
import datetime as dt
import hashlib
import json
import os
import subprocess
import sys
import time
ROOT = Path(__file__).resolve().parents[1]
SCOPE = ('Repeated CuPy reproducibility checks of the fixed baseline renderer fixture. '
'Not new design exploration, 100 MWp preset coverage, browser rendering, '
'electrical approval, collision checking, or automatic repair.')
def stamp():
return dt.datetime.now(dt.timezone.utc).isoformat()
def atomic_json(path, value):
temporary = path.with_suffix('.tmp')
temporary.write_text(json.dumps(value, indent=2), encoding='utf-8')
os.replace(temporary, path)
def hashes(fixture):
files = [fixture, ROOT / 'check_scene_gpu.py', ROOT / 'web/explore.mjs',
ROOT / 'tests/explore.test.mjs', Path(__file__).resolve()]
return {str(p): hashlib.sha256(p.read_bytes()).hexdigest() for p in files}
def run_watch(args):
output = ROOT / '.local/watch'
output.mkdir(parents=True, exist_ok=True)
run_id = dt.datetime.now(dt.timezone.utc).strftime('%Y%m%dT%H%M%S%fZ')
run_dir = output / run_id
run_dir.mkdir()
started = time.monotonic()
deadline = started + args.duration
state = {'run_id': run_id, 'state': 'running', 'started_at': stamp(),
'duration_s': args.duration, 'interval_s': args.interval,
'samples': 0, 'scope': SCOPE, 'run_directory': str(run_dir)}
def save():
state['updated_at'] = stamp()
atomic_json(output / 'status.json', state)
atomic_json(run_dir / 'status.json', state)
save()
try:
baseline = hashes(args.fixture)
state['source_hashes'] = baseline
save()
for sample in range(1, 61):
due = started + (sample - 1) * args.interval
if due >= deadline:
break
time.sleep(max(0, due - time.monotonic()))
current = hashes(args.fixture)
if current != baseline:
raise RuntimeError('Source or fixture changed; stopped to avoid reporting stale-fixture validation.')
record = {'sample': sample, 'started_at': stamp(), 'source_hashes': current}
flags = getattr(subprocess, 'CREATE_NO_WINDOW', 0) if os.name == 'nt' else 0
result = subprocess.run([sys.executable, str(ROOT / 'check_scene_gpu.py'),
str(args.fixture)], cwd=ROOT, capture_output=True,
text=True, timeout=45, creationflags=flags)
record.update(returncode=result.returncode, finished_at=stamp())
log = (result.stdout + '\n' + result.stderr)[-65536:]
(run_dir / f'log-{sample % 10:02d}.txt').write_text(log, encoding='utf-8')
if result.returncode == 0:
record['result'] = json.loads(result.stdout.strip().splitlines()[-1])
if record['result'].get('fixture_sha256') != baseline[str(args.fixture)]:
raise RuntimeError('Checker result refers to a different fixture.')
else:
record['error'] = log[-4000:]
atomic_json(run_dir / f'sample-{sample:02d}.json', record)
state['samples'] = sample
state['last_sample'] = record
save()
if result.returncode:
raise RuntimeError(f'GPU check failed with exit code {result.returncode}; see sample log.')
if time.monotonic() >= deadline:
break
time.sleep(max(0, deadline - time.monotonic()))
state['state'] = 'complete'
except (Exception, KeyboardInterrupt) as error:
state['state'] = 'failed'
state['error'] = str(error) or type(error).__name__
finally:
state['finished_at'] = stamp()
state['elapsed_s'] = round(time.monotonic() - started, 3)
save()
if args.dispatch_summary and state['state'] == 'complete':
result = state['last_sample']['result']
summary = {'schema': 'local-gpu-summary/1', 'status': 'pass',
'samples': state['samples'], 'fixture_sha256': result['fixture_sha256'],
'panel_max_error_m': result['panel_max_error_m'],
'route_max_error_m': max((r['max_error_m'] for r in result['routes']), default=0)}
try:
flags = getattr(subprocess, 'CREATE_NO_WINDOW', 0) if os.name == 'nt' else 0
dispatch = subprocess.run(['gh', 'workflow', 'run', 'geometry-check.yml',
'--repo', 'Ventusltd/graphics-engines-open-source',
'-f', 'local_gpu_summary=' + json.dumps(summary, separators=(',', ':'))],
capture_output=True, text=True, timeout=30, creationflags=flags)
state['dispatch'] = {'state': 'submitted' if dispatch.returncode == 0 else 'failed',
'returncode': dispatch.returncode}
if dispatch.returncode:
state['dispatch']['error'] = dispatch.stderr[-2000:]
except Exception as error:
state['dispatch'] = {'state': 'failed', 'error': str(error)}
save()
return 0 if state['state'] == 'complete' else 1
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--fixture', type=Path, default=ROOT / '.local/explore-geometry.json')
parser.add_argument('--duration', type=float, default=3600)
parser.add_argument('--interval', type=float, default=60)
parser.add_argument('--dispatch-summary', action='store_true',
help='Opt in to sending only allowlisted numeric/hash results to the public CPU workflow after success.')
args = parser.parse_args()
if not 1 <= args.duration <= 3600 or not 1 <= args.interval <= 3600:
parser.error('duration and interval must be between 1 and 3600 seconds')
args.fixture = args.fixture.resolve()
return run_watch(args)
if __name__ == '__main__':
raise SystemExit(main())Explore
A JavaScript module in Graphics Engines Open Source that builds plant, starts ac, calculates planar distances and renders with WebGL, covering cables and transformers. Served with the page at https://ventusltd.github.io/graphics-engines-open-source/web/.
interactiongraphics-engines-open-source / web/explore.mjs · lines 1–114 of 114 · Entry point · pattern routeAt (shared by 2 files)
- What it does
- It draws cables and transformers. Defines 20 functions or classes, including $, add, plantInventory, plantTablePosition, buildPlant. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain terms in the code: cables, transformers.
- Inputs & outputs
- Out: WebGL/WebGPU drawing.
- Downstream impact
- Used directly by 4 files: Route File Test (graphics-engines-open-source); Explore Test (graphics-engines-open-source); Graphics Engines Open Source — Index Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/); Geometry Check Workflow (graphics-engines-open-source). Reached from 2 other entry points, including Graphics Engines Open Source — Versions Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/versions/); Pages Workflow (graphics-engines-open-source). It is itself an entry point, published at https://ventusltd.github.io/graphics-engines-open-source/web/.
- What it achieves
- It builds plant (`buildPlant`), routes ui (`routeUI`) and starts ac (`startAC`). Independent WebGL viewer. All geometry is local `east/north/up` in metres. Its code works with 5 MVA, 352 kVA and 10 MVA. It responds to wheel, pointerdown and change events.
- Why it matters
- Loaded by the Graphics Engines Open Source page at https://ventusltd.github.io/graphics-engines-open-source/web/. Run by Geometry Check Workflow. Checked by 2 tests, including Route File Test.
- Application
- graphics-engines-open-source · web · JavaScript module
- Uses
- none found
- Used by
- referenced by Route File Test (new URL import.meta.url), referenced by Explore Test (new URL import.meta.url), loaded by Graphics Engines Open Source — Index Page (script src), run by Geometry Check Workflow (workflow run)
- Produces
- $, add, plantInventory, plantTablePosition, buildPlant, routeAt, line, loop, box, matrixMultiply, viewMatrix, projection
- Defines here
- $, add, plantInventory, plantTablePosition, buildPlant, routeAt, line, loop, box, matrixMultiply, viewMatrix, projection, routeUI, populateRoutes, reset, blockPosition, dcOrder, ridgeHeight, dcDucts, startAC
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- graphics-engines-open-source@79e0bd8ee33844835e553fc84d552b6aa1521152 web/explore.mjs:1-114 · blob ce22db1c2e0c21bd7fc99a26e5d4ce0968b0afdf · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
// Independent WebGL viewer. All geometry is local east/north/up in metres.
const $=id=>document.getElementById(id),canvas=$('scene'),gl=canvas.getContext('webgl',{antialias:true});
const add=(a,b)=>a.map((v,i)=>v+b[i]),sub=(a,b)=>a.map((v,i)=>v-b[i]),mul=(a,s)=>a.map(v=>v*s),dot=(a,b)=>a.reduce((s,v,i)=>s+v*b[i],0),cross=(a,b)=>[a[1]*b[2]-a[2]*b[1],a[2]*b[0]-a[0]*b[2],a[0]*b[1]-a[1]*b[0]],norm=a=>mul(a,1/(Math.hypot(...a)||1)),lerp=(a,b,t)=>add(a,mul(sub(b,a),t)),clamp=(x,a,b)=>Math.max(a,Math.min(b,x));
let settings={height:1.5,tilt:20,tables:12,columns:8,rows:2,moduleWidth:1.2,moduleLength:2.4},mode='orbit',origin=null,routeIndex=0,distance=0,extent=60,center=[0,0,0],yaw=-.7,pitch=.65,radius=90,eye=[0,-10,1.7],heading=0,lookPitch=0,drag=null,dirty=true,lastTime=0;
const keys=new Set(),colors={panel:[.7,.79,.88],structure:[.3,.41,.53],grid:[.09,.17,.25],cable:[.2,.45,.62],selected:[.55,.88,1],props:[.48,.58,.65]};
let vertices=[],buffer,program,vertexCount=0;
let plantMode=false,inverterMode=false,acMode=false,dcInitialised=false,stationMode=false;
const stationInverters=[],stationTransformers=[[155,320,1.5],[155,345,1.5]];
function plantInventory(){const modules=Math.ceil(100e6/660);return {targetDCMWp:100,moduleW:660,modules,actualDCMWp:modules*660/1e6,stationCount:10,transformerCount:20,transformerMVA:5,aggregateTransformerMVA:100,illustrative:true,blocks:Array.from({length:10},(_,i)=>({id:i+1,modules:Math.floor(modules/10)+(i<modules%10?1:0),station:{id:i+1,transformers:[{id:2*i+1,mva:5},{id:2*i+2,mva:5}]}}))};}
function plantTablePosition(n){const perBlock=Math.ceil(settings.tables/10),b=Math.min(9,Math.floor(n/perBlock)),local=n%perBlock;return [(b%5)*300+15+(local%5)*45,Math.floor(b/5)*300+20+Math.floor(local/5)*70];}
function buildPlant(){const s=settings,t=s.tilt*Math.PI/180,run=s.rows*(s.moduleLength+.02)-.02,depth=run*Math.cos(t),span=s.columns*(s.moduleWidth+.02)-.02;extent=1500;center=[725,275,0];for(let x=0;x<=1500;x+=50)line([x,0,0],[x,600,0],colors.grid);for(let y=0;y<=600;y+=50)line([0,y,0],[1500,y,0],colors.grid);
for(let b=0;b<10;b++){const x=(b%5)*300,y=Math.floor(b/5)*300;loop([[x,y,0],[x+250,y,0],[x+250,y+250,0],[x,y+250,0]],colors.structure);loop([[x+110,y+260,0],[x+140,y+260,0],[x+140,y+280,0],[x+110,y+280,0]],colors.selected);box(x+115,y+265,0,6,4,3,colors.panel);box(x+129,y+265,0,6,4,3,colors.panel);}
for(let n=0;n<s.tables;n++){const [x,y]=plantTablePosition(n);for(const wing of [-1,1])for(let r=0;r<s.rows;r++)for(let c=0;c<s.columns;c++){const v=r*(s.moduleLength+.02),u=c*(s.moduleWidth+.02),p=(dv,du)=>[x+wing*(depth-(v+dv)*Math.cos(t)),y+u+du,s.height+(v+dv)*Math.sin(t)];loop([p(0,0),p(s.moduleLength,0),p(s.moduleLength,s.moduleWidth),p(0,s.moduleWidth)],colors.panel);}for(const yy of [y,y+ … [line shortened here: 525 characters; full line on GitHub]
}
function activatePlant(){plantMode=true;settings={height:1.2,tilt:10,tables:100,columns:10,rows:5,moduleWidth:1.303,moduleLength:2.384};for(const [key,value]of Object.entries(settings)){const el=$('parameters').elements?.[key];if(el)el.value=value;}routes=validateRoutes(Array.from({length:10},(_,b)=>{const x=(b%5)*300,y=Math.floor(b/5)*300;return {id:'BLOCK-'+(b+1),label:'Illustrative block '+(b+1 … [line shortened here: 574 characters; full line on GitHub]
let routes=validateRoutes([
{id:'DC-01',label:'Array → inverter · DC · voltage unspecified',points:[[0,0,.4],[0,-3,.4],[12,-3,.4],[12,-8,.4],[18,-8,.4]]},
{id:'AC-01',label:'Inverter → transformer · AC · voltage unspecified',points:[[18,-8,.4],[21,-8,.4],[21,-16,.4],[30,-16,.4]]},
{id:'EXPORT-01',label:'Transformer → illustrative boundary · voltage unspecified',points:[[30,-16,.4],[35,-16,.4],[35,12,.4],[44,12,.4]]}
]);
function validateRoutes(input){if(!Array.isArray(input)||!input.length||input.length>10000)throw Error('Provide 1–1000 cable routes');let totalPoints=0;const ids=new Set();return input.map(r=>{if(!r||typeof r.id!=='string'||ids.has(r.id)||!Array.isArray(r.points)||r.points.length<2||r.points.length>10000)throw Error('Each cable needs a unique ID and 2–10000 points');totalPoints+=r.points.length;if … [line shortened here: 996 characters; full line on GitHub]
function routeAt(r,d){d=clamp(d,0,r.length);let i=1;while(i<r.lengths.length-1&&r.lengths[i]<d)i++;return lerp(r.points[i-1],r.points[i],(d-r.lengths[i-1])/(r.lengths[i]-r.lengths[i-1]));}
function line(a,b,color){vertices.push(...a,...color,...b,...color);}
function loop(points,c){points.forEach((p,i)=>line(p,points[(i+1)%points.length],c));}
function box(x,y,z,w,d,h,c){const p=[[x,y,z],[x+w,y,z],[x+w,y+d,z],[x,y+d,z]];loop(p,c);loop(p.map(a=>add(a,[0,0,h])),c);p.forEach(a=>line(a,add(a,[0,0,h]),c));}
function build(){vertices=[];const s=settings,w=s.moduleWidth,l=s.moduleLength,gap=.02,span=s.columns*(w+gap)-gap,run=s.rows*(l+gap)-gap,t=s.tilt*Math.PI/180,depth=run*Math.cos(t),rise=run*Math.sin(t),across=Math.ceil(Math.sqrt(s.tables));extent=Math.max(60,across*(span+5),Math.ceil(s.tables/across)*(depth+6));center=[(across-1)*(span+5)/2,(Math.ceil(s.tables/across)-1)*(depth+6)/2,0];$('arrayNumb … [line shortened here: 418 characters; full line on GitHub]
if(acMode){buildACStation();}else if(inverterMode){buildInverterBlock();}else if(plantMode){buildPlant();}else{
for(let x=-20;x<=extent+20;x+=5)line([x,-25,0],[x,extent+20,0],colors.grid);for(let y=-25;y<=extent+20;y+=5)line([-20,y,0],[extent+20,y,0],colors.grid);
for(let n=0;n<s.tables;n++){const ox=(n%across)*(span+5),oy=Math.floor(n/across)*(depth+6);for(let r=0;r<s.rows;r++)for(let c=0;c<s.columns;c++){const x=ox+c*(w+gap),v=r*(l+gap),pt=(dx,dv)=>[x+dx,oy+(v+dv)*Math.cos(t),s.height+(v+dv)*Math.sin(t)];loop([pt(0,0),pt(w,0),pt(w,l),pt(0,l)],colors.panel);}for(const x of [ox,ox+span/2,ox+span]){line([x,oy,0],[x,oy,s.height],colors.structure);line([x,oy+ … [line shortened here: 668 characters; full line on GitHub]
box(17,-9,0,2,2,2,colors.props);box(29,-17,0,3,2,2.5,colors.props);}
if($('props').checked){box(-5,-4,0,.5,.35,1.75,colors.props);box(-10,-7,0,4.5,1.8,1.6,colors.props);for(let z=0;z<=1;z+=1){const p=Array.from({length:24},(_,i)=>[-3+.6*Math.cos(i*Math.PI/12),-8+.6*Math.sin(i*Math.PI/12),z]);loop(p,colors.props);if(z===0)p.filter((_,i)=>i%6===0).forEach(a=>line(a,add(a,[0,0,1]),colors.props));}}
routes.forEach((r,i)=>{for(let p=1;p<r.points.length;p++)line(r.points[p-1],r.points[p],i===routeIndex?colors.selected:colors.cable);for(const point of [r.points[0],r.points.at(-1)]){line(add(point,[-.4,0,0]),add(point,[.4,0,0]),colors.selected);line(add(point,[0,-.4,0]),add(point,[0,.4,0]),colors.selected);}});
if(gl&&buffer){gl.bindBuffer(gl.ARRAY_BUFFER,buffer);gl.bufferData(gl.ARRAY_BUFFER,(vertices.length+routes.length*12)*4,gl.DYNAMIC_DRAW);gl.bufferSubData(gl.ARRAY_BUFFER,0,new Float32Array(vertices));vertexCount=vertices.length/6;}
$('summary').textContent=`${s.tables*s.rows*s.columns} panels · each ${w.toFixed(2)} × ${l.toFixed(2)} m · lower ${s.height.toFixed(2)} m / upper ${(s.height+rise).toFixed(2)} m · 5 m grid · ${routes.length} modelled cables`;
if(plantMode)$('summary').textContent=`100 MWp DC target · 151,516 × 660 W allocated = 100.00056 MWp · 10 blocks / 10 stations / 20 × 5 MVA transformers = 100 MVA AC nameplate · ${s.tables} representative EW tables (${s.tables*s.rows*s.columns*2} panels drawn), not full module layout · 50 m grid`;
dirty=true;
}
function matrixMultiply(a,b){const out=new Float32Array(16);for(let c=0;c<4;c++)for(let r=0;r<4;r++)for(let k=0;k<4;k++)out[c*4+r]+=a[k*4+r]*b[c*4+k];return out;}
function viewMatrix(position,target,up=[0,0,1]){const z=norm(sub(position,target));if(Math.abs(dot(up,z))>.999)up=[0,1,0];const x=norm(cross(up,z)),y=cross(z,x);return new Float32Array([x[0],y[0],z[0],0,x[1],y[1],z[1],0,x[2],y[2],z[2],0,-dot(x,position),-dot(y,position),-dot(z,position),1]);}
function projection(aspect,orthographic){const far=Math.max(5000,radius*2+extent*10);if(orthographic){const h=radius/2,w=h*aspect;return new Float32Array([1/w,0,0,0,0,1/h,0,0,0,0,-2/(far-.05),0,0,0,-(far+.05)/(far-.05),1]);}const f=1/Math.tan(Math.PI/6),near=.05;return new Float32Array([f/aspect,0,0,0,0,f,0,0,0,0,(far+near)/(near-far),-1,0,0,2*far*near/(near-far),0]);}
function camera(){if(mode==='top')return {position:add(center,[0,0,radius]),target:center,up:[0,1,0]};if(mode==='orbit')return {position:add(center,[radius*Math.cos(pitch)*Math.sin(yaw),-radius*Math.cos(pitch)*Math.cos(yaw),radius*Math.sin(pitch)]),target:center};if(mode==='cable'){const r=routes[routeIndex],p=routeAt(r,distance),reverse=$('reverse').checked?-1:1,d=clamp(distance+reverse*.5,0,r.le … [line shortened here: 813 characters; full line on GitHub]
function draw(){const d=Math.min(devicePixelRatio||1,2),w=Math.round(canvas.clientWidth*d),h=Math.round(canvas.clientHeight*d);if(canvas.width!==w||canvas.height!==h){canvas.width=w;canvas.height=h;}gl.viewport(0,0,w,h);gl.clearColor(.012,.027,.055,1);gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT);const c=camera();gl.uniformMatrix4fv(gl.getUniformLocation(program,'matrix'),false,matrixMultiply( … [line shortened here: 885 characters; full line on GitHub]
function routeUI(){const r=routes[routeIndex];$('routeInfo').textContent=r.label+' · illustrative route';$('distance').max=r.length;$('distance').value=distance;$('distanceInfo').textContent=`${distance.toFixed(2)} / ${r.length.toFixed(2)} m · ${r.id}`;dirty=true;}
function populateRoutes(){$('route').replaceChildren(...routes.map((r,i)=>new Option(r.id,i)));routeUI();}
function changeMode(next){mode=next;$('mode').value=next;keys.clear();if(mode==='walk'){eye=[-3,-8,1.7];heading=.3;lookPitch=0;}if(mode==='fly'){eye=[-4,-10,8];heading=.3;lookPitch=-.2;}$('help').textContent=mode==='cable'?'W/S or ↑/↓: travel selected cable · slider: exact distance · select any modelled cable':mode==='walk'||mode==='fly'?'Drag to look · WASD / arrows to move · Shift faster'+(mode= … [line shortened here: 553 characters; full line on GitHub]
function reset(){radius=extent*1.8;yaw=-.7;pitch=.65;build();changeMode(mode);}
function fullBlueprint(){build();const points=[];for(let i=0;i<vertices.length;i+=6)points.push([vertices[i],vertices[i+1]]);let minX=Infinity,minY=Infinity,maxX=-Infinity,maxY=-Infinity;for(const [x,y] of points){minX=Math.min(minX,x);maxX=Math.max(maxX,x);minY=Math.min(minY,y);maxY=Math.max(maxY,y);}center=[(minX+maxX)/2,(minY+maxY)/2,0];radius=Math.max(maxY-minY,(maxX-minX)/(canvas.clientWidth/ … [line shortened here: 528 characters; full line on GitHub]
function tick(time){const dt=Math.min((time-lastTime)/1000,.05);lastTime=time;const forward=Number(keys.has('w')||keys.has('arrowup'))-Number(keys.has('s')||keys.has('arrowdown')),side=Number(keys.has('d')||keys.has('arrowright'))-Number(keys.has('a')||keys.has('arrowleft')),speed=clamp(Number($('speed').value)||2,.1,20)*(keys.has('shift')?3:1);if(mode==='cable'&&forward){distance=clamp(distance+f … [line shortened here: 952 characters; full line on GitHub]
function init(){if(!gl)throw Error('WebGL unavailable. Enable browser graphics acceleration to use this viewer.');const shader=(type,source)=>{const s=gl.createShader(type);gl.shaderSource(s,source);gl.compileShader(s);if(!gl.getShaderParameter(s,gl.COMPILE_STATUS))throw Error(gl.getShaderInfoLog(s));return s;};program=gl.createProgram();gl.attachShader(program,shader(gl.VERTEX_SHADER,'attribute v … [line shortened here: 1,164 characters; full line on GitHub]
$('parameters').onsubmit=e=>{e.preventDefault();try{const next={};for(const key of Object.keys(settings)){const el=e.target.elements[key],v=Number(el.value);if(!el.value||!Number.isFinite(v)||v<Number(el.min)||v>Number(el.max)||(['tables','columns','rows'].includes(key)&&!Number.isInteger(v)))throw Error('Check '+key+' range');next[key]=v;}settings=next;build();$('error').textContent='';}catch(er … [line shortened here: 441 characters; full line on GitHub]
$('props').onchange=build;$('fit').onclick=reset;$('mode').onchange=e=>changeMode(e.target.value);$('route').onchange=e=>{routeIndex=Number(e.target.value);distance=0;build();routeUI();changeMode('cable');};$('distance').oninput=e=>{distance=Number(e.target.value);routeUI();changeMode('cable');};$('start').onclick=()=>{distance=0;routeUI();changeMode('cable');};$('end').onclick=()=>{distance=rout … [line shortened here: 491 characters; full line on GitHub]
$('blueprint').onclick=fullBlueprint;$('focusArray').onclick=()=>{const n=Number($('arrayNumber').value);if(!Number.isInteger(n)||n<1||n>settings.tables){$('error').textContent='Choose array 1–'+settings.tables;return;}const width=settings.columns*(settings.moduleWidth+.02)-.02,depth=(settings.rows*(settings.moduleLength+.02)-.02)*Math.cos(settings.tilt*Math.PI/180),across=Math.ceil(Math.sqrt(set … [line shortened here: 602 characters; full line on GitHub]
$('hide').onclick=()=>{document.querySelector('aside').hidden=true;$('show').hidden=false;canvas.focus();};$('show').onclick=()=>{document.querySelector('aside').hidden=false;$('show').hidden=true;};
canvas.oncontextmenu=e=>e.preventDefault();canvas.onpointerdown=e=>{drag={x:e.clientX,y:e.clientY,button:e.button};canvas.setPointerCapture(e.pointerId);};canvas.onpointermove=e=>{if(!drag)return;const dx=e.clientX-drag.x,dy=e.clientY-drag.y;drag.x=e.clientX;drag.y=e.clientY;if(mode==='top'||(mode==='orbit'&&drag.button===2)){const scale=radius/canvas.clientHeight;center[0]-=dx*scale;center[1]+=d … [line shortened here: 1,055 characters; full line on GitHub]
canvas.addEventListener('pointerdown',()=>canvas.focus());$('mode').addEventListener('change',()=>canvas.focus());$('route').addEventListener('change',()=>canvas.focus());for(const id of ['start','end'])$(id).addEventListener('click',()=>canvas.focus());$('distance').addEventListener('change',()=>canvas.focus());
window.addEventListener('keydown',e=>{if(/INPUT|SELECT|TEXTAREA|BUTTON/.test(e.target.tagName))return;const k=e.key.toLowerCase();if(['w','a','s','d','q','e','arrowup','arrowdown','arrowleft','arrowright','shift'].includes(k)){e.preventDefault();keys.add(k);}});window.addEventListener('keyup',e=>keys.delete(e.key.toLowerCase()));window.addEventListener('blur',()=>{keys.clear();drag=null;});window … [line shortened here: 443 characters; full line on GitHub]
canvas.addEventListener('webglcontextlost',e=>{e.preventDefault();$('error').textContent='Graphics context lost. Reload this page to restore the scene.';});
window.electricalExplorer={setOrigin(value){if(!value||!Number.isFinite(value.latitude)||Math.abs(value.latitude)>90||!Number.isFinite(value.longitude)||Math.abs(value.longitude)>180)throw Error('Valid latitude and longitude required');origin={latitude:value.latitude,longitude:value.longitude,label:String(value.label??'Public location')};$('origin').textContent=`${origin.label} · ${origin.latitud … [line shortened here: 830 characters; full line on GitHub]
$('plantPreset').onclick=activatePlant;
const standardFocus=$('focusArray').onclick;
$('focusArray').onclick=()=>{if(!plantMode)return standardFocus();const n=Number($('arrayNumber').value);if(!Number.isInteger(n)||n<1||n>settings.tables){$('error').textContent='Choose representative array 1–'+settings.tables;return;}const [x,y]=plantTablePosition(n-1);changeMode('fly');eye=[x,y-8,settings.height+4];heading=0;lookPitch=-.15;canvas.focus();$('error').textContent='';};
Object.defineProperty(window.electricalExplorer,'plantInventory',{get:()=>plantMode?plantInventory():null});
try{init();}catch(err){$('error').textContent=err.message;}
// Full paired table: five portrait rows, three 30-module strings per row per face.
// Topology follows the existing public inverter-48 drawing; routes remain illustrative.
const connectorModels=[],connectorSelection={id:1};
const dcLayout={wiring:'sequential',depth:.6,ductDiameter:.09,moduleW:660},blockLayout={rowGap:8,aisleGap:10,ridgeGap:.5},tableOffsets=new Map(),inverterPosition=[0,-1,1];
function blockPosition(n){const depth=(settings.rows*(settings.moduleLength+.02)-.02)*Math.cos(settings.tilt*Math.PI/180),span=settings.columns*(settings.moduleWidth+.02)-.02,o=tableOffsets.get(n)||[0,0];return [(n%4)*(2*depth+blockLayout.ridgeGap+blockLayout.rowGap)+o[0],Math.floor(n/4)*(span+blockLayout.aisleGap)+o[1]];}
function blockStrings(){const s=settings,t=s.tilt*Math.PI/180,run=s.rows*(s.moduleLength+.02)-.02,depth=run*Math.cos(t),result=[];for(let n=0;n<s.tables;n++){const [x,y]=blockPosition(n);for(const side of [-1,1])for(let r=0;r<s.rows;r++)for(let group=0;group<Math.ceil(s.columns/30);group++){const modules=[];for(let c=group*30;c<Math.min(s.columns,(group+1)*30);c++){const v=(side===1?s.rows-1-r:r)* … [line shortened here: 969 characters; full line on GitHub]
function buildInverterBlock(){extent=145;center=[0,59,0];for(let x=-20;x<=30;x+=10)line([x,-15,0],[x,130,0],colors.grid);for(let y=-15;y<=130;y+=10)line([-20,y,0],[30,y,0],colors.grid);for(const string of blockStrings()){for(const m of string.modules)loop(m.corners,string.connected?colors.panel:colors.structure);const order=dcOrder(string.modules.length);for(let i=1;i<order.length;i++){const a=str … [line shortened here: 1,404 characters; full line on GitHub]
function dcOrder(n){if(dcLayout.wiring==='sequential')return Array.from({length:n},(_,i)=>i);const a=[];for(let i=0;i<n;i+=2)a.push(i);for(let i=n%2?n-2:n-1;i>=1;i-=2)a.push(i);return a;}
function ridgeHeight(){return settings.height+(settings.rows*(settings.moduleLength+.02)-.02)*Math.sin(settings.tilt*Math.PI/180);}
function dcDucts(){const destinations=stationMode?stationInverters:[inverterPosition];return destinations.flatMap((p,i)=>Array.from({length:4},(_,d)=>{const x=p[0]+(d-1.5)*.12;return {inverter:i+1,duct:d+1,points:[[x,p[1]-2,-dcLayout.depth],[x,p[1],-dcLayout.depth],[x,p[1],p[2]-.9]]};}));}
function drawPoleInverter(p){line([p[0],p[1]+.3,0],[p[0],p[1]+.3,p[2]],colors.structure);box(p[0]-.5,p[1]-.25,p[2]-1,1,.5,1,colors.selected);for(let port=0;port<48;port++){const x=p[0]-.44+(port%24)*.038,y=p[1]-.16+Math.floor(port/24)*.12;line([x,y,p[2]-1],[x,y,p[2]-1.04],colors.cable);}const selected=(stationMode?stationInverters:[inverterPosition])[connectorSelection.id-1];if(p===selected)for(le … [line shortened here: 579 characters; full line on GitHub]
function drawDuct(points,r){for(let i=1;i<points.length;i++){const a=points[i-1],b=points[i],axis=norm(sub(b,a)),u=norm(cross(axis,Math.abs(axis[2])>.9?[0,1,0]:[0,0,1])),v=cross(axis,u),rings=[a,b].map(p=>Array.from({length:8},(_,k)=>add(p,add(mul(u,r*Math.cos(k*Math.PI/4)),mul(v,r*Math.sin(k*Math.PI/4))))));rings.forEach(ring=>loop(ring,colors.structure));for(let k=0;k<8;k+=2)line(rings[0][k],rin … [line shortened here: 429 characters; full line on GitHub]
function updateBlockRoutes(){const destinations=stationMode?stationInverters:[inverterPosition];destinations.forEach(p=>p[2]=ridgeHeight());const counts=new Map();routes=validateRoutes(blockStrings().filter(s=>s.connected).flatMap((string,i)=>{const slot=counts.get(string.inverter)||0;counts.set(string.inverter,slot+1);if(slot>=24||string.modules.length>30)throw Error('Maximum24strings of30modules … [line shortened here: 1,389 characters; full line on GitHub]
function activateInverterBlock(){if(stationMode){dcInitialised=false;stationMode=false;tableOffsets.clear();}acMode=false;inverterMode=true;plantMode=false;if(!dcInitialised){settings={height:1.2,tilt:10,tables:1,columns:90,rows:5,moduleWidth:1.303,moduleLength:2.384};dcInitialised=true;}for(const[key,value]of Object.entries(settings)){const el=$('parameters').elements?.[key];if(el)el.value=value; … [line shortened here: 562 characters; full line on GitHub]
const originalBuild=build;
build=function(){originalBuild();if(inverterMode){const all=blockStrings(),connected=all.filter(s=>s.connected);$('summary').textContent=`${settings.tables} paired table(s) / ${(settings.rows*settings.columns*2*.660).toFixed(1)} kWp each | ${all.length} strings / ${all.reduce((n,s)=>n+s.modules.length,0)} modules drawn | ${connected.length} connected strings / ${connected.length*2} DC home cables … [line shortened here: 650 characters; full line on GitHub]
const originalSubmit=$('parameters').onsubmit;
$('parameters').onsubmit=e=>{originalSubmit(e);if(inverterMode&&!$('error').textContent){updateBlockRoutes();build();}};
const plantClick=$('plantPreset').onclick;$('plantPreset').onclick=()=>{stationMode=false;dcInitialised=false;acMode=false;inverterMode=false;plantClick();};
Object.assign(window.electricalExplorer,{startInverter:activateInverterBlock,setView(next){changeMode(next);if(inverterMode&&(next==='walk'||next==='fly')){eye=[-16,-4,next==='fly'?8:1.7];heading=0;lookPitch=next==='fly'?-.2:.05;}canvas.focus();},blueprint:fullBlueprint,project(point){const c=camera(),m=matrixMultiply(projection(canvas.clientWidth/canvas.clientHeight,mode==='top'),viewMatrix(c.pos … [line shortened here: 1,660 characters; full line on GitHub]
Object.assign(window.electricalExplorer,{setSpacing(gap){if(!Number.isFinite(gap)||gap<0||gap>100)throw Error('Row gap 0?100 m');blockLayout.rowGap=gap;updateBlockRoutes();build();},moveTable(id,dx,dy){if(!inverterMode||mode!=='top')return;const old=tableOffsets.get(id-1)||[0,0],scale=radius/canvas.clientHeight;tableOffsets.set(id-1,[old[0]+dx*scale,old[1]-dy*scale]);updateBlockRoutes();build();}, … [line shortened here: 443 characters; full line on GitHub]
window.electricalExplorer.placeTable=(px,py)=>{if(!inverterMode||mode!=='top')return;if(settings.tables>=100)throw Error('This prototype currently displays up to 100 complete tables.');const x=center[0]+(px-canvas.clientWidth/2)*radius/canvas.clientHeight,y=center[1]-(py-canvas.clientHeight/2)*radius/canvas.clientHeight,n=settings.tables,[ox,oy]=blockPosition(n);tableOffsets.set(n,[x-ox,y-oy]);set … [line shortened here: 499 characters; full line on GitHub]
window.electricalExplorer.moveInverter=(dx,dy,id=1)=>{if(!inverterMode||mode!=='top')return;const scale=radius/canvas.clientHeight;const position=stationMode?stationInverters[id-1]:inverterPosition;position[0]+=dx*scale;position[1]-=dy*scale;const keepCenter=[...center];updateBlockRoutes();build();center=keepCenter;};
const acLayout={depth:.9,formation:'trefoil',diameter:.0374,inverters:Array.from({length:28},(_,i)=>({id:i+1,section:Math.floor(i/14),point:[(i%7)*10,Math.floor(i/14)===0?Math.floor((i%14)/7)*15:85+Math.floor((i%14)/7)*15,1]})),transformers:[{id:1,point:[90,43,1.5]},{id:2,point:[90,57,1.5]}]};
function acPaths(){const z=-acLayout.depth+.05+acLayout.diameter/2,d=acLayout.diameter;return acLayout.inverters.flatMap(inv=>{const [x,y]=inv.point,[tx,ty]=acLayout.transformers[inv.section].point,collection=inv.section===0?30:70;return [0,1,2].map(phase=>{const offset=acLayout.formation==='flat'?(phase-1)*d:phase===0?-d/2:phase===1?d/2:0,pz=z+(acLayout.formation==='trefoil'&&phase===2?Math.sqrt( … [line shortened here: 735 characters; full line on GitHub]
function trench(a,b,width){const dx=b[0]-a[0],dy=b[1]-a[1],l=Math.hypot(dx,dy);if(l<1e-8)return;const ox=-dy/l*width/2,oy=dx/l*width/2;for(const z of [0,-acLayout.depth])loop([[a[0]+ox,a[1]+oy,z],[b[0]+ox,b[1]+oy,z],[b[0]-ox,b[1]-oy,z],[a[0]-ox,a[1]-oy,z]],colors.structure);for(const p of [a,b])for(const sign of [-1,1])line([p[0]+sign*ox,p[1]+sign*oy,0],[p[0]+sign*ox,p[1]+sign*oy,-acLayout.depth], … [line shortened here: 414 characters; full line on GitHub]
function buildACStation(){extent=130;center=[45,50,0];for(let x=-10;x<=110;x+=10)line([x,-10,0],[x,110,0],colors.grid);for(let y=-10;y<=110;y+=10)line([-10,y,0],[110,y,0],colors.grid);for(const inv of acLayout.inverters){const[x,y]=inv.point,cy=inv.section===0?30:70;box(x-1,y-.5,0,2,1,2,colors.panel);trench([x,y],[x,cy],.35);}for(let section=0;section<2;section++){const[tx,ty]=acLayout.transformer … [line shortened here: 597 characters; full line on GitHub]
function refreshAC(){routes=validateRoutes(acPaths());routeIndex=Math.min(routeIndex,routes.length-1);distance=0;populateRoutes();const keepCenter=[...center];build();center=keepCenter;$('summary').textContent=`One 10 MVA station | 2 x 5 MVA transformers | ${acLayout.inverters.length} x 352 kVA inverters | ${acLayout.inverters.length*3} x 400 mm2 AC phase cables | ${acLayout.formation} | trench de … [line shortened here: 645 characters; full line on GitHub]
function startAC(){if(stationMode)dcInitialised=false;stationMode=false;inverterMode=false;plantMode=false;acMode=true;refreshAC();radius=190;center=[45,50,0];yaw=-.6;pitch=.75;changeMode('orbit');document.querySelector('aside').hidden=true;$('show').hidden=false;canvas.focus();}
const defaultPickTargets=window.electricalExplorer.getPickTargets;
Object.assign(window.electricalExplorer,{startAC,getPickTargets(){return acMode?[...acLayout.inverters.map(n=>({kind:'ac-inverter',id:n.id,point:[...n.point]})),...acLayout.transformers.map(n=>({kind:'transformer',id:n.id,point:[...n.point]}))]:defaultPickTargets();},setTrench(depth,formation){if(!Number.isFinite(depth)||depth<.2||depth>5||!['flat','trefoil'].includes(formation))throw Error('Depth … [line shortened here: 1,044 characters; full line on GitHub]
Object.assign(window.electricalExplorer,{getRidgeGap(){return blockLayout.ridgeGap;},setRidgeGap(gap){if(!Number.isFinite(gap)||gap<0||gap>20)throw Error('Ridge gap must be between 0 and20m');blockLayout.ridgeGap=gap;updateBlockRoutes();build();}});
Object.assign(window.electricalExplorer,{acSection(id){return acLayout.inverters.find(n=>n.id===id)?.section??0;},acSectionCount(section){return acLayout.inverters.filter(n=>n.section===section).length;},setACSectionCount(section,count){if(![0,1].includes(section)||!Number.isInteger(count)||count<1||count>100)throw Error('1 to100 inverters per section in this prototype');let current=acLayout.inver … [line shortened here: 828 characters; full line on GitHub]
// Generic complete station: 28 x 24 strings; surplus table strings remain unassigned.
function stationACPaths(){return stationInverters.flatMap((p,i)=>[0,1,2].map(phase=>{const t=stationTransformers[Math.floor(i/14)],o=acLayout.formation==='flat'?(phase-1)*.0374:phase===0?-.0187:phase===1?.0187:0,z=-acLayout.depth+.05+.0374/2+(acLayout.formation==='trefoil'&&phase===2?Math.sqrt(3)*.0374/2:0);return {id:`ST-INV-${i+1}-L${phase+1}`,label:`Inverter ${i+1} to transformer ${Math.floor(i … [line shortened here: 612 characters; full line on GitHub]
function startStation(){stationMode=true;inverterMode=true;acMode=false;plantMode=false;dcInitialised=true;tableOffsets.clear();settings={height:1.2,tilt:10,tables:23,columns:90,rows:5,moduleWidth:1.303,moduleLength:2.384};stationInverters.length=0;for(let i=0;i<28;i++){const table=Math.floor(i*24/30),[x,y]=blockPosition(table);stationInverters.push([x+(i*24%30===24?1.2:0),y-1,ridgeHeight()]);}for … [line shortened here: 671 characters; full line on GitHub]
Object.assign(window.electricalExplorer,{startStation,stationInventory(){if(!stationMode)return null;const strings=blockStrings(),connected=strings.filter(s=>s.connected);return {tables:settings.tables,installedModules:strings.reduce((n,s)=>n+s.modules.length,0),connectedModules:connected.reduce((n,s)=>n+s.modules.length,0),connectedStrings:connected.length,spareStrings:strings.length-connected.le … [line shortened here: 644 characters; full line on GitHub]
window.electricalExplorer.zoom=factor=>{if(!Number.isFinite(factor)||factor<=0)return;if(mode==='walk'||mode==='fly'){const step=(1-factor)*12;eye=add(eye,mul([Math.sin(heading)*Math.cos(lookPitch),Math.cos(heading)*Math.cos(lookPitch),mode==='fly'?Math.sin(lookPitch):0],step));}else radius=clamp(radius*factor,2,10000);dirty=true;};
Object.assign(window.electricalExplorer,{setDCWiring(value){if(!['sequential','leapfrog'].includes(value))throw Error('Choose sequential or leapfrog');dcLayout.wiring=value;if(inverterMode){updateBlockRoutes();build();}},dcWiring(){const all=blockStrings(),connected=all.filter(s=>s.connected),count=stationMode?28:1;return {wiring:dcLayout.wiring,depth:dcLayout.depth,ductDiameter:dcLayout.ductDiame … [line shortened here: 924 characters; full line on GitHub]
Object.assign(window.electricalExplorer,{loadConnectorGeometry(models){if(!Array.isArray(models)||models.length<1||models.length>2)throw Error('Load one or two local connector geometries');for(const m of models){if(m.schema!=='local-connector-lines/1'||m.units!=='m'||!Array.isArray(m.lines)||m.lines.length>15000||m.lines.some(l=>!Array.isArray(l)||l.length!==2||l.some(p=>!Array.isArray(p)||p.lengt … [line shortened here: 1,074 characters; full line on GitHub]Graphics Engines Open Source — Index Page
A web page that reads inputs for mode, route and array, covering cables, substations and transformers. Published at https://ventusltd.github.io/graphics-engines-open-source/web/.
rendergraphics-engines-open-source / web/index.html · lines 1–14 of 14 · Entry point
- What it does
- It draws cables, substations and transformers. Uses libraries explore.css, explore-direct.mjs. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- Domain terms in the code: cables, substations, transformers.
- Inputs & outputs
- In: user-supplied file (file picker); form fields (user input). Out: web page.
- Downstream impact
- Used directly by 1 file: Graphics Engines Open Source — Versions Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/versions/). It is itself an entry point, published at https://ventusltd.github.io/graphics-engines-open-source/web/.
- What it achieves
- Electrical scene explorer. Its code works with 100 MW and 5 MVA.
- Why it matters
- Loaded by the Versions page at https://ventusltd.github.io/graphics-engines-open-source/web/versions/.
- Application
- graphics-engines-open-source · web · page
- Uses
- Explore (script src), Atlas Picker (script src), Substation Picker (script src), Route Files UI (script src), explore.css, explore-direct.mjs
- Used by
- linked from Graphics Engines Open Source — Versions Page (link)
- 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
- graphics-engines-open-source@79e0bd8ee33844835e553fc84d552b6aa1521152 web/index.html:1-14 · blob 0f034e27a250717b6c0638eb05cdb99a3cfeae9d · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Electrical scene explorer</title><link rel="stylesheet" href="explore.css"></head>
<body><canvas id="scene" tabindex="0" aria-label="Interactive metric electrical scene"></canvas>
<aside><h1>Electrical scene explorer</h1><p><a href="https://globalgrid2050.com/ventus/wiring/inverter-48.html" style="color:#9cdbff">Complete DC wiring</a></p><p class="muted">Illustrative geometry · metres · no survey or engineering approval</p><section id="atlas-picker"></section><section id="substation-picker"></section>
<label>View <select id="mode"><option value="orbit">Orbit</option><option value="top">Top down</option><option value="walk">First person</option><option value="fly">Free flight</option><option value="cable">Walk cable</option></select></label>
<div class="pair"><button id="fit">Reset view</button><button id="hide">Hide controls</button></div>
<button id="plantPreset">100 MWp / 10-station overview</button><p class="muted">Generic assumption preset: 10 blocks, 2 × 5 MVA transformers per station; 660 W, five portrait rows per east/west face. Allocation is separate from the representative tables shown. 100 MWp DC does not specify 100 MW AC output. Block footprints and collection routes are illustrative, not surveyed.</p>
<details><summary>Cable route files</summary><label>Import JSON <input id="route-file" type="file" accept=".json,application/json"></label><button id="export-routes">Export cable routes</button><p class="muted">Local files only. Import replaces the cable routes; panels and origin stay as shown. Coordinates: metres, east/north/up. Export the demo for a reusable template.</p><p id="route-file-status … [line shortened here: 430 characters; full line on GitHub]
<button id="blueprint">Full-site blueprint</button><label>Array number <input id="arrayNumber" type="number" min="1" max="12" value="1"></label><button id="focusArray">Focus / fly to array</button>
<form id="parameters"><label>Lower edge (m)<input name="height" type="number" min="0.1" max="20" step="0.1" value="1.5"></label><label>Tilt (°)<input name="tilt" type="number" min="0" max="60" step="1" value="20"></label><label>Arrays<input name="tables" type="number" min="1" max="100" step="1" value="12"></label><label>Columns / array<input name="columns" type="number" min="1" max="300" step="1" … [line shortened here: 649 characters; full line on GitHub]
<label>Panel width (m)<input form="parameters" name="moduleWidth" type="number" min="0.1" max="4" step="0.001" value="1.2"></label><label>Panel length (m)<input form="parameters" name="moduleLength" type="number" min="0.1" max="4" step="0.001" value="2.4"></label>
<h2>Walk every modelled cable</h2><label>Cable <select id="route"></select></label><p id="routeInfo"></p><label>Distance along cable <input id="distance" type="range" min="0" max="1" step="0.05" value="0"></label><output id="distanceInfo"></output><div class="pair"><button id="start">Start endpoint</button><button id="end">End endpoint</button></div><label>Travel speed (m/s)<input id="speed" type= … [line shortened here: 728 characters; full line on GitHub]
<p class="muted">Scale objects: person 1.75 m tall; vehicle 4.5 × 1.8 × 1.6 m; drum Ø1.2 × 1 m. Inverter and transformer are generic boxes.</p><p id="origin">Local demo origin · X east, Y north, Z up</p><p id="error" role="alert"></p></aside>
<button id="show" hidden>Controls</button><footer><span id="summary"></span><br><span id="help">Drag to orbit · wheel to zoom · right-drag to pan</span></footer><script type="module" src="explore.mjs"></script><script type="module" src="atlas-picker.mjs"></script><script type="module" src="substation-picker.mjs"></script><script type="module" src="route-files-ui.mjs"></script><script type="module" … [line shortened here: 449 characters; full line on GitHub]