scene: the ridge and terrain scenes follow the sky state
Some checks failed
Build pull request / Build pull request (pull_request) Has been cancelled

The door (index.ts) reads getSkyState, subscribes on start and rebuilds the
scene on the same canvas when it changes; the returned scene's dispose
unsubscribes. skyForState.ts maps a state to the scene's sky option: auto
leaves it unset (today's behaviour), dusk is the ridge dusk, day and night
are the baked gradients skyBackdrop bounds.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Nibu 2026-11-09 22:20:49 +00:00
commit 0e0cff66ae
4 changed files with 310 additions and 17 deletions

View file

@ -0,0 +1,123 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { baked } from '../../../sky/baked';
import type { Scene } from './Scene';
import { startBackgroundScene } from './index';
import { setSkyState } from './skyState';
const { createRidgeScene, createScene } = vi.hoisted(() => ({
createRidgeScene: vi.fn(),
createScene: vi.fn(),
}));
vi.mock('./ridge/Ridge', () => ({ createRidgeScene }));
vi.mock('./Scene', () => ({ createScene }));
const canvas = {} as HTMLCanvasElement;
const config = { tier: 'low' as const };
const caps = { hardwareConcurrency: 8 };
const flush = () =>
new Promise<void>((r) => {
setTimeout(r, 0);
});
const fakeScene = () => ({ login: vi.fn(), dispose: vi.fn() });
const hex = (c: readonly number[]) => `#${c.map((v) => v.toString(16).padStart(2, '0')).join('')}`;
beforeEach(() => {
vi.stubGlobal('localStorage', { getItem: () => null, setItem: () => undefined });
setSkyState('auto');
createRidgeScene.mockReset();
createScene.mockReset();
});
afterEach(() => {
setSkyState('auto');
vi.unstubAllGlobals();
});
describe('startBackgroundScene follows the sky state', () => {
it('hands the ridge scene no sky for auto, as before there was a state', async () => {
createRidgeScene.mockReturnValue(fakeScene());
const scene = await startBackgroundScene(config, caps, { canvas });
expect(createRidgeScene).toHaveBeenCalledOnce();
expect(createRidgeScene.mock.calls[0][0].sky).toBeUndefined();
scene?.dispose();
});
it('starts on the stored state', async () => {
setSkyState('night');
createRidgeScene.mockReturnValue(fakeScene());
const scene = await startBackgroundScene(config, caps, { canvas });
expect(hex(createRidgeScene.mock.calls[0][0].sky.top)).toBe(baked.midnight.gradient[0]);
scene?.dispose();
});
it('rebuilds on a change: the old scene is disposed, the new one draws the new sky', async () => {
const first = fakeScene();
const second = fakeScene();
createRidgeScene.mockReturnValueOnce(first).mockReturnValueOnce(second);
const scene = await startBackgroundScene(config, caps, { canvas });
setSkyState('day');
await flush();
expect(first.dispose).toHaveBeenCalledOnce();
expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe(baked.noonday.gradient[0]);
scene?.dispose();
expect(second.dispose).toHaveBeenCalledOnce();
});
it('replays a login onto the rebuilt scene, but only if one happened', async () => {
const [a, b, c] = [fakeScene(), fakeScene(), fakeScene()];
createRidgeScene.mockReturnValueOnce(a).mockReturnValueOnce(b).mockReturnValueOnce(c);
const scene = await startBackgroundScene(config, caps, { canvas });
setSkyState('day');
await flush();
expect(b.login).not.toHaveBeenCalled();
scene?.login();
expect(b.login).toHaveBeenCalledOnce();
setSkyState('dusk');
await flush();
expect(c.login).toHaveBeenCalledOnce();
scene?.dispose();
});
it('removes the subscription on dispose', async () => {
const first = fakeScene();
createRidgeScene.mockReturnValue(first);
const scene = await startBackgroundScene(config, caps, { canvas });
scene?.dispose();
scene?.dispose();
setSkyState('day');
await flush();
expect(createRidgeScene).toHaveBeenCalledOnce();
expect(first.dispose).toHaveBeenCalledOnce();
});
it('drops a scene whose rebuild finishes after dispose', async () => {
const second = fakeScene();
createRidgeScene.mockReturnValueOnce(fakeScene()).mockReturnValueOnce(second);
const scene = await startBackgroundScene(config, caps, { canvas });
setSkyState('day');
scene?.dispose();
await flush();
expect(second.dispose).toHaveBeenCalledOnce();
});
it('keeps only the latest of two quick changes', async () => {
const scenes = [fakeScene(), fakeScene(), fakeScene()];
scenes.forEach((s) => createRidgeScene.mockReturnValueOnce(s));
const scene = await startBackgroundScene(config, caps, { canvas });
setSkyState('day');
setSkyState('night');
await flush();
expect(scenes[1].dispose).toHaveBeenCalledOnce();
expect(scenes[2].dispose).not.toHaveBeenCalled();
scene?.dispose();
});
it('leaves the ray-march scene alone: it has one fixed dusk', async () => {
const inner = fakeScene() as unknown as Scene;
createScene.mockReturnValue(inner);
const scene = await startBackgroundScene({ ...config, style: 'raymarch' }, caps, { canvas });
expect(scene).toBe(inner);
setSkyState('day');
await flush();
expect(createScene).toHaveBeenCalledOnce();
});
});

View file

@ -1,5 +1,8 @@
import type { Scene, SceneOptions } from './Scene';
import { BackgroundSceneConfig, Capabilities, resolveTier } from './tier';
import { BackgroundSceneConfig, Capabilities, SceneTier, resolveTier } from './tier';
import { getSkyState, subscribe } from './skyState';
import type { SkyState } from './skyState';
import { ridgeSkyFor, terrainSkyFor } from './skyForState';
export type { Scene, SceneStats } from './Scene';
export type { SceneStyle, SceneTier } from './tier';
@ -9,6 +12,33 @@ export type StartOptions = Omit<SceneOptions, 'tier' | 'patchSource' | 'onCompil
onCompileFail?: (e: Error) => void;
};
async function create(
config: BackgroundSceneConfig | undefined,
options: StartOptions & { tier: SceneTier },
state: SkyState
): Promise<Scene | null> {
let createScene: (o: SceneOptions) => Scene | null;
try {
if (config?.style === 'raymarch') createScene = (await import('./Scene')).createScene;
else if (config?.style === 'terrain') {
const { createTerrainScene } = await import('./terrain/Terrain');
const sky = terrainSkyFor(state);
const scene = createTerrainScene({ ...options, ...sky });
// No WebGL2 (or no usable GL): the terrain's sky alone on the same canvas, not bare ground.
if (scene) return scene;
const { createTerrainSkyScene } = await import('./terrain/TerrainSky2D');
return createTerrainSkyScene({ ...options, ...sky });
} else {
const { createRidgeScene } = await import('./ridge/Ridge');
return createRidgeScene({ ...options, sky: ridgeSkyFor(state) });
}
} catch (e) {
options.onCompileFail?.(e instanceof Error ? e : new Error(String(e)));
return null;
}
return createScene(options);
}
/**
* The client's one door to the scene. When the tier resolves to 'off' nothing is imported and no
* canvas context is requested; otherwise the scene code loads on demand, so it stays out of the
@ -16,6 +46,11 @@ export type StartOptions = Omit<SceneOptions, 'tier' | 'patchSource' | 'onCompil
* sky alone, `terrain/TerrainSky2D.ts`, where WebGL2 is missing). Null means
* "keep the CSS ground", including when that chunk fails to load (offline, stale deploy): the
* failure goes to onCompileFail and nothing throws.
*
* The ridge and terrain scenes bake their sky once, so they follow the sky state (`skyState.ts`) 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.
*/
export async function startBackgroundScene(
config: BackgroundSceneConfig | undefined,
@ -24,20 +59,38 @@ export async function startBackgroundScene(
): Promise<Scene | null> {
const tier = resolveTier(config, capabilities);
if (tier === 'off') return null;
let createScene: (o: SceneOptions) => Scene | null;
try {
if (config?.style === 'raymarch') createScene = (await import('./Scene')).createScene;
else if (config?.style === 'terrain') {
const { createTerrainScene } = await import('./terrain/Terrain');
const scene = createTerrainScene({ ...options, tier });
// No WebGL2 (or no usable GL): the terrain's sky alone on the same canvas, not bare ground.
if (scene) return scene;
const { createTerrainSkyScene } = await import('./terrain/TerrainSky2D');
return createTerrainSkyScene({ ...options, tier });
} else createScene = (await import('./ridge/Ridge')).createRidgeScene;
} catch (e) {
options.onCompileFail?.(e instanceof Error ? e : new Error(String(e)));
return null;
}
return createScene({ ...options, tier });
const build = (state: SkyState) => create(config, { ...options, tier }, state);
const first = await build(getSkyState());
if (!first || config?.style === 'raymarch') return first;
let inner: Scene | null = first;
let loggedIn = false;
let disposed = false;
let generation = 0;
const off = subscribe(async (state) => {
generation += 1;
const mine = generation;
inner?.dispose();
inner = null;
const next = await build(state);
if (disposed || mine !== generation) {
next?.dispose();
return;
}
inner = next;
if (loggedIn) inner?.login();
});
return {
login() {
loggedIn = true;
inner?.login();
},
dispose() {
if (disposed) return;
disposed = true;
off();
inner?.dispose();
inner = null;
},
};
}

View file

@ -0,0 +1,65 @@
import { describe, expect, it } from 'vitest';
import { baked } from '../../../sky/baked';
import { luminance } from '../../../sky/skyTokens.js';
import { skyColours } from './ridge/skyColour';
import { DUSK_SUN_ELEVATION, ridgeSkyFor, terrainSkyFor } from './skyForState';
import { skyBackdrop } from './skyState';
const hex = (c: readonly number[]) => `#${c.map((v) => v.toString(16).padStart(2, '0')).join('')}`;
const EPS = 1e-9;
describe('ridgeSkyFor', () => {
it('leaves auto to the scene, so it draws what it drew before there was a state', () => {
expect(ridgeSkyFor('auto')).toBeUndefined();
});
it('draws the current ridge dusk for dusk', () => {
expect(ridgeSkyFor('dusk')).toEqual(skyColours());
});
it('draws the baked gradients for day and night', () => {
const day = ridgeSkyFor('day');
const night = ridgeSkyFor('night');
expect(hex(day?.top ?? [])).toBe(baked.noonday.gradient[0]);
expect(hex(day?.horizon ?? [])).toBe(baked.noonday.gradient[6]);
expect(hex(night?.top ?? [])).toBe(baked.midnight.gradient[0]);
expect(hex(night?.horizon ?? [])).toBe(baked.midnight.gradient[6]);
});
it.each(['day', 'dusk', 'night'] as const)(
'paints a %s sky whose colours lie inside skyBackdrop',
(state) => {
const sky = ridgeSkyFor(state);
const { darkest, lightest } = skyBackdrop(state);
[sky?.top, sky?.mid, sky?.horizon].forEach((c) => {
const l = luminance(hex(c ?? []));
expect(l).toBeGreaterThanOrEqual(darkest - EPS);
expect(l).toBeLessThanOrEqual(lightest + EPS);
});
}
);
});
describe('terrainSkyFor', () => {
it('leaves auto to the clock and the URL', () => {
expect(terrainSkyFor('auto')).toEqual({});
});
it('names the baked sky for day and night, and a low sun for dusk', () => {
expect(terrainSkyFor('day')).toEqual({ sky: 'noonday' });
expect(terrainSkyFor('night')).toEqual({ sky: 'midnight' });
expect(terrainSkyFor('dusk')).toEqual({ sun: { elevation: DUSK_SUN_ELEVATION } });
});
it.each([
['day', 'noonday'],
['night', 'midnight'],
] as const)('lights %s from a gradient inside skyBackdrop', (state, name) => {
const { darkest, lightest } = skyBackdrop(state);
expect(terrainSkyFor(state).sky).toBe(name);
baked[name].gradient.forEach((c) => {
expect(luminance(c)).toBeGreaterThanOrEqual(darkest - EPS);
expect(luminance(c)).toBeLessThanOrEqual(lightest + EPS);
});
});
});

View file

@ -0,0 +1,52 @@
// What each scene is told for a sky state. 'auto' returns nothing: the scene chooses for itself
// (the ridges' fixed dusk, the terrain's clock with `?sky=` `?sun=` `?az=`), exactly as before
// there was a state. The other states name a sky explicitly, drawn from the same gradients
// `skyBackdrop` bounds, so the colours a scene paints lie inside the luminance range the login
// text was checked against.
import { baked } from '../../../sky/baked';
import type { SkyName } from './terrain/terrainSky';
import type { SkyColours, Srgb } from './ridge/skyColour';
import { skyColours } from './ridge/skyColour';
import type { SkyState } from './skyState';
const rgb = (hex: string): Srgb =>
[1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16)) as unknown as Srgb;
const fromGradient = (g: readonly string[], ground: Srgb): SkyColours => ({
top: rgb(g[0]),
mid: rgb(g[Math.floor(g.length / 2)]),
horizon: rgb(g[g.length - 1]),
ground,
});
/** Sun elevation in degrees for the terrain's dusk: just above the horizon, between the two bakes (as `?sun=` puts it). */
export const DUSK_SUN_ELEVATION = 2;
/** The ridge scene's `sky` option; undefined leaves the scene on `skyColours()`. */
export function ridgeSkyFor(state: SkyState): SkyColours | undefined {
const { ground } = skyColours();
switch (state) {
case 'dusk':
return skyColours();
case 'day':
return fromGradient(baked.noonday.gradient, ground);
case 'night':
return fromGradient(baked.midnight.gradient, ground);
default:
return undefined;
}
}
/** The terrain scene's `sky` and `sun` options; `{}` leaves the scene on its clock and URL choice. */
export function terrainSkyFor(state: SkyState): { sky?: SkyName; sun?: { elevation: number } } {
switch (state) {
case 'day':
return { sky: 'noonday' };
case 'night':
return { sky: 'midnight' };
case 'dusk':
return { sun: { elevation: DUSK_SUN_ELEVATION } };
default:
return {};
}
}