GLOBALGRID2050 / EXPLORE CODE

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

Overhead and 4 more files

A JavaScript module in the world folder of GlobalGrid2050 that works with 400kV, 33kV, 275kV and 132kV.

672 lines of JavaScript from globalgrid2050, in 5 files. Topic: Solar and storage design. Section 136 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. Overhead Line (OHL) Zones transform · globalgrid2050 / solar-design-studio/202609270145-site-world-v3/world/ohl-zones.mjs lines 1–197
  2. Overhead transform · globalgrid2050 / solar-design-studio/202609270145-site-world-v3/world/overhead.mjs lines 1–215
  3. Range UI render · globalgrid2050 / solar-design-studio/202609270145-site-world-v3/world/range-ui.mjs lines 1–43
  4. Route Tool transform · globalgrid2050 / solar-design-studio/202609270145-site-world-v3/world/route-tool.mjs lines 1–95
  5. Sun Climate render · globalgrid2050 / solar-design-studio/202609270145-site-world-v3/world/sun-climate.mjs lines 1–122

Overhead Line (OHL) Zones

A JavaScript module in the world folder of GlobalGrid2050 that works with overhead lines (OHL) and cables. It builds spans (`buildSpans`) and checks design (`checkDesign`).

transformglobalgrid2050 / solar-design-studio/202609270145-site-world-v3/world/ohl-zones.mjs · lines 1–197 of 197 · version 2026-09-27 01:45 · Not reached from any entry point (candidate for review) · pattern designItems (shared by 3 files)

What it does
It calculates overhead lines (OHL) and cables. Defines 17 functions or classes, including r1, swayOf, buildSpans, side, zoneRings.
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: overhead lines (OHL), cables.
Downstream impact
Used directly by 2 files: Overhead Line (OHL) UI (globalgrid2050); Overhead Line (OHL) UI (globalgrid2050).
What it achieves
Overhead line zones: corridors on the ground either side of each overhead line, and the design checks against them.
Why it matters
Imported by Overhead Line (OHL) UI.
Application
globalgrid2050 · solar-design-studio/202609270145-site-world-v3/world · JavaScript module
Uses
Overhead (import), Clash (import), Offset (import), Overhead Line (OHL) Gs6 (import)
Used by
imported by Overhead Line (OHL) UI (import), imported by Overhead Line (OHL) UI (import), mentioned in Standalone (comment link)
Produces
SAMPLE_M, WIRE_STEP_M, swayOf, buildSpans, zoneRings, itemShape, samplePoints, crossingOf, goalpostsFor, plantReach, checkDesign, designItems
Defines here
r1, swayOf, buildSpans, side, zoneRings, parts, itemShape, samplePoints, cross2, o, crossingOf, pointAtChainage, goalpostsFor, plantReach, checkDesign, designItems, L
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/202609270145-site-world-v3/world/ohl-zones.mjs:1-197 · blob 211949f61aeeff9584c9d94d71f64560023295cb · 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
// Overhead line zones: corridors on the ground either side of each overhead line, and the design checks against them.
// Pure: no DOM. Local metres (x east, y north, z up). The conductors come from the grid layer (layer.wires()):
//   [{ line, cls, support: 'pole' | 'tower', span, conductor, from, to, a: [x, y, z], b: [x, y, z], param }]
// where a and b are the conductor's ends on the towers and param its catenary parameter (overhead.mjs).
// Tower heights and sag are ASSUMED by the grid layer, so every zone and flag here is illustrative. The distances
// and their sources are in ohl-gs6.mjs. A place with no flag is NOT ASSESSED: nothing here says a place is free of danger.
//
// Zone of a span: the plan outline of its two outermost conductors (a four-sided area), grown by
//   distance + sway + position allowance
// where distance is the barrier (GS6 para 19) or the zone (GS6 para 11, and the earlier edition's figure by support,
// whichever is larger), sway is sag x sin(swing) (assumed), and the position allowance covers inferred tower positions.

import { catenarySpan, levelSag } from './overhead.mjs';
import { geometryDistance, distToGeometry, insideStretches } from './clash.mjs';
import { offsetUnion } from './offset.mjs';
import { ZONES, SWAY, POSITION_ALLOWANCE, ITEM_HALF, PAD_RADIUS_M, ACTION, zoneDistance, exclusionFor } from './ohl-gs6.mjs';

export const SAMPLE_M = 2;        // design items are sampled this often for the working-height check
export const WIRE_STEP_M = 1;     // conductors are sampled this often near a sample point
const r1 = v => Math.round(v * 10) / 10;

// Pure: the sideways swing allowance of a conductor: its level-span mid sag x sin(swing), never under SWAY.minM.
export function swayOf(w) {
  const L = Math.hypot(w.b[0] - w.a[0], w.b[1] - w.a[1]);
  if (!(L > 0) || !(w.param > 0)) return SWAY.minM;
  return Math.max(SWAY.minM, levelSag(L, w.param) * Math.sin(SWAY.swingDeg * Math.PI / 180));
}

// Pure: wires -> spans [{ id, line, span, cls, support, from, to, wires, quad, sway, barrierReach, zoneReach, exclusion }].
// quad: the plan outline of the two outermost conductors (a to a, b to b); a single conductor gives a segment.
export function buildSpans(wires) {
  const by = new Map();
  for (const w of Array.isArray(wires) ? wires : []) {
    if (!w || !Array.isArray(w.a) || !Array.isArray(w.b)) continue;
    const k = `${w.line}/${w.span}`;
    if (!by.has(k)) by.set(k, []);
    by.get(k).push(w);
  }
  return [...by.values()].map(ws => {
    const w0 = ws[0], dx = w0.b[0] - w0.a[0], dy = w0.b[1] - w0.a[1], L = Math.hypot(dx, dy) || 1;
    const side = w => ((w.a[0] + w.b[0]) / 2 - w0.a[0]) * (-dy / L) + ((w.a[1] + w.b[1]) / 2 - w0.a[1]) * (dx / L);
    const sorted = ws.slice().sort((p, q) => side(p) - side(q)), lo = sorted[0], hi = sorted[sorted.length - 1];
    const quad = lo === hi ? { pts: [lo.a.slice(0, 2), lo.b.slice(0, 2)], closed: false, area: false }
      : { pts: [lo.a.slice(0, 2), lo.b.slice(0, 2), hi.b.slice(0, 2), hi.a.slice(0, 2)], closed: true, area: true };
    const sway = Math.max(...ws.map(swayOf)), extra = sway + POSITION_ALLOWANCE.m;
    return { id: `${w0.from}-${w0.to}`, line: w0.line, span: w0.span, cls: w0.cls, support: w0.support, from: w0.from, to: w0.to,
      wires: ws, quad, sway, barrierReach: ZONES.barrier.m + extra, zoneReach: zoneDistance(w0.support) + extra, exclusion: exclusionFor(w0.cls) };
  });
}

