GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Solar and storage design / globalgrid2050 / solar-design-studio/202609270005-site-world-v3/world

Print and 4 more files

A JavaScript module in the world folder of GlobalGrid2050 that downloads SVG (`downloadSvg`) and png (`downloadPng`), opens sheet (`openSheet`) and draws on a canvas.

583 lines of JavaScript from globalgrid2050, in 5 files. Topic: Solar and storage design. Section 125 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Print SVG transform · globalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/print-svg.mjs lines 1–146
  2. Print render · globalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/print.mjs lines 1–155
  3. Road Lines transform · globalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/road-lines.mjs lines 1–136
  4. Search ingest · globalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/search.mjs lines 1–96
  5. Sun UI render · globalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/sun-ui.mjs lines 1–50

Print SVG

A JavaScript module in the world folder of GlobalGrid2050 that clips segment (`clipSegment`), converts to paper (`toPaper`), scales bar SVG (`scaleBarSvg`) and calculates planar distances.

transformglobalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/print-svg.mjs · lines 1–146 of 146 · version 2026-09-27 00:05 · Not reached from any entry point (candidate for review)

What it does
It calculates its inputs. Defines 14 functions or classes, including esc, f, inkFor, clipSegment, planPaths.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
Downstream impact
Used directly by 2 files: Print Sheet (globalgrid2050); Print Sheet (globalgrid2050).
What it achieves
It is built from the esc step (`esc`), the ink for helper (`inkFor`) and the clip segment helper (`clipSegment`). Print sheet drawing: builds the sheet as one SVG string, in millimetres.
Why it matters
Imported by Print Sheet.
Application
globalgrid2050 · solar-design-studio/202609270005-site-world-v3/world · JavaScript module
Uses
Camera (import), Print Layout (import)
Used by
imported by Print Sheet (import), imported by Print Sheet (import), mentioned in Standalone (comment link)
Produces
FONT, INK, esc, inkFor, clipSegment, planPaths, viewPaths, northArrow, scaleBarSvg, gridSvg
Defines here
esc, f, inkFor, clipSegment, planPaths, viewPaths, clip, toPaper, text, box, path, northArrow, scaleBarSvg, gridSvg
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609270005-site-world-v3/world/print-svg.mjs:1-146 · blob 5cb4cabdd97b094eda5d5331b76086142510c6b9 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
// Print sheet drawing: builds the sheet as one SVG string, in millimetres. Pure: no DOM, no WebGL,
// so the same call gives the same sheet in a test, a worker or the page.
// The plan is drawn from the very line batches the world draws, looked at straight down.
// The current view is either the captured frame (an image) or, if none is given, the same batches
// put through the same camera maths as the screen, drawn as vectors without terrain occlusion.

import { perspective, view, multiply } from './camera.mjs';
import { planFrame, planToPaper, scaleBar, gridTicks, refAt, trueNorthOffset, bearingText } from './print-layout.mjs';

export const FONT = "ui-monospace, 'SFMono-Regular', Menlo, Consolas, monospace";
export const INK = '#111', MUTED = '#555', RULE = '#999';

export const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
const f = v => (Math.round(v * 100) / 100).toString();

// Screen colours are light on black; paper is white. Keep the hue, darken it, and give faint lines
// a floor so they still print. Returns { stroke, opacity }.
export function inkFor(color) {
  const [r, g, b, a = 1] = color || [0.6, 0.6, 0.6, 1];
  const k = 0.55, hex = v => Math.round(Math.max(0, Math.min(1, v * k)) * 255).toString(16).padStart(2, '0');
  return { stroke: `#${hex(r)}${hex(g)}${hex(b)}`, opacity: Math.max(0.3, Math.min(1, a)) };
}

// Clips segment (x0,y0)-(x1,y1) to rectangle r (Liang-Barsky). Returns the clipped four numbers or null.
export function clipSegment(x0, y0, x1, y1, r) {
  let t0 = 0, t1 = 1;
  const dx = x1 - x0, dy = y1 - y0;
  for (const [p, q] of [[-dx, x0 - r.x], [dx, r.x + r.w - x0], [-dy, y0 - r.y], [dy, r.y + r.h - y0]]) {
    if (p === 0) { if (q < 0) return null; continue; }
    const t = q / p;
    if (p < 0) { if (t > t1) return null; if (t > t0) t0 = t; } else { if (t < t0) return null; if (t < t1) t1 = t; }
  }
  return [x0 + t0 * dx, y0 + t0 * dy, x0 + t1 * dx, y0 + t1 * dy];
}

// The plan: every line batch straight down, clipped to the drawing area. One path per batch.
export function planPaths(batches, frame, layout) {
  const out = [], d = layout.planDraw;
  for (const b of batches) {
    if (b.occluder || !b.positions) continue;
    const o = b.origin || [0, 0, 0], p = b.positions;
    let dstr = '';
    for (let i = 0; i + 5 < p.length; i += 6) {
      const [ax, ay] = planToPaper(frame, layout, p[i] + o[0], p[i + 1] + o[1]);
      const [bx, by] = planToPaper(frame, layout, p[i + 3] + o[0], p[i + 4] + o[1]);
      const c = clipSegment(ax, ay, bx, by, d);
      if (c) dstr += `M${f(c[0])} ${f(c[1])}L${f(c[2])} ${f(c[3])}`;
    }
    if (dstr) { const ink = inkFor(b.color); out.push({ key: b.key, d: dstr, ...ink }); }
  }
  return out;
}

