diff --git a/src/app/features/scene/index.test.ts b/src/app/features/scene/index.test.ts index f257d3a7..9584bee9 100644 --- a/src/app/features/scene/index.test.ts +++ b/src/app/features/scene/index.test.ts @@ -7,7 +7,6 @@ import { ridgeSkyFor } from './skyForState'; import { forgetManifests } from './ridge/manifest'; import { wireIndex, wireManifest } from './ridge/manifest.fixture'; import { FALLBACK_VIEW } from './ridge/view'; -import { frameChoice } from './ridge/frameChoice'; import { sunAt } from './ridge/sunAt'; import { ridgeWeather } from './ridge/weather'; import { parseWeatherFile, WEATHER_ATTRIBUTION, weatherFromFile } from './ridge/weatherFeed'; @@ -291,428 +290,3 @@ describe('startBackgroundScene follows the sky state', () => { expect(onCompileFail).toHaveBeenCalledWith(boom); }); }); - -describe('the ridge planes', () => { - const served = (over: Record = {}) => { - const files: Record = { - '/public/ridge/index.json': wireIndex, - '/public/ridge/vienna-abc123abc123/manifest.json': wireManifest(), - '/public/ridge/graz-def456def456/manifest.json': wireManifest({ - place: { ...(wireManifest() as any).place, id: 'graz', name: 'Graz' }, - }), - ...over, - }; - vi.stubGlobal( - 'fetch', - vi.fn(async (url: string) => - url in files - ? { ok: true, status: 200, json: async () => files[url] } - : { ok: false, status: 404, json: async () => ({}) } - ) - ); - }; - const images = (reject = false) => { - const loaded: string[] = []; - vi.stubGlobal( - 'Image', - class { - src = ''; - decoding = ''; - cloneNode = () => this; - decode = async () => { - if (reject) throw new Error('bad image'); - loaded.push(this.src); - }; - } - ); - return loaded; - }; - beforeEach(() => forgetManifests()); - - it('hands the scene the planes of the frame the sky was baked for, over the manifest view', async () => { - served(); - const loaded = images(); - createRidgeScene.mockReturnValue(fakeScene()); - const scene = await startBackgroundScene(config, caps, { canvas }); - const opts = createRidgeScene.mock.calls[0][0]; - expect(opts.backdrop.manifest.view.place.id).toBe('vienna'); - expect(opts.sky.physical.view).toBe(opts.backdrop.manifest.view); - // Midnight in Vienna: the night frame, three planes. - expect(loaded.sort()).toEqual([ - '/public/ridge/vienna-abc123abc123/night-far.webp', - '/public/ridge/vienna-abc123abc123/night-mid.webp', - '/public/ridge/vienna-abc123abc123/night-near.webp', - ]); - scene?.dispose(); - }); - - it('config place picks the index entry; an unknown id falls back to the default', async () => { - served(); - images(); - createRidgeScene.mockReturnValue(fakeScene()); - (await startBackgroundScene({ ...config, place: 'graz' }, caps, { canvas }))?.dispose(); - expect(createRidgeScene.mock.calls[0][0].backdrop.manifest.view.place.id).toBe('graz'); - forgetManifests(); - (await startBackgroundScene({ ...config, place: 'nowhere' }, caps, { canvas }))?.dispose(); - expect(createRidgeScene.mock.calls[1][0].backdrop.manifest.view.place.id).toBe('vienna'); - }); - - const skyOnly = async (onPlanesFail = vi.fn(), onCompileFail = vi.fn()) => { - createRidgeScene.mockReturnValue(fakeScene()); - const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onCompileFail }); - const opts = createRidgeScene.mock.calls[0][0]; - expect(scene).not.toBeNull(); - expect(opts.backdrop).toBeUndefined(); - expect(opts.sky.physical.view).toBe(FALLBACK_VIEW); - expect(onPlanesFail).toHaveBeenCalledOnce(); - expect(onCompileFail).not.toHaveBeenCalled(); - scene?.dispose(); - }; - - it('a 404 manifest gives the sky-only scene with the fallback view, one onPlanesFail and no onCompileFail', async () => { - served({ '/public/ridge/index.json': undefined }); - vi.stubGlobal( - 'fetch', - vi.fn(async () => ({ ok: false, status: 404, json: async () => ({}) })) - ); - images(); - await skyOnly(); - }); -}); - -describe('the ridge planes failing', () => { - it('a rejecting image gives the same sky-only scene, and a rebuild does not report again', async () => { - vi.stubGlobal( - 'fetch', - vi.fn(async (url: string) => ({ - ok: true, - status: 200, - json: async () => (url.endsWith('index.json') ? wireIndex : wireManifest()), - })) - ); - vi.stubGlobal( - 'Image', - class { - decode = async () => { - throw new Error('bad image'); - }; - } - ); - forgetManifests(); - createRidgeScene.mockReturnValue(fakeScene()); - const onPlanesFail = vi.fn(); - const onCompileFail = vi.fn(); - const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onCompileFail }); - expect(createRidgeScene.mock.calls[0][0].backdrop).toBeUndefined(); - setSkyState('day'); - await flush(); - expect(createRidgeScene).toHaveBeenCalledTimes(2); - expect(onPlanesFail).toHaveBeenCalledOnce(); - expect(onCompileFail).not.toHaveBeenCalled(); - scene?.dispose(); - }); -}); - -describe('the ridge planes and the live scene', () => { - const serve = (manifest: Record = wireManifest()) => - vi.stubGlobal( - 'fetch', - vi.fn(async (url: string) => ({ - ok: true, - status: 200, - json: async () => (url.endsWith('index.json') ? wireIndex : manifest), - })) - ); - /** Image stub whose decode waits on `gate` (when given) and then resolves or rejects as `outcome` says now. */ - const decoder = () => { - const ctl = { - pending: [] as Array<() => void>, - hold: false, - fail: false, - urls: [] as string[], - }; - vi.stubGlobal( - 'Image', - class { - src = ''; - decoding = ''; - cloneNode = () => this; - decode = () => { - const fails = ctl.fail; // the outcome belongs to the request, whenever it settles - return new Promise((resolve, reject) => { - const settle = () => { - ctl.urls.push(this.src); - if (fails) reject(new Error('bad image')); - else resolve(); - }; - if (ctl.hold) ctl.pending.push(settle); - else settle(); - }); - }; - } - ); - return { - ctl, - release: async () => { - ctl.hold = false; - ctl.pending.splice(0).forEach((s) => s()); - await flush(); - }, - }; - }; - beforeEach(() => forgetManifests()); - - it('says nothing about planes when they load', async () => { - serve(); - decoder(); - createRidgeScene.mockReturnValue(fakeScene()); - const onPlanesFail = vi.fn(); - const onPlanesOk = vi.fn(); - const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onPlanesOk }); - setSkyState('day'); - await flush(); - expect(createRidgeScene).toHaveBeenCalledTimes(2); - expect(createRidgeScene.mock.calls.every((c) => c[0].backdrop)).toBe(true); - expect(onPlanesFail).not.toHaveBeenCalled(); - expect(onPlanesOk).not.toHaveBeenCalled(); - scene?.dispose(); - }); - - it('chooses frames by the sun over the manifest place, not the fallback place', async () => { - const w = wireManifest() as any; - // A day where it is night by the clock, in the south, has the noon sun high and to the north; at Vienna it is low in the south: a different frame. - serve({ ...w, place: { ...w.place, lat: -33, lon: -163.65, tz_h: -11 } }); - decoder(); - setSkyState('day'); - createRidgeScene.mockReturnValue(fakeScene()); - (await startBackgroundScene(config, caps, { canvas }))?.dispose(); - const opts = createRidgeScene.mock.calls[0][0]; - const { manifest } = opts.backdrop; - const own = frameChoice(manifest.frames, opts.sky.physical.sun); - const fallbackSun = ridgeSkyFor('day', FALLBACK_VIEW).physical!.sun; - const theirs = frameChoice(manifest.frames, fallbackSun); - expect(own.a.key).not.toBe(theirs.a.key); - expect(opts.backdrop.choice.a.key).toBe(own.a.key); - expect(opts.backdrop.choice.b?.key ?? null).toBe(own.b?.key ?? null); - }); - - it("keys a rebuild by the manifest's place: the same sky state over a rebaked place rebuilds", async () => { - serve(); - decoder(); - const [a, b] = [fakeScene(), fakeScene()]; - createRidgeScene.mockReturnValueOnce(a).mockReturnValueOnce(b); - const w = wireManifest() as any; - 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'); - await flush(); - expect(createRidgeScene).toHaveBeenCalledOnce(); - forgetManifests(); - serve({ ...w, place: { ...w.place, id: 'graz' } }); - setSkyState('auto'); - await flush(); - expect(createRidgeScene).toHaveBeenCalledTimes(2); - expect(createRidgeScene.mock.calls[1][0].backdrop.manifest.view.place.id).toBe('graz'); - scene?.dispose(); - }); - - it("reads the weather against the manifest place's sun, not the fallback place's", async () => { - const w = wireManifest() as any; - const place = { ...w.place, id: 'weather-place', lat: -33, lon: -163.65, tz_h: -11 }; - const now = new Date('2026-11-11T10:50:00Z'); - const wx = { - fetched_at: '2026-11-11T10:45:00Z', - observed_at: '2026-11-11T10:40:00Z', - station: 11035, - precip_mm_10min: 0, - humidity_pct: 60, - sunshine_s_10min: null, - glow_wm2: 100, - attribution: WEATHER_ATTRIBUTION, - }; - vi.stubGlobal( - 'fetch', - vi.fn(async (url: string) => ({ - ok: true, - status: 200, - json: async () => - url.endsWith('weather.json') ? wx : url.endsWith('index.json') ? wireIndex : { ...w, place }, - })) - ); - decoder(); - setSkyClock(() => now); - createRidgeScene.mockReturnValue(fakeScene()); - (await startBackgroundScene(config, caps, { canvas }))?.dispose(); - const file = parseWeatherFile(wx)!; - 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)).elevation); - expect(at(FALLBACK_VIEW.place)).not.toBe(at(place)); - expect(ridgeWeather()).toBe(at(place)); - }); - - it('a failed load is the sky alone on the fallback view, never the manifest place', async () => { - serve(); - const { ctl } = decoder(); - ctl.fail = true; - createRidgeScene.mockReturnValue(fakeScene()); - const scene = await startBackgroundScene(config, caps, { canvas }); - const opts = createRidgeScene.mock.calls[0][0]; - expect(opts.backdrop).toBeUndefined(); - expect(opts.sky.physical.view).toBe(FALLBACK_VIEW); - scene?.dispose(); - }); - - it('a rebuild keeps the old scene until the new planes have loaded, then swaps', async () => { - serve(); - const d = decoder(); - const first = fakeScene(); - const second = fakeScene(); - createRidgeScene.mockReturnValueOnce(first).mockReturnValueOnce(second); - const onActive = vi.fn(); - const scene = await startBackgroundScene(config, caps, { canvas, onActive }); - d.ctl.hold = true; - setSkyState('day'); - await flush(); - expect(d.ctl.pending.length).toBeGreaterThan(0); - expect(first.dispose).not.toHaveBeenCalled(); - expect(createRidgeScene).toHaveBeenCalledOnce(); - scene?.login(); - expect(first.login).toHaveBeenCalledOnce(); - await d.release(); - expect(createRidgeScene).toHaveBeenCalledTimes(2); - expect(first.dispose).toHaveBeenCalledOnce(); - expect(second.dispose).not.toHaveBeenCalled(); - expect(onActive).toHaveBeenCalledOnce(); - expect(second.login).toHaveBeenCalledOnce(); // replayed onto the swapped-in scene - scene?.dispose(); - expect(second.dispose).toHaveBeenCalledOnce(); - }); - - it('a build that fails after the scene is disposed makes nothing and says nothing', async () => { - serve(); - const d = decoder(); - createRidgeScene.mockReturnValue(fakeScene()); - const onPlanesFail = vi.fn(); - const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail }); - d.ctl.hold = true; - d.ctl.fail = true; - setSkyState('day'); - await flush(); - scene?.dispose(); - await d.release(); - expect(createRidgeScene).toHaveBeenCalledOnce(); - expect(onPlanesFail).not.toHaveBeenCalled(); - }); - - it('a superseded build that fails does not speak for the live scene, which has planes', async () => { - serve(); - const d = decoder(); - createRidgeScene.mockReturnValue(fakeScene()); - const onPlanesFail = vi.fn(); - const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail }); - d.ctl.hold = true; - d.ctl.fail = true; - setSkyState('day'); // stale: its decodes will reject - await flush(); - d.ctl.fail = false; - setSkyState('dusk'); // the live one: its decodes will succeed - await flush(); - const stale = d.ctl.pending.splice(0, 6); - d.ctl.pending.length = 0; - d.ctl.hold = false; - stale.forEach((s) => s()); // the first six are day's, settled in order - await flush(); - expect(onPlanesFail).not.toHaveBeenCalled(); - scene?.dispose(); - }); - - it('a superseded build that finishes after the newer one touches nothing of the live scene', async () => { - serve(); - const d = decoder(); - const [first, second, third] = [fakeScene(), fakeScene(), fakeScene()]; - createRidgeScene.mockReturnValueOnce(first).mockReturnValueOnce(second).mockReturnValueOnce(third); - 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 - await flush(); - const dayDecodes = d.ctl.pending.splice(0); - setSkyState('dusk'); - await flush(); - const duskDecodes = d.ctl.pending.splice(0); - expect(dayDecodes.length).toBeGreaterThan(0); - expect(duskDecodes.length).toBeGreaterThan(0); - duskDecodes.forEach((s) => s()); - await flush(); - expect(createRidgeScene).toHaveBeenCalledTimes(2); - expect(first.dispose).toHaveBeenCalledOnce(); - expect(onActive).toHaveBeenCalledOnce(); - dayDecodes.forEach((s) => s()); // the stale build finishes last - await flush(); - expect(createRidgeScene).toHaveBeenCalledTimes(2); - expect(second.dispose).not.toHaveBeenCalled(); // the live scene is not disposed by a build that lost - expect(onActive).toHaveBeenCalledOnce(); - scene?.login(); - expect(second.login).toHaveBeenCalledOnce(); - scene?.dispose(); - expect(second.dispose).toHaveBeenCalledOnce(); - expect(third.dispose).not.toHaveBeenCalled(); - }); - - it('a build that finishes after dispose makes nothing, shows nothing and disposes nothing twice', async () => { - serve(); - const d = decoder(); - const first = fakeScene(); - createRidgeScene.mockReturnValueOnce(first).mockReturnValueOnce(fakeScene()); - const onActive = vi.fn(); - const scene = await startBackgroundScene(config, caps, { canvas, onActive }); - d.ctl.hold = true; - setSkyState('day'); - await flush(); - scene?.dispose(); - await d.release(); - expect(createRidgeScene).toHaveBeenCalledOnce(); - expect(first.dispose).toHaveBeenCalledOnce(); - expect(onActive).not.toHaveBeenCalled(); - }); - - it('a rebuild that makes no scene says nothing about planes and leaves the host inactive', async () => { - serve(); - const d = decoder(); - 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'); - await flush(); - expect(onInactive).toHaveBeenCalledOnce(); - expect(onPlanesFail).not.toHaveBeenCalled(); - scene?.dispose(); - }); - - it('tells the host when the live scene loses its planes and when it gets them back', async () => { - serve(); - const d = decoder(); - d.ctl.fail = true; - createRidgeScene.mockReturnValue(fakeScene()); - const onPlanesFail = vi.fn(); - 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 - await flush(); - expect(onPlanesFail).toHaveBeenCalledOnce(); - expect(onPlanesOk).not.toHaveBeenCalled(); - d.ctl.fail = false; - setSkyState('dusk'); - await flush(); - expect(onPlanesOk).toHaveBeenCalledOnce(); - expect(createRidgeScene.mock.calls[2][0].backdrop).toBeDefined(); - d.ctl.fail = true; - setSkyState('night'); - await flush(); - expect(onPlanesFail).toHaveBeenCalledTimes(2); - scene?.dispose(); - }); -}); diff --git a/src/app/features/scene/index.ts b/src/app/features/scene/index.ts index 3fe68a95..d4286d69 100644 --- a/src/app/features/scene/index.ts +++ b/src/app/features/scene/index.ts @@ -4,11 +4,9 @@ import { debugOverlaysAllowed } from './debugOverlays'; import { getSkyState, subscribe } from './skyState'; import type { SkyState } from './skyState'; 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 { frameChoice } from './ridge/frameChoice'; export type { Scene, SceneStats } from './Scene'; export type { SceneStyle, SceneTier } from './tier'; @@ -77,32 +75,14 @@ async function prepare( const { createRidgeScene } = await import('./ridge/Ridge'); const { manifest, fail } = await manifestOf(config); await loadWeather(weatherUrl(), (manifest?.view ?? FALLBACK_VIEW).place); - // The planes load with the scene chunk and the weather: createRidgeScene stays synchronous. Any failure is the sky alone. - let backdrop: Backdrop | null = null; + // Every failure is the sky alone: a manifest that did not load or parse (schema 1 included) names itself in `fail`. let sky: SkyColours | undefined; - let planesFail: Error | null = fail; - if (manifest) { - try { - const manifestSky = ridgeSkyFor(state, manifest.view); - sky = manifestSky; - const choice = frameChoice( - manifest.frames, - (manifestSky.physical as NonNullable).sun - ); - const { loadBackdrop } = await import('./ridge/Backdrop'); - backdrop = await loadBackdrop(manifest, choice); - if (!backdrop) throw new Error('ridge planes did not load'); - } catch (e) { - backdrop = null; - sky = undefined; - planesFail = e instanceof Error ? e : new Error(String(e)); - } - } + const planesFail: Error | null = fail; + if (manifest) sky = ridgeSkyFor(state, manifest.view); const made = guarded(() => createRidgeScene({ ...options, sky: sky ?? ridgeSkyFor(state, FALLBACK_VIEW), - backdrop: backdrop ?? undefined, }) ); return { ...made, planesFail }; diff --git a/src/app/features/scene/ridge/Backdrop.test.ts b/src/app/features/scene/ridge/Backdrop.test.ts deleted file mode 100644 index 8c88d46f..00000000 --- a/src/app/features/scene/ridge/Backdrop.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { describe, expect, it, vi } from 'vitest'; -import { loadBackdrop } from './Backdrop'; -import { frameChoice } from './frameChoice'; -import { parseManifest } from './manifest'; -import { wireManifest } from './manifest.fixture'; - -const manifest = parseManifest(wireManifest(), '/d/'); -const img = (src: string) => ({ src } as unknown as HTMLImageElement); - -describe('loadBackdrop', () => { - it('loads the planes of the needed frames only, by manifest directory', async () => { - const load = vi.fn(async (u: string) => img(u)); - const one = await loadBackdrop( - manifest, - frameChoice(manifest.frames, { elevation: 60, azimuth: 180 }), - load - ); - expect(load.mock.calls.map((c) => c[0]).sort()).toEqual([ - '/d/noon-far.webp', - '/d/noon-mid.webp', - '/d/noon-near.webp', - ]); - expect(one?.b).toBeNull(); - load.mockClear(); - const two = await loadBackdrop( - manifest, - frameChoice(manifest.frames, { elevation: 10, azimuth: 130 }), - load - ); - expect(load).toHaveBeenCalledTimes(6); - expect(two?.b?.far.src).toBe('/d/morning-far.webp'); - expect(two?.a.near.src).toBe('/d/dawn-near.webp'); - }); - - it('is null, and does not throw, when any image rejects', async () => { - const load = vi.fn(async (u: string) => { - if (u.includes('mid')) throw new Error('decode'); - return img(u); - }); - await expect( - loadBackdrop(manifest, frameChoice(manifest.frames, { elevation: 60, azimuth: 180 }), load) - ).resolves.toBeNull(); - }); -}); diff --git a/src/app/features/scene/ridge/Backdrop.ts b/src/app/features/scene/ridge/Backdrop.ts deleted file mode 100644 index f1360980..00000000 --- a/src/app/features/scene/ridge/Backdrop.ts +++ /dev/null @@ -1,44 +0,0 @@ -// The decoded planes the scene composes: only the frames the choice needs. Failure is a value (null), never a throw. -import type { FrameChoice } from './frameChoice'; -import type { Frame, PlaneName, RidgeManifest } from './manifest'; -import { PLANE_NAMES } from './manifest'; - -export type Planes = Record; - -export interface Backdrop { - manifest: RidgeManifest; - choice: FrameChoice; - /** Decoded planes of frame a, and of frame b when the choice has one. */ - a: Planes; - b: Planes | null; -} - -export type ImageLoader = (url: string) => Promise; - -/** The browser's decoder: an that has decoded, so the first paint does not wait on it. */ -export const loadImage: ImageLoader = async (url) => { - const img = new Image(); - img.decoding = 'async'; - img.src = url; - await img.decode(); - return img; -}; - -export async function loadBackdrop( - manifest: RidgeManifest, - choice: FrameChoice, - load: ImageLoader = loadImage -): Promise { - const planes = async (f: Frame): Promise => { - const [far, mid, near] = await Promise.all( - PLANE_NAMES.map((n) => load(`${manifest.dir}${f.planes[n]}`)) - ); - return { far, mid, near }; - }; - try { - const [a, b] = await Promise.all([planes(choice.a), choice.b ? planes(choice.b) : null]); - return { manifest, choice, a, b }; - } catch { - return null; - } -} diff --git a/src/app/features/scene/ridge/Ridge.test.ts b/src/app/features/scene/ridge/Ridge.test.ts index b916f59e..52e830db 100644 --- a/src/app/features/scene/ridge/Ridge.test.ts +++ b/src/app/features/scene/ridge/Ridge.test.ts @@ -6,10 +6,7 @@ import type { SkyColours } from './skyColour'; import { makeStars } from './stars'; import { makePhysicalSky, paintSky as paintPhysicalSky } from './physicalSky'; import { startBackgroundScene } from '../index'; -import { frameChoice } from './frameChoice'; -import { parseManifest } from './manifest'; import { ELSEWHERE_VIEW, wireManifest } from './manifest.fixture'; -import type { Backdrop } from './Backdrop'; import { FALLBACK_VIEW, windowFor } from './view'; describe('noise', () => { @@ -525,197 +522,6 @@ describe('rain in the scene', () => { }); }); -describe('the ridge planes in the scene', () => { - const manifest = parseManifest(wireManifest(), '/d/'); - const fakeImg = (src: string) => { - const el = fakeEl('img'); - el.src = src; - el.cloneNode = () => fakeImg(src); - return el as unknown as HTMLImageElement; - }; - const planes = (k: string) => ({ - far: fakeImg(`${k}-far`), - mid: fakeImg(`${k}-mid`), - near: fakeImg(`${k}-near`), - }); - const backdropAt = (elevation: number, azimuth: number): Backdrop => { - const choice = frameChoice(manifest.frames, { elevation, azimuth }); - return { manifest, choice, a: planes(choice.a.key), b: choice.b ? planes(choice.b.key) : null }; - }; - const NOON = backdropAt(60, 180); - const BLEND = backdropAt(10, 130); - 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), - }; - const rigOf = (parent: any) => - parent.children.find((c: any) => c.children.some((g: any) => g.anims.length)); - - it('stacks the rig after the twinkle canvas and before the rain, with no z-index and no fixed position', () => { - const { parent, canvas } = host(); - const s = createRidgeScene({ canvas, tier: 'full', sky: night, backdrop: NOON })!; - const kinds = parent.children.map((c: any) => c.tag); - expect(kinds).toEqual(['canvas', 'canvas', 'div', 'div', 'div']); - expect(parent.children[2].children).toHaveLength(3); - parent.children.forEach((c: any) => { - expect(c.style.zIndex).toBeUndefined(); - expect(c.style.position).not.toBe('fixed'); - }); - s.dispose(); - expect(parent.children).toEqual([canvas]); - }); - - it('is three groups, far to near, each placed by windowFor and drifting by its depth of driftPx', () => { - const { parent, canvas } = host(); - const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: NOON })!; - const rig = rigOf(parent); - const win = windowFor(manifest.view, 400, 800); - expect(rig.children).toHaveLength(3); - rig.children.forEach((g: any, k: number) => { - expect(g.style.width).toBe(`${win.plane.w}px`); - expect(g.style.height).toBe(`${win.plane.h}px`); - expect(g.style.bottom).toBe('0px'); - expect(g.style.left).toBe(`${(400 - win.plane.w) / 2}px`); - expect(g.children.map((i: any) => i.src)).toEqual([`noon-${['far', 'mid', 'near'][k]}`]); - const { keyframes, options } = g.anims[0]; - const reach = win.driftPx * [0.35, 0.7, 1][k]; - expect(keyframes).toEqual([ - { transform: `translate3d(${-reach}px,0,0)` }, - { transform: `translate3d(${reach}px,0,0)` }, - ]); - expect(options).toMatchObject({ - duration: 75000, - iterations: Infinity, - direction: 'alternate', - easing: 'ease-in-out', - }); - }); - s.dispose(); - }); - - it('crossfades a into b: a at 1 - w, b added at w, in a group of its own', () => { - const { parent, canvas } = host(); - const BLEND3 = backdropAt(4, 130); // w = 0.2, not the symmetric half - const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: BLEND3 })!; - const { w } = BLEND3.choice; - expect(w).toBeCloseTo(0.2, 6); - const g = rigOf(parent).children[1]; - expect(g.style.isolation).toBe('isolate'); - expect( - g.children.map((i: any) => [i.src, i.style.opacity, i.style.mixBlendMode ?? null]) - ).toEqual([ - ['dawn-mid', String(1 - w), null], - ['morning-mid', String(w), 'plus-lighter'], - ]); - s.dispose(); - }); - - it('a lone frame is drawn at full opacity with no blend mode', () => { - const { parent, canvas } = host(); - const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: NOON })!; - const g = rigOf(parent).children[1]; - expect( - g.children.map((i: any) => [i.src, i.style.opacity, i.style.mixBlendMode ?? null]) - ).toEqual([['noon-mid', '1', null]]); - s.dispose(); - }); - - it('adds no rAF or timer callback of its own: the drift is Element.animate, the stars alone loop', () => { - const { canvas } = host(); - const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: NOON })!; - expect(rafQueue).toHaveLength(1); // the frame sampler, as without planes - s.dispose(); - const bare = host(); - const b = createRidgeScene({ canvas: bare.canvas, tier: 'full', sky: DAY })!; - expect(rafQueue).toHaveLength(1); - b.dispose(); - }); - - it('pauses the drift under reduced motion, in a hidden tab, and plays it again', () => { - const { parent, canvas } = host(); - const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: NOON })!; - 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()); - 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()); - 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()); - s.dispose(); - anims.forEach((a: any) => expect(a.cancel).toHaveBeenCalled()); - }); - - it("a still sums each blended plane in an offscreen (a at 1 - w, then b lighter at w) and draws it at windowFor's placement", () => { - const { parent, canvas } = host(); - const BLEND3 = backdropAt(4, 130); - createRidgeScene({ canvas, tier: 'still', sky: DAY, backdrop: BLEND3 }); - const { w } = BLEND3.choice; - const win = windowFor(manifest.view, 400, 800); - const planesDrawn = images.filter((a) => (a[0] as any).src) as any[]; - expect(planesDrawn.map((a) => [a[0].src, a.alpha, a.op])).toEqual( - ['far', 'mid', 'near'].flatMap((n) => [ - [`dawn-${n}`, 1 - w, 'source-over'], - [`morning-${n}`, w, 'lighter'], - ]) - ); - // Each sum then meets the host canvas once, plainly, at the plane's placement. - const summed = images.filter((a) => !(a[0] as any).src && (a[0] as any).width) as any[]; - expect(summed).toHaveLength(3); - summed.forEach((a) => { - expect([a[1], a[2], a[3], a[4]]).toEqual([ - (800 - win.plane.w * 2) / 2, - 1600 - win.plane.h * 2, - win.plane.w * 2, - win.plane.h * 2, - ]); - expect([a.alpha, a.op]).toEqual([1, 'source-over']); - expect([a[0].width, a[0].height]).toEqual([win.plane.w * 2, win.plane.h * 2]); - }); - expect(parent.children).toEqual([canvas]); - }); - - it('a lone frame in a still goes straight to the host canvas at full alpha', () => { - const { canvas } = host(); - createRidgeScene({ canvas, tier: 'still', sky: DAY, backdrop: NOON }); - const win = windowFor(manifest.view, 400, 800); - const planesDrawn = images.filter((a) => (a[0] as any).src) as any[]; - expect(planesDrawn.map((a) => [a[0].src, a.alpha, a.op])).toEqual( - ['far', 'mid', 'near'].map((n) => [`noon-${n}`, 1, 'source-over']) - ); - const [, x, y, dw, dh] = planesDrawn[0]; - expect([x, y, dw, dh]).toEqual([ - (800 - win.plane.w * 2) / 2, - 1600 - win.plane.h * 2, - win.plane.w * 2, - win.plane.h * 2, - ]); - }); - - it('settles to a still with the planes painted when the frame rate is poor', () => { - const { parent, canvas } = host(); - createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: NOON }); - runFrames(100, 400); - expect(images.filter((a) => (a[0] as any).src)).toHaveLength(3); - expect(parent.children).toEqual([canvas]); - }); - - it('with no backdrop it is the sky alone', () => { - const { parent, canvas } = host(); - createRidgeScene({ canvas, tier: 'full', sky: DAY }); - expect(parent.children).toEqual([canvas]); - expect(images.filter((a) => (a[0] as any).src)).toHaveLength(0); - }); -}); - describe('the scene wiring', () => { it('sizes from the window when the canvas has no client size', () => { const { canvas } = host(); diff --git a/src/app/features/scene/ridge/Ridge.ts b/src/app/features/scene/ridge/Ridge.ts index 89eb4442..519ff0a5 100644 --- a/src/app/features/scene/ridge/Ridge.ts +++ b/src/app/features/scene/ridge/Ridge.ts @@ -4,11 +4,8 @@ import { FrameSampler, FrameStats } from './probe'; import { skyColours, SkyColours, Srgb } from './skyColour'; import { paintSky as paintPhysicalSky } from './physicalSky'; import { windowFor } from './view'; -import { crossfade } from './frameChoice'; import { activeAt, drawStars, drawTwinkle as paintTwinkle, makeStars, Star } from './stars'; import { drawRainTile, RAIN_TILES } from './rain'; -import type { Backdrop, Planes } from './Backdrop'; -import { PLANE_NAMES } from './manifest'; export type RidgeOptions = Pick & { /** Show the rAF median/p95 readout. Default: the page URL has `?probe=1`, where `debug` allows it. */ @@ -19,8 +16,6 @@ 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 planes, already decoded; none is the sky-only scene (`view.ts` FALLBACK_VIEW). */ - backdrop?: Backdrop; }; const css = (c: Srgb): string => `rgb(${c[0]},${c[1]},${c[2]})`; @@ -97,8 +92,6 @@ const clock = (): number => (typeof performance !== 'undefined' ? performance.no interface Built { /** The twinkling stars' own canvas, over the sky; absent in a day sky and in 'still'. */ twinkle?: HTMLCanvasElement; - /** The ridge planes' rig, over the twinkle canvas and under the rain; absent in 'still' (the planes are drawn into the host canvas). */ - rig?: { el: HTMLElement; anims: (Animation | undefined)[] }; /** The rain's tiles and their falling, present only when the weather rains (`rain.ts`). */ rain?: { els: HTMLElement[]; anims: (Animation | undefined)[] }; } @@ -106,13 +99,12 @@ 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; -/** Far, mid and near slide this share of the drift room (`windowFor` driftPx); one leg of the back-and-forth takes DRIFT_LEG_S, so the loop is 150 s. Authored, tunable by eye. */ -const DRIFT_DEPTH = [0.35, 0.7, 1] as const; +/** One leg of the back-and-forth drift takes DRIFT_LEG_S, so the loop is 150 s. Authored, tunable by eye. */ const DRIFT_LEG_S = 75; /** * The ridge scene: same contract as `createScene` ({ login, dispose }, null for "keep the CSS - * ground"), no WebGL. It draws the sky, the stars, the baked ridge planes when given a `backdrop` (none: the sky alone) and the rain. The host canvas holds the baked sky; it and + * ground"), no WebGL. It draws the sky, the stars and the rain. The host canvas holds the baked sky; it and * its parent must be positioned, and the canvas should fill the parent. */ export function createRidgeScene(opts: RidgeOptions): Scene | null { @@ -144,8 +136,6 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { const teardown = () => { built?.twinkle?.remove(); - built?.rig?.anims.forEach((a) => a?.cancel()); - built?.rig?.el.remove(); built?.rain?.anims.forEach((a) => a?.cancel()); built?.rain?.els.forEach((e) => e.remove()); cancelAnimationFrame(twRaf); @@ -209,108 +199,6 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { return { els, anims }; }; - /** - * The ridge over the sky: one div holding a group per plane (far, mid, near: DOM order is paint order, stacking is by order alone), each the frame's - * image and, when the choice blends two frames, the second over it at the blend weight. A group slides sideways on the compositor by - * `driftPx` times its depth; the baker's pixels are never touched. - */ - const startRig = (bd: Backdrop, w: number, h: number): NonNullable => { - const win = windowFor(bd.manifest.view, w, h); - const el = document.createElement('div'); - el.setAttribute('aria-hidden', 'true'); - Object.assign(el.style, { - position: 'absolute', - left: '0', - top: '0', - width: '100%', - height: '100%', - overflow: 'hidden', - pointerEvents: 'none', - }); - const anims: (Animation | undefined)[] = []; - PLANE_NAMES.forEach((name, k) => { - const group = document.createElement('div'); - Object.assign(group.style, { - position: 'absolute', - left: `${(w - win.plane.w) / 2}px`, - bottom: `${win.plane.bottom}px`, - width: `${win.plane.w}px`, - height: `${win.plane.h}px`, - willChange: 'transform', - }); - const layer = (planes: Planes, opacity: number, blend?: string) => { - const img = planes[name].cloneNode() as HTMLImageElement; - Object.assign(img.style, { - position: 'absolute', - left: '0', - top: '0', - width: '100%', - height: '100%', - opacity: String(opacity), - }); - if (blend) img.style.mixBlendMode = blend; - group.appendChild(img); - }; - // One rule (`crossfade`): a at 1 - w, b added to it at w; the group is its own isolated backdrop, so the sum meets the sky once. - const fade = crossfade(bd.choice); - group.style.isolation = 'isolate'; - layer(bd.a, fade.a); - if (bd.b) layer(bd.b, fade.b, 'plus-lighter'); - el.appendChild(group); - const reach = win.driftPx * DRIFT_DEPTH[k]; - anims.push( - group.animate?.( - [ - { transform: `translate3d(${-reach}px,0,0)` }, - { transform: `translate3d(${reach}px,0,0)` }, - ], - { - duration: DRIFT_LEG_S * 1000, - iterations: Infinity, - direction: 'alternate', - easing: 'ease-in-out', - } - ) - ); - }); - parent.appendChild(el); - return { el, anims }; - }; - - /** Paint the ridge planes into the host canvas, a and b crossfaded, far to near: the still scene's one image. */ - const paintPlanes = (bd: Backdrop) => { - const ctx = context2d(canvas); - if (!ctx) return; - const { w, h, scale } = viewSize(); - const win = windowFor(bd.manifest.view, w, h); - const dw = win.plane.w * scale; - const dh = win.plane.h * scale; - const x = (canvas.width - dw) / 2; - const y = canvas.height - dh - win.plane.bottom * scale; - const fade = crossfade(bd.choice); - // A blend is summed in an offscreen of its own, as the rig sums it in an isolated group: 'lighter' on the host canvas would add to the sky. - const sum = bd.b ? document.createElement('canvas') : null; - if (sum) { - sum.width = dw; - sum.height = dh; - } - const sctx = sum ? context2d(sum) : null; - PLANE_NAMES.forEach((name) => { - if (!bd.b || !sum || !sctx) { - ctx.drawImage(bd.a[name], x, y, dw, dh); - return; - } - sctx.clearRect(0, 0, dw, dh); - sctx.globalCompositeOperation = 'source-over'; - sctx.globalAlpha = fade.a; - sctx.drawImage(bd.a[name], 0, 0, dw, dh); - sctx.globalCompositeOperation = 'lighter'; - sctx.globalAlpha = fade.b; - sctx.drawImage(bd.b[name], 0, 0, dw, dh); - ctx.drawImage(sum, x, y, dw, dh); - }); - }; - /** Paint the sky, the stars and the rain. Returns false when a 2D context is missing or there is no area yet. */ const build = (): boolean => { teardown(); @@ -343,7 +231,6 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { } 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(); @@ -378,7 +265,7 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { }; function syncPlayState() { - const anims = [...(built?.rig?.anims ?? []), ...(built?.rain?.anims ?? [])]; + const anims = [...(built?.rain?.anims ?? [])]; anims.forEach((a) => (moving() ? a?.play() : a?.pause())); if (!built?.twinkle) return; if (moving()) { @@ -397,7 +284,6 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { teardown(); cancelAnimationFrame(raf); raf = 0; - if (opts.backdrop) paintPlanes(opts.backdrop); report(true); }; diff --git a/src/app/features/scene/ridge/frameChoice.test.ts b/src/app/features/scene/ridge/frameChoice.test.ts deleted file mode 100644 index 82b9f1a9..00000000 --- a/src/app/features/scene/ridge/frameChoice.test.ts +++ /dev/null @@ -1,117 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { BLEND_EDGE, crossfade, frameChoice } from './frameChoice'; -import { parseManifest } from './manifest'; -import { wireManifest } from './manifest.fixture'; - -const { frames } = parseManifest(wireManifest(), '/d/'); -const at = (elevation: number, azimuth: number) => frameChoice(frames, { elevation, azimuth }); -const keys = (c: ReturnType) => [c.a.key, c.b?.key ?? null]; - -describe('frameChoice', () => { - it('blends continuously with elevation inside a half', () => { - const ws = [3, 6, 9, 12, 15, 18].map((el) => at(el, 130).w); - ws.forEach((w, i) => i && expect(w).toBeGreaterThan(ws[i - 1])); - }); - - it('weights by the elevation between the bracketing keys, a at the lower', () => { - // Morning half: night -12, dawn 0, morning 20, noon 60. Sun 10 deg is half way from dawn to morning. - const c = at(10, 130); - expect(keys(c)).toEqual(['dawn', 'morning']); - expect(c.w).toBeCloseTo(0.5, 6); - }); - - it('uses the afternoon keys after the noon azimuth and the morning keys before', () => { - expect(keys(at(10, 130))).toEqual(['dawn', 'morning']); - expect(keys(at(-1, 250))).toEqual(['dusk', 'golden']); - expect(at(-1, 250).w).toBeCloseTo(1.5 / 8.5, 6); - }); - - it('noon is the same single frame from both halves', () => { - expect(keys(at(60, 170))).toEqual(['noon', null]); - expect(keys(at(60, 190))).toEqual(['noon', null]); - expect(keys(at(75, 190))).toEqual(['noon', null]); - }); - - it('is the night key alone at or below its elevation, in either half', () => { - expect(keys(at(-12, 10))).toEqual(['night', null]); - expect(keys(at(-40, 300))).toEqual(['night', null]); - }); - - it('blends night into dawn before sunrise and dusk into night after sunset', () => { - expect(keys(at(-6, 90))).toEqual(['night', 'dawn']); - expect(keys(at(-6, 270))).toEqual(['night', 'dusk']); - }); - - it('collapses a blend within 2% of either end to one frame, and w stays in 0..1', () => { - expect(keys(at(0.2, 130))).toEqual(['dawn', null]); // w = 0.01 - expect(keys(at(19.8, 130))).toEqual(['morning', null]); // w = 0.99 - const els = Array.from({ length: 325 }, (_, i) => -30 + i * 0.37); - els.forEach((el) => - [0, 100, 179, 181, 270].forEach((az) => { - const c = at(el, az); - expect(c.w).toBeGreaterThanOrEqual(0); - expect(c.w).toBeLessThanOrEqual(1); - expect(c.b === null).toBe(c.w === 0); - }) - ); - }); - - it("splits the halves at the noon frame's azimuth, wherever the bake put it", () => { - const w = wireManifest() as any; - const shifted = parseManifest( - { - ...w, - frames: w.frames.map((f: any) => - f.key === 'noon' ? { ...f, sun: { ...f.sun, az: 170 } } : f - ), - }, - '/d/' - ); - const pick = (az: number) => frameChoice(shifted.frames, { elevation: 10, azimuth: az }); - expect([pick(169).a.key, pick(169).b?.key]).toEqual(['dawn', 'morning']); - expect([pick(171).a.key, pick(171).b?.key]).toEqual(['golden', 'noon']); - }); - - it('collapses exactly at BLEND_EDGE and no further: a blend of 3% still has two frames', () => { - expect(BLEND_EDGE).toBe(0.02); - // Morning half dawn 0 .. morning 20: w = el / 20. - expect(keys(at(0.6, 130))).toEqual(['dawn', 'morning']); // w = 0.03 - expect(keys(at(19.4, 130))).toEqual(['dawn', 'morning']); // w = 0.97 - expect(keys(at(0.2, 130))).toEqual(['dawn', null]); // w = 0.01 - expect(keys(at(19.8, 130))).toEqual(['morning', null]); // w = 0.99 - }); -}); - -describe('crossfade: the one rule of a blend', () => { - // A baked plane is haze as alpha: no pixel opaque, the same alpha in every frame. Frames as (premultiplied) colour and alpha. - const planeA = { c: 0.2, alpha: 0.6 }; - const planeB = { c: 0.5, alpha: 0.6 }; - const sum = (c: ReturnType) => { - const f = crossfade(c); - const b = c.b ? planeB : { c: 0, alpha: 0 }; - return { c: planeA.c * f.a + b.c * f.b, alpha: planeA.alpha * f.a + b.alpha * f.b }; - }; - - it('is a lerp of the two frames: colour and haze alike, never denser than either', () => { - [0.03, 0.2, 0.5, 0.8, 0.97].forEach((w) => { - const c = { a: frames[0], b: frames[1], w }; - const got = sum(c); - expect(got.c).toBeCloseTo(planeA.c * (1 - w) + planeB.c * w, 12); - expect(got.alpha).toBeCloseTo(0.6, 12); // equal alphas stay equal: the haze is not doubled - expect(got.alpha).toBeLessThanOrEqual(Math.max(planeA.alpha, planeB.alpha) + 1e-12); - }); - }); - - it('has no jump where the choice collapses: the blend either side of an edge is within the edge of the lone frame', () => { - const gap = Math.abs(planeA.c - planeB.c); - const high = sum({ a: frames[0], b: frames[1], w: 1 - BLEND_EDGE }); - const low = sum({ a: frames[0], b: frames[1], w: BLEND_EDGE }); - expect(Math.abs(high.c - planeB.c)).toBeLessThanOrEqual(BLEND_EDGE * gap + 1e-12); // collapse shows b alone - expect(Math.abs(low.c - planeA.c)).toBeLessThanOrEqual(BLEND_EDGE * gap + 1e-12); // collapse shows a alone - expect(high.alpha).toBeCloseTo(planeB.alpha, 12); - }); - - it('a lone frame is full weight alone', () => { - expect(crossfade({ a: frames[0], b: null, w: 0 })).toEqual({ a: 1, b: 0 }); - }); -}); diff --git a/src/app/features/scene/ridge/frameChoice.ts b/src/app/features/scene/ridge/frameChoice.ts deleted file mode 100644 index 1bede129..00000000 --- a/src/app/features/scene/ridge/frameChoice.ts +++ /dev/null @@ -1,55 +0,0 @@ -// Which baked frames the live sun lies between, and how far. Pure. The frames are ordered by the sun elevation they were baked for, a -// morning half rising from the night key through dawn and morning to noon, an afternoon half falling from noon through golden and dusk -// to night; the two halves share noon and the night key. The half is the live sun's side of the noon frame's azimuth. -import type { Frame, FrameKey } from './manifest'; - -export interface FrameChoice { - /** The frame shown alone when b is null, else weighted 1 - w. */ - a: Frame; - /** The frame crossfaded in at `w`, or null when one frame stands alone. */ - b: Frame | null; - /** Weight of b in 0..1; 0 when b is null. */ - w: number; -} - -/** Blends this close to either frame are not worth a second image. */ -export const BLEND_EDGE = 0.02; - -/** - * The one rule of a blend, for the rig and the still alike: a true crossfade, a at 1 - w plus b at w, summed (premultiplied) in a group of - * their own. The baked planes carry haze as alpha (no pixel is opaque), so b laid over a at opacity w would double the haze mid-blend - * and jump when the choice collapses to b alone; the sum is a lerp of the two frames and never denser than either. - */ -export function crossfade(choice: FrameChoice): { a: number; b: number } { - return choice.b ? { a: 1 - choice.w, b: choice.w } : { a: 1, b: 0 }; -} - -const MORNING: readonly FrameKey[] = ['night', 'dawn', 'morning', 'noon']; -const AFTERNOON: readonly FrameKey[] = ['night', 'dusk', 'golden', 'noon']; - -export function frameChoice( - frames: readonly Frame[], - sun: { elevation: number; azimuth: number } -): FrameChoice { - const by = (k: FrameKey): Frame => { - const f = frames.find((x) => x.key === k); - if (!f) throw new Error(`frameChoice: no ${k} frame`); - return f; - }; - const noon = by('noon'); - const half = (sun.azimuth < noon.sun.az ? MORNING : AFTERNOON).map(by); - // Ascending in elevation along the half, whatever the bake's numbers: sort so a hand-made manifest cannot invert the order. - half.sort((p, q) => p.sun.el - q.sun.el); - const lowest = half[0]; - const highest = half[half.length - 1]; - if (sun.elevation <= lowest.sun.el) return { a: lowest, b: null, w: 0 }; - if (sun.elevation >= highest.sun.el) return { a: highest, b: null, w: 0 }; - let i = 0; - while (half[i + 1].sun.el < sun.elevation) i += 1; - const lo = half[i]; - const hi = half[i + 1]; - const w = (sun.elevation - lo.sun.el) / (hi.sun.el - lo.sun.el); - if (w < BLEND_EDGE) return { a: lo, b: null, w: 0 }; - if (w > 1 - BLEND_EDGE) return { a: hi, b: null, w: 0 }; - return { a: lo, b: hi, w }; -} diff --git a/src/app/features/scene/ridge/frameLuma.test.ts b/src/app/features/scene/ridge/frameLuma.test.ts deleted file mode 100644 index 271c55c8..00000000 --- a/src/app/features/scene/ridge/frameLuma.test.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { inkContrast, themeInk } from './frameLuma'; -import { luminance } from '../../../../sky/skyTokens.js'; - -describe('inkContrast', () => { - it('reads the ink from the themes: dark Noonday ink by day and dusk, light Midnight ink at night', () => { - expect(themeInk('day')).toBe('#342d25'); - expect(themeInk('dusk')).toBe('#342d25'); - expect(themeInk('night')).toBe('#aeccff'); - }); - - it('gives the known ratios on a white and on a black ridge', () => { - const dark = luminance('#342d25'); - const light = luminance('#aeccff'); - const day = inkContrast({ min: 1, max: 1 }, 'day'); - expect(day.atMax).toBeCloseTo(1.05 / (dark + 0.05), 10); - expect(day.atMax).toBeCloseTo(13.6, 0); - const night = inkContrast({ min: 0, max: 0 }, 'night'); - expect(night.atMin).toBeCloseTo((light + 0.05) / 0.05, 10); - expect(night.atMin).toBeCloseTo(12.9, 0); - }); - - it('the worst contrast is where the range comes closest to the ink', () => { - const ink = luminance('#342d25'); - const across = inkContrast({ min: 0, max: 1 }, 'day'); - expect(across.worst).toBe(1); - expect(inkContrast({ min: ink + 0.2, max: 0.9 }, 'day').worst).toBeCloseTo( - (ink + 0.2 + 0.05) / (ink + 0.05), - 10 - ); - }); -}); diff --git a/src/app/features/scene/ridge/frameLuma.ts b/src/app/features/scene/ridge/frameLuma.ts deleted file mode 100644 index 77ec241d..00000000 --- a/src/app/features/scene/ridge/frameLuma.ts +++ /dev/null @@ -1,33 +0,0 @@ -// What a baked frame's recorded luma (manifest `frames[].luma`, WCAG linear relative luminance of the composited planes where they are -// solid enough, export.py) means for the text over it: the contrast of the state's theme ink against the ridge's own extremes, no scrim. -// Data for ridge-ad-legibility, which sizes the scrim from it and owns the 4.5:1 pass/fail; nothing here gates. -import { baked } from '../../../../sky/baked'; -import { luminance } from '../../../../sky/skyTokens.js'; -import type { FixedSkyState } from '../skyState'; - -export interface FrameLuma { - min: number; - max: number; -} - -/** The theme text ink skyState.ts's `FixedSkyState` bands derive: Noonday Sky's for day and dusk, Midnight Sky's for night. */ -export const themeInk = (state: FixedSkyState): string => - (state === 'night' ? baked.midnight : baked.noonday).tokens.Surface.OnContainer; - -const ratio = (a: number, b: number): number => (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05); - -/** - * WCAG contrast of the state's ink over a plain backdrop of the ridge's darkest and of its lightest luminance, and `worst`: the lowest - * contrast over every luminance between them (the ink's own luminance clamped into the range, where the two are closest). - */ -export function inkContrast( - luma: FrameLuma, - state: FixedSkyState -): { atMin: number; atMax: number; worst: number } { - const ink = luminance(themeInk(state)); - return { - atMin: ratio(ink, luma.min), - atMax: ratio(ink, luma.max), - worst: ratio(ink, Math.min(luma.max, Math.max(luma.min, ink))), - }; -} diff --git a/src/app/features/scene/ridge/manifest.fixture.ts b/src/app/features/scene/ridge/manifest.fixture.ts index bdfebebb..74a55cb0 100644 --- a/src/app/features/scene/ridge/manifest.fixture.ts +++ b/src/app/features/scene/ridge/manifest.fixture.ts @@ -1,19 +1,16 @@ -// A hand-written manifest v1 and index v1 (wire form, as export.py writes them): the runtime's tests need no real bake and no decoder. -import { FRAME_KEYS } from './manifest'; +// 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. import type { View } from './view'; -const SUN: Record = { - dawn: [100, 0], - morning: [130, 20], - noon: [180, 60], - golden: [240, 6], - dusk: [262, -2.5], - night: [0, -12], -}; +/** 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; -export const wireManifest = (over: Record = {}): Record => ({ - schema: 1, - baker_version: 1, +/** A v2 manifest of `k` cards (1 to 6), nearest first, each a band of the 600-row plane. */ +export const wireManifest = ( + over: Record = {}, + k = 3 +): Record => ({ + schema: 2, + baker_version: 2, bake_id: 'abc123abc123', place: { id: 'vienna', @@ -21,9 +18,7 @@ export const wireManifest = (over: Record = {}): Record = {}): Record ({ - key, - sun: { az: SUN[key][0], el: SUN[key][1] }, - hour_utc: 0, - planes: Object.fromEntries( - ['far', 'mid', 'near'].map((n) => [ - n, - { file: `${key}-${n}.webp`, bytes: 1, w: 1280, h: 600 }, - ]) - ), - bytes: 3, - luma: { min: 0.1, max: 0.5 }, + 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 }, + 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 }, })), + w: 1280, + h: 600, + bytes: 2 * k, attribution: { credit_line: 'credit', licence: 'licence', @@ -72,5 +72,6 @@ export const ELSEWHERE_VIEW: View = { planeW: 1600, planeH: 700, pxPerDegH: 1600 / 90, + 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 21444abc..8af79c55 100644 --- a/src/app/features/scene/ridge/manifest.test.ts +++ b/src/app/features/scene/ridge/manifest.test.ts @@ -3,7 +3,7 @@ import { forgetManifests, loadManifest, parseManifest } from './manifest'; import { wireIndex, wireManifest } from './manifest.fixture'; describe('parseManifest', () => { - it('reads a v1 manifest into the View the sky and planes share', () => { + it('reads a v2 manifest into the View the sky and cards share, and K cards nearest first', () => { const m = parseManifest(wireManifest(), '/public/ridge/v/'); expect(m.dir).toBe('/public/ridge/v/'); expect(m.view).toMatchObject({ @@ -11,36 +11,85 @@ describe('parseManifest', () => { windowDeg: 72, planeW: 1280, planeH: 600, - pxPerDegH: 1280 / 72, // not px_per_deg_v (17.7): a real bake's two differ 10x + pxPerDegH: 1280 / 72, + pxPerDegV: 177.8, // not px_per_deg_h: a real bake's two differ 10x horizonRow: 314.5, }); expect(m.view.place).toEqual({ id: 'vienna', lat: 48.19, lon: 16.35, altitudeKm: 0.183 }); - expect(m.frames.map((f) => f.key)).toEqual([ - 'dawn', - 'morning', - 'noon', - 'golden', - 'dusk', - 'night', - ]); - expect(m.frames[2]).toMatchObject({ - sun: { az: 180, el: 60 }, - planes: { far: 'noon-far.webp', near: 'noon-near.webp' }, + 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({ + top: 100, + h: 500, + scale: 1.0167, + colour: 'card-1-colour.webp', + geometry: 'card-1-geometry.webp', }); expect(m.attribution.creditLine).toBe('credit'); }); - it('rejects a missing field, a wrong schema, a plane wider than 4096 and fewer than 6 frames', () => { + it.each([1, 2, 3, 4, 5, 6])('parses a bake of %i cards', (k) => { + expect(parseManifest(wireManifest({}, k), '/').cards).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', () => { + const w = wireManifest() as any; + 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', () => { const w = wireManifest() as any; expect(() => parseManifest({ ...w, bake_id: undefined }, '/')).toThrow(/bake_id/); - expect(() => parseManifest({ ...w, schema: 2 }, '/')).toThrow(/schema/); expect(() => parseManifest({ ...w, view: { ...w.view, plane_w: 4097 } }, '/')).toThrow(/4096/); - expect(() => parseManifest({ ...w, frames: w.frames.slice(1) }, '/')).toThrow(/frames/); expect(() => parseManifest({ ...w, view: { ...w.view, horizon_row: 'x' } }, '/')).toThrow( /horizon_row/ ); + expect(() => parseManifest({ ...w, encoding: { ...w.encoding, normal: 'oct' } }, '/')).toThrow( + /normal/ + ); + expect(() => + parseManifest({ ...w, encoding: { ...w.encoding, log_d_max: w.encoding.log_d_min } }, '/') + ).toThrow(/encoding/); expect(() => parseManifest(null, '/')).toThrow(); }); + + it('never echoes a value it refused', () => { + const w = wireManifest() as any; + const refusal = (bad: unknown) => { + try { + parseManifest(bad, '/'); + } catch (e) { + return String(e); + } + return ''; + }; + 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' }] }, + ]) { + const msg = refusal(bad); + expect(msg).not.toBe(''); + expect(msg).not.toContain('SECRET-VALUE-42'); + } + }); }); const serve = (files: Record) => { diff --git a/src/app/features/scene/ridge/manifest.ts b/src/app/features/scene/ridge/manifest.ts index a3d0e33e..e2ec9087 100644 --- a/src/app/features/scene/ridge/manifest.ts +++ b/src/app/features/scene/ridge/manifest.ts @@ -1,20 +1,21 @@ // 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 planes share. +// camelCase and its `view` is the View (`view.ts`) the sky and the cards share. Schema 2: K G-buffer cards, nearest first. import type { View } from './view'; -export const FRAME_KEYS = ['dawn', 'morning', 'noon', 'golden', 'dusk', 'night'] as const; -export type FrameKey = typeof FRAME_KEYS[number]; -export const PLANE_NAMES = ['far', 'mid', 'near'] as const; -export type PlaneName = typeof PLANE_NAMES[number]; export const PLANE_W_MAX = 4096; +/** As export.py MAX_CARDS: the decode budget holds this many. */ +export const MAX_CARDS = 6; -export interface Frame { - key: FrameKey; - /** The sun this frame was lit by: degrees. */ - sun: { az: number; el: number }; - /** File names inside the manifest's directory. */ - planes: Record; +/** 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. */ + 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; + colour: string; + geometry: string; } export interface RidgeManifest { @@ -24,8 +25,12 @@ export interface RidgeManifest { /** Display name of the place. */ name: string; view: View; - /** In `FRAME_KEYS` order. */ - frames: Frame[]; + /** 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. */ + encoding: { logDMin: number; logDMax: number }; + /** The widest heading either side of the look azimuth the baked cards allow, degrees. */ + camera: { headingMaxDeg: number }; + /** Nearest first. */ + cards: CardEntry[]; attribution: { creditLine: string; licence: string; demSource: string; url: string }; } @@ -57,31 +62,39 @@ 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 planes are read relative to it. */ +/** `dir` is the URL of the directory the manifest was read from; the cards are read relative to it. */ export function parseManifest(raw: unknown, dir: string): RidgeManifest { const r = rec(raw, 'manifest'); - if (r.schema !== 1) fail('schema', 'must be 1'); + if (r.schema !== 2) fail('schema', 'must be 2'); 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}`); - if (!Array.isArray(r.frames) || r.frames.length < FRAME_KEYS.length) - fail('frames', `fewer than ${FRAME_KEYS.length}`); - const frames = FRAME_KEYS.map((key) => { - const f = (r.frames as unknown[]) - .map((x, i) => rec(x, `frames[${i}]`)) - .find((x) => x.key === key); - if (!f) return fail('frames', `no ${key} frame`); - const sun = rec(f.sun, `frames.${key}.sun`); - const planes = rec(f.planes, `frames.${key}.planes`); - const file = (n: PlaneName) => - str(rec(planes[n], `frames.${key}.planes.${n}`).file, `frames.${key}.planes.${n}.file`); + 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 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 { - key, - sun: { az: num(sun.az, `frames.${key}.sun.az`), el: num(sun.el, `frames.${key}.sun.el`) }, - planes: { far: file('far'), mid: file('mid'), near: file('near') }, + 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`), }; }); + 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 a = rec(r.attribution, 'attribution'); const id = str(p.id, 'place.id'); return { @@ -98,11 +111,14 @@ export function parseManifest(raw: unknown, dir: string): RidgeManifest { lookAzDeg: num(v.look_az_deg, 'view.look_az_deg'), windowDeg: num(v.window_deg, 'view.window_deg'), planeW, - planeH: num(v.plane_h, 'view.plane_h'), + 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'), }, - frames, + encoding: { logDMin, logDMax }, + camera: { headingMaxDeg }, + cards, attribution: { creditLine: str(a.credit_line, 'attribution.credit_line'), licence: str(a.licence, 'attribution.licence'), diff --git a/src/app/features/scene/ridge/ridgeAssets.test.ts b/src/app/features/scene/ridge/ridgeAssets.test.ts deleted file mode 100644 index 96b899b0..00000000 --- a/src/app/features/scene/ridge/ridgeAssets.test.ts +++ /dev/null @@ -1,229 +0,0 @@ -// The committed baked set under public/ridge: what the baker wrote is what ships, within the budget the baker itself refuses on -// (export.py PAIR_BYTES_MAX, DECODE_BYTES_MAX). Reads with node fs. The gate reads each plane'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 manifest's w and h, -// which the decode budget is computed from; and the bake id is re-derived from the plane bytes, as the baker derives it, so any -// corruption of a plane, same length or not, fails. No pixel decoder is in the tree; the baker's own check decodes pixels. -import { createHash } from 'node:crypto'; -import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'; -import { join } from 'node:path'; -import { describe, expect, it } from 'vitest'; -import { FRAME_KEYS, PLANE_NAMES, parseIndex, parseManifest } from './manifest'; - -/** The same two constants as scripts/ridge-bake/export.py: two adjacent frames, fetched and decoded. */ -export const PAIR_BYTES_MAX = 800_000; -export const DECODE_BYTES_MAX = 20_000_000; - -interface WirePlane { - file: string; - bytes: number; - w: number; - h: number; -} -interface WireFrame { - key: string; - planes: Record; - luma: { min: number; max: number }; -} -export interface WireManifest { - bake_id: string; - frames: WireFrame[]; -} - -const planes = (f: WireFrame): WirePlane[] => PLANE_NAMES.map((n) => f.planes[n]); - -/** Why a manifest breaks the size gate, or undefined. Frames are taken in FRAME_KEYS order; the pairs are neighbours, and night meets dawn. */ -export function sizeGate(m: WireManifest): string | undefined { - const byKey = FRAME_KEYS.map((k) => m.frames.find((f) => f.key === k) as WireFrame); - for (let i = 0; i < byKey.length; i += 1) { - const pair = [byKey[i], byKey[(i + 1) % byKey.length]]; - const ps = pair.flatMap(planes); - const fetched = ps.reduce((a, p) => a + p.bytes, 0); - const decoded = ps.reduce((a, p) => a + p.w * p.h * 4, 0); - if (fetched > PAIR_BYTES_MAX) return `${pair[0].key}+${pair[1].key} fetches ${fetched}`; - if (decoded > DECODE_BYTES_MAX) return `${pair[0].key}+${pair[1].key} decodes ${decoded}`; - } - return undefined; -} - -/** - * Why a buffer is not a well-formed WebP of `w` x `h`, or undefined. Checks the RIFF envelope (its size is the file's), that the chunks tile - * the file exactly, and the dimensions the container and the bitstream header each state. - */ -export function webpFault(b: Uint8Array, w: number, h: number): string | undefined { - const u32 = (o: number) => (b[o] | (b[o + 1] << 8) | (b[o + 2] << 16) | (b[o + 3] << 24)) >>> 0; - const u24 = (o: number) => b[o] | (b[o + 1] << 8) | (b[o + 2] << 16); - const tag = (o: number) => String.fromCharCode(b[o], b[o + 1], b[o + 2], b[o + 3]); - if (b.length < 20 || tag(0) !== 'RIFF' || tag(8) !== 'WEBP') return 'not a RIFF WEBP'; - if (u32(4) + 8 !== b.length) return `RIFF size ${u32(4)} does not fit a ${b.length} byte file`; - const dims: string[] = []; - let seen = 0; - let o = 12; - while (o < b.length) { - if (o + 8 > b.length) return 'a chunk header runs past the file'; - const id = tag(o); - const len = u32(o + 4); - const body = o + 8; - if (body + len > b.length) return `chunk ${id} runs past the file`; - if (id === 'VP8X') dims.push(`${u24(body + 4) + 1}x${u24(body + 7) + 1}`); - if (id === 'VP8 ') { - if (b[body + 3] !== 0x9d || b[body + 4] !== 0x01 || b[body + 5] !== 0x2a) - return 'VP8 start code missing'; - dims.push( - `${(b[body + 6] | (b[body + 7] << 8)) & 0x3fff}x${ - (b[body + 8] | (b[body + 9] << 8)) & 0x3fff - }` - ); - seen += 1; - } - if (id === 'VP8L') { - if (b[body] !== 0x2f) return 'VP8L signature missing'; - const bits = u32(body + 1); - dims.push(`${(bits & 0x3fff) + 1}x${((bits >>> 14) & 0x3fff) + 1}`); - seen += 1; - } - o = body + len + (len & 1); - } - if (o !== b.length) return 'the chunks do not tile the file'; - if (seen !== 1) return `${seen} bitstream chunks`; - const bad = dims.find((d) => d !== `${w}x${h}`); - 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 plane bytes, frames in FRAME_KEYS order, planes far, mid, near. */ -export function bakeIdOf(planeBytes: (frame: string, plane: string) => Uint8Array): string { - const h = createHash('sha256'); - FRAME_KEYS.forEach((k) => PLANE_NAMES.forEach((n) => h.update(planeBytes(k, n)))); - return h.digest('hex').slice(0, 12); -} - -const ROOT = join(process.cwd(), 'public', 'ridge'); -const readJson = (p: string): unknown => JSON.parse(readFileSync(p, 'utf8')); -const index = parseIndex(readJson(join(ROOT, 'index.json'))); -const dirs = Object.entries(index.places); - -describe('the committed ridge assets', () => { - it('ship at least one place, and the index default is one of them', () => { - expect(dirs.length).toBeGreaterThan(0); - expect(index.places[index.default]).toBeDefined(); - }); - - dirs.forEach(([id, dir]) => { - describe(`${id} (${dir})`, () => { - const raw = readJson(join(ROOT, dir, 'manifest.json')) as WireManifest; - - it('parses, and its directory ends in its bake id', () => { - expect(() => parseManifest(raw, `${dir}/`)).not.toThrow(); - expect(dir.endsWith(`-${raw.bake_id}`)).toBe(true); - }); - - it('has every plane file, at the length the manifest states', () => { - raw.frames.flatMap(planes).forEach((p) => { - expect(statSync(join(ROOT, dir, p.file)).size, p.file).toBe(p.bytes); - }); - }); - - it('decodes every plane as the WebP of the size the manifest states', () => { - raw.frames.flatMap(planes).forEach((p) => { - expect( - webpFault(readFileSync(join(ROOT, dir, p.file)), p.w, p.h), - p.file - ).toBeUndefined(); - }); - }); - - it('holds the bytes its bake id was made from', () => { - const bytes = (frame: string, plane: string) => - readFileSync( - join( - ROOT, - dir, - (raw.frames.find((f) => f.key === frame) as WireFrame).planes[plane].file - ) - ); - expect(bakeIdOf(bytes)).toBe(raw.bake_id); - }); - - it('keeps every adjacent pair of frames inside the fetch and decode budget', () => { - expect(sizeGate(raw)).toBeUndefined(); - }); - - it('records a finite luma for every frame', () => { - expect(raw.frames).toHaveLength(FRAME_KEYS.length); - raw.frames.forEach((f) => { - expect(Number.isFinite(f.luma.min) && Number.isFinite(f.luma.max), f.key).toBe(true); - expect(f.luma.min, f.key).toBeLessThanOrEqual(f.luma.max); - }); - }); - }); - }); - - 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).frames - .flatMap(planes) - .forEach((p) => named.add(`${dir}/${p.file}`)); - }); - const onDisk = readdirSync(ROOT, { recursive: true, withFileTypes: true }) - .filter((e) => e.isFile()) - .map((e) => join(e.parentPath, e.name).slice(ROOT.length + 1)); - expect(onDisk.filter((f) => !named.has(f))).toEqual([]); - expect([...named].filter((f) => !existsSync(join(ROOT, f)))).toEqual([]); - }); -}); - -describe('the plane gates refuse a plane that is not what the manifest says', () => { - const real = readFileSync(join(ROOT, Object.values(index.places)[0], 'noon-mid.webp')); - const manifest = readJson( - join(ROOT, Object.values(index.places)[0], 'manifest.json') - ) as WireManifest; - const { w, h } = manifest.frames[2].planes.mid; - const id = (b: Uint8Array) => bakeIdOf(() => b); - - it('accepts the real plane at its size', () => { - expect(webpFault(real, w, h)).toBeUndefined(); - }); - it("refuses a manifest that lies about the plane's size, and a file cut short or padded", () => { - expect(webpFault(real, w, h + 1)).toMatch(/states/); - expect(webpFault(real.subarray(0, real.length - 1), w, h)).toBeDefined(); - expect(webpFault(Buffer.concat([real, Buffer.from([0])]), w, h)).toBeDefined(); - }); - it('refuses a frame header whose dimensions are changed, and bytes that are not a WebP', () => { - const vp8 = Buffer.from(real); - const at = vp8.indexOf('VP8 ') + 8 + 6; - vp8[at] ^= 0x01; - expect(webpFault(vp8, w, h)).toMatch(/states/); - 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 plane 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)); - }); -}); - -describe('sizeGate', () => { - const plane = (bytes: number): WirePlane => ({ file: 'x.webp', bytes, w: 1280, h: 600 }); - const frame = (key: string, bytes: number): WireFrame => ({ - key, - planes: { far: plane(bytes), mid: plane(bytes), near: plane(bytes) }, - luma: { min: 0, max: 1 }, - }); - const set = (bytes: number): WireManifest => ({ - bake_id: 'x', - frames: FRAME_KEYS.map((k) => frame(k, bytes)), - }); - - it('passes a pair at the budget and fails a 900 KB pair', () => { - expect(sizeGate(set(133_333))).toBeUndefined(); - expect(sizeGate(set(150_000))).toMatch(/fetches 900000/); - }); - - it('fails a pair that decodes past the budget', () => { - const m = set(1); - m.frames[2].planes.far = { file: 'x.webp', bytes: 1, w: 4096, h: 1000 }; - expect(sizeGate(m)).toMatch(/decodes/); - }); -}); diff --git a/src/app/features/scene/ridge/view.ts b/src/app/features/scene/ridge/view.ts index fef44b36..827114e4 100644 --- a/src/app/features/scene/ridge/view.ts +++ b/src/app/features/scene/ridge/view.ts @@ -1,5 +1,5 @@ -// The one View: where the sky's camera stands and looks, and where the ridge planes sit against it. A baked place's manifest -// (`view` and `place`, manifest v1) is a View; a sky with no planes uses FALLBACK_VIEW. `windowFor` is the single owner of the +// 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. @@ -20,6 +20,8 @@ export interface ManifestView { planeW: number; planeH: number; pxPerDegH: number; + /** Plane pixels per degree of elevation (the baker draws the vertical exaggerated: it is not `pxPerDegH`). */ + pxPerDegV: number; /** Row of the horizon in the plane, from its top. */ horizonRow: number; } @@ -41,7 +43,7 @@ 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 six-key Vienna bake. */ +/** The sky of a scene with no planes (a failed load): Vienna facing south-west, with the numbers of the Vienna bake. */ export const FALLBACK_VIEW: View = { place: { id: 'vienna', lat: 48.1929826, lon: 16.3534237, altitudeKm: 0.183 }, lookAzDeg: 214, @@ -49,6 +51,7 @@ export const FALLBACK_VIEW: View = { planeW: 1280, planeH: 600, pxPerDegH: 1280 / 72, + pxPerDegV: 177.8, horizonRow: 314.5, };