scene: auto never picks a theme; URL steers auto; quantised bounds; listener-window fix; DST
Some checks failed
Build pull request / Build pull request (pull_request) Failing after 26s
Some checks failed
Build pull request / Build pull request (pull_request) Failing after 26s
- skyThemeId('auto') is undefined again (auto must not override a signed-in theme); the resolved state stays readable by getResolvedSkyState and subscribe.
- In auto, ?sun= ?az= ?sky= reach the terrain again, shaped into the band of the clock-resolved state; an explicit state beats the URL.
- The sky-change notice is no longer swallowed by a listener arriving or leaving between the clock crossing and the tick.
- BACKDROPS bound what the 8-bit screen shows with the dither at its worst; shaping floor 0.317, night ceiling 0.085.
- The clock uses standard time, so daylight saving does not move the sun.
- A Terrain GL fake test pins uBand and uLift for each state.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
4177bdcccb
commit
577d795189
16 changed files with 287 additions and 136 deletions
|
|
@ -1,4 +1,5 @@
|
|||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { atStandardTime } from './standardTime.testkit';
|
||||
import { baked } from '../../../sky/baked';
|
||||
import type { Scene } from './Scene';
|
||||
import { startBackgroundScene } from './index';
|
||||
|
|
@ -24,7 +25,7 @@ const hex = (c: readonly number[]) => `#${c.map((v) => v.toString(16).padStart(2
|
|||
beforeEach(() => {
|
||||
vi.stubGlobal('localStorage', { getItem: () => null, setItem: () => undefined });
|
||||
// Local midnight: 'auto' resolves to night.
|
||||
setSkyClock(() => new Date(2026, 8, 22, 0, 0));
|
||||
setSkyClock(() => atStandardTime(0, 0));
|
||||
setSkyState('auto');
|
||||
createRidgeScene.mockReset();
|
||||
createScene.mockReset();
|
||||
|
|
@ -44,6 +45,17 @@ describe('startBackgroundScene follows the sky state', () => {
|
|||
scene?.dispose();
|
||||
});
|
||||
|
||||
it('rebuilds when auto is replaced by the explicit state it already resolves to (a URL may steer only auto)', async () => {
|
||||
const [a, b] = [fakeScene(), fakeScene()];
|
||||
createRidgeScene.mockReturnValueOnce(a).mockReturnValueOnce(b);
|
||||
const scene = await startBackgroundScene(config, caps, { canvas });
|
||||
setSkyState('night');
|
||||
await flush();
|
||||
expect(a.dispose).toHaveBeenCalledOnce();
|
||||
expect(createRidgeScene).toHaveBeenCalledTimes(2);
|
||||
scene?.dispose();
|
||||
});
|
||||
|
||||
it('starts on the stored state', async () => {
|
||||
setSkyState('night');
|
||||
createRidgeScene.mockReturnValue(fakeScene());
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import type { Scene, SceneOptions } from './Scene';
|
||||
import { BackgroundSceneConfig, Capabilities, SceneTier, resolveTier } from './tier';
|
||||
import { getResolvedSkyState, subscribe } from './skyState';
|
||||
import type { FixedSkyState } from './skyState';
|
||||
import { getResolvedSkyState, getSkyState, subscribe } from './skyState';
|
||||
import type { SkyState } from './skyState';
|
||||
|
||||
export type { Scene, SceneStats } from './Scene';
|
||||
export type { SceneStyle, SceneTier } from './tier';
|
||||
|
|
@ -18,7 +18,7 @@ export type StartOptions = Omit<SceneOptions, 'tier' | 'patchSource' | 'onCompil
|
|||
async function create(
|
||||
config: BackgroundSceneConfig | undefined,
|
||||
options: StartOptions & { tier: SceneTier },
|
||||
state: FixedSkyState
|
||||
state: SkyState
|
||||
): Promise<Scene | null> {
|
||||
let createScene: (o: SceneOptions) => Scene | null;
|
||||
try {
|
||||
|
|
@ -64,21 +64,25 @@ export async function startBackgroundScene(
|
|||
): Promise<Scene | null> {
|
||||
const tier = resolveTier(config, capabilities);
|
||||
if (tier === 'off') return null;
|
||||
const build = (state: FixedSkyState) => create(config, { ...options, tier }, state);
|
||||
const state = getResolvedSkyState();
|
||||
const build = (state: SkyState) => create(config, { ...options, tier }, state);
|
||||
const state = getSkyState();
|
||||
const key0 = `${state}:${getResolvedSkyState()}`;
|
||||
const first = await build(state);
|
||||
if (!first || config?.style === 'raymarch') return first;
|
||||
|
||||
let inner: Scene | null = first;
|
||||
let built = state;
|
||||
let built = key0;
|
||||
let loggedIn = false;
|
||||
let disposed = false;
|
||||
let generation = 0;
|
||||
const rebuild = async (next: FixedSkyState) => {
|
||||
if (next === built) return;
|
||||
// A rebuild is for a new choice or a new resolved sky ('auto' crossing a boundary), not for a repeat of either.
|
||||
const rebuild = async () => {
|
||||
const next = getSkyState();
|
||||
const key = `${next}:${getResolvedSkyState()}`;
|
||||
if (key === built) return;
|
||||
generation += 1;
|
||||
const mine = generation;
|
||||
built = next;
|
||||
built = key;
|
||||
inner?.dispose();
|
||||
inner = null;
|
||||
const scene = await build(next);
|
||||
|
|
@ -95,7 +99,7 @@ export async function startBackgroundScene(
|
|||
};
|
||||
const off = subscribe(rebuild);
|
||||
// A change that landed while the first build was awaited was missed by the subscription.
|
||||
rebuild(getResolvedSkyState());
|
||||
rebuild();
|
||||
return {
|
||||
login() {
|
||||
loggedIn = true;
|
||||
|
|
|
|||
|
|
@ -52,9 +52,9 @@ describe('the bands', () => {
|
|||
Object.values(SKY_BAND).forEach((b) => expect(luma(b.lift)).toBeGreaterThan(b.floor));
|
||||
});
|
||||
|
||||
it('keep the floor 0.01 above the 0.2983 text bound: gamma 2.2 reads darker than sRGB by less', () => {
|
||||
it('keep the floor above the 0.2983 text bound by what gamma 2.2, 8-bit rounding and dither can take', () => {
|
||||
const grey = shapeToBand([0, 0, 0], SKY_BAND.day);
|
||||
const shown = displayedLuminance(grey);
|
||||
const shown = displayedLuminance(grey, 'low');
|
||||
expect(shown).toBeGreaterThanOrEqual(0.2983);
|
||||
expect(shown).toBeLessThan(SKY_BAND.day.floor);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -28,13 +28,20 @@ export function hexToLinear(hex: string): Linear {
|
|||
return [ch(1), ch(3), ch(5)];
|
||||
}
|
||||
|
||||
/** How a displayed colour is read: as encoded, or as the 8-bit screen can show it, the sky pass dithers by half a step either way ('low', 'high'). */
|
||||
export type Reading = 'exact' | 'low' | 'high';
|
||||
|
||||
/**
|
||||
* Relative luminance of what the terrain shaders put on screen for a linear colour: they encode with
|
||||
* pow(1/2.2), not the sRGB curve, so the screen colour is read back through the sRGB curve.
|
||||
* pow(1/2.2), not the sRGB curve, so the screen colour is read back through the sRGB curve. 'low' and 'high' read
|
||||
* it after 8-bit quantisation with the dither at its worst, so the bounds they give hold on the screen.
|
||||
*/
|
||||
export function displayedLuminance(c: Linear): number {
|
||||
export function displayedLuminance(c: Linear, reading: Reading = 'exact'): number {
|
||||
const ch = (v: number) => {
|
||||
const e = Math.min(1, Math.max(0, v)) ** (1 / 2.2);
|
||||
let e = Math.min(1, Math.max(0, v)) ** (1 / 2.2);
|
||||
if (reading !== 'exact') {
|
||||
e = Math.min(255, Math.max(0, Math.round(e * 255 + (reading === 'low' ? -0.5 : 0.5)))) / 255;
|
||||
}
|
||||
return e <= 0.04045 ? e / 12.92 : ((e + 0.055) / 1.055) ** 2.4;
|
||||
};
|
||||
return luma([ch(c[0]), ch(c[1]), ch(c[2])]);
|
||||
|
|
@ -50,13 +57,14 @@ export interface SkyBand {
|
|||
}
|
||||
|
||||
/**
|
||||
* The shaping targets, in linear luma. The floor sits 0.01 above the text bound (0.2983) because the
|
||||
* screen encoding is gamma 2.2, which reads about 0.006 darker through the sRGB curve at this level.
|
||||
* The shaping targets, in linear luma. The floor sits 0.019 above the text bound (0.2983): the screen encoding is
|
||||
* gamma 2.2, which reads about 0.006 darker through the sRGB curve at this level, and 8-bit rounding with the sky
|
||||
* pass's dither at its worst takes about 0.006 more.
|
||||
*/
|
||||
export const SKY_BAND: Record<FixedSkyState, SkyBand> = {
|
||||
day: { floor: 0.31, ceiling: 1, lift: hexToLinear('#e2f4ff') },
|
||||
dusk: { floor: 0.31, ceiling: 1, lift: hexToLinear('#eba0b9') },
|
||||
night: { floor: 0, ceiling: 0.09, lift: hexToLinear('#484e64') },
|
||||
day: { floor: 0.317, ceiling: 1, lift: hexToLinear('#e2f4ff') },
|
||||
dusk: { floor: 0.317, ceiling: 1, lift: hexToLinear('#eba0b9') },
|
||||
night: { floor: 0, ceiling: 0.085, lift: hexToLinear('#5a6a9a') },
|
||||
};
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { atStandardTime } from './standardTime.testkit';
|
||||
import { baked } from '../../../sky/baked';
|
||||
import { AA, luminance } from '../../../sky/skyTokens.js';
|
||||
import { skyColours } from './ridge/skyColour';
|
||||
|
|
@ -33,7 +34,19 @@ const needs = (state: FixedSkyState) => {
|
|||
: { floor: AA * (l + 0.05) - 0.05, ceiling: 1 };
|
||||
};
|
||||
|
||||
afterEach(() => setSkyClock());
|
||||
let search = '';
|
||||
beforeEach(() => {
|
||||
search = '';
|
||||
vi.stubGlobal('window', {
|
||||
get location() {
|
||||
return { search };
|
||||
},
|
||||
});
|
||||
});
|
||||
afterEach(() => {
|
||||
setSkyClock();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe('the bands the text ink needs', () => {
|
||||
it('are the numbers the shaping was set from', () => {
|
||||
|
|
@ -45,11 +58,11 @@ describe('the bands the text ink needs', () => {
|
|||
|
||||
describe('ridgeSkyFor', () => {
|
||||
it('draws the gradient of the sky auto resolves to, never nothing', () => {
|
||||
setSkyClock(() => new Date(2026, 8, 22, 12, 0));
|
||||
setSkyClock(() => atStandardTime(12, 0));
|
||||
expect(ridgeSkyFor('auto')).toEqual(ridgeSkyFor('day'));
|
||||
setSkyClock(() => new Date(2026, 8, 22, 0, 0));
|
||||
setSkyClock(() => atStandardTime(0, 0));
|
||||
expect(ridgeSkyFor('auto')).toEqual(ridgeSkyFor('night'));
|
||||
setSkyClock(() => new Date(2026, 8, 22, 18, 10));
|
||||
setSkyClock(() => atStandardTime(18, 10));
|
||||
expect(ridgeSkyFor('auto')).toEqual(ridgeSkyFor('dusk'));
|
||||
});
|
||||
|
||||
|
|
@ -82,6 +95,38 @@ describe('ridgeSkyFor', () => {
|
|||
});
|
||||
});
|
||||
|
||||
// Not the generator's grid: a golden-angle spiral over the upper sphere (no shared rows or columns)
|
||||
// plus a 0.05 degree grid across the sun, five times finer than the generator's.
|
||||
const dirAt = (el: number, az: number): [number, number, number] => {
|
||||
const rad = Math.PI / 180;
|
||||
return [
|
||||
Math.cos(el * rad) * Math.sin(az * rad),
|
||||
Math.sin(el * rad),
|
||||
-Math.cos(el * rad) * Math.cos(az * rad),
|
||||
];
|
||||
};
|
||||
/** Over the sweep: the darkest the 8-bit screen can show (dither at its worst), the lightest, and the darkest as encoded. */
|
||||
const sweepOf = (sky: ReturnType<typeof chooseSky>, N = 4000, maxEl = TERRAIN_REACH_DEG) => {
|
||||
const rad = Math.PI / 180;
|
||||
const out = { low: Infinity, high: -Infinity, exactMin: Infinity };
|
||||
const see = (el: number, az: number) => {
|
||||
const c = skyColour(sky, dirAt(el, az));
|
||||
out.low = Math.min(out.low, displayedLuminance(c, 'low'));
|
||||
out.high = Math.max(out.high, displayedLuminance(c, 'high'));
|
||||
out.exactMin = Math.min(out.exactMin, displayedLuminance(c));
|
||||
};
|
||||
for (let i = 0; i < N; i += 1) {
|
||||
const y = ((i + 0.5) / N) * Math.sin(maxEl * rad); // sin(elevation): uniform from the horizon to maxEl
|
||||
see(Math.asin(y) / rad, (i * 137.50776405) % 360);
|
||||
}
|
||||
for (let dEl = -3; dEl <= 3; dEl += 0.05) {
|
||||
for (let dAz = -3; dAz <= 3; dAz += 0.05) {
|
||||
see(Math.min(maxEl, Math.max(0, sky.elevation + dEl)), sky.azimuth + dAz);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
describe('the terrain camera reach', () => {
|
||||
it('covers the highest ray the frozen camera sees, at any aspect, with a small margin', () => {
|
||||
const tanHalf = Math.tan((55 * Math.PI) / 360);
|
||||
|
|
@ -105,12 +150,45 @@ describe('the terrain camera reach', () => {
|
|||
|
||||
describe('terrainSkyFor', () => {
|
||||
it('draws the sky auto resolves to, with that state band', () => {
|
||||
setSkyClock(() => new Date(2026, 8, 22, 12, 0));
|
||||
setSkyClock(() => atStandardTime(12, 0));
|
||||
expect(terrainSkyFor('auto')).toEqual(terrainSkyFor('day'));
|
||||
setSkyClock(() => new Date(2026, 8, 22, 0, 0));
|
||||
setSkyClock(() => atStandardTime(0, 0));
|
||||
expect(terrainSkyFor('auto')).toEqual(terrainSkyFor('night'));
|
||||
});
|
||||
|
||||
it('lets the page URL steer auto, shaped into the band of the state the clock resolves to', () => {
|
||||
setSkyClock(() => atStandardTime(0, 0)); // night
|
||||
search = '?sun=30&az=120';
|
||||
expect(terrainSkyFor('auto')).toEqual({
|
||||
sun: { elevation: 30, azimuth: 120 },
|
||||
band: SKY_BAND.night,
|
||||
});
|
||||
search = '?sky=noonday';
|
||||
expect(terrainSkyFor('auto')).toEqual({ sky: 'noonday', band: SKY_BAND.night });
|
||||
search = '?sky=garbage';
|
||||
expect(terrainSkyFor('auto')).toEqual(terrainSkyFor('night'));
|
||||
setSkyClock(() => atStandardTime(18, 10)); // dusk, URL azimuth honoured
|
||||
search = '?sun=2&az=250';
|
||||
expect(terrainSkyFor('auto').sun).toEqual({ elevation: 2, azimuth: 250 });
|
||||
});
|
||||
|
||||
it('keeps a URL-chosen sun inside the band of the resolved state', () => {
|
||||
setSkyClock(() => atStandardTime(12, 0)); // day: floor
|
||||
search = '?sun=-30';
|
||||
const day = sweepOf(chooseSky(terrainSkyFor('auto')));
|
||||
expect(day.low).toBeGreaterThanOrEqual(needs('day').floor);
|
||||
setSkyClock(() => atStandardTime(0, 0)); // night: ceiling
|
||||
search = '?sun=60';
|
||||
const night = sweepOf(chooseSky(terrainSkyFor('auto')));
|
||||
expect(night.high).toBeLessThanOrEqual(needs('night').ceiling);
|
||||
});
|
||||
|
||||
it('lets an explicit state beat the URL, as before auto had one', () => {
|
||||
search = '?sun=30&az=120&sky=midnight';
|
||||
expect(terrainSkyFor('day')).toEqual({ sky: 'noonday', band: SKY_BAND.day });
|
||||
expect(terrainSkyFor('dusk').sun).toEqual({ elevation: DUSK_SUN_ELEVATION });
|
||||
});
|
||||
|
||||
it('names the baked sky for day and night, and a low sun for dusk, each with its band', () => {
|
||||
expect(terrainSkyFor('day')).toEqual({ sky: 'noonday', band: SKY_BAND.day });
|
||||
expect(terrainSkyFor('night')).toEqual({ sky: 'midnight', band: SKY_BAND.night });
|
||||
|
|
@ -121,63 +199,28 @@ describe('terrainSkyFor', () => {
|
|||
});
|
||||
});
|
||||
|
||||
// Not the generator's grid: a golden-angle spiral over the upper sphere (no shared rows or columns)
|
||||
// plus a 0.05 degree grid across the sun, five times finer than the generator's.
|
||||
const dirAt = (el: number, az: number): [number, number, number] => {
|
||||
const rad = Math.PI / 180;
|
||||
return [
|
||||
Math.cos(el * rad) * Math.sin(az * rad),
|
||||
Math.sin(el * rad),
|
||||
-Math.cos(el * rad) * Math.cos(az * rad),
|
||||
];
|
||||
};
|
||||
const sweepOf = (sky: ReturnType<typeof chooseSky>, N = 4000, maxEl = TERRAIN_REACH_DEG) => {
|
||||
const rad = Math.PI / 180;
|
||||
const out: number[] = [];
|
||||
for (let i = 0; i < N; i += 1) {
|
||||
const y = ((i + 0.5) / N) * Math.sin(maxEl * rad); // sin(elevation): uniform from the horizon to maxEl
|
||||
out.push(
|
||||
displayedLuminance(skyColour(sky, dirAt(Math.asin(y) / rad, (i * 137.50776405) % 360)))
|
||||
);
|
||||
}
|
||||
for (let dEl = -3; dEl <= 3; dEl += 0.05) {
|
||||
for (let dAz = -3; dAz <= 3; dAz += 0.05) {
|
||||
out.push(
|
||||
displayedLuminance(
|
||||
skyColour(
|
||||
sky,
|
||||
dirAt(Math.min(maxEl, Math.max(0, sky.elevation + dEl)), sky.azimuth + dAz)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
describe('the terrain sky lies in the band its text ink needs', () => {
|
||||
const sweep = (state: FixedSkyState) => sweepOf(chooseSky(terrainSkyFor(state)));
|
||||
|
||||
it('dusk needs its lift: the scatter sky alone dips below the text bound within the reach', () => {
|
||||
const { sun } = terrainSkyFor('dusk');
|
||||
const l = sweepOf(chooseSky({ sun }));
|
||||
expect(Math.min(...l)).toBeLessThan(needs('dusk').floor - 0.02);
|
||||
expect(Math.min(...sweep('dusk'))).toBeGreaterThanOrEqual(needs('dusk').floor);
|
||||
expect(sweepOf(chooseSky({ sun })).exactMin).toBeLessThan(needs('dusk').floor - 0.02);
|
||||
expect(sweep('dusk').low).toBeGreaterThanOrEqual(needs('dusk').floor);
|
||||
});
|
||||
|
||||
it.each(STATES)('%s', (state) => {
|
||||
const { floor, ceiling } = needs(state);
|
||||
const l = sweep(state);
|
||||
expect(Math.min(...l)).toBeGreaterThanOrEqual(floor);
|
||||
expect(Math.max(...l)).toBeLessThanOrEqual(ceiling);
|
||||
expect(l.low).toBeGreaterThanOrEqual(floor);
|
||||
expect(l.high).toBeLessThanOrEqual(ceiling);
|
||||
});
|
||||
|
||||
it.each(STATES)('%s holds for a sun at any elevation, as ?sun= can put it', (state) => {
|
||||
const { floor, ceiling } = needs(state);
|
||||
for (let e = -90; e <= 90; e += 10) {
|
||||
const l = sweepOf(chooseSky({ sun: { elevation: e }, band: SKY_BAND[state] }), 4000, 90);
|
||||
expect(Math.min(...l)).toBeGreaterThanOrEqual(floor);
|
||||
expect(Math.max(...l)).toBeLessThanOrEqual(ceiling);
|
||||
expect(l.low).toBeGreaterThanOrEqual(floor);
|
||||
expect(l.high).toBeLessThanOrEqual(ceiling);
|
||||
}
|
||||
});
|
||||
|
||||
|
|
@ -212,9 +255,9 @@ describe('skyBackdrop holds the union of what the scenes draw', () => {
|
|||
const l = sweepOf(chooseSky(terrainSkyFor(state)), 20000);
|
||||
const b = skyBackdrop(state);
|
||||
const r = ridgeDrawn(state);
|
||||
expect(Math.min(...l)).toBeGreaterThanOrEqual(b.darkest - EPS);
|
||||
expect(Math.max(...l)).toBeLessThanOrEqual(b.lightest + EPS);
|
||||
expect(b.lightest - Math.max(Math.max(...l), r.lightest)).toBeLessThan(5e-4);
|
||||
expect(Math.min(Math.min(...l), r.darkest) - b.darkest).toBeLessThan(5e-4);
|
||||
expect(l.low).toBeGreaterThanOrEqual(b.darkest - EPS);
|
||||
expect(l.high).toBeLessThanOrEqual(b.lightest + EPS);
|
||||
expect(b.lightest - Math.max(l.high, r.lightest)).toBeLessThan(5e-4);
|
||||
expect(Math.min(l.low, r.darkest) - b.darkest).toBeLessThan(5e-4);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@
|
|||
// it, the terrain sky shaped into it downstream of the scatter function. `skyBackdrop` bounds what comes out,
|
||||
// and the login text was checked against that bound.
|
||||
import { baked } from '../../../sky/baked';
|
||||
import { chooseSky, skyColour } from './terrain/terrainSky';
|
||||
import { chooseSky, skyColour, urlSky } from './terrain/terrainSky';
|
||||
import type { SkyName } from './terrain/terrainSky';
|
||||
import type { SkyColours, Srgb } from './ridge/skyColour';
|
||||
import { skyColours } from './ridge/skyColour';
|
||||
|
|
@ -41,14 +41,22 @@ export function ridgeSkyFor(state: SkyState): SkyColours {
|
|||
}
|
||||
}
|
||||
|
||||
/** The terrain scene's `sky`, `sun` and `band` options: the state's sky ('auto': the sky it resolves to), shaped into the state's band. */
|
||||
/**
|
||||
* The terrain scene's `sky`, `sun` and `band` options. An explicit state draws its own sky and ignores the URL. 'auto'
|
||||
* draws the sky it resolves to, unless the page URL steers (`?sun=` `?az=` `?sky=`, see `urlSky`): then the URL's sky,
|
||||
* shaped into the band of the state the clock resolves to, which keeps any sun the URL picks inside that band.
|
||||
*/
|
||||
export function terrainSkyFor(state: SkyState): {
|
||||
sky?: SkyName;
|
||||
sun?: { elevation: number };
|
||||
sun?: { elevation: number; azimuth?: number };
|
||||
band: SkyBand;
|
||||
} {
|
||||
const fixed = resolveSkyState(state);
|
||||
const band = SKY_BAND[fixed];
|
||||
if (state === 'auto') {
|
||||
const url = urlSky();
|
||||
if (url) return { ...url, band };
|
||||
}
|
||||
switch (fixed) {
|
||||
case 'day':
|
||||
return { sky: 'noonday', band };
|
||||
|
|
@ -113,12 +121,16 @@ const REFINE_FROM = 6;
|
|||
export function terrainDrawn(state: SkyState): Range {
|
||||
const sky = chooseSky(terrainSkyFor(state));
|
||||
const rad = Math.PI / 180;
|
||||
// Every point looked at is also read as the 8-bit screen would show it, dither at its worst, so the range bounds that too.
|
||||
let screenDarkest = Infinity;
|
||||
let screenLightest = -Infinity;
|
||||
const lum = (el: number, az: number) => {
|
||||
const e = Math.min(TERRAIN_REACH_DEG, Math.max(0, el)) * rad;
|
||||
const a = az * rad;
|
||||
return displayedLuminance(
|
||||
skyColour(sky, [Math.cos(e) * Math.sin(a), Math.sin(e), -Math.cos(e) * Math.cos(a)])
|
||||
);
|
||||
const c = skyColour(sky, [Math.cos(e) * Math.sin(a), Math.sin(e), -Math.cos(e) * Math.cos(a)]);
|
||||
screenDarkest = Math.min(screenDarkest, displayedLuminance(c, 'low'));
|
||||
screenLightest = Math.max(screenLightest, displayedLuminance(c, 'high'));
|
||||
return displayedLuminance(c);
|
||||
};
|
||||
const seen: { el: number; az: number; l: number }[] = [];
|
||||
const at = (el: number, az: number) => seen.push({ el, az, l: lum(el, az) });
|
||||
|
|
@ -164,5 +176,8 @@ export function terrainDrawn(state: SkyState): Range {
|
|||
byLight[byLight.length - 1].l,
|
||||
...byLight.slice(-REFINE_FROM).map((p) => refine(p, -1))
|
||||
);
|
||||
return { darkest, lightest };
|
||||
return {
|
||||
darkest: Math.min(darkest, screenDarkest),
|
||||
lightest: Math.max(lightest, screenLightest),
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { atStandardTime } from './standardTime.testkit';
|
||||
import { baked } from '../../../sky/baked';
|
||||
import { luminance } from '../../../sky/skyTokens.js';
|
||||
import {
|
||||
|
|
@ -123,7 +124,7 @@ describe('skyBackdrop', () => {
|
|||
});
|
||||
|
||||
it('is the band of the sky auto resolves to, not the union of all three', () => {
|
||||
const at = (h: number) => setSkyClock(() => new Date(2026, 8, 22, h, 0));
|
||||
const at = (h: number) => setSkyClock(() => atStandardTime(h, 0));
|
||||
at(12);
|
||||
expect(skyBackdrop('auto')).toEqual(skyBackdrop('day'));
|
||||
at(0);
|
||||
|
|
@ -139,7 +140,7 @@ describe('skyBackdrop', () => {
|
|||
});
|
||||
|
||||
describe('auto follows the clock', () => {
|
||||
const local = (h: number, m = 0) => new Date(2026, 8, 22, h, m); // local solar time ~ local clock
|
||||
const local = (h: number, m = 0) => atStandardTime(h, m); // local solar time ~ local clock
|
||||
let storage: ReturnType<typeof fakeStorage>;
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
|
|
@ -174,6 +175,24 @@ describe('auto follows the clock', () => {
|
|||
off();
|
||||
});
|
||||
|
||||
it('still tells everyone when a listener comes or goes inside the window before the clock crosses', async () => {
|
||||
const m = await fresh();
|
||||
let now = local(17, 0);
|
||||
m.setSkyClock(() => now);
|
||||
const [a, b, late] = [vi.fn(), vi.fn(), vi.fn()];
|
||||
m.subscribe(a);
|
||||
const offB = m.subscribe(b);
|
||||
vi.advanceTimersByTime(30_000);
|
||||
now = local(18, 10); // the clock has crossed; no tick has seen it yet
|
||||
const offLate = m.subscribe(late);
|
||||
offB();
|
||||
vi.advanceTimersByTime(60_000);
|
||||
expect(a.mock.calls).toEqual([['dusk']]);
|
||||
expect(b).not.toHaveBeenCalled();
|
||||
expect(late.mock.calls).toEqual([['dusk']]);
|
||||
offLate();
|
||||
});
|
||||
|
||||
it('keeps no timer without listeners or when a fixed state is chosen', async () => {
|
||||
const m = await fresh();
|
||||
const off = m.subscribe(() => undefined);
|
||||
|
|
|
|||
|
|
@ -30,10 +30,17 @@ const LAT = 45;
|
|||
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 = -now.getTimezoneOffset() / 4;
|
||||
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';
|
||||
|
|
@ -60,12 +67,12 @@ const emit = () => {
|
|||
};
|
||||
|
||||
// While anyone listens and the choice is 'auto', one timer checks the clock each minute and tells
|
||||
// listeners when the resolved sky changes. Otherwise there is no timer.
|
||||
// listeners when the resolved sky changes from the one last told (`shown`, set when telling and when the
|
||||
// first listener arrives, never by a later arrival or departure). Otherwise there is no timer.
|
||||
function sync(): void {
|
||||
clearTimeout(timer);
|
||||
timer = undefined;
|
||||
if (listeners.size === 0 || getSkyState() !== 'auto') return;
|
||||
shown = getResolvedSkyState();
|
||||
const tick = () => {
|
||||
if (getResolvedSkyState() !== shown) emit();
|
||||
timer = setTimeout(tick, TICK_MS);
|
||||
|
|
@ -96,6 +103,7 @@ export function setSkyState(s: SkyState): void {
|
|||
|
||||
/** Listeners hear the resolved sky: on a change of choice, and while 'auto', when the clock crosses a boundary. */
|
||||
export function subscribe(cb: (s: FixedSkyState) => void): () => void {
|
||||
if (listeners.size === 0) shown = getResolvedSkyState();
|
||||
listeners.add(cb);
|
||||
sync();
|
||||
return () => {
|
||||
|
|
@ -119,11 +127,11 @@ export interface SkyBackdrop {
|
|||
// this module, which the main chunk loads, does not pull in the terrain sky and the baked scattering
|
||||
// tables with it; skyForState.test.ts fails when they drift from the computed union. The ridge sky counts
|
||||
// over its whole range, the terrain sky over what its frozen camera reaches (TERRAIN_REACH_DEG, skyForState.ts).
|
||||
// Rounded outward to six places.
|
||||
// Bounds what the 8-bit screen shows too (dither at its worst), rounded outward to six places.
|
||||
const BACKDROPS: Record<FixedSkyState, SkyBackdrop> = {
|
||||
day: { darkest: 0.466725, lightest: 0.892734 },
|
||||
dusk: { darkest: 0.303835, lightest: 0.967298 },
|
||||
night: { darkest: 0.05987, lightest: 0.079657 },
|
||||
day: { darkest: 0.463644, lightest: 0.898318 },
|
||||
dusk: { darkest: 0.306293, lightest: 0.968113 },
|
||||
night: { darkest: 0.05987, lightest: 0.081133 },
|
||||
};
|
||||
|
||||
export const skyBackdrop = (state: SkyState): SkyBackdrop => BACKDROPS[resolveSkyState(state)];
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import { atStandardTime } from './standardTime.testkit';
|
||||
import { baked } from '../../../sky/baked';
|
||||
import { AA, contrast, luminance } from '../../../sky/skyTokens.js';
|
||||
import { Editor } from '../../components/editor/Editor.css';
|
||||
|
|
@ -8,7 +9,7 @@ import { MembersDrawer } from '../room/MembersDrawer.css';
|
|||
import { RoomViewTyping } from '../room/RoomViewTyping.css';
|
||||
import { SKY_PLATE_FALLBACK } from './skyPlate';
|
||||
import { SkyPlate, plateRegions } from './skyPlate.css';
|
||||
import { setSkyClock, skyBackdrop } from './skyState';
|
||||
import { getResolvedSkyState, setSkyClock, skyBackdrop } from './skyState';
|
||||
import type { SkyBackdrop } from './skyState';
|
||||
import type { FixedSkyState } from './skyBand';
|
||||
import { skyThemeId } from './skyTheme';
|
||||
|
|
@ -32,17 +33,25 @@ const ratio = (ink: string, b: SkyBackdrop) =>
|
|||
const r2 = (n: number) => n.toFixed(2);
|
||||
|
||||
describe('skyThemeId', () => {
|
||||
it('picks a theme for every fixed state, and for auto the theme of the sky it resolves to', () => {
|
||||
it('picks a theme for each explicit state', () => {
|
||||
expect(skyThemeId('day')).toBe('noonday-sky');
|
||||
expect(skyThemeId('dusk')).toBe('noonday-sky');
|
||||
expect(skyThemeId('night')).toBe('midnight-sky');
|
||||
const at = (h: number, m = 0) => setSkyClock(() => new Date(2026, 8, 22, h, m));
|
||||
at(12);
|
||||
expect(skyThemeId('auto')).toBe('noonday-sky');
|
||||
at(0);
|
||||
expect(skyThemeId('auto')).toBe('midnight-sky');
|
||||
at(18, 10);
|
||||
expect(skyThemeId('auto')).toBe('noonday-sky');
|
||||
});
|
||||
|
||||
it('picks none for auto, at any hour: auto never overrides a signed-in theme', () => {
|
||||
[0, 6, 12, 18, 23].forEach((h) => {
|
||||
setSkyClock(() => atStandardTime(h, 10));
|
||||
expect(skyThemeId('auto')).toBeUndefined();
|
||||
});
|
||||
setSkyClock();
|
||||
});
|
||||
|
||||
it('is what a wiring that follows the sky reads: the resolved state names a theme', () => {
|
||||
setSkyClock(() => atStandardTime(12));
|
||||
expect(skyThemeId(getResolvedSkyState())).toBe('noonday-sky');
|
||||
setSkyClock(() => atStandardTime(0));
|
||||
expect(skyThemeId(getResolvedSkyState())).toBe('midnight-sky');
|
||||
setSkyClock();
|
||||
});
|
||||
});
|
||||
|
|
@ -54,9 +63,9 @@ describe('ink of the theme a state picks, on bare sky', () => {
|
|||
// numbers are recorded as they are measured (Night's #609385 would clear 4.5 at a luminance of about 0.53 or more).
|
||||
// 'auto' resolves from the clock to one of these three and has the same numbers.
|
||||
const cells: [FixedSkyState, string, string, string, string, string][] = [
|
||||
['day', 'noonday-sky', '#342d25', '6.68', '#2a4f27', '4.60'],
|
||||
['dusk', 'noonday-sky', '#342d25', '4.57', '#2a4f27', '3.15'],
|
||||
['night', 'midnight-sky', '#aeccff', '4.97', '#609385', '2.32'],
|
||||
['day', 'noonday-sky', '#342d25', '6.64', '#2a4f27', '4.57'],
|
||||
['dusk', 'noonday-sky', '#342d25', '4.60', '#2a4f27', '3.17'],
|
||||
['night', 'midnight-sky', '#aeccff', '4.91', '#609385', '2.29'],
|
||||
];
|
||||
|
||||
it.each(cells)(
|
||||
|
|
@ -86,8 +95,8 @@ describe('ink of the theme a state picks, on bare sky', () => {
|
|||
[18, 'dusk'],
|
||||
[0, 'night'],
|
||||
] as const)('auto at %s:00 has the numbers of %s', (hour, state) => {
|
||||
setSkyClock(() => new Date(2026, 8, 22, hour, hour === 18 ? 10 : 0));
|
||||
const id = skyThemeId('auto');
|
||||
setSkyClock(() => atStandardTime(hour, hour === 18 ? 10 : 0));
|
||||
const id = skyThemeId(getResolvedSkyState()) as keyof typeof SKY;
|
||||
expect(id).toBe(skyThemeId(state));
|
||||
const { tokens, link } = SKY[id];
|
||||
const text = tokens.Background.OnContainer;
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
// Which theme a sky state lights the page with. 'auto' takes the theme of the sky it resolves to
|
||||
// (skyState.resolveSkyState), since that is the sky behind the text.
|
||||
// Which theme a sky state lights the page with. 'auto' picks none: it never overrides a person's theme
|
||||
// (the stored one when signed in, Midnight Sky when signed out). A wiring that follows the sky when no theme
|
||||
// is stored reads `getResolvedSkyState` (skyState.ts) and passes that fixed state here.
|
||||
//
|
||||
// Day and Dusk take the dark ink of Noonday Sky, Night the light ink of Midnight Sky. Each state's
|
||||
// drawn sky is shaped into a luminance band (skyBand.ts) in which that ink's TEXT clears 4.5:1 on
|
||||
|
|
@ -9,7 +10,6 @@
|
|||
// derived outside this code (src/sky/skyTokens.js); lightening the Night link to a luminance of
|
||||
// about 0.53 or more would clear it. The plate (skyPlate.css.ts) is still in the shell, pending
|
||||
// its removal.
|
||||
import { resolveSkyState } from './skyState';
|
||||
import type { FixedSkyState, SkyState } from './skyState';
|
||||
|
||||
export type SkyThemeId = 'midnight-sky' | 'noonday-sky';
|
||||
|
|
@ -20,4 +20,5 @@ const BY_STATE: Record<FixedSkyState, SkyThemeId> = {
|
|||
night: 'midnight-sky',
|
||||
};
|
||||
|
||||
export const skyThemeId = (state: SkyState): SkyThemeId => BY_STATE[resolveSkyState(state)];
|
||||
export const skyThemeId = (state: SkyState): SkyThemeId | undefined =>
|
||||
state === 'auto' ? undefined : BY_STATE[state];
|
||||
|
|
|
|||
7
src/app/features/scene/standardTime.testkit.ts
Normal file
7
src/app/features/scene/standardTime.testkit.ts
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
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);
|
||||
};
|
||||
|
|
@ -5,6 +5,8 @@ import { GRID, triangleCount } from './terrainWorld';
|
|||
import { groundLight, SKY, skyAtSun } from './terrainSky';
|
||||
import { AP_VOLUME, apVolumeWords, SKY_VIEW, skyViewWords } from './terrainScatter';
|
||||
import { SKY_FRAG } from './terrainShaders';
|
||||
import { SKY_BAND } from '../skyBand';
|
||||
import { terrainSkyFor } from '../skyForState';
|
||||
import { startBackgroundScene } from '../index';
|
||||
|
||||
/** A GL context that accepts every call, remembers them, reports success for compile, link and framebuffer. */
|
||||
|
|
@ -158,6 +160,32 @@ describe('createTerrainScene', () => {
|
|||
expect(has(uploaded({}), nightA)).toBe(true);
|
||||
});
|
||||
|
||||
it.each(['day', 'dusk', 'night'] as const)(
|
||||
'uploads the %s band as uBand (floor, ceiling) and uLift, in the sky pass and the grid pass',
|
||||
(state) => {
|
||||
const { gl, calls } = fakeGl();
|
||||
const opts = terrainSkyFor(state);
|
||||
createTerrainScene({ canvas: canvasWith(gl), tier: 'still', ...opts })!.dispose();
|
||||
const { floor, ceiling, lift } = SKY_BAND[state];
|
||||
const pairs = calls.uniform2fv.filter(
|
||||
(a) =>
|
||||
Math.abs((a[1] as number[])[0] - floor) < 1e-6 &&
|
||||
Math.abs((a[1] as number[])[1] - ceiling) < 1e-6
|
||||
);
|
||||
expect(pairs).toHaveLength(2);
|
||||
const lifts = calls.uniform3fv.filter((a) =>
|
||||
Array.from(a[1] as ArrayLike<number>).every((x, i) => Math.abs(x - lift[i]) < 1e-6)
|
||||
);
|
||||
expect(lifts).toHaveLength(2);
|
||||
}
|
||||
);
|
||||
|
||||
it('uploads no band (0, 1) and a zero lift without one', () => {
|
||||
const { gl, calls } = fakeGl();
|
||||
createTerrainScene({ canvas: canvasWith(gl), tier: 'still' })!.dispose();
|
||||
expect(calls.uniform2fv.filter((a) => (a[1] as number[])[1] === 1)).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('a sun elevation (option or ?sun=&az=) lights between the bakes, and wins over ?sky=', () => {
|
||||
const ambients = (opts: Record<string, unknown>) => {
|
||||
const { gl, calls } = fakeGl();
|
||||
|
|
|
|||
|
|
@ -28,7 +28,7 @@ export type TerrainOptions = Pick<
|
|||
SceneOptions,
|
||||
'canvas' | 'tier' | 'onCompileFail' | 'onContextLost'
|
||||
> & {
|
||||
/** Which baked sky lights and hazes the terrain. Default: `?sky=` in the page URL, else the night notion of `skyColours()`. */
|
||||
/** Which baked sky lights and hazes the terrain. Default: `?sky=` in the page URL, else midnight. */
|
||||
sky?: SkyName;
|
||||
/** Put the sun at this elevation (degrees) and azimuth (clockwise from north; default: noonday's) instead of at the baked sky's: `?sun=` and `?az=` in the page URL. Lights between the two bakes, for dusk. */
|
||||
sun?: { elevation: number; azimuth?: number };
|
||||
|
|
|
|||
|
|
@ -221,10 +221,25 @@ export function shade(d: SkyData, albedo: Vec3, normal: Vec3, distance: number,
|
|||
}) as unknown as Vec3;
|
||||
}
|
||||
|
||||
/** What the page URL asks of the sky, if anything: `?sun=` (with `?az=`) wins over `?sky=midnight|noonday`; a bad value asks nothing. */
|
||||
export function urlSky():
|
||||
| { sky?: SkyName; sun?: { elevation: number; azimuth?: number } }
|
||||
| undefined {
|
||||
const q = new URLSearchParams(window.location.search);
|
||||
const number = (key: string) => (q.get(key)?.trim() ? Number(q.get(key)) : NaN);
|
||||
const elevation = number('sun');
|
||||
if (Number.isFinite(elevation)) {
|
||||
const azimuth = number('az');
|
||||
return { sun: { elevation, azimuth: Number.isFinite(azimuth) ? azimuth : undefined } };
|
||||
}
|
||||
const name = q.get('sky');
|
||||
return isSkyName(name) ? { sky: name } : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* The sky to use. An explicit option wins over the page URL, so a person who picked a sky sees it: a sun
|
||||
* elevation (with its azimuth, default noonday's), else a baked sky. Only without either does the URL steer:
|
||||
* `?sun=` (with `?az=`), then `?sky=midnight|noonday`, then midnight. (The door always names a sky and a band; these are for callers that do not.)
|
||||
* elevation (with its azimuth, default noonday's), else a baked sky. Only without either does the URL steer
|
||||
* (`urlSky`), else midnight. A band, when given, shapes whichever sky that is.
|
||||
*/
|
||||
export function chooseSky(opts: {
|
||||
sky?: SkyName;
|
||||
|
|
@ -232,15 +247,7 @@ export function chooseSky(opts: {
|
|||
band?: SkyBand;
|
||||
}): SkyData {
|
||||
const banded = (d: SkyData): SkyData => (opts.band ? { ...d, band: opts.band } : d);
|
||||
if (opts.sun) return banded(skyAtSun(opts.sun.elevation, opts.sun.azimuth));
|
||||
if (opts.sky) return banded(skyData(opts.sky));
|
||||
const q = new URLSearchParams(window.location.search);
|
||||
const number = (key: string) => (q.get(key)?.trim() ? Number(q.get(key)) : NaN);
|
||||
const elevation = number('sun');
|
||||
if (Number.isFinite(elevation)) {
|
||||
const azimuth = number('az');
|
||||
return banded(skyAtSun(elevation, Number.isFinite(azimuth) ? azimuth : undefined));
|
||||
}
|
||||
const name = q.get('sky');
|
||||
return banded(skyData(isSkyName(name) ? name : 'midnight'));
|
||||
const want = opts.sun || opts.sky ? opts : urlSky() ?? { sky: 'midnight' as const };
|
||||
if (want.sun) return banded(skyAtSun(want.sun.elevation, want.sun.azimuth));
|
||||
return banded(skyData(want.sky ?? 'midnight'));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,15 +1,5 @@
|
|||
import { useSyncExternalStore } from 'react';
|
||||
import {
|
||||
getResolvedSkyState,
|
||||
getSkyState,
|
||||
subscribe,
|
||||
type FixedSkyState,
|
||||
type SkyState,
|
||||
} from '../features/scene/skyState';
|
||||
import { getSkyState, subscribe, type SkyState } from '../features/scene/skyState';
|
||||
|
||||
/** The choice, as the control shows it ('auto' stays 'auto'). */
|
||||
/** The choice, as the control shows it ('auto' stays 'auto'). The sky being drawn is `getResolvedSkyState`. */
|
||||
export const useSkyState = (): SkyState => useSyncExternalStore(subscribe, getSkyState);
|
||||
|
||||
/** The sky being drawn: the choice, resolved from the clock for 'auto'. */
|
||||
export const useResolvedSkyState = (): FixedSkyState =>
|
||||
useSyncExternalStore(subscribe, getResolvedSkyState);
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ import '../../sky.css';
|
|||
import { settingsAtom } from '../state/settings';
|
||||
import { useSetting } from '../state/hooks/settings';
|
||||
import { skyThemeId } from '../features/scene/skyTheme';
|
||||
import { useResolvedSkyState } from './useSkyState';
|
||||
import { useSkyState } from './useSkyState';
|
||||
|
||||
export enum ThemeKind {
|
||||
Light = 'light',
|
||||
|
|
@ -102,9 +102,9 @@ export const useSystemThemeKind = (): ThemeKind => {
|
|||
return themeKind;
|
||||
};
|
||||
|
||||
/** The theme the sky being drawn asks for ('auto' asks for the one of the sky it resolves to). */
|
||||
/** The theme the sky state asks for, or undefined while it is 'auto': auto never overrides a person's theme. */
|
||||
export const useSkyTheme = (): Theme | undefined => {
|
||||
const id = skyThemeId(useResolvedSkyState());
|
||||
const id = skyThemeId(useSkyState());
|
||||
return id === NoondaySkyTheme.id ? NoondaySkyTheme : id && MidnightSkyTheme;
|
||||
};
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue