GLOBALGRID2050 / EXPLORE CODE

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

Sun Mode and 1 more file

A JavaScript module in the world folder of GlobalGrid2050 that sets playing (`setPlaying`) and time (`setTime`) and syncs inputs (`syncInputs`) (units: kWh), using SHA-256.

465 lines of JavaScript from globalgrid2050, in 2 files. Topic: Solar and storage design. Section 137 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. Sun Day transform · globalgrid2050 / solar-design-studio/202609270145-site-world-v3/world/sun-day.mjs lines 1–145
  2. Sun Mode interaction · globalgrid2050 / solar-design-studio/202609270145-site-world-v3/world/sun-mode.mjs lines 1–320

Sun Day

A JavaScript module in the world folder of GlobalGrid2050 that scales colour (`scaleColour`), splits into patches (`splitIntoPatches`) and calculates planar distances.

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

What it does
It calculates its inputs. Defines 13 functions or classes, including formatter, zoneParts, zonedToUtc, zoneDay, zoneLabel.
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 splits into patches (`splitIntoPatches`) and is built from the formatter step (`formatter`) and the zone parts helper (`zoneParts`). Sun mode, pure parts: site clock (a named time zone), direct sun over a day against a terrain horizon, and the per-batch light factor that makes grid lines a little brighter on sunlit slopes and dimmer in shadow.
Why it matters
Imported by Sun Mode.
Application
globalgrid2050 · solar-design-studio/202609270145-site-world-v3/world · JavaScript module
Uses
Sun (import)
Used by
imported by Sun Mode (import), mentioned in Standalone (comment link)
Produces
SITE_ZONE, zoneParts, zonedToUtc, zoneDay, zoneLabel, horizonFunction, directAt, directSunDay, LIGHT, groundNormal, lightFactor, scaleColour
Defines here
formatter, zoneParts, zonedToUtc, zoneDay, zoneLabel, horizonFunction, directAt, directSunDay, edge, groundNormal, lightFactor, scaleColour, splitIntoPatches
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-day.mjs:1-145 · blob b24e4c2130464f8fac75502f575b1e94e5deeb28 · 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
// Sun mode, pure parts: site clock (a named time zone), direct sun over a day against a terrain horizon,
// and the per-batch light factor that makes grid lines a little brighter on sunlit slopes and dimmer in shadow.
// No DOM, no clock reads. Times are UTC milliseconds; azimuths are degrees clockwise from north.

import { solarPosition } from './sun.mjs';

const RAD = Math.PI / 180, MINUTE_MS = 60000;
export const SITE_ZONE = 'Europe/London';

// ---------------------------------------------------------------- site clock
const formatters = new Map();
function formatter(timeZone) {
  if (!formatters.has(timeZone)) {
    formatters.set(timeZone, new Intl.DateTimeFormat('en-GB', { timeZone, year: 'numeric', month: '2-digit', day: '2-digit',
      hour: '2-digit', minute: '2-digit', hourCycle: 'h23', timeZoneName: 'short' }));
  }
  return formatters.get(timeZone);
}

// Wall-clock fields in the zone for a moment: { year, month, day, hour, minute, minuteOfDay, offset (min), zone }.
export function zoneParts(ms, timeZone = SITE_ZONE) {
  const p = {};
  for (const { type, value } of formatter(timeZone).formatToParts(new Date(ms))) p[type] = value;
  const year = +p.year, month = +p.month, day = +p.day, hour = +p.hour % 24, minute = +p.minute;
  const wall = Date.UTC(year, month - 1, day, hour, minute);
  const offset = Math.round((wall - Math.floor(ms / MINUTE_MS) * MINUTE_MS) / MINUTE_MS);
  return { year, month, day, hour, minute, minuteOfDay: hour * 60 + minute, offset, zone: p.timeZoneName || 'UTC' };
}

// The UTC moment for a wall-clock date and minute of day in the zone (the later reading in a repeated hour).
export function zonedToUtc(year, month, day, minuteOfDay, timeZone = SITE_ZONE) {
  const wall = Date.UTC(year, month - 1, day, 0, minuteOfDay);
  let t = wall - zoneParts(wall, timeZone).offset * MINUTE_MS;
  t = wall - zoneParts(t, timeZone).offset * MINUTE_MS;
  return t;
}