// The current view as vectors: the screen's own camera (camera.mjs), each batch moved by its origin
// minus the eye, as lines.mjs does. Segments behind the near plane are cut there; distant lines fade
// in four bands as the shader fades them. Returns paths in the panel's box `r`.
export function viewPaths(batches, cam, r, { fade = 450, near = 0.05, far = 5000 } = {}) {
  const fov = cam.fov ?? 70 * Math.PI / 180;
  const m = multiply(perspective(fov, r.w / r.h, near, far), view([0, 0, 0], cam.yaw, cam.pitch));
  const eye = cam.pos, out = [];
  const clip = (x, y, z) => [m[0] * x + m[4] * y + m[8] * z + m[12], m[1] * x + m[5] * y + m[9] * z + m[13], m[3] * x + m[7] * y + m[11] * z + m[15]];
  const toPaper = ([cx, cy, w]) => [r.x + (cx / w + 1) / 2 * r.w, r.y + (1 - cy / w) / 2 * r.h];
  for (const b of batches) {
    if (b.occluder || !b.positions) continue;
    const o = b.origin || [0, 0, 0], p = b.positions, bands = ['', '', '', ''];
    const off = [o[0] - eye[0], o[1] - eye[1], o[2] - eye[2]];
    for (let i = 0; i + 5 < p.length; i += 6) {
      const a = [p[i] + off[0], p[i + 1] + off[1], p[i + 2] + off[2]];
      const c = [p[i + 3] + off[0], p[i + 4] + off[1], p[i + 5] + off[2]];
      const dist = Math.hypot((a[0] + c[0]) / 2, (a[1] + c[1]) / 2, (a[2] + c[2]) / 2);
      const alpha = 1 - dist / fade;
      if (alpha <= 0) continue;
      let pa = clip(...a), pc = clip(...c);
      if (pa[2] < near && pc[2] < near) continue;
      if (pa[2] < near || pc[2] < near) { // cut at the near plane
        const t = (near - pa[2]) / (pc[2] - pa[2]), cut = pa.map((v, k) => v + (pc[k] - v) * t);
        if (pa[2] < near) pa = cut; else pc = cut;
      }
      const [ax, ay] = toPaper(pa), [cx, cy] = toPaper(pc);
      const s = clipSegment(ax, ay, cx, cy, r);
      if (s) bands[Math.min(3, Math.floor((1 - alpha) * 4))] += `M${f(s[0])} ${f(s[1])}L${f(s[2])} ${f(s[3])}`;
    }
    const ink = inkFor(b.color);
    bands.forEach((d, k) => { if (d) out.push({ key: `${b.key}#${k}`, d, stroke: ink.stroke, opacity: Math.max(0.2, ink.opacity * (1 - k / 4)) }); });
  }
  return out;
}

const text = (x, y, s, size, extra = '') => `<text x="${f(x)}" y="${f(y)}" font-size="${f(size)}"${extra}>${esc(s)}</text>`;
const box = (r, extra = '') => `<rect x="${f(r.x)}" y="${f(r.y)}" width="${f(r.w)}" height="${f(r.h)}"${extra}/>`;
const path = (p, w) => `<path d="${p.d}" stroke="${p.stroke}" stroke-opacity="${f(p.opacity)}" stroke-width="${w}" fill="none"/>`;

// North arrow at (x, y), `size` mm tall, pointing up the sheet (grid north). tn: true north offset in degrees.
export function northArrow(x, y, size, tn) {
  const h = size, w = size * 0.42;
  const parts = [
    `<g transform="translate(${f(x)} ${f(y)})" stroke="${INK}" stroke-width="0.25">`,
    `<path d="M0 ${f(-h / 2)}L${f(w / 2)} ${f(h / 2)}L0 ${f(h / 4)}Z" fill="${INK}"/>`,
    `<path d="M0 ${f(-h / 2)}L${f(-w / 2)} ${f(h / 2)}L0 ${f(h / 4)}Z" fill="#fff"/>`,
    text(0, -h / 2 - 1.2, 'N', 3.2, ` text-anchor="middle" stroke="none" fill="${INK}" font-weight="700"`),
    text(0, h / 2 + 3, 'GRID', 1.8, ` text-anchor="middle" stroke="none" fill="${MUTED}" letter-spacing="0.3"`),
    '</g>'];
  if (tn !== null && tn !== undefined) {
    const say = Math.abs(tn) < 0.005 ? 'TN = GN' : `TN ${Math.abs(tn).toFixed(2)}° ${tn >= 0 ? 'E' : 'W'}`;
    parts.splice(parts.length - 1, 0, text(0, h / 2 + 5.4, say, 1.8, ` text-anchor="middle" stroke="none" fill="${MUTED}"`));
  }
  return parts.join('');
}

// Alternating black and white scale bar, left end at (x, y).
export function scaleBarSvg(bar, x, y, scale) {
  const h = 1.6, out = [`<g font-family="${FONT}" fill="${INK}">`];
  for (let i = 0; i < 4; i++) {
    const a = bar.ticks[i].mm, b = bar.ticks[i + 1].mm;
    out.push(`<rect x="${f(x + a)}" y="${f(y)}" width="${f(b - a)}" height="${h}" fill="${i % 2 ? '#fff' : INK}" stroke="${INK}" stroke-width="0.2"/>`);
  }
  for (const t of [bar.ticks[0], bar.ticks[2], bar.ticks[4]]) {
    const label = t === bar.ticks[4] ? bar.label : String(bar.m >= 1000 ? t.m / 1000 : t.m);
    out.push(text(x + t.mm, y - 0.9, label, 2, ' text-anchor="middle"'));
  }
  out.push(text(x, y + h + 2.8, `Scale 1:${scale.toLocaleString('en-GB')}`, 2, ` fill="${MUTED}"`), '</g>');
  return out.join('');
}

