From 69d8ff3fa195e0e7bb7306d11f29ea431d8f3534 Mon Sep 17 00:00:00 2001 From: Nibu Date: Fri, 6 Nov 2026 20:50:41 +0000 Subject: [PATCH] scene: analytic aerial perspective on the baked ridge layers Per-layer Beer-Lambert transmittance exp(-k d) mixes each layer toward the haze colour, with desaturation, 0-2 px edge softening (2D canvas filter, where supported) and an optional faint warm sun-side in-scatter growing with distance. All at bake time; no per-frame work. Sky colours still come only from skyColours() (gains optional sunAzimuth). Co-Authored-By: Claude Sonnet 5.5 --- src/app/features/scene/README.md | 7 + src/app/features/scene/ridge/Ridge.test.ts | 141 ++++++++++++++++++++- src/app/features/scene/ridge/Ridge.ts | 70 +++++++++- src/app/features/scene/ridge/ridgeWorld.ts | 37 +++++- src/app/features/scene/ridge/skyColour.ts | 3 + 5 files changed, 247 insertions(+), 11 deletions(-) diff --git a/src/app/features/scene/README.md b/src/app/features/scene/README.md index 1203bb84..473a92a1 100644 --- a/src/app/features/scene/README.md +++ b/src/app/features/scene/README.md @@ -18,6 +18,13 @@ means "keep the CSS ground". Everything below this section describes the opt-in and shows `n / median / p95` in a corner readout. - `ridge/skyColour.ts` `skyColours()` is the one place sky colours come from: a fixed dusk placeholder until Void's `src/sky/sun.js` `light()` lands (PR #20); replace its body, keep the signature. +- Aerial perspective (`ridge/ridgeWorld.ts` `AERIAL`, `transmittance`, `layerColour`, `edgeBlur`, `scatterAlpha`) is applied + once while the layers are baked, from the `SkyColours` the one seam returns (`sunAzimuth` optional: omit it for no + in-scatter). Layer distance d = 1 - depth; transmittance T = exp(-1.6 d) (0.24 / 0.37 / 0.58 / 1.00 far to near); colour is + `T * ground + (1 - T) * haze`, then chroma drops by `0.5 (1 - T)`; the edge is blurred up to 2 px (canvas pixels at DPR 1, + via the 2D `filter`, skipped where unsupported, e.g. Safari); a faint warm in-scatter (at most 0.16 alpha) peaks at the + sun's azimuth. Nothing runs per frame. The in-scatter lobe is painted into each layer, so it drifts with the layer + rather than staying fixed under the sun; that is a known approximation until the sun is a real, fixed light. - `harness/scene/bundle.cjs ridge` builds a standalone page (`?tier=`, `?probe=1`). - Not yet measured on a phone: see the PR description. diff --git a/src/app/features/scene/ridge/Ridge.test.ts b/src/app/features/scene/ridge/Ridge.test.ts index 5bb8fc6c..bb35209e 100644 --- a/src/app/features/scene/ridge/Ridge.test.ts +++ b/src/app/features/scene/ridge/Ridge.test.ts @@ -2,7 +2,19 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { createRidgeScene } from './Ridge'; import { fbmPeriodic, valueNoisePeriodic, hash2 } from './noise'; import { FrameSampler, frameStats, SLOW_P95_MS, WARMUP_FRAMES, WINDOW_MS } from './probe'; -import { FBM, LAYERS, layerColour, layerSize, profile, ridgeY } from './ridgeWorld'; +import { + AERIAL, + FBM, + LAYERS, + edgeBlur, + hazeColour, + layerColour, + layerSize, + profile, + ridgeY, + scatterAlpha, + transmittance, +} from './ridgeWorld'; import { skyColours } from './skyColour'; import { startBackgroundScene } from '../index'; @@ -89,6 +101,63 @@ describe('ridge profile', () => { }); }); +describe('aerial perspective', () => { + const sky = skyColours(); + const lum = (c: readonly number[]) => 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]; + const chroma = (c: readonly number[]) => Math.max(...c) - Math.min(...c); + const far = LAYERS[0]; + const near = LAYERS[LAYERS.length - 1]; + + it('transmittance is Beer-Lambert in distance: 1 at the viewer, exp(-k d) behind, strictly falling', () => { + expect(transmittance(near)).toBe(1); + for (const l of LAYERS) + expect(transmittance(l)).toBeCloseTo(Math.exp(-AERIAL.extinction * (1 - l.depth)), 12); + for (let i = 1; i < LAYERS.length; i += 1) + expect(transmittance(LAYERS[i])).toBeGreaterThan(transmittance(LAYERS[i - 1])); + // two layers' optical depths add: T(a)*T(b) = T(a+b) + const t = (d: number) => Math.exp(-AERIAL.extinction * d); + expect(t(0.3) * t(0.4)).toBeCloseTo(t(0.7), 12); + }); + + it('the nearest layer is exactly the ground colour; the farthest tends to the haze', () => { + expect(layerColour(near, sky)).toEqual([...sky.ground]); + const h = hazeColour(sky); + const f = layerColour(far, sky); + const dist = (a: readonly number[], b: readonly number[]) => + Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]); + expect(dist(f, h)).toBeLessThan(dist(sky.ground, h) * (transmittance(far) + 0.2)); + }); + + it('colour moves toward the haze and loses chroma with distance, beyond what the mix alone does', () => { + const h = hazeColour(sky); + for (const l of LAYERS.slice(0, -1)) { + const t = transmittance(l); + const c = layerColour(l, sky); + const mixed = [0, 1, 2].map((i) => sky.ground[i] * t + h[i] * (1 - t)); + expect(chroma(c)).toBeLessThan(chroma(mixed)); + expect(Math.abs(lum(c) - lum(mixed))).toBeLessThan(1.5); // desaturation keeps luma + } + }); + + it('edge softening grows with distance and is zero at the viewer', () => { + expect(edgeBlur(near)).toBe(0); + for (let i = 1; i < LAYERS.length; i += 1) + expect(edgeBlur(LAYERS[i])).toBeLessThan(edgeBlur(LAYERS[i - 1])); + expect(edgeBlur(far)).toBeLessThanOrEqual(AERIAL.blurPx); + }); + + it('in-scatter peaks at the sun azimuth, is periodic, faint, grows with distance, and is off without a sun', () => { + const az = 0.3; + const s = { ...sky, sunAzimuth: az }; + expect(scatterAlpha(far, s, az)).toBeGreaterThan(scatterAlpha(far, s, az + 0.5)); + expect(scatterAlpha(far, s, 0)).toBeCloseTo(scatterAlpha(far, s, 1), 12); + expect(scatterAlpha(far, s, az)).toBeLessThanOrEqual(AERIAL.scatter); + expect(scatterAlpha(near, s, az)).toBe(0); + expect(scatterAlpha(LAYERS[1], s, az)).toBeLessThan(scatterAlpha(far, s, az)); + expect(scatterAlpha(far, { ...sky, sunAzimuth: undefined }, az)).toBe(0); + }); +}); + describe('frame sampler', () => { const feed = (s: FrameSampler, dt: number, frames: number, from = 0) => { let t = from; @@ -177,10 +246,13 @@ function fakeEl(tag = 'div') { return el; } const draws: string[] = []; -function ctx() { - return { +function ctx(withFilter = false) { + const c: any = { + globalCompositeOperation: 'source-over', createLinearGradient: () => ({ addColorStop: vi.fn() }), - fillRect: () => draws.push('sky'), + fillRect() { + draws.push(c.globalCompositeOperation === 'source-atop' ? 'scatter' : 'sky'); + }, beginPath() {}, moveTo() {}, lineTo() {}, @@ -189,6 +261,8 @@ function ctx() { drawImage: () => draws.push('flatten'), set fillStyle(_v: unknown) {}, }; + if (withFilter) c.filter = 'none'; + return c; } let rafQueue: Array<(t: number) => void>; @@ -378,3 +452,62 @@ describe('fbm', () => { } }); }); + +describe('aerial perspective in the scene', () => { + it('is baked once: one scatter fill per hazy layer, none per frame, the nearest layer has none', () => { + const { canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full' })!; + expect(draws.filter((d) => d === 'scatter')).toHaveLength(LAYERS.length - 1); + const before = draws.length; + runFrames(16.7, 400); + expect(draws.length).toBe(before); + s.dispose(); + }); + + it('a sky without a sun bakes no scatter', () => { + const { canvas } = host(); + const s = createRidgeScene({ + canvas, + tier: 'full', + sky: { ...skyColours(), sunAzimuth: undefined }, + })!; + expect(draws.filter((d) => d === 'scatter')).toHaveLength(0); + s.dispose(); + }); + + it('softens with the canvas filter where it exists, blur scaled by DPR, tiled so the wrap does not fade', () => { + const { parent, canvas } = host(); + const filters: string[] = []; + const orig = (document as any).createElement; + (document as any).createElement = (t: string) => { + const el = orig(t); + el.getContext = vi.fn(() => { + const c = ctx(true); + let f = 'none'; + Object.defineProperty(c, 'filter', { + get: () => f, + set: (v: string) => { + f = v; + filters.push(v); + }, + }); + return c; + }); + return el; + }; + const s = createRidgeScene({ canvas, tier: 'full' })!; + const blurs = filters.filter((f) => f !== 'none'); + expect(blurs).toHaveLength(LAYERS.length - 1); // nearest is sharp + expect(blurs[0]).toBe(`blur(${edgeBlur(LAYERS[0]) * 2}px)`); // DPR 2 + expect(parent.children).toHaveLength(1 + LAYERS.length); + s.dispose(); + }); + + it("'still' tier keeps the sky and flattens the aerial layers without extra elements", () => { + const { parent, canvas } = host(); + createRidgeScene({ canvas, tier: 'still' }); + expect(parent.children).toEqual([canvas]); + expect(draws.filter((d) => d === 'sky')).toHaveLength(1); + expect(draws.filter((d) => d === 'flatten')).toHaveLength(LAYERS.length); + }); +}); diff --git a/src/app/features/scene/ridge/Ridge.ts b/src/app/features/scene/ridge/Ridge.ts index e315b554..218d7c65 100644 --- a/src/app/features/scene/ridge/Ridge.ts +++ b/src/app/features/scene/ridge/Ridge.ts @@ -1,7 +1,16 @@ import type { Scene, SceneOptions } from '../Scene'; import { FrameSampler, FrameStats } from './probe'; import { skyColours, SkyColours, Srgb } from './skyColour'; -import { LAYERS, hazeColour, layerColour, layerSize, ridgeY, LayerSpec } from './ridgeWorld'; +import { + LAYERS, + LayerSpec, + edgeBlur, + hazeColour, + layerColour, + layerSize, + ridgeY, + scatterAlpha, +} from './ridgeWorld'; export type RidgeOptions = Pick & { /** Show the rAF median/p95 readout. Default: the page URL has `?probe=1`. */ @@ -36,12 +45,64 @@ function paintSky(canvas: HTMLCanvasElement, sky: SkyColours): boolean { return true; } +const SCATTER_STOPS = 16; + +/** Warm in-scatter over the silhouette only (source-atop), as a horizontal gradient that repeats each period. */ +function scatter( + ctx: CanvasRenderingContext2D, + spec: LayerSpec, + sky: SkyColours, + size: { period: number; width: number; height: number } +) { + if (sky.sunAzimuth === undefined || scatterAlpha(spec, sky, sky.sunAzimuth) <= 0) return; + const g = ctx.createLinearGradient(0, 0, size.width, 0); + const [r, gr, b] = sky.horizon; + for (let k = 0; k <= 2 * SCATTER_STOPS; k += 1) { + const t = (k % SCATTER_STOPS) / SCATTER_STOPS; + g.addColorStop(k / (2 * SCATTER_STOPS), `rgba(${r},${gr},${b},${scatterAlpha(spec, sky, t)})`); + } + ctx.globalCompositeOperation = 'source-atop'; + ctx.fillStyle = g; + ctx.fillRect(0, 0, size.width, size.height); + ctx.globalCompositeOperation = 'source-over'; +} + +/** + * Soften the silhouette's edge by `px` once, where the browser's 2D canvas supports `filter` (not + * Safari, which keeps the sharp edge). One period is tiled past both ends and the bottom row extended below, + * then blurred in a single draw, so the blur sees the wrap and the ground instead of fading at borders. + */ +function soften(src: HTMLCanvasElement, px: number, period: number): HTMLCanvasElement { + const probe = context2d(src); + if (!probe || px <= 0 || !('filter' in probe)) return src; + const pad = Math.ceil(3 * px); + // The unfiltered tiling: blurring tile by tile would fade each tile's own border. + const tiled = document.createElement('canvas'); + tiled.width = src.width + 2 * period; + tiled.height = src.height + pad; + const tctx = context2d(tiled); + const out = document.createElement('canvas'); + out.width = src.width; + out.height = src.height; + const ctx = context2d(out); + if (!tctx || !ctx) return src; + for (let k = 0; k < 4; k += 1) { + tctx.drawImage(src, 0, 0, period, src.height, k * period, 0, period, src.height); + tctx.drawImage(src, 0, src.height - 1, period, 1, k * period, src.height, period, pad); + } + ctx.filter = `blur(${px}px)`; + ctx.drawImage(tiled, -period, 0); + ctx.filter = 'none'; + return out; +} + /** One ridge layer, painted once: a filled silhouette two periods wide on a plain 2D canvas. */ function paintLayer( spec: LayerSpec, sky: SkyColours, size: { period: number; width: number; height: number }, - viewH: number + viewH: number, + scale: number ): HTMLCanvasElement | null { const el = document.createElement('canvas'); el.width = size.width; @@ -62,7 +123,8 @@ function paintLayer( ctx.lineTo(size.width, size.height); ctx.closePath(); ctx.fill(); - return el; + scatter(ctx, spec, sky, size); + return soften(el, edgeBlur(spec) * scale, size.period); } interface Built { @@ -116,7 +178,7 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { if (!paintSky(canvas, sky)) return false; const layers: HTMLCanvasElement[] = []; for (const spec of LAYERS) { - const el = paintLayer(spec, sky, size, canvas.height); + const el = paintLayer(spec, sky, size, canvas.height, scale); if (!el) { layers.forEach((l) => l.remove()); return false; diff --git a/src/app/features/scene/ridge/ridgeWorld.ts b/src/app/features/scene/ridge/ridgeWorld.ts index 1f594702..048d1b50 100644 --- a/src/app/features/scene/ridge/ridgeWorld.ts +++ b/src/app/features/scene/ridge/ridgeWorld.ts @@ -46,11 +46,42 @@ export function hazeColour(sky: SkyColours): Srgb { ]; } -/** Layer colour: the haze for depth 0, the ground colour for depth 1, mixed in sRGB. */ +/** + * Aerial perspective, applied once at bake time. A layer at distance d (0 nearest, 1 farthest) is seen + * through Beer-Lambert transmittance T = exp(-extinction * d): it shows T of its own colour and 1 - T of + * the haze, then loses `desaturate * (1 - T)` of its chroma, is softened by up to `blurPx` (canvas + * pixels at scale 1) and takes a faint warm in-scatter of at most `scatter` on the sun side. + */ +export const AERIAL = { extinction: 1.6, desaturate: 0.5, blurPx: 2, scatter: 0.16 }; + +/** Distance of a layer from the viewer, 0 (nearest) .. 1 (farthest). */ +export const layerDistance = (spec: LayerSpec): number => 1 - spec.depth; + +export const transmittance = (spec: LayerSpec): number => + Math.exp(-AERIAL.extinction * layerDistance(spec)); + +/** Layer colour as seen: its own ground colour thinned by the haze between it and the eye. */ export function layerColour(spec: LayerSpec, sky: SkyColours): Srgb { const h = hazeColour(sky); - const m = (a: number, b: number) => Math.round(a + (b - a) * spec.depth); - return [m(h[0], sky.ground[0]), m(h[1], sky.ground[1]), m(h[2], sky.ground[2])]; + const t = transmittance(spec); + const seen = (i: number) => sky.ground[i] * t + h[i] * (1 - t); + const luma = 0.2126 * seen(0) + 0.7152 * seen(1) + 0.0722 * seen(2); + const keep = 1 - AERIAL.desaturate * (1 - t); + const out = (i: number) => Math.round(luma + (seen(i) - luma) * keep); + return [out(0), out(1), out(2)]; +} + +/** Edge softening for a layer, in canvas pixels at scale 1; 0 for the nearest. */ +export const edgeBlur = (spec: LayerSpec): number => AERIAL.blurPx * (1 - transmittance(spec)); + +/** + * Alpha of the warm sun-side in-scatter at `t` (0..1 across one period; periodic). Zero when the sky has + * no sun; grows with distance, peaks at the sun's azimuth. + */ +export function scatterAlpha(spec: LayerSpec, sky: SkyColours, t: number): number { + if (sky.sunAzimuth === undefined) return 0; + const lobe = 0.5 + 0.5 * Math.cos(2 * Math.PI * (t - sky.sunAzimuth)); + return AERIAL.scatter * (1 - transmittance(spec)) * lobe * lobe; } /** Integer pixel sizes of a layer for a viewport: one period wide, twice that painted, so a drift of one period loops. */ diff --git a/src/app/features/scene/ridge/skyColour.ts b/src/app/features/scene/ridge/skyColour.ts index 5dc80c1b..326fe66d 100644 --- a/src/app/features/scene/ridge/skyColour.ts +++ b/src/app/features/scene/ridge/skyColour.ts @@ -14,6 +14,8 @@ export interface SkyColours { horizon: Srgb; /** Nearest ridge: the ground colour the farther layers mix away from. */ ground: Srgb; + /** Where the sun sits across one drift period, 0..1; the layers pick up a faint warm in-scatter there. Omit for none. */ + sunAzimuth?: number; } export function skyColours(_now: Date = new Date()): SkyColours { @@ -22,5 +24,6 @@ export function skyColours(_now: Date = new Date()): SkyColours { mid: [78, 66, 150], horizon: [226, 130, 74], ground: [7, 17, 26], + sunAzimuth: 0.3, }; }