// The zone's local day around a moment, as UTC milliseconds [start, end).
export function zoneDay(ms, timeZone = SITE_ZONE) {
  const p = zoneParts(ms, timeZone);
  const start = zonedToUtc(p.year, p.month, p.day, 0, timeZone);
  const next = new Date(Date.UTC(p.year, p.month - 1, p.day + 1));
  return { start, end: zonedToUtc(next.getUTCFullYear(), next.getUTCMonth() + 1, next.getUTCDate(), 0, timeZone), key: `${p.year}-${p.month}-${p.day}` };
}

// "yyyy-mm-dd" and "hh:mm" in the zone, for inputs and captions.
export function zoneLabel(ms, timeZone = SITE_ZONE) {
  const p = zoneParts(ms, timeZone), d = v => String(v).padStart(2, '0');
  return { date: `${p.year}-${d(p.month)}-${d(p.day)}`, time: `${d(p.hour)}:${d(p.minute)}`, zone: p.zone, parts: p };
}

// ---------------------------------------------------------------- horizon and direct sun
// A horizon profile: n angles (degrees) at azimuths k * 360 / n clockwise from grid north; NaN is no data.
// Returns az (grid degrees) -> angle, linear between neighbours; unknown directions count as a flat horizon.
export function horizonFunction(profile) {
  if (!profile || !profile.length) return () => 0;
  const n = profile.length;
  return az => {
    const f = ((az % 360) + 360) % 360 / (360 / n), k0 = Math.floor(f) % n, k1 = (k0 + 1) % n, w = f - Math.floor(f);
    const a = profile[k0], b = profile[k1];
    if (!Number.isFinite(a) || !Number.isFinite(b)) return Number.isFinite(a) ? a : Number.isFinite(b) ? b : 0;
    return a * (1 - w) + b * w;
  };
}

// Is the sun above the local horizon at this moment? convergence: true north minus grid north (degrees).
export function directAt(lat, lon, ms, horizon, convergence = 0) {
  const s = solarPosition(lat, lon, ms);
  return s.elevation > 0 && s.elevation > horizon(s.azimuth - convergence);
}

// Direct sun across [start, end): hours in direct sun, hours of daylight (sun above a flat horizon),
// and the first and last moments of direct sun (to the minute), or null when there is none.
export function directSunDay(lat, lon, start, end, horizon = () => 0, { stepMinutes = 5, convergence = 0 } = {}) {
  const step = stepMinutes * MINUTE_MS, flat = () => 0;
  let direct = 0, daylight = 0, first = null, last = null, prev = false, prevT = start;
  for (let t = start; t < end; t += step) {
    const mid = Math.min(t + step / 2, end - 1), dt = Math.min(step, end - t);
    const on = directAt(lat, lon, mid, horizon, convergence);
    if (on) direct += dt;
    if (directAt(lat, lon, mid, flat)) daylight += dt;
    if (on && !prev) { const c = edge(lat, lon, prevT, mid, horizon, convergence, true); if (first === null) first = c; }
    if (!on && prev) last = edge(lat, lon, prevT, mid, horizon, convergence, false);
    prev = on; prevT = mid;
  }
  if (prev) last = end;
  return { directHours: direct / 3600000, daylightHours: daylight / 3600000, first, last };
}

// Bisection to the minute between a and b, where direct sun switches on (rising) or off.
function edge(lat, lon, a, b, horizon, convergence, rising) {
  while (b - a > MINUTE_MS) {
    const m = (a + b) / 2, on = directAt(lat, lon, m, horizon, convergence);
    if (on === rising) b = m; else a = m;
  }
  return Math.round((a + b) / 2 / MINUTE_MS) * MINUTE_MS;
}

// ---------------------------------------------------------------- light cue for grid lines
export const LIGHT = Object.freeze({ min: 0.72, max: 1.22, night: 0.8, patch: 64, wrap: 16 });

