diff --git a/config.json b/config.json index fea9a59e..3e349d86 100644 --- a/config.json +++ b/config.json @@ -26,7 +26,7 @@ "enabled": false }, "fileZoneShare": { - "enabled": false + "enabled": true }, "push": { "vapidPublicKey": "", diff --git a/deployment/idunn/recipe.toml b/deployment/idunn/recipe.toml index 56840740..5d163432 100644 --- a/deployment/idunn/recipe.toml +++ b/deployment/idunn/recipe.toml @@ -6,14 +6,14 @@ target = "ratatoskr" # tarball was built from, which is not this commit. source_stamp_environment = "RATATOSKR_BUILD_COMMIT" -# Release dist b30ddac0522cc110d44d12276416c000841d086a: the output of build-prod-dist.sh (ALLOW_CONFIG_DRIFT=1), packed +# Release dist a1fdfee3cc1ad370d09761bc337e5aff7e069de3: the output of build-prod-dist.sh (ALLOW_CONFIG_DRIFT=1), packed # as dist/ at the top of one gzip tar. The tree carries the repo's own config.json; what is served is the operator's # carried file, which Idunn copies beside dist/ and the vhost aliases over the tree's (a vhost without that alias would # serve the repo config). [[external_inputs]] id = "dist-tarball" -url = "https://eureka.gamecult.org/forge/GameCult/Ratatoskr/releases/download/dist-b30ddac0/ratatoskr-b30ddac0-dist.tar.gz" -sha256 = "1654dc5f0ceefc5d1abf997fce1cd31ed7aef28d50e52c8cde6ce7b5c14efd23" +url = "https://eureka.gamecult.org/forge/GameCult/Ratatoskr/releases/download/dist-a1fdfee3/ratatoskr-a1fdfee3-dist.tar.gz" +sha256 = "22e4c24c328d33e9c9a5c560646b59e0b91f028b54ffb631d8d42872be7ff938" runner = "unpack" destination = "release/dist.tar.gz" diff --git a/docs/commons-files-desk.md b/docs/commons-files-desk.md index fa7242d2..d9152065 100644 --- a/docs/commons-files-desk.md +++ b/docs/commons-files-desk.md @@ -118,9 +118,9 @@ Under A the paused service is not built, and most of its list disappears: ## Cuts under A -Status 2026-11-14 (dev da822e9e plus the size-refusal cut): built: folders by album title path with navigation and breadcrumb (#147), pagination (#148), version folding (#149), add-to-album with named refusals (#150), Stop for a send in flight, replaces loops shown, freshest last event on add (#151), and the pre-send size refusal: a file larger than the server's `m.upload.size` is named and left unsent before any upload or album root, and a server stating no cap refuses nothing. **Not built: the Commons entry row** (item 1 below, found by `#commons:gamecult.org` or the carried `media.commons` id through `lookupMediaRoom`, behind a dark `filesDesk.enabled` flag; neither the row nor the flag exists in the code). It waits on Eureka's Commons room. +Status 2026-11-14 (dev da822e9e plus the size-refusal cut): built: folders by album title path with navigation and breadcrumb (#147), pagination (#148), version folding (#149), add-to-album with named refusals (#150), Stop for a send in flight, replaces loops shown, freshest last event on add (#151), and the pre-send size refusal: a file larger than the server's `m.upload.size` is named and left unsent before any upload or album root, and a server stating no cap refuses nothing. The Commons entry row is built (item 1): `useCommons` in `MediaRow.tsx` finds the room by the alias `#commons:` (provisioning records no id for it), through `lookupZoneRoom` (the one lookup `lookupMediaRoom` also uses); `EstateNavigator` shows it above the tiers as a Commons link when joined, a join row when invited or not joined, and nothing when the room is absent, the lookup failed or is out. It is gated on the existing `fileZoneShare.enabled`, not a new `filesDesk.enabled` flag. The album view and ShareSet work there because provisioning creates the Commons with the `org.gamecult.file_zone` create type. Members can share only once the room's power levels let them post: provisioning gives the poster level to the Minds alone. -1. **Commons entry**: a Commons row in the navigator (like `MediaRow`, found by alias or carried id), opening the room's album view. Flagged, no new data layer. +1. **Commons entry**: a Commons row in the navigator (like `MediaRow`, found by alias), opening the room's album view. Flagged, no new data layer. 2. **Pagination** of albums and files in `useAlbums` (done, PR #148). 3. **Folders by title path** and the album list grouped by it. 4. **Versions**: read `org.gamecult.publish.replaces`, show the latest of a chain with the earlier versions folded under it (done, PR #149). diff --git a/docs/gamecult/client-build-install.md b/docs/gamecult/client-build-install.md index b2505fe1..7bc87dcb 100644 --- a/docs/gamecult/client-build-install.md +++ b/docs/gamecult/client-build-install.md @@ -113,9 +113,10 @@ Hard-refresh to clear `sw.js`. Do not delete the failed release; leave it for di ## Open -- The served config (checked 2026-11-12) is not the repo's: it says `backgroundScene.style` - `terrain` where the repo says `ridge` (#106, Meta 2026-11-11), lacks the repo's `dings`, - `fileZoneShare` and `registration` blocks (all off in the repo), and has no trailing newline. - The new keys default off or inert when absent, so only the style is a decision. Meta says which - style ships. Until the served file is replaced, every handoff build stops at the live check - unless `ALLOW_CONFIG_DRIFT=1` is set (section 1). +- Until the release that drops the terrain style (Meta 2026-11-17, ruling + `ratatoskr:ruling:ridge-only-scene-terrain-cut`), the served config said + `backgroundScene.style: terrain` and lacked the repo's `dings`, `fileZoneShare` and + `registration` blocks. That release replaces the carried file with the production config; a + `terrain` value left anywhere now falls to the ridge default. Until the carried file and the + build pin are equal again, every handoff build stops at the live check unless + `ALLOW_CONFIG_DRIFT=1` is set (section 1). diff --git a/src/app/components/nav/styles.css.ts b/src/app/components/nav/styles.css.ts index 5156ed41..a3845e90 100644 --- a/src/app/components/nav/styles.css.ts +++ b/src/app/components/nav/styles.css.ts @@ -133,7 +133,7 @@ const NavItemBase = style({ backgroundColor: ContainerHover, }, // While the background scene runs the shell is clear (sceneShell.css.ts); a row is a faint - // wash of the theme's own surface: the terrain stays visible, the text stays readable. + // wash of the theme's own surface: the scene stays visible, the text stays readable. // Hover, the selected row and a press each strengthen it a step. ':root[data-scene] &': { backgroundColor: `color-mix(in srgb, ${surfaceInk} ${SCRIM_ROW}, transparent)`, diff --git a/src/app/features/estate/EstateNavigator.tsx b/src/app/features/estate/EstateNavigator.tsx index b560e08c..746b45b9 100644 --- a/src/app/features/estate/EstateNavigator.tsx +++ b/src/app/features/estate/EstateNavigator.tsx @@ -37,7 +37,7 @@ import { searchModalAtom } from '../../state/searchModal'; import { getCanonicalAliasOrRoomId } from '../../utils/matrix'; import { useMatrixClient } from '../../hooks/useMatrixClient'; import { MINDS } from '../../components/message/pose/poses'; -import { MediaLink, MediaNote, useMindMedia } from './MediaRow'; +import { MediaLink, MediaNote, useCommons, useMindMedia } from './MediaRow'; import { MediaRow as MediaRowState } from './mediaRoom'; import { useSelectedRoom } from '../../hooks/router/useSelectedRoom'; import { useCallEmbed } from '../../hooks/useCallEmbed'; @@ -194,6 +194,15 @@ function MindMedia({ media }: { media: MediaRowState }) { return ; } +/** The shared Commons room above the tiers: a link when joined, a join row otherwise, nothing when there is none. */ +function CommonsEntry() { + const mx = useMatrixClient(); + const room = useCommons(); + if (!room) return null; + if (room.state === 'joined') return ; + return ; +} + function GroupSection({ tierId, group }: { tierId: string; group: EstateGroup }) { const media = useMindMedia(group.mind, group.rooms); const hasMedia = MINDS.includes(group.mind); @@ -345,6 +354,7 @@ function EstateTiers({ rootId }: { rootId: string }) { return ( <> + {tiers.map((tier) => ( ))} diff --git a/src/app/features/estate/MediaRow.test.tsx b/src/app/features/estate/MediaRow.test.tsx index 6b590158..88f7e89e 100644 --- a/src/app/features/estate/MediaRow.test.tsx +++ b/src/app/features/estate/MediaRow.test.tsx @@ -26,4 +26,14 @@ describe('Media row', () => { expect(text(html)).toBe('Media'); expect(html).toContain('href="/home/%23void-files%3Agamecult.org/"'); }); + + it('the Commons link reads "Commons" and opens the room', () => { + const html = renderToStaticMarkup( + + + + ); + expect(text(html)).toBe('Commons'); + expect(html).toContain('href="/home/%23commons%3Agamecult.org/"'); + }); }); diff --git a/src/app/features/estate/MediaRow.tsx b/src/app/features/estate/MediaRow.tsx index 6277f09c..7d64497a 100644 --- a/src/app/features/estate/MediaRow.tsx +++ b/src/app/features/estate/MediaRow.tsx @@ -15,7 +15,10 @@ import { useEstateRootId } from './useEstate'; import { STEWARDSHIPS_KEY, MediaRow as MediaRowState, + commonsAlias, + commonsRow, lookupMediaRoom, + lookupZoneRoom, mediaRoomIdFromStewardships, mediaRow, typedMediaRoom, @@ -44,7 +47,7 @@ export function MediaNote({ note, title }: { note: string; title?: string }) { } /** The joined Media row: opens the room, which shows its album view. */ -export function MediaLink({ to }: { to: string }) { +export function MediaLink({ to, label = 'Media' }: { to: string; label?: string }) { return ( @@ -52,7 +55,7 @@ export function MediaLink({ to }: { to: string }) { {mediaIcon} - Media + {label} @@ -105,3 +108,23 @@ export const useMindMedia = (mind: string, rooms: readonly EstateRoom[]): MediaR if (typed) return { kind: 'room', room: { ...typed, name: 'Media' } }; return mediaRow(lookup.data, membership); }; + +/** The shared Commons room as the navigator sees it right now: undefined means no row. Dark unless fileZoneShare.enabled. */ +export const useCommons = (): EstateRoom | undefined => { + const mx = useMatrixClient(); + const joined = useAtomValue(allRoomsAtom); + const invited = useAtomValue(allInvitesAtom); + const enabled = !!useClientConfig().fileZoneShare?.enabled; + const server = mx.getDomain() ?? ''; + // Provisioning records no id for the Commons (only per-Mind zones under @rooms.file_zones): the alias is the one way in. + const lookup = useQuery({ + queryKey: ['commons-room', server], + queryFn: () => lookupZoneRoom(mx, commonsAlias(server), server), + staleTime: 60_000, + enabled, + }); + const membership = new Map(); + invited.forEach((id) => membership.set(id, 'invite')); + joined.forEach((id) => membership.set(id, 'join')); + return commonsRow(enabled, lookup.data, membership); +}; diff --git a/src/app/features/estate/mediaRoom.test.ts b/src/app/features/estate/mediaRoom.test.ts index 934caaae..45e912e0 100644 --- a/src/app/features/estate/mediaRoom.test.ts +++ b/src/app/features/estate/mediaRoom.test.ts @@ -1,9 +1,13 @@ import { describe, expect, it } from 'vitest'; import { + commonsAlias, + commonsRow, lookupMediaRoom, + lookupZoneRoom, mediaAlias, mediaRoomIdFromStewardships, mediaRow, + MediaLookup, typedMediaRoom, } from './mediaRoom'; @@ -132,3 +136,51 @@ describe('the Media row of a Mind', () => { expect(typedMediaRoom(rooms, () => false)).toBeUndefined(); }); }); + +describe('the Commons row', () => { + const none = new Map(); + + it('is found by the alias #commons:', async () => { + const { mx, asked } = clientFor(async () => ({ room_id: '!c:gamecult.org' })); + const lookup = await lookupZoneRoom(mx, commonsAlias('gamecult.org'), 'gamecult.org'); + expect(asked).toEqual(['#commons:gamecult.org']); + expect(commonsRow(true, lookup, new Map([['!c:gamecult.org', 'join']]))).toMatchObject({ + roomId: '!c:gamecult.org', + name: 'Commons', + state: 'joined', + }); + }); + + it('shows no row when the room is absent, the lookup failed or is still out', async () => { + const missing = await lookupZoneRoom( + clientFor(async () => { + throw notFound; + }).mx, + commonsAlias('gamecult.org'), + 'gamecult.org' + ); + const failed = await lookupZoneRoom( + clientFor(async () => { + throw new Error('down'); + }).mx, + commonsAlias('gamecult.org'), + 'gamecult.org' + ); + expect(commonsRow(true, missing, none)).toBeUndefined(); + expect(commonsRow(true, failed, none)).toBeUndefined(); + expect(commonsRow(true, undefined, none)).toBeUndefined(); + }); + + it('shows no row with the flag off, even for a found room', () => { + const found: MediaLookup = { found: true, roomId: '!c:gamecult.org', via: ['gamecult.org'] }; + expect(commonsRow(false, found, new Map([['!c:gamecult.org', 'join']]))).toBeUndefined(); + }); + + it('offers a join to a viewer who has not joined, and an accept to an invited one', () => { + const found: MediaLookup = { found: true, roomId: '!c:gamecult.org', via: ['gamecult.org'] }; + expect(commonsRow(true, found, none)?.state).toBe('joinable'); + expect(commonsRow(true, found, new Map([['!c:gamecult.org', 'invite']]))?.state).toBe( + 'invited' + ); + }); +}); diff --git a/src/app/features/estate/mediaRoom.ts b/src/app/features/estate/mediaRoom.ts index 5d1503b6..2e60fe3a 100644 --- a/src/app/features/estate/mediaRoom.ts +++ b/src/app/features/estate/mediaRoom.ts @@ -13,6 +13,9 @@ export const ROOMS_KEY = '@rooms'; export const mediaAlias = (mind: string, server: string): string => `#${mind}-files:${server}`; +/** The shared Commons room's alias (gamecult-ops synapse-accounts-hand-managed.py COMMONS_ALIAS). */ +export const commonsAlias = (server: string): string => `#commons:${server}`; + /** * The room id the stewardships state names for a Mind's media room, under `@rooms.file_zones[]`. * The state's mind-to-repos lists are not read here. @@ -46,16 +49,16 @@ export type MediaLookup = | { found: true; roomId: string; via: string[] } | { found: false; reason: 'unset' | 'error'; message?: string }; -/** Resolve a Mind's media room: a carried id if there is one, else the alias. A 404 means it is not set up. */ -export const lookupMediaRoom = async ( +/** Resolve a file-zone room (a Mind's media room, or Commons): a carried id if there is one, else the alias. A 404 means it is not set up. */ +export const lookupZoneRoom = async ( mx: MediaClient, - mind: string, + alias: string, server: string, carriedId?: string ): Promise => { if (carriedId) return { found: true, roomId: carriedId, via: [server] }; try { - const r = await mx.getRoomIdForAlias(mediaAlias(mind, server)); + const r = await mx.getRoomIdForAlias(alias); return { found: true, roomId: r.room_id, via: r.servers?.length ? r.servers : [server] }; } catch (e) { const err = e as { @@ -75,6 +78,14 @@ export const lookupMediaRoom = async ( } }; +/** Resolve a Mind's media room. */ +export const lookupMediaRoom = ( + mx: MediaClient, + mind: string, + server: string, + carriedId?: string +): Promise => lookupZoneRoom(mx, mediaAlias(mind, server), server, carriedId); + export type MediaRow = | { kind: 'checking' } | { kind: 'unset' } @@ -86,7 +97,8 @@ const MEMBERSHIP_STATE = { join: 'joined', invite: 'invited', none: 'joinable' } /** What the Media row shows: the lookup result joined to the user's own membership. */ export const mediaRow = ( lookup: MediaLookup | undefined, - membership: ReadonlyMap + membership: ReadonlyMap, + name = 'Media' ): MediaRow => { if (!lookup) return { kind: 'checking' }; if (!lookup.found) { @@ -99,7 +111,7 @@ export const mediaRow = ( kind: 'room', room: { roomId: lookup.roomId, - name: 'Media', + name, state: MEMBERSHIP_STATE[m ?? 'none'], via: lookup.via, parentId: null, @@ -107,3 +119,18 @@ export const mediaRow = ( }, }; }; + +/** + * The Commons row: the shared room, or nothing. Off with the share flag; not set up, still looking and a failed lookup + * show no row (the room is shared furniture, not a per-Mind promise like Media). A found room is joined, invited or + * joinable, as for Media. + */ +export const commonsRow = ( + enabled: boolean, + lookup: MediaLookup | undefined, + membership: ReadonlyMap +): EstateRoom | undefined => { + if (!enabled) return undefined; + const row = mediaRow(lookup, membership, 'Commons'); + return row.kind === 'room' ? row.room : undefined; +}; diff --git a/src/app/features/scene/BackgroundScene.tsx b/src/app/features/scene/BackgroundScene.tsx index c447b4f0..ff1045dd 100644 --- a/src/app/features/scene/BackgroundScene.tsx +++ b/src/app/features/scene/BackgroundScene.tsx @@ -1,9 +1,8 @@ -import React, { useEffect, useMemo, useRef } from 'react'; +import React, { useEffect, useRef } from 'react'; import { useClientConfig } from '../../hooks/useClientConfig'; import { getFallbackSession } from '../../state/sessions'; import { mountBackgroundScene } from './host'; import { readCapabilities, resolveTier } from './tier'; -import { getSceneStyleOverride } from './sceneStyle'; import './sceneShell.css'; import './sceneButtons.css'; @@ -18,11 +17,7 @@ export const SCENE_ACTIVE_ATTRIBUTE = 'data-scene'; * Tier 'off' renders nothing and loads nothing. */ export function BackgroundScene() { - const configured = useClientConfig().backgroundScene; - const config = useMemo(() => { - const style = getSceneStyleOverride(); - return configured && style ? { ...configured, style } : configured; - }, [configured]); + const config = useClientConfig().backgroundScene; const enabled = resolveTier(config, readCapabilities(navigator)) !== 'off'; const canvasRef = useRef(null); diff --git a/src/app/features/scene/README.md b/src/app/features/scene/README.md index 73844795..5413bc27 100644 --- a/src/app/features/scene/README.md +++ b/src/app/features/scene/README.md @@ -42,36 +42,6 @@ Integration (a canvas under the app, `startBackgroundScene`, `login()` when the are later cuts. This PR is the render core plus the contract the host needs: flag, tier, failure callbacks and the creature sizing rule. Nothing has drawn a creature. -## Terrain scene (`style: 'terrain'`): the baked sky - -`terrain/` draws a Phacelle-displaced grid under a sky read from Void's bake (`src/sky/baked.ts`, layout in -`src/sky/README.md`); nothing is vendored. `terrainSky.ts` reads each moment's `sun.{elevation_deg, azimuth_deg, -color_linear}`, `ambient_linear` and `horizon_hex`; `terrainScatter.ts` decodes `baked.scatter` and uploads `sky_view` as an -RGB16F 3D texture (the transmittance table stays on the CPU, for the sun's colour at an elevation the bake does not hold). -Both fragment shaders sample it: `SKY_FRAG` for the sky, `GRID_FRAG` for the haze, which is the sky's colour at the horizon in the -fragment's azimuth, so far ground fades into the sky behind it at dusk too. - -Page URL: `?sky=midnight|noonday` picks a bake; `?sun=&az=` puts the sun anywhere between them -(`skyAtSun`: baked transmittance for the sun's colour, ambient and horizon blended from the midnight bake to the noonday one as -the sun climbs from -8 to 25 degrees). `?sun=` wins over `?sky=`. - -Without WebGL2 (`createTerrainScene` returns null) the door mounts `terrain/TerrainSky2D.ts` on the same canvas: the sky alone, painted once on a -96 px wide 2D canvas from `skyColour` (the CPU twin of `SKY_FRAG`, same `?sky=` `?sun=` `?az=` choice via `chooseSky`), the star layer on -top when the sky is dark, nothing moving, no sun disc. Below the horizon the image continues in the horizon's colour. A canvas that already -holds a GL context gives no 2D one, so a GL failure after context creation (compile, framebuffer) still ends in the CSS ground. - -- Sky: `1 - exp(-SKY_EXPOSURE * radiance)` plus a night glow (the midnight horizon colour, `nightness` 1 below -4 degrees, 0 above 4), a - sun disc from the sun's colour, and a +-0.5/255 dither on the 8-bit output. The table is single scattering only (no ground bounce, - no multiple scattering), so the noon horizon is pale yellow-green and a sun just under the horizon colours the whole sky orange, - where the real one keeps a blue-violet zenith. Within `HORIZON_FLOOR` (1.5 degrees) of the horizon the sky takes one flat colour, - because the table dips toward the ground there and would draw a seam against the haze. -- Stars: faded by the sun's elevation, `starGain` 1 below -12 degrees (where the table goes dark), 0 above -6, smooth between; - the field is placed against the midnight gradient and no longer gated on the sky being dark. At a baked sky that is the same as - before (midnight shows, noonday does not). -- Changed numbers: haze colour (was the gradient's horizon stop; now the scattered sky), ambient (was the gradient's zenith stop - x `AMBIENT_GAIN` 0.25 x `NIGHT_LIFT` up to 4; now `ambient_linear` as baked, so midnight's fill is about 2.5 to 3.5 times darker than - the lifted one). `HAZE_K` (0.0004 per metre) is unchanged. - ## Ridge scene: Vienna and the weather The ridge sky is the physical atmosphere (`ridge/earthAtmosphere.ts`) lit by the real sun over the viewpoint, 48.1929826 N, 16.3534237 E diff --git a/src/app/features/scene/SkyStateControl.tsx b/src/app/features/scene/SkyStateControl.tsx index 82c442a8..955394b6 100644 --- a/src/app/features/scene/SkyStateControl.tsx +++ b/src/app/features/scene/SkyStateControl.tsx @@ -23,16 +23,8 @@ import { WEATHER_DATASET, } from './ridge/credits'; import { useClientConfig } from '../../hooks/useClientConfig'; -import { - getSceneStyleOverride, - SERVED_SCENE_STYLES, - setSceneStyle, - type ServedSceneStyle, -} from './sceneStyle'; import { PhoneHit } from '../../styles/PhoneHit.css'; -const STYLE_LABEL: Record = { terrain: 'Terrain', ridge: 'Ridges' }; - const LABEL: Record = { auto: 'Auto', day: 'Day', @@ -48,13 +40,10 @@ export function SkyStateControl() { const state = useSkyState(); const [cords, setCords] = useState(); const backgroundScene = useClientConfig().backgroundScene; - const configuredStyle = backgroundScene?.style; - const sceneStyle: ServedSceneStyle = - getSceneStyleOverride() ?? (configuredStyle === 'terrain' ? 'terrain' : 'ridge'); const place = backgroundScene?.place; const [credit, setCredit] = useState(); - const ridgeOn = !!backgroundScene && sceneStyle === 'ridge'; + const ridgeOn = !!backgroundScene && backgroundScene.style !== 'raymarch'; useEffect(() => { if (!ridgeOn) return undefined; let live = true; @@ -108,37 +97,7 @@ export function SkyStateControl() { ))} - {backgroundScene && ( - <> - - Background - - {SERVED_SCENE_STYLES.map((st) => ( - { - setCords(undefined); - if (st !== sceneStyle) setSceneStyle(st); - }} - after={sceneStyle === st ? : undefined} - > - - {STYLE_LABEL[st]} - - - ))} - - )} - {backgroundScene && sceneStyle === 'ridge' && ( + {ridgeOn && ( createScene(options)); } - if (config?.style === 'terrain') { - const { createTerrainScene } = await import('./terrain/Terrain'); - const { createTerrainSkyScene } = await import('./terrain/TerrainSky2D'); - const sky = terrainSkyFor(state); - // No WebGL2 (or no usable GL): the terrain's sky alone on the same canvas, not bare ground. - return guarded( - () => - createTerrainScene({ ...options, ...sky }) ?? - createTerrainSkyScene({ ...options, ...sky }) - ); - } const { createRidgeScene } = await import('./ridge/Ridge'); const { manifest, fail } = await manifestOf(config); await loadWeather(weatherUrl(), (manifest?.view ?? FALLBACK_VIEW).place); @@ -125,16 +114,14 @@ async function prepare( /** * What a rebuild is for: the sky options the scene would be built from. A change of choice that draws the same sky - * (Day picked while the clock says day, 'auto' to the fixed state it resolves to) is not a rebuild; the page URL steers - * only 'auto' (`terrainSkyFor`), so there the two differ and the key says so. + * (Day picked while the clock says day, 'auto' to the fixed state it resolves to) is not a rebuild. */ async function skyKey( config: BackgroundSceneConfig | undefined, state: SkyState ): Promise { try { - const { loadWeather, ridgeSkyKey, terrainSkyFor } = await import('./skyForState'); - if (config?.style === 'terrain') return JSON.stringify(terrainSkyFor(state)); + const { loadWeather, ridgeSkyKey } = await import('./skyForState'); const view = (await manifestOf(config)).manifest?.view ?? FALLBACK_VIEW; await loadWeather(weatherUrl(), view.place); return ridgeSkyKey(state, view); @@ -147,12 +134,11 @@ async function skyKey( /** * The client's one door to the scene. When the tier resolves to 'off' nothing is imported and no * canvas context is requested; otherwise the scene code loads on demand, so it stays out of the - * main chunk. `config.style` picks the scene: the ridges unless it says 'raymarch' or 'terrain' (which falls back to its - * sky alone, `terrain/TerrainSky2D.ts`, where WebGL2 is missing). Null means + * main chunk. `config.style` picks the scene: the ridges unless it says 'raymarch' (any other value, an old 'terrain' included, is the ridges). Null means * "keep the CSS ground", including when that chunk fails to load (offline, stale deploy): the * failure goes to onCompileFail and nothing throws. * - * The ridge and terrain scenes bake their sky once, so they follow the sky (`skyState.ts`: the choice, resolved, so 'auto' follows the clock) by + * The ridge scene bakes its sky once, so it follows the sky (`skyState.ts`: the choice, resolved, so 'auto' follows the clock) by * being rebuilt on the same canvas when it changes: the door subscribes on start and the returned * scene's `dispose` unsubscribes. The pull-back restarts from the tree; a later `login()` is * replayed on the new scene. The ray-march scene has one fixed dusk and ignores the state. diff --git a/src/app/features/scene/ridge/frameLuma.ts b/src/app/features/scene/ridge/frameLuma.ts index e2bd1e0d..77ec241d 100644 --- a/src/app/features/scene/ridge/frameLuma.ts +++ b/src/app/features/scene/ridge/frameLuma.ts @@ -3,14 +3,14 @@ // Data for ridge-ad-legibility, which sizes the scrim from it and owns the 4.5:1 pass/fail; nothing here gates. import { baked } from '../../../../sky/baked'; import { luminance } from '../../../../sky/skyTokens.js'; -import type { FixedSkyState } from '../skyBand'; +import type { FixedSkyState } from '../skyState'; export interface FrameLuma { min: number; max: number; } -/** The theme text ink skyBand.ts's header derives: Noonday Sky's for day and dusk, Midnight Sky's for night. */ +/** The theme text ink skyState.ts's `FixedSkyState` bands derive: Noonday Sky's for day and dusk, Midnight Sky's for night. */ export const themeInk = (state: FixedSkyState): string => (state === 'night' ? baked.midnight : baked.noonday).tokens.Surface.OnContainer; diff --git a/src/app/features/scene/ridge/physicalSky.test.ts b/src/app/features/scene/ridge/physicalSky.test.ts index b0426924..8e756f6c 100644 --- a/src/app/features/scene/ridge/physicalSky.test.ts +++ b/src/app/features/scene/ridge/physicalSky.test.ts @@ -4,7 +4,7 @@ import { ELSEWHERE_VIEW } from './manifest.fixture'; import { sunForState } from './sunAt'; import { makePhysicalSky, paintSky } from './physicalSky'; import { skyBackdrop } from '../skyState'; -import type { FixedSkyState } from '../skyBand'; +import type { FixedSkyState } from '../skyState'; import { windowFor } from './view'; import type { PhysicalSky } from './physicalSky'; diff --git a/src/app/features/scene/ridge/physicalSky.ts b/src/app/features/scene/ridge/physicalSky.ts index 2136a9e5..5fb4a719 100644 --- a/src/app/features/scene/ridge/physicalSky.ts +++ b/src/app/features/scene/ridge/physicalSky.ts @@ -1,7 +1,7 @@ // The ridge scene's sky: the View's place's sun on the real clock, the atmosphere baked from it, a camera, and the display that makes it // pixels. `makePhysicalSky` does the one expensive thing (the LUT bake, tens of ms) and fits the display from a fixed 16:9 // grid, so resizing the window repaints the same sky. `paintSky` is per-texel lookups only. -import type { FixedSkyState } from '../skyBand'; +import type { FixedSkyState } from '../skyState'; import { bakeAtmosphere } from './earthAtmosphere'; import type { Atmosphere } from './earthAtmosphere'; import { domeSize, renderDome, SUN_RADIUS, sunOnScreen } from './skyDome'; diff --git a/src/app/features/scene/ridge/sunAt.ts b/src/app/features/scene/ridge/sunAt.ts index bc995be6..72a274f1 100644 --- a/src/app/features/scene/ridge/sunAt.ts +++ b/src/app/features/scene/ridge/sunAt.ts @@ -3,7 +3,7 @@ // fixed sky state. The ridge sky is the physical atmosphere (`earthAtmosphere.ts`) lit from this sun. import { sunPosition } from '../../../../sky/sun.js'; import { DAY_FROM } from '../skyState'; -import type { FixedSkyState } from '../skyBand'; +import type { FixedSkyState } from '../skyState'; import type { Place } from './view'; export interface SunSample { diff --git a/src/app/features/scene/ridge/toneMap.ts b/src/app/features/scene/ridge/toneMap.ts index 945c6a43..90f9fbc4 100644 --- a/src/app/features/scene/ridge/toneMap.ts +++ b/src/app/features/scene/ridge/toneMap.ts @@ -6,7 +6,7 @@ // Exposure is chosen per sky state (`exposureFor`): the sky is physical radiance, so brightness is the camera's, not a // shaping of the result. Day and dusk expose to the sky's own luminance (adaptation, as an eye or auto-exposure does) so the // darkest of the sky stays where the state's dark ink needs a backdrop; night is fixed, the physical dark. -import type { FixedSkyState } from '../skyBand'; +import type { FixedSkyState } from '../skyState'; type Rgb = readonly [number, number, number]; @@ -49,7 +49,7 @@ export function toneMap8(r: number, g: number, b: number, exposure: number, out: export const displayLuma = (c: ArrayLike): number => 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]; -/** What a sky state needs of its backdrop's display luminance, from the ink it wears (skyBand.ts, skyInk.ts). */ +/** What a sky state needs of its backdrop's display luminance, from the ink it wears (skyState.ts, skyInk.ts). */ export interface Budget { /** The darkest texel may not be darker than this (dark ink needs a light backdrop). 0: no floor. */ floor: number; diff --git a/src/app/features/scene/sceneStyle.ts b/src/app/features/scene/sceneStyle.ts deleted file mode 100644 index 7c31233e..00000000 --- a/src/app/features/scene/sceneStyle.ts +++ /dev/null @@ -1,28 +0,0 @@ -// Temporary: which background the viewer picked (terrain or ridges), kept in one localStorage key so the two scenes we -// serve can be compared on any device. Absent, the client config's backgroundScene.style decides. -import type { SceneStyle } from './tier'; - -export type ServedSceneStyle = Extract; -export const SERVED_SCENE_STYLES: readonly ServedSceneStyle[] = ['terrain', 'ridge']; -export const SCENE_STYLE_KEY = 'ratatoskr.sceneStyle'; - -export function getSceneStyleOverride(): ServedSceneStyle | undefined { - try { - const v = localStorage.getItem(SCENE_STYLE_KEY); - return SERVED_SCENE_STYLES.includes(v as ServedSceneStyle) - ? (v as ServedSceneStyle) - : undefined; - } catch { - return undefined; - } -} - -/** Store the pick and reload, so the scene host mounts the other scene from a clean page. */ -export function setSceneStyle(s: ServedSceneStyle): void { - try { - localStorage.setItem(SCENE_STYLE_KEY, s); - } catch { - return; - } - window.location.reload(); -} diff --git a/src/app/features/scene/skyBand.test.ts b/src/app/features/scene/skyBand.test.ts deleted file mode 100644 index e38f676a..00000000 --- a/src/app/features/scene/skyBand.test.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { displayedLuminance, hexToLinear, luma, shapeToBand, SKY_BAND } from './skyBand'; -import type { Linear } from './skyBand'; -import { GRID_FRAG, SHAPE_SKY_GLSL, SKY_FRAG } from './terrain/terrainShaders'; - -const near = (a: number, b: number) => Math.abs(a - b) < 1e-9; - -describe('shapeToBand', () => { - const dark: Linear = [0.02, 0.05, 0.2]; // a deep blue - const { day } = SKY_BAND; - - it('lifts a sky below the floor onto the floor, mixing toward the tint so the hue is kept', () => { - const c = shapeToBand(dark, day); - expect(near(luma(c), day.floor)).toBe(true); - // Between the sky and the tint on every channel: a mix, not a grey clamp. - [0, 1, 2].forEach((i) => { - expect(c[i]).toBeGreaterThanOrEqual(Math.min(dark[i], day.lift[i])); - expect(c[i]).toBeLessThanOrEqual(Math.max(dark[i], day.lift[i])); - }); - expect(c[2]).toBeGreaterThan(c[0]); // still blue - }); - - it('lifts black to the tint scaled in, not to grey', () => { - const c = shapeToBand([0, 0, 0], SKY_BAND.dusk); - expect(near(luma(c), SKY_BAND.dusk.floor)).toBe(true); - expect(c[2]).toBeGreaterThan(c[0]); // the dusk tint is Day's pale blue - }); - - it('leaves a sky already in the band as it is, and is continuous at the floor', () => { - const ok: Linear = [0.5, 0.6, 0.7]; - expect(shapeToBand(ok, day)).toEqual(ok); - const lo = shapeToBand([0.31, 0.31, 0.31], day); - const below = shapeToBand([0.3099, 0.3099, 0.3099], day); - expect(Math.abs(lo[0] - below[0])).toBeLessThan(1e-3); - }); - - it('scales a sky above the ceiling down to it, keeping its hue', () => { - const c = shapeToBand([0.9, 0.8, 1], SKY_BAND.night); - expect(near(luma(c), SKY_BAND.night.ceiling)).toBe(true); - expect(near(c[0] / c[2], 0.9)).toBe(true); - }); - - it('clamps to 0..1 as the screen does, and never leaves the band when shaped twice', () => { - expect(shapeToBand([4, 4, 4], day)).toEqual([1, 1, 1]); - const once = shapeToBand(dark, day); - shapeToBand(once, day).forEach((v, i) => expect(v).toBeCloseTo(once[i], 12)); - }); -}); - -describe('the bands', () => { - it('have a tint above the floor to lift toward', () => { - Object.values(SKY_BAND).forEach((b) => expect(luma(b.lift)).toBeGreaterThan(b.floor)); - }); - - 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, 'low'); - expect(shown).toBeGreaterThanOrEqual(0.2983); - expect(shown).toBeLessThan(SKY_BAND.day.floor); - }); - - it('decode hex as linear light', () => { - expect(hexToLinear('#ffffff')).toEqual([1, 1, 1]); - }); -}); - -describe('the GLSL twin', () => { - it('shapes with the same arithmetic: clamp, luma weights, mix to the floor, scale to the ceiling', () => { - expect(SHAPE_SKY_GLSL).toContain('c = clamp(c, 0.0, 1.0);'); - expect(SHAPE_SKY_GLSL).toContain('const vec3 LUMA = vec3(0.2126, 0.7152, 0.0722);'); - expect(SHAPE_SKY_GLSL).toContain( - 'if (l < uBand.x) return mix(c, uLift, (uBand.x - l) / (dot(uLift, LUMA) - l));' - ); - expect(SHAPE_SKY_GLSL).toContain('if (l > uBand.y) return c * (uBand.y / l);'); - }); - - it('is applied to the sky colour in both shaders that draw it, the sky pass and the haze that fades into it', () => { - [SKY_FRAG, GRID_FRAG].forEach((src) => { - expect(src).toContain(SHAPE_SKY_GLSL); - expect(src).toMatch(/return shapeSky\(1\.0 - exp\(-45\.0 \* skyScatter\(d\)\)/); - }); - }); -}); diff --git a/src/app/features/scene/skyBand.ts b/src/app/features/scene/skyBand.ts deleted file mode 100644 index a74784b3..00000000 --- a/src/app/features/scene/skyBand.ts +++ /dev/null @@ -1,90 +0,0 @@ -// The luminance band each fixed sky state's drawn sky is shaped into, so the state's theme ink -// clears 4.5:1 on bare sky (WCAG relative luminance, the `luminance` of src/sky/skyTokens.js). -// -// day Noonday Sky's dark text ink #342d25 (L 0.0274) needs a backdrop of at least 0.2983. -// The floor is that text bound (0.30 as drawn); there is no ceiling, dark ink on light is fine. -// dusk The same ink, and its link #2a4f27 (L 0.0623), which needs a backdrop of at least 0.4554. The floor is -// the link bound (0.4744 as drawn), so text clears 4.5:1 with room (6.6) and the link clears too. -// night Midnight Sky's light text ink #aeccff (L 0.594) needs a backdrop of at most 0.0931. -// The baked night sky (0.058 to 0.077) is kept; the ceiling is the bound. -// -// Night's link ink is not part of the band: see skyTheme.ts. -// -// The terrain sky is a physical scatter function, so it is shaped downstream, on its final colour: -// `shapeToBand` here, and its GLSL twin (`SHAPE_SKY_GLSL`) in terrain/terrainShaders.ts, built from the -// same constants. The ridge sky is a three-stop gradient whose stops are chosen inside the band -// (ridge/skyColour.ts, skyForState.ts), and its test sweeps the blends. -export type FixedSkyState = 'day' | 'dusk' | 'night'; -export type Linear = readonly [number, number, number]; - -/** WCAG luma weights, applied to linear RGB. */ -export const LUMA: Linear = [0.2126, 0.7152, 0.0722]; -export const luma = (c: Linear): number => LUMA[0] * c[0] + LUMA[1] * c[1] + LUMA[2] * c[2]; - -/** sRGB hex `#rrggbb` to linear RGB 0..1. */ -export function hexToLinear(hex: string): Linear { - const ch = (at: number) => { - const s = parseInt(hex.slice(at, at + 2), 16) / 255; - return s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4; - }; - return [ch(1), ch(3), ch(5)]; -} - -/** How a displayed colour is read: as encoded, or moved one 8-bit step down or up in every channel ('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. 'low' and 'high' move every - * encoded channel one 8-bit step down or up first: rounding to 8 bits (half a step) plus the sky pass's dither (half a - * step) cannot move a channel further, so they bound what the screen shows. A smooth bound, so a search can climb it. - */ -export function displayedLuminance(c: Linear, reading: Reading = 'exact'): number { - const shift = { exact: 0, low: -1 / 255, high: 1 / 255 }[reading]; - const ch = (v: number) => { - const e = Math.min(1, Math.max(0, Math.min(1, Math.max(0, v)) ** (1 / 2.2) + shift)); - 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])]); -} - -export interface SkyBand { - /** Linear luma the shaped colour is at least (0: no floor). */ - floor: number; - /** Linear luma the shaped colour is at most (1: no ceiling). */ - ceiling: number; - /** The colour a too-dark sky is mixed toward: the state's own tint, so the hue survives the lift. Its luma is above `floor`. */ - lift: Linear; -} - -/** - * The shaping targets, in linear luma. Day's floor sits 0.019 above the text bound (0.2983), Dusk's 0.019 above the link - * bound (0.4554), which skyForState.test.ts derives from the ink and ties to these: 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 (one step in every channel) takes about 0.007 more. The night ceiling is lower than the text bound - * (0.0931) by more than that: 0.077394 is the luma at which one step up reads 0.08164, the lightest the baked night sky shows - * (skyState.ts), so a sky the page URL steers at night, scaled down to the ceiling, cannot show lighter than the baked one. - */ -export const SKY_BAND: Record = { - day: { floor: 0.317, ceiling: 1, lift: hexToLinear('#e2f4ff') }, - // Dusk lifts toward Day's pale blue rather than a rose: mixing a third of the sky toward rose washed the twilight pink, and - // a rose lighter than the floor shifts hues by 47 to 72 degrees where Day's tint shifts them by 18 (measured, PR body). - dusk: { floor: 0.4744, ceiling: 1, lift: hexToLinear('#e2f4ff') }, - night: { floor: 0, ceiling: 0.077394, lift: hexToLinear('#5a6a9a') }, -}; - -/** - * Shape a linear sky colour into the band. Below the floor it mixes toward `lift` by exactly the amount - * that lands on the floor (continuous at the floor, hue kept); above the ceiling it scales down to the - * ceiling. The colour is clamped to 0..1 first, as the screen does. - */ -export function shapeToBand(c: Linear, band: SkyBand): Linear { - const k = [0, 1, 2].map((i) => Math.min(1, Math.max(0, c[i]))) as unknown as Linear; - const l = luma(k); - if (l < band.floor) { - const t = (band.floor - l) / (luma(band.lift) - l); - return [0, 1, 2].map((i) => k[i] + (band.lift[i] - k[i]) * t) as unknown as Linear; - } - if (l > band.ceiling) return [0, 1, 2].map((i) => (k[i] * band.ceiling) / l) as unknown as Linear; - return k; -} diff --git a/src/app/features/scene/skyForState.test.ts b/src/app/features/scene/skyForState.test.ts index a35f117f..f4512fc3 100644 --- a/src/app/features/scene/skyForState.test.ts +++ b/src/app/features/scene/skyForState.test.ts @@ -1,28 +1,14 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; import { FALLBACK_VIEW } from './ridge/view'; import { ELSEWHERE_VIEW } from './ridge/manifest.fixture'; import { atStandardTime } from './standardTime.testkit'; import { baked } from '../../../sky/baked'; import { AA, luminance } from '../../../sky/skyTokens.js'; -import { chooseSky, skyColour } from './terrain/terrainSky'; -import { - DUSK_SUN_ELEVATION, - TERRAIN_REACH_DEG, - ridgeDrawn, - ridgeSkyFor, - ridgeSkyKey, - loadWeather, - terrainDrawn, - terrainSkyFor, -} from './skyForState'; -import { displayedLuminance, luma, shapeToBand, SKY_BAND } from './skyBand'; -import type { FixedSkyState } from './skyBand'; +import { ridgeDrawn, ridgeSkyFor, ridgeSkyKey, loadWeather } from './skyForState'; import { DAY_FROM, setSkyClock, skyBackdrop } from './skyState'; -import { view } from './terrain/terrainWorld'; +import type { FixedSkyState } from './skyState'; import { skyThemeId } from './skyTheme'; -const hex = (c: readonly number[]) => `#${c.map((v) => v.toString(16).padStart(2, '0')).join('')}`; -const EPS = 1e-9; const STATES = ['day', 'dusk', 'night'] as const; const SKY = { 'midnight-sky': baked.midnight, 'noonday-sky': baked.noonday } as const; @@ -40,15 +26,6 @@ const needs = (state: FixedSkyState) => { : { floor: AA * ((state === 'dusk' ? link : l) + 0.05) - 0.05, ceiling: 1 }; }; -let search = ''; -beforeEach(() => { - search = ''; - vi.stubGlobal('window', { - get location() { - return { search }; - }, - }); -}); afterEach(() => { setSkyClock(); vi.unstubAllGlobals(); @@ -60,23 +37,6 @@ describe('the bands the text ink needs', () => { expect(needs('dusk').floor).toBeCloseTo(0.4554, 3); expect(needs('night').ceiling).toBeCloseTo(0.0931, 3); }); - - // The drawn floor and the lift are tied to those bounds, not to themselves: nudge either constant and this fails. - it('give Dusk a floor 0.019 above the link bound (as Day has above the text bound) and a lift Day shares', () => { - expect(SKY_BAND.dusk.floor).toBeCloseTo(needs('dusk').floor + 0.019, 4); - expect(SKY_BAND.day.floor).toBeCloseTo(needs('day').floor + 0.019, 3); - expect(SKY_BAND.dusk.lift).toEqual(SKY_BAND.day.lift); - expect(luma(SKY_BAND.dusk.lift)).toBeGreaterThan(SKY_BAND.dusk.floor); - }); - - it.each(['day', 'dusk'] as const)( - '%s: the darkest the shaping can show reads at the bound and under the floor', - (state) => { - const shown = displayedLuminance(shapeToBand([0, 0, 0], SKY_BAND[state]), 'low'); - expect(shown).toBeGreaterThanOrEqual(needs(state).floor); - expect(shown).toBeLessThan(SKY_BAND[state].floor); - } - ); }); describe('ridgeSkyFor', () => { @@ -142,244 +102,12 @@ 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, 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); - const tops = [0.4, 0.5, 1, 16 / 9, 2.4].flatMap((aspect) => - [0, 0.125, 0.25, 0.5, 0.75].flatMap((turns) => { - const v = view(aspect, turns); - return [-1, 0, 1].map((nx) => { - const d = [0, 1, 2].map( - (i) => v.forward[i] + nx * tanHalf * aspect * v.right[i] + tanHalf * v.up[i] - ); - return (Math.asin(d[1] / Math.hypot(d[0], d[1], d[2])) * 180) / Math.PI; - }); - }) - ); - const top = Math.max(...tops); - expect(top).toBeCloseTo(14.5, 1); - expect(TERRAIN_REACH_DEG).toBeGreaterThanOrEqual(top); - expect(TERRAIN_REACH_DEG - top).toBeLessThan(2); - }); -}); - -describe('terrainSkyFor', () => { - it('draws the sky auto resolves to, with that state band', () => { - setSkyClock(() => atStandardTime(12, 0)); - expect(terrainSkyFor('auto')).toEqual(terrainSkyFor('day')); - 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('keeps a URL-steered sky at night no lighter than the Night backdrop the text was checked against', () => { - setSkyClock(() => atStandardTime(0, 0)); - ['?sun=60', '?sun=10&az=40', '?sun=2&az=250', '?sky=noonday'].forEach((q) => { - search = q; - expect(terrainDrawn('auto').lightest).toBeLessThanOrEqual(skyBackdrop('night').lightest); - }); - }); - - 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 }); - expect(terrainSkyFor('dusk')).toEqual({ - sun: { elevation: DUSK_SUN_ELEVATION }, - band: SKY_BAND.dusk, - }); - }); -}); - -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'); - 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(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(l.low).toBeGreaterThanOrEqual(floor); - expect(l.high).toBeLessThanOrEqual(ceiling); - } - }); - - it('and the terrain dusk still reaches the sun glow the ridge dusk does not', () => { - expect(skyBackdrop('dusk').lightest).toBeGreaterThan(0.9); - }); -}); - -describe('skyBackdrop holds the union of what the scenes draw', () => { - // An independent extremum of the screen reading ('low' for the darkest, 'high' for the lightest: one 8-bit step each way) over the terrain camera's reach: not terrainDrawn's grid and compass search but alternating golden-section - // line searches in elevation and azimuth from 60 starts (a golden-angle spiral and scatter about the sun), the bracket - // shrinking to 1e-3 degrees. A plateau (the shader clamps) cannot stall it: each line search always - // moves to the better end of its bracket. - const extremes = (state: FixedSkyState) => { - const sky = chooseSky(terrainSkyFor(state)); - const rad = Math.PI / 180; - const f = (el: number, az: number, reading: 'low' | 'high') => { - 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)]), - reading - ); - }; - const P = 0.6180339887; - const line = (g: (x: number) => number, mid: number, w: number) => { - let a = mid - w; - let b = mid + w; - for (let k = 0; k < 40; k += 1) { - const c = b - P * (b - a); - const d = a + P * (b - a); - if (g(c) > g(d)) b = d; - else a = c; - } - return (a + b) / 2; - }; - const hunt = (sign: 1 | -1) => { - const reading = sign === 1 ? 'high' : 'low'; - let best = -Infinity; - for (let i = 0; i < 60; i += 1) { - let el = - i % 2 - ? sky.elevation + (((i * 7919) % 1600) - 800) / 100 - : Math.asin(((i + 0.5) / 60) * Math.sin(TERRAIN_REACH_DEG * rad)) / rad; - let az = - i % 2 ? sky.azimuth + (((i * 104729) % 1600) - 800) / 100 : (i * 137.50776405) % 360; - for (let w = 8; w > 1e-3; w /= 2) { - const [el0, az0] = [el, az]; - el = line((x) => sign * f(Math.max(0, x), az0, reading), el0, w); - const el1 = el; - az = line((x) => sign * f(el1, x, reading), az0, w); - best = Math.max(best, sign * f(el, az, reading)); - } - } - return sign * best; - }; - return { darkest: hunt(-1), lightest: hunt(1) }; - }; - - // At night a sky the page URL steers (?sun= ?sky=) is shaped to the band's ceiling, so the lightest it can show is one - // 8-bit step above the ceiling's own grey: the Night constant must cover it too, or text is checked against a sky - // lighter than the one it sits on. - const steeredNight = displayedLuminance( - [SKY_BAND.night.ceiling, SKY_BAND.night.ceiling, SKY_BAND.night.ceiling], - 'high' - ); - - const computed = (state: FixedSkyState) => { - const r = [ridgeDrawn(state), terrainDrawn(state)]; - const ind = extremes(state); - return { - darkest: Math.min(...r.map((x) => x.darkest), ind.darkest), - lightest: Math.max( - ...r.map((x) => x.lightest), - ind.lightest, - ...(state === 'night' ? [steeredNight] : []) - ), - }; - }; - - // The constants are the swept extremes rounded outward to six places, so each lies in [extreme, extreme + 1e-6): - // a constant 1e-6 low is under the extreme, one 2e-5 high is over the bound. SEARCH is the searches' own error. - const SEARCH = 1e-8; - it.each(STATES)( - '%s: the constant is the swept extreme rounded outward, within 1e-6 above it', - (state) => { - const c = computed(state); - const b = skyBackdrop(state); - expect(b.darkest).toBeLessThanOrEqual(c.darkest); - expect(b.lightest).toBeGreaterThanOrEqual(c.lightest); - expect(c.darkest - b.darkest).toBeLessThan(1e-6 + SEARCH); - expect(b.lightest - c.lightest).toBeLessThan(1e-6 + SEARCH); - } - ); - - it.each(STATES)('%s: an independent sweep, no looser than 5e-4 from the constant', (state) => { - // The sweep is not the generator's grid (see above), so it cannot share its blind spots. - const l = sweepOf(chooseSky(terrainSkyFor(state)), 20000); - const b = skyBackdrop(state); +describe('skyBackdrop holds the ridge sky', () => { + it.each(STATES)('%s: the backdrop bound contains the ridge display budget', (state) => { const r = ridgeDrawn(state); - 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); + const b = skyBackdrop(state); + expect(b.darkest).toBeLessThanOrEqual(r.darkest); + expect(b.lightest).toBeGreaterThanOrEqual(r.lightest); }); }); diff --git a/src/app/features/scene/skyForState.ts b/src/app/features/scene/skyForState.ts index 9d80297f..0d55d81a 100644 --- a/src/app/features/scene/skyForState.ts +++ b/src/app/features/scene/skyForState.ts @@ -1,12 +1,8 @@ -// What each scene is told for a sky state. 'auto' is a choice, not a sky: both functions draw the sky it -// resolves to (`resolveSkyState`, the clock), so every scene paints one of day, dusk or night. Each is drawn -// inside that state's luminance band (skyBand.ts): the ridge sky from gradients whose stops and blends lie in -// 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, urlSky } from './terrain/terrainSky'; -import type { SkyName } from './terrain/terrainSky'; -import type { SkyColours, Srgb } from './ridge/skyColour'; +// What the ridge scene is told for a sky state. 'auto' is a choice, not a sky: it draws the sky it +// resolves to (`resolveSkyState`, the clock), so the scene paints one of day, dusk or night, fitted to that +// state's luminance budget (ridge/toneMap.ts). `skyBackdrop` bounds what comes out, and the login text was +// checked against that bound. +import type { SkyColours } from './ridge/skyColour'; import { makePhysicalSky } from './ridge/physicalSky'; import type { Place, View } from './ridge/view'; import { BUDGET } from './ridge/toneMap'; @@ -14,13 +10,6 @@ import { ridgeWeather, setFedWeather } from './ridge/weather'; import { currentWeather, fetchWeatherFile } from './ridge/weatherFeed'; import { resolveSkyState, skyNow } from './skyState'; import type { SkyState } from './skyState'; -import { displayedLuminance, SKY_BAND } from './skyBand'; -import type { SkyBand } from './skyBand'; -import { luminance } from '../../../sky/skyTokens.js'; -import { CAMERA } from './terrain/terrainWorld'; - -/** Sun elevation in degrees for the terrain's dusk: just above the horizon, between the two bakes (as `?sun=` puts it). */ -export const DUSK_SUN_ELEVATION = 2; /** * What a rebuild of the ridge scene is for: the fixed state it draws and the weather. The sun moves with the clock inside a state and @@ -66,32 +55,6 @@ export function ridgeSkyFor( }; } -/** - * 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; 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 }; - case 'night': - return { sky: 'midnight', band }; - default: - return { sun: { elevation: DUSK_SUN_ELEVATION }, band }; - } -} - /** Relative luminance (WCAG) of the darkest and lightest colour a scene can draw. */ export interface Range { readonly darkest: number; @@ -107,81 +70,3 @@ export function ridgeDrawn(state: SkyState): Range { return { darkest: b.floor, lightest: b.ceiling }; } -/** - * How high the terrain camera can see, in degrees of elevation: it is frozen at a downward pitch and only turns - * (no pull-back), so the top edge of its view, at the centre column, is the pitch down subtracted from half the - * field of view (14.5 degrees; off-centre columns look lower). Plus a 1.5 degree margin. The terrain's range is - * over 0 to this, all azimuths, not the whole upper sphere; below the horizon the sky is the horizon's colour. - */ -export const TERRAIN_REACH_DEG = Math.ceil((CAMERA.fov / 2 - CAMERA.pitch) * (180 / Math.PI) + 1.5); - -const SAMPLE_DEG = 3; -const SUN_DEG = 0.1; -const SUN_SPAN_DEG = 8; -const HORIZON_DEG = 0.5; -const REFINE_FROM = 6; - -/** - * The terrain sky's range as the 8-bit screen shows it (`displayedLuminance`, read 'low' for the darkest and 'high' for the - * lightest: one 8-bit step each way, rounding and dither at their worst): `skyColour` (the CPU twin of its sky shader) over the part of the sky the camera reaches - * (0 to TERRAIN_REACH_DEG, every azimuth: it turns), for the sky the scene picks for this state. A 3 degree grid, a 0.5 degree - * ring of the horizon, the top of the reach and a 0.25 degree patch around the sun find where the extremes are; each of the - * best few is then refined by a compass search whose step halves from 1 degree to under 5e-7, because the sun's glow peaks - * (and the sky's darkest patch sits) between any fixed grid's samples. - */ -export function terrainDrawn(state: SkyState): Range { - const sky = chooseSky(terrainSkyFor(state)); - const rad = Math.PI / 180; - type Point = { el: number; az: number; read: number; score: number }; - const extreme = (reading: 'low' | 'high', sign: 1 | -1): number => { - const point = (el: number, az: number): Point => { - const e = Math.min(TERRAIN_REACH_DEG, Math.max(0, el)) * rad; - const a = az * rad; - const c = skyColour(sky, [ - Math.cos(e) * Math.sin(a), - Math.sin(e), - -Math.cos(e) * Math.cos(a), - ]); - const read = displayedLuminance(c, reading); - return { el, az, read, score: read }; - }; - const seen: Point[] = []; - const at = (el: number, az: number) => seen.push(point(el, az)); - for (let el = 0; el <= TERRAIN_REACH_DEG; el += SAMPLE_DEG) { - for (let az = 0; az < 360; az += SAMPLE_DEG) at(el, az); - } - for (let az = 0; az < 360; az += HORIZON_DEG) at(0, az); - at(TERRAIN_REACH_DEG, 0); - for (let dEl = -SUN_SPAN_DEG; dEl <= SUN_SPAN_DEG; dEl += SUN_DEG) { - for (let dAz = -SUN_SPAN_DEG; dAz <= SUN_SPAN_DEG; dAz += SUN_DEG) { - at(sky.elevation + dEl, sky.azimuth + dAz); - } - } - const around = (p: Point, step: number): Point[] => - [ - [step, 0], - [-step, 0], - [0, step], - [0, -step], - ].map(([dEl, dAz]) => - point(Math.min(TERRAIN_REACH_DEG, Math.max(0, p.el + dEl)), p.az + dAz) - ); - const refine = (from: Point) => { - let best = from; - for (let step = 1; step > 5e-7; step /= 2) { - let improved = true; - while (improved) { - const cur = best; - best = around(cur, step).reduce((b, c) => (sign * c.score > sign * b.score ? c : b), cur); - improved = best !== cur; - } - } - return best.read; - }; - const ranked = [...seen].sort((p, q) => sign * (q.score - p.score)); - return sign === 1 - ? Math.max(ranked[0].read, ...ranked.slice(0, REFINE_FROM).map(refine)) - : Math.min(ranked[0].read, ...ranked.slice(0, REFINE_FROM).map(refine)); - }; - return { darkest: extreme('low', -1), lightest: extreme('high', 1) }; -} diff --git a/src/app/features/scene/skyInk.test.ts b/src/app/features/scene/skyInk.test.ts index c92892f6..2007b7c3 100644 --- a/src/app/features/scene/skyInk.test.ts +++ b/src/app/features/scene/skyInk.test.ts @@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest'; import { baked } from '../../../sky/baked'; import { AA, NIGHT_SKY_LIGHTEST, luminance } from '../../../sky/skyTokens.js'; import { indexColorMXID } from '../../../util/colorMXID'; -import type { FixedSkyState } from './skyBand'; +import type { FixedSkyState } from './skyState'; import { LIGHTEST_PATCH, NIGHT_INK_MAX_L, diff --git a/src/app/features/scene/skyInk.ts b/src/app/features/scene/skyInk.ts index b8e38f31..1d0e1448 100644 --- a/src/app/features/scene/skyInk.ts +++ b/src/app/features/scene/skyInk.ts @@ -15,7 +15,7 @@ import chroma from 'chroma-js'; import { AA, luminance } from '../../../sky/skyTokens.js'; import { baked } from '../../../sky/baked'; import { indexColorMXID } from '../../../util/colorMXID'; -import type { FixedSkyState } from './skyBand'; +import type { FixedSkyState } from './skyState'; import type { SkyThemeId } from './skyTheme'; export interface SkyInk { diff --git a/src/app/features/scene/skyPlate.ts b/src/app/features/scene/skyPlate.ts index b82a3026..f7bb02c9 100644 --- a/src/app/features/scene/skyPlate.ts +++ b/src/app/features/scene/skyPlate.ts @@ -13,7 +13,7 @@ export const SKY_PLATE_FALLBACK = { * footer line. The footer is a blurred, tinted band with soft edges, not a plate: the scene shows through it. The * footer ink is the plate's, so the tint has to bring the scene behind it to where that ink clears 4.5:1. The browser * mixes in sRGB, so the test does too (skyTheme.test.ts): over pure black 0.80 gives 4.36 and 0.82 gives 4.55. The - * terrain is not black: in the shots at 390x844 (terrain scene, tier low) the darkest pixel in the footer's region is + * background is not black: in the shots at 390x844 (taken on the earlier terrain scene, tier low; not re-measured on the ridges) the darkest pixel in the footer's region is * 0.0203 at Dusk, 0.0936 at Day (dark ink) and 0.0052 at Night (light ink). Measured on the drawn pixels with the band * on, the worst link contrast is 5.0 at Dusk, 5.7 at Day and 11.2 at Night. */ diff --git a/src/app/features/scene/skyState.ts b/src/app/features/scene/skyState.ts index 52b0cdc8..5d963565 100644 --- a/src/app/features/scene/skyState.ts +++ b/src/app/features/scene/skyState.ts @@ -4,7 +4,6 @@ // text colours can be checked against it. 'auto' is a choice, not a sky: it resolves from the // clock to day, dusk or night (`resolveSkyState`), and every sky drawn is one of those three. import { sunElevation } from '../../../sky/sun.js'; -import type { FixedSkyState } from './skyBand'; export type SkyState = 'auto' | 'day' | 'dusk' | 'night'; @@ -22,7 +21,13 @@ function load(): SkyState { } } -export type { FixedSkyState }; +/** + * The three skies ever drawn. Each has the luminance band its theme ink needs against bare sky (WCAG relative luminance, + * the `luminance` of src/sky/skyTokens.js): day, at least 0.2983 (the dark text ink #342d25); dusk, at least 0.4554 (the link + * #2a4f27); night, at most 0.0931 (the light text ink #aeccff). The ridge scene's display budgets (ridge/toneMap.ts `BUDGET`) + * sit inside them. + */ +export type FixedSkyState = 'day' | 'dusk' | 'night'; /** Where the clock puts the sun: the latitude the skies are baked for (src/sky/skyTokens.js MOMENTS), the longitude of this timezone. */ const LAT = 45; @@ -125,13 +130,9 @@ export interface SkyBackdrop { readonly lightest: number; } -// The union of every sky a scene draws for the state: the ridge sky and the terrain sky, each from -// the function its scene uses (`ridgeDrawn`, `terrainDrawn` in skyForState.ts). The ridge sky is the physical sky over Vienna, its -// display fitted to the state's budget (ridge/toneMap.ts `BUDGET`): the budget is its extreme, whatever the sun's elevation. Held as constants so -// 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). -// Night's lightest also covers a sky the page URL steers (shaped to the band ceiling, skyBand.ts). +// What the ridge sky can show behind the page in each state (its display budget, ridge/toneMap.ts `BUDGET`, holds whatever the +// sun's elevation; physicalSky.test.ts sweeps the sun's year against these). Held as constants so this module, which the main chunk +// loads, does not pull in the sky generator. The bounds are at least as wide as the budgets: the login text was checked against them. // Bounds what the 8-bit screen shows too (one step each way for rounding and dither), rounded outward to six places. const BACKDROPS: Record = { day: { darkest: 0.461063, lightest: 1 }, diff --git a/src/app/features/scene/skyTheme.test.ts b/src/app/features/scene/skyTheme.test.ts index aab972fb..2bf19044 100644 --- a/src/app/features/scene/skyTheme.test.ts +++ b/src/app/features/scene/skyTheme.test.ts @@ -15,8 +15,7 @@ import { skyBackdrop, subscribe as subscribeSky, } from './skyState'; -import type { SkyBackdrop } from './skyState'; -import type { FixedSkyState } from './skyBand'; +import type { FixedSkyState, SkyBackdrop } from './skyState'; import { sceneThemeId, skyThemeId } from './skyTheme'; const SKY = { 'midnight-sky': baked.midnight, 'noonday-sky': baked.noonday } as const; @@ -218,7 +217,7 @@ describe('regions that sit on the plate', () => { describe('the sign-in footer band', () => { // The footer line is the plate's ink on a band that mixes FOOTER_TINT of the plate's fill over the blurred scene, // as the browser does: per channel, in encoded sRGB (not in linear light, which flatters dark scenes). The scene - // behind it is the terrain, taken as grey: as dark as 0, as light as the sky state's lightest backdrop. Ink + // behind it is the scene, taken as grey: as dark as 0, as light as the sky state's lightest backdrop. Ink // contrast is lowest at one of those two ends, so both are checked. const encode = (l: number) => (l <= 0.0031308 ? 12.92 * l : 1.055 * l ** (1 / 2.4) - 0.055); const channels = (hex: string) => [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255); diff --git a/src/app/features/scene/skyTheme.ts b/src/app/features/scene/skyTheme.ts index e1934d81..ee1cba40 100644 --- a/src/app/features/scene/skyTheme.ts +++ b/src/app/features/scene/skyTheme.ts @@ -3,7 +3,7 @@ // 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 +// drawn sky is held to a luminance budget (ridge/toneMap.ts, bands in skyState.ts `FixedSkyState`) in which that ink's TEXT clears 4.5:1 on // bare sky: Day at least 0.2983 (dark ink), Night at most 0.0931 (light ink). Dusk's floor is higher, the bound of // the dark link (0.4554), so its link clears as well. skyTheme.test.ts pins the measured text and link ratios. Night's // link ink is not in the band, and the themes' link colours are derived outside this code (src/sky/skyTokens.js). diff --git a/src/app/features/scene/terrain/Terrain.test.ts b/src/app/features/scene/terrain/Terrain.test.ts deleted file mode 100644 index ef1623c4..00000000 --- a/src/app/features/scene/terrain/Terrain.test.ts +++ /dev/null @@ -1,385 +0,0 @@ -/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion, @typescript-eslint/no-empty-function -- fake GL and DOM stubs, as the other scene tests */ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { createTerrainScene } from './Terrain'; -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. */ -function fakeGl(over: Record = {}) { - const calls: Record = {}; - const gl: any = new Proxy( - {}, - { - get(_t, name: string) { - if (name in over) return over[name]; - if (name === 'getShaderParameter' || name === 'getProgramParameter') return () => true; - if (name === 'getAttribLocation' || name === 'getUniformLocation') return () => 1; - if (name === 'checkFramebufferStatus') return () => 1; - if (name === 'getParameter') return () => 16; - if (/^[A-Z_0-9]+$/.test(name)) return 1; - return (...args: unknown[]) => { - (calls[name] ??= []).push(args); - return {}; - }; - }, - } - ); - return { gl, calls }; -} - -let rafQueue: Array<(t: number) => void>; -let visibility: string; -let search: string; -beforeEach(() => { - rafQueue = []; - visibility = 'visible'; - search = ''; - vi.stubGlobal('document', { - addEventListener: vi.fn(), - removeEventListener: vi.fn(), - get visibilityState() { - return visibility; - }, - createElement: () => ({ style: {}, remove() {} }), - }); - vi.stubGlobal('window', { - devicePixelRatio: 1, - innerWidth: 400, - innerHeight: 800, - matchMedia: () => ({ matches: false, addEventListener() {}, removeEventListener() {} }), - addEventListener: vi.fn(), - removeEventListener: vi.fn(), - get location() { - return { search }; - }, - setTimeout, - }); - vi.stubGlobal('performance', { now: () => 0 }); - vi.stubGlobal('requestAnimationFrame', (cb: (t: number) => void) => rafQueue.push(cb)); - vi.stubGlobal('cancelAnimationFrame', () => { - rafQueue = []; - }); -}); -afterEach(() => { - vi.unstubAllGlobals(); -}); - -function canvasWith(gl: unknown) { - return { - width: 0, - height: 0, - clientWidth: 400, - clientHeight: 800, - parentElement: { appendChild: vi.fn() }, - getContext: vi.fn(() => gl), - addEventListener: vi.fn(), - removeEventListener: vi.fn(), - } as any; -} - -describe('createTerrainScene', () => { - it("returns null at tier 'off' and touches nothing", () => { - const canvas = canvasWith(null); - expect(createTerrainScene({ canvas, tier: 'off' })).toBeNull(); - expect(canvas.getContext).not.toHaveBeenCalled(); - }); - - it('returns null without WebGL2, so the host keeps its CSS ground', () => { - const canvas = canvasWith(null); - expect(createTerrainScene({ canvas, tier: 'full' })).toBeNull(); - expect(canvas.getContext).toHaveBeenCalledWith('webgl2', expect.anything()); - }); - - it('returns null with no vertex texture units, or an incomplete bake target', () => { - expect( - createTerrainScene({ canvas: canvasWith(fakeGl({ getParameter: () => 0 }).gl), tier: 'full' }) - ).toBeNull(); - const { gl, calls } = fakeGl({ checkFramebufferStatus: () => 0 }); - expect(createTerrainScene({ canvas: canvasWith(gl), tier: 'full' })).toBeNull(); - expect(calls.deleteProgram).toHaveLength(3); - }); - - it('reports a shader that does not compile to onCompileFail and returns null', () => { - const { gl } = fakeGl({ getShaderParameter: () => false, getShaderInfoLog: () => 'bad' }); - const onCompileFail = vi.fn(); - expect(createTerrainScene({ canvas: canvasWith(gl), tier: 'full', onCompileFail })).toBeNull(); - expect(onCompileFail).toHaveBeenCalledOnce(); - expect(onCompileFail.mock.calls[0][0].log).toContain('terrain height'); - }); - - it('bakes the height map once, then draws sky and grid each frame and keeps turning', () => { - const { gl, calls } = fakeGl(); - const scene = createTerrainScene({ canvas: canvasWith(gl), tier: 'low' })!; - expect(scene).not.toBeNull(); - const bakes = calls.drawArrays.length; - expect(bakes).toBe(1); - rafQueue.shift()!(16); - rafQueue.shift()!(32); - expect(calls.drawArrays).toHaveLength(bakes + 2); // one sky draw per frame - expect(calls.drawElements).toHaveLength(2); - expect(calls.drawElements[0][1]).toBe(triangleCount(GRID.low.grid) * 3); - expect(calls.texImage2D).toHaveLength(1); // the baked map is never re-uploaded - expect(rafQueue).toHaveLength(1); - scene.dispose(); - }); - - it("'still' draws one frame and queues nothing", () => { - const { gl, calls } = fakeGl(); - const scene = createTerrainScene({ canvas: canvasWith(gl), tier: 'still' })!; - expect(calls.drawElements).toHaveLength(1); - expect(rafQueue).toHaveLength(0); - scene.dispose(); - }); - - it('lights with the sky chosen: option, then ?sky=, then the night default', () => { - const uploaded = (opts: { sky?: 'midnight' | 'noonday' }) => { - const { gl, calls } = fakeGl(); - createTerrainScene({ canvas: canvasWith(gl), tier: 'still', ...opts })!.dispose(); - // every vec3 uniform draw() sets: right, up, forward, sun, sunColour, glow, ambient, camera, soil... - return calls.uniform3fv - .filter((a) => (a[1] as ArrayLike).length === 3) - .map((a) => Array.from(a[1] as ArrayLike)); - }; - const night = uploaded({}); - const day = uploaded({ sky: 'noonday' }); - const nightA = Array.from(groundLight(SKY.midnight).ambient); - const dayA = Array.from(groundLight(SKY.noonday).ambient); - const has = (all: number[][], v: number[]) => - all.some((a) => a.every((x, i) => Math.abs(x - v[i]) < 1e-6)); - expect(has(night, nightA)).toBe(true); - expect(has(night, dayA)).toBe(false); - expect(has(day, dayA)).toBe(true); - search = '?sky=noonday'; - expect(has(uploaded({}), dayA)).toBe(true); - search = '?sky=garbage'; - 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).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) => { - const { gl, calls } = fakeGl(); - createTerrainScene({ canvas: canvasWith(gl), tier: 'still', ...opts })!.dispose(); - return calls.uniform3fv.map((a) => Array.from(a[1] as ArrayLike)); - }; - const dusk = skyAtSun(-1, 300); - const has = (all: number[][], v: readonly number[]) => - all.some((a) => a.length === 3 && a.every((x, i) => Math.abs(x - v[i]) < 1e-6)); - expect(has(ambients({ sun: { elevation: -1, azimuth: 300 } }), groundLight(dusk).ambient)).toBe( - true - ); - search = '?sky=noonday&sun=-1&az=300'; - expect(has(ambients({}), groundLight(dusk).ambient)).toBe(true); - search = '?sun=garbage'; - expect(has(ambients({}), groundLight(SKY.midnight).ambient)).toBe(true); - }); - - it('uploads the baked sky table and the aerial perspective volume once each, as half floats, to 3D textures', () => { - const { gl, calls } = fakeGl(); - createTerrainScene({ canvas: canvasWith(gl), tier: 'full' })!.dispose(); - expect(calls.texImage3D).toHaveLength(2); - const a = calls.texImage3D[0]; - expect([a[3], a[4], a[5]]).toEqual([SKY_VIEW.width, SKY_VIEW.height, SKY_VIEW.depth]); - expect(a[9]).toEqual(skyViewWords()); - const ap = calls.texImage3D[1]; - expect([ap[3], ap[4], ap[5]]).toEqual([AP_VOLUME.width, AP_VOLUME.height, AP_VOLUME.depth]); - expect(ap[9]).toEqual(apVolumeWords()); - expect(calls.deleteTexture).toHaveLength(3); - }); - - it('dithers the sky output by half an 8-bit step either way, and the terrain not at all', () => { - expect(SKY_FRAG).toContain('- 0.5'); - expect(SKY_FRAG).toContain('dither / 255.0'); - }); - - it('falls back to a still frame when the measured p95 is over 33 ms', () => { - const { gl, calls } = fakeGl(); - const onProbe = vi.fn(); - const scene = createTerrainScene({ canvas: canvasWith(gl), tier: 'full', onProbe })!; - let t = 0; - for (let i = 0; i < 400 && rafQueue.length; i += 1) rafQueue.shift()!((t += 50)); - expect(rafQueue).toHaveLength(0); - expect(onProbe).toHaveBeenLastCalledWith(expect.objectContaining({ still: true })); - expect(calls.drawElements.length).toBeLessThan(400); - scene.dispose(); - }); - - it('does not draw while the tab is hidden, or under reduced motion', () => { - const { gl, calls } = fakeGl(); - const scene = createTerrainScene({ canvas: canvasWith(gl), tier: 'full' })!; - const before = (calls.drawElements ?? []).length; - visibility = 'hidden'; - rafQueue.shift()!(16); - expect((calls.drawElements ?? []).length).toBe(before); - scene.dispose(); - vi.stubGlobal('window', { - ...(window as object), - matchMedia: () => ({ matches: true, addEventListener() {}, removeEventListener() {} }), - }); - visibility = 'visible'; - const g2 = fakeGl(); - const still = createTerrainScene({ canvas: canvasWith(g2.gl), tier: 'full' })!; - expect(rafQueue).toHaveLength(0); - expect(g2.calls.drawElements).toHaveLength(1); // one frame, then still - still.dispose(); - }); - - it('a lost context stops the scene and tells the host', () => { - const { gl, calls } = fakeGl(); - const canvas = canvasWith(gl); - const onContextLost = vi.fn(); - createTerrainScene({ canvas, tier: 'full', onContextLost })!; - const handler = canvas.addEventListener.mock.calls.find( - (c: unknown[]) => c[0] === 'webglcontextlost' - )[1]; - handler({ preventDefault() {} }); - expect(onContextLost).toHaveBeenCalledOnce(); - const n = (calls.drawElements ?? []).length; - rafQueue.splice(0).forEach((f) => f(16)); - expect((calls.drawElements ?? []).length).toBe(n); - }); - - it('dispose frees its programs, buffers and texture and queues nothing more', () => { - const { gl, calls } = fakeGl(); - createTerrainScene({ canvas: canvasWith(gl), tier: 'full' })!.dispose(); - expect(calls.deleteProgram).toHaveLength(3); - expect(calls.deleteBuffer).toHaveLength(2); - expect(calls.deleteTexture).toHaveLength(3); - expect(rafQueue).toHaveLength(0); - }); -}); - -describe("startBackgroundScene style 'terrain'", () => { - it('requests webgl2 and returns a scene once the tier is on', async () => { - const { gl } = fakeGl(); - const canvas = canvasWith(gl); - const scene = await startBackgroundScene({ tier: 'still', style: 'terrain' }, {}, { canvas }); - expect(scene).not.toBeNull(); - expect(canvas.getContext).toHaveBeenCalledWith('webgl2', expect.anything()); - scene!.dispose(); - }); - - it('stays off by default, and the default style is still the ridge (no WebGL2)', async () => { - const canvas = canvasWith(null); - expect(await startBackgroundScene({ style: 'terrain' }, {}, { canvas })).toBeNull(); - expect(canvas.getContext).not.toHaveBeenCalled(); - const { gl } = fakeGl(); - const c2 = { ...canvasWith(gl), getContext: vi.fn(() => null) }; - await startBackgroundScene({ tier: 'still' }, {}, { canvas: c2 }); - expect(c2.getContext).not.toHaveBeenCalledWith('webgl2', expect.anything()); - }); -}); - -describe('stars in the terrain scene', () => { - let overlays: any[]; - let arcs: number; - const withOverlays = () => { - overlays = []; - arcs = 0; - (document as any).createElement = () => { - const el: any = { - style: {}, - remove: vi.fn(), - setAttribute() {}, - getContext: () => ({ - clearRect() {}, - beginPath() {}, - fill() {}, - arc: () => (arcs += 1), - }), - }; - overlays.push(el); - return el; - }; - }; - const scene = (sky: 'midnight' | 'noonday', tier: 'still' | 'low' = 'low') => { - withOverlays(); - const canvas = canvasWith(fakeGl().gl); - const s = createTerrainScene({ canvas, tier, sky })!; - return { s, canvas }; - }; - - it('a midnight sky gets one star overlay beside the canvas, painted with the terrain', () => { - const { s, canvas } = scene('midnight'); - expect(overlays).toHaveLength(1); - expect(canvas.parentElement.appendChild).toHaveBeenCalledWith(overlays[0]); - rafQueue.shift()!(16); - expect(arcs).toBeGreaterThan(0); - s.dispose(); - expect(overlays[0].remove).toHaveBeenCalledOnce(); - }); - - it('a noonday sky gets no overlay and paints no stars', () => { - const { s } = scene('noonday'); - expect(overlays).toHaveLength(0); - expect(arcs).toBe(0); - s.dispose(); - }); - - it("'still' paints the stars once at base and queues nothing", () => { - const { s } = scene('midnight', 'still'); - expect(arcs).toBeGreaterThan(0); - expect(rafQueue).toHaveLength(0); - s.dispose(); - }); - - it('a hidden tab or reduced motion paints no more stars than the first frame', () => { - visibility = 'hidden'; - const { s } = scene('midnight'); - const n = arcs; - expect(n).toBeGreaterThan(0); - expect(rafQueue).toHaveLength(0); // the terrain loop never starts, so nothing repaints the stars - s.dispose(); - visibility = 'visible'; - (window as any).matchMedia = () => ({ - matches: true, - addEventListener() {}, - removeEventListener() {}, - }); - const r = scene('midnight'); - expect(rafQueue).toHaveLength(0); - expect(arcs).toBe(n); - r.s.dispose(); - }); - - it('stars turn with the terrain: a later frame is painted at a later heading', () => { - let clock = 0; - vi.stubGlobal('performance', { now: () => (clock += 1000) }); - const { s } = scene('midnight'); - rafQueue.shift()!(16); - const first = arcs; - rafQueue.shift()!(1000); - expect(arcs).toBeGreaterThan(first); - s.dispose(); - }); -}); diff --git a/src/app/features/scene/terrain/Terrain.ts b/src/app/features/scene/terrain/Terrain.ts deleted file mode 100644 index a1807305..00000000 --- a/src/app/features/scene/terrain/Terrain.ts +++ /dev/null @@ -1,443 +0,0 @@ -import type { Scene, SceneOptions } from '../Scene'; -import type { SkyBand } from '../skyBand'; -import { FrameSampler, FrameStats } from '../ridge/probe'; -import { albedoPalette } from './terrainAlbedo'; -import { sunIndex } from '../../../../sky/scatter.js'; -import { AP_VOLUME, apVolumeWords, SKY_VIEW, skyViewWords } from './terrainScatter'; -import { - nightness, - glowColour, - groundLight, - chooseSky, - SkyName, - START_TURNS, - sunDirection, -} from './terrainSky'; -import { buildGrid, CAMERA, GRID, seedOffset, TERRAIN, triangleCount, view } from './terrainWorld'; -import { - FULLSCREEN_VERT, - GRID_FRAG, - GRID_VERT, - heightFragmentSource, - SKY_FRAG, -} from './terrainShaders'; -import { createTerrainStars } from './terrainStars'; -import { overlayRequested } from '../debugOverlays'; -import { showTierLabel } from './tierLabel'; - -export type TerrainOptions = Pick< - SceneOptions, - 'canvas' | 'tier' | 'onCompileFail' | 'onContextLost' -> & { - /** 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 }; - /** The luminance band the sky is shaped into (skyBand.ts), in the sky pass and in the haze that fades into it. Default: none. */ - band?: SkyBand; - /** Terrain seed: the height map is sampled at an offset taken from it. Default 0. */ - seed?: number; - /** Show the rAF median/p95 readout (plus triangle count). Default: the page URL has `?probe=1`, where `debug` allows it. */ - probe?: boolean; - /** The diagnostic overlays (readout, tier label) may be asked for by URL (debugOverlays.ts). Default: no. */ - debug?: boolean; - onProbe?: (s: FrameStats & { still: boolean; triangles: number }) => void; -}; - -/** Same shape as Scene.ts's ShaderCompileError, redeclared so this chunk does not import the ray-march scene. */ -class ShaderCompileError extends Error { - constructor(readonly stage: 'vertex', readonly log: string) { - super(`${stage} shader failed to compile:\n${log}`); - } -} - -function program(gl: WebGL2RenderingContext, name: string, vs: string, fs: string): WebGLProgram { - const make = (type: number, src: string, which: string) => { - const s = gl.createShader(type); - if (!s) throw new Error('createShader failed'); - gl.shaderSource(s, src); - gl.compileShader(s); - if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) { - const log = gl.getShaderInfoLog(s) ?? ''; - gl.deleteShader(s); - throw new ShaderCompileError('vertex', `terrain ${name} ${which} shader: ${log}`); - } - return s; - }; - const v = make(gl.VERTEX_SHADER, vs, 'vertex'); - const f = make(gl.FRAGMENT_SHADER, fs, 'fragment'); - const p = gl.createProgram(); - if (!p) throw new Error('createProgram failed'); - gl.attachShader(p, v); - gl.attachShader(p, f); - gl.linkProgram(p); - gl.deleteShader(v); - gl.deleteShader(f); - if (!gl.getProgramParameter(p, gl.LINK_STATUS)) { - const log = gl.getProgramInfoLog(p) ?? ''; - gl.deleteProgram(p); - throw new ShaderCompileError('vertex', `terrain ${name} link: ${log}`); - } - return p; -} - -/** - * The terrain scene: same contract as `createRidgeScene`/`createScene` ({ login, dispose }, null for "keep the - * CSS ground"). WebGL2 only. The height map is baked once on the GPU (Phacelle, see terrainShaders.ts) into an - * RGBA8 texture; each frame is two draws: the sky from the baked scattering table, then a displaced grid lit by the - * baked sun and ambient and hazed toward that sky at the horizon. Cadence guard, pauses and the `?probe=1` readout match the - * ridge scene. - */ -export function createTerrainScene(opts: TerrainOptions): Scene | null { - const tier = opts.tier ?? 'full'; - if (tier === 'off') return null; - const { canvas } = opts; - const probe = opts.probe ?? overlayRequested('probe', opts.debug === true); - const gl = canvas.getContext('webgl2', { - antialias: false, - alpha: false, - }) as WebGL2RenderingContext | null; - if (!gl) return null; - const units = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS); - if (typeof units === 'number' && units < 1) return null; - - const sky = chooseSky(opts); - const spec = GRID[tier]; - - let skyProg: WebGLProgram; - let gridProg: WebGLProgram; - let bakeProg: WebGLProgram; - try { - bakeProg = program(gl, 'height', FULLSCREEN_VERT, heightFragmentSource()); - skyProg = program(gl, 'sky', FULLSCREEN_VERT, SKY_FRAG); - gridProg = program(gl, 'grid', GRID_VERT, GRID_FRAG); - } catch (e) { - opts.onCompileFail?.(e as ShaderCompileError); - return null; - } - - // The height map, baked once. - const heightTex = gl.createTexture(); - const fbo = gl.createFramebuffer(); - gl.bindTexture(gl.TEXTURE_2D, heightTex); - gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, spec.tex, spec.tex, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); - // The baked scattering table, RGB16F, uploaded as it is stored (half floats); the shader divides by the store scale. - const skyTex = gl.createTexture(); - gl.bindTexture(gl.TEXTURE_3D, skyTex); - gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1); - gl.texImage3D( - gl.TEXTURE_3D, - 0, - gl.RGB16F, - SKY_VIEW.width, - SKY_VIEW.height, - SKY_VIEW.depth, - 0, - gl.RGB, - gl.HALF_FLOAT, - skyViewWords() - ); - gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); - [gl.TEXTURE_WRAP_S, gl.TEXTURE_WRAP_T, gl.TEXTURE_WRAP_R].forEach((w) => - gl.texParameteri(gl.TEXTURE_3D, w, gl.CLAMP_TO_EDGE) - ); - // The aerial perspective volume, RGBA16F, half floats as stored (src/sky/scatter.js). - const apTex = gl.createTexture(); - gl.bindTexture(gl.TEXTURE_3D, apTex); - gl.texImage3D( - gl.TEXTURE_3D, - 0, - gl.RGBA16F, - AP_VOLUME.width, - AP_VOLUME.height, - AP_VOLUME.depth, - 0, - gl.RGBA, - gl.HALF_FLOAT, - apVolumeWords() - ); - gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); - [gl.TEXTURE_WRAP_S, gl.TEXTURE_WRAP_T, gl.TEXTURE_WRAP_R].forEach((w) => - gl.texParameteri(gl.TEXTURE_3D, w, gl.CLAMP_TO_EDGE) - ); - gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4); - gl.bindTexture(gl.TEXTURE_2D, heightTex); - gl.bindFramebuffer(gl.FRAMEBUFFER, fbo); - gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, heightTex, 0); - const complete = gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE; - const free: Array<() => void> = []; - const release = () => { - free.forEach((f) => f()); - gl.deleteTexture(heightTex); - gl.deleteTexture(skyTex); - gl.deleteTexture(apTex); - gl.deleteFramebuffer(fbo); - gl.deleteProgram(bakeProg); - gl.deleteProgram(skyProg); - gl.deleteProgram(gridProg); - }; - if (!complete) { - release(); - return null; - } - gl.viewport(0, 0, spec.tex, spec.tex); - gl.disable(gl.DEPTH_TEST); - gl.useProgram(bakeProg); - gl.uniform1f(gl.getUniformLocation(bakeProg, 'uSpan'), TERRAIN.span); - gl.uniform1f(gl.getUniformLocation(bakeProg, 'uTexels'), spec.tex); - gl.uniform2fv(gl.getUniformLocation(bakeProg, 'uSeed'), seedOffset(opts.seed ?? 0)); - gl.drawArrays(gl.TRIANGLES, 0, 3); - gl.bindFramebuffer(gl.FRAMEBUFFER, null); - - // The displaced grid. - const g = buildGrid(spec.grid); - const vao = gl.createVertexArray(); - const vbuf = gl.createBuffer(); - const ibuf = gl.createBuffer(); - gl.bindVertexArray(vao); - gl.bindBuffer(gl.ARRAY_BUFFER, vbuf); - gl.bufferData(gl.ARRAY_BUFFER, g.uv, gl.STATIC_DRAW); - gl.enableVertexAttribArray(0); - gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0); - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, ibuf); - gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, g.indices, gl.STATIC_DRAW); - gl.bindVertexArray(null); - free.push( - () => gl.deleteVertexArray(vao), - () => gl.deleteBuffer(vbuf), - () => gl.deleteBuffer(ibuf) - ); - - const sun = [...sunDirection(sky)]; - const sunLight = [...sky.direct]; - const ground = groundLight(sky); - const ambient = [...ground.ambient]; - const heading = START_TURNS; - const glow = [...glowColour(sky)]; - const band: [number, number] = sky.band ? [sky.band.floor, sky.band.ceiling] : [0, 1]; - const lift = [...(sky.band?.lift ?? [0, 0, 0])]; - const sunTexel = sunIndex(sky.elevation); - const night = nightness(sky.elevation); - const moonTexel = sunIndex(Math.abs(sky.elevation)); - const palette = albedoPalette(sky); - const triangles = triangleCount(spec.grid); - - const stars = createTerrainStars(canvas, sky); - const reducedMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)'); - const sampler = new FrameSampler(); - let still = tier === 'still'; - let disposed = false; - let lost = false; - let raf = 0; - let readout: HTMLElement | undefined; - let resizeTimer = 0; - let turnsAtPause = 0; - let playedFrom: number | undefined; - - /** Size the canvas: low renders at 0.75 of the CSS size; full at device pixel ratio capped to 2. */ - const size = () => { - const dpr = Math.min(window.devicePixelRatio || 1, 2) * (tier === 'low' ? 0.75 : 1); - canvas.width = Math.max(1, Math.round((canvas.clientWidth || window.innerWidth) * dpr)); - canvas.height = Math.max(1, Math.round((canvas.clientHeight || window.innerHeight) * dpr)); - }; - - const draw = (turns: number) => { - if (lost) return; - gl.viewport(0, 0, canvas.width, canvas.height); - const v = view(canvas.width / canvas.height, (turns + heading) % 1); - gl.disable(gl.DEPTH_TEST); - gl.useProgram(skyProg); - const us = (n: string) => gl.getUniformLocation(skyProg, n); - gl.uniform3fv(us('uSun'), sun); - gl.uniform3fv(us('uSunColour'), sunLight); - gl.uniform3fv(us('uGlow'), glow); - gl.uniform2fv(us('uBand'), band); - gl.uniform3fv(us('uLift'), lift); - gl.uniform1f(us('uSunIndex'), sunTexel); - gl.activeTexture(gl.TEXTURE1); - gl.bindTexture(gl.TEXTURE_3D, skyTex); - gl.uniform1i(us('uSky'), 1); - gl.uniform3fv(us('uRight'), v.right); - gl.uniform3fv(us('uUp'), v.up); - gl.uniform3fv(us('uForward'), v.forward); - gl.uniform2f(us('uSize'), canvas.width, canvas.height); - gl.uniform1f(us('uTanHalf'), Math.tan(CAMERA.fov / 2)); - gl.drawArrays(gl.TRIANGLES, 0, 3); - - gl.enable(gl.DEPTH_TEST); - gl.clear(gl.DEPTH_BUFFER_BIT); - gl.useProgram(gridProg); - const u = (n: string) => gl.getUniformLocation(gridProg, n); - gl.uniformMatrix4fv(u('uViewProj'), false, v.viewProj); - gl.uniform3fv(u('uCamera'), v.eye); - gl.uniform1f(u('uSpan'), TERRAIN.span); - gl.uniform1i(u('uTex'), spec.tex); - gl.uniform3fv(u('uSun'), sun); - gl.uniform3fv(u('uLightDir'), ground.dir); - gl.uniform3fv(u('uLight'), ground.colour); - gl.uniform3fv(u('uAmbient'), ambient); - gl.uniform3fv(u('uGlow'), glow); - gl.uniform2fv(u('uBand'), band); - gl.uniform3fv(u('uLift'), lift); - gl.uniform1f(u('uSunIndex'), sunTexel); - gl.activeTexture(gl.TEXTURE1); - gl.bindTexture(gl.TEXTURE_3D, skyTex); - gl.uniform1i(u('uSky'), 1); - gl.uniform1f(u('uNight'), night); - gl.uniform1f(u('uMoonIndex'), moonTexel); - gl.activeTexture(gl.TEXTURE2); - gl.bindTexture(gl.TEXTURE_3D, apTex); - gl.uniform1i(u('uAP'), 2); - gl.uniform3fv(u('uSoil'), palette.soil); - gl.uniform3fv(u('uScree'), palette.scree); - gl.uniform3fv(u('uRock'), palette.rock); - gl.uniform3fv(u('uSnow'), palette.snow); - gl.uniform1f(u('uSnowLine'), palette.snowLine); - gl.activeTexture(gl.TEXTURE0); - gl.bindTexture(gl.TEXTURE_2D, heightTex); - gl.uniform1i(u('uHeight'), 0); - gl.bindVertexArray(vao); - gl.drawElements(gl.TRIANGLES, g.indices.length, gl.UNSIGNED_INT, 0); - gl.bindVertexArray(null); - stars?.draw((turns + heading) % 1, moving() ? performance.now() / 1000 : undefined); - }; - - const moving = () => - !still && - !disposed && - !lost && - !(reducedMotion?.matches ?? false) && - document.visibilityState === 'visible'; - - const turnsNow = (now: number) => - turnsAtPause + (playedFrom === undefined ? 0 : (now - playedFrom) / (CAMERA.seconds * 1000)); - - const report = (stillNow: boolean) => { - const s = { ...sampler.stats(), still: stillNow, triangles }; - opts.onProbe?.(s); - if (readout) { - readout.textContent = `terrain · ${s.triangles} tris · n ${s.n} · median ${s.medianMs.toFixed( - 1 - )} ms · p95 ${s.p95Ms.toFixed(1)} ms${stillNow ? ' · STILL' : ''}`; - } - }; - - const settleToStill = () => { - if (playedFrom !== undefined) turnsAtPause = turnsNow(performance.now()); - playedFrom = undefined; - still = true; - cancelAnimationFrame(raf); - raf = 0; - draw(turnsAtPause); - report(true); - }; - - let sinceReport = 0; - // The first window is measured (guard against a slow device); after it the loop only draws. - let measuring = true; - const frame = (now: number) => { - raf = 0; - if (!moving()) return; - draw(turnsNow(now)); - if (!measuring) { - raf = requestAnimationFrame(frame); - return; - } - const full = sampler.push(now); - if (full) { - measuring = false; - if (sampler.slow()) { - settleToStill(); - return; - } - if (probe) report(false); - } else if (probe && now - sinceReport > 500) { - sinceReport = now; - report(false); - } - raf = requestAnimationFrame(frame); - }; - const wake = () => { - if (!moving()) { - if (playedFrom !== undefined) turnsAtPause = turnsNow(performance.now()); - playedFrom = undefined; - return; - } - if (raf) return; - playedFrom = performance.now(); - if (measuring) sampler.reset(); - raf = requestAnimationFrame(frame); - }; - - const onLost = (e: Event) => { - e.preventDefault(); - lost = true; - cancelAnimationFrame(raf); - raf = 0; - opts.onContextLost?.(); - }; - canvas.addEventListener('webglcontextlost', onLost); - - size(); - if (probe && canvas.parentElement) { - 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', - }); - canvas.parentElement.appendChild(readout); - } - const removeLabel = showTierLabel(canvas, tier, opts.debug === true); - if (still) settleToStill(); - else wake(); - if (!still && !moving()) draw(0); - - const onVisibility = () => { - sampler.reset(); - wake(); - }; - const onResize = () => { - clearTimeout(resizeTimer); - resizeTimer = window.setTimeout(() => { - if (disposed || lost) return; - size(); - stars?.resize(); - draw(turnsNow(performance.now())); - sampler.reset(); - }, 250); - }; - document.addEventListener('visibilitychange', onVisibility); - window.addEventListener('resize', onResize); - reducedMotion?.addEventListener?.('change', onVisibility); - - return { - login() { - // The camera is the same before and after. - }, - dispose() { - if (disposed) return; - disposed = true; - cancelAnimationFrame(raf); - clearTimeout(resizeTimer); - document.removeEventListener('visibilitychange', onVisibility); - window.removeEventListener('resize', onResize); - reducedMotion?.removeEventListener?.('change', onVisibility); - canvas.removeEventListener('webglcontextlost', onLost); - readout?.remove(); - removeLabel?.(); - stars?.dispose(); - release(); - }, - }; -} diff --git a/src/app/features/scene/terrain/TerrainSky2D.test.ts b/src/app/features/scene/terrain/TerrainSky2D.test.ts deleted file mode 100644 index d85d8f01..00000000 --- a/src/app/features/scene/terrain/TerrainSky2D.test.ts +++ /dev/null @@ -1,286 +0,0 @@ -/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-empty-function -- DOM stubs, as the other scene tests */ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { createTerrainSkyScene, SKY_WIDTH } from './TerrainSky2D'; -import { startBackgroundScene } from '../index'; -import { terrainSkyFor } from '../skyForState'; - -let search: string; -let arcs: number; -let overlay: { remove: ReturnType }; -let windowListeners: Record void>; -beforeEach(() => { - search = ''; - arcs = 0; - windowListeners = {}; - vi.stubGlobal('document', { - createElement: () => { - overlay = { - remove: vi.fn(), - style: {}, - setAttribute() {}, - getContext: () => ({ - clearRect() {}, - beginPath() {}, - fill() {}, - arc: () => { - arcs += 1; - }, - }), - } as any; - return overlay; - }, - }); - vi.stubGlobal('window', { - devicePixelRatio: 1, - innerWidth: 400, - innerHeight: 800, - addEventListener: (n: string, f: () => void) => { - windowListeners[n] = f; - }, - removeEventListener: (n: string) => { - delete windowListeners[n]; - }, - get location() { - return { search }; - }, - setTimeout, - }); -}); -afterEach(() => { - vi.unstubAllGlobals(); -}); - -/** A canvas with a recording 2D context; `gl` is what 'webgl2' answers. */ -function canvasWith(opts: { twoD?: boolean; gl?: unknown } = {}) { - const painted: { data: Uint8ClampedArray; width: number; height: number }[] = []; - const ctx = { - createImageData: (width: number, height: number) => ({ - width, - height, - data: new Uint8ClampedArray(width * height * 4), - }), - putImageData: (image: any) => painted.push(image), - }; - const parentAppend = vi.fn(); - const canvas: any = { - width: 0, - height: 0, - clientWidth: 400, - clientHeight: 800, - parentElement: { appendChild: parentAppend }, - getContext: vi.fn((kind: string) => { - if (kind !== '2d') return opts.gl ?? null; - return opts.twoD === false ? null : ctx; - }), - addEventListener: vi.fn(), - removeEventListener: vi.fn(), - }; - return { canvas, painted, parentAppend }; -} - -const pixel = (img: { data: Uint8ClampedArray; width: number }, x: number, y: number) => - Array.from(img.data.slice((y * img.width + x) * 4, (y * img.width + x) * 4 + 3)); -const mean = (img: { data: Uint8ClampedArray }) => { - let s = 0; - for (let i = 0; i < img.data.length; i += 4) s += img.data[i] + img.data[i + 1] + img.data[i + 2]; - return s / (img.data.length / 4) / 3; -}; - -describe('createTerrainSkyScene', () => { - it("returns null at tier 'off' and touches nothing", () => { - const { canvas } = canvasWith(); - expect(createTerrainSkyScene({ canvas, tier: 'off' })).toBeNull(); - expect(canvas.getContext).not.toHaveBeenCalled(); - }); - - it('returns null when the canvas gives no 2D context (the CSS ground stays)', () => { - const { canvas } = canvasWith({ twoD: false }); - expect(createTerrainSkyScene({ canvas, tier: 'low' })).toBeNull(); - }); - - it('paints one opaque, graded sky: the horizon end of the image is not the zenith end', () => { - const { canvas, painted } = canvasWith(); - const s = createTerrainSkyScene({ canvas, tier: 'low', sky: 'noonday' })!; - expect(painted).toHaveLength(1); - const img = painted[0]; - expect(img.width).toBe(SKY_WIDTH); - expect(canvas.width).toBe(SKY_WIDTH); - expect(canvas.height).toBe(img.height); - for (let i = 3; i < img.data.length; i += 4) expect(img.data[i]).toBe(255); - const x = Math.floor(SKY_WIDTH / 2); - expect(pixel(img, x, 0)).not.toEqual(pixel(img, x, img.height - 1)); - expect(mean(img)).toBeGreaterThan(20); - s.dispose(); - }); - - it('follows the baked sky: noon is brighter than midnight, and ?sun= / ?az= move it', () => { - const noon = canvasWith(); - createTerrainSkyScene({ canvas: noon.canvas, tier: 'low', sky: 'noonday' })!.dispose(); - const night = canvasWith(); - createTerrainSkyScene({ canvas: night.canvas, tier: 'low', sky: 'midnight' })!.dispose(); - expect(mean(noon.painted[0])).toBeGreaterThan(mean(night.painted[0]) * 1.5); - - const low = canvasWith(); - createTerrainSkyScene({ canvas: low.canvas, tier: 'low', sun: { elevation: 30 } })!.dispose(); - const down = canvasWith(); - createTerrainSkyScene({ canvas: down.canvas, tier: 'low', sun: { elevation: -20 } })!.dispose(); - expect(mean(low.painted[0])).toBeGreaterThan(mean(down.painted[0])); - - search = '?sun=30&az=0'; - const q0 = canvasWith(); - createTerrainSkyScene({ canvas: q0.canvas, tier: 'low' })!.dispose(); - search = '?sun=30&az=180'; - const q1 = canvasWith(); - createTerrainSkyScene({ canvas: q1.canvas, tier: 'low' })!.dispose(); - expect(Array.from(q0.painted[0].data)).not.toEqual(Array.from(q1.painted[0].data)); - }); - - it('stars only on a dark sky', () => { - const night = canvasWith(); - const a = createTerrainSkyScene({ canvas: night.canvas, tier: 'low', sky: 'midnight' })!; - expect(night.parentAppend).toHaveBeenCalledTimes(1); - expect(arcs).toBeGreaterThan(0); - a.dispose(); - expect(overlay.remove).toHaveBeenCalled(); - arcs = 0; - const day = canvasWith(); - createTerrainSkyScene({ canvas: day.canvas, tier: 'low', sky: 'noonday' })!.dispose(); - expect(day.parentAppend).not.toHaveBeenCalled(); - expect(arcs).toBe(0); - }); - - it('repaints on resize, and dispose stops listening', () => { - vi.useFakeTimers(); - vi.stubGlobal('window', { - ...(window as any), - setTimeout, - addEventListener: (window as any).addEventListener, - }); - const { canvas, painted } = canvasWith(); - const s = createTerrainSkyScene({ canvas, tier: 'low', sky: 'noonday' })!; - expect(windowListeners.resize).toBeDefined(); - windowListeners.resize(); - vi.advanceTimersByTime(300); - expect(painted).toHaveLength(2); - s.dispose(); - expect(windowListeners.resize).toBeUndefined(); - vi.useRealTimers(); - }); -}); - -describe('the sky-only tier label', () => { - const labels = (parentAppend: ReturnType) => - parentAppend.mock.calls.filter(([e]) => e?.textContent === 'terrain · sky-only'); - - it('shows for ?tierlabel=1 only where the overlays are allowed', () => { - search = '?tierlabel=1'; - const off = canvasWith(); - createTerrainSkyScene({ canvas: off.canvas, tier: 'low' })!.dispose(); - expect(labels(off.parentAppend)).toHaveLength(0); - const on = canvasWith(); - createTerrainSkyScene({ canvas: on.canvas, tier: 'low', debug: true })!.dispose(); - expect(labels(on.parentAppend)).toHaveLength(1); - }); - - it('the door allows it from the config flag, and not from a plain production config', async () => { - vi.stubEnv('DEV', false); - vi.stubEnv('VITE_PREVIEW_DEMO', ''); - search = '?tierlabel=1'; - const plain = canvasWith(); - ( - await startBackgroundScene({ tier: 'low', style: 'terrain' }, {}, { canvas: plain.canvas }) - )?.dispose(); - expect(labels(plain.parentAppend)).toHaveLength(0); - const flagged = canvasWith(); - ( - await startBackgroundScene( - { tier: 'low', style: 'terrain', debugOverlays: true }, - {}, - { canvas: flagged.canvas } - ) - )?.dispose(); - expect(labels(flagged.parentAppend)).toHaveLength(1); - vi.unstubAllEnvs(); - }); -}); - -describe('startBackgroundScene, terrain style', () => { - it('without WebGL2 mounts the sky on the same canvas instead of returning null', async () => { - const { canvas, painted } = canvasWith({ gl: null }); - const scene = await startBackgroundScene({ tier: 'low', style: 'terrain' }, {}, { canvas }); - expect(scene).not.toBeNull(); - expect(canvas.getContext.mock.calls.map((c: unknown[]) => c[0])).toEqual(['webgl2', '2d']); - expect(painted).toHaveLength(1); - scene!.dispose(); - }); - - it('with WebGL2 the terrain runs and the 2D sky is never requested', async () => { - const gl: any = new Proxy( - {}, - { - get(_t, name: string) { - if (name === 'getShaderParameter' || name === 'getProgramParameter') return () => true; - if (name === 'checkFramebufferStatus') return () => 1; - if (name === 'getParameter') return () => 16; - if (/^[A-Z_0-9]+$/.test(name)) return 1; - return () => ({}); - }, - } - ); - Object.assign(document, { - addEventListener() {}, - removeEventListener() {}, - visibilityState: 'visible', - }); - vi.stubGlobal('requestAnimationFrame', () => 1); - vi.stubGlobal('cancelAnimationFrame', () => {}); - vi.stubGlobal('performance', { now: () => 0 }); - (window as any).matchMedia = () => ({ - matches: false, - addEventListener() {}, - removeEventListener() {}, - }); - const { canvas, painted } = canvasWith({ gl }); - const scene = await startBackgroundScene({ tier: 'low', style: 'terrain' }, {}, { canvas }); - expect(scene).not.toBeNull(); - expect(canvas.getContext.mock.calls.map((c: unknown[]) => c[0])).toEqual(['webgl2']); - expect(painted).toHaveLength(0); - scene!.dispose(); - }); - - it('a canvas that took a GL context but gives no scene still ends as null: no 2D context to paint on', async () => { - const { canvas } = canvasWith({ gl: null, twoD: false }); - expect( - await startBackgroundScene({ tier: 'low', style: 'terrain' }, {}, { canvas }) - ).toBeNull(); - }); -}); - -describe('the 2D sky lies in the band of its state', () => { - // The painted pixels, read back through the sRGB curve as a screen shows them. - const lumOf = (rgb: number[]) => { - const [r, g, b] = rgb.map((v) => { - const e = v / 255; - return e <= 0.04045 ? e / 12.92 : ((e + 0.055) / 1.055) ** 2.4; - }); - return 0.2126 * r + 0.7152 * g + 0.0722 * b; - }; - const painted = (state: 'day' | 'dusk' | 'night') => { - const c = canvasWith(); - createTerrainSkyScene({ canvas: c.canvas, tier: 'low', ...terrainSkyFor(state) })!.dispose(); - const img = c.painted[0]; - const out: number[] = []; - for (let y = 0; y < img.height; y += 1) { - for (let x = 0; x < img.width; x += 1) out.push(lumOf(pixel(img, x, y))); - } - return out; - }; - - it.each([['day'], ['dusk']] as const)('%s: no pixel below the text bound 0.2983', (state) => { - expect(Math.min(...painted(state))).toBeGreaterThanOrEqual(0.2983); - }); - - it('night: no pixel above the text bound 0.0931', () => { - expect(Math.max(...painted('night'))).toBeLessThanOrEqual(0.0931); - }); -}); diff --git a/src/app/features/scene/terrain/TerrainSky2D.ts b/src/app/features/scene/terrain/TerrainSky2D.ts deleted file mode 100644 index 4653d470..00000000 --- a/src/app/features/scene/terrain/TerrainSky2D.ts +++ /dev/null @@ -1,90 +0,0 @@ -import type { Scene } from '../Scene'; -import type { TerrainOptions } from './Terrain'; -import { chooseSky, skyColour, START_TURNS, Vec3 } from './terrainSky'; -import { createTerrainStars } from './terrainStars'; -import { showTierLabel } from './tierLabel'; -import { CAMERA, view } from './terrainWorld'; - -/** The sky is smooth, so it is painted this many px wide and stretched by the canvas's CSS size. */ -export const SKY_WIDTH = 96; - -/** The sky of the terrain scene without WebGL2: the camera's first frame of `skyColour`, once, on a 2D canvas, with the star layer on top. */ -export type TerrainSkyOptions = Pick< - TerrainOptions, - 'canvas' | 'tier' | 'sky' | 'sun' | 'band' | 'debug' ->; - -/** - * Same contract as `createTerrainScene`. Paints the terrain scene's sky (the CPU twin of its sky shader, from the - * same baked tables and the same `?sun=` `?az=` `?sky=` choice) for the camera at its start, still: nothing moves, so - * a device that cannot run WebGL2 pays one paint and one resize repaint. Below the horizon there is no terrain, so - * the image continues with the horizon's colour. Null for "keep the CSS ground": tier off, or the canvas already - * holds a WebGL context and gives no 2D one. - */ -export function createTerrainSkyScene(opts: TerrainSkyOptions): Scene | null { - if ((opts.tier ?? 'full') === 'off') return null; - const { canvas } = opts; - const ctx = canvas.getContext('2d'); - if (!ctx) return null; - const sky = chooseSky(opts); - const stars = createTerrainStars(canvas, sky); - const heading = START_TURNS; - const tanHalf = Math.tan(CAMERA.fov / 2); - let disposed = false; - let resizeTimer = 0; - - const paint = () => { - const w = SKY_WIDTH; - const cw = canvas.clientWidth || window.innerWidth; - const ch = canvas.clientHeight || window.innerHeight; - const h = Math.max(1, Math.round((w * ch) / cw)); - canvas.width = w; - canvas.height = h; - const v = view(cw / ch, heading); - const image = ctx.createImageData(w, h); - for (let y = 0; y < h; y += 1) { - const ny = 1 - ((y + 0.5) / h) * 2; - for (let x = 0; x < w; x += 1) { - const nx = ((x + 0.5) / w) * 2 - 1; - const d = [0, 1, 2].map( - (i) => v.forward[i] + nx * tanHalf * (cw / ch) * v.right[i] + ny * tanHalf * v.up[i] - ); - const len = Math.hypot(d[0], d[1], d[2]); - const c: Vec3 = skyColour(sky, [d[0] / len, d[1] / len, d[2] / len]); - const at = (y * w + x) * 4; - for (let i = 0; i < 3; i += 1) { - image.data[at + i] = Math.round(255 * Math.min(1, Math.max(0, c[i])) ** (1 / 2.2)); - } - image.data[at + 3] = 255; - } - } - ctx.putImageData(image, 0, 0); - stars?.draw(heading); - }; - - const onResize = () => { - clearTimeout(resizeTimer); - resizeTimer = window.setTimeout(() => { - if (disposed) return; - stars?.resize(); - paint(); - }, 250); - }; - window.addEventListener('resize', onResize); - paint(); - const removeLabel = showTierLabel(canvas, 'sky-only', opts.debug === true); - - return { - login() { - // Nothing moves, so there is no pull-back to start. - }, - dispose() { - if (disposed) return; - disposed = true; - clearTimeout(resizeTimer); - window.removeEventListener('resize', onResize); - removeLabel?.(); - stars?.dispose(); - }, - }; -} diff --git a/src/app/features/scene/terrain/terrainAlbedo.test.ts b/src/app/features/scene/terrain/terrainAlbedo.test.ts deleted file mode 100644 index 6afac79d..00000000 --- a/src/app/features/scene/terrain/terrainAlbedo.test.ts +++ /dev/null @@ -1,226 +0,0 @@ -/* eslint-disable no-restricted-syntax -- tests loop over skies, heights and slopes */ -import { describe, expect, it } from 'vitest'; -import { SKY } from './terrainSky'; -import { - ALBEDO, - albedoAt, - albedoPalette, - bilinearHeight, - CAVITY, - cavityAt, - curvatureAt, - grainAt, - triWeights, - wobble, - wobbleAt, -} from './terrainAlbedo'; -import { GRID_FRAG } from './terrainShaders'; - -const near = (a: readonly number[], b: readonly number[], eps = 1e-6) => - a.every((v, i) => Math.abs(v - b[i]) < eps); -const luma = (c: readonly number[]) => 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]; -// A point where the wobble is zero, so band edges sit exactly where the palette says. -const FLAT_X = Math.PI / 0.043; -// A normal for the xz plane alone (all the weight on it), carrying `ny` for the slope bands. -const facing = (ny: number) => [0, ny, 0] as const; -const at = (sky: keyof typeof SKY, h: number, ny: number) => - albedoAt(albedoPalette(SKY[sky]), h, facing(ny), FLAT_X, 0); - -describe('albedo by slope and height', () => { - it('the test point really has no wobble', () => { - expect(Math.abs(wobble(FLAT_X, 0))).toBeLessThan(1e-9); - }); - - it('steep faces are rock at every height, gentle low ones are soil, gentle high ones are snow', () => { - const p = albedoPalette(SKY.noonday); - for (const h of [10, 90, 160, 220]) expect(near(at('noonday', h, 0.3), p.rock)).toBe(true); - expect(near(at('noonday', 10, 1), p.soil)).toBe(true); - expect(near(at('noonday', 220, 1), p.snow)).toBe(true); - }); - - it('soil grades to scree by height on gentle ground, halfway at the middle of the band', () => { - const p = albedoPalette(SKY.noonday); - const half = p.soil.map((v, i) => (v + p.scree[i]) / 2); - expect(near(at('noonday', (ALBEDO.screeFrom + ALBEDO.screeTo) / 2, 1), half)).toBe(true); - }); - - it('snow is shed as the face steepens: the same height goes snow, then mixed, then rock', () => { - const l = [1, 0.8, 0.5].map((ny) => luma(at('noonday', 220, ny))); - expect(l[0]).toBeGreaterThan(l[1]); - expect(l[1]).toBeGreaterThan(l[2]); - }); - - it('is continuous: a small step in height or slope never jumps a channel by more than a tenth', () => { - for (const sky of ['midnight', 'noonday'] as const) - for (let h = 0; h < 250; h += 1) - for (let ny = 0.3; ny <= 1; ny += 0.05) { - const a = at(sky, h, ny); - const b = at(sky, h + 1, ny + 0.01); - a.forEach((v, i) => expect(Math.abs(v - b[i])).toBeLessThan(0.1)); - } - }); - - it('never returns a negative or a super-white channel', () => { - for (const sky of ['midnight', 'noonday'] as const) - for (let h = -20; h < 300; h += 7) - for (let ny = 0; ny <= 1; ny += 0.1) - for (const v of albedoAt(albedoPalette(SKY[sky]), h, facing(ny), h * 3, ny * 91)) { - expect(v).toBeGreaterThanOrEqual(0); - expect(v).toBeLessThanOrEqual(1); - } - }); - - it('the wobble moves band edges but stays inside its stated amplitude', () => { - for (let i = 0; i < 400; i += 1) - expect(Math.abs(wobble(i * 13.7, i * -9.1))).toBeLessThanOrEqual(1); - }); -}); - -describe('per-sky palette', () => { - const mid = albedoPalette(SKY.midnight); - const noon = albedoPalette(SKY.noonday); - - it('midnight snows lower than noonday', () => { - expect(mid.snowLine).toBeLessThan(noon.snowLine); - }); - - it('midnight is tinted toward the cool horizon haze, noonday toward the warm sun', () => { - // blue share of the same material is higher at night - const blueShare = (c: readonly number[]) => c[2] / (c[0] + c[1] + c[2]); - expect(blueShare(mid.scree)).toBeGreaterThan(blueShare(noon.scree)); - expect(blueShare(mid.snow)).toBeGreaterThan(blueShare(noon.snow)); - }); - - it('a sun at the horizon lands between the two palettes', () => { - const dusk = albedoPalette({ ...SKY.noonday, elevation: 2 }); - expect(dusk.snowLine).toBeLessThan(noon.snowLine); - expect(dusk.snowLine).toBeGreaterThan(mid.snowLine); - }); - - it('keeps every material in 0..1', () => { - for (const p of [mid, noon]) - for (const c of [p.soil, p.scree, p.rock, p.snow]) - c.forEach((v) => { - expect(v).toBeGreaterThan(0); - expect(v).toBeLessThanOrEqual(1); - }); - }); -}); - -describe('shader agrees with the pure function on its numbers', () => { - it('takes every band number from ALBEDO, and reads no texture for colour', () => { - expect(GRID_FRAG).toContain(`#define ALB_SNOW_BAND ${ALBEDO.snowBand.toFixed(1)}`); - expect(GRID_FRAG).toContain(`#define ALB_ROCK_LO ${ALBEDO.rockLo}`); - expect(GRID_FRAG).toContain(`#define ALB_WOBBLE_S ${ALBEDO.wobbleSlope}`); - expect(GRID_FRAG).toContain(`#define ALB_GRAIN_COARSE ${ALBEDO.grainCoarse}`); - expect(GRID_FRAG).toContain(`#define ALB_STRATA ${ALBEDO.strata}`); - expect(GRID_FRAG).toContain(`#define ALB_FINE_WARP ${ALBEDO.fineWarp.toFixed(1)}`); - expect(GRID_FRAG).toContain('waves3(warpq(qy),'); - // the only fetch for colour-by-material would be a texture; the height map's texelFetch is the only other read, and the sky lookup is the baked scattering table's - expect(GRID_FRAG.match(/texelFetch|texture\((?!uSky|uAP)/g)).toHaveLength(1); - }); -}); - -const UP = [0, 1, 0] as const; -const EAST = [1, 0, 0] as const; - -describe('grain', () => { - const samples = (rock: number, distance: number) => - Array.from({ length: 400 }, (_, i) => - grainAt(i * 1.7, 100 + i * 0.3, i * 0.9, UP, rock, distance) - ); - const spread = (v: number[]) => Math.max(...v) - Math.min(...v); - - it('varies the surface near the eye, never goes negative, and averages about 1', () => { - const v = samples(0, 50); - expect(spread(v)).toBeGreaterThan(0.4); - expect(Math.min(...v)).toBeGreaterThanOrEqual(0); - expect(v.reduce((a, b) => a + b, 0) / v.length).toBeGreaterThan(0.85); - }); - - it('drops its fine octave with distance, so far ground does not shimmer', () => { - const rangeOf = (d: number) => - spread(Array.from({ length: 400 }, (_, i) => grainAt(i * 0.37, 100, i * 0.21, UP, 0, d))); - expect(rangeOf(900)).toBeLessThan(rangeOf(50)); - }); - - it('layers the rock: strata show only where the face is rock', () => { - const height = (rock: number) => - spread(Array.from({ length: 400 }, (_, i) => grainAt(0, 100 + i * 0.05, 0, UP, rock, 2000))); - expect(height(1)).toBeGreaterThan(0.2); - expect(height(0)).toBeLessThan(1e-9); - }); -}); - -describe('triplanar projection', () => { - it('weights sum to 1 and go to the plane the face looks along', () => { - for (const n of [UP, EAST, [0.6, 0.6, 0.529], [0, 0, 1]] as const) { - const w = triWeights(n); - expect(w[0] + w[1] + w[2]).toBeCloseTo(1, 9); - } - expect(triWeights(UP)).toEqual([0, 1, 0]); - expect(triWeights(EAST)).toEqual([1, 0, 0]); - expect(triWeights([0.8, 0.5, 0.33])[0]).toBeGreaterThan(0.7); - }); - - it('a cliff facing east takes its pattern over (z, y), so it varies with height and not with x: no vertical smear', () => { - const col = (x: number, y: number) => grainAt(x, y, 40, EAST, 0, 50); - const alongY = Array.from({ length: 200 }, (_, i) => col(10, 50 + i * 0.7)); - const alongX = Array.from({ length: 200 }, (_, i) => col(i * 0.7, 50)); - expect(Math.max(...alongY) - Math.min(...alongY)).toBeGreaterThan(0.3); - expect(Math.max(...alongX) - Math.min(...alongX)).toBeLessThan(1e-9); - expect(wobbleAt(5, 80, 40, EAST)).toBeCloseTo(wobbleAt(500, 80, 40, EAST), 12); - expect(wobbleAt(5, 80, 40, EAST)).not.toBeCloseTo(wobbleAt(5, 120, 40, EAST), 3); - }); - - it('level ground takes its pattern over (x, z) alone, as before', () => { - expect(grainAt(12, 10, 30, UP, 0, 50)).toBeCloseTo(grainAt(12, 900, 30, UP, 0, 50), 12); - expect(wobbleAt(12, 10, 30, UP)).toBeCloseTo(wobble(12, 30), 12); - }); -}); - -describe('cavity shading', () => { - // A texel grid of heights with one bump; `hAt` is the nearest texel, `bilinearAt` the continuous reading. - const bump = (i: number, j: number) => 6 * Math.exp(-((i - 20) ** 2 + (j - 20) ** 2) / 40); - const nearestAt = (px: number, pz: number) => bump(Math.floor(px + 0.5), Math.floor(pz + 0.5)); - // Largest change in curvature between neighbouring sample positions a hundredth of a texel apart, over a few texels. - const worstStep = (read: (px: number, pz: number) => number) => { - let worst = 0; - for (let px = 14; px < 26; px += 0.01) - worst = Math.max( - worst, - Math.abs(curvatureAt(read, px + 0.01, 20.3, 4) - curvatureAt(read, px, 20.3, 4)) - ); - return worst; - }; - - it('curvature is the mean of four neighbours at the radius minus the centre', () => { - expect(curvatureAt((px, pz) => px * 2 + pz, 7, 9, 3)).toBeCloseTo(0, 12); - expect(curvatureAt((px, pz) => (px - 5) ** 2 + (pz - 5) ** 2, 5, 5, 2)).toBeCloseTo(4, 12); - }); - - it('bilinear height reads the texel exactly at a texel centre and the mean at the middle of four', () => { - const t = (i: number, j: number) => i * 10 + j * 100; - expect(bilinearHeight(t, 3, 4)).toBe(430); - expect(bilinearHeight(t, 3.5, 4.5)).toBeCloseTo(485, 9); - }); - - it('shading from a bilinear read changes smoothly across texel borders; from the nearest texel it jumps', () => { - const smooth = worstStep((px, pz) => bilinearHeight(bump, px, pz)); - const blocky = worstStep(nearestAt); - expect(blocky).toBeGreaterThan(0.1); - expect(smooth).toBeLessThan(0.02); - }); - - it('the cavity factor darkens a hollow, lights a rise and leaves flat ground alone', () => { - expect(cavityAt(0)).toBe(1); - expect(cavityAt(CAVITY.range)).toBeCloseTo(1 - CAVITY.dark, 12); - expect(cavityAt(-CAVITY.range)).toBeCloseTo(1 + CAVITY.light, 12); - expect(cavityAt(10 * CAVITY.range)).toBeCloseTo(1 - CAVITY.dark, 12); - }); - - it('the grid shader reads the cavity through the bilinear height, the same constants as CAVITY', () => { - expect(GRID_FRAG).toContain(`#define CAV_RANGE ${CAVITY.range.toFixed(1)}`); - expect(GRID_FRAG).not.toMatch(/curv[^;]*hAt\(/); - }); -}); diff --git a/src/app/features/scene/terrain/terrainAlbedo.ts b/src/app/features/scene/terrain/terrainAlbedo.ts deleted file mode 100644 index fdbd9360..00000000 --- a/src/app/features/scene/terrain/terrainAlbedo.ts +++ /dev/null @@ -1,206 +0,0 @@ -// Terrain surface colour as a pure function of height, slope and world position, no texture reads: the shader -// (terrainShaders.ts GRID_FRAG) does the same arithmetic with these numbers as uniforms and #defines. No DOM, no GL. -// Rock where the face is steep, then by height soil, scree and snow; snow only settles on gentle faces. The per-sky -// part reads the baked sky (./terrainSky.ts): the snow line drops and every material is tinted toward the sky's colour -// as the sun goes down, warm by the sun's own colour by day and cool by the horizon haze at night. -import { coldness, hazeColour, SkyData, Vec3 } from './terrainSky'; - -const clamp01 = (x: number) => Math.min(1, Math.max(0, x)); -const smooth = (a: number, b: number, x: number) => { - const t = clamp01((x - a) / (b - a)); - return t * t * (3 - 2 * t); -}; -const mix = (a: number, b: number, t: number) => a + (b - a) * t; - -/** Every number the shader shares: band edges in metres, slope edges as the normal's y (cosine of the slope angle). */ -export const ALBEDO = { - /** soil fades to scree across these heights. */ - screeFrom: 80, - screeTo: 160, - /** half-width in metres of the snow line's fade. */ - snowBand: 22, - /** n.y edges: faces with n.y below `rockLo` are all rock, above `rockHi` none. */ - rockLo: 0.78, - rockHi: 0.95, - /** n.y edges: snow is shed entirely below `snowLo` and settles fully above `snowHi`. */ - snowLo: 0.74, - snowHi: 0.93, - /** world-position wobble of the height edges (metres) and the slope edges, so bands are not contour lines. */ - wobbleHeight: 14, - wobbleSlope: 0.05, - /** Albedo grain: relative swing of the two sine-product octaves (about 20 m and 5 m periods), and of the rock strata. */ - grainCoarse: 0.35, - grainFine: 0.3, - /** Metres the fine octave's coordinates are pushed by a slower sine, so its parallel stripes bend and do not read as hatching. */ - fineWarp: 7, - /** The fine octave fades out between these distances (metres): beyond them it is under a pixel and only shimmers. */ - fineNear: 250, - fineFar: 700, - strata: 0.22, -} as const; - -export interface AlbedoPalette { - soil: Vec3; - scree: Vec3; - rock: Vec3; - snow: Vec3; - /** Metres where snow is half in. */ - snowLine: number; -} - -const BASE = { - soil: [0.045, 0.08, 0.02], - scree: [0.3, 0.235, 0.16], - rock: [0.075, 0.062, 0.06], - snow: [0.72, 0.75, 0.8], -} as const; - -const SNOW_LINE_DAY = 165; -const SNOW_LINE_NIGHT = 135; - -const unit = (c: Vec3): Vec3 => { - const m = Math.max(c[0], c[1], c[2], 1e-6); - return [c[0] / m, c[1] / m, c[2] / m]; -}; - -/** The palette one baked sky gives: base reflectances tinted toward the sky's colour, and its snow line. */ -export function albedoPalette(d: SkyData): AlbedoPalette { - const cold = coldness(d); - const sun = unit(d.direct); - const haze = unit(hazeColour(d)); - const tint = [0, 1, 2].map((i) => mix(sun[i], haze[i], cold)); - const k = mix(0.15, 0.5, cold); - const tinted = (c: Vec3): Vec3 => - [0, 1, 2].map((i) => c[i] * mix(1, tint[i], k)) as unknown as Vec3; - return { - soil: tinted(BASE.soil), - scree: tinted(BASE.scree), - rock: tinted(BASE.rock), - snow: tinted(BASE.snow), - snowLine: mix(SNOW_LINE_DAY, SNOW_LINE_NIGHT, cold), - }; -} - -/** Cheap two-sine value in -1..1 from a 2D world position; stands in for noise so no texture or hash is read. */ -export const wobble = (x: number, z: number): number => - Math.sin(x * 0.043 + z * 0.017) * Math.sin(z * 0.051 - x * 0.023); - -/** - * How much each axis-aligned projection plane counts at a surface with unit normal `n`: weights for (yz, xz, xy), summing - * to 1, sharply favouring the plane the face looks along. Procedural patterns are evaluated on all three and blended by - * these (triplanar), so a cliff is not the floor pattern smeared down it. - */ -export function triWeights(n: Vec3): Vec3 { - const w = n.map((c) => Math.abs(c) ** 4); - const sum = w[0] + w[1] + w[2] || 1; - return [w[0] / sum, w[1] / sum, w[2] / sum]; -} - -/** `wobble` blended over the three projection planes, at a surface point with unit normal `n`. */ -export function wobbleAt(x: number, y: number, z: number, n: Vec3): number { - const w = triWeights(n); - return w[0] * wobble(z, y) + w[1] * wobble(x, z) + w[2] * wobble(x, y); -} - -/** - * Linear albedo at a surface point. `y` the height in metres, `n` the unit normal, `x`/`z` world metres. - * Rock takes the steep faces at any height; on the rest, soil to scree by height, then snow above the snow - * line, thinning to nothing as the face steepens. - */ -export function albedoAt(p: AlbedoPalette, y: number, n: Vec3, x: number, z: number): Vec3 { - const w = wobbleAt(x, y, z, n); - const h = y + ALBEDO.wobbleHeight * w; - const flat = n[1] + ALBEDO.wobbleSlope * w; - const ground = (i: number) => - mix(p.soil[i], p.scree[i], smooth(ALBEDO.screeFrom, ALBEDO.screeTo, h)); - const snow = - smooth(p.snowLine - ALBEDO.snowBand, p.snowLine + ALBEDO.snowBand, h) * - smooth(ALBEDO.snowLo, ALBEDO.snowHi, flat); - const rock = 1 - smooth(ALBEDO.rockLo, ALBEDO.rockHi, flat); - return [0, 1, 2].map((i) => - mix(mix(ground(i), p.snow[i], snow), p.rock[i], rock) - ) as unknown as Vec3; -} - -const COARSE = [ - [0.31, 0.27], - [-0.22, 0.35], - [0.38, -0.12], -] as const; -const FINE = [ - [1.1, 0.7], - [-0.8, 1.2], - [1.3, -0.6], -] as const; -const waves = (k: ReadonlyArray, a: number, b: number) => - k.reduce((sum, [ka, kb]) => sum + Math.sin(a * ka + b * kb), 0) / 3; -/** `waves` of coordinates warped by a sine each (the shader's `warpq`): three plane waves alone make a regular lattice. */ -const wavesWarped = (k: ReadonlyArray, a: number, b: number) => - waves( - k, - a + ALBEDO.fineWarp * Math.sin(b * 0.55 + 1.3), - b + ALBEDO.fineWarp * Math.sin(a * 0.47 + 0.7) - ); - -/** - * The multiplier on albedo that gives the surface grain and the rock its layers, at a surface point (metres) with unit - * normal `n`, `rock` (0..1, how much of the face is rock) and the distance from the eye. Grain is triplanar like the - * wobble. The shader's `ALB_GRAIN_*` block does the same arithmetic. The cavity term beside it in the shader reads the - * height map and has no twin here. - */ -export function grainAt( - x: number, - y: number, - z: number, - n: Vec3, - rock: number, - distance: number -): number { - const w = triWeights(n); - const over = (k: ReadonlyArray, f: typeof waves) => - w[0] * f(k, z, y) + w[1] * f(k, x, z) + w[2] * f(k, x, y); - const coarse = over(COARSE, waves); - const fine = over(FINE, wavesWarped) * (1 - smooth(ALBEDO.fineNear, ALBEDO.fineFar, distance)); - const layers = Math.sin(y * 0.9 + wobbleAt(x, y, z, n) * 3); - return Math.max( - 0, - 1 + ALBEDO.grainCoarse * coarse + ALBEDO.grainFine * fine + ALBEDO.strata * rock * layers - ); -} - -/** The cavity term's numbers: curvature (metres) at which a hollow is fully shaded / a rise fully lit, and by how much. */ -export const CAVITY = { radius: 12, range: 12, dark: 0.55, light: 0.3 } as const; - -/** Height at a continuous texel position, bilinear over the four texels around it (the shader's `hBil`). */ -export function bilinearHeight( - texel: (i: number, j: number) => number, - px: number, - pz: number -): number { - const i = Math.floor(px); - const j = Math.floor(pz); - const fx = px - i; - const fz = pz - j; - return mix( - mix(texel(i, j), texel(i + 1, j), fx), - mix(texel(i, j + 1), texel(i + 1, j + 1), fx), - fz - ); -} - -/** Mean of the four neighbours `r` texels away minus the centre: positive in a hollow, negative on a rise. */ -export function curvatureAt( - height: (px: number, pz: number) => number, - px: number, - pz: number, - r: number -): number { - return ( - 0.25 * (height(px + r, pz) + height(px - r, pz) + height(px, pz + r) + height(px, pz - r)) - - height(px, pz) - ); -} - -/** The multiplier on lit colour for a curvature: a hollow sits in shade, a rise catches light (the shader's `cavity`). */ -export const cavityAt = (curv: number): number => - 1 - CAVITY.dark * clamp01(curv / CAVITY.range) + CAVITY.light * clamp01(-curv / CAVITY.range); diff --git a/src/app/features/scene/terrain/terrainScatter.test.ts b/src/app/features/scene/terrain/terrainScatter.test.ts deleted file mode 100644 index c153eb5f..00000000 --- a/src/app/features/scene/terrain/terrainScatter.test.ts +++ /dev/null @@ -1,141 +0,0 @@ -/* eslint-disable no-restricted-syntax -- tests walk table texels */ -import { describe, expect, it } from 'vitest'; -import { baked } from '../../../../sky/baked'; -import { - aerialRay, - AP_ELEVATIONS, - AP_SLICES, - apElevation, - apSliceKm, - decode, - SUN_ELEVATIONS_DEG, - viewElevation, -} from '../../../../sky/scatter.js'; -import { - AERIAL_GLSL, - aerialAt, - AP_VOLUME, - apVolumeWords, - SCATTER_GLSL, - scatterRadiance, - skyViewWords, - SKY_VIEW, - tableWords, - transmittanceAt, -} from './terrainScatter'; - -const S = baked.scatter.sky_view; - -describe('the table upload', () => { - it('decodes the baked base64 to one half-float word per channel per texel', () => { - const w = skyViewWords(); - expect(w.length).toBe(S.width * S.height * S.depth * S.channels); - expect(SKY_VIEW).toEqual({ width: S.width, height: S.height, depth: S.depth }); - expect(tableWords(baked.scatter.transmittance.data)).toHaveLength(32 * 3); - }); - - it('words are little-endian: the base64 bytes lo, hi make a word hi << 8 | lo', () => { - expect(Array.from(tableWords(btoa(String.fromCharCode(0x34, 0x12, 0xff, 0x7b))))).toEqual([ - 0x1234, 0x7bff, - ]); - }); -}); - -describe('scatterRadiance (the CPU twin of the sampler)', () => { - it('returns the stored texel exactly at a texel centre: layout x azimuth, y view, z sun', () => { - const w = skyViewWords(); - for (const [z, y, x] of [ - [10, 31, 0], - [8, 5, 3], - [5, 20, 6], - [11, 0, 2], - ]) { - const base = ((z * S.height + y) * S.width + x) * 3; - const got = scatterRadiance( - S.sun_elevations_deg[z], - viewElevation(y), - x * S.azimuth_step_deg - ); - got.forEach((v, c) => expect(v).toBeCloseTo(decode(w[base + c]), 9)); - } - }); - - it('interpolates between texels and clamps beyond the table', () => { - const a = scatterRadiance(25, 10, 0)[2]; - const b = scatterRadiance(45, 10, 0)[2]; - const mid = scatterRadiance(35, 10, 0)[2]; // 35 is halfway between 25 and 45 on the sun axis - expect(mid).toBeCloseTo((a + b) / 2, 9); - expect(scatterRadiance(500, 10, 400)).toEqual(scatterRadiance(90, 10, 180)); - expect(scatterRadiance(30, 10, -90)).toEqual(scatterRadiance(30, 10, 90)); - }); - - it('is black under the planet’s shadow limit and blue at a high noon zenith', () => { - scatterRadiance(-18, 30, 0).forEach((v) => expect(v).toBeLessThan(1e-6)); - const noon = scatterRadiance(45, 85, 90); - expect(noon[2]).toBeGreaterThan(1.5 * noon[0]); - }); -}); - -describe('transmittanceAt', () => { - it('is the zenith transmittance exp(-TAU) overhead and redder at the horizon', () => { - const z = transmittanceAt(90); - [0.06, 0.12, 0.26].forEach((tau, i) => expect(z[i]).toBeCloseTo(Math.exp(-tau), 2)); - const h = transmittanceAt(2); - expect(h[2] / h[0]).toBeLessThan(0.5 * (z[2] / z[0])); - }); - - it('is zero where the ground is in the way', () => { - expect(transmittanceAt(-4)).toEqual([0, 0, 0]); - }); -}); - -describe('the GLSL sampler', () => { - it('uses the layout the README documents: texel-centre coordinates over a 7 x 32 x 12 texture, decoded by the store scale', () => { - expect(SCATTER_GLSL).toContain('(x + 0.5) / 7.0'); - expect(SCATTER_GLSL).toContain('(y + 0.5) / 32.0'); - expect(SCATTER_GLSL).toContain('(uSunIndex + 0.5) / 12.0'); - expect(SCATTER_GLSL).toContain('/ 64.0'); - expect(SCATTER_GLSL).toContain('sqrt(clamp((el - (-4.0)) / 94.0, 0.0, 1.0)) * 31.0'); - expect(SCATTER_GLSL).toContain('* 6.0'); - }); -}); - -describe('the aerial perspective volume as the terrain reads it', () => { - it('uploads RGBA half floats in the baked layout', () => { - const a = baked.scatter.aerial_perspective; - expect(apVolumeWords()).toHaveLength(a.width * a.height * a.depth * 4); - expect(AP_VOLUME).toEqual({ width: a.width, height: a.height, depth: a.depth }); - }); - - it('on a texel centre the CPU twin returns the baked ray exactly (to half-float precision)', () => { - const sunI = 8; - const ei = 5; - const slice = 6; - const want = aerialRay(SUN_ELEVATIONS_DEG[sunI], apElevation(ei), 90)[slice]; - const got = aerialAt(SUN_ELEVATIONS_DEG[sunI], apElevation(ei), 90, apSliceKm(slice)); - for (let c = 0; c < 3; c += 1) expect(got.L[c]).toBeCloseTo(want[c], 3); - expect(got.alpha).toBeCloseTo(want[3], 3); - }); - - it('between texels it is near the model: the filtering error is small against the signal', () => { - const want = aerialRay(10, -1.3, 75)[AP_SLICES - 2]; - const got = aerialAt(10, -1.3, 75, apSliceKm(AP_SLICES - 2)); - expect(Math.abs(got.alpha - want[3])).toBeLessThan(0.03); - expect(got.L[0] / want[0]).toBeGreaterThan(0.6); - expect(got.L[0] / want[0]).toBeLessThan(1.6); - }); - - it('fades to nothing at the observer, and clamps past the last slice', () => { - expect(aerialAt(45, -2, 90, 0)).toEqual({ L: [0, 0, 0], alpha: 0 }); - const last = aerialAt(45, -2, 90, apSliceKm(AP_SLICES - 1)); - const beyond = aerialAt(45, -2, 90, 1e6); - expect(beyond.alpha).toBeCloseTo(last.alpha, 9); - }); - - it('the shader lookup carries the same constants as the table', () => { - const a = baked.scatter.aerial_perspective; - expect(AERIAL_GLSL).toContain(`/ ${a.height}.0`); - expect(AERIAL_GLSL).toContain(`${a.max_km.toFixed(1)}`); - expect(AERIAL_GLSL).toContain(`${AP_ELEVATIONS}.0 +`); - }); -}); diff --git a/src/app/features/scene/terrain/terrainScatter.ts b/src/app/features/scene/terrain/terrainScatter.ts deleted file mode 100644 index 72ebfb5c..00000000 --- a/src/app/features/scene/terrain/terrainScatter.ts +++ /dev/null @@ -1,179 +0,0 @@ -// The baked scattering tables (src/sky/baked.ts `scatter`, layout in src/sky/README.md) as the terrain scene -// uses them: decoded to half-float words for the GPU, a CPU twin of the shader's sky lookup for tests and -// for the sun's colour at an arbitrary elevation, and the GLSL both shaders share. No DOM, no GL. -import { baked } from '../../../../sky/baked'; -import { - AP_DISTANCE_SCALE, - AP_ELEVATIONS, - AP_SLICES, - apElevationIndex, - apSliceIndex, - decode, - sunIndex, - viewIndex, -} from '../../../../sky/scatter.js'; -import type { Vec3 } from './terrainSky'; - -const S = baked.scatter; -const AP = S.aerial_perspective; -const SKY = S.sky_view; -const VIEW = S.view_elevation_deg; - -/** Raw little-endian half-float words of a base64 table, ready for `texImage3D(..., HALF_FLOAT, words)`. */ -export function tableWords(b64: string): Uint16Array { - const bytes = atob(b64); - return Uint16Array.from( - { length: bytes.length / 2 }, - (_, i) => bytes.charCodeAt(2 * i) + 256 * bytes.charCodeAt(2 * i + 1) - ); -} - -export const SKY_VIEW = { width: SKY.width, height: SKY.height, depth: SKY.depth } as const; -export const STORE_SCALE = S.store_scale; -export const skyViewWords = (): Uint16Array => tableWords(SKY.data); - -/** The aerial perspective volume (layout in src/sky/scatter.js): RGBA16F, x azimuth from the light, y slice-major block of elevations, z light elevation. */ -export const AP_VOLUME = { width: AP.width, height: AP.height, depth: AP.depth } as const; -export const apVolumeWords = (): Uint16Array => tableWords(AP.data); -export { AP_DISTANCE_SCALE }; - -/** Decode a stored table to values, once. */ -const decoded = (data: string) => { - let values: Float32Array | undefined; - return (): Float32Array => { - if (!values) values = Float32Array.from(tableWords(data), decode); - return values; - }; -}; -const transmittanceTable = decoded(S.transmittance.data); -const skyTable = decoded(SKY.data); -const apTable = decoded(AP.data); - -/** Sun colour at normal incidence for a sun at `elevationDeg`: the baked transmittance, per channel. Zero under the horizon. */ -export function transmittanceAt(elevationDeg: number): Vec3 { - const t = transmittanceTable(); - const f = Math.min(viewIndex(elevationDeg), VIEW.samples - 1); - const i = Math.min(Math.floor(f), VIEW.samples - 2); - const k = f - i; - return [0, 1, 2].map((c) => t[i * 3 + c] * (1 - k) + t[(i + 1) * 3 + c] * k) as unknown as Vec3; -} - -/** - * Sky radiance per steradian for a sun of unit irradiance, trilinear in (azimuth from the sun, view - * elevation, sun elevation) on texel centres, clamped at the edges: what the GPU's LINEAR sampler returns. - */ -export function scatterRadiance(sunElDeg: number, viewElDeg: number, azFromSunDeg: number): Vec3 { - const t = skyTable(); - const at = [ - Math.min(Math.abs(azFromSunDeg) / 180, 1) * (SKY.width - 1), - viewIndex(viewElDeg), - sunIndex(sunElDeg), - ]; - const lo = at.map((v, a) => Math.min(Math.floor(v), [SKY.width, SKY.height, SKY.depth][a] - 2)); - const f = at.map((v, a) => v - lo[a]); - const out = [0, 0, 0]; - for (let corner = 0; corner < 8; corner += 1) { - const dx = corner % 2; - const dy = Math.floor(corner / 2) % 2; - const dz = Math.floor(corner / 4); - const w = (dx ? f[0] : 1 - f[0]) * (dy ? f[1] : 1 - f[1]) * (dz ? f[2] : 1 - f[2]); - const base = (((lo[2] + dz) * SKY.height + lo[1] + dy) * SKY.width + lo[0] + dx) * 3; - for (let c = 0; c < 3; c += 1) out[c] += w * t[base + c]; - } - return [out[0], out[1], out[2]]; -} - -/** - * Aerial perspective along a view ray: in-scatter luminance per channel (for a light of unit irradiance) and opacity - * (1 - mean transmittance), for a light at `lightElDeg`, a ray `viewElDeg` (0 and below) and `azDeg` from the light, - * `km` of baked path along it. Trilinear in (azimuth, elevation, light elevation) and linear between slices, the arithmetic the - * shader's `aerial()` does on the GPU; below the first slice it fades to nothing at the observer (Hillaire's near-slice fade). - */ -export function aerialAt( - lightElDeg: number, - viewElDeg: number, - azDeg: number, - km: number -): { L: Vec3; alpha: number } { - const t = apTable(); - const x = Math.min(Math.abs(azDeg) / 180, 1) * (AP.width - 1); - const e = apElevationIndex(viewElDeg); - const z = sunIndex(lightElDeg); - const texel = (slice: number): number[] => { - const lo = [ - Math.min(Math.floor(x), AP.width - 2), - Math.min(Math.floor(e), AP_ELEVATIONS - 2), - Math.min(Math.floor(z), AP.depth - 2), - ]; - const f = [x - lo[0], e - lo[1], z - lo[2]]; - const out = [0, 0, 0, 0]; - for (let corner = 0; corner < 8; corner += 1) { - const dx = corner % 2; - const dy = Math.floor(corner / 2) % 2; - const dz = Math.floor(corner / 4); - const w = (dx ? f[0] : 1 - f[0]) * (dy ? f[1] : 1 - f[1]) * (dz ? f[2] : 1 - f[2]); - const base = - (((lo[2] + dz) * AP.height + slice * AP_ELEVATIONS + lo[1] + dy) * AP.width + lo[0] + dx) * - 4; - for (let c = 0; c < 4; c += 1) out[c] += w * t[base + c]; - } - return out; - }; - const f = apSliceIndex(km); - const fs = Math.min(Math.max(f, 0), AP_SLICES - 1); - const k = Math.min(Math.floor(fs), AP_SLICES - 2); - const a = texel(k); - const b = texel(k + 1); - const fade = Math.min(Math.max(f + 1, 0), 1); - const v = [0, 1, 2, 3].map((c) => (a[c] + (b[c] - a[c]) * (fs - k)) * fade); - return { L: [v[0], v[1], v[2]], alpha: v[3] }; -} - -/** - * The lowest view elevation the sky is sampled at, degrees. The table dips toward the ground over its last degree - * (its rows below the horizon are for an observer who would hit the ground), so at and below this the sky and the - * terrain's haze both take the colour here, flat to the horizon, and meet without a seam. - */ -export const HORIZON_FLOOR = 1.5; - -/** The sky shader's lookup, in GLSL: `skyScatter(viewDirection)` is unit-sun radiance, needs uSky, uSunIndex, uSun. */ -export const SCATTER_GLSL = ` -uniform highp sampler3D uSky; -uniform float uSunIndex; -uniform vec3 uSun; -vec3 skyScatter(vec3 d) { - float el = max(degrees(asin(clamp(d.y, -1.0, 1.0))), ${HORIZON_FLOOR.toFixed(1)}); - vec2 h = d.xz, s = uSun.xz; - float az = (length(h) < 1e-4 || length(s) < 1e-4) ? 0.0 - : degrees(acos(clamp(dot(normalize(h), normalize(s)), -1.0, 1.0))); - float y = sqrt(clamp((el - (${VIEW.min.toFixed(1)})) / ${(VIEW.max - VIEW.min).toFixed( - 1 -)}, 0.0, 1.0)) * ${(VIEW.samples - 1).toFixed(1)}; - float x = clamp(az / 180.0, 0.0, 1.0) * ${(SKY.width - 1).toFixed(1)}; - return texture(uSky, vec3((x + 0.5) / ${SKY.width}.0, (y + 0.5) / ${ - SKY.height -}.0, (uSunIndex + 0.5) / ${SKY.depth}.0)).rgb / ${S.store_scale.toFixed(1)}; -}`; - -/** - * The aerial perspective lookup, in GLSL: `aerial(lightIndex, viewElDeg, azDeg, km)` is `aerialAt` on the GPU. Needs uAP. - * Each slice is one hardware-filtered fetch, kept inside its block of elevation rows so the filter never reads a - * neighbouring slice; two fetches and a lerp per call. - */ -export const AERIAL_GLSL = ` -uniform highp sampler3D uAP; -vec4 apSlice(float k, float e, float x, float z) { - return texture(uAP, vec3((x + 0.5) / ${AP.width}.0, (k * ${AP.elevations}.0 + e + 0.5) / ${ - AP.height -}.0, (z + 0.5) / ${AP.depth}.0)) / ${S.store_scale.toFixed(1)}; -} -vec4 aerial(float lightIndex, float viewElDeg, float azDeg, float km) { - float e = ${(AP.elevations - 1).toFixed( - 1 - )} * (1.0 - sqrt(clamp(-viewElDeg / ${(-AP.elevation_min_deg).toFixed(1)}, 0.0, 1.0))); - float x = clamp(abs(azDeg) / 180.0, 0.0, 1.0) * ${(AP.width - 1).toFixed(1)}; - float f = ${AP.slices}.0 * sqrt(max(km, 0.0) / ${AP.max_km.toFixed(1)}) - 1.0; - float fs = clamp(f, 0.0, ${(AP.slices - 1).toFixed(1)}); - float k = min(floor(fs), ${(AP.slices - 2).toFixed(1)}); - return mix(apSlice(k, e, x, lightIndex), apSlice(k + 1.0, e, x, lightIndex), fs - k) * clamp(f + 1.0, 0.0, 1.0); -}`; diff --git a/src/app/features/scene/terrain/terrainShaders.ts b/src/app/features/scene/terrain/terrainShaders.ts deleted file mode 100644 index f6bcce37..00000000 --- a/src/app/features/scene/terrain/terrainShaders.ts +++ /dev/null @@ -1,255 +0,0 @@ -// GLSL ES 3.00. The height map is baked once by CultMath's Phacelle noise (vendored, unedited, MPL-2.0: Rune -// Skovbo Johansen's Phacelle noise, https://blog.runevision.com/2026/01/) composed into a slope-directed gully -// filter after the description in his March 2026 erosion-filter post. The composition is ours, written from -// that description; it is not his filter and has not been compared against it (see harness terrainDemo.ts on -// the terrain-tier-spike branch, from which this is promoted). The height is packed in two bytes of an RGBA8 -// target, so no float colour-buffer extension is needed. -import cultmath from '../shaders/CultMath.glsl?raw'; -import phacelle from '../shaders/CultMath.Phacelle.glsl?raw'; -import { trimGlsl } from '../cultmathTrim'; -import { LUMA } from '../skyBand'; -import { ALBEDO, CAVITY } from './terrainAlbedo'; -import { AERIAL_GLSL, AP_DISTANCE_SCALE, SCATTER_GLSL } from './terrainScatter'; -import { GLOW_ZENITH, MOON_HAZE, SKY_EXPOSURE, SKY_FADE, STAR_FLOOR } from './terrainSky'; -import { TERRAIN } from './terrainWorld'; - -const HEADER = - '#version 300 es\nprecision highp float;\nprecision highp int;\nprecision highp sampler2D;\n'; -const f1 = (x: number) => x.toFixed(1); -const lit = (x: number) => (Number.isInteger(x) ? x.toFixed(1) : String(x)); - -export const FULLSCREEN_VERT = `${HEADER} -void main() { - vec2 p = vec2(float((gl_VertexID << 1) & 2), float(gl_VertexID & 2)); - gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0); -}`; - -const HEIGHT_STAGE = ` -uniform float uSpan; -uniform vec2 uSeed; -uniform float uTexels; -out vec4 o; - -const float BASE_AMP = 60.0; -const float BASE_FREQ = 1.0 / 520.0; -const float BASE_LIFT = 110.0; -const float CELL0 = 160.0; -const float SIDE_LEN = 3.0; -const float NORM = 0.5; -const float SLOPE_REF = 0.55; -const float DETAIL = 1.5; -const float AMP0 = 11.0; -const float HLO = 20.0, HHI = 200.0; - -float easeOut(float t) { t = clamp(t, 0.0, 1.0); return 1.0 - (1.0 - t) * (1.0 - t); } -float powInv(float t, float p) { return 1.0 - pow(1.0 - t, p); } - -float height(vec2 xz) { - vec4 fg = cultmath_fbm_grad(vec3(xz * BASE_FREQ, 0.0), 4, 2.0, 0.45); - float h = BASE_LIFT + BASE_AMP * fg.w; - vec2 g = BASE_AMP * BASE_FREQ * fg.xy; - float target = clamp((h - HLO) / (HHI - HLO) * 2.0 - 1.0, -1.0, 1.0); - float combi = 1.0; - float amp = AMP0; - float cell = CELL0; - for (int i = 0; i < OCTAVES; i++) { - float slope = length(g); - vec2 downhill = slope > 1e-4 ? -g / slope : vec2(1.0, 0.0); - vec2 across = vec2(-downhill.y, downhill.x); - CultPhasor ph = cultmath_phacelle(vec3(xz / cell, 0.5), vec3(across * SIDE_LEN, 0.0), 0.0, NORM); - float mask = easeOut(slope / SLOPE_REF) * combi; - float faded = mix(target, ph.cos.w, mask); - h += amp * faded; - g += amp * mask * ph.cos.xy / cell; - combi = powInv(combi, DETAIL) * (1.0 - abs(ph.sin.w)); - target = faded; - amp *= 0.5; - cell *= 0.5; - } - return h; -} - -void main() { - vec2 uv = gl_FragCoord.xy / vec2(uTexels); - float h = clamp(height((uv - 0.5) * uSpan + uSeed) / ${f1(TERRAIN.hmax)}, 0.0, 1.0); - float q = floor(h * 65535.0 + 0.5); - o = vec4(floor(q / 256.0) / 255.0, mod(q, 256.0) / 255.0, 0.0, 1.0); -}`; - -/** The height-bake fragment shader: header, the part of CultMath that Phacelle and the stage reach, Phacelle, the stage. */ -export function heightFragmentSource(): string { - const math = trimGlsl(cultmath, [phacelle, HEIGHT_STAGE]); - return `${HEADER}#define OCTAVES 4\n${math}\n${phacelle}\n${HEIGHT_STAGE}`; -} - -const FETCH = ` -uniform sampler2D uHeight; -uniform int uTex; -float hAt(ivec2 t) { - t = clamp(t, ivec2(0), ivec2(uTex - 1)); - vec4 s = texelFetch(uHeight, t, 0); - return (floor(s.r * 255.0 + 0.5) * 256.0 + floor(s.g * 255.0 + 0.5)) / 65535.0 * ${f1( - TERRAIN.hmax - )}; -} -// The height at a point in texel units, bilinear over the four texels around it (the packed texture cannot be filtered by the GPU). -float hBil(vec2 p) { - ivec2 i = ivec2(floor(p)); - vec2 f = fract(p); - return mix(mix(hAt(i), hAt(i + ivec2(1, 0)), f.x), mix(hAt(i + ivec2(0, 1)), hAt(i + ivec2(1, 1)), f.x), f.y); -}`; - -export const GRID_VERT = `${HEADER} -layout(location = 0) in vec2 a_uv; -uniform mat4 uViewProj; -uniform float uSpan; -out vec2 v_uv; -out vec3 v_world; -${FETCH} -void main() { - // The grid is packed toward the centre, where the camera stands (terrainWorld.warpUv): s = 2u - 1, 0.5 + 0.5 (0.5 s + 0.5 s |s|). - vec2 s = a_uv * 2.0 - 1.0; - vec2 uv = 0.5 + 0.5 * (0.5 * s + 0.5 * s * abs(s)); - // The patch's rim sinks to zero so the grid has no cliff edge to show through the haze. - float rim = 1.0 - smoothstep(0.78, 1.0, 2.0 * max(abs(uv.x - 0.5), abs(uv.y - 0.5))); - float h = hBil(uv * float(uTex - 1)) * rim; - v_uv = uv; - v_world = vec3((uv.x - 0.5) * uSpan, h, (uv.y - 0.5) * uSpan); - gl_Position = uViewProj * vec4(v_world, 1.0); -}`; - -// Lit by the baked sky: uSun (direction), uSunColour (linear, zero when the sun is down), uAmbient; hazed toward the -// scattered sky at the horizon in the ray's azimuth (SKY_COLOUR_GLSL). -// The same arithmetic as terrainSky.shade(); the normal comes from the height map so shading carries detail finer than the mesh. -const ALBEDO_DEFINES = ` -#define ALB_SCREE_FROM ${lit(ALBEDO.screeFrom)} -#define ALB_SCREE_TO ${lit(ALBEDO.screeTo)} -#define ALB_SNOW_BAND ${lit(ALBEDO.snowBand)} -#define ALB_ROCK_HI ${lit(ALBEDO.rockHi)} -#define ALB_ROCK_LO ${lit(ALBEDO.rockLo)} -#define ALB_SNOW_HI ${lit(ALBEDO.snowHi)} -#define ALB_SNOW_LO ${lit(ALBEDO.snowLo)} -#define ALB_WOBBLE_H ${lit(ALBEDO.wobbleHeight)} -#define ALB_WOBBLE_S ${lit(ALBEDO.wobbleSlope)} -#define ALB_GRAIN_COARSE ${lit(ALBEDO.grainCoarse)} -#define ALB_GRAIN_FINE ${lit(ALBEDO.grainFine)} -#define ALB_FINE_WARP ${lit(ALBEDO.fineWarp)} -#define ALB_STRATA ${lit(ALBEDO.strata)} -#define ALB_FINE_NEAR ${lit(ALBEDO.fineNear)} -#define ALB_FINE_FAR ${lit(ALBEDO.fineFar)} -#define CAV_RADIUS ${lit(CAVITY.radius)} -#define CAV_RANGE ${lit(CAVITY.range)} -#define CAV_DARK ${lit(CAVITY.dark)} -#define CAV_LIGHT ${lit(CAVITY.light)} -`; -// The GLSL twin of skyBand.shapeToBand: clamp to 0..1, mix toward uLift to land on the floor uBand.x, or scale down to the ceiling uBand.y. -// No band is uBand = (0, 1). -export const SHAPE_SKY_GLSL = ` -uniform vec2 uBand; -uniform vec3 uLift; -const vec3 LUMA = vec3(${LUMA.map(lit).join(', ')}); -vec3 shapeSky(vec3 c) { - c = clamp(c, 0.0, 1.0); - float l = dot(c, LUMA); - if (l < uBand.x) return mix(c, uLift, (uBand.x - l) / (dot(uLift, LUMA) - l)); - if (l > uBand.y) return c * (uBand.y / l); - return c; -}`; -// The sky colour along a unit direction: scattering lifted by the exposure, tone-mapped, plus the night glow, shaped into -// the state's luminance band. The same arithmetic as terrainSky.skyColour(). uGlow is the baked horizon colour already -// scaled by how dark the sun is. -const SKY_COLOUR_GLSL = `${SCATTER_GLSL}${SHAPE_SKY_GLSL} -uniform vec3 uGlow; -vec3 skyColour(vec3 d) { - return shapeSky(1.0 - exp(-${lit(SKY_EXPOSURE)} * skyScatter(d)) + uGlow * mix(1.0, ${lit( - GLOW_ZENITH -)}, sqrt(clamp(d.y, 0.0, 1.0)))); -}`; - -export const GRID_FRAG = `${HEADER}${ALBEDO_DEFINES}${SKY_COLOUR_GLSL}${AERIAL_GLSL} -in vec2 v_uv; -in vec3 v_world; -uniform vec3 uCamera, uLightDir, uLight, uAmbient, uSoil, uScree, uRock, uSnow; -uniform float uSpan, uSnowLine, uNight, uMoonIndex; -out vec4 o; -${FETCH} -// Triplanar patterns: each projection plane's value, blended by the weights of the face's normal (terrainAlbedo.triWeights). -float wob2(vec2 q) { return sin(q.x * 0.043 + q.y * 0.017) * sin(q.y * 0.051 - q.x * 0.023); } -float waves3(vec2 q, vec2 a, vec2 b, vec2 c) { return (sin(dot(q, a)) + sin(dot(q, b)) + sin(dot(q, c))) / 3.0; } -// The fine octave's coordinates pushed by a slower sine each (terrainAlbedo wavesWarped): three plane waves alone make a regular lattice. -vec2 warpq(vec2 q) { return q + ALB_FINE_WARP * vec2(sin(q.y * 0.55 + 1.3), sin(q.x * 0.47 + 0.7)); } -void main() { - // Normal from the bilinear height at a continuous position, a stencil 1.5 texels each side: smooth across texel borders. - vec2 p = v_uv * float(uTex - 1); - float texel = uSpan / float(uTex - 1); - float dx = hBil(p + vec2(1.5, 0.0)) - hBil(p - vec2(1.5, 0.0)); - float dz = hBil(p + vec2(0.0, 1.5)) - hBil(p - vec2(0.0, 1.5)); - vec3 n = normalize(vec3(-dx, 3.0 * texel, -dz)); - vec3 tw = pow(abs(n), vec3(4.0)); - tw /= tw.x + tw.y + tw.z; - vec2 qx = v_world.zy, qy = v_world.xz, qz = v_world.xy; - // Procedural albedo, no texture reads; the same arithmetic as terrainAlbedo.albedoAt(). - float w = tw.x * wob2(qx) + tw.y * wob2(qy) + tw.z * wob2(qz); - float h = v_world.y + ALB_WOBBLE_H * w; - float flat_ = n.y + ALB_WOBBLE_S * w; - vec3 ground = mix(uSoil, uScree, smoothstep(ALB_SCREE_FROM, ALB_SCREE_TO, h)); - float snow = smoothstep(uSnowLine - ALB_SNOW_BAND, uSnowLine + ALB_SNOW_BAND, h) * smoothstep(ALB_SNOW_LO, ALB_SNOW_HI, flat_); - float rockW = 1.0 - smoothstep(ALB_ROCK_LO, ALB_ROCK_HI, flat_); - vec3 albedo = mix(mix(ground, uSnow, snow), uRock, rockW); - // Surface grain and rock strata, the same arithmetic as terrainAlbedo.grainAt(). - float coarse = tw.x * waves3(qx, vec2(0.31, 0.27), vec2(-0.22, 0.35), vec2(0.38, -0.12)) + tw.y * waves3(qy, vec2(0.31, 0.27), vec2(-0.22, 0.35), vec2(0.38, -0.12)) + tw.z * waves3(qz, vec2(0.31, 0.27), vec2(-0.22, 0.35), vec2(0.38, -0.12)); - float fine = tw.x * waves3(warpq(qx), vec2(1.1, 0.7), vec2(-0.8, 1.2), vec2(1.3, -0.6)) + tw.y * waves3(warpq(qy), vec2(1.1, 0.7), vec2(-0.8, 1.2), vec2(1.3, -0.6)) + tw.z * waves3(warpq(qz), vec2(1.1, 0.7), vec2(-0.8, 1.2), vec2(1.3, -0.6)); - float near = 1.0 - smoothstep(ALB_FINE_NEAR, ALB_FINE_FAR, length(v_world - uCamera)); - float layers = sin(v_world.y * 0.9 + w * 3.0); - albedo *= max(0.0, 1.0 + ALB_GRAIN_COARSE * coarse + ALB_GRAIN_FINE * near * fine + ALB_STRATA * rockW * layers); - // Cavity: a point lower than its surroundings sits in shade, one higher catches light (terrainAlbedo.cavityAt). Shader-only, from the height map, - // read bilinear at a continuous position so it does not snap to a texel (that made the shading blocks of one texel, 3 m). - float cr = CAV_RADIUS / texel; - float curv = 0.25 * (hBil(p + vec2(cr, 0.0)) + hBil(p - vec2(cr, 0.0)) + hBil(p + vec2(0.0, cr)) + hBil(p - vec2(0.0, cr))) - hBil(p); - float cavity = 1.0 - CAV_DARK * clamp(curv / CAV_RANGE, 0.0, 1.0) + CAV_LIGHT * clamp(-curv / CAV_RANGE, 0.0, 1.0); - vec3 lit = albedo * cavity * (uLight * max(dot(n, uLightDir), 0.0) + uAmbient * (0.5 + 0.5 * n.y)); - vec3 toSurface = v_world - uCamera; - float dist = length(toSurface); - // Aerial perspective (terrainSky.aerialPerspective): the baked volume by this ray's elevation, azimuth from the light and path. - vec3 ray = toSurface / dist; - float el = min(degrees(asin(clamp(ray.y, -1.0, 1.0))), 0.0); - vec2 hz = ray.xz, sz = uSun.xz; - float az = (length(hz) < 1e-4 || length(sz) < 1e-4) ? 0.0 : degrees(acos(clamp(dot(normalize(hz), normalize(sz)), -1.0, 1.0))); - float km = dist * ${lit(AP_DISTANCE_SCALE / 1000)}; - vec4 ap = aerial(uSunIndex, el, az, km); - vec3 L = ap.rgb; - // The moon lights the haze from where the sun is mirrored above the horizon, sharing its azimuth; a starlight floor stays. - if (uNight > 0.0) L += uNight * vec3(${MOON_HAZE.map(lit).join( - ', ' - )}) * aerial(uMoonIndex, el, az, km).rgb; - vec3 haze = 1.0 - exp(-${lit(SKY_EXPOSURE)} * L) + uNight * ap.a * vec3(${STAR_FLOOR.map( - lit -).join(', ')}); - // Past SKY_FADE the surface is the sky at the horizon in this ray's azimuth, the colour the sky pass draws there (terrainSky.aerialPerspective). - float toSky = smoothstep(${lit(SKY_FADE[0])}, ${lit(SKY_FADE[1])}, dist); - vec3 horizon = skyColour(vec3(ray.x, 0.0, ray.z)); - o = vec4(pow(mix(lit * (1.0 - ap.a) + haze, horizon, toSky), vec3(1.0 / 2.2)), 1.0); -}`; - -// The sky behind: the baked scattering tables by the view ray's elevation and azimuth from the sun, a sun disc, and a -// dither of +-0.5/255 on the 8-bit output so the dusk glow does not band. -const DISC = { - inner: Math.cos((0.5 * Math.PI) / 180), - outer: Math.cos((1.1 * Math.PI) / 180), - gain: 6.0, -}; -export const SKY_FRAG = `${HEADER}${SKY_COLOUR_GLSL} -uniform vec3 uSunColour; -uniform vec3 uRight, uUp, uForward; -uniform vec2 uSize; -uniform float uTanHalf; -out vec4 o; -void main() { - vec2 ndc = gl_FragCoord.xy / uSize * 2.0 - 1.0; - vec3 d = normalize(uForward + ndc.x * uTanHalf * uSize.x / uSize.y * uRight + ndc.y * uTanHalf * uUp); - vec3 c = skyColour(d) + uSunColour * ${lit(DISC.gain)} * smoothstep(${DISC.outer}, ${ - DISC.inner -}, dot(d, uSun)); - float dither = fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715)))) - 0.5; - o = vec4(pow(c, vec3(1.0 / 2.2)) + dither / 255.0, 1.0); -}`; diff --git a/src/app/features/scene/terrain/terrainSky.test.ts b/src/app/features/scene/terrain/terrainSky.test.ts deleted file mode 100644 index f409471a..00000000 --- a/src/app/features/scene/terrain/terrainSky.test.ts +++ /dev/null @@ -1,322 +0,0 @@ -/* eslint-disable no-restricted-syntax -- tests loop over skies, normals and distances */ -import { AP_DISTANCE_SCALE } from './terrainScatter'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { baked } from '../../../../sky/baked'; -import { - chooseSky, - coldness, - glowColour, - hazeColour, - hexToLinear, - nightness, - shade, - SKY, - skyAtSun, - skyData, - skyColour, - sunDirection, - aerialPerspective, - SKY_FADE, - metresToKm, - groundLight, - HAZE_K, - HAZE_POWER, - START_TURNS, - Vec3, -} from './terrainSky'; - -const UP = [0, 1, 0] as const; -const luma = (c: readonly number[]) => 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]; -/** Unit view direction at an elevation (degrees) and an azimuth clockwise from north. */ -const look = (el: number, az: number): Vec3 => { - const e = (el * Math.PI) / 180; - const a = (az * Math.PI) / 180; - return [Math.sin(a) * Math.cos(e), Math.sin(e), -Math.cos(a) * Math.cos(e)]; -}; - -describe('the baked sky is read, not copied', () => { - it('SKY carries Void’s numbers: sun, ambient, horizon', () => { - for (const name of ['midnight', 'noonday'] as const) { - const b = baked[name]; - expect(SKY[name].elevation).toBe(b.sun.elevation_deg); - expect(SKY[name].azimuth).toBe(b.sun.azimuth_deg); - expect(SKY[name].direct).toEqual(b.sun.color_linear); - expect(SKY[name].ambient).toEqual(b.ambient_linear); - expect(SKY[name].horizon).toEqual(hexToLinear(b.horizon_hex)); - } - }); - - it('keeps the two moments apart: night sun below the horizon, noon sun well above', () => { - expect(SKY.midnight.elevation).toBeLessThan(0); - expect(SKY.noonday.elevation).toBeGreaterThan(30); - }); - - it('sunDirection is a unit vector with y = sin(elevation), north at -z, south at +z', () => { - for (const d of Object.values(SKY)) { - const s = sunDirection(d); - expect(Math.hypot(...s)).toBeCloseTo(1, 9); - expect(s[1]).toBeCloseTo(Math.sin((d.elevation * Math.PI) / 180), 9); - } - expect(sunDirection({ ...SKY.noonday, elevation: 0, azimuth: 0 })[2]).toBeCloseTo(-1, 9); - expect(sunDirection({ ...SKY.noonday, elevation: 0, azimuth: 180 })[2]).toBeCloseTo(1, 9); - }); - - it('hexToLinear decodes sRGB', () => { - expect(hexToLinear('#000000')).toEqual([0, 0, 0]); - expect(hexToLinear('#ffffff')).toEqual([1, 1, 1]); - expect(hexToLinear('#808080')[0]).toBeCloseTo(0.2158, 3); - }); -}); - -describe('a sun at any elevation (skyAtSun)', () => { - it('lights nothing under the horizon and fades in across the last degrees, as sun.js does', () => { - expect(skyAtSun(-2).direct).toEqual([0, 0, 0]); - expect(skyAtSun(-30).direct).toEqual([0, 0, 0]); - const at = (e: number) => luma(skyAtSun(e).direct); - expect(at(0.3)).toBeGreaterThan(0); - expect(at(0.3)).toBeLessThan(at(1.5)); - expect(at(1.5)).toBeLessThan(at(60)); - }); - - it('agrees with the baked noon sun colour where they overlap, to a couple of percent', () => { - const want = SKY.noonday.direct; - const got = skyAtSun(SKY.noonday.elevation).direct; - got.forEach((v, i) => expect(Math.abs(v / want[i] - 1)).toBeLessThan(0.02)); - }); - - it('the sun goes red as it sets: less blue left in the direct light at 2 degrees than at 45', () => { - const lo = skyAtSun(2).direct; - const hi = skyAtSun(45).direct; - expect(lo[2] / lo[0]).toBeLessThan(0.6 * (hi[2] / hi[0])); - }); - - it('ambient and horizon run from the midnight bake to the noonday one as the sun climbs', () => { - expect(luma(skyAtSun(-30).ambient)).toBeCloseTo(luma(SKY.midnight.ambient), 9); - expect(luma(skyAtSun(60).ambient)).toBeCloseTo(luma(SKY.noonday.ambient), 9); - expect(luma(skyAtSun(5).ambient)).toBeGreaterThan(luma(SKY.midnight.ambient)); - expect(luma(skyAtSun(5).ambient)).toBeLessThan(luma(SKY.noonday.ambient)); - expect(skyAtSun(10, 270).azimuth).toBe(270); - }); -}); - -describe('lighting', () => { - it('noonday lights an upward face with the sun; midnight has none', () => { - expect(luma(SKY.noonday.direct)).toBeGreaterThan(0.5); - expect(SKY.midnight.direct).toEqual([0, 0, 0]); - }); - - it('shade never goes negative on any normal at either sky, at any distance', () => { - for (const d of [...Object.values(SKY), skyAtSun(-3), skyAtSun(1)]) - for (const n of [UP, [0, -1, 0], [1, 0, 0], [-0.6, 0.0, 0.8]] as const) - for (const dist of [0, 100, 5000]) - for (const ch of shade(d, [0.3, 0.3, 0.3], n, dist, look(-5, 40))) - expect(ch).toBeGreaterThanOrEqual(0); - }); - - it('a face turned to the noon sun is brighter than one turned away; at midnight the two match to ambient', () => { - const toSun = sunDirection(SKY.noonday); - const away = [-toSun[0], 0, -toSun[2]] as const; - const view = look(-5, 0); - const lit = luma(shade(SKY.noonday, [0.5, 0.5, 0.5], toSun, 0, view)); - const dark = luma(shade(SKY.noonday, [0.5, 0.5, 0.5], away, 0, view)); - expect(lit).toBeGreaterThan(3 * dark); - const m = (n: readonly [number, number, number]) => - shade(SKY.midnight, [0.5, 0.5, 0.5], n, 0, view); - expect(luma(m(UP))).toBeGreaterThan(0); // moonlit fill, not black - expect(luma(m(UP))).toBeLessThan(0.12); - }); - - it('noon is much brighter than midnight, ambient included', () => { - expect(luma(SKY.noonday.ambient)).toBeGreaterThan(2 * luma(SKY.midnight.ambient)); - const view = look(-5, 0); - expect(luma(shade(SKY.noonday, [0.4, 0.4, 0.4], UP, 0, view))).toBeGreaterThan( - 3 * luma(shade(SKY.midnight, [0.4, 0.4, 0.4], UP, 0, view)) - ); - }); - - it('the cold tint (albedo) is 0 with the sun up and 1 once it is below -6', () => { - expect(coldness(SKY.noonday)).toBe(0); - expect(coldness(SKY.midnight)).toBe(1); - expect(hazeColour(SKY.noonday)).toEqual(SKY.noonday.horizon); - }); -}); - -describe('the scattered sky', () => { - it('noon is blue overhead: more blue than red, much brighter than the night glow', () => { - const zenith = skyColour(SKY.noonday, [0, 1, 0]); - expect(zenith[2]).toBeGreaterThan(1.5 * zenith[0]); - expect(luma(zenith)).toBeGreaterThan(5 * luma(skyColour(SKY.midnight, [0, 1, 0]))); - zenith.forEach((v) => expect(v).toBeLessThan(1)); - }); - - it('a sun at the horizon reddens the sky toward it and darkens it away', () => { - const dusk = skyAtSun(-1, 270); - const toward = skyColour(dusk, look(3, 270)); - const away = skyColour(dusk, look(3, 90)); - const blueShare = (c: Vec3) => c[2] / (c[0] + c[1] + c[2]); - expect(blueShare(toward)).toBeLessThan(blueShare(away)); - expect(luma(toward)).toBeGreaterThan(3 * luma(away)); - }); - - it('under a deep night sun the tables are black and only the glow remains, brightest at the horizon', () => { - const d = SKY.midnight; - const horizon = skyColour(d, look(0, 180)); - const zenith = skyColour(d, [0, 1, 0]); - horizon.forEach((v, i) => expect(v).toBeCloseTo(d.horizon[i], 6)); - expect(luma(zenith)).toBeLessThan(luma(horizon)); - expect(luma(zenith)).toBeGreaterThan(0.5 * luma(horizon)); - }); - - it('the night glow fades out as the sun reaches the horizon', () => { - expect(nightness(-10)).toBe(1); - expect(nightness(5)).toBe(0); - expect(glowColour(SKY.noonday)).toEqual([0, 0, 0]); - expect(glowColour(SKY.midnight)).toEqual(SKY.midnight.horizon); - expect(luma(glowColour(skyAtSun(-2)))).toBeLessThan(luma(glowColour(skyAtSun(-6)))); - }); - - it('is continuous in the sun’s elevation through dusk: no step between neighbours', () => { - const at = (e: number) => luma(skyColour(skyAtSun(e, 270), look(10, 200))); - for (let e = -20; e < 30; e += 0.5) { - expect(Math.abs(at(e + 0.5) - at(e))).toBeLessThan(0.05); - } - }); -}); - -describe('aerial perspective', () => { - const ray = (el: number, az: number): Vec3 => look(el, az); - const along = (d: typeof SKY.midnight, el: number, az: number, m: number) => - aerialPerspective(d, ray(el, az), m); - - it('opacity grows with distance from nothing at the eye toward the far value, never past 1', () => { - let prev = along(SKY.noonday, -2, 200, 0).alpha; - expect(prev).toBe(0); - for (const m of [10, 100, 400, 800, 1000, 1300]) { - const a = along(SKY.noonday, -2, 200, m).alpha; - expect(a).toBeGreaterThan(prev); - expect(a).toBeLessThanOrEqual(1); - prev = a; - } - }); - - it('leaves the near ground its own colour and takes the far ridges', () => { - expect(along(SKY.noonday, -2, 200, 100).alpha).toBeLessThan(0.15); - expect(along(SKY.noonday, -2, 200, SKY_FADE[0]).alpha).toBeGreaterThan(0.1); - }); - - it('the in-scatter is a function of the baked volume: its colour is bluer than the sun far by day', () => { - const far = along(SKY.noonday, -2, 90, SKY_FADE[0]).colour; - expect(far[2]).toBeGreaterThan(far[0]); - }); - - it('haze toward a setting sun is brighter than away from it, and red, not blue (the sun is reddened on its way)', () => { - const dusk = skyAtSun(2, 270); - const toward = along(dusk, -1, 270, SKY_FADE[0]).colour; - const away = along(dusk, -1, 90, SKY_FADE[0]).colour; - expect(luma(toward)).toBeGreaterThan(3 * luma(away)); - expect(toward[0]).toBeGreaterThan(toward[2]); - }); - - it('night haze is a deep blue floor, not grey: dark, blue over red by a wide margin, brighter than black', () => { - const c = along(SKY.midnight, -2, 0, SKY_FADE[0]).colour; - expect(luma(c)).toBeGreaterThan(0.0003); - expect(luma(c)).toBeLessThan(0.08); - expect(c[2]).toBeGreaterThan(2.5 * c[0]); - expect(luma(along(SKY.noonday, -2, 0, SKY_FADE[0]).colour)).toBeGreaterThan(5 * luma(c)); - }); - - it('moonlight lights the night haze toward the moon more than away from it', () => { - const moon = groundLight(SKY.midnight).dir; - const toward = aerialPerspective(SKY.midnight, [moon[0], -0.02, moon[2]], SKY_FADE[0]).colour; - const away = aerialPerspective(SKY.midnight, [-moon[0], -0.02, -moon[2]], SKY_FADE[0]).colour; - expect(luma(toward)).toBeGreaterThan(luma(away)); - }); - - it('with distance a dark surface rises toward the haze and its own colour is lost', () => { - const d = SKY.noonday; - const view = ray(-4, 200); - const dark = (x: number) => luma(shade(d, [0.02, 0.02, 0.02], UP, x, view)); - expect(dark(SKY_FADE[0])).toBeGreaterThan(dark(100)); - const own = (x: number) => 1 - aerialPerspective(d, view, x).alpha; - expect(own(SKY_FADE[0])).toBeLessThan(0.9 * own(100)); - }); - - it('is continuous in the sun elevation through dusk: no step between neighbours', () => { - const at = (e: number) => luma(along(skyAtSun(e, 270), -1, 270, SKY_FADE[0]).colour); - for (let e = -12; e < 12; e += 0.5) expect(Math.abs(at(e + 0.5) - at(e))).toBeLessThan(0.45); - }); - - it('far terrain is the sky: past the fade it is the horizon sky colour in its azimuth, by day, dusk and night, whatever it was', () => { - for (const [d, az] of [ - [SKY.midnight, 0], - [skyAtSun(-1, 90), 90], - [skyAtSun(2, 270), 200], - [SKY.noonday, 120], - ] as const) { - const view = ray(-0.5, az); - const hz = skyColour(d, [view[0], 0, view[2]]); - const far = aerialPerspective(d, view, SKY_FADE[1]); - expect(far.alpha).toBe(1); - for (let i = 0; i < 3; i += 1) expect(far.colour[i]).toBeCloseTo(hz[i], 9); - expect(shade(d, [0.5, 0.5, 0.5], UP, SKY_FADE[1] + 500, view)).toEqual(far.colour); - } - }); - - it('the metres-to-km law is the scene metres times the baked distance scale', () => { - expect(metresToKm(1000)).toBeCloseTo(AP_DISTANCE_SCALE, 9); - expect(metresToKm(-5)).toBe(0); - }); -}); - -describe('ground light and haze', () => { - it("at night the ground has a moon above the horizon on the sun's mirrored side, and a lifted ambient; by day it is the sun", () => { - const night = groundLight(SKY.midnight); - expect(night.dir[1]).toBeGreaterThan(0.5); - expect(luma(night.colour)).toBeGreaterThan(0.03); - expect(luma(night.ambient)).toBeGreaterThan(2 * luma(SKY.midnight.ambient)); - const day = groundLight(SKY.noonday); - expect(Array.from(day.dir)).toEqual(Array.from(sunDirection(SKY.noonday))); - expect(Array.from(day.colour)).toEqual(Array.from(SKY.noonday.direct)); - expect(Array.from(day.ambient)).toEqual(Array.from(SKY.noonday.ambient)); - }); - - it('the ground light is continuous through sunset', () => { - const at = (e: number) => luma(groundLight(skyAtSun(e)).colour); - for (let e = -10; e < 10; e += 0.5) expect(Math.abs(at(e + 0.5) - at(e))).toBeLessThan(0.35); - }); - - it('the camera starts with the noon sun off its axis, so the light rakes the relief', () => { - const yaw = 2 * Math.PI * START_TURNS; - const forward = [Math.sin(yaw), 0, -Math.cos(yaw)]; - const sun = sunDirection(SKY.noonday); - const along = (forward[0] * sun[0] + forward[2] * sun[2]) / Math.hypot(sun[0], sun[2]); - expect(Math.abs(along)).toBeLessThan(0.4); - }); -}); - -describe('chooseSky: an explicit sky wins over the page URL', () => { - const at = (search: string) => vi.stubGlobal('window', { location: { search } }); - afterEach(() => { - vi.unstubAllGlobals(); - }); - - it('lets the URL steer when no option is given', () => { - at('?sun=40&az=90'); - expect(chooseSky({})).toEqual(skyAtSun(40, 90)); - at('?sky=noonday'); - expect(chooseSky({})).toEqual(skyData('noonday')); - }); - - it('prefers an explicit baked sky to ?sun= and ?sky=', () => { - at('?sun=40&az=90&sky=noonday'); - expect(chooseSky({ sky: 'midnight' })).toEqual(skyData('midnight')); - at('?sky=noonday'); - expect(chooseSky({ sky: 'midnight' })).toEqual(skyData('midnight')); - }); - - it('prefers an explicit sun to ?sun=, and takes no azimuth from ?az=', () => { - at('?sun=40&az=90&sky=noonday'); - expect(chooseSky({ sun: { elevation: 2 } })).toEqual(skyAtSun(2, undefined)); - expect(chooseSky({ sun: { elevation: 2, azimuth: 10 } })).toEqual(skyAtSun(2, 10)); - }); -}); diff --git a/src/app/features/scene/terrain/terrainSky.ts b/src/app/features/scene/terrain/terrainSky.ts deleted file mode 100644 index 92a2ab22..00000000 --- a/src/app/features/scene/terrain/terrainSky.ts +++ /dev/null @@ -1,253 +0,0 @@ -// Lighting, haze and sky for the terrain scene, as pure functions of one sky's baked numbers (src/sky/baked.ts, Void's -// bake, GameCult/Void PR #22). No DOM, no GL. The fragment shaders do the same arithmetic with these results as uniforms. -import { baked } from '../../../../sky/baked'; -import { hexToLinear, shapeToBand } from '../skyBand'; -import type { SkyBand } from '../skyBand'; -import { - AP_DISTANCE_SCALE, - aerialAt, - HORIZON_FLOOR, - scatterRadiance, - transmittanceAt, -} from './terrainScatter'; - -export type SkyName = 'midnight' | 'noonday'; -export type Vec3 = readonly [number, number, number]; - -export interface SkyData { - /** Degrees above the horizon, no refraction. Negative: the sun is down. */ - elevation: number; - /** Degrees clockwise from north. */ - azimuth: number; - /** Sun colour at normal incidence, linear RGB. Black when the sun is down. */ - direct: Vec3; - /** Sky ambient on an upward surface, linear RGB; at night a moonlit floor, not black. */ - ambient: Vec3; - /** The horizon, linear RGB: the baked `horizon_hex`. */ - horizon: Vec3; - /** The luminance band `skyColour` shapes the sky into (skyBand.ts); absent: the physical sky as it is. */ - band?: SkyBand; -} - -const RAD = Math.PI / 180; -const clamp01 = (x: number) => Math.min(1, Math.max(0, x)); -const smooth = (a: number, b: number, x: number) => { - const t = clamp01((x - a) / (b - a)); - return t * t * (3 - 2 * t); -}; -const mixVec = (a: Vec3, b: Vec3, t: number): Vec3 => - [0, 1, 2].map((i) => a[i] + (b[i] - a[i]) * t) as unknown as Vec3; - -export const isSkyName = (s: unknown): s is SkyName => s === 'midnight' || s === 'noonday'; - -export { hexToLinear }; - -const fromBaked = (b: typeof baked.midnight | typeof baked.noonday): SkyData => ({ - elevation: b.sun.elevation_deg, - azimuth: b.sun.azimuth_deg, - direct: b.sun.color_linear, - ambient: b.ambient_linear, - horizon: hexToLinear(b.horizon_hex), -}); - -export const SKY: Record = { - midnight: fromBaked(baked.midnight), - noonday: fromBaked(baked.noonday), -}; - -export const skyData = (name: SkyName): SkyData => SKY[name]; - -/** - * A sky for a sun at any elevation, between the two baked ones. The sun's colour is the baked transmittance at - * that elevation, faded out across the disc's last degrees the way sun.js does (gone at -0.83, whole by 1.5); - * ambient and horizon blend from the midnight bake to the noonday one as the sun climbs from -8 to 25 degrees. - */ -export function skyAtSun(elevation: number, azimuth: number = SKY.noonday.azimuth): SkyData { - const day = smooth(-8, 25, elevation); - const fade = smooth(-0.83, 1.5, elevation); - const t = transmittanceAt(Math.max(elevation, -4)); - return { - elevation, - azimuth, - direct: [t[0] * fade, t[1] * fade, t[2] * fade], - ambient: mixVec(SKY.midnight.ambient, SKY.noonday.ambient, day), - horizon: mixVec(SKY.midnight.horizon, SKY.noonday.horizon, day), - }; -} - -/** Unit vector toward the sun: x east, y up, z south (so azimuth 0, north, is -z). */ -export function sunDirection(d: SkyData): Vec3 { - const el = d.elevation * RAD; - const az = d.azimuth * RAD; - return [Math.sin(az) * Math.cos(el), Math.sin(el), -Math.cos(az) * Math.cos(el)]; -} - -/** 0 with the sun well up, 1 once it is below -6 degrees (civil twilight over): the night notion the palette shares. */ -export const coldness = (d: SkyData): number => 1 - smooth(-6, 25, d.elevation); - -/** The colour distance fades to when the air has nothing to scatter: the baked horizon. Albedo tints toward it at night. */ -export const hazeColour = (d: SkyData): Vec3 => d.horizon; - -/** Sky radiance (see the sun's `skyScatter` in terrainScatter.ts) is for unit sun irradiance; this lifts it to the image. EYEBALLED. */ -export const SKY_EXPOSURE = 45; -/** How far the night glow dims from the horizon to the zenith (1 at the horizon). EYEBALLED. */ -export const GLOW_ZENITH = 0.75; - -/** 1 with the sun below -4 degrees, 0 above 4: where the midnight horizon colour stands in for light the single-scattering tables lack. */ -export const nightness = (elevation: number): number => 1 - smooth(-4, 4, elevation); - -/** The night glow colour: the midnight bake's horizon, fading out as the sun nears the horizon (whatever horizon the day blend gives `d`). */ -export const glowColour = (d: SkyData): Vec3 => { - const k = nightness(d.elevation); - const h = SKY.midnight.horizon; - return [h[0] * k, h[1] * k, h[2] * k]; -}; - -/** - * Linear colour of the sky along a unit view direction (x east, y up, z south): the baked single-scattering - * radiance for this sun, lifted by SKY_EXPOSURE and tone-mapped `1 - exp(-x)`, plus the night glow, which sits - * brightest at the horizon; at and below the horizon, the horizon's colour; then shaped into `d.band` when it has one. - * The fragment shader does the same. - */ -export function skyColour(d: SkyData, dir: Vec3): Vec3 { - const el = Math.max(HORIZON_FLOOR, Math.asin(Math.min(1, Math.max(-1, dir[1]))) / RAD); - const sun = sunDirection(d); - const h = Math.hypot(dir[0], dir[2]); - const s = Math.hypot(sun[0], sun[2]); - const az = - h < 1e-4 || s < 1e-4 - ? 0 - : Math.acos(Math.min(1, Math.max(-1, (dir[0] * sun[0] + dir[2] * sun[2]) / (h * s)))) / RAD; - const r = scatterRadiance(d.elevation, el, az); - const glow = glowColour(d); - const shape = 1 + (GLOW_ZENITH - 1) * Math.sqrt(clamp01(dir[1])); - const c = [0, 1, 2].map( - (i) => 1 - Math.exp(-SKY_EXPOSURE * r[i]) + glow[i] * shape - ) as unknown as Vec3; - return d.band ? shapeToBand(c, d.band) : c; -} - -/** - * Aerial perspective: the baked volume of src/sky/scatter.js (after Hillaire 2020, see there for what follows the paper - * and what does not), looked up by the view ray relative to the light and the metres to the surface. The surface keeps - * (1 - alpha) of its own colour (alpha = 1 - mean transmittance, a grey transmittance as the paper) and gains the in-scatter L, - * lifted by the sky's exposure and tone-mapped the way the sky is, so far ground meets the sky's colour. SHORTCUT: the path is - * the scene's metres times AP_DISTANCE_SCALE (a real atmosphere is nearly clear over 3 km). - */ -export const metresToKm = (metres: number): number => - (Math.max(0, metres) / 1000) * AP_DISTANCE_SCALE; - -/** Moonlight's irradiance on the haze, relative to the sun's 1, at full night. EYEBALLED, far above a real moon (about 3e-6) as the sky exposure is. */ -export const MOON_HAZE: Vec3 = [0.0004, 0.0007, 0.0018]; -/** Starlight and airglow scattered by the air, added to the in-scatter in proportion to alpha, at full night: a deep blue floor, not grey. EYEBALLED. */ -export const STAR_FLOOR: Vec3 = [0.0006, 0.0012, 0.0045]; - -/** - * Metres from the eye over which the terrain gives itself up to the sky: past the far end a surface is the sky's own - * colour at the horizon in its azimuth (`skyColour` flat along the horizon, night glow included), so the patch's rim - * meets the sky above and beyond it with no seam. The volume alone is only ~40% opaque by then. EYEBALLED. - */ -export const SKY_FADE: readonly [number, number] = [600, 1350]; - -/** Haze in front of a surface seen along `dir` (unit, eye to surface) `distance` metres away: the colour it adds and the surface's loss. */ -export function aerialPerspective( - d: SkyData, - dir: Vec3, - distance: number -): { colour: Vec3; alpha: number } { - const el = Math.min(0, Math.asin(Math.min(1, Math.max(-1, dir[1]))) / RAD); - const sun = sunDirection(d); - const h = Math.hypot(dir[0], dir[2]); - const s = Math.hypot(sun[0], sun[2]); - const az = - h < 1e-4 || s < 1e-4 - ? 0 - : Math.acos(Math.min(1, Math.max(-1, (dir[0] * sun[0] + dir[2] * sun[2]) / (h * s)))) / RAD; - const km = metresToKm(distance); - const night = nightness(d.elevation); - const day = aerialAt(d.elevation, el, az, km); - const L = [...day.L]; - if (night > 0) { - // The moon stands where the sun is mirrored above the horizon (groundLight), so it shares the sun's azimuth. - const moon = aerialAt(Math.abs(d.elevation), el, az, km); - for (let i = 0; i < 3; i += 1) L[i] += MOON_HAZE[i] * night * moon.L[i]; - } - const horizon = skyColour(d, [dir[0], 0, dir[2]]); - const f = smooth(SKY_FADE[0], SKY_FADE[1], distance); - const colour = [0, 1, 2].map( - (i) => - (1 - f) * (1 - Math.exp(-SKY_EXPOSURE * L[i]) + STAR_FLOOR[i] * night * day.alpha) + - f * horizon[i] - ) as unknown as Vec3; - return { colour, alpha: (1 - f) * day.alpha + f }; -} - -/** Added to the ambient on a dark sky, scaled by `nightness`: the baked night floor is too dark to show any form on a phone. */ -export const NIGHT_AMBIENT_LIFT = 3; -/** Cool light from the mirror of the sun's below-horizon position, linear, scaled by `nightness`: gives the terrain a lit side at night. */ -export const MOON_COLOUR: Vec3 = [0.05, 0.07, 0.13]; - -/** The light on the ground: the sun, or at night the moon standing where the sun is mirrored above the horizon. Continuous through sunset. */ -export function groundLight(d: SkyData): { dir: Vec3; colour: Vec3; ambient: Vec3 } { - const sun = sunDirection(d); - const k = nightness(d.elevation); - return { - dir: [sun[0], Math.abs(sun[1]), sun[2]], - colour: [0, 1, 2].map((i) => d.direct[i] + MOON_COLOUR[i] * k) as unknown as Vec3, - ambient: [0, 1, 2].map((i) => d.ambient[i] * (1 + NIGHT_AMBIENT_LIFT * k)) as unknown as Vec3, - }; -} - -/** - * The heading the camera starts at, in turns from north: the noonday sun a hundred degrees to its right, so the light - * rakes across the relief instead of flattening it from behind. Fixed, so `?az=` still moves the sun in the picture. - */ -export const START_TURNS = ((SKY.noonday.azimuth - 100) / 360 + 1) % 1; - -/** - * Linear colour of a surface seen along the unit direction `view` (from the eye to the surface): lambert from - * the ground light plus ambient (full on an upward face, half on a vertical one, none on a downward one: `0.5 + 0.5 n.y`), - * then aerial perspective (`aerialPerspective`). `normal` is a unit vector. Never negative. - */ -export function shade(d: SkyData, albedo: Vec3, normal: Vec3, distance: number, view: Vec3): Vec3 { - const light = groundLight(d); - const sun = light.dir; - const lambert = Math.max(0, normal[0] * sun[0] + normal[1] * sun[1] + normal[2] * sun[2]); - const hemi = 0.5 + 0.5 * normal[1]; - const haze = aerialPerspective(d, view, distance); - return [0, 1, 2].map((i) => { - const lit = albedo[i] * (light.colour[i] * lambert + light.ambient[i] * Math.max(0, hemi)); - return lit * (1 - haze.alpha) + haze.colour[i]; - }) 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 - * (`urlSky`), else midnight. A band, when given, shapes whichever sky that is. - */ -export function chooseSky(opts: { - sky?: SkyName; - sun?: { elevation: number; azimuth?: number }; - band?: SkyBand; -}): SkyData { - const banded = (d: SkyData): SkyData => (opts.band ? { ...d, band: opts.band } : d); - 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')); -} diff --git a/src/app/features/scene/terrain/terrainStars.test.ts b/src/app/features/scene/terrain/terrainStars.test.ts deleted file mode 100644 index c1231bd8..00000000 --- a/src/app/features/scene/terrain/terrainStars.test.ts +++ /dev/null @@ -1,241 +0,0 @@ -/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-empty-function -- DOM stubs, as the other scene tests */ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { SKY, skyAtSun } from './terrainSky'; -import { - BRIGHTEN, - createTerrainStars, - elevationOf, - ELEVATION_TOP, - FRAME_MS, - horizonY, - PERIOD, - nightColours, - project, - starGain, -} from './terrainStars'; -import { CAMERA, view } from './terrainWorld'; -import { isNight, makeStars } from '../ridge/stars'; - -/** A 2D context that only counts: arcs painted and clears since the last reset. */ -function fakeCtx() { - const c = { - arcs: [] as Array<[number, number, number]>, - clears: 0, - alpha: 1, - alphas: [] as number[], - }; - const ctx: any = { - clearRect: () => { - c.clears += 1; - c.arcs = []; - c.alphas = []; - }, - beginPath() {}, - fill() { - c.alphas.push(ctx.globalAlpha); - }, - arc: (x: number, y: number, r: number) => c.arcs.push([x, y, r]), - globalAlpha: 1, - fillStyle: '', - }; - return { c, ctx }; -} - -let overlay: any; -let ctx2d: ReturnType; -let parent: any; -beforeEach(() => { - ctx2d = fakeCtx(); - overlay = { - style: {}, - width: 0, - height: 0, - setAttribute: vi.fn(), - getContext: vi.fn(() => ctx2d.ctx), - remove: vi.fn(), - }; - parent = { appendChild: vi.fn() }; - vi.stubGlobal('document', { createElement: () => overlay }); - vi.stubGlobal('window', { devicePixelRatio: 1, innerWidth: 390, innerHeight: 844 }); -}); -afterEach(() => vi.unstubAllGlobals()); - -const glCanvas = (w = 390, h = 844) => - ({ clientWidth: w, clientHeight: h, parentElement: parent } as any); - -describe('which skies get stars', () => { - it('the field is placed against the baked night gradient, which the ridge module calls dark', () => { - expect(isNight(nightColours())).toBe(true); - }); - - it('starGain: full below -12 degrees, none above -6, smooth and monotone between', () => { - expect(starGain(-44.6)).toBe(1); - expect(starGain(-12)).toBe(1); - expect(starGain(-6)).toBe(0); - expect(starGain(45.2)).toBe(0); - expect(starGain(-9)).toBeCloseTo(0.5, 9); - let prev = 1; - for (let e = -12; e <= -6; e += 0.25) { - expect(starGain(e)).toBeLessThanOrEqual(prev); - prev = starGain(e); - } - }); - - it('noonday gets no layer and no element', () => { - expect(createTerrainStars(glCanvas(), SKY.noonday)).toBeNull(); - expect(parent.appendChild).not.toHaveBeenCalled(); - }); - - it('twilight is a fade, not a gate: a sun at -9 degrees paints the stars at half alpha', () => { - createTerrainStars(glCanvas(), skyAtSun(-9))?.draw(0); - const half = Math.max(...ctx2d.c.alphas); - ctx2d.c.alphas = []; - createTerrainStars(glCanvas(), SKY.midnight)?.draw(0); - expect(half).toBeGreaterThan(0); - expect(half / Math.max(...ctx2d.c.alphas)).toBeCloseTo(0.5, 6); - expect(createTerrainStars(glCanvas(), skyAtSun(-6.5))).not.toBeNull(); - expect(createTerrainStars(glCanvas(), skyAtSun(-6))).toBeNull(); - }); - - it('midnight adds one overlay to the canvas parent; dispose removes it', () => { - const s = createTerrainStars(glCanvas(), SKY.midnight)!; - expect(parent.appendChild).toHaveBeenCalledWith(overlay); - s.dispose(); - expect(overlay.remove).toHaveBeenCalledOnce(); - }); - - it('is absent without a parent or a 2D context', () => { - expect( - createTerrainStars({ ...glCanvas(), parentElement: null } as any, SKY.midnight) - ).toBeNull(); - overlay.getContext = () => null; - expect(createTerrainStars(glCanvas(), SKY.midnight)).toBeNull(); - expect(parent.appendChild).not.toHaveBeenCalled(); - }); -}); - -describe('sky only', () => { - it('the overlay is as tall as the horizon line is low, never the whole screen', () => { - createTerrainStars(glCanvas(), SKY.midnight); - expect(overlay.height).toBe(Math.ceil(horizonY(844))); - expect(overlay.height).toBeLessThan(844 / 2); - expect(overlay.style.pointerEvents).toBe('none'); - }); - - it('a star at the horizon lands on the horizon line, one above it lands above', () => { - for (const aspect of [0.46, 1.78]) { - const h = 800; - const w = h * aspect; - const onLine = project(0.2, 0, w, h)!; - expect(onLine.y).toBeCloseTo(horizonY(h), 5); - expect(project(0.2, 0.05, w, h)!.y).toBeLessThan(horizonY(h)); - } - }); - - it('the camera eye clears the peaks, so the horizon line bounds the terrain', () => { - expect(CAMERA.eye).toBeGreaterThan(256); - }); - - it('every painted star is above the horizon line, at any heading', () => { - const s = createTerrainStars(glCanvas(), SKY.midnight)!; - for (let k = 0; k < 40; k += 1) { - s.draw(k / 40); - for (const [, y] of ctx2d.c.arcs) expect(y).toBeLessThanOrEqual(overlay.height); - } - }); - - it('agrees with the camera the terrain draws: the projection matches view()', () => { - const w = 390; - const h = 844; - const turns = 0.137; - const v = view(w / h, turns); - const yaw = 2 * Math.PI * turns; - const az = yaw + 0.1; - const e = 0.15; - const d = [Math.sin(az) * Math.cos(e), Math.sin(e), -Math.cos(az) * Math.cos(e)]; - const dot = (a: number[], b: readonly number[]) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; - const t = Math.tan(CAMERA.fov / 2); - const f = dot(d, v.forward); - const nx = dot(d, v.right) / f / (t * (w / h)); - const ny = dot(d, v.up) / f / t; - const at = project(0.1, e, w, h)!; - expect(at.x).toBeCloseTo(((nx + 1) / 2) * w, 6); - expect(at.y).toBeCloseTo(((1 - ny) / 2) * h, 6); - }); -}); - -describe('turning with the camera', () => { - it('stars are on screen, and slide sideways as the camera turns', () => { - const s = createTerrainStars(glCanvas(), SKY.midnight)!; - s.draw(0); - const first = ctx2d.c.arcs.slice(); - expect(first.length).toBeGreaterThan(10); - s.draw(0.002); - const later = ctx2d.c.arcs; - expect(later).not.toEqual(first); - const m = (a: number[][]) => a.reduce((t, p) => t + p[0], 0) / a.length; - expect(m(later)).not.toBeCloseTo(m(first), 1); - }); - - it('repeats every PERIOD of heading', () => { - const s = createTerrainStars(glCanvas(), SKY.midnight)!; - s.draw(0.1); - const a = ctx2d.c.arcs.map((p) => p.map((n) => Math.round(n * 1e3))); - s.draw(0.1 + PERIOD / (2 * Math.PI)); - expect(ctx2d.c.arcs.map((p) => p.map((n) => Math.round(n * 1e3)))).toEqual(a); - }); - - it('the field fills the screen top and thins toward the horizon, inside the elevation band', () => { - expect(elevationOf(0)).toBeCloseTo(ELEVATION_TOP, 9); - expect(elevationOf(0.78)).toBeCloseTo(0, 9); - }); -}); - -describe('brightness', () => { - it('draws every star at BRIGHTEN times its ridge-field alpha, capped at 1', () => { - createTerrainStars(glCanvas(), SKY.midnight)?.draw(0); - const want = makeStars(nightColours(), 390, 844).map((st) => Math.min(1, st.alpha * BRIGHTEN)); - ctx2d.c.alphas.forEach((a) => expect(want.some((w) => Math.abs(w - a) < 1e-9)).toBe(true)); - // and it is brighter than the ridge field's own top alpha - const top = Math.max(...makeStars(nightColours(), 390, 844).map((st) => st.alpha)); - expect(Math.max(...ctx2d.c.alphas)).toBeGreaterThan(top * 1.5); - }); -}); - -describe('motion', () => { - it('with no clock every star is at base and a repeat draw repaints; no twinkle', () => { - const s = createTerrainStars(glCanvas(), SKY.midnight)!; - s.draw(0.3); - const alphas = ctx2d.c.alphas.slice(); - s.draw(0.3); - expect(ctx2d.c.alphas).toEqual(alphas); - }); - - it('with the clock the twinklers swing away from base, and the repaint is throttled', () => { - const s = createTerrainStars(glCanvas(), SKY.midnight)!; - s.draw(0.3); - const still = ctx2d.c.alphas.slice(); - let moved = false; - for (let t = 1; t < 60 && !moved; t += 1.7) { - s.draw(0.3, t); - moved = ctx2d.c.alphas.some((a, i) => a !== still[i]); - } - expect(moved).toBe(true); - const clears = ctx2d.c.clears; - s.draw(0.3, 100); - s.draw(0.3, 100 + FRAME_MS / 4000); - expect(ctx2d.c.clears).toBe(clears + 1); - }); - - it('resize refits the canvas and the next draw repaints at once', () => { - const c = glCanvas(); - const s = createTerrainStars(c, SKY.midnight)!; - s.draw(0.1, 5); - c.clientHeight = 400; - s.resize(); - expect(overlay.height).toBe(Math.ceil(horizonY(400))); - const clears = ctx2d.c.clears; - s.draw(0.1, 5.001); - expect(ctx2d.c.clears).toBe(clears + 1); - }); -}); diff --git a/src/app/features/scene/terrain/terrainStars.ts b/src/app/features/scene/terrain/terrainStars.ts deleted file mode 100644 index cc310bff..00000000 --- a/src/app/features/scene/terrain/terrainStars.ts +++ /dev/null @@ -1,172 +0,0 @@ -// The terrain scene's star layer: the ridge scene's starfield (ridge/stars.ts: placement, alpha, tint, the -// rolling twinkle schedule) on a 2D overlay canvas above the WebGL canvas, faded by the sun's elevation (starGain). -// -// The WebGL canvas is opaque, so the overlay sits on top and is cut to the sky: it is only as tall as the -// horizon line is low on screen. The camera has no roll and the eye (CAMERA.eye) is above the highest peak -// (TERRAIN.hmax), so terrain never rises above that line and a star above the horizon is never over terrain. -// -// Stars turn with the camera, as sky does: the ridge field's x becomes azimuth, repeated every PERIOD (so 400 -// stars fill a sky that only ever shows 55 deg to ~120 deg of it), and y becomes elevation from the horizon -// up to ELEVATION_TOP, the top of the screen. Placement is projected with the terrain's own camera (CAMERA, -// the yaw the terrain draws at), nothing is baked, and the whole overlay is redrawn at most every FRAME_MS: a -// visible star is a few arcs on a canvas a quarter of the screen tall. The stars stop when the terrain stops: -// the layer only paints when Terrain.ts draws, and a draw with no clock (reduced motion, still tier, resize) -// paints every star at base brightness. - -import { baked } from '../../../../sky/baked'; -import type { SkyColours, Srgb } from '../ridge/skyColour'; -import { activeAt, makeStars, SKY_STOPS, Star } from '../ridge/stars'; -import { SkyData } from './terrainSky'; -import { CAMERA } from './terrainWorld'; - -/** Azimuth the star field repeats at (radians); wider than any horizontal field of view the layer is shown at. */ -export const PERIOD = (2 * Math.PI) / 3; -/** Elevation of the field's top, radians: a little above the top edge of the screen at the camera's pitch. */ -export const ELEVATION_TOP = (16 * Math.PI) / 180; -/** The overlay repaints at most this often while the terrain turns (12 px/s on a phone: under half a pixel a step). */ -export const FRAME_MS = 33; -/** The twinkle schedule is re-read this often; the swings are 2 to 7 s. */ -const TWINKLE_MS = 50; - -const hex = (h: string): Srgb => - [1, 3, 5].map((i) => parseInt(h.slice(i, i + 2), 16)) as unknown as Srgb; - -/** - * How much of the starfield shows with the sun at `elevation` degrees: all of it below -12 (where the baked - * scattering goes dark: the planet's shadow covers every sunlit air path), none above -6 (civil twilight), a smooth - * fade between. Not a dark/day gate: a sun at -9 shows the stars at half. - */ -export function starGain(elevation: number): number { - const t = Math.min(1, Math.max(0, (elevation + 12) / 6)); - return 1 - t * t * (3 - 2 * t); -} - -/** The ridge star module's view of the night sky it places stars against: the baked midnight gradient's zenith, middle and horizon stops. */ -export function nightColours(): SkyColours { - const g = baked.midnight.gradient; - return { - top: hex(g[0]), - mid: hex(g[Math.floor(g.length / 2)]), - horizon: hex(g[g.length - 1]), - }; -} - -/** Screen height in px below which there is no sky: where the horizon plane meets the image, a straight line. */ -export const horizonY = (height: number): number => - height * (0.5 - Math.tan(CAMERA.pitch) / Math.tan(CAMERA.fov / 2) / 2); - -export interface Placed { - x: number; - y: number; -} - -/** - * Where a star at azimuth `da` from the camera's heading and elevation `e` (radians) lands in a `w` x `h` px - * viewport, or null if it is behind or off the screen. The same camera as `view()` in terrainWorld.ts - * (forward, right and up are its basis written out for a camera with yaw and pitch only). - */ -export function project(da: number, e: number, w: number, h: number): Placed | null { - const p = CAMERA.pitch; - const ce = Math.cos(e); - const front = ce * Math.cos(p) * Math.cos(da) - Math.sin(e) * Math.sin(p); - if (front <= 0.01) return null; - const tanHalf = Math.tan(CAMERA.fov / 2); - const nx = (ce * Math.sin(da)) / front / (tanHalf * (w / h)); - const ny = (ce * Math.sin(p) * Math.cos(da) + Math.sin(e) * Math.cos(p)) / front / tanHalf; - if (Math.abs(nx) > 1.05) return null; - return { x: ((nx + 1) / 2) * w, y: ((1 - ny) / 2) * h }; -} - -/** Elevation in radians for a ridge-field height fraction y (0 zenith side .. SKY_STOPS.horizon at the horizon). */ -export const elevationOf = (y: number): number => ELEVATION_TOP * (1 - y / SKY_STOPS.horizon); - -const wrap = (a: number): number => a - PERIOD * Math.round(a / PERIOD); - -/** The terrain overlay draws the ridge field's stars brighter and a little larger: a phone's small, hazy sky needs it to read. */ -export const BRIGHTEN = 2.4; -export const GROW = 1.3; - -export interface TerrainStars { - /** Paint for the camera `turns` into its turn (0..1). `seconds` is the clock while the terrain moves; absent: every star at base. */ - draw(turns: number, seconds?: number): void; - /** Re-fit the overlay to the canvas's current size; the next draw repaints. */ - resize(): void; - dispose(): void; -} - -/** The layer for `canvas`'s parent, or null: the sun is too high for any star, no parent, no 2D context. */ -export function createTerrainStars(canvas: HTMLCanvasElement, sky: SkyData): TerrainStars | null { - const colours = nightColours(); - const gain = starGain(sky.elevation); - const parent = canvas.parentElement; - if (!parent || gain <= 0) return null; - const el = document.createElement('canvas'); - const ctx = el.getContext?.('2d'); - if (!ctx) return null; - el.setAttribute?.('aria-hidden', 'true'); - Object.assign(el.style, { position: 'absolute', left: '0', top: '0', pointerEvents: 'none' }); - parent.appendChild(el); - - let w = 1; - let h = 1; - let scale = 1; - let field: Star[] = []; - let lit: Array<{ star: Star; az: number; e: number }> = []; - let gains = new Map(); - let gainsAt = -Infinity; - let last = -Infinity; - - const fit = () => { - w = canvas.clientWidth || window.innerWidth; - h = canvas.clientHeight || window.innerHeight; - scale = Math.min(window.devicePixelRatio || 1, 2); - const sky = Math.max(1, Math.ceil(horizonY(h))); - el.width = Math.max(1, Math.round(w * scale)); - el.height = Math.max(1, Math.round(sky * scale)); - el.style.width = `${w}px`; - el.style.height = `${sky}px`; - field = makeStars(colours, w, h); - lit = field.map((star) => ({ star, az: star.x * PERIOD, e: elevationOf(star.y) })); - gains = new Map(); - gainsAt = -Infinity; - }; - - const paint = (turns: number, seconds: number | undefined) => { - ctx.clearRect(0, 0, el.width, el.height); - if (seconds !== undefined && seconds * 1000 - gainsAt >= TWINKLE_MS) { - gains = new Map(activeAt(field.length, seconds).map((a) => [a.star, a.gain])); - gainsAt = seconds * 1000; - } - const yaw = 2 * Math.PI * turns; - lit.forEach(({ star, az, e }, i) => { - const da = wrap(az - yaw); - const twinkle = seconds === undefined ? 1 : gains.get(i) ?? 1; - ctx.globalAlpha = Math.min(1, star.alpha * twinkle * BRIGHTEN) * gain; - ctx.fillStyle = star.fill; - [da, da > 0 ? da - PERIOD : da + PERIOD].forEach((d) => { - const at = project(d, e, w, h); - if (!at || at.y < 0 || at.y > el.height / scale) return; - ctx.beginPath(); - ctx.arc(at.x * scale, at.y * scale, star.r * GROW * scale, 0, 2 * Math.PI); - ctx.fill(); - }); - }); - ctx.globalAlpha = 1; - }; - - fit(); - return { - draw(turns, seconds) { - if (seconds !== undefined && seconds * 1000 - last < FRAME_MS) return; - last = seconds === undefined ? -Infinity : seconds * 1000; - paint(turns, seconds); - }, - resize() { - fit(); - last = -Infinity; - }, - dispose() { - el.remove(); - }, - }; -} diff --git a/src/app/features/scene/terrain/terrainWorld.test.ts b/src/app/features/scene/terrain/terrainWorld.test.ts deleted file mode 100644 index 70a9d763..00000000 --- a/src/app/features/scene/terrain/terrainWorld.test.ts +++ /dev/null @@ -1,140 +0,0 @@ -/* eslint-disable no-restricted-syntax -- tests loop over skies, normals and distances */ -import { describe, expect, it } from 'vitest'; -import { - buildGrid, - CAMERA, - GRID, - seedOffset, - TERRAIN, - triangleCount, - view, - warpUv, -} from './terrainWorld'; -import { heightFragmentSource } from './terrainShaders'; - -describe('seed', () => { - it('same seed, same offset, so the baked height map is the same; a different seed moves it', () => { - expect(seedOffset(7)).toEqual(seedOffset(7)); - expect(seedOffset(0)).toEqual([0, 0]); - expect(seedOffset(1)).not.toEqual(seedOffset(2)); - }); - - it('the height-bake source is a pure function of nothing but the world constants', () => { - expect(heightFragmentSource()).toBe(heightFragmentSource()); - const src = heightFragmentSource(); - expect(src.startsWith('#version 300 es')).toBe(true); - expect(src).toContain('cultmath_phacelle'); - expect(src).toContain(`/ ${TERRAIN.hmax.toFixed(1)}`); - expect(src).toContain('uSeed'); - }); -}); - -describe('grid', () => { - it('has (n+1)^2 vertices in 0..1 and 2n^2 triangles that index them all in range', () => { - const n = 8; - const g = buildGrid(n); - expect(g.uv.length).toBe((n + 1) * (n + 1) * 2); - expect(g.indices.length / 3).toBe(triangleCount(n)); - expect(Math.max(...g.indices)).toBe((n + 1) * (n + 1) - 1); - expect(Math.min(...g.uv)).toBe(0); - expect(Math.max(...g.uv)).toBe(1); - }); - - it('each tier fits a 32-bit index and the cheap tiers stay cheap', () => { - // 524k at 512 quads (low), 1.18M at 768 (full): Meta asked for denser terrain on 2026-11-10, up from 205k at 320. No - // phone frame time is measured (SwiftShader only); kept as a ceiling so a bigger grid is a deliberate change. - expect(triangleCount(GRID.low.grid)).toBeLessThan(540000); - expect(triangleCount(GRID.full.grid)).toBeLessThan(1200000); - (['still', 'low', 'full'] as const).forEach((t) => - expect((GRID[t].grid + 1) ** 2).toBeLessThan(2 ** 32) - ); - expect(GRID.full.grid).toBeGreaterThan(GRID.low.grid); - expect(GRID.still.tex).toBeLessThanOrEqual(GRID.low.tex); - }); -}); - -describe('camera', () => { - const project = (m: Float32Array, p: number[]) => { - const x = m[0] * p[0] + m[4] * p[1] + m[8] * p[2] + m[12]; - const y = m[1] * p[0] + m[5] * p[1] + m[9] * p[2] + m[13]; - const z = m[2] * p[0] + m[6] * p[1] + m[10] * p[2] + m[14]; - const w = m[3] * p[0] + m[7] * p[1] + m[11] * p[2] + m[15]; - return { x: x / w, y: y / w, z: z / w, w }; - }; - - it('a point straight ahead lands in the middle of the screen, in front, inside the depth range', () => { - for (const turns of [0, 0.25, 0.6]) { - const v = view(0.46, turns); - const p = v.eye.map((e, i) => e + 800 * v.forward[i]); - const s = project(v.viewProj, p); - expect(s.w).toBeGreaterThan(0); - expect(s.x).toBeCloseTo(0, 5); - expect(s.y).toBeCloseTo(0, 5); - expect(Math.abs(s.z)).toBeLessThan(1); - } - }); - - it('looks down by the pitch, and one full turn comes back to the same heading', () => { - const a = view(1, 0); - const b = view(1, 1); - expect(a.forward[1]).toBeCloseTo(-Math.sin(CAMERA.pitch), 9); - for (let i = 0; i < 3; i += 1) expect(a.forward[i]).toBeCloseTo(b.forward[i], 9); - }); - - it('sits above the highest possible terrain, so the eye is never inside a hill', () => { - expect(CAMERA.eye).toBeGreaterThan(TERRAIN.hmax); - }); - - it('the basis is orthonormal', () => { - const v = view(0.5, 0.37); - const dot = (a: number[], b: number[]) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; - expect(dot(v.right, v.up)).toBeCloseTo(0, 9); - expect(dot(v.right, v.forward)).toBeCloseTo(0, 9); - expect(dot(v.up, v.forward)).toBeCloseTo(0, 9); - expect(Math.hypot(...v.up)).toBeCloseTo(1, 9); - }); -}); - -describe('grid resolution', () => { - // The mesh must carry what the height map shows: where a quad is wider than a couple of texels the shading (read from the - // height map) has gullies the polygons cannot, and the near ground reads as hard-edged facets (the 'terrain · low' phone - // shots, 2026-11-09). Metres from the patch centre to the nearest ground the camera can see: the bottom view ray meets - // the highest terrain, hmax below the eye, at (eye - hmax) / tan(pitch + fov / 2). - const nearest = (CAMERA.eye - TERRAIN.hmax) / Math.tan(CAMERA.pitch + CAMERA.fov / 2); - const spacingAt = (grid: number, metres: number) => { - for (let i = 0; i < grid; i += 1) { - const x = (warpUv((i + 1) / grid) - 0.5) * TERRAIN.span; - if (x >= metres) return (warpUv((i + 1) / grid) - warpUv(i / grid)) * TERRAIN.span; - } - throw new Error('beyond the patch'); - }; - - it.each(['still', 'low', 'full'] as const)( - 'the %s tier has a quad no wider than two height texels at the nearest ground the camera can see', - (tier) => { - const { grid, tex } = GRID[tier]; - expect(spacingAt(grid, nearest)).toBeLessThanOrEqual((2 * TERRAIN.span) / (tex - 1)); - } - ); - - it('a dearer tier never has a coarser mesh', () => { - expect(GRID.low.grid).toBeGreaterThanOrEqual(GRID.still.grid); - expect(GRID.full.grid).toBeGreaterThanOrEqual(GRID.low.grid); - }); -}); - -describe('warpUv', () => { - it('maps the patch onto itself, monotonic, centre fixed', () => { - expect(warpUv(0)).toBe(0); - expect(warpUv(1)).toBe(1); - expect(warpUv(0.5)).toBe(0.5); - for (let i = 0; i < 100; i += 1) expect(warpUv((i + 1) / 100)).toBeGreaterThan(warpUv(i / 100)); - }); - - it('packs the vertices toward the camera at the centre: finer there, coarser at the rim, than a plain grid', () => { - const plain = 1 / 192; - const step = (u: number) => warpUv(u + 1 / 192) - warpUv(u); - expect(step(0.5)).toBeLessThan(0.6 * plain); - expect(step(0.99)).toBeGreaterThan(1.3 * plain); - }); -}); diff --git a/src/app/features/scene/terrain/terrainWorld.ts b/src/app/features/scene/terrain/terrainWorld.ts deleted file mode 100644 index 82a16bfb..00000000 --- a/src/app/features/scene/terrain/terrainWorld.ts +++ /dev/null @@ -1,140 +0,0 @@ -// The terrain scene's fixed numbers, grid and camera, as pure functions. No DOM, no GL. -// The height field itself is a function of world position written in GLSL (terrainShaders.ts), baked once -// into a texture; the CPU owns only where it is looked at from, and the seed offset it is sampled at. - -/** Metres across the patch, and the height in metres that normalised height 1.0 stands for. */ -export const TERRAIN = { span: 3000, hmax: 256 }; - -/** - * Grid quads per side and height-map texels per side, by tier. 'still' draws one frame, so it takes the cheap pair. The - * mesh is dense enough that a quad is at most two texels wide at the nearest ground (terrainWorld.test.ts); a coarser mesh - * under shading read from the height map shows as hard-edged facets and stepped crests. - */ -export const GRID = { - still: { grid: 320, tex: 1024 }, - low: { grid: 512, tex: 1024 }, - full: { grid: 768, tex: 2048 }, -} as const; - -/** The camera: at the patch centre, above the highest peak, turning slowly and looking a little down. */ -export const CAMERA = { - eye: 330, - pitch: (13 * Math.PI) / 180, - fov: (55 * Math.PI) / 180, - near: 10, - far: 6000, - /** Seconds for one full turn. */ - seconds: 420, -}; - -/** The height map's sample offset in metres for a seed: same seed, same terrain. Seed 0 is the origin. */ -export function seedOffset(seed: number): [number, number] { - const s = Math.trunc(seed); - return [(s * 7919) % 65536, (s * 104729) % 65536]; -} - -/** - * Where grid coordinate `u` (0..1 across the patch) lands in the patch, 0..1. The camera stands at the centre, so the - * grid is packed toward it: with s = 2u - 1 the spacing grows as 0.5 + |s| of the plain grid's, about half of it at the - * centre and half again as much at the rim. The vertex shader does the same arithmetic (terrainShaders.ts GRID_VERT). - */ -export const warpUv = (u: number): number => { - const s = 2 * u - 1; - return 0.5 + 0.5 * (0.5 * s + 0.5 * s * Math.abs(s)); -}; - -export const triangleCount = (grid: number): number => 2 * grid * grid; - -/** Vertex grid in unit uv: (grid + 1)^2 positions, then the two-triangle-per-quad index list. */ -export function buildGrid(grid: number): { uv: Float32Array; indices: Uint32Array } { - const uv = new Float32Array((grid + 1) * (grid + 1) * 2); - for (let j = 0, k = 0; j <= grid; j += 1) - for (let i = 0; i <= grid; i += 1, k += 2) { - uv[k] = i / grid; - uv[k + 1] = j / grid; - } - const indices = new Uint32Array(grid * grid * 6); - for (let j = 0, k = 0; j < grid; j += 1) - for (let i = 0; i < grid; i += 1, k += 6) { - const a = j * (grid + 1) + i; - indices.set([a, a + grid + 1, a + 1, a + 1, a + grid + 1, a + grid + 2], k); - } - return { uv, indices }; -} - -export interface View { - /** Column-major perspective * view. */ - viewProj: Float32Array; - eye: [number, number, number]; - /** Camera basis in world space, for the sky pass. */ - right: [number, number, number]; - up: [number, number, number]; - forward: [number, number, number]; -} - -const norm = (a: number[]): [number, number, number] => { - const l = Math.hypot(a[0], a[1], a[2]) || 1; - return [a[0] / l, a[1] / l, a[2] / l]; -}; -const cross = (a: number[], b: number[]): [number, number, number] => [ - a[1] * b[2] - a[2] * b[1], - a[2] * b[0] - a[0] * b[2], - a[0] * b[1] - a[1] * b[0], -]; - -/** The camera `turns` full turns round (0..1 wraps), for a viewport aspect (width / height). */ -export function view(aspect: number, turns: number): View { - const yaw = 2 * Math.PI * turns; - const cp = Math.cos(CAMERA.pitch); - const forward = norm([Math.sin(yaw) * cp, -Math.sin(CAMERA.pitch), -Math.cos(yaw) * cp]); - const right = norm(cross(forward, [0, 1, 0])); - const up = cross(right, forward); - const eye: [number, number, number] = [0, CAMERA.eye, 0]; - const t = (a: number[]) => -(a[0] * eye[0] + a[1] * eye[1] + a[2] * eye[2]); - const v = [ - right[0], - up[0], - -forward[0], - 0, - right[1], - up[1], - -forward[1], - 0, - right[2], - up[2], - -forward[2], - 0, - t(right), - t(up), - -t(forward), - 1, - ]; - const f = 1 / Math.tan(CAMERA.fov / 2); - const { near: n, far } = CAMERA; - const p = [ - f / aspect, - 0, - 0, - 0, - 0, - f, - 0, - 0, - 0, - 0, - (far + n) / (n - far), - -1, - 0, - 0, - (2 * far * n) / (n - far), - 0, - ]; - const viewProj = new Float32Array(16); - for (let c = 0; c < 4; c += 1) - for (let r = 0; r < 4; r += 1) { - let s = 0; - for (let k = 0; k < 4; k += 1) s += p[k * 4 + r] * v[c * 4 + k]; - viewProj[c * 4 + r] = s; - } - return { viewProj, eye, right, up, forward }; -} diff --git a/src/app/features/scene/terrain/tierLabel.test.ts b/src/app/features/scene/terrain/tierLabel.test.ts deleted file mode 100644 index e3f18871..00000000 --- a/src/app/features/scene/terrain/tierLabel.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -/* eslint-disable @typescript-eslint/no-explicit-any -- DOM stubs, as the other scene tests */ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { showTierLabel } from './tierLabel'; - -let search: string; -let appended: any[]; -const canvas = (parent: boolean) => - ({ - parentElement: parent - ? { - appendChild: (e: any) => appended.push(e), - } - : null, - } as any); - -beforeEach(() => { - search = ''; - appended = []; - vi.stubGlobal('window', { - get location() { - return { search }; - }, - }); - vi.stubGlobal('document', { - createElement: () => ({ style: {}, remove: vi.fn(), textContent: '' }), - }); -}); -afterEach(() => vi.unstubAllGlobals()); - -describe('showTierLabel', () => { - it('adds nothing in a normal build', () => { - expect(showTierLabel(canvas(true), 'full', true)).toBeNull(); - expect(appended).toHaveLength(0); - }); - - it('names the path on screen when asked with ?tierlabel=1, and removes itself', () => { - search = '?tierlabel=1'; - const remove = showTierLabel(canvas(true), 'sky-only', true); - expect(appended).toHaveLength(1); - expect(appended[0].textContent).toBe('terrain · sky-only'); - remove!(); - expect(appended[0].remove).toHaveBeenCalled(); - }); - - it('ignores ?tierlabel=1 where the overlays are not allowed (a production page)', () => { - search = '?tierlabel=1'; - expect(showTierLabel(canvas(true), 'full', false)).toBeNull(); - expect(appended).toHaveLength(0); - }); - - it('has nowhere to go without a parent', () => { - search = '?tierlabel=1'; - expect(showTierLabel(canvas(false), 'full', true)).toBeNull(); - }); -}); diff --git a/src/app/features/scene/terrain/tierLabel.ts b/src/app/features/scene/terrain/tierLabel.ts deleted file mode 100644 index 4afc8a69..00000000 --- a/src/app/features/scene/terrain/tierLabel.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { overlayRequested } from '../debugOverlays'; - -// A tiny label naming which terrain path is on screen ('full', 'low', 'still', or 'sky-only' where WebGL2 is missing), -// so a screenshot of a preview says what it shows. Built into preview builds (VITE_PREVIEW_DEMO=1), or by `?tierlabel=1` -// where the diagnostic overlays are allowed (debugOverlays.ts). -const wanted = (allowed: boolean): boolean => - import.meta.env?.VITE_PREVIEW_DEMO === '1' || overlayRequested('tierlabel', allowed); - -/** Adds the label to the canvas's parent; returns its remover, or null when no label is wanted. */ -export function showTierLabel( - canvas: HTMLCanvasElement, - text: string, - allowed: boolean -): (() => void) | null { - const parent = canvas.parentElement; - if (!parent || !wanted(allowed)) return null; - const el = document.createElement('div'); - el.textContent = `terrain · ${text}`; - Object.assign(el.style, { - position: 'absolute', - left: '2px', - top: '16px', - font: '10px monospace', - color: 'rgba(255,255,255,.75)', - background: 'rgba(0,0,0,.4)', - padding: '1px 5px', - borderRadius: '3px', - pointerEvents: 'none', - }); - parent.appendChild(el); - return () => el.remove(); -} diff --git a/src/app/features/scene/tier.ts b/src/app/features/scene/tier.ts index 265bcf8d..a7e9ad4a 100644 --- a/src/app/features/scene/tier.ts +++ b/src/app/features/scene/tier.ts @@ -17,9 +17,9 @@ export interface Capabilities { /** * 'ridge': baked parallax ridges, no WebGL (default). 'raymarch': the sphere-traced world with its tree and - * clouds. 'terrain': a baked height map on a displaced grid, lit and hazed by the baked sky (WebGL2). + * clouds. */ -export type SceneStyle = 'ridge' | 'raymarch' | 'terrain'; +export type SceneStyle = 'ridge' | 'raymarch'; export interface BackgroundSceneConfig { tier?: SceneTier; diff --git a/src/app/hooks/useSkyState.ts b/src/app/hooks/useSkyState.ts index c32979ae..9aa390de 100644 --- a/src/app/hooks/useSkyState.ts +++ b/src/app/hooks/useSkyState.ts @@ -3,9 +3,9 @@ import { getResolvedSkyState, getSkyState, subscribe, + type FixedSkyState, type SkyState, } from '../features/scene/skyState'; -import type { FixedSkyState } from '../features/scene/skyBand'; import { readCapabilities, resolveTier } from '../features/scene/tier'; import { useClientConfig } from './useClientConfig'; diff --git a/src/app/pages/auth/styles.css.ts b/src/app/pages/auth/styles.css.ts index f8a7a95b..96994a09 100644 --- a/src/app/pages/auth/styles.css.ts +++ b/src/app/pages/auth/styles.css.ts @@ -117,7 +117,7 @@ globalStyle(`${scene} ${AuthCardContent}`, { gap: config.space.S500, }); -// The footer line sits on the terrain, which is dark at its foot in every sky (luminance 0.02 at dusk), where the +// The footer line sits on the scene's ground, which is dark at its foot in every sky (luminance 0.02 at dusk), where the // sky's dark ink is unreadable. Over the scene it gets a blurred band tinted with the plate's fill and the plate's // ink, faded out at its edges so it reads as haze and not as a bar: the scene shows through and round it. A browser // without color-mix gets the plate's opaque fill, as the chat bubbles do (message/layout/layout.css.ts). The tint