diff --git a/harness/scene/README.md b/harness/scene/README.md index 91837c3e..fa618c5a 100644 --- a/harness/scene/README.md +++ b/harness/scene/README.md @@ -27,20 +27,17 @@ clamped to the place's range as the app does (phi 0: `camera.r_max_forward_m`, a npx vite --port 5199 # from the repo root; the app's vite config serves the page and public/ http://localhost:5199/harness/scene/ridgeSheet.html # four presets x six skies - ...ridgeSheet.html?preset=swiss # one preset (physical|swiss|poster|painterly) + ...ridgeSheet.html?preset=painterly # one preset (painterly|painterly-cel-2|painterly-cel-3|painterly-cel-4) ...ridgeSheet.html?looks=%5B%7B%22label%22%3A%22no-ink%22%2C%22inkScale%22%3A0%7D%2C%7B%22label%22%3A%22hazy%22%2C%22hazeScale%22%3A8%7D%5D ...?w=640 # cell width -`looks=` is a url-encoded or base64 JSON array of `{label, ...partial RidgeLook}` and replaces the preset rows (`inkKeep` and `reliefLight` merge by key). +`looks=` is a url-encoded or base64 JSON array of `{label, ...partial RidgeLook}` and replaces the preset rows (`inkKeep` merges by key). A cell costs one WebGL2 context and a card decode, so the full sheet takes tens of seconds (much longer in a background tab). -Presets (`PRESETS` in `ridgeSheet.ts`; swiss and poster take every key not named from `PHYSICAL_LOOK`, the rest from `DEFAULT_LOOK`, the painterly cel look), chosen by reasoning, not by eye, for Self to tune: +Presets (`PRESETS` in `ridgeSheet.ts`; every key not named comes from `DEFAULT_LOOK`, the painterly cel-3 look), chosen by reasoning, not by eye, for Self to tune: | preset | values | | --- | --- | -| physical | PHYSICAL_LOOK (Lambert, no noise, sky haze, full ink) | -| swiss | reliefLight {mix 0.7, azimuthDeg -45, elevationDeg 40}, contrastByDistance 0.9, hazeScale 6, hazeTint [0, 0.05, 0.25], nearWarm 0.5, inkScale 0.6 | -| poster | reliefWeight 0.15, cardToneStep 0.25, cardGradient 0.5, inkKeep {edge 0.25, occlude 0.9, crease 1}, hazeScale 4 | | painterly | DEFAULT_LOOK: groundNoise 0.35, cloudShadows 0.5, nearWarm 0.6, hazeScale 2, inkScale 0.4, celBands 3, celSoftness 0.05, celAmbientAway 0.7 | | painterly-cel-2 / -3 / -4 | painterly with celBands 2 / 3 / 4 | diff --git a/harness/scene/ridgeDemo.ts b/harness/scene/ridgeDemo.ts index 17e67774..e61162ee 100644 --- a/harness/scene/ridgeDemo.ts +++ b/harness/scene/ridgeDemo.ts @@ -1,6 +1,5 @@ // Standalone page for the ridge scene: full window, no host app. `?tier=still|low|full` picks the -// tier, `?probe=1` shows the rAF median/p95 readout. The long tasks the page saw are on `window.longTasks` -// for a driver to read. Not shipped. +// tier. The long tasks the page saw are on `window.longTasks` for a driver to read. Not shipped. import { startBackgroundScene } from '../../src/app/features/scene'; import type { SceneTier } from '../../src/app/features/scene'; diff --git a/harness/scene/ridgeSheet.ts b/harness/scene/ridgeSheet.ts index 440a3a57..f0f10fa9 100644 --- a/harness/scene/ridgeSheet.ts +++ b/harness/scene/ridgeSheet.ts @@ -3,8 +3,8 @@ // `?views=214:0:200,0:0:200,100:0:200,214:90:98.2` one column per view `heading:phi:offset` (degrees, degrees, metres) at one sky (`?sky=2`, an index of SKIES, noon by default); a heading // of 360 or 0 is across north. `&sun=100:6` puts the sun of that sky at azimuth 100, 6 degrees up (the stars are always those of the moment the sheet is opened). The offset is clamped to the place's range as the app does (phi 0: the bake's forward bound, any other phi: the worst-case bound), and a phi other than 0 is the offset-only rotation mode, the camera circling the centre. // `?place=vienna` the baked place (index.json's default if absent) -// `?preset=all|physical|swiss|poster|painterly|painterly-cel-2|painterly-cel-3|painterly-cel-4` (default all: one row each; painterly is DEFAULT_LOOK); `?looks=` replaces the rows with -// the given `{label, ...partial RidgeLook}` entries (inkKeep and reliefLight merge by key). `?w=480` sets the cell width, 16:9 unless `?h=` gives the height (`?w=375&h=812` is a phone). +// `?preset=all|painterly|painterly-cel-2|painterly-cel-3|painterly-cel-4` (default all: one row each; painterly is DEFAULT_LOOK); `?looks=` replaces the rows with +// the given `{label, ...partial RidgeLook}` entries (inkKeep merges by key). `?w=480` sets the cell width, 16:9 unless `?h=` gives the height (`?w=375&h=812` is a phone). // The sky behind a cell is the app's own: `makePhysicalSky` + `paintSky` upscaled smoothly, with the real stars and the moon (`nightBodies`), // without the sun disc or clouds. Columns are the SKIES below (a sun elevation each, the stars and moon of the moment the sheet was opened), or: // `?moments=2026-11-24T22:00Z,2026-12-09T20:00Z` explicit UTC moments: the sun, moon and stars are those of the moment, the state follows the sun's elevation @@ -12,7 +12,7 @@ // (`?hours=18,21,0,4` UTC), plus deep dusk (sun at -10 degrees) of the evening of the full moon // `?labels=1` DEBUG: label each constellation chain in frame with its d3-celestial abbreviation (fetched from the source repository at run time; not shipped) // `?lines=1` constellation lines over the stars, as the Sky menu's hidden toggle does (night cells only) -import { DEFAULT_LOOK, PHYSICAL_LOOK, createLighter } from '../../src/app/features/scene/ridge/lightCards'; +import { DEFAULT_LOOK, createLighter } from '../../src/app/features/scene/ridge/lightCards'; import type { RidgeLook } from '../../src/app/features/scene/ridge/lightCards'; import { parseIndex, parseManifest } from '../../src/app/features/scene/ridge/manifest'; import { makePhysicalSky } from '../../src/app/features/scene/ridge/physicalSky'; @@ -28,12 +28,9 @@ import { moonPhase } from '../../src/sky/moon.js'; import { MOMENT_IDS, momentFor } from '../../src/app/features/scene/ridge/skyMoment'; -type Override = Partial> & { +type Override = Partial> & { label: string; - /** The look the unnamed keys come from (DEFAULT_LOOK, the painterly cel look, if absent). */ - base?: 'physical'; inkKeep?: Partial; - reliefLight?: Partial; }; interface Column { @@ -58,26 +55,6 @@ const SKIES: Column[] = [ /** The art directions, chosen by reasoning, not by eye: Self tunes them (values listed in harness/scene/README.md). */ const PRESETS: Record = { - physical: { label: 'physical', base: 'physical' }, - swiss: { - label: 'swiss', - base: 'physical', - reliefLight: { mix: 0.7, azimuthDeg: -45, elevationDeg: 40 }, - contrastByDistance: 0.9, - hazeScale: 6, - hazeTint: [0, 0.05, 0.25], - nearWarm: 0.5, - inkScale: 0.6, - }, - poster: { - label: 'poster', - base: 'physical', - reliefWeight: 0.15, - cardToneStep: 0.25, - cardGradient: 0.5, - inkKeep: { edge: 0.25, occlude: 0.9, crease: 1 }, - hazeScale: 4, - }, painterly: { label: 'painterly (default, cel 3)' }, 'painterly-cel-2': { label: 'painterly-cel-2', celBands: 2 }, 'painterly-cel-3': { label: 'painterly-cel-3', celBands: 3 }, @@ -85,15 +62,13 @@ const PRESETS: Record = { }; const merge = (o: Override): { label: string; look: RidgeLook } => { - const { label, base: baseName, inkKeep, reliefLight, ...rest } = o; - const base = baseName === 'physical' ? PHYSICAL_LOOK : DEFAULT_LOOK; + const { label, inkKeep, ...rest } = o; return { label, look: { - ...base, + ...DEFAULT_LOOK, ...rest, - inkKeep: { ...base.inkKeep, ...inkKeep }, - reliefLight: { ...base.reliefLight, ...reliefLight }, + inkKeep: { ...DEFAULT_LOOK.inkKeep, ...inkKeep }, }, }; }; @@ -187,7 +162,7 @@ const pinned = q.get('moments') || q.get('night'); const rows = (q.get('looks') ? parseLooks(q.get('looks') as string) : preset && preset !== 'all' - ? [PRESETS[preset] ?? PRESETS.physical] + ? [PRESETS[preset] ?? PRESETS.painterly] : pinned ? [PRESETS.painterly] // a night set is read in the default look unless a preset or looks say otherwise : Object.values(PRESETS) diff --git a/src/app/features/scene/README.md b/src/app/features/scene/README.md index a93da532..fd71d9da 100644 --- a/src/app/features/scene/README.md +++ b/src/app/features/scene/README.md @@ -2,7 +2,7 @@ The ridge scene (`ridge/`): no per-frame WebGL (the baked cards are lit once per scene build, in a WebGL2 context that is released after). `startBackgroundScene` runs it; the tier flag still defaults to `off`, and null still means "keep the CSS ground". -- `ridge/Ridge.ts` `createRidgeScene({ canvas, tier, probe?, onProbe?, sky?, backdrop? })` returns `{ dispose }` or +- `ridge/Ridge.ts` `createRidgeScene({ canvas, tier, sky?, backdrop? })` returns `{ dispose }` or null (tier `off`, no 2D context). It paints the sky (`ridge/physicalSky.ts`, from the `SkyColours` the host passes) into a sky plate (`ridge/skyTurn.ts`): one element over the host canvas, the viewport's width plus its slack of sky each side (20 degrees, more as the turn speeds up: the margin of the speed in force over a tick and 2 s of lateness, and 14 degrees of travel), centred on the heading `heading.ts` owns, holding the sky with the real stars, the moon and the lines baked into it and a twinkle canvas for the swinging stars (`ridge/stars.ts`) over it. The sky is at infinity, so one animation slides the plate by the heading's turn at the cards' px per degree, on the @@ -14,11 +14,6 @@ The ridge scene (`ridge/`): no per-frame WebGL (the baked cards are lit once per (`index.ts`). - Paused when the tab is hidden; under `prefers-reduced-motion` the rain is paused and the stars stay at base brightness. `tier: 'still'` paints the sky (facing the heading its pose froze at) and stars into the host canvas and adds no plate, no rain and no loop. -- Cadence guard: for the first 2 s after start (after 5 warm-up frames) rAF intervals are sampled; if their p95 is over - 33 ms the scene settles to a still image (`ridge/probe.ts`) and stops. `?probe=1` (or `probe: true`) keeps sampling - and shows `n / median / p95` in a corner readout. -- `ridge/skyColour.ts` `skyColours()` is the fallback three-stop palette (top, mid, horizon) a scene gets with no `sky` option; the host - passes `ridgeSkyFor` (skyForState.ts) instead. - Ridge cards: `ridge/manifest.ts` `loadManifest` reads `${BASE_URL}public/ridge/index.json` (`skyPlace.ts` `resolvePlaceId` picks the entry: the viewer's choice if the index lists it, else config `backgroundScene.place` if listed, else the index default), then the place's `manifest.json` (schema 3, written by `scripts/ridge-bake/export.py`; it is the one JSON the backdrop reads): the whole 360 degree ring, K G-buffer cards nearest first, each cut into azimuth tiles (32 of 11.25 degrees) of a colour WebP (albedo, @@ -42,7 +37,7 @@ The ridge scene (`ridge/`): no per-frame WebGL (the baked cards are lit once per anywhere (404, a manifest that is not schema 3, no tile that will decode, no WebGL2, a lighting pass that throws) is the sky-only scene on `FALLBACK_VIEW`, told to the host by the live scene alone, through `onPlanesFail` when the live scene has no cards and `onPlanesOk` when a later one has them (never from a stale or disposed build); it is never `onCompileFail`. `vite.config.js` copies `public/ridge` into `dist/public/`. -- `harness/scene/bundle.cjs ` builds a standalone page (`?tier=`, `?probe=1`). +- `harness/scene/bundle.cjs ` builds a standalone page (`?tier=`). ## Ridge scene: Vienna and the weather @@ -59,8 +54,7 @@ today's at the place (Night tonight's: the solar midnight nearest, before the da `place.tz`, the IANA zone the baker writes into the manifest (`scripts/ridge-bake/places.json`); the viewer's own zone decides nothing. Auto and the named moments draw today's weather; a free moment draws a clear sky. -`skyState.ts` holds the stores (choice, place, constellation lines) and tells listeners; the choice persists in `ratatoskr.skyChoice`. The key -of the old four-state menu is read once by `skyState.ts` (Day became Noon) and removed. `skyPlace.ts` is the one writer of the place: a scene start loads the manifest of the place `resolvePlaceId` names, the viewer's pick (`placeState.ts`, localStorage `ratatoskr.skyPlace`, per viewer) before the config's place before the index default (nothing else fetches it, so a page with no scene fetches nothing) and the build +`skyState.ts` holds the stores (choice, place, constellation lines) and tells listeners; the choice persists in `ratatoskr.skyChoice`. `skyPlace.ts` is the one writer of the place: a scene start loads the manifest of the place `resolvePlaceId` names, the viewer's pick (`placeState.ts`, localStorage `ratatoskr.skyPlace`, per viewer) before the config's place before the index default (nothing else fetches it, so a page with no scene fetches nothing) and the build settles what it draws, the manifest's place when the cards load, `FALLBACK_VIEW`'s when they do not (a failed manifest, no tile that will decode), so the sky, the weather, the ink and the Auto timer read the place that is drawn. Until a scene has settled it no sky is drawn for ink and the theme's own ink stands. The one timer (Auto, a named moment) tells listeners when the band changes or a named moment's place-local day rolls over. diff --git a/src/app/features/scene/debugOverlays.test.ts b/src/app/features/scene/debugOverlays.test.ts deleted file mode 100644 index e1a4e61e..00000000 --- a/src/app/features/scene/debugOverlays.test.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { debugOverlaysAllowed, overlayRequested } from './debugOverlays'; - -let search = ''; -beforeEach(() => { - search = ''; - vi.stubGlobal('window', { - get location() { - return { search }; - }, - }); -}); -afterEach(() => { - vi.unstubAllGlobals(); - vi.unstubAllEnvs(); -}); - -describe('debugOverlaysAllowed', () => { - it('a production build allows nothing by default', () => { - vi.stubEnv('DEV', false); - vi.stubEnv('VITE_PREVIEW_DEMO', ''); - expect(debugOverlaysAllowed(undefined)).toBe(false); - expect(debugOverlaysAllowed({ tier: 'full' })).toBe(false); - expect(debugOverlaysAllowed({ tier: 'full', debugOverlays: false })).toBe(false); - }); - - it('a dev build, a demo preview build or an explicit config flag allows them', () => { - vi.stubEnv('DEV', true); - expect(debugOverlaysAllowed(undefined)).toBe(true); - vi.stubEnv('DEV', false); - vi.stubEnv('VITE_PREVIEW_DEMO', '1'); - expect(debugOverlaysAllowed(undefined)).toBe(true); - vi.stubEnv('VITE_PREVIEW_DEMO', ''); - expect(debugOverlaysAllowed({ debugOverlays: true })).toBe(true); - }); -}); - -describe('overlayRequested', () => { - it('needs both the query and the permission', () => { - search = '?probe=1'; - expect(overlayRequested('probe', true)).toBe(true); - expect(overlayRequested('probe', false)).toBe(false); - expect(overlayRequested('tierlabel', true)).toBe(false); - search = '?tierlabel=1'; - expect(overlayRequested('tierlabel', true)).toBe(true); - search = ''; - expect(overlayRequested('probe', true)).toBe(false); - }); -}); diff --git a/src/app/features/scene/debugOverlays.ts b/src/app/features/scene/debugOverlays.ts deleted file mode 100644 index a02d9e92..00000000 --- a/src/app/features/scene/debugOverlays.ts +++ /dev/null @@ -1,15 +0,0 @@ -import type { BackgroundSceneConfig } from './tier'; - -/** - * Whether the page URL may switch on the scene's diagnostic overlays (`?probe=1` frame readout, `?tierlabel=1` path - * label). Only a dev build, a demo preview build (VITE_PREVIEW_DEMO=1), or a config that says `debugOverlays: true` - * allows it; a production visitor adding a query string gets nothing. - */ -export const debugOverlaysAllowed = (config: BackgroundSceneConfig | undefined): boolean => - import.meta.env?.DEV === true || - import.meta.env?.VITE_PREVIEW_DEMO === '1' || - config?.debugOverlays === true; - -/** The page URL asks for this overlay (`?name=1`), and the overlays are allowed. */ -export const overlayRequested = (name: 'probe' | 'tierlabel', allowed: boolean): boolean => - allowed && new URLSearchParams(window.location.search).get(name) === '1'; diff --git a/src/app/features/scene/index.ts b/src/app/features/scene/index.ts index c249760e..2e094991 100644 --- a/src/app/features/scene/index.ts +++ b/src/app/features/scene/index.ts @@ -1,11 +1,10 @@ import type { Scene } from './ridge/Ridge'; import { BackgroundSceneConfig, Capabilities, SceneTier, resolveTier } from './tier'; -import { debugOverlaysAllowed } from './debugOverlays'; import { getConstellationLines, getSkyChoice, skyBandAt, subscribe } from './skyState'; import type { FixedSkyState, SkyChoice } from './ridge/skyMoment'; import { drawnView, ensureSkyPlace, resetSkyPlanes } from './skyPlace'; import { subscribePlaceChoice } from './placeState'; -import type { SkyColours } from './ridge/skyColour'; +import type { SkyColours } from './ridge/physicalSky'; import type { Backdrop } from './ridge/Backdrop'; import { FALLBACK_VIEW, HFOV_MAX_DEG, maxSpeed } from './ridge/view'; @@ -71,7 +70,7 @@ const holdsATile = (backdrop: Backdrop, stop: AbortSignal): Promise => async function prepare( config: BackgroundSceneConfig | undefined, - options: StartOptions & { tier: SceneTier; debug?: boolean }, + options: StartOptions & { tier: SceneTier }, choice: SkyChoice, /** Nothing with a ridge is up to wait behind: the page's first scene, or a rebuild over a scene that is the sky alone. It waits against the deadline and, with no tile, is the sky alone. */ first: boolean, @@ -205,7 +204,6 @@ export async function startBackgroundScene( ): Promise { const tier = resolveTier(config, capabilities); if (tier === 'off') return null; - const debug = debugOverlaysAllowed(config); // What the host was last told of the planes: only the live scene speaks, and only when its state changes. let planesFailed = false; const announce = (planesFail: Error | null) => { @@ -213,7 +211,7 @@ export async function startBackgroundScene( if (!planesFail && planesFailed) options.onPlanesOk?.(); planesFailed = planesFail !== null; }; - const prepared = (choice: SkyChoice, first: boolean, stop: AbortSignal) => prepare(config, { ...options, tier, debug }, choice, first, stop); + const prepared = (choice: SkyChoice, first: boolean, stop: AbortSignal) => prepare(config, { ...options, tier }, choice, first, stop); resetSkyPlanes(); const choice = getSkyChoice(); const key0 = await skyKey(config, choice); diff --git a/src/app/features/scene/ridge/Ridge.test.ts b/src/app/features/scene/ridge/Ridge.test.ts index 884c3423..85950cf3 100644 --- a/src/app/features/scene/ridge/Ridge.test.ts +++ b/src/app/features/scene/ridge/Ridge.test.ts @@ -2,9 +2,8 @@ import { readFileSync } from 'node:fs'; import { join } from 'node:path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { createRidgeScene, RESIDENCY_MS } from './Ridge'; -import { valueNoise, hash2 } from './noise'; -import { FrameSampler, frameStats, SLOW_P95_MS, WARMUP_FRAMES, WINDOW_MS } from './probe'; -import type { SkyColours } from './skyColour'; +import { hash2 } from './noise'; +import type { SkyColours } from './physicalSky'; import { nightBodies } from './nightBodies'; import { sunAt } from './sunAt'; import { makePhysicalSky, paintSky as paintPhysicalSky } from './physicalSky'; @@ -31,70 +30,13 @@ const posed = (m: Parameters[0], card: number, t: number, w: Pa describe('noise', () => { it('is deterministic and in [0, 1)', () => { - expect(hash2(3, 5)).toBe(hash2(3, 5)); for (let i = 0; i < 200; i += 1) { - const v = valueNoise(i * 0.37 - 20, 2); + const v = hash2(i, 2); expect(v).toBeGreaterThanOrEqual(0); expect(v).toBeLessThan(1); - expect(valueNoise(i * 0.37 - 20, 2)).toBe(v); + expect(hash2(i, 2)).toBe(v); } }); - - it('different rows are different profiles', () => { - expect(valueNoise(1.5, 0)).not.toBeCloseTo(valueNoise(1.5, 1), 3); - }); -}); - -describe('frame sampler', () => { - const feed = (s: FrameSampler, dt: number, frames: number, from = 0) => { - let t = from; - let done = false; - for (let i = 0; i < frames && !done; i += 1) { - t += dt; - done = s.push(t); - } - return done; - }; - - it('median and p95 of known intervals', () => { - const v = Array.from({ length: 100 }, (_, i) => (i < 90 ? 16 : 50)); - expect(frameStats(v)).toEqual({ n: 100, medianMs: 16, p95Ms: 50 }); - expect(frameStats([])).toEqual({ n: 0, medianMs: 0, p95Ms: 0 }); - }); - - it('does not complete before 2 s of measured frames, and ignores the warm-up', () => { - const s = new FrameSampler(); - expect(feed(s, 16, 100)).toBe(false); // 1.6 s - expect(feed(s, 16, 40, 1600)).toBe(true); - expect(s.stats().n).toBeLessThan(100 + 40 - WARMUP_FRAMES + 1); - }); - - it('a smooth 60 Hz run is not slow; a run of 40 ms frames is', () => { - const good = new FrameSampler(); - feed(good, 16.7, 400); - expect(good.slow()).toBe(false); - const bad = new FrameSampler(); - feed(bad, 100, 400); // ~100 ms frames, the PR #13 readout - expect(bad.stats().p95Ms).toBeGreaterThan(SLOW_P95_MS); - expect(bad.slow()).toBe(true); - }); - - it('a long warm-up frame does not poison the window', () => { - const s = new FrameSampler(); - let t = 0; - s.push(t); - for (let i = 0; i < WARMUP_FRAMES; i += 1) s.push((t += 300)); // setup, upload, JIT - feed(s, 16.7, 200, t); - expect(s.slow()).toBe(false); - expect(WINDOW_MS).toBe(2000); - }); - - it('reset forgets a hidden-tab gap', () => { - const s = new FrameSampler(); - feed(s, 16, 20); - s.reset(); - expect(s.stats().n).toBe(0); - }); }); // A minimal DOM: just what createRidgeScene touches. @@ -242,7 +184,6 @@ function ctx() { let rafQueue: Array<(t: number) => void>; let motion: { matches: boolean; addEventListener: any; removeEventListener: any }; let doc: any; -let search: string; beforeEach(() => { rafQueue = []; @@ -253,7 +194,6 @@ beforeEach(() => { arcs.length = 0; twinks.length = 0; onPaint = undefined; - search = ''; motion = { matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn() }; doc = Object.assign(new EventTarget(), { visibilityState: 'visible', @@ -268,11 +208,6 @@ beforeEach(() => { innerHeight: 800, matchMedia: () => motion, clearTimeout, - location: { - get search() { - return search; - }, - }, setTimeout, }) ); @@ -334,26 +269,6 @@ describe('createRidgeScene', () => { s.dispose(); }); - it('a smooth run draws nothing more and ends its rAF loop', () => { - const { canvas } = host(); - const s = createRidgeScene({ canvas, tier: 'full', sky: DAY })!; - const before = draws.length; - runFrames(16.7, 400); - expect(draws.length).toBe(before); - expect(rafQueue).toHaveLength(0); // no per-frame work left - s.dispose(); - }); - - it('p95 over 33 ms across 2 s settles to a still and reports it', () => { - const { canvas } = host(); - const onProbe = vi.fn(); - const s = createRidgeScene({ canvas, tier: 'full', onProbe, sky: DAY })!; - runFrames(100, 100); - expect(onProbe).toHaveBeenLastCalledWith(expect.objectContaining({ still: true })); - expect(rafQueue).toHaveLength(0); - s.dispose(); - }); - it("'still' tier never starts a loop", () => { const { parent, canvas } = host(); createRidgeScene({ canvas, tier: 'still' }); @@ -361,28 +276,6 @@ describe('createRidgeScene', () => { expect(rafQueue).toHaveLength(0); }); - it('?probe=1 keeps the rAF loop alive and shows median and p95', () => { - search = '?probe=1'; - const { parent, canvas } = host(); - const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, debug: true })!; - const readout = parent.children[parent.children.length - 1]; - runFrames(16.7, 300); - expect(rafQueue.length).toBe(1); // still sampling - expect(readout.textContent).toMatch(/median 16\.\d ms · p95 1[67]\.\d ms/); - s.dispose(); - expect(parent.children.some((c: any) => c === readout)).toBe(false); - }); - - it('?probe=1 does nothing where the overlays are not allowed: no readout, the loop ends', () => { - search = '?probe=1'; - const { parent, canvas } = host(); - const s = createRidgeScene({ canvas, tier: 'full', sky: DAY })!; - expect(parent.children).toEqual([canvas]); - runFrames(16.7, 300); - expect(rafQueue.length).toBe(0); - s.dispose(); - }); - it('a scene started at zero size paints nothing, then builds on the first non-zero resize', async () => { const { parent, canvas } = host(); canvas.clientWidth = 0; @@ -528,16 +421,6 @@ describe('the starfield in the scene', () => { s.dispose(); }); - it('flattening to a still (slow frames) drops the overlay and leaves every star baked into the sky', () => { - const { parent, canvas } = host(); - const s = createRidgeScene({ canvas, tier: 'full', sky: night })!; - runFrames(100, 100); - expect(parent.children).toEqual([canvas]); - expect(count('star')).toBe(NPLATE + N); // the plate's, then the still's own in the host canvas - expect(rafQueue).toHaveLength(0); - s.dispose(); - }); - it('dispose removes the overlay and stops the loop', () => { const { parent, canvas } = host(); const s = createRidgeScene({ canvas, tier: 'full', sky: night })!; diff --git a/src/app/features/scene/ridge/Ridge.ts b/src/app/features/scene/ridge/Ridge.ts index 2604a120..d2081169 100644 --- a/src/app/features/scene/ridge/Ridge.ts +++ b/src/app/features/scene/ridge/Ridge.ts @@ -1,8 +1,6 @@ import type { SceneTier } from '../tier'; -import { overlayRequested } from '../debugOverlays'; -import { FrameSampler, FrameStats } from './probe'; -import { skyColours, SkyColours, Srgb } from './skyColour'; import { paintSky as paintPhysicalSky } from './physicalSky'; +import type { SkyColours, Srgb } from './physicalSky'; import { cardArc, cardPose, HFOV_MAX_DEG, offsetRange, SEGMENT_S, sweepArc, windowFor } from './view'; import type { Camera, CardPose, View } from './view'; import type { TileCard } from './manifest'; @@ -24,13 +22,7 @@ export interface Scene { export type RidgeOptions = { canvas: HTMLCanvasElement; tier?: SceneTier; - /** Show the rAF median/p95 readout. Default: the page URL has `?probe=1`, where `debug` allows it. */ - probe?: boolean; - /** The diagnostic overlays may be asked for by URL (debugOverlays.ts). Default: no. */ - debug?: boolean; - /** Each time the readout would update, and once with `still` when the fallback fires. */ - onProbe?: (s: FrameStats & { still: boolean }) => void; - /** The sky's colours; default `skyColours()`, the one function to replace with Void's sun.js. */ + /** The sky's colours; defaults to a twilight gradient when omitted. */ sky?: SkyColours; /** The baked ridge cards by tile, lit for `sky` (`Backdrop.ts`), the arc around the heading already made; none is the sky-only scene (`view.ts` FALLBACK_VIEW). The scene owns it from here and disposes it with itself. */ backdrop?: Backdrop; @@ -38,6 +30,12 @@ export type RidgeOptions = { lines?: boolean; }; +const FALLBACK_SKY: SkyColours = { + top: [170, 145, 220], + mid: [225, 130, 165], + horizon: [240, 150, 80], +}; + const css = (c: Srgb): string => `rgb(${c[0]},${c[1]},${c[2]})`; function context2d(c: HTMLCanvasElement): CanvasRenderingContext2D | null { return c.getContext('2d'); @@ -204,8 +202,7 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { const canvas = opts.canvas; const parent = canvas.parentElement; if (!parent) return null; - const sky = opts.sky ?? skyColours(); - const probe = opts.probe ?? overlayRequested('probe', opts.debug === true); + const sky = opts.sky ?? FALLBACK_SKY; const reducedMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)'); let built: Built | undefined; @@ -213,14 +210,11 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { let twLast = 0; /** Paint a plate's twinkle canvas at t seconds, or clear it (set by the plate the scene is up with). */ let paintTwinkleOf: (of: Pick, t?: number) => void = () => undefined; - let still = tier === 'still'; + const still = tier === 'still'; let disposed = false; - let raf = 0; - let readout: HTMLElement | undefined; let resizeTimer = 0; /** The pose a still shows: taken at its first paint and drawn at every repaint after, tile arrivals included; a resize takes a new one. A still has no clock. */ let stillPose: Pose | undefined; - const sampler = new FrameSampler(); const viewSize = () => { const w = canvas.clientWidth || window.innerWidth; @@ -674,76 +668,12 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { } } - /** Drop the twinkle and the rain, leaving the painted sky as a still image. */ - const settleToStill = () => { - if (still && !built) return; - if (!still) stillPose = undefined; // a live scene that flattens freezes the pose it has now - still = true; - teardown(); - cancelAnimationFrame(raf); - raf = 0; - paintStill(); - report(true); - }; - - const report = (stillNow: boolean) => { - const s = { ...sampler.stats(), still: stillNow }; - opts.onProbe?.(s); - if (readout) { - readout.textContent = `ridge · n ${s.n} · median ${s.medianMs.toFixed( - 1 - )} ms · p95 ${s.p95Ms.toFixed(1)} ms${stillNow ? ' · STILL' : ''}`; - } - }; - - let sinceReport = 0; - const tick = (now: number) => { - raf = 0; - if (!moving()) return; - const full = sampler.push(now); - if (full && sampler.slow() && !still) { - settleToStill(); - return; - } - // After the window the series keeps rolling only for the readout; otherwise the loop ends here. - if (full && !probe) return; - if (probe && now - sinceReport > 500) { - sinceReport = now; - report(false); - } - raf = requestAnimationFrame(tick); - }; - - const wake = () => { - syncPlayState(); - if (!moving() || raf) return; - sampler.reset(); - raf = requestAnimationFrame(tick); - }; - // No area yet is not a failure: the resize listener below builds once the host has one. if (!build() && !hasNoArea()) return null; - if (probe) { - readout = document.createElement('div'); - Object.assign(readout.style, { - position: 'absolute', - left: '8px', - top: '8px', - font: '12px monospace', - color: '#fff', - background: 'rgba(0,0,0,.55)', - padding: '2px 6px', - borderRadius: '3px', - pointerEvents: 'none', - }); - parent.appendChild(readout); - } - if (still) settleToStill(); - else wake(); + if (still) paintStill(); const onVisibility = () => { - sampler.reset(); - wake(); + syncPlayState(); }; /** Make the scene again at the size it has now and settle as it was: after a resize, and after tiles arrive into a still. A burst of either is one rebuild, 250 ms after the last. */ let freshPose = false; @@ -752,22 +682,17 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { clearTimeout(resizeTimer); resizeTimer = window.setTimeout(() => { if (disposed) return; - const wasStill = still; if (freshPose) { // A resize is a new view: a still takes the pose the heading has now and asks for the tiles of it; the arrivals then repaint that pose. stillPose = undefined; - if (wasStill && opts.backdrop) { + if (still && opts.backdrop) { const { h } = headingPose(clock()); opts.backdrop.ensure({ fromDeg: h - HFOV_MAX_DEG / 2, toDeg: h + HFOV_MAX_DEG / 2 }).catch(() => undefined); } } freshPose = false; if (!build()) return; - if (wasStill) settleToStill(); - else { - sampler.reset(); - wake(); - } + if (still) paintStill(); }, 250); }; // A still draws once and has no timer to ask for tiles, so it is told of each one that is made after its paint (the deadline of a scene start leaves the rest of the @@ -788,7 +713,6 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { dispose() { if (disposed) return; disposed = true; - cancelAnimationFrame(raf); offTile?.(); opts.backdrop?.dispose(); clearTimeout(resizeTimer); @@ -796,7 +720,6 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { window.removeEventListener('resize', onResize); reducedMotion?.removeEventListener?.('change', onMotionChange); teardown(); - readout?.remove(); }, }; } diff --git a/src/app/features/scene/ridge/lightCards.test.ts b/src/app/features/scene/ridge/lightCards.test.ts index 8b1b76b3..d92c95c9 100644 --- a/src/app/features/scene/ridge/lightCards.test.ts +++ b/src/app/features/scene/ridge/lightCards.test.ts @@ -2,7 +2,6 @@ import { describe, expect, it, vi } from 'vitest'; import { decodeNormal, DEFAULT_LOOK, - PHYSICAL_LOOK, celShade, celLevels, FRAGMENT, @@ -276,33 +275,22 @@ describe('the look reaches the shader', () => { expect(u.uInkKeep[0]).toBe(1); }); - it('carries the art-pass axes: relief, fixed light, tint, tone, ink scale, noise', () => { + it('carries the art-pass axes: near warm, ink scale, ground noise, cloud shadows', () => { const u = run({ - reliefWeight: 0.15, - reliefLight: { mix: 1, azimuthDeg: 0, elevationDeg: 90 }, - hazeTint: [0, 0.1, 0.3], nearWarm: 0.5, - contrastByDistance: 1.5, - cardToneStep: 0.2, - cardGradient: 0.3, inkScale: 0, groundNoise: 0.4, cloudShadows: 0.6, }); - expect(u.uRelief).toEqual([0.15, 1]); - expect(u.uFixedLight[2]).toBeCloseTo(1, 12); // a light straight up - expect(u.uHazeTint).toEqual([0, 0.1, 0.3]); - expect(u.uDist).toEqual([0.5, 1.5]); - expect(u.uCard).toEqual([1, 0.3]); // a single card sits at the centre of the tone steps + expect(u.uNearWarm).toEqual([0.5]); expect(u.uInkScale).toEqual([0]); expect(u.uGround).toEqual([0.4, 0.6]); }); - it('scales the haze optical depth and the ambient light, and moves the sun cut-off', () => { + it('scales the haze optical depth and moves the sun cut-off', () => { const base = run(); - const look = run({ hazeScale: 2 * DEFAULT_LOOK.hazeScale, ambientScale: 0.5 }); + const look = run({ hazeScale: 2 * DEFAULT_LOOK.hazeScale }); look.uExt.forEach((e, k) => expect(e).toBeCloseTo(2 * base.uExt[k], 12)); - expect(look.uAmbient[2]).toBeCloseTo(0.15, 6); // plus the airglow's ambient expect( lightingOf(manifest, sky30(), { ...DEFAULT_LOOK, sunCutoffDeg: 45 }).key.direct ).toEqual([0, 0, 0]); @@ -368,13 +356,13 @@ describe('night key light', () => { }); describe('cel shading', () => { - const sweep = (bands: number, softness: number, levels?: number[]) => { + const sweep = (bands: number, softness: number) => { const out = new Set(); for (let i = -20; i <= 100; i += 1) { const x = i / 100; // away from the band edges (i / bands), where a softened edge is between two levels if (Array.from({ length: bands }, (_, k) => k / bands).some((e) => e > 0 && Math.abs(x - e) <= softness / 2 + 1e-9)) continue; - out.add(Math.round(celShade(x, bands, softness, levels) * 1e9)); + out.add(Math.round(celShade(x, bands, softness) * 1e9)); } return out; }; @@ -395,14 +383,9 @@ describe('cel shading', () => { expect(celShade(-0.5, 3, 0)).toBe(0); expect(celShade(1, 3, 0)).toBe(1); }); - it('takes the band levels it is given', () => { - expect(celLevels(3, [0.2, 0.5, 0.9]).slice(0, 3)).toEqual([0.2, 0.5, 0.9]); - expect(celShade(0.9, 3, 0, [0.2, 0.5, 0.9])).toBe(0.9); - expect(celShade(-1, 3, 0, [0.2, 0.5, 0.9])).toBe(0.2); - }); - it('is on in the default look and off in the physical one; the shader carries the ramp', () => { - expect(DEFAULT_LOOK.celBands).toBeGreaterThan(0); - expect(PHYSICAL_LOOK.celBands).toBe(0); + it('computes evenly spaced levels and uses cel3 in the default look; the shader carries the ramp', () => { + expect(celLevels(3).slice(0, 3)).toEqual([0, 0.5, 1]); + expect(DEFAULT_LOOK.celBands).toBe(3); expect(FRAGMENT).toContain('float cel(float x)'); expect(FRAGMENT).toContain('uBandLevels[6]'); }); diff --git a/src/app/features/scene/ridge/lightCards.ts b/src/app/features/scene/ridge/lightCards.ts index 39c5fcc9..c9d4b6f1 100644 --- a/src/app/features/scene/ridge/lightCards.ts +++ b/src/app/features/scene/ridge/lightCards.ts @@ -40,22 +40,8 @@ export interface RidgeLook { sunCutoffDeg: number; /** Multiplies the optical depth of the aerial perspective: 1 is the sky's own extinction, 0 no haze. */ hazeScale: number; - /** Multiplies the ambient irradiance the terrain is lit by. */ - ambientScale: number; - /** 0 = no normal shading (the flat card tone, as a horizontal surface), 1 = shaded by the normals. */ - reliefWeight: number; - /** The relief light: `mix` 0 is the sun, 1 a fixed light; `azimuthDeg` is clockwise of the view ray (-45 = upper left, behind the ridge), `elevationDeg` above the horizon. */ - reliefLight: { mix: number; azimuthDeg: number; elevationDeg: number }; - /** Added to the sky radiance used for the haze, rgb in units of that radiance's own luminance (so it holds at every sky): positive blue = cool far. */ - hazeTint: readonly [number, number, number]; /** Strength (0..1) of a warm tint on the near, fading out with the log-distance across the baked range. */ nearWarm: number; - /** The relief's contrast about the pixel's flat tone scales by exp(c (1 - 2 d)), d the log-distance across the baked range: c > 0 near contrasty, far flat. */ - contrastByDistance: number; - /** Value of each card multiplies by 1 + step (index - centre); the nearest card is index 0, so a positive step makes near darkest. */ - cardToneStep: number; - /** Value ramp inside each card: 1 + g (y - 1/2), y the fraction down the card; positive lightens toward the foot. */ - cardGradient: number; /** Multiplies each ink's darkening: 0 = no lines. */ inkScale: number; /** Procedural albedo variation (a stand-in for land cover we do not bake): fbm in metres on the ground, so its screen frequency follows distance. 0 = none. */ @@ -66,59 +52,37 @@ export interface RidgeLook { celBands: number; /** Width of each band edge in n.s units (0 = hard). */ celSoftness: number; - /** The level of each band, 0..1, darkest first (default: evenly from 0 to 1). Length `celBands`. */ - celBandLevels?: readonly number[]; /** The ambient is coarse too: surfaces facing the sky (the normal's up component past `celAmbientEdge`) keep it whole, the rest keep this fraction (1 = no step). */ celAmbientAway: number; celAmbientEdge: number; } -/** The first art pass's look: Lambert relief, no procedural variation, the sky's own haze, full ink. Kept for comparison in the look sheet. */ -export const PHYSICAL_LOOK: RidgeLook = { +/** The default: painterly cel-3 (ground variation, cloud shadows, warm near, moderate haze, light ink). */ +export const DEFAULT_LOOK: RidgeLook = { occludeLogD: 0.35, creaseCos: 0.85, inkKeep: { edge: 0.45, occlude: 0.55, crease: 0.8 }, sunCutoffDeg: -1, - hazeScale: 1, - ambientScale: 1, - reliefWeight: 1, - reliefLight: { mix: 0, azimuthDeg: -45, elevationDeg: 40 }, - hazeTint: [0, 0, 0], - nearWarm: 0, - contrastByDistance: 0, - cardToneStep: 0, - cardGradient: 0, - inkScale: 1, - groundNoise: 0, - cloudShadows: 0, - celBands: 0, - celSoftness: 0, - celAmbientAway: 1, - celAmbientEdge: 0.7, -}; - -/** The default: painterly (ground variation, cloud shadows, warm near, moderate haze, light ink) with cel-shaded relief. */ -export const DEFAULT_LOOK: RidgeLook = { - ...PHYSICAL_LOOK, + hazeScale: 2, + nearWarm: 0.6, + inkScale: 0.4, groundNoise: 0.35, cloudShadows: 0.5, - nearWarm: 0.6, - hazeScale: 2, - inkScale: 0.4, celBands: 3, celSoftness: 0.05, celAmbientAway: 0.7, + celAmbientEdge: 0.7, }; /** Most bands the shader's uniform holds. */ export const CEL_MAX = 6; -/** The level of each of `bands` cel bands, darkest first: `custom` where given, else evenly 0..1 (one band is fully lit). Padded to `CEL_MAX`. */ -export function celLevels(bands: number, custom?: readonly number[]): number[] { +/** The level of each of `bands` cel bands, darkest first, evenly 0..1 (one band is fully lit). Padded to `CEL_MAX`. */ +export function celLevels(bands: number): number[] { const n = Math.min(CEL_MAX, Math.max(1, Math.round(bands))); return Array.from({ length: CEL_MAX }, (_, i) => { const k = Math.min(i, n - 1); - return custom?.[k] ?? (n === 1 ? 1 : k / (n - 1)); + return n === 1 ? 1 : k / (n - 1); }); } @@ -131,9 +95,9 @@ const smooth = (a: number, b: number, v: number): number => { * The cel ramp: the light of a surface whose normal makes `ndl` with the sun, in `bands` flat bands, edges at i / bands (i = 1..bands-1), each * edge `softness` wide. The lowest band holds the unlit side too (its level is what ambient light alone leaves). The shader writes the same. */ -export function celShade(ndl: number, bands: number, softness: number, levels?: readonly number[]): number { +export function celShade(ndl: number, bands: number, softness: number): number { const n = Math.min(CEL_MAX, Math.max(1, Math.round(bands))); - const lv = celLevels(n, levels); + const lv = celLevels(n); let out = lv[0]; for (let i = 1; i < n; i += 1) { const e = i / n; @@ -202,7 +166,7 @@ export interface KeyLight { } export function keyLight(sky: PhysicalSky, look: RidgeLook = DEFAULT_LOOK): KeyLight { - const ambient = scale3(sky.atm.irradiance.ambient, look.ambientScale); + const ambient = sky.atm.irradiance.ambient; const glow = [0, 0, 0]; airglow(0.6, glow); const base = add3(ambient, scale3([glow[0], glow[1], glow[2]], Math.PI)); @@ -216,7 +180,7 @@ export function keyLight(sky: PhysicalSky, look: RidgeLook = DEFAULT_LOOK): KeyL azimuth: m.azimuth, elevation: m.elevation, direct: [trans[0] * fade, trans[1] * fade, trans[2] * fade], - ambient: add3(base, scale3(scale3(m.atm.irradiance.ambient, look.ambientScale), m.ratio)), + ambient: add3(base, scale3(m.atm.irradiance.ambient, m.ratio)), }; } sky.atm.transmittanceToSpace(Math.max(Math.sin(sky.sun.elevation * RAD), 0), trans); @@ -309,11 +273,7 @@ uniform float uCm[${KNOTS}]; uniform vec2 uInkGeometry; // occludeLogD, creaseCos uniform vec3 uInkKeep; // edge, occlude, crease uniform float uInkScale; -uniform vec2 uRelief; // weight, mix toward the fixed light -uniform vec3 uFixedLight; // in the column frame -uniform vec3 uHazeTint; -uniform vec2 uDist; // nearWarm, contrastByDistance -uniform vec2 uCard; // value of this card, gradient +uniform float uNearWarm; uniform vec2 uGround; // groundNoise, cloudShadows uniform vec4 uCel; // bands (0 = Lambert), softness, ambientAway, ambientEdge uniform float uBandLevels[${CEL_MAX}]; @@ -321,7 +281,6 @@ out vec4 outColor; const float PI = 3.14159265358979; const vec3 NEAR_WARM = vec3(1.0, 0.82, 0.62); -const vec3 LUMA = vec3(0.2126, 0.7152, 0.0722); const float WALL_RT2 = ${glsl(WALL_RT2)}; ${[0, 1, 2] .map((i) => `const vec3 IN_R${i} = vec3(${ACES_IN[i].map(glsl).join(', ')});`) @@ -438,7 +397,6 @@ void main() { int col = ((uCol0 + p.x) % uRingW + uRingW) % uRingW; vec3 s = texelFetch(uSun, ivec2(col, 0), 0).xyz; - if (uRelief.y > 0.0) s = normalize(mix(s, uFixedLight, uRelief.y)); float dist = exp(g.logD); // The ground's noise is a function of the ground point, dist x (sin psi, cos psi) for the column's absolute azimuth psi, so it is periodic over the wrap. float psi = (float(col) + 0.5) / float(uRingW) * 2.0 * PI; @@ -447,21 +405,14 @@ void main() { if (uGround.x > 0.0) albedo *= max(1.0 + uGround.x * (2.0 * fbm(world / 250.0) - 1.0), 0.0); float cloud = uGround.y > 0.0 ? 1.0 - uGround.y * smoothstep(0.5, 0.72, fbm(world / 4000.0 + 17.0)) : 1.0; float lit = uCel.x > 0.5 ? cel(dot(g.n, s)) : max(dot(g.n, s), 0.0); - float ndl = mix(max(s.z, 0.0), lit, uRelief.x); float ambStep = uCel.x > 0.5 ? mix(uCel.z, 1.0, smoothstep(uCel.w - uCel.y * 0.5, uCel.w + uCel.y * 0.5 + 1e-4, g.n.z)) : 1.0; - vec3 radiance = albedo * (uTSun * ndl * cloud + uAmbient * mix(1.0, ambStep, uRelief.x)) / PI; + vec3 radiance = albedo * (uTSun * lit * cloud + uAmbient * ambStep) / PI; float dn = clamp((g.logD - uLogD.x) / uLogD.y, 0.0, 1.0); - if (uDist.y != 0.0) { - vec3 flatTone = albedo * (uTSun * max(s.z, 0.0) * cloud + uAmbient) / PI; - radiance = flatTone + (radiance - flatTone) * exp(uDist.y * (1.0 - 2.0 * dn)); - } - radiance *= mix(vec3(1.0), NEAR_WARM, uDist.x * (1.0 - dn)); + radiance *= mix(vec3(1.0), NEAR_WARM, uNearWarm * (1.0 - dn)); vec3 T = exp(-uExt * (dist / 1000.0)); vec2 uv = vec2((float(col) + 0.5) / float(uRingW), (float(uTop + p.y) + 0.5) / uPlaneH); vec3 haze = skyAt(uv); - haze += uHazeTint * dot(haze, LUMA); radiance = radiance * T + haze * (1.0 - T); - radiance *= max(uCard.x * (1.0 + uCard.y * ((float(p.y) + 0.5) / float(uSize.y) - 0.5)), 0.0); float keep = 1.0; ivec2 dirs[4] = ivec2[4](ivec2(1, 0), ivec2(-1, 0), ivec2(0, 1), ivec2(0, -1)); @@ -613,19 +564,10 @@ export function createLighter( gl.uniform2f(u('uInkGeometry'), look.occludeLogD, look.creaseCos); gl.uniform3f(u('uInkKeep'), look.inkKeep.edge, look.inkKeep.occlude, look.inkKeep.crease); gl.uniform1f(u('uInkScale'), look.inkScale); - gl.uniform2f(u('uRelief'), look.reliefWeight, look.reliefLight.mix); - const fl = look.reliefLight; - gl.uniform3f( - u('uFixedLight'), - Math.cos(fl.elevationDeg * RAD) * Math.cos(fl.azimuthDeg * RAD), - Math.cos(fl.elevationDeg * RAD) * Math.sin(fl.azimuthDeg * RAD), - Math.sin(fl.elevationDeg * RAD) - ); - gl.uniform3f(u('uHazeTint'), ...look.hazeTint); - gl.uniform2f(u('uDist'), look.nearWarm, look.contrastByDistance); + gl.uniform1f(u('uNearWarm'), look.nearWarm); gl.uniform2f(u('uGround'), look.groundNoise, look.cloudShadows); gl.uniform4f(u('uCel'), look.celBands, look.celSoftness, look.celAmbientAway, look.celAmbientEdge); - gl.uniform1fv(u('uBandLevels'), celLevels(look.celBands, look.celBandLevels)); + gl.uniform1fv(u('uBandLevels'), celLevels(look.celBands)); gl.uniform2i(u('uSkySize'), SKY_LUT.w, SKY_LUT.h); floatTexture(gl, 2, lit.ringW, 1, sunColumns(view, lit.key)); floatTexture(gl, 3, SKY_LUT.w, SKY_LUT.h, skyLut(sky, view, SKY_LUT.w, SKY_LUT.h)); @@ -647,11 +589,6 @@ export function createLighter( gl.uniform2i(u('uSize'), colour.width, colour.height); gl.uniform1i(u('uTop'), entry.top); gl.uniform1i(u('uCol0'), tile * view.tileW - view.apron); - gl.uniform2f( - u('uCard'), - 1 + look.cardToneStep * (card - (manifest.cards.length - 1) / 2), - look.cardGradient - ); gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT); gl.drawArrays(gl.TRIANGLES, 0, 3); diff --git a/src/app/features/scene/ridge/noise.ts b/src/app/features/scene/ridge/noise.ts index 20d97a4d..d40d2838 100644 --- a/src/app/features/scene/ridge/noise.ts +++ b/src/app/features/scene/ridge/noise.ts @@ -1,25 +1,8 @@ -// CultMath's value noise on the CPU, in one dimension, over the whole line (no period). Clean-room: -// the algorithm is read from shaders/CultMath.glsl (`cultmath_hash`, `cultmath_value_noise`), not -// copied from any other terrain. Doubles instead of floats, so values differ from the GLSL in the -// last digits; nothing here has to match a shader. +// CultMath's hash function on the CPU. Clean-room: +// the algorithm is read from CultMath (`cultmath_hash`). const frac = (v: number): number => v - Math.floor(v); /** `cultmath_hash(vec2)`. */ export const hash2 = (x: number, y: number): number => frac(Math.sin(x * 127.1 + y * 311.7) * 43758.5453); - -const smooth = (t: number): number => t * t * (3 - 2 * t); - -/** - * `cultmath_value_noise` along row `row` of the lattice, in [0, 1). `row` is an integer, so the - * vertical blend of the 2D original is the identity. The lattice is hashed per cell, never wrapped: - * a ridge is a function of world-x, with no period for the eye to find. - */ -export function valueNoise(x: number, row: number): number { - const cell = Math.floor(x); - const u = smooth(x - cell); - const a = hash2(cell, row); - const b = hash2(cell + 1, row); - return a + (b - a) * u; -} diff --git a/src/app/features/scene/ridge/physicalSky.ts b/src/app/features/scene/ridge/physicalSky.ts index 7f8f5f24..70d32fd0 100644 --- a/src/app/features/scene/ridge/physicalSky.ts +++ b/src/app/features/scene/ridge/physicalSky.ts @@ -7,8 +7,20 @@ import { bakeAtmosphere } from './earthAtmosphere'; import type { Atmosphere } from './earthAtmosphere'; import { domeSize, renderDome, SUN_RADIUS, sunOnScreen } from './skyDome'; import type { Dome } from './skyDome'; -import type { Srgb } from './skyColour'; import { display8, fitDisplay } from './toneMap'; + +export type Srgb = readonly [number, number, number]; + +export interface SkyColours { + /** Top of the sky gradient, sRGB 0..255. */ + top: Srgb; + /** Mid-sky band. */ + mid: Srgb; + /** Colour at the horizon. */ + horizon: Srgb; + /** The physical sky this palette was read from; when present the host canvas is painted from it, not from the three stops. */ + physical?: PhysicalSky; +} import type { Display, Fit } from './toneMap'; import { moonAt } from './nightSky'; import type { MoonSample, NightLight } from './nightSky'; diff --git a/src/app/features/scene/ridge/probe.ts b/src/app/features/scene/ridge/probe.ts deleted file mode 100644 index 5ab9c57d..00000000 --- a/src/app/features/scene/ridge/probe.ts +++ /dev/null @@ -1,60 +0,0 @@ -// Frame cadence from rAF timestamps: what `?probe=1` shows, and what the still-image fallback -// decides on. Pure, so it is tested without a browser. - -export interface FrameStats { - /** Frame intervals counted. */ - n: number; - medianMs: number; - p95Ms: number; -} - -/** The fallback's threshold and window, from the brief: p95 over 33 ms across 2 s. */ -export const SLOW_P95_MS = 33; -export const WINDOW_MS = 2000; -/** The first frames pay for layout, canvas upload and JIT; they say nothing about steady cadence. */ -export const WARMUP_FRAMES = 5; - -const quantile = (sorted: readonly number[], q: number): number => - sorted.length === 0 ? 0 : sorted[Math.min(sorted.length - 1, Math.floor(q * sorted.length))]; - -export function frameStats(intervals: readonly number[]): FrameStats { - const s = [...intervals].sort((a, b) => a - b); - return { n: s.length, medianMs: quantile(s, 0.5), p95Ms: quantile(s, 0.95) }; -} - -export class FrameSampler { - private last: number | undefined; - private skipped = 0; - private startedAt: number | undefined; - private readonly intervals: number[] = []; - - /** Feed each rAF timestamp. Returns true once a full window has been measured. */ - push(now: number): boolean { - const prev = this.last; - this.last = now; - if (prev === undefined) return false; - if (this.skipped < WARMUP_FRAMES) { - this.skipped += 1; - return false; - } - this.startedAt ??= prev; - this.intervals.push(now - prev); - return now - this.startedAt >= WINDOW_MS; - } - - /** A pause (hidden tab, resize) breaks the series: its gap is not a slow frame. */ - reset(): void { - this.last = undefined; - this.skipped = 0; - this.startedAt = undefined; - this.intervals.length = 0; - } - - stats(): FrameStats { - return frameStats(this.intervals); - } - - slow(): boolean { - return this.stats().p95Ms > SLOW_P95_MS; - } -} diff --git a/src/app/features/scene/ridge/rain.ts b/src/app/features/scene/ridge/rain.ts index 2644ed96..7883facf 100644 --- a/src/app/features/scene/ridge/rain.ts +++ b/src/app/features/scene/ridge/rain.ts @@ -2,7 +2,7 @@ // script, no per-frame paint). Two tiles of different size and speed read as depth. The streaks wear the sky's own horizon colour, so // whatever they lighten stays inside the state's luminance bounds (a streak is a blend of two colours the sky already has). import { hash2 } from './noise'; -import type { Srgb } from './skyColour'; +import type { Srgb } from './physicalSky'; export interface RainTile { /** Tile edge, canvas px. */ diff --git a/src/app/features/scene/ridge/skyColour.ts b/src/app/features/scene/ridge/skyColour.ts deleted file mode 100644 index 259fb2da..00000000 --- a/src/app/features/scene/ridge/skyColour.ts +++ /dev/null @@ -1,27 +0,0 @@ -// The one place the sky's colours come from. Void's `src/sky/sun.js` (`light({ time, lat, lon, -// cloud_cover, precipitation })`, PR #20) is the intended source; until it lands this returns a -// fixed twilight: lavender zenith, rose mid-sky, orange horizon. Replace the body, keep the signature: the scene calls it once, at startup, -// and paints the result. - -import type { PhysicalSky } from './physicalSky'; - -export type Srgb = readonly [number, number, number]; - -export interface SkyColours { - /** Top of the sky gradient, sRGB 0..255. */ - top: Srgb; - /** Mid-sky band. */ - mid: Srgb; - /** Colour at the horizon. */ - horizon: Srgb; - /** The physical sky this palette was read from; when present the host canvas is painted from it, not from the three stops. */ - physical?: PhysicalSky; -} - -export function skyColours(_now: Date = new Date()): SkyColours { - return { - top: [170, 145, 220], - mid: [225, 130, 165], - horizon: [240, 150, 80], - }; -} diff --git a/src/app/features/scene/skyForState.ts b/src/app/features/scene/skyForState.ts index 79110262..26a5b3ff 100644 --- a/src/app/features/scene/skyForState.ts +++ b/src/app/features/scene/skyForState.ts @@ -1,7 +1,7 @@ // 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 type { SkyColours } from './ridge/physicalSky'; import { momentFor, momentKey, skyBand } from './ridge/skyMoment'; import type { FixedSkyState, SkyChoice } from './ridge/skyMoment'; import { sunAt } from './ridge/sunAt'; diff --git a/src/app/features/scene/skyState.test.ts b/src/app/features/scene/skyState.test.ts index ffd25717..7ebda076 100644 --- a/src/app/features/scene/skyState.test.ts +++ b/src/app/features/scene/skyState.test.ts @@ -7,7 +7,6 @@ import type { SkyChoice } from './ridge/skyMoment'; type Mod = typeof import('./skyState'); const VIENNA = FALLBACK_VIEW.place; -const OLD_KEY = 'ratatoskr.skyState'; const noon: SkyChoice = { kind: 'named', id: 'noon' }; const dusk: SkyChoice = { kind: 'named', id: 'dusk' }; const night: SkyChoice = { kind: 'named', id: 'night' }; @@ -73,35 +72,6 @@ describe('persistence', () => { expect((await fresh()).getSkyChoice()).toEqual(auto); }); - it.each([ - ['auto', auto], - ['day', noon], - ['dusk', dusk], - ['night', night], - ] as const)('migrates the old key %s to %j once, and removes it', async (old, want) => { - storage.data.set(OLD_KEY, old); - const m = await fresh(); - expect(m.getSkyChoice()).toEqual(want); - expect(storage.data.has(OLD_KEY)).toBe(false); - expect(JSON.parse(storage.data.get(SKY_CHOICE_KEY) as string)).toEqual(want); - m.setSkyChoice(dusk); - expect(storage.data.has(OLD_KEY)).toBe(false); - expect((await fresh()).getSkyChoice()).toEqual(dusk); - }); - - it.each(['noon', 'NIGHT', '', '"night"', 'null'])('ignores the old key holding %j, and removes it', async (old) => { - storage.data.set(OLD_KEY, old); - expect((await fresh()).getSkyChoice()).toEqual(auto); - expect(storage.data.has(OLD_KEY)).toBe(false); - }); - - it('the new key wins over a stale old one', async () => { - storage.data.set(OLD_KEY, 'night'); - storage.data.set(SKY_CHOICE_KEY, JSON.stringify(dusk)); - expect((await fresh()).getSkyChoice()).toEqual(dusk); - expect(storage.data.has(OLD_KEY)).toBe(false); - }); - it('keeps the pick for the page load when storage is refused', async () => { vi.stubGlobal('localStorage', { getItem: () => { @@ -120,36 +90,6 @@ describe('persistence', () => { expect(m.getSkyChoice()).toEqual(night); }); - it('migrates an old pick even when the new key cannot be written: the pick holds for the page load, the old key stays', async () => { - storage.data.set(OLD_KEY, 'day'); - vi.stubGlobal('localStorage', { - ...storage, - setItem: () => { - throw new Error('denied'); - }, - }); - expect((await fresh()).getSkyChoice()).toEqual(noon); - expect(storage.data.has(OLD_KEY)).toBe(true); - }); - - it('writes the new key before it removes the old one', async () => { - storage.data.set(OLD_KEY, 'dusk'); - const order: string[] = []; - vi.stubGlobal('localStorage', { - ...storage, - setItem: (k: string, v: string) => { - order.push(`set ${k}`); - storage.data.set(k, v); - }, - removeItem: (k: string) => { - order.push(`remove ${k}`); - storage.data.delete(k); - }, - }); - expect((await fresh()).getSkyChoice()).toEqual(dusk); - expect(order).toEqual([`set ${SKY_CHOICE_KEY}`, `remove ${OLD_KEY}`]); - }); - it('persists a set choice under one key and reads it back after a reload', async () => { (await fresh()).setSkyChoice(dusk); expect([...storage.data.entries()]).toEqual([[SKY_CHOICE_KEY, JSON.stringify(dusk)]]); diff --git a/src/app/features/scene/skyState.ts b/src/app/features/scene/skyState.ts index 3267468c..7dbedc12 100644 --- a/src/app/features/scene/skyState.ts +++ b/src/app/features/scene/skyState.ts @@ -34,32 +34,8 @@ export function parseSkyChoice(raw: unknown): SkyChoice | undefined { const same = (a: SkyChoice, b: SkyChoice): boolean => JSON.stringify(a) === JSON.stringify(b); -// The old 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 old = localStorage.getItem(OLD_KEY); - if (old !== null) { - const migrated = FROM_OLD.get(old); - if (migrated && localStorage.getItem(SKY_CHOICE_KEY) === null) { - try { - // The new key first: a refusal leaves the old one in place, and the pick holds for this page load. - localStorage.setItem(SKY_CHOICE_KEY, JSON.stringify(migrated)); - } catch { - return migrated; - } - localStorage.removeItem(OLD_KEY); - return migrated; - } - localStorage.removeItem(OLD_KEY); - } const stored = localStorage.getItem(SKY_CHOICE_KEY); return (stored !== null && parseSkyChoice(JSON.parse(stored))) || AUTO; } catch { diff --git a/src/app/features/scene/tier.ts b/src/app/features/scene/tier.ts index a74950ed..e35faa44 100644 --- a/src/app/features/scene/tier.ts +++ b/src/app/features/scene/tier.ts @@ -19,8 +19,6 @@ export interface BackgroundSceneConfig { tier?: SceneTier; /** The baked ridge place to show (a key of the ridge index); unknown or absent: the index's default. */ place?: string; - /** Let the page URL switch on the diagnostic overlays (`?probe=1`, `?tierlabel=1`) in a production build. Default: no. */ - debugOverlays?: boolean; } export function readCapabilities(nav: Navigator): Capabilities {