// Grid tick marks and their figures on the plan's border band; the 100 km square letters in the corner.
export function gridSvg(ticks, layout) {
  const d = layout.planDraw, p = layout.plan, out = [`<g font-family="${FONT}" fill="${MUTED}" font-size="1.9">`];
  out.push(`<g stroke="${RULE}" stroke-width="0.12" stroke-dasharray="0.6 1.2">`);
  for (const t of ticks.eastings) out.push(`<path d="M${f(t.x)} ${f(d.y)}V${f(d.y + d.h)}"/>`);
  for (const t of ticks.northings) out.push(`<path d="M${f(d.x)} ${f(t.y)}H${f(d.x + d.w)}"/>`);
  out.push('</g>');
  for (const t of ticks.eastings) {
    out.push(`<path d="M${f(t.x)} ${f(p.y)}V${f(d.y)}M${f(t.x)} ${f(d.y + d.h)}V${f(p.y + p.h)}" stroke="${INK}" stroke-width="0.2"/>`);
    out.push(text(t.x + 0.6, p.y + layout.band - 1.6, t.label, 1.9), text(t.x + 0.6, p.y + p.h - 1.4, t.label, 1.9));
  }
  for (const t of ticks.northings) {
    out.push(`<path d="M${f(p.x)} ${f(t.y)}H${f(d.x)}M${f(d.x + d.w)} ${f(t.y)}H${f(p.x + p.w)}" stroke="${INK}" stroke-width="0.2"/>`);
    out.push(text(p.x + 1, t.y - 0.6, t.label, 1.9), text(p.x + p.w - 1, t.y - 0.6, t.label, 1.9, ' text-anchor="end"'));
  }
  const sq = (ticks.squares || [...new Set([...ticks.eastings, ...ticks.northings].map(t => t.square))]).join('/');
  if (sq) out.push(text(p.x + 1, p.y + layout.band - 1.6, sq, 2.2, ` fill="${INK}" font-weight="700"`));
  out.push('</g>');
  return out.join('');
}

export { planFrame, scaleBar, gridTicks, refAt, trueNorthOffset, bearingText };

Print

A JavaScript module in the world folder of GlobalGrid2050 that downloads SVG (`downloadSvg`) and png (`downloadPng`), opens sheet (`openSheet`) and draws on a canvas.

renderglobalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/print.mjs · lines 1–155 of 155 · version 2026-09-27 00:05 · Not reached from any entry point (candidate for review) · pattern openSheet (shared by 6 files)

What it does
It draws its content. Defines 15 functions or classes, including captureView, sheetFileName, p, save, downloadSvg. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
Out: canvas drawing.
Downstream impact
Used directly by 2 files: Project UI (globalgrid2050); Project UI (globalgrid2050).
What it achieves
It downloads SVG (`downloadSvg`), downloads png (`downloadPng`) and opens sheet (`openSheet`). A sheet of the world on A3 or A4 landscape, as SVG, PNG or through the browser's own print. It responds to afterprint, click and keydown events.
Why it matters
Imported by Project UI.
Application
globalgrid2050 · solar-design-studio/202609270005-site-world-v3/world · JavaScript module
Uses
Print Sheet (import), Print Layout (import)
Used by
imported by Project UI (import), imported by Project UI (import), mentioned in Standalone (comment link)
Produces
captureView, sheetFileName, downloadSvg, sheetPng, downloadPng, printCss, printSheet, openSheet
Defines here
captureView, sheetFileName, p, save, downloadSvg, sheetPng, downloadPng, printCss, printSheet, clean, openSheet, button, show, close, onKey
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609270005-site-world-v3/world/print.mjs:1-155 · blob 07b8f3d15ae8a1fc0f9f1004424525b7818ac9c4 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
// Print: a sheet of the world on A3 or A4 landscape, as SVG, PNG or through the browser's own print.
// The sheet itself is built by print-sheet.mjs (pure); this file only touches the page.
//
// The current view is taken from the WebGL canvas INSIDE the frame that drew it: the world's context is
// made without preserveDrawingBuffer, so a read at any other time gives a blank, perfectly valid PNG
// (the lesson GridAtlas's print learnt the hard way). captureView therefore redraws and copies in one
// go, checks the copy is not blank, and returns null rather than a blank picture; the sheet then
// redraws the view as vectors from the same lines and says so on the sheet.

import { buildSheet, sheetDate } from './print-sheet.mjs';
import { PAPER } from './print-layout.mjs';

export { buildSheet, sheetDate, PAPER };

const SHEET_ID = 'world-print-sheet', STYLE_ID = 'world-print-css', PREVIEW_ID = 'world-print-preview';