// Upward unit normal of the ground around (x, y) from four heights `half` metres away; null without ground.
export function groundNormal(heightAt, x, y, half = LIGHT.patch / 2) {
  const e = heightAt(x + half, y), w = heightAt(x - half, y), n = heightAt(x, y + half), s = heightAt(x, y - half);
  if (![e, w, n, s].every(Number.isFinite)) return null;
  const gx = (e - w) / (2 * half), gy = (n - s) / (2 * half), len = Math.hypot(gx, gy, 1);
  return [-gx / len, -gy / len, 1 / len];
}

// Colour factor for a patch. sun: { direction: [x, y, z] in world axes, elevation }. normal: ground normal or
// null (flat assumed). shadowed: fraction 0..1 of the patch in terrain shadow. Flat sunlit ground gives 1;
// slopes facing the sun are brighter, slopes facing away and shadow dimmer, within LIGHT.min..LIGHT.max.
export function lightFactor(sun, normal, shadowed = 0) {
  if (!sun || !(sun.elevation > 0)) return LIGHT.night;
  const n = normal || [0, 0, 1], d = sun.direction;
  const cosI = Math.max(0, n[0] * d[0] + n[1] * d[1] + n[2] * d[2]);
  const ratio = Math.min(2, cosI / Math.max(Math.sin(sun.elevation * RAD), 0.1)); // 1 on flat ground
  const lit = 1 + 0.22 * Math.max(-1, Math.min(1, ratio - 1));
  const f = lit * (1 - shadowed) + LIGHT.min * shadowed;
  return Math.min(LIGHT.max, Math.max(LIGHT.min, f));
}

export const scaleColour = (c, f) => [Math.min(1, c[0] * f), Math.min(1, c[1] * f), Math.min(1, c[2] * f), Math.min(1, c[3] * f)];

// Splits a line batch into square patches of `size` metres by segment midpoint (in local metres), so each
// patch can take its own colour factor. Keys wrap every `wrap` patches, so the set of GPU buffers stays
// bounded however far the viewer walks. Returns [{ ix, iy, cx, cy, key, version, origin, positions }].
export function splitIntoPatches(batch, size = LIGHT.patch, wrap = LIGHT.wrap) {
  const p = batch.positions, o = batch.origin || [0, 0, 0], bins = new Map();
  for (let k = 0; k + 5 < p.length; k += 6) {
    const mx = (p[k] + p[k + 3]) / 2 + o[0], my = (p[k + 1] + p[k + 4]) / 2 + o[1];
    const ix = Math.floor(mx / size), iy = Math.floor(my / size), id = ix + ',' + iy;
    let bin = bins.get(id);
    if (!bin) bins.set(id, bin = { ix, iy, idx: [] });
    bin.idx.push(k);
  }
  const out = [], m = v => ((v % wrap) + wrap) % wrap;
  for (const { ix, iy, idx } of bins.values()) {
    const positions = new Float32Array(idx.length * 6);
    idx.forEach((k, i) => positions.set(p.subarray(k, k + 6), i * 6));
    out.push({ ix, iy, cx: (ix + 0.5) * size, cy: (iy + 0.5) * size, key: `${batch.key}#${m(ix)},${m(iy)}`,
      version: `${batch.version}#${ix},${iy}`, origin: batch.origin, positions });
  }
  return out;
}

Sun Mode

A JavaScript module in the world folder of GlobalGrid2050 that sets playing (`setPlaying`) and time (`setTime`) and syncs inputs (`syncInputs`) (units: kWh), using SHA-256.

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