// Pure: the rings to draw, per line: { line, cls, zone: rings, barrier: rings }. The union of every span's grown quad.
export function zoneRings(spans, { segments = 16 } = {}) {
  const lines = new Map();
  for (const s of spans) { if (!lines.has(s.line)) lines.set(s.line, []); lines.get(s.line).push(s); }
  return [...lines.values()].map(ss => {
    const parts = key => ss.map(s => ({ pts: s.quad.pts, closed: s.quad.closed, area: s.quad.area, d: s[key] }));
    return { line: ss[0].line, cls: ss[0].cls, support: ss[0].support,
      zone: offsetUnion(parts('zoneReach'), { segments }).rings, barrier: offsetUnion(parts('barrierReach'), { segments }).rings };
  });
}

// Pure: a design item's plan geometry. items: [{ id, kind, pts: [[x, y], ...], area?, closed?, half? }] in local metres.
// area: a filled outline (a pad); closed: an outline only (a fence); neither: a path (trench, cable, road, piles, hdd).
export function itemShape(it) {
  const pts = (it.pts || []).filter(p => Number.isFinite(p?.[0]) && Number.isFinite(p?.[1])).map(p => [p[0], p[1]]);
  const area = !!it.area && pts.length > 2;
  let half = Number.isFinite(it.half) ? it.half : ITEM_HALF[it.kind] ?? 0.5;
  if (it.kind === 'pad' && pts.length < 3) half = Math.max(half, PAD_RADIUS_M); // a pad drawn by its centre: a disc
  return { core: { pts: it.kind === 'pad' && pts.length === 2 ? [pts[0]] : pts, closed: area || (!!it.closed && pts.length > 2), area }, half };
}

// Pure: sample points along an item every step metres (vertices included; a pad centre adds a ring of eight).
export function samplePoints(it, step = SAMPLE_M) {
  const { core, half } = itemShape(it), p = core.pts, out = [];
  if (p.length === 1) {
    out.push(p[0]);
    for (let k = 0; k < 8 && half > 0; k++) out.push([p[0][0] + half * Math.cos(k * Math.PI / 4), p[0][1] + half * Math.sin(k * Math.PI / 4)]);
    return out;
  }
  const n = core.closed ? p.length : p.length - 1;
  for (let i = 0; i < n; i++) {
    const a = p[i], b = p[(i + 1) % p.length], m = Math.max(1, Math.ceil(Math.hypot(b[0] - a[0], b[1] - a[1]) / step));
    for (let k = 0; k < m; k++) out.push([a[0] + (b[0] - a[0]) * k / m, a[1] + (b[1] - a[1]) * k / m]);
  }
  if (!core.closed) out.push(p[p.length - 1]);
  return out;
}

const cross2 = (a, b, c, d) => {
  const o = (p, q, r) => Math.sign((q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0]));
  return o(a, b, c) * o(a, b, d) < 0 && o(c, d, a) * o(c, d, b) < 0;
};
// Pure: where an item's path first crosses under a conductor of the span, or null.
export function crossingOf(core, span) {
  const n = core.closed ? core.pts.length : core.pts.length - 1;
  for (let i = 0; i < n; i++) {
    const a = core.pts[i], b = core.pts[(i + 1) % core.pts.length];
    for (const w of span.wires) if (cross2(a, b, w.a, w.b)) return [a, b];
  }
  return null;
}

// Pure: points at chainages along a polyline.
function pointAtChainage(pts, s) {
  let run = 0;
  for (let i = 1; i < pts.length; i++) {
    const L = Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]);
    if (run + L >= s || i === pts.length - 1) { const f = L > 0 ? Math.min(1, Math.max(0, (s - run) / L)) : 0;
      return [pts[i - 1][0] + (pts[i][0] - pts[i - 1][0]) * f, pts[i - 1][1] + (pts[i][1] - pts[i - 1][1]) * f]; }
    run += L;
  }
  return pts[0];
}

// Pure: goalpost positions for a road crossing a span: where its centreline (plus half-width) enters and leaves
// the barrier zone, one pair per passage. [{ at: [x, y], end: 'enter' | 'leave' }].
export function goalpostsFor(core, half, span) {
  const st = insideStretches(core.pts, span.quad, span.barrierReach + half);
  return st.flatMap(r => [{ at: pointAtChainage(core.pts, r.from_m), end: 'enter' }, { at: pointAtChainage(core.pts, r.to_m), end: 'leave' }]);
}

// Pure: the least distance from plant of height H standing at (x, y) on ground g to a span's conductors, allowing
// for sway and position (horizontal distance reduced by both). { d, wire, s } or null when no conductor is near.
export function plantReach(x, y, g, H, span, step = WIRE_STEP_M) {
  const slack = span.sway + POSITION_ALLOWANCE.m, top = g + H;
  let best = null;
  for (const w of span.wires) {
    const L = Math.hypot(w.b[0] - w.a[0], w.b[1] - w.a[1]);
    if (!(L > 0)) continue;
    const ux = (w.b[0] - w.a[0]) / L, uy = (w.b[1] - w.a[1]) / L;
    const s0 = (x - w.a[0]) * ux + (y - w.a[1]) * uy, off = Math.abs((x - w.a[0]) * -uy + (y - w.a[1]) * ux);
    // Horizontal distance to any point of the wire is at least off, and more than window away along it is further.
    const window = span.exclusion + slack + step;
    if (off - slack >= span.exclusion || s0 < -window || s0 > L + window) continue;
    const c = catenarySpan(L, w.a[2], w.b[2], w.param);
    const lo = Math.max(0, s0 - window), hi = Math.min(L, s0 + window);
    for (let s = lo; s <= hi + 1e-9; s += step) {
      const cx = w.a[0] + ux * s, cy = w.a[1] + uy * s, z = c.z(s);
      const dh = Math.max(0, Math.hypot(x - cx, y - cy) - slack), dz = z > top ? z - top : z < g ? g - z : 0;
      const d = Math.hypot(dh, dz);
      if (!best || d < best.d) best = { d, wire: w, s, z };
    }
  }
  return best;
}