// Redraws (if given a redraw function) and copies the canvas in the same task. Returns
// { href, width, height } or null when the copy is blank (every pixel pure black or transparent).
export function captureView(canvas, redraw) {
  if (typeof redraw === 'function') redraw();
  const w = canvas.width, h = canvas.height;
  if (!w || !h) return null;
  const copy = document.createElement('canvas');
  copy.width = w; copy.height = h;
  const g = copy.getContext('2d', { willReadFrequently: true });
  g.drawImage(canvas, 0, 0);
  const probe = document.createElement('canvas');
  probe.width = 64; probe.height = 64;
  const pg = probe.getContext('2d', { willReadFrequently: true });
  pg.drawImage(copy, 0, 0, 64, 64);
  const px = pg.getImageData(0, 0, 64, 64).data;
  let lit = false;
  for (let i = 0; i < px.length && !lit; i += 4) lit = px[i] + px[i + 1] + px[i + 2] > 0 && px[i + 3] > 0;
  return lit ? { href: copy.toDataURL('image/png'), width: w, height: h } : null;
}

// A file name that sorts by time and carries the paper: site-world-a3-20260926-2215.svg
export function sheetFileName(paper, ext, date = new Date()) {
  const p = n => String(n).padStart(2, '0');
  const stamp = `${date.getFullYear()}${p(date.getMonth() + 1)}${p(date.getDate())}-${p(date.getHours())}${p(date.getMinutes())}`;
  return `site-world-${String(paper).toLowerCase()}-${stamp}.${ext}`;
}

function save(blob, name) {
  const url = URL.createObjectURL(blob), a = document.createElement('a');
  a.href = url; a.download = name; a.rel = 'noopener';
  document.body.appendChild(a); a.click();
  // Revoking at once races the browser's own read of the blob on some builds.
  setTimeout(() => { URL.revokeObjectURL(url); a.remove(); }, 30000);
}

export function downloadSvg(svg, name) {
  save(new Blob([svg], { type: 'image/svg+xml' }), name);
}

// Rasterises the sheet at `dpi` (150 by default: A3 is then 2480 x 1754 px) and resolves to a PNG blob.
export async function sheetPng(svg, paper = 'A3', dpi = 150) {
  const P = PAPER[paper], pxPerMM = dpi / 25.4;
  const w = Math.round(P.w * pxPerMM), h = Math.round(P.h * pxPerMM);
  const url = URL.createObjectURL(new Blob([svg], { type: 'image/svg+xml' }));
  try {
    const img = new Image();
    await new Promise((ok, fail) => { img.onload = ok; img.onerror = () => fail(Error('the sheet could not be drawn as an image')); img.src = url; });
    const c = document.createElement('canvas');
    c.width = w; c.height = h;
    const g = c.getContext('2d');
    g.fillStyle = '#fff'; g.fillRect(0, 0, w, h);
    g.drawImage(img, 0, 0, w, h);
    return await new Promise((ok, fail) => c.toBlob(b => (b ? ok(b) : fail(Error('the browser gave no PNG'))), 'image/png'));
  } finally { URL.revokeObjectURL(url); }
}

export async function downloadPng(svg, paper, name, dpi) {
  save(await sheetPng(svg, paper, dpi), name);
}

// The print stylesheet: on paper only the sheet shows, at its true size, on a page of its own size.
export function printCss(paper = 'A3') {
  const P = PAPER[paper];
  return `#${SHEET_ID}{display:none}
@media print{
  @page{size:${P.name} landscape;margin:0}
  html,body{background:#fff!important;height:auto!important;overflow:visible!important;margin:0!important;padding:0!important}
  body>*:not(#${SHEET_ID}){display:none!important}
  #${SHEET_ID}{display:block!important;width:${P.w}mm;height:${P.h}mm;overflow:hidden;break-inside:avoid;page-break-after:avoid}
  #${SHEET_ID} svg{display:block;width:${P.w}mm;height:${P.h}mm}
}`;
}

// Sends the sheet to the browser's print dialogue, then tidies up. afterprint is not fired by every
// browser, notably some mobile ones, so the sheet is also removed on a timer; it is hidden on screen anyway.
export function printSheet(svg, paper = 'A3') {
  document.getElementById(SHEET_ID)?.remove();
  document.getElementById(STYLE_ID)?.remove();
  const style = document.createElement('style');
  style.id = STYLE_ID; style.textContent = printCss(paper);
  const host = document.createElement('div');
  host.id = SHEET_ID; host.innerHTML = svg;
  document.head.appendChild(style); document.body.appendChild(host);
  let done = false;
  const clean = () => { if (done) return; done = true; host.remove(); style.remove(); removeEventListener('afterprint', clean); };
  addEventListener('afterprint', clean);
  // A frame for the stylesheet to apply before the dialogue measures the page.
  setTimeout(() => window.print(), 60);
  setTimeout(clean, 20000);
  return clean;
}