What it does
It draws its content. Defines 17 functions or classes, including el, hours, attachSunMode, back, setOn. 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
Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
What it achieves
It sets playing (`setPlaying`), sets time (`setTime`) and syncs inputs (`syncInputs`). One Sun toggle in the Layers panel (the dash keeps Walk, Drone, Find, Design, Layers). It responds to click, change and input events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · solar-design-studio/202609270145-site-world-v3/world · JavaScript module
Uses
Sun (import), Bng (import), Sun Day (import), Sun Climate (import), Layers (import)
Used by
none found
Produces
PLAY_FPS, SPEEDS, LIT_KEYS, GEOMETRIC, CELL_NEAR_M, attachSunMode
Defines here
el, hours, attachSunMode, back, setOn, setPlaying, setTime, enableShade, refresh, syncInputs, loadData, cellHere, tilesNear, trimCells, factorFor, write, update
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-mode.mjs:1-320 · blob 81996670c20661582e9a0c0a2542737bd64e3479 · 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
// Sun mode: one Sun toggle in the Layers panel (the dash keeps Walk, Drone, Find, Design, Layers). When on, a slim time bar along the bottom
// (date, time of day, play/pause at a chosen speed; opens at the current hour today, site time), the sun's
// direction for the shade layer, grid lines a little brighter on sunlit slopes and dimmer in shadow, and a
// readout where you stand: elevation, bearing, direct-sun hours today from the terrain horizon, first and
// last direct sun. When the site offers measured sun climate (manifest site.sun), typical monthly sunshine
// and horizon-shaded irradiation for the month are shown too, with the source credited in the footer.
// Until then the readout says "clear sky, terrain only". Nothing here calls a live API; every file is local
// and hash-checked. The page draws only while playing (up to PLAY_FPS) or when something changes.

import { solarPosition, sunDirection, gridConvergence, MIN_MS, MAX_MS } from './sun.mjs';
import { bngToWgs84 } from './bng.mjs';
import { SITE_ZONE, zoneParts, zonedToUtc, zoneDay, zoneLabel, horizonFunction, directSunDay, groundNormal, lightFactor,
  scaleColour, splitIntoPatches, LIGHT } from './sun-day.mjs';
import { readClimate, readCellIndex, readCellTile, tileFor, tileDistance, cellValue, climateLines } from './sun-climate.mjs';
import { makeApi } from './layers.mjs';

export const PLAY_FPS = 30;
export const SPEEDS = [{ minutes: 10, label: '10 min/s' }, { minutes: 60, label: '1 h/s' }, { minutes: 180, label: '3 h/s' }];
export const LIT_KEYS = ['ground-grid/minor', 'ground-grid/major'];
export const GEOMETRIC = 'Clear sky, terrain only';
export const CELL_NEAR_M = 96, CELL_KEEP = 4;
const HOUR_MS = 3600000, FOOT = 'var(--foot, 20px)', SUN_H = 'var(--sun-h, 0px)';

const CSS = `
#sun-row { margin: 0 0 8px; }
#sun-bar { position: fixed; left: 8px; right: 8px; bottom: calc(${FOOT} + 4px); box-sizing: border-box; background: var(--panel);
  border: 1px solid var(--edge); border-radius: 6px; padding: 4px 8px 6px; }
#sun-bar[hidden] { display: none; }
#sun-readout { margin: 0 0 4px; color: var(--dim); font-size: 11px; line-height: 15px; }
#sun-readout span { display: block; } #sun-readout .lead { color: var(--text); }
#sun-bar .sun-row { display: flex; gap: 6px; align-items: center; }
#sun-bar button, #sun-bar input[type="date"], #sun-bar select { min-height: var(--btn, 30px); background: #111; color: var(--text);
  border: 1px solid var(--edge); border-radius: 4px; font: inherit; box-sizing: border-box; }
#sun-play { min-width: var(--btn, 30px); cursor: pointer; }
#sun-play[aria-pressed="true"] { border-color: var(--line); }
#sun-hour { flex: 1 1 120px; min-width: 80px; height: var(--btn, 30px); margin: 0; accent-color: #9cdbff; }
#attribution .sun-credit[hidden] { display: none; }
body.sun-on #help-toggle { bottom: calc(${FOOT} + ${SUN_H} + 10px); }
body.sun-on #pad { bottom: calc(${FOOT} + ${SUN_H} + 16px); }
@media (max-width: 600px) { #sun-bar .sun-row { flex-wrap: wrap; } #sun-hour { flex-basis: 100%; order: -1; } }
@media (pointer: fine) {
  body.sun-on #where { bottom: calc(${FOOT} + ${SUN_H} + 12px); }
  body.sun-on #help { bottom: calc(${FOOT} + ${SUN_H} + 46px); max-height: calc(100vh - ${FOOT} - ${SUN_H} - 110px); }
  body.sun-on:has(#help:not([hidden])) #lift { right: calc(min(320px, 100vw - 20px) + 20px); } /* Up/Down beside Controls */
  body.sun-on #layers, body.sun-on #design { max-height: calc(100vh - var(--btn, 30px) - 64px - ${FOOT} - ${SUN_H}); } /* above the time bar */
}
@media (pointer: coarse) {
  #sun-bar button, #sun-bar input[type="date"], #sun-bar select { min-height: 44px; }
  #sun-play { min-width: 44px; } #sun-hour { height: 44px; }
  body.sun-on #lift, body.sun-on #layers:not([hidden]) ~ #lift, body.sun-on #design:not([hidden]) ~ #lift {
    bottom: calc(${FOOT} + ${SUN_H} + 64px); transform: none; }
  body.sun-on #help, body.sun-on #layers, body.sun-on #find.find-panel {
    max-height: calc(100vh - var(--btn, 44px) - 40px - ${FOOT} - 180px - ${SUN_H}); }
  body.sun-on #plan { bottom: calc(${FOOT} + ${SUN_H} + 180px); } /* the plan inset stays above the joypad */
  body.sun-on[data-panel="design"] #sun-bar { display: none; } /* the Design sheet takes the bottom of the screen */
}`;