// Pure: every flag for the design. items as itemShape takes; spans from buildSpans; measuredAt(x, y) -> ground or NaN.
// opts.height: working height (user-set, metres). Returns { flags, goalposts, unmeasured } where each flag is
// { item, kind, flag: 'inside' | 'crosses' | 'height', span, at, message }.
export function checkDesign(items, spans, measuredAt = () => NaN, { height = 0 } = {}) {
  const flags = [], goalposts = [];
  let unmeasured = 0;
  for (const it of Array.isArray(items) ? items : []) {
    const { core, half } = itemShape(it);
    if (!core.pts.length) continue;
    const name = `${it.kind} ${it.id}`;
    for (const sp of spans) {
      const g = geometryDistance(core, sp.quad);
      if (!(g.d < sp.zoneReach + half)) continue;
      const path = !core.area && core.pts.length > 1, crossing = path ? crossingOf(core, sp) : null;
      flags.push({ item: it.id, kind: it.kind, flag: crossing ? 'crosses' : 'inside', span: sp.id, at: g.at || core.pts[0],
        message: `${name} ${crossing ? 'crosses under' : 'is inside'} the overhead line zone of span ${sp.id} (${sp.cls}): ${ACTION}` });
      if (crossing && it.kind === 'road') {
        for (const gp of goalpostsFor(core, half, sp)) goalposts.push({ item: it.id, span: sp.id, ...gp });
      }
    }
    if (!(height > 0)) continue;
    let worst = null;
    for (const p of samplePoints(it)) {
      const near = spans.filter(sp => distToGeometry(sp.quad, p[0], p[1]) < sp.zoneReach + height + sp.exclusion);
      if (!near.length) continue;
      const gz = measuredAt(p[0], p[1]);
      if (!Number.isFinite(gz)) { unmeasured++; continue; }
      for (const sp of near) {
        const r = plantReach(p[0], p[1], gz, height, sp);
        if (r && r.d < sp.exclusion && (!worst || r.d < worst.d)) worst = { ...r, sp, at: p };
      }
    }
    if (worst) flags.push({ item: it.id, kind: it.kind, flag: 'height', span: worst.sp.id, at: worst.at, reach_m: r1(worst.d),
      message: `${name}: plant ${r1(height)} m tall (user-set) would come within the ${worst.sp.exclusion} m exclusion distance `
        + `of a conductor on span ${worst.sp.id} (${worst.sp.cls}, conductor height assumed): ${ACTION}` });
  }
  return { flags, goalposts, unmeasured };
}

// Pure: the design snapshot (design-ui snapshot, national-grid metres) -> items in local metres.
export function designItems(design, origin) {
  const L = path => (path || []).filter(p => Number.isFinite(p?.e) && Number.isFinite(p?.n)).map(p => [p.e - origin.e, p.n - origin.n]);
  const out = [];
  (design?.trenches || []).forEach((t, i) => out.push({ id: `trench-${i + 1}`, kind: 'trench', pts: L(t.path) }));
  (design?.cables || []).forEach((c, i) => out.push({ id: `cable-${i + 1}`, kind: 'cable', pts: L(c.path) }));
  (design?.works || []).forEach((w, i) => {
    const pts = L(w.path), id = `${w.kind}-${i + 1}`;
    out.push({ id, kind: w.kind, pts, area: w.kind === 'pad' && pts.length > 2, closed: w.kind === 'fence' });
  });
  return out.filter(it => it.pts.length >= 1);
}

Overhead

A JavaScript module in the world folder of GlobalGrid2050 that works with 400kV, 33kV, 275kV and 132kV.

transformglobalgrid2050 / solar-design-studio/202609270145-site-world-v3/world/overhead.mjs · lines 1–215 of 215 · version 2026-09-27 01:45 · pattern buildOverhead (shared by 2 files)

