scene: ridge scene as the default background, no WebGL
Four ridge layers generated once on the CPU from CultMath value-noise fbm, each painted once to an integer-size 2D canvas over a baked sky; CSS translate3d drift only. Pauses hidden / reduced motion; falls back to a still image if rAF p95 > 33 ms over 2 s; ?probe=1 shows median/p95. Same createScene contract, tier flag still defaults off. Ray-march scene stays behind backgroundScene.style = 'raymarch'. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
14d9fa6246
commit
b48685b986
13 changed files with 939 additions and 13 deletions
|
|
@ -1,10 +1,12 @@
|
|||
// Bundles entry.ts with the scene's ?raw GLSL imports into $OUT/bundle.js plus an index.html.
|
||||
// usage: node bundle.cjs <outdir> [demo] (esbuild from NODE_PATH). `demo` bundles the standalone page.
|
||||
// usage: node bundle.cjs <outdir> [demo|ridge] (esbuild from NODE_PATH). `demo` bundles the ray-march
|
||||
// standalone page; `ridge` the ridge scene's page (open it with ?probe=1 for the cadence readout).
|
||||
const esbuild = require('esbuild');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const out = process.argv[2];
|
||||
const demo = process.argv[3] === 'demo';
|
||||
const ridge = process.argv[3] === 'ridge';
|
||||
fs.mkdirSync(out, { recursive: true });
|
||||
const rawPlugin = {
|
||||
name: 'raw',
|
||||
|
|
@ -21,7 +23,7 @@ const rawPlugin = {
|
|||
};
|
||||
esbuild
|
||||
.build({
|
||||
entryPoints: [path.join(__dirname, demo ? 'demo.ts' : 'entry.ts')],
|
||||
entryPoints: [path.join(__dirname, ridge ? 'ridgeDemo.ts' : demo ? 'demo.ts' : 'entry.ts')],
|
||||
bundle: true,
|
||||
outfile: path.join(out, 'bundle.js'),
|
||||
plugins: [rawPlugin],
|
||||
|
|
@ -29,6 +31,13 @@ esbuild
|
|||
target: 'es2020',
|
||||
})
|
||||
.then(() => {
|
||||
if (ridge) {
|
||||
fs.writeFileSync(
|
||||
path.join(out, 'index.html'),
|
||||
'<!doctype html><meta charset=utf-8><meta name=viewport content="width=device-width,initial-scale=1"><title>Ratatoskr ridge scene</title><body style="margin:0;background:#07111a"><div id=stage style="position:relative;width:100vw;height:100vh;overflow:hidden"><canvas id=c style="width:100%;height:100%;display:block"></canvas></div><script src=bundle.js></script>'
|
||||
);
|
||||
return;
|
||||
}
|
||||
fs.writeFileSync(
|
||||
path.join(out, 'index.html'),
|
||||
'<!doctype html><meta charset=utf-8><title>Ratatoskr scene: trace prepass</title><body style="margin:0;background:#000"><canvas id=c style="width:100vw;height:100vh;display:block"></canvas>' +
|
||||
|
|
|
|||
12
harness/scene/ridgeDemo.ts
Normal file
12
harness/scene/ridgeDemo.ts
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
// Standalone page for the ridge scene: full window, no host app. `?tier=still|low|full` picks the
|
||||
// tier, `?probe=1` shows the rAF median/p95 readout. Not shipped.
|
||||
import { startBackgroundScene } from '../../src/app/features/scene';
|
||||
import type { SceneTier } from '../../src/app/features/scene';
|
||||
|
||||
const q = new URLSearchParams(location.search);
|
||||
const tier = (q.get('tier') ?? 'full') as SceneTier;
|
||||
const canvas = document.getElementById('c') as HTMLCanvasElement;
|
||||
startBackgroundScene({ tier }, {}, { canvas }).then((scene) => {
|
||||
(window as unknown as { scene: unknown }).scene = scene;
|
||||
document.title = scene ? 'ridge: running' : 'ridge: unavailable (CSS ground)';
|
||||
});
|
||||
|
|
@ -1,5 +1,28 @@
|
|||
# Background scene
|
||||
|
||||
**Default: the ridge scene** (`ridge/`), no WebGL. `startBackgroundScene` runs it unless the client
|
||||
config says `backgroundScene.style: 'raymarch'`; the tier flag still defaults to `off`, and null still
|
||||
means "keep the CSS ground". Everything below this section describes the opt-in ray-march scene.
|
||||
|
||||
- `ridge/Ridge.ts` `createRidgeScene({ canvas, tier, probe?, onProbe?, sky? })` returns `{ login, dispose }` or
|
||||
null (tier `off`, no 2D context). Four ridge layers are generated once on the CPU from CultMath's
|
||||
value-noise fbm (`ridge/noise.ts`, a clean-room port, periodic so the drift loops), each painted once to a plain
|
||||
2D canvas of integer size (two periods wide; DPR 2 or more paints at 2x, otherwise 1x; no resampling between
|
||||
layers) over a baked sky gradient on the host canvas. Per frame the only motion is the browser sliding each layer with a
|
||||
CSS transform (a Web Animation of `translate3d`, 150-420 s per period, farther is slower); no script runs per frame.
|
||||
The host canvas and the layers' parent must be positioned and the canvas should fill the parent.
|
||||
- Paused when the tab is hidden; under `prefers-reduced-motion` the layers are painted but never played.
|
||||
`tier: 'still'` flattens sky and layers into the host canvas at once and leaves no extra elements.
|
||||
- Cadence guard: for the first 2 s after start (after 5 warm-up frames) rAF intervals are sampled; if their p95 is over
|
||||
33 ms the scene flattens to a still image (`ridge/probe.ts`) and stops. `?probe=1` (or `probe: true`) keeps sampling
|
||||
and shows `n / median / p95` in a corner readout.
|
||||
- `ridge/skyColour.ts` `skyColours()` is the 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.
|
||||
- `harness/scene/bundle.cjs <out> ridge` builds a standalone page (`?tier=`, `?probe=1`).
|
||||
- Not yet measured on a phone: see the PR description.
|
||||
|
||||
## Ray-march scene
|
||||
|
||||
A two-pass WebGL2 scene for the client's background canvas: an infinite terrain of CultMath
|
||||
noise with a world tree at its centre, dusk atmosphere and clouds, and a camera that pulls back
|
||||
from the tree on login. It is a self-contained module; nothing in the client imports it yet.
|
||||
|
|
|
|||
|
|
@ -397,7 +397,7 @@ describe('startBackgroundScene', () => {
|
|||
it('applies the device ceiling: saveData runs a still, one frame', async () => {
|
||||
const { gl, calls } = fakeGl();
|
||||
const scene = await startBackgroundScene(
|
||||
{ tier: 'full' },
|
||||
{ tier: 'full', style: 'raymarch' },
|
||||
{ saveData: true },
|
||||
{ canvas: asCanvas(fakeCanvas(gl)) }
|
||||
);
|
||||
|
|
@ -416,13 +416,19 @@ describe('startBackgroundScene', () => {
|
|||
const { startBackgroundScene: start } = await import('./index');
|
||||
const onCompileFail = vi.fn();
|
||||
const canvas = fakeCanvas(fakeGl().gl);
|
||||
const scene = await start({ tier: 'full' }, {}, { canvas: asCanvas(canvas), onCompileFail });
|
||||
const scene = await start(
|
||||
{ tier: 'full', style: 'raymarch' },
|
||||
{},
|
||||
{ canvas: asCanvas(canvas), onCompileFail }
|
||||
);
|
||||
expect(scene).toBeNull();
|
||||
expect(onCompileFail).toHaveBeenCalledTimes(1);
|
||||
expect(onCompileFail.mock.calls[0][0]).toBeInstanceOf(Error);
|
||||
expect(canvas.getContext).not.toHaveBeenCalled();
|
||||
// and with no callback it still does not throw
|
||||
expect(await start({ tier: 'full' }, {}, { canvas: asCanvas(canvas) })).toBeNull();
|
||||
expect(
|
||||
await start({ tier: 'full', style: 'raymarch' }, {}, { canvas: asCanvas(canvas) })
|
||||
).toBeNull();
|
||||
} finally {
|
||||
vi.doUnmock('./Scene');
|
||||
vi.resetModules();
|
||||
|
|
@ -433,7 +439,7 @@ describe('startBackgroundScene', () => {
|
|||
const { gl } = fakeGl(0);
|
||||
const onCompileFail = vi.fn();
|
||||
const scene = await startBackgroundScene(
|
||||
{ tier: 'full' },
|
||||
{ tier: 'full', style: 'raymarch' },
|
||||
{},
|
||||
{ canvas: asCanvas(fakeCanvas(gl)), onCompileFail }
|
||||
);
|
||||
|
|
|
|||
|
|
@ -100,8 +100,8 @@ export interface SceneOptions {
|
|||
}
|
||||
|
||||
export interface Scene {
|
||||
/** Texture format of the prepass start target. */
|
||||
readonly startFormat: 'RGBA32F' | 'RGBA16F';
|
||||
/** Texture format of the ray-march scene's prepass start target; the ridge scene has none. */
|
||||
readonly startFormat?: 'RGBA32F' | 'RGBA16F';
|
||||
/** Start the camera pull-back from the tree. */
|
||||
login(): void;
|
||||
dispose(): void;
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import type { Scene, SceneOptions } from './Scene';
|
|||
import { BackgroundSceneConfig, Capabilities, resolveTier } from './tier';
|
||||
|
||||
export type { Scene, SceneStats } from './Scene';
|
||||
export type { SceneTier } from './tier';
|
||||
export type { SceneStyle, SceneTier } from './tier';
|
||||
|
||||
export type StartOptions = Omit<SceneOptions, 'tier' | 'patchSource' | 'onCompileFail'> & {
|
||||
/** A shader failed to compile, or the scene chunk failed to load. The host keeps its ground. */
|
||||
|
|
@ -12,8 +12,9 @@ export type StartOptions = Omit<SceneOptions, 'tier' | 'patchSource' | 'onCompil
|
|||
/**
|
||||
* 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. Null means "keep the CSS ground", including when that chunk fails to load (offline,
|
||||
* stale deploy): the failure goes to onCompileFail and nothing throws.
|
||||
* main chunk. `config.style` picks the scene: the ridges unless it says 'raymarch'. Null means
|
||||
* "keep the CSS ground", including when that chunk fails to load (offline, stale deploy): the
|
||||
* failure goes to onCompileFail and nothing throws.
|
||||
*/
|
||||
export async function startBackgroundScene(
|
||||
config: BackgroundSceneConfig | undefined,
|
||||
|
|
@ -22,9 +23,12 @@ export async function startBackgroundScene(
|
|||
): Promise<Scene | null> {
|
||||
const tier = resolveTier(config, capabilities);
|
||||
if (tier === 'off') return null;
|
||||
let createScene: typeof import('./Scene').createScene;
|
||||
let createScene: (o: SceneOptions) => Scene | null;
|
||||
try {
|
||||
({ createScene } = await import('./Scene'));
|
||||
createScene =
|
||||
config?.style === 'raymarch'
|
||||
? (await import('./Scene')).createScene
|
||||
: (await import('./ridge/Ridge')).createRidgeScene;
|
||||
} catch (e) {
|
||||
options.onCompileFail?.(e instanceof Error ? e : new Error(String(e)));
|
||||
return null;
|
||||
|
|
|
|||
380
src/app/features/scene/ridge/Ridge.test.ts
Normal file
380
src/app/features/scene/ridge/Ridge.test.ts
Normal file
|
|
@ -0,0 +1,380 @@
|
|||
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 { skyColours } from './skyColour';
|
||||
import { startBackgroundScene } from '../index';
|
||||
|
||||
describe('noise', () => {
|
||||
it('is deterministic and in [0, 1)', () => {
|
||||
expect(hash2(3, 5)).toBe(hash2(3, 5));
|
||||
for (let i = 0; i < 200; i += 1) {
|
||||
const v = valueNoisePeriodic(i * 0.37, 2, 7);
|
||||
expect(v).toBeGreaterThanOrEqual(0);
|
||||
expect(v).toBeLessThan(1);
|
||||
}
|
||||
});
|
||||
|
||||
it('wraps: the lattice repeats every `period` cells', () => {
|
||||
for (const x of [0, 0.4, 3.9, 6.99]) {
|
||||
expect(valueNoisePeriodic(x + 7, 4, 7)).toBeCloseTo(valueNoisePeriodic(x, 4, 7), 12);
|
||||
}
|
||||
});
|
||||
|
||||
it('different rows are different profiles', () => {
|
||||
expect(valueNoisePeriodic(1.5, 0, 9)).not.toBeCloseTo(valueNoisePeriodic(1.5, 1, 9), 3);
|
||||
});
|
||||
});
|
||||
|
||||
describe('ridge profile', () => {
|
||||
it('every layer is periodic in t, so a drift of one period loops seamlessly', () => {
|
||||
for (const spec of LAYERS) {
|
||||
for (const t of [0, 0.13, 0.5, 0.97]) {
|
||||
expect(Number.isFinite(profile(spec, t))).toBe(true);
|
||||
}
|
||||
// the end of one period meets the start of the next
|
||||
expect(profile(spec, 1 - 1e-9)).toBeCloseTo(profile(spec, 0), 3);
|
||||
}
|
||||
});
|
||||
|
||||
it('every octave count is an integer lattice, which periodicity needs', () => {
|
||||
for (const spec of LAYERS) {
|
||||
for (let k = 0; k < FBM.octaves; k += 1) {
|
||||
expect(Number.isInteger(spec.baseCells * FBM.lacunarity ** k)).toBe(true);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('stays in [0, 1] and layers differ', () => {
|
||||
for (const spec of LAYERS) {
|
||||
for (let i = 0; i < 100; i += 1) {
|
||||
const p = profile(spec, i / 100);
|
||||
expect(p).toBeGreaterThanOrEqual(0);
|
||||
expect(p).toBeLessThanOrEqual(1);
|
||||
}
|
||||
}
|
||||
expect(profile(LAYERS[0], 0.3)).not.toBeCloseTo(profile(LAYERS[1], 0.3), 3);
|
||||
});
|
||||
|
||||
it('ridge tops lie inside the layer band and rise with farther base', () => {
|
||||
const size = layerSize(400, 800, 1);
|
||||
for (const spec of LAYERS) {
|
||||
for (let x = 0; x < size.period; x += 17) {
|
||||
const y = ridgeY(spec, x, size.period, size.height, 800);
|
||||
expect(y).toBeGreaterThanOrEqual(0);
|
||||
expect(y).toBeLessThanOrEqual(size.height);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('layers get darker and slower toward the viewer, and their sizes are integers', () => {
|
||||
const sky = skyColours();
|
||||
const lum = (c: readonly number[]) => c[0] + c[1] + c[2];
|
||||
for (let i = 1; i < LAYERS.length; i += 1) {
|
||||
expect(lum(layerColour(LAYERS[i], sky))).toBeLessThan(lum(layerColour(LAYERS[i - 1], sky)));
|
||||
expect(LAYERS[i].seconds).toBeLessThan(LAYERS[i - 1].seconds);
|
||||
}
|
||||
for (const [w, h, s] of [
|
||||
[393, 851, 2],
|
||||
[1280, 720, 1],
|
||||
[412.5, 915.3, 2],
|
||||
] as const) {
|
||||
const z = layerSize(w, h, s);
|
||||
expect(
|
||||
Number.isInteger(z.period) && Number.isInteger(z.width) && Number.isInteger(z.height)
|
||||
).toBe(true);
|
||||
expect(z.width).toBe(2 * z.period);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('frame sampler', () => {
|
||||
const feed = (s: FrameSampler, dt: number, frames: number, from = 0) => {
|
||||
let t = from;
|
||||
let done = false;
|
||||
for (let i = 0; i < frames && !done; i += 1) {
|
||||
t += dt;
|
||||
done = s.push(t);
|
||||
}
|
||||
return done;
|
||||
};
|
||||
|
||||
it('median and p95 of known intervals', () => {
|
||||
const v = Array.from({ length: 100 }, (_, i) => (i < 90 ? 16 : 50));
|
||||
expect(frameStats(v)).toEqual({ n: 100, medianMs: 16, p95Ms: 50 });
|
||||
expect(frameStats([])).toEqual({ n: 0, medianMs: 0, p95Ms: 0 });
|
||||
});
|
||||
|
||||
it('does not complete before 2 s of measured frames, and ignores the warm-up', () => {
|
||||
const s = new FrameSampler();
|
||||
expect(feed(s, 16, 100)).toBe(false); // 1.6 s
|
||||
expect(feed(s, 16, 40, 1600)).toBe(true);
|
||||
expect(s.stats().n).toBeLessThan(100 + 40 - WARMUP_FRAMES + 1);
|
||||
});
|
||||
|
||||
it('a smooth 60 Hz run is not slow; a run of 40 ms frames is', () => {
|
||||
const good = new FrameSampler();
|
||||
feed(good, 16.7, 400);
|
||||
expect(good.slow()).toBe(false);
|
||||
const bad = new FrameSampler();
|
||||
feed(bad, 100, 400); // ~100 ms frames, the PR #13 readout
|
||||
expect(bad.stats().p95Ms).toBeGreaterThan(SLOW_P95_MS);
|
||||
expect(bad.slow()).toBe(true);
|
||||
});
|
||||
|
||||
it('a long warm-up frame does not poison the window', () => {
|
||||
const s = new FrameSampler();
|
||||
let t = 0;
|
||||
s.push(t);
|
||||
for (let i = 0; i < WARMUP_FRAMES; i += 1) s.push((t += 300)); // setup, upload, JIT
|
||||
feed(s, 16.7, 200, t);
|
||||
expect(s.slow()).toBe(false);
|
||||
expect(WINDOW_MS).toBe(2000);
|
||||
});
|
||||
|
||||
it('reset forgets a hidden-tab gap', () => {
|
||||
const s = new FrameSampler();
|
||||
feed(s, 16, 20);
|
||||
s.reset();
|
||||
expect(s.stats().n).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
// A minimal DOM: just what createRidgeScene touches.
|
||||
function fakeEl(tag = 'div') {
|
||||
const el: any = {
|
||||
tag,
|
||||
style: {},
|
||||
children: [] as any[],
|
||||
parentElement: null as any,
|
||||
width: 0,
|
||||
height: 0,
|
||||
clientWidth: 400,
|
||||
clientHeight: 800,
|
||||
attrs: {} as Record<string, string>,
|
||||
setAttribute(k: string, v: string) {
|
||||
this.attrs[k] = v;
|
||||
},
|
||||
getContext: vi.fn(() => ctx()),
|
||||
remove() {
|
||||
if (this.parentElement)
|
||||
this.parentElement.children = this.parentElement.children.filter((c: any) => c !== this);
|
||||
this.parentElement = null;
|
||||
},
|
||||
appendChild(c: any) {
|
||||
c.parentElement = this;
|
||||
this.children.push(c);
|
||||
return c;
|
||||
},
|
||||
animate: vi.fn(() => {
|
||||
const a = { currentTime: 0, play: vi.fn(), pause: vi.fn(), cancel: vi.fn() };
|
||||
el.anims.push(a);
|
||||
return a;
|
||||
}),
|
||||
anims: [] as any[],
|
||||
};
|
||||
return el;
|
||||
}
|
||||
const draws: string[] = [];
|
||||
function ctx() {
|
||||
return {
|
||||
createLinearGradient: () => ({ addColorStop: vi.fn() }),
|
||||
fillRect: () => draws.push('sky'),
|
||||
beginPath() {},
|
||||
moveTo() {},
|
||||
lineTo() {},
|
||||
closePath() {},
|
||||
fill: () => draws.push('fill'),
|
||||
drawImage: () => draws.push('flatten'),
|
||||
set fillStyle(_v: unknown) {},
|
||||
};
|
||||
}
|
||||
|
||||
let rafQueue: Array<(t: number) => void>;
|
||||
let motion: { matches: boolean; addEventListener: any; removeEventListener: any };
|
||||
let doc: any;
|
||||
let search: string;
|
||||
|
||||
beforeEach(() => {
|
||||
rafQueue = [];
|
||||
draws.length = 0;
|
||||
search = '';
|
||||
motion = { matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn() };
|
||||
doc = Object.assign(new EventTarget(), {
|
||||
visibilityState: 'visible',
|
||||
createElement: (t: string) => fakeEl(t),
|
||||
});
|
||||
vi.stubGlobal('document', doc);
|
||||
vi.stubGlobal(
|
||||
'window',
|
||||
Object.assign(new EventTarget(), {
|
||||
devicePixelRatio: 2,
|
||||
innerWidth: 400,
|
||||
innerHeight: 800,
|
||||
matchMedia: () => motion,
|
||||
location: {
|
||||
get search() {
|
||||
return search;
|
||||
},
|
||||
},
|
||||
setTimeout,
|
||||
})
|
||||
);
|
||||
vi.stubGlobal('requestAnimationFrame', (cb: (t: number) => void) => rafQueue.push(cb));
|
||||
vi.stubGlobal('cancelAnimationFrame', () => {
|
||||
rafQueue = [];
|
||||
});
|
||||
});
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
function host() {
|
||||
const parent = fakeEl('div');
|
||||
const canvas = fakeEl('canvas');
|
||||
parent.appendChild(canvas);
|
||||
return { parent, canvas };
|
||||
}
|
||||
const runFrames = (dt: number, n: number, from = 0) => {
|
||||
let t = from;
|
||||
for (let i = 0; i < n && rafQueue.length; i += 1) {
|
||||
t += dt;
|
||||
rafQueue.shift()!(t);
|
||||
}
|
||||
return t;
|
||||
};
|
||||
|
||||
describe('createRidgeScene', () => {
|
||||
it("returns null at tier 'off' and touches nothing", () => {
|
||||
const { canvas } = host();
|
||||
expect(createRidgeScene({ canvas, tier: 'off' })).toBeNull();
|
||||
expect(canvas.getContext).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns null when 2D context is missing, so the host keeps its CSS ground', () => {
|
||||
const { canvas } = host();
|
||||
canvas.getContext = vi.fn(() => null);
|
||||
expect(createRidgeScene({ canvas, tier: 'full' })).toBeNull();
|
||||
});
|
||||
|
||||
it('bakes the sky once and paints four layers at integer sizes, farthest first', () => {
|
||||
const { parent, canvas } = host();
|
||||
const s = createRidgeScene({ canvas, tier: 'full' })!;
|
||||
expect(s).not.toBeNull();
|
||||
const layers = parent.children.slice(1);
|
||||
expect(layers).toHaveLength(LAYERS.length);
|
||||
layers.forEach((l: any) => {
|
||||
expect(Number.isInteger(l.width) && Number.isInteger(l.height)).toBe(true);
|
||||
expect(l.width).toBe(canvas.width * 2); // DPR 2: layer is two periods wide
|
||||
expect(l.animate).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
expect(draws.filter((d) => d === 'sky')).toHaveLength(1);
|
||||
expect(draws.filter((d) => d === 'fill')).toHaveLength(LAYERS.length);
|
||||
s.dispose();
|
||||
});
|
||||
|
||||
it('after the layers are painted, a smooth run draws nothing more and ends its rAF loop', () => {
|
||||
const { canvas } = host();
|
||||
const s = createRidgeScene({ canvas, tier: 'full' })!;
|
||||
const before = draws.length;
|
||||
runFrames(16.7, 400);
|
||||
expect(draws.length).toBe(before);
|
||||
expect(rafQueue).toHaveLength(0); // no per-frame work left
|
||||
s.dispose();
|
||||
});
|
||||
|
||||
it('p95 over 33 ms across 2 s flattens to a still image and removes the layers', () => {
|
||||
const { parent, canvas } = host();
|
||||
const onProbe = vi.fn();
|
||||
const s = createRidgeScene({ canvas, tier: 'full', onProbe })!;
|
||||
runFrames(100, 100);
|
||||
expect(draws.filter((d) => d === 'flatten')).toHaveLength(LAYERS.length);
|
||||
expect(parent.children).toEqual([canvas]);
|
||||
expect(onProbe).toHaveBeenLastCalledWith(expect.objectContaining({ still: true }));
|
||||
expect(rafQueue).toHaveLength(0);
|
||||
s.dispose();
|
||||
});
|
||||
|
||||
it("'still' tier flattens immediately and never starts a loop", () => {
|
||||
const { parent, canvas } = host();
|
||||
createRidgeScene({ canvas, tier: 'still' });
|
||||
expect(parent.children).toEqual([canvas]);
|
||||
expect(draws.filter((d) => d === 'flatten')).toHaveLength(LAYERS.length);
|
||||
expect(rafQueue).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('prefers-reduced-motion: layers are built but never played, and nothing is sampled', () => {
|
||||
motion.matches = true;
|
||||
const { canvas } = host();
|
||||
const s = createRidgeScene({ canvas, tier: 'full' })!;
|
||||
const anims = canvas.anims.concat(...canvas.parentElement.children.map((c: any) => c.anims));
|
||||
expect(anims.length).toBe(LAYERS.length);
|
||||
anims.forEach((a: any) => expect(a.play).not.toHaveBeenCalled());
|
||||
expect(rafQueue).toHaveLength(0);
|
||||
s.dispose();
|
||||
});
|
||||
|
||||
it('pauses the drift when the tab is hidden and resumes when it is visible', () => {
|
||||
const { parent, canvas } = host();
|
||||
const s = createRidgeScene({ canvas, tier: 'full' })!;
|
||||
const anims = parent.children.slice(1).flatMap((l: any) => l.anims);
|
||||
anims.forEach((a: any) => a.pause.mockClear());
|
||||
doc.visibilityState = 'hidden';
|
||||
doc.dispatchEvent(new Event('visibilitychange'));
|
||||
anims.forEach((a: any) => expect(a.pause).toHaveBeenCalled());
|
||||
anims.forEach((a: any) => a.play.mockClear());
|
||||
doc.visibilityState = 'visible';
|
||||
doc.dispatchEvent(new Event('visibilitychange'));
|
||||
anims.forEach((a: any) => expect(a.play).toHaveBeenCalled());
|
||||
s.dispose();
|
||||
});
|
||||
|
||||
it('?probe=1 keeps the rAF loop alive and shows median and p95', () => {
|
||||
search = '?probe=1';
|
||||
const { parent, canvas } = host();
|
||||
const s = createRidgeScene({ canvas, tier: 'full' })!;
|
||||
const readout = parent.children[parent.children.length - 1];
|
||||
runFrames(16.7, 300);
|
||||
expect(rafQueue.length).toBe(1); // still sampling
|
||||
expect(readout.textContent).toMatch(/median 16\.\d ms · p95 1[67]\.\d ms/);
|
||||
s.dispose();
|
||||
expect(parent.children.some((c: any) => c === readout)).toBe(false);
|
||||
});
|
||||
|
||||
it('dispose cancels the loop, the animations and the layers', () => {
|
||||
const { parent, canvas } = host();
|
||||
const s = createRidgeScene({ canvas, tier: 'full' })!;
|
||||
const anims = parent.children.slice(1).flatMap((l: any) => l.anims);
|
||||
s.dispose();
|
||||
anims.forEach((a: any) => expect(a.cancel).toHaveBeenCalled());
|
||||
expect(parent.children).toEqual([canvas]);
|
||||
expect(rafQueue).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the door', () => {
|
||||
it('runs the ridge scene by default and never requests a WebGL context', async () => {
|
||||
const { canvas } = host();
|
||||
const getContext = vi.fn((kind: string) => (kind === '2d' ? ctx() : null));
|
||||
canvas.getContext = getContext;
|
||||
const scene = await startBackgroundScene({ tier: 'full' }, {}, { canvas });
|
||||
expect(scene).not.toBeNull();
|
||||
expect(getContext.mock.calls.every(([k]) => k === '2d')).toBe(true);
|
||||
scene!.dispose();
|
||||
});
|
||||
|
||||
it('the tier flag still defaults to off: nothing imported, no context', async () => {
|
||||
const { canvas } = host();
|
||||
expect(await startBackgroundScene(undefined, {}, { canvas })).toBeNull();
|
||||
expect(canvas.getContext).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('fbm', () => {
|
||||
it('is normalised into [0, 1]', () => {
|
||||
for (let i = 0; i < 100; i += 1) {
|
||||
const v = fbmPeriodic(i / 100, 0, 3, FBM);
|
||||
expect(v).toBeGreaterThanOrEqual(0);
|
||||
expect(v).toBeLessThanOrEqual(1);
|
||||
}
|
||||
});
|
||||
});
|
||||
276
src/app/features/scene/ridge/Ridge.ts
Normal file
276
src/app/features/scene/ridge/Ridge.ts
Normal file
|
|
@ -0,0 +1,276 @@
|
|||
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';
|
||||
|
||||
export type RidgeOptions = Pick<SceneOptions, 'canvas' | 'tier'> & {
|
||||
/** Show the rAF median/p95 readout. Default: the page URL has `?probe=1`. */
|
||||
probe?: boolean;
|
||||
/** Each time the readout would update, and once with `still` when the fallback fires. */
|
||||
onProbe?: (s: FrameStats & { still: boolean }) => void;
|
||||
/** The sky's colours; default `skyColours()`, the one function to replace with Void's sun.js. */
|
||||
sky?: SkyColours;
|
||||
};
|
||||
|
||||
const css = (c: Srgb): string => `rgb(${c[0]},${c[1]},${c[2]})`;
|
||||
const mix = (a: Srgb, b: Srgb, t: number): Srgb => [
|
||||
Math.round(a[0] + (b[0] - a[0]) * t),
|
||||
Math.round(a[1] + (b[1] - a[1]) * t),
|
||||
Math.round(a[2] + (b[2] - a[2]) * t),
|
||||
];
|
||||
|
||||
function context2d(c: HTMLCanvasElement): CanvasRenderingContext2D | null {
|
||||
return c.getContext('2d');
|
||||
}
|
||||
|
||||
function paintSky(canvas: HTMLCanvasElement, sky: SkyColours): boolean {
|
||||
const ctx = context2d(canvas);
|
||||
if (!ctx) return false;
|
||||
const g = ctx.createLinearGradient(0, 0, 0, canvas.height);
|
||||
g.addColorStop(0, css(sky.top));
|
||||
g.addColorStop(0.5, css(sky.mid));
|
||||
g.addColorStop(0.78, css(sky.horizon));
|
||||
g.addColorStop(1, css(sky.horizon));
|
||||
ctx.fillStyle = g;
|
||||
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** 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
|
||||
): HTMLCanvasElement | null {
|
||||
const el = document.createElement('canvas');
|
||||
el.width = size.width;
|
||||
el.height = size.height;
|
||||
const ctx = context2d(el);
|
||||
if (!ctx) return null;
|
||||
const top: number[] = [];
|
||||
for (let x = 0; x < size.period; x += 1)
|
||||
top.push(ridgeY(spec, x, size.period, size.height, viewH));
|
||||
const c = layerColour(spec, sky);
|
||||
const g = ctx.createLinearGradient(0, 0, 0, size.height);
|
||||
g.addColorStop(0, css(c));
|
||||
g.addColorStop(1, css(mix(c, hazeColour(sky), 0.5 * (1 - spec.depth))));
|
||||
ctx.fillStyle = g;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(0, size.height);
|
||||
for (let x = 0; x <= size.width; x += 1) ctx.lineTo(x, top[x % size.period]);
|
||||
ctx.lineTo(size.width, size.height);
|
||||
ctx.closePath();
|
||||
ctx.fill();
|
||||
return el;
|
||||
}
|
||||
|
||||
interface Built {
|
||||
layers: HTMLCanvasElement[];
|
||||
anims: Animation[];
|
||||
}
|
||||
|
||||
/**
|
||||
* The ridge scene: same contract as `createScene` ({ login, dispose }, null for "keep the CSS
|
||||
* ground"), no WebGL. The layers are painted once on the CPU; per frame the only work is the
|
||||
* browser compositor sliding each layer with a CSS transform (a Web Animation, no script). The host
|
||||
* canvas holds the baked sky; it and the layers' parent must be positioned, and the canvas should fill it.
|
||||
*/
|
||||
export function createRidgeScene(opts: RidgeOptions): Scene | null {
|
||||
const tier = opts.tier ?? 'full';
|
||||
if (tier === 'off') return null;
|
||||
const canvas = opts.canvas;
|
||||
const parent = canvas.parentElement;
|
||||
if (!parent) return null;
|
||||
const sky = opts.sky ?? skyColours();
|
||||
const probe = opts.probe ?? new URLSearchParams(window.location.search).get('probe') === '1';
|
||||
const reducedMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)');
|
||||
|
||||
let built: Built | undefined;
|
||||
let still = tier === 'still';
|
||||
let disposed = false;
|
||||
let raf = 0;
|
||||
let readout: HTMLElement | undefined;
|
||||
let resizeTimer = 0;
|
||||
const sampler = new FrameSampler();
|
||||
|
||||
const viewSize = () => {
|
||||
const w = canvas.clientWidth || window.innerWidth;
|
||||
const h = canvas.clientHeight || window.innerHeight;
|
||||
return { w, h, scale: (window.devicePixelRatio || 1) >= 2 ? 2 : 1 };
|
||||
};
|
||||
|
||||
const teardownLayers = () => {
|
||||
built?.anims.forEach((a) => a.cancel());
|
||||
built?.layers.forEach((l) => l.remove());
|
||||
built = undefined;
|
||||
};
|
||||
|
||||
/** Bake the sky, then the layers. Returns false when a 2D context is missing. */
|
||||
const build = (): boolean => {
|
||||
teardownLayers();
|
||||
const { w, h, scale } = viewSize();
|
||||
const size = layerSize(w, h, scale);
|
||||
canvas.width = size.period;
|
||||
canvas.height = Math.round(h * scale);
|
||||
if (!paintSky(canvas, sky)) return false;
|
||||
const layers: HTMLCanvasElement[] = [];
|
||||
for (const spec of LAYERS) {
|
||||
const el = paintLayer(spec, sky, size, canvas.height);
|
||||
if (!el) {
|
||||
layers.forEach((l) => l.remove());
|
||||
return false;
|
||||
}
|
||||
el.setAttribute('aria-hidden', 'true');
|
||||
Object.assign(el.style, {
|
||||
position: 'absolute',
|
||||
left: '0',
|
||||
bottom: '0',
|
||||
width: `${size.width / scale}px`,
|
||||
height: `${size.height / scale}px`,
|
||||
pointerEvents: 'none',
|
||||
willChange: 'transform',
|
||||
});
|
||||
layers.push(el);
|
||||
}
|
||||
// DOM order is paint order: farthest first, so the nearest ridge ends up on top.
|
||||
layers.forEach((l) => parent.appendChild(l));
|
||||
const anims = layers
|
||||
.map((el, i) =>
|
||||
el.animate?.(
|
||||
[
|
||||
{ transform: 'translate3d(0,0,0)' },
|
||||
{ transform: `translate3d(${-size.period / scale}px,0,0)` },
|
||||
],
|
||||
{ duration: LAYERS[i].seconds * 1000, iterations: Infinity, easing: 'linear' }
|
||||
)
|
||||
)
|
||||
.filter((a): a is Animation => !!a);
|
||||
built = { layers, anims };
|
||||
syncPlayState();
|
||||
return true;
|
||||
};
|
||||
|
||||
const moving = () =>
|
||||
!still &&
|
||||
!disposed &&
|
||||
!(reducedMotion?.matches ?? false) &&
|
||||
document.visibilityState === 'visible';
|
||||
|
||||
function syncPlayState() {
|
||||
built?.anims.forEach((a) => (moving() ? a.play() : a.pause()));
|
||||
}
|
||||
|
||||
/** Flatten the sky and layers into the host canvas and drop the layers: a still image, no compositor layers left. */
|
||||
const settleToStill = () => {
|
||||
if (still && !built) return;
|
||||
still = true;
|
||||
const ctx = context2d(canvas);
|
||||
if (ctx && built) {
|
||||
const { anims } = built;
|
||||
built.layers.forEach((l, i) => {
|
||||
// Freeze where the drift is, so the swap to a still does not jump.
|
||||
const a = anims[i];
|
||||
const t = Number(a?.currentTime ?? 0);
|
||||
const turns = (t % (LAYERS[i].seconds * 1000)) / (LAYERS[i].seconds * 1000);
|
||||
ctx.drawImage(l, -Math.round(turns * canvas.width), canvas.height - l.height);
|
||||
});
|
||||
}
|
||||
teardownLayers();
|
||||
cancelAnimationFrame(raf);
|
||||
raf = 0;
|
||||
report(true);
|
||||
};
|
||||
|
||||
const report = (stillNow: boolean) => {
|
||||
const s = { ...sampler.stats(), still: stillNow };
|
||||
opts.onProbe?.(s);
|
||||
if (readout) {
|
||||
readout.textContent = `ridge · n ${s.n} · median ${s.medianMs.toFixed(
|
||||
1
|
||||
)} ms · p95 ${s.p95Ms.toFixed(1)} ms${stillNow ? ' · STILL' : ''}`;
|
||||
}
|
||||
};
|
||||
|
||||
let sinceReport = 0;
|
||||
const tick = (now: number) => {
|
||||
raf = 0;
|
||||
if (!moving()) return;
|
||||
const full = sampler.push(now);
|
||||
if (full && sampler.slow() && !still) {
|
||||
settleToStill();
|
||||
return;
|
||||
}
|
||||
// After the window the series keeps rolling only for the readout; otherwise the loop ends here.
|
||||
if (full && !probe) return;
|
||||
if (probe && now - sinceReport > 500) {
|
||||
sinceReport = now;
|
||||
report(false);
|
||||
}
|
||||
raf = requestAnimationFrame(tick);
|
||||
};
|
||||
|
||||
const wake = () => {
|
||||
syncPlayState();
|
||||
if (!moving() || raf) return;
|
||||
sampler.reset();
|
||||
raf = requestAnimationFrame(tick);
|
||||
};
|
||||
|
||||
if (!build()) return null;
|
||||
if (probe) {
|
||||
readout = document.createElement('div');
|
||||
Object.assign(readout.style, {
|
||||
position: 'absolute',
|
||||
left: '8px',
|
||||
top: '8px',
|
||||
font: '12px monospace',
|
||||
color: '#fff',
|
||||
background: 'rgba(0,0,0,.55)',
|
||||
padding: '2px 6px',
|
||||
borderRadius: '3px',
|
||||
pointerEvents: 'none',
|
||||
});
|
||||
parent.appendChild(readout);
|
||||
}
|
||||
if (still) settleToStill();
|
||||
else wake();
|
||||
|
||||
const onVisibility = () => {
|
||||
sampler.reset();
|
||||
wake();
|
||||
};
|
||||
const onResize = () => {
|
||||
clearTimeout(resizeTimer);
|
||||
resizeTimer = window.setTimeout(() => {
|
||||
if (disposed) return;
|
||||
const wasStill = still;
|
||||
if (!build()) return;
|
||||
if (wasStill) settleToStill();
|
||||
else {
|
||||
sampler.reset();
|
||||
wake();
|
||||
}
|
||||
}, 250);
|
||||
};
|
||||
document.addEventListener('visibilitychange', onVisibility);
|
||||
window.addEventListener('resize', onResize);
|
||||
reducedMotion?.addEventListener?.('change', syncPlayState);
|
||||
|
||||
return {
|
||||
login() {
|
||||
// No camera to pull back; the ridges are 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', syncPlayState);
|
||||
teardownLayers();
|
||||
readout?.remove();
|
||||
},
|
||||
};
|
||||
}
|
||||
51
src/app/features/scene/ridge/noise.ts
Normal file
51
src/app/features/scene/ridge/noise.ts
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
// CultMath's value noise and fbm on the CPU, in one dimension and periodic. Clean-room: the
|
||||
// algorithm is read from shaders/CultMath.glsl (`cultmath_hash`, `cultmath_value_noise`), not copied
|
||||
// from any other terrain. Doubles instead of floats, so values differ from the GLSL in the last
|
||||
// digits; nothing here has to match a shader.
|
||||
|
||||
const frac = (v: number): number => v - Math.floor(v);
|
||||
|
||||
/** `cultmath_hash(vec2)`. */
|
||||
export const hash2 = (x: number, y: number): number =>
|
||||
frac(Math.sin(x * 127.1 + y * 311.7) * 43758.5453);
|
||||
|
||||
const smooth = (t: number): number => t * t * (3 - 2 * t);
|
||||
|
||||
/**
|
||||
* `cultmath_value_noise` along row `row` of the lattice, with the lattice wrapping every `period`
|
||||
* cells: noise(x + period) === noise(x). `row` is an integer, so the vertical blend of the 2D
|
||||
* original is the identity.
|
||||
*/
|
||||
export function valueNoisePeriodic(x: number, row: number, period: number): number {
|
||||
const cell = Math.floor(x);
|
||||
const u = smooth(x - cell);
|
||||
const wrap = (c: number) => ((c % period) + period) % period;
|
||||
const a = hash2(wrap(cell), row);
|
||||
const b = hash2(wrap(cell + 1), row);
|
||||
return a + (b - a) * u;
|
||||
}
|
||||
|
||||
export interface FbmShape {
|
||||
octaves: number;
|
||||
lacunarity: number;
|
||||
gain: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fractal sum in [0, 1]. `t` runs 0..1 across one period; the first octave has `baseCells` cells
|
||||
* per period and each next one `lacunarity` times more, so `baseCells * lacunarity^k` must be an
|
||||
* integer for the sum to be periodic (checked by the caller's config, not here).
|
||||
*/
|
||||
export function fbmPeriodic(t: number, row: number, baseCells: number, s: FbmShape): number {
|
||||
let sum = 0;
|
||||
let norm = 0;
|
||||
let amp = 1;
|
||||
let cells = baseCells;
|
||||
for (let k = 0; k < s.octaves; k += 1) {
|
||||
sum += amp * valueNoisePeriodic(t * cells, row + k * 13, cells);
|
||||
norm += amp;
|
||||
amp *= s.gain;
|
||||
cells *= s.lacunarity;
|
||||
}
|
||||
return sum / norm;
|
||||
}
|
||||
60
src/app/features/scene/ridge/probe.ts
Normal file
60
src/app/features/scene/ridge/probe.ts
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
// Frame cadence from rAF timestamps: what `?probe=1` shows, and what the still-image fallback
|
||||
// decides on. Pure, so it is tested without a browser.
|
||||
|
||||
export interface FrameStats {
|
||||
/** Frame intervals counted. */
|
||||
n: number;
|
||||
medianMs: number;
|
||||
p95Ms: number;
|
||||
}
|
||||
|
||||
/** The fallback's threshold and window, from the brief: p95 over 33 ms across 2 s. */
|
||||
export const SLOW_P95_MS = 33;
|
||||
export const WINDOW_MS = 2000;
|
||||
/** The first frames pay for layout, canvas upload and JIT; they say nothing about steady cadence. */
|
||||
export const WARMUP_FRAMES = 5;
|
||||
|
||||
const quantile = (sorted: readonly number[], q: number): number =>
|
||||
sorted.length === 0 ? 0 : sorted[Math.min(sorted.length - 1, Math.floor(q * sorted.length))];
|
||||
|
||||
export function frameStats(intervals: readonly number[]): FrameStats {
|
||||
const s = [...intervals].sort((a, b) => a - b);
|
||||
return { n: s.length, medianMs: quantile(s, 0.5), p95Ms: quantile(s, 0.95) };
|
||||
}
|
||||
|
||||
export class FrameSampler {
|
||||
private last: number | undefined;
|
||||
private skipped = 0;
|
||||
private startedAt: number | undefined;
|
||||
private readonly intervals: number[] = [];
|
||||
|
||||
/** Feed each rAF timestamp. Returns true once a full window has been measured. */
|
||||
push(now: number): boolean {
|
||||
const prev = this.last;
|
||||
this.last = now;
|
||||
if (prev === undefined) return false;
|
||||
if (this.skipped < WARMUP_FRAMES) {
|
||||
this.skipped += 1;
|
||||
return false;
|
||||
}
|
||||
this.startedAt ??= prev;
|
||||
this.intervals.push(now - prev);
|
||||
return now - this.startedAt >= WINDOW_MS;
|
||||
}
|
||||
|
||||
/** A pause (hidden tab, resize) breaks the series: its gap is not a slow frame. */
|
||||
reset(): void {
|
||||
this.last = undefined;
|
||||
this.skipped = 0;
|
||||
this.startedAt = undefined;
|
||||
this.intervals.length = 0;
|
||||
}
|
||||
|
||||
stats(): FrameStats {
|
||||
return frameStats(this.intervals);
|
||||
}
|
||||
|
||||
slow(): boolean {
|
||||
return this.stats().p95Ms > SLOW_P95_MS;
|
||||
}
|
||||
}
|
||||
75
src/app/features/scene/ridge/ridgeWorld.ts
Normal file
75
src/app/features/scene/ridge/ridgeWorld.ts
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
// Every number of the ridge scene, and the pure functions that turn them into silhouettes. No DOM.
|
||||
import { fbmPeriodic, FbmShape } from './noise';
|
||||
import type { Srgb, SkyColours } from './skyColour';
|
||||
|
||||
export interface LayerSpec {
|
||||
/** 0 farthest. Also the noise row, so layers never share a profile. */
|
||||
index: number;
|
||||
/** Lattice cells across one period for the first octave; the fbm octaves scale it by `lacunarity`. */
|
||||
baseCells: number;
|
||||
/** Peak-to-valley height of the silhouette, as a fraction of the layer band. */
|
||||
relief: number;
|
||||
/** 0 hills (plain fbm) .. 1 crags (ridged: 1 - |2n - 1|). */
|
||||
crag: number;
|
||||
/** Ridge top at its lowest point, fraction of the viewport height up from the bottom. */
|
||||
base: number;
|
||||
/** 0 = the layer is the horizon haze, 1 = the nearest ground colour. */
|
||||
depth: number;
|
||||
/** Seconds for the layer to drift one period. Farther layers are slower. */
|
||||
seconds: number;
|
||||
}
|
||||
|
||||
/** Four layers. `lacunarity` 2 with these base cell counts keeps every octave an integer. */
|
||||
export const LAYERS: readonly LayerSpec[] = [
|
||||
{ index: 0, baseCells: 3, relief: 0.24, crag: 0.8, base: 0.34, depth: 0.12, seconds: 420 },
|
||||
{ index: 1, baseCells: 4, relief: 0.2, crag: 0.55, base: 0.26, depth: 0.38, seconds: 300 },
|
||||
{ index: 2, baseCells: 5, relief: 0.16, crag: 0.3, base: 0.17, depth: 0.66, seconds: 210 },
|
||||
{ index: 3, baseCells: 6, relief: 0.12, crag: 0.1, base: 0.08, depth: 1, seconds: 150 },
|
||||
];
|
||||
|
||||
export const FBM: FbmShape = { octaves: 5, lacunarity: 2, gain: 0.5 };
|
||||
|
||||
/** Silhouette height in [0, 1] at `t` (0..1 across one period); periodic in t. */
|
||||
export function profile(spec: LayerSpec, t: number): number {
|
||||
const n = fbmPeriodic(t, spec.index * 101, spec.baseCells, FBM);
|
||||
const crag = 1 - Math.abs(2 * n - 1);
|
||||
return n + (crag - n) * spec.crag;
|
||||
}
|
||||
|
||||
/** The distance haze the far layers dissolve into: between the mid sky and the horizon, not the horizon glow itself. */
|
||||
export function hazeColour(sky: SkyColours): Srgb {
|
||||
const m = (a: number, b: number) => Math.round(a + (b - a) * 0.4);
|
||||
return [
|
||||
m(sky.mid[0], sky.horizon[0]),
|
||||
m(sky.mid[1], sky.horizon[1]),
|
||||
m(sky.mid[2], sky.horizon[2]),
|
||||
];
|
||||
}
|
||||
|
||||
/** Layer colour: the haze for depth 0, the ground colour for depth 1, mixed in sRGB. */
|
||||
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])];
|
||||
}
|
||||
|
||||
/** Integer pixel sizes of a layer for a viewport: one period wide, twice that painted, so a drift of one period loops. */
|
||||
export function layerSize(cssW: number, cssH: number, scale: number) {
|
||||
const period = Math.round(cssW * scale);
|
||||
const band = Math.round(cssH * scale * 0.6);
|
||||
return { period, width: period * 2, height: band };
|
||||
}
|
||||
|
||||
/** Ridge-top y (canvas pixels, from the top of the layer's band) for pixel column x. */
|
||||
export function ridgeY(
|
||||
spec: LayerSpec,
|
||||
x: number,
|
||||
period: number,
|
||||
bandH: number,
|
||||
viewH: number
|
||||
): number {
|
||||
const amp = spec.relief * viewH;
|
||||
const bottomOffset = spec.base * viewH; // lowest the top sits above the viewport bottom
|
||||
const topFromBottom = bottomOffset + amp * profile(spec, (x % period) / period);
|
||||
return bandH - Math.min(bandH, topFromBottom);
|
||||
}
|
||||
26
src/app/features/scene/ridge/skyColour.ts
Normal file
26
src/app/features/scene/ridge/skyColour.ts
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
// The one place the sky's colours come from. Void's `src/sky/sun.js` (`light({ time, lat, lon,
|
||||
// cloud_cover, precipitation })`, PR #20) is the intended source; until it lands this returns a
|
||||
// fixed dusk drawn from GameCult's nebula inputs (see ../palette.ts). Replace the body, keep the
|
||||
// signature: the scene calls it once, at startup, and bakes the result.
|
||||
|
||||
export type Srgb = readonly [number, number, number];
|
||||
|
||||
export interface SkyColours {
|
||||
/** Top of the sky gradient, sRGB 0..255. */
|
||||
top: Srgb;
|
||||
/** Mid-sky band. */
|
||||
mid: Srgb;
|
||||
/** Colour at the horizon, which the far ridges fade into. */
|
||||
horizon: Srgb;
|
||||
/** Nearest ridge: the ground colour the farther layers mix away from. */
|
||||
ground: Srgb;
|
||||
}
|
||||
|
||||
export function skyColours(_now: Date = new Date()): SkyColours {
|
||||
return {
|
||||
top: [24, 30, 78],
|
||||
mid: [78, 66, 150],
|
||||
horizon: [226, 130, 74],
|
||||
ground: [7, 17, 26],
|
||||
};
|
||||
}
|
||||
|
|
@ -15,8 +15,12 @@ export interface Capabilities {
|
|||
hardwareConcurrency?: number;
|
||||
}
|
||||
|
||||
/** 'ridge': baked parallax ridges, no WebGL (default). 'raymarch': the sphere-traced world with its tree and clouds. */
|
||||
export type SceneStyle = 'ridge' | 'raymarch';
|
||||
|
||||
export interface BackgroundSceneConfig {
|
||||
tier?: SceneTier;
|
||||
style?: SceneStyle;
|
||||
}
|
||||
|
||||
export function readCapabilities(nav: Navigator): Capabilities {
|
||||
|
|
|
|||
Loading…
Reference in a new issue