// A preview over the world with Print, Save SVG, Save PNG, a paper choice and Close.
// make(paper) must return buildSheet's result for that paper; it is called again when the paper changes.
// Returns { close, sheet() } so a caller or a test can read what is shown.
export function openSheet(make, { paper = 'A3' } = {}) {
  document.getElementById(PREVIEW_ID)?.remove();
  const root = document.createElement('div');
  root.id = PREVIEW_ID;
  root.setAttribute('role', 'dialog'); root.setAttribute('aria-label', 'Print sheet');
  root.style.cssText = 'position:fixed;inset:0;z-index:50;background:rgba(10,10,10,.94);display:flex;flex-direction:column;'
    + 'font:12px/1.4 ui-monospace,Menlo,Consolas,monospace;color:#cfe9ff';
  const bar = document.createElement('div');
  bar.style.cssText = 'display:flex;flex-wrap:wrap;gap:6px;align-items:center;padding:8px 10px;border-bottom:1px solid #1c2c3a';
  const stage = document.createElement('div');
  stage.style.cssText = 'flex:1;min-height:0;display:flex;align-items:center;justify-content:center;padding:10px;overflow:auto';
  const note = document.createElement('span');
  note.style.cssText = 'color:#6f8ea6;margin-left:auto;overflow-wrap:anywhere';
  let current = null;
  const button = (label, fn, extra = {}) => {
    const b = document.createElement('button');
    b.type = 'button'; b.textContent = label;
    b.style.cssText = 'min-height:44px;padding:0 12px;background:#0a0a0a;color:#cfe9ff;border:1px solid #1c2c3a;border-radius:4px;font:inherit;cursor:pointer';
    Object.entries(extra).forEach(([k, v]) => b.setAttribute(k, v));
    b.addEventListener('click', fn); bar.appendChild(b); return b;
  };
  const papers = Object.keys(PAPER).map(p => button(p, () => show(p), { 'data-paper': p, 'aria-pressed': 'false' }));
  function show(p) {
    paper = p; current = make(p);
    stage.innerHTML = current.svg;
    const svg = stage.querySelector('svg');
    svg.removeAttribute('width'); svg.removeAttribute('height');
    svg.style.cssText = `max-width:100%;max-height:100%;width:100%;height:auto;aspect-ratio:${PAPER[p].w}/${PAPER[p].h};background:#fff;box-shadow:0 0 0 1px #1c2c3a`;
    for (const b of papers) b.setAttribute('aria-pressed', String(b.dataset.paper === p));
    note.textContent = `${p} landscape · 1:${current.meta.scale.toLocaleString('en-GB')} · view: ${current.meta.view === 'image' ? 'captured frame' : 'vector redraw'}`;
  }
  button('Print', () => printSheet(current.svg, paper), { 'data-print': 'print' });
  button('Save SVG', () => downloadSvg(current.svg, sheetFileName(paper, 'svg')), { 'data-print': 'svg' });
  button('Save PNG', () => downloadPng(current.svg, paper, sheetFileName(paper, 'png')), { 'data-print': 'png' });
  const close = () => { root.remove(); removeEventListener('keydown', onKey); };
  const onKey = e => { if (e.key === 'Escape') close(); };
  button('Close', close, { 'data-print': 'close' });
  bar.appendChild(note);
  root.append(bar, stage);
  document.body.appendChild(root);
  addEventListener('keydown', onKey);
  show(paper);
  return { close, sheet: () => current };
}

Road Lines

A JavaScript module in the world folder of GlobalGrid2050 that works with offset line (`offsetLine`) and edge lines (`edgeLines`) and calculates planar distances.

transformglobalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/road-lines.mjs · lines 1–136 of 136 · version 2026-09-27 00:05 · Not reached from any entry point (candidate for review) · pattern sectionLines (shared by 3 files)

What it does
It calculates its inputs. Defines 11 functions or classes, including frame, offsetLine, densify, finishedAtPoint, edgeLines.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Downstream impact
Used directly by 2 files: Design Earthworks (globalgrid2050); Design Earthworks (globalgrid2050).
What it achieves
It is built from the frame step (`frame`), the offset line helper (`offsetLine`) and the densify step (`densify`). Lines for drawing a road made by `createRoad` (`road.mjs`).
Why it matters
Imported by Design Earthworks.
Application
globalgrid2050 · solar-design-studio/202609270005-site-world-v3/world · JavaScript module
Uses
none found
Used by
imported by Design Earthworks (import), imported by Design Earthworks (import), mentioned in Standalone (comment link)
Produces
STEEP_NOTE, DRAIN_NOTE, offsetLine, edgeLines, batterLines, sectionLines
Defines here
frame, offsetLine, densify, finishedAtPoint, edgeLines, run, daylight, raw, batterLines, sectionLines, at
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609270005-site-world-v3/world/road-lines.mjs:1-136 · blob 99a27af04e6422518bd84445f454a070d994a513 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
// road-lines.mjs: lines for drawing a road made by createRoad (road.mjs). No imports, no DOM.
//
// Every function takes the road object and returns a Float32Array of line pairs (x, y, z, x, y, z) in
// local metres, ready for a line batch. Edge offset lines are mitred on the inside of a bend and follow
// an arc round the outside, matching the road's nearest-point rule (the outside of a bend is rounded).

export const STEEP_NOTE = 'grade over the limit (10 % assumed unless set)';
export const DRAIN_NOTE = 'edge in cut: needs a side drain';

function frame(road) {
  const pts = road.path, segs = [];
  for (let i = 0; i < pts.length - 1; i++) {
    const [ax, ay] = pts[i], [bx, by] = pts[i + 1], len = Math.hypot(bx - ax, by - ay);
    segs.push({ dx: (bx - ax) / len, dy: (by - ay) / len, nx: -(by - ay) / len, ny: (bx - ax) / len });
  }
  return { pts, segs };
}

