From 6347148d7d7c55bd4339ebc158d87bf137c4e8ae Mon Sep 17 00:00:00 2001 From: Nibu Date: Sat, 14 Nov 2026 09:25:49 +0000 Subject: [PATCH] ridge: the View is the one owner of the sun's place, with no default; the rebuild key, weather and sky are given it Co-Authored-By: Claude Sonnet 5.5 --- src/app/features/scene/index.test.ts | 71 +++++++++++++++++-- src/app/features/scene/index.ts | 59 +++++++++------ src/app/features/scene/ridge/Ridge.test.ts | 27 +++++-- .../features/scene/ridge/manifest.fixture.ts | 12 ++++ .../features/scene/ridge/physicalSky.test.ts | 37 ++++++++-- src/app/features/scene/ridge/physicalSky.ts | 4 +- .../features/scene/ridge/weatherFeed.test.ts | 33 ++++++--- src/app/features/scene/ridge/weatherFeed.ts | 8 +-- src/app/features/scene/skyForState.test.ts | 51 ++++++++++--- src/app/features/scene/skyForState.ts | 19 ++--- 10 files changed, 247 insertions(+), 74 deletions(-) diff --git a/src/app/features/scene/index.test.ts b/src/app/features/scene/index.test.ts index 4da1b3b7..5cdb1fa7 100644 --- a/src/app/features/scene/index.test.ts +++ b/src/app/features/scene/index.test.ts @@ -8,6 +8,9 @@ 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'; const { createRidgeScene, createScene } = vi.hoisted(() => ({ createRidgeScene: vi.fn(), @@ -51,7 +54,7 @@ describe('startBackgroundScene follows the sky state', () => { createRidgeScene.mockReturnValue(fakeScene()); const scene = await startBackgroundScene(config, caps, { canvas }); expect(createRidgeScene).toHaveBeenCalledOnce(); - expect(hex(createRidgeScene.mock.calls[0][0].sky.top)).toBe(hex(ridgeSkyFor('night').top)); + expect(hex(createRidgeScene.mock.calls[0][0].sky.top)).toBe(hex(ridgeSkyFor('night', FALLBACK_VIEW).top)); scene?.dispose(); }); @@ -70,7 +73,7 @@ describe('startBackgroundScene follows the sky state', () => { setSkyState('night'); createRidgeScene.mockReturnValue(fakeScene()); const scene = await startBackgroundScene(config, caps, { canvas }); - expect(hex(createRidgeScene.mock.calls[0][0].sky.top)).toBe(hex(ridgeSkyFor('night').top)); + expect(hex(createRidgeScene.mock.calls[0][0].sky.top)).toBe(hex(ridgeSkyFor('night', FALLBACK_VIEW).top)); scene?.dispose(); }); @@ -82,7 +85,7 @@ describe('startBackgroundScene follows the sky state', () => { setSkyState('day'); await flush(); expect(first.dispose).toHaveBeenCalledOnce(); - expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe(hex(ridgeSkyFor('day').top)); + expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe(hex(ridgeSkyFor('day', FALLBACK_VIEW).top)); scene?.dispose(); expect(second.dispose).toHaveBeenCalledOnce(); }); @@ -95,7 +98,7 @@ describe('startBackgroundScene follows the sky state', () => { const scene = await started; await flush(); expect(createRidgeScene).toHaveBeenCalledTimes(2); - expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe(hex(ridgeSkyFor('day').top)); + expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe(hex(ridgeSkyFor('day', FALLBACK_VIEW).top)); expect(a.dispose).toHaveBeenCalledOnce(); scene?.dispose(); expect(b.dispose).toHaveBeenCalledOnce(); @@ -175,7 +178,7 @@ describe('startBackgroundScene follows the sky state', () => { // 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').top) + hex(ridgeSkyFor('dusk', FALLBACK_VIEW).top) ); const live = scenes[built - 1]; scene?.login(); @@ -205,7 +208,7 @@ describe('startBackgroundScene follows the sky state', () => { 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').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]; @@ -456,13 +459,67 @@ describe('the ridge planes and the live scene', () => { const opts = createRidgeScene.mock.calls[0][0]; const { manifest } = opts.backdrop; const own = frameChoice(manifest.frames, opts.sky.physical.sun); - const fallbackSun = ridgeSkyFor('day').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(); diff --git a/src/app/features/scene/index.ts b/src/app/features/scene/index.ts index f4464612..151148cc 100644 --- a/src/app/features/scene/index.ts +++ b/src/app/features/scene/index.ts @@ -6,6 +6,8 @@ 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'; @@ -27,6 +29,20 @@ 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; @@ -70,31 +86,33 @@ async function prepare( ); } const { createRidgeScene } = await import('./ridge/Ridge'); - await loadWeather(weatherUrl()); + 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; let sky: SkyColours | undefined; - let planesFail: Error | null = null; - try { - const manifest = await loadManifest(import.meta.env.BASE_URL, config?.place); - const manifestSky = ridgeSkyFor(state, undefined, undefined, 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)); + 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 made = guarded(() => createRidgeScene({ ...options, - sky: sky ?? ridgeSkyFor(state), + sky: sky ?? ridgeSkyFor(state, FALLBACK_VIEW), backdrop: backdrop ?? undefined, }) ); @@ -117,8 +135,9 @@ async function skyKey( try { const { loadWeather, ridgeSkyKey, terrainSkyFor } = await import('./skyForState'); if (config?.style === 'terrain') return JSON.stringify(terrainSkyFor(state)); - await loadWeather(weatherUrl()); - return ridgeSkyKey(state); + const view = (await manifestOf(config)).manifest?.view ?? FALLBACK_VIEW; + await loadWeather(weatherUrl(), view.place); + return ridgeSkyKey(state, view); } catch { // The chunk failed to load: no key, so every change rebuilds (and `create` reports the failure). return null; diff --git a/src/app/features/scene/ridge/Ridge.test.ts b/src/app/features/scene/ridge/Ridge.test.ts index d463fff7..b916f59e 100644 --- a/src/app/features/scene/ridge/Ridge.test.ts +++ b/src/app/features/scene/ridge/Ridge.test.ts @@ -4,13 +4,13 @@ import { valueNoise, hash2 } from './noise'; import { FrameSampler, frameStats, SLOW_P95_MS, WARMUP_FRAMES, WINDOW_MS } from './probe'; import type { SkyColours } from './skyColour'; import { makeStars } from './stars'; -import { makePhysicalSky } from './physicalSky'; +import { makePhysicalSky, paintSky as paintPhysicalSky } from './physicalSky'; import { startBackgroundScene } from '../index'; import { frameChoice } from './frameChoice'; import { parseManifest } from './manifest'; -import { wireManifest } from './manifest.fixture'; +import { ELSEWHERE_VIEW, wireManifest } from './manifest.fixture'; import type { Backdrop } from './Backdrop'; -import { windowFor } from './view'; +import { FALLBACK_VIEW, windowFor } from './view'; describe('noise', () => { it('is deterministic and in [0, 1)', () => { @@ -138,6 +138,8 @@ const DAY: SkyColours = { }; const draws: string[] = []; const images: unknown[][] = []; +/** Every RGBA grid the host canvas was painted from (the small canvas's putImageData). */ +const painted: Uint8ClampedArray[] = []; function ctx() { const c: any = { createLinearGradient: () => ({ addColorStop: vi.fn() }), @@ -153,7 +155,9 @@ function ctx() { width: w, height: h, }), - putImageData() {}, + putImageData(img: { data: Uint8ClampedArray }) { + painted.push(img.data); + }, beginPath() {}, moveTo() {}, stroke() {}, @@ -192,6 +196,7 @@ beforeEach(() => { rafQueue = []; draws.length = 0; images.length = 0; + painted.length = 0; search = ''; motion = { matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn() }; doc = Object.assign(new EventTarget(), { @@ -260,6 +265,16 @@ describe('createRidgeScene', () => { s.dispose(); }); + 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 s = createRidgeScene({ canvas, tier: 'full', sky: { ...DAY, physical } })!; + const want = paintPhysicalSky(physical, 400, 800, windowFor(ELSEWHERE_VIEW, 400, 800).camera); + expect(painted).toHaveLength(1); + expect(Array.from(painted[0])).toEqual(Array.from(want.data)); + s.dispose(); + }); + it('a smooth run draws nothing more and ends its rAF loop', () => { const { canvas } = host(); const s = createRidgeScene({ canvas, tier: 'full', sky: DAY })!; @@ -470,7 +485,7 @@ 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), + physical: makePhysicalSky('day', new Date('2026-06-21T10:40:00Z'), w, FALLBACK_VIEW), }); const rainEls = (parent: any) => parent.children.filter((c: any) => c.tag === 'div'); @@ -534,7 +549,7 @@ describe('the ridge planes in the scene', () => { top: [10, 14, 40], mid: [30, 34, 80], horizon: [60, 50, 90], - physical: makePhysicalSky('night', new Date('2026-06-21T22:40:00Z'), 1), + 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)); diff --git a/src/app/features/scene/ridge/manifest.fixture.ts b/src/app/features/scene/ridge/manifest.fixture.ts index 951dcc0d..bdfebebb 100644 --- a/src/app/features/scene/ridge/manifest.fixture.ts +++ b/src/app/features/scene/ridge/manifest.fixture.ts @@ -1,5 +1,6 @@ // 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'; +import type { View } from './view'; const SUN: Record = { dawn: [100, 0], @@ -62,3 +63,14 @@ export const wireIndex = { default: 'vienna', 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. */ +export const ELSEWHERE_VIEW: View = { + place: { id: 'elsewhere', lat: -33.9, lon: 151.2, altitudeKm: 1.5 }, + lookAzDeg: 20, + windowDeg: 90, + planeW: 1600, + planeH: 700, + pxPerDegH: 1600 / 90, + horizonRow: 250, +}; diff --git a/src/app/features/scene/ridge/physicalSky.test.ts b/src/app/features/scene/ridge/physicalSky.test.ts index f386a87e..b0426924 100644 --- a/src/app/features/scene/ridge/physicalSky.test.ts +++ b/src/app/features/scene/ridge/physicalSky.test.ts @@ -1,4 +1,7 @@ import { describe, expect, it } from 'vitest'; +import { FALLBACK_VIEW } from './view'; +import { ELSEWHERE_VIEW } from './manifest.fixture'; +import { sunForState } from './sunAt'; import { makePhysicalSky, paintSky } from './physicalSky'; import { skyBackdrop } from '../skyState'; import type { FixedSkyState } from '../skyBand'; @@ -40,7 +43,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); + const sky = makePhysicalSky(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) { @@ -61,7 +64,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); + const sky = makePhysicalSky('day', at, w, FALLBACK_VIEW); return paintSky(sky, 640, 360, camera(sky, 640, 360)); }; const clear = paint(0); @@ -92,7 +95,7 @@ describe('the sun disc', () => { let drawn = 0; for (const state of ['day', 'dusk'] as FixedSkyState[]) { for (let m = 0; m < 24 * 60; m += 10) { - const sky = makePhysicalSky(state, new Date(Date.UTC(2026, 10, 11, 0, m)), 0); + const sky = makePhysicalSky(state, new Date(Date.UTC(2026, 10, 11, 0, m)), 0, FALLBACK_VIEW); const d = paintSky(sky, 1280, 720, facingSun(sky, 1280, 720)).sunDisc; if (!d) continue; drawn += 1; @@ -106,7 +109,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); + const sky = makePhysicalSky('day', noon, 0, FALLBACK_VIEW); const d = disc(sky).sunDisc; expect(d).toBeDefined(); expect(d!.x).toBeGreaterThan(0); @@ -117,12 +120,32 @@ 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)).sunDisc).toBeUndefined(); - expect(disc(makePhysicalSky('night', noon, 0)).sunDisc).toBeUndefined(); + expect(disc(makePhysicalSky('day', noon, 0.7, FALLBACK_VIEW)).sunDisc).toBeUndefined(); + expect(disc(makePhysicalSky('night', noon, 0, FALLBACK_VIEW)).sunDisc).toBeUndefined(); }); it('is orange-tinted low in the sky', () => { - const d = disc(makePhysicalSky('dusk', noon, 0)).sunDisc; + const d = disc(makePhysicalSky('dusk', noon, 0, FALLBACK_VIEW)).sunDisc; expect(d).toBeDefined(); expect(d!.rgb[0]).toBeGreaterThan(d!.rgb[2]); }); }); + +describe('the sky is made from the View it is given', () => { + const NOW = new Date('2026-06-21T10:40:00Z'); + 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); + 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.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); + 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 f151cba3..2136a9e5 100644 --- a/src/app/features/scene/ridge/physicalSky.ts +++ b/src/app/features/scene/ridge/physicalSky.ts @@ -11,7 +11,7 @@ import { display8, fitDisplay, holdBudget, MARGIN } from './toneMap'; import type { Display, Fit } from './toneMap'; import { sunForState } from './sunAt'; import type { SunSample } from './sunAt'; -import { FALLBACK_VIEW, windowFor } from './view'; +import { windowFor } from './view'; import type { Camera, View } from './view'; import { weatherOf } from './weather'; import type { Weather } from './weather'; @@ -53,7 +53,7 @@ export function makePhysicalSky( state: FixedSkyState, now: Date, weatherValue: number, - view: View = FALLBACK_VIEW + view: View ): PhysicalSky { const t0 = clock(); const sun = sunForState(view.place, state, now); diff --git a/src/app/features/scene/ridge/weatherFeed.test.ts b/src/app/features/scene/ridge/weatherFeed.test.ts index 2cda82e9..0163224d 100644 --- a/src/app/features/scene/ridge/weatherFeed.test.ts +++ b/src/app/features/scene/ridge/weatherFeed.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from 'vitest'; import { sunAt } from './sunAt'; import { FALLBACK_VIEW } from './view'; +import { ELSEWHERE_VIEW } from './manifest.fixture'; import { CLEAR_SKY, currentWeather, @@ -121,17 +122,18 @@ describe('weather from the file', () => { describe('the weather now', () => { it('uses the file while it is fresh', () => { - expect(currentWeather(file({ glow_wm2: 0, humidity_pct: 95 }), NOW)).toBeCloseTo(0.7, 2); + expect(currentWeather(file({ glow_wm2: 0, humidity_pct: 95 }), FALLBACK_VIEW.place, NOW)).toBeCloseTo(0.7, 2); }); it('falls back to a clear sky when the file was fetched more than 30 minutes ago', () => { const f = file({ humidity_pct: 100, fetched_at: '2026-11-11T10:19:00Z' }); expect(NOW.getTime() - Date.parse(f.fetched_at)).toBeGreaterThan(STALE_MS); - expect(currentWeather(f, NOW)).toBe(CLEAR_SKY); + expect(currentWeather(f, FALLBACK_VIEW.place, NOW)).toBe(CLEAR_SKY); }); it('the 30 minute mark itself is still fresh', () => { expect( currentWeather( file({ glow_wm2: 0, humidity_pct: 100, fetched_at: '2026-11-11T10:20:00Z' }), + FALLBACK_VIEW.place, NOW ) ).toBe(0.75); @@ -139,19 +141,34 @@ describe('the weather now', () => { it('falls back to a clear sky when the observation is more than 40 minutes old, though the file is fresh', () => { const f = file({ precip_mm_10min: 2, observed_at: '2026-11-11T10:09:00Z' }); expect(NOW.getTime() - Date.parse(f.observed_at)).toBeGreaterThan(OBSERVATION_STALE_MS); - expect(currentWeather(f, NOW)).toBe(CLEAR_SKY); + expect(currentWeather(f, FALLBACK_VIEW.place, NOW)).toBe(CLEAR_SKY); expect( - currentWeather(file({ precip_mm_10min: 2, observed_at: '2026-11-11T10:11:00Z' }), NOW) + currentWeather(file({ precip_mm_10min: 2, observed_at: '2026-11-11T10:11:00Z' }), FALLBACK_VIEW.place, NOW) ).toBeGreaterThan(0.8); }); it('falls back to a clear sky with no file, and with a fetch time from the future', () => { - expect(currentWeather(null, NOW)).toBe(CLEAR_SKY); + expect(currentWeather(null, FALLBACK_VIEW.place, NOW)).toBe(CLEAR_SKY); expect( - currentWeather(file({ precip_mm_10min: 2, fetched_at: '2026-11-12T10:40:00Z' }), NOW) + currentWeather(file({ precip_mm_10min: 2, fetched_at: '2026-11-12T10:40:00Z' }), FALLBACK_VIEW.place, NOW) ).toBe(CLEAR_SKY); }); }); +describe('the sun the weather is read against is the place it is given', () => { + it("sets radiation against the sun over that place: by day in Vienna it reads cloud, at the other side of the world, in the night, it reads the humidity", () => { + const f = file({ glow_wm2: 100, sunshine_s_10min: null, humidity_pct: 60 }); + const sunEl = (place: typeof FALLBACK_VIEW.place) => + sunAt(place, new Date(Date.parse(f.observed_at) - 5 * 60_000)).elevation; + expect(sunEl(FALLBACK_VIEW.place)).toBeGreaterThan(20); + expect(sunEl(ELSEWHERE_VIEW.place)).toBeLessThan(0); + const vienna = currentWeather(f, FALLBACK_VIEW.place, NOW); + const elsewhere = currentWeather(f, ELSEWHERE_VIEW.place, NOW); + expect(vienna).toBe(weatherFromFile(f, sunEl(FALLBACK_VIEW.place))); + expect(elsewhere).toBe(weatherFromFile(f, sunEl(ELSEWHERE_VIEW.place))); + expect(vienna).not.toBe(elsewhere); + }); +}); + describe('bad instrument values', () => { it('a negative sunshine is no reading, not full cloud', () => { expect(cloudEstimate(file({ glow_wm2: null, sunshine_s_10min: -5 }), 21)).toBeNull(); @@ -165,7 +182,7 @@ describe('bad instrument values', () => { sunshine_s_10min: null, humidity_pct: 50, }); - const at = (m: number) => currentWeather(f, new Date(Date.parse(f.observed_at) + m * 60_000)); + const at = (m: number) => currentWeather(f, FALLBACK_VIEW.place, new Date(Date.parse(f.observed_at) + m * 60_000)); expect(at(0)).toBe(at(29)); }); }); @@ -194,7 +211,7 @@ describe('reading weather.json', () => { sunshine_s_10min: null, glow_wm2: null, }); - expect(currentWeather(gap, new Date('2026-11-11T22:50:00Z'))).toBe(CLEAR_SKY); + expect(currentWeather(gap, FALLBACK_VIEW.place, new Date('2026-11-11T22:50:00Z'))).toBe(CLEAR_SKY); }); it("is not another station's file", () => { expect(parseWeatherFile({ ...file(), station: 11036 })).toBeNull(); diff --git a/src/app/features/scene/ridge/weatherFeed.ts b/src/app/features/scene/ridge/weatherFeed.ts index 890e72a9..7a99ff11 100644 --- a/src/app/features/scene/ridge/weatherFeed.ts +++ b/src/app/features/scene/ridge/weatherFeed.ts @@ -7,7 +7,7 @@ // missing, unreadable, malformed or stale (below) is no observation, and no observation is a clear sky. import { WEATHER_CREDIT } from './credits'; import { sunAt } from './sunAt'; -import { FALLBACK_VIEW } from './view'; +import type { Place } from './view'; /** Reader rule of docs/weather-feed.md: the file is stale 30 minutes after it was fetched or 40 after the observation it holds (the station reports every 10). */ export const STALE_MS = 30 * 60_000; @@ -105,8 +105,8 @@ export function weatherFromFile(f: WeatherFile, sunEl: number): number { return Math.max(0.7 * cloud, mist); } -/** The weather number now: the file's, or a clear sky when there is none or it is stale (see STALE_MS) or from the future. */ -export function currentWeather(f: WeatherFile | null, now: Date = new Date()): number { +/** The weather number now, its sun taken at `place` (the View's): the file's, or a clear sky when there is none or it is stale (see STALE_MS) or from the future. */ +export function currentWeather(f: WeatherFile | null, place: Place, now: Date = new Date()): number { if (!f) return CLEAR_SKY; const fetched = now.getTime() - Date.parse(f.fetched_at); const observed = now.getTime() - Date.parse(f.observed_at); @@ -120,7 +120,7 @@ export function currentWeather(f: WeatherFile | null, now: Date = new Date()): n ) return CLEAR_SKY; // GLOW and SO are means of the ten minutes ending at observed_at: the sun of their midpoint is the one to set them against. - return weatherFromFile(f, sunAt(FALLBACK_VIEW.place, new Date(Date.parse(f.observed_at) - 5 * 60_000)).elevation); + return weatherFromFile(f, sunAt(place, new Date(Date.parse(f.observed_at) - 5 * 60_000)).elevation); } /** Fetch and parse `weather.json`; null on any failure. */ diff --git a/src/app/features/scene/skyForState.test.ts b/src/app/features/scene/skyForState.test.ts index 3252fdfe..a35f117f 100644 --- a/src/app/features/scene/skyForState.test.ts +++ b/src/app/features/scene/skyForState.test.ts @@ -1,4 +1,6 @@ import { afterEach, beforeEach, 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 { baked } from '../../../sky/baked'; import { AA, luminance } from '../../../sky/skyTokens.js'; @@ -9,6 +11,7 @@ import { ridgeDrawn, ridgeSkyFor, ridgeSkyKey, + loadWeather, terrainDrawn, terrainSkyFor, } from './skyForState'; @@ -79,7 +82,7 @@ describe('the bands the text ink needs', () => { describe('ridgeSkyFor', () => { it('carries the physical sky of the state', () => { for (const state of STATES) { - const sky = ridgeSkyFor(state, 0.3); + 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 }); } @@ -93,27 +96,39 @@ describe('ridgeSkyFor', () => { s.physical?.sun, ]; setSkyClock(() => atStandardTime(12, 0)); - expect(key(ridgeSkyFor('auto', 0.3))).toEqual(key(ridgeSkyFor('day', 0.3))); + expect(key(ridgeSkyFor('auto', FALLBACK_VIEW, 0.3))).toEqual(key(ridgeSkyFor('day', FALLBACK_VIEW, 0.3))); setSkyClock(() => atStandardTime(0, 0)); - expect(key(ridgeSkyFor('auto', 0.3))).toEqual(key(ridgeSkyFor('night', 0.3))); + expect(key(ridgeSkyFor('auto', FALLBACK_VIEW, 0.3))).toEqual(key(ridgeSkyFor('night', FALLBACK_VIEW, 0.3))); setSkyClock(() => atStandardTime(18, 10)); - expect(key(ridgeSkyFor('auto', 0.3))).toEqual(key(ridgeSkyFor('dusk', 0.3))); + expect(key(ridgeSkyFor('auto', FALLBACK_VIEW, 0.3))).toEqual(key(ridgeSkyFor('dusk', FALLBACK_VIEW, 0.3))); }); 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', 0); + const day = ridgeSkyFor('day', FALLBACK_VIEW, 0); expect(day.physical?.sun.elevation).toBeGreaterThanOrEqual(DAY_FROM); expect(day.top[2]).toBeGreaterThan(day.top[0]); - const dusk = ridgeSkyFor('dusk', 0); + const dusk = ridgeSkyFor('dusk', FALLBACK_VIEW, 0); expect(Math.abs(dusk.physical?.sun.elevation ?? 99)).toBeLessThanOrEqual(DAY_FROM); - expect(ridgeSkyFor('night', 0).physical?.sun.elevation).toBeLessThanOrEqual(-DAY_FROM); + expect(ridgeSkyFor('night', FALLBACK_VIEW, 0).physical?.sun.elevation).toBeLessThanOrEqual(-DAY_FROM); + }); + + it("is made over the View's place: the sun and the observer are the View's", () => { + const sky = ridgeSkyFor('day', 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', 0.3)).toBe(ridgeSkyKey('day', 0.3)); - expect(ridgeSkyKey('day', 0.3)).not.toBe(ridgeSkyKey('day', 0.8)); - expect(ridgeSkyKey('day', 0.3)).not.toBe(ridgeSkyKey('night', 0.3)); + 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)); }); it.each(STATES)('%s: the display is fitted to the budget its text ink needs', (state) => { @@ -121,7 +136,7 @@ describe('ridgeSkyFor', () => { const r = ridgeDrawn(state); expect(r.darkest).toBeGreaterThanOrEqual(floor); expect(r.lightest).toBeLessThanOrEqual(ceiling); - const fit = ridgeSkyFor(state, 0.3).physical?.fit; + const fit = ridgeSkyFor(state, FALLBACK_VIEW, 0.3).physical?.fit; expect(fit?.lo).toBeGreaterThanOrEqual(r.darkest - 1e-9); expect(fit?.hi).toBeLessThanOrEqual(r.lightest + 1e-9); }); @@ -367,3 +382,17 @@ describe('skyBackdrop holds the union of what the scenes draw', () => { expect(Math.min(l.low, r.darkest) - b.darkest).toBeLessThan(5e-4); }); }); + +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 () => ({}) })); + vi.stubGlobal('fetch', fetched); + const t = new Date('2030-01-01T00:00:00Z'); + await loadWeather('/w.json', FALLBACK_VIEW.place, t); + await loadWeather('/w.json', FALLBACK_VIEW.place, new Date(t.getTime() + 60_000)); + expect(fetched).toHaveBeenCalledTimes(1); + await loadWeather('/w.json', ELSEWHERE_VIEW.place, new Date(t.getTime() + 120_000)); + expect(fetched).toHaveBeenCalledTimes(2); + vi.unstubAllGlobals(); + }); +}); diff --git a/src/app/features/scene/skyForState.ts b/src/app/features/scene/skyForState.ts index 4992876f..9d80297f 100644 --- a/src/app/features/scene/skyForState.ts +++ b/src/app/features/scene/skyForState.ts @@ -8,8 +8,7 @@ import { chooseSky, skyColour, urlSky } from './terrain/terrainSky'; import type { SkyName } from './terrain/terrainSky'; import type { SkyColours, Srgb } from './ridge/skyColour'; import { makePhysicalSky } from './ridge/physicalSky'; -import { FALLBACK_VIEW } from './ridge/view'; -import type { View } from './ridge/view'; +import type { Place, View } from './ridge/view'; import { BUDGET } from './ridge/toneMap'; import { ridgeWeather, setFedWeather } from './ridge/weather'; import { currentWeather, fetchWeatherFile } from './ridge/weatherFeed'; @@ -29,21 +28,23 @@ export const DUSK_SUN_ELEVATION = 2; */ export const ridgeSkyKey = ( state: SkyState, + view: View, weather: number = ridgeWeather(), - now: Date = skyNow(), - view: View = FALLBACK_VIEW + now: Date = skyNow() ): string => `ridge:${resolveSkyState(state, now)}:${weather}:${view.place.id}`; const WEATHER_REFRESH_MS = 10 * 60_000; let weatherAt = -Infinity; +let weatherPlace = ''; /** * Read `weather.json` (the page's own, next to config.json) into the weather the ridge sky is drawn for; at most once in ten minutes. * Never throws: a missing, stale or broken file is a clear sky (`currentWeather`). */ -export async function loadWeather(url: string, now: Date = skyNow()): Promise { - if (now.getTime() - weatherAt < WEATHER_REFRESH_MS) return; +export async function loadWeather(url: string, place: Place, now: Date = skyNow()): Promise { + if (place.id === weatherPlace && now.getTime() - weatherAt < WEATHER_REFRESH_MS) return; weatherAt = now.getTime(); - setFedWeather(currentWeather(await fetchWeatherFile(url), now)); + weatherPlace = place.id; + setFedWeather(currentWeather(await fetchWeatherFile(url), place, now)); } /** @@ -53,9 +54,9 @@ export async function loadWeather(url: string, now: Date = skyNow()): Promise