From ca77bacb4a93d9814b9680f3966e296e2bf556cb Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 20 Nov 2026 23:36:06 +0100 Subject: [PATCH] Sky choice store: Auto, named or free moment resolved at the loaded place skyState.ts holds the choice, the place and the lines and resolves the band through momentFor and skyBand; resolveSkyState, LAT and the page-zone clock approximation are deleted. skyPlace.ts shares the manifest with the scene; hooks, theme and ink take an undefined sky until a place is known. Old 'ratatoskr.skyState' is read once and removed; the choice persists as 'ratatoskr.skyChoice'. Co-Authored-By: Claude Sonnet 5.5 --- src/app/features/scene/index.ts | 53 ++--- .../features/scene/ridge/skyMoment.test.ts | 201 ++++++++++++++++++ src/app/features/scene/ridge/skyTestkit.ts | 28 +++ src/app/features/scene/skyForState.ts | 47 ++-- src/app/features/scene/skyInk.ts | 4 +- src/app/features/scene/skyPlace.ts | 24 +++ src/app/features/scene/skyState.ts | 157 ++++++++------ src/app/features/scene/skyTheme.ts | 12 +- .../features/scene/standardTime.testkit.ts | 7 - src/app/hooks/useSkyState.ts | 29 +-- src/app/pages/ThemeManager.tsx | 3 + 11 files changed, 421 insertions(+), 144 deletions(-) create mode 100644 src/app/features/scene/ridge/skyMoment.test.ts create mode 100644 src/app/features/scene/ridge/skyTestkit.ts create mode 100644 src/app/features/scene/skyPlace.ts delete mode 100644 src/app/features/scene/standardTime.testkit.ts diff --git a/src/app/features/scene/index.ts b/src/app/features/scene/index.ts index aa0493ce..3a53cb02 100644 --- a/src/app/features/scene/index.ts +++ b/src/app/features/scene/index.ts @@ -1,12 +1,11 @@ import type { Scene, SceneOptions } from './Scene'; import { BackgroundSceneConfig, Capabilities, SceneTier, resolveTier } from './tier'; import { debugOverlaysAllowed } from './debugOverlays'; -import { getConstellationLines, getSkyState, subscribe } from './skyState'; -import type { SkyState } from './skyState'; +import { getConstellationLines, getSkyChoice, subscribe } from './skyState'; +import type { SkyChoice } from './ridge/skyMoment'; +import { ensureSkyPlace } from './skyPlace'; import type { SkyColours } from './ridge/skyColour'; import type { Backdrop } from './ridge/Backdrop'; -import { loadManifest } from './ridge/manifest'; -import type { RidgeManifest } from './ridge/manifest'; import { FALLBACK_VIEW } from './ridge/view'; export type { Scene, SceneStats } from './Scene'; @@ -15,7 +14,7 @@ export type { SceneStyle, SceneTier } from './tier'; export type StartOptions = Omit & { /** A shader failed to compile, or the scene chunk failed to load. The host keeps its ground. */ onCompileFail?: (e: Error) => void; - /** A rebuild for a new sky state made no scene: the host puts the CSS ground back (as on a lost context). */ + /** A rebuild for a new sky made no scene: the host puts the CSS ground back (as on a lost context). */ onInactive?: () => void; /** A rebuild made a scene again: the host lets it show. */ onActive?: () => void; @@ -28,20 +27,6 @@ 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; @@ -52,7 +37,7 @@ interface Prepared { async function prepare( config: BackgroundSceneConfig | undefined, options: StartOptions & { tier: SceneTier; debug?: boolean }, - state: SkyState + choice: SkyChoice ): Promise { // Whatever throws in making the scene is a compile failure, as whatever throws in loading it. const guarded = (make: () => Scene | null): Prepared => ({ @@ -74,7 +59,7 @@ async function prepare( return guarded(() => createScene(options)); } const { createRidgeScene } = await import('./ridge/Ridge'); - const { manifest, fail } = await manifestOf(config); + const { manifest, fail } = await ensureSkyPlace(config); await loadWeather(weatherUrl(), (manifest?.view ?? FALLBACK_VIEW).place); // The cards load with the scene chunk and the weather, and are lit here for this sky (once per build: a sky change comes through a rebuild, never per // frame), so createRidgeScene stays synchronous. Any failure, a missing WebGL2 included, is the sky alone. @@ -83,7 +68,7 @@ async function prepare( let planesFail: Error | null = fail; if (manifest) { try { - const manifestSky = ridgeSkyFor(state, manifest.view); + const manifestSky = ridgeSkyFor(choice, manifest.view); sky = manifestSky; const { loadBackdrop } = await import('./ridge/Backdrop'); backdrop = await loadBackdrop( @@ -100,7 +85,7 @@ async function prepare( const made = guarded(() => createRidgeScene({ ...options, - sky: sky ?? ridgeSkyFor(state, FALLBACK_VIEW), + sky: sky ?? ridgeSkyFor(choice, FALLBACK_VIEW), backdrop: backdrop ?? undefined, lines: getConstellationLines(), }) @@ -114,17 +99,17 @@ async function prepare( /** * What a rebuild is for: the sky options the scene would be built from. A change of choice that draws the same sky - * (Day picked while the clock says day, 'auto' to the fixed state it resolves to) is not a rebuild. + * (Auto picked as a named moment it already is drawing) is not a rebuild. */ async function skyKey( config: BackgroundSceneConfig | undefined, - state: SkyState + choice: SkyChoice ): Promise { try { const { loadWeather, ridgeSkyKey } = await import('./skyForState'); - const view = (await manifestOf(config)).manifest?.view ?? FALLBACK_VIEW; + const view = (await ensureSkyPlace(config)).manifest?.view ?? FALLBACK_VIEW; await loadWeather(weatherUrl(), view.place); - return ridgeSkyKey(state, view); + return ridgeSkyKey(choice, view); } catch { // The chunk failed to load: no key, so every change rebuilds (and `create` reports the failure). return null; @@ -138,7 +123,7 @@ async function skyKey( * "keep the CSS ground", including when that chunk fails to load (offline, stale deploy): the * failure goes to onCompileFail and nothing throws. * - * The ridge scene bakes its sky once, so it follows the sky (`skyState.ts`: the choice, resolved, so 'auto' follows the clock) by + * The ridge scene bakes its sky once, so it follows the sky (`skyState.ts`: the choice at the place, so Auto follows the clock) by * being rebuilt on the same canvas when it changes: the door subscribes on start and the returned * scene's `dispose` unsubscribes. The pull-back restarts from the tree; a later `login()` is * replayed on the new scene. The ray-march scene has one fixed dusk and ignores the state. @@ -158,10 +143,10 @@ export async function startBackgroundScene( if (!planesFail && planesFailed) options.onPlanesOk?.(); planesFailed = planesFail !== null; }; - const prepared = (state: SkyState) => prepare(config, { ...options, tier, debug }, state); - const state = getSkyState(); - const key0 = config?.style === 'raymarch' ? null : await skyKey(config, state); - const firstReady = await prepared(state); + const prepared = (choice: SkyChoice) => prepare(config, { ...options, tier, debug }, choice); + const choice = getSkyChoice(); + const key0 = config?.style === 'raymarch' ? null : await skyKey(config, choice); + const firstReady = await prepared(choice); const first = firstReady.make(); if (!first || config?.style === 'raymarch') return first; announce(firstReady.planesFail); @@ -174,9 +159,9 @@ export async function startBackgroundScene( // A rebuild is for a different sky ('auto' crossing a boundary, a new choice), not for a repeat of the one drawn. const rebuild = async () => { // The choice can move while the key is awaited; that change has its own rebuild, so this one stands down. - const next = getSkyState(); + const next = getSkyChoice(); const key = await skyKey(config, next); - if (getSkyState() !== next) return; + if (getSkyChoice() !== next) return; if ((key !== null && key === built) || disposed) return; generation += 1; const mine = generation; diff --git a/src/app/features/scene/ridge/skyMoment.test.ts b/src/app/features/scene/ridge/skyMoment.test.ts new file mode 100644 index 00000000..cd840d4f --- /dev/null +++ b/src/app/features/scene/ridge/skyMoment.test.ts @@ -0,0 +1,201 @@ +import { describe, expect, it } from 'vitest'; +import { + DAY_FROM, + MOMENT_IDS, + localDate, + localMinutes, + momentFor, + momentKey, + skyBand, + zonedInstant, +} from './skyMoment'; +import type { MomentId } from './skyMoment'; +import { sunAt } from './sunAt'; +import type { Place } from './view'; + +const PLACES: Record = { + vienna: { id: 'vienna', lat: 48.19, lon: 16.35, altitudeKm: 0.18, tz: 'Europe/Vienna' }, + matterhorn: { id: 'matterhorn', lat: 45.98, lon: 7.78, altitudeKm: 3.1, tz: 'Europe/Zurich' }, + fuji: { id: 'fuji', lat: 35.31, lon: 138.63, altitudeKm: 0.4, tz: 'Asia/Tokyo' }, + amadablam: { id: 'amadablam', lat: 27.9, lon: 86.9, altitudeKm: 4.2, tz: 'Asia/Kathmandu' }, + halfdome: { id: 'halfdome', lat: 37.73, lon: -119.55, altitudeKm: 1.2, tz: 'America/Los_Angeles' }, +}; +const DAYS = ['2026-06-21', '2026-12-21', '2026-03-20']; +const MIN = 60_000; + +/** The place-local noon of `date`: any instant of that local day names it. */ +const during = (date: string, p: Place): Date => zonedInstant(date, 720, p.tz); +const at = (id: MomentId, p: Place, date: string): Date => + momentFor({ kind: 'named', id }, p, during(date, p)); +const el = (p: Place, t: Date): number => sunAt(p, t).elevation; + +describe('the named moments', () => { + describe.each(Object.entries(PLACES))('%s', (_name, p) => { + it.each(DAYS)('%s: dawn < morning < noon < golden < dusk inside the local day, night after noon', (date) => { + const t = Object.fromEntries(MOMENT_IDS.map((id) => [id, at(id, p, date).getTime()])); + expect(t.dawn).toBeLessThan(t.morning); + expect(t.morning).toBeLessThan(t.noon); + expect(t.noon).toBeLessThan(t.golden); + expect(t.golden).toBeLessThan(t.dusk); + expect(t.night).toBeGreaterThan(t.noon); + (['dawn', 'morning', 'noon', 'golden', 'dusk'] as const).forEach((id) => + expect(localDate(new Date(t[id]), p.tz)).toBe(date) + ); + }); + + it.each(DAYS)('%s: each crossing is at its table elevation, within 0.05 degrees', (date) => { + const noonEl = el(p, at('noon', p, date)); + expect(el(p, at('dawn', p, date))).toBeCloseTo(-3, 1); + expect(el(p, at('morning', p, date))).toBeCloseTo(Math.min(15, noonEl / 2), 1); + expect(el(p, at('golden', p, date))).toBeCloseTo(4, 1); + expect(el(p, at('dusk', p, date))).toBeCloseTo(-3, 1); + }); + + it.each(DAYS)('%s: noon is the day maximum and night the lowest of the 24 h after it', (date) => { + const noon = at('noon', p, date); + const night = at('night', p, date); + for (let m = 0; m < 24 * 60; m += 5) { + const t = new Date(noon.getTime() + m * MIN); + expect(el(p, t)).toBeGreaterThanOrEqual(el(p, night) - 1e-3); + } + const dayStart = zonedInstant(date, 0, p.tz).getTime(); + for (let m = 0; m < 24 * 60; m += 5) { + expect(el(p, new Date(dayStart + m * MIN))).toBeLessThanOrEqual(el(p, noon) + 1e-3); + } + }); + }); + + it('morning is half the noon elevation at Vienna in December (the 15 degree rule would never be met)', () => { + const p = PLACES.vienna; + const noonEl = el(p, at('noon', p, '2026-12-21')); + expect(noonEl).toBeLessThan(30); + expect(el(p, at('morning', p, '2026-12-21'))).toBeCloseTo(noonEl / 2, 1); + expect(el(p, at('morning', p, '2026-06-21'))).toBeCloseTo(15, 1); + }); + + it('a named moment is today of the place: the same local date gives the same instant, the next day another', () => { + const p = PLACES.fuji; + const a = momentFor({ kind: 'named', id: 'dusk' }, p, zonedInstant('2026-12-21', 30, p.tz)); + const b = momentFor({ kind: 'named', id: 'dusk' }, p, zonedInstant('2026-12-21', 1400, p.tz)); + const c = momentFor({ kind: 'named', id: 'dusk' }, p, zonedInstant('2026-12-22', 30, p.tz)); + expect(a.getTime()).toBe(b.getTime()); + expect(c.getTime()).not.toBe(a.getTime()); + }); + + it('is total at a pole, where there is no dawn or no dusk: it falls to noon or midnight', () => { + const pole: Place = { id: 'pole', lat: 80, lon: 0, altitudeKm: 0, tz: 'UTC' }; + for (const date of ['2026-06-21', '2026-12-21']) { + const now = zonedInstant(date, 720, 'UTC'); + for (const id of MOMENT_IDS) { + const t = momentFor({ kind: 'named', id }, pole, now); + expect(Number.isFinite(t.getTime())).toBe(true); + } + } + const june = zonedInstant('2026-06-21', 720, 'UTC'); + expect(momentFor({ kind: 'named', id: 'dawn' }, pole, june).getTime()).toBe( + momentFor({ kind: 'named', id: 'noon' }, pole, june).getTime() + ); + }); +}); + +describe('zones', () => { + it.each(['Europe/Vienna', 'Asia/Tokyo', 'Asia/Kathmandu', 'America/Phoenix'])( + '%s: zonedInstant round-trips every minute of a day', + (tz) => { + for (let m = 0; m < 1440; m += 1) { + const t = zonedInstant('2026-06-21', m, tz); + expect(localDate(t, tz)).toBe('2026-06-21'); + expect(localMinutes(t, tz)).toBe(m); + } + } + ); + + it('Kathmandu is UTC+5:45 and Phoenix has no daylight saving', () => { + expect(zonedInstant('2026-12-21', 720, 'Asia/Kathmandu').toISOString()).toBe('2026-12-21T06:15:00.000Z'); + expect(zonedInstant('2026-07-01', 720, 'America/Phoenix').toISOString()).toBe('2026-07-01T19:00:00.000Z'); + }); + + it('a wall time in the spring-forward gap lands after it; one that happens twice is the first', () => { + // Vienna, 2026-03-29: 02:00 became 03:00 (01:00Z). 2026-10-25: 03:00 became 02:00 (01:00Z). + expect(zonedInstant('2026-03-29', 150, 'Europe/Vienna').toISOString()).toBe('2026-03-29T01:30:00.000Z'); + expect(zonedInstant('2026-10-25', 150, 'Europe/Vienna').toISOString()).toBe('2026-10-25T00:30:00.000Z'); + }); + + it('the place decides, not the zone of the client', () => { + const p = PLACES.fuji; + const probe = () => ({ + noon: momentFor({ kind: 'named', id: 'noon' }, p, new Date('2026-12-21T05:00:00Z')).getTime(), + free: momentFor({ kind: 'free', date: '2026-07-15', minutes: 330 }, p, new Date()).getTime(), + date: localDate(new Date('2026-12-21T16:00:00Z'), p.tz), + zi: zonedInstant('2026-03-29', 150, 'Europe/Vienna').getTime(), + }); + const was = process.env.TZ; + try { + const seen = ['Pacific/Kiritimati', 'America/Anchorage', 'UTC'].map((tz) => { + process.env.TZ = tz; + return probe(); + }); + expect(seen[1]).toEqual(seen[0]); + expect(seen[2]).toEqual(seen[0]); + } finally { + if (was === undefined) delete process.env.TZ; + else process.env.TZ = was; + } + }); +}); + +describe('Fuji dawn is Japanese dawn', () => { + it('lands in the Japanese morning, east of south-east, and a world away from the Vienna one', () => { + const fuji = PLACES.fuji; + const now = new Date('2026-12-21T04:00:00Z'); // local noon at Fuji + const t = momentFor({ kind: 'named', id: 'dawn' }, fuji, now); + const hourUtc = t.getUTCHours() + t.getUTCMinutes() / 60; + expect(t.getUTCDate()).toBe(20); // the previous UTC day + expect(hourUtc).toBeGreaterThan(20.5); + expect(hourUtc).toBeLessThan(22); + const s = sunAt(fuji, t); + expect(s.elevation).toBeCloseTo(-3, 1); + expect(s.azimuth).toBeGreaterThan(110); + expect(s.azimuth).toBeLessThan(125); + const vienna = momentFor({ kind: 'named', id: 'dawn' }, PLACES.vienna, now); + expect(Math.abs(vienna.getTime() - t.getTime()) / 3_600_000).toBeGreaterThan(7); + expect(Math.abs(vienna.getTime() - t.getTime()) / 3_600_000).toBeLessThan(9.5); + }); +}); + +describe('purity and bands', () => { + it('auto is the time it is given', () => { + const now = new Date('2026-05-05T05:05:05Z'); + expect(momentFor({ kind: 'auto' }, PLACES.vienna, now)).toBe(now); + expect(momentKey({ kind: 'auto' }, PLACES.vienna, now)).toBe('live'); + }); + + it('a free moment is the place-local wall time, held inside 1900..2100', () => { + const p = PLACES.vienna; + const t = momentFor({ kind: 'free', date: '2026-12-21', minutes: 400 }, p, new Date()); + expect(localDate(t, p.tz)).toBe('2026-12-21'); + expect(localMinutes(t, p.tz)).toBe(400); + expect(localDate(momentFor({ kind: 'free', date: '1800-01-01', minutes: 0 }, p, new Date()), p.tz)).toBe('1900-01-01'); + expect(localDate(momentFor({ kind: 'free', date: '2999-05-05', minutes: 0 }, p, new Date()), p.tz)).toBe('2100-12-31'); + }); + + it('skyBand: day at 6.0, night at -6.0, dusk between', () => { + expect(skyBand(DAY_FROM)).toBe('day'); + expect(skyBand(-DAY_FROM)).toBe('night'); + expect(skyBand(DAY_FROM - 0.001)).toBe('dusk'); + expect(skyBand(-DAY_FROM + 0.001)).toBe('dusk'); + expect(skyBand(0)).toBe('dusk'); + expect(skyBand(80)).toBe('day'); + expect(skyBand(-80)).toBe('night'); + }); + + it('the key of a moment follows its local date and id, or its date and minutes', () => { + const p = PLACES.vienna; + const n = { kind: 'named', id: 'noon' } as const; + expect(momentKey(n, p, new Date('2026-06-21T10:00:00Z'))).toBe(momentKey(n, p, new Date('2026-06-21T20:00:00Z'))); + expect(momentKey(n, p, new Date('2026-06-21T10:00:00Z'))).not.toBe(momentKey(n, p, new Date('2026-06-22T10:00:00Z'))); + expect(momentKey({ kind: 'free', date: '2026-06-21', minutes: 5 }, p, new Date())).not.toBe( + momentKey({ kind: 'free', date: '2026-06-21', minutes: 10 }, p, new Date()) + ); + }); +}); diff --git a/src/app/features/scene/ridge/skyTestkit.ts b/src/app/features/scene/ridge/skyTestkit.ts new file mode 100644 index 00000000..e66a0731 --- /dev/null +++ b/src/app/features/scene/ridge/skyTestkit.ts @@ -0,0 +1,28 @@ +// Test helpers for the sky: a moment named by the clock of the place, and the sun of a band. Tests only. +import { momentFor } from './skyMoment'; +import type { FixedSkyState } from './skyMoment'; +import { sunAt } from './sunAt'; +import type { SunSample } from './sunAt'; +import { FALLBACK_VIEW } from './view'; +import type { Place } from './view'; + +const VIENNA = FALLBACK_VIEW.place; + +/** 22 September 2026 at h:m of local solar time at Vienna (the equinox: the sun is up from about 06:00 to 18:00 and the equation of time is a few minutes). */ +export const atSolarTime = (h: number, m = 0): Date => + new Date(Date.UTC(2026, 8, 22, h, m) - VIENNA.lon * 4 * 60_000); + +/** The sun of a band on the local day of `date` at `place`: Day is noon, Dusk the evening's -3 degrees, Night solar midnight. */ +export const sunOfBand = ( + place: Place, + band: FixedSkyState, + date: Date, +): SunSample => + sunAt( + place, + momentFor( + { kind: 'named', id: band === 'day' ? 'noon' : band }, + place, + date + ) + ); diff --git a/src/app/features/scene/skyForState.ts b/src/app/features/scene/skyForState.ts index 988c7dee..75dc28c1 100644 --- a/src/app/features/scene/skyForState.ts +++ b/src/app/features/scene/skyForState.ts @@ -1,27 +1,36 @@ -// What the ridge scene is told for a sky state. 'auto' is a choice, not a sky: it draws the sky it -// resolves to (`resolveSkyState`, the clock), so the scene paints one of day, dusk or night, fitted to that -// state's luminance budget (ridge/toneMap.ts). +// What the ridge scene is told for a sky choice. The choice is not a sky: `momentFor` (ridge/skyMoment.ts) decides the instant it draws, +// the sun at that instant is what the physical sky is lit from, and its band (`skyBand`) picks the display's luminance budget (ridge/toneMap.ts). import type { SkyColours } from './ridge/skyColour'; import { makePhysicalSky } from './ridge/physicalSky'; +import { momentFor, momentKey, skyBand } from './ridge/skyMoment'; +import type { FixedSkyState, SkyChoice } from './ridge/skyMoment'; +import { sunAt } from './ridge/sunAt'; import type { Place, View } from './ridge/view'; import { BUDGET } from './ridge/toneMap'; import { ridgeWeather, setFedWeather } from './ridge/weather'; import { currentWeather, fetchWeatherFile } from './ridge/weatherFeed'; -import { getConstellationLines, resolveSkyState, skyNow } from './skyState'; -import type { SkyState } from './skyState'; +import { getConstellationLines, skyNow } from './skyState'; + +/** A clear sky: what a free moment is drawn with (ruling ridge-weather-on-frozen-moments: today's weather says nothing of another date). */ +export const CLEAR_SKY = 0; + +/** The weather a choice is drawn with: a free moment is clear; Auto and the named moments of today draw today's weather. */ +const weatherFor = (choice: SkyChoice): number => + choice.kind === 'free' ? CLEAR_SKY : ridgeWeather(); /** - * What a rebuild of the ridge scene is for: the fixed state it draws, the weather and, at night, the constellation lines. The sun moves with the clock inside a state and - * is not part of the key (the scene is baked at its start), as the sky was one gradient per state before. + * What a rebuild of the ridge scene is for: the band and moment it draws, the weather, the place and, at night, the constellation lines. + * The sun moves with the clock inside an Auto band and is not part of the key (the scene is baked at its start); a named moment is its id + * and local date, a free one its date and minutes. */ export const ridgeSkyKey = ( - state: SkyState, + choice: SkyChoice, view: View, - weather: number = ridgeWeather(), + weather: number = weatherFor(choice), now: Date = skyNow() ): string => { - const fixed = resolveSkyState(state, now); - return `ridge:${fixed}:${weather}:${view.place.id}${fixed === 'night' && getConstellationLines() ? ':lines' : ''}`; + const band = skyBand(sunAt(view.place, momentFor(choice, view.place, now)).elevation); + return `ridge:${band}:${weather}:${view.place.id}:${momentKey(choice, view.place, now)}${band === 'night' && getConstellationLines() ? ':lines' : ''}`; }; const WEATHER_REFRESH_MS = 10 * 60_000; @@ -39,18 +48,17 @@ export async function loadWeather(url: string, place: Place, now: Date = skyNow( } /** - * The ridge scene's `sky` option: the physical sky over the View's place for the state ('auto': the real sun now; a forced state: the - * sun of today at a moment inside it, `sunForState`), as a palette for the layers and stars plus the `physical` sky the host canvas + * The ridge scene's `sky` option: the physical sky over the View's place at the instant the choice draws (`momentFor`: Auto the real sun now, + * a named or free moment its own), as a palette for the layers and stars plus the `physical` sky the host canvas * is painted from. The atmosphere LUTs are baked here, once per scene start (tens of ms). */ export function ridgeSkyFor( - state: SkyState, + choice: SkyChoice, view: View, - weather: number = ridgeWeather(), + weather: number = weatherFor(choice), now: Date = skyNow() ): SkyColours { - const fixed = resolveSkyState(state, now); - const physical = makePhysicalSky(fixed, now, weather, view); + const physical = makePhysicalSky(sunAt(view.place, momentFor(choice, view.place, now)), weather, view); return { ...physical.stops, physical, @@ -67,8 +75,7 @@ export interface Range { * The ridge sky's range: what its display is fitted to hold (`BUDGET`, toneMap.ts), which `physicalSky.test.ts` proves over the * sun's whole year over Vienna. Dark ink needs the floor; light ink the ceiling. */ -export function ridgeDrawn(state: SkyState): Range { - const b = BUDGET[resolveSkyState(state)]; +export function ridgeDrawn(band: FixedSkyState): Range { + const b = BUDGET[band]; return { darkest: b.floor, lightest: b.ceiling }; } - diff --git a/src/app/features/scene/skyInk.ts b/src/app/features/scene/skyInk.ts index 9c62f717..d3aa2028 100644 --- a/src/app/features/scene/skyInk.ts +++ b/src/app/features/scene/skyInk.ts @@ -31,9 +31,9 @@ export interface SkyInk { export const sceneInk = ( themeId: SkyThemeId | undefined, sceneOn: boolean, - state: FixedSkyState, + state: FixedSkyState | undefined, phone: boolean -): SkyInk | undefined => (themeId && sceneOn ? { state, phone } : undefined); +): SkyInk | undefined => (themeId && sceneOn && state ? { state, phone } : undefined); /** WCAG relative luminance of the lightest 24x12 patch of terrain behind the timeline. */ export const LIGHTEST_PATCH: Record = { diff --git a/src/app/features/scene/skyPlace.ts b/src/app/features/scene/skyPlace.ts new file mode 100644 index 00000000..227b5d09 --- /dev/null +++ b/src/app/features/scene/skyPlace.ts @@ -0,0 +1,24 @@ +// The place the sky is over: the baked place's manifest, loaded once and shared. 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; its Place is what the sky store (skyState.ts) resolves the drawn sky for, so the +// ink and the scene read one place. Main-chunk safe: no sky, no ridge code, only the manifest parser and the store. +import type { BackgroundSceneConfig } from './tier'; +import { loadManifest } from './ridge/manifest'; +import type { RidgeManifest } from './ridge/manifest'; +import { setSkyPlace } from './skyState'; + +/** + * Load the manifest of the place `config` names (unknown or absent: the index's default, as `loadManifest` decides) and make its place the + * sky's. Safe to call whenever a reader wants the manifest: the load is memoised and setting the same place is not a change. A failed load + * leaves the place as it was (none, at first: no sky is drawn for ink) and is returned, so the scene can be the sky alone. + */ +export async function ensureSkyPlace( + config: Pick | undefined +): Promise<{ manifest: RidgeManifest | null; fail: Error | null }> { + try { + const manifest = await loadManifest(import.meta.env.BASE_URL, config?.place); + setSkyPlace(manifest.view.place); + return { manifest, fail: null }; + } catch (e) { + return { manifest: null, fail: e instanceof Error ? e : new Error(String(e)) }; + } +} diff --git a/src/app/features/scene/skyState.ts b/src/app/features/scene/skyState.ts index 1d93b07e..b4b34361 100644 --- a/src/app/features/scene/skyState.ts +++ b/src/app/features/scene/skyState.ts @@ -1,54 +1,67 @@ -// Which sky the signed-out page is drawn against. The choice is one value, kept in one -// localStorage key; whoever draws the sky (the scene, the title bar's control) reads it here. -// 'auto' is a choice, not a sky: it resolves from the clock to day, dusk or night -// (`resolveSkyState`), and every sky drawn is one of those three. -import { sunElevation } from '../../../sky/sun.js'; +// Which sky the signed-out page is drawn against: three small stores and the notice that one of them moved. The viewer's choice (Auto, a +// named moment, a free moment), the place the sky is over, and the constellation lines. They decide nothing: which instant is drawn is +// `momentFor` and which band it is, `skyBand` (ridge/skyMoment.ts); the resolved sky here is those two applied to the stores. +import { MOMENT_IDS, FREE_DATE_MAX, FREE_DATE_MIN, isDate, momentFor, skyBand } from './ridge/skyMoment'; +import type { FixedSkyState, MomentId, SkyChoice } from './ridge/skyMoment'; +import { sunAt } from './ridge/sunAt'; +import type { Place } from './ridge/view'; -export type SkyState = 'auto' | 'day' | 'dusk' | 'night'; +export const SKY_CHOICE_KEY = 'ratatoskr.skyChoice'; -export const SKY_STATES: readonly SkyState[] = ['auto', 'day', 'dusk', 'night']; -export const SKY_STATE_KEY = 'ratatoskr.skyState'; +const AUTO: SkyChoice = { kind: 'auto' }; -const isSkyState = (v: unknown): v is SkyState => SKY_STATES.includes(v as SkyState); +/** A stored value as a choice, or undefined when it is not one (wrong shape, unknown moment, a date outside 1900..2100, minutes outside 0..1439). */ +export function parseSkyChoice(raw: unknown): SkyChoice | undefined { + if (typeof raw !== 'object' || raw === null) return undefined; + const c = raw as Record; + if (c.kind === 'auto') return AUTO; + if (c.kind === 'named' && MOMENT_IDS.includes(c.id as MomentId)) { + return { kind: 'named', id: c.id as MomentId }; + } + if ( + c.kind === 'free' && + isDate(c.date) && + c.date >= FREE_DATE_MIN && + c.date <= FREE_DATE_MAX && + Number.isInteger(c.minutes) && + (c.minutes as number) >= 0 && + (c.minutes as number) <= 1439 + ) { + return { kind: 'free', date: c.date, minutes: c.minutes as number }; + } + return undefined; +} -function load(): SkyState { +const same = (a: SkyChoice, b: SkyChoice): boolean => JSON.stringify(a) === JSON.stringify(b); + +// The sky menu once held Auto, Day, Dusk and Night under another key. It is read once, here, and removed: Day became Noon. +const OLD_KEY = 'ratatoskr.skyState'; +const FROM_OLD = new Map([ + ['auto', AUTO], + ['day', { kind: 'named', id: 'noon' }], + ['dusk', { kind: 'named', id: 'dusk' }], + ['night', { kind: 'named', id: 'night' }], +]); + +function load(): SkyChoice { try { - const stored = localStorage.getItem(SKY_STATE_KEY); - return isSkyState(stored) ? stored : 'auto'; + const old = localStorage.getItem(OLD_KEY); + if (old !== null) { + localStorage.removeItem(OLD_KEY); + const migrated = FROM_OLD.get(old); + if (migrated && localStorage.getItem(SKY_CHOICE_KEY) === null) { + localStorage.setItem(SKY_CHOICE_KEY, JSON.stringify(migrated)); + return migrated; + } + } + const stored = localStorage.getItem(SKY_CHOICE_KEY); + return (stored !== null && parseSkyChoice(JSON.parse(stored))) || AUTO; } catch { - return 'auto'; + return AUTO; } } -/** - * The three skies ever drawn. Each has the luminance band its theme ink needs against bare sky (WCAG relative luminance, - * the `luminance` of src/sky/skyTokens.js): day, at least 0.2983 (the dark text ink #342d25); dusk, at least 0.4554 (the link - * #2a4f27); night, at most 0.0931 (the light text ink #aeccff). The ridge scene's display budgets (ridge/toneMap.ts `BUDGET`) - * sit inside them. - */ -export type FixedSkyState = 'day' | 'dusk' | 'night'; - -/** Where the clock puts the sun: the latitude the skies are baked for (src/sky/skyTokens.js MOMENTS), the longitude of this timezone. */ -const LAT = 45; -/** Sun elevation (degrees) from which it is day, and below the negative of which it is night; between, dusk (dawn included). */ -export const DAY_FROM = 6; - let clock: () => Date = () => new Date(); -/** Minutes west of UTC of this timezone's standard time (the larger of its January and July offsets), so daylight saving does not move the sun. */ -export const standardOffsetMinutes = (now: Date): number => - Math.max( - new Date(now.getFullYear(), 0, 1).getTimezoneOffset(), - new Date(now.getFullYear(), 6, 1).getTimezoneOffset() - ); - -/** The fixed sky a choice draws now: itself, or for 'auto' the sky the sun's elevation here calls for. */ -export function resolveSkyState(s: SkyState, now: Date = clock()): FixedSkyState { - if (s !== 'auto') return s; - const lon = -standardOffsetMinutes(now) / 4; - const el = sunElevation(now, LAT, lon) as number; - if (el >= DAY_FROM) return 'day'; - return el <= -DAY_FROM ? 'night' : 'dusk'; -} /** The constellation lines (a hidden extra, ruling ridge-constellation-lines-hidden-extra): on or off, per viewer, off by default. */ export const SKY_LINES_KEY = 'ratatoskr.skyLines'; @@ -66,33 +79,41 @@ export const getConstellationLines = (): boolean => { return lines; }; -let current: SkyState | undefined; -const listeners = new Set<(s: FixedSkyState) => void>(); +let current: SkyChoice | undefined; +let place: Place | undefined; +const listeners = new Set<(s: FixedSkyState | undefined) => void>(); let timer: ReturnType | undefined; let shown: FixedSkyState | undefined; const TICK_MS = 60_000; /** The choice (what the control shows). */ -export const getSkyState = (): SkyState => { +export const getSkyChoice = (): SkyChoice => { current ??= load(); return current; }; -/** The sky being drawn: the choice, resolved. */ -export const getResolvedSkyState = (): FixedSkyState => resolveSkyState(getSkyState()); +/** The place the sky is over: the loaded manifest's, set by skyPlace.ts; undefined until one is known. */ +export const getSkyPlace = (): Place | undefined => place; + +/** The moment the sky is drawn for: the real time, or the test clock. */ +export const skyNow = (): Date => clock(); + +/** The band being drawn: the choice at the place, through `momentFor` and `skyBand`; undefined until a place is known (no sky is drawn for ink). */ +export const getResolvedSkyState = (): FixedSkyState | undefined => + place && skyBand(sunAt(place, momentFor(getSkyChoice(), place, skyNow())).elevation); const emit = () => { shown = getResolvedSkyState(); - [...listeners].forEach((cb) => cb(shown as FixedSkyState)); + [...listeners].forEach((cb) => cb(shown)); }; -// While anyone listens and the choice is 'auto', one timer checks the clock each minute and tells -// listeners when the resolved sky changes from the one last told (`shown`, set when telling and when the +// While anyone listens and the choice is Auto, one timer checks the clock each minute and tells +// listeners when the resolved band changes from the one last told (`shown`, set when telling and when the // first listener arrives, never by a later arrival or departure). Otherwise there is no timer. function sync(): void { clearTimeout(timer); timer = undefined; - if (listeners.size === 0 || getSkyState() !== 'auto') return; + if (listeners.size === 0 || getSkyChoice().kind !== 'auto') return; const tick = () => { if (getResolvedSkyState() !== shown) emit(); timer = setTimeout(tick, TICK_MS); @@ -100,21 +121,19 @@ function sync(): void { timer = setTimeout(tick, TICK_MS); } -/** The moment the sky is drawn for: the real time, or the test clock. */ -export const skyNow = (): Date => clock(); - /** Replace the clock (tests); no argument restores the real one. */ export function setSkyClock(now?: () => Date): void { clock = now ?? (() => new Date()); sync(); } -export function setSkyState(s: SkyState): void { - if (!isSkyState(s)) return; - const changed = s !== getSkyState(); - current = s; +export function setSkyChoice(c: SkyChoice): void { + const next = parseSkyChoice(c); + if (!next) return; + const changed = !same(next, getSkyChoice()); + current = next; try { - localStorage.setItem(SKY_STATE_KEY, s); + localStorage.setItem(SKY_CHOICE_KEY, JSON.stringify(next)); } catch { // Storage is refused (private mode, quota): the choice holds for this page load only. } @@ -124,12 +143,22 @@ export function setSkyState(s: SkyState): void { } } +/** The place the sky is over (skyPlace.ts, once the manifest is loaded). Listeners hear it, since the band depends on it. */ +export function setSkyPlace(p: Place | undefined): void { + if (p?.id === place?.id && p?.tz === place?.tz && p?.lat === place?.lat && p?.lon === place?.lon) { + return; + } + place = p; + emit(); +} + /** - * A pick in the sky menu. Picking a state sets it; picking Night while the choice already is Night toggles the constellation lines, which + * A pick in the sky menu. Picking a choice sets it; picking Night while the choice already is Night toggles the constellation lines, which * listeners hear as a sky change (the scene is rebuilt for it: `ridgeSkyKey` carries the flag). */ -export function pickSkyState(s: SkyState): void { - if (s === 'night' && getSkyState() === 'night') { +export function pickSkyChoice(c: SkyChoice): void { + const now = getSkyChoice(); + if (c.kind === 'named' && c.id === 'night' && now.kind === 'named' && now.id === 'night') { lines = !getConstellationLines(); try { localStorage.setItem(SKY_LINES_KEY, lines ? 'on' : 'off'); @@ -139,11 +168,11 @@ export function pickSkyState(s: SkyState): void { emit(); return; } - setSkyState(s); + setSkyChoice(c); } -/** Listeners hear the resolved sky: on a change of choice, and while 'auto', when the clock crosses a boundary. */ -export function subscribe(cb: (s: FixedSkyState) => void): () => void { +/** Listeners hear the resolved band: on a change of choice or place, and while Auto, when the clock crosses a boundary. */ +export function subscribe(cb: (s: FixedSkyState | undefined) => void): () => void { if (listeners.size === 0) shown = getResolvedSkyState(); listeners.add(cb); sync(); diff --git a/src/app/features/scene/skyTheme.ts b/src/app/features/scene/skyTheme.ts index fef313ec..1d54ee8e 100644 --- a/src/app/features/scene/skyTheme.ts +++ b/src/app/features/scene/skyTheme.ts @@ -1,8 +1,8 @@ -// Which theme the drawn sky lights the page with. While a scene is on, the sky being drawn (the fixed pick, or the -// clock's state under 'auto'; `useResolvedSkyState`) alone decides the theme and, with it, the ink: Day and Dusk +// Which theme the drawn sky lights the page with. While a scene is on, the sky being drawn (the +// choice at the place; `useResolvedSkyState`) alone decides the theme and, with it, the ink: Day and Dusk // wear Noonday Sky, Night wears Midnight Sky. A person's own theme (the theme menu) stands only where no sky is // drawn, that is with the scene off. -import type { FixedSkyState } from './skyState'; +import type { FixedSkyState } from './ridge/skyMoment'; export type SkyThemeId = 'midnight-sky' | 'noonday-sky'; @@ -13,5 +13,7 @@ const BY_STATE: Record = { }; /** The theme the page wears: the drawn sky's while a scene is on, otherwise none (the person's theme stands). */ -export const sceneThemeId = (resolved: FixedSkyState, sceneOn: boolean): SkyThemeId | undefined => - sceneOn ? BY_STATE[resolved] : undefined; +export const sceneThemeId = ( + resolved: FixedSkyState | undefined, + sceneOn: boolean +): SkyThemeId | undefined => (sceneOn && resolved ? BY_STATE[resolved] : undefined); diff --git a/src/app/features/scene/standardTime.testkit.ts b/src/app/features/scene/standardTime.testkit.ts deleted file mode 100644 index a6966238..00000000 --- a/src/app/features/scene/standardTime.testkit.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { standardOffsetMinutes } from './skyState'; - -/** 22 September 2026 at h:m of local solar time as the sky clock reads it (standard time, whatever daylight saving says). */ -export const atStandardTime = (h: number, m = 0): Date => { - const probe = new Date(2026, 8, 22); - return new Date(Date.UTC(2026, 8, 22, h, m) + standardOffsetMinutes(probe) * 60000); -}; diff --git a/src/app/hooks/useSkyState.ts b/src/app/hooks/useSkyState.ts index 02cde126..e608f4d5 100644 --- a/src/app/hooks/useSkyState.ts +++ b/src/app/hooks/useSkyState.ts @@ -1,19 +1,24 @@ -import { useSyncExternalStore } from 'react'; -import { - getResolvedSkyState, - getSkyState, - subscribe, - type FixedSkyState, - type SkyState, -} from '../features/scene/skyState'; +import { useEffect, useSyncExternalStore } from 'react'; +import { getResolvedSkyState, getSkyChoice, subscribe } from '../features/scene/skyState'; +import type { FixedSkyState, SkyChoice } from '../features/scene/ridge/skyMoment'; +import { ensureSkyPlace } from '../features/scene/skyPlace'; import { getSceneDrawn, subscribeSceneDrawn } from '../features/scene/sceneDrawn'; +import { useClientConfig } from './useClientConfig'; -/** The choice, as the control shows it ('auto' stays 'auto'). The sky being drawn is `useResolvedSkyState`. */ -export const useSkyState = (): SkyState => useSyncExternalStore(subscribe, getSkyState); +/** The choice, as the control shows it (Auto stays Auto). The sky being drawn is `useResolvedSkyState`. */ +export const useSkyChoice = (): SkyChoice => useSyncExternalStore(subscribe, getSkyChoice); -/** The sky being drawn: day, dusk or night. Unlike the choice it changes as the clock crosses, so it re-renders. */ -export const useResolvedSkyState = (): FixedSkyState => +/** The sky being drawn: day, dusk or night, or undefined until the place is known. Unlike the choice it changes as the clock crosses under Auto, so it re-renders. */ +export const useResolvedSkyState = (): FixedSkyState | undefined => useSyncExternalStore(subscribe, getResolvedSkyState); +/** Make the configured place the sky's (skyPlace.ts). Mounted once by each theme manager; the load is shared and idempotent. */ +export const useSkyPlace = (): void => { + const place = useClientConfig().backgroundScene?.place; + useEffect(() => { + ensureSkyPlace({ place }); + }, [place]); +}; + /** Whether a background scene is drawing a sky right now (not merely configured): false on a failed or lost context. */ export const useSceneOn = (): boolean => useSyncExternalStore(subscribeSceneDrawn, getSceneDrawn); diff --git a/src/app/pages/ThemeManager.tsx b/src/app/pages/ThemeManager.tsx index 092ace6c..3ed4c8dd 100644 --- a/src/app/pages/ThemeManager.tsx +++ b/src/app/pages/ThemeManager.tsx @@ -8,6 +8,7 @@ import { useSceneInk, useSkyTheme, } from '../hooks/useTheme'; +import { useSkyPlace } from '../hooks/useSkyState'; import { useSetting } from '../state/hooks/settings'; import { settingsAtom } from '../state/settings'; import { labelInk } from '../features/scene/skyInk'; @@ -16,6 +17,7 @@ import { SKY_LABEL_INK } from '../features/scene/skyLabelInk'; export function UnAuthRouteThemeManager() { // Signed-out pages are Midnight Sky unless the sky state picks otherwise; they ignore the // system scheme. + useSkyPlace(); const theme = useSkyTheme() ?? MidnightSkyTheme; useEffect(() => { @@ -28,6 +30,7 @@ export function UnAuthRouteThemeManager() { } export function AuthRouteThemeManager({ children }: { children: ReactNode }) { + useSkyPlace(); const activeTheme = useActiveTheme(); const [monochromeMode] = useSetting(settingsAtom, 'monochromeMode'); const skyInk = useSceneInk();