// Offset line at signed distance h (positive to the left of the direction of travel).
export function offsetLine(road, h) {
  const { pts, segs } = frame(road);
  const out = [[pts[0][0] + segs[0].nx * h, pts[0][1] + segs[0].ny * h]];
  for (let k = 1; k < pts.length - 1; k++) {
    const a = segs[k - 1], b = segs[k], turn = a.dx * b.dy - a.dy * b.dx; // > 0 turns left
    const [vx, vy] = pts[k];
    if (turn * h > 0 || Math.abs(turn) < 1e-9) {                        // inside (or straight): mitre
      const c = 1 + a.nx * b.nx + a.ny * b.ny;
      out.push([vx + (a.nx + b.nx) / c * h, vy + (a.ny + b.ny) / c * h]);
    } else {                                                            // outside: arc
      const a0 = Math.atan2(a.ny, a.nx);
      let da = Math.atan2(b.ny, b.nx) - a0;
      if (da > Math.PI) da -= 2 * Math.PI;
      if (da < -Math.PI) da += 2 * Math.PI;
      const m = Math.max(2, Math.ceil(Math.abs(da) / 0.2));
      for (let q = 0; q <= m; q++) { const t = a0 + da * q / m; out.push([vx + Math.cos(t) * h, vy + Math.sin(t) * h]); }
    }
  }
  const e = segs[segs.length - 1], last = pts[pts.length - 1];
  out.push([last[0] + e.nx * h, last[1] + e.ny * h]);
  return out;
}

function densify(line, every) {
  const out = [line[0]];
  for (let k = 1; k < line.length; k++) {
    const [ax, ay] = line[k - 1], [bx, by] = line[k], m = Math.max(1, Math.ceil(Math.hypot(bx - ax, by - ay) / every));
    for (let q = 1; q <= m; q++) out.push([ax + (bx - ax) * q / m, ay + (by - ay) * q / m]);
  }
  return out;
}

// Finished level at a plan point, clamped to the carriageway.
const finishedAtPoint = (road, x, y) => {
  const p = road.locate(x, y), half = road.width / 2;
  return p ? road.finishedAt(p.s, Math.max(-half, Math.min(half, p.off))) : road.designLevel(0);
};

// The two carriageway edges, the centreline and the square ends, at finished level.
export function edgeLines(road) {
  const v = [], half = road.width / 2, { segs } = frame(road);
  const run = (line) => {
    for (let k = 1; k < line.length; k++) {
      const [ax, ay] = line[k - 1], [bx, by] = line[k];
      v.push(ax, ay, finishedAtPoint(road, ax, ay), bx, by, finishedAtPoint(road, bx, by));
    }
  };
  run(densify(offsetLine(road, half), 1)); run(densify(offsetLine(road, -half), 1)); run(densify(offsetLine(road, 0), 1));
  for (const [s, g] of [[0, segs[0]], [road.length2d, segs[segs.length - 1]]]) {
    const [cx, cy] = road.pointAt(s);
    run(densify([[cx + g.nx * half, cy + g.ny * half], [cx - g.nx * half, cy - g.ny * half]], 0.5));
  }
  return new Float32Array(v);
}

// Where a batter meets the ground, going outward from an edge point along (ux, uy). null if not met.
function daylight(road, x, y, ux, uy, zE, g) {
  const { fillSlope, cutSlope } = road, limit = road.reach - road.width / 2;
  const g0 = g(x, y);
  if (Math.abs(zE - g0) < 1e-6) return { d: 0, z: g0 };
  const fillSide = zE > g0, sgn = fillSide ? 1 : -1;
  const raw = (d) => (fillSide ? zE - d / fillSlope : zE + d / cutSlope) - g(x + ux * d, y + uy * d);
  let a = 0, b = 0.25;
  while (sgn * raw(b) > 0) { a = b; b += 0.25; if (b > limit) return null; }
  for (let k = 0; k < 30; k++) { const m = (a + b) / 2; if (sgn * raw(m) > 0) a = m; else b = m; }
  return { d: b, z: fillSide ? zE - b / fillSlope : zE + b / cutSlope };
}

// The daylight line (top of cut, toe of fill) along each side and a hatch line from the edge to it every
// `tick` metres. The result's .unmet counts edge points whose batter did not reach the ground within the
// road's reach (a hillside steeper than the batter).
export function batterLines(road, g = road.groundAt, { tick = 5 } = {}) {
  const v = [], half = road.width / 2;
  let unmet = 0;
  for (const side of [1, -1]) {
    const edge = densify(offsetLine(road, side * half), 1);
    let prev = null, run = 0, lastTick = -Infinity;
    for (let k = 0; k < edge.length; k++) {
      const [x, y] = edge[k], p = road.locate(x, y);
      if (k > 0) run += Math.hypot(x - edge[k - 1][0], y - edge[k - 1][1]);
      if (!p) { prev = null; continue; }
      const ux = (x - p.fx) / (p.d || 1), uy = (y - p.fy) / (p.d || 1), zE = road.finishedAt(p.s, side * half);
      const hit = daylight(road, x, y, ux, uy, zE, g);
      if (!hit) { unmet++; prev = null; continue; }
      const q = [x + ux * hit.d, y + uy * hit.d, hit.z];
      if (prev) v.push(...prev, ...q);
      if (hit.d > 0.05 && run - lastTick >= tick - 1e-9) { v.push(x, y, zE, ...q); lastTick = run; }
      prev = q;
    }
  }
  const out = new Float32Array(v);
  out.unmet = unmet;
  return out;
}

