diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 00000000..77100e3b
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,5 @@
+# The ridge bake is addressed by its bytes (bake_id covers the manifest text and the tile files): public/ridge is checked out exactly as committed, whatever
+# core.autocrlf says, so a Windows working tree serves the bytes its directory name was hashed from.
+public/ridge/** -text
+# The baker's inputs and schema are text, read the same everywhere.
+scripts/ridge-bake/**/*.json text eol=lf
diff --git a/docs/gamecult/ridge-backdrop-target.md b/docs/gamecult/ridge-backdrop-target.md
index a2529901..6baeea5f 100644
--- a/docs/gamecult/ridge-backdrop-target.md
+++ b/docs/gamecult/ridge-backdrop-target.md
@@ -6,9 +6,11 @@ The scene's bottom silhouette is replaced by baked A+D ridge planes. The baker i
The live noise ridge is nearly invisible on a phone (about 1.35:1 against the darkest sky) because every ridge pixel is lifted to the text-contrast floor, and the star dots show between nav and header glyphs because the shell is transparent. Meta, 2026-11-13: do not polish the old backdrop; ship the A+D ridge pipeline (round 2 mockup: https://minds.gamecult.org/nibu/ridge-mockups-ad/).
## Ends
-- One owner per decision: the baker owns ridge geometry and shading; the runtime owns only frame choice, blending, camera drift and compositing. No ridge geometry is computed in the browser.
+- One owner per decision: the baker owns ridge geometry and shading; the runtime owns only the ring's residency, the camera's pose against its heading, blending and compositing. No ridge geometry is computed in the browser.
- Nothing from the scene paints above app content: the scene is one stacking context at the back of the app, and nothing it creates has its own z-index or lives outside it.
- Phone cost is bounded: no per-frame script for the ridge, decoded size and fetched size gated in CI.
+- The ring is the bake and the heading is unbounded: the whole 360 degrees ships as azimuth tiles, the client holds only the arc it is about to need and fetches more as the view turns, and nothing caps the heading: it is unwrapped within a stretch of motion and `ridge/heading.ts` `normalize` brings it into [0, 360) before each one, so no angle or pixel position grows with uptime, while `ridge/ring.ts` is the one place that reasons about the wrap at 0 / 360.
+- Motion is derived, not authored: a card's scale and shift come each second from the heading, the camera's angle on its circle and the viewer's offset (one pose, one owner: `ridge/heading.ts`, whose every change starts a segment from the pose the view has, and whose eases keep each pose inside the baked bound) and the card's distance (`ridge/view.ts` `cardPose`), and ride the compositor as one animation per card.
- The baker has fixtures with known right answers (the far-plateau spike, chain-end taper, slot union, seam) and a mutation runner that must kill each re-introduced cause.
- A baked asset names its baker version, DEM source and licence in a validated manifest; the credits shown in the Sky menu come from the manifest.
diff --git a/harness/scene/README.md b/harness/scene/README.md
index 514bb7dc..217e2241 100644
--- a/harness/scene/README.md
+++ b/harness/scene/README.md
@@ -21,11 +21,25 @@ directory whose ancestors hold no empty `package.json` (esbuild reads them).
Timings from SwiftShader are CPU time: use them for the split between passes and for before and
after of one change, never as a phone frame time.
+## Ridge live scene
+
+`ridgeLive.html` is one live scene (tier 'full', the sky plate and the cards on the compositor) filling the window, for a driver to turn and screenshot: `?h=214&sun=232:22&speed=6` (start heading, the sun's azimuth and elevation, degrees a second of rotation),
+`?sky=night&lines=1`. `window.live` offers `hold(h)`, `pose()`, `plate()`, `left()` (the plate's left edge on the page) and `plateCost()` (ms of main thread to paint one plate here); `window.longTasks` lists the tasks over 50 ms.
+A held heading's sun lands within a tenth of a pixel of the column the heading owner says, across re-centres of the plate.
+
## Ridge look sheet
-Renders the Vienna cards (`public/ridge/vienna-6815bb9dca99`) lit for six sky states (dawn 2, morning 15, noon 55, golden 6, dusk -3, night -30 degrees of sun)
-by a set of looks (`RidgeLook`, `src/app/features/scene/ridge/lightCards.ts`, the one owner of look values), one 480x270 canvas per cell at heading 0. The sky
-behind a cell is the app's own (`makePhysicalSky` + `paintSky`, upscaled), without the sun disc, stars or clouds. Not shipped.
+Renders a baked place (`?place=`, the index default otherwise) lit for six sky states (dawn 2, morning 15, noon 55, golden 6, dusk -3, night -30 degrees of sun)
+by a set of looks (`RidgeLook`, `src/app/features/scene/ridge/lightCards.ts`, the one owner of look values), one 480x270 canvas per cell, drawn by the app's own still
+path (`createRidgeScene` at tier 'still' over a `createBackdrop` of the tiles round the heading), at the rest azimuth unless `?views=` says otherwise. The sky
+behind a cell is the app's own, without clouds. Not shipped.
+
+ ...ridgeSheet.html?views=214:0:200,0:0:200,214:90:98.2&sky=2 # one column per view heading:phi:offset (degrees, degrees, metres) at one sky (an index of SKIES)
+
+`&sun=100:6` puts the sun of that sky at compass azimuth 100, 6 degrees up (the stars are those of the moment the sheet is opened): a sun at the heading's side shows where the turned sky puts it, `&sky=5&lines=1` is the night.
+
+A heading of 0 or 360 is across north; a phi other than 0 is the offset-only rotation mode (the camera circling the centre, the view direction staying); the offset is
+clamped to the place's range as the app does (phi 0: `camera.r_max_forward_m`, another phi: `camera.r_max_m`).
npx vite --port 5199 # from the repo root; the app's vite config serves the page and public/
http://localhost:5199/harness/scene/ridgeSheet.html # four presets x six skies
@@ -46,4 +60,4 @@ Presets (`PRESETS` in `ridgeSheet.ts`; swiss and poster take every key not named
| painterly | DEFAULT_LOOK: groundNoise 0.35, cloudShadows 0.5, nearWarm 0.6, hazeScale 2, inkScale 0.4, celBands 3, celSoftness 0.05, celAmbientAway 0.7 |
| painterly-cel-2 / -3 / -4 | painterly with celBands 2 / 3 / 4 |
-Night sets (`ridgeSheet.html`): `?moments=2026-11-24T22:00Z,2026-12-09T20:00Z` pins explicit UTC moments (the sun, moon and stars are those of the moment); `?night=1` renders the next new moon, first quarter and full moon from today (`&from=YYYY-MM-DD`) at four hours each (`&hours=18,21,0,4`, UTC) plus deep dusk of the full-moon evening; `&lines=1` draws the constellation lines (the Sky menu's hidden toggle). Use `&w=300` for the 13-column set. The night look's knobs: `NIGHT_LOOK` in `ridge/nightSky.ts` (star point spread, contrast exponents, moon size, earthshine, line opacity), `NIGHT_CEILING` and `SCOTOPIC` in `ridge/toneMap.ts`, the night `Budget` (key, targets, partial adaptation).
+Named moments (`ridgeSheet.html?named=1`): the six moments of the Sky menu (dawn, morning, noon, golden hour, dusk, night) at the baked place on the December and June solstices, drawn from `momentFor` as the app draws them (`SKY_MOMENTS` in `ridge/skyMoment.ts` is the table tuned by eye from this sheet). Night sets (`ridgeSheet.html`): `?moments=2026-11-24T22:00Z,2026-12-09T20:00Z` pins explicit UTC moments (the sun, moon and stars are those of the moment); `?night=1` renders the next new moon, first quarter and full moon from today (`&from=YYYY-MM-DD`) at four hours each (`&hours=18,21,0,4`, UTC) plus deep dusk of the full-moon evening; `&lines=1` draws the constellation lines (the Sky menu's hidden toggle). Use `&w=300` for the 13-column set. The night look's knobs: `NIGHT_LOOK` in `ridge/nightSky.ts` (star point spread, contrast exponents, moon size, earthshine, line opacity), `NIGHT_CEILING` and `SCOTOPIC` in `ridge/toneMap.ts`, the night `Budget` (key, targets, partial adaptation).
diff --git a/harness/scene/ridgeLive.html b/harness/scene/ridgeLive.html
new file mode 100644
index 00000000..fba96a06
--- /dev/null
+++ b/harness/scene/ridgeLive.html
@@ -0,0 +1,8 @@
+
+
+
+
Ridge live scene
+
+
+
+
diff --git a/harness/scene/ridgeLive.ts b/harness/scene/ridgeLive.ts
new file mode 100644
index 00000000..fcab4092
--- /dev/null
+++ b/harness/scene/ridgeLive.ts
@@ -0,0 +1,71 @@
+// One live ridge scene (tier 'full': the sky plate and the cards on the compositor) filling the window, for a driver to turn and screenshot. Not shipped.
+// `?h=214` the heading the scene starts at; `?sun=232:22` the sun's compass azimuth and elevation (degrees); `?sky=night` the stars of now (sun below the horizon); `?lines=1` the constellation lines.
+// `?speed=6` degrees a second the view turns (rotation mode 'both'); 0 holds it. The page offers `window.live`: `hold(h)` turns the view by hand, `pose()` is the heading owner's pose now,
+// `plate()` the sky plate's element and `left()` its left edge and width on the page.
+import { parseManifest } from '../../src/app/features/scene/ridge/manifest';
+import { makePhysicalSky } from '../../src/app/features/scene/ridge/physicalSky';
+import { createBackdrop } from '../../src/app/features/scene/ridge/Backdrop';
+import { createRidgeScene } from '../../src/app/features/scene/ridge/Ridge';
+import { anchor, hold, poseAt } from '../../src/app/features/scene/ridge/heading';
+import { setCamera } from '../../src/app/features/scene/cameraState';
+import { HFOV_MAX_DEG, windowFor } from '../../src/app/features/scene/ridge/view';
+import { paintSky } from '../../src/app/features/scene/ridge/physicalSky';
+import { nightBodies } from '../../src/app/features/scene/ridge/nightBodies';
+import { plateCamera, plateSize, SLACK_MIN_DEG } from '../../src/app/features/scene/ridge/skyTurn';
+
+const q = new URLSearchParams(location.search);
+/** The main-thread tasks over 50 ms the page saw, ms: `window.longTasks`. */
+const longTasks: number[] = [];
+(window as unknown as { longTasks: number[] }).longTasks = longTasks;
+try {
+ new PerformanceObserver((l) => l.getEntries().forEach((e) => longTasks.push(e.duration))).observe({ entryTypes: ['longtask'] });
+} catch {
+ // No long-task entries in this browser.
+}
+
+async function main() {
+ const index = await (await fetch('/public/ridge/index.json')).json();
+ const dir = `/public/ridge/${index.places[q.get('place') ?? index.default]}/`;
+ const manifest = parseManifest(await (await fetch(`${dir}manifest.json`)).json(), dir);
+ const { view } = manifest;
+ const [az, el] = (q.get('sun') ?? '232:22').split(':').map(Number);
+ const time = new Date();
+ const sun = q.get('sky') === 'night' ? { azimuth: 0, elevation: -30, time } : { azimuth: az, elevation: el, time };
+ const physical = makePhysicalSky(sun, 0, view);
+ const h0 = Number(q.get('h') ?? view.lookAzDeg);
+ anchor(view.place.id, h0, performance.now());
+ setCamera({ mode: 'both', speedDegPerS: Number(q.get('speed') ?? 0), offsetM: 200 });
+ const backdrop = createBackdrop(manifest, physical);
+ await backdrop.ensure({ fromDeg: h0 - HFOV_MAX_DEG, toDeg: h0 + HFOV_MAX_DEG });
+ const canvas = document.getElementById('c') as HTMLCanvasElement;
+ const scene = createRidgeScene({ canvas, tier: 'full', sky: { ...physical.stops, physical }, backdrop, lines: q.get('lines') === '1' });
+ const host = document.getElementById('host') as HTMLElement;
+ // The plate is the host's div whose first child is a canvas (the rig's first child is a div, the rain's has none).
+ const plate = () => [...host.children].find((c) => c.tagName === 'DIV' && c.firstElementChild?.tagName === 'CANVAS');
+ (window as unknown as { live: unknown }).live = {
+ scene,
+ hold: (h: number) => hold(h, performance.now()),
+ pose: () => poseAt(performance.now()),
+ plate,
+ /** Mean ms of the main-thread part of painting one plate here (the dome, its pixels and the bodies, not the canvas upscale), over `n` runs. */
+ plateCost: (n = 10) => {
+ const w = innerWidth;
+ const h = innerHeight;
+ const win = windowFor(view, w, h);
+ const { cssW } = plateSize(win, w, h, devicePixelRatio >= 2 ? 2 : 1, SLACK_MIN_DEG);
+ const t0 = performance.now();
+ for (let i = 0; i < n; i += 1) nightBodies(physical, paintSky(physical, cssW, h, plateCamera(win, 214 + i, SLACK_MIN_DEG)), true);
+ return (performance.now() - t0) / n;
+ },
+ left: () => {
+ const r = plate()?.getBoundingClientRect();
+ return r && { left: r.left, width: r.width };
+ },
+ };
+ document.title = 'ridge live: done';
+}
+
+main().catch((e) => {
+ console.error(e);
+ document.title = `ridge live: failed ${e}`;
+});
diff --git a/harness/scene/ridgeSheet.ts b/harness/scene/ridgeSheet.ts
index 3471e8be..440a3a57 100644
--- a/harness/scene/ridgeSheet.ts
+++ b/harness/scene/ridgeSheet.ts
@@ -1,4 +1,8 @@
-// Look sheet for the lit ridge cards: the Vienna bake lit for a grid of sky states (or pinned moments) x looks, each cell a small canvas at heading 0. Not shipped.
+// Look sheet for the lit ridge cards: a baked place lit for a grid of sky states (or pinned moments) x looks, each cell a small canvas drawn by the app's own still path
+// (`createRidgeScene` at tier 'still', the tiles of the arc round the heading, each card at `cardPose`). Not shipped.
+// `?views=214:0:200,0:0:200,100:0:200,214:90:98.2` one column per view `heading:phi:offset` (degrees, degrees, metres) at one sky (`?sky=2`, an index of SKIES, noon by default); a heading
+// of 360 or 0 is across north. `&sun=100:6` puts the sun of that sky at azimuth 100, 6 degrees up (the stars are always those of the moment the sheet is opened). The offset is clamped to the place's range as the app does (phi 0: the bake's forward bound, any other phi: the worst-case bound), and a phi other than 0 is the offset-only rotation mode, the camera circling the centre.
+// `?place=vienna` the baked place (index.json's default if absent)
// `?preset=all|physical|swiss|poster|painterly|painterly-cel-2|painterly-cel-3|painterly-cel-4` (default all: one row each; painterly is DEFAULT_LOOK); `?looks=` replaces the rows with
// the given `{label, ...partial RidgeLook}` entries (inkKeep and reliefLight merge by key). `?w=480` sets the cell width, 16:9 unless `?h=` gives the height (`?w=375&h=812` is a phone).
// The sky behind a cell is the app's own: `makePhysicalSky` + `paintSky` upscaled smoothly, with the real stars and the moon (`nightBodies`),
@@ -8,19 +12,21 @@
// (`?hours=18,21,0,4` UTC), plus deep dusk (sun at -10 degrees) of the evening of the full moon
// `?labels=1` DEBUG: label each constellation chain in frame with its d3-celestial abbreviation (fetched from the source repository at run time; not shipped)
// `?lines=1` constellation lines over the stars, as the Sky menu's hidden toggle does (night cells only)
-import { DEFAULT_LOOK, PHYSICAL_LOOK, lightCards } from '../../src/app/features/scene/ridge/lightCards';
+import { DEFAULT_LOOK, PHYSICAL_LOOK, createLighter } from '../../src/app/features/scene/ridge/lightCards';
import type { RidgeLook } from '../../src/app/features/scene/ridge/lightCards';
-import { parseManifest } from '../../src/app/features/scene/ridge/manifest';
-import { makePhysicalSky, paintSky } from '../../src/app/features/scene/ridge/physicalSky';
-import { windowFor } from '../../src/app/features/scene/ridge/view';
-import { nightBodies, onScreen, paintNightBodies } from '../../src/app/features/scene/ridge/nightBodies';
+import { parseIndex, parseManifest } from '../../src/app/features/scene/ridge/manifest';
+import { makePhysicalSky } from '../../src/app/features/scene/ridge/physicalSky';
+import { HFOV_MAX_DEG, windowFor } from '../../src/app/features/scene/ridge/view';
+import { onScreen } from '../../src/app/features/scene/ridge/nightBodies';
+import { createBackdrop } from '../../src/app/features/scene/ridge/Backdrop';
+import { createRidgeScene } from '../../src/app/features/scene/ridge/Ridge';
+import { anchor, hold } from '../../src/app/features/scene/ridge/heading';
+import { setCamera } from '../../src/app/features/scene/cameraState';
import { sunAt } from '../../src/app/features/scene/ridge/sunAt';
import { linesAt } from '../../src/app/features/scene/ridge/starCatalogue';
import { moonPhase } from '../../src/sky/moon.js';
-import { DAY_FROM } from '../../src/app/features/scene/skyState';
-import type { FixedSkyState } from '../../src/app/features/scene/skyState';
+import { MOMENT_IDS, momentFor } from '../../src/app/features/scene/ridge/skyMoment';
-const DIR = '/public/ridge/vienna-6815bb9dca99/';
type Override = Partial> & {
label: string;
@@ -36,9 +42,11 @@ interface Column {
azimuth?: number;
/** A moment: the sun is the real one of it. */
time?: Date;
+ /** Where the view faces and the camera stands: heading and phi in degrees, offset in metres. Absent: the rest azimuth, phi 0, the app's default offset. */
+ view?: { h: number; phi: number; r: number };
}
-/** Sun elevation and compass azimuth of each column; the cards look at 214 +- 36. Elevation picks the display budget (day from DAY_FROM, night below its negative). */
+/** Sun elevation and compass azimuth of each column; the cards look at 214 +- 36. The band of the elevation (`skyBand`) picks the display budget. */
const SKIES: Column[] = [
{ label: 'dawn 2 deg', elevation: 2, azimuth: 100 },
{ label: 'morning 15 deg', elevation: 15, azimuth: 135 },
@@ -138,6 +146,14 @@ function momentsFrom(params: URLSearchParams, place: Parameters[0]
if (Number.isNaN(time.getTime())) throw new Error(`moments=: ${iso} is not a date`);
return { label: fmt(time), time };
});
+ // `named=1`: the six named moments of the sky menu (`momentFor`, as the app draws them) on both solstices at the place: the look sheet the elevation table is tuned from.
+ if (params.get('named'))
+ return ['2026-12-21', '2026-06-21'].flatMap((day) =>
+ MOMENT_IDS.map((id) => {
+ const time = momentFor({ kind: 'named', id }, place, new Date(`${day}T12:00:00Z`));
+ return { label: `${id} ${day.slice(5)} ${fmt(time)}`, time };
+ })
+ );
if (!params.get('night')) return undefined;
const from = params.get('from') ? new Date(`${params.get('from')}T00:00:00Z`) : new Date();
const hours = (params.get('hours') ?? '18,21,0,4').split(',').map(Number);
@@ -155,6 +171,17 @@ function momentsFrom(params: URLSearchParams, place: Parameters[0]
});
return cols;
}
+/** `?views=h:phi:r,...`: one column per view, all at the sky `?sky=` (default noon), whose sun `?sun=az:el` may put elsewhere (compass degrees, degrees above the horizon). */
+function viewsFrom(params: URLSearchParams): Column[] | undefined {
+ const list = params.get('views');
+ if (!list) return undefined;
+ const [az, el] = (params.get('sun') ?? '').split(':').map(Number);
+ const sky = { ...SKIES[Number(params.get('sky') ?? 2)], ...(Number.isFinite(az) && Number.isFinite(el) ? { azimuth: az, elevation: el } : {}) };
+ return list.split(',').map((v) => {
+ const [h, phi, r] = v.split(':').map(Number);
+ return { ...sky, label: `h ${h} phi ${phi} r ${r}`, view: { h, phi, r } };
+ });
+}
const preset = q.get('preset');
const pinned = q.get('moments') || q.get('night');
const rows = (q.get('looks')
@@ -176,23 +203,14 @@ const W = Number(q.get('w') ?? 480);
const H = q.get('h') ? Number(q.get('h')) : Math.round((W * 9) / 16);
const root = document.getElementById('sheet') as HTMLElement;
-const stateOf = (el: number): FixedSkyState =>
- el >= DAY_FROM ? 'day' : el <= -DAY_FROM ? 'night' : 'dusk';
-
async function main() {
+ const index = parseIndex(await (await fetch('/public/ridge/index.json')).json());
+ const DIR = `/public/ridge/${index.places[q.get('place') ?? index.default] ?? index.places[index.default]}/`;
const manifest = parseManifest(await (await fetch(`${DIR}manifest.json`)).json(), DIR);
- const blobs = await Promise.all(
- manifest.cards.map(async (c) => ({
- colour: await (await fetch(`${DIR}${c.colour}`)).blob(),
- geometry: await (await fetch(`${DIR}${c.geometry}`)).blob(),
- }))
- );
- const decode = (b: Blob) =>
- createImageBitmap(b, { premultiplyAlpha: 'none', colorSpaceConversion: 'none' });
const { view } = manifest;
const win = windowFor(view, W, H);
const now = new Date();
- const columns = momentsFrom(q, view.place) ?? SKIES;
+ const columns = viewsFrom(q) ?? momentsFrom(q, view.place) ?? SKIES;
const ids = q.get('labels') === '1' ? await chainIds() : undefined;
const table = document.createElement('table');
@@ -213,34 +231,33 @@ async function main() {
col.time !== undefined
? sunAt(view.place, col.time)
: { elevation: col.elevation as number, azimuth: col.azimuth as number, time };
- const physical = makePhysicalSky(stateOf(sun.elevation), time, 0, view, sun);
- const px = paintSky(physical, W, H, win.camera);
- const bodies = nightBodies(physical, px, withLines);
- const small = document.createElement('canvas');
- small.width = px.w;
- small.height = px.h;
- const sctx = small.getContext('2d') as CanvasRenderingContext2D;
- const img = sctx.createImageData(px.w, px.h);
- img.data.set(px.data);
- sctx.putImageData(img, 0, 0);
+ const physical = makePhysicalSky(sun, 0, view);
+ const sky = { ...physical.stops, physical };
+ const v = col.view ?? { h: view.lookAzDeg, phi: 0, r: 200 };
for (let r = 0; r < rows.length; r += 1) {
- const bitmaps = await Promise.all(
- blobs.map(async (b) => ({
- colour: await decode(b.colour),
- geometry: await decode(b.geometry),
- }))
- );
- const cards = lightCards(manifest, bitmaps, physical, rows[r].look);
+ // A host as the page has one: a positioned box of the cell's size holding the canvas the scene paints.
+ const host = document.createElement('div');
+ Object.assign(host.style, { position: 'relative', width: `${W}px`, height: `${H}px`, overflow: 'hidden' });
const cell = document.createElement('canvas');
- cell.width = W;
- cell.height = H;
- const ctx = cell.getContext('2d') as CanvasRenderingContext2D;
- ctx.imageSmoothingQuality = 'high';
- ctx.drawImage(small, 0, 0, W, H);
- paintNightBodies(ctx, bodies, W, H, 1);
+ Object.assign(cell.style, { position: 'absolute', left: '0', top: '0', width: '100%', height: '100%' });
+ host.append(cell);
+ tr[r].insertCell().append(host);
+
+ // The heading owner as the app leaves it: this view's heading, the camera on its circle at phi (offset-only rotation), the offset the viewer chose.
+ const t0 = performance.now() - 3_600_000;
+ anchor(`sheet-${manifest.bakeId}-${columns.indexOf(col)}-${r}`, v.h, t0); // a key of its own: every cell starts from phi 0
+ setCamera({ mode: 'offset', speedDegPerS: 1, offsetM: v.r }, t0); // the offset-only rotation mode for phi seconds at 1 degree per second ...
+ hold(v.h, t0 + v.phi * 1000); // ... then the view is held at h: the mode is still, the camera stays at phi (phi 0 is the camera on its heading)
+
+ const backdrop = createBackdrop(manifest, physical, { lighter: (m, s) => createLighter(m, s, rows[r].look) });
+ await backdrop.ensure({ fromDeg: v.h - HFOV_MAX_DEG, toDeg: v.h + HFOV_MAX_DEG });
+ const scene = createRidgeScene({ canvas: cell, tier: 'still', sky, backdrop, lines: withLines });
+ scene?.dispose();
+
if (ids) {
// Debug labels: each chain's id at the mean of its vertices that lie in the frame.
+ const ctx = cell.getContext('2d') as CanvasRenderingContext2D;
ctx.font = '11px monospace';
ctx.fillStyle = '#ffd24a';
linesAt(physical.sun.time, view.place.lat, view.place.lon).forEach((chain, i) => {
@@ -251,26 +268,6 @@ async function main() {
ctx.fillText(`${ids[i]} ${pts.length}/${chain.length}`, mx * W, my * H);
});
}
- // As Ridge.ts paintCards at heading 0: farthest first, each card at its own scale about the horizon row of the plane.
- const s = win.plane.scale;
- const x0 = (W - win.plane.w) / 2;
- const planeTop = H - (win.plane.h + win.plane.bottom);
- const ox = x0 + win.plane.w / 2;
- const oy = planeTop + view.horizonRow * s;
- for (let k = cards.length - 1; k >= 0; k -= 1) {
- ctx.save();
- ctx.translate(ox, oy);
- ctx.scale(cards[k].scale, cards[k].scale);
- ctx.drawImage(
- cards[k].canvas,
- x0 - ox,
- planeTop + cards[k].top * s - oy,
- win.plane.w,
- cards[k].h * s
- );
- ctx.restore();
- }
- tr[r].insertCell().append(cell);
}
}
document.title = 'ridge look sheet: done';
diff --git a/public/ridge/index.json b/public/ridge/index.json
index 8c3323ed..ad51909b 100644
--- a/public/ridge/index.json
+++ b/public/ridge/index.json
@@ -2,6 +2,6 @@
"schema": 1,
"default": "vienna",
"places": {
- "vienna": "vienna-6815bb9dca99"
+ "vienna": "vienna-2aac8e6fee59"
}
}
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t00-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t00-colour.webp
new file mode 100644
index 00000000..13246968
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t00-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t00-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t00-geometry.webp
new file mode 100644
index 00000000..3d011161
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t00-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t01-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t01-colour.webp
new file mode 100644
index 00000000..8b23e1cb
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t01-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t01-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t01-geometry.webp
new file mode 100644
index 00000000..df1f1e86
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t01-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t02-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t02-colour.webp
new file mode 100644
index 00000000..ee2f52bb
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t02-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t02-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t02-geometry.webp
new file mode 100644
index 00000000..a119adf7
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t02-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t03-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t03-colour.webp
new file mode 100644
index 00000000..8f032bc9
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t03-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t03-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t03-geometry.webp
new file mode 100644
index 00000000..a3d9c65a
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t03-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t04-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t04-colour.webp
new file mode 100644
index 00000000..e4157192
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t04-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t04-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t04-geometry.webp
new file mode 100644
index 00000000..f787120e
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t04-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t05-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t05-colour.webp
new file mode 100644
index 00000000..13d4b141
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t05-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t05-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t05-geometry.webp
new file mode 100644
index 00000000..a26acc06
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t05-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t06-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t06-colour.webp
new file mode 100644
index 00000000..a3d23180
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t06-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t06-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t06-geometry.webp
new file mode 100644
index 00000000..00abe410
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t06-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t07-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t07-colour.webp
new file mode 100644
index 00000000..67fd7605
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t07-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t07-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t07-geometry.webp
new file mode 100644
index 00000000..998d80ca
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t07-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t08-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t08-colour.webp
new file mode 100644
index 00000000..d47c3d71
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t08-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t08-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t08-geometry.webp
new file mode 100644
index 00000000..1c2e742c
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t08-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t09-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t09-colour.webp
new file mode 100644
index 00000000..43545dad
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t09-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t09-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t09-geometry.webp
new file mode 100644
index 00000000..7c06ba9b
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t09-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t10-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t10-colour.webp
new file mode 100644
index 00000000..71db26f9
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t10-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t10-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t10-geometry.webp
new file mode 100644
index 00000000..64b8f54e
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t10-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t11-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t11-colour.webp
new file mode 100644
index 00000000..217387dc
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t11-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t11-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t11-geometry.webp
new file mode 100644
index 00000000..f2127ce4
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t11-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t12-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t12-colour.webp
new file mode 100644
index 00000000..908e626b
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t12-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t12-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t12-geometry.webp
new file mode 100644
index 00000000..1ccc9f79
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t12-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t13-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t13-colour.webp
new file mode 100644
index 00000000..a7406271
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t13-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t13-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t13-geometry.webp
new file mode 100644
index 00000000..36933b0d
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t13-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t14-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t14-colour.webp
new file mode 100644
index 00000000..ee3823c5
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t14-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t14-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t14-geometry.webp
new file mode 100644
index 00000000..064ee277
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t14-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t15-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t15-colour.webp
new file mode 100644
index 00000000..29409430
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t15-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t15-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t15-geometry.webp
new file mode 100644
index 00000000..75ae86c3
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t15-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t16-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t16-colour.webp
new file mode 100644
index 00000000..a50024d4
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t16-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t16-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t16-geometry.webp
new file mode 100644
index 00000000..c0286780
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t16-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t17-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t17-colour.webp
new file mode 100644
index 00000000..df1d26bc
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t17-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t17-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t17-geometry.webp
new file mode 100644
index 00000000..ad94826f
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t17-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t18-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t18-colour.webp
new file mode 100644
index 00000000..51b89544
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t18-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t18-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t18-geometry.webp
new file mode 100644
index 00000000..717fb6f8
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t18-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t19-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t19-colour.webp
new file mode 100644
index 00000000..dbdac364
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t19-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t19-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t19-geometry.webp
new file mode 100644
index 00000000..ec133982
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t19-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t20-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t20-colour.webp
new file mode 100644
index 00000000..b1eccb3c
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t20-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t20-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t20-geometry.webp
new file mode 100644
index 00000000..64692465
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t20-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t21-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t21-colour.webp
new file mode 100644
index 00000000..8eeb4af1
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t21-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t21-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t21-geometry.webp
new file mode 100644
index 00000000..e01306ad
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t21-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t22-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t22-colour.webp
new file mode 100644
index 00000000..070d8d99
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t22-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t22-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t22-geometry.webp
new file mode 100644
index 00000000..42c7ba9f
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t22-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t23-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t23-colour.webp
new file mode 100644
index 00000000..26820fc4
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t23-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t23-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t23-geometry.webp
new file mode 100644
index 00000000..d578769b
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t23-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t24-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t24-colour.webp
new file mode 100644
index 00000000..944d2d7f
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t24-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t24-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t24-geometry.webp
new file mode 100644
index 00000000..a18af569
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t24-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t25-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t25-colour.webp
new file mode 100644
index 00000000..f902bea7
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t25-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t25-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t25-geometry.webp
new file mode 100644
index 00000000..b2e5def3
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t25-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t26-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t26-colour.webp
new file mode 100644
index 00000000..3fb4534e
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t26-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t26-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t26-geometry.webp
new file mode 100644
index 00000000..11686a9d
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t26-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t27-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t27-colour.webp
new file mode 100644
index 00000000..677043f4
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t27-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t27-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t27-geometry.webp
new file mode 100644
index 00000000..3cebb65f
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t27-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t28-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t28-colour.webp
new file mode 100644
index 00000000..7af5977a
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t28-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t28-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t28-geometry.webp
new file mode 100644
index 00000000..4f2f9c37
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t28-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t29-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t29-colour.webp
new file mode 100644
index 00000000..800c6122
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t29-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t29-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t29-geometry.webp
new file mode 100644
index 00000000..f999157e
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t29-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t30-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t30-colour.webp
new file mode 100644
index 00000000..70184748
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t30-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t30-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t30-geometry.webp
new file mode 100644
index 00000000..ce1d97de
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t30-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t31-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t31-colour.webp
new file mode 100644
index 00000000..efdc79b1
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t31-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-0-t31-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-0-t31-geometry.webp
new file mode 100644
index 00000000..03bb0be0
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-0-t31-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t00-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t00-colour.webp
new file mode 100644
index 00000000..c5af4bb6
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t00-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t00-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t00-geometry.webp
new file mode 100644
index 00000000..58cd96a5
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t00-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t01-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t01-colour.webp
new file mode 100644
index 00000000..a6439983
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t01-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t01-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t01-geometry.webp
new file mode 100644
index 00000000..aad4b786
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t01-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t02-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t02-colour.webp
new file mode 100644
index 00000000..6ea1f7af
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t02-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t02-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t02-geometry.webp
new file mode 100644
index 00000000..0c103115
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t02-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t03-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t03-colour.webp
new file mode 100644
index 00000000..1a779093
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t03-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t03-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t03-geometry.webp
new file mode 100644
index 00000000..28a2644b
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t03-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t04-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t04-colour.webp
new file mode 100644
index 00000000..950fc2a6
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t04-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t04-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t04-geometry.webp
new file mode 100644
index 00000000..708c2c10
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t04-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t05-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t05-colour.webp
new file mode 100644
index 00000000..46107bf7
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t05-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t05-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t05-geometry.webp
new file mode 100644
index 00000000..d249f8de
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t05-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t06-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t06-colour.webp
new file mode 100644
index 00000000..2a32bca9
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t06-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t06-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t06-geometry.webp
new file mode 100644
index 00000000..f3250ed8
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t06-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t07-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t07-colour.webp
new file mode 100644
index 00000000..41081904
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t07-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t07-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t07-geometry.webp
new file mode 100644
index 00000000..d5e46567
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t07-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t08-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t08-colour.webp
new file mode 100644
index 00000000..97db459b
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t08-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t08-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t08-geometry.webp
new file mode 100644
index 00000000..554e502e
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t08-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t09-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t09-colour.webp
new file mode 100644
index 00000000..c30c2166
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t09-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t09-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t09-geometry.webp
new file mode 100644
index 00000000..fb7f668d
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t09-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t10-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t10-colour.webp
new file mode 100644
index 00000000..981fe509
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t10-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t10-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t10-geometry.webp
new file mode 100644
index 00000000..27b1fb7a
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t10-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t11-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t11-colour.webp
new file mode 100644
index 00000000..763fed8f
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t11-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t11-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t11-geometry.webp
new file mode 100644
index 00000000..d64787ea
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t11-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t12-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t12-colour.webp
new file mode 100644
index 00000000..55103a11
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t12-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t12-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t12-geometry.webp
new file mode 100644
index 00000000..7e71327f
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t12-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t13-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t13-colour.webp
new file mode 100644
index 00000000..84863b23
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t13-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t13-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t13-geometry.webp
new file mode 100644
index 00000000..0cf1bfa6
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t13-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t14-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t14-colour.webp
new file mode 100644
index 00000000..26a04948
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t14-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t14-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t14-geometry.webp
new file mode 100644
index 00000000..f513b6de
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t14-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t15-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t15-colour.webp
new file mode 100644
index 00000000..5c449c09
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t15-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t15-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t15-geometry.webp
new file mode 100644
index 00000000..c4fa92b3
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t15-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t16-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t16-colour.webp
new file mode 100644
index 00000000..2b2a61ce
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t16-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t16-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t16-geometry.webp
new file mode 100644
index 00000000..42d24b90
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t16-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t17-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t17-colour.webp
new file mode 100644
index 00000000..b6522d96
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t17-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t17-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t17-geometry.webp
new file mode 100644
index 00000000..d50da47f
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t17-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t18-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t18-colour.webp
new file mode 100644
index 00000000..45e7edb8
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t18-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t18-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t18-geometry.webp
new file mode 100644
index 00000000..af61ad07
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t18-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t19-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t19-colour.webp
new file mode 100644
index 00000000..df60d40a
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t19-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t19-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t19-geometry.webp
new file mode 100644
index 00000000..66127020
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t19-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t20-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t20-colour.webp
new file mode 100644
index 00000000..b6659fdd
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t20-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t20-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t20-geometry.webp
new file mode 100644
index 00000000..0bca3b52
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t20-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t21-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t21-colour.webp
new file mode 100644
index 00000000..987eaac3
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t21-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t21-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t21-geometry.webp
new file mode 100644
index 00000000..9d623baf
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t21-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t22-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t22-colour.webp
new file mode 100644
index 00000000..9d947e7b
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t22-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t22-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t22-geometry.webp
new file mode 100644
index 00000000..84f0813e
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t22-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t23-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t23-colour.webp
new file mode 100644
index 00000000..6a0fb7ab
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t23-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t23-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t23-geometry.webp
new file mode 100644
index 00000000..c05fd3c7
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t23-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t24-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t24-colour.webp
new file mode 100644
index 00000000..2aae2a91
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t24-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t24-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t24-geometry.webp
new file mode 100644
index 00000000..02be7816
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t24-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t25-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t25-colour.webp
new file mode 100644
index 00000000..d88a2cf5
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t25-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t25-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t25-geometry.webp
new file mode 100644
index 00000000..5a840047
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t25-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t26-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t26-colour.webp
new file mode 100644
index 00000000..ca02aa50
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t26-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t26-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t26-geometry.webp
new file mode 100644
index 00000000..d1274f06
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t26-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t27-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t27-colour.webp
new file mode 100644
index 00000000..368ed321
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t27-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t27-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t27-geometry.webp
new file mode 100644
index 00000000..acfcf68e
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t27-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t28-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t28-colour.webp
new file mode 100644
index 00000000..99278ff3
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t28-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t28-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t28-geometry.webp
new file mode 100644
index 00000000..97c25e93
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t28-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t29-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t29-colour.webp
new file mode 100644
index 00000000..6896f47c
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t29-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t29-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t29-geometry.webp
new file mode 100644
index 00000000..b86f0e94
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t29-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t30-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t30-colour.webp
new file mode 100644
index 00000000..7053645b
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t30-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t30-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t30-geometry.webp
new file mode 100644
index 00000000..29f233d2
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t30-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t31-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t31-colour.webp
new file mode 100644
index 00000000..a67cd724
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t31-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-1-t31-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-1-t31-geometry.webp
new file mode 100644
index 00000000..b1365240
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-1-t31-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t00-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t00-colour.webp
new file mode 100644
index 00000000..8bfde290
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t00-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t00-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t00-geometry.webp
new file mode 100644
index 00000000..ae5550f5
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t00-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t01-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t01-colour.webp
new file mode 100644
index 00000000..8039a109
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t01-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t01-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t01-geometry.webp
new file mode 100644
index 00000000..6b086a39
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t01-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t02-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t02-colour.webp
new file mode 100644
index 00000000..1317a36d
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t02-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t02-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t02-geometry.webp
new file mode 100644
index 00000000..1ba99ab8
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t02-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t03-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t03-colour.webp
new file mode 100644
index 00000000..e1be6372
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t03-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t03-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t03-geometry.webp
new file mode 100644
index 00000000..6cb9b9c5
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t03-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t04-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t04-colour.webp
new file mode 100644
index 00000000..45d9819b
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t04-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t04-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t04-geometry.webp
new file mode 100644
index 00000000..6a0204d6
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t04-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t05-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t05-colour.webp
new file mode 100644
index 00000000..a3e8391e
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t05-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t05-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t05-geometry.webp
new file mode 100644
index 00000000..58b0f626
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t05-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t06-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t06-colour.webp
new file mode 100644
index 00000000..40674442
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t06-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t06-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t06-geometry.webp
new file mode 100644
index 00000000..8b9fdb41
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t06-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t07-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t07-colour.webp
new file mode 100644
index 00000000..ec5da0e4
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t07-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t07-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t07-geometry.webp
new file mode 100644
index 00000000..4cb83331
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t07-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t08-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t08-colour.webp
new file mode 100644
index 00000000..b7c9cccf
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t08-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t08-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t08-geometry.webp
new file mode 100644
index 00000000..5ae5e3ae
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t08-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t09-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t09-colour.webp
new file mode 100644
index 00000000..b9fa4d48
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t09-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t09-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t09-geometry.webp
new file mode 100644
index 00000000..cc630325
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t09-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t10-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t10-colour.webp
new file mode 100644
index 00000000..b63b2a9b
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t10-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t10-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t10-geometry.webp
new file mode 100644
index 00000000..c634800f
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t10-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t11-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t11-colour.webp
new file mode 100644
index 00000000..f0c1b27e
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t11-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t11-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t11-geometry.webp
new file mode 100644
index 00000000..8d79bb99
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t11-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t12-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t12-colour.webp
new file mode 100644
index 00000000..42cf3107
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t12-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t12-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t12-geometry.webp
new file mode 100644
index 00000000..f2dafbd9
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t12-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t13-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t13-colour.webp
new file mode 100644
index 00000000..07dd9300
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t13-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t13-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t13-geometry.webp
new file mode 100644
index 00000000..e20a9170
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t13-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t14-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t14-colour.webp
new file mode 100644
index 00000000..623e6edb
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t14-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t14-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t14-geometry.webp
new file mode 100644
index 00000000..02b1258f
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t14-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t15-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t15-colour.webp
new file mode 100644
index 00000000..079fd725
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t15-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t15-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t15-geometry.webp
new file mode 100644
index 00000000..cea2b8e4
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t15-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t16-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t16-colour.webp
new file mode 100644
index 00000000..67f196c1
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t16-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t16-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t16-geometry.webp
new file mode 100644
index 00000000..3702ec15
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t16-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t17-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t17-colour.webp
new file mode 100644
index 00000000..b2c864e2
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t17-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t17-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t17-geometry.webp
new file mode 100644
index 00000000..133bb147
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t17-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t18-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t18-colour.webp
new file mode 100644
index 00000000..a0d4d8fa
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t18-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t18-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t18-geometry.webp
new file mode 100644
index 00000000..34949f41
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t18-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t19-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t19-colour.webp
new file mode 100644
index 00000000..7a44160b
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t19-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t19-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t19-geometry.webp
new file mode 100644
index 00000000..bffe85bd
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t19-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t20-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t20-colour.webp
new file mode 100644
index 00000000..760155fd
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t20-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t20-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t20-geometry.webp
new file mode 100644
index 00000000..c24bf013
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t20-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t21-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t21-colour.webp
new file mode 100644
index 00000000..b38a28e1
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t21-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t21-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t21-geometry.webp
new file mode 100644
index 00000000..60482a18
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t21-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t22-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t22-colour.webp
new file mode 100644
index 00000000..b0dc679f
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t22-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t22-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t22-geometry.webp
new file mode 100644
index 00000000..35103f4a
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t22-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t23-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t23-colour.webp
new file mode 100644
index 00000000..30cd1c5b
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t23-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t23-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t23-geometry.webp
new file mode 100644
index 00000000..d9c75f82
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t23-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t24-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t24-colour.webp
new file mode 100644
index 00000000..5233fb24
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t24-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t24-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t24-geometry.webp
new file mode 100644
index 00000000..48a2aa42
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t24-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t25-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t25-colour.webp
new file mode 100644
index 00000000..fc092679
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t25-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t25-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t25-geometry.webp
new file mode 100644
index 00000000..4c5e7fc8
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t25-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t26-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t26-colour.webp
new file mode 100644
index 00000000..aa277098
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t26-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t26-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t26-geometry.webp
new file mode 100644
index 00000000..06258cf4
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t26-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t27-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t27-colour.webp
new file mode 100644
index 00000000..34d07fee
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t27-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t27-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t27-geometry.webp
new file mode 100644
index 00000000..f23c776f
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t27-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t28-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t28-colour.webp
new file mode 100644
index 00000000..f3dbe838
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t28-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t28-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t28-geometry.webp
new file mode 100644
index 00000000..c3157c79
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t28-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t29-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t29-colour.webp
new file mode 100644
index 00000000..6319a327
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t29-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t29-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t29-geometry.webp
new file mode 100644
index 00000000..c02f2b73
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t29-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t30-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t30-colour.webp
new file mode 100644
index 00000000..4a604811
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t30-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t30-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t30-geometry.webp
new file mode 100644
index 00000000..f0f62f6f
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t30-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t31-colour.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t31-colour.webp
new file mode 100644
index 00000000..ac008a73
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t31-colour.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/card-2-t31-geometry.webp b/public/ridge/vienna-2aac8e6fee59/card-2-t31-geometry.webp
new file mode 100644
index 00000000..b60767fd
Binary files /dev/null and b/public/ridge/vienna-2aac8e6fee59/card-2-t31-geometry.webp differ
diff --git a/public/ridge/vienna-2aac8e6fee59/manifest.json b/public/ridge/vienna-2aac8e6fee59/manifest.json
new file mode 100644
index 00000000..b518a149
--- /dev/null
+++ b/public/ridge/vienna-2aac8e6fee59/manifest.json
@@ -0,0 +1,1376 @@
+{
+ "schema": 3,
+ "baker_version": 5,
+ "bake_id": "2aac8e6fee59",
+ "place": {
+ "id": "vienna",
+ "name": "Vienna, looking SW to Rax/Schneeberg",
+ "lat": 48.1929826,
+ "lon": 16.3534237,
+ "altitude_km": 0.18330000000000002,
+ "eye_m": 213.3,
+ "tz": "Europe/Vienna"
+ },
+ "view": {
+ "look_az_deg": 214.0,
+ "plane_h": 600,
+ "px_per_deg_h": 17.77777777777778,
+ "px_per_deg_v": 171.73831979090915,
+ "exaggeration": 9.660280488238639,
+ "horizon_row": 357.01990847502145,
+ "sky_row": 24.0,
+ "near_row": 396.0,
+ "ring_w": 6400,
+ "tile_w": 200,
+ "tiles": 32,
+ "apron": 2
+ },
+ "curvature": {
+ "r_earth_m": 6371000.0,
+ "k_ref": 0.13
+ },
+ "encoding": {
+ "log_d_min": 6.214608098422191,
+ "log_d_max": 11.462786662662916,
+ "normal": "rt8"
+ },
+ "camera": {
+ "r_max_m": 95.8,
+ "r_max_forward_m": 198.4
+ },
+ "cards": [
+ {
+ "near_m": null,
+ "far_m": 4013.740853069043
+ },
+ {
+ "near_m": 4013.740853069043,
+ "far_m": 41206.78494161152
+ },
+ {
+ "near_m": 41206.78494161152,
+ "far_m": null
+ }
+ ],
+ "tiles": [
+ [
+ {
+ "top": 337,
+ "h": 263,
+ "distance_m": 603.4103393554688,
+ "colour": {
+ "file": "card-0-t00-colour.webp",
+ "bytes": 842
+ },
+ "geometry": {
+ "file": "card-0-t00-geometry.webp",
+ "bytes": 7318
+ }
+ },
+ {
+ "top": 254,
+ "h": 346,
+ "distance_m": 7923.6240234375,
+ "colour": {
+ "file": "card-1-t00-colour.webp",
+ "bytes": 1328
+ },
+ "geometry": {
+ "file": "card-1-t00-geometry.webp",
+ "bytes": 21430
+ }
+ },
+ {
+ "top": 326,
+ "h": 274,
+ "distance_m": 41265.13671875,
+ "colour": {
+ "file": "card-2-t00-colour.webp",
+ "bytes": 894
+ },
+ "geometry": {
+ "file": "card-2-t00-geometry.webp",
+ "bytes": 8502
+ }
+ }
+ ],
+ [
+ {
+ "top": 397,
+ "h": 203,
+ "distance_m": 681.6199951171875,
+ "colour": {
+ "file": "card-0-t01-colour.webp",
+ "bytes": 702
+ },
+ "geometry": {
+ "file": "card-0-t01-geometry.webp",
+ "bytes": 5444
+ }
+ },
+ {
+ "top": 294,
+ "h": 306,
+ "distance_m": 12328.642578125,
+ "colour": {
+ "file": "card-1-t01-colour.webp",
+ "bytes": 1202
+ },
+ "geometry": {
+ "file": "card-1-t01-geometry.webp",
+ "bytes": 19568
+ }
+ },
+ {
+ "top": 359,
+ "h": 241,
+ "distance_m": 41087.56640625,
+ "colour": {
+ "file": "card-2-t01-colour.webp",
+ "bytes": 652
+ },
+ "geometry": {
+ "file": "card-2-t01-geometry.webp",
+ "bytes": 3190
+ }
+ }
+ ],
+ [
+ {
+ "top": 437,
+ "h": 163,
+ "distance_m": 802.34912109375,
+ "colour": {
+ "file": "card-0-t02-colour.webp",
+ "bytes": 634
+ },
+ "geometry": {
+ "file": "card-0-t02-geometry.webp",
+ "bytes": 7220
+ }
+ },
+ {
+ "top": 353,
+ "h": 247,
+ "distance_m": 9379.99609375,
+ "colour": {
+ "file": "card-1-t02-colour.webp",
+ "bytes": 956
+ },
+ "geometry": {
+ "file": "card-1-t02-geometry.webp",
+ "bytes": 16212
+ }
+ },
+ {
+ "top": 362,
+ "h": 238,
+ "distance_m": 38873.109375,
+ "colour": {
+ "file": "card-2-t02-colour.webp",
+ "bytes": 506
+ },
+ "geometry": {
+ "file": "card-2-t02-geometry.webp",
+ "bytes": 2514
+ }
+ }
+ ],
+ [
+ {
+ "top": 439,
+ "h": 161,
+ "distance_m": 1497.642333984375,
+ "colour": {
+ "file": "card-0-t03-colour.webp",
+ "bytes": 600
+ },
+ "geometry": {
+ "file": "card-0-t03-geometry.webp",
+ "bytes": 9330
+ }
+ },
+ {
+ "top": 357,
+ "h": 243,
+ "distance_m": 9379.99609375,
+ "colour": {
+ "file": "card-1-t03-colour.webp",
+ "bytes": 986
+ },
+ "geometry": {
+ "file": "card-1-t03-geometry.webp",
+ "bytes": 15134
+ }
+ },
+ {
+ "top": 371,
+ "h": 229,
+ "distance_m": 39822.90234375,
+ "colour": {
+ "file": "card-2-t03-colour.webp",
+ "bytes": 482
+ },
+ "geometry": {
+ "file": "card-2-t03-geometry.webp",
+ "bytes": 1748
+ }
+ }
+ ],
+ [
+ {
+ "top": 455,
+ "h": 145,
+ "distance_m": 1587.480712890625,
+ "colour": {
+ "file": "card-0-t04-colour.webp",
+ "bytes": 678
+ },
+ "geometry": {
+ "file": "card-0-t04-geometry.webp",
+ "bytes": 7418
+ }
+ },
+ {
+ "top": 363,
+ "h": 237,
+ "distance_m": 7940.0009765625,
+ "colour": {
+ "file": "card-1-t04-colour.webp",
+ "bytes": 1008
+ },
+ "geometry": {
+ "file": "card-1-t04-geometry.webp",
+ "bytes": 15664
+ }
+ },
+ {
+ "top": 380,
+ "h": 220,
+ "distance_m": 42715.42578125,
+ "colour": {
+ "file": "card-2-t04-colour.webp",
+ "bytes": 510
+ },
+ "geometry": {
+ "file": "card-2-t04-geometry.webp",
+ "bytes": 516
+ }
+ }
+ ],
+ [
+ {
+ "top": 461,
+ "h": 139,
+ "distance_m": 1739.9998779296875,
+ "colour": {
+ "file": "card-0-t05-colour.webp",
+ "bytes": 552
+ },
+ "geometry": {
+ "file": "card-0-t05-geometry.webp",
+ "bytes": 9882
+ }
+ },
+ {
+ "top": 390,
+ "h": 210,
+ "distance_m": 7191.796875,
+ "colour": {
+ "file": "card-1-t05-colour.webp",
+ "bytes": 498
+ },
+ "geometry": {
+ "file": "card-1-t05-geometry.webp",
+ "bytes": 9640
+ }
+ },
+ {
+ "top": 342,
+ "h": 258,
+ "distance_m": 73387.6015625,
+ "colour": {
+ "file": "card-2-t05-colour.webp",
+ "bytes": 994
+ },
+ "geometry": {
+ "file": "card-2-t05-geometry.webp",
+ "bytes": 6354
+ }
+ }
+ ],
+ [
+ {
+ "top": 461,
+ "h": 139,
+ "distance_m": 1397.39599609375,
+ "colour": {
+ "file": "card-0-t06-colour.webp",
+ "bytes": 384
+ },
+ "geometry": {
+ "file": "card-0-t06-geometry.webp",
+ "bytes": 7150
+ }
+ },
+ {
+ "top": 393,
+ "h": 207,
+ "distance_m": 6499.99853515625,
+ "colour": {
+ "file": "card-1-t06-colour.webp",
+ "bytes": 514
+ },
+ "geometry": {
+ "file": "card-1-t06-geometry.webp",
+ "bytes": 10622
+ }
+ },
+ {
+ "top": 323,
+ "h": 277,
+ "distance_m": 60884.40234375,
+ "colour": {
+ "file": "card-2-t06-colour.webp",
+ "bytes": 1652
+ },
+ "geometry": {
+ "file": "card-2-t06-geometry.webp",
+ "bytes": 18624
+ }
+ }
+ ],
+ [
+ {
+ "top": 440,
+ "h": 160,
+ "distance_m": 1639.5902099609375,
+ "colour": {
+ "file": "card-0-t07-colour.webp",
+ "bytes": 584
+ },
+ "geometry": {
+ "file": "card-0-t07-geometry.webp",
+ "bytes": 9288
+ }
+ },
+ {
+ "top": 393,
+ "h": 207,
+ "distance_m": 7020.00244140625,
+ "colour": {
+ "file": "card-1-t07-colour.webp",
+ "bytes": 604
+ },
+ "geometry": {
+ "file": "card-1-t07-geometry.webp",
+ "bytes": 8706
+ }
+ },
+ {
+ "top": 332,
+ "h": 268,
+ "distance_m": 53030.578125,
+ "colour": {
+ "file": "card-2-t07-colour.webp",
+ "bytes": 1356
+ },
+ "geometry": {
+ "file": "card-2-t07-geometry.webp",
+ "bytes": 14322
+ }
+ }
+ ],
+ [
+ {
+ "top": 404,
+ "h": 196,
+ "distance_m": 1494.0631103515625,
+ "colour": {
+ "file": "card-0-t08-colour.webp",
+ "bytes": 728
+ },
+ "geometry": {
+ "file": "card-0-t08-geometry.webp",
+ "bytes": 9320
+ }
+ },
+ {
+ "top": 393,
+ "h": 207,
+ "distance_m": 7499.99755859375,
+ "colour": {
+ "file": "card-1-t08-colour.webp",
+ "bytes": 700
+ },
+ "geometry": {
+ "file": "card-1-t08-geometry.webp",
+ "bytes": 10602
+ }
+ },
+ {
+ "top": 329,
+ "h": 271,
+ "distance_m": 44656.86328125,
+ "colour": {
+ "file": "card-2-t08-colour.webp",
+ "bytes": 1258
+ },
+ "geometry": {
+ "file": "card-2-t08-geometry.webp",
+ "bytes": 9538
+ }
+ }
+ ],
+ [
+ {
+ "top": 396,
+ "h": 204,
+ "distance_m": 1222.066650390625,
+ "colour": {
+ "file": "card-0-t09-colour.webp",
+ "bytes": 558
+ },
+ "geometry": {
+ "file": "card-0-t09-geometry.webp",
+ "bytes": 8568
+ }
+ },
+ {
+ "top": 360,
+ "h": 240,
+ "distance_m": 9976.568359375,
+ "colour": {
+ "file": "card-1-t09-colour.webp",
+ "bytes": 876
+ },
+ "geometry": {
+ "file": "card-1-t09-geometry.webp",
+ "bytes": 12968
+ }
+ },
+ {
+ "top": 370,
+ "h": 230,
+ "distance_m": 44772.3828125,
+ "colour": {
+ "file": "card-2-t09-colour.webp",
+ "bytes": 626
+ },
+ "geometry": {
+ "file": "card-2-t09-geometry.webp",
+ "bytes": 2232
+ }
+ }
+ ],
+ [
+ {
+ "top": 380,
+ "h": 220,
+ "distance_m": 1104.7967529296875,
+ "colour": {
+ "file": "card-0-t10-colour.webp",
+ "bytes": 576
+ },
+ "geometry": {
+ "file": "card-0-t10-geometry.webp",
+ "bytes": 6836
+ }
+ },
+ {
+ "top": 355,
+ "h": 245,
+ "distance_m": 14817.3876953125,
+ "colour": {
+ "file": "card-1-t10-colour.webp",
+ "bytes": 938
+ },
+ "geometry": {
+ "file": "card-1-t10-geometry.webp",
+ "bytes": 12918
+ }
+ },
+ {
+ "top": 370,
+ "h": 230,
+ "distance_m": 38822.984375,
+ "colour": {
+ "file": "card-2-t10-colour.webp",
+ "bytes": 474
+ },
+ "geometry": {
+ "file": "card-2-t10-geometry.webp",
+ "bytes": 2060
+ }
+ }
+ ],
+ [
+ {
+ "top": 285,
+ "h": 315,
+ "distance_m": 1123.831787109375,
+ "colour": {
+ "file": "card-0-t11-colour.webp",
+ "bytes": 1002
+ },
+ "geometry": {
+ "file": "card-0-t11-geometry.webp",
+ "bytes": 10782
+ }
+ },
+ {
+ "top": 312,
+ "h": 288,
+ "distance_m": 16307.2421875,
+ "colour": {
+ "file": "card-1-t11-colour.webp",
+ "bytes": 544
+ },
+ "geometry": {
+ "file": "card-1-t11-geometry.webp",
+ "bytes": 2216
+ }
+ },
+ {
+ "top": 358,
+ "h": 242,
+ "distance_m": 37985.00390625,
+ "colour": {
+ "file": "card-2-t11-colour.webp",
+ "bytes": 630
+ },
+ "geometry": {
+ "file": "card-2-t11-geometry.webp",
+ "bytes": 1840
+ }
+ }
+ ],
+ [
+ {
+ "top": 272,
+ "h": 328,
+ "distance_m": 1142.0506591796875,
+ "colour": {
+ "file": "card-0-t12-colour.webp",
+ "bytes": 758
+ },
+ "geometry": {
+ "file": "card-0-t12-geometry.webp",
+ "bytes": 13578
+ }
+ },
+ {
+ "top": 281,
+ "h": 319,
+ "distance_m": 5059.99853515625,
+ "colour": {
+ "file": "card-1-t12-colour.webp",
+ "bytes": 520
+ },
+ "geometry": {
+ "file": "card-1-t12-geometry.webp",
+ "bytes": 176
+ }
+ },
+ {
+ "top": 350,
+ "h": 250,
+ "distance_m": 37450.98828125,
+ "colour": {
+ "file": "card-2-t12-colour.webp",
+ "bytes": 646
+ },
+ "geometry": {
+ "file": "card-2-t12-geometry.webp",
+ "bytes": 612
+ }
+ }
+ ],
+ [
+ {
+ "top": 265,
+ "h": 335,
+ "distance_m": 1120.1195068359375,
+ "colour": {
+ "file": "card-0-t13-colour.webp",
+ "bytes": 582
+ },
+ "geometry": {
+ "file": "card-0-t13-geometry.webp",
+ "bytes": 11368
+ }
+ },
+ {
+ "top": 309,
+ "h": 291,
+ "distance_m": 35995.66015625,
+ "colour": {
+ "file": "card-1-t13-colour.webp",
+ "bytes": 952
+ },
+ "geometry": {
+ "file": "card-1-t13-geometry.webp",
+ "bytes": 5842
+ }
+ },
+ {
+ "top": 332,
+ "h": 268,
+ "distance_m": 37581.2578125,
+ "colour": {
+ "file": "card-2-t13-colour.webp",
+ "bytes": 634
+ },
+ "geometry": {
+ "file": "card-2-t13-geometry.webp",
+ "bytes": 1514
+ }
+ }
+ ],
+ [
+ {
+ "top": 247,
+ "h": 353,
+ "distance_m": 1184.9326171875,
+ "colour": {
+ "file": "card-0-t14-colour.webp",
+ "bytes": 608
+ },
+ "geometry": {
+ "file": "card-0-t14-geometry.webp",
+ "bytes": 10944
+ }
+ },
+ {
+ "top": 312,
+ "h": 288,
+ "distance_m": 33968.61328125,
+ "colour": {
+ "file": "card-1-t14-colour.webp",
+ "bytes": 1280
+ },
+ "geometry": {
+ "file": "card-1-t14-geometry.webp",
+ "bytes": 15154
+ }
+ },
+ {
+ "top": 318,
+ "h": 282,
+ "distance_m": 37484.328125,
+ "colour": {
+ "file": "card-2-t14-colour.webp",
+ "bytes": 678
+ },
+ "geometry": {
+ "file": "card-2-t14-geometry.webp",
+ "bytes": 1148
+ }
+ }
+ ],
+ [
+ {
+ "top": 244,
+ "h": 356,
+ "distance_m": 1333.3995361328125,
+ "colour": {
+ "file": "card-0-t15-colour.webp",
+ "bytes": 684
+ },
+ "geometry": {
+ "file": "card-0-t15-geometry.webp",
+ "bytes": 10824
+ }
+ },
+ {
+ "top": 346,
+ "h": 254,
+ "distance_m": 7460.00048828125,
+ "colour": {
+ "file": "card-1-t15-colour.webp",
+ "bytes": 602
+ },
+ "geometry": {
+ "file": "card-1-t15-geometry.webp",
+ "bytes": 6172
+ }
+ },
+ {
+ "top": 315,
+ "h": 285,
+ "distance_m": 56122.19140625,
+ "colour": {
+ "file": "card-2-t15-colour.webp",
+ "bytes": 1052
+ },
+ "geometry": {
+ "file": "card-2-t15-geometry.webp",
+ "bytes": 10512
+ }
+ }
+ ],
+ [
+ {
+ "top": 248,
+ "h": 352,
+ "distance_m": 1396.94775390625,
+ "colour": {
+ "file": "card-0-t16-colour.webp",
+ "bytes": 810
+ },
+ "geometry": {
+ "file": "card-0-t16-geometry.webp",
+ "bytes": 11362
+ }
+ },
+ {
+ "top": 364,
+ "h": 236,
+ "distance_m": 6820.00048828125,
+ "colour": {
+ "file": "card-1-t16-colour.webp",
+ "bytes": 436
+ },
+ "geometry": {
+ "file": "card-1-t16-geometry.webp",
+ "bytes": 4668
+ }
+ },
+ {
+ "top": 303,
+ "h": 297,
+ "distance_m": 53429.6796875,
+ "colour": {
+ "file": "card-2-t16-colour.webp",
+ "bytes": 1488
+ },
+ "geometry": {
+ "file": "card-2-t16-geometry.webp",
+ "bytes": 18396
+ }
+ }
+ ],
+ [
+ {
+ "top": 286,
+ "h": 314,
+ "distance_m": 1396.3682861328125,
+ "colour": {
+ "file": "card-0-t17-colour.webp",
+ "bytes": 684
+ },
+ "geometry": {
+ "file": "card-0-t17-geometry.webp",
+ "bytes": 10000
+ }
+ },
+ {
+ "top": 240,
+ "h": 360,
+ "distance_m": 14172.7490234375,
+ "colour": {
+ "file": "card-1-t17-colour.webp",
+ "bytes": 1104
+ },
+ "geometry": {
+ "file": "card-1-t17-geometry.webp",
+ "bytes": 10308
+ }
+ },
+ {
+ "top": 235,
+ "h": 365,
+ "distance_m": 65859.734375,
+ "colour": {
+ "file": "card-2-t17-colour.webp",
+ "bytes": 1674
+ },
+ "geometry": {
+ "file": "card-2-t17-geometry.webp",
+ "bytes": 16832
+ }
+ }
+ ],
+ [
+ {
+ "top": 314,
+ "h": 286,
+ "distance_m": 1440.37646484375,
+ "colour": {
+ "file": "card-0-t18-colour.webp",
+ "bytes": 552
+ },
+ "geometry": {
+ "file": "card-0-t18-geometry.webp",
+ "bytes": 11138
+ }
+ },
+ {
+ "top": 122,
+ "h": 478,
+ "distance_m": 14387.8525390625,
+ "colour": {
+ "file": "card-1-t18-colour.webp",
+ "bytes": 1796
+ },
+ "geometry": {
+ "file": "card-1-t18-geometry.webp",
+ "bytes": 30488
+ }
+ },
+ {
+ "top": 211,
+ "h": 389,
+ "distance_m": 44942.2578125,
+ "colour": {
+ "file": "card-2-t18-colour.webp",
+ "bytes": 1396
+ },
+ "geometry": {
+ "file": "card-2-t18-geometry.webp",
+ "bytes": 17582
+ }
+ }
+ ],
+ [
+ {
+ "top": 317,
+ "h": 283,
+ "distance_m": 1704.598388671875,
+ "colour": {
+ "file": "card-0-t19-colour.webp",
+ "bytes": 704
+ },
+ "geometry": {
+ "file": "card-0-t19-geometry.webp",
+ "bytes": 12068
+ }
+ },
+ {
+ "top": 144,
+ "h": 456,
+ "distance_m": 11607.04296875,
+ "colour": {
+ "file": "card-1-t19-colour.webp",
+ "bytes": 1898
+ },
+ "geometry": {
+ "file": "card-1-t19-geometry.webp",
+ "bytes": 27774
+ }
+ },
+ {
+ "top": 111,
+ "h": 489,
+ "distance_m": 53726.9609375,
+ "colour": {
+ "file": "card-2-t19-colour.webp",
+ "bytes": 2010
+ },
+ "geometry": {
+ "file": "card-2-t19-geometry.webp",
+ "bytes": 24316
+ }
+ }
+ ],
+ [
+ {
+ "top": 297,
+ "h": 303,
+ "distance_m": 2042.0157470703125,
+ "colour": {
+ "file": "card-0-t20-colour.webp",
+ "bytes": 724
+ },
+ "geometry": {
+ "file": "card-0-t20-geometry.webp",
+ "bytes": 11566
+ }
+ },
+ {
+ "top": 95,
+ "h": 505,
+ "distance_m": 10982.046875,
+ "colour": {
+ "file": "card-1-t20-colour.webp",
+ "bytes": 1794
+ },
+ "geometry": {
+ "file": "card-1-t20-geometry.webp",
+ "bytes": 28234
+ }
+ },
+ {
+ "top": 171,
+ "h": 429,
+ "distance_m": 40730.703125,
+ "colour": {
+ "file": "card-2-t20-colour.webp",
+ "bytes": 1772
+ },
+ "geometry": {
+ "file": "card-2-t20-geometry.webp",
+ "bytes": 17478
+ }
+ }
+ ],
+ [
+ {
+ "top": 269,
+ "h": 331,
+ "distance_m": 2420.00048828125,
+ "colour": {
+ "file": "card-0-t21-colour.webp",
+ "bytes": 998
+ },
+ "geometry": {
+ "file": "card-0-t21-geometry.webp",
+ "bytes": 18072
+ }
+ },
+ {
+ "top": 174,
+ "h": 426,
+ "distance_m": 8230.6103515625,
+ "colour": {
+ "file": "card-1-t21-colour.webp",
+ "bytes": 1386
+ },
+ "geometry": {
+ "file": "card-1-t21-geometry.webp",
+ "bytes": 15038
+ }
+ },
+ {
+ "top": 199,
+ "h": 401,
+ "distance_m": 41044.6015625,
+ "colour": {
+ "file": "card-2-t21-colour.webp",
+ "bytes": 1644
+ },
+ "geometry": {
+ "file": "card-2-t21-geometry.webp",
+ "bytes": 16786
+ }
+ }
+ ],
+ [
+ {
+ "top": 279,
+ "h": 321,
+ "distance_m": 1978.4818115234375,
+ "colour": {
+ "file": "card-0-t22-colour.webp",
+ "bytes": 1478
+ },
+ "geometry": {
+ "file": "card-0-t22-geometry.webp",
+ "bytes": 19720
+ }
+ },
+ {
+ "top": 80,
+ "h": 520,
+ "distance_m": 7335.22265625,
+ "colour": {
+ "file": "card-1-t22-colour.webp",
+ "bytes": 1866
+ },
+ "geometry": {
+ "file": "card-1-t22-geometry.webp",
+ "bytes": 21744
+ }
+ },
+ {
+ "top": 232,
+ "h": 368,
+ "distance_m": 40101.375,
+ "colour": {
+ "file": "card-2-t22-colour.webp",
+ "bytes": 1206
+ },
+ "geometry": {
+ "file": "card-2-t22-geometry.webp",
+ "bytes": 6988
+ }
+ }
+ ],
+ [
+ {
+ "top": 351,
+ "h": 249,
+ "distance_m": 925.3698120117188,
+ "colour": {
+ "file": "card-0-t23-colour.webp",
+ "bytes": 946
+ },
+ "geometry": {
+ "file": "card-0-t23-geometry.webp",
+ "bytes": 10266
+ }
+ },
+ {
+ "top": 79,
+ "h": 521,
+ "distance_m": 7168.36474609375,
+ "colour": {
+ "file": "card-1-t23-colour.webp",
+ "bytes": 1384
+ },
+ "geometry": {
+ "file": "card-1-t23-geometry.webp",
+ "bytes": 20954
+ }
+ },
+ {
+ "top": 289,
+ "h": 311,
+ "distance_m": 41300.6875,
+ "colour": {
+ "file": "card-2-t23-colour.webp",
+ "bytes": 934
+ },
+ "geometry": {
+ "file": "card-2-t23-geometry.webp",
+ "bytes": 4296
+ }
+ }
+ ],
+ [
+ {
+ "top": 244,
+ "h": 356,
+ "distance_m": 1025.4903564453125,
+ "colour": {
+ "file": "card-0-t24-colour.webp",
+ "bytes": 1106
+ },
+ "geometry": {
+ "file": "card-0-t24-geometry.webp",
+ "bytes": 11518
+ }
+ },
+ {
+ "top": 159,
+ "h": 441,
+ "distance_m": 11321.796875,
+ "colour": {
+ "file": "card-1-t24-colour.webp",
+ "bytes": 1558
+ },
+ "geometry": {
+ "file": "card-1-t24-geometry.webp",
+ "bytes": 18134
+ }
+ },
+ {
+ "top": 319,
+ "h": 281,
+ "distance_m": 57565.35546875,
+ "colour": {
+ "file": "card-2-t24-colour.webp",
+ "bytes": 954
+ },
+ "geometry": {
+ "file": "card-2-t24-geometry.webp",
+ "bytes": 6602
+ }
+ }
+ ],
+ [
+ {
+ "top": 229,
+ "h": 371,
+ "distance_m": 933.5433349609375,
+ "colour": {
+ "file": "card-0-t25-colour.webp",
+ "bytes": 808
+ },
+ "geometry": {
+ "file": "card-0-t25-geometry.webp",
+ "bytes": 12278
+ }
+ },
+ {
+ "top": 72,
+ "h": 528,
+ "distance_m": 5733.2158203125,
+ "colour": {
+ "file": "card-1-t25-colour.webp",
+ "bytes": 1614
+ },
+ "geometry": {
+ "file": "card-1-t25-geometry.webp",
+ "bytes": 15386
+ }
+ },
+ {
+ "top": 313,
+ "h": 287,
+ "distance_m": 59443.39453125,
+ "colour": {
+ "file": "card-2-t25-colour.webp",
+ "bytes": 1490
+ },
+ "geometry": {
+ "file": "card-2-t25-geometry.webp",
+ "bytes": 16294
+ }
+ }
+ ],
+ [
+ {
+ "top": 250,
+ "h": 350,
+ "distance_m": 673.9866943359375,
+ "colour": {
+ "file": "card-0-t26-colour.webp",
+ "bytes": 680
+ },
+ "geometry": {
+ "file": "card-0-t26-geometry.webp",
+ "bytes": 9514
+ }
+ },
+ {
+ "top": 28,
+ "h": 572,
+ "distance_m": 5613.7412109375,
+ "colour": {
+ "file": "card-1-t26-colour.webp",
+ "bytes": 1432
+ },
+ "geometry": {
+ "file": "card-1-t26-geometry.webp",
+ "bytes": 20908
+ }
+ },
+ {
+ "top": 338,
+ "h": 262,
+ "distance_m": 65859.734375,
+ "colour": {
+ "file": "card-2-t26-colour.webp",
+ "bytes": 1384
+ },
+ "geometry": {
+ "file": "card-2-t26-geometry.webp",
+ "bytes": 14708
+ }
+ }
+ ],
+ [
+ {
+ "top": 278,
+ "h": 322,
+ "distance_m": 533.818603515625,
+ "colour": {
+ "file": "card-0-t27-colour.webp",
+ "bytes": 714
+ },
+ "geometry": {
+ "file": "card-0-t27-geometry.webp",
+ "bytes": 6664
+ }
+ },
+ {
+ "top": 24,
+ "h": 576,
+ "distance_m": 6389.61474609375,
+ "colour": {
+ "file": "card-1-t27-colour.webp",
+ "bytes": 1470
+ },
+ "geometry": {
+ "file": "card-1-t27-geometry.webp",
+ "bytes": 23794
+ }
+ },
+ {
+ "top": 344,
+ "h": 256,
+ "distance_m": 50670.5078125,
+ "colour": {
+ "file": "card-2-t27-colour.webp",
+ "bytes": 1080
+ },
+ "geometry": {
+ "file": "card-2-t27-geometry.webp",
+ "bytes": 11834
+ }
+ }
+ ],
+ [
+ {
+ "top": 309,
+ "h": 291,
+ "distance_m": 500.0000305175781,
+ "colour": {
+ "file": "card-0-t28-colour.webp",
+ "bytes": 562
+ },
+ "geometry": {
+ "file": "card-0-t28-geometry.webp",
+ "bytes": 3694
+ }
+ },
+ {
+ "top": 94,
+ "h": 506,
+ "distance_m": 5985.80078125,
+ "colour": {
+ "file": "card-1-t28-colour.webp",
+ "bytes": 1472
+ },
+ "geometry": {
+ "file": "card-1-t28-geometry.webp",
+ "bytes": 23606
+ }
+ },
+ {
+ "top": 338,
+ "h": 262,
+ "distance_m": 41220.84765625,
+ "colour": {
+ "file": "card-2-t28-colour.webp",
+ "bytes": 782
+ },
+ "geometry": {
+ "file": "card-2-t28-geometry.webp",
+ "bytes": 5094
+ }
+ }
+ ],
+ [
+ {
+ "top": 327,
+ "h": 273,
+ "distance_m": 500.0000305175781,
+ "colour": {
+ "file": "card-0-t29-colour.webp",
+ "bytes": 612
+ },
+ "geometry": {
+ "file": "card-0-t29-geometry.webp",
+ "bytes": 3196
+ }
+ },
+ {
+ "top": 53,
+ "h": 547,
+ "distance_m": 7741.88134765625,
+ "colour": {
+ "file": "card-1-t29-colour.webp",
+ "bytes": 1768
+ },
+ "geometry": {
+ "file": "card-1-t29-geometry.webp",
+ "bytes": 26930
+ }
+ },
+ {
+ "top": 334,
+ "h": 266,
+ "distance_m": 39778.60546875,
+ "colour": {
+ "file": "card-2-t29-colour.webp",
+ "bytes": 802
+ },
+ "geometry": {
+ "file": "card-2-t29-geometry.webp",
+ "bytes": 4504
+ }
+ }
+ ],
+ [
+ {
+ "top": 324,
+ "h": 276,
+ "distance_m": 500.0000305175781,
+ "colour": {
+ "file": "card-0-t30-colour.webp",
+ "bytes": 476
+ },
+ "geometry": {
+ "file": "card-0-t30-geometry.webp",
+ "bytes": 3626
+ }
+ },
+ {
+ "top": 58,
+ "h": 542,
+ "distance_m": 7652.43017578125,
+ "colour": {
+ "file": "card-1-t30-colour.webp",
+ "bytes": 1816
+ },
+ "geometry": {
+ "file": "card-1-t30-geometry.webp",
+ "bytes": 28380
+ }
+ },
+ {
+ "top": 344,
+ "h": 256,
+ "distance_m": 39515.10546875,
+ "colour": {
+ "file": "card-2-t30-colour.webp",
+ "bytes": 756
+ },
+ "geometry": {
+ "file": "card-2-t30-geometry.webp",
+ "bytes": 4638
+ }
+ }
+ ],
+ [
+ {
+ "top": 330,
+ "h": 270,
+ "distance_m": 548.6560668945312,
+ "colour": {
+ "file": "card-0-t31-colour.webp",
+ "bytes": 478
+ },
+ "geometry": {
+ "file": "card-0-t31-geometry.webp",
+ "bytes": 4738
+ }
+ },
+ {
+ "top": 85,
+ "h": 515,
+ "distance_m": 7773.806640625,
+ "colour": {
+ "file": "card-1-t31-colour.webp",
+ "bytes": 1642
+ },
+ "geometry": {
+ "file": "card-1-t31-geometry.webp",
+ "bytes": 25034
+ }
+ },
+ {
+ "top": 326,
+ "h": 274,
+ "distance_m": 39216.27734375,
+ "colour": {
+ "file": "card-2-t31-colour.webp",
+ "bytes": 760
+ },
+ "geometry": {
+ "file": "card-2-t31-geometry.webp",
+ "bytes": 4148
+ }
+ }
+ ]
+ ],
+ "bytes": 1198740,
+ "attribution": {
+ "credit_line": "Contains modified Copernicus data: DEM \u00a9 DLR e.V. 2010-2014 and \u00a9 Airbus Defence and Space GmbH 2014-2018 provided under COPERNICUS by the European Union and ESA; all rights reserved.",
+ "licence": "Copernicus DEM licence: free, full and open access, with the credit line shown",
+ "dem_source": "Copernicus DEM GLO-30 (30 m)",
+ "url": "https://spacedata.copernicus.eu/collections/copernicus-digital-elevation-model"
+ }
+}
diff --git a/public/ridge/vienna-6815bb9dca99/card-0-colour.webp b/public/ridge/vienna-6815bb9dca99/card-0-colour.webp
deleted file mode 100644
index 133c6cd8..00000000
Binary files a/public/ridge/vienna-6815bb9dca99/card-0-colour.webp and /dev/null differ
diff --git a/public/ridge/vienna-6815bb9dca99/card-0-geometry.webp b/public/ridge/vienna-6815bb9dca99/card-0-geometry.webp
deleted file mode 100644
index 4e0c79f6..00000000
Binary files a/public/ridge/vienna-6815bb9dca99/card-0-geometry.webp and /dev/null differ
diff --git a/public/ridge/vienna-6815bb9dca99/card-1-colour.webp b/public/ridge/vienna-6815bb9dca99/card-1-colour.webp
deleted file mode 100644
index 21ea85ab..00000000
Binary files a/public/ridge/vienna-6815bb9dca99/card-1-colour.webp and /dev/null differ
diff --git a/public/ridge/vienna-6815bb9dca99/card-1-geometry.webp b/public/ridge/vienna-6815bb9dca99/card-1-geometry.webp
deleted file mode 100644
index 06c99e06..00000000
Binary files a/public/ridge/vienna-6815bb9dca99/card-1-geometry.webp and /dev/null differ
diff --git a/public/ridge/vienna-6815bb9dca99/card-2-colour.webp b/public/ridge/vienna-6815bb9dca99/card-2-colour.webp
deleted file mode 100644
index 66d048e7..00000000
Binary files a/public/ridge/vienna-6815bb9dca99/card-2-colour.webp and /dev/null differ
diff --git a/public/ridge/vienna-6815bb9dca99/card-2-geometry.webp b/public/ridge/vienna-6815bb9dca99/card-2-geometry.webp
deleted file mode 100644
index 631e894b..00000000
Binary files a/public/ridge/vienna-6815bb9dca99/card-2-geometry.webp and /dev/null differ
diff --git a/public/ridge/vienna-6815bb9dca99/manifest.json b/public/ridge/vienna-6815bb9dca99/manifest.json
deleted file mode 100644
index 935e5abd..00000000
--- a/public/ridge/vienna-6815bb9dca99/manifest.json
+++ /dev/null
@@ -1,100 +0,0 @@
-{
- "schema": 2,
- "baker_version": 2,
- "bake_id": "6815bb9dca99",
- "place": {
- "id": "vienna",
- "name": "Vienna, looking SW to Rax/Schneeberg",
- "lat": 48.1929826,
- "lon": 16.3534237,
- "altitude_km": 0.18330000000000002,
- "eye_m": 213.3
- },
- "view": {
- "look_az_deg": 214.0,
- "plane_h": 600,
- "px_per_deg_h": 17.77777777777778,
- "px_per_deg_v": 177.77777777777777,
- "exaggeration": 10.0,
- "horizon_row": 294.58455032829386,
- "sky_row": 24.0,
- "near_row": 396.0,
- "window_deg": 72,
- "plane_w": 1280
- },
- "curvature": {
- "r_earth_m": 6371000.0,
- "k_ref": 0.13
- },
- "encoding": {
- "log_d_min": 6.214608098422191,
- "log_d_max": 11.462786662662916,
- "normal": "rt8"
- },
- "camera": {
- "r_m": 200.0,
- "heading_max_deg": 23.0
- },
- "cards": [
- {
- "top": 182,
- "h": 418,
- "near_m": null,
- "far_m": 5392.093596252347,
- "median_m": 1478.456787109375,
- "distance_m": 1478.456787109375,
- "scale": 1.1564386078720779,
- "colour": {
- "file": "card-0-colour.webp",
- "bytes": 4598
- },
- "geometry": {
- "file": "card-0-geometry.webp",
- "bytes": 95716
- }
- },
- {
- "top": 24,
- "h": 576,
- "near_m": 5392.093596252347,
- "far_m": 39877.08347165139,
- "median_m": 11107.0283203125,
- "distance_m": 11107.0283203125,
- "scale": 1.0183368002838622,
- "colour": {
- "file": "card-1-colour.webp",
- "bytes": 8396
- },
- "geometry": {
- "file": "card-1-geometry.webp",
- "bytes": 130870
- }
- },
- {
- "top": 40,
- "h": 560,
- "near_m": 39877.08347165139,
- "far_m": null,
- "median_m": 48378.26953125,
- "distance_m": 48378.26953125,
- "scale": 1.0041512491408657,
- "colour": {
- "file": "card-2-colour.webp",
- "bytes": 9718
- },
- "geometry": {
- "file": "card-2-geometry.webp",
- "bytes": 118378
- }
- }
- ],
- "w": 1280,
- "h": 600,
- "bytes": 367676,
- "attribution": {
- "credit_line": "Contains modified Copernicus data: DEM \u00a9 DLR e.V. 2010-2014 and \u00a9 Airbus Defence and Space GmbH 2014-2018 provided under COPERNICUS by the European Union and ESA; all rights reserved.",
- "licence": "Copernicus DEM licence: free, full and open access, with the credit line shown",
- "dem_source": "Copernicus DEM GLO-30 (30 m)",
- "url": "https://spacedata.copernicus.eu/collections/copernicus-digital-elevation-model"
- }
-}
diff --git a/scripts/ridge-bake/README.md b/scripts/ridge-bake/README.md
index d74f4871..7c2c25c3 100644
--- a/scripts/ridge-bake/README.md
+++ b/scripts/ridge-bake/README.md
@@ -1,6 +1,6 @@
# ridge-bake
-Offline baker for the ridge backdrop: it turns a Copernicus DEM into K+1 G-buffer cards per place, split by K authored seams, plus a `manifest.json` (schema 2) and an `index.json` that the runtime reads. Each card is a colour WebP (albedo and coverage) and a geometry WebP (normal and log-distance). The baker is not shipped; `public/ridge/` holds its output. The client owns lighting, haze and ink: no sun, haze or shadow is baked.
+Offline baker for the ridge backdrop: it turns a Copernicus DEM into K+1 G-buffer cards per place, split by K authored seams and cut into 32 azimuth tiles round the whole 360 degree ring, plus a `manifest.json` (schema 3) and an `index.json` that the runtime reads. Each card tile is a colour WebP (albedo and coverage) and a geometry WebP (normal and log-distance). The baker is not shipped; `public/ridge/` holds its output. The client owns lighting, haze and ink: no sun, haze or shadow is baked.
## Run
@@ -8,7 +8,7 @@ Offline baker for the ridge backdrop: it turns a Copernicus DEM into K+1 G-buffe
python3 -I scripts/ridge-bake/export.py --tiles DIR --out public/ridge/ [--work DIR] [--sheet contact.png]
```
-Needs Python 3 with `numpy`, `tifffile` and `imagecodecs`. `--tiles` is a directory of Copernicus GLO-30 tiles (never committed); `--work` caches the mosaic and rays (default `$TMPDIR/ridge-bake-work`); `--sheet` writes the contact sheet (the composite, every card alone and the depth image with every seam, lit by one fixed light). `python3 -I scripts/ridge-bake/export.py --write-schema` rewrites `ridge-bake.schema.json`, which the tests pin.
+Needs Python 3 with `numpy`, `tifffile` and `imagecodecs`. `--tiles` is a directory of Copernicus GLO-30 tiles (never committed); `--work` caches the mosaic and rays (default `$TMPDIR/ridge-bake-work`); `--sheet` writes the contact sheet at 1/4 of the ring's width (the ring composite, every card's strip alone and the depth image with every seam, the 32 tile boundaries drawn, lit by one fixed light). The bake prints `r_max_m`, the resident run and the worst fit error per card. `python3 -I scripts/ridge-bake/export.py --write-schema` rewrites `ridge-bake.schema.json`, which the tests pin.
Tests: `RIDGE_PY= RIDGE_TILES=DIR scripts/ridge-bake/tests/run.sh [test_ridge.py|mutate.py]` (`mutate.py` re-introduces each rule's failure into a copy of the baker and fails if a test does not notice).
@@ -31,13 +31,16 @@ Files are `Copernicus_DSM_COG_10_dd_00_ddd_00_DEM.tif`; the list below
1. **March.** `stage0` marches 6400 azimuth columns of rays over the DEM with Earth curvature and refraction (`ridge.elev`), cached by a key of its inputs.
2. **Low-pass.** `prefilter` blurs the sampled heights with a Gaussian of `prefilter_m` metres along each ray and across rays at equal distance (sigma = `prefilter_m` / (distance x column width) columns), then recomputes the angles. Roofs go, hills stay.
-3. **View.** `set_view` maps angle to row linearly: the highest skyline angle in the window sits at 4% of the frame height, the lowest at 66%, clamped to 1x to 10x vertical exaggeration.
-4. **Seams.** `coverage` counts the visible rows of the opaque view per log-distance bin and column. `seams` finds one seam per authored split per column by dynamic programming (seam carving, forward energy): it sits in a gap between depths, moving it costs 2 per bin plus the visible rows it sweeps (so it never hops across a ridge between two columns and splits it side by side), a seam inside visible terrain is cheap to cross-fade, the authored depth only breaks ties. Seam k stays 0.4 nat beyond seam k-1.
-5. **Cards.** `cards` makes card i from the first visible hit at or beyond seam i-1 (layered depth: a farther card keeps the terrain a nearer ridge hides), alpha 1 minus a smoothstep over seam i in log-distance (the cross-fade), crest rows with fractional coverage, distance and normal interpolated between samples by angle, albedo from a small height and slope material, cropped to the rows where alpha is not zero. The rows of card i > 0 below the angle of its first sample (hit and first sample of the card) are its **wall**: the extruded face of the ridge the card starts at, which keeps that sample's distance, wears the ground material at its height with the face up, and is flagged `wall` (card 0 has none: its rows there are the ground). The alpha-over composite of the cards equals the opaque view; `check_cover` refuses a bake that differs by more than 0.02.
-6. **Camera.** `CAMERA_R_M` (+200 m, signed: + forward, - backward; `camera_r_m` in `places.json` per place) and `HEADING_MAX_DEG` (23) are the camera on a circle round the bake centre (ruling `ridge-camera-on-circle`). `pack` gives each card `distance_m` (the median distance of its solid pixels that are not wall; `median_m` is the same number) and `scale = distance_m / (distance_m - r)`, the card's pan rate per unit of heading and its static size. It refuses `|r|` at or above half the nearest card's distance, a card with no solid terrain apart from its wall, and (in `write_bake`) a camera that lifts the nearest card off the frame bottom (every backward `r`: the bake is not wider and taller yet) or shrinks a card below what a 16:9 viewport needs at rest.
-7. **Normals.** `normals` takes the along-ray slope and the across-ray slope at equal distance (neighbouring columns, same sample), both times the vertical exaggeration.
+3. **View.** `set_view` maps angle to row linearly: the highest skyline angle of the whole ring sits at 4% of the frame height, the lowest at 66%, clamped to 1x to 10x vertical exaggeration (ruling `ridge-ring-vertical-anchors`: every azimuth sits inside one frame).
+4. **Seams.** `coverage` counts the visible rows of the opaque view per log-distance bin and column. `seams` finds one seam per authored split per column by dynamic programming (seam carving, forward energy): it sits in a gap between depths, moving it costs 2 per bin plus the visible rows it sweeps (so it never hops across a ridge between two columns and splits it side by side), a seam inside visible terrain is cheap to cross-fade, the authored depth only breaks ties. Seam k stays 0.4 nat beyond seam k-1. The DP runs over the ring three times side by side and keeps the middle lap, so a seam is continuous across the wrap (column 6399 to 0) and a tile boundary is only a crop.
+5. **Cards.** `cards` runs per tile, on that tile's columns and the matching normals (it is column-independent: a tile is a crop of per-column results, so no seam appears at a tile boundary). It makes card i from the first visible hit at or beyond seam i-1 (layered depth: a farther card keeps the terrain a nearer ridge hides), alpha 1 minus a smoothstep over seam i in log-distance (the cross-fade), crest rows with fractional coverage, distance and normal interpolated between samples by angle, albedo from a small height and slope material, cropped to the rows where alpha is not zero. The rows of card i > 0 below the angle of its first sample (hit and first sample of the card) are its **wall**: the extruded face of the ridge the card starts at, which keeps that sample's distance, wears the ground material at its height with the face up, and is flagged `wall` (card 0 has none: its rows there are the ground). The alpha-over composite of the cards equals the opaque view; `check_cover` refuses a tile that differs by more than 0.02.
+6. **Tiles.** The ring is absolute compass, column 0 = north, column c at azimuth (c + 0.5) / 6400 x 360; `places.json`'s `az_deg` / `look_at` is only the rest azimuth (`view.look_az_deg`). Tile t owns columns [200 t, 200 t + 200) (11.25 degrees) and its files hold [200 t - 2, 200 t + 202): two columns of real neighbour data each side (the client's ink pass and lighting read one texel each way; the client crops it), taken periodically by `ridge.ring_cols`. Per card and tile the file is cropped to the rows where that tile's 8-bit alpha is not zero (`top`, `h`); a card that holds nothing in a tile is `null` there (the client interpolates its distance from the neighbours); a card with no solid pixel in any tile is refused.
+7. **Distance and the offset range.** The bake holds no camera (ruling `ridge-camera-full-ring`). `pack` gives each card tile `distance_m` = exp(median ln d) over the tile's solid pixels that are not wall (its interior 200 columns); the client derives each card's slide from that and the viewer's offset r and heading. `camera.r_max_m` is the largest |r| (never above half the nearest card's smallest tile distance) at which, for every tile, card and phi (24 steps of the camera's angle on the circle against its heading; the offset-only rotation mode moves phi round the whole circle), the least-squares line `a + s beta` fitted to the exact view angle `atan2(R sin beta - r sin phi, R cos beta - r cos phi)` over the widest viewport (`HFOV_MAX_DEG` = 72 / 1.1) errs by at most `FIT_PX_MAX` = 24 card px (the continuous error: the line by quadrature over the viewport, the worst error looked for on 513 points, so a handful of samples cannot undercount it); the card sits at the tile's `distance_m` (R = d) and the line is fitted for that same distance, and the resident gate (below) must hold at r_max_m too. `camera.r_max_forward_m` is the same search at phi = 0 alone (same `FIT_PX_MAX`, the same half-distance cap, the same resident gate): the camera pushed forward along its heading, which is where the offset stays when the view direction turns with it (the modes 'still' and 'both'), so it is at least `r_max_m`; the client takes `r_max_m` for the offset-only mode and for a backward offset, `r_max_forward_m` for a forward one in the other modes (`view.ts` `offsetRange`). `FIT_PX_MAX` is provisional, tuned by eye (ruling `ridge-offset-range-fit`). A bake whose `r_max_m` is below `R_MAX_FLOOR_M` = 25 m is refused, naming the card and tile.
+8. **Normals.** `normals` takes the along-ray slope and the across-ray slope at equal distance (neighbouring columns, same sample), both times the vertical exaggeration.
-Files per card `i`: `card--colour.webp` (lossy RGB albedo, lossless straight alpha) and `card--geometry.webp` (lossless: R, G = (n + 1) / 2 for the normal's along and across components, B = log-distance normalised between `encoding.log_d_min` and `log_d_max`; wall pixels write R = G = 255, a code outside the unit disc that no real normal reaches). The manifest lists the cards nearest first with their row band (`top`, `h`), median seam depths, `distance_m`, `scale` and files, and the `camera` {`r_m`, `heading_max_deg`}; the runtime paints the list last to first. `check_budget` refuses more than `MAX_CARDS` cards, more than 1.5 MB of card files, or more than 20 MB decoded (2 textures x width x band rows x 4 bytes per card); a cap is never raised to fit a bake.
+Files per card `i` and tile `t`: `card--t-colour.webp` (lossy RGB albedo, lossless straight alpha) and `card--t-geometry.webp` (lossless: R, G = (n + 1) / 2 for the normal's along and across components, B = log-distance normalised between `encoding.log_d_min` and `log_d_max`; wall pixels write R = G = 255, a code outside the unit disc that no real normal reaches), each 204 columns wide. The manifest lists the cards nearest first (`near_m`, `far_m`: the median seam depths over the ring) and `tiles[t][i]` = `{ top, h, distance_m, colour, geometry }` or `null`; the runtime paints the cards last to first. The `bake_id` is the sha256 of the files, tile-major, then card, colour then geometry.
+
+Budgets (`check_budget`; a cap is never raised to fit a bake, the lever is `TILES` = 64): every file of one tile at most 235 kB (1.5 MB per 72 degrees), every file of the place at most 7.5 MB, at most 6 cards, and the lit canvases (4 bytes x 202 columns x band rows, per card) of the worst run of N consecutive tiles, cyclic, at most 20 MB, where N = ceil(arc_max / 11.25) + 5 and arc_max = `HFOV_MAX_DEG` / s_min + 2 (r_max / Rmin) 57.3 degrees with Rmin the nearest card's smallest tile distance and s_min = Rmin / (Rmin + r_max). The loader decodes one tile at a time, so the decode transient is not gated.
## Licence
diff --git a/scripts/ridge-bake/export.py b/scripts/ridge-bake/export.py
index 0ace0244..6d3c8c98 100644
--- a/scripts/ridge-bake/export.py
+++ b/scripts/ridge-bake/export.py
@@ -1,28 +1,34 @@
-"""Ridge backdrop export: bake a place with ridge.py and write its K+1 G-buffer cards (colour + geometry WebP each), a manifest v2 and the index.
+"""Ridge backdrop export: bake a place with ridge.py and write its K+1 G-buffer cards as 32 azimuth tiles each (colour + geometry WebP per card per tile), a manifest v3 and the index.
python3 -I scripts/ridge-bake/export.py --tiles DIR --out public/ridge/ [--work DIR] [--sheet contact.png]
python3 -I scripts/ridge-bake/export.py --write-schema (rewrites ridge-bake.schema.json from SCHEMA below)
-The runtime reads manifest.json (SCHEMA is its contract) and nothing else about the bake; the camera (ruling ridge-camera-on-circle) is the baker's, so per-card scale and the heading range ride the manifest; it lights the cards itself (ruling ridge-cards-runtime-lit). The pure parts (budget, bake_id, manifest, index, schema check)
-import no baker; bake_place imports ridge, which needs RIDGE_TILES and RIDGE_WORK (main sets them from --tiles / --work)."""
+The runtime reads manifest.json (SCHEMA is its contract) and nothing else about the bake. The ring is the whole 360 degrees (ruling ridge-camera-full-ring), absolute compass, column 0 = north, cut into TILES tiles of TILE_W columns plus an APRON of real neighbour
+columns each side; the bake holds no camera: it ships each card tile's distance_m and camera.r_max_m, the largest offset the per-card linear slide can take (ruling ridge-offset-range-fit); the client lights the cards itself (ruling ridge-cards-runtime-lit).
+The pure parts (budget, bake_id, manifest, index, schema check) import no baker; bake_place imports ridge, which needs RIDGE_TILES and RIDGE_WORK (main sets them from --tiles / --work)."""
import os, sys, json, math, shutil, hashlib, argparse, tempfile
from pathlib import Path
+from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import numpy as np, imagecodecs
-BAKER_VERSION = 2
-WINDOW_DEG = 72
-PLANE_W = 1280 # every card is the whole 72 deg window wide
-PLANE_W_MAX = 4096
-MAX_CARDS = 6 # per place; a full-frame card decodes to 2 textures x 1280 x 600 x 4 B = 6.1 MB, the decode budget below holds 3 of them and cropping to the row band is what lets a livelier place have more
-TOTAL_BYTES_MAX = 1_500_000 # every card file of a place together
-DECODE_BYTES_MAX = 20_000_000 # the cards decoded: sum over cards of 2 textures x w x band h x 4 bytes
-COVER_TOL = 0.02 # the composite of the cards may differ from the opaque view by this much of a pixel, nowhere more
-CAMERA_R_M = 200.0 # ruling ridge-camera-on-circle: the camera sits on a circle of this radius round the bake centre, signed, + forward along its heading and - backward; places.json may set camera_r_m per place. The steward's calibration for feel, tuned in the art pass
-HEADING_MAX_DEG = 23.0 # the drift's heading range each side of look_az: today's phone sweep, 409 card px (the runtime caps it by what a viewport can cover)
-R_FRAC_MAX = 0.5 # |r| stays under this share of the nearest card's distance: the offset must stay well inside the nearest cylinder
-REST_SCALE_MIN = 1 / 1.1 # a 16:9 viewport is width-bound and the runtime's plane is 1.1 viewport widths wide (view.ts windowFor, DRIFT_FRAC 0.05 a side): a card scaled below this leaves the viewport's edge bare at rest
+BAKER_VERSION = 5
+RING_W = 6400 # the ring's columns (ridge.W, asserted in bake_place): column c is at azimuth (c + 0.5) / RING_W x 360, column 0 = north
+TILES = 32 # azimuth tiles of the ring, each card cut into TILES files per kind (ruling ridge-camera-full-ring: the client loads the arc near its heading)
+TILE_W = RING_W // TILES # 200 columns = 11.25 degrees owned by a tile
+APRON = 2 # real neighbour columns each side in a tile's file: the client's ink pass and lighting read +-1 texel; the client crops it
+LIT_W = TILE_W + 2 # a lit canvas keeps one apron texel each side
+TILE_DEG = 360.0 / TILES
+MAX_CARDS = 6 # per place; a card is cropped to its row band in every tile, which is what lets a livelier place have more
+TILE_BYTES_MAX = 235_000 # every file of one tile (1.5 MB per 72 degrees, scaled to 11.25)
+PLACE_BYTES_MAX = 7_500_000 # every file of the place
+RESIDENT_BYTES_MAX = 20_000_000 # the lit canvases (4 B x LIT_W x band h per card) of the worst run of consecutive tiles, cyclic; the loader decodes one tile at a time, so the decode transient is not gated
+HFOV_MAX_DEG = 72 / 1.1 # the widest viewport: a 16:9 viewport with 1.1 widths of plane (view.ts windowFor)
+FIT_PX_MAX = 24.0 # the per-card linear slide may err by this many card pixels over the viewport (provisional, tuned by eye: ruling ridge-offset-range-fit)
+R_MAX_FLOOR_M = 25.0 # a bake whose cards cannot take this offset is refused
+PHI_STEPS = 24 # the camera's angle on its circle against its heading, sampled by the r_max search
+COVER_TOL = 0.02 # the composite of a tile's cards may differ from the opaque view by this much of a pixel, nowhere more
WEBP_QUALITY = 80
SHEET_SKY = (0.80, 0.86, 0.94) # the flat sky of the contact sheet
SHEET_LIGHT = (-0.35, 0.55, 0.76) # the fixed light of the contact sheet in (along ray, across ray, up); the sheet is a look at the cards, the client lights the real thing
@@ -35,26 +41,34 @@ ATTRIBUTION = dict(
# ------------------------------------------------------------------------------------ schema (the one dict the schema file and the validator both come from)
_num, _int, _str = {'type': 'number'}, {'type': 'integer'}, {'type': 'string'}
_numnull = {'type': ['number', 'null']}
+_tz = {'type': 'string', 'format': 'iana-tz'} # an IANA zone the system knows, as ridge.load_preset requires; validate() checks it
def _obj(**props): return {'type': 'object', 'required': list(props), 'additionalProperties': False, 'properties': props}
+def _objnull(**props): return dict(_obj(**props), type=['object', 'null'])
_file = _obj(file=_str, bytes=_int)
-SCHEMA = {'$schema': 'https://json-schema.org/draft/2020-12/schema', 'title': 'ridge-bake manifest v2 and index v1', '$defs': {
- 'manifest': _obj(schema={'const': 2}, baker_version=_int, bake_id=_str,
- place=_obj(id=_str, name=_str, lat=_num, lon=_num, altitude_km=_num, eye_m=_num),
- view=_obj(look_az_deg=_num, window_deg={'const': WINDOW_DEG}, plane_w={'type': 'integer', 'maximum': PLANE_W_MAX}, plane_h=_int, px_per_deg_h=_num, px_per_deg_v=_num, exaggeration=_num, horizon_row=_num, sky_row=_num, near_row=_num),
+SCHEMA = {'$schema': 'https://json-schema.org/draft/2020-12/schema', 'title': 'ridge-bake manifest v3 and index v1', '$defs': {
+ 'manifest': _obj(schema={'const': 3}, baker_version=_int, bake_id=_str,
+ place=_obj(id=_str, name=_str, lat=_num, lon=_num, altitude_km=_num, eye_m=_num, tz=_tz),
+ view=_obj(look_az_deg=_num, ring_w={'const': RING_W}, tile_w={'const': TILE_W}, tiles={'const': TILES}, apron={'const': APRON}, plane_h=_int, px_per_deg_h=_num, px_per_deg_v=_num, exaggeration=_num, horizon_row=_num, sky_row=_num, near_row=_num),
curvature=_obj(r_earth_m=_num, k_ref=_num),
encoding=_obj(log_d_min=_num, log_d_max=_num, normal={'const': 'rt8'}),
- camera=_obj(r_m=_num, heading_max_deg=_num),
- cards={'type': 'array', 'minItems': 1, 'maxItems': MAX_CARDS, 'items': dict(_obj(top=_int, h=_int, near_m=_numnull, far_m=_numnull, median_m=_num, distance_m=_num, scale=_num, colour=_file, geometry=_file),
- description="nearest first; the runtime paints the list last to first. top and h place the card back at its rows of the frame; near_m and far_m are the median seam depths, null at the ends; median_m and distance_m are the median distance of the card's solid pixels that are not wall; scale = distance_m / (distance_m - camera.r_m) is the card's pan rate per unit of heading and its static size.")},
- w=_int, h=_int, bytes=_int,
+ camera=_obj(r_max_m=_num, r_max_forward_m=_num),
+ cards={'type': 'array', 'minItems': 1, 'maxItems': MAX_CARDS, 'items': _obj(near_m=_numnull, far_m=_numnull),
+ 'description': "nearest first; the runtime paints the list last to first. near_m and far_m are the median seam depths over the ring, null at the ends."},
+ tiles={'type': 'array', 'minItems': TILES, 'maxItems': TILES, 'items': {'type': 'array', 'minItems': 1, 'maxItems': MAX_CARDS, 'items': _objnull(top=_int, h=_int, distance_m=_num, colour=_file, geometry=_file)},
+ 'description': "tiles[t][i] is card i in tile t, or null where the card holds nothing in that tile (the client takes its distance from the neighbouring tiles). Tile t owns the ring columns [tile_w t, tile_w (t + 1)), column c at azimuth (c + 0.5) / ring_w x 360, 0 = north; its files hold [tile_w t - apron, tile_w (t + 1) + apron), wrapping at the ring's end, and are tile_w + 2 apron columns wide. top and h place the card's band back at its rows of the frame; distance_m = exp(median ln d) of the card's solid pixels in the tile that are not wall (the interior tile_w columns)."},
+ bytes=_int,
attribution=_obj(credit_line=_str, licence=_str, dem_source=_str, url=_str)),
'index': _obj(schema={'const': 1}, default=_str, places={'type': 'object', 'additionalProperties': _str})}}
+def tile_file(i, t, kind): return f'card-{i}-t{t:02d}-{kind}.webp'
def validate(x, s, path='$'):
"""The subset of JSON Schema SCHEMA uses; raises ValueError naming the path."""
if '$ref' in s: return validate(x, SCHEMA['$defs'][s['$ref'].split('/')[-1]], path)
tys = s.get('type'); tys = [tys] if isinstance(tys, str) else tys; py = {'object': dict, 'array': list, 'string': str, 'number': (int, float), 'integer': int, 'null': type(None)}
if tys and not any(isinstance(x, py[t]) and not (isinstance(x, bool) and t != 'null') for t in tys): raise ValueError(f'{path}: not a {"/".join(tys)}')
+ if s.get('format') == 'iana-tz':
+ try: ZoneInfo(x)
+ except (ZoneInfoNotFoundError, ValueError, OSError): raise ValueError(f'{path}: {x!r} is not a time zone the system knows')
if 'const' in s and x != s['const']: raise ValueError(f"{path}: must be {s['const']!r}")
if 'enum' in s and x not in s['enum']: raise ValueError(f'{path}: not one of {s["enum"]}')
if 'maximum' in s and x > s['maximum']: raise ValueError(f'{path}: above {s["maximum"]}')
@@ -70,6 +84,18 @@ def validate(x, s, path='$'):
elif extra is False: raise ValueError(f'{path}: extra key {k}')
elif isinstance(extra, dict): validate(v, extra, f'{path}.{k}')
+def validate_manifest(m):
+ """The schema plus what it cannot say: every tile lists one entry per card, every card holds something in some tile, each file is named for its card and tile, bytes is the sum of the files."""
+ validate(m, SCHEMA['$defs']['manifest']); k = len(m['cards'])
+ for t, row in enumerate(m['tiles']):
+ if len(row) != k: raise ValueError(f'$.tiles[{t}]: {len(row)} entries for {k} cards')
+ for i, e in enumerate(row):
+ for kind in (('colour', 'geometry') if e else ()):
+ if e[kind]['file'] != tile_file(i, t, kind): raise ValueError(f'$.tiles[{t}][{i}].{kind}: file {e[kind]["file"]!r} is not {tile_file(i, t, kind)!r}')
+ for i in range(k):
+ if all(row[i] is None for row in m['tiles']): raise ValueError(f'card {i} is null in every tile')
+ if m['bytes'] != sum(e[kind]['bytes'] for row in m['tiles'] for e in row if e for kind in ('colour', 'geometry')): raise ValueError('bytes is not the sum of the files')
+
# ------------------------------------------------------------------------------------ cards -> bytes
def u8(a): return np.clip(np.rint(np.asarray(a) * 255.0), 0, 255).astype(np.uint8)
def encode_colour(albedo, alpha):
@@ -96,84 +122,151 @@ def check_cover(cards, opaque, tol=COVER_TOL):
err = np.abs(composite_alpha(cards, *opaque.shape) - opaque); bad = err > tol
if bad.any(): y, x = np.unravel_index(int(np.argmax(err)), err.shape); raise ValueError(f'the cards do not composite to the opaque view within {tol}: {int(bad.sum())} pixels differ, worst {err.max():.3f} at x={x} row {y}')
-def check_budget(card_bytes, w, bands):
- """Refuse a bake the runtime could not hold: more than MAX_CARDS cards, a card wider than PLANE_W_MAX, every card file together above TOTAL_BYTES_MAX, or the cards decoding (2 textures x w x band rows x 4 bytes each) above DECODE_BYTES_MAX."""
- if len(card_bytes) > MAX_CARDS: raise ValueError(f'{len(card_bytes)} cards, above {MAX_CARDS}')
- if w > PLANE_W_MAX: raise ValueError(f'card width {w} above {PLANE_W_MAX}')
- if sum(card_bytes) > TOTAL_BYTES_MAX: raise ValueError(f'the cards are {sum(card_bytes)} bytes, above {TOTAL_BYTES_MAX}')
- decoded = sum(2 * w * h * 4 for h in bands)
- if decoded > DECODE_BYTES_MAX: raise ValueError(f'the cards decode to {decoded} bytes, above {DECODE_BYTES_MAX}')
+def run_tiles(r_max_m, rmin_m):
+ """N, the consecutive tiles the loader keeps resident: the viewport arc at the smallest slide rate plus the offset's own swing (arc_max = HFOV_MAX_DEG / s_min + 2 (r_max / Rmin) 57.3 degrees, s_min = Rmin / (Rmin + r_max)), one straddled tile and two tiles of margin each side."""
+ s_min = rmin_m / (rmin_m + r_max_m); arc = HFOV_MAX_DEG / s_min + 2 * (r_max_m / rmin_m) * 57.3
+ return min(TILES, math.ceil(arc / TILE_DEG) + 1 + 4)
+def resident_bytes(bands, n):
+ """The lit canvases (4 bytes x LIT_W x band rows, per card) of the worst run of n consecutive tiles of the ring, wrapping. bands[t]: the row counts of the cards that tile holds."""
+ per = [sum(4 * LIT_W * h for h in b) for b in bands]; n = min(n, TILES)
+ return max(sum(per[(t + k) % TILES] for k in range(n)) for t in range(TILES))
+def check_budget(n_cards, tile_bytes, bands, r_max_m, rmin_m):
+ """Refuse a bake the runtime could not hold: more than MAX_CARDS cards, a tile whose files together are above TILE_BYTES_MAX, every file of the place above PLACE_BYTES_MAX, or the worst run of run_tiles(r_max_m, rmin_m) consecutive tiles lit above RESIDENT_BYTES_MAX."""
+ if n_cards > MAX_CARDS: raise ValueError(f'{n_cards} cards, above {MAX_CARDS}')
+ for t, b in enumerate(tile_bytes):
+ if b > TILE_BYTES_MAX: raise ValueError(f'tile {t} is {b} bytes, above {TILE_BYTES_MAX}')
+ if sum(tile_bytes) > PLACE_BYTES_MAX: raise ValueError(f'the place is {sum(tile_bytes)} bytes, above {PLACE_BYTES_MAX}')
+ n = run_tiles(r_max_m, rmin_m); res = resident_bytes(bands, n)
+ if res > RESIDENT_BYTES_MAX: raise ValueError(f'{n} consecutive tiles light to {res} bytes, above {RESIDENT_BYTES_MAX}')
-def card_scales(distances, r_m):
- """scale_i = d_i / (d_i - r) for the cards' distances (m), nearest first: the card's pan rate per unit of heading and its static size seen from a camera r metres along its heading (ruling ridge-camera-on-circle; + forward, - backward). Refuses |r| >= R_FRAC_MAX x the nearest distance."""
- if abs(r_m) >= R_FRAC_MAX * min(distances): raise ValueError(f"the camera offset {r_m:g} m is not under {R_FRAC_MAX} x the nearest card's distance {min(distances):g} m")
- return [d / (d - r_m) for d in distances]
-def check_camera(scales, tops, bands, view):
- """Refuse a camera whose scaled cards leave the frame uncovered: the nearest card, scaled about the horizon row, must still reach the frame bottom (a backward camera shrinks it away), and no card may be smaller than REST_SCALE_MIN (a 16:9 viewport's edge)."""
- hr = view['horizon_row']; bottom = hr + (tops[0] + bands[0] - hr) * scales[0]
- if bottom < view['plane_h'] - 1e-6: raise ValueError(f"the camera lifts the nearest card to row {bottom:.1f}, off the frame bottom (row {view['plane_h']})")
- if min(scales) < REST_SCALE_MIN: raise ValueError(f'a card scaled {min(scales):.3f} cannot cover a 16:9 viewport at rest (below {REST_SCALE_MIN:.3f})')
+FIT_QUAD = 48 # Gauss-Legendre nodes for the least-squares line (exact for the smooth alpha(beta) to far below a card pixel)
+FIT_GRID = 513 # points the worst error is looked for on, ends included: the error is smooth between them, so the maximum found is within 0.01 card px of the continuous one
+def fit_px(d, r, px_per_deg, phis=None):
+ """The worst error, in card pixels, of a card tile's linear slide at offset r (m): over the camera's angle phi on its circle against its heading (`phis` steps, PHI_STEPS by default; 1 is phi = 0 alone, the camera pushed forward along its heading) and the viewport (beta in +-HFOV_MAX_DEG / 2), the exact view angle of a cylinder point at the tile's
+ distance d, alpha = atan2(d sin beta - r sin phi, d cos beta - r cos phi), against the continuous least-squares line a + s beta over the viewport (ruling ridge-offset-range-fit; the line by quadrature, the error on FIT_GRID points: it is the continuous worst error, not the error of a few samples)."""
+ half = math.radians(HFOV_MAX_DEG) / 2; p = np.linspace(0, 2 * math.pi, PHI_STEPS if phis is None else phis, endpoint=False)[:, None]
+ alpha = lambda b: np.arctan2(d * np.sin(b) - r * np.sin(p), d * np.cos(b) - r * np.cos(p)); x, w = np.polynomial.legendre.leggauss(FIT_QUAD); bq = half * x[None, :]; A = alpha(bq)
+ a0 = (A * w).sum(-1, keepdims=True) / 2; s = (A * bq * w).sum(-1, keepdims=True) / (bq * bq * w).sum(); b = np.linspace(-half, half, FIT_GRID)[None, :]
+ return math.degrees(float(np.abs(alpha(b) - (a0 + s * b)).max())) * px_per_deg
+def fit_table(dist, r, px_per_deg, phis=None):
+ """(tiles, cards) fit_px of every card tile at offset r; nan where the card is null in that tile."""
+ return np.array([[np.nan if d is None else fit_px(d, r, px_per_deg, phis) for d in row] for row in dist])
+def solve_r_max(dist, bands, px_per_deg, phis=None):
+ """The largest offset r (m, down to 0.1 m) at which every card tile fits within FIT_PX_MAX over `phis` camera angles (PHI_STEPS: the whole circle, the offset-only rotation mode; 1: phi = 0 alone, the modes where the offset turns with the view) and the resident gate holds: never above half the nearest card's smallest tile distance. Scans r upward from 0 on 128 steps to the first failure, then bisects that step.
+ Refuses (naming the card and tile that bind) a bake whose r_max_m is below R_MAX_FLOOR_M."""
+ near = min((row[0], t) for t, row in enumerate(dist) if row[0] is not None); rmin = near[0]; cap = 0.5 * rmin
+ ok = lambda r: bool(np.nanmax(fit_table(dist, r, px_per_deg, phis)) <= FIT_PX_MAX) and resident_bytes(bands, run_tiles(r, rmin)) <= RESIDENT_BYTES_MAX
+ lo, hi = 0.0, None
+ for r in np.linspace(0, cap, 129)[1:]:
+ if ok(r): lo = float(r)
+ else: hi = float(r); break
+ if hi is None: lo = cap
+ else:
+ for _ in range(24):
+ mid = 0.5 * (lo + hi)
+ if ok(mid): lo = mid
+ else: hi = mid
+ r_max = math.floor(lo * 10) / 10
+ if r_max < R_MAX_FLOOR_M:
+ if cap < R_MAX_FLOOR_M: raise ValueError(f'r_max_m {r_max:g} is below {R_MAX_FLOOR_M:g} m: card 0 stands {rmin:.0f} m away in tile {near[1]} and the offset stays under half of that')
+ tb = fit_table(dist, R_MAX_FLOOR_M, px_per_deg, phis); t, i = np.unravel_index(int(np.nanargmax(tb)), tb.shape)
+ if tb[t, i] > FIT_PX_MAX: raise ValueError(f'r_max_m {r_max:g} is below {R_MAX_FLOOR_M:g} m: card {i} in tile {t} errs {tb[t, i]:.1f} card px at {R_MAX_FLOOR_M:g} m (the bound is {FIT_PX_MAX:g})')
+ n = run_tiles(R_MAX_FLOOR_M, rmin); raise ValueError(f'r_max_m {r_max:g} is below {R_MAX_FLOOR_M:g} m: at {R_MAX_FLOOR_M:g} m, {n} consecutive tiles light to {resident_bytes(bands, n)} bytes, above {RESIDENT_BYTES_MAX}')
+ return r_max
-def bake_id(cards):
- """First 12 hex of sha256 over the card files in index order, colour then geometry. cards: [(colour bytes, geometry bytes)]."""
- h = hashlib.sha256()
- for colour, geometry in cards: h.update(colour); h.update(geometry)
+BAKE_ID_BLANK = '0' * 12
+def bake_id(manifest_text, files):
+ """First 12 hex of sha256 over the whole bake: the manifest.json text as written with its bake_id value BAKE_ID_BLANK (the id cannot hash itself), then the tile files, tile-major then card, colour then geometry (a null card tile writes none), so any change to the manifest or a tile is a new directory.
+ files: [(colour bytes, geometry bytes)] in that order."""
+ h = hashlib.sha256(); h.update(manifest_text.encode('utf-8'))
+ for colour, geometry in files: h.update(colour); h.update(geometry)
return h.hexdigest()[:12]
-def write_bake(out, place, view, meta, cards, opaque, default=None):
- """Write out/-/ (card WebPs + manifest.json), rewrite out/index.json, delete the place's previous dir. cards: [dict(top, colour bytes, geometry bytes, near_m, far_m, median_m, distance_m, scale)], nearest first; opaque (h, w) is
- the opaque view's coverage. Refuses before writing a bake whose files decode to different sizes, leave the frame or the view's plane_h, break the budget or composite away from the opaque view. meta: dict(curvature, encoding, camera dict(r_m, heading_max_deg)). Returns the directory."""
- dec = [(decode(c['colour']), decode(c['geometry'])) for c in cards]; shapes = {a.shape[:2] for pair in dec for a in pair}; bands = [a.shape[0] for a, _ in dec]
- if any(c.shape[:2] != g.shape[:2] for c, g in dec): raise ValueError('a card colour and geometry are not one size')
- if len({a.shape[1] for pair in dec for a in pair}) != 1: raise ValueError(f'the cards are not one width: {sorted(shapes)}')
- w = dec[0][0].shape[1]; h = view['plane_h']
- if any(band < 1 or c['top'] < 0 or c['top'] + band > h for c, band in zip(cards, bands)): raise ValueError(f'a card leaves the {h} rows of the frame')
- if opaque.shape != (h, w): raise ValueError(f'the opaque view is {opaque.shape}, the frame {(h, w)}')
- sizes = [len(c['colour']) + len(c['geometry']) for c in cards]; check_budget(sizes, w, bands)
- check_cover([(c['top'], col[..., 3] / 255.0) for c, (col, _) in zip(cards, dec)], opaque); check_camera([c['scale'] for c in cards], [c['top'] for c in cards], bands, view)
- bid = bake_id([(c['colour'], c['geometry']) for c in cards]); name = f"{place['id']}-{bid}"; out = Path(out); dest = out / name
- manifest = dict(schema=2, baker_version=BAKER_VERSION, bake_id=bid, place=place, view=dict(view, window_deg=WINDOW_DEG, plane_w=w), curvature=meta['curvature'], encoding=dict(meta['encoding'], normal='rt8'), camera=dict(r_m=meta['camera']['r_m'], heading_max_deg=meta['camera']['heading_max_deg']),
- cards=[dict(top=c['top'], h=band, near_m=c['near_m'], far_m=c['far_m'], median_m=c['median_m'], distance_m=c['distance_m'], scale=c['scale'], colour=dict(file=f'card-{i}-colour.webp', bytes=len(c['colour'])), geometry=dict(file=f'card-{i}-geometry.webp', bytes=len(c['geometry'])))
- for i, (c, band) in enumerate(zip(cards, bands))], w=w, h=h, bytes=sum(sizes), attribution=ATTRIBUTION)
- validate(manifest, SCHEMA['$defs']['manifest']); out.mkdir(parents=True, exist_ok=True); tmp = Path(tempfile.mkdtemp(dir=out, prefix='.bake-'))
- for i, c in enumerate(cards): (tmp / f'card-{i}-colour.webp').write_bytes(c['colour']); (tmp / f'card-{i}-geometry.webp').write_bytes(c['geometry'])
- (tmp / 'manifest.json').write_text(json.dumps(manifest, indent=1) + '\n')
+def write_bake(out, place, view, meta, packed, opaque, default=None):
+ """Write out/-/ (tile WebPs + manifest.json; the id addresses both), rewrite out/index.json, delete the place's previous dir. packed: dict(cards [dict(near_m, far_m)], tiles [TILES][cards] of dict(top, colour bytes, geometry bytes, distance_m) or None,
+ camera dict(r_max_m, r_max_forward_m)); opaque: TILES arrays (plane_h, TILE_W + 2 APRON), each the opaque view's coverage over a tile's columns. Refuses before writing a bake whose files decode to the wrong size, leave the frame, break a budget (the resident gate at r_max_m and at r_max_forward_m) or composite
+ away from the opaque view in any tile. meta: dict(curvature, encoding). Returns the directory."""
+ cards, tiles, camera = packed['cards'], packed['tiles'], packed['camera']; k = len(cards); h = view['plane_h']; w = TILE_W + 2 * APRON
+ if len(tiles) != TILES or len(opaque) != TILES or any(len(row) != k for row in tiles): raise ValueError(f'the bake needs {TILES} tiles of {k} cards each')
+ for i in range(k):
+ if all(row[i] is None for row in tiles): raise ValueError(f'card {i} is null in every tile')
+ dec = [[None if e is None else (decode(e['colour']), decode(e['geometry'])) for e in row] for row in tiles]; bands = [[pair[0].shape[0] for pair in row if pair] for row in dec]; tile_bytes = []
+ for t, (row, drow) in enumerate(zip(tiles, dec)):
+ tile_bytes.append(sum(len(e['colour']) + len(e['geometry']) for e in row if e))
+ for i, (e, pair) in enumerate(zip(row, drow)):
+ if e is None: continue
+ c, g = pair
+ if c.shape[:2] != g.shape[:2]: raise ValueError(f'tile {t} card {i}: colour and geometry are not one size')
+ if c.shape[1] != w: raise ValueError(f'tile {t} card {i} is {c.shape[1]} columns wide, not {w} (tile {TILE_W} + 2 apron {APRON})')
+ if c.shape[0] < 1 or e['top'] < 0 or e['top'] + c.shape[0] > h: raise ValueError(f'tile {t} card {i} leaves the {h} rows of the frame')
+ if opaque[t].shape != (h, w): raise ValueError(f'tile {t}: the opaque view is {opaque[t].shape}, the frame {(h, w)}')
+ rmin = min(row[0]['distance_m'] for row in tiles if row[0])
+ if camera['r_max_forward_m'] < camera['r_max_m']: raise ValueError(f"r_max_forward_m {camera['r_max_forward_m']:g} is below r_max_m {camera['r_max_m']:g}: phi = 0 is one of the angles r_max_m holds for")
+ for r in (camera['r_max_m'], camera['r_max_forward_m']): check_budget(k, tile_bytes, bands, r, rmin)
+ for t, (row, drow) in enumerate(zip(tiles, dec)):
+ try: check_cover([(e['top'], pair[0][..., 3] / 255.0) for e, pair in zip(row, drow) if e], opaque[t])
+ except ValueError as ex: raise ValueError(f'tile {t}: {ex}')
+ out = Path(out)
+ manifest = dict(schema=3, baker_version=BAKER_VERSION, bake_id=BAKE_ID_BLANK, place=place, view=dict(view, ring_w=RING_W, tile_w=TILE_W, tiles=TILES, apron=APRON), curvature=meta['curvature'], encoding=dict(meta['encoding'], normal='rt8'), camera=dict(r_max_m=camera['r_max_m'], r_max_forward_m=camera['r_max_forward_m']),
+ cards=[dict(near_m=c['near_m'], far_m=c['far_m']) for c in cards],
+ tiles=[[None if e is None else dict(top=e['top'], h=pair[0].shape[0], distance_m=e['distance_m'], colour=dict(file=tile_file(i, t, 'colour'), bytes=len(e['colour'])), geometry=dict(file=tile_file(i, t, 'geometry'), bytes=len(e['geometry'])))
+ for i, (e, pair) in enumerate(zip(row, drow))] for t, (row, drow) in enumerate(zip(tiles, dec))], bytes=sum(tile_bytes), attribution=ATTRIBUTION)
+ validate_manifest(manifest); text = json.dumps(manifest, indent=1) + '\n'; blank = f'"bake_id": "{BAKE_ID_BLANK}"'; assert text.count(blank) == 1
+ bid = bake_id(text, [(e['colour'], e['geometry']) for row in tiles for e in row if e]); name = f"{place['id']}-{bid}"; dest = out / name; text = text.replace(blank, f'"bake_id": "{bid}"')
+ out.mkdir(parents=True, exist_ok=True); tmp = Path(tempfile.mkdtemp(dir=out, prefix='.bake-'))
+ for t, row in enumerate(tiles):
+ for i, e in enumerate(row):
+ if e: (tmp / tile_file(i, t, 'colour')).write_bytes(e['colour']); (tmp / tile_file(i, t, 'geometry')).write_bytes(e['geometry'])
+ (tmp / 'manifest.json').write_bytes(text.encode('utf-8')) # bytes, so the platform's newline cannot move the file under its id
idx_path = out / 'index.json'; idx = json.loads(idx_path.read_text()) if idx_path.exists() else dict(schema=1, default=place['id'], places={})
old = idx['places'].get(place['id']); idx['places'][place['id']] = name; idx['default'] = default or (idx['default'] if idx['default'] in idx['places'] else place['id'])
validate(idx, SCHEMA['$defs']['index'])
if dest.exists(): shutil.rmtree(dest)
- os.rename(tmp, dest); (out / '.index.tmp').write_text(json.dumps(idx, indent=1) + '\n'); os.replace(out / '.index.tmp', idx_path)
+ os.rename(tmp, dest); (out / '.index.tmp').write_bytes((json.dumps(idx, indent=1) + '\n').encode('utf-8')); os.replace(out / '.index.tmp', idx_path)
if old and old != name: shutil.rmtree(out / old, ignore_errors=True)
return dest
# ------------------------------------------------------------------------------------ the bake
-def bake_place(pid):
- """stage 0, prefilter, set_view, coverage, seams, cards: dict(place, view, meta, cards (ridge.cards arrays), seams (K, w) in m, cov (bins, w), opaque (h, w) coverage). Needs RIDGE_TILES / RIDGE_WORK."""
+def cut_ring(d, a, h, splits_km):
+ """The ring cut of a prefiltered march (set_view done): normals, coverage, the periodic seams on all RING_W columns, then ridge.cards per tile on its TILE_W + 2 APRON columns with the matching normals. Returns dict(cards [TILES][cards] (ridge.cards arrays),
+ splits_km, seams (K, ring) in m, cov (bins, ring), opaque [TILES] (rows, TILE_W + 2 APRON) coverage, edges)."""
import ridge
- assert ridge.WIN == PLANE_W and ridge.H > 0
- p = ridge.configure(ridge.load_preset(pid)); ridge.mosaic(p); d, _, Hh, _ = ridge.stage0(False); a, h = ridge.prefilter(d, Hh, p.get('prefilter_m', 0)); v = ridge.set_view(a.max(0))
- nrm = tuple(ridge.win(x) for x in ridge.normals(d, h)); aw, hw = ridge.win(a), ridge.win(h); cov = ridge.coverage(d, aw); sm = ridge.seams(cov, [k * 1000.0 for k in p['card_split_km']], d)
- place = dict(id=p['id'], name=p['name'], lat=p['lat'], lon=p['lon'], altitude_km=p['ground_m'] / 1000.0, eye_m=p['eye_m'])
+ nrm = ridge.normals(d, h); cov = ridge.coverage(d, a); sm = ridge.seams(cov, [k * 1000.0 for k in splits_km], d); op = ridge.opaque(a); cols = lambda x, t: ridge.ring_cols(x, t * TILE_W - APRON, TILE_W + 2 * APRON); tiles = []
+ for t in range(TILES): tiles.append(ridge.cards(d, cols(a, t), cols(h, t), cols(sm, t), tuple(cols(x, t) for x in nrm))); print(f'tile {t + 1}/{TILES}', file=sys.stderr, flush=True)
+ return dict(cards=tiles, splits_km=list(splits_km), seams=sm, cov=cov, opaque=[cols(op, t) for t in range(TILES)], edges=ridge.log_edges(d))
+
+def bake_place(pid):
+ """stage 0, prefilter, set_view on the whole ring, cut_ring: dict(place, view, meta, v, and cut_ring's cards, splits_km, seams, cov, opaque, edges). Needs RIDGE_TILES / RIDGE_WORK."""
+ import ridge
+ assert ridge.W == RING_W and ridge.H > 0
+ p = ridge.configure(ridge.load_preset(pid)); ridge.mosaic(p); d, _, Hh, _ = ridge.stage0(False); a, h = ridge.prefilter(d, Hh, p.get('prefilter_m', 0)); v = ridge.set_view(a.max(0)); ring = cut_ring(d, a, h, p['card_split_km'])
+ place = dict(id=p['id'], name=p['name'], lat=p['lat'], lon=p['lon'], altitude_km=p['ground_m'] / 1000.0, eye_m=p['eye_m'], tz=p['tz'])
view = dict(look_az_deg=p['az_center'], plane_h=ridge.H, px_per_deg_h=ridge.HPX_DEG, px_per_deg_v=v['px_per_deg'], exaggeration=v['exaggeration'], horizon_row=v['horizon_row'], sky_row=v['sky_row'] * ridge.H, near_row=v['near_row'] * ridge.H)
- meta = dict(curvature=dict(r_earth_m=ridge.R_EARTH, k_ref=ridge.KREF), encoding=dict(log_d_min=math.log(d[0]), log_d_max=math.log(d[-1])), camera=dict(r_m=float(p.get('camera_r_m', CAMERA_R_M)), heading_max_deg=HEADING_MAX_DEG))
- return dict(place=place, view=view, meta=meta, cards=ridge.cards(d, aw, hw, sm, nrm), splits_km=list(p['card_split_km']), seams=sm, cov=cov, opaque=ridge.opaque(aw), edges=ridge.log_edges(d))
+ meta = dict(curvature=dict(r_earth_m=ridge.R_EARTH, k_ref=ridge.KREF), encoding=dict(log_d_min=math.log(d[0]), log_d_max=math.log(d[-1])))
+ return dict(place=place, view=view, meta=meta, v=v, **ring)
def pack(bake):
- """The cards of a bake as bytes plus their manifest facts: median seam depths either side, the median distance of the card's solid pixels that are not wall (median_m = distance_m), and scale = distance_m / (distance_m - camera r). Refuses a card
- with no solid terrain apart from its wall rows, and a camera offset the cards cannot take (card_scales)."""
- enc = bake['meta']['encoding']; sm = bake['seams']; out = []; sp = bake['splits_km']; cs = bake['cards']
- for i, c in enumerate(cs):
- if c['alpha'].shape[0] == 0: raise ValueError(f"card {i} is empty: it lies between the splits {' and '.join(f'{sp[j]:g} km' for j in (i - 1, i) if 0 <= j < len(sp))} (card_split_km {sp}) and holds no terrain nothing nearer hides; move or remove a split")
- dist = []
- for i, c in enumerate(cs):
- ground = (c['alpha'] >= 0.5) & ~c['wall']
- if not ground.any(): raise ValueError(f'card {i} holds no solid terrain apart from its wall rows')
- dist.append(float(np.exp(np.median(c['logd'][ground]))))
- scales = card_scales(dist, bake['meta']['camera']['r_m'])
- for i, c in enumerate(cs):
- out.append(dict(top=c['top'], colour=encode_colour(c['albedo'], c['alpha']), geometry=encode_geometry(c['n_r'], c['n_t'], c['logd'], enc, c['wall']),
- near_m=float(np.median(sm[i - 1])) if i else None, far_m=float(np.median(sm[i])) if i < len(sm) else None, median_m=dist[i], distance_m=dist[i], scale=scales[i]))
- return out
+ """The tiles of a bake as bytes plus their manifest facts. Per card tile: distance_m = exp(median ln d) over the solid (alpha >= 0.5) pixels that are not wall of the interior TILE_W columns (a tile with none falls back to its non-wall, then any, lit pixels);
+ a card with no rows in a tile is null there. Per card: the median seam depths over the ring. camera.r_max_m: solve_r_max over the card tiles' distances and every camera angle on its circle (the offset-only rotation mode), camera.r_max_forward_m: the same at phi = 0 alone (the modes where the offset turns with the view). Refuses a card empty in every tile (naming the splits) and a card with
+ no solid terrain apart from its wall in any tile. Returns dict(cards, tiles, camera, report) (report is printed, not written)."""
+ sm = bake['seams']; sp = bake['splits_km']; k = len(sp) + 1; ppd = bake['view']['px_per_deg_h']; inner = slice(APRON, APRON + TILE_W); enc = bake['meta']['encoding']
+ for i in range(k):
+ if all(tile[i]['alpha'].shape[0] == 0 for tile in bake['cards']): raise ValueError(f"card {i} is empty: it lies between the splits {' and '.join(f'{sp[j]:g} km' for j in (i - 1, i) if 0 <= j < len(sp))} (card_split_km {sp}) and holds no terrain nothing nearer hides; move or remove a split")
+ tiles, dist, bands = [], [], []; any_solid = [False] * k
+ for tile in bake['cards']:
+ row, drow, brow = [], [], []
+ for i, c in enumerate(tile):
+ if c['alpha'].shape[0] == 0: row.append(None); drow.append(None); continue
+ al, wl, ld = c['alpha'][:, inner], c['wall'][:, inner], c['logd'][:, inner]; solid = (al >= 0.5) & ~wl; any_solid[i] |= bool(solid.any())
+ pool = next((m, l) for m, l in ((solid, ld), ((al > 0) & ~wl, ld), (al > 0, ld), (c['alpha'] > 0, c['logd'])) if m.any())
+ dm = float(np.exp(np.median(pool[1][pool[0]])))
+ row.append(dict(top=c['top'], colour=encode_colour(c['albedo'], c['alpha']), geometry=encode_geometry(c['n_r'], c['n_t'], c['logd'], enc, c['wall']), distance_m=dm)); drow.append(dm); brow.append(c['alpha'].shape[0])
+ tiles.append(row); dist.append(drow); bands.append(brow)
+ for i in range(k):
+ if not any_solid[i]: raise ValueError(f'card {i} holds no solid terrain apart from its wall rows')
+ r_max = solve_r_max(dist, bands, ppd); r_fwd = solve_r_max(dist, bands, ppd, phis=1); rmin = min(row[0] for row in dist if row[0] is not None); n = run_tiles(r_fwd, rmin); worst = np.nanmax(fit_table(dist, r_max, ppd), axis=0)
+ cards = [dict(near_m=float(np.median(sm[i - 1])) if i else None, far_m=float(np.median(sm[i])) if i < len(sm) else None) for i in range(k)]
+ return dict(cards=cards, tiles=tiles, camera=dict(r_max_m=r_max, r_max_forward_m=r_fwd), report=dict(fit_px=[float(x) for x in worst], run_tiles=n, resident_bytes=resident_bytes(bands, n), nearest_m=rmin))
def lit(c):
"""albedo x (0.35 + 0.65 max(n.L, 0)) under the fixed sheet light, with the card's alpha: (rgb, alpha). Wall pixels are lit with the face up, as the runtime reads their code."""
@@ -181,26 +274,34 @@ def lit(c):
up = np.sqrt(np.clip(1 - n_r ** 2 - n_t ** 2, 0, 1)); L = np.array(SHEET_LIGHT) / np.linalg.norm(SHEET_LIGHT); nl = np.clip(n_r * L[0] + n_t * L[1] + up * L[2], 0, 1)
return c['albedo'] * (0.35 + 0.65 * nl)[..., None], c['alpha']
def sheet(bake):
- """Contact sheet (png bytes), stacked: the composite, every card alone, and the depth image (log-distance bins, far at the top, every seam drawn). All lit by SHEET_LIGHT over the flat SHEET_SKY; reads the arrays the encoder writes."""
- h, w = bake['opaque'].shape; sky = np.broadcast_to(np.array(SHEET_SKY), (h, w, 3)); comp = sky.copy(); panels = []
- for c in bake['cards']:
- rgb, al = lit(c); alone = sky.copy(); sl = slice(c['top'], c['top'] + al.shape[0]); alone[sl] = sky[sl] * (1 - al[..., None]) + rgb * al[..., None]; panels.append(alone)
- for c in reversed(bake['cards']): rgb, al = lit(c); sl = slice(c['top'], c['top'] + al.shape[0]); comp[sl] = comp[sl] * (1 - al[..., None]) + rgb * al[..., None]
- cov = bake['cov']; img = np.repeat(np.log1p(cov[::-1]) / np.log1p(cov.max()), 2, 0); depth = np.dstack([img] * 3) * 0.92 + 0.04; nb = cov.shape[0]; cols = np.arange(w)
- for k, s in enumerate(bake['seams']):
- j = np.clip(np.searchsorted(bake['edges'], np.log(s), 'right') - 1, 0, nb - 1); col = [(0.24, 0.78, 1.0), (1.0, 0.47, 0.24), (0.6, 1.0, 0.4), (1.0, 0.9, 0.3), (0.9, 0.4, 1.0)][k % 5]
- for dy in (0, 1): depth[(nb - 1 - j) * 2 + dy, cols] = col
- return bytes(imagecodecs.png_encode(u8(np.concatenate([comp] + panels + [depth], 0))))
+ """Contact sheet (png bytes) at 1/4 of the ring's width, stacked: the ring composite, every card's strip alone, and the depth image (log-distance bins, far at the top, every seam); the TILES tile boundaries drawn on each. All lit by SHEET_LIGHT over the flat
+ SHEET_SKY; reads the arrays the encoder writes (each tile's interior columns, the apron dropped)."""
+ h = bake['opaque'][0].shape[0]; k = len(bake['cards'][0]); sky = np.broadcast_to(np.array(SHEET_SKY, np.float32), (h, RING_W, 3)); rgbs = [np.zeros((h, RING_W, 3), np.float32) for _ in range(k)]; als = [np.zeros((h, RING_W), np.float32) for _ in range(k)]
+ for t, tile in enumerate(bake['cards']):
+ for i, c in enumerate(tile):
+ if c['alpha'].shape[0] == 0: continue
+ rgb, al = lit(c); sl = slice(c['top'], c['top'] + al.shape[0]); x0 = t * TILE_W; rgbs[i][sl, x0:x0 + TILE_W] = rgb[:, APRON:APRON + TILE_W]; als[i][sl, x0:x0 + TILE_W] = al[:, APRON:APRON + TILE_W]
+ comp = sky.copy(); panels = []
+ for rgb, al in zip(rgbs, als): panels.append(sky * (1 - al[..., None]) + rgb * al[..., None])
+ for rgb, al in zip(reversed(rgbs), reversed(als)): comp = comp * (1 - al[..., None]) + rgb * al[..., None]
+ q = lambda a: a.reshape((a.shape[0], RING_W // 4, 4) + a.shape[2:]).mean(2); mark = np.arange(TILES) * TILE_W // 4; red = np.array([1.0, 0.2, 0.2])
+ def bounds(img): img[:, mark] = 0.45 * img[:, mark] + 0.55 * red; return img
+ cov = bake['cov'][:, ::4]; w = cov.shape[1]; img = np.repeat(np.log1p(cov[::-1]) / np.log1p(cov.max()), 2, 0); depth = np.dstack([img] * 3) * 0.92 + 0.04; nb = cov.shape[0]; cols = np.arange(w)
+ for j, s in enumerate(bake['seams']):
+ b = np.clip(np.searchsorted(bake['edges'], np.log(s[::4]), 'right') - 1, 0, nb - 1); col = [(0.24, 0.78, 1.0), (1.0, 0.47, 0.24), (0.6, 1.0, 0.4), (1.0, 0.9, 0.3), (0.9, 0.4, 1.0)][j % 5]
+ for dy in (0, 1): depth[(nb - 1 - b) * 2 + dy, cols] = col
+ return bytes(imagecodecs.png_encode(u8(np.concatenate([bounds(q(comp))] + [bounds(q(p)) for p in panels] + [bounds(depth)], 0))))
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__.split('\n')[0]); ap.add_argument('place', nargs='?'); ap.add_argument('--tiles'); ap.add_argument('--out'); ap.add_argument('--work'); ap.add_argument('--sheet'); ap.add_argument('--write-schema', action='store_true')
a = ap.parse_args(argv)
- if a.write_schema: (HERE / 'ridge-bake.schema.json').write_text(json.dumps(SCHEMA, indent=1, ensure_ascii=False) + '\n'); return 0
+ if a.write_schema: (HERE / 'ridge-bake.schema.json').write_bytes((json.dumps(SCHEMA, indent=1, ensure_ascii=False) + '\n').encode('utf-8')); return 0
if not (a.place and a.tiles and a.out): ap.error('place, --tiles and --out are required')
os.environ['RIDGE_TILES'] = a.tiles; os.environ['RIDGE_WORK'] = a.work or os.path.join(os.environ.get('TMPDIR', tempfile.gettempdir()), 'ridge-bake-work'); os.makedirs(os.environ['RIDGE_WORK'], exist_ok=True)
bake = bake_place(a.place)
if a.sheet: Path(a.sheet).write_bytes(sheet(bake))
- dest = write_bake(a.out, bake['place'], bake['view'], bake['meta'], pack(bake), bake['opaque'])
- print(dest); return 0
+ packed = pack(bake); rp = packed['report']
+ print(f"r_max_m {packed['camera']['r_max_m']:g} r_max_forward_m {packed['camera']['r_max_forward_m']:g} nearest card {rp['nearest_m']:.0f} m resident run {rp['run_tiles']} tiles = {rp['resident_bytes']} bytes worst fit error per card (card px, bound {FIT_PX_MAX:g}) {[round(x, 1) for x in rp['fit_px']]}", file=sys.stderr, flush=True)
+ dest = write_bake(a.out, bake['place'], bake['view'], bake['meta'], packed, bake['opaque']); print(dest); return 0
if __name__ == '__main__': sys.exit(main())
diff --git a/scripts/ridge-bake/places.json b/scripts/ridge-bake/places.json
index c6dde613..a85e5191 100644
--- a/scripts/ridge-bake/places.json
+++ b/scripts/ridge-bake/places.json
@@ -1,8 +1,9 @@
{
- "_doc": "Place presets for the A+D baker (ridge.py). eye = observer lat/lon; eye_h_m = eye above the local DEM surface (ground_override_m replaces the DEM ground elevation, used for Vienna to keep round 1's 183.3 m); look_at = target lat/lon whose bearing centres the 72 deg window (or az_deg); rmax_km = ring radius (decides the tile list: every 1x1 deg GLO-30 tile whose rectangle intersects the circle); card_split_km = the ordered list of 1 to MAX_CARDS - 1 authored seam depths in km (the seam search refines each per column; K splits make K+1 cards; required, never defaulted); prefilter_m = Gaussian sigma in metres of the height low-pass before the cards are cut (default 0).",
+ "_doc": "Place presets for the A+D baker (ridge.py). eye = observer lat/lon; eye_h_m = eye above the local DEM surface (ground_override_m replaces the DEM ground elevation, used for Vienna to keep round 1's 183.3 m); look_at = target lat/lon whose bearing is the rest azimuth, where the view looks at rest (or az_deg); the ring itself is the whole 360 degrees, absolute compass, column 0 = north; tz = the place's IANA time zone (required, never defaulted: the runtime draws named sky moments in the place's local day); rmax_km = ring radius (decides the tile list: every 1x1 deg GLO-30 tile whose rectangle intersects the circle); card_split_km = the ordered list of 1 to MAX_CARDS - 1 authored seam depths in km (the seam search refines each per column; K splits make K+1 cards; required, never defaulted); prefilter_m = Gaussian sigma in metres of the height low-pass before the cards are cut (default 0).",
"presets": [
{
"id": "vienna",
+ "tz": "Europe/Vienna",
"name": "Vienna, looking SW to Rax/Schneeberg",
"kind": "far range over a flat foreground",
"lat": 48.1929826,
@@ -22,6 +23,7 @@
},
{
"id": "matterhorn",
+ "tz": "Europe/Zurich",
"name": "Matterhorn from the Gornergrat (photo cell, 9.7 km)",
"kind": "lone horn, close, 27 deg of relief",
"lat": 45.983139,
@@ -151,6 +153,7 @@
},
{
"id": "fuji",
+ "tz": "Asia/Tokyo",
"name": "Fuji from the Shiraito Falls side, 13.8 km WSW (photo cell)",
"kind": "lone cone, smooth",
"lat": 35.312467222222494,
@@ -297,6 +300,7 @@
},
{
"id": "halfdome",
+ "tz": "America/Los_Angeles",
"name": "Half Dome from the Yosemite Valley floor (Sentinel Bridge photo cell)",
"kind": "granite wall across a valley",
"lat": 37.745833333333,
@@ -454,6 +458,7 @@
},
{
"id": "amadablam",
+ "tz": "Asia/Kathmandu",
"name": "Ama Dablam and the Everest massif, 4 km WSW of Tengboche near Khumjung (photo cell)",
"kind": "far high range behind a near spire",
"lat": 27.822000000000003,
@@ -528,6 +533,7 @@
},
{
"id": "trecime",
+ "tz": "Europe/Rome",
"name": "Tre Cime di Lavaredo from the Dreizinnenhuette area, 2.4 km N (photo cell)",
"kind": "cirque wall, spires",
"lat": 46.636906,
diff --git a/scripts/ridge-bake/ridge-bake.schema.json b/scripts/ridge-bake/ridge-bake.schema.json
index b58a6c69..f6b5fed4 100644
--- a/scripts/ridge-bake/ridge-bake.schema.json
+++ b/scripts/ridge-bake/ridge-bake.schema.json
@@ -1,6 +1,6 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
- "title": "ridge-bake manifest v2 and index v1",
+ "title": "ridge-bake manifest v3 and index v1",
"$defs": {
"manifest": {
"type": "object",
@@ -14,15 +14,14 @@
"encoding",
"camera",
"cards",
- "w",
- "h",
+ "tiles",
"bytes",
"attribution"
],
"additionalProperties": false,
"properties": {
"schema": {
- "const": 2
+ "const": 3
},
"baker_version": {
"type": "integer"
@@ -38,7 +37,8 @@
"lat",
"lon",
"altitude_km",
- "eye_m"
+ "eye_m",
+ "tz"
],
"additionalProperties": false,
"properties": {
@@ -59,6 +59,10 @@
},
"eye_m": {
"type": "number"
+ },
+ "tz": {
+ "type": "string",
+ "format": "iana-tz"
}
}
},
@@ -66,8 +70,10 @@
"type": "object",
"required": [
"look_az_deg",
- "window_deg",
- "plane_w",
+ "ring_w",
+ "tile_w",
+ "tiles",
+ "apron",
"plane_h",
"px_per_deg_h",
"px_per_deg_v",
@@ -81,12 +87,17 @@
"look_az_deg": {
"type": "number"
},
- "window_deg": {
- "const": 72
+ "ring_w": {
+ "const": 6400
},
- "plane_w": {
- "type": "integer",
- "maximum": 4096
+ "tile_w": {
+ "const": 200
+ },
+ "tiles": {
+ "const": 32
+ },
+ "apron": {
+ "const": 2
},
"plane_h": {
"type": "integer"
@@ -150,15 +161,15 @@
"camera": {
"type": "object",
"required": [
- "r_m",
- "heading_max_deg"
+ "r_max_m",
+ "r_max_forward_m"
],
"additionalProperties": false,
"properties": {
- "r_m": {
+ "r_max_m": {
"type": "number"
},
- "heading_max_deg": {
+ "r_max_forward_m": {
"type": "number"
}
}
@@ -170,24 +181,11 @@
"items": {
"type": "object",
"required": [
- "top",
- "h",
"near_m",
- "far_m",
- "median_m",
- "distance_m",
- "scale",
- "colour",
- "geometry"
+ "far_m"
],
"additionalProperties": false,
"properties": {
- "top": {
- "type": "integer"
- },
- "h": {
- "type": "integer"
- },
"near_m": {
"type": [
"number",
@@ -199,57 +197,78 @@
"number",
"null"
]
- },
- "median_m": {
- "type": "number"
- },
- "distance_m": {
- "type": "number"
- },
- "scale": {
- "type": "number"
- },
- "colour": {
- "type": "object",
- "required": [
- "file",
- "bytes"
- ],
- "additionalProperties": false,
- "properties": {
- "file": {
- "type": "string"
- },
- "bytes": {
- "type": "integer"
+ }
+ }
+ },
+ "description": "nearest first; the runtime paints the list last to first. near_m and far_m are the median seam depths over the ring, null at the ends."
+ },
+ "tiles": {
+ "type": "array",
+ "minItems": 32,
+ "maxItems": 32,
+ "items": {
+ "type": "array",
+ "minItems": 1,
+ "maxItems": 6,
+ "items": {
+ "type": [
+ "object",
+ "null"
+ ],
+ "required": [
+ "top",
+ "h",
+ "distance_m",
+ "colour",
+ "geometry"
+ ],
+ "additionalProperties": false,
+ "properties": {
+ "top": {
+ "type": "integer"
+ },
+ "h": {
+ "type": "integer"
+ },
+ "distance_m": {
+ "type": "number"
+ },
+ "colour": {
+ "type": "object",
+ "required": [
+ "file",
+ "bytes"
+ ],
+ "additionalProperties": false,
+ "properties": {
+ "file": {
+ "type": "string"
+ },
+ "bytes": {
+ "type": "integer"
+ }
}
- }
- },
- "geometry": {
- "type": "object",
- "required": [
- "file",
- "bytes"
- ],
- "additionalProperties": false,
- "properties": {
- "file": {
- "type": "string"
- },
- "bytes": {
- "type": "integer"
+ },
+ "geometry": {
+ "type": "object",
+ "required": [
+ "file",
+ "bytes"
+ ],
+ "additionalProperties": false,
+ "properties": {
+ "file": {
+ "type": "string"
+ },
+ "bytes": {
+ "type": "integer"
+ }
}
}
}
- },
- "description": "nearest first; the runtime paints the list last to first. top and h place the card back at its rows of the frame; near_m and far_m are the median seam depths, null at the ends; median_m and distance_m are the median distance of the card's solid pixels that are not wall; scale = distance_m / (distance_m - camera.r_m) is the card's pan rate per unit of heading and its static size."
- }
- },
- "w": {
- "type": "integer"
- },
- "h": {
- "type": "integer"
+ }
+ },
+ "description": "tiles[t][i] is card i in tile t, or null where the card holds nothing in that tile (the client takes its distance from the neighbouring tiles). Tile t owns the ring columns [tile_w t, tile_w (t + 1)), column c at azimuth (c + 0.5) / ring_w x 360, 0 = north; its files hold [tile_w t - apron, tile_w (t + 1) + apron), wrapping at the ring's end, and are tile_w + 2 apron columns wide. top and h place the card's band back at its rows of the frame; distance_m = exp(median ln d) of the card's solid pixels in the tile that are not wall (the interior tile_w columns)."
},
"bytes": {
"type": "integer"
diff --git a/scripts/ridge-bake/ridge.py b/scripts/ridge-bake/ridge.py
index 80d38e4c..839e378b 100644
--- a/scripts/ridge-bake/ridge.py
+++ b/scripts/ridge-bake/ridge.py
@@ -1,15 +1,17 @@
"""Ridge baker: the ray march of a place, cut into K+1 layered-depth G-buffer cards by K authored seams (places.json), no painter, no sun.
Offline baker for the ridge backdrop (scripts/ridge-bake); export.py drives it.
- load_preset(id) -> configure() : observer, tiles, mosaic origin, ring radius, window azimuth, card splits and prefilter from places.json
+ load_preset(id) -> configure() : observer, tiles, mosaic origin, ring radius, rest azimuth, card splits and prefilter from places.json
stage0(detail) : ray march of all 6400 azimuth columns (curvature+refraction), optional authored sub-DEM foreground detail, cached
prefilter(d, h, sigma_m) : Gaussian low-pass of the sampled heights (along each ray, across rays at equal distance), angles recomputed with elev
- set_view(skyline) : authored Y mapping from the march skyline: angle -> row, see set_view
- coverage(d, a) / seams(cov, ..) : visible rows per log-distance bin; one forward-energy seam per authored split, per column
+ set_view(skyline) : authored Y mapping from the march skyline of the whole ring: angle -> row, see set_view
+ ring_cols(a, c0, n) : n columns of the ring from column c0, periodic (the tile cut)
+ coverage(d, a) / seams(cov, ..) : visible rows per log-distance bin; one forward-energy seam per authored split, per column, periodic round the ring
normals(d, h) / cards(...) : per-sample normals; the K+1 cards (coverage, distance, normal, albedo), each cropped to its band of rows
Vertical exaggeration is AUTHORED and derived per view by set_view (printed on the page). The client owns lighting, haze and ink (ruling ridge-cards-runtime-lit)."""
import sys, time, math, json
import os, hashlib
+from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import numpy as np, tifffile
@@ -21,7 +23,6 @@ def _env_dir(name, what):
B = _env_dir('RIDGE_WORK', 'the work directory (the mosaic / ray caches)')
COP = _env_dir('RIDGE_TILES', 'the directory of Copernicus GLO-30 tiles (Copernicus_DSM_COG_10_*_DEM.tif)')
W = 6400 # ring columns: 360 deg at 17.78 px/deg
-WIN = 1280 # window = 72 deg of the ring
HPX_DEG = W / 360.0
H = 600 # frame rows
COLW = math.radians(360.0 / W)
@@ -31,11 +32,15 @@ P = {} # configured preset
rowang = np.zeros(H); PXDEG_V = 100.0; TOP_DEG = 2.6; BOTTOM_DEG = -3.4
def load_preset(pid, path=Path(__file__).resolve().parent / 'places.json'):
- """The preset dict. card_split_km is the ordered list of authored seam depths (km): required, strictly increasing, at most export.MAX_CARDS - 1 (the cap is export's, which owns the budget); refused here, before any march."""
+ """The preset dict. tz is required, an IANA zone the system knows (the runtime draws named sky moments in the place's local day). card_split_km is the ordered list of authored seam depths (km): required, strictly increasing, at most export.MAX_CARDS - 1 (the cap is export's, which owns the budget); refused here, before any march."""
d = json.load(open(path)); p = dict(next(x for x in d['presets'] if x['id'] == pid)); sp = p.get('card_split_km')
from export import MAX_CARDS
if not sp: raise ValueError(f"preset {pid}: card_split_km is required (an ordered list of 1 to {MAX_CARDS - 1} depths in km)")
if len(sp) > MAX_CARDS - 1 or any(b <= a for a, b in zip(sp, sp[1:])): raise ValueError(f"preset {pid}: card_split_km {sp} must be strictly increasing with at most {MAX_CARDS - 1} entries")
+ tz = p.get('tz')
+ if not isinstance(tz, str) or not tz: raise ValueError(f"preset {pid}: tz is required (an IANA time zone name such as Europe/Vienna)")
+ try: ZoneInfo(tz)
+ except (ZoneInfoNotFoundError, ValueError, OSError): raise ValueError(f"preset {pid}: tz {tz!r} is not a time zone the system knows")
return p
# ====================================================================== configuration, DEM
@@ -77,7 +82,7 @@ def bil(a, lat_top, lon_left, lat, lon):
return (a[y0, x0] * (1 - fx) * (1 - fy) + a[y0, x0 + 1] * fx * (1 - fy) + a[y0 + 1, x0] * (1 - fx) * fy + a[y0 + 1, x0 + 1] * fx * fy)
def configure(p):
- """Set the module state for a preset: observer, eye elevation (DEM ground + eye height, or ground_override), window azimuth."""
+ """Set the module state for a preset: observer, eye elevation (DEM ground + eye height, or ground_override), rest azimuth (az_center: where the view looks at rest; the ring itself is absolute compass, column 0 = north)."""
global P
P = p; m, lt, ll = mosaic(p)
ground = p['ground_override_m'] if 'ground_override_m' in p else float(bil(m, lt, ll, np.array(p['lat']), np.array(p['lon'])))
@@ -85,10 +90,11 @@ def configure(p):
if 'look_at' in p:
la, lo = p['look_at']; P['az_center'] = (math.degrees(math.atan2((lo - p['lon']) * math.cos(math.radians(p['lat'])), la - p['lat'])) + 360) % 360
else: P['az_center'] = p['az_deg']
- P['win0'] = int(round(P['az_center'] / 360 * W - WIN / 2)) % W
return P
-def win(img): return np.take(img, (P['win0'] + np.arange(WIN)) % W, axis=1)
+def ring_cols(a, c0, n):
+ """n columns of the ring array a (last axis W) from column c0 (negative or past W wraps): the one periodic take, the wrap at 0 / 360 degrees is handled here."""
+ return np.take(a, (c0 + np.arange(n)) % W, axis=-1)
# ====================================================================== authored sub-DEM foreground detail (Aetheria / CultMath ridged multifractal)
def _frac(v): return v - np.floor(v)
@@ -177,10 +183,10 @@ def normals(d, h):
# ====================================================================== the authored Y mapping
def set_view(skyline, sky_row=0.04, near_row=0.66):
"""AUTHORED vertical mapping, linear in elevation angle: row = (TOP_DEG - angle) * PXDEG_V over the whole 600-row frame (cylindrical, horizontal 17.78 px/deg). skyline is the highest angle any sample reaches in each
- ring column (W,), straight from the march. Two anchors: the highest skyline angle in the window sits at `sky_row` (4%) of the frame height, the LOWEST sits at `near_row` (66%); everything below is body and ground.
- PXDEG_V = (near_row - sky_row) * 600 / (highest - lowest), clamped to [17.78, 178] px/deg = vertical exaggeration 1x..10x. TOP_DEG = highest + sky_row*600/PXDEG_V; BOTTOM_DEG = TOP_DEG - 600/PXDEG_V."""
+ ring column (W,), straight from the march. Two anchors on the whole ring (ruling ridge-ring-vertical-anchors): the highest skyline angle of the ring sits at `sky_row` (4%) of the frame height, the LOWEST sits at `near_row` (66%);
+ everything below is body and ground. PXDEG_V = (near_row - sky_row) * 600 / (highest - lowest), clamped to [17.78, 178] px/deg = vertical exaggeration 1x..10x. TOP_DEG = highest + sky_row*600/PXDEG_V; BOTTOM_DEG = TOP_DEG - 600/PXDEG_V."""
global rowang, PXDEG_V, TOP_DEG, BOTTOM_DEG
- w = win(np.asarray(skyline)[None, :])[0]; sky = float(w.max()); low = float(w.min())
+ sk = np.asarray(skyline); sky = float(sk.max()); low = float(sk.min())
ppd = float(np.clip((near_row - sky_row) * H / max(sky - low, 0.05), HPX_DEG, 10 * HPX_DEG))
PXDEG_V = ppd; TOP_DEG = sky + sky_row * H / ppd; BOTTOM_DEG = TOP_DEG - H / ppd; rowang = TOP_DEG - (np.arange(H) + 0.5) / PXDEG_V
return dict(top_deg=TOP_DEG, bottom_deg=BOTTOM_DEG, px_per_deg=PXDEG_V, exaggeration=PXDEG_V / HPX_DEG, horizon_row=TOP_DEG * PXDEG_V, sky_deg=sky, low_deg=low, sky_row=sky_row, near_row=near_row)
@@ -189,7 +195,7 @@ def set_view(skyline, sky_row=0.04, near_row=0.66):
COV_BINS = 160 # log-distance bins between the first and the last sample
SIG_B = 1.5 # blur of the coverage along depth (bins): seams settle in gaps
SEAM_LAM, SEAM_UNARY = 2.0, 0.25 # forward energy: a seam that moves a bin between neighbouring columns pays SEAM_LAM per bin plus every visible row it sweeps; one that sits in visible terrain pays SEAM_UNARY x those rows (cross-fadable)
-SEAM_PRIOR = 0.02 # the authored depth is a faint pull, rows per nat^2 (the test pins the window: six synthetic receding ridges tear at 0.1, and without the swept-rows term at 0.02 they tear again)
+SEAM_PRIOR = 0.02 # the authored depth is a faint pull, rows per nat^2 (the tests pin the window: six synthetic receding ridges, a sawtooth round the ring, tear at 0.05, and without the swept-rows term at 0.02 they tear too)
SEAM_SEP = 0.4 # seams at least this far apart in log-distance (nat)
XF = 0.07 # half-width of a seam's cross-fade, nat (about two bins)
@@ -211,21 +217,22 @@ def _dt(f, u):
u = u.reshape((-1,) + (1,) * (f.ndim - 1)); return np.minimum(np.minimum.accumulate(f - u, axis=0) + u, np.flip(np.minimum.accumulate(np.flip(f + u, 0), axis=0), 0) - u)
def seams(cov, targets, d):
- """(K, n) ordered seam distances (m), one per authored target (m), each column. One 1D forward-energy DP per seam, in target order (seam carving, Avidan & Shamir 2007; forward energy, Rubinstein et al. 2008): unary
+ """(K, n) ordered seam distances (m), one per authored target (m), each column of a RING (cov is periodic: the last column neighbours the first). One 1D forward-energy DP per seam, in target order (seam carving, Avidan & Shamir 2007; forward energy, Rubinstein et al. 2008): unary
SEAM_UNARY x the rows at the seam; moving a bin between neighbouring columns costs SEAM_LAM per bin plus the rows swept, an L1 distance in u = cumsum(rows) + SEAM_LAM x bin; a weak prior to the target. Seam k is held at
- least SEAM_SEP nat beyond seam k-1 in every column. Sequential, not joint: a joint DP has NB^K states per column and seams in gaps do not interact."""
- cov = np.asarray(cov, np.float64); nb, n = cov.shape; edges = log_edges(d, nb); bc = 0.5 * (edges[:-1] + edges[1:]); sep = int(math.ceil(SEAM_SEP / (edges[1] - edges[0]))); INF = 1e12
+ least SEAM_SEP nat beyond seam k-1 in every column. Sequential, not joint: a joint DP has NB^K states per column and seams in gaps do not interact. Periodic: the DP runs over the ring three times side by side and keeps the middle lap,
+ so a seam is continuous across the wrap and a tile boundary is only a crop."""
+ cov = np.tile(np.asarray(cov, np.float64), (1, 3)); nb, n3 = cov.shape; n = n3 // 3; edges = log_edges(d, nb); bc = 0.5 * (edges[:-1] + edges[1:]); sep = int(math.ceil(SEAM_SEP / (edges[1] - edges[0]))); INF = 1e12
r = int(3 * SIG_B) + 1; kern = np.exp(-0.5 * (np.arange(-r, r + 1) / SIG_B) ** 2); kern /= kern.sum(); pad = np.pad(cov, ((r, r), (0, 0)), mode='edge'); Cs = sum(kv * pad[i:i + nb] for i, kv in enumerate(kern))
- bins = np.arange(nb); lo = np.zeros(n, int); out = np.zeros((len(targets), n))
+ bins = np.arange(nb); lo = np.zeros(n3, int); out = np.zeros((len(targets), n3))
for t, T in enumerate(targets):
prior = SEAM_PRIOR * (bc - math.log(T)) ** 2; need = np.minimum(lo + (sep if t else 0), nb - 1); feas = bins[:, None] >= need[None, :]
warp = lambda x: np.cumsum(0.5 * (cov[:, x - 1] + cov[:, x])) + SEAM_LAM * bins
cost = np.where(feas[:, 0], SEAM_UNARY * Cs[:, 0] + prior, INF); store = [cost]
- for x in range(1, n): cost = np.where(feas[:, x], _dt(cost, warp(x)) + SEAM_UNARY * Cs[:, x] + prior, INF); store.append(cost)
- j = np.zeros(n, int); j[-1] = int(np.argmin(store[-1]))
- for x in range(n - 1, 0, -1): u = warp(x); j[x - 1] = int(np.argmin(store[x - 1] + np.abs(u - u[j[x]])))
+ for x in range(1, n3): cost = np.where(feas[:, x], _dt(cost, warp(x)) + SEAM_UNARY * Cs[:, x] + prior, INF); store.append(cost)
+ j = np.zeros(n3, int); j[-1] = int(np.argmin(store[-1]))
+ for x in range(n3 - 1, 0, -1): u = warp(x); j[x - 1] = int(np.argmin(store[x - 1] + np.abs(u - u[j[x]])))
out[t] = np.exp(bc[j]); lo = j
- return out
+ return out[:, n:2 * n]
# ====================================================================== cards: layered depth, one per band between seams
GRASS, FOREST, ROCK, SNOW = (0.36, 0.44, 0.26), (0.22, 0.31, 0.20), (0.47, 0.44, 0.41), (0.93, 0.95, 0.97)
@@ -239,7 +246,7 @@ def cards(d, a, h, seams, nrm=None):
card keeps the terrain a nearer ridge hides. Its alpha is that pixel's coverage (a crest row holds the share of its angular span under the card's running maximum) times 1 - smoothstep over seam i +- XF in
log-distance of the hit; card 0 owns the rows below the first sample, the last card has no far edge. Alphas are then made nested so the alpha-over composite of all cards is exactly the opaque coverage (a row two
cards both hold partly is not counted twice). Distance and normal are interpolated between sample k-1 and k by angle. Each card is cropped to the rows where its 8-bit alpha is not zero.
- nrm is normals(d, h) of the same columns (default: computed from h as given, so pass it for a window cut from the ring). Rows of a card i > 0 below the angle of its first sample (hit and idx == 0) are the extruded wall of the ridge the card starts at: they keep that sample's distance, their albedo is the ground material at their height with the face up (n_up = 1),
+ nrm is normals(d, h) of the same columns (default: computed from h as given, so pass it for columns cut from the ring: the lateral slope reads the neighbouring columns). Rows of a card i > 0 below the angle of its first sample (hit and idx == 0) are the extruded wall of the ridge the card starts at: they keep that sample's distance, their albedo is the ground material at their height with the face up (n_up = 1),
and `wall` flags them (card 0 has no wall: its rows below the first sample are the ground). Each card: dict(top, alpha (h,n), albedo (h,n,3), n_r, n_t, logd (ln metres) (h,n), wall (h,n) bool)."""
d = np.asarray(d, np.float64); a = np.asarray(a, np.float64); h = np.asarray(h, np.float64); seams = np.asarray(seams, np.float64); nk, n = a.shape; nc = len(seams) + 1
n_r, n_t, n_u = nrm if nrm is not None else normals(d, h); ld = np.broadcast_to(np.log(d)[:, None], (nk, n)); p = 1.0 / PXDEG_V; lo = rowang - 0.5 * p
diff --git a/scripts/ridge-bake/tests/mutate.py b/scripts/ridge-bake/tests/mutate.py
index 70b889fb..17e2a817 100644
--- a/scripts/ridge-bake/tests/mutate.py
+++ b/scripts/ridge-bake/tests/mutate.py
@@ -1,5 +1,5 @@
"""Mutation check: re-introduce a cause into a COPY of the baker, run the fixtures against it, and require that at least one fails.
- venv/bin/python tests/mutate.py (prints one line per mutant; exit 1 if a mutant survives)"""
+ venv/bin/python tests/mutate.py [word ...] (prints one line per mutant whose name holds every word; exit 1 if a mutant survives)"""
import os, shutil, subprocess, sys, tempfile
HERE = os.path.dirname(os.path.abspath(__file__)); SRC = os.path.join(HERE, '..')
MUTANTS = { # name -> (text in ridge.py or export.py, replacement)
@@ -14,7 +14,6 @@ MUTANTS = { # name -> (text in ridge.py or export.py, replacement)
'prefilter across rays uses one sigma in columns (not per distance)': ("sc = sigma_m / (d * COLW)", "sc = sigma_m / (d[0] * COLW) * np.ones_like(d)"),
'bake_id hashes geometry before colour': ("h.update(colour); h.update(geometry)", "h.update(geometry); h.update(colour)"),
'check_cover accepts any composite': ("if bad.any(): y, x", "if False: y, x"),
- 'check_budget ignores the cropped bands (decoded as full frames)': ("decoded = sum(2 * w * h * 4 for h in bands)", "decoded = 0"),
'load_preset accepts splits that do not increase': ("or any(b <= a for a, b in zip(sp, sp[1:]))", ""),
'geometry: n_r and n_t channels swapped': ("r, t = u8((np.asarray(n_r) + 1) / 2), u8((np.asarray(n_t) + 1) / 2)", "r, t = u8((np.asarray(n_t) + 1) / 2), u8((np.asarray(n_r) + 1) / 2)"),
'geometry: log-distance not normalised by the encoding range': ("b = (np.asarray(logd) - enc['log_d_min']) / (enc['log_d_max'] - enc['log_d_min'])", "b = np.asarray(logd) / 12.0"),
@@ -31,20 +30,42 @@ MUTANTS = { # name -> (text in ridge.py or export.py, replacement)
'wall: albedo takes the face normal, not the face up': ("np.where(Wl[i, sl], 1.0, g[4] / nz)", "g[4] / nz"),
'wall: the code is not written to the geometry': ("if wall is not None: m = np.asarray(wall, bool)", "if False: m = np.asarray(wall, bool)"),
'wall: the sheet lights wall rows with their normal': ("wall = c['wall']; n_r, n_t = np.where(wall, 0.0, c['n_r']), np.where(wall, 0.0, c['n_t'])", "n_r, n_t = c['n_r'], c['n_t']"),
- 'camera: the sign of r is flipped in the scale': ("return [d / (d - r_m) for d in distances]", "return [d / (d + r_m) for d in distances]"),
- 'camera: the scale is clamped (a function of r that is not the formula)': ("return [d / (d - r_m) for d in distances]", "return [min(d / (d - r_m), 1.2) for d in distances]"),
- 'camera: the card distance includes wall rows': ("ground = (c['alpha'] >= 0.5) & ~c['wall']", "ground = (c['alpha'] >= 0.5)"),
- 'camera: the offset bound is ignored': ("if abs(r_m) >= R_FRAC_MAX * min(distances): raise", "if False: raise"),
- 'camera: the frame-bottom coverage check is removed': ("if bottom < view['plane_h'] - 1e-6: raise", "if False: raise"),
- 'camera: the 16:9 rest coverage check is removed': ("if min(scales) < REST_SCALE_MIN: raise", "if False: raise"),
- 'camera: the preset camera_r_m is ignored': ("r_m=float(p.get('camera_r_m', CAMERA_R_M))", "r_m=float(CAMERA_R_M)"),
- 'camera: the manifest writes the default heading range, not the bake\'s': ("heading_max_deg=meta['camera']['heading_max_deg']),", "heading_max_deg=HEADING_MAX_DEG),"),
- 'export: an empty card is not refused': ("if c['alpha'].shape[0] == 0: raise", "if False: raise"),
+ 'ring: the seam DP is not periodic (the first lap is kept, not the middle)': ("return out[:, n:2 * n]", "return out[:, :n]"),
+ 'ring: the tile take does not wrap (the ring ends repeat their edge column)': ("return np.take(a, (c0 + np.arange(n)) % W, axis=-1)", "return np.take(a, np.clip(c0 + np.arange(n), 0, W - 1), axis=-1)"),
+ 'tile: the apron is shifted (a tile starts at its own first column)': ("ridge.ring_cols(x, t * TILE_W - APRON, TILE_W + 2 * APRON)", "ridge.ring_cols(x, t * TILE_W, TILE_W + 2 * APRON)"),
+ 'tile: the seams are cut from tile 0 for every tile': ("cols(sm, t), tuple(cols(x, t) for x in nrm)", "cols(sm, 0), tuple(cols(x, t) for x in nrm)"),
+ 'view: the vertical anchors read the first 72 degrees only (the old window)': ("sk = np.asarray(skyline); sky", "sk = np.asarray(skyline)[:1280]; sky"),
+ 'bake_id: card-major instead of tile-major': ("bake_id(text, [(e['colour'], e['geometry']) for row in tiles for e in row if e])", "bake_id(text, [(row[i]['colour'], row[i]['geometry']) for i in range(k) for row in tiles if row[i]])"),
+ 'bake_id: the manifest is not hashed (a manifest moves under its id)': ("h = hashlib.sha256(); h.update(manifest_text.encode('utf-8'))", "h = hashlib.sha256()"),
+ 'bake_id: the manifest is hashed with the id already in it (the blank is skipped)': ("bid = bake_id(text, [", "bid = bake_id(text.replace(BAKE_ID_BLANK, '111111111111'), ["),
+ 'write: the per-tile cover check is dropped': ("except ValueError as ex: raise ValueError(f'tile {t}: {ex}')", "except ValueError as ex: pass"),
+ 'write: the apron width is not checked': ("if c.shape[1] != w: raise", "if False: raise"),
+ 'budget: the tile cap is ignored': ("if b > TILE_BYTES_MAX: raise", "if False: raise"),
+ 'budget: the place cap is ignored': ("if sum(tile_bytes) > PLACE_BYTES_MAX: raise", "if False: raise"),
+ 'budget: the resident gate is ignored': ("if res > RESIDENT_BYTES_MAX: raise", "if False: raise"),
+ 'budget: the resident run does not wrap the ring': ("sum(per[(t + k) % TILES] for k in range(n))", "sum(per[t + k] for k in range(n) if t + k < TILES)"),
+ 'budget: the run length forgets the margin tiles': ("math.ceil(arc / TILE_DEG) + 1 + 4", "math.ceil(arc / TILE_DEG)"),
+ 'r_max: the camera sweeps forward only (phi = 0)': ("PHI_STEPS = 24 ", "PHI_STEPS = 1 "),
+ 'r_max: every card of a tile is fitted at the nearest card distance': ("fit_px(d, r, px_per_deg, phis) for d in row", "fit_px(row[0] if row[0] is not None else d, r, px_per_deg, phis) for d in row"),
+ 'r_max_forward: the forward offset is searched over the whole circle': ("r_fwd = solve_r_max(dist, bands, ppd, phis=1)", "r_fwd = solve_r_max(dist, bands, ppd)"),
+ 'r_max_forward: the resident gate is not checked at the forward offset': ("for r in (camera['r_max_m'], camera['r_max_forward_m']): check_budget", "for r in (camera['r_max_m'],): check_budget"),
+ 'r_max_forward: a forward offset below r_max_m is accepted': ("if camera['r_max_forward_m'] < camera['r_max_m']: raise", "if False: raise"),
+ 'fit: the line is the least squares of 33 uniform samples, as the first gate drew it': ("x, w = np.polynomial.legendre.leggauss(FIT_QUAD)", "x = np.linspace(-1, 1, 33); w = np.full(33, 2 / 33)"),
+ 'fit: the line is a two-node quadrature': ("FIT_QUAD = 48 ", "FIT_QUAD = 2 "),
+ 'write: the manifest is written as platform text (CRLF on Windows)': ("(tmp / 'manifest.json').write_bytes(text.encode('utf-8'))", "(tmp / 'manifest.json').write_text(text)"),
+ 'write: the index is written as platform text (CRLF on Windows)': ("(out / '.index.tmp').write_bytes((json.dumps(idx, indent=1) + '\\n').encode('utf-8'))", "(out / '.index.tmp').write_text(json.dumps(idx, indent=1) + '\\n')"),
+ 'r_max: not capped at half the nearest distance': ("cap = 0.5 * rmin", "cap = 5.0 * rmin"),
+ 'r_max: the resident gate is not part of the search': (" and resident_bytes(bands, run_tiles(r, rmin)) <= RESIDENT_BYTES_MAX\n", "\n"),
+ 'r_max: a bake below the floor is accepted': ("if r_max < R_MAX_FLOOR_M:", "if False:"),
+ 'pack: the distance counts wall rows': ("solid = (al >= 0.5) & ~wl; any_solid", "solid = (al >= 0.5); any_solid"),
+ 'pack: the distance reads the apron columns too': ("inner = slice(APRON, APRON + TILE_W)", "inner = slice(0, TILE_W + 2 * APRON)"),
+ 'sheet: the tile boundaries are not drawn': ("def bounds(img): img[:, mark] = 0.45 * img[:, mark] + 0.55 * red; return img", "def bounds(img): return img"),
+ 'export: an empty card is not refused': ("if all(tile[i]['alpha'].shape[0] == 0 for tile in bake['cards']): raise", "if False: raise"),
'rays cache key ignores the refraction constant': ("R_EARTH, KREF, W, bool(detail)", "R_EARTH, W, bool(detail)"),
'rays cache key ignores the eye elevation': ("round(float(P['eye_m']), 3), ", ""),
'mosaic cache key ignores the tile list': ("sorted(tiles_for(p)), 3600", "3600"),
}
-EQUIVALENT = {} # mutant name -> one line on why it is behaviourally equivalent (reported, not run)
+EQUIVALENT = {'fit: the error is looked for between four points': "the worst error of the best line is at the viewport's two ends for every distance and offset the bound is searched over (checked against a 20001-sample brute force in test_fit_px_is_the_continuous_error); the grid only guards a shape where it is not"} # mutant name -> one line on why it is behaviourally equivalent (reported, not run)
def run(item):
name, (a, b) = item; d = tempfile.mkdtemp(); shutil.copytree(SRC, os.path.join(d, 'src'), ignore=shutil.ignore_patterns('tests', '__pycache__')); p = next(q for q in (os.path.join(d, 'src', f) for f in ('ridge.py', 'export.py')) if a in open(q).read()); s = open(p).read(); assert a in s, name
open(p, 'w').write(s.replace(a, b))
@@ -54,7 +75,7 @@ def run(item):
return line, r.returncode == 0
if __name__ == '__main__':
from concurrent.futures import ThreadPoolExecutor
- with ThreadPoolExecutor(int(os.environ.get('MUTATE_JOBS', '6'))) as ex: res = list(ex.map(run, [(n, v) for n, v in MUTANTS.items() if n not in EQUIVALENT]))
+ with ThreadPoolExecutor(int(os.environ.get('MUTATE_JOBS', '6'))) as ex: res = list(ex.map(run, [(n, v) for n, v in MUTANTS.items() if n not in EQUIVALENT and all(w in n for w in sys.argv[1:])]))
for line, _ in res: print(line, flush=True)
for n, why in EQUIVALENT.items(): print('EQUIVALENT ' + n + ' -> ' + why)
sys.exit(1 if any(sv for _, sv in res) else 0)
diff --git a/scripts/ridge-bake/tests/test_ridge.py b/scripts/ridge-bake/tests/test_ridge.py
index 8a323cf5..7cba627e 100644
--- a/scripts/ridge-bake/tests/test_ridge.py
+++ b/scripts/ridge-bake/tests/test_ridge.py
@@ -4,10 +4,13 @@ Synthetic terrain has a known right answer; the Vienna tests bake the real prese
import os, sys, math, json, shutil, tempfile, traceback
SRC = os.environ.get('RIDGE_SRC') or os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'); sys.path.insert(0, SRC) # RIDGE_WORK and RIDGE_TILES must be set (tests/run.sh sets them)
import numpy as np, ridge, export
-from ridge import W, WIN, H
+from ridge import W, H
+NW = 1280 # the synthetic bakes' window: columns 0..NW of the ring (azimuth 0..72); the pieces that need the whole ring (seams across the wrap, the tile cut) run on the ring
+TW = export.TILE_W + 2 * export.APRON
+_w = lambda x: ridge.ring_cols(x, 0, NW)
EYE = 100.0; GROUND = 50.0 # ground below the eye: every ray climbs, so only the placed blocks make ridges
-ridge.P = dict(id='synthetic', rmax_km=95, eye_m=100.0, win0=0)
+ridge.P = dict(id='synthetic', rmax_km=95, eye_m=100.0)
D = ridge.schedule(False)
def az_of(x): return (x + 0.5) / W * 360.0
def col_of(az): return int(round(az / 360.0 * W - 0.5)) % W
@@ -45,16 +48,13 @@ def test_paths_come_from_the_environment_with_no_default():
r = subprocess.run([sys.executable, '-I', '-c', 'import sys; sys.path.insert(0, %r); import ridge' % SRC], env=e, capture_output=True, text=True); assert r.returncode and var in r.stderr and 'not set' in r.stderr, (var, r.stderr[-200:])
# ---------------------------------------------------------------------------------------- synthetic bakes: the shared steps of export.bake_place on rays the fixtures make
-def _bake(hfun, splits_km, sigma=0.0):
- """prefilter, set_view, coverage, seams, cards on synthetic rays (window = columns 0..WIN, i.e. azimuth 0..72): the dict bake_place returns."""
- A, Hh = rays(hfun); ridge.P.update(win0=0, eye_m=EYE); a, h = ridge.prefilter(D, Hh, sigma); v = ridge.set_view(a.max(0))
- nrm = tuple(ridge.win(x) for x in ridge.normals(D, h)); aw, hw = ridge.win(a), ridge.win(h); cov = ridge.coverage(D, aw); sm = ridge.seams(cov, [k * 1000.0 for k in splits_km], D)
- place = dict(id='synthetic', name='Synthetic', lat=48.0, lon=16.0, altitude_km=0.05, eye_m=EYE)
- view = dict(look_az_deg=36.0, plane_h=H, px_per_deg_h=ridge.HPX_DEG, px_per_deg_v=v['px_per_deg'], exaggeration=v['exaggeration'], horizon_row=v['horizon_row'], sky_row=v['sky_row'] * H, near_row=v['near_row'] * H)
- meta = dict(curvature=dict(r_earth_m=ridge.R_EARTH, k_ref=ridge.KREF), encoding=dict(log_d_min=math.log(D[0]), log_d_max=math.log(D[-1])), camera=dict(r_m=export.CAMERA_R_M, heading_max_deg=17.0))
- return dict(place=place, view=view, meta=meta, cards=ridge.cards(D, aw, hw, sm, nrm, ), splits_km=list(splits_km), seams=sm, cov=cov, opaque=ridge.opaque(aw), edges=ridge.log_edges(D), a=aw, h=hw, v=v)
+def _bake(hfun, splits_km, sigma=0.0, fixed_m=None):
+ """prefilter, whole-ring set_view, coverage and the periodic seams on the whole ring (or fixed_m, one seam depth in m for every column), then the window columns 0..NW (azimuth 0..72) of them and the cards on those, of synthetic rays: the pieces of the bake a fixture can look at cheaply."""
+ A, Hh = rays(hfun); ridge.P.update(eye_m=EYE); a, h = ridge.prefilter(D, Hh, sigma); v = ridge.set_view(a.max(0))
+ nrm = tuple(_w(x) for x in ridge.normals(D, h)); aw, hw = _w(a), _w(h); cov_ring = ridge.coverage(D, a); cov = _w(cov_ring); sm = _w(ridge.seams(cov_ring, [k * 1000.0 for k in splits_km], D)) if fixed_m is None else np.array([np.full(NW, float(v)) for v in fixed_m])
+ return dict(cards=ridge.cards(D, aw, hw, sm, nrm), splits_km=list(splits_km), seams=sm, cov=cov, opaque=ridge.opaque(aw), edges=ridge.log_edges(D), a=aw, h=hw, nrm=nrm, v=v)
def _canvas(card, key='alpha'):
- out = np.zeros((H, WIN) + card[key].shape[2:], np.float32); out[card['top']:card['top'] + card[key].shape[0]] = card[key]; return out
+ out = np.zeros((H, NW) + card[key].shape[2:], np.float32); out[card['top']:card['top'] + card[key].shape[0]] = card[key]; return out
def _row(deg): return int(np.argmin(np.abs(ridge.rowang - deg)))
THREE = terrain(block(0, 359.99, 3000, 3600, 350), block(0, 359.99, 20000, 21500, 1800), block(0, 359.99, 70000, 72000, 7000)) # ridges at 3, 20 and 70 km, each taller in angle than the one before
WIDE3 = terrain(block(0, 359.99, 9000, 10000, 300), block(0, 359.99, 38000, 40000, 2000), block(0, 359.99, 70000, 72000, 3000)) # low near hills, then ridges at 39 and 71 km: the frame reaches below the ground at the seams (so cards have wall rows) and the horizon is inside it
@@ -62,26 +62,35 @@ WALLED = terrain(block(0, 359.99, 9000, 10000, 300), block(0, 359.99, 38000, 400
NEARHILL = terrain(block(0, 359.99, 0, 4000, 150), block(0, 359.99, 38000, 40000, 2000)) # ground above the eye from the first sample on: every row of card 0 lies below its first sample
def _ramp(dk, az): return np.maximum(GROUND, np.where(dk > 12000, (dk - 12000) * 0.045 + 50.0, 0.0)) # a slope the first sample of card 1 stands on: n_up about 0.9, so the material would be rock if the face counted
+def test_the_vertical_anchors_read_the_whole_ring():
+ """set_view anchors the highest skyline angle of the ring at 4% of the frame and the lowest at 66%, wherever they are: a peak at column 3555 and a low at column 5333, both outside the first 72 degrees, set the mapping."""
+ sk = np.full(W, 1.0); sk[3555] = 3.0; sk[5333] = -1.0; sk[10] = 1.5; v = ridge.set_view(sk)
+ assert v['sky_deg'] == 3.0 and v['low_deg'] == -1.0 and abs(v['px_per_deg'] - 0.62 * H / 4.0) < 1e-9 and abs(v['horizon_row'] - ridge.TOP_DEG * v['px_per_deg']) < 1e-9 and abs(ridge.TOP_DEG - (3.0 + 0.04 * H / v['px_per_deg'])) < 1e-9, v
def test_seams_fall_in_depth_gaps():
"""Three ridges at 3, 20 and 70 km: targets [6, 40] give a seam in (3, 20) and one in (20, 70) in EVERY column, ordered with at least 0.4 nat between; targets [6] give one seam in (3, 20)."""
- b = _bake(THREE, [6, 40]); s = b['seams']; assert s.shape == (2, WIN)
+ b = _bake(THREE, [6, 40]); s = b['seams']; assert s.shape == (2, NW)
assert (s[0] > 3600).all() and (s[0] < 20000).all() and (s[1] > 21500).all() and (s[1] < 70000).all(), (s.min(1), s.max(1)); assert (np.log(s[1]) - np.log(s[0]) >= 0.4 - 1e-9).all()
- s1 = _bake(THREE, [6])['seams']; assert s1.shape == (1, WIN) and (s1[0] > 3600).all() and (s1[0] < 20000).all(), (s1.min(), s1.max())
+ s1 = _bake(THREE, [6])['seams']; assert s1.shape == (1, NW) and (s1[0] > 3600).all() and (s1[0] < 20000).all(), (s1.min(), s1.max())
def _recede(d0, d1, thick=300.0, hgt=1500.0):
- """A ridge `thick` m thick whose distance runs from d0 m at azimuth 0 to d1 m at azimuth 72."""
- return terrain(lambda dk, az: np.where((az <= 72) & (np.abs(dk - (d0 + (d1 - d0) * np.clip(az / 72.0, 0, 1))) < thick / 2), hgt, 0.0))
+ """A ridge `thick` m thick whose distance runs from d0 m at azimuth 0 to d1 m at azimuth 72, and again in every 72 degrees of the ring (so the ring's skyline is the ridge's everywhere, as the window's was)."""
+ return terrain(lambda dk, az: np.where(np.abs(dk - (d0 + (d1 - d0) * ((az % 72) / 72.0))) < thick / 2, hgt, 0.0))
def _receding(dk, az): return _recede(4000.0, 15000.0)(dk, az)
def test_the_swept_rows_term_keeps_the_seam_from_hopping_under_a_stronger_pull():
- """With the authored depth pulling harder (0.1 instead of 0.02) the 4 to 15 km ridge's seam still follows the ridge: only the cost of the visible rows it would sweep holds it back (with that term out of the cost it hops between two columns)."""
- old = ridge.SEAM_PRIOR; ridge.SEAM_PRIOR = 0.1
- try: j0, j1, cover = _alpha_jumps(4, 15, 6)
+ """With the authored depth pulling five times as hard (0.1 instead of 0.02) the seams of the 3-12, 4-15 (split 10) and 6-14 km ridges still follow the ridge, and twice as hard (0.04) those of the 4-15 (split 6), 5-30 and 8-40 km ridges: only the cost of the visible rows it would sweep holds it back (with that term out of the cost it hops between two columns)."""
+ old = ridge.SEAM_PRIOR
+ try:
+ ridge.SEAM_PRIOR = 0.1
+ for d0, d1, sp in ((3, 12, 6), (4, 15, 10), (6, 14, 9)):
+ j0, j1, cover = _alpha_jumps(d0, d1, sp); assert j0 < 0.35 and j1 < 0.35 and cover > 0.999, ('the seam hopped across the ridge', (d0, d1, sp), j0, j1)
+ ridge.SEAM_PRIOR = 0.04 # these three tear above 0.04 (measured: 0.05 tears 5-30 and 8-40, 0.1 tears 4-15/6): the seam is closed on the ring, so a stronger pull makes one tear per period cheaper than staying beyond the ridge
+ for d0, d1, sp in ((4, 15, 6), (5, 30, 12), (8, 40, 15)):
+ j0, j1, cover = _alpha_jumps(d0, d1, sp); assert j0 < 0.35 and j1 < 0.35 and cover > 0.999, ('the seam hopped across the ridge', (d0, d1, sp), j0, j1)
finally: ridge.SEAM_PRIOR = old
- assert j0 < 0.35 and j1 < 0.35 and cover > 0.999, ('the seam hopped across the ridge', j0, j1)
RECEDING = [(4, 15, 6), (3, 12, 6), (5, 30, 12), (8, 40, 15), (4, 15, 10), (6, 14, 9)] # km at azimuth 0, km at azimuth 72, authored split km
def _alpha_jumps(d0, d1, split):
"""The two cards' alpha on the ridge body (crest + 4 rows), column to column: the largest step of each. """
b = _bake(_recede(d0 * 1000.0, d1 * 1000.0), [split]); c0 = _canvas(b['cards'][0]); c1 = _canvas(b['cards'][1]); crest = np.argmax(b['opaque'] > 0.5, axis=0); r = np.clip(crest + 4, 0, H - 1); ok = crest > 0
- a0 = c0[r, np.arange(WIN)]; a1 = c1[r, np.arange(WIN)]; return float(np.abs(np.diff(a0[ok])).max()), float(np.abs(np.diff(a1[ok])).max()), (a0 + (1 - a0) * a1)[ok].min()
+ a0 = c0[r, np.arange(NW)]; a1 = c1[r, np.arange(NW)]; return float(np.abs(np.diff(a0[ok])).max()), float(np.abs(np.diff(a1[ok])).max()), (a0 + (1 - a0) * a1)[ok].min()
def test_seam_never_splits_a_receding_ridge_side_by_side():
"""Six synthetic ridges whose distance recedes across the window (4 to 15, 3 to 12, 5 to 30, 8 to 40, 4 to 15 and 6 to 14 km, targets 6, 6, 12, 15, 10, 9 km): the nearer and the farther card's alpha on the ridge's body never jumps by 0.35 between neighbouring
columns (a tear: one card here, the other next door; fading slowly over the cross-fade is fine) and the two cards together cover the body. With the swept-rows term out of the seam cost the seam hops across the ridge; with the prior at 0.1 it hops on two of the six."""
@@ -96,8 +105,8 @@ def test_far_card_keeps_terrain_hidden_behind_a_nearer_ridge():
r = _row(0.5 * (theta(350, 3000) + theta(2400, 20000))); assert c0[r, 900] < 0.01 and a1[r, 900] > 0.99 and abs(math.exp(ld1[r, 900]) - 20000) < 1500, (c0[r, 900], a1[r, 900])
def test_crossfade_is_complementary():
"""A ridge across the seam (seam fixed at 6 km, the ridge's front face at 5.9 km inside the cross-fade): the nearer card is partly transparent over the window, the farther card is opaque on the ridge, and the composite stays at coverage 1 below the crest."""
- A, Hh = rays(terrain(block(0, 359.99, 5900, 6100, 900))); ridge.P.update(win0=0, eye_m=EYE); ridge.set_view(A.max(0)); aw, hw = ridge.win(A), ridge.win(Hh)
- cs = ridge.cards(D, aw, hw, np.full((1, WIN), 6000.0)); c0, c1 = _canvas(cs[0]), _canvas(cs[1]); crest = int(np.argmax(ridge.opaque(aw)[:, 500] > 0.5)); r = crest + 6
+ A, Hh = rays(terrain(block(0, 359.99, 5900, 6100, 900))); ridge.P.update(eye_m=EYE); ridge.set_view(A.max(0)); aw, hw = _w(A), _w(Hh)
+ cs = ridge.cards(D, aw, hw, np.full((1, NW), 6000.0)); c0, c1 = _canvas(cs[0]), _canvas(cs[1]); crest = int(np.argmax(ridge.opaque(aw)[:, 500] > 0.5)); r = crest + 6
assert 0.2 < c0[r, 500] < 0.8, ('the near card does not fade over the window', c0[r, 500]); assert c1[r, 500] > 0.99, 'the far card is not opaque on the ridge'
comp = 1 - (1 - c0) * (1 - c1); assert (comp[crest + 3:, :] > 0.999).all(), 'the composite dips below coverage 1 under the crest'
def test_normals_of_a_tilted_plane():
@@ -127,7 +136,7 @@ def test_prefilter_flattens_roofs_and_keeps_hills():
assert np.allclose(ridge.prefilter(D, Hh, 0.0)[1], Hh), 'sigma 0 changed the heights'
def test_crest_rows_have_fractional_coverage():
"""The top row of a card's run has alpha equal to the share of its angular span under the running maximum, and the rows below it are 1 (a lower ridge in columns 0..640 so its crest is not at the frame's top edge)."""
- A, Hh = rays(terrain(block(0, 36, 5000, 5600, 500), block(36, 359.99, 5000, 5600, 560))); ridge.P.update(win0=0, eye_m=EYE); ridge.set_view(A.max(0)); aw, hw = ridge.win(A), ridge.win(Hh); c = ridge.cards(D, aw, hw, np.zeros((0, WIN)))[0]
+ A, Hh = rays(terrain(block(0, 36, 5000, 5600, 500), block(36, 359.99, 5000, 5600, 560))); ridge.P.update(eye_m=EYE); ridge.set_view(A.max(0)); aw, hw = _w(A), _w(Hh); c = ridge.cards(D, aw, hw, np.zeros((0, NW)))[0]
cv = _canvas(c)[:, 300]; r = int(np.argmax(cv > 0)); top = float(aw.max(0)[300]); p = 1.0 / ridge.PXDEG_V; want = (top - (ridge.rowang[r] - 0.5 * p)) / p
assert 0.0 < want < 1.0 and abs(cv[r] - want) < 0.01, (cv[r], want, r); assert (cv[r + 1:] > 0.999).all()
def test_cards_composite_to_the_opaque_view():
@@ -139,93 +148,176 @@ def test_cards_composite_to_the_opaque_view():
if _canvas(c)[r, col] > 0.99: first = math.exp(_canvas(c, 'logd')[r, col]); break
assert first is not None and abs(first - D[k]) < 0.1 * D[k] + 60, (first, D[k])
-# ---------------------------------------------------------------------------------------- the real thing: Vienna
-def _vienna(splits):
- saved = ridge.P
- try:
- p = ridge.configure(dict(ridge.load_preset('vienna'), card_split_km=splits)); d, _, Hh, _ = ridge.stage0(False); a, h = ridge.prefilter(d, Hh, p['prefilter_m']); ridge.set_view(a.max(0)); aw = ridge.win(a); hw = ridge.win(h)
- nrm = tuple(ridge.win(x) for x in ridge.normals(d, h)); cov = ridge.coverage(d, aw); sm = ridge.seams(cov, [k * 1000.0 for k in splits], d); return d, aw, ridge.cards(d, aw, hw, sm, nrm), sm, ridge.opaque(aw)
- finally: ridge.P = saved
-def test_vienna_k1_k2_k3():
- """Vienna with card_split_km [6], [6, 40] and [6, 20, 40]: 2, 3 and 4 cards, seams ordered in every column, each composite equals the opaque view within 0.02; the cross-fade column count of each K is printed."""
- for sp in ([6], [6, 40], [6, 20, 40]):
- d, aw, cs, sm, op = _vienna(sp); assert len(cs) == len(sp) + 1 and sm.shape == (len(sp), WIN)
- if len(sp) > 1: assert (np.diff(np.log(sm), axis=0) >= 0.4 - 1e-9).all(), 'seams out of order'
- comp = 1 - np.prod([1 - _canvas(c) for c in cs], axis=0); assert np.abs(comp - op).max() < 0.02, (sp, np.abs(comp - op).max())
- xf = int(np.any([((0.02 < _canvas(c)) & (_canvas(c) < 0.98)).sum(0) > 3 for c in cs], axis=0).sum())
- print(f' K={len(sp)} splits {sp}: {len(cs)} cards, bands {[(c["top"], c["alpha"].shape[0]) for c in cs]}, seam medians km {[round(float(np.median(s)) / 1000, 1) for s in sm]}, cross-fade columns {xf} of {WIN}')
-def test_bake_place_manifest_fields_on_vienna():
- """bake_place on the real Vienna preset: three cards, the place carries the ground (km) and the eye, horizon_row is the row where the elevation angle is 0, px_per_deg_h is the ring's; write_bake of its packed cards validates, index default 'vienna', and no temp dir is left."""
- saved = ridge.P
- load = ridge.load_preset; ridge.load_preset = lambda pid, *a: dict(load(pid, *a), camera_r_m=123.0) # a preset's camera_r_m is the bake's camera
- try: b = export.bake_place('vienna'); P = ridge.P; rowang = ridge.rowang; pxv = ridge.PXDEG_V
- finally: ridge.P = saved; ridge.load_preset = load
- assert b['meta']['camera'] == dict(r_m=123.0, heading_max_deg=export.HEADING_MAX_DEG), b['meta']['camera']
- pl, view = b['place'], b['view']; assert abs(pl['altitude_km'] * 1000 - P['ground_m']) < 1e-6 and abs(pl['eye_m'] - P['eye_m']) < 1e-9 and pl['id'] == 'vienna' and len(b['cards']) == 3
- assert 0 < view['sky_row'] < view['horizon_row'] < view['near_row'] < H and abs(rowang[int(view['horizon_row'])]) <= 1.0 / pxv, (view, rowang[int(view['horizon_row'])]); assert view['px_per_deg_h'] == ridge.HPX_DEG and abs(view['exaggeration'] - pxv / ridge.HPX_DEG) < 1e-9
- d = tempfile.mkdtemp()
- try:
- dest = export.write_bake(d, pl, view, b['meta'], export.pack(b), b['opaque']); m = json.load(open(dest / 'manifest.json')); export.validate(m, export.SCHEMA['$defs']['manifest'])
- assert json.load(open(d + '/index.json'))['default'] == 'vienna' and sorted(os.listdir(d)) == sorted(['index.json', dest.name]), os.listdir(d); print(' vienna manifest bytes', m['bytes'], 'cards', [(c['top'], c['h'], c['colour']['bytes'] + c['geometry']['bytes']) for c in m['cards']])
- finally: shutil.rmtree(d)
+# ---------------------------------------------------------------------------------------- the ring: tiles are crops of per-column results, the wrap is periodic
+_RING = {}
+def _ring(key, hfun, splits_km):
+ """export.cut_ring on synthetic rays (prefilter, whole-ring set_view, then the ring cut), cached by key: dict(bake = what export.bake_place returns, minus the place)."""
+ if key not in _RING:
+ A, Hh = rays(hfun); ridge.P.update(eye_m=EYE); a, h = ridge.prefilter(D, Hh, 0.0); v = ridge.set_view(a.max(0)); r = export.cut_ring(D, a, h, splits_km)
+ _RING[key] = dict(r, op_ring=ridge.opaque(a), place=dict(id='synthetic', name='Synthetic', lat=48.0, lon=16.0, altitude_km=0.05, eye_m=EYE, tz='Europe/Vienna'), v=v,
+ view=dict(look_az_deg=36.0, plane_h=H, px_per_deg_h=ridge.HPX_DEG, px_per_deg_v=v['px_per_deg'], exaggeration=v['exaggeration'], horizon_row=v['horizon_row'], sky_row=v['sky_row'] * H, near_row=v['near_row'] * H),
+ meta=dict(curvature=dict(r_earth_m=ridge.R_EARTH, k_ref=ridge.KREF), encoding=dict(log_d_min=math.log(D[0]), log_d_max=math.log(D[-1]))))
+ return _RING[key]
+def _tile_canvas(card, key='alpha'):
+ out = np.zeros((H, TW) + card[key].shape[2:], np.float32); out[card['top']:card['top'] + card[key].shape[0]] = card[key]; return out
+def _across_north(dk, az): return np.where(in_arc(az, 340, 20) & (np.abs(dk - (12000.0 + 400.0 * (((az + 180) % 360) - 180))) < 200), 1500.0, 0.0) # a ridge across the wrap at 4 km (az -20) to 20 km (az +20)
+ACROSS = terrain(block(0, 359.99, 3000, 3600, 350), _across_north, block(0, 359.99, 70000, 72000, 3000), block(0.0, 0.05, 6000, 7000, 2500), block(359.95, 359.99, 6000, 7000, 2500)) # and a tower one column wide on each side of north
+def test_ring_wrap():
+ """A ridge across column 6399 / 0 (receding from 4 km at -20 deg to 20 km at +20 deg): the seam is continuous over the wrap (its jump there no larger than the largest jump elsewhere), tile 31's right apron equals tile 0's first columns and tile 0's left apron
+ tile 31's last (every card, pixel for pixel), neighbouring tiles agree on their shared apron, and the interiors of all tiles composite to the opaque ring."""
+ b = _ring('across', ACROSS, [8]); sm = np.log(b['seams'][0]); jumps = np.abs(np.diff(np.append(sm, sm[0]))); assert jumps[-1] <= jumps[:-1].max() + 1e-9, ('the seam jumps over the wrap', jumps[-1], jumps[:-1].max())
+ A_ = export.APRON; T_ = export.TILE_W; ring = np.zeros((H, W)); op = np.zeros((H, W))
+ for t, tile in enumerate(b['cards']):
+ nxt = b['cards'][(t + 1) % export.TILES]
+ for i, c in enumerate(tile):
+ assert (_tile_canvas(c)[:, T_ + A_:T_ + 2 * A_] == _tile_canvas(nxt[i])[:, A_:2 * A_]).all(), ('the apron differs from the neighbour', t, i); seen = _tile_canvas(c)[:, T_ + A_:T_ + 2 * A_] > 0
+ for key in ('logd', 'wall'): assert (_tile_canvas(c, key)[:, T_ + A_:T_ + 2 * A_][seen] == _tile_canvas(nxt[i], key)[:, A_:2 * A_][seen]).all(), ('the apron differs from the neighbour', t, i, key)
+ comp = 1 - np.prod([1 - _tile_canvas(c) for c in tile], axis=0); ring[:, t * T_:(t + 1) * T_] = comp[:, A_:A_ + T_]; op[:, t * T_:(t + 1) * T_] = b['opaque'][t][:, A_:A_ + T_]
+ assert np.abs(ring - op).max() < 0.02, np.abs(ring - op).max(); assert np.abs(ring - b['op_ring']).max() < 0.02 and b['op_ring'][:, [0, W - 1]].sum(0).min() > b['op_ring'][:, [1, W - 2]].sum(0).max() + 10, 'the tiles hold the wrong columns of the ring (a tower on column 0 and column 6399 is the fixture)'
+ assert b['opaque'][0].shape == (H, T_ + 2 * A_) and (b['opaque'][0][:, :A_] == b['opaque'][export.TILES - 1][:, T_:T_ + A_]).all(), 'the left apron of tile 0 is not the last columns of tile 31'
+def test_every_tile_is_cut_at_its_own_seam():
+ """The seams sweep from 5 km to 30 km once round the ring (ridge.seams stands in): in every tile the near card holds nothing beyond its columns' seam (plus the cross-fade) and the far card nothing before it, so no tile is cut with another tile's seams."""
+ saved = ridge.seams; sweep = 5000.0 * 6.0 ** (np.arange(W) / W)
+ ridge.seams = lambda cov, targets, d: sweep[None, :]
+ try: b = _ring('swept', terrain(block(0, 359.99, 3000, 3600, 350), block(0, 359.99, 20000, 21500, 1800), block(0, 359.99, 70000, 72000, 3000)), [8])
+ finally: ridge.seams = saved
+ T_, A_ = export.TILE_W, export.APRON; ix = slice(A_, A_ + T_); xf = ridge.XF; seen = 0
+ for t, tile in enumerate(b['cards']):
+ s_t = np.broadcast_to(sweep[np.arange(T_) + t * T_], (H, T_)); c0, c1 = tile[0], tile[1]; d0 = np.exp(_tile_canvas(c0, 'logd')[:, ix]); d1 = np.exp(_tile_canvas(c1, 'logd')[:, ix])
+ n0 = (_tile_canvas(c0)[:, ix] >= 0.5) & (_tile_canvas(c0, 'wall')[:, ix] < 0.5); n1 = (_tile_canvas(c1)[:, ix] >= 0.5) & (_tile_canvas(c1, 'wall')[:, ix] < 0.5); seen += int(n0.sum() + n1.sum())
+ assert (d0[n0] <= s_t[n0] * math.exp(xf) * 1.02 + 100).all() and (d1[n1] >= s_t[n1] * math.exp(-xf) * 0.98 - 100).all(), ('a card tile is cut at another tile seam', t)
+ assert seen > 100_000, 'the fixture holds no card pixels'
+def test_tile_is_a_crop_of_the_columns():
+ """ridge.cards on a tile's columns (the 200 it owns and the apron) equals the same columns of ridge.cards on a wider run of columns, pixel for pixel, for fixed seams: the tile cut changes no pixel and adds no seam."""
+ b = _bake(terrain(_receding, block(0, 359.99, 3000, 3600, 350)), [6]); x0 = 500; n = export.TILE_W + 2 * export.APRON; sl = slice(x0, x0 + n)
+ tile = ridge.cards(D, b['a'][:, sl], b['h'][:, sl], b['seams'][:, sl], tuple(x[:, sl] for x in b['nrm']))
+ for c, w in zip(tile, b['cards']):
+ assert np.array_equal(_canvas(w)[:, sl], _tile_canvas(c)), 'a tile is not a crop of the columns'; seen = _tile_canvas(c) > 0
+ for key in ('albedo', 'n_r', 'n_t', 'logd', 'wall'): assert np.array_equal(_canvas(w, key)[:, sl][seen], _tile_canvas(c, key)[seen]), ('a tile is not a crop of the columns', key)
-# ---------------------------------------------------------------------------------------- export: manifest v2, budget, cover
-def _packed(b=None):
- b = b or _bake(WIDE3, [20, 55]); return b, export.pack(b)
+# ---------------------------------------------------------------------------------------- toy bakes: tile data made by hand, for the packer and the writer
+def _toy(dists=(3000.0, 15000.0, 50000.0), bands=(300, 400, 500), tops=(300, 150, 60), amp=0.01):
+ """TILES tiles of len(dists) cards: card i is a solid band of rows (top, h) whose distance is dists[i] x (1 + amp sin x) across the columns, no wall; the opaque view is their composite. Returns the bake dict pack() reads."""
+ n = export.TILE_W + 2 * export.APRON; x = np.arange(n); tile = []; k = len(dists)
+ for i in range(k):
+ ld = np.log(dists[i] * (1 + amp * np.sin(x * 0.3)))[None, :].repeat(bands[i], 0).astype(np.float32)
+ tile.append(dict(top=tops[i], alpha=np.ones((bands[i], n), np.float32), albedo=np.full((bands[i], n, 3), 0.4, np.float32), n_r=np.full((bands[i], n), 0.1, np.float32), n_t=np.full((bands[i], n), -0.1, np.float32), logd=ld, wall=np.zeros((bands[i], n), bool)))
+ comp = export.composite_alpha([(c['top'], c['alpha']) for c in tile], H, n)
+ return dict(cards=[[dict(c) for c in tile] for _ in range(export.TILES)], splits_km=[6.0 * (j + 1) for j in range(k - 1)], seams=np.tile(np.array(dists[:-1])[:, None] * 0.5, (1, W)), opaque=[comp.copy() for _ in range(export.TILES)],
+ view=dict(look_az_deg=36.0, plane_h=H, px_per_deg_h=ridge.HPX_DEG, px_per_deg_v=100.0, exaggeration=5.0, horizon_row=60.0, sky_row=24.0, near_row=396.0), meta=dict(curvature=dict(r_earth_m=ridge.R_EARTH, k_ref=ridge.KREF), encoding=dict(log_d_min=math.log(500.0), log_d_max=math.log(100000.0))),
+ place=dict(id='toy', name='Toy', lat=0.0, lon=0.0, altitude_km=0.0, eye_m=1.0, tz='UTC'))
+def _write(out, b, packed, **kw):
+ args = dict(place=b['place'], view=b['view'], meta=b['meta'], packed=packed, opaque=b['opaque']); args.update(kw); return export.write_bake(out, **args)
def _refuses(out, b, packed, why, **kw):
- args = dict(place=b['place'], view=b['view'], meta=b['meta'], cards=packed, opaque=b['opaque']); args.update(kw)
- try: export.write_bake(out, **args)
+ try: _write(out, b, packed, **kw)
except ValueError: assert not os.path.exists(out), ('a refused bake left files', why)
else: assert False, why
-def test_manifest_v2_writer():
- """Two independent bakes give the same bytes and bake_id; the manifest validates (an extra key does not), cards are nearest first with their bands and seam medians, the files are what the manifest says, the index points at the dir, a rebake replaces
- the old dir, the committed schema is current, and the Copernicus attribution is the four pinned strings."""
+def _pins():
+ assert (export.RING_W, export.TILES, export.TILE_W, export.APRON, export.MAX_CARDS, export.BAKER_VERSION) == (6400, 32, 200, 2, 6, 5), 'the ring layout is pinned'
+ assert (export.TILE_BYTES_MAX, export.PLACE_BYTES_MAX, export.RESIDENT_BYTES_MAX, export.FIT_PX_MAX, export.R_MAX_FLOOR_M, export.PHI_STEPS) == (235_000, 7_500_000, 20_000_000, 24.0, 25.0, 24), 'the budgets and the fit bound are pinned'
+ assert abs(export.HFOV_MAX_DEG - 72 / 1.1) < 1e-12
+
+def test_schema3():
+ """The manifest validates; a tile array of the wrong length, a missing apron, a file named for another tile, and any key of schema 2 left behind (the camera's heading range and offset, the window, the plane width, the card's median and scale, the whole-bake w and h) are refused; the schema file is pinned; the layout constants are pinned."""
+ _pins(); d = tempfile.mkdtemp()
+ try:
+ b = _toy(); pk = export.pack(b); dest = _write(d, b, pk); m = json.load(open(dest / 'manifest.json')); export.validate_manifest(m); mk = lambda: json.loads(json.dumps(m))
+ assert m['schema'] == 3 and m['baker_version'] == 5 and set(m['view']) >= {'ring_w', 'tile_w', 'tiles', 'apron'} and 'rows_above' not in m['view'] and m['camera'] == dict(r_max_m=pk['camera']['r_max_m'], r_max_forward_m=pk['camera']['r_max_forward_m']) and m['camera']['r_max_forward_m'] >= m['camera']['r_max_m'] and len(m['tiles']) == 32 and 'w' not in m and 'h' not in m
+ def bad(f, why):
+ x = mk(); f(x)
+ try: export.validate_manifest(x)
+ except ValueError: return
+ raise AssertionError(why)
+ bad(lambda x: x['camera'].pop('r_max_forward_m'), 'a camera without its forward offset validated'); bad(lambda x: x['camera'].pop('r_max_m'), 'a camera without its offset validated')
+ bad(lambda x: x['tiles'].pop(), 'a manifest of 31 tiles validated'); bad(lambda x: x['tiles'][3].pop(), 'a tile with a card missing validated'); bad(lambda x: x['tiles'][3].append(None), 'a tile with an extra card validated'); bad(lambda x: x['view'].pop('apron'), 'a missing apron validated')
+ bad(lambda x: x['view'].update(apron=0), 'an apron of 0 validated'); bad(lambda x: x['tiles'][2][1]['colour'].update(file='card-1-t03-colour.webp'), 'a file named for another tile validated')
+ bad(lambda x: x['tiles'].__setitem__(slice(None), [[None] * 3 for _ in range(32)]), 'a card null in every tile validated'); bad(lambda x: x.update(bytes=x['bytes'] + 1), 'a wrong byte total validated')
+ for where, key in (('camera', 'heading_max' + '_deg'), ('view', 'window' + '_deg'), ('view', 'plane' + '_w'), ('view', 'rows_above'), ('camera', 'r_m'), (None, 'w'), (None, 'h')): # schema 2's names are spelled in pieces: the baker's tree must hold none of them
+ bad(lambda x: (x[where] if where else x).update({key: 1}), f'a leftover {key} validated')
+ bad(lambda x: x['cards'][0].update(**{'median' + '_m': 1.0}), 'a leftover median validated'); bad(lambda x: x['cards'][0].update(scale=1.0), 'a leftover scale validated'); bad(lambda x: x['tiles'][0][0].update(scale=1.0), 'a tile entry with a scale validated')
+ bad(lambda x: x['tiles'][0][0].update(distance_m='far'), 'a distance that is not a number validated'); bad(lambda x: x['place'].update(tz='Mars/Olympus'), 'a zone the system does not know validated')
+ assert json.load(open(os.path.join(SRC, 'ridge-bake.schema.json'))) == json.loads(json.dumps(export.SCHEMA)), 'ridge-bake.schema.json is stale (export.py --write-schema)'
+ finally: shutil.rmtree(d)
+def test_manifest_v3_writer():
+ """Two packs of one bake give the same bytes and bake_id; tiles[t][i] files are where the manifest says with the sizes it says and decode to tile_w + 2 apron columns; the bake_id is the sha256 of the files tile-major, then card, colour then geometry; the index points at the dir, a
+ rebake replaces the old dir, cards are nearest first with their seam medians, the attribution is the four pinned strings."""
d = tempfile.mkdtemp()
try:
- b, pk = _packed(); b2, pk2 = _packed(_bake(WIDE3, [20, 55])); assert [(c['colour'], c['geometry']) for c in pk] == [(c['colour'], c['geometry']) for c in pk2], 'two independent bakes gave different bytes'
- a = export.write_bake(d + '/a', b['place'], b['view'], b['meta'], pk, b['opaque']); assert a.name == 'synthetic-' + export.bake_id([(c['colour'], c['geometry']) for c in pk]); assert sorted(os.listdir(d + '/a')) == sorted(['index.json', a.name])
- m = json.load(open(a / 'manifest.json')); export.validate(m, export.SCHEMA['$defs']['manifest']); assert m['schema'] == 2 and m['baker_version'] == export.BAKER_VERSION and len(m['cards']) == 3 and m['w'] == WIN and m['h'] == H
- assert m['camera'] == dict(r_m=export.CAMERA_R_M, heading_max_deg=17.0) and all(c['scale'] == c['distance_m'] / (c['distance_m'] - export.CAMERA_R_M) and c['distance_m'] == c['median_m'] for c in m['cards']), m['camera']
- assert m['cards'][0]['near_m'] is None and m['cards'][-1]['far_m'] is None and m['cards'][0]['far_m'] == m['cards'][1]['near_m'] and m['cards'][0]['median_m'] < m['cards'][1]['median_m'] < m['cards'][2]['median_m']
- for c in m['cards']:
- for kind in ('colour', 'geometry'): f = a / c[kind]['file']; assert f.stat().st_size == c[kind]['bytes'] and export.decode(f.read_bytes()).shape[:2] == (c['h'], WIN), c
- assert m['bytes'] == sum(c[k]['bytes'] for c in m['cards'] for k in ('colour', 'geometry')) and m['encoding']['normal'] == 'rt8' and m['curvature'] == dict(r_earth_m=ridge.R_EARTH, k_ref=ridge.KREF)
- idx = json.load(open(d + '/a/index.json')); export.validate(idx, export.SCHEMA['$defs']['index']); assert idx == dict(schema=1, default='synthetic', places={'synthetic': a.name})
- pk3 = [dict(c) for c in pk]; pk3[1]['geometry'] = pk3[1]['geometry'] + b'x'; assert export.bake_id([(c['colour'], c['geometry']) for c in pk3]) != export.bake_id([(c['colour'], c['geometry']) for c in pk]), 'a changed byte kept the bake_id'
- import hashlib; want = hashlib.sha256(b''.join(c['colour'] + c['geometry'] for c in pk)).hexdigest()[:12]; assert export.bake_id([(c['colour'], c['geometry']) for c in pk]) == want, 'bake_id is not the sha256 of the card files, colour then geometry, in index order'
- assert export.bake_id([(c['geometry'], c['colour']) for c in pk]) != want and export.bake_id([(c['colour'], c['geometry']) for c in pk[::-1]]) != want, 'bake_id ignores the file order'
- bad = json.loads(json.dumps(m)); bad['cards'][0]['extra'] = 1
- try: export.validate(bad, export.SCHEMA['$defs']['manifest'])
- except ValueError: pass
- else: assert False, 'an extra key passed the schema'
- assert json.load(open(os.path.join(SRC, 'ridge-bake.schema.json'))) == json.loads(json.dumps(export.SCHEMA)), 'ridge-bake.schema.json is stale (export.py --write-schema)'
+ b = _toy(); pk = export.pack(b); pk2 = export.pack(b); files = lambda p: [(e['colour'], e['geometry']) for row in p['tiles'] for e in row if e]; assert files(pk) == files(pk2), 'two packs gave different bytes'
+ a = _write(d + '/a', b, pk); m = json.load(open(a / 'manifest.json')); export.validate_manifest(m); text = (a / 'manifest.json').read_bytes().decode('utf-8'); blank = text.replace(f'"bake_id": "{m["bake_id"]}"', f'"bake_id": "{export.BAKE_ID_BLANK}"'); assert blank != text and a.name == 'toy-' + m['bake_id'] and sorted(os.listdir(d + '/a')) == sorted(['index.json', a.name])
+ import hashlib; want = hashlib.sha256(blank.encode() + b''.join(c + g for c, g in files(pk))).hexdigest()[:12]; assert m['bake_id'] == want and export.bake_id(blank, files(pk)) == want, 'bake_id is not the sha256 of the manifest with its id blanked, then the tile files tile-major, then card, colour then geometry'
+ assert export.bake_id(blank, [(g, c) for c, g in files(pk)]) != want and export.bake_id(blank, files(pk)[::-1]) != want and export.bake_id(blank, [f for i, f in enumerate(files(pk)) if i % 3 != 1] + [f for i, f in enumerate(files(pk)) if i % 3 == 1]) != want, 'bake_id ignores the file order'
+ pk3 = [list(f) for f in files(pk)]; pk3[40][1] += b'x'; assert export.bake_id(blank, [tuple(f) for f in pk3]) != want, 'a changed byte kept the bake_id'
+ assert export.bake_id(blank.replace('"r_max_forward_m"', '"r_max_forward_m "', 1), files(pk)) != want and export.bake_id(blank + ' ', files(pk)) != want, 'a changed manifest kept the bake_id'
+ import pathlib; was = pathlib.Path.write_text; pathlib.Path.write_text = lambda self, data, *a, **k: open(self, 'wb').write(data.replace('\n', '\r\n').encode('utf-8')) # a platform whose text files end lines with CRLF
+ try: w = _write(d + '/crlf', b, pk)
+ finally: pathlib.Path.write_text = was
+ raw = (w / 'manifest.json').read_bytes(); idx_raw = open(d + '/crlf/index.json', 'rb').read(); assert w.name == a.name and b'\r' not in raw and b'\r' not in idx_raw, 'the manifest or the index was written with the platform newline: the bytes served are not the bytes the id was hashed from'
+ assert hashlib.sha256(raw.replace(m['bake_id'].encode(), export.BAKE_ID_BLANK.encode()) + b''.join(c + g for c, g in files(pk))).hexdigest()[:12] == m['bake_id']
+ pk4 = dict(pk, camera=dict(pk['camera'], r_max_forward_m=pk['camera']['r_max_forward_m'] + 0.1)); a4 = _write(d + '/d', b, pk4); assert a4.name != a.name and [(e['colour'], e['geometry']) for row in pk4['tiles'] for e in row if e] == files(pk), 'a manifest moved under the same bake id (tile bytes identical, camera differs)'
+ assert m['cards'][0]['near_m'] is None and m['cards'][-1]['far_m'] is None and m['cards'][0]['far_m'] == m['cards'][1]['near_m'] and len(m['cards']) == 3
+ for t, row in enumerate(m['tiles']):
+ for i, e in enumerate(row):
+ for kind in ('colour', 'geometry'): f = a / e[kind]['file']; assert f.stat().st_size == e[kind]['bytes'] and export.decode(f.read_bytes()).shape[:2] == (e['h'], export.TILE_W + 2 * export.APRON), (t, i, kind)
+ assert m['bytes'] == sum(e[k]['bytes'] for row in m['tiles'] for e in row for k in ('colour', 'geometry')) and m['encoding']['normal'] == 'rt8' and m['curvature'] == dict(r_earth_m=ridge.R_EARTH, k_ref=ridge.KREF)
+ idx = json.load(open(d + '/a/index.json')); export.validate(idx, export.SCHEMA['$defs']['index']); assert idx == dict(schema=1, default='toy', places={'toy': a.name})
want = dict(credit_line='Contains modified Copernicus data: DEM © DLR e.V. 2010-2014 and © Airbus Defence and Space GmbH 2014-2018 provided under COPERNICUS by the European Union and ESA; all rights reserved.',
- licence='Copernicus DEM licence: free, full and open access, with the credit line shown', dem_source='Copernicus DEM GLO-30 (30 m)', url='https://spacedata.copernicus.eu/collections/copernicus-digital-elevation-model')
- assert m['attribution'] == want, m['attribution']
- c = export.write_bake(d + '/a', b['place'], b['view'], b['meta'], pk, b['opaque'])
- assert c.name == a.name; other = dict(b['place'], id='other'); export.write_bake(d + '/a', other, b['view'], b['meta'], pk, b['opaque']); assert json.load(open(d + '/a/index.json'))['default'] == 'synthetic'
- export.write_bake(d + '/a', other, b['view'], b['meta'], pk, b['opaque'], default='other'); assert json.load(open(d + '/a/index.json'))['default'] == 'other'
- idx = json.load(open(d + '/a/index.json')); idx['default'] = 'gone'; open(d + '/a/index.json', 'w').write(json.dumps(idx)); export.write_bake(d + '/a', other, b['view'], b['meta'], pk, b['opaque']); assert json.load(open(d + '/a/index.json'))['default'] == 'other'
+ licence='Copernicus DEM licence: free, full and open access, with the credit line shown', dem_source='Copernicus DEM GLO-30 (30 m)', url='https://spacedata.copernicus.eu/collections/copernicus-digital-elevation-model'); assert m['attribution'] == want, m['attribution']
+ c = _write(d + '/a', b, pk); assert c.name == a.name; other = dict(b['place'], id='other'); _write(d + '/a', b, pk, place=other); assert json.load(open(d + '/a/index.json'))['default'] == 'toy'
+ _write(d + '/a', b, pk, place=other, default='other'); assert json.load(open(d + '/a/index.json'))['default'] == 'other'
+ idx = json.load(open(d + '/a/index.json')); idx['default'] = 'gone'; open(d + '/a/index.json', 'w').write(json.dumps(idx)); _write(d + '/a', b, pk, place=other); assert json.load(open(d + '/a/index.json'))['default'] == 'other'
+ finally: shutil.rmtree(d)
+def test_tile_crop_and_null():
+ """Each card tile is exactly the rows where its 8-bit alpha is non-zero (top and h in the manifest are those rows, the files decode to that band, the written alpha is the card's); a card with no rows in a tile is null there, writes no file and the bake still validates;
+ a card empty everywhere is refused naming the splits, and a card with no solid terrain in any tile is refused."""
+ d = tempfile.mkdtemp()
+ try:
+ b = _ring('wide3', WIDE3, [20, 55]); pk = export.pack(b); dest = _write(d, b, pk); m = json.load(open(dest / 'manifest.json'))
+ for t in (0, 9, 31):
+ for c, e in zip(b['cards'][t], m['tiles'][t]):
+ rows = np.flatnonzero(np.rint(_tile_canvas(c) * 255).max(1) > 0); assert e['top'] == rows[0] and e['h'] == rows[-1] - rows[0] + 1 == c['alpha'].shape[0], (t, e, rows[0], rows[-1])
+ col = export.decode((dest / e['colour']['file']).read_bytes()); assert col.shape[:2] == (e['h'], export.TILE_W + 2 * export.APRON) and np.abs(col[..., 3].astype(int) - np.rint(c['alpha'] * 255)).max() == 0, 'the written alpha is not the card alpha'
+ t0 = _toy(); cs = [[dict(c) for c in tile] for tile in t0['cards']]; empty = dict(top=0, alpha=np.zeros((0, 204), np.float32), albedo=np.zeros((0, 204, 3), np.float32), n_r=np.zeros((0, 204), np.float32), n_t=np.zeros((0, 204), np.float32), logd=np.zeros((0, 204), np.float32), wall=np.zeros((0, 204), bool))
+ cs[5][2] = empty; op = [x.copy() for x in t0['opaque']]; op[5] = export.composite_alpha([(c['top'], c['alpha']) for c in cs[5] if c['alpha'].shape[0]], H, 204); b5 = dict(t0, cards=cs, opaque=op); pk5 = export.pack(b5)
+ assert pk5['tiles'][5][2] is None and pk5['tiles'][4][2] is not None; dest = _write(d + '/null', b5, pk5); m5 = json.load(open(dest / 'manifest.json')); assert m5['tiles'][5][2] is None and not (dest / export.tile_file(2, 5, 'colour')).exists() and (dest / export.tile_file(2, 4, 'colour')).exists()
+ for i, why in ((1, '20 km'), (2, '55 km')):
+ gone = [[empty if j == i else c for j, c in enumerate(tile)] for tile in b['cards']]
+ try: export.pack(dict(b, cards=gone))
+ except ValueError as e: assert f'card {i} is empty' in str(e) and why in str(e), str(e)
+ else: assert False, ('an empty card', i, 'was packed')
+ liquid = [[dict(c, alpha=c['alpha'] * 0.4) if j == 1 else c for j, c in enumerate(tile)] for tile in t0['cards']]
+ try: export.pack(dict(t0, cards=liquid))
+ except ValueError as e: assert 'no solid terrain' in str(e), str(e)
+ else: assert False, 'a card with no solid pixel in any tile was packed'
+ walled = [[dict(c, wall=np.ones_like(c['wall'])) if j == 1 else c for j, c in enumerate(tile)] for tile in t0['cards']]
+ try: export.pack(dict(t0, cards=walled))
+ except ValueError as e: assert 'no solid terrain' in str(e), str(e)
+ else: assert False, 'a card that is all wall was packed'
finally: shutil.rmtree(d)
def test_cover_and_size_refusals_write_nothing():
- """write_bake measures the files it is handed: a card with a hole (alpha zeroed in a band of columns) fails the cover check, a card leaving the frame, cards of two widths and a colour/geometry size mismatch are refused, and nothing is written."""
+ """write_bake measures the files it is handed: a hole in one tile's card (alpha zeroed over a band of columns) fails that tile's cover check and names the tile, a card leaving the frame, a tile file without its apron, colour and geometry of two sizes and an opaque view of the wrong
+ rows are refused, and nothing is written."""
d = tempfile.mkdtemp()
try:
- b, pk = _packed(); c1 = b['cards'][1]; hole = c1['alpha'].copy(); hole[:, 200:260] = 0
- holed = [dict(c) for c in pk]; holed[1]['colour'] = export.encode_colour(c1['albedo'], hole); holed[2] = dict(pk[2], colour=export.encode_colour(b['cards'][2]['albedo'], b['cards'][2]['alpha'] * 0)); _refuses(d + '/hole', b, holed, 'a bake whose cards leave a hole was written')
- _refuses(d + '/off', b, [dict(c, top=H - 5) if i == 0 else c for i, c in enumerate(pk)], 'a card leaving the frame was written')
- narrow = [dict(c) for c in pk]; narrow[0]['colour'] = export.encode_colour(b['cards'][0]['albedo'][:, :1000], b['cards'][0]['alpha'][:, :1000]); _refuses(d + '/wide', b, narrow, 'cards of two widths were written')
- _refuses(d + '/rows', b, pk, 'view plane_h disagreeing with the opaque view was written', view=dict(b['view'], plane_h=H + 1))
+ b = _toy(); pk = export.pack(b); c = b['cards'][3][2]; hole = c['alpha'].copy(); hole[:, 100:140] = 0; bad = [list(r) for r in pk['tiles']]; bad[3][2] = dict(bad[3][2], colour=export.encode_colour(c['albedo'], hole)); _refuses(d + '/hole', b, dict(pk, tiles=bad), 'a bake whose card leaves a hole was written')
+ try: _write(d + '/hole', b, dict(pk, tiles=bad))
+ except ValueError as e: assert 'tile 3' in str(e), str(e)
+ off = [list(r) for r in pk['tiles']]; off[7][0] = dict(off[7][0], top=H - 5); _refuses(d + '/off', b, dict(pk, tiles=off), 'a card leaving the frame was written')
+ narrow = [list(r) for r in pk['tiles']]; c0 = b['cards'][2][0]; narrow[2][0] = dict(narrow[2][0], colour=export.encode_colour(c0['albedo'][:, 2:-2], c0['alpha'][:, 2:-2]), geometry=export.encode_geometry(c0['n_r'][:, 2:-2], c0['n_t'][:, 2:-2], c0['logd'][:, 2:-2], b['meta']['encoding'])); _refuses(d + '/apron', b, dict(pk, tiles=narrow), 'a tile without its apron was written')
+ try: _write(d + '/apron', b, dict(pk, tiles=narrow))
+ except ValueError as e: assert 'apron' in str(e), str(e)
+ mism = [list(r) for r in pk['tiles']]; mism[4][1] = dict(mism[4][1], geometry=export.encode_geometry(c0['n_r'][:50], c0['n_t'][:50], c0['logd'][:50], b['meta']['encoding'])); _refuses(d + '/size', b, dict(pk, tiles=mism), 'a colour and geometry of two sizes were written')
+ _refuses(d + '/rows', b, pk, 'view plane_h disagreeing with the opaque view was written', view=dict(b['view'], plane_h=H + 1)); _refuses(d + '/short', b, dict(pk, tiles=pk['tiles'][:31]), 'a bake of 31 tiles was written')
finally: shutil.rmtree(d)
-def _flat_card(top, h, w=WIN, seed=0, noise=False):
+def _flat_entry(top, h, w=export.TILE_W + 2 * export.APRON, seed=0, noise=False, distance_m=1000.0):
rng = np.random.default_rng(seed); alpha = np.ones((h, w), np.float32); rgb = rng.random((h, w, 3)).astype(np.float32) if noise else np.full((h, w, 3), 0.5, np.float32); geo = rng.random((h, w)).astype(np.float32) if noise else np.full((h, w), 0.5, np.float32)
- enc = dict(log_d_min=0.0, log_d_max=1.0); return dict(top=top, colour=export.encode_colour(rgb, alpha), geometry=export.encode_geometry(geo, geo, geo, enc), near_m=None, far_m=None, median_m=1.0, distance_m=1.0, scale=1.0)
+ enc = dict(log_d_min=0.0, log_d_max=1.0); return dict(top=top, colour=export.encode_colour(rgb, alpha), geometry=export.encode_geometry(geo, geo, geo, enc), distance_m=distance_m)
def test_card_cap_refusals():
- """A preset with 6 splits, or splits not increasing, is refused by load_preset before any march; write_bake refuses 4 full-frame 1280x600 cards (24.6 MB decoded) and writes nothing; 6 cards whose bands fit the budget are written; the card count and bytes are capped."""
+ """A preset with 6 splits, or splits not increasing, is refused by load_preset before any march; a bake of 7 cards is refused; 6 cards that fit the budgets are written; 6 full-frame cards in every tile (the lit canvases of 13 tiles are 38 MB) are refused and write nothing."""
d = tempfile.mkdtemp()
try:
for bad in ([5, 10, 20, 30, 40, 50], [6, 6], [6, 5], []):
- p = os.path.join(d, 'p.json'); json.dump(dict(presets=[dict(id='x', card_split_km=bad)]), open(p, 'w'))
+ p = os.path.join(d, 'p.json'); json.dump(dict(presets=[dict(id='x', tz='UTC', card_split_km=bad)]), open(p, 'w')) # a valid zone, so only the splits can refuse it
try: ridge.load_preset('x', p)
except ValueError: pass
else: assert False, ('a preset with splits', bad, 'was accepted')
@@ -233,79 +325,175 @@ def test_card_cap_refusals():
try: ridge.load_preset('x', os.path.join(d, 'q.json'))
except ValueError: pass
else: assert False, 'a preset without card_split_km was defaulted'
- json.dump(dict(presets=[dict(id='x', card_split_km=[1, 2, 3, 4, 5])]), open(os.path.join(d, 'r.json'), 'w')); assert ridge.load_preset('x', os.path.join(d, 'r.json'))['card_split_km'] == [1, 2, 3, 4, 5]
- place = dict(id='synthetic', name='S', lat=0.0, lon=0.0, altitude_km=0.0, eye_m=1.0); meta = dict(curvature=dict(r_earth_m=1.0, k_ref=0.1), encoding=dict(log_d_min=0.0, log_d_max=1.0), camera=dict(r_m=0.0, heading_max_deg=1.0)); view = dict(look_az_deg=0.0, plane_h=H, px_per_deg_h=1.0, px_per_deg_v=1.0, exaggeration=1.0, horizon_row=1.0, sky_row=1.0, near_row=1.0)
- full = np.ones((H, WIN))
- _refuses(d + '/four', dict(place=place, view=view, meta=meta, opaque=full), [_flat_card(0, H) for _ in range(4)], 'four full-frame cards (24.6 MB decoded) were written')
- ok = [_flat_card(0, H)] + [_flat_card(0, 150, seed=i) for i in range(1, 6)]; dest = export.write_bake(d + '/six', place, view, meta, ok, full); assert len(json.load(open(dest / 'manifest.json'))['cards']) == 6
- try: export.check_budget([1000] * 7, WIN, [10] * 7)
+ json.dump(dict(presets=[dict(id='x', tz='Europe/Vienna', card_split_km=[1, 2, 3, 4, 5])]), open(os.path.join(d, 'r.json'), 'w')); assert ridge.load_preset('x', os.path.join(d, 'r.json'))['card_split_km'] == [1, 2, 3, 4, 5]
+ for bad_tz in (None, '', 'Not/AZone'):
+ p = os.path.join(d, 'tz.json'); json.dump(dict(presets=[dict(id='x', card_split_km=[6], **({} if bad_tz is None else dict(tz=bad_tz)))]), open(p, 'w'))
+ try: ridge.load_preset('x', p)
+ except ValueError: pass
+ else: assert False, ('a preset with tz', bad_tz, 'was accepted')
+ place = dict(id='synthetic', name='S', lat=0.0, lon=0.0, altitude_km=0.0, eye_m=1.0, tz='UTC'); meta = dict(curvature=dict(r_earth_m=1.0, k_ref=0.1), encoding=dict(log_d_min=0.0, log_d_max=1.0)); view = dict(look_az_deg=0.0, plane_h=H, px_per_deg_h=1.0, px_per_deg_v=1.0, exaggeration=1.0, horizon_row=1.0, sky_row=1.0, near_row=1.0)
+ full = [np.ones((H, 204)) for _ in range(32)]; cards = lambda k: [dict(near_m=None if i == 0 else 1.0, far_m=None if i == k - 1 else 1.0) for i in range(k)]; cam = dict(r_max_m=100.0, r_max_forward_m=100.0)
+ big = dict(cards=cards(6), tiles=[[_flat_entry(0, H, seed=0)] + [_flat_entry(0, H) for _ in range(5)] for _ in range(32)], camera=cam)
+ try: export.write_bake(d + '/big', place, view, meta, big, full)
+ except ValueError as e: assert 'consecutive tiles' in str(e), str(e)
+ else: assert False, 'six full-frame cards in every tile were written'
+ assert not os.path.exists(d + '/big')
+ ok = dict(cards=cards(6), tiles=[[_flat_entry(0, H, seed=0)] + [_flat_entry(0, 100, seed=i) for i in range(1, 6)] for _ in range(32)], camera=cam); dest = export.write_bake(d + '/six', place, view, meta, ok, full); assert len(json.load(open(dest / 'manifest.json'))['cards']) == 6
+ fwd = lambda r: dict(ok, camera=dict(r_max_m=100.0, r_max_forward_m=r)); bands6 = [[H] + [100] * 5] * 32; assert export.resident_bytes(bands6, export.run_tiles(100.0, 1000.0)) <= export.RESIDENT_BYTES_MAX < export.resident_bytes(bands6, export.run_tiles(1e6, 1000.0)), 'the fixture cannot tell the gate at r_max_forward_m from the gate at r_max_m'
+ try: export.write_bake(d + '/fwd', place, view, meta, fwd(1e6), full)
+ except ValueError as e: assert 'consecutive tiles' in str(e), str(e)
+ else: assert False, 'a bake whose forward offset breaks the resident gate was written'
+ try: export.write_bake(d + '/low', place, view, meta, fwd(50.0), full)
+ except ValueError as e: assert 'below r_max_m' in str(e), str(e)
+ else: assert False, 'a bake whose forward offset is below the worst-case offset was written'
+ assert not os.path.exists(d + '/fwd') and not os.path.exists(d + '/low')
+ try: export.check_budget(7, [1000] * 32, [[10] * 7] * 32, 100.0, 1000.0)
except ValueError as e: assert 'above 6' in str(e)
else: assert False, '7 cards were accepted'
- try: export.check_budget([750_001, 750_000], WIN, [10, 10])
- except ValueError as e: assert 'bytes' in str(e)
- else: assert False, 'cards above TOTAL_BYTES_MAX were accepted'
- export.check_budget([750_000, 750_000], WIN, [10, 10])
- try: export.check_budget([1, 1], export.PLANE_W_MAX + 1, [10, 10])
- except ValueError: pass
- else: assert False, 'a card wider than the cap was accepted'
finally: shutil.rmtree(d)
-def test_cards_are_cropped_to_their_band():
- """Each card is exactly the rows where its 8-bit alpha is non-zero; the manifest top and h place it back at the same rows (colour and geometry decode to that band, alpha in the file equals the canvas row for row)."""
+def test_budgets():
+ """A tile over 235 kB, a place over 7.5 MB and a resident run over 20 MB each refuse and one byte (one band row) under passes; the resident run wraps the ring: the last tiles and the first count as consecutive."""
+ none = [[] for _ in range(export.TILES)]; call = lambda tb, bands, r=100.0, rmin=1000.0: export.check_budget(3, tb, bands, r, rmin)
+ def refused(*a, **k):
+ try: call(*a, **k)
+ except ValueError: return True
+ return False
+ assert not refused([235_000] + [0] * 31, none) and refused([235_001] + [0] * 31, none), 'the tile cap'
+ assert not refused([234_375] * 32, none) and refused([234_375] * 31 + [234_376], none), 'the place cap'
+ rows = 20_000_000 // (4 * export.LIT_W); one = lambda h: [[h]] + [[] for _ in range(31)]
+ assert not refused([0] * 32, one(rows)) and refused([0] * 32, one(rows + 1)), 'the resident cap'
+ n = export.run_tiles(100.0, 1000.0); assert 5 < n < 32; split = [[] for _ in range(32)]; split[31] = [rows // 2]; split[0] = [rows - rows // 2 + 1]
+ assert refused([0] * 32, split), 'the resident run does not wrap the ring (tile 31 and tile 0 are consecutive)'; split[0] = [rows - rows // 2]; assert not refused([0] * 32, split)
+ far = [[] for _ in range(32)]; far[0] = [rows // 2]; far[n + 3] = [rows - rows // 2 + 1]; assert not refused([0] * 32, far), 'a run is only N tiles long'; far[n - 1] = far[n + 3]; far[n + 3] = []; assert refused([0] * 32, far)
+ assert export.run_tiles(0.0, 1000.0) == math.ceil(export.HFOV_MAX_DEG / 11.25) + 5 and export.run_tiles(250.0, 20000.0) > export.run_tiles(25.0, 20000.0) and export.run_tiles(1e9, 1.0) == 32, 'N = ceil(arc_max / 11.25) + 1 + 4'
+ rows_t = [[10, 20] if t in (30, 31, 0, 1) else [] for t in range(32)]; assert export.resident_bytes(rows_t, 4) == 4 * export.LIT_W * 120 and export.resident_bytes(rows_t, 3) == 4 * export.LIT_W * 90 and export.resident_bytes(rows_t, 40) == 4 * export.LIT_W * 120
+def _fit(d, r, phis=None): return export.fit_px(d, r, ridge.HPX_DEG, phis)
+def _brute_fit(d, r, phis, ppd, n=20001):
+ """The worst error of the best line, by brute force: the least-squares line over n uniform samples (the integral to within 1e-4 of itself), the error on the same n."""
+ half = math.radians(export.HFOV_MAX_DEG) / 2; b = np.linspace(-half, half, n)[None, :]; p = np.linspace(0, 2 * math.pi, phis, endpoint=False)[:, None]; A = np.arctan2(d * np.sin(b) - r * np.sin(p), d * np.cos(b) - r * np.cos(p))
+ bc = b - b.mean(); s = (A * bc).sum(-1, keepdims=True) / (bc * bc).sum(); return math.degrees(float(np.abs(A - (A.mean(-1, keepdims=True) + s * bc)).max())) * ppd
+def test_fit_px_is_the_continuous_error():
+ """fit_px is the worst error of the best line over the whole viewport, not of a few samples of it: it equals a brute-force measure (20001 samples, line and error) within 0.1 card px at the offsets the bound is set at (an offset a few samples undercount by more than that), over the whole circle and at phi = 0."""
+ ppd = ridge.HPX_DEG; seen = 0
+ for d, r, phis in ((410.0, 205.0, 1), (410.0, 98.0, export.PHI_STEPS), (1500.0, 600.0, 1), (1500.0, 300.0, export.PHI_STEPS), (60.0, 30.0, export.PHI_STEPS), (20000.0, 9000.0, 1)):
+ got, want = _fit(d, r, phis), _brute_fit(d, r, phis, ppd); assert abs(got - want) < 0.1, ('fit_px is not the continuous error', d, r, phis, got, want); seen += want > 5
+ assert seen >= 4, 'the cases are too tame to tell a coarse measure from the continuous one'
+def test_r_max():
+ """On a card at 1.5 km: r_max_m falls as FIT_PX_MAX falls and is at most half the distance; it is the largest offset within the bound (the fit error at r_max is within it, a little more is not); a forward-only sweep of phi finds a larger r_max than the whole circle (the error is in the phi
+ that is not forward); the binding card tile is the nearest one (each tile's line is fitted at its own distance_m); the resident gate binds when its tiles are heavy; a place whose r_max_m is below 25 refuses and names the card and tile."""
+ ppd = ridge.HPX_DEG; dist = [[1500.0] for _ in range(32)]; bands = [[100] for _ in range(32)]; saved = (export.FIT_PX_MAX, export.PHI_STEPS)
+ try:
+ r = export.solve_r_max(dist, bands, ppd); assert 25 < r <= 750 and _fit(1500.0, r) <= export.FIT_PX_MAX + 1e-9 and _fit(1500.0, r + 0.5) > export.FIT_PX_MAX, ('r_max is not the largest offset within the bound', r, _fit(1500.0, r), _fit(1500.0, r + 0.5))
+ export.FIT_PX_MAX = 12.0; r12 = export.solve_r_max(dist, bands, ppd); export.FIT_PX_MAX = 60.0; r60 = export.solve_r_max(dist, bands, ppd); export.FIT_PX_MAX = saved[0]; assert r12 < r < r60, (r12, r, r60)
+ export.FIT_PX_MAX = 1e9; assert export.solve_r_max(dist, bands, ppd) == 750.0, 'r_max is not capped at half the nearest distance'; export.FIT_PX_MAX = saved[0]
+ export.PHI_STEPS = 1; rf = export.solve_r_max(dist, bands, ppd); export.PHI_STEPS = saved[1]; assert rf > r + 5, ('a forward-only sweep finds the same r_max', rf, r)
+ rp = export.solve_r_max(dist, bands, ppd, phis=1); assert rp == rf and 25 < rp <= 750 and _fit(1500.0, rp, 1) <= export.FIT_PX_MAX + 1e-9 and _fit(1500.0, rp + 0.5, 1) > export.FIT_PX_MAX, ('the phi = 0 bound is not the largest offset within the bound at phi = 0', rp, rf)
+ assert _fit(1500.0, rp) > export.FIT_PX_MAX, 'the forward offset fits at some other phi, so the two numbers do not differ'
+ mixed = [[1500.0 if t == 3 else 9000.0] for t in range(32)]; assert export.solve_r_max(mixed, bands, ppd) == r, 'the binding tile is not the nearest one'
+ dist2 = [[20000.0] for _ in range(32)]; free = export.solve_r_max(dist2, bands, ppd); heavy = [[1700000 // (4 * export.LIT_W)] for _ in range(32)]; held = export.solve_r_max(dist2, heavy, ppd)
+ assert held < free - 100 and export.resident_bytes(heavy, export.run_tiles(held, 20000.0)) <= export.RESIDENT_BYTES_MAX < export.resident_bytes(heavy, export.run_tiles(held + 1.0, 20000.0)), ('the resident gate does not bind r_max', held, free)
+ held_f = export.solve_r_max(dist2, heavy, ppd, phis=1); assert held_f >= held and export.resident_bytes(heavy, export.run_tiles(held_f, 20000.0)) <= export.RESIDENT_BYTES_MAX < export.resident_bytes(heavy, export.run_tiles(held_f + 1.0, 20000.0)), ('the resident gate does not bind the forward offset', held_f, held)
+ two = [[5000.0, 40.0 if t == 7 else 5000.0] for t in range(32)]
+ try: export.solve_r_max(two, [[100, 100] for _ in range(32)], ppd)
+ except ValueError as e: assert 'below 25' in str(e) and 'card 1' in str(e) and 'tile 7' in str(e), str(e)
+ else: assert False, 'a bake whose r_max_m is below 25 was accepted'
+ close = [[30.0] for _ in range(32)]
+ try: export.solve_r_max(close, bands, ppd)
+ except ValueError as e: assert 'below 25' in str(e) and 'card 0' in str(e), str(e)
+ else: assert False, 'a nearest card at 30 m was accepted'
+ finally: export.FIT_PX_MAX, export.PHI_STEPS = saved
+def test_pack_distance_and_r_max_in_the_bake():
+ """pack: a card tile's distance_m is exp(median ln d) over the interior solid pixels that are not wall (not the wall rows, not the apron columns); the manifest camera is the r_max_m of those distances and no per-card scale or median is written."""
+ b = _toy(); cs = [[dict(c) for c in tile] for tile in b['cards']]; c = dict(cs[10][1]); n = c['alpha'].shape[0]; wall = np.zeros_like(c['wall']); wall[:n * 3 // 4] = True; ld = np.where(wall, c['logd'] + 3.0, c['logd']).copy(); ld[:, :2] += 2.0; ld[:, -2:] += 2.0; cs[10][1] = dict(c, wall=wall, logd=ld)
+ pk = export.pack(dict(b, cards=cs)); inner = (slice(None), slice(2, -2)); want = float(np.exp(np.median(ld[inner][~wall[inner]]))); with_wall = float(np.exp(np.median(ld[inner]))); assert abs(with_wall - want) > 0.05 * want, 'the fixture cannot tell wall rows from ground'
+ assert abs(pk['tiles'][10][1]['distance_m'] - want) < 1e-9 * want, ('the distance counted wall rows or the apron', pk['tiles'][10][1]['distance_m'], want); assert set(pk['tiles'][10][1]) == {'top', 'colour', 'geometry', 'distance_m'} and set(pk['cards'][0]) == {'near_m', 'far_m'}
+ base = export.pack(b); assert base['camera']['r_max_m'] >= 25 and base['camera']['r_max_forward_m'] >= base['camera']['r_max_m'] and abs(base['report']['nearest_m'] - min(e[0]['distance_m'] for e in base['tiles'])) < 1e-9 and len(base['report']['fit_px']) == 3 and max(base['report']['fit_px']) <= export.FIT_PX_MAX + 1e-6
+ near = export.pack(_toy(dists=(1500.0, 15000.0, 50000.0))); assert near['camera']['r_max_forward_m'] > near['camera']['r_max_m'] + 5, ('the forward offset was searched over the whole circle', near['camera'])
+ assert abs(base['cards'][0]['far_m'] - 1500.0) < 1e-6 and base['cards'][0]['near_m'] is None and base['cards'][1]['near_m'] == base['cards'][0]['far_m']
+def test_the_sheet_draws_the_ring():
+ """The contact sheet is the ring at 1/4 width (1600 px) with a mark on each of the 32 tile boundaries, in the composite, every card's strip and the depth image, stacked: composite, K cards, depth."""
+ b = _ring('wide3', WIDE3, [20, 55]); png = export.sheet(b); img = export.imagecodecs.png_decode(png); k = 3; nb = b['cov'].shape[0]; assert img.shape == ((1 + k) * H + 2 * nb, W // 4, 3), img.shape
+ mark = np.arange(32) * 200 // 4; sky = np.array(export.SHEET_SKY); reddish = lambda px: (px[..., 0] > px[..., 2] + 40); assert reddish(img[2, mark].astype(int)).all() and not reddish(img[2, mark + 7].astype(int)).any(), 'the tile boundaries are not drawn on the composite'
+ assert reddish(img[(1 + k) * H + 3, mark].astype(int)).all(), 'the tile boundaries are not drawn on the depth image'; assert abs(img[2, 1].astype(int) - np.rint(np.array(export.SHEET_SKY) * 255)).max() <= 2, 'the sky is not the flat sky'
+
+# ---------------------------------------------------------------------------------------- the real thing: Vienna
+_VIENNA = {}
+def _vienna_bake():
+ if 'b' not in _VIENNA:
+ saved = ridge.P
+ try: b = export.bake_place('vienna'); _VIENNA.update(b=b, pxv=ridge.PXDEG_V, P=dict(ridge.P), rowang=ridge.rowang.copy(), skyline=None)
+ finally: ridge.P = saved
+ return _VIENNA['b']
+def _vienna_ring(splits, tiles):
+ """Vienna's whole-ring march and seams for the given splits, cards on only the given tiles: (d, seams, {t: cards}, {t: opaque})."""
+ saved = ridge.P
+ try:
+ p = ridge.configure(dict(ridge.load_preset('vienna'), card_split_km=splits)); d, _, Hh, _ = ridge.stage0(False); a, h = ridge.prefilter(d, Hh, p['prefilter_m']); ridge.set_view(a.max(0)); nrm = ridge.normals(d, h); sm = ridge.seams(ridge.coverage(d, a), [k * 1000.0 for k in splits], d); op = ridge.opaque(a)
+ cols = lambda x, t: ridge.ring_cols(x, t * export.TILE_W - export.APRON, export.TILE_W + 2 * export.APRON)
+ return d, sm, {t: ridge.cards(d, cols(a, t), cols(h, t), cols(sm, t), tuple(cols(x, t) for x in nrm)) for t in tiles}, {t: cols(op, t) for t in tiles}
+ finally: ridge.P = saved
+def test_vienna_k1_k2_k3():
+ """Vienna with card_split_km [6], [6, 40] and [6, 20, 40]: 2, 3 and 4 cards, seams ordered in every column of the ring, each composite of a tile (the rest azimuth's, the north's and the last one) equals the opaque view within 0.02; the cross-fade column count is printed."""
+ for sp in ([6], [6, 40], [6, 20, 40]):
+ d, sm, cs, op = _vienna_ring(sp, (0, 19, 31)); assert sm.shape == (len(sp), W)
+ if len(sp) > 1: assert (np.diff(np.log(sm), axis=0) >= 0.4 - 1e-9).all(), 'seams out of order'
+ for t, tile in cs.items():
+ assert len(tile) == len(sp) + 1; comp = 1 - np.prod([1 - _tile_canvas(c) for c in tile], axis=0); assert np.abs(comp - op[t]).max() < 0.02, (sp, t, np.abs(comp - op[t]).max())
+ xf = int(np.any([((0.02 < _tile_canvas(c)) & (_tile_canvas(c) < 0.98)).sum(0) > 3 for c in cs[19]], axis=0).sum())
+ print(f' K={len(sp)} splits {sp}: {len(cs[19])} cards, tile 19 bands {[(c["top"], c["alpha"].shape[0]) for c in cs[19]]}, seam medians km {[round(float(np.median(s)) / 1000, 1) for s in sm]}, cross-fade columns {xf} of {export.TILE_W + 4} in tile 19')
+def test_bake_place_manifest_fields_on_vienna():
+ """bake_place on the real Vienna preset: 32 tiles of three cards, the place carries the ground (km) and the eye, horizon_row is the row where the elevation angle is 0, px_per_deg_h is the ring's, look_az_deg is the rest azimuth; the shared apron of neighbouring tiles is the same pixels
+ (the tile cut at the real preset), and write_bake of its packed tiles validates with index default 'vienna', no temp dir left, r_max_m and the worst fit error per card printed."""
+ b = _vienna_bake(); P = _VIENNA['P']; rowang = _VIENNA['rowang']; pxv = _VIENNA['pxv']; pl, view = b['place'], b['view']; assert len(b['cards']) == 32 and all(len(t) == 3 for t in b['cards']) and len(b['opaque']) == 32 and b['seams'].shape == (2, W)
+ assert abs(pl['altitude_km'] * 1000 - P['ground_m']) < 1e-6 and abs(pl['eye_m'] - P['eye_m']) < 1e-9 and pl['id'] == 'vienna' and view['look_az_deg'] == P['az_center'] == 214.0
+ assert 0 < view['sky_row'] < view['horizon_row'] < view['near_row'] < H and abs(rowang[int(view['horizon_row'])]) <= 1.0 / pxv, (view, rowang[int(view['horizon_row'])]); assert view['px_per_deg_h'] == ridge.HPX_DEG and abs(view['exaggeration'] - pxv / ridge.HPX_DEG) < 1e-9
+ T_, A_ = export.TILE_W, export.APRON
+ for t in (0, 19, 31):
+ nxt = b['cards'][(t + 1) % 32]
+ for i, c in enumerate(b['cards'][t]):
+ assert (_tile_canvas(c)[:, T_ + A_:T_ + 2 * A_] == _tile_canvas(nxt[i])[:, A_:2 * A_]).all(), ('the apron is not the neighbour tile', t, i); seen = _tile_canvas(c)[:, T_ + A_:T_ + 2 * A_] > 0
+ assert (_tile_canvas(c, 'logd')[:, T_ + A_:T_ + 2 * A_][seen] == _tile_canvas(nxt[i], 'logd')[:, A_:2 * A_][seen]).all(), ('the apron is not the neighbour tile', t, i, 'logd')
d = tempfile.mkdtemp()
try:
- b, pk = _packed(); dest = export.write_bake(d, b['place'], b['view'], b['meta'], pk, b['opaque']); m = json.load(open(dest / 'manifest.json'))
- for c, rec in zip(b['cards'], m['cards']):
- canvas = _canvas(c); rows = np.flatnonzero(np.rint(canvas * 255).max(1) > 0); assert rec['top'] == rows[0] and rec['h'] == rows[-1] - rows[0] + 1 == c['alpha'].shape[0], (rec, rows[0], rows[-1])
- col = export.decode((dest / rec['colour']['file']).read_bytes()); assert col.shape[:2] == (rec['h'], WIN) and np.abs(col[..., 3].astype(int) - np.rint(c['alpha'] * 255)).max() == 0, 'the written alpha is not the card alpha'
- assert export.decode((dest / rec['geometry']['file']).read_bytes()).shape[:2] == (rec['h'], WIN)
+ pk = export.pack(b); rp = pk['report']; print(' vienna r_max_m', pk['camera']['r_max_m'], 'r_max_forward_m', pk['camera']['r_max_forward_m'], 'nearest card m', round(rp['nearest_m']), 'resident run', rp['run_tiles'], 'tiles', rp['resident_bytes'], 'bytes; worst fit error per card (card px)', [round(x, 1) for x in rp['fit_px']], 'sky/low deg', round(b['v']['sky_deg'], 2), round(b['v']['low_deg'], 2), 'exaggeration', round(view['exaggeration'], 2))
+ dest = _write(d, b, pk); m = json.load(open(dest / 'manifest.json')); export.validate_manifest(m); assert m['camera']['r_max_m'] >= export.R_MAX_FLOOR_M and m['camera']['r_max_forward_m'] >= m['camera']['r_max_m']
+ assert json.load(open(d + '/index.json'))['default'] == 'vienna' and sorted(os.listdir(d)) == sorted(['index.json', dest.name]), os.listdir(d); print(' vienna manifest bytes', m['bytes'], 'largest tile', max(sum(e[k]['bytes'] for e in row if e for k in ('colour', 'geometry')) for row in m['tiles']))
finally: shutil.rmtree(d)
-def test_an_empty_card_is_refused_before_writing_naming_the_split():
- """A card with no rows (its splits leave it no terrain) stops pack with a message that names the splits, instead of dying inside the codec."""
- b = _bake(THREE, [6, 40]); b['cards'][1] = dict(top=0, alpha=np.zeros((0, WIN), np.float32), albedo=np.zeros((0, WIN, 3), np.float32), n_r=np.zeros((0, WIN), np.float32), n_t=np.zeros((0, WIN), np.float32), logd=np.zeros((0, WIN), np.float32), wall=np.zeros((0, WIN), bool))
- try: export.pack(b)
- except ValueError as e: assert 'card 1 is empty' in str(e) and '6 km' in str(e) and '40 km' in str(e), str(e)
- else: assert False, 'an empty card was packed'
- b['cards'][2] = b['cards'][1]
- try: export.pack(dict(b, cards=[b['cards'][0], _bake(THREE, [6, 40])['cards'][1], b['cards'][1]]))
- except ValueError as e: assert 'card 2 is empty' in str(e) and '40 km' in str(e), str(e)
- else: assert False, 'an empty last card was packed'
-
# ---------------------------------------------------------------------------------------- the written files are the cards
def test_written_cards_decode_to_the_cards_in_memory():
- """Vienna's three cards, written and decoded again: alpha exactly, albedo within the lossy codec (and straight, not premultiplied, at partial alpha), the normal channels in their order (R along the ray, G across it), and the log-distance over the encoding range, within quantisation."""
- saved = ridge.P
- try: b = export.bake_place('vienna')
- finally: ridge.P = saved
- d = tempfile.mkdtemp()
+ """Vienna's cards in three tiles (north, the rest azimuth's, the wrap), written and decoded again: alpha exactly, albedo within the lossy codec (and straight, not premultiplied, at partial alpha), the normal channels in their order (R along the ray, G across it), and the log-distance over the encoding
+ range, within quantisation."""
+ b = _vienna_bake(); d = tempfile.mkdtemp()
try:
- dest = export.write_bake(d, b['place'], b['view'], b['meta'], export.pack(b), b['opaque']); m = json.load(open(dest / 'manifest.json')); enc = m['encoding']; span = enc['log_d_max'] - enc['log_d_min']; partial_seen = 0
- for c, rec in zip(b['cards'], m['cards']):
- col = export.decode((dest / rec['colour']['file']).read_bytes()); geo = export.decode((dest / rec['geometry']['file']).read_bytes()); al = c['alpha']; wall = c['wall']; solid = (al > 0) & ~wall; part = (al > 0.05) & (al < 0.95) & ~wall; partial_seen += int(part.sum())
- assert (col[..., 3] == np.rint(al * 255)).all(), 'alpha is not exact'; e = np.abs(col[..., :3] / 255.0 - c['albedo']).max(-1)
- assert e[solid].mean() < 0.02 and np.percentile(e[solid], 99) < 0.08, ('albedo is off', e[solid].mean(), np.percentile(e[solid], 99)); assert part.sum() == 0 or e[part].mean() < 0.1, ('albedo at partial alpha is off: premultiplied?', e[part].mean())
- assert (geo[..., 3] == 255).all(); q = 1.0 / 255 + 1e-6; assert (((geo[..., 0] == 255) & (geo[..., 1] == 255)) == wall).all(), 'the wall code is not R = G = 255 on exactly the wall pixels'
- assert np.abs(geo[..., 0] / 255.0 * 2 - 1 - c['n_r'])[solid].max() < 2 * q and np.abs(geo[..., 1] / 255.0 * 2 - 1 - c['n_t'])[solid].max() < 2 * q, 'a normal channel is off or swapped'
- assert np.abs(enc['log_d_min'] + geo[..., 2] / 255.0 * span - c['logd'])[solid].max() < span * q, 'the log-distance is off or not over the encoding range'
- assert np.abs(c['n_r'][solid]).mean() > 0.05 and np.abs(c['n_t'][solid]).mean() > 0.01 and np.abs(c['n_r'][solid].mean() - c['n_t'][solid].mean()) > 0.0, 'the fixture does not tell the channels apart'
- assert col[..., :3][solid].mean() > 20, 'albedo is zeroed'
+ dest = _write(d, b, export.pack(b)); m = json.load(open(dest / 'manifest.json')); enc = m['encoding']; span = enc['log_d_max'] - enc['log_d_min']; partial_seen = 0
+ for t in (0, 19, 31):
+ for c, rec in zip(b['cards'][t], m['tiles'][t]):
+ col = export.decode((dest / rec['colour']['file']).read_bytes()); geo = export.decode((dest / rec['geometry']['file']).read_bytes()); al = c['alpha']; wall = c['wall']; solid = (al > 0) & ~wall; part = (al > 0.05) & (al < 0.95) & ~wall; partial_seen += int(part.sum())
+ assert (col[..., 3] == np.rint(al * 255)).all(), 'alpha is not exact'; e = np.abs(col[..., :3] / 255.0 - c['albedo']).max(-1)
+ assert e[solid].mean() < 0.021 and np.percentile(e[solid], 99) < 0.081, ('albedo is off', e[solid].mean(), np.percentile(e[solid], 99)); assert part.sum() == 0 or e[part].mean() < 0.1, ('albedo at partial alpha is off: premultiplied?', e[part].mean())
+ assert (geo[..., 3] == 255).all(); q = 1.0 / 255 + 1e-6; assert (((geo[..., 0] == 255) & (geo[..., 1] == 255)) == wall).all(), 'the wall code is not R = G = 255 on exactly the wall pixels'
+ assert np.abs(geo[..., 0] / 255.0 * 2 - 1 - c['n_r'])[solid].max() < 2 * q and np.abs(geo[..., 1] / 255.0 * 2 - 1 - c['n_t'])[solid].max() < 2 * q, 'a normal channel is off or swapped'
+ assert np.abs(enc['log_d_min'] + geo[..., 2] / 255.0 * span - c['logd'])[solid].max() < span * q, 'the log-distance is off or not over the encoding range'
+ assert np.abs(c['n_r'][solid]).mean() > 0.05 and np.abs(c['n_t'][solid]).mean() > 0.01 and np.abs(c['n_r'][solid].mean() - c['n_t'][solid].mean()) > 0.0, 'the fixture does not tell the channels apart'
+ assert col[..., :3][solid].mean() > 20, 'albedo is zeroed'
assert partial_seen > 0, 'the fixture has no partial alpha'
finally: shutil.rmtree(d)
-# ---------------------------------------------------------------------------------------- wall rows and the camera
+# ---------------------------------------------------------------------------------------- wall rows
def _first_sample_angle(b, i):
"""Per column, the angle of the first sample card i (> 0) reads: the first sample at or beyond its near seam, less the cross-fade half-width."""
- k0 = np.array([np.searchsorted(D, b['seams'][i - 1][x] * math.exp(-ridge.XF)) for x in range(WIN)]); return k0, b['a'][k0, np.arange(WIN)]
+ k0 = np.array([np.searchsorted(D, b['seams'][i - 1][x] * math.exp(-ridge.XF)) for x in range(NW)]); return k0, b['a'][k0, np.arange(NW)]
def test_wall_rows_flagged():
"""Card i > 0 flags as wall exactly the rows below the angle of its first sample (the extruded face of the ridge it starts at), card 0 none; the wall carries R = G = 255 in the geometry file and no other pixel has r2 + t2 above 1.02; wall pixels keep that sample's
distance and their albedo is the ground material of the sample's height with the face up (so a steep face is not rock), constant down the column."""
steep = 0
- for make in (lambda: _bake(WALLED, [20]), lambda: _bake(WIDE3, [20, 55]), lambda: _bake(_receding, [6]), lambda: _bake(_ramp, [20])):
+ for make in (lambda: _bake(WALLED, [20]), lambda: _bake(WIDE3, [20, 55]), lambda: _bake(_receding, [6]), lambda: _bake(_ramp, [20], fixed_m=[20000.0])): # the ramp's seam is fixed: the wall must stand on the slope, below the height where every material is rock or snow
b = make(); assert not b['cards'][0]['wall'].any(), 'card 0 has a wall'; lo = ridge.rowang - 0.5 / ridge.PXDEG_V; seen = 0
for i, c in enumerate(b['cards']):
if i == 0: continue
k0, a0 = _first_sample_angle(b, i); want = (lo[:, None] < a0[None, :])[c['top']:c['top'] + c['alpha'].shape[0]]; assert (c['wall'] == want).all(), ('wall rows are not the rows below the first sample', i, int((c['wall'] != want).sum())); seen += int(want.sum())
- geo = export.decode(export.encode_geometry(c['n_r'], c['n_t'], c['logd'], b['meta']['encoding'], c['wall'])); r, t = geo[..., 0] / 255.0 * 2 - 1, geo[..., 1] / 255.0 * 2 - 1; code = (geo[..., 0] == 255) & (geo[..., 1] == 255)
+ geo = export.decode(export.encode_geometry(c['n_r'], c['n_t'], c['logd'], dict(log_d_min=math.log(D[0]), log_d_max=math.log(D[-1])), c['wall'])); r, t = geo[..., 0] / 255.0 * 2 - 1, geo[..., 1] / 255.0 * 2 - 1; code = (geo[..., 0] == 255) & (geo[..., 1] == 255)
assert (code == c['wall']).all() and (r[~code] ** 2 + t[~code] ** 2 <= 1.02).all(), 'the wall code is not on exactly the wall pixels, or a real normal reaches it'
for x in np.flatnonzero(c['wall'].any(0)):
rows = np.flatnonzero(c['wall'][:, x]); ld = c['logd'][rows, x]; assert np.ptp(ld) < 1e-5 and abs(math.exp(ld[0]) - D[k0[x]]) < 1e-3 * D[k0[x]] + 60, ('a wall keeps its sample distance', x)
@@ -321,36 +509,6 @@ def test_the_sheet_lights_a_wall_with_the_face_up():
n = 4; c = dict(albedo=np.ones((n, n, 3), np.float32), alpha=np.ones((n, n), np.float32), n_r=np.full((n, n), 0.9, np.float32), n_t=np.zeros((n, n), np.float32), wall=np.zeros((n, n), bool)); c['wall'][:, :2] = True
rgb, _ = export.lit(c); L = np.array(export.SHEET_LIGHT) / np.linalg.norm(export.SHEET_LIGHT); up = 0.35 + 0.65 * L[2]; tilted = 0.35 + 0.65 * np.clip(0.9 * L[0] + np.sqrt(1 - 0.81) * L[2], 0, 1)
assert np.allclose(rgb[:, :2], up) and np.allclose(rgb[:, 2:], tilted) and abs(up - tilted) > 0.05, (rgb[0, 0], rgb[0, 3])
-def test_camera_contract():
- """scale_i = d_i / (d_i - r) for r = +200 and r = -100 (a function of r, not a constant or a clamp); a card's distance excludes its wall rows; |r| at half the nearest distance is refused; an r that lifts the nearest card off the frame bottom (backward) is
- refused and writes nothing; a card shrunk below what a 16:9 viewport needs is refused; one card works."""
- ds = [1000.0, 12000.0, 40000.0]
- for r in (200.0, -100.0, 0.0): assert export.card_scales(ds, r) == [d / (d - r) for d in ds], r
- assert export.card_scales(ds, 200.0)[0] > 1.2 and export.card_scales(ds, -100.0)[0] < 0.92 and export.card_scales(ds, 0.0) == [1.0, 1.0, 1.0]
- for bad in (500.0, -500.0, 800.0):
- try: export.card_scales(ds, bad)
- except ValueError: pass
- else: assert False, ('an offset of', bad, 'was accepted')
- export.card_scales(ds, 499.0); export.card_scales(ds, -499.0)
- b = _bake(WIDE3, [20, 55]); c1 = b['cards'][1]; solid = c1['alpha'] >= 0.5; c1['wall'] = np.zeros_like(c1['wall']); c1['wall'][:c1['alpha'].shape[0] * 3 // 4] = True; c1['logd'] = np.where(c1['wall'], c1['logd'] + 3.0, c1['logd']) # three quarters of the card is wall, far off the rest
- want = float(np.exp(np.median(c1['logd'][solid & ~c1['wall']]))); with_wall = float(np.exp(np.median(c1['logd'][solid]))); assert abs(with_wall - want) > 0.05 * want, ('the fixture cannot tell the median with walls from the one without', with_wall, want)
- pk = export.pack(b); assert abs(pk[1]['distance_m'] - want) < 1e-6 * want and pk[1]['median_m'] == pk[1]['distance_m'], ('the distance counted wall rows', pk[1]['distance_m'], want)
- assert [p['scale'] for p in pk] == [p['distance_m'] / (p['distance_m'] - export.CAMERA_R_M) for p in pk]
- d = tempfile.mkdtemp()
- try:
- back = dict(b['meta'], camera=dict(r_m=-100.0, heading_max_deg=23.0)); pkb = export.pack(dict(b, meta=back)); assert all(p['scale'] < 1 for p in pkb)
- _refuses(d + '/back', b, pkb, 'a backward camera that lifts the nearest card off the frame bottom was written', meta=back)
- try: export.pack(dict(b, meta=dict(b['meta'], camera=dict(r_m=0.5 * pk[0]['distance_m'], heading_max_deg=23.0))))
- except ValueError: pass
- else: assert False, 'an offset of half the nearest distance was packed'
- view = b['view']; tops = [c['top'] for c in b['cards']]; bands = [c['alpha'].shape[0] for c in b['cards']]; export.check_camera([1.0, 1.0, 1.0], tops, bands, view)
- try: export.check_camera([1.0, 1.0, 0.8], tops, bands, view)
- except ValueError as e: assert '16:9' in str(e), str(e)
- else: assert False, 'a card too small for a 16:9 viewport at rest was accepted'
- one, pk1 = _packed(_bake(WALLED, [])); assert len(pk1) == 1 and pk1[0]['scale'] == pk1[0]['distance_m'] / (pk1[0]['distance_m'] - export.CAMERA_R_M); dest = export.write_bake(d + '/one', one['place'], one['view'], one['meta'], pk1, one['opaque'])
- assert len(json.load(open(dest / 'manifest.json'))['cards']) == 1
- finally: shutil.rmtree(d)
-
# ---------------------------------------------------------------------------------------- rules that no other test touched
def test_seams_keep_their_separation():
"""Two authored targets closer than SEAM_SEP (6 and 7 km, 0.15 nat): the seams still sit at least 0.4 nat apart in every column."""
@@ -363,15 +521,15 @@ def test_elev_is_the_curved_refracted_angle():
def test_coverage_counts_every_visible_row_including_the_foreground():
"""Per column the coverage sums to the visible rows of the opaque view: (min(skyline, top) - bottom) x px per degree, the rows below the first sample included once, not twice (a ground just under the eye shows below the first sample)."""
for i, hf in enumerate((terrain(block(0, 359.99, 0, 20000, 91), block(0, 359.99, 20000, 21500, 600)), THREE)):
- A, Hh = rays(hf); ridge.P.update(win0=0, eye_m=EYE); ridge.set_view(A.max(0)); aw = ridge.win(A); cov = ridge.coverage(D, aw); want = np.clip(np.minimum(aw.max(0), ridge.TOP_DEG) - ridge.BOTTOM_DEG, 0, None) * ridge.PXDEG_V
- assert np.abs(cov.sum(0) - want).max() < 1e-6, np.abs(cov.sum(0) - want).max(); assert cov.shape == (ridge.COV_BINS, WIN)
+ A, Hh = rays(hf); ridge.P.update(eye_m=EYE); ridge.set_view(A.max(0)); aw = _w(A); cov = ridge.coverage(D, aw); want = np.clip(np.minimum(aw.max(0), ridge.TOP_DEG) - ridge.BOTTOM_DEG, 0, None) * ridge.PXDEG_V
+ assert np.abs(cov.sum(0) - want).max() < 1e-6, np.abs(cov.sum(0) - want).max(); assert cov.shape == (ridge.COV_BINS, NW)
if i == 0: assert (cov[0] > 100).all(), ('no foreground rows in the first bin', float(cov[0].min()))
def test_cards_interpolate_between_samples_and_renormalise():
"""On a ramp face every card pixel sits between two samples: its log-distance lies strictly between theirs (not on the nearer sample), and its normal is the normalised blend of theirs by that same fraction (the samples carry alternating normals, so a blend
that is not renormalised, or a hit that is not interpolated, differs)."""
- A, Hh = rays(terrain(lambda dk, az: np.where(dk >= 4000, GROUND + 0.5 * (dk - 4000), 0.0) + 0 * az)); ridge.P.update(win0=0, eye_m=EYE); ridge.set_view(A.max(0)); aw, hw = ridge.win(A), ridge.win(Hh); k = np.arange(len(D))[:, None]
+ A, Hh = rays(terrain(lambda dk, az: np.where(dk >= 4000, GROUND + 0.5 * (dk - 4000), 0.0) + 0 * az)); ridge.P.update(eye_m=EYE); ridge.set_view(A.max(0)); aw, hw = _w(A), _w(Hh); k = np.arange(len(D))[:, None]
nr = np.broadcast_to(np.where(k % 2 == 0, -0.8, 0.8), aw.shape).astype(float); nt = np.broadcast_to(np.where(k % 3 == 0, 0.3, -0.3), aw.shape).astype(float); nu = np.sqrt(1 - nr ** 2 - nt ** 2) * 0 + 0.5
- c = ridge.cards(D, aw, hw, np.zeros((0, WIN)), nrm=(nr, nt, nu))[0]; x = 300; sel = np.flatnonzero(c['alpha'][:, x] > 0.999); ld = c['logd'][sel, x].astype(np.float64); L = np.log(D); kk = np.searchsorted(L, ld, 'left'); kp = kk - 1; ok = kp >= 0
+ c = ridge.cards(D, aw, hw, np.zeros((0, NW)), nrm=(nr, nt, nu))[0]; x = 300; sel = np.flatnonzero(c['alpha'][:, x] > 0.999); ld = c['logd'][sel, x].astype(np.float64); L = np.log(D); kk = np.searchsorted(L, ld, 'left'); kp = kk - 1; ok = kp >= 0
t = (ld - L[np.maximum(kp, 0)]) / (L[kk] - L[np.maximum(kp, 0)]); inner = ok & (t > 0.02) & (t < 0.98); assert inner.sum() > 0.3 * len(sel), ('hits sit on samples, not between them', int(inner.sum()), len(sel))
mix = lambda arr: arr[np.maximum(kp, 0), x] + t * (arr[kk, x] - arr[np.maximum(kp, 0), x]); m = np.sqrt(mix(nr) ** 2 + mix(nt) ** 2 + mix(nu) ** 2); er = np.abs(c['n_r'][sel, x] - mix(nr) / m)[inner]; et = np.abs(c['n_t'][sel, x] - mix(nt) / m)[inner]
assert er.max() < 1e-3 and et.max() < 1e-3, ('the normal is not the normalised blend of the two samples', er.max(), et.max())
diff --git a/src/app/features/scene/BackgroundScene.tsx b/src/app/features/scene/BackgroundScene.tsx
index 23f50f04..23875a7b 100644
--- a/src/app/features/scene/BackgroundScene.tsx
+++ b/src/app/features/scene/BackgroundScene.tsx
@@ -24,7 +24,7 @@ export function BackgroundScene() {
if (!enabled || !canvas) return undefined;
const dispose = mountBackgroundScene(config, readCapabilities(navigator), canvas, {
loggedIn: !!getFallbackSession(),
- onActive: () => setSceneDrawn(true),
+ onActive: (sky) => setSceneDrawn(true, sky),
onInactive: () => setSceneDrawn(false),
// eslint-disable-next-line no-console
onFail: (e) => console.warn('Background scene unavailable:', e),
diff --git a/src/app/features/scene/README.md b/src/app/features/scene/README.md
index 1c6c5ad6..9679079f 100644
--- a/src/app/features/scene/README.md
+++ b/src/app/features/scene/README.md
@@ -5,34 +5,43 @@ config says `backgroundScene.style: 'raymarch'`; the tier flag still defaults to
means "keep the CSS ground". Everything below this section describes the opt-in ray-march scene.
- `ridge/Ridge.ts` `createRidgeScene({ canvas, tier, probe?, onProbe?, sky?, backdrop? })` returns `{ login, dispose }` or
- null (tier `off`, no 2D context). It paints the sky (`ridge/physicalSky.ts`, from the `SkyColours` the host passes) on the host
- canvas at the viewport's size in canvas pixels, then the stars baked into it, a twinkle overlay canvas for the swinging ones
- (`ridge/stars.ts`), the lit ridge cards (below) and, when it rains, tiled rain streaks slid down on the compositor (`ridge/rain.ts`).
- With no cards (the load failed) the scene shows sky, stars and weather only. No script runs per frame except the twinkle, at most every 50 ms.
- The host canvas and its parent must be positioned and the canvas should fill the parent. A resize rebuilds it; so does a sky change
+ null (tier `off`, no 2D context). It paints the sky (`ridge/physicalSky.ts`, from the `SkyColours` the host passes) into a sky plate (`ridge/skyTurn.ts`): one element over the host
+ canvas, the viewport's width plus its slack of sky each side (20 degrees, more as the turn speeds up: the margin of the speed in force over a tick and 2 s of lateness, and 14 degrees of travel), centred on the heading `heading.ts` owns, holding the sky with the real stars, the moon and the lines baked into it and a
+ twinkle canvas for the swinging stars (`ridge/stars.ts`) over it. The sky is at infinity, so one animation slides the plate by the heading's turn at the cards' px per degree, on the
+ same keyframes as the cards; a residency tick or a reissue paints a new plate about the heading once it is within that margin of the plate's edge (or the speed asks for more slack) and swaps it in the same tick,
+ keyed from the clock after the paint (the same sky at the same screen place, so nothing moves; the twinkle schedule runs over the catalogue, so a swap keeps which stars swing; the plate's backing store is capped at 3 Mpx, the pixel ratio lowering before the plate shrinks). Then come the lit ridge
+ cards (below) and, when it rains, tiled rain streaks slid down on the compositor (`ridge/rain.ts`). A sky with no physical model is a gradient in the host canvas.
+ With no cards (the load failed) the scene shows the sky, stars and weather only, the plate facing the place's rest azimuth and staying. No script runs per frame except the twinkle, at most every 50 ms.
+ The host canvas and its parent must be positioned and the parent must clip (the plate is wider than the viewport); the canvas should fill the parent. A resize rebuilds it; so does a sky change
(`index.ts`).
- Paused when the tab is hidden; under `prefers-reduced-motion` the rain is paused and the stars stay at base brightness.
- `tier: 'still'` paints the sky and stars and adds no overlay, no rain and no loop.
+ `tier: 'still'` paints the sky (facing the heading its pose froze at) and stars into the host canvas and adds no plate, no rain and no loop.
- Cadence guard: for the first 2 s after start (after 5 warm-up frames) rAF intervals are sampled; if their p95 is over
33 ms the scene settles to a still image (`ridge/probe.ts`) and stops. `?probe=1` (or `probe: true`) keeps sampling
and shows `n / median / p95` in a corner readout.
- `ridge/skyColour.ts` `skyColours()` is the fallback three-stop palette (top, mid, horizon) a scene gets with no `sky` option; the host
passes `ridgeSkyFor` (skyForState.ts) instead.
- Ridge cards: `ridge/manifest.ts` `loadManifest` reads `${BASE_URL}public/ridge/index.json` (config `backgroundScene.place` picks the entry,
- unknown or absent: the index default), then the place's `manifest.json` (schema 2, written by `scripts/ridge-bake/export.py`; it is the one JSON
- the backdrop reads): K G-buffer cards, nearest first, each a colour WebP (albedo, straight alpha) and a geometry WebP (the normal as 'rt8', the
- log-distance, and the wall code R = G = 255 for the extruded face under a ridge). `index.ts` `prepare()` loads the manifest and, with the scene chunk,
- `ridge/Backdrop.ts` `loadBackdrop`: every card's two files fetched and decoded straight (no premultiply, no colour management), then
- `ridge/lightCards.ts` lights each card once in WebGL2 for the sky of this build (sun and ambient from the atmosphere, aerial perspective from the
- geometry's distance, ink on occluding edges and creases, the sky's own display so terrain and sky share an exposure) into a 2D canvas, and releases
- the context. A sky change is a rebuild, so it lights again; nothing is lit per frame, and the host canvas is only ever asked for 2d.
- `createRidgeScene({ backdrop })` stays synchronous, and a rebuild keeps the old scene up until the new one's cards are lit, then swaps. The rig
- is one div of K card elements (farthest first; DOM order is paint order; no z-index, no fixed position, nothing outside the scene's parent),
- each placed at its rows of the plane and moved by `view.ts` `cardMotion`: the camera turns through the baker's heading range (capped so every card still covers
- the viewport) and card i pans `scale_i` x heading and is drawn `scale_i` times its bake, about the horizon centre, as a camera pushed forward on a circle
- round the bake centre sees it (ruling ridge-camera-on-circle); the scales come from the manifest. It drifts on `Element.animate` (transform only, 150 s loop,
- paused when the tab is hidden, motion is reduced or the scene is still); a still draws the same cards at heading 0 into the host canvas. A failure
- anywhere (404, a manifest that is not schema 2, a card that will not decode, no WebGL2, a lighting pass that throws) is the sky-only scene on `FALLBACK_VIEW`,
+ unknown or absent: the index default), then the place's `manifest.json` (schema 3, written by `scripts/ridge-bake/export.py`; it is the one JSON
+ the backdrop reads): the whole 360 degree ring, K G-buffer cards nearest first, each cut into azimuth tiles (32 of 11.25 degrees) of a colour WebP (albedo,
+ straight alpha) and a geometry WebP (the normal as 'rt8', the log-distance, and the wall code R = G = 255 for the extruded face under a ridge), each tile
+ with the card's distance there; `camera.r_max_m` bounds the parallax offset over every angle of the camera on its circle and `camera.r_max_forward_m` with the camera on its heading alone. Schema 2 is refused with a message naming the stale deploy. `index.ts`
+ `prepare()` loads the manifest, anchors the heading (`ridge/heading.ts`) and, with the scene chunk, `ridge/Backdrop.ts` `createBackdrop`: `ensure(arc)`
+ asks for the files of the tiles of an arc of azimuth it does not hold a few at a time (6 requests, each with a timeout) and decodes them one tile at a time (no premultiply, no colour management), and `ridge/lightCards.ts`
+ `createLighter` lights each card of a tile in WebGL2 for the sky of this build (sun and ambient from the atmosphere in absolute azimuth, aerial perspective from the
+ geometry's distance, ink on occluding edges and creases, the sky's own display so terrain and sky share an exposure) into a 2D canvas of the tile's interior and one
+ overlap column each side. The backdrop holds the arc ahead and two tiles beyond and lets go of the rest; a tile that fails is absent and asked for again by the backdrop itself after a pause that doubles to a minute, for as long as the arc last asked for wants it (a still has no timer of its own), and a file the server answers 404 is not asked for again (the tile is drawn with the cards that came). A sky change is a
+ rebuild, so it makes a new lighter; nothing is lit per frame, and the host canvas is only ever asked for 2d.
+ `createRidgeScene({ backdrop })` stays synchronous (`prepare()` awaits the first arc), and a rebuild keeps the old scene up until the new one holds tiles, then swaps (a build a newer one supersedes is given up at once, its requests aborted; a rebuild has no failure end: with no tile it stays pending beside the scene that is up, its loader asking again, and replaces it the moment it holds one; only a build with no ridge up behind it, a first load or a rebuild over the sky alone, that ends with no tile is the sky alone). The page theme and ink follow the sky of the scene that is up (`sceneDrawn.ts` holds it, set by the door's `onActive`), never the band announced; the
+ pose survives it. The rig is one div of K boxes, one per card (farthest first; DOM order is paint order; no z-index, no fixed position, nothing outside the scene's
+ parent), each holding that card's resident tiles at their unwrapped azimuth. A card's pose (scale and shift) is derived by `view.ts` `cardPose` from its distance at
+ the heading (`ring.ts`), the viewer's offset and the camera's angle on its circle, as a camera on a circle round the bake centre sees it (ruling ridge-camera-on-circle;
+ the offset is signed and clamped by `offsetRange`, the one clamp, by the mode: the forward bound with the camera on its heading, the worst-case bound where it circles; the speed by `maxSpeed`,
+ what the baked resident count sustains, applied to the stored choice). `cameraState.ts` is the one owner of the viewer's mode, speed and offset in `ratatoskr.camera`; `heading.ts` owns the view's pose, the direction, the camera's angle over it and its offset, as one segment (module
+ state: the pose at a clock, the mode and speed in force and the ease to the pose the choices owe; any change of a choice, a hold, a bound or reduced motion starts a new segment from the pose it has at that clock, `poseAt(t)` is a pure function of it, and a mode pick eases the angle and the offset one after the other, 300 ms each, in the order that keeps every pose inside the bound; `cameraState.ts` hands it each change synchronously before its listeners and keeps no log; `view.ts` `offsetRange`, given to it by the scene, is the one clamp; angles are normalized into [0, 360) before each stretch so nothing grows with uptime; a manual `hold` sets the mode to still, so a rebuild or a reload keeps it). The motion is one `Element.animate` per card (transform only, a
+ keyframe each second for 30 s and every 50 ms while an ease runs, reissued at 80% and on any change; paused when the tab is hidden or motion is reduced, then constant); a 500 ms timer asks the backdrop for
+ the arc every pose of the next 30 s passes over (`view.ts` `sweepArc`, sampled four times a second, not its two ends) and mounts the tiles it has made. A still draws the sky and the tiles of the arc into the host canvas at the heading now. A failure
+ anywhere (404, a manifest that is not schema 3, no tile that will decode, no WebGL2, a lighting pass that throws) is the sky-only scene on `FALLBACK_VIEW`,
told to the host by the live scene alone, through `onPlanesFail` when the live scene has no cards and `onPlanesOk` when a later one has them (never from a stale
or disposed build); it is never `onCompileFail`. `vite.config.js` copies `public/ridge` into `dist/public/`.
- `harness/scene/bundle.cjs ridge` builds a standalone page (`?tier=`, `?probe=1`).
@@ -50,8 +59,24 @@ callbacks and the creature sizing rule. Nothing has drawn a creature.
## Ridge scene: Vienna and the weather
-The ridge sky is the physical atmosphere (`ridge/earthAtmosphere.ts`) lit by the real sun over the viewpoint, 48.1929826 N, 16.3534237 E
-(`ridge/vienna.ts`).
+The ridge sky is the physical atmosphere (`ridge/earthAtmosphere.ts`) lit by the sun over the viewpoint (Vienna's is 48.1929826 N, 16.3534237 E, from the manifest).
+
+### The sky choice
+
+The viewer's choice is Auto, one of six named moments (Dawn, Morning, Noon, Golden hour, Dusk, Night) or a free moment (a place-local date and
+minute of the day). `ridge/skyMoment.ts` is the one owner of what it draws: `momentFor(choice, place, now)` returns the instant and `skyBand(elevation)`
+turns the sun at that instant into day, dusk or night (day from 6 degrees up, night from 6 down), which the ink theme (`skyTheme.ts`, `skyInk.ts`), the
+display budget (`ridge/toneMap.ts`) and the rebuild key (`skyForState.ts`) all read. Auto is the real sun over the loaded place now. A named moment is
+today's at the place (Night tonight's: the solar midnight nearest, before the day's noon the one just passed or coming, after it the one coming), from the sun's elevation crossings of the place-local day (`SKY_MOMENTS`, one row each: dawn and dusk at -3 degrees, golden hour at
++4, morning at the lesser of 15 degrees and half the noon elevation, noon the day's maximum, night solar midnight). Place-local time comes only from
+`place.tz`, the IANA zone the baker writes into the manifest (`scripts/ridge-bake/places.json`); the viewer's own zone decides nothing. Auto and the
+named moments draw today's weather; a free moment draws a clear sky.
+
+`skyState.ts` holds the stores (choice, place, constellation lines) and tells listeners; the choice persists in `ratatoskr.skyChoice`. The key
+of the old four-state menu is read once by `skyState.ts` (Day became Noon) and removed. `skyPlace.ts` is the one writer of the place: a scene start loads the manifest of the configured place (nothing else fetches it, so a page with no scene fetches nothing) and the build
+settles what it draws, the manifest's place when the cards load, `FALLBACK_VIEW`'s when they do not (a failed manifest, no tile that will decode), so the sky, the weather, the ink and the Auto
+timer read the place that is drawn. Until a scene has settled it no sky is drawn for ink and the theme's own ink stands. The one timer (Auto, a named moment) tells listeners when the band
+changes or a named moment's place-local day rolls over.
The weather is one number (`ridge/weather.ts`), from the page URL's `?weather=`, else `weather.json` beside `config.json`, else clear.
The browser never calls a weather service. `weather.json` is written by Eureka's refresher (gamecult-ops `docs/weather-feed.md`, a 5-minute timer; the only writer) from GeoSphere Austria's TAWES station 11035 (Wien Hohe Warte), credit
diff --git a/src/app/features/scene/SkyStateControl.test.tsx b/src/app/features/scene/SkyStateControl.test.tsx
new file mode 100644
index 00000000..df06280b
--- /dev/null
+++ b/src/app/features/scene/SkyStateControl.test.tsx
@@ -0,0 +1,173 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type { SkyChoice } from './ridge/skyMoment';
+import { FALLBACK_VIEW } from './ridge/view';
+import {
+ MENU_CHOICES,
+ SkyMomentPicker,
+ SkyStateControl,
+ choiceLabel,
+ useNativeChange,
+} from './SkyStateControl';
+
+// The component's hooks are held still, as in RoomOutbox.actions.test.tsx: state is its initial value, refs are plain boxes, effects are
+// kept to be run once the test has put an element in each ref. The element tree it returns is read and its native events are dispatched
+// on a fake input, so no DOM is needed.
+const held = vi.hoisted(() => ({
+ effects: [] as Array<() => unknown>,
+ choice: { kind: 'auto' } as unknown,
+}));
+vi.mock('react', async (importOriginal) => {
+ const actual = await importOriginal();
+ const useState = (init: unknown) => [
+ typeof init === 'function' ? (init as () => unknown)() : init,
+ () => undefined,
+ ];
+ const useRef = (init: unknown) => ({ current: init });
+ const useEffect = (fn: () => unknown) => {
+ held.effects.push(fn);
+ };
+ return {
+ ...actual,
+ default: { ...actual, useState, useRef, useEffect },
+ useState,
+ useRef,
+ useEffect,
+ };
+});
+vi.mock('../../hooks/useSkyState', () => ({
+ useSkyChoice: () => held.choice,
+ useDrawnPlace: () => FALLBACK_VIEW.place,
+}));
+vi.mock('../../hooks/useClientConfig', () => ({ useClientConfig: () => ({}) }));
+
+type El = { type?: unknown; ref?: unknown; props?: Record };
+/** Every element reachable through any prop (children, `content`, `after`). */
+const walk = (node: unknown): El[] => {
+ if (Array.isArray(node)) return node.flatMap(walk);
+ if (node && typeof node === 'object' && 'props' in node) {
+ const el = node as El;
+ return [el, ...Object.values(el.props ?? {}).flatMap(walk)];
+ }
+ return [];
+};
+const textOf = (node: unknown): string => {
+ if (typeof node === 'string' || typeof node === 'number') return String(node);
+ if (Array.isArray(node)) return node.map(textOf).join('');
+ if (node && typeof node === 'object' && 'props' in node) {
+ return textOf((node as El).props?.children);
+ }
+ return '';
+};
+/** A stand-in input: a real EventTarget with a value. */
+const fakeInput = (value: string) => Object.assign(new EventTarget(), { value });
+const fire = (el: EventTarget, type: 'input' | 'change') => el.dispatchEvent(new Event(type));
+
+beforeEach(() => {
+ held.effects.length = 0;
+ held.choice = { kind: 'auto' };
+});
+
+describe('the sky menu choices', () => {
+ const tree = () => walk(SkyStateControl());
+ const radios = () => tree().filter((e) => e.props?.role === 'menuitemradio');
+
+ it('lists Auto and the six named moments, then Pick a moment', () => {
+ expect(MENU_CHOICES.map(choiceLabel)).toEqual([
+ 'Auto',
+ 'Dawn',
+ 'Morning',
+ 'Noon',
+ 'Golden hour',
+ 'Dusk',
+ 'Night',
+ ]);
+ expect(radios().map((e) => textOf(e))).toEqual([
+ 'Auto',
+ 'Dawn',
+ 'Morning',
+ 'Noon',
+ 'Golden hour',
+ 'Dusk',
+ 'Night',
+ 'Pick a moment',
+ ]);
+ });
+
+ it.each([
+ [{ kind: 'auto' }, 0],
+ [{ kind: 'named', id: 'dawn' }, 1],
+ [{ kind: 'named', id: 'night' }, 6],
+ [{ kind: 'free', date: '2026-12-21', minutes: 400 }, 7],
+ ] as Array<[SkyChoice, number]>)('aria-checked follows the choice %j', (choice, checked) => {
+ held.choice = choice;
+ radios().forEach((e, i) => expect(e.props?.['aria-checked'], `item ${i}`).toBe(i === checked));
+ });
+
+ it("the button reads 'Sky: Auto', 'Sky: Dawn' or 'Sky: '", () => {
+ const label = () =>
+ tree().find((e) => e.props?.['aria-haspopup'] === 'menu')?.props?.['aria-label'];
+ expect(label()).toBe('Sky: Auto');
+ held.choice = { kind: 'named', id: 'dawn' };
+ expect(label()).toBe('Sky: Dawn');
+ held.choice = { kind: 'free', date: '2026-12-21', minutes: 6 * 60 + 40 };
+ expect(label()).toBe('Sky: 2026-12-21 06:40');
+ });
+});
+
+describe('committing on change, not on input', () => {
+ it('a native input event commits nothing and the change event commits once', () => {
+ const commits: string[] = [];
+ const ref = useNativeChange((el) => commits.push(el.value));
+ const target = fakeInput('600');
+ (ref as { current: unknown }).current = target;
+ held.effects.forEach((run) => run());
+ for (let i = 0; i < 5; i += 1) fire(target, 'input');
+ expect(commits).toEqual([]);
+ fire(target, 'change');
+ expect(commits).toEqual(['600']);
+ });
+
+ it('the picker commits the slider on release only, with the date it holds, and the date on change when it is a date in range', () => {
+ const commits: unknown[] = [];
+ const tree = walk(
+ SkyMomentPicker({
+ seed: { kind: 'free', date: '2026-12-21', minutes: 600 },
+ tz: 'Europe/Vienna',
+ onCommit: (c) => commits.push(c),
+ })
+ );
+ const input = (type: string) => tree.find((e) => e.type === 'input' && e.props?.type === type);
+ const date = fakeInput('2026-12-21');
+ const slider = fakeInput('600');
+ (input('date')?.ref as { current: unknown }).current = date;
+ (input('range')?.ref as { current: unknown }).current = slider;
+ held.effects.forEach((run) => run());
+
+ slider.value = '735';
+ fire(slider, 'input');
+ fire(slider, 'input');
+ expect(commits).toEqual([]);
+ fire(slider, 'change');
+ expect(commits).toEqual([{ kind: 'free', date: '2026-12-21', minutes: 735 }]);
+
+ date.value = '2026-07-15';
+ fire(date, 'change');
+ expect(commits[1]).toEqual({ kind: 'free', date: '2026-07-15', minutes: 735 });
+ date.value = '1800-01-01';
+ fire(date, 'change');
+ date.value = '';
+ fire(date, 'change');
+ expect(commits).toHaveLength(2);
+ expect(input('range')?.props).toMatchObject({ min: 0, max: 1439, step: 5 });
+ expect(input('date')?.props).toMatchObject({ min: '1900-01-01', max: '2100-12-31' });
+ });
+
+ it('the picker shows the place-local time and the zone beside the slider', () => {
+ const tree = SkyMomentPicker({
+ seed: { kind: 'free', date: '2026-12-21', minutes: 400 },
+ tz: 'Europe/Vienna',
+ onCommit: () => undefined,
+ });
+ expect(textOf(tree)).toMatch(/^06:40 \S+/);
+ });
+});
diff --git a/src/app/features/scene/SkyStateControl.tsx b/src/app/features/scene/SkyStateControl.tsx
index 49e21c38..c8c5a374 100644
--- a/src/app/features/scene/SkyStateControl.tsx
+++ b/src/app/features/scene/SkyStateControl.tsx
@@ -1,4 +1,4 @@
-import React, { MouseEventHandler, useEffect, useState } from 'react';
+import React, { MouseEventHandler, useEffect, useRef, useState } from 'react';
import {
Box,
config,
@@ -13,8 +13,19 @@ import {
} from 'folds';
import FocusTrap from 'focus-trap-react';
import { stopPropagation } from '../../utils/keyboard';
-import { useSkyState } from '../../hooks/useSkyState';
-import { SKY_STATES, pickSkyState, type SkyState } from './skyState';
+import { useDrawnPlace, useSkyChoice } from '../../hooks/useSkyState';
+import { pickSkyChoice, skyNow } from './skyState';
+import {
+ FREE_DATE_MAX,
+ FREE_DATE_MIN,
+ MOMENT_IDS,
+ isDate,
+ seedFree,
+ zoneName,
+ zonedInstant,
+} from './ridge/skyMoment';
+import type { MomentId, SkyChoice } from './ridge/skyMoment';
+import { FALLBACK_VIEW } from './ridge/view';
import { loadManifest } from './ridge/manifest';
import {
LINES_CREDIT,
@@ -27,36 +38,129 @@ import {
import { useClientConfig } from '../../hooks/useClientConfig';
import { PhoneHit } from '../../styles/PhoneHit.css';
-const LABEL: Record = {
- auto: 'Auto',
- day: 'Day',
+export const MOMENT_LABEL: Record = {
+ dawn: 'Dawn',
+ morning: 'Morning',
+ noon: 'Noon',
+ golden: 'Golden hour',
dusk: 'Dusk',
night: 'Night',
};
+const hhmm = (minutes: number): string =>
+ `${String(Math.floor(minutes / 60)).padStart(2, '0')}:${String(minutes % 60).padStart(2, '0')}`;
+
+/** What the button and the menu call a choice: Auto, the moment's name, or the free moment's place-local date and time. */
+export const choiceLabel = (c: SkyChoice): string =>
+ c.kind === 'auto'
+ ? 'Auto'
+ : c.kind === 'named'
+ ? MOMENT_LABEL[c.id]
+ : `${c.date} ${hhmm(c.minutes)}`;
+
+/** The choices the menu lists, in order. */
+export const MENU_CHOICES: readonly SkyChoice[] = [
+ { kind: 'auto' },
+ ...MOMENT_IDS.map((id): SkyChoice => ({ kind: 'named', id })),
+];
+
+const sameChoice = (a: SkyChoice, b: SkyChoice): boolean => JSON.stringify(a) === JSON.stringify(b);
+
/**
- * One title-bar button that opens the four sky states. A single button, not a row, so the bar
- * still fits a 320 px phone beside the search button; the menu items carry the state names.
+ * Run `onChange` on the element's native `change` event: for a slider, its release, not every `input` tick (React's onChange is the
+ * input event). Each commit rebuilds the scene, so a drag must commit once.
+ */
+export function useNativeChange(onChange: (el: T) => void) {
+ const ref = useRef(null);
+ const latest = useRef(onChange);
+ latest.current = onChange;
+ useEffect(() => {
+ const el = ref.current;
+ if (!el) return undefined;
+ const handler = () => latest.current(el);
+ el.addEventListener('change', handler);
+ return () => el.removeEventListener('change', handler);
+ }, []);
+ return ref;
+}
+
+type Free = Extract;
+
+/** A date and a time of day at the place, committed when each input changes (the slider on release), never per `input` tick. */
+export function SkyMomentPicker({
+ seed,
+ tz,
+ onCommit,
+}: {
+ seed: Free;
+ tz: string;
+ onCommit: (c: Free) => void;
+}) {
+ const [minutes, setMinutes] = useState(seed.minutes);
+ const at = useRef({ date: seed.date, minutes: seed.minutes });
+ const dateRef = useNativeChange((el) => {
+ if (!isDate(el.value) || el.value < FREE_DATE_MIN || el.value > FREE_DATE_MAX) return;
+ at.current.date = el.value;
+ onCommit({ kind: 'free', ...at.current });
+ });
+ const sliderRef = useNativeChange((el) => {
+ at.current.minutes = Number(el.value);
+ onCommit({ kind: 'free', ...at.current });
+ });
+ const zone = zoneName(zonedInstant(at.current.date, minutes, tz), tz);
+ return (
+
+
+ setMinutes(Number(evt.currentTarget.value))}
+ />
+
+ {hhmm(minutes)} {zone}
+
+
+ );
+}
+
+/**
+ * One title-bar button that opens the sky choices: Auto, the six named moments of today at the place, and a free date and time. A single
+ * button, not a row, so the bar still fits a 320 px phone beside the search button; the menu items carry the names.
*/
export function SkyStateControl() {
- const state = useSkyState();
+ const choice = useSkyChoice();
+ const drawn = useDrawnPlace();
+ const [picking, setPicking] = useState(false);
const [cords, setCords] = useState();
const backgroundScene = useClientConfig().backgroundScene;
- const place = backgroundScene?.place;
+ const placeId = backgroundScene?.place;
+ const place = drawn ?? FALLBACK_VIEW.place;
const [credit, setCredit] = useState();
const ridgeOn = !!backgroundScene && backgroundScene.style !== 'raymarch';
useEffect(() => {
if (!ridgeOn) return undefined;
let live = true;
- loadManifest(import.meta.env.BASE_URL, place).then(
+ loadManifest(import.meta.env.BASE_URL, placeId).then(
(m) => live && setCredit(terrainCredit(m)),
() => live && setCredit(undefined)
);
return () => {
live = false;
};
- }, [ridgeOn, place]);
+ }, [ridgeOn, placeId]);
const open: MouseEventHandler = (evt) => {
setCords(evt.currentTarget.getBoundingClientRect());
};
@@ -71,34 +175,63 @@ export function SkyStateControl() {
focusTrapOptions={{
initialFocus: '[aria-checked="true"]',
returnFocusOnDeactivate: true,
- onDeactivate: () => setCords(undefined),
+ onDeactivate: () => {
+ setCords(undefined);
+ setPicking(false);
+ },
clickOutsideDeactivates: true,
- isKeyForward: (evt: KeyboardEvent) => evt.key === 'ArrowDown',
- isKeyBackward: (evt: KeyboardEvent) => evt.key === 'ArrowUp',
+ isKeyForward: (evt: KeyboardEvent) =>
+ evt.key === 'ArrowDown' && !(evt.target instanceof HTMLInputElement),
+ isKeyBackward: (evt: KeyboardEvent) =>
+ evt.key === 'ArrowUp' && !(evt.target instanceof HTMLInputElement),
escapeDeactivates: stopPropagation,
}}
>
- {SKY_STATES.map((s) => (
- {
- pickSkyState(s);
- setCords(undefined);
- }}
- after={state === s ? : undefined}
- >
-
- {LABEL[s]}
-
-
- ))}
+ {MENU_CHOICES.map((c) => {
+ const checked = sameChoice(c, choice);
+ return (
+ {
+ pickSkyChoice(c);
+ setCords(undefined);
+ }}
+ after={checked ? : undefined}
+ >
+
+ {choiceLabel(c)}
+
+
+ );
+ })}
+ setPicking(!picking)}
+ after={choice.kind === 'free' ? : undefined}
+ >
+
+ Pick a moment
+
+
+ {picking && (
+
+ )}
{ridgeOn && (
();
+const reduced = { matches: false };
+
+beforeEach(() => {
+ store.clear();
+ reduced.matches = false;
+ resetCamera();
+ vi.stubGlobal('localStorage', {
+ getItem: (k: string) => store.get(k) ?? null,
+ setItem: (k: string, v: string) => void store.set(k, v),
+ });
+ vi.stubGlobal('window', { matchMedia: () => reduced });
+});
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('the viewer camera', () => {
+ it('starts at the defaults: both, a turn in ten minutes, 200 m forward', () => {
+ expect(getCamera()).toEqual({ mode: 'both', speedDegPerS: 0.6, offsetM: 200 });
+ expect(DEFAULT_CAMERA).toEqual(getCamera());
+ });
+
+ it('starts still under reduced motion, and a stored choice outranks that', () => {
+ reduced.matches = true;
+ expect(getCamera().mode).toBe('still');
+ resetCamera();
+ store.set(CAMERA_KEY, JSON.stringify({ mode: 'offset', speedDegPerS: 1, offsetM: -30 }));
+ expect(getCamera()).toEqual({ mode: 'offset', speedDegPerS: 1, offsetM: -30 });
+ });
+
+ it('keeps each change per viewer, and tells listeners only of a change', () => {
+ const cb = vi.fn();
+ subscribe(cb);
+ setCamera({ offsetM: 50 });
+ expect(JSON.parse(store.get(CAMERA_KEY) as string)).toEqual({ ...DEFAULT_CAMERA, offsetM: 50 });
+ setCamera({ offsetM: 50 });
+ setCamera({ mode: 'both' });
+ expect(cb).toHaveBeenCalledTimes(1);
+ setCamera({ mode: 'offset', speedDegPerS: 2 });
+ expect(cb).toHaveBeenCalledTimes(2);
+ expect(getCamera()).toEqual({ mode: 'offset', speedDegPerS: 2, offsetM: 50 });
+ });
+
+ it('tells listeners what the choice was and the clock it changed at, so the kinematics can be taken to that moment', () => {
+ const cb = vi.fn();
+ subscribe(cb);
+ setCamera({ mode: 'offset' }, 1234);
+ expect(cb).toHaveBeenCalledWith({ ...DEFAULT_CAMERA, mode: 'offset' }, DEFAULT_CAMERA, 1234, false);
+ });
+
+ it('hands a change to the owner before any listener, at its clock, whenever the listeners registered, and keeps no log of it', () => {
+ const order: string[] = [];
+ subscribe(() => order.push('early'));
+ bindOwner((at) => order.push(`owner ${at}`));
+ subscribe(() => order.push('late'));
+ setCamera({ offsetM: 5 }, 42);
+ holdCamera(43);
+ setCamera({ mode: 'both' }, 44); // picking a mode ends the hold
+ setCamera({ offsetM: 5 }, 45); // nothing changed
+ expect(order).toEqual(['owner 42', 'early', 'late', 'owner 43', 'early', 'late', 'owner 44', 'early', 'late']);
+ resetCamera(); // a reload of the choice does not unbind the owner: it outlives the scenes
+ setCamera({ offsetM: 9 }, 50);
+ expect(order.at(-1)).toBe('owner 50');
+ expect(Object.keys(camera)).not.toContain('takeChanges');
+ bindOwner(undefined);
+ });
+
+ it('a hold is session state: the mode in effect is still, the chosen mode is untouched and stored as chosen, and a reload does not hold', () => {
+ setCamera({ mode: 'offset', speedDegPerS: 2 });
+ const cb = vi.fn();
+ subscribe(cb);
+ holdCamera(5);
+ expect(isHeld()).toBe(true);
+ expect(effectiveMode()).toBe('still');
+ expect(getCamera().mode).toBe('offset');
+ expect(JSON.parse(store.get(CAMERA_KEY) as string).mode).toBe('offset');
+ expect(cb).toHaveBeenCalledTimes(1);
+ holdCamera(6); // already held
+ expect(cb).toHaveBeenCalledTimes(1);
+ setCamera({ offsetM: 10 }); // a slider does not end a hold
+ expect(isHeld()).toBe(true);
+ resetCamera(); // a reload
+ expect(isHeld()).toBe(false);
+ expect(effectiveMode()).toBe('offset');
+ });
+
+ it('picking a mode ends a hold, the one already chosen included, and is heard as a change though nothing stored moved', () => {
+ setCamera({ mode: 'both' });
+ holdCamera(1);
+ const cb = vi.fn();
+ subscribe(cb);
+ setCamera({ mode: 'both' }, 9);
+ expect(isHeld()).toBe(false);
+ expect(effectiveMode()).toBe('both');
+ expect(cb).toHaveBeenCalledTimes(1);
+ expect(cb.mock.calls[0][2]).toBe(9);
+ expect(cb.mock.calls[0][3]).toBe(true); // it was held until this change
+ setCamera({ mode: 'both' }, 10); // nothing held, nothing changed
+ expect(cb).toHaveBeenCalledTimes(1);
+ });
+
+ it('ignores a stored value that is not a choice, and a change that is not one', () => {
+ store.set(CAMERA_KEY, '{"mode":"spin","speedDegPerS":1,"offsetM":0}');
+ expect(getCamera()).toEqual(DEFAULT_CAMERA);
+ store.set(CAMERA_KEY, 'not json');
+ resetCamera();
+ expect(getCamera()).toEqual(DEFAULT_CAMERA);
+ setCamera({ speedDegPerS: Number.NaN });
+ setCamera({ mode: 'spin' as never });
+ expect(getCamera()).toEqual(DEFAULT_CAMERA);
+ expect(parseCamera({ mode: 'still', speedDegPerS: Infinity, offsetM: 0 })).toBeUndefined();
+ });
+
+ it('holds the choice for the page load when storage refuses', () => {
+ vi.stubGlobal('localStorage', {
+ getItem: () => {
+ throw new Error('blocked');
+ },
+ setItem: () => {
+ throw new Error('blocked');
+ },
+ });
+ resetCamera();
+ expect(getCamera()).toEqual(DEFAULT_CAMERA);
+ setCamera({ offsetM: -10 });
+ expect(getCamera().offsetM).toBe(-10);
+ });
+});
diff --git a/src/app/features/scene/cameraState.ts b/src/app/features/scene/cameraState.ts
new file mode 100644
index 00000000..8d09216b
--- /dev/null
+++ b/src/app/features/scene/cameraState.ts
@@ -0,0 +1,130 @@
+// How the viewer wants the ridge camera to move: the rotation mode, the speed and the parallax offset, per viewer in localStorage. The one owner of the
+// chosen mode, speed and offset (persisted, never rewritten by anything but the viewer: the clamp on the offset, `ridge/view.ts` `offsetRange`, and the bound
+// on the speed, `maxSpeed`, are derived from them at read for the mode and the bake in force) and of the hold: a manual turn (`ridge/heading.ts` `hold`) makes the
+// mode in effect 'still' until the viewer picks a mode, the one already chosen included. The hold is session state: a rebuild keeps it, a reload does not
+// (a reload is a Return). `ridge/heading.ts` integrates the view direction over the mode in effect. Main-chunk safe (no ridge code is imported at runtime), as placeState and skyState are.
+import type { RotationMode } from './ridge/heading';
+
+export const CAMERA_KEY = 'ratatoskr.camera';
+
+export interface CameraChoice {
+ mode: RotationMode;
+ /** Degrees per second the view (or the camera on its circle) turns at. */
+ speedDegPerS: number;
+ /** The camera's offset from the bake centre in metres, forward positive; a scene clamps it to the place's range. */
+ offsetM: number;
+}
+
+/**
+ * What a first visit sees (question ridge-view-defaults, provisional): a turn in ten minutes with the camera 200 m forward, view direction and camera
+ * together (ruling ridge-scene-view-fullscreen). A visit that asks for reduced motion starts with nothing turning.
+ */
+export const DEFAULT_CAMERA: CameraChoice = { mode: 'both', speedDegPerS: 0.6, offsetM: 200 };
+
+const MODES: readonly RotationMode[] = ['still', 'offset', 'both'];
+
+/** A stored value as a choice, or undefined when it is not one (an unknown mode, a speed or offset that is not a finite number). */
+export function parseCamera(raw: unknown): CameraChoice | undefined {
+ if (typeof raw !== 'object' || raw === null) return undefined;
+ const c = raw as Record;
+ if (
+ !MODES.includes(c.mode as RotationMode) ||
+ typeof c.speedDegPerS !== 'number' ||
+ !Number.isFinite(c.speedDegPerS) ||
+ typeof c.offsetM !== 'number' ||
+ !Number.isFinite(c.offsetM)
+ ) {
+ return undefined;
+ }
+ return { mode: c.mode as RotationMode, speedDegPerS: c.speedDegPerS, offsetM: c.offsetM };
+}
+
+const reducedMotion = (): boolean => {
+ try {
+ return window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches === true;
+ } catch {
+ return false;
+ }
+};
+
+let current: CameraChoice | undefined;
+/** Hears a change of the choice or of the hold: the choice now, what it was, the clock, and whether the view was held before. */
+type Listener = (next: CameraChoice, prev: CameraChoice, at: number, wasHeld: boolean) => void;
+let held = false;
+const listeners = new Set();
+/**
+ * The one reader that must have taken a change before anyone else hears of it: the heading owner (`ridge/heading.ts`), which starts a new segment of the view's
+ * motion at the clock `at`. Called synchronously by the change, before every listener, so no order of registration can put a listener ahead of it, and nothing is
+ * queued. Cleared by nothing: the owner outlives the scenes and the choice.
+ */
+let owner: ((at: number) => void) | undefined;
+export const bindOwner = (cb: ((at: number) => void) | undefined): void => {
+ owner = cb;
+};
+const clock = (): number => (typeof performance !== 'undefined' ? performance.now() : Date.now());
+
+function load(): CameraChoice {
+ try {
+ const stored = localStorage.getItem(CAMERA_KEY);
+ const parsed = stored === null ? undefined : parseCamera(JSON.parse(stored));
+ if (parsed) return parsed;
+ } catch {
+ // Storage is unreadable (private mode, bad JSON): the defaults hold for this page load.
+ }
+ return reducedMotion() ? { ...DEFAULT_CAMERA, mode: 'still' } : { ...DEFAULT_CAMERA };
+}
+
+export const getCamera = (): CameraChoice => {
+ current ??= load();
+ return current;
+};
+
+/** Change any of the three, at the clock `at` (ms, `performance.now()` by default); listeners hear it, with what it was and `at`, only when something moved. */
+export function setCamera(change: Partial, at: number = clock()): void {
+ const next = parseCamera({ ...getCamera(), ...change });
+ if (!next) return;
+ const prev = getCamera();
+ const wasHeld = held;
+ // Picking a mode, the one already chosen included, ends a hold: it is a change whenever a hold is on.
+ const resumes = wasHeld && change.mode !== undefined;
+ const same = next.mode === prev.mode && next.speedDegPerS === prev.speedDegPerS && next.offsetM === prev.offsetM;
+ if (same && !resumes) return;
+ current = next;
+ if (resumes) held = false;
+ if (!same) {
+ try {
+ localStorage.setItem(CAMERA_KEY, JSON.stringify(next));
+ } catch {
+ // Storage is refused: the choice holds for this page load only.
+ }
+ }
+ owner?.(at);
+ [...listeners].forEach((cb) => cb(next, prev, at, wasHeld));
+}
+
+/** A manual turn is on: the mode in effect is 'still' whatever the viewer chose. Not stored. */
+export const isHeld = (): boolean => held;
+
+/** The mode in effect: the viewer's choice, 'still' while the view is held. */
+export const effectiveMode = (): RotationMode => (held ? 'still' : getCamera().mode);
+
+/** Take the view by hand: hold it. Listeners hear it only when it was not held already. */
+export function holdCamera(at: number = clock()): void {
+ if (held) return;
+ held = true;
+ const cam = getCamera();
+ owner?.(at);
+ [...listeners].forEach((cb) => cb(cam, cam, at, false));
+}
+
+export function subscribe(cb: Listener): () => void {
+ listeners.add(cb);
+ return () => listeners.delete(cb);
+}
+
+/** For tests: forget what was read, so the next read starts from storage again. */
+export function resetCamera(): void {
+ current = undefined;
+ held = false;
+ listeners.clear();
+}
diff --git a/src/app/features/scene/host.test.ts b/src/app/features/scene/host.test.ts
index b987d0cc..d5514d52 100644
--- a/src/app/features/scene/host.test.ts
+++ b/src/app/features/scene/host.test.ts
@@ -44,6 +44,14 @@ describe('mountBackgroundScene', () => {
expect(scene.login).not.toHaveBeenCalled();
});
+ it('tells onActive the sky the started scene draws', async () => {
+ startBackgroundScene.mockResolvedValue({ ...fakeScene(), drawnSky: 'dusk' });
+ const onActive = vi.fn();
+ mountBackgroundScene(config, caps, canvas, { loggedIn: false, onActive });
+ await flush();
+ expect(onActive).toHaveBeenCalledWith('dusk');
+ });
+
it('disposes the scene on unmount, once', async () => {
const scene = fakeScene();
startBackgroundScene.mockResolvedValue(scene);
diff --git a/src/app/features/scene/host.ts b/src/app/features/scene/host.ts
index 9a31c812..fccba78f 100644
--- a/src/app/features/scene/host.ts
+++ b/src/app/features/scene/host.ts
@@ -1,12 +1,13 @@
import { startBackgroundScene } from './index';
-import type { Scene } from './index';
+import type { StartedScene } from './index';
+import type { FixedSkyState } from './ridge/skyMoment';
import type { BackgroundSceneConfig, Capabilities } from './tier';
export type HostOptions = {
/** A Matrix session already exists, so the scene starts past its login moment. */
loggedIn: boolean;
- /** The scene is running: the host may now let it show through. Not called when there is none. */
- onActive?: () => void;
+ /** The scene is running: the host may now let it show through, over the sky it draws. Not called when there is none. */
+ onActive?: (sky?: FixedSkyState) => void;
/** The scene stopped because its GL context was lost: put the CSS ground back until it restores. */
onInactive?: () => void;
/** A shader failed to compile, the chunk failed to load, or starting threw. The CSS ground stays. */
@@ -30,7 +31,7 @@ export function mountBackgroundScene(
{ loggedIn, onActive, onInactive, onFail }: HostOptions
): () => void {
let cancelled = false;
- let scene: Scene | null = null;
+ let scene: StartedScene | null = null;
let generation = 0;
const start = () => {
@@ -57,7 +58,7 @@ export function mountBackgroundScene(
}
scene = started;
if (!scene) return;
- onActive?.();
+ onActive?.(scene.drawnSky);
if (loggedIn) scene.login();
},
(e) => {
diff --git a/src/app/features/scene/index.test.ts b/src/app/features/scene/index.test.ts
index bed1e23e..7a0db7d9 100644
--- a/src/app/features/scene/index.test.ts
+++ b/src/app/features/scene/index.test.ts
@@ -1,24 +1,28 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { atStandardTime } from './standardTime.testkit';
+import { atSolarTime } from './ridge/skyTestkit';
import type { Scene } from './Scene';
-import { startBackgroundScene } from './index';
-import { pickSkyState, setSkyClock, setSkyState } from './skyState';
+import { PREPARE_DEADLINE_MS, startBackgroundScene } from './index';
+import { getResolvedSkyState, getSkyPlace, pickSkyChoice, setSkyChoice, setSkyClock, setSkyPlace, subscribe } from './skyState';
+import { skyBand } from './ridge/skyMoment';
+import type { SkyChoice } from './ridge/skyMoment';
import { ridgeSkyFor } from './skyForState';
import { forgetManifests } from './ridge/manifest';
import { wireIndex, wireManifest } from './ridge/manifest.fixture';
-import { FALLBACK_VIEW } from './ridge/view';
+import { FALLBACK_VIEW, HFOV_MAX_DEG, maxSpeed } from './ridge/view';
+import { hold, poseAt, resetHeading } from './ridge/heading';
+import { resetCamera, setCamera } from './cameraState';
import { sunAt } from './ridge/sunAt';
import { ridgeWeather } from './ridge/weather';
import { parseWeatherFile, WEATHER_ATTRIBUTION, weatherFromFile } from './ridge/weatherFeed';
-const { createRidgeScene, createScene, loadBackdrop } = vi.hoisted(() => ({
+const { createRidgeScene, createScene, createBackdrop } = vi.hoisted(() => ({
createRidgeScene: vi.fn(),
createScene: vi.fn(),
- loadBackdrop: vi.fn(),
+ createBackdrop: vi.fn(),
}));
vi.mock('./ridge/Ridge', () => ({ createRidgeScene }));
-// Decoding and lighting are the cards' own tests' (Backdrop.test.ts, lightCards.test.ts); here the door sees a loader it can hold, fail and count.
-vi.mock('./ridge/Backdrop', () => ({ loadBackdrop }));
+// Decoding and lighting are the cards' own tests' (Backdrop.test.ts, lightCards.test.ts); here the door sees a backdrop whose first arc it can hold, fail and count.
+vi.mock('./ridge/Backdrop', () => ({ createBackdrop }));
vi.mock('./Scene', () => ({ createScene }));
// The physical sky is baked per call (tens of ms: atmosphere LUTs) and the clock here is fixed, so a state always
// draws the same sky. Baking once per state keeps the 21-offset sweep under the default timeout when the machine is
@@ -30,14 +34,19 @@ vi.mock('./skyForState', async (importOriginal) => {
...actual,
ridgeSkyFor: (...args: Parameters) => {
const [state, view] = args;
- // One bake per state and place; the view is the one owner of the place, so it is part of what a sky is.
- const key = `${state}@${JSON.stringify(view.place)}`;
+ // One bake per choice and place; the view is the one owner of the place, so it is part of what a sky is.
+ const key = `${JSON.stringify(state)}@${JSON.stringify(view.place)}`;
if (!baked.has(key)) baked.set(key, actual.ridgeSkyFor(...args));
return baked.get(key) as ReturnType;
},
};
});
+const AUTO: SkyChoice = { kind: 'auto' };
+const NOON: SkyChoice = { kind: 'named', id: 'noon' };
+const DUSK: SkyChoice = { kind: 'named', id: 'dusk' };
+const NIGHT: SkyChoice = { kind: 'named', id: 'night' };
+
const canvas = {} as HTMLCanvasElement;
const config = { tier: 'low' as const };
const caps = { hardwareConcurrency: 8 };
@@ -51,26 +60,47 @@ const microtasks = (n: number) =>
(p) => p.then(() => undefined),
Promise.resolve()
);
-/** A loader for `loadBackdrop` that waits on `ctl.hold` (queueing its settle in `ctl.pending`), then resolves a backdrop or, with `ctl.fail` as it stood when asked, null. `ctl.calls` is the sky each call was lit for. */
+/** A `createBackdrop` whose first `ensure` waits on `ctl.hold` (queueing its settle in `ctl.pending`), then makes tiles or, with `ctl.fail` as it stood when asked, none. `ctl.calls` is the sky each backdrop was lit for; `ctl.made` the backdrops. */
const loader = () => {
const ctl = {
pending: [] as Array<() => void>,
hold: false,
fail: false,
calls: [] as any[],
+ made: [] as any[],
+ /** The loader's retry succeeds: every backdrop that was asked while `fail` was set now holds a tile, and tells whoever listens. */
+ arrive: () => undefined as void,
};
- loadBackdrop.mockImplementation(
- (manifest: unknown, physical: unknown) =>
- new Promise((resolve) => {
- const fails = ctl.fail; // the outcome belongs to the request, whenever it settles
- const settle = () => {
- ctl.calls.push(physical);
- resolve(fails ? null : { manifest, cards: [] });
- };
- if (ctl.hold) ctl.pending.push(settle);
- else settle();
- })
- );
+ const heard = new Set<() => void>();
+ ctl.arrive = () => {
+ arrived = true;
+ [...heard].forEach((cb) => cb());
+ };
+ let arrived = false;
+ createBackdrop.mockImplementation((manifest: unknown, physical: unknown) => {
+ const fails = ctl.fail; // the outcome belongs to the request, whenever it settles
+ let made = false;
+ const bd = {
+ manifest,
+ dispose: vi.fn(),
+ litTiles: () => (made && (!fails || arrived) ? [{ tile: 0, card: 0, canvas: {} }] : []),
+ onTile: vi.fn((cb: () => void) => (heard.add(cb), () => void heard.delete(cb))),
+ ensure: vi.fn(
+ () =>
+ new Promise((resolve) => {
+ const settle = () => {
+ made = true;
+ ctl.calls.push(physical);
+ resolve();
+ };
+ if (ctl.hold) ctl.pending.push(settle);
+ else settle();
+ })
+ ),
+ };
+ ctl.made.push(bd);
+ return bd;
+ });
return {
ctl,
release: async () => {
@@ -84,17 +114,22 @@ const fakeScene = () => ({ login: vi.fn(), dispose: vi.fn() });
const hex = (c: readonly number[]) => `#${c.map((v) => v.toString(16).padStart(2, '0')).join('')}`;
beforeEach(() => {
- vi.stubGlobal('localStorage', { getItem: () => null, setItem: () => undefined });
+ vi.stubGlobal('localStorage', {
+ getItem: () => null,
+ setItem: () => undefined,
+ removeItem: () => undefined,
+ });
// Local midnight: 'auto' resolves to night.
- setSkyClock(() => atStandardTime(0, 0));
- setSkyState('auto');
+ setSkyClock(() => atSolarTime(0, 0));
+ setSkyChoice(AUTO);
+ setSkyPlace(FALLBACK_VIEW.place);
createRidgeScene.mockReset();
createScene.mockReset();
- loadBackdrop.mockReset();
+ createBackdrop.mockReset();
});
afterEach(() => {
setSkyClock();
- setSkyState('auto');
+ setSkyChoice(AUTO);
vi.unstubAllGlobals();
});
@@ -104,28 +139,31 @@ describe('startBackgroundScene follows the sky state', () => {
const scene = await startBackgroundScene(config, caps, { canvas });
expect(createRidgeScene).toHaveBeenCalledOnce();
expect(hex(createRidgeScene.mock.calls[0][0].sky.top)).toBe(
- hex(ridgeSkyFor('night', FALLBACK_VIEW).top)
+ hex(ridgeSkyFor(AUTO, FALLBACK_VIEW).top)
);
scene?.dispose();
});
- it('does not rebuild when auto is replaced by the explicit state it already resolves to', async () => {
- const a = fakeScene();
- createRidgeScene.mockReturnValueOnce(a);
+ it('rebuilds when Auto is replaced by the named moment of the same band: live and frozen are different skies, and the same pick again is not a rebuild', async () => {
+ const [a, b] = [fakeScene(), fakeScene()];
+ createRidgeScene.mockReturnValueOnce(a).mockReturnValueOnce(b);
const scene = await startBackgroundScene(config, caps, { canvas });
- setSkyState('night');
+ setSkyChoice(NIGHT);
await flush();
- expect(a.dispose).not.toHaveBeenCalled();
- expect(createRidgeScene).toHaveBeenCalledOnce();
+ expect(a.dispose).toHaveBeenCalledOnce();
+ expect(createRidgeScene).toHaveBeenCalledTimes(2);
+ setSkyChoice(NIGHT);
+ await flush();
+ expect(createRidgeScene).toHaveBeenCalledTimes(2);
scene?.dispose();
});
it('starts on the stored state', async () => {
- setSkyState('night');
+ setSkyChoice(NIGHT);
createRidgeScene.mockReturnValue(fakeScene());
const scene = await startBackgroundScene(config, caps, { canvas });
expect(hex(createRidgeScene.mock.calls[0][0].sky.top)).toBe(
- hex(ridgeSkyFor('night', FALLBACK_VIEW).top)
+ hex(ridgeSkyFor(NIGHT, FALLBACK_VIEW).top)
);
scene?.dispose();
});
@@ -135,11 +173,11 @@ describe('startBackgroundScene follows the sky state', () => {
const second = fakeScene();
createRidgeScene.mockReturnValueOnce(first).mockReturnValueOnce(second);
const scene = await startBackgroundScene(config, caps, { canvas });
- setSkyState('day');
+ setSkyChoice(NOON);
await flush();
expect(first.dispose).toHaveBeenCalledOnce();
expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe(
- hex(ridgeSkyFor('day', FALLBACK_VIEW).top)
+ hex(ridgeSkyFor(NOON, FALLBACK_VIEW).top)
);
scene?.dispose();
expect(second.dispose).toHaveBeenCalledOnce();
@@ -149,12 +187,12 @@ describe('startBackgroundScene follows the sky state', () => {
const [a, b] = [fakeScene(), fakeScene()];
createRidgeScene.mockReturnValueOnce(a).mockReturnValueOnce(b);
const started = startBackgroundScene(config, caps, { canvas });
- setSkyState('day');
+ setSkyChoice(NOON);
const scene = await started;
await flush();
expect(createRidgeScene).toHaveBeenCalledTimes(2);
expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe(
- hex(ridgeSkyFor('day', FALLBACK_VIEW).top)
+ hex(ridgeSkyFor(NOON, FALLBACK_VIEW).top)
);
expect(a.dispose).toHaveBeenCalledOnce();
scene?.dispose();
@@ -165,12 +203,12 @@ describe('startBackgroundScene follows the sky state', () => {
const [a, b, c] = [fakeScene(), fakeScene(), fakeScene()];
createRidgeScene.mockReturnValueOnce(a).mockReturnValueOnce(b).mockReturnValueOnce(c);
const scene = await startBackgroundScene(config, caps, { canvas });
- setSkyState('day');
+ setSkyChoice(NOON);
await flush();
expect(b.login).not.toHaveBeenCalled();
scene?.login();
expect(b.login).toHaveBeenCalledOnce();
- setSkyState('dusk');
+ setSkyChoice(DUSK);
await flush();
expect(c.login).toHaveBeenCalledOnce();
scene?.dispose();
@@ -183,11 +221,11 @@ describe('startBackgroundScene follows the sky state', () => {
const onActive = vi.fn();
const scene = await startBackgroundScene(config, caps, { canvas, onInactive, onActive });
expect(onInactive).not.toHaveBeenCalled();
- setSkyState('day');
+ setSkyChoice(NOON);
await flush();
expect(onInactive).toHaveBeenCalledOnce();
expect(onActive).not.toHaveBeenCalled();
- setSkyState('dusk');
+ setSkyChoice(DUSK);
await flush();
expect(onActive).toHaveBeenCalledOnce();
expect(onInactive).toHaveBeenCalledOnce();
@@ -198,7 +236,7 @@ describe('startBackgroundScene follows the sky state', () => {
createRidgeScene.mockReturnValueOnce(fakeScene()).mockReturnValueOnce(null);
const onInactive = vi.fn();
const scene = await startBackgroundScene(config, caps, { canvas, onInactive });
- setSkyState('day');
+ setSkyChoice(NOON);
scene?.dispose();
await flush();
expect(onInactive).not.toHaveBeenCalled();
@@ -210,7 +248,7 @@ describe('startBackgroundScene follows the sky state', () => {
const scene = await startBackgroundScene(config, caps, { canvas });
scene?.dispose();
scene?.dispose();
- setSkyState('day');
+ setSkyChoice(NOON);
await flush();
expect(createRidgeScene).toHaveBeenCalledOnce();
expect(first.dispose).toHaveBeenCalledOnce();
@@ -219,7 +257,7 @@ describe('startBackgroundScene follows the sky state', () => {
it('builds nothing for a rebuild that is disposed before it starts', async () => {
createRidgeScene.mockReturnValueOnce(fakeScene()).mockReturnValueOnce(fakeScene());
const scene = await startBackgroundScene(config, caps, { canvas });
- setSkyState('day');
+ setSkyChoice(NOON);
scene?.dispose();
await flush();
expect(createRidgeScene).toHaveBeenCalledOnce();
@@ -229,13 +267,13 @@ describe('startBackgroundScene follows the sky state', () => {
const scenes = [fakeScene(), fakeScene(), fakeScene()];
scenes.forEach((s) => createRidgeScene.mockReturnValueOnce(s));
const scene = await startBackgroundScene(config, caps, { canvas });
- setSkyState('day');
- setSkyState('dusk');
+ setSkyChoice(NOON);
+ setSkyChoice(DUSK);
await flush();
// The sky last built is dusk's, and it is the live scene: a login reaches it and nothing else.
const built = createRidgeScene.mock.calls.length;
expect(hex(createRidgeScene.mock.calls[built - 1][0].sky.top)).toBe(
- hex(ridgeSkyFor('dusk', FALLBACK_VIEW).top)
+ hex(ridgeSkyFor(DUSK, FALLBACK_VIEW).top)
);
const live = scenes[built - 1];
scene?.login();
@@ -253,13 +291,13 @@ describe('startBackgroundScene follows the sky state', () => {
createRidgeScene.mockReturnValueOnce(fakeScene()).mockReturnValueOnce(fakeScene());
createRidgeScene.mockReturnValue(fakeScene());
const scene = await startBackgroundScene(config, caps, { canvas });
- setSkyState('day');
- setSkyState('dusk');
+ setSkyChoice(NOON);
+ setSkyChoice(DUSK);
await flush();
// The initial build and one rebuild, for dusk; day's rebuild stood down before building anything.
expect(createRidgeScene).toHaveBeenCalledTimes(2);
expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe(
- hex(ridgeSkyFor('dusk', FALLBACK_VIEW).top)
+ hex(ridgeSkyFor(DUSK, FALLBACK_VIEW).top)
);
scene?.dispose();
});
@@ -268,19 +306,19 @@ describe('startBackgroundScene follows the sky state', () => {
// change finished loading, was found stale and was never made (so it never showed or spoke), and only the newest sky was announced.
const changeAfter = async (ticks: number) => {
createRidgeScene.mockReset();
- setSkyState('auto');
+ setSkyChoice(AUTO);
const [a, b, c] = [fakeScene(), fakeScene(), fakeScene()];
createRidgeScene.mockReturnValueOnce(a).mockReturnValueOnce(b).mockReturnValueOnce(c);
const onActive = vi.fn();
const scene = await startBackgroundScene(config, caps, { canvas, onActive });
- setSkyState('day');
+ setSkyChoice(NOON);
await microtasks(ticks);
- setSkyState('dusk');
+ setSkyChoice(DUSK);
await flush();
const at = `at ${ticks} microtasks`;
const built = createRidgeScene.mock.calls.length;
expect(hex(createRidgeScene.mock.calls[built - 1][0].sky.top), at).toBe(
- hex(ridgeSkyFor('dusk', FALLBACK_VIEW).top)
+ hex(ridgeSkyFor(DUSK, FALLBACK_VIEW).top)
);
// The newest build is live, every earlier one disposed exactly once, and only the live one is shown.
const live = [a, b, c][built - 1];
@@ -313,7 +351,7 @@ describe('startBackgroundScene follows the sky state', () => {
createScene.mockReturnValue(inner);
const scene = await startBackgroundScene({ ...config, style: 'raymarch' }, caps, { canvas });
expect(scene).toBe(inner);
- setSkyState('day');
+ setSkyChoice(NOON);
await flush();
expect(createScene).toHaveBeenCalledOnce();
});
@@ -369,6 +407,200 @@ describe('the ridge planes', () => {
scene?.dispose();
});
+ it('awaits the first arc of tiles round the heading before the scene is made, and anchors a new place at its rest azimuth', async () => {
+ served();
+ resetHeading();
+ const d = loader();
+ createRidgeScene.mockReturnValue(fakeScene());
+ d.ctl.hold = true;
+ const started = startBackgroundScene(config, caps, { canvas });
+ await flush();
+ expect(createRidgeScene).not.toHaveBeenCalled(); // the tiles are not made yet
+ expect(d.ctl.made).toHaveLength(1);
+ const arc = d.ctl.made[0].ensure.mock.calls[0][0];
+ expect((arc.fromDeg + arc.toDeg) / 2).toBeCloseTo(214, 0); // the Vienna rest azimuth, nothing having turned the view
+ expect(arc.toDeg - arc.fromDeg).toBeCloseTo(HFOV_MAX_DEG, 6);
+ await d.release();
+ (await started)?.dispose();
+ expect(createRidgeScene).toHaveBeenCalledOnce();
+ // A rebuild for a new sky keeps the heading the view has turned to.
+ hold(100, performance.now());
+ forgetManifests();
+ (await startBackgroundScene(config, caps, { canvas }))?.dispose();
+ const second = d.ctl.made[1].ensure.mock.calls[0][0];
+ expect((second.fromDeg + second.toDeg) / 2).toBeCloseTo(100, 0);
+ });
+
+ it('bounds the speed from the anchor: while the first tiles load the view turns no faster than the place sustains, whatever speed is stored', async () => {
+ served({ '/public/ridge/vienna-abc123abc123/manifest.json': wireManifest({ camera: { r_max_m: 98.2, r_max_forward_m: 205.4 } }, 3, 32) }); // a ring whose gate holds fewer than all its tiles
+ resetHeading();
+ resetCamera();
+ setCamera({ mode: 'both', speedDegPerS: 12 }, 0);
+ const clock = vi.spyOn(performance, 'now').mockReturnValue(1_000);
+ const d = loader();
+ let seen = NaN;
+ createRidgeScene.mockImplementation(() => {
+ seen = poseAt(performance.now()).h;
+ return fakeScene();
+ });
+ d.ctl.hold = true;
+ const started = startBackgroundScene(config, caps, { canvas });
+ await flush();
+ clock.mockReturnValue(6_000); // the tiles took five seconds
+ await d.release();
+ (await started)?.dispose();
+ const slow = maxSpeed(d.ctl.made[0].manifest, 'both');
+ expect(slow).toBeLessThan(12);
+ expect(seen).toBeCloseTo(214 + 5 * slow, 6); // not 214 + 60
+ clock.mockRestore();
+ resetCamera();
+ });
+
+ describe('a scene start with a deadline', () => {
+ /** A backdrop whose first arc never settles, holding `tiles` tiles. */
+ const silent = (tiles: number) => {
+ const made: any[] = [];
+ createBackdrop.mockImplementation((manifest: unknown) => {
+ const bd = {
+ manifest,
+ dispose: vi.fn(),
+ litTiles: () => Array.from({ length: tiles }, (_, tile) => ({ tile, card: 0, canvas: {} })),
+ ensure: vi.fn(() => new Promise(() => undefined)),
+ };
+ made.push(bd);
+ return bd;
+ });
+ return made;
+ };
+ const real = () => new Promise((r) => setImmediate(r));
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('draws with the tiles it has when the server is slow, and the rest fill in: the backdrop is the scene, not a finished load', async () => {
+ served();
+ resetHeading();
+ const made = silent(2);
+ createRidgeScene.mockReturnValue(fakeScene());
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+ const started = startBackgroundScene(config, caps, { canvas });
+ for (let i = 0; i < 20; i += 1) await real();
+ expect(made).toHaveLength(1);
+ expect(createRidgeScene).not.toHaveBeenCalled(); // the first arc is still out
+ await vi.advanceTimersByTimeAsync(PREPARE_DEADLINE_MS - 1);
+ for (let i = 0; i < 5; i += 1) await real();
+ expect(createRidgeScene).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(1);
+ const scene = await started;
+ expect(createRidgeScene).toHaveBeenCalledOnce();
+ expect(createRidgeScene.mock.calls[0][0].backdrop).toBe(made[0]); // the scene holds it, and goes on asking it for the arcs ahead
+ expect(made[0].dispose).not.toHaveBeenCalled();
+ scene?.dispose();
+ });
+
+ it('a rebuild has no deadline: the scene it replaces stays up, planes are not told to fail, and the new scene is swapped in when its tiles arrive', async () => {
+ served();
+ resetHeading();
+ const scenes: any[] = [];
+ createRidgeScene.mockImplementation(() => {
+ const s = fakeScene();
+ scenes.push(s);
+ return s;
+ });
+ const onPlanesFail = vi.fn();
+ loader();
+ const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail });
+ expect(scenes).toHaveLength(1);
+ let held = 0;
+ let arrive = () => undefined as void;
+ const made: any[] = [];
+ createBackdrop.mockImplementation((manifest: unknown) => {
+ const bd = {
+ manifest,
+ dispose: vi.fn(),
+ litTiles: () => Array.from({ length: held }, (_, tile) => ({ tile, card: 0, canvas: {} })),
+ ensure: vi.fn(
+ () =>
+ new Promise((resolve) => {
+ arrive = () => {
+ held = 1;
+ resolve();
+ };
+ })
+ ),
+ };
+ made.push(bd);
+ return bd;
+ });
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+ setSkyChoice(NOON);
+ for (let i = 0; i < 20; i += 1) await real();
+ expect(made).toHaveLength(1);
+ await vi.advanceTimersByTimeAsync(10 * PREPARE_DEADLINE_MS);
+ for (let i = 0; i < 5; i += 1) await real();
+ expect(createRidgeScene).toHaveBeenCalledOnce(); // still the first scene
+ expect(scenes[0].dispose).not.toHaveBeenCalled();
+ expect(made[0].dispose).not.toHaveBeenCalled();
+ expect(onPlanesFail).not.toHaveBeenCalled();
+ arrive();
+ for (let i = 0; i < 20; i += 1) await real();
+ expect(createRidgeScene).toHaveBeenCalledTimes(2);
+ expect(createRidgeScene.mock.calls[1][0].backdrop).toBe(made[0]);
+ expect(scenes[0].dispose).toHaveBeenCalledOnce();
+ expect(onPlanesFail).not.toHaveBeenCalled();
+ scene?.dispose();
+ });
+
+ it('is the sky alone, told once, when the deadline passes with no tile held, and lets go of the backdrop and its requests', async () => {
+ served();
+ resetHeading();
+ const made = silent(0);
+ createRidgeScene.mockReturnValue(fakeScene());
+ const onPlanesFail = vi.fn();
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+ const started = startBackgroundScene(config, caps, { canvas, onPlanesFail });
+ for (let i = 0; i < 20; i += 1) await real();
+ await vi.advanceTimersByTimeAsync(PREPARE_DEADLINE_MS);
+ const scene = await started;
+ expect(createRidgeScene).toHaveBeenCalledOnce();
+ expect(createRidgeScene.mock.calls[0][0].backdrop).toBeUndefined();
+ expect(made[0].dispose).toHaveBeenCalledOnce();
+ expect(onPlanesFail).toHaveBeenCalledOnce();
+ scene?.dispose();
+ });
+ });
+
+ it('a build that goes stale disposes the backdrop it made, and a scene that fails to be made does too', async () => {
+ served();
+ const d = loader();
+ createRidgeScene.mockReturnValue(fakeScene());
+ const scene = await startBackgroundScene(config, caps, { canvas });
+ d.ctl.hold = true;
+ setSkyChoice(NOON); // stale once the next choice lands
+ await flush();
+ const day = d.ctl.pending.splice(0);
+ setSkyChoice(DUSK);
+ await flush();
+ const dusk = d.ctl.pending.splice(0);
+ dusk.forEach((s) => s());
+ await flush();
+ day.forEach((s) => s());
+ await flush();
+ const [, dayBackdrop, duskBackdrop] = d.ctl.made;
+ expect(dayBackdrop.dispose).toHaveBeenCalledOnce();
+ expect(duskBackdrop.dispose).not.toHaveBeenCalled(); // it is the live scene's
+ scene?.dispose();
+ createRidgeScene.mockImplementationOnce(() => {
+ throw new Error('boom');
+ });
+ d.ctl.hold = false;
+ const onCompileFail = vi.fn();
+ forgetManifests();
+ await startBackgroundScene(config, caps, { canvas, onCompileFail });
+ expect(onCompileFail).toHaveBeenCalled();
+ expect(d.ctl.made[d.ctl.made.length - 1].dispose).toHaveBeenCalledOnce();
+ });
+
it('config place picks the index entry; an unknown id falls back to the default', async () => {
served();
loader();
@@ -380,6 +612,89 @@ describe('the ridge planes', () => {
expect(createRidgeScene.mock.calls[1][0].backdrop.manifest.view.place.id).toBe('vienna');
});
+ it("makes the manifest's place the sky's place, so the ink and the scene read one place; a failed load makes it the drawn fallback's", async () => {
+ served();
+ loader();
+ createRidgeScene.mockReturnValue(fakeScene());
+ setSkyPlace(undefined);
+ (await startBackgroundScene({ ...config, place: 'graz' }, caps, { canvas }))?.dispose();
+ expect(getSkyPlace()?.id).toBe('graz');
+ expect(getSkyPlace()?.tz).toBe('Europe/Vienna');
+ forgetManifests();
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => ({ ok: false, status: 404, json: async () => ({}) }))
+ );
+ setSkyPlace(undefined);
+ (await startBackgroundScene(config, caps, { canvas }))?.dispose();
+ expect(getSkyPlace()).toEqual(FALLBACK_VIEW.place);
+ });
+
+ it('a manifest that fails to load: the ink follows the drawn fallback sky, and Auto still ticks', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => ({ ok: false, status: 404, json: async () => ({}) }))
+ );
+ createRidgeScene.mockReturnValue(fakeScene());
+ setSkyPlace(undefined);
+ setSkyChoice(NOON);
+ const scene = await startBackgroundScene(config, caps, { canvas });
+ try {
+ const opts = createRidgeScene.mock.calls[0][0];
+ expect(opts.sky.physical.view).toBe(FALLBACK_VIEW);
+ expect(getSkyPlace()).toEqual(FALLBACK_VIEW.place);
+ expect(getResolvedSkyState()).toBe('day');
+ expect(getResolvedSkyState()).toBe(skyBand(opts.sky.physical.sun.elevation));
+ } finally {
+ scene?.dispose();
+ }
+ // Auto crosses dusk with the place the fallback scene drew.
+ setSkyChoice(AUTO);
+ vi.useFakeTimers();
+ try {
+ let now = atSolarTime(17, 0);
+ setSkyClock(() => now);
+ const heard = vi.fn();
+ const off = subscribe(heard);
+ now = atSolarTime(18, 10);
+ vi.advanceTimersByTime(60_000);
+ expect(heard).toHaveBeenCalledWith('dusk');
+ off();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('cards that fail on a place that is not the fallback: the sky and the ink are at the one place, the fallback', async () => {
+ const fuji = {
+ ...(wireManifest() as any).place,
+ id: 'fuji',
+ lat: 35.36,
+ lon: 138.73,
+ tz: 'Asia/Tokyo',
+ };
+ served({ '/public/ridge/vienna-abc123abc123/manifest.json': wireManifest({ place: fuji }) });
+ const { ctl } = loader();
+ ctl.fail = true;
+ createRidgeScene.mockReturnValue(fakeScene());
+ setSkyPlace(undefined);
+ setSkyChoice(NOON);
+ const scene = await startBackgroundScene(config, caps, { canvas });
+ try {
+ const opts = createRidgeScene.mock.calls[0][0];
+ expect(opts.backdrop).toBeUndefined();
+ expect(opts.sky.physical.view).toBe(FALLBACK_VIEW);
+ expect(getSkyPlace()).toEqual(FALLBACK_VIEW.place);
+ expect(getResolvedSkyState()).toBe(skyBand(opts.sky.physical.sun.elevation));
+ // The next key, made before the next build, is for the view that is drawn: the place does not flip back to the manifest's.
+ setSkyChoice(DUSK);
+ await flush();
+ expect(getSkyPlace()).toEqual(FALLBACK_VIEW.place);
+ } finally {
+ scene?.dispose();
+ }
+ });
+
const skyOnly = async (onPlanesFail = vi.fn(), onCompileFail = vi.fn()) => {
createRidgeScene.mockReturnValue(fakeScene());
const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onCompileFail });
@@ -420,7 +735,7 @@ describe('the ridge cards failing', () => {
const onCompileFail = vi.fn();
const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onCompileFail });
expect(createRidgeScene.mock.calls[0][0].backdrop).toBeUndefined();
- setSkyState('day');
+ setSkyChoice(NOON);
await flush();
expect(createRidgeScene).toHaveBeenCalledTimes(2);
expect(onPlanesFail).toHaveBeenCalledOnce();
@@ -448,7 +763,7 @@ describe('the ridge cards and the live scene', () => {
const onPlanesFail = vi.fn();
const onPlanesOk = vi.fn();
const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onPlanesOk });
- setSkyState('day');
+ setSkyChoice(NOON);
await flush();
expect(createRidgeScene).toHaveBeenCalledTimes(2);
expect(createRidgeScene.mock.calls.every((c) => c[0].backdrop)).toBe(true);
@@ -463,12 +778,12 @@ describe('the ridge cards and the live scene', () => {
createRidgeScene.mockReturnValue(fakeScene());
const scene = await startBackgroundScene(config, caps, { canvas });
expect(ctl.calls.map((s) => s.state)).toEqual(['night']);
- setSkyState('night'); // the sky already drawn: no rebuild, no lighting
- await flush();
- expect(ctl.calls).toHaveLength(1);
- setSkyState('day');
+ setSkyChoice(NOON);
await flush();
expect(ctl.calls.map((s) => s.state)).toEqual(['night', 'day']);
+ setSkyChoice(NOON); // the sky already drawn: no rebuild, no lighting
+ await flush();
+ expect(ctl.calls).toHaveLength(2);
expect(createRidgeScene.mock.calls[1][0].sky.physical).toBe(ctl.calls[1]);
expect(createRidgeScene.mock.calls[1][0].backdrop.manifest.view.place.id).toBe('vienna');
scene?.dispose();
@@ -480,22 +795,25 @@ describe('the ridge cards and the live scene', () => {
createRidgeScene.mockReturnValue(fakeScene());
const scene = await startBackgroundScene(config, caps, { canvas });
expect(createRidgeScene.mock.calls[0][0].lines).toBe(false);
- pickSkyState('night'); // from Auto: a choice, the same sky
- await flush();
- expect(createRidgeScene).toHaveBeenCalledTimes(1);
- pickSkyState('night'); // re-picked: the lines
+ pickSkyChoice(NIGHT); // from Auto: a choice, a frozen sky
await flush();
expect(createRidgeScene).toHaveBeenCalledTimes(2);
- expect(createRidgeScene.mock.calls[1][0].lines).toBe(true);
- pickSkyState('night');
+ expect(createRidgeScene.mock.calls[1][0].lines).toBe(false);
+ pickSkyChoice(NIGHT); // re-picked: the lines
await flush();
- expect(createRidgeScene.mock.calls[2][0].lines).toBe(false);
+ expect(createRidgeScene).toHaveBeenCalledTimes(3);
+ expect(createRidgeScene.mock.calls[2][0].lines).toBe(true);
+ pickSkyChoice(NIGHT);
+ await flush();
+ expect(createRidgeScene.mock.calls[3][0].lines).toBe(false);
scene?.dispose();
});
it('a lighting pass that throws (no WebGL2) is the sky alone, one onPlanesFail and never onCompileFail', async () => {
serve();
- loadBackdrop.mockRejectedValue(new Error('ridge: no WebGL2'));
+ createBackdrop.mockImplementation(() => {
+ throw new Error('ridge: no WebGL2');
+ });
createRidgeScene.mockReturnValue(fakeScene());
const onPlanesFail = vi.fn();
const onCompileFail = vi.fn();
@@ -508,20 +826,21 @@ describe('the ridge cards and the live scene', () => {
scene?.dispose();
});
- it("keys a rebuild by the manifest's place: the same sky state over a rebaked place rebuilds", async () => {
+ it("keys a rebuild by the manifest's place: the same sky over a rebaked place rebuilds", async () => {
serve();
loader();
const [a, b] = [fakeScene(), fakeScene()];
createRidgeScene.mockReturnValueOnce(a).mockReturnValueOnce(b);
const w = wireManifest() as any;
+ setSkyChoice(NIGHT);
const scene = await startBackgroundScene(config, caps, { canvas });
- // 'auto' at midnight and 'night' are one sky: no rebuild, while the place is the one drawn.
- setSkyState('night');
+ // The same choice, told again while the place is the one drawn: no rebuild.
+ setSkyPlace(undefined);
await flush();
expect(createRidgeScene).toHaveBeenCalledOnce();
forgetManifests();
serve({ ...w, place: { ...w.place, id: 'graz' } });
- setSkyState('auto');
+ setSkyPlace(undefined);
await flush();
expect(createRidgeScene).toHaveBeenCalledTimes(2);
expect(createRidgeScene.mock.calls[1][0].backdrop.manifest.view.place.id).toBe('graz');
@@ -563,7 +882,7 @@ describe('the ridge cards and the live scene', () => {
const at = (p: { lat: number; lon: number }) =>
weatherFromFile(
file,
- sunAt({ id: 'x', altitudeKm: 0, ...p }, new Date(Date.parse(wx.observed_at) - 5 * 60_000))
+ sunAt({ id: 'x', altitudeKm: 0, tz: 'UTC', ...p }, new Date(Date.parse(wx.observed_at) - 5 * 60_000))
.elevation
);
expect(at(FALLBACK_VIEW.place)).not.toBe(at(place));
@@ -591,7 +910,7 @@ describe('the ridge cards and the live scene', () => {
const onActive = vi.fn();
const scene = await startBackgroundScene(config, caps, { canvas, onActive });
d.ctl.hold = true;
- setSkyState('day');
+ setSkyChoice(NOON);
await flush();
expect(d.ctl.pending.length).toBeGreaterThan(0);
expect(first.dispose).not.toHaveBeenCalled();
@@ -616,7 +935,7 @@ describe('the ridge cards and the live scene', () => {
const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail });
d.ctl.hold = true;
d.ctl.fail = true;
- setSkyState('day');
+ setSkyChoice(NOON);
await flush();
scene?.dispose();
await d.release();
@@ -632,10 +951,10 @@ describe('the ridge cards and the live scene', () => {
const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail });
d.ctl.hold = true;
d.ctl.fail = true;
- setSkyState('day'); // stale: its decodes will reject
+ setSkyChoice(NOON); // stale: its decodes will reject
await flush();
d.ctl.fail = false;
- setSkyState('dusk'); // the live one: its decodes will succeed
+ setSkyChoice(DUSK); // the live one: its decodes will succeed
await flush();
const stale = d.ctl.pending.splice(0, 1);
d.ctl.pending.length = 0;
@@ -657,10 +976,10 @@ describe('the ridge cards and the live scene', () => {
const onActive = vi.fn();
const scene = await startBackgroundScene(config, caps, { canvas, onActive });
d.ctl.hold = true;
- setSkyState('day'); // stale: its decodes are held until after the newer build is live
+ setSkyChoice(NOON); // stale: its decodes are held until after the newer build is live
await flush();
const dayDecodes = d.ctl.pending.splice(0);
- setSkyState('dusk');
+ setSkyChoice(DUSK);
await flush();
const duskDecodes = d.ctl.pending.splice(0);
expect(dayDecodes.length).toBeGreaterThan(0);
@@ -690,7 +1009,7 @@ describe('the ridge cards and the live scene', () => {
const onActive = vi.fn();
const scene = await startBackgroundScene(config, caps, { canvas, onActive });
d.ctl.hold = true;
- setSkyState('day');
+ setSkyChoice(NOON);
await flush();
scene?.dispose();
await d.release();
@@ -699,21 +1018,94 @@ describe('the ridge cards and the live scene', () => {
expect(onActive).not.toHaveBeenCalled();
});
- it('a rebuild that makes no scene says nothing about planes and leaves the host inactive', async () => {
+ it('a rebuild whose scene cannot be made says nothing about planes and leaves the host inactive', async () => {
serve();
- const d = loader();
+ loader();
createRidgeScene.mockReturnValueOnce(fakeScene()).mockReturnValueOnce(null);
const onPlanesFail = vi.fn();
const onInactive = vi.fn();
const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onInactive });
- d.ctl.fail = true;
- setSkyState('day');
+ setSkyChoice(NOON);
await flush();
expect(onInactive).toHaveBeenCalledOnce();
expect(onPlanesFail).not.toHaveBeenCalled();
scene?.dispose();
});
+ it('a rebuild has no failure end: with no tile it stays pending beside the scene that is up (its loader asking again), replaces it the moment a tile is held, and the ink follows the sky drawn throughout', async () => {
+ serve();
+ const d = loader();
+ const [first, second] = [fakeScene(), fakeScene()];
+ createRidgeScene.mockReturnValueOnce(first).mockReturnValueOnce(second);
+ const [onPlanesFail, onInactive, onActive] = [vi.fn(), vi.fn(), vi.fn()];
+ setSkyChoice(NOON);
+ const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onInactive, onActive });
+ expect(scene?.drawnSky).toBe('day');
+ d.ctl.fail = true; // the link blinks for the whole pass of the rebuild
+ setSkyChoice(NIGHT);
+ await flush();
+ await flush();
+ expect(createRidgeScene).toHaveBeenCalledOnce();
+ expect(first.dispose).not.toHaveBeenCalled(); // the ridge that was fine is still up
+ expect(d.ctl.made[1].dispose).not.toHaveBeenCalled(); // and the build for the new sky is alive, not given up
+ expect(getResolvedSkyState()).toBe('night'); // the sky is announced as night
+ expect(scene?.drawnSky).toBe('day'); // the scene up draws day, and that is what the ink follows
+ expect([onPlanesFail, onInactive, onActive].map((f) => f.mock.calls.length)).toEqual([0, 0, 0]);
+ d.ctl.arrive(); // the loader's retry got a tile through
+ await flush();
+ expect(createRidgeScene).toHaveBeenCalledTimes(2);
+ expect(first.dispose).toHaveBeenCalledOnce();
+ expect(onActive).toHaveBeenCalledOnce();
+ expect(onActive).toHaveBeenCalledWith('night');
+ expect(scene?.drawnSky).toBe('night');
+ expect(onPlanesFail).not.toHaveBeenCalled();
+ scene?.dispose();
+ });
+
+ it('a pending rebuild is superseded by a newer one, which is given up at once; the newest replaces the scene', async () => {
+ serve();
+ const d = loader();
+ const [first, second] = [fakeScene(), fakeScene()];
+ createRidgeScene.mockReturnValueOnce(first).mockReturnValueOnce(second);
+ const onActive = vi.fn();
+ setSkyChoice(NOON);
+ const scene = await startBackgroundScene(config, caps, { canvas, onActive });
+ d.ctl.fail = true;
+ setSkyChoice(NIGHT);
+ await flush();
+ setSkyChoice(DUSK);
+ await flush();
+ expect(d.ctl.made[1].dispose).toHaveBeenCalledOnce();
+ expect(d.ctl.made[2].dispose).not.toHaveBeenCalled();
+ d.ctl.arrive();
+ await flush();
+ expect(createRidgeScene).toHaveBeenCalledTimes(2);
+ expect(onActive).toHaveBeenCalledOnce();
+ expect(onActive).toHaveBeenCalledWith('dusk');
+ scene?.dispose();
+ });
+
+ it('a build a newer one supersedes is given up at once: its backdrop is disposed when the newer begins, not when its own pass ends', async () => {
+ serve();
+ const d = loader();
+ createRidgeScene.mockReturnValue(fakeScene());
+ const scene = await startBackgroundScene(config, caps, { canvas });
+ d.ctl.hold = true; // a slow link: no pass ends
+ for (const choice of [NOON, DUSK, NIGHT, NOON, DUSK]) {
+ setSkyChoice(choice);
+ await flush();
+ }
+ const [live, ...builds] = d.ctl.made;
+ expect(builds).toHaveLength(5);
+ builds.slice(0, 4).forEach((b) => expect(b.dispose).toHaveBeenCalledOnce()); // all but the newest, while their requests are still out
+ expect(builds[4].dispose).not.toHaveBeenCalled();
+ expect(live.dispose).not.toHaveBeenCalled(); // the scene that is up is not theirs to give up
+ scene?.dispose();
+ expect(builds[4].dispose).toHaveBeenCalledOnce(); // and disposing the door gives up the one in flight
+ await d.release();
+ expect(createRidgeScene).toHaveBeenCalledOnce();
+ });
+
it('tells the host when the live scene loses its planes and when it gets them back', async () => {
serve();
const d = loader();
@@ -723,19 +1115,24 @@ describe('the ridge cards and the live scene', () => {
const onPlanesOk = vi.fn();
const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onPlanesOk });
expect(onPlanesFail).toHaveBeenCalledOnce();
- setSkyState('day'); // still failing: the host is not told twice
+ setSkyChoice(NOON); // still failing: the host is not told twice
await flush();
expect(onPlanesFail).toHaveBeenCalledOnce();
expect(onPlanesOk).not.toHaveBeenCalled();
d.ctl.fail = false;
- setSkyState('dusk');
+ setSkyChoice(DUSK);
await flush();
expect(onPlanesOk).toHaveBeenCalledOnce();
expect(createRidgeScene.mock.calls[2][0].backdrop).toBeDefined();
- d.ctl.fail = true;
- setSkyState('night');
+ d.ctl.fail = true; // a rebuild with no tile does not take the planes from the scene that has them: it waits
+ setSkyChoice(NIGHT);
await flush();
- expect(onPlanesFail).toHaveBeenCalledTimes(2);
+ expect(onPlanesFail).toHaveBeenCalledOnce();
+ expect(createRidgeScene).toHaveBeenCalledTimes(3);
+ d.ctl.arrive();
+ await flush();
+ expect(createRidgeScene).toHaveBeenCalledTimes(4);
+ expect(onPlanesFail).toHaveBeenCalledOnce();
scene?.dispose();
});
});
diff --git a/src/app/features/scene/index.ts b/src/app/features/scene/index.ts
index aa0493ce..de2a0693 100644
--- a/src/app/features/scene/index.ts
+++ b/src/app/features/scene/index.ts
@@ -1,24 +1,28 @@
import type { Scene, SceneOptions } from './Scene';
import { BackgroundSceneConfig, Capabilities, SceneTier, resolveTier } from './tier';
import { debugOverlaysAllowed } from './debugOverlays';
-import { getConstellationLines, getSkyState, subscribe } from './skyState';
-import type { SkyState } from './skyState';
+import { getConstellationLines, getResolvedSkyState, getSkyChoice, subscribe } from './skyState';
+import type { FixedSkyState, SkyChoice } from './ridge/skyMoment';
+import { drawnView, ensureSkyPlace, resetSkyPlanes } from './skyPlace';
import type { SkyColours } from './ridge/skyColour';
import type { Backdrop } from './ridge/Backdrop';
-import { loadManifest } from './ridge/manifest';
-import type { RidgeManifest } from './ridge/manifest';
-import { FALLBACK_VIEW } from './ridge/view';
+import { FALLBACK_VIEW, HFOV_MAX_DEG, maxSpeed } from './ridge/view';
export type { Scene, SceneStats } from './Scene';
+
+/** The scene the door returns: it also says which sky it draws now (the band of the scene that is up, not of the sky announced). */
+export interface StartedScene extends Scene {
+ readonly drawnSky: FixedSkyState | undefined;
+}
export type { SceneStyle, SceneTier } from './tier';
export type StartOptions = Omit & {
/** A shader failed to compile, or the scene chunk failed to load. The host keeps its ground. */
onCompileFail?: (e: Error) => void;
- /** A rebuild for a new sky state made no scene: the host puts the CSS ground back (as on a lost context). */
+ /** A rebuild for a new sky made no scene: the host puts the CSS ground back (as on a lost context). */
onInactive?: () => void;
- /** A rebuild made a scene again: the host lets it show. */
- onActive?: () => void;
+ /** A rebuild made a scene again: the host lets it show, over the sky that scene draws (what the page ink follows). */
+ onActive?: (sky?: FixedSkyState) => void;
/** The live scene is the sky alone because the baked ridge cards did not load (no manifest, a missing or undecodable card, no WebGL2 to light them). The host may fill the ground. Told when the live scene changes to that state, never for a build that did not win. */
onPlanesFail?: (e: Error) => void;
/** The live scene has its planes after `onPlanesFail` said it had none: the host lets go of the ground it filled. */
@@ -28,39 +32,67 @@ export type StartOptions = Omit `${import.meta.env.BASE_URL.replace(/\/$/, '')}/weather.json`;
-/**
- * The baked place's manifest, or why there is none. Its View is the one owner of the sun's place and the camera for the weather, the sky,
- * the rebuild key and the planes; a scene with no manifest has FALLBACK_VIEW.
- */
-async function manifestOf(
- config: BackgroundSceneConfig | undefined
-): Promise<{ manifest: RidgeManifest | null; fail: Error | null }> {
- try {
- return { manifest: await loadManifest(import.meta.env.BASE_URL, config?.place), fail: null };
- } catch (e) {
- return { manifest: null, fail: e instanceof Error ? e : new Error(String(e)) };
- }
-}
-
/** A scene made ready: every await is done, so `make` is synchronous and a rebuild can keep the old scene until the instant it swaps. */
interface Prepared {
make: () => Scene | null;
+ /** Let go of what was made for a scene that will never be made (a build that went stale): the backdrop's lighting context. */
+ discard: () => void;
/** Why this scene is the sky alone, when the baked planes did not load; null when it has planes or none are asked for. */
planesFail: Error | null;
+ /** The band of the sky this scene is made with: what it draws once made. */
+ sky: FixedSkyState | undefined;
}
+/** How long the first scene start waits for the first tiles, ms: past it the scene draws with the tiles it has and the rest arrive into it; with none, it is the sky alone. A rebuild over a scene with a ridge has no deadline and no failure end: the scene it replaces stays up until the new one holds tiles. */
+export const PREPARE_DEADLINE_MS = 6_000;
+
+/** Resolves when `backdrop` holds a tile (its loader retries a failed one on its own backoff) or `stop` aborts. */
+const holdsATile = (backdrop: Backdrop, stop: AbortSignal): Promise =>
+ new Promise((done) => {
+ if (backdrop.litTiles().length > 0 || stop.aborted) {
+ done();
+ return;
+ }
+ const off = backdrop.onTile(() => {
+ off();
+ done();
+ });
+ stop.addEventListener(
+ 'abort',
+ () => {
+ off();
+ done();
+ },
+ { once: true }
+ );
+ });
+
async function prepare(
config: BackgroundSceneConfig | undefined,
options: StartOptions & { tier: SceneTier; debug?: boolean },
- state: SkyState
+ choice: SkyChoice,
+ /** Nothing with a ridge is up to wait behind: the page's first scene, or a rebuild over a scene that is the sky alone. It waits against the deadline and, with no tile, is the sky alone. */
+ first: boolean,
+ superseded: AbortSignal
): Promise {
// Whatever throws in making the scene is a compile failure, as whatever throws in loading it.
+ let backdrop: Backdrop | null = null;
+ /** Give up the backdrop this build made, once: when a newer build supersedes it, or when it is not the scene's. */
+ const release = () => {
+ backdrop?.dispose();
+ backdrop = null;
+ };
+ superseded.addEventListener('abort', release, { once: true });
+ let band: FixedSkyState | undefined;
const guarded = (make: () => Scene | null): Prepared => ({
planesFail: null,
+ sky: band,
+ discard: release,
make: () => {
try {
return make();
} catch (e) {
+ release();
options.onCompileFail?.(e instanceof Error ? e : new Error(String(e)));
return null;
}
@@ -74,33 +106,55 @@ async function prepare(
return guarded(() => createScene(options));
}
const { createRidgeScene } = await import('./ridge/Ridge');
- const { manifest, fail } = await manifestOf(config);
+ const { manifest, fail } = await ensureSkyPlace(config);
await loadWeather(weatherUrl(), (manifest?.view ?? FALLBACK_VIEW).place);
- // The cards load with the scene chunk and the weather, and are lit here for this sky (once per build: a sky change comes through a rebuild, never per
- // frame), so createRidgeScene stays synchronous. Any failure, a missing WebGL2 included, is the sky alone.
- let backdrop: Backdrop | null = null;
- let sky: SkyColours | undefined;
+ // The tiles around the heading load with the scene chunk and the weather, and are lit here for this sky (a sky change comes through a rebuild), so
+ // createRidgeScene stays synchronous and the scene's first frame has its ridge; it asks for the tiles ahead as the view turns. Any failure, a missing
+ // WebGL2 included, is the sky alone, over the view the store is told of.
+ let lit: SkyColours | undefined;
let planesFail: Error | null = fail;
if (manifest) {
try {
- const manifestSky = ridgeSkyFor(state, manifest.view);
- sky = manifestSky;
- const { loadBackdrop } = await import('./ridge/Backdrop');
- backdrop = await loadBackdrop(
- manifest,
- manifestSky.physical as NonNullable
- );
- if (!backdrop) throw new Error('ridge cards did not load');
+ const manifestSky = ridgeSkyFor(choice, manifest.view);
+ band = getResolvedSkyState();
+ const { createBackdrop } = await import('./ridge/Backdrop');
+ const heading = await import('./ridge/heading');
+ backdrop = createBackdrop(manifest, manifestSky.physical as NonNullable);
+ // A place not shown before faces its rest azimuth; a rebuild for a sky keeps the heading the view has turned to. The speed is bounded from here on, not
+ // from the scene's first frame: the view does not turn further than the place sustains while the tiles load.
+ const now = performance.now();
+ heading.anchor(manifest.view.place.id, manifest.view.lookAzDeg, now, (mode) => maxSpeed(manifest, mode));
+ const { h } = heading.poseAt(now);
+ // The first arc. The first scene of a page has nothing to show meanwhile, so it waits against a deadline (a slow or silent server must not hold it back):
+ // what is held by then is drawn and the rest fills in. A rebuild has the old scene up and has no end: it waits for a tile as long as that takes, its loader asking again.
+ let timer: ReturnType | undefined;
+ try {
+ await Promise.race([
+ backdrop.ensure({ fromDeg: h - HFOV_MAX_DEG / 2, toDeg: h + HFOV_MAX_DEG / 2 }),
+ new Promise((late) => {
+ if (first) timer = setTimeout(late, PREPARE_DEADLINE_MS);
+ }),
+ ]);
+ } finally {
+ clearTimeout(timer);
+ }
+ if (!first) await holdsATile(backdrop, superseded);
+ if (superseded.aborted) throw new Error('ridge: superseded');
+ if (backdrop.litTiles().length === 0) throw new Error('ridge cards did not load');
+ lit = manifestSky;
} catch (e) {
- backdrop = null;
- sky = undefined;
+ release();
planesFail = e instanceof Error ? e : new Error(String(e));
}
}
+ const view = drawnView(backdrop ? manifest : null);
+ if (!lit) await loadWeather(weatherUrl(), view.place);
+ const sky = lit ?? ridgeSkyFor(choice, view);
+ if (!lit) band = getResolvedSkyState();
const made = guarded(() =>
createRidgeScene({
...options,
- sky: sky ?? ridgeSkyFor(state, FALLBACK_VIEW),
+ sky,
backdrop: backdrop ?? undefined,
lines: getConstellationLines(),
})
@@ -108,23 +162,23 @@ async function prepare(
return { ...made, planesFail };
} catch (e) {
options.onCompileFail?.(e instanceof Error ? e : new Error(String(e)));
- return { make: () => null, planesFail: null };
+ return { make: () => null, discard: () => undefined, planesFail: null, sky: undefined };
}
}
/**
* What a rebuild is for: the sky options the scene would be built from. A change of choice that draws the same sky
- * (Day picked while the clock says day, 'auto' to the fixed state it resolves to) is not a rebuild.
+ * (Auto picked as a named moment it already is drawing) is not a rebuild.
*/
async function skyKey(
config: BackgroundSceneConfig | undefined,
- state: SkyState
+ choice: SkyChoice
): Promise {
try {
const { loadWeather, ridgeSkyKey } = await import('./skyForState');
- const view = (await manifestOf(config)).manifest?.view ?? FALLBACK_VIEW;
+ const { view } = await ensureSkyPlace(config);
await loadWeather(weatherUrl(), view.place);
- return ridgeSkyKey(state, view);
+ return ridgeSkyKey(choice, view);
} catch {
// The chunk failed to load: no key, so every change rebuilds (and `create` reports the failure).
return null;
@@ -138,7 +192,7 @@ async function skyKey(
* "keep the CSS ground", including when that chunk fails to load (offline, stale deploy): the
* failure goes to onCompileFail and nothing throws.
*
- * The ridge scene bakes its sky once, so it follows the sky (`skyState.ts`: the choice, resolved, so 'auto' follows the clock) by
+ * The ridge scene bakes its sky once, so it follows the sky (`skyState.ts`: the choice at the place, so Auto follows the clock) by
* being rebuilt on the same canvas when it changes: the door subscribes on start and the returned
* scene's `dispose` unsubscribes. The pull-back restarts from the tree; a later `login()` is
* replayed on the new scene. The ray-march scene has one fixed dusk and ignores the state.
@@ -147,7 +201,7 @@ export async function startBackgroundScene(
config: BackgroundSceneConfig | undefined,
capabilities: Capabilities,
options: StartOptions
-): Promise {
+): Promise {
const tier = resolveTier(config, capabilities);
if (tier === 'off') return null;
const debug = debugOverlaysAllowed(config);
@@ -158,40 +212,62 @@ export async function startBackgroundScene(
if (!planesFail && planesFailed) options.onPlanesOk?.();
planesFailed = planesFail !== null;
};
- const prepared = (state: SkyState) => prepare(config, { ...options, tier, debug }, state);
- const state = getSkyState();
- const key0 = config?.style === 'raymarch' ? null : await skyKey(config, state);
- const firstReady = await prepared(state);
+ const prepared = (choice: SkyChoice, first: boolean, stop: AbortSignal) => prepare(config, { ...options, tier, debug }, choice, first, stop);
+ resetSkyPlanes();
+ const choice = getSkyChoice();
+ const key0 = config?.style === 'raymarch' ? null : await skyKey(config, choice);
+ const firstReady = await prepared(choice, true, new AbortController().signal);
const first = firstReady.make();
- if (!first || config?.style === 'raymarch') return first;
+ if (!first) return null;
+ // The ray-march scene has one fixed dusk.
+ if (config?.style === 'raymarch') return Object.assign(first, { drawnSky: 'dusk' as const });
announce(firstReady.planesFail);
let inner: Scene | null = first;
let built = key0;
+ let shown = key0; // the sky key of the scene that is up
+ let drawnSky = firstReady.sky; // the band of the scene that is up
let loggedIn = false;
let disposed = false;
let generation = 0;
- // A rebuild is for a different sky ('auto' crossing a boundary, a new choice), not for a repeat of the one drawn.
+ let building: AbortController | undefined;
+ // A rebuild is for a different sky ('auto' crossing a boundary, a new choice), not for a repeat of the one drawn. What replaces the scene that is up: a new backdrop,
+ // the moment it holds tiles (its loader asks again on its own until it does; a rebuild has no failure end); a build a newer one supersedes is given up at once (its
+ // requests aborted). A rebuild never swaps a ridge for the sky alone; only a build with no ridge up behind it (the first load, or a rebuild over the sky alone) that ends with no tile is the sky alone.
const rebuild = async () => {
// The choice can move while the key is awaited; that change has its own rebuild, so this one stands down.
- const next = getSkyState();
+ const next = getSkyChoice();
const key = await skyKey(config, next);
- if (getSkyState() !== next) return;
+ if (getSkyChoice() !== next) return;
if ((key !== null && key === built) || disposed) return;
generation += 1;
const mine = generation;
built = key;
+ building?.abort();
+ const mineAborts = new AbortController();
+ building = mineAborts;
// The old scene stays up while the next one loads; a build that is stale or after dispose is never made, so it never speaks.
- const ready = await prepared(next);
- if (disposed || mine !== generation) return;
+ const ready = await prepared(next, planesFailed, mineAborts.signal); // over a sky-only scene there is no ridge to protect: the new sky is drawn at once
+ if (disposed || mine !== generation) {
+ ready.discard();
+ return;
+ }
+ building = undefined;
+ if (ready.planesFail && !planesFailed) {
+ ready.discard();
+ built = shown;
+ return;
+ }
inner?.dispose();
inner = null;
const scene = ready.make();
inner = scene;
+ shown = key;
+ drawnSky = ready.sky;
if (scene) announce(ready.planesFail);
if (!scene) options.onInactive?.();
else {
- options.onActive?.();
+ options.onActive?.(ready.sky);
if (loggedIn) scene.login();
}
};
@@ -199,6 +275,9 @@ export async function startBackgroundScene(
// A change that landed while the first build was awaited was missed by the subscription.
rebuild();
return {
+ get drawnSky() {
+ return drawnSky;
+ },
login() {
loggedIn = true;
inner?.login();
@@ -207,6 +286,7 @@ export async function startBackgroundScene(
if (disposed) return;
disposed = true;
off();
+ building?.abort();
inner?.dispose();
inner = null;
},
diff --git a/src/app/features/scene/ridge/Backdrop.test.ts b/src/app/features/scene/ridge/Backdrop.test.ts
index bd030b85..04ee6185 100644
--- a/src/app/features/scene/ridge/Backdrop.test.ts
+++ b/src/app/features/scene/ridge/Backdrop.test.ts
@@ -1,90 +1,478 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { loadBackdrop } from './Backdrop';
-import type { LitCard } from './lightCards';
+import type { Mock } from 'vitest';
+import {
+ createBackdrop,
+ FETCH_PARALLEL,
+ FETCH_TIMEOUT_MS,
+ NotFound,
+ RETRY_FIRST_MS,
+ RETRY_MAX_MS,
+} from './Backdrop';
+import type { CardBitmaps, Lighter } from './lightCards';
import { parseManifest } from './manifest';
import { wireManifest } from './manifest.fixture';
import type { PhysicalSky } from './physicalSky';
+import { KEEP_MARGIN_TILES, LOAD_MARGIN_TILES, residentTiles, runTiles } from './ring';
+import { HFOV_MAX_DEG } from './view';
const sky = {} as PhysicalSky;
-const manifest = parseManifest(wireManifest(), '/d/');
+const manifest = parseManifest(wireManifest({}, 3, 32), '/d/'); // the ring as the baker cuts it: 32 tiles of 11.25 degrees, 3 cards
+const tileOf = (url: string) => Number(/-t(\d\d)-/.exec(url)?.[1]);
-const stubDecoder = () => {
- const made: { url: string; opts: unknown; closed: boolean }[] = [];
- vi.stubGlobal(
- 'createImageBitmap',
- vi.fn(async (blob: Blob & { url: string }, opts: unknown) => {
- if (blob.url.endsWith('card-2-geometry.webp') && fail.on) throw new Error('bad card');
- const bmp = { url: blob.url, opts, closed: false, close: () => (bmp.closed = true) };
- made.push(bmp);
- return bmp;
- })
- );
- return made;
+/** A decoder that keeps count: which bitmaps are open, which tiles are being decoded at once. */
+const rig = (fail: (url: string) => boolean = () => false, missing: (url: string) => boolean = () => false) => {
+ const fetched: string[] = [];
+ const bitmaps: { url: string; closed: boolean; close: () => void }[] = [];
+ let inFlight = new Map();
+ let mostTiles = 0;
+ let clock = 0;
+ const fetchBlob = vi.fn(async (url: string, _signal?: AbortSignal) => {
+ fetched.push(url);
+ if (missing(url)) throw new NotFound('ridge: 404');
+ if (fail(url)) throw new Error('ridge: 503');
+ return { url } as unknown as Blob;
+ });
+ const decode = vi.fn(async (blob: Blob) => {
+ const { url } = blob as unknown as { url: string };
+ const t = tileOf(url);
+ inFlight.set(t, (inFlight.get(t) ?? 0) + 1);
+ mostTiles = Math.max(mostTiles, inFlight.size);
+ await new Promise((r) => setTimeout(r, 0));
+ inFlight.set(t, (inFlight.get(t) ?? 1) - 1);
+ if (inFlight.get(t) === 0) inFlight.delete(t);
+ const b = { url, closed: false, close: () => (b.closed = true) };
+ bitmaps.push(b);
+ return b as unknown as ImageBitmap;
+ });
+ const canvases: { tile: number; card: number; width: number; height: number }[] = [];
+ const lighter = (): Lighter & { light: Mock<[CardBitmaps, number, number], HTMLCanvasElement> } => ({
+ lost: false,
+ release: vi.fn(),
+ light: vi.fn((_b: CardBitmaps, tile: number, card: number) => {
+ const c = { tile, card, width: 202, height: 100 };
+ canvases.push(c);
+ return c as unknown as HTMLCanvasElement;
+ }),
+ });
+ return {
+ fetched,
+ bitmaps,
+ fetchBlob,
+ decode,
+ canvases,
+ lighter,
+ mostTiles: () => mostTiles,
+ now: () => clock,
+ tick: (ms: number) => void (clock += ms),
+ };
};
-const fail = { on: false };
-const blobFor = async (url: string) => ({ url } as unknown as Blob);
-const lit = (m: typeof manifest): LitCard[] =>
- m.cards.map((c) => ({ canvas: {} as HTMLCanvasElement, top: c.top, h: c.h, scale: c.scale }));
+
+const urlsOfTiles = (tiles: number[]) =>
+ tiles.flatMap((t) =>
+ manifest.tiles[t].flatMap((e) => (e ? [`/d/${e.colour}`, `/d/${e.geometry}`] : []))
+ );
+const arc72 = (centre: number) => ({ fromDeg: centre - 36, toDeg: centre + 36 });
afterEach(() => {
- fail.on = false;
- vi.unstubAllGlobals();
+ vi.useRealTimers();
});
-describe('loadBackdrop', () => {
- it('fetches and decodes both files of every card straight, lights once, and returns the cards nearest first', async () => {
- const made = stubDecoder();
- const light = vi.fn((m: typeof manifest) => lit(m));
- const bd = await loadBackdrop(manifest, sky, { fetchBlob: blobFor, light });
- expect(bd?.cards.map((c) => c.scale)).toEqual([1.2, 1.0167, 1.005]);
- expect(bd?.manifest).toBe(manifest);
- expect(made.map((b) => b.url).sort()).toEqual(
- [0, 1, 2].flatMap((i) => [`/d/card-${i}-colour.webp`, `/d/card-${i}-geometry.webp`]).sort()
+describe('createBackdrop', () => {
+ it('fetches nothing until it is asked, and then the files of the tiles of the arc and one tile beyond it, straight, and no others', async () => {
+ const r = rig();
+ const bd = createBackdrop(manifest, sky, { ...r, lighter: r.lighter });
+ expect(r.fetchBlob).not.toHaveBeenCalled();
+ await bd.ensure(arc72(180));
+ const want = residentTiles(manifest.view, 180, 36 + LOAD_MARGIN_TILES * 11.25).map((t) => t.tile);
+ expect(want).toHaveLength(10);
+ expect([...r.fetched].sort()).toEqual(urlsOfTiles(want).sort());
+ expect(bd.litTiles().map((t) => t.tile).sort((a, b) => a - b)).toEqual(
+ want.flatMap((t) => manifest.tiles[t].flatMap((e, card) => (e ? [t] : []))).sort((a, b) => a - b)
);
- made.forEach((b) =>
- expect(b.opts).toEqual({ premultiplyAlpha: 'none', colorSpaceConversion: 'none' })
- );
- expect(light).toHaveBeenCalledOnce();
- // Handed over in manifest order, each card its own pair.
- const given = light.mock.calls[0] as unknown as [
- unknown,
- { colour: { url: string }; geometry: { url: string } }[],
- unknown
- ];
- expect(given[1].map((p) => [p.colour.url, p.geometry.url])).toEqual(
- [0, 1, 2].map((i) => [`/d/card-${i}-colour.webp`, `/d/card-${i}-geometry.webp`])
- );
- expect(given[2]).toBe(sky);
+ r.bitmaps.forEach((b) => expect(b.closed).toBe(true));
});
- it('closes the decoded bitmaps once they are lit', async () => {
- const made = stubDecoder();
- await loadBackdrop(manifest, sky, { fetchBlob: blobFor, light: lit });
- expect(made).toHaveLength(6);
- expect(made.every((b) => b.closed)).toBe(true);
+ it('lights each card of a tile that holds it, naming the tile and the card, and leaves a card the tile lacks out', async () => {
+ const r = rig();
+ const lighter = r.lighter();
+ const bd = createBackdrop(manifest, sky, { ...r, lighter: () => lighter });
+ await bd.ensure({ fromDeg: 208, toDeg: 209 });
+ const calls = lighter.light.mock.calls.map((c) => [c[1], c[2]]);
+ // Tile 17 holds three cards; tile 18 (18 % 4 = 2) holds only two: card 2 is absent there.
+ expect(calls).toContainEqual([17, 2]);
+ expect(calls).toContainEqual([18, 1]);
+ expect(calls).not.toContainEqual([18, 2]);
+ const colourOf = (c: unknown[]) => (c[0] as { colour: { url: string } }).colour.url;
+ expect(lighter.light.mock.calls.every((c) => colourOf(c).includes(`-t${String(c[1]).padStart(2, '0')}-`))).toBe(true);
});
- it('is null when any one card will not decode, lights nothing and closes what it decoded', async () => {
- const made = stubDecoder();
- fail.on = true;
- const light = vi.fn(lit);
- expect(await loadBackdrop(manifest, sky, { fetchBlob: blobFor, light })).toBeNull();
- expect(light).not.toHaveBeenCalled();
+ it('decodes with straight alpha and no colour management by default', async () => {
+ const made: unknown[] = [];
+ vi.stubGlobal(
+ 'createImageBitmap',
+ vi.fn(async (_b: unknown, opts: unknown) => {
+ made.push(opts);
+ return { close: () => undefined };
+ })
+ );
+ const r = rig();
+ const bd = createBackdrop(manifest, sky, { fetchBlob: r.fetchBlob, lighter: r.lighter });
+ await bd.ensure({ fromDeg: 0, toDeg: 1 });
expect(made.length).toBeGreaterThan(0);
- expect(made.every((b) => b.closed)).toBe(true);
+ made.forEach((o) => expect(o).toEqual({ premultiplyAlpha: 'none', colorSpaceConversion: 'none' }));
+ vi.unstubAllGlobals();
});
- it('is null when a file is missing, and when the lighting pass throws', async () => {
- const made = stubDecoder();
- const gone = async (url: string) => {
- if (url.endsWith('card-1-colour.webp')) throw new Error('ridge: 404');
- return blobFor(url);
+ it('decodes one tile at a time', async () => {
+ const r = rig();
+ const bd = createBackdrop(manifest, sky, { ...r, lighter: r.lighter });
+ await bd.ensure(arc72(100));
+ expect(r.decode).toHaveBeenCalled();
+ expect(r.mostTiles()).toBe(1);
+ });
+
+ it('sweeping the heading through 360 degrees fetches each tile once on the way and never holds more than the baker counted', async () => {
+ const r = rig();
+ const bd = createBackdrop(manifest, sky, { ...r, lighter: r.lighter });
+ const N = runTiles(manifest.view, HFOV_MAX_DEG, manifest.camera.rMaxM, 1000);
+ const per = new Map();
+ let most = 0;
+ for (let h = 0; h <= 360; h += 6) {
+ await bd.ensure(arc72(h));
+ most = Math.max(most, new Set(bd.litTiles().map((t) => t.tile)).size);
+ }
+ // Card 0 is in every tile: its colour file counts a tile's fetches.
+ for (const u of r.fetched) {
+ if (u.includes('card-0-') && u.endsWith('colour.webp')) per.set(tileOf(u), (per.get(tileOf(u)) ?? 0) + 1);
+ }
+ expect(per.size).toBe(32);
+ // The tiles round north are held at the start and wanted again at the end of the turn: those two fetches aside, every tile came once.
+ const start = new Set(residentTiles(manifest.view, 0, 36 + LOAD_MARGIN_TILES * 11.25).map((t) => t.tile));
+ for (const [t, n] of per) expect(n, `tile ${t}`).toBe(start.has(t) ? 2 : 1);
+ expect(most).toBeLessThanOrEqual(N);
+ expect(most).toBeLessThanOrEqual(
+ Math.ceil((72 + 2 * KEEP_MARGIN_TILES * 11.25) / 11.25) + 1
+ );
+ });
+
+ it('lets go of the tiles beyond the arc and two tiles of margin, and makes nothing twice that it still holds', async () => {
+ const r = rig();
+ const lighter = r.lighter();
+ const bd = createBackdrop(manifest, sky, { ...r, lighter: () => lighter });
+ await bd.ensure(arc72(180));
+ const first = bd.litTiles();
+ const lit = lighter.light.mock.calls.length;
+ await bd.ensure(arc72(180)); // the same arc again: nothing is made
+ expect(lighter.light.mock.calls.length).toBe(lit);
+ await bd.ensure(arc72(0)); // the far side of the ring: everything held before is let go
+ first.forEach((t) => expect(t.canvas.width).toBe(0));
+ const keep = new Set(
+ residentTiles(manifest.view, 0, 36 + KEEP_MARGIN_TILES * 11.25).map((t) => t.tile)
+ );
+ expect(bd.litTiles().length).toBeGreaterThan(0);
+ bd.litTiles().forEach((t) => {
+ expect(keep.has(t.tile)).toBe(true);
+ expect(t.canvas.width).toBe(202);
+ });
+ });
+
+ it('a tile that fails is absent, not an error, and is made at the next ensure', async () => {
+ let broken = true;
+ const r = rig((u) => broken && tileOf(u) === 16 && u.includes('card-1-'));
+ const lighter = r.lighter();
+ const bd = createBackdrop(manifest, sky, { ...r, lighter: () => lighter });
+ await expect(bd.ensure({ fromDeg: 180, toDeg: 181 })).resolves.toBeUndefined();
+ expect(bd.litTiles().some((t) => t.tile === 16)).toBe(false); // a tile is lit whole or not at all
+ expect(bd.litTiles().some((t) => t.tile === 15)).toBe(true);
+ r.bitmaps.forEach((b) => expect(b.closed).toBe(true));
+ broken = false;
+ r.tick(RETRY_FIRST_MS); // after its pause
+ await bd.ensure({ fromDeg: 180, toDeg: 181 });
+ expect(bd.litTiles().filter((t) => t.tile === 16).map((t) => t.card).sort()).toEqual([0, 1, 2]);
+ });
+
+ it('a lighting pass that throws is a failed tile too', async () => {
+ const r = rig();
+ const lighter = r.lighter();
+ lighter.light.mockImplementation(() => {
+ throw new Error('no 2D context');
+ });
+ const bd = createBackdrop(manifest, sky, { ...r, lighter: () => lighter });
+ await expect(bd.ensure({ fromDeg: 0, toDeg: 1 })).resolves.toBeUndefined();
+ expect(bd.litTiles()).toEqual([]);
+ r.bitmaps.forEach((b) => expect(b.closed).toBe(true));
+ });
+
+ it('is made only where the cards can be lit: a lighter that throws is the caller to answer for', () => {
+ const r = rig();
+ expect(() =>
+ createBackdrop(manifest, sky, {
+ ...r,
+ lighter: () => {
+ throw new Error('ridge: no WebGL2');
+ },
+ })
+ ).toThrow(/WebGL2/);
+ });
+
+ it('makes another lighter after the context is lost, and releases the spent one', async () => {
+ const r = rig();
+ const first = r.lighter();
+ const second = r.lighter();
+ const make = vi.fn().mockReturnValueOnce(first).mockReturnValueOnce(second);
+ const bd = createBackdrop(manifest, sky, { ...r, lighter: make });
+ await bd.ensure({ fromDeg: 0, toDeg: 1 });
+ expect(first.light).toHaveBeenCalled();
+ (first as { lost: boolean }).lost = true;
+ await bd.ensure({ fromDeg: 180, toDeg: 181 });
+ expect(make).toHaveBeenCalledTimes(2);
+ expect(first.release).toHaveBeenCalled();
+ expect(second.light).toHaveBeenCalled();
+ });
+
+ it('takes the newest arc when asked again mid-pass, and answers every caller once everything it could make is made', async () => {
+ const r = rig();
+ const bd = createBackdrop(manifest, sky, { ...r, lighter: r.lighter });
+ const a = bd.ensure(arc72(40));
+ const b = bd.ensure(arc72(220));
+ await Promise.all([a, b]);
+ const held = new Set(bd.litTiles().map((t) => t.tile));
+ residentTiles(manifest.view, 220, 36 + LOAD_MARGIN_TILES * 11.25).forEach((t) => expect(held.has(t.tile)).toBe(true));
+ });
+
+ it('tells a listener of each tile as it is made, not of a tile that failed, and no longer once it stops listening or the backdrop is disposed', async () => {
+ const r = rig((url) => tileOf(url) === 17);
+ const bd = createBackdrop(manifest, sky, { ...r, lighter: r.lighter });
+ const seen: number[] = [];
+ const off = bd.onTile(() => seen.push(bd.litTiles().length));
+ await bd.ensure({ fromDeg: 180, toDeg: 181 }); // tiles 15 to 17 and the margin: 17 fails
+ const made = new Set(bd.litTiles().map((t) => t.tile));
+ expect(made.has(17)).toBe(false);
+ expect(seen).toHaveLength(made.size); // one call per tile held, each with its tile already held
+ seen.forEach((n, i) => expect(n).toBeGreaterThan(i));
+ off();
+ await bd.ensure({ fromDeg: 0, toDeg: 1 });
+ expect(seen).toHaveLength(made.size);
+ const late = vi.fn();
+ bd.onTile(late);
+ bd.dispose();
+ await bd.ensure({ fromDeg: 100, toDeg: 101 });
+ expect(late).not.toHaveBeenCalled();
+ });
+
+ it('disposes: the canvases are dropped, the lighting context released, and a later ensure does nothing', async () => {
+ const r = rig();
+ const lighter = r.lighter();
+ const bd = createBackdrop(manifest, sky, { ...r, lighter: () => lighter });
+ await bd.ensure({ fromDeg: 0, toDeg: 1 });
+ const lit = bd.litTiles().map((t) => t.canvas);
+ expect(lit.length).toBeGreaterThan(0);
+ bd.dispose();
+ bd.dispose();
+ expect(lighter.release).toHaveBeenCalledTimes(1);
+ lit.forEach((c) => expect(c.width).toBe(0));
+ expect(bd.litTiles()).toEqual([]);
+ const n = r.fetched.length;
+ await bd.ensure({ fromDeg: 100, toDeg: 101 });
+ expect(r.fetched).toHaveLength(n);
+ });
+
+ it('asks for the tile under the view first and then outward, not outward from the middle of the sweep', async () => {
+ const r = rig();
+ const bd = createBackdrop(manifest, sky, { ...r, lighter: r.lighter });
+ // The sweep spans 144 to 216 degrees; the view is at its start, in tile 13 (146.25 to 157.5).
+ await bd.ensure({ fromDeg: 144, toDeg: 216 }, { fromDeg: 150, toDeg: 152 });
+ const order = [...new Set(r.fetched.map(tileOf))];
+ expect(order[0]).toBe(13);
+ const dist = (t: number) => Math.abs(t * 11.25 + 5.625 - 151);
+ expect(order.map(dist)).toEqual([...order.map(dist)].sort((a, b) => a - b));
+ // Without a view it is outward from the middle of the arc, as before.
+ const r2 = rig();
+ const bd2 = createBackdrop(manifest, sky, { ...r2, lighter: r2.lighter });
+ await bd2.ensure({ fromDeg: 144, toDeg: 216 });
+ expect([15, 16]).toContain(tileOf(r2.fetched[0])); // the two tiles either side of 180
+ });
+
+ it('asks for the files of the tiles of an arc a few at a time, not one after another and not all at once', async () => {
+ let active = 0;
+ let most = 0;
+ const r = rig();
+ const fetchBlob = vi.fn(async (url: string) => {
+ active += 1;
+ most = Math.max(most, active);
+ await new Promise((go) => setTimeout(go, 5));
+ active -= 1;
+ return { url } as unknown as Blob;
+ });
+ const bd = createBackdrop(manifest, sky, { ...r, fetchBlob, lighter: r.lighter });
+ await bd.ensure(arc72(180)); // ten tiles of up to six files each
+ expect(most).toBeGreaterThan(1); // the files are not asked for one after another
+ expect(most).toBe(FETCH_PARALLEL); // and the pipe is kept full while there is more to ask, and no fuller
+ expect(bd.litTiles().length).toBeGreaterThan(20);
+ });
+
+ it('keeps the cap while the arc changes under it: aborted passes hand their slots on, and a pass begun at once takes none of them', async () => {
+ vi.useFakeTimers();
+ let live = 0;
+ let most = 0;
+ const r = rig();
+ const fetchBlob = vi.fn(
+ (url: string, signal?: AbortSignal) =>
+ new Promise((resolve, reject) => {
+ live += 1;
+ most = Math.max(most, live);
+ const timer = setTimeout(() => {
+ live -= 1;
+ resolve({ url } as unknown as Blob);
+ }, 300);
+ signal?.addEventListener('abort', () => {
+ clearTimeout(timer);
+ live -= 1;
+ reject(new Error('aborted'));
+ });
+ })
+ );
+ const bd = createBackdrop(manifest, sky, { ...r, fetchBlob, lighter: r.lighter });
+ for (let i = 0; i < 60; i += 1) {
+ void bd.ensure({ fromDeg: 100 + i * 2, toDeg: 180 + i * 2 }); // a turning view: a new arc every half second, each one aborting the last
+ await vi.advanceTimersByTimeAsync(500);
+ }
+ expect(fetchBlob.mock.calls.length).toBeGreaterThan(FETCH_PARALLEL * 3); // the loader worked the whole time
+ expect(most).toBeLessThanOrEqual(FETCH_PARALLEL);
+ });
+
+ it('gives up on a request that never answers, draws absence and goes on, and aborts it', async () => {
+ vi.useFakeTimers();
+ const r = rig();
+ const signals: AbortSignal[] = [];
+ const fetchBlob = vi.fn((url: string, signal?: AbortSignal) => {
+ if (tileOf(url) === 17) {
+ signals.push(signal as AbortSignal);
+ return new Promise(() => undefined); // never settles, and ignores its signal
+ }
+ return Promise.resolve({ url } as unknown as Blob);
+ });
+ const bd = createBackdrop(manifest, sky, { ...r, fetchBlob, lighter: r.lighter });
+ const done = bd.ensure({ fromDeg: 200, toDeg: 201 });
+ await vi.advanceTimersByTimeAsync(FETCH_TIMEOUT_MS + 10);
+ await done;
+ expect(signals.length).toBeGreaterThan(0);
+ signals.forEach((s) => expect(s.aborted).toBe(true));
+ expect(bd.litTiles().some((t) => t.tile === 17)).toBe(false);
+ expect(bd.litTiles().some((t) => t.tile === 16 || t.tile === 18)).toBe(true);
+ });
+
+ it('does not ask again at once for a tile that failed: the pause doubles to a cap, so a tile that keeps failing is a few requests a minute', async () => {
+ const r = rig((u) => tileOf(u) === 19);
+ const bd = createBackdrop(manifest, sky, { ...r, lighter: r.lighter });
+ const tile19 = () =>
+ r.fetched.filter((u) => tileOf(u) === 19 && u.includes('card-0-') && u.endsWith('colour.webp')).length;
+ await bd.ensure({ fromDeg: 215, toDeg: 216 });
+ expect(tile19()).toBe(1);
+ // The scene asks every half second for a minute: the broken tile is asked for about as often as its pauses allow.
+ for (let t = 0; t < 120; t += 1) {
+ r.tick(500);
+ await bd.ensure({ fromDeg: 215, toDeg: 216 });
+ }
+ expect(tile19()).toBeGreaterThan(3);
+ expect(tile19()).toBeLessThanOrEqual(8); // 1 s, 2 s, 4 s, 8 s, 16 s, 32 s: not 121
+ expect(RETRY_MAX_MS).toBeGreaterThanOrEqual(32_000);
+ expect(bd.litTiles().some((t) => t.tile === 19)).toBe(false);
+ });
+
+ describe('the loader asks again on its own', () => {
+ /** Nothing waits on a timer but the retry: files and decodes settle at once. */
+ const quick = (fail: (url: string) => boolean) => {
+ const r = rig(fail);
+ const decode = vi.fn(async (blob: Blob) => ({ url: (blob as unknown as { url: string }).url, close: () => undefined }) as unknown as ImageBitmap);
+ return { r, deps: { ...r, decode, lighter: r.lighter } };
};
- expect(await loadBackdrop(manifest, sky, { fetchBlob: gone, light: lit })).toBeNull();
- const boom = () => {
- throw new Error('no WebGL2');
- };
- expect(await loadBackdrop(manifest, sky, { fetchBlob: blobFor, light: boom })).toBeNull();
- expect(made.every((b) => b.closed)).toBe(true);
+ const tile = (r: ReturnType, t: number) => r.fetched.filter((u) => tileOf(u) === t && u.includes('card-1-') && u.endsWith('colour.webp')).length;
+
+ it('a tile that failed is asked for again at the end of its pause with no one asking, and the listener hears it arrive', async () => {
+ vi.useFakeTimers();
+ let broken = true;
+ const { r, deps } = quick((u) => broken && tileOf(u) === 16 && u.includes('card-1-'));
+ const bd = createBackdrop(manifest, sky, deps);
+ const heard = vi.fn();
+ bd.onTile(heard);
+ await bd.ensure({ fromDeg: 180, toDeg: 181 }); // the only ask: a still has no timer to make another
+ expect(bd.litTiles().some((t) => t.tile === 16)).toBe(false);
+ const arrived = heard.mock.calls.length;
+ broken = false;
+ r.tick(RETRY_FIRST_MS - 1);
+ await vi.advanceTimersByTimeAsync(RETRY_FIRST_MS - 1);
+ expect(tile(r, 16)).toBe(1); // not before its pause
+ r.tick(1);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(bd.litTiles().filter((t) => t.tile === 16).map((t) => t.card).sort()).toEqual([0, 1, 2]);
+ expect(heard.mock.calls.length).toBe(arrived + 1);
+ const n = r.fetched.length;
+ r.tick(10 * RETRY_MAX_MS);
+ await vi.advanceTimersByTimeAsync(10 * RETRY_MAX_MS);
+ expect(r.fetched.length).toBe(n); // nothing is left to ask for
+ bd.dispose();
+ });
+
+ it('keeps asking, on a pause that doubles, while the arc wants the tile, and stops when the arc has moved on or the backdrop is gone', async () => {
+ vi.useFakeTimers();
+ const { r, deps } = quick((u) => tileOf(u) === 19);
+ const bd = createBackdrop(manifest, sky, deps);
+ await bd.ensure({ fromDeg: 215, toDeg: 216 });
+ expect(tile(r, 19)).toBe(1);
+ for (let s = 0; s < 120; s += 1) {
+ r.tick(1000);
+ await vi.advanceTimersByTimeAsync(1000);
+ }
+ expect(tile(r, 19)).toBeGreaterThan(3);
+ expect(tile(r, 19)).toBeLessThanOrEqual(8); // 1 s, 2 s, 4 s, 8 s, 16 s, 32 s: a few a minute, not one a second
+ await bd.ensure({ fromDeg: 0, toDeg: 1 }); // the view has gone the other way: tile 19 is no longer wanted
+ const asked = tile(r, 19);
+ for (let s = 0; s < 300; s += 1) {
+ r.tick(1000);
+ await vi.advanceTimersByTimeAsync(1000);
+ }
+ expect(tile(r, 19)).toBe(asked);
+ await bd.ensure({ fromDeg: 215, toDeg: 216 });
+ bd.dispose();
+ const n = r.fetched.length;
+ r.tick(10 * RETRY_MAX_MS);
+ await vi.advanceTimersByTimeAsync(10 * RETRY_MAX_MS);
+ expect(r.fetched.length).toBe(n); // a disposed backdrop asks for nothing
+ });
+ });
+
+ it('does not ask again for a file the server does not have: the tile is drawn with the cards that came', async () => {
+ const r = rig(
+ () => false,
+ (u) => tileOf(u) === 19 && u.includes('card-1-')
+ );
+ const bd = createBackdrop(manifest, sky, { ...r, lighter: r.lighter });
+ const tile19 = () => r.fetched.filter((u) => tileOf(u) === 19).length;
+ await bd.ensure({ fromDeg: 215, toDeg: 216 });
+ const first = tile19();
+ expect(first).toBeGreaterThan(0);
+ expect(bd.litTiles().filter((t) => t.tile === 19).map((t) => t.card)).toEqual([0, 2]); // card 1 is absent, the others are there
+ for (let t = 0; t < 40; t += 1) {
+ r.tick(5_000);
+ await bd.ensure({ fromDeg: 215, toDeg: 216 });
+ }
+ expect(tile19()).toBe(first); // not once more while the tile stays
+ r.bitmaps.forEach((b) => expect(b.closed).toBe(true));
+ });
+
+ it('gives up on a tile every file of which is gone, without a retry loop, and draws its neighbours', async () => {
+ const r = rig(
+ () => false,
+ (u) => tileOf(u) === 19
+ );
+ const bd = createBackdrop(manifest, sky, { ...r, lighter: r.lighter });
+ await bd.ensure({ fromDeg: 215, toDeg: 216 });
+ const n = r.fetched.length;
+ r.tick(RETRY_MAX_MS * 2);
+ await bd.ensure({ fromDeg: 215, toDeg: 216 });
+ expect(r.fetched.length).toBe(n);
+ expect(bd.litTiles().some((t) => t.tile === 19)).toBe(false);
+ expect(bd.litTiles().some((t) => t.tile === 18)).toBe(true);
});
});
diff --git a/src/app/features/scene/ridge/Backdrop.ts b/src/app/features/scene/ridge/Backdrop.ts
index 5e2eca3d..13ef8d79 100644
--- a/src/app/features/scene/ridge/Backdrop.ts
+++ b/src/app/features/scene/ridge/Backdrop.ts
@@ -1,55 +1,286 @@
-// The ridge cards the scene composes, lit: every card's two files fetched and decoded exactly as the baker wrote them, then lit once for the sky
-// (`lightCards.ts`). Failure is a value (null), never a throw.
+// The ridge cards the scene composes, lit, kept resident by tile: the one owner of which tiles of the ring are in memory. `ensure` is told the arc of
+// azimuth the view is about to need; it fetches and decodes the tiles of that arc it does not hold, one tile at a time, lights each card of a tile
+// (`lightCards.ts`, one lighter for the one sky this backdrop was made for) and drops the tiles beyond the arc and its margin. The files of the tiles to make
+// are fetched a few at a time, each against a timeout. A tile that fails is a tile the scene draws as absence, asked for again by the loader itself after a growing
+// pause, for as long as the arc last asked for wants it (whoever asked, a scene's timer or none: a still has no timer); a file the server says is not there (404) is
+// not asked for again while its tile stays: the scene draws the cards of the tile that came. Nothing is thrown into the scene.
import type { RidgeManifest } from './manifest';
import type { PhysicalSky } from './physicalSky';
-import { lightCards } from './lightCards';
-import type { CardBitmaps, LitCard } from './lightCards';
+import { createLighter } from './lightCards';
+import type { CardBitmaps, Lighter } from './lightCards';
+import { KEEP_MARGIN_TILES, LOAD_MARGIN_TILES, residentTiles } from './ring';
+
+/** A range of unwrapped compass azimuth, degrees, `fromDeg <= toDeg`. */
+export interface Arc {
+ fromDeg: number;
+ toDeg: number;
+}
+
+/** One card of one tile, lit: its pixels premultiplied by the card's alpha, `tileW + 2` columns by the band's rows. */
+export interface LitTile {
+ tile: number;
+ card: number;
+ canvas: HTMLCanvasElement;
+}
export interface Backdrop {
manifest: RidgeManifest;
- /** Nearest first, as the manifest lists them. */
- cards: LitCard[];
+ /**
+ * Hold the tiles of `arc` and one tile beyond it each side; let go of those past two tiles. Resolves when every tile it could make is made. They are asked for
+ * and made nearest first to `first`, the arc the view shows now (the middle of `arc` when absent), so what is on screen comes before what the sweep reaches later.
+ */
+ ensure(arc: Arc, first?: Arc): Promise;
+ /** Every card of every tile held, in no order. */
+ litTiles(): readonly LitTile[];
+ /** Hear each tile as it is made and held, however late (a still scene has no timer of its own and draws only what it held); not a tile that failed. Returns the way to stop. */
+ onTile(cb: () => void): () => void;
+ /** Let go of everything, the lighting context included. Idempotent. */
+ dispose(): void;
}
export interface BackdropDeps {
- fetchBlob: (url: string) => Promise;
- light: (manifest: RidgeManifest, bitmaps: CardBitmaps[], sky: PhysicalSky) => LitCard[];
+ /** Rejects with `NotFound` when the server has no such file, with anything else for a failure that may pass. `signal` aborts it. */
+ fetchBlob: (url: string, signal?: AbortSignal) => Promise;
+ decode: (blob: Blob) => Promise;
+ lighter: (manifest: RidgeManifest, sky: PhysicalSky) => Lighter;
+ /** The clock (ms) the pauses between a tile's attempts run on. */
+ now: () => number;
}
-const fetchBlob = async (url: string): Promise => {
- const res = await fetch(url);
+/** A file the server answered 404 or 410 for: asking again will not make it appear. */
+export class NotFound extends Error {}
+
+/** Requests in flight at once, over all tiles; how long one may take; the pause before a failed tile is asked for again (doubled each failure, to the cap). */
+export const FETCH_PARALLEL = 6;
+export const FETCH_TIMEOUT_MS = 15_000;
+export const RETRY_FIRST_MS = 1_000;
+export const RETRY_MAX_MS = 60_000;
+
+const fetchBlob = async (url: string, signal?: AbortSignal): Promise => {
+ const res = await fetch(url, { signal });
+ if (res.status === 404 || res.status === 410) throw new NotFound(`ridge: ${url} answered ${res.status}`);
if (!res.ok) throw new Error(`ridge: ${url} answered ${res.status}`);
return res.blob();
};
-/** Straight alpha and the file's own values: the colour card's alpha is coverage and the geometry card's channels are data, so neither may be premultiplied or colour-managed. */
+/** Straight alpha and the file's own values: the colour file's alpha is coverage and the geometry file's channels are data, so neither may be premultiplied or colour-managed. */
const decode = (blob: Blob): Promise =>
createImageBitmap(blob, { premultiplyAlpha: 'none', colorSpaceConversion: 'none' });
-export async function loadBackdrop(
+/**
+ * A backdrop for `sky`. Throws at once when the cards cannot be lit (no WebGL2, a shader that will not link): the caller makes the sky-only scene.
+ * Nothing is fetched until the first `ensure`.
+ */
+export function createBackdrop(
manifest: RidgeManifest,
sky: PhysicalSky,
deps: Partial = {}
-): Promise {
+): Backdrop {
const get = deps.fetchBlob ?? fetchBlob;
- const light = deps.light ?? lightCards;
- const open: ImageBitmap[] = [];
- try {
- const files = manifest.cards.flatMap((c) => [c.colour, c.geometry]);
- const settled = await Promise.allSettled(
- files.map(async (f) => decode(await get(`${manifest.dir}${f}`)))
+ const open = deps.decode ?? decode;
+ const makeLighter = deps.lighter ?? createLighter;
+ const now = deps.now ?? (() => (typeof performance !== 'undefined' ? performance.now() : Date.now()));
+ const { view } = manifest;
+ const tileDeg = 360 / view.tiles;
+ let lighter = makeLighter(manifest, sky);
+ const held = new Map();
+ /** Tiles that failed, when they may be asked for again and the pause after the next failure. */
+ const failed = new Map();
+ const heard = new Set<() => void>();
+ let disposed = false;
+ let running: Promise | null = null;
+ let want: { arc: Arc; first?: Arc } | null = null;
+ /** The arc last asked for: what the loader keeps its tiles for and retries for. */
+ let wanted: { arc: Arc; first?: Arc } | null = null;
+ /** Ask for the arc wanted once more: a pass ends in `schedule`, which is defined before the backdrop that can be asked. */
+ let askAgain: () => void = () => undefined;
+ let retry: ReturnType | undefined;
+ /** The pass that is on the wire: dispose gives up its requests, as a newer arc does. */
+ let current: AbortController | null = null;
+
+ const drop = (tile: number) => {
+ held.get(tile)?.forEach((t) => {
+ t.canvas.width = 0;
+ t.canvas.height = 0;
+ });
+ held.delete(tile);
+ };
+
+ // At most FETCH_PARALLEL requests at once over every tile, each with its own timeout (the signal is passed on, and a fetch that ignores it is still given up on).
+ // A slot is handed straight to the next waiter, so `active` never dips for a request issued in between to slip into; it falls only when nobody waits.
+ let active = 0;
+ const queue: (() => void)[] = [];
+ const request = async (url: string, signal: AbortSignal): Promise => {
+ if (active < FETCH_PARALLEL) active += 1;
+ else await new Promise((go) => queue.push(go));
+ try {
+ if (signal.aborted) throw new Error('ridge: aborted');
+ return await new Promise((resolve, reject) => {
+ const ctl = new AbortController();
+ const stop = () => {
+ ctl.abort();
+ reject(new Error(`ridge: ${url} ${signal.aborted ? 'aborted' : 'timed out'}`));
+ };
+ const timer = setTimeout(stop, FETCH_TIMEOUT_MS);
+ signal.addEventListener('abort', stop, { once: true });
+ get(url, ctl.signal).then(resolve, reject).finally(() => {
+ clearTimeout(timer);
+ signal.removeEventListener('abort', stop);
+ });
+ });
+ } finally {
+ const next = queue.shift();
+ if (next) next();
+ else active -= 1;
+ }
+ };
+
+ /** The files of a tile, each settled on its own: a blob, or what became of it (`gone`: the server has none; `failed`: it may pass). */
+ type Fetched = { blob: Blob } | 'gone' | 'failed';
+ async function fetchTile(tile: number, signal: AbortSignal): Promise<{ card: number; files: Fetched[] }[]> {
+ const cards = manifest.tiles[tile].flatMap((e, card) => (e ? [{ e, card }] : []));
+ return Promise.all(
+ cards.map(async ({ e, card }) => ({
+ card,
+ files: await Promise.all(
+ [e.colour, e.geometry].map(
+ (f): Promise =>
+ request(`${manifest.dir}${f}`, signal).then(
+ (blob) => ({ blob }),
+ (err: unknown) => (err instanceof NotFound ? 'gone' : 'failed')
+ )
+ )
+ ),
+ }))
);
- settled.forEach((s) => s.status === 'fulfilled' && open.push(s.value));
- const failed = settled.find((s) => s.status === 'rejected');
- if (failed) throw (failed as PromiseRejectedResult).reason;
- const bitmaps = manifest.cards.map((_, i) => ({
- colour: open[2 * i],
- geometry: open[2 * i + 1],
- }));
- return { manifest, cards: light(manifest, bitmaps, sky) };
- } catch {
- return null;
- } finally {
- open.forEach((b) => b.close?.());
}
+
+ /**
+ * Decode and light what a tile's fetch brought, one card at a time, and hold the tile. A card with a file the server does not have is left out (the scene
+ * draws the others); a tile with any file that failed otherwise is not kept (it is lit whole or not at all) and is asked for again after a pause.
+ */
+ async function make(tile: number, fetched: { card: number; files: Fetched[] }[]): Promise {
+ const made: LitTile[] = [];
+ const bitmaps: ImageBitmap[] = [];
+ try {
+ if (fetched.some((f) => f.files.includes('failed'))) throw new Error('ridge: a file of the tile failed');
+ if (lighter.lost) {
+ lighter.release();
+ lighter = makeLighter(manifest, sky);
+ }
+ for (const { card, files } of fetched) {
+ if (files.includes('gone')) continue;
+ const [colour, geometry] = await Promise.all(
+ files.map(async (f) => {
+ const b = await open((f as { blob: Blob }).blob);
+ bitmaps.push(b);
+ return b;
+ })
+ );
+ if (disposed) return;
+ made.push({ tile, card, canvas: lighter.light({ colour, geometry }, tile, card) });
+ }
+ held.set(tile, made);
+ failed.delete(tile);
+ heard.forEach((cb) => cb());
+ } catch {
+ made.forEach((t) => (t.canvas.width = 0));
+ const pause = Math.min(RETRY_MAX_MS, (failed.get(tile)?.pause ?? RETRY_FIRST_MS / 2) * 2);
+ failed.set(tile, { until: now() + pause, pause });
+ } finally {
+ bitmaps.forEach((b) => b.close?.());
+ }
+ }
+
+ async function pass(arc: Arc, first?: Arc): Promise {
+ const centre = (arc.fromDeg + arc.toDeg) / 2;
+ const from0 = first ? (first.fromDeg + first.toDeg) / 2 : centre;
+ const half = (arc.toDeg - arc.fromDeg) / 2;
+ const near = residentTiles(view, centre, half + LOAD_MARGIN_TILES * tileDeg);
+ const keep = new Set(
+ residentTiles(view, centre, half + KEEP_MARGIN_TILES * tileDeg).map((r) => r.tile)
+ );
+ [...held.keys()].filter((t) => !keep.has(t)).forEach(drop);
+ // The tile under the view first, then outward along the sweep: what the view needs now comes before what it needs next.
+ const from = (r: { tile: number; turn: number }) => r.turn * 360 + r.tile * tileDeg + tileDeg / 2;
+ const order = [...near]
+ .sort((a, b) => Math.abs(from(a) - from0) - Math.abs(from(b) - from0))
+ .map((r) => r.tile)
+ .filter((t) => !held.has(t) && (failed.get(t)?.until ?? 0) <= now());
+ // Every tile's files are asked for at once (the requests queue to FETCH_PARALLEL, in this order) and made one tile at a time as they arrive.
+ const stop = new AbortController();
+ current = stop;
+ try {
+ const asked = order.map((tile) => fetchTile(tile, stop.signal));
+ for (const [i, tile] of order.entries()) {
+ const fetched = await asked[i];
+ if (disposed) return;
+ await make(tile, fetched);
+ // A newer arc is waiting: take it up now, with this tile made, instead of finishing an arc the view has left.
+ if (want && held.has(tile)) return;
+ }
+ } finally {
+ stop.abort(); // what is still on the wire is for an arc the view has left
+ if (current === stop) current = null;
+ }
+ }
+
+ /** When the arc wanted holds a tile that failed, ask for it again at the end of its pause: the loader's own retry, the same for every tier. */
+ function schedule(): void {
+ clearTimeout(retry);
+ retry = undefined;
+ if (disposed || !wanted) return;
+ const { arc } = wanted;
+ const half = (arc.toDeg - arc.fromDeg) / 2 + LOAD_MARGIN_TILES * tileDeg;
+ const due = residentTiles(view, (arc.fromDeg + arc.toDeg) / 2, half)
+ .filter((r) => !held.has(r.tile) && failed.has(r.tile))
+ .map((r) => (failed.get(r.tile) as { until: number }).until);
+ if (!due.length) return;
+ retry = setTimeout(() => {
+ retry = undefined;
+ askAgain();
+ }, Math.max(0, Math.min(...due) - now()));
+ }
+
+ async function loop(): Promise {
+ while (want && !disposed) {
+ const { arc, first } = want;
+ want = null;
+ await pass(arc, first);
+ }
+ schedule();
+ }
+
+ const api: Backdrop = {
+ manifest,
+ ensure(arc, first) {
+ if (disposed) return Promise.resolve();
+ wanted = { arc, first };
+ want = wanted;
+ running ??= loop().finally(() => {
+ running = null;
+ });
+ return running;
+ },
+ litTiles: () => [...held.values()].flat(),
+ onTile(cb) {
+ heard.add(cb);
+ return () => heard.delete(cb);
+ },
+ dispose() {
+ if (disposed) return;
+ disposed = true;
+ heard.clear();
+ wanted = null;
+ want = null;
+ clearTimeout(retry);
+ current?.abort(); // a scene that did not wait for its tiles, or was replaced, leaves nothing asking for them
+ [...held.keys()].forEach(drop);
+ lighter.release();
+ },
+ };
+ askAgain = () => {
+ if (wanted) api.ensure(wanted.arc, wanted.first).catch(() => undefined);
+ };
+ return api;
}
diff --git a/src/app/features/scene/ridge/Ridge.test.ts b/src/app/features/scene/ridge/Ridge.test.ts
index f2918637..1f462a5e 100644
--- a/src/app/features/scene/ridge/Ridge.test.ts
+++ b/src/app/features/scene/ridge/Ridge.test.ts
@@ -1,16 +1,33 @@
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { createRidgeScene } from './Ridge';
+import { createRidgeScene, RESIDENCY_MS } from './Ridge';
import { valueNoise, hash2 } from './noise';
import { FrameSampler, frameStats, SLOW_P95_MS, WARMUP_FRAMES, WINDOW_MS } from './probe';
import type { SkyColours } from './skyColour';
import { nightBodies } from './nightBodies';
import { sunAt } from './sunAt';
import { makePhysicalSky, paintSky as paintPhysicalSky } from './physicalSky';
+import { sunOfBand } from './skyTestkit';
import { startBackgroundScene } from '../index';
-import { parseManifest } from './manifest';
+import { parseIndex, parseManifest } from './manifest';
import { ELSEWHERE_VIEW, wireManifest } from './manifest.fixture';
-import type { Backdrop } from './Backdrop';
-import { cardMotion, FALLBACK_VIEW, windowFor } from './view';
+import type { Arc, Backdrop, LitTile } from './Backdrop';
+import type { Mock } from 'vitest';
+import { cardArc, cardPose, FALLBACK_VIEW, HFOV_MAX_DEG, maxSpeed, offsetRange, SEGMENT_S, windowFor } from './view';
+import { LATENESS_S, plateCamera, plateSize, SLACK_MIN_DEG, slackFor } from './skyTurn';
+import { ringAzimuth, sunColumns, sunInColumn } from './lightCards';
+import { norm, residentTiles } from './ring';
+import { anchor, hold, poseAt, resetHeading, settledAt, STAGE_MS } from './heading';
+import { effectiveMode, getCamera, isHeld, resetCamera, setCamera } from '../cameraState';
+
+/** The two stages of the ease of a mode pick (the angle, then the offset, or the other way round). */
+const EASE_MS = 2 * STAGE_MS;
+/** A card's pose as the heading owner has the view at `t`: what the rig lays the card out from. */
+const posed = (m: Parameters[0], card: number, t: number, w: Parameters[5]) => {
+ const p = poseAt(t);
+ return cardPose(m, card, p.h, p.phi, p.r, w);
+};
describe('noise', () => {
it('is deterministic and in [0, 1)', () => {
@@ -107,9 +124,16 @@ function fakeEl(tag = 'div') {
this.children.push(c);
return c;
},
+ insertBefore(c: any, before: any) {
+ c.parentElement = this;
+ this.children.splice(this.children.indexOf(before), 0, c);
+ return c;
+ },
animate: vi.fn((keyframes: any[], options: any) => {
const a: any = {
currentTime: 0,
+ /** The clock it was issued at (the mocked `performance.now`). */
+ at: performance.now(),
keyframes,
options,
onfinish: null,
@@ -140,6 +164,12 @@ const draws: string[] = [];
const images: unknown[][] = [];
/** Every RGBA grid the host canvas was painted from (the small canvas's putImageData). */
const painted: Uint8ClampedArray[] = [];
+/** Where each sun disc (its gradient's centre) and each body (an arc) was drawn into a sky canvas, in that canvas's device px, in paint order. */
+const suns: number[][] = [];
+const arcs: number[][] = [];
+/** Where each star of the twinkle overlay was drawn (its canvas's device px), in draw order; and what happens while a sky is painted (a paint takes time). */
+const twinks: number[][] = [];
+let onPaint: (() => void) | undefined;
function ctx() {
const c: any = {
createLinearGradient: () => ({ addColorStop: vi.fn() }),
@@ -168,13 +198,17 @@ function ctx() {
}),
putImageData(img: { data: Uint8ClampedArray }) {
painted.push(img.data);
+ onPaint?.();
},
beginPath() {},
moveTo() {},
stroke() {
draws.push('line');
},
- createRadialGradient: () => ({ addColorStop: vi.fn() }),
+ createRadialGradient: (x: number, y: number) => {
+ suns.push([x, y]);
+ return { addColorStop: vi.fn() };
+ },
lineTo() {},
closePath() {},
// Stars: arc+fill is one draw. A context that has cleared a rect is the twinkle overlay's.
@@ -182,8 +216,10 @@ function ctx() {
c.overlay = true;
draws.push('clear');
},
- arc() {
+ arc(x: number, y: number) {
draws.push(c.overlay ? 'twinkle' : 'star');
+ if (!c.overlay) arcs.push([x, y]);
+ else twinks.push([x, y]);
c.arcing = true;
},
fill: () => {
@@ -213,6 +249,10 @@ beforeEach(() => {
draws.length = 0;
images.length = 0;
painted.length = 0;
+ suns.length = 0;
+ arcs.length = 0;
+ twinks.length = 0;
+ onPaint = undefined;
search = '';
motion = { matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn() };
doc = Object.assign(new EventTarget(), {
@@ -227,6 +267,7 @@ beforeEach(() => {
innerWidth: 400,
innerHeight: 800,
matchMedia: () => motion,
+ clearTimeout,
location: {
get search() {
return search;
@@ -283,9 +324,11 @@ describe('createRidgeScene', () => {
it("paints the sky through the camera of the physical sky's own View, not a default one", () => {
const { canvas } = host();
- const physical = makePhysicalSky('day', new Date('2026-06-21T10:40:00Z'), 0, ELSEWHERE_VIEW);
+ const physical = makePhysicalSky(sunOfBand(ELSEWHERE_VIEW.place, 'day', new Date('2026-06-21T10:40:00Z')), 0, ELSEWHERE_VIEW);
const s = createRidgeScene({ canvas, tier: 'full', sky: { ...DAY, physical } })!;
- const want = paintPhysicalSky(physical, 400, 800, windowFor(ELSEWHERE_VIEW, 400, 800).camera);
+ // a live sky is a plate about the heading, which with no ridge is the View's rest azimuth
+ const win = windowFor(ELSEWHERE_VIEW, 400, 800);
+ const want = paintPhysicalSky(physical, plateSize(win, 400, 800, 2, SLACK_MIN_DEG).cssW, 800, plateCamera(win, ELSEWHERE_VIEW.lookAzDeg, SLACK_MIN_DEG));
expect(painted).toHaveLength(1);
expect(Array.from(painted[0])).toEqual(Array.from(want.data));
s.dispose();
@@ -385,11 +428,14 @@ describe('the starfield in the scene', () => {
const count = (kind: string) => draws.filter((d) => d === kind).length;
// A moonless-horizon night over Vienna (the moon is 17 degrees below it): the real stars of that moment, and no moon to count as an arc.
const t = new Date('2026-12-04T00:00:00Z');
- const physical = makePhysicalSky('night', t, 0, FALLBACK_VIEW, sunAt(FALLBACK_VIEW.place, t));
+ const physical = makePhysicalSky(sunAt(FALLBACK_VIEW.place, t), 0, FALLBACK_VIEW);
const night: SkyColours = { ...DAY, physical };
- const N = nightBodies(
+ const view400 = windowFor(FALLBACK_VIEW, 400, 800);
+ /** The stars of a still, painted through the viewport's own camera, and of a live plate, painted through the viewport's plus the slack each side. */
+ const N = nightBodies(physical, paintPhysicalSky(physical, 400, 800, view400.camera), false).stars.length;
+ const NPLATE = nightBodies(
physical,
- paintPhysicalSky(physical, 400, 800, windowFor(FALLBACK_VIEW, 400, 800).camera),
+ paintPhysicalSky(physical, plateSize(view400, 400, 800, 2, SLACK_MIN_DEG).cssW, 800, plateCamera(view400, FALLBACK_VIEW.lookAzDeg, SLACK_MIN_DEG)),
false
).stars.length;
const hear = (name: string) => {
@@ -402,17 +448,18 @@ describe('the starfield in the scene', () => {
it('bakes every star once into the sky; per frame only the overlay is touched', () => {
const { parent, canvas } = host();
const s = createRidgeScene({ canvas, tier: 'full', sky: night })!;
- expect(count('star')).toBe(N);
+ expect(count('star')).toBe(NPLATE);
expect(painted).toHaveLength(1); // the physical sky's one grid
- expect(parent.children[1].anims).toHaveLength(0); // the overlay, above the sky
+ const plate = parent.children[1]; // one element over the host canvas: the sky and, above it, the twinkle canvas
+ expect(plate.children.map((c: any) => c.tag)).toEqual(['canvas', 'canvas']);
expect(parent.children).toHaveLength(2);
const before = baked();
runFrames(16.7, 300); // 5 s at 60 fps; the overlay repaints at 20 fps
expect(baked()).toBe(before);
expect(count('clear')).toBeGreaterThan(60);
expect(count('clear')).toBeLessThanOrEqual(101);
- // each pass paints at most SLOTS stars, each as its cover and the star again
- expect(count('twinkle')).toBeLessThanOrEqual(count('clear') * 64);
+ // the schedule runs over the catalogue and the plate has a share of it: SLOTS of the plate's stars twinkle on average, each drawn as its cover and the star again
+ expect(count('twinkle')).toBeLessThanOrEqual(count('clear') * 64 * 2);
expect(count('twinkle')).toBeGreaterThan(0);
s.dispose();
});
@@ -486,7 +533,7 @@ describe('the starfield in the scene', () => {
const s = createRidgeScene({ canvas, tier: 'full', sky: night })!;
runFrames(100, 100);
expect(parent.children).toEqual([canvas]);
- expect(count('star')).toBe(N);
+ expect(count('star')).toBe(NPLATE + N); // the plate's, then the still's own in the host canvas
expect(rafQueue).toHaveLength(0);
s.dispose();
});
@@ -503,9 +550,9 @@ describe('the starfield in the scene', () => {
describe('rain in the scene', () => {
const rainy = (w: number): SkyColours => ({
...DAY,
- physical: makePhysicalSky('day', new Date('2026-06-21T10:40:00Z'), w, FALLBACK_VIEW),
+ physical: makePhysicalSky(sunOfBand(FALLBACK_VIEW.place, 'day', new Date('2026-06-21T10:40:00Z')), w, FALLBACK_VIEW),
});
- const rainEls = (parent: any) => parent.children.filter((c: any) => c.tag === 'div');
+ const rainEls = (parent: any) => parent.children.filter((c: any) => c.tag === 'div' && c.style.backgroundImage);
it('lays one falling tile per rain layer over the sky when it rains, each slid by its own height on the compositor', () => {
const { parent, canvas } = host();
@@ -544,26 +591,56 @@ describe('rain in the scene', () => {
});
describe('the ridge cards in the scene', () => {
- const manifest = parseManifest(wireManifest(), '/d/'); // three cards, scales 1.2, 1.0167, 1.005, nearest first
- const litCards = (): Backdrop => ({
- manifest,
- cards: manifest.cards.map((c, k) => {
- const canvas = fakeEl('canvas');
- canvas.id = `card-${k}`;
- return { canvas: canvas as unknown as HTMLCanvasElement, top: c.top, h: c.h, scale: c.scale };
- }),
- });
+ const manifest = parseManifest(wireManifest(), '/d/'); // four tiles of 90 degrees, three cards (card 2 absent in tile 2); rest azimuth 214
+ const { view } = manifest;
+ const tilesOf = (): LitTile[] =>
+ manifest.tiles.flatMap((row, tile) =>
+ row.flatMap((e, card) => {
+ if (!e) return [];
+ const canvas = fakeEl('canvas');
+ canvas.id = `t${tile}c${card}`;
+ canvas.width = 1602;
+ return [{ tile, card, canvas: canvas as unknown as HTMLCanvasElement }];
+ })
+ );
+ const litCards = (): Backdrop & { ensure: Mock<[Arc, Arc?], Promise>; dispose: Mock<[], void> } => {
+ const lit = tilesOf();
+ return {
+ manifest,
+ ensure: vi.fn(async (_arc: Arc): Promise => undefined),
+ litTiles: () => lit,
+ onTile: () => () => undefined,
+ dispose: vi.fn(),
+ };
+ };
const night: SkyColours = {
...DAY,
top: [10, 14, 40],
mid: [30, 34, 80],
horizon: [60, 50, 90],
- physical: makePhysicalSky('night', new Date('2026-06-21T22:40:00Z'), 1, FALLBACK_VIEW),
+ physical: makePhysicalSky(sunOfBand(FALLBACK_VIEW.place, 'night', new Date('2026-06-21T22:40:00Z')), 1, FALLBACK_VIEW),
};
const rigOf = (parent: any) =>
parent.children.find((c: any) => c.children.some((g: any) => g.anims.length));
const win = windowFor(manifest.view, 400, 800);
- const motion400 = cardMotion(manifest, win);
+ const planeTop = 800 - win.plane.bottom - win.plane.h;
+ const horizonY = planeTop + view.horizonRow * win.plane.scale;
+ const k = win.plane.scale * view.pxPerDegH;
+ /** The animations of a box that are still running: a reissue cancels the one before it. */
+ const live = (box: any): any[] => box.anims.filter((a: any) => a.cancel.mock.calls.length === 0);
+ const mountedIds = (rig: any): string[] =>
+ rig.children.flatMap((box: any) => box.children.map((c: any) => c.id)).sort();
+ const T0 = 5_000;
+
+ beforeEach(() => {
+ resetHeading();
+ resetCamera();
+ vi.spyOn(performance, 'now').mockReturnValue(T0);
+ anchor(view.place.id, view.lookAzDeg, T0); // what index.ts prepare does before the scene is made
+ });
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
it('lays the night bodies (lines, stars, moon) in the sky before any card, so the cards occlude them', () => {
const { canvas } = host();
@@ -578,137 +655,1276 @@ describe('the ridge cards in the scene', () => {
const images = draws.map((d, i) => (d === 'image' ? i : -1)).filter((i) => i >= 0);
expect(bodies.length).toBeGreaterThan(0);
expect(draws).toContain('line'); // the lines are drawn (the sky is a night one)
- const cards = images.slice(-3); // the sky's upscale first, then the three cards, farthest first
- expect(cards).toHaveLength(3);
+ const cards = images.slice(1); // the sky's upscale first, then the cards' tiles
+ expect(cards.length).toBeGreaterThan(0);
expect(Math.max(...bodies)).toBeLessThan(Math.min(...cards));
});
- it('keeps the live sky canvas, with every body baked into it, under the twinkle canvas and the rig', () => {
+ it('keeps the live sky, with every body baked into it, and the twinkle canvas in one plate under the rig; the host canvas is not painted', () => {
const { parent, canvas } = host();
createRidgeScene({ canvas, tier: 'full', sky: { ...night }, backdrop: litCards(), lines: true });
const rig = rigOf(parent);
- const twinkle = parent.children.findIndex((c: any) => c.tag === 'canvas');
- expect(twinkle).toBeGreaterThanOrEqual(0);
- expect(parent.children.indexOf(rig)).toBeGreaterThan(twinkle);
- expect(draws.filter((d) => d === 'image')).toHaveLength(1); // only the sky's own upscale is in the host canvas: the cards are DOM above it
+ const plate = parent.children.find((c: any) => c.children.some((g: any) => g.tag === 'canvas'));
+ expect(plate.children.map((c: any) => c.tag)).toEqual(['canvas', 'canvas']); // the sky, then the twinkle canvas over it
+ expect(parent.children.indexOf(rig)).toBeGreaterThan(parent.children.indexOf(plate));
+ expect(draws.filter((d) => d === 'image')).toHaveLength(1); // only the plate's sky upscale: nothing in the host canvas, the cards are DOM above the plate
+ expect(live(plate)).toHaveLength(1); // one animation slides it
});
- it('stacks the rig after the twinkle canvas and before the rain, with no z-index and no fixed position', () => {
+ it('stacks the rig after the twinkle canvas and before the rain, with no z-index and no fixed position, and disposes the backdrop with itself', () => {
const { parent, canvas } = host();
- const s = createRidgeScene({ canvas, tier: 'full', sky: night, backdrop: litCards() })!;
+ const bd = litCards();
+ const s = createRidgeScene({ canvas, tier: 'full', sky: night, backdrop: bd })!;
const kinds = parent.children.map((c: any) => c.tag);
- expect(kinds).toEqual(['canvas', 'canvas', 'div', 'div', 'div']);
+ expect(kinds).toEqual(['canvas', 'div', 'div', 'div', 'div']); // the host canvas, the sky plate, the rig, the rain
expect(parent.children[2].children).toHaveLength(3);
parent.children.forEach((c: any) => {
expect(c.style.zIndex).toBeUndefined();
expect(c.style.position).not.toBe('fixed');
});
+ expect(bd.dispose).not.toHaveBeenCalled();
s.dispose();
expect(parent.children).toEqual([canvas]);
+ expect(bd.dispose).toHaveBeenCalledOnce();
});
- it('is one element per card, farthest first, each at its rows of the plane and its origin on the horizon centre', () => {
+ it('is one box per card, farthest first, spanning the viewport with its origin on the horizon centre, holding that card’s tiles', () => {
const { parent, canvas } = host();
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!;
const rig = rigOf(parent);
expect(rig.children.map((c: any) => c.id)).toEqual(['card-2', 'card-1', 'card-0']);
- const planeTop = 800 - win.plane.bottom - win.plane.h;
- rig.children.forEach((el: any, j: number) => {
- const card = manifest.cards[2 - j];
- expect(el.style.left).toBe(`${(400 - win.plane.w) / 2}px`);
- expect(el.style.width).toBe(`${win.plane.w}px`);
- expect(el.style.top).toBe(`${planeTop + card.top * win.plane.scale}px`);
- expect(el.style.height).toBe(`${card.h * win.plane.scale}px`);
- expect(el.style.transformOrigin).toBe(
- `${win.plane.w / 2}px ${(manifest.view.horizonRow - card.top) * win.plane.scale}px`
- );
+ rig.children.forEach((el: any) => {
+ expect(el.style.left).toBe('0');
+ expect(el.style.width).toBe('400px');
+ expect(el.style.height).toBe('800px');
+ expect(el.style.transformOrigin).toBe(`200px ${horizonY}px`);
+ });
+ // Each card's tiles are its own: the box of card 0 holds only c0 canvases.
+ rig.children.forEach((el: any) => {
+ const card = Number(el.id.slice(-1));
+ el.children.forEach((c: any) => expect(c.id.endsWith(`c${card}`)).toBe(true));
});
s.dispose();
});
- it('pans card i by scale_i x heading and scales it by scale_i, to and fro on the compositor', () => {
+ it('mounts the tiles of the arc about to be seen at their unwrapped azimuth, at their own rows of the plane, one overlap column before the interior', () => {
const { parent, canvas } = host();
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!;
- rigOf(parent).children.forEach((el: any, j: number) => {
- const k = 2 - j;
- const { scale, reachPx } = motion400.cards[k];
- const { keyframes, options } = el.anims[0];
- expect(scale).toBe(manifest.cards[k].scale);
- expect(keyframes).toEqual([
- { transform: `translate3d(${-reachPx}px,0,0) scale(${scale})` },
- { transform: `translate3d(${reachPx}px,0,0) scale(${scale})` },
- ]);
- expect(options).toMatchObject({
- duration: 75000,
- iterations: Infinity,
- direction: 'alternate',
- easing: 'ease-in-out',
- });
- });
- // The nearer the card, the further it travels.
- const reach = (j: number) => motion400.cards[2 - j].reachPx;
- expect(reach(2)).toBeGreaterThan(reach(1));
- expect(reach(1)).toBeGreaterThan(reach(0));
+ const rig = rigOf(parent);
+ // Rest azimuth 214: tile 2 (180..270). Tile 1 and tile 3 are out of sight for the next 30 s at 0.6 degrees per second.
+ expect(mountedIds(rig)).toEqual(['t2c0', 't2c1']);
+ const c0 = rig.children[2].children[0];
+ const e = manifest.tiles[2][0]!;
+ const colDeg = 360 / view.ringW;
+ const px = (v: string) => parseFloat(v);
+ expect(px(c0.style.left)).toBeCloseTo(200 + (180 - colDeg - 214) * k, 6);
+ expect(px(c0.style.top)).toBeCloseTo(horizonY + (e.top - view.horizonRow) * win.plane.scale, 6);
+ expect(px(c0.style.width)).toBeCloseTo((view.tileW + 2) * win.plane.scale, 6);
+ expect(px(c0.style.height)).toBeCloseTo(e.h * win.plane.scale, 6);
s.dispose();
});
- it('adds no rAF or timer callback of its own: the drift is Element.animate, the stars alone loop', () => {
+ it('is one animation per card, not per tile, carrying the pose the heading owner gives each second for 30 seconds', () => {
+ const { parent, canvas } = host();
+ const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!;
+ const rig = rigOf(parent);
+ rig.children.forEach((box: any) => expect(live(box)).toHaveLength(1));
+ rig.children.forEach((box: any) => {
+ const card = Number(box.id.slice(-1));
+ const { keyframes, options } = live(box)[0];
+ expect(options).toEqual({ duration: 30000, easing: 'linear', fill: 'forwards' });
+ expect(keyframes).toHaveLength(31);
+ const pose = (t: number) =>
+ posed(manifest, card, t, win);
+ [0, 1, 17, 30].forEach((n) => {
+ const p = pose(T0 + n * 1000);
+ expect(keyframes[n]).toEqual({ transform: `translate3d(${p.shiftPx}px,0,0) scale(${p.scale})` });
+ });
+ // The view turns at the viewer's 0.6 degrees per second: the container moves one pan per second, a nearer card faster.
+ });
+ const near = live(rig.children[2])[0].keyframes;
+ const far = live(rig.children[0])[0].keyframes;
+ const shift = (kf: any) => Number(/translate3d\((-?[\d.e-]+)px/.exec(kf.transform)?.[1]);
+ expect(Math.abs(shift(near[30]) - shift(near[0]))).toBeGreaterThan(Math.abs(shift(far[30]) - shift(far[0])));
+ s.dispose();
+ });
+
+ describe('the sky turns with the heading', () => {
+ const W = 400;
+ const SUN_ABOVE_REST = 5; // the sun stands this many degrees clockwise of the rest azimuth, 15 degrees up
+ const sunSky = (): SkyColours => ({
+ ...DAY,
+ physical: makePhysicalSky({ azimuth: view.lookAzDeg + SUN_ABOVE_REST, elevation: 15, time: new Date('2026-06-21T10:40:00Z') }, 0, view),
+ });
+ const nightSky = (): SkyColours => ({
+ ...DAY,
+ physical: makePhysicalSky(sunOfBand(view.place, 'night', new Date('2026-12-04T00:00:00Z')), 0, view),
+ });
+ const px = (v: string) => parseFloat(v);
+ const plateOf = (parent: any) => parent.children.find((c: any) => c.children.some((g: any) => g.tag === 'canvas'));
+ /** The plate's pan (px) at the clock `t`, read from its running animation: its keyframes are a second apart. */
+ const panAt = (plate: any, t: number): number => {
+ const a = live(plate)[0];
+ const at = (n: number) => px(/translate3d\((-?[\d.e+-]+)px/.exec(a.keyframes[n].transform)![1]);
+ const s = Math.max(0, (t - a.at) / 1000);
+ const i = Math.min(Math.floor(s), a.keyframes.length - 2);
+ return at(i) * (1 - (s - i)) + at(i + 1) * (s - i);
+ };
+ /** Where a point drawn at `x` device px of the plate's sky canvas is on the viewport at `t`, CSS px from its left edge. */
+ const onViewport = (plate: any, x: number, t: number): number => {
+ const ratio = plate.children[0].width / px(plate.style.width);
+ return px(plate.style.left) + x / ratio + panAt(plate, t);
+ };
+ const ticking = () => {
+ vi.useFakeTimers();
+ (window as any).setTimeout = setTimeout;
+ (window as any).clearTimeout = clearTimeout;
+ };
+
+ it('paints the plate about the heading the view has, not the rest azimuth, and holds it still there', () => {
+ hold(100, T0);
+ const { parent, canvas } = host();
+ const s = createRidgeScene({ canvas, tier: 'full', sky: sunSky(), backdrop: litCards() })!;
+ const sky = sunSky().physical!;
+ const wn = windowFor(view, W, 800);
+ const want = paintPhysicalSky(sky, plateSize(wn, W, 800, 2, SLACK_MIN_DEG).cssW, 800, plateCamera(wn, 100, SLACK_MIN_DEG));
+ expect(Array.from(painted[0])).toEqual(Array.from(want.data));
+ expect(painted).toHaveLength(1); // the host canvas has none: the plate is the sky
+ const plate = plateOf(parent);
+ expect(px(plate.style.left)).toBeCloseTo((W - plateSize(wn, W, 800, 2, SLACK_MIN_DEG).cssW) / 2, 9); // centred on the viewport
+ expect(panAt(plate, T0)).toBeCloseTo(0, 9);
+ s.dispose();
+ });
+
+ it('moves the sun and a catalogue star by exactly the turn times the px per degree between a plate centred on h and one centred on h + delta', () => {
+ const first = host();
+ const a = createRidgeScene({ canvas: first.canvas, tier: 'full', sky: sunSky(), backdrop: litCards() })!;
+ const sunA = [...suns[0]];
+ const plateA = plateOf(first.parent);
+ const xA = onViewport(plateA, sunA[0], T0);
+ expect(xA).toBeCloseTo(W / 2 + SUN_ABOVE_REST * k, 0); // the sun at its true azimuth against the heading
+ a.dispose();
+ suns.length = 0;
+ hold(view.lookAzDeg + 10, T0);
+ const second = host();
+ const b = createRidgeScene({ canvas: second.canvas, tier: 'full', sky: sunSky(), backdrop: litCards() })!;
+ const xB = onViewport(plateOf(second.parent), suns[0][0], T0);
+ expect(xA - xB).toBeCloseTo(10 * k, 0);
+ expect(suns[0][1]).toBe(sunA[1]); // the sun does not climb: only the azimuth turns
+ b.dispose();
+
+ });
+
+ it('moves a catalogue star by exactly the turn times the px per degree too, and the stars that stay in sight are the same ones', () => {
+ const starsAt = (heading: number) => {
+ resetHeading();
+ anchor(view.place.id, heading, T0);
+ arcs.length = 0;
+ const h = host();
+ createRidgeScene({ canvas: h.canvas, tier: 'full', sky: nightSky(), backdrop: litCards() })!.dispose();
+ return arcs.map((p) => [p[0], p[1]]);
+ };
+ const plateX = (device: number) => {
+ const wn = windowFor(view, W, 800);
+ const size = plateSize(wn, W, 800, 2, SLACK_MIN_DEG);
+ return (device / Math.floor(size.cssW * size.ratio)) * size.cssW + (W - size.cssW) / 2;
+ };
+ const here = starsAt(view.lookAzDeg).map(([x, y]) => [plateX(x), y]);
+ const turned = starsAt(view.lookAzDeg + 10).map(([x, y]) => [plateX(x), y]);
+ const inSight = here.filter(([x]) => x - 10 * k > 0 && x - 10 * k < W && x > 0 && x < W);
+ expect(inSight.length).toBeGreaterThan(3);
+ inSight.forEach(([x, y]) => {
+ // pan 0 in both: the viewport position is the plate's, and it moved left by ten degrees of pixels
+ const found = turned.find(([tx, ty]) => ty === y && Math.abs(tx - (x - 10 * k)) < 0.75);
+ expect(found).toBeDefined();
+ });
+ });
+
+ it('keeps the sun and every star where the view faces them across a re-centre: the old plate goes, a new one stands in its place, the sun moves by less than a pixel', () => {
+ ticking();
+ const now = vi.mocked(performance.now);
+ setCamera({ speedDegPerS: 4 }); // the view turns 4 degrees a second: the plate runs to 14 degrees off its centre in 3.5 s
+ const { parent, canvas } = host();
+ const s = createRidgeScene({ canvas, tier: 'full', sky: sunSky(), backdrop: litCards() })!;
+ const first = plateOf(parent);
+ const kinds = parent.children.map((c: any) => c.tag);
+ const seen = new Set([first]);
+ let last = onViewport(first, suns[suns.length - 1][0], T0);
+ for (let ms = 500; ms <= 9_000; ms += 500) {
+ now.mockReturnValue(T0 + ms);
+ vi.advanceTimersByTime(500);
+ const plate = plateOf(parent);
+ seen.add(plate);
+ const x = onViewport(plate, suns[suns.length - 1][0], T0 + ms);
+ const want = W / 2 + (view.lookAzDeg + SUN_ABOVE_REST - poseAt(T0 + ms).h) * k; // the sun's true place on the viewport
+ expect(Math.abs(x - want)).toBeLessThan(1);
+ expect(Math.abs(x - last + 4 * 0.5 * k)).toBeLessThan(1); // it moved only as the view turned (half a second of it)
+ last = x;
+ expect(parent.children.map((c: any) => c.tag)).toEqual(kinds); // the plate is replaced in its place: nothing stacks up
+ }
+ expect(seen.size).toBe(3); // 36 degrees of turn: replaced at 16 and at 32 degrees
+ expect([...seen].filter((p) => p.parentElement).length).toBe(1);
+ expect(live(plateOf(parent))).toHaveLength(1);
+ s.dispose();
+ expect(parent.children).toEqual([canvas]);
+ vi.useRealTimers();
+ });
+
+ it('keys a swapped plate from the clock after it is painted, so a paint, however long, is not lag behind the heading', () => {
+ ticking();
+ const now = vi.mocked(performance.now);
+ setCamera({ speedDegPerS: 4 });
+ const { parent, canvas } = host();
+ const s = createRidgeScene({ canvas, tier: 'full', sky: sunSky(), backdrop: litCards() })!;
+ const first = plateOf(parent);
+ const PAINT_MS = 250; // a phone: the clock runs on while the sky is painted
+ let swapped: any;
+ for (let ms = 500; ms <= 9_000 && !swapped; ms += 500) {
+ now.mockReturnValue(T0 + ms);
+ onPaint = () => now.mockReturnValue(T0 + ms + PAINT_MS);
+ vi.advanceTimersByTime(500);
+ onPaint = undefined;
+ if (plateOf(parent) !== first) swapped = plateOf(parent);
+ }
+ expect(swapped).toBeDefined();
+ const a = live(swapped)[0];
+ expect(a.at % 500).toBe(PAINT_MS); // keyed after the paint: from the clock the paint ended at
+ // the sun is where the view faces it at the instant the slide begins, to the pixel
+ const x = onViewport(swapped, suns[suns.length - 1][0], a.at);
+ expect(Math.abs(x - (W / 2 + (view.lookAzDeg + SUN_ABOVE_REST - poseAt(a.at).h) * k))).toBeLessThan(1);
+ s.dispose();
+ vi.useRealTimers();
+ });
+
+ it('never runs a plate out at the speed in force, whichever phase a late tick falls in, and sizes the slack to that speed', () => {
+ ticking();
+ const now = vi.mocked(performance.now);
+ const SPEED = 12;
+ setCamera({ speedDegPerS: SPEED });
+ const { parent, canvas } = host();
+ const s = createRidgeScene({ canvas, tier: 'full', sky: sunSky(), backdrop: litCards() })!;
+ const hfov = win.camera.hfovDeg;
+ expect(px(plateOf(parent).style.width) / k).toBeCloseTo(hfov + 2 * slackFor(SPEED, RESIDENCY_MS), 6); // the slack of 12 degrees a second, not of 0.6
+ // Ticks every half second, one in four two seconds late: at no instant may the viewport's edge pass the plate's.
+ let t = 0;
+ let widest = 0;
+ for (let n = 0; t < 24_000; n += 1) {
+ const gap = n % 4 === 3 ? 500 + LATENESS_S * 1000 : 500;
+ for (let at = t; at < t + gap; at += 50) {
+ const plate = plateOf(parent);
+ const edge = (px(plate.style.width) - W) / 2; // px the plate reaches past the viewport each side
+ widest = Math.max(widest, Math.abs(panAt(plate, T0 + at)) - edge);
+ }
+ t += gap;
+ now.mockReturnValue(T0 + t);
+ vi.advanceTimersByTime(500);
+ }
+ expect(widest).toBeLessThanOrEqual(1e-6); // the viewport's edge never got past the plate's
+ s.dispose();
+ vi.useRealTimers();
+ });
+
+ it('slides a slow turn on the least slack, and sizes the plate again when the speed asks for more', () => {
+ ticking();
+ const { parent, canvas } = host();
+ const s = createRidgeScene({ canvas, tier: 'full', sky: sunSky(), backdrop: litCards() })!;
+ const hfov = win.camera.hfovDeg;
+ expect(px(plateOf(parent).style.width) / k).toBeCloseTo(hfov + 2 * SLACK_MIN_DEG, 6);
+ const slow = plateOf(parent);
+ setCamera({ speedDegPerS: 12 }); // the viewer speeds the turn up: a plate with the slack of a slow one would be run out
+ const fast = plateOf(parent);
+ expect(fast).not.toBe(slow);
+ expect(px(fast.style.width) / k).toBeCloseTo(hfov + 2 * slackFor(12, RESIDENCY_MS), 6);
+ expect(panAt(fast, T0)).toBeCloseTo(0, 6);
+ s.dispose();
+ vi.useRealTimers();
+ });
+
+ it('keeps which stars twinkle, and their phase, across a swap, and shows the new plate with its twinkles already drawn', () => {
+ ticking();
+ const now = vi.mocked(performance.now);
+ setCamera({ speedDegPerS: 4 });
+ const { parent, canvas } = host();
+ const s = createRidgeScene({ canvas, tier: 'full', sky: nightSky(), backdrop: litCards() })!;
+ /** One display frame of the twinkle loop alone, at the clock now. */
+ const frame = () => {
+ const cbs = rafQueue.filter((c) => c.name === 'twTick');
+ rafQueue = rafQueue.filter((c) => c.name !== 'twTick');
+ cbs.forEach((c) => c(now()));
+ };
+ /** The stars drawn since `twinks` was cleared, as where they are on the viewport and how high, once each. */
+ const seen = (plate: any): string[] =>
+ [...new Set(twinks.map(([x, y]) => `${Math.round(onViewport(plate, x, now()))},${Math.round(y)}`))].filter((p) => {
+ const x = Number(p.split(',')[0]);
+ return x > 2 && x < W - 2;
+ });
+ let compared = 0;
+ for (let ms = 500; ms <= 9_000 && compared === 0; ms += 500) {
+ now.mockReturnValue(T0 + ms);
+ const before = plateOf(parent);
+ twinks.length = 0;
+ frame(); // the loop's frame at this clock: the stars the plate that is up has swinging
+ const old = seen(before);
+ twinks.length = 0;
+ vi.advanceTimersByTime(500); // the tick, at the same clock, which swaps the plate when the heading is near its edge
+ const after = plateOf(parent);
+ if (after === before) continue;
+ const next = seen(after);
+ expect(old.length).toBeGreaterThan(0);
+ const near = (a: string, list: string[]) =>
+ list.some((b) => {
+ const [ax, ay] = a.split(',').map(Number);
+ const [bx, by] = b.split(',').map(Number);
+ return Math.abs(ax - bx) <= 1 && ay === by;
+ });
+ old.forEach((p) => expect(near(p, next)).toBe(true)); // each star swinging a moment ago is swinging now, at the same place
+ next.forEach((p) => expect(near(p, old)).toBe(true)); // and no other
+ compared += 1;
+ }
+ expect(compared).toBe(1);
+ s.dispose();
+ vi.useRealTimers();
+ });
+
+ it('does not repaint a plate for a view that stays or turns within its slack', () => {
+ ticking();
+ const now = vi.mocked(performance.now);
+ const { parent, canvas } = host();
+ const s = createRidgeScene({ canvas, tier: 'full', sky: sunSky(), backdrop: litCards() })!; // 0.6 degrees a second
+ const first = plateOf(parent);
+ for (let ms = 500; ms <= 20_000; ms += 500) {
+ now.mockReturnValue(T0 + ms);
+ vi.advanceTimersByTime(500);
+ }
+ expect(plateOf(parent)).toBe(first); // 12 degrees of turn: inside the 14
+ expect(painted).toHaveLength(1);
+ s.dispose();
+ vi.useRealTimers();
+ });
+
+ it('re-centres on a reissue too: a turn by hand past the edge paints a plate about where the view now faces', () => {
+ ticking();
+ const { parent, canvas } = host();
+ const s = createRidgeScene({ canvas, tier: 'full', sky: sunSky(), backdrop: litCards() })!;
+ const first = plateOf(parent);
+ hold(view.lookAzDeg + 60, T0);
+ const plate = plateOf(parent);
+ expect(plate).not.toBe(first);
+ expect(panAt(plate, T0)).toBeCloseTo(0, 6);
+ expect(live(plate)).toHaveLength(1);
+ s.dispose();
+ vi.useRealTimers();
+ });
+
+ it('puts the twinkle canvas in the plate, over the sky, and nothing animates but the plate', () => {
+ const { parent, canvas } = host();
+ const s = createRidgeScene({ canvas, tier: 'full', sky: nightSky(), backdrop: litCards() })!;
+ const plate = plateOf(parent);
+ expect(plate.children.map((c: any) => c.tag)).toEqual(['canvas', 'canvas']);
+ expect([plate.children[1].width, plate.children[1].height]).toEqual([plate.children[0].width, plate.children[0].height]);
+ plate.children.forEach((c: any) => expect(c.anims).toHaveLength(0)); // they ride the plate
+ expect(parent.children.filter((c: any) => c.tag === 'canvas')).toEqual([canvas]); // no twinkle canvas of the page's own
+ s.dispose();
+ });
+
+ it('paints a plate that stays under the pixel cap and pans by the same px per degree as the cards', () => {
+ const { parent, canvas } = host();
+ const s = createRidgeScene({ canvas, tier: 'full', sky: sunSky(), backdrop: litCards() })!;
+ const plate = plateOf(parent);
+ expect(plate.children[0].width * plate.children[0].height).toBeLessThanOrEqual(3_000_000);
+ expect(px(plate.style.width) / (win.camera.hfovDeg + 40)).toBeCloseTo(k, 9);
+ hold(view.lookAzDeg + 10, T0); // a turn by hand inside the slack: the same plate slides ten degrees of pixels
+ expect(panAt(plateOf(parent), T0)).toBeCloseTo(-10 * k, 6);
+ s.dispose();
+ });
+
+ it('shows the sun at the azimuth the ridge is lit from: facing it the sky puts it on the centre column and the ridge faces it; facing away it is off the plate and the ridge is in shade', () => {
+ const sun = { azimuth: view.lookAzDeg + 17, elevation: 12 };
+ const lit = { ...DAY, physical: makePhysicalSky({ ...sun, time: new Date('2026-06-21T10:40:00Z') }, 0, view) };
+ // The ridge's own: the column whose face looks at the sun is the one the lit table gives most to.
+ const cols = sunColumns(view, sun);
+ let best = 0;
+ for (let c = 0; c < view.ringW; c += 1) if (cols[c * 4] > cols[best * 4]) best = c;
+ expect(Math.abs(ringAzimuth(best, view.ringW) - sun.azimuth)).toBeLessThanOrEqual(360 / view.ringW);
+
+ resetHeading();
+ anchor(view.place.id, sun.azimuth, T0);
+ const facing = host();
+ createRidgeScene({ canvas: facing.canvas, tier: 'full', sky: lit, backdrop: litCards() })!.dispose();
+ expect(suns).toHaveLength(1);
+ const wn = windowFor(view, W, 800);
+ const size = plateSize(wn, W, 800, 2, SLACK_MIN_DEG);
+ const centreCol = (suns[0][0] / Math.floor(size.cssW * size.ratio)) * size.cssW + (W - size.cssW) / 2;
+ expect(Math.abs(centreCol - W / 2)).toBeLessThan(1); // the sky's sun is on the column the view centres, whose face the ridge lights fullest
+ expect(sunInColumn(sun, sun.azimuth)[0]).toBeCloseTo(Math.cos((sun.elevation * Math.PI) / 180), 12);
+
+ suns.length = 0;
+ resetHeading();
+ anchor(view.place.id, sun.azimuth + 180, T0);
+ const away = host();
+ createRidgeScene({ canvas: away.canvas, tier: 'full', sky: lit, backdrop: litCards() })!.dispose();
+ expect(suns).toHaveLength(0); // the sun is behind the camera: no disc anywhere on the plate
+ expect(sunInColumn(sun, sun.azimuth + 180)[0]).toBeLessThan(0); // and the ridge faces it away
+ });
+ });
+
+ it('a heading of 400 degrees places the tiles a heading of 40 does, a revolution on', () => {
+ const at = (h: number) => {
+ resetHeading();
+ anchor(view.place.id, view.lookAzDeg, T0);
+ hold(h, T0);
+ const { parent, canvas } = host();
+ const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!;
+ const rig = rigOf(parent);
+ const out = {
+ ids: mountedIds(rig),
+ left: Number(rig.children[2].children[0].style.left.slice(0, -2)),
+ heading: poseAt(T0).h,
+ };
+ s.dispose();
+ return out;
+ };
+ // A manual turn leaves the rotation off, and a scene made over it keeps it off.
+ const a = at(40);
+ const b = at(400);
+ expect(b.ids).toEqual(a.ids);
+ // The rig lays out from the heading brought into [0, 360): a revolution on is the same picture, with nothing grown.
+ expect(b.heading).toBeCloseTo(a.heading, 9);
+ expect(b.left).toBeCloseTo(a.left, 6);
+ });
+
+ it('asks the backdrop for the arc between now and the end of the stretch, at once and every half second, and mounts what it has made', async () => {
+ vi.useFakeTimers();
+ (window as any).setTimeout = setTimeout;
+ (window as any).clearTimeout = clearTimeout;
+ const { parent, canvas } = host();
+ const bd = litCards();
+ const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: bd })!;
+ expect(bd.ensure).not.toHaveBeenCalled(); // the first arc was made before the scene (index.ts prepare)
+ vi.advanceTimersByTime(500);
+ expect(bd.ensure).toHaveBeenCalledTimes(1);
+ const arc = bd.ensure.mock.calls[0][0];
+ // The heading is 214 and turns 0.6 degrees per second to 232 in 30 s; on a 400 x 800 viewport a card shows about 28 degrees of itself.
+ expect(arc.fromDeg).toBeLessThan(214 - 10);
+ expect(arc.toDeg).toBeGreaterThan(232 + 10);
+ vi.advanceTimersByTime(1500);
+ expect(bd.ensure).toHaveBeenCalledTimes(4);
+ // The view is turned by hand to the north: the next tick holds the tiles there.
+ const before = mountedIds(rigOf(parent));
+ hold(300, T0);
+ vi.advanceTimersByTime(500);
+ const after = mountedIds(rigOf(parent));
+ expect(before).toEqual(['t2c0', 't2c1']);
+ expect(after).not.toContain('t2c0');
+ expect(after.some((id) => id.startsWith('t3'))).toBe(true);
+ s.dispose();
+ vi.useRealTimers();
+ });
+
+ it('issues the next stretch of motion once 80% of the last has run, on any change of heading, mode or offset, and not otherwise', () => {
+ vi.useFakeTimers();
+ (window as any).setTimeout = setTimeout;
+ (window as any).clearTimeout = clearTimeout;
+ const now = vi.mocked(performance.now);
+ const { parent, canvas } = host();
+ const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!;
+ const rig = rigOf(parent);
+ const issued = () => rig.children.map((b: any) => b.anims.length);
+ const base = issued()[0];
+ now.mockReturnValue(T0 + 20_000);
+ vi.advanceTimersByTime(20_000);
+ expect(issued()[0]).toBe(base); // 20 s of 30: not yet
+ now.mockReturnValue(T0 + 24_500);
+ vi.advanceTimersByTime(4_500);
+ expect(issued()[0]).toBe(base + 1);
+ expect(rig.children[0].anims[base - 1].cancel).toHaveBeenCalled();
+ const afterReissue = issued()[0];
+ setCamera({ offsetM: 20 });
+ expect(issued()[0]).toBe(afterReissue + 1);
+ setCamera({ offsetM: 20 }); // nothing changed
+ expect(issued()[0]).toBe(afterReissue + 1);
+ hold(10, T0 + 24_500);
+ expect(issued()[0]).toBe(afterReissue + 2);
+ s.dispose();
+ setCamera({ offsetM: 30 });
+ expect(issued()[0]).toBe(afterReissue + 2); // a disposed scene is deaf
+ vi.useRealTimers();
+ });
+
+ it('adds no rAF of its own over ten idle seconds: the drift is Element.animate, the stars alone loop', () => {
+ vi.useFakeTimers();
+ (window as any).setTimeout = setTimeout;
+ (window as any).clearTimeout = clearTimeout;
const { canvas } = host();
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!;
expect(rafQueue).toHaveLength(1); // the frame sampler, as without cards
+ vi.advanceTimersByTime(10_000);
+ expect(rafQueue).toHaveLength(1);
+ s.dispose();
+ vi.useRealTimers();
+ });
+
+ it('runs constant keyframes under reduced motion, and the view turns nothing whatever the viewer asked for', () => {
+ motion.matches = true;
+ const { parent, canvas } = host();
+ const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!;
+ expect(poseAt(T0 + 10_000).h).toBe(poseAt(T0).h); // nothing turns, whatever the viewer chose
+ expect(getCamera().mode).toBe('both'); // and the viewer's choice is not rewritten for it
+ rigOf(parent).children.forEach((box: any) => {
+ const { keyframes } = live(box)[0];
+ expect(keyframes.length).toBeGreaterThan(0);
+ keyframes.forEach((f: any) => expect(f).toEqual(keyframes[0]));
+ });
s.dispose();
});
- it('pauses the drift under reduced motion, in a hidden tab, and plays it again', () => {
+ it('pauses the motion in a hidden tab and when motion is reduced, plays it again from where the clock is, and cancels it on dispose', () => {
const { parent, canvas } = host();
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!;
- const anims = rigOf(parent).children.map((g: any) => g.anims[0]);
- anims.forEach((a: any) => expect(a.play).toHaveBeenCalled());
- anims.forEach((a: any) => a.pause.mockClear());
+ const rig = rigOf(parent);
+ const anims = () => rig.children.map((g: any) => g.anims[g.anims.length - 1]);
+ anims().forEach((a: any) => expect(a.play).toHaveBeenCalled());
+ const first = anims();
+ first.forEach((a: any) => a.pause.mockClear());
motion.matches = true;
motion.addEventListener.mock.calls
.filter((c: any[]) => c[0] === 'change')
.forEach((c: any[]) => c[1]());
- anims.forEach((a: any) => expect(a.pause).toHaveBeenCalled());
+ anims().forEach((a: any) => expect(a.pause).toHaveBeenCalled());
motion.matches = false;
- anims.forEach((a: any) => a.pause.mockClear());
doc.visibilityState = 'hidden';
doc.dispatchEvent(new Event('visibilitychange'));
- anims.forEach((a: any) => expect(a.pause).toHaveBeenCalled());
+ anims().forEach((a: any) => expect(a.pause).toHaveBeenCalled());
+ doc.visibilityState = 'visible';
+ (performance.now as any).mockReturnValue(T0 + 60_000);
+ doc.dispatchEvent(new Event('visibilitychange'));
+ const resumed = anims();
+ resumed.forEach((a: any) => expect(a.play).toHaveBeenCalled());
+ // Back in view the motion starts from the clock now, not from where it stopped.
+ const frame0 = (box: any) => box.anims[box.anims.length - 1].keyframes[0].transform;
+ const p = posed(manifest, 0, T0 + 60_000, win);
+ expect(frame0(rig.children[2])).toBe(`translate3d(${p.shiftPx}px,0,0) scale(${p.scale})`);
s.dispose();
- anims.forEach((a: any) => expect(a.cancel).toHaveBeenCalled());
+ resumed.forEach((a: any) => expect(a.cancel).toHaveBeenCalled());
});
- it("a still draws every card, farthest first, scaled by its own scale about the rig's origin, at heading 0", () => {
+ describe('after the viewer takes the view by hand, and for the long run', () => {
+ const fixtureRing = (camera: Record = { r_max_m: 98.2, r_max_forward_m: 205.4 }) =>
+ parseManifest(wireManifest({ camera }, 3, 32), '/d/'); // the ring as the baker cuts it, with Vienna's two offset bounds
+ const ringBackdrop = (m: typeof manifest): Backdrop & { ensure: Mock<[Arc, Arc?], Promise> } => {
+ const lit = m.tiles.flatMap((row, tile) =>
+ row.flatMap((e, card) => {
+ if (!e) return [];
+ const canvas = fakeEl('canvas');
+ canvas.id = `t${tile}c${card}`;
+ return [{ tile, card, canvas: canvas as unknown as HTMLCanvasElement }];
+ })
+ );
+ return {
+ manifest: m,
+ ensure: vi.fn(async (_arc: Arc, _first?: Arc): Promise => undefined),
+ litTiles: () => lit,
+ onTile: () => () => undefined,
+ dispose: vi.fn(),
+ };
+ };
+ const frame = (box: any, n: number) => live(box)[0].keyframes[n].transform as string;
+ const pending = () => {
+ vi.useFakeTimers();
+ (window as any).setTimeout = setTimeout;
+ (window as any).clearTimeout = clearTimeout;
+ };
+
+ it('a manual turn holds through a rebuild: a resize makes a new scene and the view stays where the viewer left it', () => {
+ pending();
+ const { parent, canvas } = host();
+ const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!;
+ hold(100, T0);
+ const at = poseAt(T0).h;
+ window.dispatchEvent(new Event('resize'));
+ vi.advanceTimersByTime(300); // the debounced rebuild: startRig runs again
+ expect(effectiveMode()).toBe('still'); // held, and the chosen mode untouched
+ expect(getCamera().mode).toBe('both');
+ expect(poseAt(T0 + 60_000).h).toBe(at);
+ rigOf(parent).children.forEach((box: any) => expect(frame(box, 30)).toBe(frame(box, 0)));
+ s.dispose();
+ // And a scene made afterwards, as a sky change makes one.
+ const again = createRidgeScene({ canvas: host().canvas, tier: 'full', sky: night, backdrop: litCards() })!;
+ expect(poseAt(T0 + 60_000).h).toBe(at);
+ again.dispose();
+ vi.useRealTimers();
+ });
+
+ it('picking the mode they already had after a hold resumes the turn, and the rig moves again', () => {
+ const { parent, canvas } = host();
+ const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!;
+ hold(100, T0);
+ rigOf(parent).children.forEach((box: any) => expect(frame(box, 30)).toBe(frame(box, 0)));
+ expect(isHeld()).toBe(true);
+ setCamera({ mode: 'both' }); // what the View's rotation picker sends: the mode the viewer had when they took the view
+ expect(isHeld()).toBe(false);
+ expect(poseAt(T0 + 10_000).h).toBeCloseTo(106, 9);
+ rigOf(parent).children.forEach((box: any) => expect(frame(box, 30)).not.toBe(frame(box, 0)));
+ s.dispose();
+ });
+
+ it('mounts and asks for the tiles of every pose a stretch passes through, not those at its ends: offset-only turning swings the near card out and back', () => {
+ pending();
+ const ring = fixtureRing();
+ const bd = ringBackdrop(ring);
+ const w2 = windowFor(ring.view, 400, 800);
+ setCamera({ mode: 'offset', speedDegPerS: 12, offsetM: 98 });
+ const { parent, canvas } = host();
+ const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: bd })!;
+ vi.advanceTimersByTime(500);
+ const asked = bd.ensure.mock.calls[0][0];
+ let from = Infinity;
+ let to = -Infinity;
+ let endFrom = Infinity;
+ let endTo = -Infinity;
+ for (let ms = 0; ms <= 30_000; ms += 100) {
+ for (let i = 0; i < 3; i += 1) {
+ const a = cardArc(ring.view, w2, 400, posed(ring, i, T0 + ms, w2));
+ from = Math.min(from, a.fromDeg);
+ to = Math.max(to, a.toDeg);
+ if (ms === 0 || ms === 30_000) {
+ endFrom = Math.min(endFrom, a.fromDeg);
+ endTo = Math.max(endTo, a.toDeg);
+ }
+ }
+ }
+ expect(endTo - endFrom).toBeLessThan(to - from - 5); // the ends alone miss degrees of it (a whole turn of the camera comes back to where it began)
+ expect(asked.fromDeg).toBeLessThanOrEqual(from + 0.01);
+ expect(asked.toDeg).toBeGreaterThanOrEqual(to - 0.01);
+ const need = new Set(residentTiles(ring.view, (from + to) / 2, (to - from) / 2 - 0.02).map((r) => r.tile));
+ const mounted = new Set(mountedIds(rigOf(parent)).map((id) => Number(/^t(\d+)c/.exec(id)?.[1])));
+ need.forEach((t) => expect(mounted.has(t), `tile ${t}`).toBe(true));
+ s.dispose();
+ vi.useRealTimers();
+ });
+
+ it('tells the loader where the view is now besides the arc it will sweep, so the tiles on screen are asked for first', () => {
+ pending();
+ const ring = fixtureRing();
+ const bd = ringBackdrop(ring);
+ const w2 = windowFor(ring.view, 400, 800);
+ const { canvas } = host();
+ const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: bd })!;
+ vi.advanceTimersByTime(500);
+ const [arc, first] = bd.ensure.mock.calls[0];
+ expect(first).toBeDefined();
+ const now = [0, 1, 2].map((i) => cardArc(ring.view, w2, 400, posed(ring, i, T0, w2)));
+ expect(first!.fromDeg).toBeCloseTo(Math.min(...now.map((a) => a.fromDeg)), 6);
+ expect(first!.toDeg).toBeCloseTo(Math.max(...now.map((a) => a.toDeg)), 6);
+ expect(first!.toDeg - first!.fromDeg).toBeLessThan(arc.toDeg - arc.fromDeg);
+ s.dispose();
+ vi.useRealTimers();
+ });
+
+ it('takes the default 200 m where the camera stays on its heading and the bake allows it, and the worst-case bound where the camera circles', () => {
+ const ring = fixtureRing();
+ const w2 = windowFor(ring.view, 400, 800);
+ const keyframe0 = (mode: 'both' | 'offset') => {
+ resetHeading(); // a page of its own for each mode: the view starts where the choice puts it
+ anchor(view.place.id, view.lookAzDeg, T0);
+ setCamera({ mode, speedDegPerS: 0.6, offsetM: 200 });
+ const { parent, canvas } = host();
+ const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: ringBackdrop(ring) })!;
+ const got = frame(rigOf(parent).children[2], 0);
+ s.dispose();
+ return got;
+ };
+ const posed = (offset: number) => {
+ const p = cardPose(ring, 0, poseAt(T0).h, poseAt(T0).phi, offset, w2);
+ return `translate3d(${p.shiftPx}px,0,0) scale(${p.scale})`;
+ };
+ expect(keyframe0('both')).toBe(posed(200));
+ expect(keyframe0('offset')).toBe(posed(98.2));
+ });
+
+ it('bounds the speed at read to what the baked resident count sustains, for the mode in force, and never rewrites the stored speed', () => {
+ const ring = fixtureRing();
+ const slow = maxSpeed(ring, 'both');
+ expect(slow).toBeGreaterThan(0.6);
+ expect(slow).toBeLessThan(12);
+ setCamera({ mode: 'both', speedDegPerS: 50 }); // a stored or future-slider value
+ anchor(view.place.id, view.lookAzDeg, T0, (m) => maxSpeed(ring, m)); // what index.ts prepare does with the manifest, before the scene is made
+ const { canvas } = host();
+ const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: ringBackdrop(ring) })!;
+ expect(getCamera().speedDegPerS).toBe(50);
+ expect(poseAt(T0 + 10_000).h - poseAt(T0).h).toBeCloseTo(10 * slow, 9);
+ setCamera({ speedDegPerS: -50 });
+ expect(getCamera().speedDegPerS).toBe(-50);
+ expect(poseAt(T0 + 10_000).h - poseAt(T0).h).toBeCloseTo(-10 * slow, 9);
+ setCamera({ mode: 'offset', speedDegPerS: 11 }); // the offset-only mode sweeps the circle the gate counts, whatever the speed
+ expect(poseAt(T0 + 20_000).phi - poseAt(T0 + 10_000).phi).toBeCloseTo(110, 9);
+ setCamera({ mode: 'both' });
+ expect(getCamera().speedDegPerS).toBe(11); // still the viewer's value
+ expect(poseAt(T0 + 10_000).h - poseAt(T0).h).toBeCloseTo(10 * slow, 9);
+ s.dispose();
+ });
+
+ it('derives the offset clamp at read and never writes it back: offset-only to a forward mode restores 200 m', () => {
+ const ring = fixtureRing();
+ const w2 = windowFor(ring.view, 400, 800);
+ setCamera({ mode: 'offset', speedDegPerS: 0.6, offsetM: 200 });
+ const { parent, canvas } = host();
+ const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: ringBackdrop(ring) })!;
+ const posed = (offset: number) => {
+ const p = cardPose(ring, 0, poseAt(T0).h, poseAt(T0).phi, offset, w2);
+ return `translate3d(${p.shiftPx}px,0,0) scale(${p.scale})`;
+ };
+ expect(frame(rigOf(parent).children[2], 0)).toBe(posed(98.2));
+ expect(getCamera().offsetM).toBe(200);
+ setCamera({ mode: 'both' });
+ expect(getCamera().offsetM).toBe(200);
+ const keys = live(rigOf(parent).children[2])[0].keyframes;
+ expect(keys[0].transform).toBe(posed(98.2)); // the view leaves from the offset it showed (the pick does not move it) ...
+ const p = cardPose(ring, 0, poseAt(T0 + STAGE_MS).h, 0, 200, w2);
+ expect(keys.find((f: any) => f.offset >= STAGE_MS / (SEGMENT_S * 1000) - 1e-9).transform).toBe(`translate3d(${p.shiftPx}px,0,0) scale(${p.scale})`); // ... and is at 200 when the ease is spent
+ s.dispose();
+ });
+
+ it('eases a mode pick: the view the viewer saw is the first frame, the new regime the frame an EASE_MS later, one animation and no timer of its own', () => {
+ const ring = fixtureRing();
+ const w2 = windowFor(ring.view, 400, 800);
+ setCamera({ mode: 'offset', speedDegPerS: 12, offsetM: 200 });
+ const { parent, canvas } = host();
+ const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: ringBackdrop(ring) })!;
+ const at = T0 + 7_500; // 90 degrees round its circle at 12 degrees a second, at the offset 98.2 the mode clamps to
+ const tf = (ms: number, phi: number, offset: number) => {
+ const p = cardPose(ring, 0, poseAt(at + ms).h, phi, offset, w2);
+ return { text: `translate3d(${p.shiftPx}px,0,0) scale(${p.scale})`, scale: p.scale };
+ };
+ expect(poseAt(at).phi).toBeCloseTo(90, 6);
+ const seen = tf(0, poseAt(at).phi, 98.2);
+ vi.mocked(performance.now).mockReturnValue(at);
+ setCamera({ mode: 'both' }, at); // phi goes to 0 and the clamp releases to 200: both used to land in one frame
+ const run = live(rigOf(parent).children[2])[0];
+ expect(run.keyframes[0].transform).toBe(seen.text);
+ const spent = EASE_MS / (SEGMENT_S * 1000);
+ const end = run.keyframes.find((f: any) => f.offset >= spent - 1e-9);
+ const there = tf(EASE_MS, 0, 200);
+ expect(end.transform).toBe(there.text);
+ const eased = run.keyframes.filter((f: any) => f.offset <= spent + 1e-9);
+ expect(eased.length).toBeGreaterThan(10); // keyed finely while it runs
+ const scale = (f: any) => parseFloat(/scale\(([^)]*)\)/.exec(f.transform)![1]);
+ const jump = Math.abs(there.scale - seen.scale);
+ expect(jump).toBeGreaterThan(0.05); // the pop this pick used to be
+ eased.slice(1).forEach((f: any, i: number) => expect(Math.abs(scale(f) - scale(eased[i]))).toBeLessThan(jump / 4));
+ expect(run.keyframes.at(-1).offset).toBe(1);
+ s.dispose();
+ });
+
+ describe('the ease of a mode pick stays inside the fit of the card slide', () => {
+ // The baked Vienna: its distances and its two bounds, as shipped.
+ const root = join(process.cwd(), 'public', 'ridge');
+ const dir = parseIndex(JSON.parse(readFileSync(join(root, 'index.json'), 'utf8'))).places.vienna;
+ const vienna = parseManifest(JSON.parse(readFileSync(join(root, dir, 'manifest.json'), 'utf8')), `${dir}/`);
+ const FIT_PX_MAX = 24; // scripts/ridge-bake/export.py
+ /** The baker's `fit_px` (export.py): the worst error, in card px, of a card at distance `d` metres seen from offset `r` at camera angle `phiDeg`, against its best line over the widest field, the continuous error (the line by the trapezoid rule on 1025 samples, the error on the same). */
+ const fitPx = (d: number, r: number, phiDeg: number, n = 1025): number => {
+ const phi = (phiDeg * Math.PI) / 180;
+ const half = (HFOV_MAX_DEG * Math.PI) / 360;
+ const b = Array.from({ length: n }, (_, i) => -half + (2 * half * i) / (n - 1));
+ const a = b.map((x) => Math.atan2(d * Math.sin(x) - r * Math.sin(phi), d * Math.cos(x) - r * Math.cos(phi)));
+ const w = (i: number) => (i === 0 || i === n - 1 ? 0.5 : 1);
+ let sw = 0;
+ let sa = 0;
+ let sab = 0;
+ let sbb = 0;
+ a.forEach((y, i) => {
+ sw += w(i);
+ sa += w(i) * y;
+ sab += w(i) * y * b[i];
+ sbb += w(i) * b[i] * b[i];
+ });
+ const mean = sa / sw;
+ const s = sab / sbb;
+ return (Math.max(...a.map((y, i) => Math.abs(y - (mean + s * b[i])))) * 180) / Math.PI * vienna.view.pxPerDegH;
+ };
+ const distances = vienna.tiles.flatMap((row) => row.flatMap((e) => (e ? [e.distanceM] : [])));
+ /** The worst of every card of the bake at the camera angle `phiDeg` and offset `r`. */
+ const worstPx = (r: number, phiDeg: number): number => Math.max(...distances.map((d) => fitPx(d, r, phiDeg)));
+ /** The same over the six nearest cards and 129 samples (the trapezoid rule is exact to a few thousandths of a pixel there): the nearest cards bind, and a property run asks it thousands of times. */
+ const nearest = [...distances].sort((a, b) => a - b).slice(0, 6);
+ const quickPx = (r: number, phiDeg: number): number => Math.max(...nearest.map((d) => fitPx(d, r, phiDeg, 129)));
+ const w2 = windowFor(vienna.view, 400, 800);
+ /** The offset a keyframe's pose was made from: the one `cardPose` gives the transform at this heading and camera angle (a scan, then a finer one), with how far it is off. */
+ const offsetOf = (transform: string, heading: number, phi: number): { r: number; miss: number } => {
+ const m = /translate3d\((-?[\d.e+-]+)px,0,0\) scale\((-?[\d.e+-]+)\)/.exec(transform)!;
+ const want = { shiftPx: Number(m[1]), scale: Number(m[2]) };
+ const miss = (r: number) => {
+ const p = cardPose(vienna, 0, heading, phi, r, w2);
+ return Math.hypot(p.shiftPx - want.shiftPx, (p.scale - want.scale) * 400);
+ };
+ let best = { r: 0, miss: Infinity };
+ for (const step of [0.5, 0.02, 0.001]) {
+ const from = best.miss === Infinity ? -300 : best.r - 20 * step;
+ const to = best.miss === Infinity ? 300 : best.r + 20 * step;
+ for (let r = from; r <= to; r += step) {
+ const e = miss(r);
+ if (e < best.miss) best = { r, miss: e };
+ }
+ }
+ return best;
+ };
+ /** Every (camera angle, offset) a stretch of keyframes poses card 0 from, recovered from the transforms, from the pick on. */
+ const pairsOf = (box: any, at: number): { phi: number; r: number; ms: number; miss: number }[] => {
+ const keys = live(box)[0].keyframes;
+ return keys.map((f: any, n: number) => {
+ const ms = (f.offset ?? n / (keys.length - 1)) * SEGMENT_S * 1000;
+ const phi = poseAt(at + ms).phi;
+ return { phi, ms, ...offsetOf(f.transform, poseAt(at + ms).h, phi) };
+ });
+ };
+ const pick = (from: { mode: 'both' | 'offset'; speed: number; waitS: number }, to: 'both' | 'offset') => {
+ setCamera({ mode: from.mode, speedDegPerS: from.speed, offsetM: 200 });
+ const { parent, canvas } = host();
+ const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: ringBackdrop(vienna) })!;
+ const at = T0 + from.waitS * 1000;
+ vi.mocked(performance.now).mockReturnValue(at);
+ setCamera({ mode: to }, at);
+ const got = pairsOf(rigOf(parent).children[2], at);
+ s.dispose();
+ return got;
+ };
+
+ it('measures the fit as the baker does: Vienna sits at the bound at its two offsets, and above it past them', () => {
+ const { rMaxM, rMaxForwardM } = vienna.camera;
+ expect([rMaxM, rMaxForwardM]).toEqual([95.8, 198.4]);
+ const circle = Array.from({ length: 24 }, (_, i) => i * 15);
+ expect(Math.max(...circle.map((phi) => worstPx(rMaxM, phi)))).toBeGreaterThan(FIT_PX_MAX - 0.5);
+ expect(Math.max(...circle.map((phi) => worstPx(rMaxM, phi)))).toBeLessThanOrEqual(FIT_PX_MAX + 0.05);
+ expect(worstPx(rMaxForwardM, 0)).toBeGreaterThan(FIT_PX_MAX - 0.5);
+ expect(worstPx(rMaxForwardM, 0)).toBeLessThanOrEqual(FIT_PX_MAX + 0.05);
+ expect(worstPx(200, 90)).toBeGreaterThan(FIT_PX_MAX); // the blend the ease used to pass through
+ expect(worstPx(rMaxForwardM + 1, 0)).toBeGreaterThan(FIT_PX_MAX); // past the forward bound, and the circle's bound is not the forward one
+ expect(Math.max(...circle.map((phi) => worstPx(rMaxM + 1, phi)))).toBeGreaterThan(FIT_PX_MAX);
+ });
+
+ [
+ { name: 'offset-only to both from the camera a quarter round', from: { mode: 'offset', speed: 12, waitS: 7.5 }, to: 'both' },
+ { name: 'offset-only to both with the camera half way round', from: { mode: 'offset', speed: 12, waitS: 15 }, to: 'both' },
+ { name: 'offset-only to both with the camera just off its heading', from: { mode: 'offset', speed: 12, waitS: 1.25 }, to: 'both' },
+ { name: 'both to offset-only at the default speed', from: { mode: 'both', speed: 0.6, waitS: 3 }, to: 'offset' },
+ { name: 'both to offset-only at the fastest turn', from: { mode: 'both', speed: 12, waitS: 3 }, to: 'offset' },
+ ].forEach(({ name, from, to }) => {
+ it(`${name}: every keyframe is the pose of an angle and an offset inside the card fit, at Vienna's bounds`, () => {
+ const got = pick(from as any, to as any);
+ expect(got.length).toBeGreaterThan(12);
+ got.forEach((g) => expect(g.miss, `a pose of the camera at ${g.phi.toFixed(1)} degrees, ${g.r.toFixed(1)} m`).toBeLessThan(0.05));
+ const worst = Math.max(...got.map((g) => worstPx(g.r, g.phi)));
+ expect(worst).toBeLessThanOrEqual(FIT_PX_MAX + 0.05);
+ // The angle and the offset take a stage each: never both between their ends at once.
+ const moving = (v: number[], i: number) => i > 0 && Math.abs(v[i] - v[i - 1]) > 1e-3;
+ const phis = got.map((g) => g.phi);
+ const rs = got.map((g) => g.r);
+ got.forEach((_, i) => expect(moving(phis, i) && moving(rs, i), `keyframe ${i}`).toBe(false));
+ const last = got.at(-1)!;
+ expect(last.r).toBeCloseTo(to === 'both' ? Math.min(200, vienna.camera.rMaxForwardM) : vienna.camera.rMaxM, 1); // the offset owed: the default 200 or the forward bound, or the bound of the circling mode
+ if (to === 'both') expect(last.phi % 360).toBe(0);
+ });
+ });
+
+ /** A transform's two numbers. */
+ const parsed = (transform: string): { shift: number; scale: number } => {
+ const m = /translate3d\((-?[\d.e+-]+)px,0,0\) scale\((-?[\d.e+-]+)\)/.exec(transform)!;
+ return { shift: Number(m[1]), scale: Number(m[2]) };
+ };
+ /** What the compositor shows `ms` into an animation: the keyframes' straight lines. */
+ const playedAt = (anim: any, ms: number): { shift: number; scale: number } => {
+ const keys: any[] = anim.keyframes;
+ const at = (k: number) => (keys[k].offset ?? k / (keys.length - 1)) * anim.options.duration;
+ let k = 1;
+ while (k < keys.length - 1 && at(k) < ms) k += 1;
+ const [a, b] = [parsed(keys[k - 1].transform), parsed(keys[k].transform)];
+ const x = Math.min(1, Math.max(0, (ms - at(k - 1)) / (at(k) - at(k - 1))));
+ return { shift: a.shift + (b.shift - a.shift) * x, scale: a.scale + (b.scale - a.scale) * x };
+ };
+
+ describe('a pick made while an ease is under way, and a rebuild in the middle of one', () => {
+ const picks: { name: string; from: 'both' | 'offset'; waitS: number; then: ['still' | 'offset' | 'both', number][] }[] = [
+ { name: 'offset-only to both, then to still a moment later', from: 'offset', waitS: 7.8, then: [['both', 0], ['still', 100]] },
+ { name: 'offset-only to both, then back to offset-only', from: 'offset', waitS: 7.8, then: [['both', 0], ['offset', 100]] },
+ { name: 'offset-only to both, to still, and to both again', from: 'offset', waitS: 7.8, then: [['both', 0], ['still', 100], ['both', 150]] },
+ { name: 'offset-only to both, then offset-only as the angle lands', from: 'offset', waitS: 7.8, then: [['both', 0], ['offset', 295]] },
+ { name: 'offset-only to both, then still with the offset on its way out', from: 'offset', waitS: 7.8, then: [['both', 0], ['still', 450]] },
+ { name: 'both to offset-only, then to both before the offset is in', from: 'both', waitS: 3, then: [['offset', 0], ['both', 150]] },
+ { name: 'both to offset-only, then to still, then to offset-only', from: 'both', waitS: 3, then: [['offset', 0], ['still', 100], ['offset', 120]] },
+ ];
+ picks.forEach(({ name, from, waitS, then }) => {
+ it(`${name}: every keyframe the last pick lays out is the pose of an angle and an offset inside the card fit`, () => {
+ setCamera({ mode: from, speedDegPerS: 12, offsetM: 200 });
+ const { parent, canvas } = host();
+ const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: ringBackdrop(vienna) })!;
+ let at = T0 + waitS * 1000;
+ for (const [mode, after] of then) {
+ at += after;
+ vi.mocked(performance.now).mockReturnValue(at);
+ setCamera({ mode }, at);
+ }
+ const got = pairsOf(rigOf(parent).children[2], at);
+ got.forEach((g) => expect(g.miss, `a pose of the camera at ${g.phi.toFixed(1)} degrees, ${g.r.toFixed(1)} m`).toBeLessThan(0.05));
+ const worst = Math.max(...got.map((g) => worstPx(g.r, g.phi)));
+ expect(worst).toBeLessThanOrEqual(FIT_PX_MAX + 0.05);
+ s.dispose();
+ });
+ });
+
+ it('a rebuild in the middle of an ease lands where the old scene was: the first frame of the new rig is the frame the old one showed', () => {
+ pending();
+ for (const gap of [100, 250, 400, 550]) {
+ resetHeading();
+ resetCamera();
+ vi.mocked(performance.now).mockReturnValue(T0);
+ anchor(vienna.view.place.id, vienna.view.lookAzDeg, T0);
+ setCamera({ mode: 'offset', speedDegPerS: 12, offsetM: 200 });
+ const { parent, canvas } = host();
+ const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: ringBackdrop(vienna) })!;
+ const at = T0 + 7_800;
+ vi.mocked(performance.now).mockReturnValue(at);
+ setCamera({ mode: 'both' }, at);
+ const old = rigOf(parent).children.map((box: any) => live(box)[0]);
+ vi.mocked(performance.now).mockReturnValue(at + gap);
+ window.dispatchEvent(new Event('resize'));
+ vi.advanceTimersByTime(300); // the debounced rebuild: a new rig at this clock
+ const now = rigOf(parent).children.map((box: any) => live(box)[0]);
+ now.forEach((a: any, i: number) => {
+ expect(a).not.toBe(old[i]);
+ const was = playedAt(old[i], gap);
+ const is = parsed(a.keyframes[0].transform);
+ expect(Math.abs(is.shift - was.shift), `card ${i} ${gap} ms into the ease`).toBeLessThan(2);
+ expect(Math.abs(is.scale - was.scale), `card ${i} ${gap} ms into the ease`).toBeLessThan(0.01);
+ });
+ s.dispose();
+ }
+ vi.useRealTimers();
+ });
+ });
+
+ describe('random sequences of picks, holds, speeds, offsets and rebuilds at random times', () => {
+ /** A seeded generator (mulberry32): a failing sequence is the seed it prints. */
+ const random = (seed: number) => () => {
+ seed = (seed + 0x6d2b79f5) | 0;
+ let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+ const modes = ['still', 'offset', 'both'] as const;
+ const inside = ([lo, hi]: [number, number], v: number, slack = 1e-6) => v >= lo - slack && v <= hi + slack;
+
+ /** Every pose a laid-out stretch passes through is one the baker's bound allows, at the offset it has: whenever the camera angle moves, the circle's bound holds at both ends; and the keyframes are the poses the heading owner has. */
+ const checkLayout = (parent: any, label: string) => {
+ const boxes = rigOf(parent).children as any[];
+ boxes.forEach((box) => expect(live(box)).toHaveLength(1));
+ // The rig lays every card out from the owner's pose at the clock of each keyframe.
+ boxes.forEach((box) => {
+ const card = Number(box.id.slice(-1));
+ const { keyframes, options, at } = live(box)[0];
+ keyframes.forEach((f: any, n: number) => {
+ const t = at + (f.offset ?? n / (keyframes.length - 1)) * options.duration;
+ const p = poseAt(t);
+ const c = cardPose(vienna, card, p.h, p.phi, p.r, w2);
+ expect(f.transform, `${label}: card ${card} keyframe ${n}`).toBe(`translate3d(${c.shiftPx}px,0,0) scale(${c.scale})`);
+ });
+ });
+ // The pose itself, every 2 ms through the ease and every half second after.
+ const t0: number = live(boxes[0])[0].at;
+ const home = Math.max(t0, settledAt());
+ const times: number[] = [];
+ for (let t = t0; t <= home + 2; t += 2) times.push(t);
+ for (let t = home; t <= t0 + SEGMENT_S * 1000; t += 500) times.push(t);
+ let last = poseAt(times[0]);
+ times.forEach((t, i) => {
+ const p = poseAt(t);
+ expect(inside(offsetRange(vienna, w2, 'both', p.phi), p.r), `${label}: phi ${p.phi}, r ${p.r} at +${t - t0} ms`).toBe(true);
+ if (i && Math.abs(p.phi - last.phi) > 1e-9) {
+ const circle = offsetRange(vienna, w2, 'offset');
+ expect(inside(circle, p.r, 0.02) && inside(circle, last.r, 0.02), `${label}: the angle moves with r ${last.r} then ${p.r} at +${t - t0} ms`).toBe(true);
+ }
+ if (i % 40 === 0 || i === times.length - 1) expect(quickPx(p.r, p.phi), `${label}: fit at phi ${p.phi}, r ${p.r}`).toBeLessThanOrEqual(FIT_PX_MAX + 0.1);
+ last = p;
+ });
+ };
+
+ let inEase = 0;
+ const sequence = (seed: number): number => {
+ const next = random(seed);
+ const pick = (xs: readonly T[]): T => xs[Math.floor(next() * xs.length)];
+ resetHeading();
+ resetCamera();
+ const clock = vi.mocked(performance.now);
+ let now = T0;
+ clock.mockReturnValue(now);
+ anchor(vienna.view.place.id, vienna.view.lookAzDeg, T0);
+ setCamera({ mode: pick(modes), speedDegPerS: pick([0.6, 3, 12, -12, 0]), offsetM: pick([200, 98, -60, 0, 999]) }, now);
+ let { parent, canvas } = host();
+ let scene = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: ringBackdrop(vienna) })!;
+ let rebuilds = 0;
+ for (let step = 0; step < 36; step += 1) {
+ const gap = pick([0, 20, 60, 100, 150, 299, 301, 450, 700, 3000, 24_500]);
+ now += gap;
+ clock.mockReturnValue(now);
+ vi.advanceTimersByTime(gap);
+ const label = `seed ${seed} step ${step}`;
+ const op = Math.floor(next() * 9);
+ const before = poseAt(now);
+ const fine = now <= settledAt(); // the old stretch is keyed every 50 ms here, a second apart after: the straight lines between keyframes are the pose only where they are close
+ const old = rigOf(parent).children.map((box: any) => live(box)[0]);
+ if (op <= 2) setCamera({ mode: pick(modes) }, now);
+ else if (op === 3) hold(next() * 1000 - 300, now);
+ else if (op === 4) setCamera({ speedDegPerS: pick([0.6, 3, 12, -12, 0, 7.5]) }, now);
+ else if (op === 5) setCamera({ offsetM: Math.round(next() * 600 - 300) }, now);
+ else if (op === 6) setCamera({ mode: pick(modes), speedDegPerS: pick([0.6, 12, -12]), offsetM: pick([200, 0, 50]) }, now);
+ else if (op === 7) {
+ window.dispatchEvent(new Event('resize'));
+ vi.advanceTimersByTime(300);
+ } else {
+ scene.dispose();
+ ({ parent, canvas } = host());
+ scene = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: ringBackdrop(vienna) })!;
+ }
+ if (op >= 7) {
+ rebuilds += 1;
+ if (fine) inEase += 1;
+ // A rebuild changes where nothing is: the owner's pose is the same before and after it, and the first frame laid out is the frame that was showing.
+ const after = poseAt(now);
+ expect(after.r, label).toBeCloseTo(before.r, 9);
+ expect(norm(after.phi), label).toBeCloseTo(norm(before.phi), 6);
+ expect(norm(after.h), label).toBeCloseTo(norm(before.h), 6);
+ rigOf(parent).children.forEach((box: any, i: number) => {
+ if (!fine) return;
+ const was = playedAt(old[i], now - old[i].at);
+ const is = parsed(live(box)[0].keyframes[0].transform);
+ // The new stretch is laid out from angles brought into [0, 360): a whole turn of the heading is a whole turn of the shift, the same picture.
+ const turn = is.scale * w2.plane.scale * vienna.view.pxPerDegH * 360;
+ const jump = Math.abs(is.shift - was.shift);
+ expect(Math.abs(jump - turn * Math.round(jump / turn)), `${label}: card ${i} popped at the rebuild`).toBeLessThan(3);
+ expect(Math.abs(is.scale - was.scale), `${label}: card ${i} popped at the rebuild`).toBeLessThan(0.02);
+ });
+ }
+ checkLayout(parent, label);
+ }
+ scene.dispose();
+ return rebuilds;
+ };
+
+ it('every pose laid out is inside the bound the baker set, and a rebuild never moves the view', () => {
+ pending();
+ let rebuilds = 0;
+ for (let seed = 1; seed <= 24; seed += 1) rebuilds += sequence(seed);
+ expect(rebuilds).toBeGreaterThan(100);
+ expect(inEase).toBeGreaterThan(10); // and some of them in the middle of eases, not only at rest
+ vi.useRealTimers();
+ }, 120_000);
+ });
+ });
+
+ describe('under reduced motion there is no ease: the pose owed is the pose issued', () => {
+ const owed = (ring: typeof manifest, offset: number, phi: number, at = T0) => {
+ const p = cardPose(ring, 0, poseAt(at).h, phi, offset, windowFor(ring.view, 400, 800));
+ return `translate3d(${p.shiftPx}px,0,0) scale(${p.scale})`;
+ };
+
+ it('lands on the offset the mode allows at the pick, each way, and the next pick starts from there', () => {
+ const ring = fixtureRing();
+ motion.matches = true;
+ setCamera({ mode: 'both', speedDegPerS: 0.6, offsetM: 200 });
+ const { parent, canvas } = host();
+ const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: ringBackdrop(ring) })!;
+ const box = () => rigOf(parent).children[2];
+ expect(frame(box(), 0)).toBe(owed(ring, 200, 0));
+ setCamera({ mode: 'offset' });
+ expect(frame(box(), 0)).toBe(owed(ring, 98.2, 0)); // the clamp, at once: not the 200 m it showed
+ setCamera({ mode: 'both' });
+ expect(frame(box(), 0)).toBe(owed(ring, 200, 0)); // and back, not the 98.2 it was left at
+ s.dispose();
+ });
+
+ it('lands on the camera angle the mode owes when the setting arrives with the camera turned away from its heading', () => {
+ const ring = fixtureRing();
+ setCamera({ mode: 'offset', speedDegPerS: 12, offsetM: 200 });
+ const { parent, canvas } = host();
+ const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: ringBackdrop(ring) })!;
+ const at = T0 + 7_500; // a quarter round
+ vi.mocked(performance.now).mockReturnValue(at);
+ motion.matches = true;
+ motion.addEventListener.mock.calls.filter((c: any) => c[0] === 'change').forEach((c: any) => c[1]());
+ expect(poseAt(at).phi).toBeCloseTo(90, 6);
+ setCamera({ mode: 'both' }, at);
+ expect(poseAt(at + 10_000).phi).toBe(0);
+ expect(frame(rigOf(parent).children[2], 0)).toBe(owed(ring, 200, 0, at));
+ s.dispose();
+ });
+ });
+
+ it('keeps the angles, the transforms and the tile positions bounded after days of uptime: the rig normalizes before each stretch', () => {
+ const now = vi.mocked(performance.now);
+ const { parent, canvas } = host();
+ const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!;
+ const fiveDays = 5 * 86_400_000;
+ now.mockReturnValue(T0 + fiveDays);
+ setCamera({ offsetM: 20 }); // any change issues the next stretch from the clock now
+ const h = poseAt(T0 + fiveDays).h;
+ expect(h).toBeGreaterThanOrEqual(0);
+ expect(h).toBeLessThan(360 + 1);
+ expect(h).toBeCloseTo((214 + 0.6 * (fiveDays / 1000)) % 360, 4); // the view is where five days of turning put it
+ const rig = rigOf(parent);
+ const shifts = rig.children.flatMap((box: any) =>
+ live(box)[0].keyframes.map((f: any) => Math.abs(Number(/translate3d\((-?[\d.e+-]+)px/.exec(f.transform)?.[1])))
+ );
+ expect(Math.max(...shifts)).toBeLessThan(100_000); // days of turning would be millions of px
+ rig.children.forEach((box: any) =>
+ box.children.forEach((c: any) => expect(Math.abs(parseFloat(c.style.left))).toBeLessThan(100_000))
+ );
+ expect(mountedIds(rig).length).toBeGreaterThan(0); // the tiles the heading shows are mounted, not lost in the wrap
+ s.dispose();
+ });
+ });
+
+ it('a still draws the tiles of the arc in the host canvas, farthest card first, each card at its pose about the rig’s origin, at the heading now', () => {
const { parent, canvas } = host();
createRidgeScene({ canvas, tier: 'still', sky: DAY, backdrop: litCards() });
const drawn = images.filter((a) => (a[0] as any).id) as any[];
- expect(drawn.map((a) => a[0].id)).toEqual(['card-2', 'card-1', 'card-0']);
+ expect(drawn.map((a) => a[0].id)).toEqual(['t2c1', 't2c0']);
+ expect(drawn[0][0].id.endsWith('c1')).toBe(true);
const dpr = 2;
- const s = win.plane.scale * dpr;
- const x0 = (800 - win.plane.w * dpr) / 2;
- const planeTop = 1600 - (win.plane.h + win.plane.bottom) * dpr;
- const origin = [x0 + (win.plane.w * dpr) / 2, planeTop + manifest.view.horizonRow * s];
- drawn.forEach((a, j) => {
- const card = manifest.cards[2 - j];
- expect(a.k).toBe(card.scale);
- expect(a.t).toEqual(origin);
+ drawn.forEach((a) => {
+ const card = Number(a[0].id.slice(-1));
+ const p = posed(manifest, card, T0, win);
+ expect(a.k).toBe(p.scale);
+ expect(a.t).toEqual([(200 + p.shiftPx) * dpr, horizonY * dpr]);
+ const e = manifest.tiles[2][card]!;
+ const colDeg = 360 / view.ringW;
expect([a[1], a[2], a[3], a[4]]).toEqual([
- x0 - origin[0],
- planeTop + card.top * s - origin[1],
- win.plane.w * dpr,
- card.h * s,
+ (180 - colDeg - 214) * k * dpr,
+ (e.top - view.horizonRow) * win.plane.scale * dpr,
+ (view.tileW + 2) * win.plane.scale * dpr,
+ e.h * win.plane.scale * dpr,
]);
expect([a.alpha, a.op]).toEqual([1, 'source-over']);
});
expect(parent.children).toEqual([canvas]);
});
- it('settles to a still with the cards painted when the frame rate is poor', () => {
+ describe('a still whose tiles arrive after its paint', () => {
+ /** A backdrop holding the tiles of `held`, and tiles that arrive afterwards: `arrive` holds one more and tells whoever listens, as the loader does. */
+ const ring = parseManifest(wireManifest({}, 3, 32), '/d/'); // 32 tiles of 11.25 degrees: the rest view shows tiles 16 to 21
+ const arriving = (held: number[]) => {
+ const all = ring.tiles.flatMap((row, tile) =>
+ row.flatMap((e, card) => {
+ if (!e) return [];
+ const canvas = fakeEl('canvas');
+ canvas.id = `t${String(tile).padStart(2, '0')}c${card}`;
+ canvas.width = 202;
+ return [{ tile, card, canvas: canvas as unknown as HTMLCanvasElement }];
+ })
+ );
+ const lit = all.filter((t) => held.includes(t.tile));
+ const heard = new Set<() => void>();
+ const bd = {
+ manifest: ring,
+ ensure: vi.fn(async (_arc: Arc): Promise => undefined),
+ litTiles: () => lit,
+ onTile: (cb: () => void) => (heard.add(cb), () => void heard.delete(cb)),
+ dispose: vi.fn(),
+ };
+ const arrive = (tile: number) => {
+ lit.push(...all.filter((t) => t.tile === tile));
+ heard.forEach((cb) => cb());
+ };
+ return { bd, arrive, listeners: () => heard.size };
+ };
+ const drawnTiles = () => new Set(images.filter((a) => (a[0] as any).id).map((a: any) => a[0].id.slice(0, 3)));
+ const timers = () => {
+ vi.useFakeTimers();
+ (window as any).setTimeout = setTimeout;
+ (window as any).clearTimeout = clearTimeout;
+ };
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('repaints once for a burst of arrivals, with every tile held by then, asks for nothing, and is done when the tiles stop', () => {
+ timers();
+ const { bd, arrive } = arriving([18]);
+ const { canvas } = host();
+ const s = createRidgeScene({ canvas, tier: 'still', sky: DAY, backdrop: bd })!;
+ expect(drawnTiles()).toEqual(new Set(['t18']));
+ const first = images.length;
+ arrive(17);
+ vi.advanceTimersByTime(100);
+ arrive(19); // a burst: the wait starts again
+ vi.advanceTimersByTime(200);
+ expect(images.length).toBe(first); // not yet
+ vi.advanceTimersByTime(60);
+ expect(drawnTiles()).toEqual(new Set(['t18', 't17', 't19'])); // one paint, with all of them
+ const second = images.length;
+ expect(second).toBeGreaterThan(first);
+ vi.advanceTimersByTime(600_000);
+ expect(images.length).toBe(second); // no loop, no timer left
+ expect(bd.ensure).not.toHaveBeenCalled();
+ arrive(20);
+ vi.advanceTimersByTime(300);
+ expect(drawnTiles().has('t20')).toBe(true); // a straggler is drawn too
+ s.dispose();
+ });
+
+ it('a still shows one pose: a tile that arrives half a minute late is drawn at the pose of the first paint, and a resize takes the pose of its own clock', () => {
+ timers();
+ const { bd, arrive } = arriving([18]);
+ const { canvas } = host();
+ const s = createRidgeScene({ canvas, tier: 'still', sky: DAY, backdrop: bd })!;
+ const placed = (id: string) => images.filter((a) => (a[0] as any).id?.startsWith(id)).map((a: any) => [a.t, a[1], a[2], a[3], a[4], a.k]);
+ const first = placed('t18');
+ expect(first.length).toBeGreaterThan(0);
+ images.length = 0;
+ vi.spyOn(performance, 'now').mockReturnValue(T0 + 30_000); // the clock has turned the heading 18 degrees on
+ arrive(17);
+ vi.advanceTimersByTime(300);
+ expect(drawnTiles()).toEqual(new Set(['t18', 't17'])); // the tile chosen for the first pose is on the canvas
+ expect(placed('t18')).toEqual(first); // and the old ones have not moved
+ expect(bd.ensure).not.toHaveBeenCalled();
+ images.length = 0;
+ window.dispatchEvent(new Event('resize'));
+ vi.advanceTimersByTime(300);
+ expect(bd.ensure).toHaveBeenCalledTimes(1); // a new view: the tiles of the pose it takes
+ const arc = bd.ensure.mock.calls[0][0];
+ expect((arc.fromDeg + arc.toDeg) / 2).toBeCloseTo(poseAt(T0 + 30_000).h, 6);
+ expect(placed('t18')).not.toEqual(first);
+ s.dispose();
+ });
+
+ it('is the same after a settle from the live tier, and stops listening with the scene', () => {
+ timers();
+ const { bd, arrive, listeners } = arriving([18]);
+ const { canvas } = host();
+ const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: bd })!;
+ arrive(17);
+ vi.advanceTimersByTime(1_000);
+ expect(images.length).toBe(0); // the live tier mounts tiles from its own timer: nothing is painted into the host canvas
+ runFrames(100, 400); // a poor frame rate: it settles to a still
+ const settled = images.length;
+ expect(drawnTiles()).toEqual(new Set(['t18', 't17']));
+ arrive(19);
+ vi.advanceTimersByTime(300);
+ expect(images.length).toBeGreaterThan(settled);
+ expect(drawnTiles().has('t19')).toBe(true);
+ s.dispose();
+ expect(listeners()).toBe(0);
+ const after = images.length;
+ arrive(20);
+ vi.advanceTimersByTime(1_000);
+ expect(images.length).toBe(after);
+ });
+ });
+
+ it('settles to a still with the tiles painted when the frame rate is poor', () => {
const { parent, canvas } = host();
createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() });
runFrames(100, 400);
- expect(images.filter((a) => (a[0] as any).id)).toHaveLength(3);
+ expect(images.filter((a) => (a[0] as any).id).length).toBeGreaterThan(0);
expect(parent.children).toEqual([canvas]);
});
@@ -719,7 +1935,7 @@ describe('the ridge cards in the scene', () => {
expect(images.filter((a) => (a[0] as any).id)).toHaveLength(0);
});
- it('asks the host canvas, and every canvas it makes, only for 2d: the cards arrive lit', () => {
+ it('asks the host canvas, and every canvas it makes, only for 2d: the tiles arrive lit', () => {
const { canvas } = host();
const kinds: string[] = [];
const ask = (el: any) => {
diff --git a/src/app/features/scene/ridge/Ridge.ts b/src/app/features/scene/ridge/Ridge.ts
index 639c4df1..b6f5d729 100644
--- a/src/app/features/scene/ridge/Ridge.ts
+++ b/src/app/features/scene/ridge/Ridge.ts
@@ -3,12 +3,19 @@ import { overlayRequested } from '../debugOverlays';
import { FrameSampler, FrameStats } from './probe';
import { skyColours, SkyColours, Srgb } from './skyColour';
import { paintSky as paintPhysicalSky } from './physicalSky';
-import { cardMotion, windowFor } from './view';
-import { activeAt, drawTwinkle as paintTwinkle, Star } from './stars';
+import { cardArc, cardPose, HFOV_MAX_DEG, offsetRange, SEGMENT_S, sweepArc, windowFor } from './view';
+import type { Camera, CardPose, View } from './view';
+import type { TileCard } from './manifest';
+import { residentTiles } from './ring';
+import { freeze, normalize, poseAt as headingPose, setRange, settledAt, subscribe as onHeading, turnRate } from './heading';
+import type { Pose } from './heading';
+import { activeAt, drawTwinkle as paintTwinkle, slotsFor, Star } from './stars';
+import { STAR_COUNT } from './nightSkyData';
+import { alignTurns, panPx, plateCamera, plateSize, recentre, slackFor } from './skyTurn';
import { nightBodies, paintNightBodies } from './nightBodies';
import type { NightBodies } from './nightBodies';
import { drawRainTile, RAIN_TILES } from './rain';
-import type { Backdrop } from './Backdrop';
+import type { Arc, Backdrop, LitTile } from './Backdrop';
export type RidgeOptions = Pick & {
/** Show the rAF median/p95 readout. Default: the page URL has `?probe=1`, where `debug` allows it. */
@@ -19,7 +26,7 @@ export type RidgeOptions = Pick & {
onProbe?: (s: FrameStats & { still: boolean }) => void;
/** The sky's colours; default `skyColours()`, the one function to replace with Void's sun.js. */
sky?: SkyColours;
- /** The baked ridge cards, already lit for `sky` (`Backdrop.ts`); none is the sky-only scene (`view.ts` FALLBACK_VIEW). */
+ /** The baked ridge cards by tile, lit for `sky` (`Backdrop.ts`), the arc around the heading already made; none is the sky-only scene (`view.ts` FALLBACK_VIEW). The scene owns it from here and disposes it with itself. */
backdrop?: Backdrop;
/** Draw the constellation lines over the stars (a hidden extra, `skyState.ts`); only a night sky shows them. */
lines?: boolean;
@@ -50,25 +57,21 @@ function drawSun(
}
/**
- * The host canvas's sky: the physical sky (`physicalSky.ts`) as a small grid of display pixels, scaled up smoothly (it is a soft
- * field); without one, the three-stop gradient.
+ * A canvas's sky: the physical sky (`physicalSky.ts`) seen through `camera` as a small grid of display pixels, scaled up smoothly (it is a soft
+ * field); without one, the three-stop gradient. `cssW` and `cssH` are the canvas's size in CSS px, which `camera`'s field of view spans.
*/
function paintSky(
canvas: HTMLCanvasElement,
sky: SkyColours,
+ camera: Camera | undefined,
cssW: number,
cssH: number,
makeCanvas: () => HTMLCanvasElement
): { ok: boolean; px?: ReturnType } {
const ctx = context2d(canvas);
if (!ctx) return { ok: false };
- if (sky.physical) {
- const px = paintPhysicalSky(
- sky.physical,
- cssW,
- cssH,
- windowFor(sky.physical.view, cssW, cssH).camera
- );
+ if (sky.physical && camera) {
+ const px = paintPhysicalSky(sky.physical, cssW, cssH, camera);
const small = makeCanvas();
small.width = px.w;
small.height = px.h;
@@ -96,11 +99,53 @@ function paintSky(
const clock = (): number => (typeof performance !== 'undefined' ? performance.now() : Date.now());
-interface Built {
- /** The twinkling stars' own canvas, over the sky; absent in a day sky and in 'still'. */
+/** The rig: one box per card, each holding that card's resident tiles and carried by one animation of its pose. */
+interface Rig {
+ el: HTMLElement;
+ anims: (Animation | undefined)[];
+ /** Issue the next stretch of every card's motion from the heading owner's clock now (a tab shown again). */
+ reissue: () => void;
+ /** Take the viewer's mode and speed to the heading owner again, then reissue (reduced motion switched). */
+ sync: () => void;
+ /** Stop the residency timer and the subscriptions. */
+ stop: () => void;
+}
+
+/**
+ * The sky of a live scene: one element, wider than the viewport, holding the painted sky (every real body baked into it) and, with stars, the twinkling
+ * stars' canvas over it. One animation slides it with the heading (`skyTurn.ts`). Replaced, element and all, when the heading nears its edge.
+ */
+interface Plate {
+ el: HTMLElement;
+ /** The twinkle canvas of this plate, over its sky; absent in a day sky. */
twinkle?: HTMLCanvasElement;
- /** The ridge cards' rig, over the twinkle canvas and under the rain; absent in 'still' (the cards are drawn into the host canvas). */
- rig?: { el: HTMLElement; anims: (Animation | undefined)[] };
+ /** The stars this plate was painted with, by catalogue index: the identity the twinkle schedule is keyed by. */
+ stars: ReadonlyMap;
+ /** Device pixels per CSS px of the plate's canvases (capped by `PLATE_MAX_PX`). */
+ ratio: number;
+ /** Degrees of sky it holds beyond the viewport each side (`skyTurn.ts` `slackFor`, at the speed it was painted for). */
+ slack: number;
+ /** The compass azimuth the plate is centred on, unwrapped to the heading owner's turn. */
+ centre: number;
+ /** The one animation that slides it. */
+ anim?: Animation;
+ /**
+ * Paint a new plate about the heading in this one's place when the heading is near its edge, or the speed in force needs more slack than it has; `periodMs`:
+ * the real period of the residency tick. True when it did, and then the slide is not keyed yet: `key` it, from a clock read after this.
+ */
+ refit: (periodMs: number) => boolean;
+ /** Key the slide from `t0` (ms), the heading owner's clock read after the plate was last painted; `play`: the motion runs. */
+ key: (t0: number, frozen: boolean, play: boolean) => void;
+ /** The residency tick: refit, and key from the clock after the paint if it painted. */
+ tend: (periodMs: number) => void;
+ stop: () => void;
+}
+
+interface Built {
+ /** The sky and its twinkling stars, under the rig; absent in 'still' (the sky is painted into the host canvas) and in a sky with no physical model (a gradient in the host canvas). */
+ plate?: Plate;
+ /** The ridge cards' rig, over the plate and under the rain; absent in 'still' (the cards are drawn into the host canvas). */
+ rig?: Rig;
/** The rain's tiles and their falling, present only when the weather rains (`rain.ts`). */
rain?: { els: HTMLElement[]; anims: (Animation | undefined)[] };
}
@@ -108,8 +153,38 @@ interface Built {
/** The twinkle overlay redraws at most this often: the swings are 2 to 7 s, no need for 60 fps. */
const TWINKLE_FRAME_MS = 50;
-/** One leg of the back-and-forth drift, a turn of the heading from one end of its range to the other, takes DRIFT_LEG_S, so the loop is 150 s. Authored, tunable by eye. */
-const DRIFT_LEG_S = 75;
+/**
+ * A card's motion is issued as one animation of SEGMENT_S seconds (`view.ts`), a keyframe each second sampled from the heading owner (`heading.ts`) and the
+ * viewer's offset, and issued again once REISSUE_FRAC of it has run, so the compositor always has the next stretch before it needs it. Authored.
+ */
+const REISSUE_FRAC = 0.8;
+/** How often the arc of tiles ahead is asked for and the mounted tiles are brought up to date. */
+export const RESIDENCY_MS = 500;
+
+/** Keyframe spacing while an ease runs, ms: fine enough that the straight lines between them are the smoothstep to a pixel. */
+const EASE_KEY_MS = 50;
+/** The instants of a stretch keyed finely up to `easeMs`, then every second to SEGMENT_S: ms from the stretch's start, ascending, ending at the stretch's length. */
+const easeTimes = (easeMs: number): number[] => {
+ const times: number[] = [];
+ for (let ms = 0; ms < easeMs; ms += EASE_KEY_MS) times.push(ms);
+ times.push(easeMs);
+ for (let ms = (Math.floor(easeMs / 1000) + 1) * 1000; ms <= SEGMENT_S * 1000; ms += 1000) times.push(ms);
+ return times;
+};
+
+/**
+ * The keyframes of a stretch of motion from `t0` (ms), the transform at each instant from `transformAt`: a keyframe a second for SEGMENT_S seconds, finely
+ * keyed while an ease of the heading owner runs, constant under reduced motion. The cards and the sky are keyed by it alike, so they turn together.
+ */
+const stretch = (t0: number, frozen: boolean, transformAt: (t: number) => string): Keyframe[] => {
+ if (frozen) {
+ const at = transformAt(t0);
+ return [{ transform: at }, { transform: at }];
+ }
+ const easeMs = Math.min(SEGMENT_S * 1000, Math.max(0, settledAt() - t0));
+ if (easeMs > 0) return easeTimes(easeMs).map((ms) => ({ transform: transformAt(t0 + ms), offset: ms / (SEGMENT_S * 1000) }));
+ return Array.from({ length: SEGMENT_S + 1 }, (_, n) => ({ transform: transformAt(t0 + n * 1000) }));
+};
/**
* The ridge scene: same contract as `createScene` ({ login, dispose }, null for "keep the CSS
@@ -128,14 +203,17 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
const reducedMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)');
let built: Built | undefined;
- let field: Star[] = [];
let twRaf = 0;
let twLast = 0;
+ /** Paint a plate's twinkle canvas at t seconds, or clear it (set by the plate the scene is up with). */
+ let paintTwinkleOf: (of: Pick, t?: number) => void = () => undefined;
let still = tier === 'still';
let disposed = false;
let raf = 0;
let readout: HTMLElement | undefined;
let resizeTimer = 0;
+ /** The pose a still shows: taken at its first paint and drawn at every repaint after, tile arrivals included; a resize takes a new one. A still has no clock. */
+ let stillPose: Pose | undefined;
const sampler = new FrameSampler();
const viewSize = () => {
@@ -144,8 +222,11 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
return { w, h, scale: (window.devicePixelRatio || 1) >= 2 ? 2 : 1 };
};
+ const makeCanvas = () => document.createElement('canvas');
+
const teardown = () => {
- built?.twinkle?.remove();
+ built?.plate?.stop();
+ built?.rig?.stop();
built?.rig?.anims.forEach((a) => a?.cancel());
built?.rig?.el.remove();
built?.rain?.anims.forEach((a) => a?.cancel());
@@ -211,15 +292,29 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
return { els, anims };
};
+ /** Where a tile sits in a card's box, in viewport px from the centre column and the horizon: its left edge (one overlap column before its interior) and its band. */
+ const tileBox = (view: View, scale: number, lt: LitTile, turn: number, entry: TileCard) => {
+ const colDeg = 360 / view.ringW;
+ const az = turn * 360 + (lt.tile * 360) / view.tiles - colDeg;
+ return {
+ left: (az - view.lookAzDeg) * view.pxPerDegH * scale,
+ top: (entry.top - view.horizonRow) * scale,
+ w: (view.tileW + 2) * scale,
+ h: entry.h * scale,
+ };
+ };
+
/**
- * The ridge over the sky: one element per lit card, farthest first (DOM order is paint order, stacking is by order alone), placed at the card's rows
- * of the plane and scaled about the horizon's centre by the baker's `scale` (`view.ts` `cardMotion` owns every offset and scale). The camera
- * turns through its heading range and back on the compositor: card i pans `scale` x heading, so a nearer card leads the far range.
+ * The ridge over the sky: one box per card, farthest first (DOM order is paint order, stacking is by order alone). A box spans the viewport with its
+ * transform origin on the horizon centre and holds the resident tiles of its card at their azimuth; one animation per box carries its pose
+ * (`view.ts` `cardPose`) over SEGMENT_S seconds of the heading owner's clock. A timer asks the backdrop for the arc ahead and mounts what it has made.
*/
- const startRig = (bd: Backdrop, w: number, h: number): NonNullable => {
+ const startRig = (bd: Backdrop, w: number, h: number, plate?: Plate): Rig => {
const { view } = bd.manifest;
const win = windowFor(view, w, h);
- const motion = cardMotion(bd.manifest, win);
+ const planeTop = h - win.plane.bottom - win.plane.h;
+ const horizonY = planeTop + view.horizonRow * win.plane.scale;
+ const k = bd.manifest.cards.length;
const el = document.createElement('div');
el.setAttribute('aria-hidden', 'true');
Object.assign(el.style, {
@@ -231,65 +326,282 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
overflow: 'hidden',
pointerEvents: 'none',
});
- const anims: (Animation | undefined)[] = [];
- const planeTop = h - win.plane.bottom - win.plane.h;
- for (let k = bd.cards.length - 1; k >= 0; k -= 1) {
- const card = bd.cards[k];
- const { scale, reachPx } = motion.cards[k];
- const node = card.canvas;
- Object.assign(node.style, {
+ const boxes: HTMLElement[] = [];
+ for (let i = k - 1; i >= 0; i -= 1) {
+ const box = document.createElement('div');
+ box.id = `card-${i}`;
+ Object.assign(box.style, {
position: 'absolute',
- left: `${(w - win.plane.w) / 2}px`,
- top: `${planeTop + card.top * win.plane.scale}px`,
- width: `${win.plane.w}px`,
- height: `${card.h * win.plane.scale}px`,
- transformOrigin: `${win.plane.w / 2}px ${(view.horizonRow - card.top) * win.plane.scale}px`,
+ left: '0',
+ top: '0',
+ width: `${w}px`,
+ height: `${h}px`,
+ transformOrigin: `${w / 2}px ${horizonY}px`,
willChange: 'transform',
+ pointerEvents: 'none',
});
- el.appendChild(node);
- anims.push(
- node.animate?.(
- [
- { transform: `translate3d(${-reachPx}px,0,0) scale(${scale})` },
- { transform: `translate3d(${reachPx}px,0,0) scale(${scale})` },
- ],
- {
- duration: DRIFT_LEG_S * 1000,
- iterations: Infinity,
- direction: 'alternate',
- easing: 'ease-in-out',
- }
- )
- );
+ el.appendChild(box);
+ boxes[i] = box;
}
+ const anims: (Animation | undefined)[] = new Array(k).fill(undefined);
+ freeze(reducedMotion?.matches === true, clock()); // reduced motion turns nothing, whatever the viewer chose
+ /** A card's pose at the clock `t`: the heading owner's pose (view direction, camera angle, offset), the one place any of them is decided. */
+ const poseAt = (card: number, t: number): CardPose => {
+ const p = headingPose(t);
+ return cardPose(bd.manifest, card, p.h, p.phi, p.r, win);
+ };
+ const transform = (p: CardPose) => `translate3d(${p.shiftPx}px,0,0) scale(${p.scale})`;
+ let issuedAt = 0;
+ let live = true;
+
+ /** The next stretch of every card's motion, from now: it replaces the one running, which agrees with it where they meet. */
+ const issue = () => {
+ if (!live) return;
+ normalize(clock()); // the angles of this stretch start within a turn of zero, so the transforms stay small however long the page has been open
+ plate?.refit(tickMs); // a new plate costs a paint: whatever it costs, the cards and the sky are keyed from the clock after it, so none of it is lag
+ const t0 = clock();
+ issuedAt = t0;
+ const frozen = reducedMotion?.matches === true;
+ const play = moving();
+ for (let i = 0; i < k; i += 1) {
+ const frames = stretch(t0, frozen, (t) => transform(poseAt(i, t)));
+ boxes[i].style.transform = frames[0].transform as string;
+ anims[i]?.cancel();
+ anims[i] = boxes[i].animate?.(frames, {
+ duration: SEGMENT_S * 1000,
+ easing: 'linear',
+ fill: 'forwards',
+ });
+ if (!play) anims[i]?.pause();
+ }
+ plate?.key(t0, frozen, play); // the sky turns on the same keyframes, from the same poses
+ mount(sweep(t0)); // laid out from the same angles as the keyframes, in the same tick
+ };
+
+ /** The arc of azimuth any card shows at any instant of the stretch from `t0`: every pose it passes through, not its ends. */
+ const sweep = (t0: number): Arc => sweepArc(view, win, w, k, poseAt, t0, SEGMENT_S);
+
+ const mounted = new Map();
+ /** Put the made tiles the arc shows into their card's box at their azimuth, and take the others out. */
+ const mount = (arc: Arc) => {
+ const refs = residentTiles(view, (arc.fromDeg + arc.toDeg) / 2, (arc.toDeg - arc.fromDeg) / 2);
+ const turnOf = new Map(refs.map((r) => [r.tile, r.turn]));
+ const keep = new Set();
+ for (const lt of bd.litTiles()) {
+ const turn = turnOf.get(lt.tile);
+ const entry = bd.manifest.tiles[lt.tile][lt.card];
+ if (turn === undefined || !entry) continue;
+ keep.add(lt.canvas);
+ if (mounted.get(lt.canvas) === turn && lt.canvas.parentElement === boxes[lt.card]) continue;
+ const b = tileBox(view, win.plane.scale, lt, turn, entry);
+ Object.assign(lt.canvas.style, {
+ position: 'absolute',
+ left: `${w / 2 + b.left}px`,
+ top: `${horizonY + b.top}px`,
+ width: `${b.w}px`,
+ height: `${b.h}px`,
+ });
+ mounted.set(lt.canvas, turn);
+ boxes[lt.card].appendChild(lt.canvas);
+ }
+ for (const c of [...mounted.keys()]) {
+ if (keep.has(c)) continue;
+ c.remove();
+ mounted.delete(c);
+ }
+ };
+
+ // The one timer: ask for the arc ahead, mount what is made, and issue the next stretch once this one is mostly spent.
+ const win0 = window;
+ let timer = 0;
+ let lastTick: number | undefined;
+ /** The real period of the tick, ms: what the last two began apart (a tick is a timeout chain, so its work and its lateness are in it), never less than RESIDENCY_MS. */
+ let tickMs = RESIDENCY_MS;
+ const residency = () => {
+ timer = 0;
+ if (!live) return;
+ const t = clock();
+ if (lastTick !== undefined) tickMs = Math.max(RESIDENCY_MS, t - lastTick);
+ lastTick = t;
+ const play = moving();
+ if (play && t - issuedAt >= SEGMENT_S * 1000 * REISSUE_FRAC) issue();
+ else if (play) plate?.tend(tickMs);
+ const arc = sweep(t);
+ mount(arc);
+ void bd.ensure(arc, sweepArc(view, win, w, k, poseAt, t, 0)).then(() => live && mount(arc)); // the view now first, then along the sweep
+ timer = win0.setTimeout(residency, RESIDENCY_MS);
+ };
parent.appendChild(el);
- return { el, anims };
+ issue();
+ const sync = () => {
+ freeze(reducedMotion?.matches === true, clock());
+ issue();
+ };
+ const offHeading = onHeading(issue); // every change of the pose's course: the viewer's choice, a hold, a bound, a place
+ timer = win0.setTimeout(residency, RESIDENCY_MS);
+ return {
+ el,
+ anims,
+ reissue: issue,
+ sync,
+ stop: () => {
+ live = false;
+ win0.clearTimeout(timer);
+ offHeading();
+ },
+ };
};
- /** Paint the lit cards into the host canvas, farthest first, each at its scale about the same origin as the rig, at heading 0: the still scene's one image. */
+ /** Paint the lit tiles of every card into the host canvas, farthest first, each card at its pose about the rig's origin, at the pose the still froze at its first paint: the still scene's one image. */
const paintCards = (bd: Backdrop) => {
const ctx = context2d(canvas);
if (!ctx) return;
const { view } = bd.manifest;
- const { w, h, scale } = viewSize();
+ const { w, h, scale: dpr } = viewSize();
const win = windowFor(view, w, h);
- const s = win.plane.scale * scale;
- const dw = win.plane.w * scale;
- const x0 = (canvas.width - dw) / 2;
- const planeTop = canvas.height - (win.plane.h + win.plane.bottom) * scale;
- const ox = x0 + dw / 2;
- const oy = planeTop + view.horizonRow * s;
- for (let k = bd.cards.length - 1; k >= 0; k -= 1) {
- const card = bd.cards[k];
+ stillPose ??= headingPose(clock());
+ const at = stillPose;
+ const planeTop = h - win.plane.bottom - win.plane.h;
+ const horizonY = planeTop + view.horizonRow * win.plane.scale;
+ const poses = bd.manifest.cards.map((_, i) =>
+ cardPose(bd.manifest, i, at.h, at.phi, at.r, win)
+ );
+ const arcs = poses.map((p) => cardArc(view, win, w, p));
+ const from = Math.min(...arcs.map((a) => a.fromDeg));
+ const to = Math.max(...arcs.map((a) => a.toDeg));
+ const turnOf = new Map(residentTiles(view, (from + to) / 2, (to - from) / 2).map((r) => [r.tile, r.turn]));
+ const lit = bd.litTiles();
+ for (let i = poses.length - 1; i >= 0; i -= 1) {
ctx.save();
- ctx.translate(ox, oy);
- ctx.scale(card.scale, card.scale);
- ctx.drawImage(card.canvas, x0 - ox, planeTop + card.top * s - oy, dw, card.h * s);
+ ctx.translate((w / 2 + poses[i].shiftPx) * dpr, horizonY * dpr);
+ ctx.scale(poses[i].scale, poses[i].scale);
+ for (const lt of lit.filter((x) => x.card === i)) {
+ const turn = turnOf.get(lt.tile);
+ const entry = bd.manifest.tiles[lt.tile][i];
+ if (turn === undefined || !entry) continue;
+ const b = tileBox(view, win.plane.scale, lt, turn, entry);
+ ctx.drawImage(lt.canvas, b.left * dpr, b.top * dpr, b.w * dpr, b.h * dpr);
+ }
ctx.restore();
}
};
- /** Paint the sky, the stars and the rain. Returns false when a 2D context is missing or there is no area yet. */
+ /** A still's one image in the host canvas: the sky facing the pose it froze at, its bodies, and the cards of that pose over them. */
+ const paintStill = () => {
+ const { w, h, scale } = viewSize();
+ const physical = sky.physical;
+ if (opts.backdrop) stillPose ??= headingPose(clock());
+ const facing = stillPose?.h ?? physical?.view.lookAzDeg ?? 0; // with no ridge there is no heading: the place's rest azimuth
+ const camera = physical && plateCamera(windowFor(physical.view, w, h), facing, 0);
+ const painted = paintSky(canvas, sky, camera, w, h, makeCanvas);
+ const ctx = context2d(canvas);
+ if (ctx && physical && painted.px)
+ paintNightBodies(ctx, nightBodies(physical, painted.px, opts.lines === true), canvas.width, canvas.height, scale);
+ if (opts.backdrop) paintCards(opts.backdrop);
+ };
+
+ /**
+ * The sky of a live scene (`skyTurn.ts`): a plate painted about the heading the view has, under a stretch of the heading owner's keyframes. The real stars,
+ * the moon and (when asked) the constellation lines are baked into the plate's sky; the twinkling stars get their own canvas on it, which a per-frame pass
+ * clears and paints over. A sky-only scene has no rig to issue it: its plate faces the place's rest azimuth and stays.
+ */
+ const startPlate = (physical: NonNullable, w: number, h: number, dpr: number): Plate | undefined => {
+ const win = windowFor(physical.view, w, h);
+ const pxPerDeg = w / win.camera.hfovDeg;
+ /** Slots of the twinkle schedule, fixed by the first plate: the schedule runs over the catalogue, so every plate of this sky twinkles the same stars in the same phase. */
+ let slots = 0;
+ const paint = (centre: number, slack: number) => {
+ const { cssW, ratio } = plateSize(win, w, h, dpr, slack);
+ const el = document.createElement('div');
+ el.setAttribute('aria-hidden', 'true');
+ Object.assign(el.style, {
+ position: 'absolute',
+ left: `${(w - cssW) / 2}px`,
+ top: '0',
+ width: `${cssW}px`,
+ height: `${h}px`,
+ willChange: 'transform',
+ pointerEvents: 'none',
+ });
+ const layer = (): HTMLCanvasElement => {
+ const c = document.createElement('canvas');
+ c.width = Math.floor(cssW * ratio);
+ c.height = Math.floor(h * ratio);
+ c.setAttribute('aria-hidden', 'true');
+ Object.assign(c.style, { position: 'absolute', left: '0', top: '0', width: '100%', height: '100%', pointerEvents: 'none' });
+ el.appendChild(c);
+ return c;
+ };
+ const skyEl = layer();
+ const painted = paintSky(skyEl, sky, plateCamera(win, centre, slack), cssW, h, makeCanvas);
+ const skyCtx = context2d(skyEl);
+ if (!painted.ok || !painted.px || !skyCtx) return undefined;
+ const bodies: NightBodies = nightBodies(physical, painted.px, opts.lines === true);
+ paintNightBodies(skyCtx, bodies, skyEl.width, skyEl.height, ratio);
+ slots ||= slotsFor(STAR_COUNT, bodies.stars.length);
+ return {
+ el,
+ twinkle: bodies.stars.length ? layer() : undefined,
+ stars: new Map(bodies.stars.map((star) => [star.id, star])),
+ ratio,
+ slack,
+ };
+ };
+ /** The overlay of `of` at `t` seconds: the stars of the catalogue that twinkle then, those of them this plate has. */
+ paintTwinkleOf = (of, t) => {
+ const el = of.twinkle;
+ const ctx = el && context2d(el);
+ if (!el || !ctx) return;
+ const active = t === undefined ? [] : activeAt(STAR_COUNT, t, slots);
+ paintTwinkle(ctx, of.stars, active, el.width, el.height, of.ratio);
+ };
+ const facing = opts.backdrop ? headingPose(clock()).h : physical.view.lookAzDeg; // with no ridge there is no heading: the place's rest azimuth
+ const first = paint(facing, slackFor(turnRate(), RESIDENCY_MS));
+ if (!first) return undefined;
+ parent.appendChild(first.el);
+ /** The slide from `t0` of a plate centred on `centre`: its pan at every instant of the stretch is the heading owner's `h` there against that centre. */
+ const key = (el: HTMLElement, centre: number, t0: number, frozen: boolean, play: boolean): Animation | undefined => {
+ const frames = stretch(t0, frozen, (t) => `translate3d(${panPx(headingPose(t).h, centre, pxPerDeg)}px,0,0)`);
+ el.style.transform = frames[0].transform as string;
+ const anim = el.animate?.(frames, { duration: SEGMENT_S * 1000, easing: 'linear', fill: 'forwards' });
+ if (!play) anim?.pause();
+ return anim;
+ };
+ const plate: Plate = {
+ ...first,
+ centre: facing,
+ refit: (periodMs) => {
+ const at = headingPose(clock()).h;
+ plate.centre = alignTurns(plate.centre, at);
+ const rate = turnRate();
+ const slack = slackFor(rate, RESIDENCY_MS);
+ if (slack <= plate.slack && !recentre(at, plate.centre, plate.slack, rate, periodMs)) return false;
+ // A plate about the heading, in the place of this one: the same sky at the same place on the screen, so nothing moves. Undefined (this one stays) if it cannot be painted.
+ const next = paint(at, slack);
+ if (!next) return false;
+ if (moving()) paintTwinkleOf(next, clock() / 1000); // its twinkles as the old one's are now: shown with the stars already swinging
+ parent.insertBefore(next.el, plate.el);
+ plate.anim?.cancel();
+ plate.el.remove();
+ Object.assign(plate, next, { centre: at, anim: undefined });
+ return true;
+ },
+ key: (t0, frozen, play) => {
+ plate.anim?.cancel();
+ plate.anim = key(plate.el, plate.centre, t0, frozen, play);
+ },
+ tend: (periodMs) => {
+ if (plate.refit(periodMs)) plate.key(clock(), false, true); // ticks run only while moving
+ },
+ stop: () => {
+ plate.anim?.cancel();
+ plate.el.remove();
+ },
+ };
+ return plate;
+ };
+
+ /** Paint the cards' rig, the sky and the rain. Returns false when a 2D context is missing or there is no area yet. */
const build = (): boolean => {
teardown();
// A zero-size canvas throws on drawImage; wait for the first resize that gives the host an area.
@@ -297,36 +609,22 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
const { w, h, scale } = viewSize();
canvas.width = Math.round(w * scale);
canvas.height = Math.round(h * scale);
- const painted = paintSky(canvas, sky, w, h, () => document.createElement('canvas'));
- if (!painted.ok) return false;
- // The real stars, the moon and (when asked) the constellation lines are baked into the sky; the twinkling stars get their own
- // canvas, which a per-frame pass clears and paints over. 'still' has no overlay. A sky with no physical model has no bodies.
- const bodies: NightBodies =
- painted.px && sky.physical
- ? nightBodies(sky.physical, painted.px, opts.lines === true)
- : { stars: [], lines: [] };
- const stars = bodies.stars;
- const skyCtx = context2d(canvas);
- if (skyCtx) paintNightBodies(skyCtx, bodies, canvas.width, canvas.height, scale);
- let twinkle: HTMLCanvasElement | undefined;
- if (stars.length && tier !== 'still') {
- twinkle = document.createElement('canvas');
- twinkle.width = canvas.width;
- twinkle.height = canvas.height;
- twinkle.setAttribute('aria-hidden', 'true');
- Object.assign(twinkle.style, {
- position: 'absolute',
- left: '0',
- top: '0',
- width: '100%',
- height: '100%',
- pointerEvents: 'none',
- });
- parent.appendChild(twinkle);
+ if (!context2d(canvas)) return false;
+ built = {};
+ if (!still) {
+ // The host canvas keeps a still's sky (`paintStill`); a live scene's physical sky is a plate over it, and one with none is a gradient in the host canvas.
+ if (sky.physical) {
+ built.plate = startPlate(sky.physical, w, h, scale);
+ if (!built.plate) return false;
+ } else if (!paintSky(canvas, sky, undefined, w, h, makeCanvas).ok) return false;
+ }
+ if (opts.backdrop) {
+ // The offsets this place and viewport allow, to the one owner of the pose: a rebuild at another size is a new bound, and the view eases from the pose it has.
+ const { manifest } = opts.backdrop;
+ const win = windowFor(manifest.view, w, h);
+ setRange((mode, phi) => offsetRange(manifest, win, mode, phi), clock());
+ if (!still) built.rig = startRig(opts.backdrop, w, h, built.plate);
}
- field = stars;
- built = { twinkle };
- if (opts.backdrop && !still) built.rig = startRig(opts.backdrop, w, h);
if (tier !== 'still' && sky.physical && sky.physical.weather.rain > 0)
built.rain = startRain(sky.physical.weather.rain, sky.horizon, w, h, scale);
syncPlayState();
@@ -339,20 +637,16 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
!(reducedMotion?.matches ?? false) &&
document.visibilityState === 'visible';
- /** Paint the overlay at t seconds (stars away from base), or just clear it with no t (all at base). */
+ /** Paint the overlay of the plate that is up at t seconds (stars away from base), or just clear it with no t (all at base). */
const drawTwinkle = (t?: number) => {
- const el = built?.twinkle;
- const ctx = el && context2d(el);
- if (!el || !ctx) return;
- const active = t === undefined ? [] : activeAt(field.length, t);
- paintTwinkle(ctx, field, active, el.width, el.height, viewSize().scale);
+ if (built?.plate) paintTwinkleOf(built.plate, t);
};
// The same guard as the drift: not still, not disposed, not reduced motion, tab visible. Not moving
// stops the loop and leaves the stars steady at base brightness.
const twTick = (now: number) => {
twRaf = 0;
- if (!moving() || !built?.twinkle) return;
+ if (!moving() || !built?.plate?.twinkle) return;
if (now - twLast >= TWINKLE_FRAME_MS) {
twLast = now;
drawTwinkle(now / 1000);
@@ -361,9 +655,10 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
};
function syncPlayState() {
- const anims = [...(built?.rig?.anims ?? []), ...(built?.rain?.anims ?? [])];
+ if (moving()) built?.rig?.reissue();
+ const anims = [...(built?.rig?.anims ?? []), ...(built?.rain?.anims ?? []), built?.plate?.anim];
anims.forEach((a) => (moving() ? a?.play() : a?.pause()));
- if (!built?.twinkle) return;
+ if (!built?.plate?.twinkle) return;
if (moving()) {
if (!twRaf) twRaf = requestAnimationFrame(twTick);
} else {
@@ -376,11 +671,12 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
/** Drop the twinkle and the rain, leaving the painted sky as a still image. */
const settleToStill = () => {
if (still && !built) return;
+ if (!still) stillPose = undefined; // a live scene that flattens freezes the pose it has now
still = true;
teardown();
cancelAnimationFrame(raf);
raf = 0;
- if (opts.backdrop) paintCards(opts.backdrop);
+ paintStill();
report(true);
};
@@ -443,11 +739,23 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
sampler.reset();
wake();
};
- const onResize = () => {
+ /** Make the scene again at the size it has now and settle as it was: after a resize, and after tiles arrive into a still. A burst of either is one rebuild, 250 ms after the last. */
+ let freshPose = false;
+ const rebuild = (fresh: boolean) => {
+ freshPose ||= fresh;
clearTimeout(resizeTimer);
resizeTimer = window.setTimeout(() => {
if (disposed) return;
const wasStill = still;
+ if (freshPose) {
+ // A resize is a new view: a still takes the pose the heading has now and asks for the tiles of it; the arrivals then repaint that pose.
+ stillPose = undefined;
+ if (wasStill && opts.backdrop) {
+ const { h } = headingPose(clock());
+ opts.backdrop.ensure({ fromDeg: h - HFOV_MAX_DEG / 2, toDeg: h + HFOV_MAX_DEG / 2 }).catch(() => undefined);
+ }
+ }
+ freshPose = false;
if (!build()) return;
if (wasStill) settleToStill();
else {
@@ -456,9 +764,19 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
}
}, 250);
};
+ // A still draws once and has no timer to ask for tiles, so it is told of each one that is made after its paint (the deadline of a scene start leaves the rest of the
+ // first arc loading); the live tier mounts them on its own timer. Nothing asks for more: a repaint adds no request, so the fill-in ends with the last tile.
+ const offTile = opts.backdrop?.onTile(() => {
+ if (still && !disposed) rebuild(false);
+ });
document.addEventListener('visibilitychange', onVisibility);
+ const onResize = () => rebuild(true);
window.addEventListener('resize', onResize);
- reducedMotion?.addEventListener?.('change', syncPlayState);
+ const onMotionChange = () => {
+ built?.rig?.sync();
+ syncPlayState();
+ };
+ reducedMotion?.addEventListener?.('change', onMotionChange);
return {
login() {
@@ -468,10 +786,12 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
if (disposed) return;
disposed = true;
cancelAnimationFrame(raf);
+ offTile?.();
+ opts.backdrop?.dispose();
clearTimeout(resizeTimer);
document.removeEventListener('visibilitychange', onVisibility);
window.removeEventListener('resize', onResize);
- reducedMotion?.removeEventListener?.('change', syncPlayState);
+ reducedMotion?.removeEventListener?.('change', onMotionChange);
teardown();
readout?.remove();
},
diff --git a/src/app/features/scene/ridge/heading.test.ts b/src/app/features/scene/ridge/heading.test.ts
new file mode 100644
index 00000000..4019bc70
--- /dev/null
+++ b/src/app/features/scene/ridge/heading.test.ts
@@ -0,0 +1,450 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { anchor, freeze, hold, normalize, poseAt, resetHeading, setRange, settledAt, STAGE_MS, subscribe, turnRate } from './heading';
+import type { RotationMode } from './heading';
+import * as camera from '../cameraState';
+import { effectiveMode, getCamera, isHeld, resetCamera, setCamera, subscribe as onCamera } from '../cameraState';
+import { maxSpeed } from './view';
+import { norm } from './ring';
+import { parseManifest } from './manifest';
+import { wireManifest } from './manifest.fixture';
+
+const S = 1000;
+
+/** The viewer's choice, at the clock `at` (ms): the one way the mode and the speed reach the view. */
+const choose = (mode: RotationMode, speedDegPerS: number, at: number) => setCamera({ mode, speedDegPerS }, at);
+
+/** The bound of a baked place, as `view.ts` `offsetRange` draws it: 100 m round the circle, 200 m forward with the camera exactly on its heading and the view turning with it. */
+const BACK = 100;
+const FORWARD = 200;
+const range = (mode: RotationMode, phi: number): [number, number] => [-BACK, mode !== 'offset' && Math.abs(norm(phi + 180) - 180) < 1e-6 ? FORWARD : BACK];
+/** Whether a pose is one the bound allows, whatever mode led there. */
+const fits = (p: { phi: number; r: number }): boolean => p.r >= range('both', p.phi)[0] - 1e-9 && p.r <= range('both', p.phi)[1] + 1e-9;
+
+const store = new Map();
+
+beforeEach(() => {
+ store.clear();
+ vi.stubGlobal('localStorage', {
+ getItem: (k: string) => store.get(k) ?? null,
+ setItem: (k: string, v: string) => void store.set(k, v),
+ });
+ resetCamera();
+ resetHeading();
+ setCamera({ mode: 'still', speedDegPerS: 0, offsetM: 0 }, 0);
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('turnRate', () => {
+ it('is the speed the view direction turns at: the viewer sets, bounded by the place, and nothing while it does not turn', () => {
+ anchor('p', 0, 0, (mode) => (mode === 'both' ? 5 : 12));
+ expect(turnRate()).toBe(0); // still
+ choose('both', 3, 0);
+ expect(turnRate()).toBe(3);
+ choose('both', -12, 0);
+ expect(turnRate()).toBe(5); // the place sustains 5, not the ceiling
+ choose('offset', 12, 0);
+ expect(turnRate()).toBe(0); // the camera circles: the view direction stays
+ choose('both', 3, 0);
+ freeze(true, 0);
+ expect(turnRate()).toBe(0);
+ freeze(false, 0);
+ hold(40, 0);
+ expect(turnRate()).toBe(0); // held by hand
+ });
+});
+
+describe('the heading owner', () => {
+ it('faces nothing in particular until a place anchors it, and turns nothing while the viewer chose nothing to turn', () => {
+ expect(poseAt(5 * S)).toEqual({ h: 0, phi: 0, r: 0 });
+ });
+
+ it('anchors a place at its rest azimuth once, and a later anchor of the same place changes nothing', () => {
+ anchor('vienna', 214, 0);
+ expect(poseAt(0).h).toBe(214);
+ choose('both', 0.6, 0);
+ expect(poseAt(10 * S).h).toBeCloseTo(220, 9);
+ anchor('vienna', 214, 10 * S); // a rebuild for a new sky: the view keeps the direction it has turned to
+ expect(poseAt(10 * S).h).toBeCloseTo(220, 9);
+ anchor('fuji', 100, 10 * S); // another place faces its own rest azimuth, with the camera on its heading
+ expect(poseAt(10 * S)).toMatchObject({ h: 100, phi: 0 });
+ });
+
+ it('is unwrapped over several revolutions between normalizations: nothing wraps or clamps it', () => {
+ anchor('p', 0, 0);
+ choose('both', 6, 0);
+ expect(poseAt(60 * S).h).toBeCloseTo(360, 9);
+ expect(poseAt(210 * S).h).toBeCloseTo(1260, 9);
+ choose('both', -6, 210 * S);
+ expect(poseAt(330 * S).h).toBeCloseTo(540, 9);
+ expect(poseAt(500 * S).h).toBeLessThan(0);
+ });
+
+ it('turns the view direction in both mode, the camera on its circle alone in offset mode, and nothing when still', () => {
+ anchor('p', 100, 0);
+ choose('both', 2, 0);
+ expect(poseAt(10 * S)).toMatchObject({ h: 120, phi: 0 });
+ choose('offset', 2, 10 * S); // nothing jumps at the change
+ expect(poseAt(10 * S)).toMatchObject({ h: 120, phi: 0 });
+ expect(poseAt(20 * S)).toMatchObject({ h: 120, phi: 20 });
+ choose('still', 2, 20 * S);
+ expect(poseAt(99 * S)).toMatchObject({ h: 120, phi: 20 });
+ choose('offset', 2, 99 * S); // the camera keeps the angle it stopped at, and goes on from there
+ expect(poseAt(104 * S)).toMatchObject({ h: 120, phi: 30 });
+ });
+
+ it('puts the camera back on its heading when the view direction is made to turn with it, by the short way round, and the view direction turns meanwhile', () => {
+ anchor('p', 100, 0);
+ choose('offset', 12, 0);
+ expect(poseAt(7.5 * S).phi).toBeCloseTo(90, 9);
+ choose('both', 12, 7.5 * S);
+ expect(poseAt(7.5 * S)).toMatchObject({ h: 100 }); // the pick moves nothing in the frame it is made
+ const gone = [0, 0.25, 0.5, 0.75, 1].map((x) => poseAt(7.5 * S + x * STAGE_MS).phi);
+ gone.slice(1).forEach((v, i) => expect(v).toBeLessThan(gone[i]));
+ expect(gone[4]).toBe(0);
+ expect(poseAt(7.5 * S + 5 * S).phi).toBe(0);
+ expect(poseAt(7.5 * S + 5 * S).h).toBeCloseTo(100 + 12 * 5, 9);
+ // 270 degrees on is 90 short of home the other way: the camera goes forward to 360, not back through 270.
+ choose('offset', 12, 20 * S);
+ choose('offset', 12, 20 * S + 22.5 * S);
+ const t = 20 * S + 22.5 * S;
+ expect(norm(poseAt(t).phi)).toBeCloseTo(270, 9);
+ choose('both', 12, t);
+ const mid = poseAt(t + STAGE_MS / 2).phi;
+ expect(norm(mid)).toBeGreaterThan(270);
+ expect(norm(poseAt(t + STAGE_MS).phi)).toBeCloseTo(0, 9);
+ });
+
+ it('a speed change takes effect from now, without moving the view', () => {
+ anchor('p', 0, 0);
+ choose('both', 1, 0);
+ choose('both', 3, 10 * S);
+ expect(poseAt(10 * S).h).toBe(10);
+ expect(poseAt(20 * S).h).toBe(40);
+ });
+
+ it('a manual turn sets the view direction in every mode and stops the rotation: the hold is the one fact, the chosen mode is left alone', () => {
+ for (const mode of ['still', 'offset', 'both'] as const) {
+ resetHeading();
+ anchor('p', 0, 0);
+ choose(mode, 1, 0);
+ hold(300, 10 * S);
+ expect(poseAt(10 * S).h).toBe(300);
+ expect(getCamera().mode).toBe(mode);
+ expect(effectiveMode()).toBe('still');
+ expect(poseAt(500 * S).h).toBe(300);
+ expect(poseAt(500 * S).phi).toBe(poseAt(10 * S).phi);
+ choose('both', 1, 500 * S); // a rotation mode chosen again resumes it
+ expect(poseAt(510 * S).h).toBe(310);
+ }
+ });
+
+ it('a hold outlives a rebuild and not a reload: a reload is a Return, and rotation resumes in the chosen mode', () => {
+ anchor('p', 0, 0);
+ choose('both', 1, 0);
+ hold(100, 10 * S);
+ anchor('p', 0, 20 * S); // what every scene build does
+ expect(poseAt(60 * S).h).toBe(100);
+ expect(isHeld()).toBe(true);
+ const stored = getCamera();
+ expect(stored.mode).toBe('both'); // what is stored is what the viewer chose
+ resetCamera(); // a reload reads the stored choice
+ expect(getCamera()).toEqual(stored);
+ expect(isHeld()).toBe(false);
+ expect(effectiveMode()).toBe('both');
+ resetHeading();
+ anchor('p', 0, 100 * S); // the new page faces its rest azimuth and turns
+ expect(poseAt(110 * S).h).toBe(10);
+ });
+
+ it('bounds the speed for the mode and the place and never rewrites the stored one: switching to a mode with room restores it', () => {
+ const ring = parseManifest(wireManifest({}, 3, 32), '/d/');
+ const slow = maxSpeed(ring, 'both');
+ anchor('p', 0, 0, (m) => maxSpeed(ring, m));
+ choose('both', 50, 0);
+ expect(poseAt(10 * S).h).toBeCloseTo(10 * slow, 9);
+ expect(getCamera().speedDegPerS).toBe(50); // the viewer's value
+ choose('offset', 50, 10 * S);
+ expect(poseAt(11 * S).phi).toBeCloseTo(12, 9); // the ceiling of that mode, not the turning mode's bound
+ choose('both', 50, 11 * S);
+ expect(poseAt(21 * S).h - poseAt(11 * S).h).toBeCloseTo(10 * slow, 9);
+ expect(getCamera().speedDegPerS).toBe(50);
+ setCamera({ speedDegPerS: -50 }, 21 * S);
+ expect(poseAt(31 * S).h - poseAt(21 * S).h).toBeCloseTo(-10 * slow, 9);
+ });
+
+ it('bounds the speed from the anchor, before anything has been told the place is loaded: a stored speed above the bound does not run over the load', () => {
+ const ring = parseManifest(wireManifest({}, 3, 32), '/d/');
+ const slow = maxSpeed(ring, 'both');
+ setCamera({ mode: 'both', speedDegPerS: 12 }, 0);
+ anchor('p', 214, 0, (m) => maxSpeed(ring, m)); // what a scene start does, then awaits the first tiles
+ expect(poseAt(5 * S).h).toBeCloseTo(214 + 5 * slow, 9);
+ expect(slow).toBeLessThan(12);
+ anchor('p', 214, 5 * S, (m) => maxSpeed(ring, m)); // a rebuild keeps the heading and the bound
+ expect(poseAt(10 * S).h).toBeCloseTo(214 + 10 * slow, 9);
+ });
+
+ it('choosing the mode the viewer had before a hold resumes the view: the mode they had is not still any more, so the choice is a change', () => {
+ anchor('p', 0, 0);
+ choose('both', 1, 0);
+ hold(100, 10 * S);
+ setCamera({ mode: 'both' }, 20 * S);
+ expect(poseAt(30 * S).h).toBe(110);
+ expect(getCamera().mode).toBe('both');
+ });
+
+ it('keeps the pose when the scene is rebuilt: the module outlives it', () => {
+ anchor('p', 50, 0);
+ choose('both', 1, 0);
+ expect(poseAt(30 * S).h).toBe(80);
+ anchor('p', 50, 30 * S);
+ expect(poseAt(30 * S).h).toBe(80);
+ });
+
+ it('freezes under reduced motion without moving the view, and goes on from where it stopped', () => {
+ anchor('p', 0, 0);
+ choose('both', 1, 0);
+ freeze(true, 10 * S);
+ expect(poseAt(10 * S).h).toBe(10);
+ expect(poseAt(50 * S).h).toBe(10);
+ expect(getCamera().mode).toBe('both'); // the viewer's choice is untouched
+ freeze(false, 50 * S);
+ expect(poseAt(60 * S).h).toBe(20);
+ });
+
+ it('normalizes into [0, 360) without changing the view, so the angles never grow with uptime, and an ease under way goes on as it was', () => {
+ anchor('p', 0, 0);
+ choose('both', 6, 0);
+ const day = 24 * 3600 * S;
+ normalize(day);
+ const h = poseAt(day).h;
+ expect(h).toBeGreaterThanOrEqual(0);
+ expect(h).toBeLessThan(360);
+ expect(h).toBeCloseTo((6 * 86400) % 360, 6);
+ expect(poseAt(day + 30 * S).h).toBeCloseTo(h + 180, 6);
+ choose('offset', 6, day + 30 * S);
+ normalize(day + 100 * S);
+ expect(poseAt(day + 100 * S).phi).toBeGreaterThanOrEqual(0);
+ expect(poseAt(day + 100 * S).phi).toBeLessThan(360);
+ setCamera({ speedDegPerS: -6 }, day + 100 * S);
+ normalize(day + 101 * S);
+ expect(poseAt(day + 101 * S).phi).toBeGreaterThanOrEqual(0); // a turn the other way is brought into range too
+ // An ease is the same ease before and after it is renormalized, in the middle.
+ choose('offset', 12, day + 200 * S);
+ choose('both', 12, day + 207.5 * S);
+ const at = day + 207.5 * S;
+ const before = [0.2, 0.5, 0.9].map((x) => poseAt(at + x * STAGE_MS));
+ normalize(at + 0.3 * STAGE_MS);
+ const after = [0.2, 0.5, 0.9].map((x) => poseAt(at + x * STAGE_MS));
+ after.forEach((p, i) => {
+ expect(norm(p.phi)).toBeCloseTo(norm(before[i].phi), 6);
+ expect(norm(p.h)).toBeCloseTo(norm(before[i].h), 6);
+ expect(p.r).toBeCloseTo(before[i].r, 9);
+ });
+ });
+
+ it('tells subscribers of every change of its course: a choice, a hold, a bound, a manual turn while held, a new place; and of nothing that changes nothing', () => {
+ const cb = vi.fn();
+ const off = subscribe(cb);
+ anchor('p', 0, 0);
+ expect(cb).toHaveBeenCalledTimes(1);
+ anchor('p', 0, 1); // the same place, no new bound: nothing
+ expect(cb).toHaveBeenCalledTimes(1);
+ setCamera({ mode: 'both', speedDegPerS: 1 }, 2);
+ expect(cb).toHaveBeenCalledTimes(2);
+ setCamera({ mode: 'both', speedDegPerS: 1 }, 3); // nothing changed
+ expect(cb).toHaveBeenCalledTimes(2);
+ hold(5, 4); // takes the hold: told once
+ expect(cb).toHaveBeenCalledTimes(3);
+ hold(6, 5); // turned again by hand while held: told
+ expect(cb).toHaveBeenCalledTimes(4);
+ setRange(range, 6);
+ expect(cb).toHaveBeenCalledTimes(5);
+ off();
+ anchor('q', 0, 7);
+ expect(cb).toHaveBeenCalledTimes(5);
+ });
+
+ it('is the one owner of the order: the heading is current when a listener of the camera hears of a change, whenever the listener registered', () => {
+ setCamera({ mode: 'both', speedDegPerS: 1 }, 0);
+ const early: number[] = [];
+ const offEarly = onCamera((_n, _p, at) => early.push(poseAt(at).h)); // before the place is anchored: first of the listeners, as a control mounted before the scene start is
+ anchor('p', 214, 0);
+ const late: number[] = [];
+ const offLate = onCamera((_n, _p, at) => late.push(poseAt(at).h));
+ anchor('p', 214, 1 * S); // a rebuild for a sky anchors the same place again
+ setCamera({ speedDegPerS: 4 }, 5 * S);
+ expect(poseAt(10 * S).h).toBeCloseTo(214 + 5 + 20, 9);
+ setCamera({ mode: 'still' }, 11 * S);
+ expect(early).toEqual(late);
+ expect(early[0]).toBeCloseTo(214 + 5, 9); // the heading at the change, with the speed it had until it
+ expect(early[1]).toBeCloseTo(214 + 5 + 24, 9);
+ offEarly();
+ offLate();
+ });
+
+ it('keeps no log of the camera: the owner takes each change as it is made, so a change nobody reads is held nowhere', () => {
+ expect(Object.keys(camera)).not.toContain('takeChanges');
+ anchor('p', 100, 0);
+ choose('both', 2, 0);
+ choose('both', 4, 3 * S); // 6 degrees by then
+ choose('offset', 4, 5 * S); // 14 degrees: the view stops, the camera starts
+ choose('both', 1, 7 * S); // the camera went 8 degrees round, and is put back on its heading
+ expect(poseAt(9 * S).h).toBeCloseTo(100 + 14 + 2, 9);
+ });
+
+ describe('a change of mode eases the pose in two stages inside the bound, from wherever the pose is', () => {
+ const sample = (from: number, to: number, step = 1): { h: number; phi: number; r: number }[] => {
+ const out = [];
+ for (let t = from; t <= to; t += step) out.push(poseAt(t));
+ return out;
+ };
+ /** Every pose inside the bound, and whenever the camera angle moves the offset is inside the circle's bound at both ends of the move. */
+ const insideTheBound = (poses: { phi: number; r: number }[]) => {
+ poses.forEach((p, i) => {
+ expect(fits(p), `pose ${i}: phi ${p.phi}, r ${p.r}`).toBe(true);
+ if (i && Math.abs(p.phi - poses[i - 1].phi) > 1e-9) {
+ expect(Math.abs(p.r)).toBeLessThanOrEqual(BACK + 0.02); // a sample step may straddle the end of a stage: a thousandth of the ease on
+ expect(Math.abs(poses[i - 1].r)).toBeLessThanOrEqual(BACK + 0.02);
+ }
+ });
+ };
+
+ /** The clock at which the camera has gone a quarter round its circle at 12 degrees a second, started when its offset is in: the offset comes in first, and the angle is let go after. */
+ const QUARTER = 90 / 12 * S + STAGE_MS;
+
+ beforeEach(() => {
+ setCamera({ offsetM: 200 }, 0);
+ anchor('p', 100, 0);
+ setRange(range, 0);
+ });
+
+ it('goes to a mode that stands the camera on its heading in two stages: the angle first, the offset let out after, and the view direction never waits', () => {
+ choose('offset', 12, 0);
+ const at = QUARTER;
+ expect(poseAt(at)).toMatchObject({ phi: 90, r: BACK });
+ choose('both', 12, at);
+ expect(poseAt(at)).toMatchObject({ h: 100, phi: 90, r: BACK }); // what is seen at the pick
+ expect(settledAt()).toBe(at + 2 * STAGE_MS);
+ const stage1 = sample(at, at + STAGE_MS);
+ expect(stage1.every((p) => p.r === BACK)).toBe(true); // the angle alone
+ expect(stage1.at(-1)!.phi).toBeCloseTo(0, 9);
+ const stage2 = sample(at + STAGE_MS, at + 2 * STAGE_MS);
+ expect(stage2.every((p) => p.phi === 0)).toBe(true); // the offset alone
+ expect(stage2.at(-1)!.r).toBe(FORWARD);
+ expect(poseAt(at + 10 * S)).toMatchObject({ phi: 0, r: FORWARD });
+ expect(poseAt(at + 3 * S).h).toBeCloseTo(100 + 36, 9); // turning from the instant of the pick
+ insideTheBound(sample(at, at + 2 * STAGE_MS));
+ });
+
+ it('goes to a mode that takes the camera off its heading the other way: the offset comes in first with the camera held where it stood, then the camera goes', () => {
+ choose('both', 12, 0);
+ const at = 10 * S;
+ expect(poseAt(at)).toMatchObject({ phi: 0, r: FORWARD });
+ choose('offset', 12, at);
+ const stage1 = sample(at, at + STAGE_MS);
+ expect(stage1.every((p) => p.phi === 0)).toBe(true);
+ expect(stage1.at(-1)!.r).toBe(BACK);
+ expect(poseAt(at + STAGE_MS + 1 * S)).toMatchObject({ r: BACK });
+ expect(poseAt(at + STAGE_MS + 1 * S).phi).toBeCloseTo(12, 9); // and goes round from the angle it stood at, at the speed
+ insideTheBound(sample(at, at + 3 * STAGE_MS));
+ });
+
+ it('a pick that asks nothing of the offset does not wait for it: the angle goes at once', () => {
+ choose('both', 12, 0);
+ setCamera({ offsetM: 50 }, 1 * S);
+ choose('offset', 12, 2 * S);
+ expect(poseAt(2 * S + 1 * S).phi).toBeCloseTo(12, 9);
+ });
+
+ it('a pick made while an ease is under way starts from the pose the view has, and every pose on the way stays inside the bound', () => {
+ const picks: RotationMode[] = ['still', 'offset', 'both'];
+ let checked = 0;
+ for (const first of picks) {
+ for (const second of picks) {
+ for (const gap of [10, 100, 250, 310, 450, 590]) {
+ resetHeading();
+ resetCamera();
+ setCamera({ mode: 'offset', speedDegPerS: 12, offsetM: 200 }, 0);
+ anchor('p', 100, 0);
+ setRange(range, 0);
+ const at = QUARTER;
+ setCamera({ mode: first }, at);
+ const seen = poseAt(at + gap);
+ setCamera({ mode: second }, at + gap);
+ expect(poseAt(at + gap), `${first} then ${second} after ${gap} ms`).toEqual(seen); // nothing moves at the pick
+ insideTheBound(sample(at, at + 4 * STAGE_MS, 3));
+ checked += 1;
+ }
+ }
+ }
+ expect(checked).toBe(54);
+ });
+
+ it('a pick to both made from the offset-only mode mid-way, then to offset-only again, never leaves the bound: the case a target-only order got wrong', () => {
+ choose('offset', 12, 0);
+ const at = QUARTER;
+ choose('both', 12, at); // the angle goes first, the offset held at the circle's bound
+ choose('offset', 12, at + 100); // and the offset-only mode has the offset on the circle's bound already
+ insideTheBound(sample(at, at + 4 * STAGE_MS, 2));
+ // From both with the offset out, pick still then both then offset within a stage each.
+ resetHeading();
+ resetCamera();
+ setCamera({ mode: 'both', speedDegPerS: 12, offsetM: 200 }, 0);
+ anchor('p', 100, 0);
+ setRange(range, 0);
+ choose('offset', 12, 5 * S); // the offset comes in first
+ choose('both', 12, 5 * S + 100); // back out: the camera is still on its heading, so the offset can go straight out
+ insideTheBound(sample(5 * S, 5 * S + 4 * STAGE_MS, 2));
+ expect(poseAt(5 * S + 10 * S)).toMatchObject({ phi: 0, r: FORWARD });
+ });
+
+ it('a slider eases in one stage, inside the bound the mode keeps, and an offset past it is held to it', () => {
+ choose('both', 0.6, 0);
+ setCamera({ offsetM: 20 }, 1 * S);
+ expect(poseAt(1 * S).r).toBe(FORWARD);
+ expect(poseAt(1 * S + STAGE_MS).r).toBe(20);
+ expect(settledAt()).toBe(1 * S + STAGE_MS);
+ setCamera({ offsetM: 999 }, 5 * S);
+ expect(poseAt(6 * S).r).toBe(FORWARD);
+ choose('offset', 0.6, 7 * S);
+ expect(poseAt(9 * S).r).toBe(BACK); // the viewer's 999 is not rewritten
+ expect(getCamera().offsetM).toBe(999);
+ choose('both', 0.6, 10 * S);
+ expect(poseAt(12 * S).r).toBe(FORWARD);
+ });
+
+ it('a new bound is a new segment from the pose the view has: a rebuild mid-ease lands exactly where the old scene was', () => {
+ choose('offset', 12, 0);
+ const at = QUARTER;
+ choose('both', 12, at);
+ for (const gap of [50, 150, 299, 301, 450]) {
+ const seen = poseAt(at + gap);
+ setRange(range, at + gap); // what a rebuild at another size, or a rebuilt scene, does
+ const now = poseAt(at + gap);
+ expect(now.h).toBeCloseTo(seen.h, 9);
+ expect(now.phi).toBeCloseTo(seen.phi, 9);
+ expect(now.r).toBeCloseTo(seen.r, 9);
+ }
+ insideTheBound(sample(at, at + 4 * STAGE_MS, 2));
+ expect(poseAt(at + 5 * S)).toMatchObject({ phi: 0, r: FORWARD });
+ });
+
+ it('has no ease under reduced motion: the pose owed is the pose shown at once, and one begun before is cut short', () => {
+ choose('offset', 12, 0);
+ const at = QUARTER;
+ choose('both', 12, at);
+ expect(settledAt()).toBeGreaterThan(at);
+ freeze(true, at + 10);
+ expect(poseAt(at + 10)).toMatchObject({ phi: 0, r: FORWARD });
+ expect(poseAt(at + 5 * S).h).toBe(poseAt(at + 10).h); // and nothing turns
+ setCamera({ mode: 'offset', speedDegPerS: 12 }, at + 20);
+ expect(poseAt(at + 21)).toMatchObject({ r: BACK }); // the clamp, at once
+ setCamera({ mode: 'both', speedDegPerS: 12 }, at + 30);
+ expect(poseAt(at + 31)).toMatchObject({ phi: 0, r: FORWARD });
+ expect(settledAt()).toBeLessThanOrEqual(at + 30);
+ });
+ });
+});
diff --git a/src/app/features/scene/ridge/heading.ts b/src/app/features/scene/ridge/heading.ts
new file mode 100644
index 00000000..880caa59
--- /dev/null
+++ b/src/app/features/scene/ridge/heading.ts
@@ -0,0 +1,210 @@
+// The heading owner: the one place that knows where the view faces (`h`), where the camera stands on its circle against that (`phi`) and how far from the
+// centre (`r`), at any clock. Module-level state, so a sky change that makes a new scene keeps the pose. Angles are unwrapped compass degrees between two
+// `normalize` calls (the rig makes one before each stretch of motion); `ring.ts` is the one place that reasons about 0 / 360.
+//
+// The state is one SEGMENT: the pose at its start `t0`, the mode and bounded speed in force, and the ease that takes the pose to the one the inputs owe.
+// `poseAt(t)` is a pure function of the segment and `t`, ease included. Every change of an input (a mode pick, a hold, the speed, the offset, a bound, reduced
+// motion, a place) starts a new segment from `poseAt(now)`: no log of changes, no second copy of the ease, so whoever reads at any clock, a rebuilt scene
+// included, gets the pose the view has.
+//
+// The camera sits on its circle at angle `h + phi` and distance `r` (signed, forward positive): with `phi` 0 it is pushed forward along its own heading
+// (`view.ts` `cardPose`), and rotating the offset alone moves `phi` and leaves the view direction where it is (ruling ridge-scene-view-submenus). `phi` is 0
+// whenever the view direction turns with the camera ('both'). The bound on `r` is the baker's (`view.ts` `offsetRange`, given by the scene as `setRange`): a
+// forward offset past `rMaxM` fits only with the camera exactly on its heading. So an ease takes `phi` and `r` one after the other, STAGE_MS each, in the
+// order that keeps every pose inside it from wherever it starts: a camera going to stand on its heading turns first and lets the offset out after; one going
+// off it brings the offset in first and lets the camera go after.
+import { bindOwner, getCamera, holdCamera, isHeld } from '../cameraState';
+
+/** `still`: nothing turns. `offset`: the camera circles the centre, the view direction stays. `both`: the view direction turns and the camera with it. */
+export type RotationMode = 'still' | 'offset' | 'both';
+
+/** Where the view faces, where the camera stands on its circle against that, and its offset (m, signed): the pose the rig lays the cards out from. */
+export interface Pose {
+ h: number;
+ phi: number;
+ r: number;
+}
+
+/** What the baked place and the viewport allow: the speed (degrees per second, either way) a mode may turn at, and the offsets the camera may take at an angle in a mode. */
+type Speed = (mode: RotationMode) => number;
+type Range = (mode: RotationMode, phiDeg: number) => [number, number];
+
+export const STAGE_MS = 300; // one stage of an ease, ms
+const EPS = 1e-9; // a pose this close to the one owed is there: nothing eases
+
+interface Segment extends Pose {
+ /** The clock (ms) at which `h`, `phi` and `r` hold. */
+ t0: number;
+ /** Degrees per second of whatever turns, signed and bounded, and what that is: the view direction ('both'), the camera on its circle ('offset') or nothing. */
+ rate: number;
+ turns: 'h' | 'phi' | undefined;
+ /** The camera's angle turns only from this clock (ms): after the offset has come in. */
+ turnsFrom: number;
+ /** The angle an ease takes `phi` to from `t0` (unwrapped, the nearest way round); undefined: `phi` is what `turns` makes it. */
+ phiTo: number | undefined;
+ /** The offset an ease takes `r` to, from `rAt`. */
+ rTo: number;
+ rAt: number;
+ /** The clock (ms) at which everything eased is home. */
+ endAt: number;
+}
+
+let seg: Segment | undefined;
+let frozen = false;
+let anchored: string | undefined;
+let speed: Speed | undefined;
+let range: Range | undefined;
+const listeners = new Set<() => void>();
+
+/** 0 at `at`, 1 at `at + STAGE_MS` (smoothstep): the one curve of the view's easing. */
+const ease = (at: number, now: number): number => {
+ const x = Math.min(1, Math.max(0, (now - at) / STAGE_MS));
+ return x * x * (3 - 2 * x);
+};
+const free: [number, number] = [-Infinity, Infinity];
+/** What each mode turns: the view direction, the camera on its circle, or nothing. */
+const TURNS: Record = { both: 'h', offset: 'phi', still: undefined };
+const rangeOf = (mode: RotationMode, phi: number): [number, number] => range?.(mode, phi) ?? free;
+
+function pose(s: Segment, t: number): Pose {
+ const sec = (t - s.t0) / 1000;
+ return {
+ h: s.h + (s.turns === 'h' ? s.rate * sec : 0),
+ phi:
+ s.phiTo !== undefined
+ ? s.phi + (s.phiTo - s.phi) * ease(s.t0, t)
+ : s.phi + (s.turns === 'phi' ? (s.rate * Math.max(0, t - s.turnsFrom)) / 1000 : 0),
+ r: s.r + (s.rTo - s.r) * ease(s.rAt, t),
+ };
+}
+
+/**
+ * Start a segment at `now` from `from`, the pose the view has there, under the inputs in force: the viewer's choice, the hold, reduced motion and the bounds.
+ * What the inputs owe is where the camera must stand (on its heading when the view turns with it and is not held) and the offset the bound allows there; an
+ * ease is what takes `from` to it, none when `snap` (a place or a bound met for the first time) or while frozen.
+ */
+function begin(now: number, from: Pose, snap = false): void {
+ const cam = getCamera();
+ const held = isHeld();
+ const kin: RotationMode = frozen || held ? 'still' : cam.mode;
+ const toHeading = cam.mode === 'both' && !held;
+ const limit = speed?.(cam.mode) ?? Infinity;
+ const phiTo = toHeading ? 360 * Math.round(from.phi / 360) : undefined;
+ const landed = phiTo ?? from.phi;
+ const [lo, hi] = rangeOf(cam.mode, landed); // the bound is the chosen mode's, held or frozen or not: a hold does not move the offset
+ const rTo = Math.min(hi, Math.max(lo, cam.offsetM));
+ const easing = !snap && !frozen;
+ const turnsPhi = easing && phiTo !== undefined && Math.abs(phiTo - from.phi) > EPS;
+ const movesR = easing && Math.abs(rTo - from.r) > EPS;
+ // Going to circle with the offset out past the circle's bound: the camera stays on its heading until the offset is in.
+ const [circleLo, circleHi] = rangeOf('offset', from.phi);
+ const holdsPhi = movesR && kin === 'offset' && (from.r < circleLo || from.r > circleHi);
+ const rAt = turnsPhi ? now + STAGE_MS : now;
+ seg = {
+ t0: now,
+ h: from.h,
+ phi: turnsPhi ? from.phi : landed,
+ r: movesR ? from.r : rTo,
+ rate: Math.sign(cam.speedDegPerS) * Math.min(Math.abs(cam.speedDegPerS), limit),
+ turns: TURNS[kin],
+ turnsFrom: holdsPhi ? now + STAGE_MS : now,
+ phiTo: turnsPhi ? phiTo : undefined,
+ rTo,
+ rAt,
+ endAt: Math.max(turnsPhi ? now + STAGE_MS : now, movesR ? rAt + STAGE_MS : now),
+ };
+}
+
+const current = (now: number): Segment => {
+ if (!seg) begin(now, { h: 0, phi: 0, r: 0 }, true);
+ return seg as Segment;
+};
+/** The pose at `now` (ms): unwrapped degrees, bounded by the last `normalize` and the stretch since. */
+export function poseAt(now: number): Pose {
+ return pose(current(now), now);
+}
+const emit = () => [...listeners].forEach((cb) => cb());
+/** A new segment at `now` from the pose the view has, told to the subscribers. */
+function restart(now: number, over: Partial = {}, snap = false): void {
+ begin(now, { ...poseAt(now), ...over }, snap);
+ emit();
+}
+
+/**
+ * Degrees per second the view direction turns at under the inputs in force: the viewer's speed bounded by what the place sustains in the mode picked (`anchor`'s
+ * limit), and nothing while the view does not turn (a mode that turns the camera on its circle, a hold, reduced motion). Every change of any of these starts a
+ * segment and is heard by `subscribe`, so a reader that sizes something to this speed learns when it must size again.
+ */
+export const turnRate = (): number => (seg?.turns === 'h' ? Math.abs(seg.rate) : 0);
+
+/** The clock (ms) at which what the last change eased is home. */
+export const settledAt = (): number => seg?.endAt ?? 0;
+
+// The viewer's choice or hold changed: a new segment at that clock, before any listener hears of it.
+bindOwner((at) => restart(Math.max(at, seg?.t0 ?? at)));
+
+/**
+ * Bound the speed in each mode to what the baked place sustains (`view.ts` `maxSpeed`), from this moment, before anything awaits the place's tiles, and point
+ * the view at a place: a place not shown before faces its rest azimuth, the camera on its heading, with no ease; the same place again keeps the pose.
+ */
+export function anchor(key: string, restDeg: number, now: number, limit?: Speed): void {
+ if (limit) speed = limit;
+ if (anchored === key) {
+ if (limit) restart(now);
+ return;
+ }
+ anchored = key;
+ range = undefined; // the bound belongs to the place before
+ restart(now, { h: restDeg, phi: 0 }, true);
+}
+
+/** The offsets the scene's place and viewport allow (`view.ts` `offsetRange`); the first one met takes the offset to its bound at once, a new one eases there. */
+export function setRange(limit: Range, now: number): void {
+ const first = range === undefined;
+ range = limit;
+ restart(now, {}, first);
+}
+
+/**
+ * A manual turn: the view direction becomes `h` now, in every mode, and the rotation stops where the viewer left it (ruling ridge-view-turn-handback): the view
+ * is held in cameraState, which leaves the chosen mode as it is; a rebuild keeps the hold, and picking a mode, the one already chosen included, resumes it.
+ */
+export function hold(h: number, now: number): void {
+ begin(now, { ...poseAt(now), h });
+ if (isHeld()) emit();
+ else holdCamera(now); // the owner starts the held segment, then the camera's listeners hear it, once
+}
+
+/** Nothing turns while `on` (reduced motion), whatever the viewer chose; the view takes the pose owed at once and stays there. */
+export function freeze(on: boolean, now: number): void {
+ if (on === frozen) return;
+ frozen = on;
+ restart(now);
+}
+
+/** Bring `h` and `phi` into [0, 360) at `now`, so the transforms stay small however long the page has been open: the whole turns are all that goes, and the ease and the motion go on. Silent: the caller lays out again. */
+export function normalize(now: number): void {
+ const s = current(now);
+ const p = pose(s, now);
+ const dh = 360 * Math.floor(p.h / 360);
+ const dphi = 360 * Math.floor(p.phi / 360);
+ s.h -= dh;
+ s.phi -= dphi;
+ if (s.phiTo !== undefined) s.phiTo -= dphi;
+}
+
+/** Hear every change of the pose's course: the viewer's choice or hold, a bound, reduced motion, a manual turn, a new place; returns the way to stop. */
+export function subscribe(cb: () => void): () => void {
+ listeners.add(cb);
+ return () => listeners.delete(cb);
+}
+
+/** For tests: the state of a fresh page. */
+export function resetHeading(): void {
+ seg = undefined;
+ frozen = false;
+ anchored = undefined;
+ speed = undefined;
+ range = undefined;
+ listeners.clear();
+}
diff --git a/src/app/features/scene/ridge/lightCards.test.ts b/src/app/features/scene/ridge/lightCards.test.ts
index 496f3073..8b1b76b3 100644
--- a/src/app/features/scene/ridge/lightCards.test.ts
+++ b/src/app/features/scene/ridge/lightCards.test.ts
@@ -6,8 +6,9 @@ import {
celShade,
celLevels,
FRAGMENT,
- lightCards,
+ createLighter,
lightingOf,
+ ringAzimuth,
skyLut,
SKY_LUT,
sunColumns,
@@ -49,15 +50,20 @@ describe("the sun in a column's frame", () => {
expect(sunInColumn({ azimuth: 10, elevation: 0 }, 100)[1]).toBeCloseTo(-1, 12);
});
- it('is computed for every column of the window, from its own azimuth', () => {
+ it('is computed for every column of the ring, from its own absolute azimuth', () => {
const view = manifest.view;
const cols = sunColumns(view, { azimuth: 214, elevation: 20 });
- expect(cols).toHaveLength(view.planeW * 4);
+ expect(cols).toHaveLength(view.ringW * 4);
const at = (x: number) => Array.from(cols.slice(x * 4, x * 4 + 3));
- const mid = at(view.planeW / 2);
- expect(mid[0]).toBeCloseTo(Math.cos(20 * RAD), 3); // the middle column looks near the sun's azimuth
- expect(at(0)[1]).toBeGreaterThan(0.1); // the left edge has the sun to its right
- expect(at(view.planeW - 1)[1]).toBeLessThan(-0.1);
+ const sunCol = Math.floor((214 / 360) * view.ringW);
+ expect(ringAzimuth(sunCol, view.ringW)).toBeCloseTo(214, 1);
+ expect(at(sunCol)[0]).toBeCloseTo(Math.cos(20 * RAD), 3); // the column that looks at the sun's azimuth
+ expect(at(sunCol - 1000)[1]).toBeGreaterThan(0.1); // the sun is to the right of columns before it, and to the left of those after
+ expect(at(sunCol + 1000)[1]).toBeLessThan(-0.1);
+ // Every column is a unit vector, the first column of the ring looks north and the last looks just west of it.
+ for (let x = 0; x < view.ringW; x += 400) expect(Math.hypot(...at(x))).toBeCloseTo(1, 5);
+ expect(ringAzimuth(0, view.ringW)).toBeCloseTo(0.028125, 6);
+ expect(ringAzimuth(view.ringW - 1, view.ringW)).toBeCloseTo(360 - 0.028125, 6);
});
});
@@ -146,10 +152,34 @@ describe('the lighting inputs', () => {
7 // the airglow floor adds a few 1e-9
);
expect(texel(0, SKY_LUT.h - 1)[0]).toBeCloseTo(0, 7);
- // The sun lies at 214 degrees, the middle of the window: the cosine from the sun is 1 there and falls to the sides.
- const mid = texel(SKY_LUT.w / 2, above)[1];
+ // The sun lies at 214 degrees: the cosine from the sun is 1 at its column and falls round the ring. The table spans the ring, so 320 columns.
+ expect(SKY_LUT.w).toBe(320);
+ const sunI = Math.floor((214 / 360) * SKY_LUT.w);
+ const mid = texel(sunI, above)[1];
expect(mid).toBeGreaterThan(0.999);
expect(texel(0, above)[1]).toBeLessThan(mid);
+ expect(texel(sunI + 160, above)[1]).toBeLessThan(-0.9);
+ });
+});
+
+describe('the ring in the shader', () => {
+ it('reads the sun and the sky by the column of the ring, not of the file, and wraps at the ends', () => {
+ expect(FRAGMENT).toContain('int col = ((uCol0 + p.x) % uRingW + uRingW) % uRingW;');
+ expect(FRAGMENT).toContain('texelFetch(uSun, ivec2(col, 0), 0)');
+ expect(FRAGMENT).toContain('(float(col) + 0.5) / float(uRingW)');
+ expect(FRAGMENT).toContain('(int(b.x) % w + w) % w'); // the sky table wraps in azimuth
+ });
+ it('gives the ground noise the ground point, so it is the same at ring column 0 and column 6400', () => {
+ // The noise coordinate is dist x (sin psi, cos psi) with psi from the wrapped column: sin and cos of 0 and of a whole turn are one point.
+ expect(FRAGMENT).toContain('vec2 world = vec2(sin(psi), cos(psi)) * dist;');
+ expect(FRAGMENT).toContain('float psi = (float(col) + 0.5) / float(uRingW) * 2.0 * PI;');
+ expect(FRAGMENT).not.toContain("uRadPerPx");
+ const at = (col: number, w: number) => {
+ const psi = ((((col % w) + w) % w) + 0.5) / w * 2 * Math.PI;
+ return [Math.sin(psi), Math.cos(psi)];
+ };
+ expect(at(6400, 6400)[0]).toBeCloseTo(at(0, 6400)[0], 12);
+ expect(at(6400, 6400)[1]).toBeCloseTo(at(0, 6400)[1], 12);
});
});
@@ -169,12 +199,13 @@ describe('the display of the shader', () => {
describe('the look reaches the shader', () => {
// A recording WebGL2: every uniform call is kept by the name of its location, nothing is drawn.
- const run = (look?: Partial) => {
+ const run = (look?: Partial, tile = 0) => {
const uniforms: Record = {};
+ const crops: number[][] = [];
const gl = new Proxy(
{
getUniformLocation: (_p: unknown, name: string) => name,
- uniform1i: () => undefined,
+ drawImage: (...a: unknown[]) => crops.push(a.slice(1) as number[]),
getShaderParameter: () => true,
getProgramParameter: () => true,
getExtension: () => null,
@@ -192,7 +223,7 @@ describe('the look reaches the shader', () => {
);
const el = { width: 0, height: 0, getContext: () => gl };
vi.stubGlobal('document', { createElement: () => el });
- const bmp = { width: 1, height: 1, close: () => undefined } as unknown as ImageBitmap;
+ const bmp = { width: 1604, height: 7, close: () => undefined } as unknown as ImageBitmap;
const sky = {
sun: { azimuth: 214, elevation: 30 },
atm: {
@@ -206,14 +237,34 @@ describe('the look reaches the shader', () => {
view: manifest.view,
} as unknown as PhysicalSky;
const one = { ...manifest, cards: manifest.cards.slice(0, 1) };
+ let canvas: { width: number; height: number } | undefined;
try {
- lightCards(one, [{ colour: bmp, geometry: bmp }], sky, look && { ...DEFAULT_LOOK, ...look });
+ const lighter = createLighter(one, sky, look && { ...DEFAULT_LOOK, ...look });
+ canvas = lighter.light({ colour: bmp, geometry: bmp }, tile, 0) as unknown as typeof canvas;
} finally {
vi.unstubAllGlobals();
}
- return uniforms;
+ return Object.assign(uniforms, { crops, canvas });
};
+ it('lights a tile from its own columns: the ring column of the file, the band, and the interior with one overlap column each side', () => {
+ const u = run(undefined, 3);
+ const { view } = manifest;
+ expect(u.uCol0).toEqual([3 * view.tileW - view.apron]); // tile 3 of 4: the file starts two columns before its first
+ expect(u.uRingW).toEqual([view.ringW]);
+ expect(u.uTop).toEqual([manifest.tiles[3][0]!.top]);
+ expect(u.uSkySize).toEqual([320, 64]);
+ // The file holds tileW + 2 apron columns; the canvas keeps columns apron - 1 .. apron + tileW: the interior and one column each side.
+ expect(u.crops).toEqual([[view.apron - 1, 0, view.tileW + 2, 7, 0, 0, view.tileW + 2, 7]]);
+ expect(u.canvas).toMatchObject({ width: view.tileW + 2, height: 7 });
+ });
+
+ it('throws without WebGL2: the caller makes the sky alone', () => {
+ vi.stubGlobal('document', { createElement: () => ({ getContext: () => null }) });
+ expect(() => createLighter(manifest, {} as PhysicalSky)).toThrow(/WebGL2/);
+ vi.unstubAllGlobals();
+ });
+
it('defaults to DEFAULT_LOOK', () => {
const u = run();
expect(u.uInkKeep).toEqual([0.45, 0.55, 0.8]);
diff --git a/src/app/features/scene/ridge/lightCards.ts b/src/app/features/scene/ridge/lightCards.ts
index 5ffbd6fc..39c5fcc9 100644
--- a/src/app/features/scene/ridge/lightCards.ts
+++ b/src/app/features/scene/ridge/lightCards.ts
@@ -1,7 +1,9 @@
-// The one lighting pass of the ridge cards (ruling ridge-cards-runtime-lit): each baked G-buffer card (colour with straight alpha, geometry with the
+// The one lighting pass of the ridge cards (ruling ridge-cards-runtime-lit): each baked G-buffer card tile (colour with straight alpha, geometry with the
// 'rt8' normal and log-distance, `scripts/ridge-bake/export.py`) is lit once, for the sky this scene build was made for, in one WebGL2 context on a
-// canvas of its own, and copied into a 2D canvas of the card's size. After the last card the context is released: there is no per-frame WebGL, and the
-// host canvas stays 2D (`Ridge.ts`). A sky change rebuilds the scene and lights again; nothing patches the lit canvases.
+// canvas of its own (a lighter, one per sky), and copied into a 2D canvas of the tile's interior plus one overlap column each side. The sun and the sky's
+// haze are tables over the whole ring in absolute azimuth, so a tile is lit from its own files alone and the apron (the neighbours' real columns, read for
+// the ink pass and dropped) makes its edges equal what a lit neighbour would give. There is no per-frame WebGL, and the host canvas stays 2D
+// (`Ridge.ts`). A sky change rebuilds the scene and makes a new lighter; nothing patches the lit canvases.
//
// Per pixel: the normal from the geometry card in the column's frame (r along the ray, t across it, up), the sun brought into that frame per column;
// radiance = albedo x (sun transmittance x max(n.s, 0) + ambient irradiance) / pi; aerial perspective L T(d) + Lsky (1 - T(d)) with d from the
@@ -17,23 +19,11 @@ import { ACES_FIT, ACES_IN, ACES_OUT, KNOTS, SCOTOPIC } from './toneMap';
import type { Curve } from './toneMap';
import type { View } from './view';
-export interface CardBitmaps {
- colour: ImageBitmap;
- geometry: ImageBitmap;
-}
-
-/** A lit card: its pixels, premultiplied by the card's alpha, at the card's own size, and where the card sits in the plane. */
-export interface LitCard {
- canvas: HTMLCanvasElement;
- top: number;
- h: number;
- scale: number;
-}
/** A real normal has r2 + t2 at most 0.998 (probe on the Vienna bake); the wall code is 2. A code of the data, not of the look. */
export const WALL_RT2 = 1.02;
-/** The lookup of the sky's radiance for the haze: azimuth columns by plane rows, filtered in the shader. */
-export const SKY_LUT = { w: 64, h: 64 } as const;
+/** The lookup of the sky's radiance for the haze: azimuth columns over the whole ring (the angular density of 64 over a 72 degree window) by plane rows, filtered in the shader. */
+export const SKY_LUT = { w: 320, h: 64 } as const;
/**
* The look: every number of the art pass (ratatoskr:follow_up:ridge-art-quality-rework), the one owner of them. None is a rule of the machine.
@@ -165,9 +155,8 @@ export function sunInColumn(
return [Math.cos(el) * Math.cos(d), Math.cos(el) * Math.sin(d), Math.sin(el)];
}
-/** The azimuth of plane column `x` of `w` (the card is the whole baked window wide). */
-export const columnAzimuth = (view: View, x: number, w: number): number =>
- view.lookAzDeg + ((x + 0.5) / w - 0.5) * view.windowDeg;
+/** The compass azimuth of ring column `col` of `w` columns (column 0 = north), taken at the column's centre. */
+export const ringAzimuth = (col: number, w: number): number => ((col + 0.5) / w) * 360;
/** A geometry texel's red and green bytes as the shader reads them: a wall, or the unit normal (along the ray, across it, up). */
export function decodeNormal(
@@ -184,7 +173,7 @@ export function decodeNormal(
/** Everything the lighting reads of the sky and the manifest, as the numbers the shader's uniforms hold. */
export interface Lighting {
- planeW: number;
+ ringW: number;
planeH: number;
logDMin: number;
logDSpan: number;
@@ -249,7 +238,7 @@ export function lightingOf(
look: RidgeLook = DEFAULT_LOOK
): Lighting {
return {
- planeW: manifest.view.planeW,
+ ringW: manifest.view.ringW,
planeH: manifest.view.planeH,
logDMin: manifest.encoding.logDMin,
logDSpan: manifest.encoding.logDMax - manifest.encoding.logDMin,
@@ -261,18 +250,18 @@ export function lightingOf(
};
}
-/** The sun in every column's frame, RGBA32F texels (a, b, c, 0), one row of `planeW`. */
+/** The sun in every column's frame, RGBA32F texels (a, b, c, 0), one row of `ringW`: absolute azimuth, so every tile reads the same table. */
export function sunColumns(view: View, sun: { azimuth: number; elevation: number }): Float32Array {
- const out = new Float32Array(view.planeW * 4);
- for (let x = 0; x < view.planeW; x += 1) {
- const [r, t, u] = sunInColumn(sun, columnAzimuth(view, x, view.planeW));
+ const out = new Float32Array(view.ringW * 4);
+ for (let x = 0; x < view.ringW; x += 1) {
+ const [r, t, u] = sunInColumn(sun, ringAzimuth(x, view.ringW));
out.set([r, t, u, 0], x * 4);
}
return out;
}
/**
- * The sky's radiance (per unit of sun irradiance) as the haze needs it: a small grid over the window's azimuths and the plane's rows, the view
+ * The sky's radiance (per unit of sun irradiance) as the haze needs it: a small grid over the ring's azimuths and the plane's rows, the view
* direction of each texel's centre. Rows below the horizon take the horizon's radiance (the haze in front of a ridge is the air at its foot).
*/
export function skyLut(sky: PhysicalSky, view: View, w: number, h: number): Float32Array {
@@ -281,7 +270,7 @@ export function skyLut(sky: PhysicalSky, view: View, w: number, h: number): Floa
for (let j = 0; j < h; j += 1) {
const elDeg = Math.max(0, (view.horizonRow - ((j + 0.5) / h) * view.planeH) / view.pxPerDegV);
for (let i = 0; i < w; i += 1) {
- const az = columnAzimuth(view, ((i + 0.5) / w) * view.planeW - 0.5, view.planeW);
+ const az = ((i + 0.5) / w) * 360;
sky.atm.radiance(Math.sin(elDeg * RAD), Math.cos((az - sky.sun.azimuth) * RAD), rgb);
addNightRadiance(sky.night, Math.sin(elDeg * RAD), az * RAD, rgb);
out.set([rgb[0], rgb[1], rgb[2], 0], (j * w + i) * 4);
@@ -304,7 +293,9 @@ uniform sampler2D uSky;
uniform ivec2 uSize;
uniform ivec2 uSkySize;
uniform int uTop;
-uniform vec2 uPlane;
+uniform int uCol0; // the ring column of the file's first texel (a tile's first column less its apron; may be below 0)
+uniform int uRingW;
+uniform float uPlaneH;
uniform vec2 uLogD;
uniform vec3 uExt;
uniform vec3 uTSun;
@@ -326,7 +317,6 @@ uniform vec2 uCard; // value of this card, gradient
uniform vec2 uGround; // groundNoise, cloudShadows
uniform vec4 uCel; // bands (0 = Lambert), softness, ambientAway, ambientEdge
uniform float uBandLevels[${CEL_MAX}];
-uniform float uRadPerPx; // radians of azimuth per plane pixel
out vec4 outColor;
const float PI = 3.14159265358979;
@@ -397,12 +387,14 @@ float cel(float x) {
return l;
}
+// The sky's table spans the ring: it wraps in azimuth (x) and clamps in elevation (y).
vec3 skyAt(vec2 uv) {
vec2 f = uv * vec2(uSkySize) - 0.5;
vec2 b = floor(f);
vec2 t = f - b;
- ivec2 lo = clamp(ivec2(b), ivec2(0), uSkySize - 1);
- ivec2 hi = clamp(ivec2(b) + 1, ivec2(0), uSkySize - 1);
+ int w = uSkySize.x;
+ ivec2 lo = ivec2((int(b.x) % w + w) % w, clamp(int(b.y), 0, uSkySize.y - 1));
+ ivec2 hi = ivec2((int(b.x) + 1) % w, clamp(int(b.y) + 1, 0, uSkySize.y - 1));
vec3 a = mix(texelFetch(uSky, ivec2(lo.x, lo.y), 0).rgb, texelFetch(uSky, ivec2(hi.x, lo.y), 0).rgb, t.x);
vec3 c = mix(texelFetch(uSky, ivec2(lo.x, hi.y), 0).rgb, texelFetch(uSky, ivec2(hi.x, hi.y), 0).rgb, t.x);
return mix(a, c, t.y);
@@ -444,10 +436,13 @@ void main() {
if (c.a <= 0.0) { outColor = vec4(0.0); return; }
Geo g = geoAt(p);
- vec3 s = texelFetch(uSun, ivec2(p.x, 0), 0).xyz;
+ int col = ((uCol0 + p.x) % uRingW + uRingW) % uRingW;
+ vec3 s = texelFetch(uSun, ivec2(col, 0), 0).xyz;
if (uRelief.y > 0.0) s = normalize(mix(s, uFixedLight, uRelief.y));
float dist = exp(g.logD);
- vec2 world = vec2(float(p.x) * uRadPerPx, 1.0) * dist;
+ // The ground's noise is a function of the ground point, dist x (sin psi, cos psi) for the column's absolute azimuth psi, so it is periodic over the wrap.
+ float psi = (float(col) + 0.5) / float(uRingW) * 2.0 * PI;
+ vec2 world = vec2(sin(psi), cos(psi)) * dist;
vec3 albedo = toLinear(c.rgb);
if (uGround.x > 0.0) albedo *= max(1.0 + uGround.x * (2.0 * fbm(world / 250.0) - 1.0), 0.0);
float cloud = uGround.y > 0.0 ? 1.0 - uGround.y * smoothstep(0.5, 0.72, fbm(world / 4000.0 + 17.0)) : 1.0;
@@ -462,7 +457,7 @@ void main() {
}
radiance *= mix(vec3(1.0), NEAR_WARM, uDist.x * (1.0 - dn));
vec3 T = exp(-uExt * (dist / 1000.0));
- vec2 uv = vec2((float(p.x) + 0.5) / uPlane.x, (float(uTop + p.y) + 0.5) / uPlane.y);
+ vec2 uv = vec2((float(col) + 0.5) / float(uRingW), (float(uTop + p.y) + 0.5) / uPlaneH);
vec3 haze = skyAt(uv);
haze += uHazeTint * dot(haze, LUMA);
radiance = radiance * T + haze * (1.0 - T);
@@ -544,16 +539,35 @@ function bitmapTexture(gl: WebGL2RenderingContext, unit: number, bmp: ImageBitma
return t;
}
+/** A tile of a card as its two files decoded: the colour with straight alpha and the geometry, each tileW + 2 apron columns by the band's rows. */
+export interface CardBitmaps {
+ colour: ImageBitmap;
+ geometry: ImageBitmap;
+}
+
+/** One sky's lighting of the ring's tiles. */
+export interface Lighter {
+ /**
+ * Light card `card` of tile `tile` from its decoded files: a 2D canvas of the tile's interior columns plus one overlap column each side (the apron is
+ * read and dropped; the overlap hides the hairline between adjacent canvases at a fractional scale), premultiplied by the card's alpha. The bitmaps
+ * stay the caller's to close. Throws when the context is lost or the tile holds no such card.
+ */
+ light(bitmaps: CardBitmaps, tile: number, card: number): HTMLCanvasElement;
+ /** True once the GL context was lost: this lighter is spent and the next ensure makes another. */
+ readonly lost: boolean;
+ /** Let go of the GL context and its tables. */
+ release(): void;
+}
+
/**
- * Light the cards of `manifest` for `sky`, nearest first, as the manifest lists them. Throws without WebGL2 or when the shader will not link;
- * the caller (`loadBackdrop`) turns any throw into the sky alone. Closes the bitmaps, and releases the context after the last card.
+ * The lighter for `sky`: one WebGL2 context on a canvas of its own, the program, the ring-wide sun columns and the sky's lookup uploaded once, a tile lit
+ * per call. Throws without WebGL2 or when the shader will not link; the caller (`Backdrop.ts`) turns any throw into the sky alone.
*/
-export function lightCards(
+export function createLighter(
manifest: RidgeManifest,
- bitmaps: CardBitmaps[],
sky: PhysicalSky,
look: RidgeLook = DEFAULT_LOOK
-): LitCard[] {
+): Lighter {
const glCanvas = document.createElement('canvas');
const gl = glCanvas.getContext('webgl2', {
alpha: true,
@@ -563,6 +577,18 @@ export function lightCards(
stencil: false,
});
if (!gl) throw new Error('ridge: no WebGL2');
+ let lost = false;
+ let released = false;
+ const release = () => {
+ if (released) return;
+ released = true;
+ gl.getExtension('WEBGL_lose_context')?.loseContext();
+ };
+ glCanvas.addEventListener?.('webglcontextlost', () => {
+ lost = true;
+ });
+ const { view } = manifest;
+ const litW = view.tileW + 2;
try {
const lit = lightingOf(manifest, sky, look);
const prog = program(gl);
@@ -572,7 +598,8 @@ export function lightCards(
gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
['uColour', 'uGeo', 'uSun', 'uSky'].forEach((n, i) => gl.uniform1i(u(n), i));
- gl.uniform2f(u('uPlane'), lit.planeW, lit.planeH);
+ gl.uniform1i(u('uRingW'), lit.ringW);
+ gl.uniform1f(u('uPlaneH'), lit.planeH);
gl.uniform2f(u('uLogD'), lit.logDMin, lit.logDSpan);
gl.uniform3f(u('uExt'), ...lit.extinction);
gl.uniform3f(u('uTSun'), ...lit.key.direct);
@@ -599,49 +626,49 @@ export function lightCards(
gl.uniform2f(u('uGround'), look.groundNoise, look.cloudShadows);
gl.uniform4f(u('uCel'), look.celBands, look.celSoftness, look.celAmbientAway, look.celAmbientEdge);
gl.uniform1fv(u('uBandLevels'), celLevels(look.celBands, look.celBandLevels));
- gl.uniform1f(u('uRadPerPx'), (manifest.view.windowDeg * RAD) / lit.planeW);
gl.uniform2i(u('uSkySize'), SKY_LUT.w, SKY_LUT.h);
- const sunTex = floatTexture(gl, 2, lit.planeW, 1, sunColumns(manifest.view, lit.key));
- const skyTex = floatTexture(
- gl,
- 3,
- SKY_LUT.w,
- SKY_LUT.h,
- skyLut(sky, manifest.view, SKY_LUT.w, SKY_LUT.h)
- );
- const out = manifest.cards.map((card, i): LitCard => {
- const { colour, geometry } = bitmaps[i];
- glCanvas.width = colour.width;
- glCanvas.height = colour.height;
- gl.viewport(0, 0, colour.width, colour.height);
- const colourTex = bitmapTexture(gl, 0, colour);
- const geoTex = bitmapTexture(gl, 1, geometry);
- gl.uniform2i(u('uSize'), colour.width, colour.height);
- gl.uniform1i(u('uTop'), card.top);
- gl.uniform2f(
- u('uCard'),
- 1 + look.cardToneStep * (i - (manifest.cards.length - 1) / 2),
- look.cardGradient
- );
- gl.clearColor(0, 0, 0, 0);
- gl.clear(gl.COLOR_BUFFER_BIT);
- gl.drawArrays(gl.TRIANGLES, 0, 3);
- const canvas = document.createElement('canvas');
- canvas.width = colour.width;
- canvas.height = colour.height;
- const ctx = canvas.getContext('2d');
- if (!ctx) throw new Error('ridge: no 2D context for a lit card');
- ctx.drawImage(glCanvas, 0, 0);
- gl.deleteTexture(colourTex);
- gl.deleteTexture(geoTex);
- colour.close();
- geometry.close();
- return { canvas, top: card.top, h: card.h, scale: card.scale };
- });
- gl.deleteTexture(sunTex);
- gl.deleteTexture(skyTex);
- return out;
- } finally {
- gl.getExtension('WEBGL_lose_context')?.loseContext();
+ floatTexture(gl, 2, lit.ringW, 1, sunColumns(view, lit.key));
+ floatTexture(gl, 3, SKY_LUT.w, SKY_LUT.h, skyLut(sky, view, SKY_LUT.w, SKY_LUT.h));
+ return {
+ get lost() {
+ return lost;
+ },
+ release,
+ light(bitmaps, tile, card) {
+ const entry = manifest.tiles[tile]?.[card];
+ if (!entry) throw new Error(`ridge: tile ${tile} holds no card ${card}`);
+ if (lost || released) throw new Error('ridge: the lighting context is gone');
+ const { colour, geometry } = bitmaps;
+ glCanvas.width = colour.width;
+ glCanvas.height = colour.height;
+ gl.viewport(0, 0, colour.width, colour.height);
+ const colourTex = bitmapTexture(gl, 0, colour);
+ const geoTex = bitmapTexture(gl, 1, geometry);
+ gl.uniform2i(u('uSize'), colour.width, colour.height);
+ gl.uniform1i(u('uTop'), entry.top);
+ gl.uniform1i(u('uCol0'), tile * view.tileW - view.apron);
+ gl.uniform2f(
+ u('uCard'),
+ 1 + look.cardToneStep * (card - (manifest.cards.length - 1) / 2),
+ look.cardGradient
+ );
+ gl.clearColor(0, 0, 0, 0);
+ gl.clear(gl.COLOR_BUFFER_BIT);
+ gl.drawArrays(gl.TRIANGLES, 0, 3);
+ const canvas = document.createElement('canvas');
+ canvas.width = litW;
+ canvas.height = colour.height;
+ const ctx = canvas.getContext('2d');
+ if (!ctx) throw new Error('ridge: no 2D context for a lit tile');
+ // The file's columns apron - 1 .. apron + tileW (inclusive): the interior and one overlap column each side.
+ ctx.drawImage(glCanvas, view.apron - 1, 0, litW, colour.height, 0, 0, litW, colour.height);
+ gl.deleteTexture(colourTex);
+ gl.deleteTexture(geoTex);
+ return canvas;
+ },
+ };
+ } catch (e) {
+ release();
+ throw e;
}
}
diff --git a/src/app/features/scene/ridge/manifest.fixture.ts b/src/app/features/scene/ridge/manifest.fixture.ts
index 74a55cb0..673b1bd3 100644
--- a/src/app/features/scene/ridge/manifest.fixture.ts
+++ b/src/app/features/scene/ridge/manifest.fixture.ts
@@ -1,16 +1,22 @@
-// A hand-written manifest v2 and index v1 (wire form, as export.py writes them): the runtime's tests need no real bake and no decoder.
+// A hand-written manifest schema 3 and index v1 (wire form, as export.py writes them): the runtime's tests need no real bake and no decoder. The ring is
+// four tiles of 90 degrees, so a tile is a quarter of the compass and wrap-around at north is easy to meet.
import type { View } from './view';
-/** Card scales of the fixture, nearest first, as the baker derives them for a camera 200 m forward (distances 1.2 km, 12 km, 40 km). */
-const SCALES = [1.2, 1.0167, 1.005] as const;
+/** A card's distance in each of the fixture's four tiles, metres, nearest card first; null where the tile holds no such card (the third card is absent over the south). */
+export const DISTANCES: (number | null)[][] = [
+ [1000, 1200, 1400, 1100],
+ [10000, 12000, 14000, 11000],
+ [40000, 41000, null, 39000],
+];
-/** A v2 manifest of `k` cards (1 to 6), nearest first, each a band of the 600-row plane. */
+/** A schema 3 manifest of `k` cards (1 to 3, nearest first), each a band of the 600-row plane, over `tiles` tiles (4 by default, 32 as the baker cuts) whose distances repeat the four above. */
export const wireManifest = (
over: Record = {},
- k = 3
+ k = 3,
+ tiles = 4
): Record => ({
- schema: 2,
- baker_version: 2,
+ schema: 3,
+ baker_version: 4,
bake_id: 'abc123abc123',
place: {
id: 'vienna',
@@ -18,37 +24,45 @@ export const wireManifest = (
lat: 48.19,
lon: 16.35,
altitude_km: 0.183,
+ tz: 'Europe/Vienna',
eye_m: 1.7,
},
view: {
look_az_deg: 214,
- window_deg: 72,
- plane_w: 1280,
plane_h: 600,
- px_per_deg_h: 1280 / 72,
- px_per_deg_v: 177.8,
+ px_per_deg_h: 6400 / 360,
+ px_per_deg_v: 171.7,
exaggeration: 10,
- horizon_row: 314.5,
+ horizon_row: 357,
sky_row: 24,
near_row: 396,
+ ring_w: 6400,
+ tile_w: 6400 / tiles,
+ tiles,
+ apron: 2,
},
curvature: { r_earth_m: 6371000, k_ref: 0.13 },
encoding: { log_d_min: 4.6, log_d_max: 11.5, normal: 'rt8' },
- camera: { r_m: 200, heading_max_deg: 23 },
+ camera: { r_max_m: 100, r_max_forward_m: 180 },
cards: Array.from({ length: k }, (_, i) => ({
- top: 100 * i,
- h: 600 - 100 * i,
- near_m: i ? 1000 * i : null,
- far_m: i < k - 1 ? 1000 * (i + 1) : null,
- median_m: 1000 * (i + 1),
- distance_m: 1000 * (i + 1),
- scale: SCALES[i] ?? 1.001,
- colour: { file: `card-${i}-colour.webp`, bytes: 1 },
- geometry: { file: `card-${i}-geometry.webp`, bytes: 1 },
+ near_m: i ? 1000 * 10 ** (i - 1) * 4 : null,
+ far_m: i < k - 1 ? 4000 * 10 ** i : null,
})),
- w: 1280,
- h: 600,
- bytes: 2 * k,
+ tiles: Array.from({ length: tiles }, (_, t) =>
+ Array.from({ length: k }, (_, i) => {
+ const d = DISTANCES[i][t % 4];
+ return d === null
+ ? null
+ : {
+ top: 100 * i,
+ h: 600 - 100 * i,
+ distance_m: d,
+ colour: { file: `card-${i}-t${String(t).padStart(2, '0')}-colour.webp`, bytes: 1 },
+ geometry: { file: `card-${i}-t${String(t).padStart(2, '0')}-geometry.webp`, bytes: 1 },
+ };
+ })
+ ),
+ bytes: 0,
attribution: {
credit_line: 'credit',
licence: 'licence',
@@ -64,14 +78,16 @@ export const wireIndex = {
places: { vienna: 'vienna-abc123abc123', graz: 'graz-def456def456' },
};
-/** A View that differs from FALLBACK_VIEW in every field the sky reads (place, altitude, look azimuth, window, horizon row), so a test can tell the two apart. */
+/** A View that differs from FALLBACK_VIEW in every field the sky reads (place, altitude, look azimuth, horizon row), so a test can tell the two apart. */
export const ELSEWHERE_VIEW: View = {
- place: { id: 'elsewhere', lat: -33.9, lon: 151.2, altitudeKm: 1.5 },
+ place: { id: 'elsewhere', lat: -33.9, lon: 151.2, altitudeKm: 1.5, tz: 'Australia/Sydney' },
lookAzDeg: 20,
- windowDeg: 90,
- planeW: 1600,
+ ringW: 3600,
+ tileW: 900,
+ tiles: 4,
+ apron: 2,
planeH: 700,
- pxPerDegH: 1600 / 90,
+ pxPerDegH: 10,
pxPerDegV: 100,
horizonRow: 250,
};
diff --git a/src/app/features/scene/ridge/manifest.test.ts b/src/app/features/scene/ridge/manifest.test.ts
index 8af79c55..2ac2e85c 100644
--- a/src/app/features/scene/ridge/manifest.test.ts
+++ b/src/app/features/scene/ridge/manifest.test.ts
@@ -3,61 +3,83 @@ import { forgetManifests, loadManifest, parseManifest } from './manifest';
import { wireIndex, wireManifest } from './manifest.fixture';
describe('parseManifest', () => {
- it('reads a v2 manifest into the View the sky and cards share, and K cards nearest first', () => {
+ it('reads a schema 3 manifest into the View the sky and cards share, the offset bound, and the cards by tile', () => {
const m = parseManifest(wireManifest(), '/public/ridge/v/');
expect(m.dir).toBe('/public/ridge/v/');
expect(m.view).toMatchObject({
lookAzDeg: 214,
- windowDeg: 72,
- planeW: 1280,
+ ringW: 6400,
+ tileW: 1600,
+ tiles: 4,
+ apron: 2,
planeH: 600,
- pxPerDegH: 1280 / 72,
- pxPerDegV: 177.8, // not px_per_deg_h: a real bake's two differ 10x
- horizonRow: 314.5,
+ pxPerDegH: 6400 / 360,
+ pxPerDegV: 171.7, // not px_per_deg_h: a real bake's two differ 10x
+ horizonRow: 357,
+ });
+ expect(m.view.place).toEqual({
+ id: 'vienna',
+ lat: 48.19,
+ lon: 16.35,
+ altitudeKm: 0.183,
+ tz: 'Europe/Vienna',
});
- expect(m.view.place).toEqual({ id: 'vienna', lat: 48.19, lon: 16.35, altitudeKm: 0.183 });
expect(m.encoding).toEqual({ logDMin: 4.6, logDMax: 11.5 });
- expect(m.camera).toEqual({ headingMaxDeg: 23 });
- expect(m.cards.map((c) => c.scale)).toEqual([1.2, 1.0167, 1.005]);
- expect(m.cards[1]).toEqual({
+ expect(m.camera).toEqual({ rMaxM: 100, rMaxForwardM: 180 });
+ expect(m.cards).toEqual([
+ { nearM: null, farM: 4000 },
+ { nearM: 4000, farM: 40000 },
+ { nearM: 40000, farM: null },
+ ]);
+ expect(m.tiles).toHaveLength(4);
+ expect(m.tiles[1][1]).toEqual({
top: 100,
h: 500,
- scale: 1.0167,
- colour: 'card-1-colour.webp',
- geometry: 'card-1-geometry.webp',
+ distanceM: 12000,
+ colour: 'card-1-t01-colour.webp',
+ geometry: 'card-1-t01-geometry.webp',
});
+ expect(m.tiles[2][2]).toBeNull(); // the third card holds nothing over the south
expect(m.attribution.creditLine).toBe('credit');
});
- it.each([1, 2, 3, 4, 5, 6])('parses a bake of %i cards', (k) => {
- expect(parseManifest(wireManifest({}, k), '/').cards).toHaveLength(k);
+ it.each([1, 2, 3])('parses a bake of %i cards', (k) => {
+ const m = parseManifest(wireManifest({}, k), '/');
+ expect(m.cards).toHaveLength(k);
+ m.tiles.forEach((row) => expect(row).toHaveLength(k));
});
- it('keeps only what the runtime reads: no distances, no camera offset', () => {
- const m = parseManifest(wireManifest(), '/') as unknown as Record;
- expect(JSON.stringify(m)).not.toMatch(/median|near_m|far_m|distance|rM|r_m/);
- });
-
- it('refuses schema 1, no cards, seven cards, a card past the plane, a scale that is not above 0, a missing camera', () => {
+ it('refuses schema 2 naming the stale deploy, and any other schema', () => {
const w = wireManifest() as any;
+ expect(() => parseManifest({ ...w, schema: 2 }, '/')).toThrow(/stale ridge bake/);
expect(() => parseManifest({ ...w, schema: 1 }, '/')).toThrow(/schema/);
- expect(() => parseManifest({ ...w, cards: [] }, '/')).toThrow(/cards/);
- expect(() => parseManifest(wireManifest({}, 7), '/')).toThrow(/cards/);
- const card = w.cards[0];
- const withCard = (c: unknown) => ({ ...w, cards: [c] });
- expect(() => parseManifest(withCard({ ...card, top: 300, h: 301 }), '/')).toThrow(/rows/);
- expect(() => parseManifest(withCard({ ...card, top: -1 }), '/')).toThrow(/rows/);
- expect(() => parseManifest(withCard({ ...card, scale: 0 }), '/')).toThrow(/scale/);
- expect(() => parseManifest(withCard({ ...card, scale: -1 }), '/')).toThrow(/scale/);
- expect(() => parseManifest(withCard({ ...card, scale: Infinity }), '/')).toThrow(/scale/);
- expect(() => parseManifest({ ...w, camera: undefined }, '/')).toThrow(/camera/);
- expect(() => parseManifest({ ...w, camera: { heading_max_deg: 0 } }, '/')).toThrow(/heading/);
});
- it('rejects a missing field, a plane wider than 4096, a normal that is not rt8 and a backwards encoding', () => {
+ it('refuses no cards, seven cards, a ring that is not tiles x tile_w, a tile row of the wrong length, a card in no tile, a band past the plane', () => {
+ const w = wireManifest() as any;
+ expect(() => parseManifest({ ...w, cards: [] }, '/')).toThrow(/cards/);
+ expect(() => parseManifest({ ...w, cards: Array(7).fill({ near_m: null, far_m: null }) }, '/')).toThrow(/cards/);
+ expect(() => parseManifest({ ...w, view: { ...w.view, ring_w: 6401 } }, '/')).toThrow(/ring_w/);
+ expect(() => parseManifest({ ...w, tiles: w.tiles.slice(1) }, '/')).toThrow(/tiles/);
+ expect(() => parseManifest({ ...w, tiles: w.tiles.map((r: unknown[]) => r.slice(1)) }, '/')).toThrow(/entries/);
+ expect(() =>
+ parseManifest({ ...w, tiles: w.tiles.map((r: unknown[]) => [r[0], r[1], null]) }, '/')
+ ).toThrow(/null in every tile/);
+ const withTile = (e: unknown) => ({ ...w, tiles: [[e, w.tiles[0][1], w.tiles[0][2]], ...w.tiles.slice(1)] });
+ const t = w.tiles[0][0];
+ expect(() => parseManifest(withTile({ ...t, top: 300, h: 301 }), '/')).toThrow(/rows/);
+ expect(() => parseManifest(withTile({ ...t, top: -1 }), '/')).toThrow(/rows/);
+ expect(() => parseManifest(withTile({ ...t, distance_m: 0 }), '/')).toThrow(/distance/);
+ expect(() => parseManifest(withTile({ ...t, distance_m: Infinity }), '/')).toThrow(/distance/);
+ expect(() => parseManifest({ ...w, camera: undefined }, '/')).toThrow(/camera/);
+ expect(() => parseManifest({ ...w, camera: { r_max_m: 0, r_max_forward_m: 0 } }, '/')).toThrow(/r_max_m/);
+ expect(() => parseManifest({ ...w, camera: { r_max_m: 100 } }, '/')).toThrow(/r_max_forward_m/);
+ expect(() => parseManifest({ ...w, camera: { r_max_m: 100, r_max_forward_m: 99 } }, '/')).toThrow(/r_max_forward_m/);
+ });
+
+ it('rejects a missing field, a normal that is not rt8 and a backwards encoding', () => {
const w = wireManifest() as any;
expect(() => parseManifest({ ...w, bake_id: undefined }, '/')).toThrow(/bake_id/);
- expect(() => parseManifest({ ...w, view: { ...w.view, plane_w: 4097 } }, '/')).toThrow(/4096/);
expect(() => parseManifest({ ...w, view: { ...w.view, horizon_row: 'x' } }, '/')).toThrow(
/horizon_row/
);
@@ -70,6 +92,13 @@ describe('parseManifest', () => {
expect(() => parseManifest(null, '/')).toThrow();
});
+ it('rejects a manifest without place.tz and one naming a zone Intl does not know', () => {
+ const w = wireManifest() as any;
+ expect(() => parseManifest({ ...w, place: { ...w.place, tz: undefined } }, '/')).toThrow(/place\.tz/);
+ expect(() => parseManifest({ ...w, place: { ...w.place, tz: 'Not/AZone' } }, '/')).toThrow(/place\.tz/);
+ expect(parseManifest({ ...w, place: { ...w.place, tz: 'Asia/Kathmandu' } }, '/').view.place.tz).toBe('Asia/Kathmandu');
+ });
+
it('never echoes a value it refused', () => {
const w = wireManifest() as any;
const refusal = (bad: unknown) => {
@@ -82,8 +111,9 @@ describe('parseManifest', () => {
};
for (const bad of [
{ ...w, schema: 'SECRET-VALUE-42' },
- { ...w, camera: { heading_max_deg: 'SECRET-VALUE-42' } },
- { ...w, cards: [{ ...w.cards[0], scale: 'SECRET-VALUE-42' }] },
+ { ...w, camera: { r_max_m: 'SECRET-VALUE-42', r_max_forward_m: 180 } },
+ { ...w, camera: { r_max_m: 100, r_max_forward_m: 'SECRET-VALUE-42' } },
+ { ...w, tiles: [[{ ...w.tiles[0][0], distance_m: 'SECRET-VALUE-42' }, ...w.tiles[0].slice(1)], ...w.tiles.slice(1)] },
]) {
const msg = refusal(bad);
expect(msg).not.toBe('');
diff --git a/src/app/features/scene/ridge/manifest.ts b/src/app/features/scene/ridge/manifest.ts
index e2ec9087..a54deb2b 100644
--- a/src/app/features/scene/ridge/manifest.ts
+++ b/src/app/features/scene/ridge/manifest.ts
@@ -1,23 +1,29 @@
// The ridge backdrop's one JSON boundary: a static asset between the offline Python baker (scripts/ridge-bake/export.py, whose SCHEMA is the
// contract) and the page; no daemon state. Main-chunk safe: types, a parser and fetch only. Wire names are snake_case; the parsed manifest is
-// camelCase and its `view` is the View (`view.ts`) the sky and the cards share. Schema 2: K G-buffer cards, nearest first.
+// camelCase and its `view` is the View (`view.ts`) the sky and the cards share. Schema 3: the whole 360 degree ring, K G-buffer cards cut into
+// azimuth tiles, each tile two files.
import type { View } from './view';
-export const PLANE_W_MAX = 4096;
/** As export.py MAX_CARDS: the decode budget holds this many. */
export const MAX_CARDS = 6;
-/** One G-buffer card: its rows of the plane, how large it sits against the bake, and its two files (names inside the manifest's directory). */
-export interface CardEntry {
- /** First row of the card in the plane, and its height in rows. */
+/** One card's tile: its rows of the plane, the card's distance there, and its two files (names inside the manifest's directory). */
+export interface TileCard {
+ /** First row of the card's band in the plane, and its height in rows. */
top: number;
h: number;
- /** The card's pan rate per unit of heading and its static size, as the baker derived them from the camera and the card's distance (ruling ridge-camera-on-circle). */
- scale: number;
+ /** exp(median ln d) of the card's solid pixels in the tile's interior, metres. */
+ distanceM: number;
colour: string;
geometry: string;
}
+/** A card as the bake lists it: the median seam depths over the ring, null at the ends. */
+export interface CardEntry {
+ nearM: number | null;
+ farM: number | null;
+}
+
export interface RidgeManifest {
bakeId: string;
/** Absolute-or-rooted URL of the bake's directory, with a trailing slash. */
@@ -25,12 +31,18 @@ export interface RidgeManifest {
/** Display name of the place. */
name: string;
view: View;
- /** How the geometry card's blue channel maps to ln metres: `logD = logDMin + b x (logDMax - logDMin)`, b in 0..1. The red and green channels are the 'rt8' normal. */
+ /** How the geometry file's blue channel maps to ln metres: `logD = logDMin + b x (logDMax - logDMin)`, b in 0..1. The red and green channels are the 'rt8' normal. */
encoding: { logDMin: number; logDMax: number };
- /** The widest heading either side of the look azimuth the baked cards allow, degrees. */
- camera: { headingMaxDeg: number };
+ /**
+ * The largest camera offset from the bake centre the cards' linear slide fits, metres (ruling ridge-offset-range-fit): `rMaxM` over every angle of the camera
+ * on its circle (the offset-only rotation mode), `rMaxForwardM` with the camera pushed forward along the view direction alone (the modes where the offset
+ * turns with the view), so never below `rMaxM`.
+ */
+ camera: { rMaxM: number; rMaxForwardM: number };
/** Nearest first. */
cards: CardEntry[];
+ /** `tiles[t][i]` is card i in tile t, or null where the card holds nothing there. */
+ tiles: (TileCard | null)[][];
attribution: { creditLine: string; licence: string; demSource: string; url: string };
}
@@ -51,6 +63,18 @@ const num = (x: unknown, path: string): number =>
typeof x === 'number' && Number.isFinite(x) ? x : fail(path, 'not a number');
const str = (x: unknown, path: string): string =>
typeof x === 'string' ? x : fail(path, 'not a string');
+const numOrNull = (x: unknown, path: string): number | null => (x === null ? null : num(x, path));
+
+/** An IANA zone name Intl knows (the one place besides skyMoment.ts that touches Intl.DateTimeFormat). */
+const zone = (x: unknown, path: string): string => {
+ const tz = str(x, path);
+ try {
+ new Intl.DateTimeFormat('en-US', { timeZone: tz });
+ } catch {
+ fail(path, `unknown time zone ${tz}`);
+ }
+ return tz;
+};
export function parseIndex(raw: unknown): RidgeIndex {
const r = rec(raw, 'index');
@@ -62,39 +86,67 @@ export function parseIndex(raw: unknown): RidgeIndex {
return { default: str(r.default, 'index.default'), places: out };
}
-/** `dir` is the URL of the directory the manifest was read from; the cards are read relative to it. */
+/** `dir` is the URL of the directory the manifest was read from; the tile files are read relative to it. */
export function parseManifest(raw: unknown, dir: string): RidgeManifest {
const r = rec(raw, 'manifest');
- if (r.schema !== 2) fail('schema', 'must be 2');
+ if (r.schema !== 3) {
+ fail(
+ 'schema',
+ `must be 3: this build reads ring bakes only, so the deploy holds a stale ridge bake (rebake the place, or redeploy a matching build)`
+ );
+ }
const p = rec(r.place, 'place');
const v = rec(r.view, 'view');
- const planeW = num(v.plane_w, 'view.plane_w');
- if (planeW > PLANE_W_MAX) fail('view.plane_w', `above ${PLANE_W_MAX}`);
+ const ringW = num(v.ring_w, 'view.ring_w');
+ const tileW = num(v.tile_w, 'view.tile_w');
+ const tiles = num(v.tiles, 'view.tiles');
+ if (!Number.isInteger(tiles) || tiles < 1) fail('view.tiles', 'not a count');
+ if (ringW !== tiles * tileW) fail('view.ring_w', 'is not tiles x tile_w');
const planeH = num(v.plane_h, 'view.plane_h');
if (!Array.isArray(r.cards) || r.cards.length < 1) fail('cards', 'none');
- if ((r.cards as unknown[]).length > MAX_CARDS) fail('cards', `more than ${MAX_CARDS}`);
+ const k = (r.cards as unknown[]).length;
+ if (k > MAX_CARDS) fail('cards', `more than ${MAX_CARDS}`);
const cards = (r.cards as unknown[]).map((x, i): CardEntry => {
const c = rec(x, `cards[${i}]`);
- const top = num(c.top, `cards[${i}].top`);
- const h = num(c.h, `cards[${i}].h`);
- if (top < 0 || h < 1 || top + h > planeH) fail(`cards[${i}]`, 'outside the plane rows');
- const scale = num(c.scale, `cards[${i}].scale`);
- if (!(scale > 0)) fail(`cards[${i}].scale`, 'not above 0');
return {
- top,
- h,
- scale,
- colour: str(rec(c.colour, `cards[${i}].colour`).file, `cards[${i}].colour.file`),
- geometry: str(rec(c.geometry, `cards[${i}].geometry`).file, `cards[${i}].geometry.file`),
+ nearM: numOrNull(c.near_m, `cards[${i}].near_m`),
+ farM: numOrNull(c.far_m, `cards[${i}].far_m`),
};
});
+ if (!Array.isArray(r.tiles) || r.tiles.length !== tiles) fail('tiles', `not ${tiles} tiles`);
+ const grid = (r.tiles as unknown[]).map((row, t) => {
+ if (!Array.isArray(row) || row.length !== k) fail(`tiles[${t}]`, `not ${k} entries`);
+ return (row as unknown[]).map((x, i): TileCard | null => {
+ if (x === null) return null;
+ const path = `tiles[${t}][${i}]`;
+ const e = rec(x, path);
+ const top = num(e.top, `${path}.top`);
+ const h = num(e.h, `${path}.h`);
+ if (top < 0 || h < 1 || top + h > planeH) fail(path, 'outside the plane rows');
+ const distanceM = num(e.distance_m, `${path}.distance_m`);
+ if (!(distanceM > 0)) fail(`${path}.distance_m`, 'not above 0');
+ return {
+ top,
+ h,
+ distanceM,
+ colour: str(rec(e.colour, `${path}.colour`).file, `${path}.colour.file`),
+ geometry: str(rec(e.geometry, `${path}.geometry`).file, `${path}.geometry.file`),
+ };
+ });
+ });
+ for (let i = 0; i < k; i += 1) {
+ if (grid.every((row) => row[i] === null)) fail(`cards[${i}]`, 'is null in every tile');
+ }
const e = rec(r.encoding, 'encoding');
if (e.normal !== 'rt8') fail('encoding.normal', "must be 'rt8'");
const logDMin = num(e.log_d_min, 'encoding.log_d_min');
const logDMax = num(e.log_d_max, 'encoding.log_d_max');
if (!(logDMax > logDMin)) fail('encoding', 'log_d_max not above log_d_min');
- const headingMaxDeg = num(rec(r.camera, 'camera').heading_max_deg, 'camera.heading_max_deg');
- if (!(headingMaxDeg > 0)) fail('camera.heading_max_deg', 'not above 0');
+ const cam = rec(r.camera, 'camera');
+ const rMaxM = num(cam.r_max_m, 'camera.r_max_m');
+ if (!(rMaxM > 0)) fail('camera.r_max_m', 'not above 0');
+ const rMaxForwardM = num(cam.r_max_forward_m, 'camera.r_max_forward_m');
+ if (!(rMaxForwardM >= rMaxM)) fail('camera.r_max_forward_m', 'below camera.r_max_m');
const a = rec(r.attribution, 'attribution');
const id = str(p.id, 'place.id');
return {
@@ -107,18 +159,22 @@ export function parseManifest(raw: unknown, dir: string): RidgeManifest {
lat: num(p.lat, 'place.lat'),
lon: num(p.lon, 'place.lon'),
altitudeKm: num(p.altitude_km, 'place.altitude_km'),
+ tz: zone(p.tz, 'place.tz'),
},
lookAzDeg: num(v.look_az_deg, 'view.look_az_deg'),
- windowDeg: num(v.window_deg, 'view.window_deg'),
- planeW,
+ ringW,
+ tileW,
+ tiles,
+ apron: num(v.apron, 'view.apron'),
planeH,
pxPerDegH: num(v.px_per_deg_h, 'view.px_per_deg_h'),
pxPerDegV: num(v.px_per_deg_v, 'view.px_per_deg_v'),
horizonRow: num(v.horizon_row, 'view.horizon_row'),
},
encoding: { logDMin, logDMax },
- camera: { headingMaxDeg },
+ camera: { rMaxM, rMaxForwardM },
cards,
+ tiles: grid,
attribution: {
creditLine: str(a.credit_line, 'attribution.credit_line'),
licence: str(a.licence, 'attribution.licence'),
@@ -148,7 +204,7 @@ export function loadManifest(baseUrl: string, placeId?: string): Promise {
const index = parseIndex(
- // The index is the one mutable pointer (a rebake deletes the old directory it named); the manifest and planes are content-addressed.
+ // The index is the one mutable pointer (a rebake deletes the old directory it named); the manifest and tiles are content-addressed.
await getJson(`${root}index.json`, { cache: 'no-cache' })
);
const id = placeId !== undefined && placeId in index.places ? placeId : index.default;
diff --git a/src/app/features/scene/ridge/nightBodies.test.ts b/src/app/features/scene/ridge/nightBodies.test.ts
index 6289cf2c..c0c2ac50 100644
--- a/src/app/features/scene/ridge/nightBodies.test.ts
+++ b/src/app/features/scene/ridge/nightBodies.test.ts
@@ -13,7 +13,7 @@ const camera: Camera = { azimuthDeg: 180, hfovDeg: 340, vfovDeg: 170, horizonAt:
const sky = (iso: string, state: 'day' | 'dusk' | 'night' = 'night') => {
const t = new Date(iso);
- return makePhysicalSky(state, t, 0, FALLBACK_VIEW, sunAt(P, t));
+ return makePhysicalSky(sunAt(P, t), 0, FALLBACK_VIEW);
};
const bodies = (iso: string, state: 'day' | 'dusk' | 'night' = 'night', lines = false) => {
const p = sky(iso, state);
@@ -134,7 +134,7 @@ describe('the stars under the figures', () => {
const { linesAt } = await import('./starCatalogue');
const cam = windowFor(FALLBACK_VIEW, 1100, 619).camera;
const t = new Date('2026-11-25T00:00:00Z'); // full moon, high in the south
- const p = makePhysicalSky('night', t, 0, FALLBACK_VIEW, sunAt(P, t));
+ const p = makePhysicalSky(sunAt(P, t), 0, FALLBACK_VIEW);
const nb = nightBodies(p, paintSky(p, 1100, 619, cam), false);
let vertices = 0;
let carried = 0;
diff --git a/src/app/features/scene/ridge/nightBodies.ts b/src/app/features/scene/ridge/nightBodies.ts
index 40fde6e2..bf313a4a 100644
--- a/src/app/features/scene/ridge/nightBodies.ts
+++ b/src/app/features/scene/ridge/nightBodies.ts
@@ -181,6 +181,7 @@ export function nightBodies(p: PhysicalSky, px: SkyPixels, withLines: boolean):
if (Math.max(Math.abs(base[0] - out[0]), Math.abs(base[1] - out[1]), Math.abs(base[2] - out[2])) < 3) continue;
const { base: r0, perMag } = NIGHT_LOOK.starRadius;
stars.push({
+ id: s.index,
x: at.x,
y: at.y,
r: r0 + perMag * Math.max(0, MAG_LIMIT - m),
diff --git a/src/app/features/scene/ridge/physicalSky.test.ts b/src/app/features/scene/ridge/physicalSky.test.ts
index 87721078..20d5187e 100644
--- a/src/app/features/scene/ridge/physicalSky.test.ts
+++ b/src/app/features/scene/ridge/physicalSky.test.ts
@@ -1,10 +1,12 @@
import { describe, expect, it } from 'vitest';
import { FALLBACK_VIEW } from './view';
import { ELSEWHERE_VIEW } from './manifest.fixture';
-import { sunForState } from './sunAt';
+import { sunAt } from './sunAt';
+import { momentFor } from './skyMoment';
import { makePhysicalSky, paintSky } from './physicalSky';
+import { sunOfBand } from './skyTestkit';
import { ridgeDrawn } from '../skyForState';
-import type { FixedSkyState } from '../skyState';
+import type { FixedSkyState } from './skyMoment';
import { windowFor } from './view';
import type { PhysicalSky } from './physicalSky';
@@ -43,7 +45,7 @@ describe.each(['day', 'dusk', 'night'] as FixedSkyState[])(
let hi = -1;
for (const day of DAYS) {
for (const w of WEATHER) {
- const sky = makePhysicalSky(state, new Date(`${day}T10:40:00Z`), w, FALLBACK_VIEW);
+ const sky = makePhysicalSky(sunOfBand(FALLBACK_VIEW.place, state, new Date(`${day}T10:40:00Z`)), w, FALLBACK_VIEW);
for (const [vw, vh] of VIEWPORTS) {
const px = paintSky(sky, vw, vh, camera(sky, vw, vh));
for (let i = 0; i < px.w * px.h * 4; i += 4) {
@@ -64,7 +66,7 @@ describe('weather in the sky', () => {
it('overcast is cloud: less blue and less contrast than clear air at the same sun', () => {
const at = new Date('2026-06-21T10:40:00Z');
const paint = (w: number) => {
- const sky = makePhysicalSky('day', at, w, FALLBACK_VIEW);
+ const sky = makePhysicalSky(sunOfBand(FALLBACK_VIEW.place, 'day', at), w, FALLBACK_VIEW);
return paintSky(sky, 640, 360, camera(sky, 640, 360));
};
const clear = paint(0);
@@ -92,7 +94,7 @@ describe('the sun disc', () => {
const disc = (sky: PhysicalSky) => paintSky(sky, 1280, 720, facingSun(sky, 1280, 720));
const noon = new Date('2026-12-21T11:00:00Z'); // about 18 degrees: higher suns are above the top of the window
it('is drawn by the host, in a clear sky by day, white with the sun high', () => {
- const sky = makePhysicalSky('day', noon, 0, FALLBACK_VIEW);
+ const sky = makePhysicalSky(sunOfBand(FALLBACK_VIEW.place, 'day', noon), 0, FALLBACK_VIEW);
const d = disc(sky).sunDisc;
expect(d).toBeDefined();
expect(d!.x).toBeGreaterThan(0);
@@ -103,11 +105,12 @@ describe('the sun disc', () => {
expect(Math.min(...d!.rgb)).toBeGreaterThan(150); // a warm white at 21 degrees
});
it('is hidden by overcast and absent at night', () => {
- expect(disc(makePhysicalSky('day', noon, 0.7, FALLBACK_VIEW)).sunDisc).toBeUndefined();
- expect(disc(makePhysicalSky('night', noon, 0, FALLBACK_VIEW)).sunDisc).toBeUndefined();
+ expect(disc(makePhysicalSky(sunOfBand(FALLBACK_VIEW.place, 'day', noon), 0.7, FALLBACK_VIEW)).sunDisc).toBeUndefined();
+ expect(disc(makePhysicalSky(sunOfBand(FALLBACK_VIEW.place, 'night', noon), 0, FALLBACK_VIEW)).sunDisc).toBeUndefined();
});
- it('is orange-tinted low in the sky', () => {
- const d = disc(makePhysicalSky('dusk', noon, 0, FALLBACK_VIEW)).sunDisc;
+ it('is orange-tinted low in the sky (golden hour, 4 degrees up)', () => {
+ const golden = momentFor({ kind: 'named', id: 'golden' }, FALLBACK_VIEW.place, noon);
+ const d = disc(makePhysicalSky(sunAt(FALLBACK_VIEW.place, golden), 0, FALLBACK_VIEW)).sunDisc;
expect(d).toBeDefined();
expect(d!.rgb[0]).toBeGreaterThan(d!.rgb[2]);
});
@@ -118,16 +121,16 @@ describe('the sky is made from the View it is given', () => {
const sameSpotOtherCamera = { ...FALLBACK_VIEW, lookAzDeg: 30, windowDeg: 100, horizonRow: 200 };
it("lights the sky from the sun over the View's place, at its altitude", () => {
- const sky = makePhysicalSky('day', NOW, 0, ELSEWHERE_VIEW);
+ const sky = makePhysicalSky(sunOfBand(ELSEWHERE_VIEW.place, 'day', NOW), 0, ELSEWHERE_VIEW);
expect(sky.view).toBe(ELSEWHERE_VIEW);
- expect(sky.sun).toEqual(sunForState(ELSEWHERE_VIEW.place, 'day', NOW));
- expect(sky.sun).not.toEqual(sunForState(FALLBACK_VIEW.place, 'day', NOW));
+ expect(sky.sun).toEqual(sunOfBand(ELSEWHERE_VIEW.place, 'day', NOW));
+ expect(sky.sun).not.toEqual(sunAt(FALLBACK_VIEW.place, sunOfBand(ELSEWHERE_VIEW.place, 'day', NOW).time));
expect(sky.atm.observerKm).toBe(ELSEWHERE_VIEW.place.altitudeKm);
});
it("fits and samples the stops through the View's camera: the same place and sun with another look is another gradient", () => {
- const a = makePhysicalSky('day', NOW, 0, FALLBACK_VIEW);
- const b = makePhysicalSky('day', NOW, 0, sameSpotOtherCamera);
+ const a = makePhysicalSky(sunOfBand(FALLBACK_VIEW.place, 'day', NOW), 0, FALLBACK_VIEW);
+ const b = makePhysicalSky(sunOfBand(sameSpotOtherCamera.place, 'day', NOW), 0, sameSpotOtherCamera);
expect(b.sun).toEqual(a.sun);
expect(b.stops).not.toEqual(a.stops);
});
diff --git a/src/app/features/scene/ridge/physicalSky.ts b/src/app/features/scene/ridge/physicalSky.ts
index e17a150e..7f8f5f24 100644
--- a/src/app/features/scene/ridge/physicalSky.ts
+++ b/src/app/features/scene/ridge/physicalSky.ts
@@ -1,7 +1,8 @@
-// The ridge scene's sky: the View's place's sun on the real clock, the atmosphere baked from it, a camera, and the display that makes it
+// The ridge scene's sky: the sun over the View's place at the drawn moment, the atmosphere baked from it, a camera, and the display that makes it
// pixels. `makePhysicalSky` does the one expensive thing (the LUT bake, tens of ms) and fits the display from a fixed 16:9
// grid, so resizing the window repaints the same sky. `paintSky` is per-texel lookups only.
-import type { FixedSkyState } from '../skyState';
+import { skyBand } from './skyMoment';
+import type { FixedSkyState } from './skyMoment';
import { bakeAtmosphere } from './earthAtmosphere';
import type { Atmosphere } from './earthAtmosphere';
import { domeSize, renderDome, SUN_RADIUS, sunOnScreen } from './skyDome';
@@ -11,7 +12,6 @@ import { display8, fitDisplay } from './toneMap';
import type { Display, Fit } from './toneMap';
import { moonAt } from './nightSky';
import type { MoonSample, NightLight } from './nightSky';
-import { sunForState } from './sunAt';
import type { SunSample } from './sunAt';
import { windowFor } from './view';
import type { Camera, View } from './view';
@@ -55,16 +55,10 @@ export function rowMean(dome: Dome, display: Display, row: number): Srgb {
return [Math.round(acc[0] / dome.w), Math.round(acc[1] / dome.w), Math.round(acc[2] / dome.w)];
}
-export function makePhysicalSky(
- state: FixedSkyState,
- now: Date,
- weatherValue: number,
- view: View,
- /** A sun to draw instead of the state's own (the look sheet's grid of elevations); `state` still picks the display budget. */
- sunOverride?: SunSample
-): PhysicalSky {
+/** The sky lit by the sun it is given (the moment is skyMoment.ts's choice); the display budget is the band of that sun. */
+export function makePhysicalSky(sun: SunSample, weatherValue: number, view: View): PhysicalSky {
const t0 = clock();
- const sun = sunOverride ?? sunForState(view.place, state, now);
+ const state = skyBand(sun.elevation);
const weather = weatherOf(weatherValue);
const atm = bakeAtmosphere({
sunElevationDeg: sun.elevation,
diff --git a/src/app/features/scene/ridge/ridgeAssets.test.ts b/src/app/features/scene/ridge/ridgeAssets.test.ts
index aaec06ee..2795285c 100644
--- a/src/app/features/scene/ridge/ridgeAssets.test.ts
+++ b/src/app/features/scene/ridge/ridgeAssets.test.ts
@@ -1,46 +1,75 @@
-// The committed baked set under public/ridge: what the baker wrote is what ships, within the budget the baker itself refuses on
-// (export.py MAX_CARDS, TOTAL_BYTES_MAX, DECODE_BYTES_MAX). Reads with node fs. The gate reads each card file's own bytes, not the manifest's
-// claims about them: the WebP container is walked and its stated dimensions (VP8X canvas, VP8 / VP8L frame header) must equal the card's
-// width and band height, which the decode budget is computed from; and the bake id is re-derived from the card bytes as the baker derives it,
-// so any corruption of a card, same length or not, fails. No pixel decoder is in the tree; the baker's own check decodes pixels.
+// The committed baked set under public/ridge: what the baker wrote is what ships, within the budget the baker itself refuses on (export.py MAX_CARDS,
+// TILE_BYTES_MAX, PLACE_BYTES_MAX, RESIDENT_BYTES_MAX). Reads with node fs. The gate reads each tile file's own bytes, not the manifest's claims about
+// them: the WebP container is walked and its stated dimensions (VP8X canvas, VP8 / VP8L frame header) must equal the tile's width (tile_w + 2 apron) and
+// its band height, which the resident budget is computed from; and the bake id is re-derived from the tile bytes as the baker derives it (tile-major, then
+// card, colour then geometry), so any corruption of a tile, same length or not, fails. No pixel decoder is in the tree; the baker's own check decodes pixels.
+import { execFileSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
import { join, sep } from 'node:path';
import { describe, expect, it } from 'vitest';
import { MAX_CARDS, parseIndex, parseManifest } from './manifest';
+import { runTiles } from './ring';
+import { HFOV_MAX_DEG } from './view';
-/** The same constants as scripts/ridge-bake/export.py: every card file of a place, and the cards decoded (2 textures x w x band rows x 4 bytes each). */
-export const TOTAL_BYTES_MAX = 1_500_000;
-export const DECODE_BYTES_MAX = 20_000_000;
+/** The same constants as scripts/ridge-bake/export.py. */
+export const TILE_BYTES_MAX = 235_000;
+export const PLACE_BYTES_MAX = 7_500_000;
+export const RESIDENT_BYTES_MAX = 20_000_000;
interface WireFile {
file: string;
bytes: number;
}
-interface WireCard {
+interface WireTile {
top: number;
h: number;
- scale: number;
+ distance_m: number;
colour: WireFile;
geometry: WireFile;
}
export interface WireManifest {
+ schema: number;
bake_id: string;
- w: number;
- cards: WireCard[];
- camera?: { heading_max_deg?: number };
+ view: { ring_w: number; tile_w: number; tiles: number; apron: number };
+ camera: { r_max_m: number; r_max_forward_m: number };
+ cards: unknown[];
+ tiles: (WireTile | null)[][];
}
-const files = (c: WireCard): WireFile[] => [c.colour, c.geometry];
+const files = (e: WireTile | null): WireFile[] => (e ? [e.colour, e.geometry] : []);
+const bytesOf = (row: (WireTile | null)[]): number =>
+ row.flatMap(files).reduce((a, f) => a + f.bytes, 0);
-/** Why a manifest breaks the size gate, or undefined: too many cards, too many bytes, or too many decoded bytes. */
+/**
+ * N and the lit bytes of the worst run of N consecutive tiles (4 bytes x (tile_w + 2) x band rows, per card), cyclic: the same N and the same sum as
+ * export.py `run_tiles` and `resident_bytes`, recomputed from the manifest alone, at the larger of the two offsets the bake ships. The nearest distance is card 0's smallest over the tiles.
+ */
+export function residentBytes(m: WireManifest): { n: number; bytes: number } {
+ const { tiles, tile_w } = m.view;
+ const rmin = Math.min(...m.tiles.flatMap((row) => (row[0] ? [row[0].distance_m] : [])));
+ const n = runTiles({ tiles }, HFOV_MAX_DEG, Math.max(m.camera.r_max_m, m.camera.r_max_forward_m), rmin);
+ const per = m.tiles.map((row) => row.reduce((a, e) => a + (e ? 4 * (tile_w + 2) * e.h : 0), 0));
+ let worst = 0;
+ for (let t = 0; t < tiles; t += 1) {
+ let sum = 0;
+ for (let k = 0; k < n; k += 1) sum += per[(t + k) % tiles];
+ worst = Math.max(worst, sum);
+ }
+ return { n, bytes: worst };
+}
+
+/** Why a manifest breaks the size gate, or undefined: too many cards, a tile or the place too many bytes, or the resident run lit past the budget. */
export function sizeGate(m: WireManifest): string | undefined {
if (m.cards.length > MAX_CARDS) return `${m.cards.length} cards, above ${MAX_CARDS}`;
- const bytes = m.cards.flatMap(files).reduce((a, f) => a + f.bytes, 0);
- if (bytes > TOTAL_BYTES_MAX) return `the cards are ${bytes} bytes, above ${TOTAL_BYTES_MAX}`;
- const decoded = m.cards.reduce((a, c) => a + 2 * m.w * c.h * 4, 0);
- return decoded > DECODE_BYTES_MAX
- ? `the cards decode to ${decoded} bytes, above ${DECODE_BYTES_MAX}`
+ const tileBytes = m.tiles.map(bytesOf);
+ const worst = tileBytes.findIndex((b) => b > TILE_BYTES_MAX);
+ if (worst >= 0) return `tile ${worst} is ${tileBytes[worst]} bytes, above ${TILE_BYTES_MAX}`;
+ const total = tileBytes.reduce((a, b) => a + b, 0);
+ if (total > PLACE_BYTES_MAX) return `the place is ${total} bytes, above ${PLACE_BYTES_MAX}`;
+ const res = residentBytes(m);
+ return res.bytes > RESIDENT_BYTES_MAX
+ ? `${res.n} consecutive tiles light to ${res.bytes} bytes, above ${RESIDENT_BYTES_MAX}`
: undefined;
}
@@ -85,16 +114,18 @@ export function webpFault(b: Uint8Array, w: number, h: number): string | undefin
return bad ? `states ${bad}, the manifest ${w}x${h}` : undefined;
}
-/** The baker's bake id (export.py `bake_id`): first 12 hex of sha256 over the card files in index order, colour then geometry. */
-export function bakeIdOf(
- cardBytes: (card: number, kind: 'colour' | 'geometry') => Uint8Array,
- n: number
-): string {
+const BLANK_ID = '0'.repeat(12);
+
+/** The manifest text as the baker hashed it: the bytes as committed, with the bake_id value blanked (an id cannot hash itself). */
+export function blankedManifest(text: string, bakeId: string): string {
+ return text.replace(`"bake_id": "${bakeId}"`, `"bake_id": "${BLANK_ID}"`);
+}
+
+/** The baker's bake id (export.py `bake_id`): first 12 hex of sha256 over the blanked manifest text, then the tile files, tile-major then card, colour then geometry (a card absent from a tile writes none): the id addresses the whole bake. */
+export function bakeIdOf(blankManifest: string, tileFiles: Uint8Array[]): string {
const h = createHash('sha256');
- for (let i = 0; i < n; i += 1) {
- h.update(cardBytes(i, 'colour'));
- h.update(cardBytes(i, 'geometry'));
- }
+ h.update(blankManifest, 'utf8');
+ tileFiles.forEach((b) => h.update(b));
return h.digest('hex').slice(0, 12);
}
@@ -111,58 +142,77 @@ describe('the committed ridge assets', () => {
dirs.forEach(([id, dir]) => {
describe(`${id} (${dir})`, () => {
- const raw = readJson(join(ROOT, dir, 'manifest.json')) as WireManifest & { schema: number };
+ const raw = readJson(join(ROOT, dir, 'manifest.json')) as WireManifest;
const read = (f: WireFile) => readFileSync(join(ROOT, dir, f.file));
+ const all = raw.tiles.flatMap((row) => row.flatMap(files));
- it('is schema 2, parses, and its directory ends in its bake id', () => {
- expect(raw.schema).toBe(2);
+ it('is schema 3, parses, and its directory ends in its bake id', () => {
+ expect(raw.schema).toBe(3);
expect(() => parseManifest(raw, `${dir}/`)).not.toThrow();
expect(dir.endsWith(`-${raw.bake_id}`)).toBe(true);
});
- it('has every card file, at the length the manifest states', () => {
- raw.cards.flatMap(files).forEach((f) => {
+ it('names a time zone Intl knows (the sky draws its named moments in the place local day)', () => {
+ const tz = (raw as unknown as { place: { tz?: unknown } }).place.tz;
+ expect(typeof tz).toBe('string');
+ expect(() => new Intl.DateTimeFormat('en-US', { timeZone: tz as string })).not.toThrow();
+ });
+
+ it('has every tile file, at the length the manifest states', () => {
+ all.forEach((f) => {
expect(statSync(join(ROOT, dir, f.file)).size, f.file).toBe(f.bytes);
});
});
- it('decodes every card file as the WebP of the width and band height the manifest states', () => {
- raw.cards.forEach((c) =>
- files(c).forEach((f) => {
- expect(webpFault(read(f), raw.w, c.h), f.file).toBeUndefined();
- })
+ it('decodes every tile file as the WebP of tile_w + 2 apron columns by the band height the manifest states', () => {
+ const w = raw.view.tile_w + 2 * raw.view.apron;
+ raw.tiles.forEach((row) =>
+ row.forEach((e) =>
+ files(e).forEach((f) => {
+ expect(webpFault(read(f), w, (e as WireTile).h), f.file).toBeUndefined();
+ })
+ )
);
});
- it('holds the bytes its bake id was made from', () => {
- const bytes = (i: number, kind: 'colour' | 'geometry') => read(raw.cards[i][kind]);
- expect(bakeIdOf(bytes, raw.cards.length)).toBe(raw.bake_id);
+ it('holds the manifest and the bytes its bake id was made from', () => {
+ const ordered = raw.tiles.flatMap((row) => row.flatMap(files)).map(read);
+ const text = blankedManifest(readFileSync(join(ROOT, dir, 'manifest.json'), 'utf8'), raw.bake_id);
+ expect(text).toContain(`"bake_id": "${BLANK_ID}"`);
+ expect(bakeIdOf(text, ordered)).toBe(raw.bake_id);
+ expect(bakeIdOf(text.replace('"r_max_forward_m"', '"r_max_forward_m "'), ordered), 'a changed manifest keeps its id').not.toBe(raw.bake_id);
});
- it('keeps the place inside the card, byte and decode budget', () => {
+ it('is checked out as committed: git converts no line end of the manifest, the index or a tile, so the bytes served are the bytes the id was made from', () => {
+ const attr = (file: string) =>
+ execFileSync('git', ['check-attr', 'text', 'eol', '--', file], { encoding: 'utf8' }).replace(/\r/g, '').trim().split('\n');
+ const tile = files(raw.tiles[0].find((e) => e)!)[0].file;
+ [`public/ridge/${dir}/manifest.json`, 'public/ridge/index.json', `public/ridge/${dir}/${tile}`].forEach((f) =>
+ expect(attr(f), f).toEqual([`${f}: text: unset`, `${f}: eol: unspecified`])
+ );
+ expect(readFileSync(join(ROOT, dir, 'manifest.json'), 'utf8')).not.toContain('\r');
+ });
+
+ it('keeps the place inside the tile, place and resident budgets, computed from the manifest alone', () => {
expect(sizeGate(raw)).toBeUndefined();
+ expect(residentBytes(raw).n).toBeLessThanOrEqual(raw.view.tiles);
});
- it('carries its camera and a scale for every card', () => {
- expect(Number.isFinite(raw.camera?.heading_max_deg)).toBe(true);
- raw.cards.forEach((c) => expect(Number.isFinite(c.scale) && c.scale > 0).toBe(true));
+ it('carries the offset bound and a distance for every tile a card holds', () => {
+ expect(raw.camera.r_max_m).toBeGreaterThan(0);
+ expect(raw.camera.r_max_forward_m).toBeGreaterThanOrEqual(raw.camera.r_max_m);
+ raw.tiles.forEach((row) => row.forEach((e) => e && expect(e.distance_m).toBeGreaterThan(0)));
+ raw.cards.forEach((_, i) => expect(raw.tiles.some((row) => row[i] !== null)).toBe(true));
});
});
});
- it('shows Vienna from a camera pushed forward: no card is smaller than its bake', () => {
- const vienna = index.places.vienna;
- expect(vienna).toBeDefined();
- const m = readJson(join(ROOT, vienna, 'manifest.json')) as WireManifest;
- m.cards.forEach((c) => expect(c.scale).toBeGreaterThanOrEqual(1));
- });
-
it('holds no file a manifest does not name', () => {
const named = new Set(['index.json']);
dirs.forEach(([, dir]) => {
named.add(`${dir}/manifest.json`);
- (readJson(join(ROOT, dir, 'manifest.json')) as WireManifest).cards
- .flatMap(files)
+ (readJson(join(ROOT, dir, 'manifest.json')) as WireManifest).tiles
+ .flatMap((row) => row.flatMap(files))
.forEach((f) => named.add(`${dir}/${f.file}`));
});
const onDisk = readdirSync(ROOT, { recursive: true, withFileTypes: true })
@@ -178,65 +228,83 @@ describe('the committed ridge assets', () => {
});
});
-describe('the card gates refuse a card that is not what the manifest says', () => {
+describe('the tile gates refuse a tile that is not what the manifest says', () => {
const dir = Object.values(index.places)[0];
const manifest = readJson(join(ROOT, dir, 'manifest.json')) as WireManifest;
- const real = readFileSync(join(ROOT, dir, manifest.cards[1].geometry.file));
- const { h } = manifest.cards[1];
- const w = manifest.w;
- const id = (b: Uint8Array) => bakeIdOf(() => b, 1);
+ const e = manifest.tiles.map((row) => row[1]).find((x) => x) as WireTile;
+ const real = readFileSync(join(ROOT, dir, e.geometry.file));
+ const { h } = e;
+ const w = manifest.view.tile_w + 2 * manifest.view.apron;
- it('accepts the real card at its size', () => {
+ it('accepts the real tile at its size', () => {
expect(webpFault(real, w, h)).toBeUndefined();
});
- it("refuses a manifest that lies about the card's size, and a file cut short or padded", () => {
+ it("refuses a manifest that lies about the tile's size, and a file cut short or padded", () => {
expect(webpFault(real, w, h + 1)).toMatch(/states/);
+ expect(webpFault(real, manifest.view.tile_w, h)).toMatch(/states/); // a tile without its apron
expect(webpFault(real.subarray(0, real.length - 1), w, h)).toBeDefined();
expect(webpFault(Buffer.concat([real, Buffer.from([0])]), w, h)).toBeDefined();
});
it('refuses bytes that are not a WebP', () => {
expect(webpFault(Buffer.from('not a webp, but long enough to try'), w, h)).toMatch(/RIFF/);
});
- it('re-derives a different bake id from a card with the same length and 8 bytes overwritten', () => {
+ it('re-derives a different bake id from a tile with the same length and 8 bytes overwritten', () => {
const bad = Buffer.from(real);
bad.fill(0xab, 100, 108);
expect(bad.length).toBe(real.length);
- expect(id(bad)).not.toBe(id(real));
+ expect(bakeIdOf('m', [bad])).not.toBe(bakeIdOf('m', [real]));
});
- it('derives the id from colour then geometry, in card order', () => {
- const a = Buffer.from('a-colour');
- const b = Buffer.from('b-geometry');
- const order = (c: number, k: 'colour' | 'geometry') => (c === 0 && k === 'colour' ? a : b);
- const swapped = (c: number, k: 'colour' | 'geometry') => (c === 0 && k === 'colour' ? b : a);
- const want = createHash('sha256').update(a).update(b).update(b).update(b);
- expect(bakeIdOf(order, 2)).toBe(want.digest('hex').slice(0, 12));
- expect(bakeIdOf(swapped, 2)).not.toBe(bakeIdOf(order, 2));
+ it('derives the id over the files in the order the baker writes them: any other order is another id', () => {
+ const [a, b, c] = [Buffer.from('t0-c0-colour'), Buffer.from('t0-c0-geometry'), Buffer.from('t1-c0-colour')];
+ const want = createHash('sha256').update('manifest').update(a).update(b).update(c).digest('hex').slice(0, 12);
+ expect(bakeIdOf('manifest', [a, b, c])).toBe(want);
+ expect(bakeIdOf('manifest', [a, c, b])).not.toBe(want);
+ expect(bakeIdOf('manifest', [b, a, c])).not.toBe(want);
+ expect(bakeIdOf('manifest!', [a, b, c])).not.toBe(want);
});
});
describe('sizeGate', () => {
- const card = (bytes: number, h: number): WireCard => ({
+ const entry = (bytes: number, h = 100): WireTile => ({
top: 0,
h,
- scale: 1,
- colour: { file: 'c.webp', bytes },
- geometry: { file: 'g.webp', bytes },
+ distance_m: 1000,
+ colour: { file: 'c.webp', bytes: Math.floor(bytes / 2) },
+ geometry: { file: 'g.webp', bytes: bytes - Math.floor(bytes / 2) },
});
- const set = (n: number, bytes: number, h: number): WireManifest => ({
+ const ring = (tiles: number, perTile: number, h = 100, cards = 1): WireManifest => ({
+ schema: 3,
bake_id: 'x',
- w: 1280,
- cards: Array.from({ length: n }, () => card(bytes, h)),
+ view: { ring_w: 6400, tile_w: 6400 / tiles, tiles, apron: 2 },
+ camera: { r_max_m: 50, r_max_forward_m: 50 },
+ cards: Array.from({ length: cards }, () => ({})),
+ tiles: Array.from({ length: tiles }, () =>
+ Array.from({ length: cards }, () => entry(perTile / cards, h))
+ ),
});
- it('passes a place at the byte budget and fails one a byte over', () => {
- expect(sizeGate(set(3, 250_000, 100))).toBeUndefined();
- expect(sizeGate(set(3, 250_001, 100))).toMatch(/1500006 bytes/);
+ it('passes a tile at the byte cap and fails one a byte over', () => {
+ expect(sizeGate(ring(32, 7000, 10))).toBeUndefined();
+ const at = ring(32, 1, 10);
+ expect(sizeGate({ ...at, tiles: [[entry(TILE_BYTES_MAX, 10)], ...at.tiles.slice(1)] })).toBeUndefined();
+ expect(sizeGate({ ...at, tiles: [[entry(TILE_BYTES_MAX + 1, 10)], ...at.tiles.slice(1)] })).toMatch(
+ /tile 0 is 235001 bytes/
+ );
});
- it('fails a seventh card, and cards that decode past the budget', () => {
- expect(sizeGate(set(6, 1, 150))).toBeUndefined();
- expect(sizeGate(set(7, 1, 150))).toMatch(/7 cards/);
- expect(sizeGate(set(2, 1, 600))).toBeUndefined();
- expect(sizeGate(set(4, 1, 600))).toMatch(/decode/);
+ it('passes a place at the byte cap and fails one a byte over', () => {
+ // 32 tiles at 234 375 bytes is exactly 7 500 000; one byte more on one tile is over.
+ const at = ring(32, PLACE_BYTES_MAX / 32, 10);
+ expect(sizeGate(at)).toBeUndefined();
+ const over = { ...at, tiles: [[entry(PLACE_BYTES_MAX / 32 + 1, 10)], ...at.tiles.slice(1)] };
+ expect(sizeGate(over)).toMatch(/the place is 7500001 bytes/);
+ });
+
+ it('fails a seventh card, and a ring that lights past the resident budget by a row', () => {
+ expect(sizeGate({ ...ring(32, 1, 10), cards: Array(7).fill({}) })).toMatch(/7 cards/);
+ const n = residentBytes(ring(32, 1, 100)).n;
+ const rows = Math.floor(RESIDENT_BYTES_MAX / (n * 4 * 202)); // the most rows N tiles can hold lit within the budget
+ expect(sizeGate(ring(32, 1, rows))).toBeUndefined();
+ expect(sizeGate(ring(32, 1, rows + 1))).toMatch(/consecutive tiles light to/);
});
});
diff --git a/src/app/features/scene/ridge/ring.test.ts b/src/app/features/scene/ridge/ring.test.ts
new file mode 100644
index 00000000..bfe049fa
--- /dev/null
+++ b/src/app/features/scene/ridge/ring.test.ts
@@ -0,0 +1,93 @@
+import { describe, expect, it } from 'vitest';
+import { distanceAt, norm, residentTiles, runTiles, tileAzimuth } from './ring';
+import { parseManifest } from './manifest';
+import { wireManifest } from './manifest.fixture';
+
+const ring32 = { tiles: 32 };
+
+describe('norm', () => {
+ it('brings any angle into [0, 360)', () => {
+ expect(norm(0)).toBe(0);
+ expect(norm(360)).toBe(0);
+ expect(norm(-10)).toBe(350);
+ expect(norm(725)).toBe(5);
+ });
+});
+
+describe('residentTiles', () => {
+ it('names the tiles an arc overlaps across north, with turns 0 and 1 and monotone unwrapped azimuths', () => {
+ // Centre 355, half 40: [315, 395] overlaps tiles 28..31 of the first turn and 0..3 of the next.
+ const refs = residentTiles(ring32, 355, 40);
+ expect(refs.map((r) => r.tile)).toEqual([28, 29, 30, 31, 0, 1, 2, 3]);
+ expect(refs.map((r) => r.turn)).toEqual([0, 0, 0, 0, 1, 1, 1, 1]);
+ const az = refs.map((r) => tileAzimuth(ring32, r));
+ az.slice(1).forEach((a, i) => expect(a).toBeGreaterThan(az[i]));
+ expect(az[0]).toBe(315);
+ expect(az[4]).toBe(360);
+ });
+
+ it('picks the same tiles for a heading and the heading a revolution on, in another turn', () => {
+ const a = residentTiles(ring32, 40, 30);
+ const b = residentTiles(ring32, 400, 30);
+ expect(b.map((r) => r.tile)).toEqual(a.map((r) => r.tile));
+ expect(b.every((r, i) => r.turn === a[i].turn + 1)).toBe(true);
+ // And a heading turned backwards across north.
+ const c = residentTiles(ring32, -20, 30);
+ expect(c.map((r) => r.tile)).toEqual([27, 28, 29, 30, 31, 0]);
+ expect(c.map((r) => r.turn)).toEqual([-1, -1, -1, -1, -1, 0]);
+ });
+
+ it('names a tile once at most, even for an arc of a whole ring or more', () => {
+ const all = residentTiles(ring32, 100, 400);
+ expect(all).toHaveLength(32);
+ expect(new Set(all.map((r) => r.tile)).size).toBe(32);
+ });
+
+ it('is one tile for an arc inside a tile, and includes a tile an arc only touches at its edge', () => {
+ expect(residentTiles(ring32, 5, 1).map((r) => r.tile)).toEqual([0]);
+ expect(residentTiles(ring32, 11.25, 0).map((r) => r.tile)).toEqual([1]);
+ });
+});
+
+describe('distanceAt', () => {
+ const m = parseManifest(wireManifest(), '/d/'); // four tiles of 90 degrees, centres at 45, 135, 225, 315
+ it('is the tile distance at a tile centre and interpolates linearly between centres', () => {
+ expect(distanceAt(m, 0, 45)).toBeCloseTo(1000, 9);
+ expect(distanceAt(m, 0, 135)).toBeCloseTo(1200, 9);
+ expect(distanceAt(m, 0, 90)).toBeCloseTo(1100, 9);
+ });
+
+ it('interpolates across the wrap at north and takes any unwrapped heading the same as its wrapped one', () => {
+ // between tile 3 (315 degrees, 1100 m) and tile 0 (45, 1000 m): north is halfway.
+ expect(distanceAt(m, 0, 0)).toBeCloseTo(1050, 9);
+ expect(distanceAt(m, 0, 360)).toBeCloseTo(1050, 9);
+ expect(distanceAt(m, 0, -360)).toBeCloseTo(1050, 9);
+ expect(distanceAt(m, 0, 400)).toBeCloseTo(distanceAt(m, 0, 40), 9);
+ expect(distanceAt(m, 0, -20)).toBeCloseTo(distanceAt(m, 0, 340), 9);
+ });
+
+ it('skips a tile where the card is absent: the line runs on to the next tile that holds it', () => {
+ // card 2 is absent in tile 2 (centre 225): between tile 1 (41000 m at 135) and tile 3 (39000 m at 315), 225 is halfway.
+ expect(distanceAt(m, 2, 225)).toBeCloseTo(40000, 9);
+ expect(distanceAt(m, 2, 135)).toBeCloseTo(41000, 9);
+ expect(distanceAt(m, 2, 180)).toBeCloseTo(40500, 9);
+ expect(distanceAt(m, 2, 270)).toBeCloseTo(39500, 9);
+ });
+
+ it('is the one distance all round for a card that is in one tile only', () => {
+ const one = wireManifest({}, 3) as { tiles: (unknown | null)[][] };
+ const only = { ...one, tiles: one.tiles.map((row, t) => [row[0], row[1], t === 1 ? row[2] : null]) };
+ const mo = parseManifest(only, '/d/');
+ [0, 77, 135, 200, 359].forEach((az) => expect(distanceAt(mo, 2, az)).toBeCloseTo(41000, 9));
+ });
+});
+
+describe('runTiles', () => {
+ it('is export.py run_tiles: the arc at the smallest slide rate plus the offset swing, a straddled tile and two tiles of margin each side', () => {
+ // Vienna's numbers: r_max 98.2, nearest card 603 m. s_min = 603 / 701.2; arc = 65.45 / s_min + 2 (98.2 / 603) 57.3.
+ const sMin = 603 / (603 + 98.2);
+ const arc = 65.4545 / sMin + 2 * (98.2 / 603) * 57.3;
+ expect(runTiles(ring32, 72 / 1.1, 98.2, 603)).toBe(Math.ceil(arc / 11.25) + 1 + 4);
+ expect(runTiles(ring32, 72 / 1.1, 100000, 603)).toBe(32);
+ });
+});
diff --git a/src/app/features/scene/ridge/ring.ts b/src/app/features/scene/ridge/ring.ts
new file mode 100644
index 00000000..746ae12e
--- /dev/null
+++ b/src/app/features/scene/ridge/ring.ts
@@ -0,0 +1,79 @@
+// The ring: the one place that reasons about wrap-around at 0 / 360 degrees (a heading is unwrapped and never wrapped by a consumer), and the
+// one place a card's distance at an azimuth is read from its tiles. Pure: no DOM, no state.
+import type { RidgeManifest } from './manifest';
+import type { View } from './view';
+
+/** Tiles fetched beyond the arc each side, and tiles kept beyond it each side (the baker's resident gate counts the keep: `export.py` `run_tiles`; `view.ts` `maxSpeed` spends what it leaves). */
+export const LOAD_MARGIN_TILES = 1;
+export const KEEP_MARGIN_TILES = 2;
+
+/** A compass angle brought into [0, 360). */
+export const norm = (deg: number): number => ((deg % 360) + 360) % 360;
+
+/** A tile of the ring and the revolution it is met in: its unwrapped azimuth is `turn x 360 + tile x (360 / tiles)`. */
+export interface TileRef {
+ tile: number;
+ turn: number;
+}
+
+/**
+ * The tiles that overlap `[centre - half, centre + half]`, unwrapped compass degrees, in increasing unwrapped azimuth. Each tile is named at most once
+ * (an arc of a whole ring or more is every tile, from the one the arc starts in).
+ */
+export function residentTiles(
+ view: Pick,
+ centreDeg: number,
+ halfArcDeg: number
+): TileRef[] {
+ const w = 360 / view.tiles;
+ const first = Math.floor((centreDeg - halfArcDeg) / w);
+ const last = Math.min(Math.floor((centreDeg + halfArcDeg) / w), first + view.tiles - 1);
+ const out: TileRef[] = [];
+ for (let u = first; u <= last; u += 1) {
+ out.push({ tile: ((u % view.tiles) + view.tiles) % view.tiles, turn: Math.floor(u / view.tiles) });
+ }
+ return out;
+}
+
+/** The unwrapped azimuth of the left edge of a tile met in `turn`. */
+export const tileAzimuth = (view: Pick, ref: TileRef): number =>
+ ref.turn * 360 + (ref.tile * 360) / view.tiles;
+
+/**
+ * The distance of card `card` at compass angle `azDeg`, metres: the circular linear interpolation of the tiles' `distanceM` between tile centres, a tile
+ * where the card is absent skipped (the line runs on to the next tile that holds it; a card in one tile only has that distance all round).
+ */
+export function distanceAt(manifest: RidgeManifest, card: number, azDeg: number): number {
+ const n = manifest.view.tiles;
+ const at = (t: number) => manifest.tiles[t][card]?.distanceM;
+ const u = norm(azDeg) / (360 / n) - 0.5; // tile-centre coordinates: tile t's centre is at t
+ const lo = Math.floor(u);
+ const frac = u - lo;
+ const held = (from: number, step: number): number => {
+ for (let k = 0; k < n; k += 1) {
+ const t = (((from + step * k) % n) + n) % n;
+ if (at(t) !== undefined) return k;
+ }
+ throw new Error(`ridge: card ${card} is in no tile`);
+ };
+ // The nearest tiles that hold the card at or before the point (back) and after it (ahead), by how many tile steps away they are.
+ const back = held(lo, -1);
+ const ahead = held(lo + 1, 1);
+ const tBack = (((lo - back) % n) + n) % n;
+ const tAhead = (((lo + 1 + ahead) % n) + n) % n;
+ const dBack = at(tBack) as number;
+ const dAhead = at(tAhead) as number;
+ const span = back + 1 + ahead; // tile steps between the two holders
+ const along = back + frac; // steps from the back holder to the point
+ return dBack + (dAhead - dBack) * (along / span);
+}
+
+/**
+ * N: the tiles the loader may hold at once for a bake (export.py `run_tiles`): the widest viewport arc at the smallest slide rate plus the offset's own
+ * swing, one straddled tile and two tiles of margin each side. `rminM` is the nearest card's nearest distance.
+ */
+export function runTiles(view: Pick, hfovMaxDeg: number, rMaxM: number, rminM: number): number {
+ const sMin = rminM / (rminM + rMaxM);
+ const arc = hfovMaxDeg / sMin + 2 * (rMaxM / rminM) * 57.3;
+ return Math.min(view.tiles, Math.ceil(arc / (360 / view.tiles)) + 1 + 4);
+}
diff --git a/src/app/features/scene/ridge/skyMoment.test.ts b/src/app/features/scene/ridge/skyMoment.test.ts
new file mode 100644
index 00000000..019c58ba
--- /dev/null
+++ b/src/app/features/scene/ridge/skyMoment.test.ts
@@ -0,0 +1,271 @@
+import { describe, expect, it } from 'vitest';
+import {
+ DAY_FROM,
+ MOMENT_IDS,
+ localDate,
+ localMinutes,
+ momentFor,
+ momentKey,
+ seedFree,
+ skyBand,
+ zonedInstant,
+} from './skyMoment';
+import type { MomentId } from './skyMoment';
+import { sunAt } from './sunAt';
+import type { Place } from './view';
+
+const PLACES: Record = {
+ vienna: { id: 'vienna', lat: 48.19, lon: 16.35, altitudeKm: 0.18, tz: 'Europe/Vienna' },
+ matterhorn: { id: 'matterhorn', lat: 45.98, lon: 7.78, altitudeKm: 3.1, tz: 'Europe/Zurich' },
+ fuji: { id: 'fuji', lat: 35.31, lon: 138.63, altitudeKm: 0.4, tz: 'Asia/Tokyo' },
+ amadablam: { id: 'amadablam', lat: 27.9, lon: 86.9, altitudeKm: 4.2, tz: 'Asia/Kathmandu' },
+ halfdome: {
+ id: 'halfdome',
+ lat: 37.73,
+ lon: -119.55,
+ altitudeKm: 1.2,
+ tz: 'America/Los_Angeles',
+ },
+};
+const DAYS = ['2026-06-21', '2026-12-21', '2026-03-20'];
+const MIN = 60_000;
+
+/** 18:00 place-local on `date`: any instant of that local day names it, and one after the sun's noon, so Night is the coming midnight. */
+const during = (date: string, p: Place): Date => zonedInstant(date, 1080, p.tz);
+const at = (id: MomentId, p: Place, date: string): Date =>
+ momentFor({ kind: 'named', id }, p, during(date, p));
+const el = (p: Place, t: Date): number => sunAt(p, t).elevation;
+
+describe('the named moments', () => {
+ describe.each(Object.entries(PLACES))('%s', (_name, p) => {
+ it.each(DAYS)(
+ '%s: dawn < morning < noon < golden < dusk inside the local day, night after noon',
+ (date) => {
+ const t = Object.fromEntries(MOMENT_IDS.map((id) => [id, at(id, p, date).getTime()]));
+ expect(t.dawn).toBeLessThan(t.morning);
+ expect(t.morning).toBeLessThan(t.noon);
+ expect(t.noon).toBeLessThan(t.golden);
+ expect(t.golden).toBeLessThan(t.dusk);
+ expect(t.night).toBeGreaterThan(t.noon);
+ (['dawn', 'morning', 'noon', 'golden', 'dusk'] as const).forEach((id) =>
+ expect(localDate(new Date(t[id]), p.tz)).toBe(date)
+ );
+ }
+ );
+
+ it.each(DAYS)('%s: each crossing is at its table elevation, within 0.05 degrees', (date) => {
+ const noonEl = el(p, at('noon', p, date));
+ expect(el(p, at('dawn', p, date))).toBeCloseTo(-3, 1);
+ expect(el(p, at('morning', p, date))).toBeCloseTo(Math.min(15, noonEl / 2), 1);
+ expect(el(p, at('golden', p, date))).toBeCloseTo(4, 1);
+ expect(el(p, at('dusk', p, date))).toBeCloseTo(-3, 1);
+ });
+
+ it.each(DAYS)(
+ '%s: noon is the day maximum and night the lowest of the 24 h after it',
+ (date) => {
+ const noon = at('noon', p, date);
+ const night = at('night', p, date);
+ for (let m = 0; m < 24 * 60; m += 5) {
+ const t = new Date(noon.getTime() + m * MIN);
+ expect(el(p, t)).toBeGreaterThanOrEqual(el(p, night) - 1e-3);
+ }
+ const dayStart = zonedInstant(date, 0, p.tz).getTime();
+ for (let m = 0; m < 24 * 60; m += 5) {
+ expect(el(p, new Date(dayStart + m * MIN))).toBeLessThanOrEqual(el(p, noon) + 1e-3);
+ }
+ }
+ );
+ });
+
+ it('morning is half the noon elevation at Vienna in December (the 15 degree rule would never be met)', () => {
+ const p = PLACES.vienna;
+ const noonEl = el(p, at('noon', p, '2026-12-21'));
+ expect(noonEl).toBeLessThan(30);
+ expect(el(p, at('morning', p, '2026-12-21'))).toBeCloseTo(noonEl / 2, 1);
+ expect(el(p, at('morning', p, '2026-06-21'))).toBeCloseTo(15, 1);
+ });
+
+ it('a named moment is today of the place: the same local date gives the same instant, the next day another', () => {
+ const p = PLACES.fuji;
+ const a = momentFor({ kind: 'named', id: 'dusk' }, p, zonedInstant('2026-12-21', 30, p.tz));
+ const b = momentFor({ kind: 'named', id: 'dusk' }, p, zonedInstant('2026-12-21', 1400, p.tz));
+ const c = momentFor({ kind: 'named', id: 'dusk' }, p, zonedInstant('2026-12-22', 30, p.tz));
+ expect(a.getTime()).toBe(b.getTime());
+ expect(c.getTime()).not.toBe(a.getTime());
+ });
+
+ it('is total at a pole, where there is no dawn or no dusk: it falls to noon or midnight', () => {
+ const pole: Place = { id: 'pole', lat: 80, lon: 0, altitudeKm: 0, tz: 'UTC' };
+ for (const date of ['2026-06-21', '2026-12-21']) {
+ const now = zonedInstant(date, 720, 'UTC');
+ for (const id of MOMENT_IDS) {
+ const t = momentFor({ kind: 'named', id }, pole, now);
+ expect(Number.isFinite(t.getTime())).toBe(true);
+ }
+ }
+ const june = zonedInstant('2026-06-21', 720, 'UTC');
+ expect(momentFor({ kind: 'named', id: 'dawn' }, pole, june).getTime()).toBe(
+ momentFor({ kind: 'named', id: 'noon' }, pole, june).getTime()
+ );
+ });
+});
+
+describe('zones', () => {
+ it.each(['Europe/Vienna', 'Asia/Tokyo', 'Asia/Kathmandu', 'America/Phoenix'])(
+ '%s: zonedInstant round-trips every minute of a day',
+ (tz) => {
+ for (let m = 0; m < 1440; m += 1) {
+ const t = zonedInstant('2026-06-21', m, tz);
+ expect(localDate(t, tz)).toBe('2026-06-21');
+ expect(localMinutes(t, tz)).toBe(m);
+ }
+ }
+ );
+
+ it('Kathmandu is UTC+5:45 and Phoenix has no daylight saving', () => {
+ expect(zonedInstant('2026-12-21', 720, 'Asia/Kathmandu').toISOString()).toBe(
+ '2026-12-21T06:15:00.000Z'
+ );
+ expect(zonedInstant('2026-07-01', 720, 'America/Phoenix').toISOString()).toBe(
+ '2026-07-01T19:00:00.000Z'
+ );
+ });
+
+ it('a wall time in the spring-forward gap lands after it; one that happens twice is the first', () => {
+ // Vienna, 2026-03-29: 02:00 became 03:00 (01:00Z). 2026-10-25: 03:00 became 02:00 (01:00Z).
+ expect(zonedInstant('2026-03-29', 150, 'Europe/Vienna').toISOString()).toBe(
+ '2026-03-29T01:30:00.000Z'
+ );
+ expect(zonedInstant('2026-10-25', 150, 'Europe/Vienna').toISOString()).toBe(
+ '2026-10-25T00:30:00.000Z'
+ );
+ });
+
+ it('the place decides, not the zone of the client', () => {
+ const p = PLACES.fuji;
+ const probe = () => ({
+ noon: momentFor({ kind: 'named', id: 'noon' }, p, new Date('2026-12-21T05:00:00Z')).getTime(),
+ free: momentFor({ kind: 'free', date: '2026-07-15', minutes: 330 }, p, new Date()).getTime(),
+ date: localDate(new Date('2026-12-21T16:00:00Z'), p.tz),
+ zi: zonedInstant('2026-03-29', 150, 'Europe/Vienna').getTime(),
+ });
+ const was = process.env.TZ;
+ try {
+ const seen = ['Pacific/Kiritimati', 'America/Anchorage', 'UTC'].map((tz) => {
+ process.env.TZ = tz;
+ return probe();
+ });
+ expect(seen[1]).toEqual(seen[0]);
+ expect(seen[2]).toEqual(seen[0]);
+ } finally {
+ if (was === undefined) delete process.env.TZ;
+ else process.env.TZ = was;
+ }
+ });
+});
+
+describe('Fuji dawn is Japanese dawn', () => {
+ it('lands in the Japanese morning, east of south-east, and a world away from the Vienna one', () => {
+ const fuji = PLACES.fuji;
+ const now = new Date('2026-12-21T04:00:00Z'); // local noon at Fuji
+ const t = momentFor({ kind: 'named', id: 'dawn' }, fuji, now);
+ const hourUtc = t.getUTCHours() + t.getUTCMinutes() / 60;
+ expect(t.getUTCDate()).toBe(20); // the previous UTC day
+ expect(hourUtc).toBeGreaterThan(20.5);
+ expect(hourUtc).toBeLessThan(22);
+ const s = sunAt(fuji, t);
+ expect(s.elevation).toBeCloseTo(-3, 1);
+ expect(s.azimuth).toBeGreaterThan(110);
+ expect(s.azimuth).toBeLessThan(125);
+ const vienna = momentFor({ kind: 'named', id: 'dawn' }, PLACES.vienna, now);
+ expect(Math.abs(vienna.getTime() - t.getTime()) / 3_600_000).toBeGreaterThan(7);
+ expect(Math.abs(vienna.getTime() - t.getTime()) / 3_600_000).toBeLessThan(9.5);
+ });
+});
+
+describe("Night is tonight's, the nearest one", () => {
+ const night = { kind: 'named', id: 'night' } as const;
+ const p = PLACES.vienna;
+ it('at 00:30 it is the midnight coming within the hour, not the one a day ahead; after noon the one coming', () => {
+ const at = Date.parse('2026-06-21T22:30:00Z'); // 00:30 on June 22, Vienna
+ const early = momentFor(night, p, new Date(at));
+ expect(localDate(early, p.tz)).toBe('2026-06-22');
+ expect(early.getTime() - at).toBeGreaterThan(0);
+ expect(early.getTime() - at).toBeLessThan(2 * 3_600_000);
+ const evening = momentFor(night, p, new Date('2026-06-22T12:00:00Z')); // 14:00 June 22
+ expect(localDate(evening, p.tz)).toBe('2026-06-23');
+ expect(evening.getTime() - early.getTime()).toBeGreaterThan(23.9 * 3_600_000);
+ expect(evening.getTime() - early.getTime()).toBeLessThan(24.1 * 3_600_000);
+ expect(momentFor(night, p, new Date('2026-06-22T18:00:00Z')).getTime()).toBe(evening.getTime());
+ });
+ it('the key follows the instant drawn: it is the same across the midnight roll and changes at the noon side', () => {
+ const k = (iso: string) => momentKey(night, p, new Date(iso));
+ expect(k('2026-06-21T22:30:00Z')).toBe(k('2026-06-21T21:30:00Z')); // 00:30 and 23:30
+ expect(k('2026-06-21T22:30:00Z')).not.toBe(k('2026-06-22T12:00:00Z'));
+ expect(k('2026-06-22T12:00:00Z')).toBe(k('2026-06-22T20:00:00Z'));
+ });
+});
+
+describe('purity and bands', () => {
+ it('auto is the time it is given', () => {
+ const now = new Date('2026-05-05T05:05:05Z');
+ expect(momentFor({ kind: 'auto' }, PLACES.vienna, now)).toBe(now);
+ expect(momentKey({ kind: 'auto' }, PLACES.vienna, now)).toBe('live');
+ });
+
+ it('a free moment is the place-local wall time, held inside 1900..2100', () => {
+ const p = PLACES.vienna;
+ const t = momentFor({ kind: 'free', date: '2026-12-21', minutes: 400 }, p, new Date());
+ expect(localDate(t, p.tz)).toBe('2026-12-21');
+ expect(localMinutes(t, p.tz)).toBe(400);
+ expect(
+ localDate(momentFor({ kind: 'free', date: '1800-01-01', minutes: 0 }, p, new Date()), p.tz)
+ ).toBe('1900-01-01');
+ expect(
+ localDate(momentFor({ kind: 'free', date: '2999-05-05', minutes: 0 }, p, new Date()), p.tz)
+ ).toBe('2100-12-31');
+ });
+
+ it('skyBand: day at 6.0, night at -6.0, dusk between', () => {
+ expect(skyBand(DAY_FROM)).toBe('day');
+ expect(skyBand(-DAY_FROM)).toBe('night');
+ expect(skyBand(DAY_FROM - 0.001)).toBe('dusk');
+ expect(skyBand(-DAY_FROM + 0.001)).toBe('dusk');
+ expect(skyBand(0)).toBe('dusk');
+ expect(skyBand(80)).toBe('day');
+ expect(skyBand(-80)).toBe('night');
+ });
+
+ it('the key of a moment follows its local date and id, or its date and minutes', () => {
+ const p = PLACES.vienna;
+ const n = { kind: 'named', id: 'noon' } as const;
+ expect(momentKey(n, p, new Date('2026-06-21T10:00:00Z'))).toBe(
+ momentKey(n, p, new Date('2026-06-21T20:00:00Z'))
+ );
+ expect(momentKey(n, p, new Date('2026-06-21T10:00:00Z'))).not.toBe(
+ momentKey(n, p, new Date('2026-06-22T10:00:00Z'))
+ );
+ expect(momentKey({ kind: 'free', date: '2026-06-21', minutes: 5 }, p, new Date())).not.toBe(
+ momentKey({ kind: 'free', date: '2026-06-21', minutes: 10 }, p, new Date())
+ );
+ });
+});
+
+describe('the picker seed', () => {
+ it('opens from the moment Auto or a named choice is drawing, in the place zone, to the 5 minutes the slider steps', () => {
+ const p = PLACES.fuji;
+ const now = new Date('2026-12-21T04:03:00Z'); // 13:03 at Fuji
+ expect(seedFree({ kind: 'auto' }, p, now)).toEqual({
+ kind: 'free',
+ date: '2026-12-21',
+ minutes: 13 * 60,
+ });
+ const noon = seedFree({ kind: 'named', id: 'noon' }, p, now);
+ expect(noon.date).toBe('2026-12-21');
+ expect(Math.abs(noon.minutes - 11 * 60 - 45)).toBeLessThanOrEqual(15); // solar noon at 138.6 E is about 11:45 JST
+ expect(noon.minutes % 5).toBe(0);
+ const free = { kind: 'free', date: '2026-07-15', minutes: 330 } as const;
+ expect(seedFree(free, p, now)).toBe(free);
+ });
+});
diff --git a/src/app/features/scene/ridge/skyMoment.ts b/src/app/features/scene/ridge/skyMoment.ts
new file mode 100644
index 00000000..684fcc2c
--- /dev/null
+++ b/src/app/features/scene/ridge/skyMoment.ts
@@ -0,0 +1,286 @@
+// Which instant the sky is drawn at, and which band it is. One owner, pure (no store, no React, no clock):
+// `momentFor(choice, place, now)` turns the viewer's choice, the place and the time into the instant, and `skyBand` turns the sun
+// at that instant into the sky the ink and the tone map are fitted to. Place-local time exists only here, through Intl with `place.tz`;
+// the viewer's own zone decides nothing. The named moments are one table (`SKY_MOMENTS`), a row each, tuned by eye.
+import type { Place } from './view';
+import { sunAt } from './sunAt';
+
+/**
+ * The three skies ever drawn. Each has the luminance band its theme ink needs against bare sky (WCAG relative luminance,
+ * the `luminance` of src/sky/skyTokens.js): day, at least 0.2983 (the dark text ink #342d25); dusk, at least 0.4554 (the link
+ * #2a4f27); night, at most 0.0931 (the light text ink #aeccff). The ridge scene's display budgets (ridge/toneMap.ts `BUDGET`)
+ * sit inside them.
+ */
+export type FixedSkyState = 'day' | 'dusk' | 'night';
+
+/** Sun elevation (degrees) from which it is day, and below the negative of which it is night; between, dusk (dawn included). */
+export const DAY_FROM = 6;
+
+/** The one function that turns a sun into day, dusk or night. */
+export const skyBand = (elevationDeg: number): FixedSkyState =>
+ elevationDeg >= DAY_FROM ? 'day' : elevationDeg <= -DAY_FROM ? 'night' : 'dusk';
+
+export const MOMENT_IDS = ['dawn', 'morning', 'noon', 'golden', 'dusk', 'night'] as const;
+export type MomentId = typeof MOMENT_IDS[number];
+
+/** What the viewer picked: the live sky, a named moment of today at the place, or a place-local date and minute of the day. */
+export type SkyChoice =
+ | { kind: 'auto' }
+ | { kind: 'named'; id: MomentId }
+ | { kind: 'free'; date: string; minutes: number };
+
+/** The ephemeris range (sunAt.ts header): free dates are held inside it. */
+export const FREE_DATE_MIN = '1900-01-01';
+export const FREE_DATE_MAX = '2100-12-31';
+
+const MIN = 60_000;
+const DAY = 24 * 60 * MIN;
+
+// ---------------------------------------------------------------------------------------------------------------- place-local time
+
+const formats = new Map();
+const formatFor = (tz: string): Intl.DateTimeFormat => {
+ let f = formats.get(tz);
+ if (!f) {
+ f = new Intl.DateTimeFormat('en-US', {
+ timeZone: tz,
+ hourCycle: 'h23',
+ year: 'numeric',
+ month: '2-digit',
+ day: '2-digit',
+ hour: '2-digit',
+ minute: '2-digit',
+ second: '2-digit',
+ });
+ formats.set(tz, f);
+ }
+ return f;
+};
+
+/** The wall clock of `t` in `tz`, read as if it were UTC (ms): its difference from `t` is the zone's offset. */
+const wallAsUtc = (t: number, tz: string): number => {
+ const v: Record = {};
+ formatFor(tz)
+ .formatToParts(new Date(t))
+ .forEach((p) => {
+ if (p.type !== 'literal') v[p.type] = Number(p.value);
+ });
+ return Date.UTC(v.year, v.month - 1, v.day, v.hour, v.minute, v.second);
+};
+const offsetAt = (t: number, tz: string): number => wallAsUtc(t, tz) - Math.floor(t / 1000) * 1000;
+
+const pad = (n: number, w = 2): string => String(n).padStart(w, '0');
+const dateOf = (utcMs: number): string => {
+ const d = new Date(utcMs);
+ return `${pad(d.getUTCFullYear(), 4)}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())}`;
+};
+const DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
+const utcOfDate = (date: string): number => {
+ const m = DATE.exec(date);
+ if (!m) return NaN;
+ return Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]));
+};
+
+/** True for a real calendar date 'YYYY-MM-DD'. */
+export const isDate = (date: unknown): date is string =>
+ typeof date === 'string' && DATE.test(date) && dateOf(utcOfDate(date)) === date;
+
+/** The place-local calendar date of `now`, 'YYYY-MM-DD'. */
+export const localDate = (now: Date, tz: string): string => dateOf(wallAsUtc(now.getTime(), tz));
+
+/** The place-local minute of the day (0..1439) of `now`. */
+export const localMinutes = (now: Date, tz: string): number => {
+ const wall = new Date(wallAsUtc(now.getTime(), tz));
+ return wall.getUTCHours() * 60 + wall.getUTCMinutes();
+};
+
+/**
+ * The instant at which the wall clock of `tz` reads `date` and `minutes`. A wall time that does not exist (the spring-forward gap) is
+ * shifted forward by the gap, so it lands after it; one that happens twice (fall-back) resolves to the first.
+ */
+export function zonedInstant(date: string, minutes: number, tz: string): Date {
+ const guess = utcOfDate(date) + minutes * MIN;
+ const before = offsetAt(guess - DAY, tz);
+ const after = offsetAt(guess + DAY, tz);
+ const valid = [...new Set([before, after])]
+ .map((o) => guess - o)
+ .filter((t) => offsetAt(t, tz) === guess - t)
+ .sort((a, b) => a - b);
+ return new Date(valid.length ? valid[0] : guess - before);
+}
+
+/** The short name of the zone at that instant ('CET', 'GMT+5:45'): what the picker shows beside a place-local time. */
+export const zoneName = (at: Date, tz: string): string =>
+ new Intl.DateTimeFormat('en-US', { timeZone: tz, timeZoneName: 'short' })
+ .formatToParts(at)
+ .find((p) => p.type === 'timeZoneName')?.value ?? tz;
+
+// ---------------------------------------------------------------------------------------------------------------- the named moments
+
+const elevationAt = (place: Place, t: number): number => sunAt(place, new Date(t)).elevation;
+const STEP = 5 * MIN;
+
+/** The time in [a, b] (ms) where `f` is largest (sign 1) or smallest (sign -1), to under a minute: the function is unimodal there. */
+function extremum(f: (t: number) => number, a: number, b: number, sign: 1 | -1): number {
+ let lo = a;
+ let hi = b;
+ while (hi - lo > MIN / 2) {
+ const m1 = lo + (hi - lo) / 3;
+ const m2 = hi - (hi - lo) / 3;
+ if (sign * f(m1) < sign * f(m2)) lo = m1;
+ else hi = m2;
+ }
+ return (lo + hi) / 2;
+}
+
+/** The time in [from, to] where `f` is largest (sign 1) or smallest (sign -1): a scan in 5-minute steps, refined to under a minute. */
+function peak(f: (t: number) => number, from: number, to: number, sign: 1 | -1): number {
+ let best = from;
+ let bestV = -Infinity;
+ for (let t = from; t <= to; t += STEP) {
+ const v = sign * f(t);
+ if (v > bestV) {
+ bestV = v;
+ best = t;
+ }
+ }
+ return extremum(f, Math.max(from, best - STEP), Math.min(to, best + STEP), sign);
+}
+
+/** The first rising (or last setting) crossing of `deg` in [from, to]: a 5-minute scan, bisected under a second; undefined when there is none. */
+function crossing(
+ f: (t: number) => number,
+ deg: number,
+ from: number,
+ to: number,
+ rising: boolean
+): number | undefined {
+ const above = (t: number) => f(t) >= deg;
+ let found: [number, number] | undefined;
+ for (let a = from; a < to; a += STEP) {
+ const b = Math.min(a + STEP, to);
+ if (above(a) !== above(b) && above(b) === rising) {
+ found = [a, b];
+ if (rising) break;
+ }
+ }
+ if (!found) return undefined;
+ let [lo, hi] = found;
+ while (hi - lo > 500) {
+ const m = (lo + hi) / 2;
+ if (above(m) === rising) hi = m;
+ else lo = m;
+ }
+ return (lo + hi) / 2;
+}
+
+/** The place-local day a named moment is a moment of: its start and end, and the sun's noon in between. */
+interface Day {
+ place: Place;
+ from: number;
+ to: number;
+ noon: number;
+ noonElevation: number;
+}
+
+interface Rule {
+ /** 'noon' and 'midnight' are the extremes; 'rising' and 'setting' are the crossing of `deg` (a function of the day's noon elevation) before and after noon. */
+ at: 'noon' | 'midnight' | 'rising' | 'setting';
+ deg?: (noonElevation: number) => number;
+}
+
+/**
+ * The named moments, one row each (tuned by eye, ruling ridge-look-tuned-by-eye-no-contrast-gates). A crossing the day does not have
+ * (polar) falls to the day's noon (rising) or midnight (setting). Night is solar midnight, tonight's: before the day's noon the one that
+ * just passed or is coming this morning, after it the one that is coming (`momentOf`'s `before`), never one a whole day away.
+ */
+export const SKY_MOMENTS: Record = {
+ dawn: { at: 'rising', deg: () => -3 },
+ morning: { at: 'rising', deg: (noon) => Math.min(15, noon / 2) },
+ noon: { at: 'noon' },
+ golden: { at: 'setting', deg: () => 4 },
+ dusk: { at: 'setting', deg: () => -3 },
+ night: { at: 'midnight' },
+};
+
+function momentOf(id: MomentId, d: Day, before: boolean): number {
+ const rule = SKY_MOMENTS[id];
+ const f = (t: number) => elevationAt(d.place, t);
+ const midnight = () => peak(f, d.noon, d.noon + DAY, -1);
+ if (rule.at === 'noon') return d.noon;
+ if (rule.at === 'midnight') return before ? peak(f, d.noon - DAY, d.noon, -1) : midnight();
+ const deg = rule.deg ? rule.deg(d.noonElevation) : 0;
+ if (rule.at === 'rising') return crossing(f, deg, d.from, d.noon, true) ?? d.noon;
+ return crossing(f, deg, d.noon, d.to, false) ?? midnight();
+}
+
+const days = new Map();
+const named = new Map();
+/** The place-local day `date` at the place (memoised: a pure function of these). */
+function dayOf(place: Place, date: string): Day {
+ const key = `${date}|${place.tz}|${place.lat}|${place.lon}`;
+ let d = days.get(key);
+ if (!d) {
+ const from = zonedInstant(date, 0, place.tz).getTime();
+ const to = zonedInstant(dateOf(utcOfDate(date) + DAY), 0, place.tz).getTime();
+ const noon = peak((x) => elevationAt(place, x), from, to, 1);
+ d = { place, from, to, noon, noonElevation: elevationAt(place, noon) };
+ if (days.size > 256) days.clear();
+ days.set(key, d);
+ }
+ return d;
+}
+
+/** The instant of a named moment on a place-local date at the place (memoised). Only Night looks at `now`: which side of the day's noon it is. */
+function namedInstant(id: MomentId, place: Place, date: string, now: Date): Date {
+ const d = dayOf(place, date);
+ const before = now.getTime() < d.noon;
+ const key = `${id}|${date}|${before}|${place.tz}|${place.lat}|${place.lon}`;
+ let t = named.get(key);
+ if (t === undefined) {
+ t = momentOf(id, d, before);
+ if (named.size > 256) named.clear();
+ named.set(key, t);
+ }
+ return new Date(t);
+}
+
+// ---------------------------------------------------------------------------------------------------------------- the one decision
+
+/** A free date held inside the ephemeris range; anything that is not a date reads as the range's start. */
+const clampDate = (date: string): string =>
+ !isDate(date) || date < FREE_DATE_MIN
+ ? FREE_DATE_MIN
+ : date > FREE_DATE_MAX
+ ? FREE_DATE_MAX
+ : date;
+const clampMinutes = (m: number): number => Math.min(1439, Math.max(0, Math.floor(m) || 0));
+
+/** The instant the sky is drawn at for a choice at a place: auto is `now`; a named moment is today's at the place (Night: tonight's, the nearest one); a free moment is its own. */
+export function momentFor(choice: SkyChoice, place: Place, now: Date): Date {
+ if (choice.kind === 'auto') return now;
+ if (choice.kind === 'named') return namedInstant(choice.id, place, localDate(now, place.tz), now);
+ return zonedInstant(clampDate(choice.date), clampMinutes(choice.minutes), place.tz);
+}
+
+/** The free moment (place-local date, minute to the 5 the slider steps) a choice is drawing now: where the picker opens from. */
+export function seedFree(
+ choice: SkyChoice,
+ place: Place,
+ now: Date
+): Extract {
+ if (choice.kind === 'free') return choice;
+ const at = momentFor(choice, place, now);
+ return {
+ kind: 'free',
+ date: localDate(at, place.tz),
+ minutes: Math.floor(localMinutes(at, place.tz) / 5) * 5,
+ };
+}
+
+/** What a rebuild is for, of the moment: live for auto, the id and place-local date of the instant for a named one, the date and minutes for a free one. */
+export function momentKey(choice: SkyChoice, place: Place, now: Date): string {
+ if (choice.kind === 'auto') return 'live';
+ if (choice.kind === 'named') return `${choice.id}@${localDate(momentFor(choice, place, now), place.tz)}`;
+ return `${clampDate(choice.date)}@${clampMinutes(choice.minutes)}`;
+}
diff --git a/src/app/features/scene/ridge/skyTestkit.ts b/src/app/features/scene/ridge/skyTestkit.ts
new file mode 100644
index 00000000..e66a0731
--- /dev/null
+++ b/src/app/features/scene/ridge/skyTestkit.ts
@@ -0,0 +1,28 @@
+// Test helpers for the sky: a moment named by the clock of the place, and the sun of a band. Tests only.
+import { momentFor } from './skyMoment';
+import type { FixedSkyState } from './skyMoment';
+import { sunAt } from './sunAt';
+import type { SunSample } from './sunAt';
+import { FALLBACK_VIEW } from './view';
+import type { Place } from './view';
+
+const VIENNA = FALLBACK_VIEW.place;
+
+/** 22 September 2026 at h:m of local solar time at Vienna (the equinox: the sun is up from about 06:00 to 18:00 and the equation of time is a few minutes). */
+export const atSolarTime = (h: number, m = 0): Date =>
+ new Date(Date.UTC(2026, 8, 22, h, m) - VIENNA.lon * 4 * 60_000);
+
+/** The sun of a band on the local day of `date` at `place`: Day is noon, Dusk the evening's -3 degrees, Night solar midnight. */
+export const sunOfBand = (
+ place: Place,
+ band: FixedSkyState,
+ date: Date,
+): SunSample =>
+ sunAt(
+ place,
+ momentFor(
+ { kind: 'named', id: band === 'day' ? 'noon' : band },
+ place,
+ date
+ )
+ );
diff --git a/src/app/features/scene/ridge/skyTurn.test.ts b/src/app/features/scene/ridge/skyTurn.test.ts
new file mode 100644
index 00000000..bd6e4bec
--- /dev/null
+++ b/src/app/features/scene/ridge/skyTurn.test.ts
@@ -0,0 +1,130 @@
+import { describe, expect, it } from 'vitest';
+import {
+ alignTurns,
+ LATENESS_S,
+ marginFor,
+ MIN_TRAVEL_DEG,
+ panPx,
+ plateCamera,
+ plateSize,
+ PLATE_MAX_PX,
+ recentre,
+ SLACK_MIN_DEG,
+ slackFor,
+ TRAVEL_DEG,
+} from './skyTurn';
+import { FALLBACK_VIEW, SPEED_CEILING_DEG_S, windowFor } from './view';
+import { RESIDENCY_MS } from './Ridge';
+
+const win = windowFor(FALLBACK_VIEW, 1280, 720);
+
+describe('plateCamera', () => {
+ it('spans the viewport plus the slack each side about its centre, at the viewport angles per pixel', () => {
+ const cam = plateCamera(win, 100, SLACK_MIN_DEG);
+ expect(cam.azimuthDeg).toBe(100);
+ expect(cam.hfovDeg).toBeCloseTo(win.camera.hfovDeg + 2 * SLACK_MIN_DEG, 12);
+ expect(cam.vfovDeg).toBe(win.camera.vfovDeg);
+ expect(cam.horizonAt).toBe(win.camera.horizonAt);
+ // a plate is `plateSize` wide and shows the same degrees per pixel as the viewport
+ const { cssW } = plateSize(win, 1280, 720, 1, SLACK_MIN_DEG);
+ expect(cssW / cam.hfovDeg).toBeCloseTo(1280 / win.camera.hfovDeg, 9);
+ });
+
+ it('names its centre within one turn, whatever turn the heading owner is on', () => {
+ expect(plateCamera(win, 750, SLACK_MIN_DEG).azimuthDeg).toBe(30);
+ expect(plateCamera(win, -10, SLACK_MIN_DEG).azimuthDeg).toBe(350);
+ expect(plateCamera(win, 214, 0).hfovDeg).toBe(win.camera.hfovDeg); // no slack: the viewport's own camera, as a still paints
+ });
+});
+
+describe('recentre', () => {
+ const still = (heading: number, centre: number, slack = SLACK_MIN_DEG) => recentre(heading, centre, slack, 0, RESIDENCY_MS);
+
+ it('fires at the slack for a heading that does not turn, and not for one that stays', () => {
+ expect(still(100, 100)).toBe(false);
+ expect(still(119.9, 100)).toBe(false);
+ expect(still(120.1, 100)).toBe(true);
+ expect(still(80.1, 100)).toBe(false);
+ expect(still(79.9, 100)).toBe(true);
+ });
+
+ it('takes the margin from the speed in force and the tick: a faster turn is replaced sooner, a slower tick sooner too', () => {
+ const slack = slackFor(4, RESIDENCY_MS); // 4 degrees a second: margin 10 in 2.5 s
+ expect(marginFor(4, RESIDENCY_MS)).toBeCloseTo(4 * (LATENESS_S + 0.5), 12);
+ expect(recentre(100 + slack - 10.1, 100, slack, 4, RESIDENCY_MS)).toBe(false);
+ expect(recentre(100 + slack - 9.9, 100, slack, 4, RESIDENCY_MS)).toBe(true);
+ expect(recentre(100 + slack - 10.1, 100, slack, 4, 1500)).toBe(true); // a tick that really took 1.5 s: margin 14
+ expect(recentre(100 + slack - 10.1, 100, slack, 0, RESIDENCY_MS)).toBe(false);
+ });
+
+ it('never takes the whole slack: a plate just painted is not due again whatever the tick', () => {
+ expect(recentre(100, 100, SLACK_MIN_DEG, 12, 60_000)).toBe(false);
+ expect(recentre(100 + MIN_TRAVEL_DEG - 0.1, 100, SLACK_MIN_DEG, 12, 60_000)).toBe(false);
+ expect(recentre(100 + MIN_TRAVEL_DEG + 0.1, 100, SLACK_MIN_DEG, 12, 60_000)).toBe(true);
+ });
+
+ it('reads the heading on the turn of the centre', () => {
+ expect(still(10 + 360, 10)).toBe(false);
+ expect(still(350, 5, 14)).toBe(true); // 15 degrees off, the short way
+ expect(still(358, 5)).toBe(false);
+ expect(alignTurns(10, 725)).toBe(730);
+ expect(alignTurns(370, 5)).toBe(10);
+ });
+});
+
+describe('the slack at the speed in force', () => {
+ const speeds = [0, 0.6, 4, 6, SPEED_CEILING_DEG_S];
+
+ it('holds the margin and the travel between replacements, at every speed, and is the floor when the view barely turns', () => {
+ for (const v of speeds) {
+ const slack = slackFor(v, RESIDENCY_MS);
+ expect(slack).toBeGreaterThanOrEqual(SLACK_MIN_DEG);
+ expect(slack).toBeGreaterThanOrEqual(marginFor(v, RESIDENCY_MS) + TRAVEL_DEG);
+ }
+ expect(slackFor(0, RESIDENCY_MS)).toBe(SLACK_MIN_DEG);
+ expect(slackFor(SPEED_CEILING_DEG_S, RESIDENCY_MS)).toBe(TRAVEL_DEG + SPEED_CEILING_DEG_S * (LATENESS_S + RESIDENCY_MS / 1000));
+ });
+
+ it('is never run out between two ticks, in the worst phase, with a late tick, at every speed: a tick that finds the plate whole is followed by one that does too', () => {
+ for (const v of speeds) {
+ for (const periodMs of [RESIDENCY_MS, 700]) {
+ const slack = slackFor(v, RESIDENCY_MS);
+ // The farthest from its centre a heading can be at a tick that leaves the plate alone, found by walking out from the centre.
+ let edge = 0;
+ while (!recentre(100 + edge + 0.001, 100, slack, v, periodMs)) edge += 0.001;
+ // The next tick comes a period later and as late as the budget lets it be.
+ const worst = edge + v * (periodMs / 1000 + LATENESS_S);
+ expect(worst).toBeLessThanOrEqual(slack + 1e-6);
+ }
+ }
+ });
+});
+
+describe('plateSize', () => {
+ it('never has more backing store than PLATE_MAX_PX: the pixel ratio lowers, the plate does not shrink', () => {
+ [
+ [1280, 720, 2],
+ [1920, 1080, 2],
+ [3840, 2160, 1],
+ [390, 844, 3],
+ [800, 600, 1],
+ ].forEach(([w, h, dpr]) => {
+ const wn = windowFor(FALLBACK_VIEW, w, h);
+ const p = plateSize(wn, w, h, dpr, SLACK_MIN_DEG);
+ expect(Math.floor(p.cssW * p.ratio) * Math.floor(h * p.ratio)).toBeLessThanOrEqual(PLATE_MAX_PX);
+ expect(p.ratio).toBeLessThanOrEqual(dpr);
+ expect(p.cssW).toBeCloseTo((w * (wn.camera.hfovDeg + 2 * SLACK_MIN_DEG)) / wn.camera.hfovDeg, 9);
+ });
+ // a small viewport keeps the whole device ratio, a phone-sized one at 2x loses a little of it
+ expect(plateSize(windowFor(FALLBACK_VIEW, 300, 500), 300, 500, 2, SLACK_MIN_DEG).ratio).toBe(2);
+ });
+});
+
+describe('panPx', () => {
+ it('slides the plate one for one with the heading, opposite to it', () => {
+ const ppd = 1280 / win.camera.hfovDeg;
+ expect(panPx(214, 214, ppd)).toBeCloseTo(0, 12);
+ expect(panPx(224, 214, ppd)).toBeCloseTo(-10 * ppd, 9);
+ expect(panPx(204, 214, ppd)).toBeCloseTo(10 * ppd, 9);
+ });
+});
diff --git a/src/app/features/scene/ridge/skyTurn.ts b/src/app/features/scene/ridge/skyTurn.ts
new file mode 100644
index 00000000..15654778
--- /dev/null
+++ b/src/app/features/scene/ridge/skyTurn.ts
@@ -0,0 +1,66 @@
+// The sky that turns with the view. The sky is at infinity: it pans one for one with the view direction and ignores the camera's offset (`view.ts`
+// `cardPose` is where the near cards differ). So the live scene paints it once into a PLATE, a canvas wider than the viewport by its slack each side,
+// centred on a heading, and the compositor slides the plate by `(heading - centre)` degrees of pixels on the same keyframes as the cards (`heading.ts`
+// `poseAt`). The slack, sized to the speed of the turn (`slackFor`), lets the heading wander before the plate runs out; the scene paints a new plate about the heading it has reached, in the same
+// tick it takes the old one away. Both plates are the same sky, so nothing moves. This file owns which arc of sky a plate holds and when it is replaced.
+import { norm } from './ring';
+import type { Camera, Window } from './view';
+
+/** The least sky painted beyond the viewport on each side of it, degrees: what a slow turn gets. Authored. */
+export const SLACK_MIN_DEG = 20;
+/** Degrees the heading may wander from a fresh plate's centre before it is due a new one, however fast it turns: a plate is not repainted more often than this. Authored. */
+export const TRAVEL_DEG = 14;
+/**
+ * How late a residency tick may run, seconds, beyond its own period, before the plate can run out: a tile mount, a paint, a collection or a busy phone each cost
+ * a tick a few hundred milliseconds; this is a budget for several of them. Authored.
+ */
+export const LATENESS_S = 2;
+/** The margin never takes more than this much of the slack, degrees, so a plate that has just been painted is not due again at once. */
+export const MIN_TRAVEL_DEG = 1;
+/** The most backing store a plate may have, pixels: the pixel ratio lowers before the plate shrinks. */
+export const PLATE_MAX_PX = 3_000_000;
+
+/**
+ * Degrees a heading turning at `rateDegPerS` covers between a residency tick that finds the plate good and the next one: a tick's period (`periodMs`, the real
+ * one, work included) and the lateness budget. A plate is replaced once the heading is nearer its edge than this, so the next tick, however late, finds it whole.
+ */
+export const marginFor = (rateDegPerS: number, periodMs: number): number => Math.abs(rateDegPerS) * (LATENESS_S + periodMs / 1000);
+
+/** The slack a plate needs at `rateDegPerS`, the speed in force (`heading.ts` `turnRate`): its margin at the nominal tick `tickMs` and the travel between replacements. */
+export const slackFor = (rateDegPerS: number, tickMs: number): number =>
+ Math.max(SLACK_MIN_DEG, TRAVEL_DEG + marginFor(rateDegPerS, tickMs));
+
+/** The camera of a plate: the viewport's, with `slackDeg` more field each side, centred on the compass azimuth `centreDeg` (any turn of it). Angles per pixel are the viewport's. */
+export function plateCamera(win: Window, centreDeg: number, slackDeg: number): Camera {
+ return { ...win.camera, azimuthDeg: norm(centreDeg), hfovDeg: win.camera.hfovDeg + 2 * slackDeg };
+}
+
+/** The plate for a viewport `w` x `h` CSS px at `dpr` device pixels per CSS px with `slackDeg` of slack: its CSS width (the viewport's px per degree is the plate's), and the pixel ratio of its backing store. */
+export function plateSize(
+ win: Window,
+ w: number,
+ h: number,
+ dpr: number,
+ slackDeg: number
+): { cssW: number; ratio: number; pxPerDeg: number } {
+ const pxPerDeg = w / win.camera.hfovDeg;
+ const cssW = pxPerDeg * (win.camera.hfovDeg + 2 * slackDeg);
+ const ratio = Math.min(dpr, Math.sqrt(PLATE_MAX_PX / (cssW * h)));
+ return { cssW, ratio, pxPerDeg };
+}
+
+/** `centreDeg` shifted by whole turns to the one nearest `headingDeg` (the heading owner keeps its angles within a turn of zero, so the plate's centre follows). */
+export const alignTurns = (centreDeg: number, headingDeg: number): number =>
+ centreDeg + 360 * Math.round((headingDeg - centreDeg) / 360);
+
+/**
+ * Whether a plate with `slackDeg` of slack centred on `centreDeg` should be replaced now: the heading is nearer its edge than the margin, which the speed in
+ * force and the tick's real period set (`marginFor`) and which never takes more than the slack less MIN_TRAVEL_DEG. A still heading never is.
+ */
+export function recentre(headingDeg: number, centreDeg: number, slackDeg: number, rateDegPerS: number, periodMs: number): boolean {
+ const margin = Math.min(marginFor(rateDegPerS, periodMs), slackDeg - MIN_TRAVEL_DEG);
+ return Math.abs(headingDeg - alignTurns(centreDeg, headingDeg)) > slackDeg - margin;
+}
+
+/** How far the plate is slid, px, when the view faces `headingDeg` and the plate is centred on `centreDeg` (both in the same turn, `alignTurns`): negative once the view has turned clockwise. */
+export const panPx = (headingDeg: number, centreDeg: number, pxPerDeg: number): number => -(headingDeg - centreDeg) * pxPerDeg;
diff --git a/src/app/features/scene/ridge/stars.test.ts b/src/app/features/scene/ridge/stars.test.ts
index f036a7ee..87a1244f 100644
--- a/src/app/features/scene/ridge/stars.test.ts
+++ b/src/app/features/scene/ridge/stars.test.ts
@@ -6,6 +6,7 @@ import {
TWINKLE_PERIOD,
activeAt,
slotCount,
+ slotsFor,
slotOffset,
slotPeriod,
twinkleGain,
@@ -18,6 +19,28 @@ function hash2(a: number, b: number) {
return ((a * 7919 + b * 104729) % 1000) / 1000;
}
+describe('the schedule over a universe of which a plate shows a share', () => {
+ const U = 2887;
+ const shown = 90; // stars on the plate: the first of the universe's, as any plate's are some of them
+
+ it('twinkles SLOTS of the shown stars on average, and is the same schedule whichever plate asks', () => {
+ const slots = slotsFor(U, shown);
+ let on = 0;
+ const ts = Array.from({ length: 300 }, (_, i) => i * 0.53);
+ for (const t of ts) on += activeAt(U, t, slots).filter((a) => a.star < shown).length;
+ expect(on / ts.length).toBeGreaterThan(SLOTS * 0.7);
+ expect(on / ts.length).toBeLessThan(SLOTS * 1.3);
+ // a star's twinkle is keyed by its identity: asked again, by another plate, the same star has the same phase and gain
+ expect(activeAt(U, 41.3, slots)).toEqual(activeAt(U, 41.3, slots));
+ });
+
+ it('never has more slots than half the universe, nor fewer than one', () => {
+ expect(slotsFor(U, 1)).toBe(Math.floor(U / 2));
+ expect(slotsFor(U, 0)).toBe(Math.floor(U / 2));
+ expect(slotsFor(2, 5)).toBe(1);
+ });
+});
+
describe('twinkle schedule', () => {
const times = Array.from({ length: 400 }, (_, i) => i * 0.37);
diff --git a/src/app/features/scene/ridge/stars.ts b/src/app/features/scene/ridge/stars.ts
index cbdc9a7a..d91a6f6c 100644
--- a/src/app/features/scene/ridge/stars.ts
+++ b/src/app/features/scene/ridge/stars.ts
@@ -14,6 +14,8 @@ export const TWINKLE_GAIN = { dim: 0.35, bright: 1.15 } as const;
const SEED = 0x57a45eed;
export interface Star {
+ /** The star's index in the catalogue (`starCatalogue.ts`): the identity the twinkle schedule is keyed by, the same on every plate of a sky. */
+ id: number;
/** Position as fractions of the sky canvas width and height. */
x: number;
y: number;
@@ -39,6 +41,13 @@ export function hash(a: number, b = 0, c = 0): number {
// ---- The schedule ---------------------------------------------------------------------------
export const slotCount = (stars: number): number => Math.min(SLOTS, stars);
+/**
+ * The slots for a schedule over `universe` stars of which `shown` are on the plate that is up: enough that SLOTS of the ones shown twinkle at any instant on
+ * average, though the schedule runs over the whole universe (the catalogue), so that the same stars twinkle whichever plate shows them. Never more than half
+ * the universe, so each slot has a star to turn to.
+ */
+export const slotsFor = (universe: number, shown: number): number =>
+ Math.max(1, Math.min(Math.floor(universe / 2), Math.round((SLOTS * universe) / Math.max(1, shown)), universe));
/** A slot's twinkle period in seconds: its own, in TWINKLE_PERIOD. */
export const slotPeriod = (j: number): number =>
TWINKLE_PERIOD.min + (TWINKLE_PERIOD.max - TWINKLE_PERIOD.min) * hash(j, 1);
@@ -89,9 +98,8 @@ export interface Twinkling {
gain: number;
}
-/** The active set at time `t` seconds for a field of `stars` stars, in slot order. */
-export function activeAt(stars: number, t: number): Twinkling[] {
- const slots = slotCount(stars);
+/** The active set at time `t` seconds for a universe of `stars` stars, in slot order, in `slots` slots (`slotCount` of them, or `slotsFor`). `star` is an index into the universe. */
+export function activeAt(stars: number, t: number, slots: number = slotCount(stars)): Twinkling[] {
return Array.from({ length: slots }, (_, j) => {
const period = slotPeriod(j);
const off = slotOffset(j);
@@ -115,12 +123,12 @@ export function activeAt(stars: number, t: number): Twinkling[] {
// ---- Drawing --------------------------------------------------------------------------------
/**
- * The overlay pass: clear, then for each active star whose gain is off base, cover the baked star with the sky behind it and draw it again
+ * The overlay pass over the plate's stars by identity: clear, then for each active star on this plate whose gain is off base, cover the baked star with the sky behind it and draw it again
* at the gain. A star at base draws nothing.
*/
export function drawTwinkle(
ctx: CanvasRenderingContext2D,
- stars: readonly Star[],
+ stars: ReadonlyMap,
active: readonly Twinkling[],
w: number,
h: number,
@@ -128,7 +136,7 @@ export function drawTwinkle(
) {
ctx.clearRect(0, 0, w, h);
active.forEach((a) => {
- const s = stars[a.star];
+ const s = stars.get(a.star);
if (!s || Math.abs(a.gain - 1) < 0.01) return;
ctx.fillStyle = s.cover;
ctx.beginPath();
diff --git a/src/app/features/scene/ridge/sunAt.test.ts b/src/app/features/scene/ridge/sunAt.test.ts
index f9d2e586..ed66552f 100644
--- a/src/app/features/scene/ridge/sunAt.test.ts
+++ b/src/app/features/scene/ridge/sunAt.test.ts
@@ -1,10 +1,13 @@
import { describe, expect, it } from 'vitest';
-import { solarNoon, STATE_ELEVATION, sunAt, sunForState } from './sunAt';
+import { sunAt } from './sunAt';
+import { momentFor } from './skyMoment';
import { FALLBACK_VIEW } from './view';
const P = FALLBACK_VIEW.place;
const at = (iso: string) => new Date(iso);
+/** The sun's noon of the local day of `t` (the named moment of the sky menu). */
+const noonOf = (p: typeof P, t: Date) => momentFor({ kind: 'named', id: 'noon' }, p, t);
describe('the sun over Vienna', () => {
it('the Vienna place reproduces the sun the old Vienna constant gave, exactly, at three dates', () => {
@@ -22,24 +25,24 @@ describe('the sun over Vienna', () => {
});
it('stands at 90 - lat + declination at solar noon: the solstices and equinox', () => {
- const june = sunAt(P, solarNoon(P, at('2026-06-21T12:00:00Z')));
+ const june = sunAt(P, noonOf(P, at('2026-06-21T12:00:00Z')));
expect(june.elevation).toBeCloseTo(90 - P.lat + 23.44, 0);
- const december = sunAt(P, solarNoon(P, at('2026-12-21T12:00:00Z')));
+ const december = sunAt(P, noonOf(P, at('2026-12-21T12:00:00Z')));
expect(december.elevation).toBeCloseTo(90 - P.lat - 23.44, 0);
- const march = sunAt(P, solarNoon(P, at('2026-03-20T12:00:00Z')));
+ const march = sunAt(P, noonOf(P, at('2026-03-20T12:00:00Z')));
expect(march.elevation).toBeCloseTo(90 - P.lat, 0);
});
it('is due south at solar noon, east in the morning and west in the afternoon', () => {
- const noon = solarNoon(P, at('2026-09-23T12:00:00Z'));
- expect(Math.abs(sunAt(P, noon).azimuth - 180)).toBeLessThan(2); // solarNoon is found to 5 minutes, which is 1.25 degrees of azimuth
+ const noon = noonOf(P, at('2026-09-23T12:00:00Z'));
+ expect(Math.abs(sunAt(P, noon).azimuth - 180)).toBeLessThan(2); // noonOf is found to under a minute
expect(sunAt(P, new Date(noon.getTime() - 3 * 3600_000)).azimuth).toBeLessThan(150);
expect(sunAt(P, new Date(noon.getTime() + 3 * 3600_000)).azimuth).toBeGreaterThan(210);
});
it('solar noon at 16.35 E falls near 10:40 UTC in mid November', () => {
// 16.3534 E is 65.4 minutes ahead of Greenwich; the equation of time in mid November is +15 minutes (sun early): 12:00 - 65.5 - 15 = 10:40 UTC.
- const n = solarNoon(P, at('2026-11-11T12:00:00Z'));
+ const n = noonOf(P, at('2026-11-11T12:00:00Z'));
const minutes = n.getUTCHours() * 60 + n.getUTCMinutes();
expect(minutes).toBeGreaterThan(10 * 60 + 30);
expect(minutes).toBeLessThan(10 * 60 + 50);
@@ -55,20 +58,4 @@ describe('the sun over Vienna', () => {
expect(Math.abs(daylight('2026-12-21T00:00:00Z') - (8 * 60 + 4))).toBeLessThan(15);
expect(Math.abs(daylight('2026-06-21T00:00:00Z') - (16 * 60 + 0))).toBeLessThan(15);
});
-
- it('sunForState: the real sun when it is in the state, else a moment of today that is', () => {
- const noon = solarNoon(P, at('2026-11-11T12:00:00Z'));
- expect(sunForState(P, 'day', noon).time).toEqual(noon);
- const midnight = new Date(noon.getTime() + 12 * 3600_000);
- for (const state of ['day', 'dusk', 'night'] as const) {
- for (const now of [noon, midnight, at('2026-11-11T15:30:00Z')]) {
- const s = sunForState(P, state, now);
- const [lo, hi] = STATE_ELEVATION[state];
- expect(s.elevation).toBeGreaterThanOrEqual(lo - 0.01);
- expect(s.elevation).toBeLessThanOrEqual(hi + 0.01);
- }
- }
- expect(sunForState(P, 'dusk', noon).elevation).toBeCloseTo(0, 1);
- expect(sunForState(P, 'dusk', noon).azimuth).toBeGreaterThan(180); // sets in the west half
- });
});
diff --git a/src/app/features/scene/ridge/sunAt.ts b/src/app/features/scene/ridge/sunAt.ts
index 72a274f1..6e688285 100644
--- a/src/app/features/scene/ridge/sunAt.ts
+++ b/src/app/features/scene/ridge/sunAt.ts
@@ -1,9 +1,6 @@
// The sun over a Place (`view.ts`) at a real moment: one ephemeris, `sunPosition` of src/sky/sun.js (the
-// low-precision NOAA/Meeus series, a hundredth of a degree for 1900..2100; no refraction), and the choice of a moment for each
-// fixed sky state. The ridge sky is the physical atmosphere (`earthAtmosphere.ts`) lit from this sun.
+// low-precision NOAA/Meeus series, a hundredth of a degree for 1900..2100; no refraction). The moment a sky is drawn at is skyMoment.ts's. The ridge sky is the physical atmosphere (`earthAtmosphere.ts`) lit from this sun.
import { sunPosition } from '../../../../sky/sun.js';
-import { DAY_FROM } from '../skyState';
-import type { FixedSkyState } from '../skyState';
import type { Place } from './view';
export interface SunSample {
@@ -22,53 +19,3 @@ export function sunAt(place: Place, time: Date): SunSample {
};
return { elevation, azimuth, time };
}
-
-const MIN = 60_000;
-
-/** Sun elevation range of each fixed state: the thresholds `resolveSkyState` uses (day from DAY_FROM, night below -DAY_FROM). */
-export const STATE_ELEVATION: Record = {
- day: [DAY_FROM, 90],
- dusk: [-DAY_FROM, DAY_FROM],
- night: [-90, -DAY_FROM],
-};
-
-const startOfUtcDay = (t: Date): number =>
- Math.floor(t.getTime() / (24 * 60 * MIN)) * 24 * 60 * MIN;
-
-/** The moment of the day (UTC day of `t`, every 5 minutes) the sun is highest over the place: solar noon to the step. */
-export function solarNoon(place: Place, t: Date): Date {
- const d0 = startOfUtcDay(t);
- let best = d0;
- let bestEl = -90;
- for (let m = 0; m < 24 * 60; m += 5) {
- const el = sunAt(place, new Date(d0 + m * MIN)).elevation;
- if (el > bestEl) {
- bestEl = el;
- best = d0 + m * MIN;
- }
- }
- return new Date(best);
-}
-
-/**
- * The sun a state draws. The real sun over the place now when it is in the state's range (so 'auto' is the real sky); otherwise the
- * sun of today at a moment that is: noon for Day, the evening sunset for Dusk, the opposite of noon for Night. A picker that
- * forces Day at night shows a noon sky, as a person looking at a noon photograph would.
- */
-export function sunForState(place: Place, state: FixedSkyState, now: Date): SunSample {
- const real = sunAt(place, now);
- const [lo, hi] = STATE_ELEVATION[state];
- if (real.elevation >= lo && real.elevation <= hi) return real;
- const noon = solarNoon(place, now);
- if (state === 'day') return sunAt(place, noon);
- if (state === 'night') return sunAt(place, new Date(noon.getTime() + 12 * 60 * MIN));
- // Dusk: bisect the evening crossing of the horizon between noon and the opposite moment.
- let a = noon.getTime();
- let b = noon.getTime() + 12 * 60 * MIN;
- for (let i = 0; i < 30; i += 1) {
- const m = (a + b) / 2;
- if (sunAt(place, new Date(m)).elevation > 0) a = m;
- else b = m;
- }
- return sunAt(place, new Date((a + b) / 2));
-}
diff --git a/src/app/features/scene/ridge/toneMap.test.ts b/src/app/features/scene/ridge/toneMap.test.ts
index d27cc979..5c19912b 100644
--- a/src/app/features/scene/ridge/toneMap.test.ts
+++ b/src/app/features/scene/ridge/toneMap.test.ts
@@ -1,11 +1,12 @@
import { describe, expect, it } from 'vitest';
import { FALLBACK_VIEW } from './view';
import { makePhysicalSky } from './physicalSky';
+import { sunOfBand } from './skyTestkit';
import { renderDome } from './skyDome';
import { windowFor } from './view';
import { applyCurve, BLACK_LIFT, BUDGET, NIGHT_CEILING, NIGHT_LIFT, SCOTOPIC, displayLumaOf, fitDisplay, makeCurve, scotopic, scotopicWeight } from './toneMap';
import { sunAt } from './sunAt';
-import type { FixedSkyState } from '../skyState';
+import type { FixedSkyState } from './skyMoment';
const sweep = (c: ReturnType) =>
Array.from({ length: 401 }, (_, i) => applyCurve(c, i / 400));
@@ -28,7 +29,7 @@ describe('the tone curve', () => {
});
describe.each(['day', 'dusk', 'night'] as FixedSkyState[])('the %s curve fitted to a sky', (state) => {
- const sky = makePhysicalSky(state, new Date('2026-06-21T10:40:00Z'), 0, FALLBACK_VIEW);
+ const sky = makePhysicalSky(sunOfBand(FALLBACK_VIEW.place, state, new Date('2026-06-21T10:40:00Z')), 0, FALLBACK_VIEW);
const { camera } = windowFor(sky.view, 64, 36);
const dome = renderDome(sky.atm, sky.sun, camera, 64, 36, sky.weather.cover, sky.night);
const b = BUDGET[state];
@@ -67,7 +68,7 @@ describe.each(['day', 'dusk', 'night'] as FixedSkyState[])('the %s curve fitted
describe('the night display', () => {
const night = (iso: string) => {
const t = new Date(iso);
- return makePhysicalSky('night', t, 0, FALLBACK_VIEW, sunAt(FALLBACK_VIEW.place, t));
+ return makePhysicalSky(sunAt(FALLBACK_VIEW.place, t), 0, FALLBACK_VIEW);
};
const fullMoon = night('2026-11-24T22:00:00Z');
const newMoon = night('2026-12-09T20:00:00Z');
@@ -86,7 +87,7 @@ describe('the night display', () => {
it('grades toward the rods at night and not by day', () => {
expect(fullMoon.fit.display.grade).toBeGreaterThan(0.8);
expect(newMoon.fit.display.grade).toBeGreaterThan(0.99);
- expect(makePhysicalSky('day', new Date('2026-06-21T10:40:00Z'), 0, FALLBACK_VIEW).fit.display.grade ?? 0).toBe(0);
+ expect(makePhysicalSky(sunOfBand(FALLBACK_VIEW.place, 'day', new Date('2026-06-21T10:40:00Z')), 0, FALLBACK_VIEW).fit.display.grade ?? 0).toBe(0);
});
it('has no fixed night ceiling: the curve tops out at NIGHT_CEILING', () => {
diff --git a/src/app/features/scene/ridge/toneMap.ts b/src/app/features/scene/ridge/toneMap.ts
index 0a41bb07..e7a8f0cc 100644
--- a/src/app/features/scene/ridge/toneMap.ts
+++ b/src/app/features/scene/ridge/toneMap.ts
@@ -10,7 +10,7 @@
// distribution of the sky grid so that its 5th, 50th and 95th percentiles land on the state's target display luminances. The curve
// starts at a small black lift and ends at white, or at the state's ceiling when it has one. It is fitted on the sky grid alone: the
// cards are not sampled, they ride the same curve.
-import type { FixedSkyState } from '../skyState';
+import type { FixedSkyState } from './skyMoment';
import { SUN_LUX } from './nightSky';
type Rgb = readonly [number, number, number];
diff --git a/src/app/features/scene/ridge/view.test.ts b/src/app/features/scene/ridge/view.test.ts
index 2900523e..d7ceb382 100644
--- a/src/app/features/scene/ridge/view.test.ts
+++ b/src/app/features/scene/ridge/view.test.ts
@@ -1,6 +1,19 @@
import { describe, expect, it } from 'vitest';
-import { sunOnScreen } from './skyDome';
-import { cardMotion, DRIFT_FRAC, FALLBACK_VIEW, HORIZON_AT, windowFor } from './view';
+import {
+ cardArc,
+ cardPose,
+ FALLBACK_VIEW,
+ HFOV_MAX_DEG,
+ HORIZON_AT,
+ maxSpeed,
+ offsetRange,
+ RIDGE_BAND_FRAC,
+ SEGMENT_S,
+ SPEED_CEILING_DEG_S,
+ sweepArc,
+ windowFor,
+} from './view';
+import { KEEP_MARGIN_TILES, residentTiles, runTiles } from './ring';
import { parseManifest } from './manifest';
import { wireManifest } from './manifest.fixture';
import type { View } from './view';
@@ -11,28 +24,41 @@ const VIEWPORTS: [number, number][] = [
[3440, 1440],
];
+const manifest = parseManifest(wireManifest(), '/d/'); // distances: card 0 1000-1400 m, card 1 10-14 km, card 2 39-41 km
+const withView = (over: Record) =>
+ parseManifest(wireManifest({ view: { ...(wireManifest().view as object), ...over } }), '/d/');
+const DEG = Math.PI / 180;
+
describe('windowFor', () => {
+ it('gives a 16:9 viewport the scale and the 65.45 degrees it had when a window was baked, and a phone the band scale', () => {
+ const v = FALLBACK_VIEW;
+ const wide = windowFor(v, 1920, 1080);
+ expect(wide.plane.scale).toBeCloseTo((1920 * 1.1) / 1280, 9);
+ expect(wide.camera.hfovDeg).toBeCloseTo(72 / 1.1, 9);
+ expect(HFOV_MAX_DEG).toBeCloseTo(65.4545, 4);
+ const phone = windowFor(v, 390, 844);
+ expect(phone.plane.scale).toBeCloseTo((RIDGE_BAND_FRAC * 844) / v.planeH, 9);
+ expect(phone.camera.hfovDeg).toBeCloseTo(390 / (phone.plane.scale * v.pxPerDegH), 9);
+ });
+
it.each(VIEWPORTS)(
- "%i x %i: the planes cover the viewport, the camera sees only baked sky, the horizon is the plane's",
+ "%i x %i: the camera never sees more than the widest field, the horizon is the plane's, the plane reaches the bottom",
(w, h) => {
const v = FALLBACK_VIEW;
const win = windowFor(v, w, h);
- expect(win.driftPx).toBeGreaterThanOrEqual(0);
- expect(win.plane.w - 2 * win.driftPx).toBeCloseTo(w, 6);
+ expect(win.camera.hfovDeg).toBeLessThanOrEqual(HFOV_MAX_DEG + 1e-9);
expect(win.plane.h).toBeLessThanOrEqual(h * 4); // sanity: scale is not runaway
- // Angle seen never exceeds the baked window minus the drift margin on both sides.
- expect(win.camera.hfovDeg).toBeLessThanOrEqual(v.windowDeg / (1 + 2 * DRIFT_FRAC) + 1e-9);
- // The plane's horizon row lands at the camera's horizon fraction of the viewport.
const horizonY = h - win.plane.bottom - win.plane.h + win.plane.scale * v.horizonRow;
expect(Math.abs(horizonY - win.camera.horizonAt * h)).toBeLessThan(0.5);
expect(win.camera.azimuthDeg).toBe(v.lookAzDeg);
expect(win.camera.vfovDeg / win.camera.hfovDeg).toBeCloseTo(h / w, 9); // one scale on both axes
+ expect(win.plane.bottom).toBeLessThanOrEqual(0);
}
);
- it('puts the horizon at one fraction of the height, whatever the viewport, the view or the sky state', () => {
- const wide: View = { ...FALLBACK_VIEW, lookAzDeg: 10, windowDeg: 144, planeW: 2560, horizonRow: 200 };
- for (const v of [FALLBACK_VIEW, wide])
+ it('puts the horizon at one fraction of the height, whatever the viewport or the view', () => {
+ const other: View = { ...FALLBACK_VIEW, lookAzDeg: 10, horizonRow: 200, pxPerDegH: 10 };
+ for (const v of [FALLBACK_VIEW, other])
for (const [w, h] of [...VIEWPORTS, [1024, 768], [375, 812], [1100, 619]] as [number, number][])
expect(windowFor(v, w, h).camera.horizonAt).toBe(HORIZON_AT);
expect(HORIZON_AT).toBeGreaterThan(0.5);
@@ -46,110 +72,234 @@ describe('windowFor', () => {
expect(sky).toBeLessThan(34);
});
- it.each([
- [1024, 768],
- [1920, 1080],
- [375, 812],
- [1100, 619],
- ])('%i x %i: the plane covers the viewport bottom and sides, drift included, with baked ground to spare below the horizon', (w, h) => {
- const win = windowFor(FALLBACK_VIEW, w, h);
- expect(win.plane.bottom).toBeLessThanOrEqual(0); // the foot of the plane is at or below the viewport's bottom edge
- expect(win.plane.w - 2 * win.driftPx).toBeCloseTo(w, 6);
- expect(win.driftPx).toBeGreaterThanOrEqual(0);
- // The baked ground below the horizon row that the viewport crops to: more than the viewport needs.
- const needed = (1 - HORIZON_AT) * h;
- const baked = win.plane.scale * (FALLBACK_VIEW.planeH - FALLBACK_VIEW.horizonRow);
- expect(baked).toBeGreaterThanOrEqual(needed);
+ it('points the camera at the rest azimuth, and a north-crossing one is not wrapped', () => {
+ expect(windowFor({ ...FALLBACK_VIEW, lookAzDeg: 355 }, 1920, 1080).camera.azimuthDeg).toBe(355);
+ });
+});
+
+describe('cardPose', () => {
+ const win = windowFor(manifest.view, 1920, 1080);
+ const rest = manifest.view.lookAzDeg;
+ const k = win.plane.scale * manifest.view.pxPerDegH;
+
+ it('at phi 0 is the tangent R / (R - r) the camera pushed forward gives, a card pans with the heading, and the offset 0 leaves it at scale 1', () => {
+ // Heading 135 is tile 1's centre: card 1 stands 12 km away there.
+ const p = cardPose(manifest, 1, 135, 0, 200, win);
+ expect(p.scale).toBeCloseTo(12000 / (12000 - 200), 2);
+ expect(Math.abs(p.scale - 12000 / (12000 - 200))).toBeLessThan(0.002);
+ const flat = cardPose(manifest, 1, 135, 0, 0, win);
+ expect(flat.scale).toBeCloseTo(1, 9);
+ // The column the view faces lands on the centre: at scale s the container shifts by -s (h - rest) k.
+ expect(flat.shiftPx).toBeCloseTo(-(135 - rest) * k, 6);
});
- it('is shaped by the View alone: another window and plane give another camera (azimuth and field of view; the horizon stays put)', () => {
- const wide: View = {
- ...FALLBACK_VIEW,
- lookAzDeg: 10,
- windowDeg: 144,
- planeW: 2560,
- horizonRow: 200,
- };
- const a = windowFor(FALLBACK_VIEW, 1920, 1080).camera;
- const b = windowFor(wide, 1920, 1080).camera;
- expect(b.azimuthDeg).toBe(10);
- expect(windowFor(FALLBACK_VIEW, 1920, 1080).camera.hfovDeg).not.toBeCloseTo(windowFor(wide, 1920, 1080).camera.hfovDeg, 2);
- expect(b.horizonAt).toBe(a.horizonAt);
+ it('is mirrored behind the centre: a backward offset shrinks the card and a larger one shrinks it more', () => {
+ const fwd = cardPose(manifest, 0, 45, 0, 100, win).scale;
+ const back = cardPose(manifest, 0, 45, 0, -100, win).scale;
+ expect(fwd).toBeGreaterThan(1);
+ expect(back).toBeLessThan(1);
+ expect(cardPose(manifest, 0, 45, 0, -200, win).scale).toBeLessThan(back);
});
- it('registration: a sun 10 degrees right of the look azimuth sits where the plane puts that azimuth', () => {
+ it('at phi 90 shifts the card sideways by r / R x 57.3 degrees and leaves its size alone', () => {
+ const at = (phi: number) => cardPose(manifest, 1, 135, phi, 200, win);
+ const p = at(90);
+ // The sideways part of a pose: where the line meets the heading's own column, a0 = shift / k + s (h - rest).
+ const a0 = (q: { scale: number; shiftPx: number }) => q.shiftPx / k + q.scale * (135 - rest);
+ expect(a0(at(0))).toBeCloseTo(0, 6);
+ // A camera to the clockwise side of the heading (east of a north view) sees the card to the left of it, and one on the other side to the right.
+ expect(a0(p)).toBeLessThan(0);
+ expect(a0(at(-90))).toBeGreaterThan(0);
+ // r / R x 57.3 degrees at the heading's own column; the line fitted over the arc takes the mean of cos over it, about 0.93 of that.
+ const centre = (200 / 12000) * (180 / Math.PI);
+ expect(Math.abs(a0(p)) / centre).toBeGreaterThan(0.9);
+ expect(Math.abs(a0(p)) / centre).toBeLessThanOrEqual(1);
+ expect(p.scale).toBeCloseTo(1, 2);
+ });
+
+ it('is the same at a heading and a revolution on: nothing about it wraps', () => {
+ const a = cardPose(manifest, 0, 100, 10, 80, win);
+ const b = cardPose(manifest, 0, 100 + 360, 10, 80, win);
+ expect(b.scale).toBeCloseTo(a.scale, 9);
+ // The unwrapped heading moves the container a revolution, which is what keeps the tiles at their unwrapped azimuth.
+ expect(b.shiftPx - a.shiftPx).toBeCloseTo(-a.scale * 360 * k, 4);
+ });
+
+ it('is exact where the sheet is: a card seen from its own circle lands on the line it fits', () => {
+ // The fitted line passes through the exact angle at the middle of the arc within a card pixel at a small offset.
+ const R = 12000;
+ const r = 150;
+ const p = cardPose(manifest, 1, 135, 0, r, win);
+ const exact = Math.atan2(R * Math.sin(10 * DEG), R * Math.cos(10 * DEG) - r) / DEG;
+ const line = (p.shiftPx / k + p.scale * (135 - rest)) + p.scale * 10;
+ expect(Math.abs(exact - line) * k).toBeLessThan(0.5);
+ });
+});
+
+describe('cardArc', () => {
+ const win = windowFor(manifest.view, 1920, 1080);
+ it('is the viewport arc at the rest heading with no offset, and follows the heading and the scale', () => {
+ const rest = manifest.view.lookAzDeg;
+ const half = win.camera.hfovDeg / 2;
+ const flat = cardArc(manifest.view, win, 1920, cardPose(manifest, 1, rest, 0, 0, win));
+ expect(flat.fromDeg).toBeCloseTo(rest - half, 6);
+ expect(flat.toDeg).toBeCloseTo(rest + half, 6);
+ const turned = cardArc(manifest.view, win, 1920, cardPose(manifest, 1, rest + 400, 0, 0, win));
+ expect(turned.fromDeg).toBeCloseTo(rest + 400 - half, 6);
+ // A card that is larger on screen shows less of itself.
+ const near = cardPose(manifest, 0, 45, 0, 100, win);
+ const arc = cardArc(manifest.view, win, 1920, near);
+ expect(arc.toDeg - arc.fromDeg).toBeCloseTo((2 * half) / near.scale, 6);
+ });
+});
+
+describe('offsetRange', () => {
+ it('is the bake worst-case bound either way round in the offset-only mode, whose camera circles the whole ring of angles', () => {
for (const [w, h] of VIEWPORTS) {
- const v = FALLBACK_VIEW;
- const win = windowFor(v, w, h);
- const sun = { elevation: 12, azimuth: v.lookAzDeg + 10, time: new Date(0) };
- const at = sunOnScreen(sun, win.camera)!;
- const planeX = w / 2 + 10 * v.pxPerDegH * win.plane.scale; // plane centred on lookAz
- expect(Math.abs(at.x * w - planeX)).toBeLessThan(0.5);
- // and its height above the ridge's horizon is 12 degrees of plane pixels
- const planeY = win.camera.horizonAt * h - 12 * v.pxPerDegH * win.plane.scale;
- expect(Math.abs(at.y * h - planeY)).toBeLessThan(0.5);
- }
- });
-
- it('the sun is seen across north: azimuths wrap', () => {
- const v: View = { ...FALLBACK_VIEW, lookAzDeg: 355 };
- const win = windowFor(v, 1920, 1080);
- const at = sunOnScreen({ elevation: 10, azimuth: 5, time: new Date(0) }, win.camera)!;
- expect(Math.abs(at.x * 1920 - (960 + 10 * v.pxPerDegH * win.plane.scale))).toBeLessThan(0.5);
- });
-
- it('the sun does not turn the camera: the same camera for any sun', () => {
- expect(windowFor(FALLBACK_VIEW, 1280, 720).camera.azimuthDeg).toBe(FALLBACK_VIEW.lookAzDeg);
- });
-});
-
-describe('cardMotion', () => {
- const manifest = parseManifest(wireManifest(), '/d/'); // scales 1.2, 1.0167, 1.005; heading range 23 deg; 1280 px plane, 17.78 px per degree
- const motion = (w: number, h: number) => cardMotion(manifest, windowFor(manifest.view, w, h));
-
- it('turns the whole baked range on a phone and is capped by coverage on a wide screen', () => {
- expect(motion(390, 844).headingDeg).toBe(23);
- expect(motion(1920, 1080).headingDeg).toBeCloseTo(3.4, 1);
- expect(motion(768, 1024).headingDeg).toBeLessThan(23);
- expect(motion(768, 1024).headingDeg).toBeGreaterThan(motion(1920, 1080).headingDeg);
- });
-
- it.each([
- [390, 844],
- [768, 1024],
- [1920, 1080],
- [3440, 1440],
- ])(
- '%i x %i: every card still covers the viewport at the end of the drift, and the cap is exact for the card that gives out first',
- (w, h) => {
const win = windowFor(manifest.view, w, h);
- const { headingDeg } = cardMotion(manifest, win);
- const half = w / 2 / win.plane.scale;
- const slack = manifest.cards.map(
- (c) => manifest.view.planeW / 2 - half / c.scale - headingDeg * manifest.view.pxPerDegH
- );
- slack.forEach((s) => expect(s).toBeGreaterThanOrEqual(-1e-6));
- if (headingDeg < manifest.camera.headingMaxDeg) expect(Math.min(...slack)).toBeCloseTo(0, 6);
+ expect(offsetRange(manifest, win, 'offset')).toEqual([-manifest.camera.rMaxM, manifest.camera.rMaxM]);
+ // The angle the camera stands at does not matter there: it is going to all of them.
+ expect(offsetRange(manifest, win, 'offset', 0)).toEqual(offsetRange(manifest, win, 'offset', 123));
}
- );
-
- it('pans card i by scale_i x heading and keeps the scales the manifest gave', () => {
- const win = windowFor(manifest.view, 390, 844);
- const m = cardMotion(manifest, win);
- expect(m.cards.map((c) => c.scale)).toEqual([1.2, 1.0167, 1.005]);
- m.cards.forEach((c) =>
- expect(c.reachPx).toBeCloseTo(c.scale * 23 * manifest.view.pxPerDegH * win.plane.scale, 6)
- );
- // The nearer a card, the faster it pans.
- expect(m.cards[0].reachPx).toBeGreaterThan(m.cards[1].reachPx);
- expect(m.cards[1].reachPx).toBeGreaterThan(m.cards[2].reachPx);
});
- it('a wider baker range moves a phone further, a narrower one less', () => {
- const win = windowFor(manifest.view, 390, 844);
- const at = (deg: number) => cardMotion({ ...manifest, camera: { headingMaxDeg: deg } }, win);
- expect(at(10).headingDeg).toBe(10);
- expect(at(40).headingDeg).toBeLessThan(40); // the phone's coverage gives out first
- expect(at(10).cards[0].reachPx).toBeLessThan(at(20).cards[0].reachPx);
+ it('lets a forward offset go as far as the bake phi 0 bound where the offset turns with the view, and a backward one only as far as the worst case', () => {
+ for (const [w, h] of VIEWPORTS) {
+ const win = windowFor(manifest.view, w, h);
+ for (const mode of ['both', 'still'] as const) {
+ const [lo, hi] = offsetRange(manifest, win, mode);
+ expect(hi).toBe(manifest.camera.rMaxForwardM);
+ expect(lo).toBe(-manifest.camera.rMaxM);
+ }
+ }
+ expect(manifest.camera.rMaxForwardM).toBeGreaterThan(manifest.camera.rMaxM);
+ });
+
+ it('a camera held at an angle of its circle is bounded as the circle is: the bound follows where the camera stands, not only the mode', () => {
+ const win = windowFor(manifest.view, 1920, 1080);
+ expect(offsetRange(manifest, win, 'still', 0)[1]).toBe(manifest.camera.rMaxForwardM);
+ expect(offsetRange(manifest, win, 'still', 360)[1]).toBe(manifest.camera.rMaxForwardM);
+ expect(offsetRange(manifest, win, 'still', 137)).toEqual([-manifest.camera.rMaxM, manifest.camera.rMaxM]);
+ });
+
+ it('keeps a default +200 m where phi stays 0 and the bake allows it, and takes it to the worst-case bound where the camera circles', () => {
+ const vienna = parseManifest(
+ wireManifest({ camera: { r_max_m: 98.2, r_max_forward_m: 205.4 } }),
+ '/d/'
+ );
+ const win = windowFor(vienna.view, 1920, 1080);
+ const clamp = (mode: 'both' | 'offset' | 'still') => {
+ const [lo, hi] = offsetRange(vienna, win, mode);
+ return Math.min(hi, Math.max(lo, 200));
+ };
+ expect(clamp('both')).toBe(200);
+ expect(clamp('still')).toBe(200);
+ expect(clamp('offset')).toBe(98.2);
+ });
+
+ it('gives up part of its backward half where the nearest card shrunk by R / (R + r) would lift its foot above the viewport bottom, and all of it past that', () => {
+ // 1920 x 1080: keep = (1 - HORIZON_AT) 1080 / (scale (planeH - horizonRow)). Put the horizon row so that keep is 0.95, and the nearest card is 1000 m away.
+ const scale = windowFor(manifest.view, 1920, 1080).plane.scale;
+ const near = withView({ horizon_row: 600 - (0.15 * 1080) / 0.95 / scale });
+ const win = windowFor(near.view, 1920, 1080);
+ const [lo, hi] = offsetRange(near, win, 'both');
+ expect(hi).toBe(180);
+ expect(lo).toBeCloseTo(-1000 * (1 / 0.95 - 1), 6);
+ // At that offset the card's foot is exactly at the viewport bottom.
+ const s = 1000 / (1000 - lo);
+ expect(s * win.plane.scale * (near.view.planeH - near.view.horizonRow)).toBeCloseTo(0.15 * 1080, 6);
+ const none = withView({ horizon_row: 599 });
+ expect(offsetRange(none, windowFor(none.view, 1920, 1080), 'both')).toEqual([-0, 180]);
+ });
+
+ it('gives up the same part of its forward half in the offset-only mode: the camera circles round to phi 180 and the nearest card shrinks as it does for a backward offset', () => {
+ const scale = windowFor(manifest.view, 1920, 1080).plane.scale;
+ const near = withView({ horizon_row: 600 - (0.15 * 1080) / 0.95 / scale });
+ const win = windowFor(near.view, 1920, 1080);
+ const [lo, hi] = offsetRange(near, win, 'offset');
+ expect(hi).toBeCloseTo(1000 * (1 / 0.95 - 1), 6);
+ expect(lo).toBe(-hi);
+ // The camera at phi 180 and offset hi puts the nearest card at the scale that leaves its foot on the bottom edge.
+ const R = 1000;
+ const p = cardPose(near, 0, near.view.lookAzDeg, 180, hi, win);
+ expect(Math.abs(p.scale - R / (R + hi))).toBeLessThan(0.02); // the fitted line is within a hair of the tangent the clamp uses
+ const none = withView({ horizon_row: 599 });
+ expect(offsetRange(none, windowFor(none.view, 1920, 1080), 'offset')).toEqual([-0, 0]);
+ });
+});
+
+describe('maxSpeed', () => {
+ const ring = parseManifest(wireManifest({}, 3, 32), '/d/'); // the ring as the baker cuts it: 32 tiles of 11.25 degrees, rmin 1000 m, r_max 100, forward 180
+ const win = windowFor(ring.view, 1920, 1080);
+ const poses = (v: number, h: number, off: number) => (card: number, ms: number) =>
+ cardPose(ring, card, h + (v * ms) / 1000, 0, off, win);
+ /** The most tiles the loader would hold for a view turning at v, over a sweep of headings and the offsets the mode allows. */
+ const mostHeld = (v: number): number => {
+ const [lo, hi] = offsetRange(ring, win, 'both');
+ let most = 0;
+ for (const off of [lo, 0, hi]) {
+ for (let h = 0; h < 360; h += 3.7) {
+ const arc = sweepArc(ring.view, win, 1920, 3, poses(v, h, off), 0);
+ const keep = residentTiles(
+ ring.view,
+ (arc.fromDeg + arc.toDeg) / 2,
+ (arc.toDeg - arc.fromDeg) / 2 + KEEP_MARGIN_TILES * 11.25
+ );
+ most = Math.max(most, keep.length);
+ }
+ }
+ return most;
+ };
+ const N = runTiles(ring.view, HFOV_MAX_DEG, ring.camera.rMaxForwardM, 1000);
+
+ it('is what the baked resident count leaves in the mode where the view turns, and the ceiling where it does not', () => {
+ const v = maxSpeed(ring, 'both');
+ expect(v).toBeGreaterThan(0);
+ expect(v).toBeLessThan(SPEED_CEILING_DEG_S);
+ expect(maxSpeed(ring, 'offset')).toBe(SPEED_CEILING_DEG_S);
+ expect(maxSpeed(ring, 'still')).toBe(SPEED_CEILING_DEG_S);
+ // Held to N by the sweep of SEGMENT_S seconds at the bound, and over it a little above.
+ expect(mostHeld(v)).toBeLessThanOrEqual(N);
+ expect(mostHeld(v * 1.6)).toBeGreaterThan(N);
+ expect(SEGMENT_S).toBe(30);
+ });
+
+ it('is never above the ceiling, whatever room the ring has, and never below 0', () => {
+ const open = parseManifest(wireManifest({ camera: { r_max_m: 0.1, r_max_forward_m: 0.1 } }, 3, 32), '/d/');
+ expect(maxSpeed(open, 'both')).toBeLessThanOrEqual(SPEED_CEILING_DEG_S);
+ const tight = parseManifest(wireManifest({ camera: { r_max_m: 100, r_max_forward_m: 100 } }, 3, 32), '/d/');
+ expect(maxSpeed(tight, 'both')).toBeGreaterThanOrEqual(0);
+ });
+});
+
+describe('sweepArc', () => {
+ const ring = parseManifest(wireManifest({}, 3, 32), '/d/');
+ const win = windowFor(ring.view, 1920, 1080);
+ // The offset-only mode at 12 degrees a second and the offset own bound: the nearest card swings out and back over the stretch.
+ const v = 12;
+ const [, hi] = offsetRange(ring, win, 'offset');
+ const poseAt = (card: number, ms: number) => cardPose(ring, card, 100, 30 + (v * ms) / 1000, hi, win);
+
+ it('covers every pose the stretch passes through, not the two it begins and ends with', () => {
+ const swept = sweepArc(ring.view, win, 1920, 3, poseAt, 0);
+ let from = Infinity;
+ let to = -Infinity;
+ for (let ms = 0; ms <= SEGMENT_S * 1000; ms += 50) {
+ for (let i = 0; i < 3; i += 1) {
+ const a = cardArc(ring.view, win, 1920, poseAt(i, ms));
+ from = Math.min(from, a.fromDeg);
+ to = Math.max(to, a.toDeg);
+ }
+ }
+ // Within a hundredth of a degree of the dense answer, either side: it covers the swing and is not the whole ring.
+ expect(Math.abs(swept.fromDeg - from)).toBeLessThan(0.01);
+ expect(Math.abs(swept.toDeg - to)).toBeLessThan(0.01);
+ // The two ends alone fall short of the dense answer by whole degrees.
+ const ends = [0, SEGMENT_S * 1000].flatMap((ms) =>
+ [0, 1, 2].map((i) => cardArc(ring.view, win, 1920, poseAt(i, ms)))
+ );
+ const endFrom = Math.min(...ends.map((a) => a.fromDeg));
+ const endTo = Math.max(...ends.map((a) => a.toDeg));
+ expect(endFrom - from > 1 || to - endTo > 1).toBe(true);
});
});
diff --git a/src/app/features/scene/ridge/view.ts b/src/app/features/scene/ridge/view.ts
index 42968603..7dbd6429 100644
--- a/src/app/features/scene/ridge/view.ts
+++ b/src/app/features/scene/ridge/view.ts
@@ -1,7 +1,11 @@
// The one View: where the sky's camera stands and looks, and where the ridge cards sit against it. A baked place's manifest
-// (`view` and `place`, manifest v2) is a View; a sky with no planes uses FALLBACK_VIEW. `windowFor` is the single owner of the
-// registration between sky and ridge: one View and a viewport in, the sky Camera and the plane's placement out. Nothing else
-// chooses a field of view, a horizon row or an azimuth.
+// (`view` and `place`, manifest schema 3) is a View; a sky with no planes uses FALLBACK_VIEW. `windowFor` is the single owner of the
+// registration between sky and ridge: one View and a viewport in, the sky Camera and the plane's placement out. `offsetRange` is the one
+// clamp on the camera's offset and `cardPose` the one place a card's scale and shift are derived (ruling ridge-camera-on-circle). Nothing
+// else chooses a field of view, a horizon row, an azimuth, a scale or a shift.
+import { distanceAt, KEEP_MARGIN_TILES, norm, runTiles } from './ring';
+import type { RidgeManifest } from './manifest';
+import type { RotationMode } from './heading';
/** Where the observer stands. `id` names the baked place (it keys a rebuild); `altitudeKm` is the ground height, eye height excluded. */
export interface Place {
@@ -9,15 +13,21 @@ export interface Place {
lat: number;
lon: number;
altitudeKm: number;
+ /** The place's IANA time zone (the baker writes it): the one owner of place-local time is skyMoment.ts. */
+ tz: string;
}
-/** The manifest's `view`: the baked window of the sky the planes cover. Angles are degrees, planes are in plane pixels. */
+/**
+ * The manifest's `view`: the ring the planes cover, all 360 degrees, absolute compass (column 0 = north), cut into `tiles` azimuth tiles of `tileW` columns
+ * (`apron` real neighbour columns each side in a tile's files). Angles are degrees, planes are in plane pixels.
+ */
export interface ManifestView {
- /** Compass azimuth at the centre of the planes, degrees clockwise from north. */
+ /** The rest azimuth: the compass azimuth the view faces before anything turns it, degrees clockwise from north. */
lookAzDeg: number;
- /** Horizontal angle the planes span. */
- windowDeg: number;
- planeW: number;
+ ringW: number;
+ tileW: number;
+ tiles: number;
+ apron: number;
planeH: number;
pxPerDegH: number;
/** Plane pixels per degree of elevation (the baker draws the vertical exaggerated: it is not `pxPerDegH`). */
@@ -43,21 +53,24 @@ export interface Camera {
horizonAt: number;
}
-/** The sky of a scene with no planes (a failed load): Vienna facing south-west, with the numbers of the Vienna bake. */
+/** The sky of a scene with no planes (a failed load): Vienna facing south-west, with the numbers of the Vienna ring bake. */
export const FALLBACK_VIEW: View = {
- place: { id: 'vienna', lat: 48.1929826, lon: 16.3534237, altitudeKm: 0.183 },
+ place: { id: 'vienna', lat: 48.1929826, lon: 16.3534237, altitudeKm: 0.183, tz: 'Europe/Vienna' },
lookAzDeg: 214,
- windowDeg: 72,
- planeW: 1280,
+ ringW: 6400,
+ tileW: 200,
+ tiles: 32,
+ apron: 2,
planeH: 600,
- pxPerDegH: 1280 / 72,
- pxPerDegV: 177.8,
- horizonRow: 314.5,
+ pxPerDegH: 6400 / 360,
+ pxPerDegV: 171.73831979090915,
+ horizonRow: 357.01990847502145,
};
-/** The share of the viewport height the plane's height is at least scaled to, and the slack each side of the viewport kept for drift. Authored, tunable by eye. */
+/** The share of the viewport height the plane's height is at least scaled to. Authored, tunable by eye. */
export const RIDGE_BAND_FRAC = 0.6;
-export const DRIFT_FRAC = 0.05;
+/** The widest field of view a viewport may show: a 16:9 viewport with 1.1 widths of plane (72 / 1.1 degrees), as export.py HFOV_MAX_DEG. */
+export const HFOV_MAX_DEG = 72 / 1.1;
/**
* Where the horizon sits down the viewport, as a fraction of its height: one constant for every sky state and every viewport (ruling
* ridge-frame-more-sky-fixed-pitch: the camera pitch never changes between day and night). The plane extends below the viewport bottom and
@@ -67,16 +80,14 @@ export const HORIZON_AT = 0.85;
export interface Window {
camera: Camera;
- /** The planes in viewport pixels: scaled size, centred on `lookAzDeg`, placed so the horizon row lands at `HORIZON_AT` of the height. `bottom` is the distance of the plane's foot above the viewport's bottom edge: negative, the plane runs on below it. */
- plane: { scale: number; w: number; h: number; bottom: number };
- /** How far the plane may slide sideways from centre and still cover the viewport. */
- driftPx: number;
+ /** The planes in viewport pixels: the scale of a plane pixel, the plane's height, and `bottom`, the distance of its foot above the viewport's bottom edge (negative: the plane runs on below it). The horizon row lands at `HORIZON_AT`. */
+ plane: { scale: number; h: number; bottom: number };
}
export function windowFor(view: View, viewportW: number, viewportH: number): Window {
const scale = Math.max(
(RIDGE_BAND_FRAC * viewportH) / view.planeH,
- (viewportW * (1 + 2 * DRIFT_FRAC)) / view.planeW
+ viewportW / (HFOV_MAX_DEG * view.pxPerDegH)
);
const hfovDeg = viewportW / (scale * view.pxPerDegH);
return {
@@ -88,45 +99,162 @@ export function windowFor(view: View, viewportW: number, viewportH: number): Win
},
plane: {
scale,
- w: scale * view.planeW,
h: scale * view.planeH,
bottom: (1 - HORIZON_AT) * viewportH - scale * (view.planeH - view.horizonRow),
},
- driftPx: (scale * view.planeW - viewportW) / 2,
};
}
-/** What `cardMotion` reads of a manifest: the cards' scales, the baker's heading range and the View. */
-interface CardRig {
- view: View;
- camera: { headingMaxDeg: number };
- cards: readonly { scale: number }[];
+/** Nearest card's nearest tile distance, metres: where the camera first meets a card. */
+const nearestM = (manifest: RidgeManifest): number =>
+ Math.min(...manifest.tiles.map((row) => row[0]?.distanceM ?? Infinity));
+
+/** Whether the camera stands on its heading (phi 0, a whole turn off it included): a mode where the offset turns with the view puts it there. */
+const onHeading = (mode: RotationMode, phiDeg: number): boolean =>
+ mode !== 'offset' && Math.abs(norm(phiDeg + 180) - 180) < 1e-6;
+
+/**
+ * The offsets the camera may take on its circle, metres, forward positive: the one clamp (ruling ridge-offset-range-fit, "the slider stops where the linear
+ * map holds"). How well a card's linear slide fits depends on the camera's angle `phiDeg` on its circle, so the bound depends on where the mode keeps it. With
+ * the camera on its heading (modes 'still' and 'both', `phi` 0) a forward offset goes to the bake's `rMaxForwardM`, the largest every card fits at phi 0;
+ * everywhere else (the offset-only mode swings the camera round the whole circle, and a backward offset at phi 0 is the camera at phi 180) the bound is
+ * `rMaxM`, the worst over every phi. The nearest card, shrunk by R / (R + r) about the horizon, would lift its foot above the viewport bottom and show the
+ * sky under it past the point where `1 / keep - 1` of its distance is the offset: the baker's nearest-card-off-the-bottom refusal as a clamp, applied to
+ * every position the camera can reach at the offset's sign (backward always, forward too where the circle takes it round to phi 180).
+ */
+export function offsetRange(
+ manifest: RidgeManifest,
+ win: Window,
+ mode: RotationMode,
+ phiDeg = 0
+): [number, number] {
+ const { rMaxM, rMaxForwardM } = manifest.camera;
+ const { planeH, horizonRow } = manifest.view;
+ const below = win.plane.scale * (planeH - horizonRow);
+ const keep = 1 + win.plane.bottom / below; // the smallest scale at which the foot stays under the viewport bottom
+ const foot = keep >= 1 ? 0 : nearestM(manifest) * (1 / keep - 1);
+ const back = Math.min(rMaxM, foot);
+ return onHeading(mode, phiDeg) ? [-back, rMaxForwardM] : [-back, back];
}
-export interface CardMotion {
- /** The heading either side of the look azimuth the drift turns through, degrees. */
- headingDeg: number;
- /** Per card, in manifest order (nearest first): the static scale the baker derived and how far it pans, in viewport px, at the end of the drift. */
- cards: { scale: number; reachPx: number }[];
+/** The longest stretch of motion the rig issues at once, seconds: the loader holds the tiles it passes over, so it also bounds how far a turn may sweep. */
+export const SEGMENT_S = 30;
+/** The fastest the view or the camera may turn, degrees per second, whatever the loader holds: a keyframe a second must not skip a whole tile (11.25 degrees at 32 tiles). */
+export const SPEED_CEILING_DEG_S = 12;
+
+/**
+ * The largest speed (degrees per second, either direction) the baked resident count sustains in `mode`: the loader holds the tiles of the arc a card shows
+ * over the next SEGMENT_S seconds and two tiles beyond it each side, and the bake's gate (`ring.ts` `runTiles`, `export.py`) priced N of them. Turning the view
+ * widens that arc by speed x SEGMENT_S, so in 'both' the speed is what N leaves after the widest card arc (the viewport over the smallest slide rate, at the
+ * backward offset `rMaxM`) and the margin tiles. The offset-only mode sweeps the camera over a circle the gate already counts whatever the speed, and a still
+ * view has none: those take the ceiling, as does a ring the gate priced whole.
+ */
+export function maxSpeed(manifest: RidgeManifest, mode: RotationMode): number {
+ if (mode !== 'both') return SPEED_CEILING_DEG_S;
+ const { view, camera } = manifest;
+ const tileDeg = 360 / view.tiles;
+ const rmin = nearestM(manifest);
+ const n = runTiles(view, HFOV_MAX_DEG, camera.rMaxForwardM, rmin);
+ if (n >= view.tiles) return SPEED_CEILING_DEG_S; // the gate counted the whole ring: nothing the loader holds can exceed it
+ const sMin = rmin / (rmin + camera.rMaxM);
+ const room = (n - 1 - 2 * KEEP_MARGIN_TILES) * tileDeg - HFOV_MAX_DEG / sMin;
+ return Math.min(SPEED_CEILING_DEG_S, Math.max(0, room / SEGMENT_S));
+}
+
+/** What a card does on screen: its scale about the horizon and how far it is shifted sideways, viewport px, at a heading and camera angle. */
+export interface CardPose {
+ scale: number;
+ shiftPx: number;
+}
+
+const RAD = Math.PI / 180;
+const FIT_SAMPLES = 9;
+
+/**
+ * Where a card goes on a viewport: the camera stands on its circle of radius `offsetM` (signed, forward positive) at angle `phiDeg` against the heading
+ * `headingDeg`; a card at distance R (`ring.ts` `distanceAt` at the heading) seen from there is at angle `atan2(R sin b - r sin phi, R cos b - r cos phi)`
+ * from the heading for a point `b` degrees off it. A card is one flat sheet (ruling ridge-cards-per-card-slide), so that curve is fitted by the line
+ * `a + s b` over the viewport's arc, and the card is scaled by `s` about the horizon and shifted so the column at azimuth `az` lands at `a + s (az - heading)`.
+ * `shiftPx` is the translate of a container whose tiles sit at `(az - rest) x px per degree`, rest being the View's rest azimuth.
+ */
+export function cardPose(
+ manifest: RidgeManifest,
+ card: number,
+ headingDeg: number,
+ phiDeg: number,
+ offsetM: number,
+ win: Window
+): CardPose {
+ const R = distanceAt(manifest, card, headingDeg);
+ const half = win.camera.hfovDeg / 2;
+ const phi = phiDeg * RAD;
+ let sb = 0;
+ let sa = 0;
+ let sbb = 0;
+ let sba = 0;
+ for (let i = 0; i < FIT_SAMPLES; i += 1) {
+ const b = (-half + (2 * half * i) / (FIT_SAMPLES - 1)) * RAD;
+ const a = Math.atan2(R * Math.sin(b) - offsetM * Math.sin(phi), R * Math.cos(b) - offsetM * Math.cos(phi)) / RAD;
+ const bd = b / RAD;
+ sb += bd;
+ sa += a;
+ sbb += bd * bd;
+ sba += bd * a;
+ }
+ const n = FIT_SAMPLES;
+ const s = (n * sba - sb * sa) / (n * sbb - sb * sb);
+ const a0 = (sa - s * sb) / n;
+ const { view } = manifest;
+ return {
+ scale: s,
+ shiftPx: win.plane.scale * view.pxPerDegH * (a0 - s * (headingDeg - view.lookAzDeg)),
+ };
}
/**
- * Where each card goes on a viewport: the single owner of pan reach and heading range (ruling ridge-camera-on-circle). The heading is the baker's
- * `headingMaxDeg` unless a card could no longer cover the viewport at it, so it is capped by the card that would uncover first: card i is `scale` times
- * wider on screen, and shown at heading delta d it needs `half viewport / scale + d x pxPerDegH` of its half width. Card i pans `scale` x heading x
- * `pxPerDegH` plane pixels, at the plane's scale. One scale per card on both axes; nothing is reprojected inside a card (ruling ridge-cards-per-card-slide).
+ * The compass azimuths, unwrapped, of the card columns a pose puts on a viewport `viewportW` px wide: a column at `az` lands at `shiftPx + scale x (az - rest)
+ * x px per degree` from the centre. This is the arc the loader must hold for that card.
*/
-export function cardMotion(m: CardRig, win: Window): CardMotion {
- const half = (win.plane.w - 2 * win.driftPx) / (2 * win.plane.scale); // half the viewport, in plane px
- const cap = Math.min(
- ...m.cards.map((c) => (m.view.planeW / 2 - half / c.scale) / m.view.pxPerDegH)
- );
- const headingDeg = Math.max(0, Math.min(m.camera.headingMaxDeg, cap));
+export function cardArc(
+ view: View,
+ win: Window,
+ viewportW: number,
+ pose: CardPose
+): { fromDeg: number; toDeg: number } {
+ const per = pose.scale * win.plane.scale * view.pxPerDegH;
return {
- headingDeg,
- cards: m.cards.map((c) => ({
- scale: c.scale,
- reachPx: c.scale * headingDeg * m.view.pxPerDegH * win.plane.scale,
- })),
+ fromDeg: view.lookAzDeg + (-viewportW / 2 - pose.shiftPx) / per,
+ toDeg: view.lookAzDeg + (viewportW / 2 - pose.shiftPx) / per,
};
}
+
+/** How often the pose is sampled to find the arc a stretch of motion passes over, seconds: finer than the rig's keyframe a second, so no swing between two keyframes is missed. */
+const SWEEP_STEP_S = 0.25;
+
+/**
+ * The arc of azimuth any of `cards` cards shows at any instant of the `seconds` after `t0` (ms), by `poseAt(card, ms)`: the union of `cardArc` over the whole
+ * stretch, not its ends. A pose is not monotone in time (offset-only rotation carries the nearest card out and back as the camera circles), so a card's reach
+ * peaks mid-stretch, and the tiles it needs there are the ones to mount and to ask the loader for.
+ */
+export function sweepArc(
+ view: View,
+ win: Window,
+ viewportW: number,
+ cards: number,
+ poseAt: (card: number, ms: number) => CardPose,
+ t0: number,
+ seconds: number = SEGMENT_S
+): { fromDeg: number; toDeg: number } {
+ let fromDeg = Infinity;
+ let toDeg = -Infinity;
+ const steps = Math.ceil(seconds / SWEEP_STEP_S);
+ for (let n = 0; n <= steps; n += 1) {
+ const t = t0 + Math.min(seconds, n * SWEEP_STEP_S) * 1000;
+ for (let i = 0; i < cards; i += 1) {
+ const a = cardArc(view, win, viewportW, poseAt(i, t));
+ fromDeg = Math.min(fromDeg, a.fromDeg);
+ toDeg = Math.max(toDeg, a.toDeg);
+ }
+ }
+ return { fromDeg, toDeg };
+}
diff --git a/src/app/features/scene/sceneDrawn.test.ts b/src/app/features/scene/sceneDrawn.test.ts
index 5e51f7ce..9e555cad 100644
--- a/src/app/features/scene/sceneDrawn.test.ts
+++ b/src/app/features/scene/sceneDrawn.test.ts
@@ -1,6 +1,7 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import {
SCENE_ACTIVE_ATTRIBUTE,
+ getDrawnSky,
getSceneDrawn,
setSceneDrawn,
subscribeSceneDrawn,
@@ -34,4 +35,20 @@ describe('sceneDrawn: one store owns the flag and html[data-scene]', () => {
setSceneDrawn(true);
expect(cb).toHaveBeenCalledTimes(2);
});
+
+ it('owns the sky the scene that is up draws: set with the scene, told to subscribers when it changes, gone with the scene', () => {
+ const cb = vi.fn();
+ const off = subscribeSceneDrawn(cb);
+ expect(getDrawnSky()).toBeUndefined();
+ setSceneDrawn(true, 'day');
+ expect(getDrawnSky()).toBe('day');
+ setSceneDrawn(true, 'day');
+ expect(cb).toHaveBeenCalledTimes(1);
+ setSceneDrawn(true, 'night'); // a rebuilt scene replaced the one shown
+ expect(getDrawnSky()).toBe('night');
+ expect(cb).toHaveBeenCalledTimes(2);
+ setSceneDrawn(false, 'night'); // no scene draws no sky
+ expect(getDrawnSky()).toBeUndefined();
+ off();
+ });
});
diff --git a/src/app/features/scene/sceneDrawn.ts b/src/app/features/scene/sceneDrawn.ts
index ae7e47e0..b1a98875 100644
--- a/src/app/features/scene/sceneDrawn.ts
+++ b/src/app/features/scene/sceneDrawn.ts
@@ -1,16 +1,22 @@
-// Whether a background scene is drawing a sky right now. BackgroundScene is the only writer: it sets this when the
-// ridge scene starts, and clears it when the scene stops, fails to start, or loses its WebGL context (a restored
-// context sets it again). This store also owns html[data-scene], so the attribute the CSS reads and the flag the theme
-// hooks read cannot disagree. The configured tier only says a scene may run; this says one does.
+// Whether a background scene is drawing a sky right now, and which sky (day, dusk or night) the scene that is up draws. BackgroundScene is the only
+// writer: it sets this when a scene is up (told the band of the scene it shows, so a rebuild still loading changes nothing here until it replaces it),
+// and clears it when the scene stops, fails to start, or loses its WebGL context (a restored context sets it again). The page theme and ink follow
+// this sky, never the band the clock or the choice announces (ruling ink-follows-drawn-sky). This store also owns html[data-scene], so the attribute
+// the CSS reads and the flag the theme hooks read cannot disagree. The configured tier only says a scene may run; this says one does.
+import type { FixedSkyState } from './ridge/skyMoment';
/** Set on while a scene is drawn, so signed-out screens can let it show through. */
export const SCENE_ACTIVE_ATTRIBUTE = 'data-scene';
let drawn = false;
+let drawnSky: FixedSkyState | undefined;
const listeners = new Set<() => void>();
export const getSceneDrawn = (): boolean => drawn;
+/** The sky the scene that is up draws; undefined with no scene, or a scene whose sky is not known. */
+export const getDrawnSky = (): FixedSkyState | undefined => drawnSky;
+
export const subscribeSceneDrawn = (cb: () => void): (() => void) => {
listeners.add(cb);
return () => {
@@ -18,12 +24,14 @@ export const subscribeSceneDrawn = (cb: () => void): (() => void) => {
};
};
-export function setSceneDrawn(on: boolean): void {
+export function setSceneDrawn(on: boolean, sky?: FixedSkyState): void {
if (typeof document !== 'undefined') {
if (on) document.documentElement.setAttribute(SCENE_ACTIVE_ATTRIBUTE, '');
else document.documentElement.removeAttribute(SCENE_ACTIVE_ATTRIBUTE);
}
- if (on === drawn) return;
+ const next = on ? sky : undefined;
+ if (on === drawn && next === drawnSky) return;
drawn = on;
+ drawnSky = next;
[...listeners].forEach((cb) => cb());
}
diff --git a/src/app/features/scene/skyForState.test.ts b/src/app/features/scene/skyForState.test.ts
index 12bf7519..8523443a 100644
--- a/src/app/features/scene/skyForState.test.ts
+++ b/src/app/features/scene/skyForState.test.ts
@@ -1,81 +1,132 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { FALLBACK_VIEW } from './ridge/view';
import { ELSEWHERE_VIEW } from './ridge/manifest.fixture';
-import { atStandardTime } from './standardTime.testkit';
-import { ridgeDrawn, ridgeSkyFor, ridgeSkyKey, loadWeather } from './skyForState';
-import { DAY_FROM, setSkyClock } from './skyState';
+import { atSolarTime } from './ridge/skyTestkit';
+import { CLEAR_SKY, ridgeDrawn, ridgeSkyFor, ridgeSkyKey, loadWeather } from './skyForState';
+import { setSkyClock } from './skyState';
+import { DAY_FROM } from './ridge/skyMoment';
+import type { SkyChoice } from './ridge/skyMoment';
import { BUDGET } from './ridge/toneMap';
+import { ridgeWeather, setFedWeather } from './ridge/weather';
-const STATES = ['day', 'dusk', 'night'] as const;
+const auto: SkyChoice = { kind: 'auto' };
+const named = (id: 'dawn' | 'morning' | 'noon' | 'golden' | 'dusk' | 'night'): SkyChoice => ({
+ kind: 'named',
+ id,
+});
+const BANDS = [
+ ['day', named('noon')],
+ ['dusk', named('dusk')],
+ ['night', named('night')],
+] as const;
afterEach(() => {
setSkyClock();
+ setFedWeather(undefined);
vi.unstubAllGlobals();
});
describe('ridgeSkyFor', () => {
- it('carries the physical sky of the state', () => {
- for (const state of STATES) {
- const sky = ridgeSkyFor(state, FALLBACK_VIEW, 0.3);
- expect(sky.physical?.state).toBe(state);
- expect(sky.physical?.stops).toEqual({ top: sky.top, mid: sky.mid, horizon: sky.horizon });
- }
+ it.each(BANDS)('carries the physical sky of the %s moment', (band, choice) => {
+ const sky = ridgeSkyFor(choice, FALLBACK_VIEW, 0.3);
+ expect(sky.physical?.state).toBe(band);
+ expect(sky.physical?.stops).toEqual({ top: sky.top, mid: sky.mid, horizon: sky.horizon });
});
- it('draws the sky auto resolves to, never nothing', () => {
- const key = (s: ReturnType) => [
- s.top,
- s.mid,
- s.horizon,
- s.physical?.sun,
- ];
- setSkyClock(() => atStandardTime(12, 0));
- expect(key(ridgeSkyFor('auto', FALLBACK_VIEW, 0.3))).toEqual(key(ridgeSkyFor('day', FALLBACK_VIEW, 0.3)));
- setSkyClock(() => atStandardTime(0, 0));
- expect(key(ridgeSkyFor('auto', FALLBACK_VIEW, 0.3))).toEqual(key(ridgeSkyFor('night', FALLBACK_VIEW, 0.3)));
- setSkyClock(() => atStandardTime(18, 10));
- expect(key(ridgeSkyFor('auto', FALLBACK_VIEW, 0.3))).toEqual(key(ridgeSkyFor('dusk', FALLBACK_VIEW, 0.3)));
+ it('Auto draws the real sun now, never nothing', () => {
+ const key = (s: ReturnType) => [s.top, s.mid, s.horizon, s.physical?.sun.time];
+ const noon = atSolarTime(12, 0);
+ expect(key(ridgeSkyFor(auto, FALLBACK_VIEW, 0.3, noon))[3]).toEqual(noon);
+ expect(ridgeSkyFor(auto, FALLBACK_VIEW, 0.3, noon).physical?.state).toBe('day');
+ expect(ridgeSkyFor(auto, FALLBACK_VIEW, 0.3, atSolarTime(0, 0)).physical?.state).toBe('night');
+ expect(ridgeSkyFor(auto, FALLBACK_VIEW, 0.3, atSolarTime(18, 10)).physical?.state).toBe('dusk');
});
- it("is lit from the real sun over Vienna: a forced state's sun is inside the state, the clear noon sky is blue", () => {
- const day = ridgeSkyFor('day', FALLBACK_VIEW, 0);
+ it("is lit from the real sun over Vienna: a moment's sun is inside its band, the clear noon sky is blue", () => {
+ const day = ridgeSkyFor(named('noon'), FALLBACK_VIEW, 0);
expect(day.physical?.sun.elevation).toBeGreaterThanOrEqual(DAY_FROM);
expect(day.top[2]).toBeGreaterThan(day.top[0]);
- const dusk = ridgeSkyFor('dusk', FALLBACK_VIEW, 0);
- expect(Math.abs(dusk.physical?.sun.elevation ?? 99)).toBeLessThanOrEqual(DAY_FROM);
- expect(ridgeSkyFor('night', FALLBACK_VIEW, 0).physical?.sun.elevation).toBeLessThanOrEqual(-DAY_FROM);
+ expect(Math.abs(ridgeSkyFor(named('dusk'), FALLBACK_VIEW, 0).physical?.sun.elevation ?? 99)).toBeLessThanOrEqual(DAY_FROM);
+ expect(ridgeSkyFor(named('night'), FALLBACK_VIEW, 0).physical?.sun.elevation).toBeLessThanOrEqual(-DAY_FROM);
+ });
+
+ it('a free moment is lit from the sun of its own date', () => {
+ const sky = ridgeSkyFor({ kind: 'free', date: '2026-07-15', minutes: 13 * 60 }, FALLBACK_VIEW);
+ expect(sky.physical?.sun.time.toISOString()).toBe('2026-07-15T11:00:00.000Z');
+ expect(sky.physical?.state).toBe('day');
});
it("is made over the View's place: the sun and the observer are the View's", () => {
- const sky = ridgeSkyFor('day', ELSEWHERE_VIEW, 0);
+ const sky = ridgeSkyFor(named('noon'), ELSEWHERE_VIEW, 0);
expect(sky.physical?.view).toBe(ELSEWHERE_VIEW);
expect(sky.physical?.atm.observerKm).toBe(ELSEWHERE_VIEW.place.altitudeKm);
});
- it("keys a rebuild by the View's place as well: another place is another key", () => {
- const other = { ...FALLBACK_VIEW, place: { ...FALLBACK_VIEW.place, id: 'graz' } };
- expect(ridgeSkyKey('day', FALLBACK_VIEW, 0.3)).not.toBe(ridgeSkyKey('day', other, 0.3));
- expect(ridgeSkyKey('day', other, 0.3)).toContain('graz');
- });
-
- it('keys a rebuild by state and weather, not by the moving sun', () => {
- setSkyClock(() => atStandardTime(12, 0));
- expect(ridgeSkyKey('auto', FALLBACK_VIEW, 0.3)).toBe(ridgeSkyKey('day', FALLBACK_VIEW, 0.3));
- expect(ridgeSkyKey('day', FALLBACK_VIEW, 0.3)).not.toBe(ridgeSkyKey('day', FALLBACK_VIEW, 0.8));
- expect(ridgeSkyKey('day', FALLBACK_VIEW, 0.3)).not.toBe(ridgeSkyKey('night', FALLBACK_VIEW, 0.3));
- });
-
- // Each state's ceiling is its budget's (night's is a tunable, NIGHT_CEILING: the operator tunes it by eye).
- it.each(STATES)('%s: the display is the curve of its budget: black lift at the floor, and its ceiling', (state) => {
- const r = ridgeDrawn(state);
- expect(r.darkest).toBe(BUDGET[state].floor);
- expect(r.lightest).toBeLessThanOrEqual(BUDGET[state].ceiling);
- const fit = ridgeSkyFor(state, FALLBACK_VIEW, 0.3).physical?.fit;
+ // Each band's ceiling is its budget's (night's is a tunable, NIGHT_CEILING: the operator tunes it by eye).
+ it.each(BANDS)('%s: the display is the curve of its budget: black lift at the floor, and its ceiling', (band, choice) => {
+ const r = ridgeDrawn(band);
+ expect(r.darkest).toBe(BUDGET[band].floor);
+ expect(r.lightest).toBeLessThanOrEqual(BUDGET[band].ceiling);
+ const fit = ridgeSkyFor(choice, FALLBACK_VIEW, 0.3).physical?.fit;
expect(fit?.lo).toBeGreaterThanOrEqual(r.darkest - 1e-9);
expect(fit?.hi).toBeLessThanOrEqual(r.lightest + 1e-9);
});
});
+describe('ridgeSkyKey', () => {
+ const noonNow = atSolarTime(12, 0);
+
+ it("keys a rebuild by the View's place as well: another place is another key", () => {
+ const other = { ...FALLBACK_VIEW, place: { ...FALLBACK_VIEW.place, id: 'graz' } };
+ expect(ridgeSkyKey(named('noon'), FALLBACK_VIEW, 0.3, noonNow)).not.toBe(ridgeSkyKey(named('noon'), other, 0.3, noonNow));
+ expect(ridgeSkyKey(named('noon'), other, 0.3, noonNow)).toContain('graz');
+ });
+
+ it('differs between Auto-at-day and Noon: live against frozen', () => {
+ expect(ridgeSkyKey(auto, FALLBACK_VIEW, 0.3, noonNow)).not.toBe(ridgeSkyKey(named('noon'), FALLBACK_VIEW, 0.3, noonNow));
+ });
+
+ it('is equal for one named moment across two calls on one local date, and changes with the weather and the moment', () => {
+ const a = ridgeSkyKey(named('noon'), FALLBACK_VIEW, 0.3, atSolarTime(9, 0));
+ expect(ridgeSkyKey(named('noon'), FALLBACK_VIEW, 0.3, atSolarTime(21, 0))).toBe(a);
+ expect(ridgeSkyKey(named('noon'), FALLBACK_VIEW, 0.8, noonNow)).not.toBe(a);
+ expect(ridgeSkyKey(named('night'), FALLBACK_VIEW, 0.3, noonNow)).not.toBe(a);
+ expect(ridgeSkyKey(named('noon'), FALLBACK_VIEW, 0.3, new Date(noonNow.getTime() + 24 * 3_600_000))).not.toBe(a);
+ });
+
+ it('changes with the free date or minutes', () => {
+ const k = (date: string, minutes: number) => ridgeSkyKey({ kind: 'free', date, minutes }, FALLBACK_VIEW, 0, noonNow);
+ expect(k('2026-07-15', 300)).not.toBe(k('2026-07-16', 300));
+ expect(k('2026-07-15', 300)).not.toBe(k('2026-07-15', 305));
+ expect(k('2026-07-15', 300)).toBe(k('2026-07-15', 300));
+ });
+
+ it('is stable under the minute tick inside a band (Auto)', () => {
+ const at = (m: number) => ridgeSkyKey(auto, FALLBACK_VIEW, 0.3, new Date(atSolarTime(11, 0).getTime() + m * 60_000));
+ expect(at(0)).toBe(at(1));
+ expect(at(0)).toBe(at(90));
+ });
+});
+
+describe('the weather of a moment', () => {
+ it('a free moment draws a clear sky whatever the feed holds; Auto and the named moments draw the feed', () => {
+ setFedWeather(0.9);
+ expect(ridgeWeather()).toBe(0.9);
+ const noonNow = atSolarTime(12, 0);
+ const free: SkyChoice = { kind: 'free', date: '2026-07-15', minutes: 13 * 60 };
+ expect(ridgeSkyFor(free, FALLBACK_VIEW, undefined, noonNow).physical?.weather).toEqual(
+ ridgeSkyFor(free, FALLBACK_VIEW, CLEAR_SKY, noonNow).physical?.weather
+ );
+ expect(ridgeSkyKey(free, FALLBACK_VIEW, undefined, noonNow)).toContain(`:${CLEAR_SKY}:`);
+ for (const choice of [auto, named('noon')]) {
+ expect(ridgeSkyKey(choice, FALLBACK_VIEW, undefined, noonNow)).toContain(':0.9:');
+ expect(ridgeSkyFor(choice, FALLBACK_VIEW, undefined, noonNow).physical?.weather).toEqual(
+ ridgeSkyFor(choice, FALLBACK_VIEW, 0.9, noonNow).physical?.weather
+ );
+ }
+ });
+});
+
describe('loadWeather', () => {
it('reads the file again for another place inside the refresh window: the weather it set belongs to the sun of the place it was read for', async () => {
const fetched = vi.fn(async () => ({ ok: false, status: 404, json: async () => ({}) }));
@@ -92,15 +143,16 @@ describe('loadWeather', () => {
describe('the rebuild key and the constellation lines', () => {
it('carries the lines at night only: toggling them is a different sky, a day sky is the same', async () => {
- vi.stubGlobal('localStorage', { getItem: () => null, setItem: () => undefined });
+ vi.stubGlobal('localStorage', { getItem: () => null, setItem: () => undefined, removeItem: () => undefined });
vi.resetModules();
const st = await import('./skyState');
const f = await import('./skyForState');
- const off = f.ridgeSkyKey('night', FALLBACK_VIEW, 0);
- const dayOff = f.ridgeSkyKey('day', FALLBACK_VIEW, 0);
- st.pickSkyState('night');
- st.pickSkyState('night');
- expect(f.ridgeSkyKey('night', FALLBACK_VIEW, 0)).toBe(`${off}:lines`);
- expect(f.ridgeSkyKey('day', FALLBACK_VIEW, 0)).toBe(dayOff);
+ const now = atSolarTime(12, 0);
+ const off = f.ridgeSkyKey(named('night'), FALLBACK_VIEW, 0, now);
+ const dayOff = f.ridgeSkyKey(named('noon'), FALLBACK_VIEW, 0, now);
+ st.pickSkyChoice(named('night'));
+ st.pickSkyChoice(named('night'));
+ expect(f.ridgeSkyKey(named('night'), FALLBACK_VIEW, 0, now)).toBe(`${off}:lines`);
+ expect(f.ridgeSkyKey(named('noon'), FALLBACK_VIEW, 0, now)).toBe(dayOff);
});
});
diff --git a/src/app/features/scene/skyForState.ts b/src/app/features/scene/skyForState.ts
index 988c7dee..75dc28c1 100644
--- a/src/app/features/scene/skyForState.ts
+++ b/src/app/features/scene/skyForState.ts
@@ -1,27 +1,36 @@
-// What the ridge scene is told for a sky state. 'auto' is a choice, not a sky: it draws the sky it
-// resolves to (`resolveSkyState`, the clock), so the scene paints one of day, dusk or night, fitted to that
-// state's luminance budget (ridge/toneMap.ts).
+// What the ridge scene is told for a sky choice. The choice is not a sky: `momentFor` (ridge/skyMoment.ts) decides the instant it draws,
+// the sun at that instant is what the physical sky is lit from, and its band (`skyBand`) picks the display's luminance budget (ridge/toneMap.ts).
import type { SkyColours } from './ridge/skyColour';
import { makePhysicalSky } from './ridge/physicalSky';
+import { momentFor, momentKey, skyBand } from './ridge/skyMoment';
+import type { FixedSkyState, SkyChoice } from './ridge/skyMoment';
+import { sunAt } from './ridge/sunAt';
import type { Place, View } from './ridge/view';
import { BUDGET } from './ridge/toneMap';
import { ridgeWeather, setFedWeather } from './ridge/weather';
import { currentWeather, fetchWeatherFile } from './ridge/weatherFeed';
-import { getConstellationLines, resolveSkyState, skyNow } from './skyState';
-import type { SkyState } from './skyState';
+import { getConstellationLines, skyNow } from './skyState';
+
+/** A clear sky: what a free moment is drawn with (ruling ridge-weather-on-frozen-moments: today's weather says nothing of another date). */
+export const CLEAR_SKY = 0;
+
+/** The weather a choice is drawn with: a free moment is clear; Auto and the named moments of today draw today's weather. */
+const weatherFor = (choice: SkyChoice): number =>
+ choice.kind === 'free' ? CLEAR_SKY : ridgeWeather();
/**
- * What a rebuild of the ridge scene is for: the fixed state it draws, the weather and, at night, the constellation lines. The sun moves with the clock inside a state and
- * is not part of the key (the scene is baked at its start), as the sky was one gradient per state before.
+ * What a rebuild of the ridge scene is for: the band and moment it draws, the weather, the place and, at night, the constellation lines.
+ * The sun moves with the clock inside an Auto band and is not part of the key (the scene is baked at its start); a named moment is its id
+ * and local date, a free one its date and minutes.
*/
export const ridgeSkyKey = (
- state: SkyState,
+ choice: SkyChoice,
view: View,
- weather: number = ridgeWeather(),
+ weather: number = weatherFor(choice),
now: Date = skyNow()
): string => {
- const fixed = resolveSkyState(state, now);
- return `ridge:${fixed}:${weather}:${view.place.id}${fixed === 'night' && getConstellationLines() ? ':lines' : ''}`;
+ const band = skyBand(sunAt(view.place, momentFor(choice, view.place, now)).elevation);
+ return `ridge:${band}:${weather}:${view.place.id}:${momentKey(choice, view.place, now)}${band === 'night' && getConstellationLines() ? ':lines' : ''}`;
};
const WEATHER_REFRESH_MS = 10 * 60_000;
@@ -39,18 +48,17 @@ export async function loadWeather(url: string, place: Place, now: Date = skyNow(
}
/**
- * The ridge scene's `sky` option: the physical sky over the View's place for the state ('auto': the real sun now; a forced state: the
- * sun of today at a moment inside it, `sunForState`), as a palette for the layers and stars plus the `physical` sky the host canvas
+ * The ridge scene's `sky` option: the physical sky over the View's place at the instant the choice draws (`momentFor`: Auto the real sun now,
+ * a named or free moment its own), as a palette for the layers and stars plus the `physical` sky the host canvas
* is painted from. The atmosphere LUTs are baked here, once per scene start (tens of ms).
*/
export function ridgeSkyFor(
- state: SkyState,
+ choice: SkyChoice,
view: View,
- weather: number = ridgeWeather(),
+ weather: number = weatherFor(choice),
now: Date = skyNow()
): SkyColours {
- const fixed = resolveSkyState(state, now);
- const physical = makePhysicalSky(fixed, now, weather, view);
+ const physical = makePhysicalSky(sunAt(view.place, momentFor(choice, view.place, now)), weather, view);
return {
...physical.stops,
physical,
@@ -67,8 +75,7 @@ export interface Range {
* The ridge sky's range: what its display is fitted to hold (`BUDGET`, toneMap.ts), which `physicalSky.test.ts` proves over the
* sun's whole year over Vienna. Dark ink needs the floor; light ink the ceiling.
*/
-export function ridgeDrawn(state: SkyState): Range {
- const b = BUDGET[resolveSkyState(state)];
+export function ridgeDrawn(band: FixedSkyState): Range {
+ const b = BUDGET[band];
return { darkest: b.floor, lightest: b.ceiling };
}
-
diff --git a/src/app/features/scene/skyInk.test.ts b/src/app/features/scene/skyInk.test.ts
index 616569f9..edb44929 100644
--- a/src/app/features/scene/skyInk.test.ts
+++ b/src/app/features/scene/skyInk.test.ts
@@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest';
import { baked } from '../../../sky/baked';
import { AA, luminance } from '../../../sky/skyTokens.js';
import { indexColorMXID } from '../../../util/colorMXID';
-import type { FixedSkyState } from './skyState';
+import type { FixedSkyState } from './ridge/skyMoment';
import {
LIGHTEST_PATCH,
NIGHT_INK_MAX_L,
diff --git a/src/app/features/scene/skyInk.ts b/src/app/features/scene/skyInk.ts
index d12d558b..d3aa2028 100644
--- a/src/app/features/scene/skyInk.ts
+++ b/src/app/features/scene/skyInk.ts
@@ -15,7 +15,7 @@ import chroma from 'chroma-js';
import { AA, luminance } from '../../../sky/skyTokens.js';
import { baked } from '../../../sky/baked';
import { indexColorMXID } from '../../../util/colorMXID';
-import type { FixedSkyState } from './skyState';
+import type { FixedSkyState } from './ridge/skyMoment';
import type { SkyThemeId } from './skyTheme';
export interface SkyInk {
@@ -31,9 +31,9 @@ export interface SkyInk {
export const sceneInk = (
themeId: SkyThemeId | undefined,
sceneOn: boolean,
- state: FixedSkyState,
+ state: FixedSkyState | undefined,
phone: boolean
-): SkyInk | undefined => (themeId && sceneOn ? { state, phone } : undefined);
+): SkyInk | undefined => (themeId && sceneOn && state ? { state, phone } : undefined);
/** WCAG relative luminance of the lightest 24x12 patch of terrain behind the timeline. */
export const LIGHTEST_PATCH: Record = {
diff --git a/src/app/features/scene/skyPlace.ts b/src/app/features/scene/skyPlace.ts
new file mode 100644
index 00000000..bf91d708
--- /dev/null
+++ b/src/app/features/scene/skyPlace.ts
@@ -0,0 +1,47 @@
+// The place the sky is over, and the one decision of which place is drawn. The store (skyState.ts) holds the place; this file is the only writer
+// of it: the baked place's manifest, loaded once and shared, when the ridge planes are drawn, and the fallback view (view.ts FALLBACK_VIEW) when
+// they are not (the manifest or its cards did not load), because the scene is then the sky alone over that view. So the sky, the weather, the
+// rebuild key, the ink and the Auto timer all read the place the scene draws. Main-chunk safe: no sky, no ridge code, only the manifest parser,
+// the fallback view and the store.
+import type { BackgroundSceneConfig } from './tier';
+import { loadManifest } from './ridge/manifest';
+import type { RidgeManifest } from './ridge/manifest';
+import { FALLBACK_VIEW } from './ridge/view';
+import type { View } from './ridge/view';
+import { setSkyPlace } from './skyState';
+
+// Set when a build drew the sky alone, so a rebuild key made before the next build is for the view that is drawn.
+let skyOnly = false;
+
+/** A scene start is a fresh attempt at the planes. */
+export function resetSkyPlanes(): void {
+ skyOnly = false;
+}
+
+/**
+ * Load the manifest of the place `config` names (unknown or absent: the index's default, as `loadManifest` decides) and make the view being
+ * drawn the sky's place. Safe to call whenever a reader wants the view: the load is memoised and setting the same place is not a change. A
+ * failed load is the fallback view, returned with its error so the scene can be the sky alone.
+ */
+export async function ensureSkyPlace(
+ config: Pick | undefined
+): Promise<{ manifest: RidgeManifest | null; view: View; fail: Error | null }> {
+ let manifest: RidgeManifest | null = null;
+ let fail: Error | null = null;
+ try {
+ manifest = await loadManifest(import.meta.env.BASE_URL, config?.place);
+ } catch (e) {
+ fail = e instanceof Error ? e : new Error(String(e));
+ }
+ const view = manifest && !skyOnly ? manifest.view : FALLBACK_VIEW;
+ setSkyPlace(view.place);
+ return { manifest, view, fail };
+}
+
+/** A build has settled what it draws: the manifest's planes (the manifest), or the sky alone (null). Makes that view's place the sky's and returns the view. */
+export function drawnView(manifest: RidgeManifest | null): View {
+ skyOnly = manifest === null;
+ const view = manifest?.view ?? FALLBACK_VIEW;
+ setSkyPlace(view.place);
+ return view;
+}
diff --git a/src/app/features/scene/skyState.test.ts b/src/app/features/scene/skyState.test.ts
index a1585f42..73576ed8 100644
--- a/src/app/features/scene/skyState.test.ts
+++ b/src/app/features/scene/skyState.test.ts
@@ -1,12 +1,17 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { atStandardTime } from './standardTime.testkit';
-import {
- SKY_STATE_KEY,
- resolveSkyState,
- type SkyState,
-} from './skyState';
+import { atSolarTime } from './ridge/skyTestkit';
+import { FALLBACK_VIEW } from './ridge/view';
+import { sceneThemeId } from './skyTheme';
+import { SKY_CHOICE_KEY } from './skyState';
+import type { SkyChoice } from './ridge/skyMoment';
type Mod = typeof import('./skyState');
+const VIENNA = FALLBACK_VIEW.place;
+const OLD_KEY = 'ratatoskr.skyState';
+const noon: SkyChoice = { kind: 'named', id: 'noon' };
+const dusk: SkyChoice = { kind: 'named', id: 'dusk' };
+const night: SkyChoice = { kind: 'named', id: 'night' };
+const auto: SkyChoice = { kind: 'auto' };
function fakeStorage(initial: Record = {}) {
const data = new Map(Object.entries(initial));
@@ -16,6 +21,9 @@ function fakeStorage(initial: Record = {}) {
setItem: (k: string, v: string) => {
data.set(k, v);
},
+ removeItem: (k: string) => {
+ data.delete(k);
+ },
};
}
const fresh = (): Promise => {
@@ -27,31 +35,74 @@ afterEach(() => {
vi.unstubAllGlobals();
});
-describe('sky state', () => {
+describe('persistence', () => {
let storage: ReturnType;
beforeEach(() => {
storage = fakeStorage();
vi.stubGlobal('localStorage', storage);
});
- it('defaults to auto when nothing is stored', async () => {
- expect((await fresh()).getSkyState()).toBe('auto');
+ it('defaults to Auto when nothing is stored', async () => {
+ expect((await fresh()).getSkyChoice()).toEqual(auto);
});
- it.each(['night', 'day', 'dusk', 'auto'] as const)('restores a stored %s', async (s) => {
- storage.data.set(SKY_STATE_KEY, s);
- expect((await fresh()).getSkyState()).toBe(s);
- });
-
- it.each(['', 'noon', 'NIGHT', '"night"', 'null'])(
- 'falls back to auto on stored %j',
- async (v) => {
- storage.data.set(SKY_STATE_KEY, v);
- expect((await fresh()).getSkyState()).toBe('auto');
+ it.each([auto, noon, night, { kind: 'free', date: '2026-12-21', minutes: 400 }] as SkyChoice[])(
+ 'restores a stored %j',
+ async (c) => {
+ storage.data.set(SKY_CHOICE_KEY, JSON.stringify(c));
+ expect((await fresh()).getSkyChoice()).toEqual(c);
}
);
- it('falls back to auto when storage throws', async () => {
+ it.each([
+ '',
+ 'night',
+ 'null',
+ '{',
+ JSON.stringify({ kind: 'named', id: 'midday' }),
+ JSON.stringify({ kind: 'named' }),
+ JSON.stringify({ kind: 'free', date: '1899-12-31', minutes: 0 }),
+ JSON.stringify({ kind: 'free', date: '2101-01-01', minutes: 0 }),
+ JSON.stringify({ kind: 'free', date: '2026-02-30', minutes: 0 }),
+ JSON.stringify({ kind: 'free', date: '2026-06-21', minutes: 1440 }),
+ JSON.stringify({ kind: 'free', date: '2026-06-21', minutes: -1 }),
+ JSON.stringify({ kind: 'free', date: '2026-06-21', minutes: 1.5 }),
+ JSON.stringify({ kind: 'free', date: 20260621, minutes: 5 }),
+ ])('reads %j as Auto', async (v) => {
+ storage.data.set(SKY_CHOICE_KEY, v);
+ expect((await fresh()).getSkyChoice()).toEqual(auto);
+ });
+
+ it.each([
+ ['auto', auto],
+ ['day', noon],
+ ['dusk', dusk],
+ ['night', night],
+ ] as const)('migrates the old key %s to %j once, and removes it', async (old, want) => {
+ storage.data.set(OLD_KEY, old);
+ const m = await fresh();
+ expect(m.getSkyChoice()).toEqual(want);
+ expect(storage.data.has(OLD_KEY)).toBe(false);
+ expect(JSON.parse(storage.data.get(SKY_CHOICE_KEY) as string)).toEqual(want);
+ m.setSkyChoice(dusk);
+ expect(storage.data.has(OLD_KEY)).toBe(false);
+ expect((await fresh()).getSkyChoice()).toEqual(dusk);
+ });
+
+ it.each(['noon', 'NIGHT', '', '"night"', 'null'])('ignores the old key holding %j, and removes it', async (old) => {
+ storage.data.set(OLD_KEY, old);
+ expect((await fresh()).getSkyChoice()).toEqual(auto);
+ expect(storage.data.has(OLD_KEY)).toBe(false);
+ });
+
+ it('the new key wins over a stale old one', async () => {
+ storage.data.set(OLD_KEY, 'night');
+ storage.data.set(SKY_CHOICE_KEY, JSON.stringify(dusk));
+ expect((await fresh()).getSkyChoice()).toEqual(dusk);
+ expect(storage.data.has(OLD_KEY)).toBe(false);
+ });
+
+ it('keeps the pick for the page load when storage is refused', async () => {
vi.stubGlobal('localStorage', {
getItem: () => {
throw new Error('denied');
@@ -59,70 +110,154 @@ describe('sky state', () => {
setItem: () => {
throw new Error('denied');
},
+ removeItem: () => {
+ throw new Error('denied');
+ },
});
const m = await fresh();
- expect(m.getSkyState()).toBe('auto');
- m.setSkyState('night');
- expect(m.getSkyState()).toBe('night');
+ expect(m.getSkyChoice()).toEqual(auto);
+ m.setSkyChoice(night);
+ expect(m.getSkyChoice()).toEqual(night);
});
- it('persists a set state under one key and reads it back after a reload', async () => {
- (await fresh()).setSkyState('dusk');
- expect([...storage.data.entries()]).toEqual([[SKY_STATE_KEY, 'dusk']]);
- expect((await fresh()).getSkyState()).toBe('dusk');
+ it('migrates an old pick even when the new key cannot be written: the pick holds for the page load, the old key stays', async () => {
+ storage.data.set(OLD_KEY, 'day');
+ vi.stubGlobal('localStorage', {
+ ...storage,
+ setItem: () => {
+ throw new Error('denied');
+ },
+ });
+ expect((await fresh()).getSkyChoice()).toEqual(noon);
+ expect(storage.data.has(OLD_KEY)).toBe(true);
});
- it('ignores an invalid state', async () => {
+ it('writes the new key before it removes the old one', async () => {
+ storage.data.set(OLD_KEY, 'dusk');
+ const order: string[] = [];
+ vi.stubGlobal('localStorage', {
+ ...storage,
+ setItem: (k: string, v: string) => {
+ order.push(`set ${k}`);
+ storage.data.set(k, v);
+ },
+ removeItem: (k: string) => {
+ order.push(`remove ${k}`);
+ storage.data.delete(k);
+ },
+ });
+ expect((await fresh()).getSkyChoice()).toEqual(dusk);
+ expect(order).toEqual([`set ${SKY_CHOICE_KEY}`, `remove ${OLD_KEY}`]);
+ });
+
+ it('persists a set choice under one key and reads it back after a reload', async () => {
+ (await fresh()).setSkyChoice(dusk);
+ expect([...storage.data.entries()]).toEqual([[SKY_CHOICE_KEY, JSON.stringify(dusk)]]);
+ expect((await fresh()).getSkyChoice()).toEqual(dusk);
+ });
+
+ it('ignores an invalid choice', async () => {
const m = await fresh();
- m.setSkyState('night');
- m.setSkyState('noon' as SkyState);
- expect(m.getSkyState()).toBe('night');
- expect(storage.data.get(SKY_STATE_KEY)).toBe('night');
+ m.setSkyChoice(night);
+ m.setSkyChoice({ kind: 'named', id: 'midday' } as unknown as SkyChoice);
+ expect(m.getSkyChoice()).toEqual(night);
});
it('notifies subscribers on change only, and stops after unsubscribe', async () => {
const m = await fresh();
+ m.setSkyPlace(VIENNA);
const cb = vi.fn();
const off = m.subscribe(cb);
- m.setSkyState('day');
- m.setSkyState('day');
- expect(cb.mock.calls).toEqual([['day']]);
+ m.setSkyChoice(noon);
+ m.setSkyChoice(noon);
+ expect(cb).toHaveBeenCalledTimes(1);
off();
- m.setSkyState('night');
+ m.setSkyChoice(night);
expect(cb).toHaveBeenCalledTimes(1);
});
it('tells a late subscriber nothing until the next change', async () => {
const m = await fresh();
- m.setSkyState('day');
+ m.setSkyChoice(noon);
const cb = vi.fn();
m.subscribe(cb);
expect(cb).not.toHaveBeenCalled();
});
});
-describe('auto follows the clock', () => {
- const local = (h: number, m = 0) => atStandardTime(h, m); // local solar time ~ local clock
- let storage: ReturnType;
+describe('one authority: the choice at the place decides the sky and the ink', () => {
+ let m: Mod;
+ beforeEach(async () => {
+ vi.stubGlobal('localStorage', fakeStorage());
+ m = await fresh();
+ m.setSkyClock(() => atSolarTime(0, 0));
+ });
+
+ it('Noon picked at local midnight is day, and the ink theme is Noonday Sky', () => {
+ m.setSkyPlace(VIENNA);
+ m.setSkyChoice(noon);
+ expect(m.getResolvedSkyState()).toBe('day');
+ expect(sceneThemeId(m.getResolvedSkyState(), true)).toBe('noonday-sky');
+ });
+
+ it('Night picked at noon is night, and the ink theme is Midnight Sky', () => {
+ m.setSkyPlace(VIENNA);
+ m.setSkyClock(() => atSolarTime(12, 0));
+ m.setSkyChoice(night);
+ expect(m.getResolvedSkyState()).toBe('night');
+ expect(sceneThemeId(m.getResolvedSkyState(), true)).toBe('midnight-sky');
+ });
+
+ it('a free moment is its own sky: December at 06:40 Vienna is dusk or night, July at 13:00 day', () => {
+ m.setSkyPlace(VIENNA);
+ m.setSkyChoice({ kind: 'free', date: '2026-12-21', minutes: 6 * 60 + 40 });
+ expect(m.getResolvedSkyState()).toBe('night');
+ m.setSkyChoice({ kind: 'free', date: '2026-07-15', minutes: 13 * 60 });
+ expect(m.getResolvedSkyState()).toBe('day');
+ });
+
+ it('with no place the resolved sky is undefined and the theme is not decided', () => {
+ m.setSkyChoice(noon);
+ expect(m.getResolvedSkyState()).toBeUndefined();
+ expect(sceneThemeId(m.getResolvedSkyState(), true)).toBeUndefined();
+ });
+
+ it('setting the place tells the listeners, once', () => {
+ const cb = vi.fn();
+ m.subscribe(cb);
+ m.setSkyPlace(VIENNA);
+ m.setSkyPlace({ ...VIENNA });
+ expect(cb.mock.calls).toEqual([['night']]);
+ expect(m.getSkyPlace()).toEqual(VIENNA);
+ });
+});
+
+describe('Auto follows the clock', () => {
+ const local = (h: number, m = 0) => atSolarTime(h, m);
beforeEach(() => {
vi.useFakeTimers();
- storage = fakeStorage();
- vi.stubGlobal('localStorage', storage);
+ vi.stubGlobal('localStorage', fakeStorage());
});
afterEach(() => {
vi.useRealTimers();
});
- it('resolves noon to day, midnight to night and the twilight after sunset to dusk', () => {
- expect(resolveSkyState('auto', local(12))).toBe('day');
- expect(resolveSkyState('auto', local(0))).toBe('night');
- expect(resolveSkyState('auto', local(18, 10))).toBe('dusk');
- expect(resolveSkyState('auto', local(5, 50))).toBe('dusk');
- expect(resolveSkyState('day', local(0))).toBe('day');
+ it('is the real sun over the place: noon is day, midnight night and the twilight after sunset dusk', async () => {
+ const m = await fresh();
+ m.setSkyPlace(VIENNA);
+ const at = (t: Date) => {
+ m.setSkyClock(() => t);
+ return m.getResolvedSkyState();
+ };
+ expect(at(local(12))).toBe('day');
+ expect(at(local(0))).toBe('night');
+ expect(at(local(18, 10))).toBe('dusk');
+ expect(at(local(5, 50))).toBe('dusk');
});
it('tells listeners the resolved sky when the clock crosses a boundary, and only then', async () => {
const m = await fresh();
+ m.setSkyPlace(VIENNA);
let now = local(17, 0);
m.setSkyClock(() => now);
const cb = vi.fn();
@@ -139,6 +274,7 @@ describe('auto follows the clock', () => {
it('still tells everyone when a listener comes or goes inside the window before the clock crosses', async () => {
const m = await fresh();
+ m.setSkyPlace(VIENNA);
let now = local(17, 0);
m.setSkyClock(() => now);
const [a, b, late] = [vi.fn(), vi.fn(), vi.fn()];
@@ -155,25 +291,46 @@ describe('auto follows the clock', () => {
offLate();
});
- it('keeps no timer without listeners or when a fixed state is chosen', async () => {
+ it('keeps no timer without listeners or when a free moment is chosen; one timer serves Auto and a named moment', async () => {
const m = await fresh();
const off = m.subscribe(() => undefined);
expect(vi.getTimerCount()).toBe(1);
- m.setSkyState('night');
+ m.setSkyChoice({ kind: 'free', date: '2026-07-01', minutes: 600 });
expect(vi.getTimerCount()).toBe(0);
- m.setSkyState('auto');
+ m.setSkyChoice(night);
+ expect(vi.getTimerCount()).toBe(1);
+ m.setSkyChoice(auto);
expect(vi.getTimerCount()).toBe(1);
off();
expect(vi.getTimerCount()).toBe(0);
});
+ it('a named moment is told again when the place-local day rolls over, once, and not before', async () => {
+ const m = await fresh();
+ m.setSkyPlace(VIENNA);
+ m.setSkyChoice(noon);
+ let now = new Date('2026-06-21T21:30:00Z'); // 23:30 in Vienna
+ m.setSkyClock(() => now);
+ const cb = vi.fn();
+ const off = m.subscribe(cb);
+ vi.advanceTimersByTime(10 * 60_000);
+ expect(cb).not.toHaveBeenCalled();
+ now = new Date('2026-06-21T22:05:00Z'); // 00:05 on the 22nd
+ vi.advanceTimersByTime(60_000);
+ expect(cb).toHaveBeenCalledTimes(1);
+ vi.advanceTimersByTime(60 * 60_000);
+ expect(cb).toHaveBeenCalledTimes(1);
+ off();
+ });
+
it('notifies a change of choice with the resolved sky', async () => {
const m = await fresh();
+ m.setSkyPlace(VIENNA);
m.setSkyClock(() => local(12));
const cb = vi.fn();
m.subscribe(cb);
- m.setSkyState('night');
- m.setSkyState('auto');
+ m.setSkyChoice(night);
+ m.setSkyChoice(auto);
expect(cb.mock.calls).toEqual([['night'], ['day']]);
});
});
@@ -188,40 +345,41 @@ describe('the constellation lines toggle', () => {
it('are off by default, and a first pick of Night is a plain choice that leaves them off', async () => {
const m = await fresh();
expect(m.getConstellationLines()).toBe(false);
- m.pickSkyState('night');
- expect(m.getSkyState()).toBe('night');
+ m.pickSkyChoice(night);
+ expect(m.getSkyChoice()).toEqual(night);
expect(m.getConstellationLines()).toBe(false);
});
it('re-picking Night while the choice is Night toggles them, tells the listeners, and keeps the choice', async () => {
const m = await fresh();
- m.pickSkyState('night');
+ m.setSkyPlace(VIENNA);
+ m.pickSkyChoice(night);
const cb = vi.fn();
m.subscribe(cb);
- m.pickSkyState('night');
+ m.pickSkyChoice(night);
expect(m.getConstellationLines()).toBe(true);
expect(cb.mock.calls).toEqual([['night']]);
- expect(m.getSkyState()).toBe('night');
- m.pickSkyState('night');
+ expect(m.getSkyChoice()).toEqual(night);
+ m.pickSkyChoice(night);
expect(m.getConstellationLines()).toBe(false);
expect(cb).toHaveBeenCalledTimes(2);
});
- it('are not toggled by re-picking any other state, nor by picking Night from Auto that resolves to night', async () => {
+ it('are not toggled by re-picking any other choice, nor by picking Night from Auto that is drawing night', async () => {
const m = await fresh();
- m.pickSkyState('day');
- m.pickSkyState('day');
+ m.pickSkyChoice(noon);
+ m.pickSkyChoice(noon);
expect(m.getConstellationLines()).toBe(false);
m.setSkyClock(() => new Date('2026-12-04T00:00:00Z'));
- m.pickSkyState('auto');
- m.pickSkyState('night');
+ m.pickSkyChoice(auto);
+ m.pickSkyChoice(night);
expect(m.getConstellationLines()).toBe(false);
});
it('persist per viewer, and come back from storage', async () => {
const m = await fresh();
- m.pickSkyState('night');
- m.pickSkyState('night');
+ m.pickSkyChoice(night);
+ m.pickSkyChoice(night);
expect(storage.data.get(m.SKY_LINES_KEY)).toBe('on');
const again = await fresh();
expect(again.getConstellationLines()).toBe(true);
@@ -235,11 +393,14 @@ describe('the constellation lines toggle', () => {
setItem: () => {
throw new Error('denied');
},
+ removeItem: () => {
+ throw new Error('denied');
+ },
});
const m = await fresh();
expect(m.getConstellationLines()).toBe(false);
- m.pickSkyState('night');
- m.pickSkyState('night');
+ m.pickSkyChoice(night);
+ m.pickSkyChoice(night);
expect(m.getConstellationLines()).toBe(true);
});
});
diff --git a/src/app/features/scene/skyState.ts b/src/app/features/scene/skyState.ts
index 1d93b07e..0551b021 100644
--- a/src/app/features/scene/skyState.ts
+++ b/src/app/features/scene/skyState.ts
@@ -1,54 +1,73 @@
-// Which sky the signed-out page is drawn against. The choice is one value, kept in one
-// localStorage key; whoever draws the sky (the scene, the title bar's control) reads it here.
-// 'auto' is a choice, not a sky: it resolves from the clock to day, dusk or night
-// (`resolveSkyState`), and every sky drawn is one of those three.
-import { sunElevation } from '../../../sky/sun.js';
+// Which sky the signed-out page is drawn against: three small stores and the notice that one of them moved. The viewer's choice (Auto, a
+// named moment, a free moment), the place the sky is over, and the constellation lines. They decide nothing: which instant is drawn is
+// `momentFor` and which band it is, `skyBand` (ridge/skyMoment.ts); the resolved sky here is those two applied to the stores.
+import { MOMENT_IDS, FREE_DATE_MAX, FREE_DATE_MIN, isDate, momentFor, momentKey, skyBand } from './ridge/skyMoment';
+import type { FixedSkyState, MomentId, SkyChoice } from './ridge/skyMoment';
+import { sunAt } from './ridge/sunAt';
+import type { Place } from './ridge/view';
-export type SkyState = 'auto' | 'day' | 'dusk' | 'night';
+export const SKY_CHOICE_KEY = 'ratatoskr.skyChoice';
-export const SKY_STATES: readonly SkyState[] = ['auto', 'day', 'dusk', 'night'];
-export const SKY_STATE_KEY = 'ratatoskr.skyState';
+const AUTO: SkyChoice = { kind: 'auto' };
-const isSkyState = (v: unknown): v is SkyState => SKY_STATES.includes(v as SkyState);
+/** A stored value as a choice, or undefined when it is not one (wrong shape, unknown moment, a date outside 1900..2100, minutes outside 0..1439). */
+export function parseSkyChoice(raw: unknown): SkyChoice | undefined {
+ if (typeof raw !== 'object' || raw === null) return undefined;
+ const c = raw as Record;
+ if (c.kind === 'auto') return AUTO;
+ if (c.kind === 'named' && MOMENT_IDS.includes(c.id as MomentId)) {
+ return { kind: 'named', id: c.id as MomentId };
+ }
+ if (
+ c.kind === 'free' &&
+ isDate(c.date) &&
+ c.date >= FREE_DATE_MIN &&
+ c.date <= FREE_DATE_MAX &&
+ Number.isInteger(c.minutes) &&
+ (c.minutes as number) >= 0 &&
+ (c.minutes as number) <= 1439
+ ) {
+ return { kind: 'free', date: c.date, minutes: c.minutes as number };
+ }
+ return undefined;
+}
-function load(): SkyState {
+const same = (a: SkyChoice, b: SkyChoice): boolean => JSON.stringify(a) === JSON.stringify(b);
+
+// The sky menu once held Auto, Day, Dusk and Night under another key. It is read once, here, and removed: Day became Noon.
+const OLD_KEY = 'ratatoskr.skyState';
+const FROM_OLD = new Map([
+ ['auto', AUTO],
+ ['day', { kind: 'named', id: 'noon' }],
+ ['dusk', { kind: 'named', id: 'dusk' }],
+ ['night', { kind: 'named', id: 'night' }],
+]);
+
+function load(): SkyChoice {
try {
- const stored = localStorage.getItem(SKY_STATE_KEY);
- return isSkyState(stored) ? stored : 'auto';
+ const old = localStorage.getItem(OLD_KEY);
+ if (old !== null) {
+ const migrated = FROM_OLD.get(old);
+ if (migrated && localStorage.getItem(SKY_CHOICE_KEY) === null) {
+ try {
+ // The new key first: a refusal leaves the old one in place, and the pick holds for this page load.
+ localStorage.setItem(SKY_CHOICE_KEY, JSON.stringify(migrated));
+ } catch {
+ return migrated;
+ }
+ localStorage.removeItem(OLD_KEY);
+ return migrated;
+ }
+ localStorage.removeItem(OLD_KEY);
+ }
+ const stored = localStorage.getItem(SKY_CHOICE_KEY);
+ return (stored !== null && parseSkyChoice(JSON.parse(stored))) || AUTO;
} catch {
- return 'auto';
+ return AUTO;
}
}
-/**
- * The three skies ever drawn. Each has the luminance band its theme ink needs against bare sky (WCAG relative luminance,
- * the `luminance` of src/sky/skyTokens.js): day, at least 0.2983 (the dark text ink #342d25); dusk, at least 0.4554 (the link
- * #2a4f27); night, at most 0.0931 (the light text ink #aeccff). The ridge scene's display budgets (ridge/toneMap.ts `BUDGET`)
- * sit inside them.
- */
-export type FixedSkyState = 'day' | 'dusk' | 'night';
-
-/** Where the clock puts the sun: the latitude the skies are baked for (src/sky/skyTokens.js MOMENTS), the longitude of this timezone. */
-const LAT = 45;
-/** Sun elevation (degrees) from which it is day, and below the negative of which it is night; between, dusk (dawn included). */
-export const DAY_FROM = 6;
-
let clock: () => Date = () => new Date();
-/** Minutes west of UTC of this timezone's standard time (the larger of its January and July offsets), so daylight saving does not move the sun. */
-export const standardOffsetMinutes = (now: Date): number =>
- Math.max(
- new Date(now.getFullYear(), 0, 1).getTimezoneOffset(),
- new Date(now.getFullYear(), 6, 1).getTimezoneOffset()
- );
-
-/** The fixed sky a choice draws now: itself, or for 'auto' the sky the sun's elevation here calls for. */
-export function resolveSkyState(s: SkyState, now: Date = clock()): FixedSkyState {
- if (s !== 'auto') return s;
- const lon = -standardOffsetMinutes(now) / 4;
- const el = sunElevation(now, LAT, lon) as number;
- if (el >= DAY_FROM) return 'day';
- return el <= -DAY_FROM ? 'night' : 'dusk';
-}
/** The constellation lines (a hidden extra, ruling ridge-constellation-lines-hidden-extra): on or off, per viewer, off by default. */
export const SKY_LINES_KEY = 'ratatoskr.skyLines';
@@ -66,55 +85,67 @@ export const getConstellationLines = (): boolean => {
return lines;
};
-let current: SkyState | undefined;
-const listeners = new Set<(s: FixedSkyState) => void>();
+let current: SkyChoice | undefined;
+let place: Place | undefined;
+const listeners = new Set<(s: FixedSkyState | undefined) => void>();
let timer: ReturnType | undefined;
let shown: FixedSkyState | undefined;
+let shownKey: string | undefined;
const TICK_MS = 60_000;
/** The choice (what the control shows). */
-export const getSkyState = (): SkyState => {
+export const getSkyChoice = (): SkyChoice => {
current ??= load();
return current;
};
-/** The sky being drawn: the choice, resolved. */
-export const getResolvedSkyState = (): FixedSkyState => resolveSkyState(getSkyState());
+/** The place the sky is over: the loaded manifest's, set by skyPlace.ts; undefined until one is known. */
+export const getSkyPlace = (): Place | undefined => place;
+
+/** The moment the sky is drawn for: the real time, or the test clock. */
+export const skyNow = (): Date => clock();
+
+/** The band being drawn: the choice at the place, through `momentFor` and `skyBand`; undefined until a place is known (no sky is drawn for ink). */
+export const getResolvedSkyState = (): FixedSkyState | undefined =>
+ place && skyBand(sunAt(place, momentFor(getSkyChoice(), place, skyNow())).elevation);
+
+/** What a rebuild would be for, of the moment now drawn (`momentKey`): a named moment's changes when the place-local day rolls over. */
+const drawnKey = (): string | undefined => place && momentKey(getSkyChoice(), place, skyNow());
const emit = () => {
shown = getResolvedSkyState();
- [...listeners].forEach((cb) => cb(shown as FixedSkyState));
+ shownKey = drawnKey();
+ [...listeners].forEach((cb) => cb(shown));
};
-// While anyone listens and the choice is 'auto', one timer checks the clock each minute and tells
-// listeners when the resolved sky changes from the one last told (`shown`, set when telling and when the
-// first listener arrives, never by a later arrival or departure). Otherwise there is no timer.
+// While anyone listens and the choice is Auto or a named moment, one timer checks the clock each minute and tells
+// listeners when the resolved band, or the moment drawn (an Auto band, a named moment's place-local day), changes from the one
+// last told (`shown` and `shownKey`, set when telling and when the first listener arrives, never by a later arrival or departure).
+// A free moment does not move with the clock, so it has no timer.
function sync(): void {
clearTimeout(timer);
timer = undefined;
- if (listeners.size === 0 || getSkyState() !== 'auto') return;
+ if (listeners.size === 0 || getSkyChoice().kind === 'free') return;
const tick = () => {
- if (getResolvedSkyState() !== shown) emit();
+ if (getResolvedSkyState() !== shown || drawnKey() !== shownKey) emit();
timer = setTimeout(tick, TICK_MS);
};
timer = setTimeout(tick, TICK_MS);
}
-/** The moment the sky is drawn for: the real time, or the test clock. */
-export const skyNow = (): Date => clock();
-
/** Replace the clock (tests); no argument restores the real one. */
export function setSkyClock(now?: () => Date): void {
clock = now ?? (() => new Date());
sync();
}
-export function setSkyState(s: SkyState): void {
- if (!isSkyState(s)) return;
- const changed = s !== getSkyState();
- current = s;
+export function setSkyChoice(c: SkyChoice): void {
+ const next = parseSkyChoice(c);
+ if (!next) return;
+ const changed = !same(next, getSkyChoice());
+ current = next;
try {
- localStorage.setItem(SKY_STATE_KEY, s);
+ localStorage.setItem(SKY_CHOICE_KEY, JSON.stringify(next));
} catch {
// Storage is refused (private mode, quota): the choice holds for this page load only.
}
@@ -124,12 +155,22 @@ export function setSkyState(s: SkyState): void {
}
}
+/** The place the sky is over (skyPlace.ts, once the manifest is loaded). Listeners hear it, since the band depends on it. */
+export function setSkyPlace(p: Place | undefined): void {
+ if (p?.id === place?.id && p?.tz === place?.tz && p?.lat === place?.lat && p?.lon === place?.lon) {
+ return;
+ }
+ place = p;
+ emit();
+}
+
/**
- * A pick in the sky menu. Picking a state sets it; picking Night while the choice already is Night toggles the constellation lines, which
+ * A pick in the sky menu. Picking a choice sets it; picking Night while the choice already is Night toggles the constellation lines, which
* listeners hear as a sky change (the scene is rebuilt for it: `ridgeSkyKey` carries the flag).
*/
-export function pickSkyState(s: SkyState): void {
- if (s === 'night' && getSkyState() === 'night') {
+export function pickSkyChoice(c: SkyChoice): void {
+ const now = getSkyChoice();
+ if (c.kind === 'named' && c.id === 'night' && now.kind === 'named' && now.id === 'night') {
lines = !getConstellationLines();
try {
localStorage.setItem(SKY_LINES_KEY, lines ? 'on' : 'off');
@@ -139,12 +180,15 @@ export function pickSkyState(s: SkyState): void {
emit();
return;
}
- setSkyState(s);
+ setSkyChoice(c);
}
-/** Listeners hear the resolved sky: on a change of choice, and while 'auto', when the clock crosses a boundary. */
-export function subscribe(cb: (s: FixedSkyState) => void): () => void {
- if (listeners.size === 0) shown = getResolvedSkyState();
+/** Listeners hear the resolved band: on a change of choice or place, while Auto, when the clock crosses a band, and while a named moment, when the place-local day rolls over. */
+export function subscribe(cb: (s: FixedSkyState | undefined) => void): () => void {
+ if (listeners.size === 0) {
+ shown = getResolvedSkyState();
+ shownKey = drawnKey();
+ }
listeners.add(cb);
sync();
return () => {
diff --git a/src/app/features/scene/skyTheme.test.ts b/src/app/features/scene/skyTheme.test.ts
index c78f3928..cce8a657 100644
--- a/src/app/features/scene/skyTheme.test.ts
+++ b/src/app/features/scene/skyTheme.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, it, vi } from 'vitest';
-import { atStandardTime } from './standardTime.testkit';
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
+import { atSolarTime } from './ridge/skyTestkit';
import { baked } from '../../../sky/baked';
import { AA, contrast } from '../../../sky/skyTokens.js';
import { Editor } from '../../components/editor/Editor.css';
@@ -12,9 +12,14 @@ import { SkyPlate, plateRegions } from './skyPlate.css';
import {
getResolvedSkyState,
setSkyClock,
+ setSkyPlace,
subscribe as subscribeSky,
} from './skyState';
import { sceneThemeId } from './skyTheme';
+import { FALLBACK_VIEW } from './ridge/view';
+
+beforeAll(() => setSkyPlace(FALLBACK_VIEW.place));
+afterAll(() => setSkyPlace(undefined));
const SKY = { 'midnight-sky': baked.midnight, 'noonday-sky': baked.noonday } as const;
const r2 = (n: number) => n.toFixed(2);
@@ -32,7 +37,7 @@ describe('sceneThemeId, the theme the page wears', () => {
it('auto draws the clock sky and that sky decides', () => {
[0, 12, 23].forEach((h) => {
- setSkyClock(() => atStandardTime(h, 10));
+ setSkyClock(() => atSolarTime(h, 10));
expect(sceneThemeId(getResolvedSkyState(), true)).toBe(
h === 12 ? 'noonday-sky' : 'midnight-sky'
);
@@ -40,6 +45,13 @@ describe('sceneThemeId, the theme the page wears', () => {
setSkyClock();
});
+ it('with no place known there is no drawn sky to follow: the theme is not decided', () => {
+ setSkyPlace(undefined);
+ expect(getResolvedSkyState()).toBeUndefined();
+ expect(sceneThemeId(getResolvedSkyState(), true)).toBeUndefined();
+ setSkyPlace(FALLBACK_VIEW.place);
+ });
+
it('with the scene off no sky is drawn, so the person theme stands', () => {
(['day', 'dusk', 'night'] as const).forEach((st) =>
expect(sceneThemeId(st, false)).toBeUndefined()
@@ -49,12 +61,12 @@ describe('sceneThemeId, the theme the page wears', () => {
it('the resolved sky a hook subscribes to changes as the clock crosses, so theme classes follow', () => {
vi.useFakeTimers();
let hour = 12;
- setSkyClock(() => atStandardTime(hour, 10));
- const seen: string[] = [];
+ setSkyClock(() => atSolarTime(hour, 10));
+ const seen: Array = [];
const off = subscribeSky((s) => seen.push(s));
expect(getResolvedSkyState()).toBe('day');
hour = 0;
- setSkyClock(() => atStandardTime(hour, 10));
+ setSkyClock(() => atSolarTime(hour, 10));
vi.advanceTimersByTime(61_000);
expect(seen).toEqual(['night']);
expect(getResolvedSkyState()).toBe('night');
diff --git a/src/app/features/scene/skyTheme.ts b/src/app/features/scene/skyTheme.ts
index fef313ec..8993b127 100644
--- a/src/app/features/scene/skyTheme.ts
+++ b/src/app/features/scene/skyTheme.ts
@@ -1,8 +1,8 @@
-// Which theme the drawn sky lights the page with. While a scene is on, the sky being drawn (the fixed pick, or the
-// clock's state under 'auto'; `useResolvedSkyState`) alone decides the theme and, with it, the ink: Day and Dusk
+// Which theme the drawn sky lights the page with. While a scene is on, the sky being drawn (the
+// scene that is up draws; `useDrawnSky`) alone decides the theme and, with it, the ink: Day and Dusk
// wear Noonday Sky, Night wears Midnight Sky. A person's own theme (the theme menu) stands only where no sky is
// drawn, that is with the scene off.
-import type { FixedSkyState } from './skyState';
+import type { FixedSkyState } from './ridge/skyMoment';
export type SkyThemeId = 'midnight-sky' | 'noonday-sky';
@@ -13,5 +13,7 @@ const BY_STATE: Record = {
};
/** The theme the page wears: the drawn sky's while a scene is on, otherwise none (the person's theme stands). */
-export const sceneThemeId = (resolved: FixedSkyState, sceneOn: boolean): SkyThemeId | undefined =>
- sceneOn ? BY_STATE[resolved] : undefined;
+export const sceneThemeId = (
+ resolved: FixedSkyState | undefined,
+ sceneOn: boolean
+): SkyThemeId | undefined => (sceneOn && resolved ? BY_STATE[resolved] : undefined);
diff --git a/src/app/features/scene/standardTime.testkit.ts b/src/app/features/scene/standardTime.testkit.ts
deleted file mode 100644
index a6966238..00000000
--- a/src/app/features/scene/standardTime.testkit.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import { standardOffsetMinutes } from './skyState';
-
-/** 22 September 2026 at h:m of local solar time as the sky clock reads it (standard time, whatever daylight saving says). */
-export const atStandardTime = (h: number, m = 0): Date => {
- const probe = new Date(2026, 8, 22);
- return new Date(Date.UTC(2026, 8, 22, h, m) + standardOffsetMinutes(probe) * 60000);
-};
diff --git a/src/app/hooks/useSkyState.ts b/src/app/hooks/useSkyState.ts
index 02cde126..e95a8725 100644
--- a/src/app/hooks/useSkyState.ts
+++ b/src/app/hooks/useSkyState.ts
@@ -1,19 +1,17 @@
import { useSyncExternalStore } from 'react';
-import {
- getResolvedSkyState,
- getSkyState,
- subscribe,
- type FixedSkyState,
- type SkyState,
-} from '../features/scene/skyState';
-import { getSceneDrawn, subscribeSceneDrawn } from '../features/scene/sceneDrawn';
+import { getSkyChoice, getSkyPlace, subscribe } from '../features/scene/skyState';
+import type { Place } from '../features/scene/ridge/view';
+import type { FixedSkyState, SkyChoice } from '../features/scene/ridge/skyMoment';
+import { getDrawnSky, getSceneDrawn, subscribeSceneDrawn } from '../features/scene/sceneDrawn';
-/** The choice, as the control shows it ('auto' stays 'auto'). The sky being drawn is `useResolvedSkyState`. */
-export const useSkyState = (): SkyState => useSyncExternalStore(subscribe, getSkyState);
+/** The choice, as the control shows it (Auto stays Auto). The sky being drawn is `useDrawnSky`. */
+export const useSkyChoice = (): SkyChoice => useSyncExternalStore(subscribe, getSkyChoice);
-/** The sky being drawn: day, dusk or night. Unlike the choice it changes as the clock crosses, so it re-renders. */
-export const useResolvedSkyState = (): FixedSkyState =>
- useSyncExternalStore(subscribe, getResolvedSkyState);
+/** The sky the scene that is up draws: day, dusk or night, or undefined with no scene. It moves when a scene replaces the one shown, not when the clock or the choice announces a band the scene has not caught up with. */
+export const useDrawnSky = (): FixedSkyState | undefined => useSyncExternalStore(subscribeSceneDrawn, getDrawnSky);
+
+/** The place the sky is over, or undefined until a scene has settled what it draws (skyPlace.ts). */
+export const useDrawnPlace = (): Place | undefined => useSyncExternalStore(subscribe, getSkyPlace);
/** Whether a background scene is drawing a sky right now (not merely configured): false on a failed or lost context. */
export const useSceneOn = (): boolean => useSyncExternalStore(subscribeSceneDrawn, getSceneDrawn);
diff --git a/src/app/hooks/useTheme.test.ts b/src/app/hooks/useTheme.test.ts
index 5707e5f1..90c543f9 100644
--- a/src/app/hooks/useTheme.test.ts
+++ b/src/app/hooks/useTheme.test.ts
@@ -24,8 +24,8 @@ vi.stubGlobal('window', {
vi.mock('./useSkyState', async () => {
const drawn = await import('../features/scene/sceneDrawn');
return {
- useResolvedSkyState: () => 'night',
- useSkyState: () => 'night',
+ useDrawnSky: () => drawn.getDrawnSky(),
+ useSkyChoice: () => ({ kind: 'named', id: 'night' }),
useSceneOn: () => drawn.getSceneDrawn(),
};
});
@@ -70,7 +70,14 @@ describe('the drawn sky decides the theme and ink; the stored theme stands where
});
it('a scene running over a stored theme wears the sky theme and ink', () => {
- setSceneDrawn(true);
+ setSceneDrawn(true, 'night');
+ expect(read()).toBe('midnight-sky|{"state":"night","phone":false}');
+ });
+
+ it('follows the sky of the scene that is up, whatever the clock or the choice announce, and moves when a scene replaces it', () => {
+ setSceneDrawn(true, 'dusk'); // the choice says night (mocked above); the scene up draws dusk
+ expect(read()).toBe('noonday-sky|{"state":"dusk","phone":false}');
+ setSceneDrawn(true, 'night'); // a rebuilt scene replaced it
expect(read()).toBe('midnight-sky|{"state":"night","phone":false}');
});
@@ -79,10 +86,10 @@ describe('the drawn sky decides the theme and ink; the stored theme stands where
});
it('a restored context wears the sky again', () => {
- setSceneDrawn(true);
+ setSceneDrawn(true, 'night');
setSceneDrawn(false);
expect(read()).toBe('dark-theme|null');
- setSceneDrawn(true);
+ setSceneDrawn(true, 'night');
expect(read()).toBe('midnight-sky|{"state":"night","phone":false}');
});
});
diff --git a/src/app/hooks/useTheme.ts b/src/app/hooks/useTheme.ts
index 69afc382..a66d88d8 100644
--- a/src/app/hooks/useTheme.ts
+++ b/src/app/hooks/useTheme.ts
@@ -14,7 +14,7 @@ import { settingsAtom } from '../state/settings';
import { useSetting } from '../state/hooks/settings';
import { sceneThemeId } from '../features/scene/skyTheme';
import { sceneInk, type SkyInk } from '../features/scene/skyInk';
-import { useResolvedSkyState, useSceneOn } from './useSkyState';
+import { useDrawnSky, useSceneOn } from './useSkyState';
import { ScreenSize, useScreenSizeContext } from './useScreenSize';
export enum ThemeKind {
@@ -109,16 +109,16 @@ const toTheme = (id: ReturnType): Theme | undefined =>
/** The theme the drawn sky asks for while a scene is on, or undefined for none (signed-out pages then wear Midnight Sky). */
export const useSkyTheme = (): Theme | undefined =>
- toTheme(sceneThemeId(useResolvedSkyState(), useSceneOn()));
+ toTheme(sceneThemeId(useDrawnSky(), useSceneOn()));
/** The sky theme the page wears while a scene is on, or undefined when the person's own theme stands. */
const useSceneSkyThemeId = (): ReturnType =>
- sceneThemeId(useResolvedSkyState(), useSceneOn());
+ sceneThemeId(useDrawnSky(), useSceneOn());
/** The ink the page wears over the scene (`sceneInk`, skyInk.ts), or undefined when the theme's own ink stands. */
export const useSceneInk = (): SkyInk | undefined => {
const themeId = useSceneSkyThemeId();
- const state = useResolvedSkyState();
+ const state = useDrawnSky();
const sceneOn = useSceneOn();
const phone = useScreenSizeContext() === ScreenSize.Mobile;
return useMemo(() => sceneInk(themeId, sceneOn, state, phone), [themeId, sceneOn, state, phone]);