const el = (tag, attrs = {}, text = '') => {
  const e = document.createElement(tag);
  for (const [k, v] of Object.entries(attrs)) e.setAttribute(k, v);
  if (text) e.textContent = text;
  return e;
};
const hours = h => { const m = Math.round(h * 60); return `${Math.floor(m / 60)} h ${String(m % 60).padStart(2, '0')} min`; };

// h: { pos(), heightAt(x, y), origin() -> { e, n }, site() -> manifest site, layer(id), base (URL of the world
//      folder), redraw(), onPlay(), onToggle?(on), setShade?(on) (the page switches the shadow layer), now?(), zone? }. Returns the hooks the substrate calls each frame.
export function attachSunMode(h) {
  const zone = h.zone || SITE_ZONE, clock = h.now || (() => Date.now());
  const api = makeApi(h.base || new URL('./world/', location.href).href, { invalidate: () => h.redraw() });
  let on = false, playing = false, speed = 60, utcMs = Math.floor(clock() / HOUR_MS) * HOUR_MS;
  let place = null, sunNow = null, sunKey = '';
  let dayKey = '', dayInfo = null, lastLines = [], lastHeight = -1;
  let climate = null, cells = null, dataState = 'idle', note = '';
  const cellTiles = new Map(), cellLoading = new Set(), splits = new Map(), factors = new Map();

  // ------------------------------------------------------------ DOM
  const style = el('style'); style.textContent = CSS; document.head.append(style);
  const toggle = el('button', { type: 'button', id: 'sun-toggle', 'aria-pressed': 'false', 'aria-label': 'Sun',
    'aria-controls': 'sun-bar', title: 'Sun: light, shade and time of day' }, '☀ Sun');
  const layers = document.getElementById('layers'), head = layers?.querySelector('.head'), sunRow = el('div', { class: 'row', id: 'sun-row' });
  sunRow.append(toggle);
  if (head) head.after(sunRow); else (layers || document.getElementById('help'))?.append(sunRow);
  const bar = el('section', { id: 'sun-bar', 'aria-label': 'Sun and time of day' });
  bar.hidden = true;
  const readout = el('p', { id: 'sun-readout' });
  const row = el('div', { class: 'sun-row' });
  const play = el('button', { type: 'button', id: 'sun-play', 'aria-pressed': 'false', 'aria-label': 'Play' }, '▶');
  const date = el('input', { type: 'date', id: 'sun-date', 'aria-label': 'Date', min: '1800-01-01', max: '2100-12-31' });
  const hour = el('input', { type: 'range', id: 'sun-hour', 'aria-label': 'Time of day', min: '0', max: '1439', step: '15' });
  const pace = el('select', { id: 'sun-speed', 'aria-label': 'Playing speed' });
  for (const s of SPEEDS) { const o = el('option', { value: String(s.minutes) }, s.label); if (s.minutes === speed) o.selected = true; pace.append(o); }
  row.append(play, date, hour, pace);
  bar.append(readout, row);
  document.body.append(bar);
  const credit = el('span', { class: 'sun-credit' });
  credit.hidden = true;
  document.getElementById('attribution')?.append(credit);

  // A pointer click hands the keys back to the world (Space flies up); a keyboard press keeps focus here.
  const back = e => { if (e.detail > 0) document.getElementById('view')?.focus(); };
  toggle.addEventListener('click', e => { setOn(!on); back(e); });
  play.addEventListener('click', e => { setPlaying(!playing); back(e); });
  pace.addEventListener('change', () => { speed = Number(pace.value) || 60; });
  date.addEventListener('change', () => {
    const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(date.value);
    if (m) setTime(zonedToUtc(+m[1], +m[2], +m[3], zoneParts(utcMs, zone).minuteOfDay, zone));
  });
  hour.addEventListener('input', () => { const p = zoneParts(utcMs, zone); setTime(zonedToUtc(p.year, p.month, p.day, Number(hour.value), zone)); });

  // ------------------------------------------------------------ state
  function setOn(next) {
    on = !!next;
    toggle.setAttribute('aria-pressed', String(on));
    bar.hidden = !on;
    document.body.classList.toggle('sun-on', on);
    if (!on && playing) setPlaying(false);
    if (!on) cellTiles.clear();
    if (on && dataState === 'idle') loadData();
    enableShade(true);
    h.onToggle?.(on);
    credit.hidden = !(on && climate);
    refresh();
    h.redraw();
  }
  function setPlaying(next) {
    playing = !!next && on;
    play.setAttribute('aria-pressed', String(playing));
    play.setAttribute('aria-label', playing ? 'Pause' : 'Play');
    play.textContent = playing ? '❚❚' : '▶';
    h.onPlay?.(playing);
  }
  function setTime(ms) {
    utcMs = Math.min(MAX_MS, Math.max(MIN_MS, Math.round(ms)));
    refresh();
    h.redraw();
  }
  let shadeByUs = false; // Sun switched the terrain shadow on, so Sun switches it off again
  function enableShade(changed = false) {
    if (h.setShade) { // the page's Layers panel owns the shadow switch (it loads the layer on first use and credits it)
      if (!changed) return;
      if (on) { shadeByUs = !h.layer('shade')?.enabled; h.setShade(true); } else if (shadeByUs) { shadeByUs = false; h.setShade(false); }
      return;
    }
    const shade = h.layer('shade');
    if (shade && typeof shade.setEnabled === 'function' && shade.enabled !== on) shade.setEnabled(on);
  }

  // Place and sun: the viewer's latitude and longitude (to 250 m), then the sun for the current moment.
  function refresh() {
    const o = h.origin(), [x, y] = h.pos(), e = o.e + Math.round(x / 250) * 250, n = o.n + Math.round(y / 250) * 250;
    if (!place || place.e !== e || place.n !== n) {
      const g = bngToWgs84(e, n);
      place = { e, n, lat: g.lat, lon: g.lon, convergence: gridConvergence(g.lat, g.lon), key: `${e},${n}` };
    }
    const key = `${utcMs}@${place.key}`;
    if (key !== sunKey) {
      sunKey = key;
      const s = solarPosition(place.lat, place.lon, utcMs), azimuth = ((s.azimuth - place.convergence) % 360 + 360) % 360;
      sunNow = { azimuth, elevation: s.elevation, trueAzimuth: s.azimuth, direction: sunDirection({ azimuth, elevation: s.elevation }) };
    }
    syncInputs();
  }
  function syncInputs() {
    const l = zoneLabel(utcMs, zone);
    if (date.value !== l.date) date.value = l.date;
    const m = String(l.parts.minuteOfDay);
    if (hour.value !== m && document.activeElement !== hour) hour.value = m;
  }

  // ------------------------------------------------------------ measured sun climate (optional)
  function loadData() {
    const cfg = h.site()?.sun;
    if (!cfg) { dataState = 'none'; return; }
    dataState = 'loading';
    const jobs = [];
    if (cfg.climate?.path && cfg.climate?.sha256) {
      jobs.push(api.fetchJSON(cfg.climate.path, cfg.climate.sha256).then(j => {
        climate = readClimate(j);
        credit.textContent = ` · ${climate.short}`; // HadUK-Grid sunshine (OGL, with its DOI) and PVGIS irradiance, both credited
        credit.title = [climate.haduk && `${climate.haduk.credit} Licence: ${climate.haduk.licence}.`,
          `${climate.credit} ${climate.licence}.`].filter(Boolean).join(' ');
      }));
    }
    if (cfg.cells?.index && cfg.cells?.sha256) {
      jobs.push(api.fetchJSON(cfg.cells.index, cfg.cells.sha256).then(j => { cells = readCellIndex(j, cfg.cells.index); }));
    }
    Promise.allSettled(jobs).then(r => {
      const bad = r.filter(x => x.status === 'rejected').map(x => x.reason?.message || String(x.reason));
      note = bad.join('; ');
      dataState = 'ready';
      credit.hidden = !(on && climate);
      dayKey = '';
      h.redraw();
    });
  }
  // Sun-cell tiles (about 200 kB each) load only while Sun mode is on, only the tile under the viewer and those
  // within CELL_NEAR_M of it, and at most CELL_KEEP are kept; the farthest go first. Turning Sun off drops them.
  function cellHere(x, y, month) {
    if (!cells) return null;
    const o = h.origin(), e = o.e + x, n = o.n + y;
    for (const t of tilesNear(cells, e, n)) {
      if (cellTiles.has(t.key) || cellLoading.has(t.key) || cellLoading.size >= 2) continue;
      cellLoading.add(t.key);
      api.fetchVerified(t.path, t.sha256).then(b => { if (on) cellTiles.set(t.key, readCellTile(b)); })
        .catch(err => { note = `sun cell ${t.key}: ${err.message}`; cellTiles.set(t.key, null); })
        .finally(() => { cellLoading.delete(t.key); trimCells(e, n); dayKey = ''; h.redraw(); });
    }
    const t = tileFor(cells, e, n), tile = t && cellTiles.get(t.key);
    if (!tile) return null;
    const direct = cellValue(tile, cells, e, n, month, 'tmy_direct_kwh_m2');
    return direct === null ? null : { direct, sunshine: cellValue(tile, cells, e, n, month, 'sunshine_hours'),
      open: cells.base.tmy_direct_kwh_m2[month - 1] };
  }
  function tilesNear(index, e, n) {
    return index.tiles.map(t => ({ t, d: tileDistance(index, t, e, n) })).filter(x => x.d <= CELL_NEAR_M)
      .sort((a, b) => a.d - b.d).slice(0, CELL_KEEP).map(x => x.t);
  }
  function trimCells(e, n) {
    if (cellTiles.size <= CELL_KEEP) return;
    const far = cells.tiles.filter(t => cellTiles.has(t.key)).sort((a, b) => tileDistance(cells, b, e, n) - tileDistance(cells, a, e, n));
    for (const t of far.slice(0, cellTiles.size - CELL_KEEP)) cellTiles.delete(t.key);
  }

  // ------------------------------------------------------------ light cue on grid lines
  function factorFor(p, ctx, shade) {
    const id = `${p.ix},${p.iy}`;
    let f = factors.get(id);
    if (!f || f.gv !== ctx.groundVersion) {
      if (factors.size > 2000) factors.clear();
      f = { gv: ctx.groundVersion, normal: groundNormal(ctx.heightAt, p.cx, p.cy, LIGHT.patch / 2), sunKey: '', value: 1 };
      factors.set(id, f);
    }
    if (f.sunKey !== sunKey) {
      let known = 0, dark = 0;
      if (shade && sunNow.elevation > 0) {
        for (let j = -1; j <= 1; j++) for (let i = -1; i <= 1; i++) {
          const a = shade.horizonAngle(p.cx + i * LIGHT.patch / 3, p.cy + j * LIGHT.patch / 3, sunNow.azimuth);
          if (Number.isFinite(a)) { known++; if (sunNow.elevation < a) dark++; }
        }
      }
      f.value = lightFactor(sunNow, f.normal, known ? dark / known : 0);
      f.sunKey = sunKey;
    }
    return f.value;
  }

  // ------------------------------------------------------------ readout
  function write(lines) {
    if (lines.length === lastLines.length && lines.every((l, i) => l === lastLines[i])) return;
    lastLines = lines;
    readout.replaceChildren(...lines.map((l, i) => el('span', i ? {} : { class: 'lead' }, l)));
    const px = bar.offsetHeight;
    if (px !== lastHeight) { lastHeight = px; document.documentElement.style.setProperty('--sun-h', px + 'px'); }
  }
  function update(ctx) {
    const [x, y] = ctx.pos, shade = h.layer('shade');
    const profile = typeof shade?.horizonProfile === 'function' ? shade.horizonProfile(x, y) : null;
    const day = zoneDay(utcMs, zone), label = zoneLabel(utcMs, zone);
    const key = `${Math.floor(x / 4)},${Math.floor(y / 4)}|${day.key}|${profile ? 'h' : '-'}|${place.key}`;
    if (key !== dayKey) {
      dayKey = key;
      dayInfo = directSunDay(place.lat, place.lon, day.start, day.end, horizonFunction(profile), { convergence: place.convergence });
      dayInfo.horizon = !profile ? 'none' : profile.some(v => !Number.isFinite(v)) ? 'partial' : 'full';
    }
    const s = sunNow, t = ms => zoneLabel(ms, zone).time;
    const lead = `${label.date} ${label.time} ${label.zone} · ` + (s.elevation > 0
      ? `sun ${s.elevation.toFixed(1)}° up, bearing ${Math.round(s.trueAzimuth)}° from true north`
      : 'sun below the horizon');
    const d = dayInfo;
    let here = d.first === null ? `Here today: no direct sun (${hours(d.daylightHours)} of daylight)`
      : `Here today: ${hours(d.directHours)} of direct sun, first ${t(d.first)}, last ${t(d.last)}`;
    if (d.horizon === 'none') here += ' · terrain horizon not loaded here';
    else if (d.horizon === 'partial') here += ' · horizon partly beyond the site';
    const month = label.parts.month, extra = climateLines(climate, month, cellHere(x, y, month));
    write([lead, here, ...(extra.length ? extra : [GEOMETRIC])]);
  }

  return {
    PLAY_FPS,
    on: () => on,
    playing: () => playing,
    // Moves the clock on by a frame's interval while playing.
    advance(intervalMs) {
      if (!playing) return;
      const next = utcMs + (Math.min(intervalMs, 100) / 1000) * speed * 60000;
      if (next >= MAX_MS) setPlaying(false);
      utcMs = Math.min(MAX_MS, next);
      refresh();
    },
    // The sun for the layers (grid azimuth, elevation), or undefined when Sun mode is off.
    sun: () => (on && sunNow ? { azimuth: sunNow.azimuth, elevation: sunNow.elevation } : undefined),
    // Splits the ground grid into patches and scales each patch's colour by its light factor.
    decorate(batches, ctx) {
      if (!on || !sunNow) return batches;
      const shade = typeof h.layer('shade')?.horizonAngle === 'function' ? h.layer('shade') : null, out = [];
      for (const b of batches) {
        if (!LIT_KEYS.includes(b.key) || !b.positions) { out.push(b); continue; }
        let sp = splits.get(b.key);
        if (!sp || sp.version !== b.version || sp.positions !== b.positions) {
          sp = { version: b.version, positions: b.positions, patches: splitIntoPatches(b) };
          splits.set(b.key, sp);
        }
        for (const p of sp.patches) out.push({ key: p.key, version: p.version, origin: p.origin, positions: p.positions,
          color: scaleColour(b.color, factorFor(p, ctx, shade)) });
      }
      return out;
    },
    afterDraw(ctx) {
      if (!on) return;
      enableShade();
      refresh();
      update(ctx);
    },
    setTime, setOn, setPlaying,
    debug: () => ({ on, playing, speed, utcMs, sun: sunNow, place, day: dayInfo, lines: [...lastLines], dataState, note,
      climate: !!climate, cells: !!cells, cellTiles: [...cellTiles.keys()], patches: [...splits.values()].reduce((n, s) => n + s.patches.length, 0),
      factors: [...factors.values()].map(f => f.value) })
  };
}