// A line over each chainage run in `sections` ([{ from, to, side? }]), lifted by `lift` metres so it reads
// above the surface: on the centreline, or along the named edge when a run has a side ('left' | 'right').
// Draw steepSections in red with STEEP_NOTE, drainSections with DRAIN_NOTE.
export function sectionLines(road, sections, { lift = 0.05, every = 1 } = {}) {
  const v = [], { segs } = frame(road), half = road.width / 2;
  const at = (s, off) => {
    const [x, y] = road.pointAt(s);
    let i = 0, s0 = 0;
    for (; i < segs.length - 1; i++) {
      const [ax, ay] = road.path[i], [bx, by] = road.path[i + 1], len = Math.hypot(bx - ax, by - ay);
      if (s <= s0 + len) break;
      s0 += len;
    }
    return [x + segs[i].nx * off, y + segs[i].ny * off, road.finishedAt(s, off) + lift];
  };
  for (const { from, to, side } of sections) {
    const off = side === 'left' ? half : side === 'right' ? -half : 0;
    const m = Math.max(1, Math.ceil((to - from) / every));
    for (let k = 0; k < m; k++) v.push(...at(from + (to - from) * k / m, off), ...at(from + (to - from) * (k + 1) / m, off));
  }
  return new Float32Array(v);
}

Search

A JavaScript module in the world folder of GlobalGrid2050 that parses coords (`parseCoords`) and query (`parseQuery`) (units: MW), covering postcodes. It parses coords (`parseCoords`) and parses query (`parseQuery`).

ingestglobalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/search.mjs · lines 1–96 of 96 · version 2026-09-27 00:05 · pattern prepare (shared by 9 files)