What it does
It calculates 400kV, 33kV, 275kV and 132kV. Defines 19 functions or classes, including clearanceBasis, coshm1, levelSag, paramFromSag, catenarySpan.
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: 400kV, 33kV, 275kV, 132kV, 66kV.
Inputs & outputs
Voltage levels named: 400kV, 275kV, 132kV, 66kV, 33kV.
Downstream impact
Used directly by 3 files: Overhead Line (OHL) Zones (globalgrid2050); Layers (globalgrid2050); Layers (globalgrid2050). Reached from 4 other entry points, including Solar Design Studio — Site World Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609271853-site-world/); Solar Design Studio — Site World V3 Page (globalgrid2050, https://globalgrid2050.com/solar-design-studio/202609270402-site-world-v3/); Substrate (globalgrid2050).
What it achieves
It draws tower (`drawTower`) and is built from the clearance basis helper (`clearanceBasis`) and the coshm1 step (`coshm1`). Overhead lines: lattice towers, wood poles and catenary conductors as light wireframe. Its code works with 400 kV, 33 kV and 132 kV.
Why it matters
Imported by Overhead Line (OHL) Zones and Layers.
Application
globalgrid2050 · solar-design-studio/202609270145-site-world-v3/world · JavaScript module
Uses
none found
Used by
imported by Overhead Line (OHL) Zones (import), imported by Layers (dynamic import), imported by Layers (dynamic import)
Produces
SAG_TO_SPAN, STEP, ESQCR_SOURCE, MIN_CLEARANCE, MIN_CLEARANCE_OVER_ROAD, clearanceBasis, TOWER_TYPES, levelSag, paramFromSag, catenarySpan, buildOverhead
Defines here
clearanceBasis, coshm1, levelSag, paramFromSag, catenarySpan, z, unit, directionAt, specOf, attachments, at, drawTower, P, L, ring, solidOf, buildOverhead, need, xy
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/202609270145-site-world-v3/world/overhead.mjs:1-215 · blob 2fe84494bdd571990082caf63503f12efa34f3eb · 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
// Overhead lines: lattice towers, wood poles and catenary conductors as light wireframe. Pure: no imports, no DOM.
// Local east (x), north (y), up (z), metres. Output lines are gl.LINES pairs: x,y,z, x,y,z per segment.
//
// buildOverhead(towers, opts) -> { lines: Float32Array, solids: [{ min, max }],
//   clearances: [{ span, minClearance, at, conductor, required, requiredOverRoad, source, basis }],
//   wires: [{ span, conductor, a: [x, y, z], b: [x, y, z], param }] }  each conductor's ends and catenary parameter
//   basis always reads "at an assumed 3.5 % sag, not the sag at maximum conductor temperature" (or the sag given).
//   towers: [{ id, x, y, ground, type?: '400kV'|'275kV'|'132kV'|'33kV' }] in order along the line
//   opts.groundAt(x, y): ground height under the span (default: straight between the two tower grounds)
//   opts.tensionPerWeight: catenary parameter a = H/w in metres (horizontal tension over weight per metre); wins if given
//   opts.sagRatio: mid-span sag / span on the equivalent level span (default SAG_TO_SPAN); a is solved from it
//   opts.step: conductor sample spacing in metres (default 5)
//
// EVERY DIMENSION BELOW IS TYPICAL, NOT SURVEYED. They draw a believable outline; they are not a design of any real line.

// Default sag: 3.5 % of span. Typical, not surveyed. UK 400 kV spans of ~360 m commonly sag 10-13 m at maximum
// design temperature, i.e. roughly 3-4 %. No single public source was checked for this figure in this session.
export const SAG_TO_SPAN = 0.035;
export const STEP = 5;          // conductor sample spacing, metres
const CLEAR_STEP = 1;           // clearance search spacing, metres (finer than the drawing, so a hill top is not missed)

// Minimum height of a bare overhead conductor above ground, metres, by nominal voltage: the Electricity Safety,
// Quality and Continuity Regulations 2002 (SI 2002/2665), regulation 17 and Schedule 2. Schedule 2 gives one column
// over roads and one for other locations: not exceeding 33 kV 5.8 m over a road, 5.2 m elsewhere; above 33 kV up to
// 66 kV 6.0 m both; up to 132 kV 6.7 m; up to 275 kV 7.0 m; up to 400 kV 7.3 m. Quoted from the Schedule as commonly
// reproduced, not re-read against the legislation.gov.uk text in this session: check before use.
export const ESQCR_SOURCE = 'ESQCR 2002 (SI 2002/2665) Schedule 2';
export const MIN_CLEARANCE = { '400kV': 7.3, '275kV': 7.0, '132kV': 6.7, '33kV': 5.2 };          // other locations
export const MIN_CLEARANCE_OVER_ROAD = { '400kV': 7.3, '275kV': 7.0, '132kV': 6.7, '33kV': 5.8 };  // over roads
// Every clearance here is worked out on the drawn sag, which is assumed, so every clearance carries this label.
export const clearanceBasis = (sagRatio = SAG_TO_SPAN) =>
  `at an assumed ${Number((sagRatio * 100).toFixed(2))} % sag, not the sag at maximum conductor temperature`;

// Tower classes. Typical, not surveyed. z = height above the tower's ground; half = half-width across the line.
// arms: cross-arm levels, each carrying one phase per side (double circuit). insulator: string length hanging below the arm.
// Public context (not re-checked in this session):
//  - 400 kV: National Grid describes its standard lattice pylons (L6, and the later L12) as about 50 m tall,
//    with a typical span of about 360 m. Arm widths here are proportioned by eye from published elevations.
//  - 275 kV: the L2 design (1950s) is a smaller double-circuit lattice, commonly given as about 40-45 m.
//  - 132 kV: the PL1 / PL16 family is commonly given as about 26-27 m, spans about 250-300 m.
//  - 33 kV: wood poles, commonly 10-13 m long with about 1.5-2 m in the ground, spans about 80-120 m.
export const TOWER_TYPES = {
  '400kV': { kind: 'lattice', height: 50, baseHalf: 4.5, topHalf: 1.0, peakHalf: 0.4, insulator: 5.0,
    arms: [{ z: 44, half: 6.1 }, { z: 35.5, half: 7.9 }, { z: 27, half: 6.9 }] },
  '275kV': { kind: 'lattice', height: 41, baseHalf: 3.8, topHalf: 0.9, peakHalf: 0.35, insulator: 3.5,
    arms: [{ z: 36, half: 5.2 }, { z: 29, half: 6.4 }, { z: 22, half: 5.6 }] },
  '132kV': { kind: 'lattice', height: 27, baseHalf: 2.5, topHalf: 0.7, peakHalf: 0.3, insulator: 1.8,
    arms: [{ z: 24, half: 3.4 }, { z: 20, half: 3.8 }, { z: 16, half: 3.4 }] },
  '33kV': { kind: 'pole', height: 9.5, radius: 0.15, armZ: 8.9, armHalf: 1.2, pin: 0.3 },
};
const DEFAULT_TYPE = '400kV';

// ---- catenary maths -------------------------------------------------------------------------------------------------

const coshm1 = (u) => { const s = Math.sinh(u / 2); return 2 * s * s; }; // cosh(u) - 1 without cancellation

// Mid-span sag of a level span of horizontal length L with parameter a: a (cosh(L / 2a) - 1).
export const levelSag = (L, a) => a * coshm1(L / (2 * a));

// The catenary parameter a whose level span of length L sags sagRatio * L. Sag falls as a grows, so bisect (in log a).
export function paramFromSag(L, sagRatio) {
  if (!(L > 0) || !(sagRatio > 0)) throw Error('span and sag ratio must be positive');
  const target = sagRatio * L;
  let lo = Math.log(L * 1e-3), hi = Math.log(L * 1e7);
  for (let i = 0; i < 200; i++) {
    const mid = (lo + hi) / 2;
    if (levelSag(L, Math.exp(mid)) > target) lo = mid; else hi = mid;
  }
  return Math.exp((lo + hi) / 2);
}

// A span of horizontal length L from height h1 (s = 0) to h2 (s = L). The curve is z = zLow + a (cosh((s - s0) / a) - 1),
// i.e. y = a cosh(x / a) shifted so its vertex sits at (s0, zLow). Solving both end conditions gives
//   s0 = L/2 - a asinh((h2 - h1) / (2 a sinh(L / 2a)))
// so the vertex moves toward the lower support, and past it when the slope is steep (then s0 < 0 or s0 > L).
export function catenarySpan(L, h1, h2, a) {
  const s0 = L / 2 - a * Math.asinh((h2 - h1) / (2 * a * Math.sinh(L / (2 * a))));
  const zLow = h1 - a * coshm1(s0 / a);
  const z = (s) => zLow + a * coshm1((s - s0) / a);
  const sMin = Math.min(L, Math.max(0, s0)); // lowest point actually on the wire
  return { s0, zLow, z, sMin, zMin: z(sMin) };
}

// ---- tower geometry ------------------------------------------------------------------------------------------------

const unit = (dx, dy) => { const l = Math.hypot(dx, dy); return l > 0 ? [dx / l, dy / l] : [0, 0]; };

// Line direction at tower k: the bisector of the incoming and outgoing spans (a single tower faces north).
function directionAt(towers, k) {
  let dx = 0, dy = 0;
  if (k > 0) { const u = unit(towers[k].x - towers[k - 1].x, towers[k].y - towers[k - 1].y); dx += u[0]; dy += u[1]; }
  if (k < towers.length - 1) { const u = unit(towers[k + 1].x - towers[k].x, towers[k + 1].y - towers[k].y); dx += u[0]; dy += u[1]; }
  const d = unit(dx, dy);
  return d[0] === 0 && d[1] === 0 ? [0, 1] : d;
}

function specOf(t) {
  const spec = TOWER_TYPES[t.type || DEFAULT_TYPE];
  if (!spec) throw Error(`unknown tower type ${t.type} on ${t.id}`);
  return spec;
}

// Conductor attachment points in world coordinates, in a fixed order so phase j meets phase j on the next tower.
function attachments(t, spec, d, p) {
  const at = (across, z) => [t.x + p[0] * across, t.y + p[1] * across, t.ground + z];
  if (spec.kind === 'pole') {
    const z = spec.armZ + spec.pin;
    return [at(-spec.armHalf, z), at(0, spec.height), at(spec.armHalf, z)];
  }
  const out = [];
  for (const side of [-1, 1]) for (const arm of spec.arms) out.push(at(side * arm.half, arm.z - spec.insulator));
  return out;
}

// Wireframe for one tower into seg (flat array of x,y,z pairs). d = along the line, p = across it.
function drawTower(seg, t, spec, d, p) {
  const P = (along, across, z) => [t.x + d[0] * along + p[0] * across, t.y + d[1] * along + p[1] * across, t.ground + z];
  const L = (a, b) => seg.push(a[0], a[1], a[2], b[0], b[1], b[2]);
  if (spec.kind === 'pole') {
    L(P(0, 0, 0), P(0, 0, spec.height));
    L(P(0, -spec.armHalf, spec.armZ), P(0, spec.armHalf, spec.armZ));
    L(P(0, -spec.armHalf * 0.6, spec.armZ), P(0, 0, spec.armZ - 0.8)); // crossarm braces
    L(P(0, spec.armHalf * 0.6, spec.armZ), P(0, 0, spec.armZ - 0.8));
    return;
  }
  // Body: a square tapering from baseHalf at the ground to topHalf at the top arm, then a peak for the earth wire.
  const topZ = spec.arms[0].z, halfAt = (z) => spec.baseHalf + (spec.topHalf - spec.baseHalf) * Math.min(1, z / topZ);
  const levels = [0, ...spec.arms.map((a) => a.z).sort((a, b) => a - b)];
  if (levels[1] > 10) levels.splice(1, 0, levels[1] * 0.45); // a waist panel below the lowest arm
  const corners = [[1, 1], [-1, 1], [-1, -1], [1, -1]];
  const ring = (z) => corners.map(([i, j]) => P(i * halfAt(z), j * halfAt(z), z));
  for (let n = 0; n < levels.length; n++) {
    const r = ring(levels[n]);
    for (let c = 0; c < 4; c++) L(r[c], r[(c + 1) % 4]);              // horizontal ring
    if (n === 0) continue;
    const q = ring(levels[n - 1]);
    for (let c = 0; c < 4; c++) {
      L(q[c], r[c]);                                                   // leg
      L(q[c], r[(c + 1) % 4]); L(q[(c + 1) % 4], r[c]);                // X bracing on each face
    }
  }
  const top = ring(topZ), peak = P(0, 0, spec.height);
  for (let c = 0; c < 4; c++) L(top[c], peak);
  // Cross-arms: a triangle each side, top chord level, bottom chord rising to the tip; a short line for the insulator.
  for (const arm of spec.arms) {
    const h = halfAt(arm.z), depth = Math.min(3, arm.half * 0.35);
    for (const side of [-1, 1]) {
      const tip = P(0, side * arm.half, arm.z);
      for (const along of [-1, 1]) {
        L(P(along * h, side * h, arm.z), tip);
        L(P(along * h, side * h, arm.z - depth), tip);
      }
      L(tip, P(0, side * arm.half, arm.z - spec.insulator));
    }
  }
}

function solidOf(t, spec) {
  const r = spec.kind === 'pole' ? spec.radius : spec.baseHalf; // an axis-aligned box that covers the base at any heading
  const h = spec.kind === 'pole' ? spec.height : spec.arms[spec.arms.length - 1].z;
  return { min: [t.x - r, t.y - r, t.ground], max: [t.x + r, t.y + r, t.ground + h] };
}

// ---- the line --------------------------------------------------------------------------------------------------------

export function buildOverhead(towers, opts = {}) {
  const step = opts.step > 0 ? opts.step : STEP;
  const seg = [], solids = [], clearances = [], hangs = [], wires = [];
  towers.forEach((t, k) => {
    const spec = specOf(t), d = directionAt(towers, k), p = [d[1], -d[0]]; // p points to the right of travel
    drawTower(seg, t, spec, d, p);
    solids.push(solidOf(t, spec));
    hangs.push(attachments(t, spec, d, p));
  });

  for (let k = 0; k + 1 < towers.length; k++) {
    const A = towers[k], B = towers[k + 1];
    const groundAt = typeof opts.groundAt === 'function' ? opts.groundAt : (x, y) => {
      const L = Math.hypot(B.x - A.x, B.y - A.y) || 1, f = ((x - A.x) * (B.x - A.x) + (y - A.y) * (B.y - A.y)) / (L * L);
      return A.ground + (B.ground - A.ground) * Math.min(1, Math.max(0, f));
    };
    const need = (t) => Math.max(t[A.type || DEFAULT_TYPE], t[B.type || DEFAULT_TYPE]);
    const required = need(MIN_CLEARANCE), requiredOverRoad = need(MIN_CLEARANCE_OVER_ROAD);
    const basis = opts.tensionPerWeight > 0
      ? `at an assumed catenary parameter ${opts.tensionPerWeight} m, not the sag at maximum conductor temperature`
      : clearanceBasis(opts.sagRatio > 0 ? opts.sagRatio : SAG_TO_SPAN);
    let best = { span: k, from: A.id, to: B.id, minClearance: Infinity, at: null, conductor: -1, required, requiredOverRoad,
      source: ESQCR_SOURCE, basis };
    const n = Math.min(hangs[k].length, hangs[k + 1].length);
    for (let j = 0; j < n; j++) {
      const a0 = hangs[k][j], b0 = hangs[k + 1][j];
      const L = Math.hypot(b0[0] - a0[0], b0[1] - a0[1]);
      if (!(L > 0)) continue;
      const a = opts.tensionPerWeight > 0 ? opts.tensionPerWeight : paramFromSag(L, opts.sagRatio > 0 ? opts.sagRatio : SAG_TO_SPAN);
      const c = catenarySpan(L, a0[2], b0[2], a);
      wires.push({ span: k, conductor: j, a: [...a0], b: [...b0], param: a });
      const xy = (s) => [a0[0] + (b0[0] - a0[0]) * s / L, a0[1] + (b0[1] - a0[1]) * s / L];
      const m = Math.max(1, Math.ceil(L / step - 1e-9));                  // samples no more than `step` apart
      let prev = [a0[0], a0[1], a0[2]];
      for (let i = 1; i <= m; i++) {
        const s = L * i / m, [x, y] = xy(s), cur = [x, y, i === m ? b0[2] : c.z(s)];
        seg.push(prev[0], prev[1], prev[2], cur[0], cur[1], cur[2]);
        prev = cur;
      }
      const mc = Math.max(1, Math.ceil(L / CLEAR_STEP)), check = (s) => {
        const [x, y] = xy(s), z = c.z(s), gap = z - groundAt(x, y);
        if (gap < best.minClearance) best = { ...best, minClearance: gap, at: [x, y, z], conductor: j };
      };
      for (let i = 0; i <= mc; i++) check(L * i / mc);
      check(c.sMin);                                                     // the exact lowest point of the wire
    }
    clearances.push(best);
  }
  return { lines: new Float32Array(seg), solids, clearances, wires };
}

Range UI

A JavaScript module in the world folder of GlobalGrid2050 that starts miles (`startMiles`).

renderglobalgrid2050 / solar-design-studio/202609270145-site-world-v3/world/range-ui.mjs · lines 1–43 of 43 · version 2026-09-27 01:45 · Not reached from any entry point (candidate for review)

What it does
It draws its content. Defines startMiles, mountRange, apply, set. 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.
Downstream impact
Used directly by 2 files: Layers UI (globalgrid2050); Layers UI (globalgrid2050).
What it achieves
It starts miles (`startMiles`) and is built from the mount range helper (`mountRange`) and the apply step (`apply`). Range for the wider-area roads and rail (`layers/national.mjs`): 2, 5 or 10 miles, under the Layers panel, shown only while that layer is on. It responds to click events.
Why it matters
Imported by Layers UI.
Application
globalgrid2050 · solar-design-studio/202609270145-site-world-v3/world · JavaScript module
Uses
none found
Used by
imported by Layers UI (import), imported by Layers UI (import)
Produces
RANGES_MI, startMiles, mountRange
Defines here
startMiles, mountRange, apply, set
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/202609270145-site-world-v3/world/range-ui.mjs:1-43 · blob eeac2d5f5c9446eb05e4dd08daa6e3c5938b7ae6 · 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
// Range for the wider-area roads and rail (layers/national.mjs): 2, 5 or 10 miles, under the Layers panel, shown only
// while that layer is on. The choice survives a reload (browser storage, when there is any). Phones start at 2 miles.
export const RANGES_MI = [2, 5, 10];
const KEY = 'world.national.range';

export function startMiles(store, coarse) {
  let v = NaN;
  try { v = Number(store?.getItem(KEY)); } catch { /* no storage */ }
  return RANGES_MI.includes(v) ? v : coarse ? 2 : 5;
}

// host: element to hold the control. layer(): the national layer once loaded (or null). onChange(miles) after a choice.
// Returns { element, show(v), miles(), apply() }: apply() hands the range to the layer (it loads after first switch-on).
export function mountRange(host, { layer = () => null, store = null, coarse = false, onChange = () => {} } = {}) {
  if (!host) return null;
  const doc = host.ownerDocument || document;
  let miles = startMiles(store, coarse);
  const box = doc.createElement('fieldset');
  box.className = 'sun-time national-range';
  box.hidden = true;
  box.innerHTML = '<legend>Roads and rail, wider area: range</legend><div class="row" role="group" aria-label="Range"></div>';
  const row = box.querySelector('.row');
  const buttons = RANGES_MI.map(mi => {
    const b = doc.createElement('button');
    b.type = 'button'; b.dataset.range = String(mi); b.textContent = `${mi} miles`;
    b.addEventListener('click', () => set(mi));
    row.appendChild(b);
    return b;
  });
  function apply() {
    const l = layer();
    if (l && typeof l.setRange === 'function' && typeof l.range === 'function' && Math.abs(l.range() - miles * 1609.344) > 1) l.setRange(miles);
  }
  function set(mi) {
    miles = mi;
    for (const b of buttons) b.setAttribute('aria-pressed', String(Number(b.dataset.range) === miles));
    try { store?.setItem(KEY, String(miles)); } catch { /* private window */ }
    apply(); onChange(miles);
  }
  for (const b of buttons) b.setAttribute('aria-pressed', String(Number(b.dataset.range) === miles));
  host.appendChild(box);
  return { element: box, show(v) { box.hidden = !v; if (v) apply(); }, miles: () => miles, apply, set };
}

Route Tool

A JavaScript module in the world folder of GlobalGrid2050 that works with cables and substations.

Set aside from the main view: 92% of its lines are the same as web/versions/202609262227-site-world/world/route-tool.mjs (graphics-engines-open-source), which stays. (near-copy-of, proposed by families.py). 92% of lines shared with Route Tool; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9242 to graphics-engines-open-source@79e0bd8ee33844835e553fc84d552b6aa1521152 web/versions/202609262227-site-world/world/route-tool.mjs:1-93 f02616000d156992dbdf4444dd5f814ae85d462b
  • sha256 c2ec842566e11fedf8edf15808551d346c401ee1eac7c2ce8c9be659ead6e8ec
  • target sha256 957b34702f805ce200e47951a56975a165b5613ae9ebecaa2fdf3a4f91ae63e4
  • group of 2 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

transformglobalgrid2050 / solar-design-studio/202609270145-site-world-v3/world/route-tool.mjs · lines 1–95 of 95 · version 2026-09-27 01:45 · Not reached from any entry point (candidate for review) · pattern describeControls (shared by 2 files)

What it does
It calculates cables and substations. Defines createRouteTool, snapshot, changed, point, describeControls.
Why it exists in the grid workflow
Domain stage field_execution (path word 'route'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work. Domain terms in the code: cables, substations.
Downstream impact
Used directly by 2 files: Design UI (globalgrid2050); Design UI (globalgrid2050).
What it achieves
It describes controls (`describeControls`) and is built from the snapshot step (`snapshot`) and the changed step (`changed`). A small state machine for drawing a route on the ground, in Walk or Drone view.
Why it matters
Imported by Design UI.
Application
globalgrid2050 · solar-design-studio/202609270145-site-world-v3/world · JavaScript module
Uses
none found
Used by
imported by Design UI (import), imported by Design UI (import), mentioned in Standalone (comment link)
Produces
createRouteTool, describeControls
Defines here
createRouteTool, snapshot, changed, point, describeControls
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/202609270145-site-world-v3/world/route-tool.mjs:1-95 · blob e081aef5643085eff28a8c54388fb0ea6efdafc3 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: duplicate_candidate
// Route tool: a small state machine for drawing a route on the ground, in Walk or Drone view.
// It knows nothing about the DOM, trenches or cables; it only holds an ordered list of points in local
// metres [x, y, z] (east, north, up from the site origin). The page turns clicks into ground points and
// keys into calls; a layer draws state.points. Every change calls onChange(state) once.
//
// Rules:
//   addPoint   appends a point; ignored once the route is finished, or if it repeats the last point.
//   movePoint  moves an existing point (allowed before and after finishing) and selects it.
//   removeLast undoes the last point; ignored once the route is finished (clear starts again).
//   finish     closes the route; needs at least two points.
//   clear      empties the route and reopens it.
// Each method returns true if it changed the route, false if it was ignored.

const MAX_POINTS = 10000;   // one route; route-file.mjs caps a whole file at 100 000 points
const MAX_ABS_M = 1e6;      // local metres; anything further is a bad ground pick, not a route
const SAME_M = 0.01;        // a second click within 1 cm of the last point is a double click, not a point

export function createRouteTool({ onChange = () => {} } = {}) {
  let points = [], finished = false, selected = null;

  const snapshot = () => Object.freeze({
    points: Object.freeze(points.map(p => Object.freeze([...p]))),
    finished, selected
  });
  const changed = () => { onChange(snapshot()); return true; };

  return {
    get state() { return snapshot(); },

    addPoint(p) {
      if (finished || points.length >= MAX_POINTS) return false;
      const q = point(p);
      const last = points[points.length - 1];
      if (last && Math.hypot(q[0] - last[0], q[1] - last[1], q[2] - last[2]) < SAME_M) return false;
      points.push(q);
      selected = points.length - 1;
      return changed();
    },

    movePoint(i, p) {
      if (!Number.isInteger(i) || i < 0 || i >= points.length) return false;
      points[i] = point(p);
      selected = i;
      return changed();
    },

    removeLast() {
      if (finished || !points.length) return false;
      points.pop();
      selected = points.length ? points.length - 1 : null;
      return changed();
    },

    finish() {
      if (finished || points.length < 2) return false;
      finished = true;
      selected = null;
      return changed();
    },

    clear() {
      if (!points.length && !finished) return false;
      points = []; finished = false; selected = null;
      return changed();
    }
  };
}

// Copies and checks one point; throws on anything that is not three finite local-metre numbers.
function point(p) {
  if (!Array.isArray(p) || p.length !== 3) throw Error('a route point is [x, y, z] in metres');
  const q = p.map(Number);
  if (!q.every(v => Number.isFinite(v) && Math.abs(v) <= MAX_ABS_M)) throw Error('a route point needs finite metres within 1000 km of the origin');
  return q;
}

// Lines for the '?' panel while the route tool is active: [keys, meaning] pairs, so the page can render
// them as <dt>/<dd> like the rest of the panel. Plain British English.
export function describeControls({ touch = false } = {}) {
  return touch
    ? [
        ['Tap', 'the ground to add a point'],
        ['Undo', 'removes the last point'],
        ['Done', 'completes the route (two points or more)'],
        ['Clear', 'removes the route and starts again'],
        ['Snap', 'a cable point within 25 m of a substation or pylon moves onto it (ringed)']
      ]
    : [
        ['Click', 'the ground to add a point'],
        ['Backspace', 'removes the last point'],
        ['Enter', 'completes the route (two points or more)'],
        ['Esc', 'removes the route and starts again'],
        ['Snap', 'a cable point within 25 m of a substation or pylon moves onto it (ringed)']
      ];
}

Sun Climate

A JavaScript module in the world folder of GlobalGrid2050 that reads cell index (`readCellIndex`), tiles distance (`tileDistance`), reads cell tile (`readCellTile`) and calculates planar distances (units: kWh), using SHA-256.

renderglobalgrid2050 / solar-design-studio/202609270145-site-world-v3/world/sun-climate.mjs · lines 1–122 of 122 · version 2026-09-27 01:45 · Not reached from any entry point (candidate for review) · pattern tileFor (shared by 2 files)

What it does
It lists and searches its content. Defines 11 functions or classes, including num, text, twelve, readClimate, readCellIndex.
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 1 file: Sun Mode (globalgrid2050).
What it achieves
It reads climate (`readClimate`), reads cell index (`readCellIndex`) and reads cell tile (`readCellTile`). Sun mode, measured-climate data: readers for a site's precomputed sun files (gw-LiDAR `sun-data/src/sun_data.py` and `sun_cells.py`).
Why it matters
Imported by Sun Mode.
Application
globalgrid2050 · solar-design-studio/202609270145-site-world-v3/world · JavaScript module
Uses
none found
Used by
imported by Sun Mode (import)
Produces
MONTHS, QUANTITIES, SHORT_CREDIT, HADUK_SHORT, HADUK_DOI, readClimate, readCellIndex, tileDistance, tileFor, readCellTile, cellValue, climateLines
Defines here
num, text, twelve, readClimate, readCellIndex, tileDistance, tileFor, readCellTile, cellValue, fix, climateLines
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/202609270145-site-world-v3/world/sun-climate.mjs:1-122 · blob 18b2e7fb48bc6de31f7b341b6ed91aed5b419cc8 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
// Sun mode, measured-climate data: readers for a site's precomputed sun files (gw-lidar sun-data/src/sun_data.py
// and sun_cells.py). Pure: no DOM, no fetching. The page fetches each file through the substrate's hash check.
// Every value keeps its source and licence; nothing is shown without them.
//
// <site>/sun/sun-climate.json  format "sun-climate/1": PVGIS 5.3 typical meteorological year at the site centre.
//   { source: { radiation_db, meteo_db, years }, licence: { name, text, url }, attribution: "...",
//     monthly: { sunshine_hours: [12], ghi_kwh_m2: [12], bhi_kwh_m2: [12], ... }, hourly: { file, sha256, ... } }
//   (tmy-hourly.bin, the 8760 hourly values, is not needed by the page and is not fetched.)
// <site>/sun/cells/sun-cells.json  format "gsc1": { tile_m: 256, cell_m: 4, scale: 250, nodata: 255,
//   base: { <quantity>: [12 open-sky monthly values] }, attribution: [..], tiles: [ { key, file, sha256, e0, n0 } ] }
// <site>/sun/cells/tiles/<ix>_<iy>.gsc  little-endian, 32-byte header:
//   0 "GSC1" | 4 u16 version=1 | 6 u16 samples=65 | 8 u16 spacing_mm | 10 u16 months=12 | 12 i32 e0 | 16 i32 n0 (SW)
//   | 20 u16 quantities=4 | 22 u16 scale | 24 u32 nodata_cells | 28 u32 reserved; then u8[samples^2 * 12 * 4],
//   rows south to north, each west to east; per sample 12 months x 4 quantities; value / scale = share of the
//   open-sky monthly base; 255 = unknown. Samples sit on the 4 m grid and share the tile edges.

export const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September',
  'October', 'November', 'December'];
export const QUANTITIES = ['clear_beam_hours', 'clear_direct_kwh_m2', 'sunshine_hours', 'tmy_direct_kwh_m2'];
export const SHORT_CREDIT = 'Sun: PVGIS, EU JRC';
export const HADUK_SHORT = 'Sunshine: Met Office HadUK-Grid, OGL v3.0';
export const HADUK_DOI = '10.5285/789b3065d74a4c948ab05d33556c86d0';

const num = v => (typeof v === 'number' && Number.isFinite(v) ? v : null);
const text = v => (typeof v === 'string' && v.trim() ? v.trim() : '');
const twelve = a => (Array.isArray(a) && a.length === 12 ? a.map(num) : Array(12).fill(null));

// Sunshine hours: the file's "preferred" block names the source. HadUK-Grid (Met Office station observations,
// gridded, 1991-2020 monthly averages; Open Government Licence v3.0) is used when it is preferred and complete;
// otherwise PVGIS's typical-year count (hours with beam >= 120 W/m2). Irradiance is always PVGIS.
// -> { credit, licence, source, short, sunshineSource: 'haduk' | 'pvgis', sunshine: [12] h, pvgisSunshine: [12] h,
//      direct: [12] kWh/m2 (horizontal beam), global: [12] kWh/m2, haduk: { credit, licence, doi } | null }
export function readClimate(j) {
  if (!j || typeof j !== 'object') throw Error('sun-climate.json is not an object');
  if (j.format !== 'sun-climate/1') throw Error(`sun-climate.json format ${j.format} is not sun-climate/1`);
  const credit = text(j.attribution), licence = text(j.licence?.name) || text(j.licence);
  if (!credit || !licence) throw Error('sun-climate.json must carry its attribution and licence');
  const s = j.source || {}, m = j.monthly || {};
  const source = [s.radiation_db, s.meteo_db].filter(Boolean).join(' + ') + (Array.isArray(s.years) ? ` ${s.years.join('-')}` : '');
  const pvgisSunshine = twelve(m.sunshine_hours);
  const out = { credit, licence, source, short: SHORT_CREDIT, sunshineSource: 'pvgis', sunshine: pvgisSunshine, pvgisSunshine,
    direct: twelve(m.bhi_kwh_m2), global: twelve(m.ghi_kwh_m2), haduk: null };
  const hk = j.haduk_grid, hkHours = twelve(hk?.monthly_sunshine_hours);
  const hkCredit = text(hk?.attribution), hkLicence = text(hk?.licence?.name) || text(hk?.licence);
  if (j.preferred?.sunshine_hours === 'haduk_grid' && hkHours.every(v => v !== null) && hkCredit && hkLicence) {
    out.sunshine = hkHours; out.sunshineSource = 'haduk';
    out.haduk = { credit: hkCredit, licence: hkLicence, doi: text(hk.source?.doi) || HADUK_DOI };
    out.short = `${HADUK_SHORT} · ${SHORT_CREDIT}`;
  }
  if (!out.sunshine.some(v => v !== null)) throw Error('sun-climate.json has no monthly sunshine');
  return out;
}

// -> { size, cell, nodata, base: { quantity: [12] }, credit, tiles: [{ key, path, e0, n0, sha256 }] }
export function readCellIndex(j, indexPath = '') {
  if (!j || j.format !== 'gsc1' || !Array.isArray(j.tiles)) throw Error('sun-cell index is not gsc1 with a tiles list');
  const size = num(j.tile_m), cell = num(j.cell_m);
  if (!(size > 0 && cell > 0)) throw Error('sun-cell index needs tile_m and cell_m');
  const base = {};
  for (const q of QUANTITIES) {
    base[q] = twelve(j.base?.[q]);
    if (base[q].some(v => v === null)) throw Error(`sun-cell index has no open-sky base for ${q}`);
  }
  const dir = indexPath.includes('/') ? indexPath.slice(0, indexPath.lastIndexOf('/') + 1) : '';
  const credit = Array.isArray(j.attribution) ? text(j.attribution[0]) : text(j.attribution);
  return { size, cell, nodata: num(j.nodata) ?? 255, base, credit,
    tiles: j.tiles.filter(t => t && t.file && /^[0-9a-f]{64}$/i.test(t.sha256 || '') && Number.isFinite(t.e0) && Number.isFinite(t.n0))
      .map(t => ({ key: String(t.key ?? `${t.e0}_${t.n0}`), path: dir + t.file, e0: t.e0, n0: t.n0, sha256: t.sha256 })) };
}

// Distance in metres from (e, n) to an index tile's square (0 inside).
export const tileDistance = (index, t, e, n) =>
  Math.hypot(Math.max(t.e0 - e, 0, e - t.e0 - index.size), Math.max(t.n0 - n, 0, n - t.n0 - index.size));

// The index tile holding national-grid point (e, n), or null.
export const tileFor = (index, e, n) =>
  index.tiles.find(t => e >= t.e0 && n >= t.n0 && e < t.e0 + index.size && n < t.n0 + index.size) || null;

// Parses a .gsc tile (ArrayBuffer or Uint8Array) -> { e0, n0, samples, spacing, months, quantities, scale, values }.
export function readCellTile(buf) {
  const bytes = buf instanceof Uint8Array ? buf : new Uint8Array(buf);
  if (bytes.length < 32) throw Error('sun-cell tile is too short');
  const v = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
  if (String.fromCharCode(...bytes.subarray(0, 4)) !== 'GSC1' || v.getUint16(4, true) !== 1) throw Error('sun-cell tile is not GSC1 v1');
  const samples = v.getUint16(6, true), spacing = v.getUint16(8, true) / 1000, months = v.getUint16(10, true);
  const quantities = v.getUint16(20, true), scale = v.getUint16(22, true);
  if (months !== 12 || quantities !== QUANTITIES.length || !(samples > 1 && spacing > 0 && scale > 0)) throw Error('sun-cell tile header is not as expected');
  if (bytes.length !== 32 + samples * samples * months * quantities) throw Error('sun-cell tile has the wrong size');
  return { e0: v.getInt32(12, true), n0: v.getInt32(16, true), samples, spacing, months, quantities, scale, values: bytes.subarray(32) };
}

// One quantity for month 1-12 at national-grid point (e, n), nearest 4 m sample, in the base's units (h or kWh/m2);
// null outside the tile or where the horizon is unknown.
export function cellValue(tile, index, e, n, month, quantity) {
  const q = QUANTITIES.indexOf(quantity);
  const i = Math.round((e - tile.e0) / tile.spacing), j = Math.round((n - tile.n0) / tile.spacing);
  if (q < 0 || i < 0 || j < 0 || i >= tile.samples || j >= tile.samples || !(month >= 1 && month <= 12)) return null;
  const raw = tile.values[((j * tile.samples + i) * tile.months + (month - 1)) * tile.quantities + q];
  if (raw === index.nodata) return null;
  return (raw / tile.scale) * index.base[quantity][month - 1];
}

const fix = v => (v >= 10 ? String(Math.round(v)) : v.toFixed(1));

// The readout lines for a month: [] without data. here = { sunshine, direct, open? } on this spot (horizon-shaded;
// open = the open-sky direct base the cells were computed against) or null.
export function climateLines(climate, month, here = null) {
  if (!climate) return [];
  const k = month - 1, name = MONTHS[k], out = [];
  const hrs = climate.sunshine[k], dir = climate.direct[k], glob = climate.global[k];
  const station = climate.sunshineSource === 'haduk' ? ' (Met Office 1991-2020)' : '';
  if (hrs !== null) out.push(`Typical ${name}: ${Math.round(hrs)} h of sunshine${station}` + (glob !== null ? `, ${fix(glob)} kWh/m² on open ground` : ''));
  if (here && here.direct !== null) {
    // The cells give sunshine as PVGIS hours times the share the horizon leaves; with station sunshine preferred,
    // the same share is applied to the station figure for the month.
    const pv = climate.pvgisSunshine?.[k], sun = here.sunshine === null || here.sunshine === undefined ? null
      : climate.sunshineSource === 'haduk' && pv > 0 && hrs !== null ? here.sunshine * (hrs / pv) : here.sunshine;
    out.push(`This spot in ${name}, horizon-shaded: ` + (sun !== null ? `${Math.round(sun)} h of sunshine, ` : '')
      + `${fix(here.direct)} kWh/m² direct` + ((here.open ?? dir) !== null ? ` (open ground ${fix(here.open ?? dir)})` : ''));
  }
  return out;
}