What it does
It lists and searches postcodes. Defines 8 functions or classes, including norm, compact, parseCoords, parseQuery, prepare.
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: postcodes.
Downstream impact
Used directly by 2 files: Search UI (globalgrid2050); Search UI (globalgrid2050). Reached from 3 other entry points, including Graphics Engines Open Source — Versions Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/versions/); Versions — Site World Page (graphics-engines-open-source, https://ventusltd.github.io/graphics-engines-open-source/web/versions/202609262227-site-world/); Substrate (graphics-engines-open-source).
What it achieves
Project search over `web/world/data/projects.json`. Pure: no imports, no DOM.
Why it matters
Imported by Search UI.
Application
globalgrid2050 · solar-design-studio/202609270005-site-world-v3/world · JavaScript module
Uses
none found
Used by
imported by Search UI (import), imported by Search UI (import), mentioned in Standalone (comment link)
Produces
SCORE, parseCoords, parseQuery, search
Defines here
norm, compact, parseCoords, parseQuery, prepare, altMatches, score, search
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609270005-site-world-v3/world/search.mjs:1-96 · blob 17f3ed6afacc8427996f7d752be8e66b8c41fc91 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
// Project search over web/world/data/projects.json. Pure: no imports, no DOM.
// Rules follow GridAtlas: space-separated terms must all match (AND), a term
// may hold '/'-separated alternatives (OR), matching is substring over name,
// postcode, county and ref. Scores: exact postcode +10000, exact ref +9000,
// exact name +2000, name prefix +500, any other match +200.
// Typed "lat, lon" returns { kind: 'coords', lat, lon }; British grid
// references are parsed elsewhere.

export const SCORE = { postcode: 10000, ref: 9000, name: 2000, prefix: 500, other: 200 };

const COORDS = /^\s*(-?\d{1,2}(?:\.\d+)?)\s*[,\s]\s*(-?\d{1,3}(?:\.\d+)?)\s*$/;

const norm = (s) => (s == null ? '' : String(s).toLowerCase().replace(/\s+/g, ' ').trim());
const compact = (s) => norm(s).replace(/ /g, '');

export function parseCoords(text) {
  const m = COORDS.exec(String(text ?? ''));
  if (!m) return null;
  const lat = Number(m[1]), lon = Number(m[2]);
  if (!Number.isFinite(lat) || !Number.isFinite(lon)) return null;
  if (Math.abs(lat) > 90 || Math.abs(lon) > 180) return null;
  // Two bare integers ("12 400") are more likely a name or number than a point.
  if (!m[1].includes('.') && !m[2].includes('.')) return null;
  return { kind: 'coords', lat, lon };
}

// Split the query into terms, each a list of alternatives.
export function parseQuery(text) {
  return norm(text)
    .split(' ')
    .map((t) => t.split('/').map((a) => a.trim()).filter(Boolean))
    .filter((alts) => alts.length > 0);
}

// Turn the index into objects with pre-normalised search text, once per index.
const PREPARED = new WeakMap();
const DEFAULT_FIELDS = ['repd_ref', 'name', 'postcode', 'county', 'technology', 'status', 'capacity_mw', 'lat', 'lon'];

function prepare(index) {
  if (PREPARED.has(index)) return PREPARED.get(index);
  const fields = index.fields ?? DEFAULT_FIELDS;
  const rows = (index.records ?? []).map((r) => {
    const rec = Array.isArray(r) ? Object.fromEntries(fields.map((f, i) => [f, r[i]])) : r;
    return {
      rec,
      name: norm(rec.name),
      postcode: norm(rec.postcode),
      postcodeC: compact(rec.postcode),
      county: norm(rec.county),
      ref: norm(rec.repd_ref),
    };
  });
  PREPARED.set(index, rows);
  return rows;
}

function altMatches(row, alt) {
  const c = alt.replace(/ /g, '');
  return row.name.includes(alt) || row.county.includes(alt) || row.ref.includes(alt) ||
    row.postcode.includes(alt) || (c.length > 0 && row.postcodeC.includes(c));
}

function score(row, whole) {
  let s = 0;
  for (const q of whole) {
    const qc = q.replace(/ /g, '');
    if (row.postcodeC && row.postcodeC === qc) s += SCORE.postcode;
    if (row.ref && row.ref === q) s += SCORE.ref;
    if (row.name && row.name === q) s += SCORE.name;
    else if (row.name && row.name.startsWith(q)) s += SCORE.prefix;
  }
  return s > 0 ? s : SCORE.other;
}

export function search(index, query, limit = 12) {
  const coords = parseCoords(query);
  if (coords) return coords;
  const terms = parseQuery(query);
  if (terms.length === 0 || !index) return { kind: 'projects', total: 0, results: [] };
  // Whole-query forms for the exact and prefix bonuses: the full text, or each
  // alternative when the query is a single term.
  const whole = terms.length === 1 ? terms[0] : [norm(query)];
  const hits = [];
  for (const row of prepare(index)) {
    if (!terms.every((alts) => alts.some((a) => altMatches(row, a)))) continue;
    hits.push({ ...row.rec, score: score(row, whole) });
  }
  hits.sort((a, b) =>
    b.score - a.score ||
    (b.capacity_mw ?? -1) - (a.capacity_mw ?? -1) ||
    String(a.name ?? '').localeCompare(String(b.name ?? '')) ||
    String(a.repd_ref ?? '').localeCompare(String(b.repd_ref ?? '')));
  return { kind: 'projects', total: hits.length, results: hits.slice(0, Math.max(0, limit)) };
}

export default search;

Sun UI

A JavaScript module in the world folder of GlobalGrid2050 that mounts sun control (`mountSunControl`), covering solar.

renderglobalgrid2050 / solar-design-studio/202609270005-site-world-v3/world/sun-ui.mjs · lines 1–50 of 50 · version 2026-09-27 00:05 · Not reached from any entry point (candidate for review)

What it does
It draws solar. Defines startState, gridSun, mountSunControl, apply. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage sub33kv_design (path word 'design'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: solar.
Inputs & outputs
In: form fields (user input). Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
What it achieves
It starts state (`startState`) and is built from the grid sun helper (`gridSun`) and the mount sun control helper (`mountSunControl`). Date and time for the Terrain shadow layer: a date field and a time-of-day slider under the Layers panel, shown only while the layer is on. It responds to change and input events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · solar-design-studio/202609270005-site-world-v3/world · JavaScript module
Uses
Sun (import), Bng (import)
Used by
none found
Produces
startState, gridSun, mountSunControl
Defines here
startState, gridSun, mountSunControl, apply
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 solar-design-studio/202609270005-site-world-v3/world/sun-ui.mjs:1-50 · blob ed82cdb140100340617fe77abb8809b9c725792b · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
// Date and time for the Terrain shadow layer: a date field and a time-of-day slider (UTC) under the Layers panel,
// shown only while the layer is on. Each change works out the sun at the site centre (sun.mjs) and hands the layer
// its grid bearing (true bearing less the grid convergence) and elevation.
import { timeState, applyTime, timeView, sunAt, gridConvergence } from './sun.mjs';
import { bngToWgs84 } from './bng.mjs';

// The moment to start from: now, or today's solar noon when the sun is down (a shadow at night shows nothing).
export function startState(lat, lon, nowMs = Date.now()) {
  const now = timeState(nowMs, 15);
  return sunAt(lat, lon, now).up ? now : applyTime(now, { type: 'solarNoon', lon });
}

// { azimuth, elevation, status } the shade layer takes for one moment at one place.
export function gridSun(lat, lon, state) {
  const s = sunAt(lat, lon, state);
  return { azimuth: s.azimuth - gridConvergence(lat, lon), elevation: s.elevation, status: s.status };
}

// host: element to hold the control. layer: the shade layer object. site: { centre_e, centre_n }.
// Returns { element, show(v), state() } or null when there is no layer or site.
export function mountSunControl(host, { layer, site, nowMs } = {}) {
  if (!host || !layer || typeof layer.setSun !== 'function' || !site) return null;
  const { lat, lon } = bngToWgs84(site.centre_e, site.centre_n);
  const doc = host.ownerDocument || document;
  let state = startState(lat, lon, nowMs);
  const box = doc.createElement('fieldset');
  box.className = 'sun-time';
  box.hidden = true;
  box.innerHTML = '<legend>Sun for the terrain shadow</legend>' +
    '<label>Date <input type="date" data-sun="date"></label>' +
    '<label>Time (UTC) <input type="range" min="0" max="1439" step="15" data-sun="minute"></label>' +
    '<p class="note" aria-live="polite" data-sun="status"></p>';
  const date = box.querySelector('[data-sun="date"]'), minute = box.querySelector('[data-sun="minute"]');
  const status = box.querySelector('[data-sun="status"]');
  const apply = () => {
    const v = timeView(state), s = gridSun(lat, lon, state);
    date.value = v.date; minute.value = String(v.minuteOfDay);
    status.textContent = s.status;
    layer.setSun(s);
  };
  date.addEventListener('change', () => {
    const [y, m, d] = date.value.split('-').map(Number);
    try { state = applyTime(state, { type: 'date', year: y, month: m, day: d }); } catch { /* keep the last good date */ }
    apply();
  });
  minute.addEventListener('input', () => { state = applyTime(state, { type: 'minuteOfDay', minute: Number(minute.value) }); apply(); });
  host.appendChild(box);
  apply();
  return { element: box, show(v) { box.hidden = !v; }, state: () => state };
}