diff --git a/harness/scene/README.md b/harness/scene/README.md index ef735d2e..f6f5cf40 100644 --- a/harness/scene/README.md +++ b/harness/scene/README.md @@ -9,6 +9,7 @@ Chromium. Not shipped, not run by CI. node drive.cjs measure # GPU time per pass by timer query, two viewports, two levels node drive.cjs variants # the same with source patches (no erosion, no tree, value-only fbm) node drive.cjs trace # mean trace steps per pixel and pass ms at three camera poses, PREPASS=0,1 arms + node drive.cjs voxel # voxel scene: lookups per pixel and ms per frame at fixed poses, POSES=pull:seconds SCALES=0.75,0.5 node drive.cjs diff # one frozen frame with and without the prepass, pixel diff and both PNGs node drive.cjs phacelle # the Phacelle gradient probe behind world.ts `phacelleGradBound` diff --git a/harness/scene/bundle.cjs b/harness/scene/bundle.cjs index 027a2006..189318ca 100644 --- a/harness/scene/bundle.cjs +++ b/harness/scene/bundle.cjs @@ -1,10 +1,13 @@ // Bundles entry.ts with the scene's ?raw GLSL imports into $OUT/bundle.js plus an index.html. -// usage: node bundle.cjs [demo] (esbuild from NODE_PATH). `demo` bundles the standalone page. +// usage: node bundle.cjs [demo|voxel] (esbuild from NODE_PATH). `demo` bundles the ray-march +// standalone page, `voxel` the voxel scene's. const esbuild = require('esbuild'); const fs = require('fs'); const path = require('path'); const out = process.argv[2]; -const demo = process.argv[3] === 'demo'; +const kind = process.argv[3]; +const demo = kind === 'demo'; +const voxel = kind === 'voxel'; fs.mkdirSync(out, { recursive: true }); const rawPlugin = { name: 'raw', @@ -21,7 +24,7 @@ const rawPlugin = { }; esbuild .build({ - entryPoints: [path.join(__dirname, demo ? 'demo.ts' : 'entry.ts')], + entryPoints: [path.join(__dirname, demo ? 'demo.ts' : voxel ? 'voxelDemo.ts' : 'entry.ts')], bundle: true, outfile: path.join(out, 'bundle.js'), plugins: [rawPlugin], @@ -31,8 +34,10 @@ esbuild .then(() => { fs.writeFileSync( path.join(out, 'index.html'), - 'Ratatoskr scene: trace prepass' + - (demo + 'Ratatoskr scene' + + (voxel + ? '
device
' + : demo ? '
device
' : '') + '' diff --git a/harness/scene/demo.ts b/harness/scene/demo.ts index 40424ff5..f259bba8 100644 --- a/harness/scene/demo.ts +++ b/harness/scene/demo.ts @@ -4,10 +4,10 @@ import { createScene, Scene, SceneStats, - SceneUnavailable, TraceStats, } from '../../src/app/features/scene/Scene'; import { LEVELS } from '../../src/app/features/scene/budget'; +import { describeDevice, WHY } from './device'; let canvas = document.getElementById('c') as HTMLCanvasElement; const out = document.getElementById('out') as HTMLPreElement; @@ -21,33 +21,6 @@ const timerless = (() => { return !g?.getExtension('EXT_disjoint_timer_query_webgl2'); })(); -const WHY: Record = { - 'no-webgl2': 'this browser gave no WebGL2 context', - 'no-float-or-half-float-colour-buffer': - 'WebGL2 is there, but neither EXT_color_buffer_float nor EXT_color_buffer_half_float is', -}; - -// What the browser says about itself, read from a scratch context so it shows even when the scene -// could not start. A canvas that never got a WebGL2 context is asked for WebGL1 to name the GPU. -function describeDevice(): string { - const c = document.createElement('canvas'); - const gl2 = c.getContext('webgl2'); - const gl = gl2 ?? (document.createElement('canvas').getContext('webgl') as WebGLRenderingContext | null); - const lines = [`webgl2 context: ${gl2 ? 'yes' : 'NO'}`]; - if (!gl) return [...lines, 'webgl1 context: NO'].join('\n'); - const dbg = gl.getExtension('WEBGL_debug_renderer_info'); - lines.push( - `renderer: ${gl.getParameter(dbg ? dbg.UNMASKED_RENDERER_WEBGL : gl.RENDERER)}`, - `vendor: ${gl.getParameter(dbg ? dbg.UNMASKED_VENDOR_WEBGL : gl.VENDOR)}`, - `version: ${gl.getParameter(gl.VERSION)}`, - `user agent: ${navigator.userAgent}` - ); - const ext = gl.getSupportedExtensions() ?? []; - for (const n of ['EXT_color_buffer_float', 'EXT_color_buffer_half_float', 'OES_texture_float_linear', 'EXT_disjoint_timer_query_webgl2']) - lines.push(`${n}: ${ext.includes(n) ? 'yes' : 'NO'}`); - lines.push(`extensions (${ext.length}): ${ext.join(' ')}`); - return lines.join('\n'); -} info.textContent = describeDevice(); let scene: Scene | null = null; diff --git a/harness/scene/device.ts b/harness/scene/device.ts new file mode 100644 index 00000000..51f3c0d1 --- /dev/null +++ b/harness/scene/device.ts @@ -0,0 +1,31 @@ +// What a standalone page tells the reader about the browser, so a phone that cannot run the scene +// says why on screen. Not shipped. +import type { SceneUnavailable } from '../../src/app/features/scene/Scene'; + +export const WHY: Record = { + 'no-webgl2': 'this browser gave no WebGL2 context', + 'no-float-or-half-float-colour-buffer': + 'WebGL2 is there, but neither EXT_color_buffer_float nor EXT_color_buffer_half_float is', +}; + +// What the browser says about itself, read from a scratch context so it shows even when the scene +// could not start. A canvas that never got a WebGL2 context is asked for WebGL1 to name the GPU. +export function describeDevice(): string { + const c = document.createElement('canvas'); + const gl2 = c.getContext('webgl2'); + const gl = gl2 ?? (document.createElement('canvas').getContext('webgl') as WebGLRenderingContext | null); + const lines = [`webgl2 context: ${gl2 ? 'yes' : 'NO'}`]; + if (!gl) return [...lines, 'webgl1 context: NO'].join('\n'); + const dbg = gl.getExtension('WEBGL_debug_renderer_info'); + lines.push( + `renderer: ${gl.getParameter(dbg ? dbg.UNMASKED_RENDERER_WEBGL : gl.RENDERER)}`, + `vendor: ${gl.getParameter(dbg ? dbg.UNMASKED_VENDOR_WEBGL : gl.VENDOR)}`, + `version: ${gl.getParameter(gl.VERSION)}`, + `user agent: ${navigator.userAgent}` + ); + const ext = gl.getSupportedExtensions() ?? []; + for (const n of ['EXT_color_buffer_float', 'EXT_color_buffer_half_float', 'OES_texture_float_linear', 'EXT_disjoint_timer_query_webgl2']) + lines.push(`${n}: ${ext.includes(n) ? 'yes' : 'NO'}`); + lines.push(`extensions (${ext.length}): ${ext.join(' ')}`); + return lines.join('\n'); +} diff --git a/harness/scene/drive.cjs b/harness/scene/drive.cjs index 0f34191f..64889b8c 100644 --- a/harness/scene/drive.cjs +++ b/harness/scene/drive.cjs @@ -221,6 +221,65 @@ const [, , dir, mode, outdir = '.'] = process.argv; } } + if (mode === 'voxel') { + // The voxel scene at fixed poses (POSES=pull:seconds,...) and internal scales (SCALES=0.75,0.5): + // lookups per pixel, and the median ms to draw one frame (a one-texel sync read), two viewports. + report.runs = []; + for (const [w, h] of process.env.PORTRAIT === '0' + ? [[960, 540]] + : [ + [960, 540], + [540, 1200], + ]) { + for (const pose of (process.env.POSES || '0:0,0:60,1:60').split(',')) { + for (const scale of (process.env.SCALES || '0.75').split(',').map(Number)) { + await page.setViewportSize({ width: w, height: h }); + const [pull, t] = pose.split(':').map(Number); + const r = await page.evaluate( + ({ pull, t, scale }) => + new Promise((res) => { + const ms = []; + const looks = []; + let size; + const done = () => { + s.dispose(); + const med = (xs) => xs.sort((a, b) => a - b)[xs.length >> 1]; + res({ + size, + readbacks: looks.length, + lookupsPerPixel: +(looks.slice(1).reduce((a, b) => a + b, 0) / (looks.length - 1)).toFixed(2), + medianRenderMs: +med(ms.slice(1)).toFixed(1), + }); + }; + const s = window.__scene.createVoxelScene({ + canvas: document.getElementById('c'), + unthrottled: true, + fixedPull: pull, + clock: () => t, + fixedLevel: { solidScale: scale }, + onTraceStats: (x) => { + looks.push(x.traceSteps); + if (looks.length >= 12) done(); + }, + onFrameStats: (x) => { + size = x.size; + if (x.renderMs !== undefined) ms.push(x.renderMs); + }, + }); + if (!s) res({ error: 'createVoxelScene returned null' }); + }), + { pull, t, scale } + ); + report.runs.push({ viewport: [w, h], pull, t, scale, ...r }); + await page.evaluate(() => { + const c = document.getElementById('c'); + c.replaceWith(c.cloneNode()); + }); + } + } + } + } + if (mode === 'diff') { // Same frozen frame (reduced motion: time 0, 32 frames) with and without the prepass, compared // pixel by pixel. The prepass is meant to change cost, not the picture. diff --git a/harness/scene/entry.ts b/harness/scene/entry.ts index d43a5453..305e8c7d 100644 --- a/harness/scene/entry.ts +++ b/harness/scene/entry.ts @@ -1,11 +1,14 @@ // Browser entry for the harness: exposes the scene's seams to the driver. Not shipped. -import { createScene, linkStage, ShaderCompileError } from '../../src/app/features/scene/Scene'; +import { createScene } from '../../src/app/features/scene/Scene'; +import { createVoxelScene } from '../../src/app/features/scene/voxel/Voxel'; +import { linkStage, ShaderCompileError } from '../../src/app/features/scene/link'; import { LEVELS } from '../../src/app/features/scene/budget'; import { fragmentSource } from '../../src/app/features/scene/shaderSource'; import { WORLD } from '../../src/app/features/scene/world'; (window as unknown as Record).__scene = { createScene, + createVoxelScene, linkStage, ShaderCompileError, LEVELS, diff --git a/harness/scene/voxelDemo.ts b/harness/scene/voxelDemo.ts new file mode 100644 index 00000000..ca046d11 --- /dev/null +++ b/harness/scene/voxelDemo.ts @@ -0,0 +1,72 @@ +// Standalone page: the voxel scene full-window with a readout of lookups per pixel and frame ms, +// the internal scale, and what the browser says about itself. Not shipped. +import { createVoxelScene, SCALE_LEVELS } from '../../src/app/features/scene/voxel/Voxel'; +import type { FrameStats, Scene, TraceStats } from '../../src/app/features/scene/Scene'; +import { LEVELS } from '../../src/app/features/scene/budget'; +import { describeDevice, WHY } from './device'; + +let canvas = document.getElementById('c') as HTMLCanvasElement; +const out = document.getElementById('out') as HTMLPreElement; +const pull = document.getElementById('pull') as HTMLInputElement; +const scaleSel = document.getElementById('scale') as HTMLInputElement; +const scaleName = document.getElementById('scaleName') as HTMLSpanElement; +/** The slider's positions: the ladder's own, or auto. */ +const SCALES = ['auto', ...SCALE_LEVELS.map((l) => String(l.scale))]; +const scaleChoice = () => SCALES[+scaleSel.value]; +const measure = document.getElementById('measure') as HTMLInputElement; +const dev = document.getElementById('dev') as HTMLDetailsElement; +const info = document.getElementById('info') as HTMLPreElement; +info.textContent = describeDevice(); + +let scene: Scene | null = null; +let trace: TraceStats | undefined; +let frames: FrameStats | undefined; +let drawMs: number | undefined; +let cadence = 0; + +function start() { + scene?.dispose(); + trace = frames = drawMs = undefined; + cadence = 0; + // A fresh canvas: dispose leaves the old context bound to the old one. + const fresh = canvas.cloneNode() as HTMLCanvasElement; + canvas.replaceWith(fresh); + canvas = fresh; + out.textContent = ''; + scene = createVoxelScene({ + canvas: fresh, + fixedPull: +pull.value, + fixedLevel: + scaleChoice() === 'auto' ? undefined : { ...LEVELS[0], solidScale: +scaleChoice() }, + onTraceStats: measure.checked ? (t) => (trace = t) : undefined, + onFrameStats: (s) => { + frames = s; + cadence = cadence ? cadence * 0.9 + s.frameMs * 0.1 : s.frameMs; + if (s.renderMs !== undefined) drawMs = s.renderMs; + }, + onUnavailable: (r) => (out.textContent = `createVoxelScene returned null: ${WHY[r]}`), + onCompileFail: (e) => (out.textContent = `createVoxelScene returned null: ${e.message}`), + }); + dev.open = !scene; +} + +setInterval(() => { + if (!scene) return; + const lines = [`voxel pull ${pull.value} scale ${scaleChoice()}`]; + if (frames) { + lines.push( + `frame ms ${cadence.toFixed(1)} (cadence; the cap is 33.3) buffer ${frames.size.join('x')} at scale ${frames.scale}` + ); + } + if (trace) lines.push(`lookups/pixel ${trace.traceSteps.toFixed(2)} draw ms ${drawMs?.toFixed(1)} (one frame in 8, synced)`); + else if (measure.checked) lines.push('lookups/pixel: waiting for the first counted frame'); + out.textContent = lines.join('\n'); +}, 500); + +pull.addEventListener('input', start); +scaleSel.addEventListener('input', () => { + scaleName.textContent = scaleChoice(); + start(); +}); +measure.addEventListener('change', start); +start(); diff --git a/src/app/features/scene/index.ts b/src/app/features/scene/index.ts index c896649e..09803283 100644 --- a/src/app/features/scene/index.ts +++ b/src/app/features/scene/index.ts @@ -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 & { /** A shader failed to compile, or the scene chunk failed to load. The host keeps its ground. */ @@ -12,7 +12,7 @@ export type StartOptions = Omit { 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('./voxel/Voxel')).createVoxelScene; } catch (e) { options.onCompileFail?.(e instanceof Error ? e : new Error(String(e))); return null; diff --git a/src/app/features/scene/shaderSource.ts b/src/app/features/scene/shaderSource.ts index 42631d57..5e569364 100644 --- a/src/app/features/scene/shaderSource.ts +++ b/src/app/features/scene/shaderSource.ts @@ -8,10 +8,21 @@ import terrainFrag from './shaders/terrain.frag.glsl?raw'; import atmosphereFrag from './shaders/atmosphere.frag.glsl?raw'; import resolveFrag from './shaders/resolve.frag.glsl?raw'; import compositeFrag from './shaders/composite.frag.glsl?raw'; +import voxelHeightFrag from './shaders/voxelHeight.frag.glsl?raw'; +import voxelSkyFrag from './shaders/voxelSky.frag.glsl?raw'; +import voxelFrag from './shaders/voxel.frag.glsl?raw'; import { WORLD, worldDefines } from './world'; import { trimGlsl } from './cultmathTrim'; -export type Stage = 'prepass' | 'terrain' | 'atmosphere' | 'resolve' | 'composite'; +export type Stage = + | 'prepass' + | 'terrain' + | 'atmosphere' + | 'resolve' + | 'composite' + | 'voxelHeight' + | 'voxelSky' + | 'voxel'; const HEADER = '#version 300 es\nprecision highp float;\nprecision highp int;\nprecision highp sampler2D;\n'; @@ -24,6 +35,9 @@ const stages: Record = { atmosphere: atmosphereFrag, resolve: resolveFrag, composite: compositeFrag, + voxelHeight: voxelHeightFrag, + voxelSky: voxelSkyFrag, + voxel: voxelFrag, }; /** @@ -33,9 +47,11 @@ const stages: Record = { * it is called. */ export function fragmentSource(stage: Stage, defines = ''): string { - const solid = stage === 'terrain' || stage === 'prepass'; + const solid = stage === 'terrain' || stage === 'prepass' || stage === 'voxelHeight'; const erosion = solid && WORLD.phacelleGradBound > 0 ? phacelle : ''; const world = solid ? sdf : ''; const math = trimGlsl(cultmath, [erosion, common, world, stages[stage]]); - return `${HEADER}${defines}${worldDefines()}\n${math}\n${erosion}\n${common}\n${world}\n${stages[stage]}`; + return `${HEADER}${defines}${worldDefines()}\n${math}\n${erosion}\n${common}\n${world}\n${ + stages[stage] + }`; } diff --git a/src/app/features/scene/shaders/voxel.frag.glsl b/src/app/features/scene/shaders/voxel.frag.glsl new file mode 100644 index 00000000..93c162f7 --- /dev/null +++ b/src/app/features/scene/shaders/voxel.frag.glsl @@ -0,0 +1,94 @@ +// One pass, straight to the canvas: for every pixel, march down its screen column from the camera +// outward, one height lookup per step, until a column of terrain rises past the pixel. +// +// Projection is a shear, as in the classic voxel renderer: a point at depth z along the view axis +// whose terrain top is h projects to ndc y = horizon + (h - camY) / (z * tanHalf.y). A pixel below +// the horizon is covered by the first sample whose top reaches it, which is the same pixel a +// running-horizon column renderer paints, found without carrying the horizon between pixels. The +// camera is above the highest terrain, so nothing is covered above the horizon (no lookups at all), +// and below it no sample shallower than (camY - VOX_HB) / (tanHalf.y * -rel) can reach the pixel, +// so the march starts there. +uniform sampler2D u_height; // RG8, the ring of 16-bit heights +uniform sampler2D u_sky; // baked sky, gamma-encoded +// u_camPos and u_tanHalf (x: tan(fov/2) * aspect, y: tan(fov/2)) come from the shared block. +uniform vec2 u_fwd; // unit forward on the ground plane (x, z) +uniform vec2 u_right; // unit right on the ground plane +uniform float u_horizon; // ndc y of the horizon +uniform vec3 u_grass; +uniform vec3 u_rock; +uniform float u_frame; + +in vec2 v_uv; +layout(location = 0) out vec4 o_color; // rgb gamma-encoded; with TRACE_STATS, a: lookups spent / 255 + +float cellHeight(ivec2 c) +{ + vec2 t = floor(texelFetch(u_height, c & (VOX_RING - 1), 0).rg * 255.0 + 0.5); + return mix(-VOX_HB, VOX_HB, (t.x * 256.0 + t.y) / 65535.0); +} + +vec3 skyAt(float az, float el) +{ + vec3 c = texture(u_sky, vec2(az * 0.15915494 + 0.5, el * 0.63661977)).rgb; + return pow(c, vec3(2.2)); +} + +void main() +{ + vec2 ndc = v_uv * 2.0 - 1.0; + vec2 d = u_fwd + u_right * (ndc.x * u_tanHalf.x); // ground direction per unit of view depth + float dl = length(d); + float rel = ndc.y - u_horizon; // ndc height above the horizon + float az = atan(d.y, d.x); + float camY = u_camPos.y; + float zFar = VOX_FAR / dl; + + int lookups = 0; + float z = 0.0; + float h = 0.0; + ivec2 cell = ivec2(0); + bool hit = false; + if (rel < 0.0) + { + z = max(VOX_NEAR, (camY - VOX_HB) / (-rel * u_tanHalf.y)); + for (int i = 0; i < VOX_MAX_LOOKUPS; i++) + { + if (z >= zFar) + break; + cell = ivec2(floor((u_camPos.xz + d * z) * (1.0 / VOX_CELL))); + h = cellHeight(cell); + lookups++; + if (rel <= (h - camY) / (z * u_tanHalf.y)) + { + hit = true; + break; + } + z += max(VOX_STEP_MIN, z * VOX_STEP_REL); + } + } + + vec3 horizonCol = skyAt(az, 0.0); + vec3 col; + if (hit) + { + float hx = cellHeight(cell + ivec2(1, 0)); + float hz = cellHeight(cell + ivec2(0, 1)); + vec3 n = normalize(vec3((h - hx) / VOX_CELL, 1.0, (h - hz) / VOX_CELL)); + float lit = max(dot(n, u_sunDir), 0.0); + float high = smoothstep(0.1, 0.9, (h + VOX_HB) / (2.0 * VOX_HB)); + vec3 albedo = mix(u_grass, u_rock, clamp((1.0 - n.y) * 4.0 + high * 0.6, 0.0, 1.0)); + col = albedo * (u_skyTop * 5.0 + u_fogColor * 2.0 + u_sunColor * (0.3 * lit)); + col = mix(col, horizonCol * 0.6 + u_fogColor, 1.0 - exp(-z * dl * VOX_FOG)); + } + else + { + float el = rel > 0.0 ? atan(rel * u_tanHalf.y, dl) : 0.0; + col = skyAt(az, el); + } + + float dither = (ign(gl_FragCoord.xy, u_frame) - 0.5) / 255.0; + o_color = vec4(pow(clamp(col, 0.0, 1.0), vec3(1.0 / 2.2)) + dither, 1.0); +#ifdef TRACE_STATS + o_color.a = float(lookups) / 255.0; +#endif +} diff --git a/src/app/features/scene/shaders/voxelHeight.frag.glsl b/src/app/features/scene/shaders/voxelHeight.frag.glsl new file mode 100644 index 00000000..b0295d4f --- /dev/null +++ b/src/app/features/scene/shaders/voxelHeight.frag.glsl @@ -0,0 +1,22 @@ +// Ring generation: writes the height of the world cell each texel of the ring holds. A pure function +// of the cell, so any order of writes gives the same ring. The camera's draw call scissors this to +// the columns and rows it just admitted. +uniform ivec2 u_origin; // lowest world cell of the ring's window + +in vec2 v_uv; +layout(location = 0) out vec4 o_height; // rg: height as 16 bits across [-VOX_HB, VOX_HB], high byte first + +void main() +{ + ivec2 texel = ivec2(gl_FragCoord.xy); + ivec2 cell = u_origin + ((texel - u_origin) & (VOX_RING - 1)); + vec2 xz = (vec2(cell) + 0.5) * VOX_CELL; + // The ray-march scene's terrain, unmasked: fbm envelope plus Phacelle ridges. + float h = W_AMP * terrainFbm(xz); +#if W_ERODE_ENABLED + h += W_ERODE_AMP * terrainPhacelle(xz).cos.w; +#endif + float q = floor(clamp((h + VOX_HB) / (2.0 * VOX_HB), 0.0, 1.0) * 65535.0 + 0.5); + float hi = floor(q / 256.0); + o_height = vec4(hi / 255.0, (q - hi * 256.0) / 255.0, 0.0, 1.0); +} diff --git a/src/app/features/scene/shaders/voxelSky.frag.glsl b/src/app/features/scene/shaders/voxelSky.frag.glsl new file mode 100644 index 00000000..2e0db3cf --- /dev/null +++ b/src/app/features/scene/shaders/voxelSky.frag.glsl @@ -0,0 +1,25 @@ +// Sky bake, run once: azimuth across, elevation up from the horizon to the zenith, with cloud +// bands. Stored gamma-encoded because the target is 8 bits. +in vec2 v_uv; +layout(location = 0) out vec4 o_sky; + +void main() +{ + float az = (v_uv.x - 0.5) * 6.2831853; + float el = v_uv.y * 1.5707963; + vec3 rd = vec3(cos(el) * cos(az), sin(el), cos(el) * sin(az)); + // Dusk: the horizon glow gives way to the night blue within the visible band, not at the zenith. + vec3 c = mix(u_skyHorizon, u_skyTop, smoothstep(0.0, 0.2, rd.y)); + c += u_sunColor * (0.5 * pow(max(dot(rd, u_sunDir), 0.0), 64.0)); + + // Bands: noise stretched along the horizon, layered by elevation. Taken from the direction + // vector so the seam at +-pi is seamless. + vec3 q = vec3(rd.x * 2.2, rd.y * 11.0, rd.z * 2.2); + float n = 0.5 + 0.5 * cultmath_snoise(q) + 0.25 * cultmath_snoise(q * 2.3 + 7.0); + float cover = smoothstep(0.62, 0.95, n) * smoothstep(0.02, 0.2, el) * (1.0 - smoothstep(0.55, 1.1, el)); + float sunSide = pow(max(dot(rd, u_sunDir), 0.0), 3.0); + vec3 cloud = u_skyHorizon * 0.9 + u_skyTop * 4.0 + u_sunColor * (0.07 * sunSide); + c = mix(c, cloud, cover * 0.8); + + o_sky = vec4(pow(clamp(c, 0.0, 1.0), vec3(1.0 / 2.2)), 1.0); +} diff --git a/src/app/features/scene/voxel/Voxel.test.ts b/src/app/features/scene/voxel/Voxel.test.ts new file mode 100644 index 00000000..acadfefc --- /dev/null +++ b/src/app/features/scene/voxel/Voxel.test.ts @@ -0,0 +1,210 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { fakeCanvas, fakeGl } from '../fakeGl'; +import heightStage from '../shaders/voxelHeight.frag.glsl?raw'; +import { fragmentSource } from '../shaderSource'; +import { startBackgroundScene } from '../index'; +import { createVoxelScene, SCALE_LEVELS } from './Voxel'; +import { VOXEL, voxelDefines } from './voxelWorld'; + +const N = VOXEL.ring; +let rafQueue: Array<(t: number) => void>; +let win: EventTarget; +let motion: EventTarget & { matches: boolean }; + +beforeEach(() => { + rafQueue = []; + motion = Object.assign(new EventTarget(), { matches: false }); + win = Object.assign(new EventTarget(), { devicePixelRatio: 1, matchMedia: () => motion }); + vi.stubGlobal('window', win); + vi.stubGlobal('document', Object.assign(new EventTarget(), { visibilityState: 'visible' })); + vi.stubGlobal('requestAnimationFrame', (cb: (t: number) => void) => rafQueue.push(cb)); + vi.stubGlobal('cancelAnimationFrame', () => {}); +}); +afterEach(() => vi.unstubAllGlobals()); + +const runFrame = (now: number) => { + const cb = rafQueue.shift(); + if (!cb) throw new Error('no frame was scheduled'); + cb(now); +}; +const asCanvas = (c: ReturnType) => c as unknown as HTMLCanvasElement; + +/** A voxel scene on a fake GL whose camera follows `time.t`, seconds. */ +function build(extra: Partial[0]> = {}) { + const { gl, calls } = fakeGl(); + const canvas = fakeCanvas(gl); + const time = { t: 0 }; + const scene = createVoxelScene({ + canvas: asCanvas(canvas), + clock: () => time.t, + ...extra, + }); + return { scene, calls, canvas, time }; +} + +describe('voxel scene contract', () => { + it("'off' returns null without a context; no WebGL2 says so", () => { + const { gl } = fakeGl(); + const canvas = fakeCanvas(gl); + expect(createVoxelScene({ canvas: asCanvas(canvas), tier: 'off' })).toBeNull(); + expect(canvas.getContext).not.toHaveBeenCalled(); + const onUnavailable = vi.fn(); + expect(createVoxelScene({ canvas: asCanvas(fakeCanvas(null)), onUnavailable })).toBeNull(); + expect(onUnavailable).toHaveBeenCalledTimes(1); + expect(onUnavailable).toHaveBeenCalledWith('no-webgl2'); + }); + + it('needs no extension and allocates no float target: only RG8 and RGBA8 textures', () => { + const { calls } = build(); + runFrame(1000); + expect(calls.getExtension).toBeUndefined(); + const formats = calls.texStorage2D.mock.calls.map((c) => c[2]); + expect(formats.sort()).toEqual([208, 209]); // RG8 ring, RGBA8 sky + }); + + it('reports a compile failure through onCompileFail and returns null', () => { + const { gl } = fakeGl(2); + const onCompileFail = vi.fn(); + expect(createVoxelScene({ canvas: asCanvas(fakeCanvas(gl)), onCompileFail })).toBeNull(); + expect(onCompileFail).toHaveBeenCalledTimes(1); + }); + + it("'still' draws one frame and schedules no more; 'full' keeps going", () => { + const still = build({ tier: 'still' }); + runFrame(1000); + expect(rafQueue).toHaveLength(0); + expect(still.scene).not.toBeNull(); + rafQueue.length = 0; + build({ tier: 'full' }); + runFrame(1000); + expect(rafQueue).toHaveLength(1); + }); + + it('login() starts a pull-back and a lost context ends the scene', () => { + const lost = vi.fn(); + const { scene, canvas } = build({ onContextLost: lost }); + runFrame(1000); + scene?.login(); + canvas.dispatchEvent(new Event('webglcontextlost')); + expect(lost).toHaveBeenCalledTimes(1); + rafQueue.length = 0; + scene?.login(); + expect(rafQueue).toHaveLength(0); + }); +}); + +describe('voxel ring generation', () => { + it('the first frame bakes the sky, fills the whole ring once, and draws the terrain', () => { + const { calls } = build(); + runFrame(1000); + expect(calls.drawArrays).toHaveBeenCalledTimes(3); + expect(calls.scissor.mock.calls).toEqual([[0, 0, N, N]]); + }); + + it('a frame in the same cell generates nothing', () => { + const { calls } = build(); + runFrame(1000); + runFrame(1034); + expect(calls.drawArrays).toHaveBeenCalledTimes(4); // one more draw: the terrain + expect(calls.scissor).toHaveBeenCalledTimes(1); + }); + + it('crossing a cell writes strips, never the whole ring again', () => { + const { calls, time } = build(); + runFrame(1000); + time.t = 1; // 14 units along the rail: a cell or two + runFrame(1034); + const strips = calls.scissor.mock.calls.slice(1); + expect(strips.length).toBeGreaterThan(0); + for (const [, , w, h] of strips) { + expect((w === N) !== (h === N)).toBe(true); // one side the whole ring, the other a few cells + expect(Math.min(w, h)).toBeLessThanOrEqual(3); + } + }); + + it('a long pause jumps the camera past the ring and regenerates it whole', () => { + const { calls, time } = build(); + runFrame(1000); + time.t = 3600; // an hour on the rail + runFrame(1034); + expect(calls.scissor.mock.calls.at(-1)).toEqual([0, 0, N, N]); + }); +}); + +describe('voxel measurement and adaptation', () => { + it('reads lookups per pixel back from alpha and times the draw, only when asked', () => { + const plain = build(); + runFrame(1000); + expect(plain.calls.readPixels).toBeUndefined(); + rafQueue.length = 0; + const onTraceStats = vi.fn(); + const onFrameStats = vi.fn(); + const m = build({ onTraceStats, onFrameStats }); + runFrame(1000); + runFrame(1034); + expect(m.calls.readPixels).toHaveBeenCalledTimes(2); // frame 0 of every 8: a one-texel sync, then the counted frame + expect(onTraceStats).toHaveBeenCalledTimes(1); + expect(m.canvas.getContext.mock.calls[0][1].alpha).toBe(false); // the canvas is opaque; the count is drawn off screen + expect(onFrameStats).toHaveBeenCalledTimes(1); // the first frame has no predecessor + expect(onFrameStats.mock.calls[0][0].frameMs).toBe(34); + }); + + it('steps the drawing buffer down when frames keep missing the cap, and never back up', () => { + const { canvas } = build({ unthrottled: true }); + let now = 1000; + runFrame(now); + expect(canvas.width).toBe(Math.round(400 * SCALE_LEVELS[0].scale)); + for (let i = 0; i < 60; i++) runFrame((now += 100)); + expect(canvas.width).toBe(Math.round(400 * SCALE_LEVELS[1].scale)); + for (let i = 0; i < 200; i++) runFrame((now += 10)); + expect(canvas.width).toBe(Math.round(400 * SCALE_LEVELS[1].scale)); + }); + + it("'low' starts below the top of the ladder", () => { + const { canvas } = build({ tier: 'low' }); + runFrame(1000); + expect(canvas.width).toBe(Math.round(400 * SCALE_LEVELS[2].scale)); + }); +}); + +describe('voxel shaders', () => { + it('the march is capped at the lookup budget and the pass uses no extension', () => { + const src = fragmentSource('voxel', voxelDefines()); + expect(src).toContain(`#define VOX_MAX_LOOKUPS ${VOXEL.maxLookups}`); + expect(src).not.toContain('#extension'); + expect(src).toContain('texelFetch(u_height'); + }); + + it('ring generation is a pure function of the cell and uses the shipped terrain', () => { + const src = fragmentSource('voxelHeight', voxelDefines()); + expect(src).toContain('terrainFbm(xz)'); + expect(src).toContain('terrainPhacelle(xz)'); + expect(heightStage).not.toContain('u_time'); // nothing in the height depends on the clock + expect(src).toContain(`#define VOX_RING ${N}`); + }); +}); + +describe('the door picks the style', () => { + it('voxel by default: one frame is sky, ring and terrain, three draws', async () => { + const { gl, calls } = fakeGl(); + const scene = await startBackgroundScene( + { tier: 'still' }, + {}, + { canvas: asCanvas(fakeCanvas(gl)) } + ); + expect(scene).not.toBeNull(); + runFrame(1000); + expect(calls.drawArrays).toHaveBeenCalledTimes(3); + }); + + it("'raymarch' keeps the sphere-traced scene", async () => { + const { gl, calls } = fakeGl(); + await startBackgroundScene( + { tier: 'still', style: 'raymarch' }, + {}, + { canvas: asCanvas(fakeCanvas(gl)) } + ); + runFrame(1000); + expect(calls.drawArrays).toHaveBeenCalledTimes(5); + }); +}); diff --git a/src/app/features/scene/voxel/Voxel.ts b/src/app/features/scene/voxel/Voxel.ts new file mode 100644 index 00000000..bcfc94b7 --- /dev/null +++ b/src/app/features/scene/voxel/Voxel.ts @@ -0,0 +1,286 @@ +// The voxel terrain scene: a wrapping ring of cell heights around the camera, drawn by one fullscreen +// pass. Same createScene contract as the ray-march scene, but WebGL2 core only: no extensions, no +// float targets. Heights are 16 bits in an RG8 ring; the sky is baked once into RGBA8; the drawing +// buffer is the internal resolution, and CSS scales it up. +import type { FrameStats, Scene, SceneOptions } from '../Scene'; +import { BudgetLadder } from '../budget'; +import { pullProgress } from '../camera'; +import { FRAME_INTERVAL_MS, startFrameLoop } from '../frameLoop'; +import { linkStage, ShaderCompileError } from '../link'; +import { PALETTE } from '../palette'; +import { Cell, ringRects, windowOrigin } from './ring'; +import { voxelPose } from './rails'; +import { VOXEL, voxelDefines } from './voxelWorld'; + +const MAX_DPR = 1.5; +const SKY_W = 512; +const SKY_H = 128; +/** Measurement readback of lookups per pixel, every this many frames. */ +const READBACK_EVERY = 8; +/** Median cadence above this, over a window, drops one level: the 30 fps cap with some grace. */ +const SLOW_MS = FRAME_INTERVAL_MS * 1.2; + +export interface ScaleLevel { + /** Drawing-buffer size as a fraction of the canvas's CSS size times device pixel ratio. */ + scale: number; +} + +/** Cheapest last. The ladder only descends. */ +export const SCALE_LEVELS: readonly ScaleLevel[] = [ + { scale: 0.75 }, + { scale: 0.6 }, + { scale: 0.5 }, + { scale: 0.4 }, +]; +const LOW_START_LEVEL = 2; + +export function createVoxelScene(opts: SceneOptions): Scene | null { + const { canvas } = opts; + const tier = opts.tier ?? 'full'; + if (tier === 'off') return null; + const measuring = !!opts.onTraceStats; + const gl = canvas.getContext('webgl2', { + antialias: false, + alpha: false, + premultipliedAlpha: false, + depth: false, + stencil: false, + powerPreference: 'low-power', + }); + if (!gl) { + opts.onUnavailable?.('no-webgl2'); + return null; + } + + // `counted` is the terrain pass with its lookup count written to alpha; it exists only for a + // measuring scene, which draws it to an offscreen target (the canvas has no alpha to spare). + type Name = 'height' | 'sky' | 'voxel' | 'counted'; + const programs = {} as Record; + const sources: Array<[Name, 'voxelHeight' | 'voxelSky' | 'voxel', string]> = [ + ['height', 'voxelHeight', ''], + ['sky', 'voxelSky', ''], + ['voxel', 'voxel', ''], + ]; + if (measuring) sources.push(['counted', 'voxel', '#define TRACE_STATS 1\n']); + try { + sources.forEach(([name, stage, extra]) => { + programs[name] = linkStage(gl, stage, opts.patchSource, voxelDefines() + extra); + }); + } catch (e) { + Object.values(programs).forEach((p) => gl.deleteProgram(p)); + if (!(e instanceof ShaderCompileError)) throw e; + opts.onCompileFail?.(e); + return null; + } + + const uniforms = new Map>(); + const loc = (p: WebGLProgram, name: string) => { + let m = uniforms.get(p); + if (!m) uniforms.set(p, (m = new Map())); + if (!m.has(name)) m.set(name, gl.getUniformLocation(p, name)); + return m.get(name) ?? null; + }; + const vec3 = (p: WebGLProgram, name: string, v: readonly number[]) => + gl.uniform3fv(loc(p, name), v as number[]); + const palette = (p: WebGLProgram) => { + vec3(p, 'u_sunDir', PALETTE.sunDir); + vec3(p, 'u_sunColor', PALETTE.sunColor); + vec3(p, 'u_skyTop', PALETTE.skyTop); + vec3(p, 'u_skyHorizon', PALETTE.skyHorizon); + vec3(p, 'u_fogColor', PALETTE.fogColor); + }; + + const vao = gl.createVertexArray(); + gl.bindVertexArray(vao); + const draw = () => gl.drawArrays(gl.TRIANGLES, 0, 3); + + const makeTexture = (w: number, h: number, format: number, filter: number, wrapS: number) => { + const tex = gl.createTexture()!; + gl.bindTexture(gl.TEXTURE_2D, tex); + gl.texStorage2D(gl.TEXTURE_2D, 1, format, w, h); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filter); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filter); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrapS); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + return tex; + }; + const fboFor = (tex: WebGLTexture) => { + const fbo = gl.createFramebuffer()!; + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo); + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0); + return fbo; + }; + + // The sky is baked once: nothing in it moves. + const skyTex = makeTexture(SKY_W, SKY_H, gl.RGBA8, gl.LINEAR, gl.REPEAT); + { + const fbo = fboFor(skyTex); + gl.viewport(0, 0, SKY_W, SKY_H); + gl.useProgram(programs.sky); + palette(programs.sky); + draw(); + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + gl.deleteFramebuffer(fbo); + gl.deleteProgram(programs.sky); + } + + const ringTex = makeTexture(VOXEL.ring, VOXEL.ring, gl.RG8, gl.NEAREST, gl.REPEAT); + const ringFbo = fboFor(ringTex); + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + let ringCell: Cell | undefined; + + /** Fill the ring for a camera in `cell`: only the columns and rows it just admitted. */ + const generate = (cell: Cell) => { + const rects = ringRects(ringCell, cell); + ringCell = cell; + if (!rects.length) return; + gl.bindFramebuffer(gl.FRAMEBUFFER, ringFbo); + gl.viewport(0, 0, VOXEL.ring, VOXEL.ring); + gl.useProgram(programs.height); + const o = windowOrigin(cell); + gl.uniform2i(loc(programs.height, 'u_origin'), o.x, o.z); + gl.enable(gl.SCISSOR_TEST); + for (const r of rects) { + gl.scissor(r.x, r.y, r.w, r.h); + draw(); + } + gl.disable(gl.SCISSOR_TEST); + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + }; + + const still = tier === 'still'; + const ladder = new BudgetLadder( + SLOW_MS, + 45, + tier === 'low' ? LOW_START_LEVEL : 0, + SCALE_LEVELS + ); + const scale = () => (opts.fixedLevel ? opts.fixedLevel.solidScale : ladder.current.scale); + + let canvasW = 0; + let canvasH = 0; + let sizedFor = 0; + const ensureSize = () => { + const dpr = Math.min(window.devicePixelRatio || 1, MAX_DPR); + const s = scale(); + const w = Math.max(2, Math.round(canvas.clientWidth * dpr * s)); + const h = Math.max(2, Math.round(canvas.clientHeight * dpr * s)); + if (w === canvasW && h === canvasH) return; + canvasW = w; + canvasH = h; + sizedFor = s; + canvas.width = w; + canvas.height = h; + }; + + // The measuring scene's offscreen copy of the terrain pass, sized like the canvas. + const counted: { tex?: WebGLTexture; fbo?: WebGLFramebuffer; w: number; h: number } = { + w: 0, + h: 0, + }; + const resizeCounted = () => { + if (counted.tex) gl.deleteTexture(counted.tex); + if (counted.fbo) gl.deleteFramebuffer(counted.fbo); + counted.tex = makeTexture(canvasW, canvasH, gl.RGBA8, gl.NEAREST, gl.CLAMP_TO_EDGE); + counted.fbo = fboFor(counted.tex); + counted.w = canvasW; + counted.h = canvasH; + }; + + const start = performance.now(); + let loginAt: number | undefined; + let frame = 0; + let prevNow: number | undefined; + const loop = startFrameLoop({ + canvas, + still, + unthrottled: opts.unthrottled, + render, + onContextLost: opts.onContextLost, + }); + + function render(now: number) { + ensureSize(); + const frozen = loop.frozen; + const time = opts.clock ? opts.clock() : frozen ? 0 : (now - start) / 1000; + let elapsed: number | undefined; + if (loginAt !== undefined) elapsed = frozen ? 1e9 : (now - loginAt) / 1000; + const pose = voxelPose(opts.fixedPull ?? pullProgress(elapsed), time); + const [px, py, pz] = pose.position; + generate({ x: Math.floor(px / VOXEL.cell), z: Math.floor(pz / VOXEL.cell) }); + + const timed = measuring && frame % READBACK_EVERY === 0; + const t0 = timed ? performance.now() : 0; + const drawTerrain = (p: WebGLProgram) => { + gl.viewport(0, 0, canvasW, canvasH); + gl.useProgram(p); + palette(p); + vec3(p, 'u_grass', PALETTE.grass); + vec3(p, 'u_rock', PALETTE.rock); + gl.uniform3f(loc(p, 'u_camPos'), px, py, pz); + gl.uniform2f(loc(p, 'u_fwd'), Math.cos(pose.yaw), Math.sin(pose.yaw)); + gl.uniform2f(loc(p, 'u_right'), Math.sin(pose.yaw), -Math.cos(pose.yaw)); + const tanY = Math.tan(pose.fov / 2); + gl.uniform2f(loc(p, 'u_tanHalf'), tanY * (canvasW / canvasH), tanY); + // The shear: the horizon sits above the centre by the amount the camera looks down. + gl.uniform1f(loc(p, 'u_horizon'), -Math.tan(pose.pitch) / tanY); + gl.uniform1f(loc(p, 'u_frame'), frame); + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, ringTex); + gl.uniform1i(loc(p, 'u_height'), 0); + gl.activeTexture(gl.TEXTURE1); + gl.bindTexture(gl.TEXTURE_2D, skyTex); + gl.uniform1i(loc(p, 'u_sky'), 1); + draw(); + }; + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + drawTerrain(programs.voxel); + + let renderMs: number | undefined; + if (timed) { + // One-texel synchronous read: it waits for the draw, so the time is the draw's, which a + // queued GPU (SwiftShader and phones alike) would otherwise not report. + gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(4)); + renderMs = performance.now() - t0; + // Then the same frame again with its lookup counts in alpha, off screen, and read back. + if (counted.w !== canvasW || counted.h !== canvasH) resizeCounted(); + gl.bindFramebuffer(gl.FRAMEBUFFER, counted.fbo); + drawTerrain(programs.counted); + const px4 = new Uint8Array(canvasW * canvasH * 4); + gl.readPixels(0, 0, canvasW, canvasH, gl.RGBA, gl.UNSIGNED_BYTE, px4); + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + let sum = 0; + for (let i = 3; i < px4.length; i += 4) sum += px4[i]; + const mean = sum / (canvasW * canvasH); + opts.onTraceStats?.({ traceSteps: mean, prepassSteps: 0, stepsPerPixel: mean }); + } + if (prevNow !== undefined) { + const frameMs = now - prevNow; + opts.onFrameStats?.({ frameMs, renderMs, scale: sizedFor, size: [canvasW, canvasH] }); + if (!opts.fixedLevel && ladder.push(frameMs)) canvasW = 0; // resize on the next frame + } + prevNow = now; + frame += 1; + } + + return { + login() { + if (still || loop.disposed) return; // a still has no pull-back + loginAt = performance.now(); + loop.restart(); + }, + dispose() { + if (loop.disposed) return; + loop.stop(); + gl.deleteTexture(ringTex); + gl.deleteTexture(skyTex); + gl.deleteFramebuffer(ringFbo); + if (counted.tex) gl.deleteTexture(counted.tex); + if (counted.fbo) gl.deleteFramebuffer(counted.fbo); + if (measuring) gl.deleteProgram(programs.counted); + gl.deleteProgram(programs.height); + gl.deleteProgram(programs.voxel); + gl.deleteVertexArray(vao); + }, + }; +} diff --git a/src/app/features/scene/voxel/rails.test.ts b/src/app/features/scene/voxel/rails.test.ts new file mode 100644 index 00000000..41932ad8 --- /dev/null +++ b/src/app/features/scene/voxel/rails.test.ts @@ -0,0 +1,43 @@ +import { describe, expect, it } from 'vitest'; +import { pullProgress } from '../camera'; +import { RAIL_HEADING, RAIL_SPEED, voxelPose } from './rails'; +import { VOXEL, heightBound } from './voxelWorld'; + +describe('voxel rails camera', () => { + it('stays above the highest terrain at every time and pull-back', () => { + for (let t = 0; t < 7200; t += 13.7) + for (const pull of [0, 0.3, 1]) + expect(voxelPose(pull, t).position[1]).toBeGreaterThanOrEqual( + heightBound() + VOXEL.clearance + ); + }); + + it('slides along the heading at the rail speed, swaying within a bound', () => { + const a = voxelPose(0, 100).position; + const b = voxelPose(0, 200).position; + const along = (b[0] - a[0]) * Math.cos(RAIL_HEADING) + (b[2] - a[2]) * Math.sin(RAIL_HEADING); + expect(along).toBeCloseTo(RAIL_SPEED * 100, 5); + const across = (p: readonly number[]) => + -p[0] * Math.sin(RAIL_HEADING) + p[2] * Math.cos(RAIL_HEADING); + expect(Math.abs(across(a))).toBeLessThanOrEqual(40); + expect(Math.abs(across(b))).toBeLessThanOrEqual(40); + }); + + it('yaws freely either side of the heading, bounded', () => { + const yaws = Array.from({ length: 500 }, (_, i) => voxelPose(0, i * 5).yaw - RAIL_HEADING); + expect(Math.max(...yaws)).toBeGreaterThan(0.3); + expect(Math.min(...yaws)).toBeLessThan(-0.3); + expect(Math.max(...yaws.map(Math.abs))).toBeLessThanOrEqual(0.35 + 1e-9); + }); + + it('login lifts the camera and tips it down, and a time step moves it a little', () => { + const rest = voxelPose(pullProgress(undefined), 50); + const pulled = voxelPose(pullProgress(99), 50); + expect(pulled.position[1]).toBeGreaterThan(rest.position[1]); + expect(pulled.pitch).toBeLessThan(rest.pitch); + const next = voxelPose(0, 50.033); + expect( + Math.hypot(next.position[0] - rest.position[0], next.position[2] - rest.position[2]) + ).toBeLessThan(1); + }); +}); diff --git a/src/app/features/scene/voxel/rails.ts b/src/app/features/scene/voxel/rails.ts new file mode 100644 index 00000000..787c78a7 --- /dev/null +++ b/src/app/features/scene/voxel/rails.ts @@ -0,0 +1,38 @@ +// The voxel scene's camera: a free-yaw rail. The camera slides along a fixed heading while its yaw +// wanders either side of it, always above the highest terrain; login() lifts it and tips it down. +// Pure functions of time, so the path is testable without a GL context. +import { heightBound, VOXEL } from './voxelWorld'; + +export interface VoxelPose { + /** World x, y (up), z. */ + position: readonly [number, number, number]; + /** Radians about +y; 0 looks down +x. */ + yaw: number; + /** Radians, negative looks down. */ + pitch: number; + /** Vertical field of view in radians. */ + fov: number; +} + +/** The rail's heading and the world units it covers per second. */ +export const RAIL_HEADING = 0.6; +export const RAIL_SPEED = 14; +const SWAY = 40; +const YAW_SWING = 0.35; + +/** @param pull 0..1 from pullProgress. @param time seconds since the scene started. */ +export function voxelPose(pull: number, time: number): VoxelPose { + const hx = Math.cos(RAIL_HEADING); + const hz = Math.sin(RAIL_HEADING); + const sway = SWAY * Math.sin(time * 0.05); + return { + position: [ + hx * RAIL_SPEED * time - hz * sway, + heightBound() + VOXEL.clearance + VOXEL.pullClimb * pull, + hz * RAIL_SPEED * time + hx * sway, + ], + yaw: RAIL_HEADING + YAW_SWING * Math.sin(time * 0.07), + pitch: -0.1 - 0.12 * pull, + fov: 1.0 - 0.1 * pull, + }; +} diff --git a/src/app/features/scene/voxel/ring.test.ts b/src/app/features/scene/voxel/ring.test.ts new file mode 100644 index 00000000..15ba0604 --- /dev/null +++ b/src/app/features/scene/voxel/ring.test.ts @@ -0,0 +1,94 @@ +import { describe, expect, it } from 'vitest'; +import { Cell, cellAt, ringRects, windowOrigin } from './ring'; +import { HALF_RING, VOXEL } from './voxelWorld'; + +const N = VOXEL.ring; + +/** What each ring texel holds after applying rewrites: the world cell it was last written as, x then z. */ +type Ring = Int32Array; +const UNWRITTEN = -2147483648; + +function applyRects(ring: Ring, rects: ReturnType, to: Cell) { + const o = windowOrigin(to); + for (const r of rects) + for (let y = r.y; y < r.y + r.h; y++) + for (let x = r.x; x < r.x + r.w; x++) { + ring[(y * N + x) * 2] = cellAt(o.x, x); + ring[(y * N + x) * 2 + 1] = cellAt(o.z, y); + } +} + +/** Index of the first texel where the rings differ, or -1. (toEqual on 131k numbers is far too slow.) */ +const firstDifference = (a: Ring, b: Ring) => a.findIndex((v, i) => v !== b[i]); + +const fill = (cell: Cell) => { + const ring: Ring = new Int32Array(N * N * 2).fill(UNWRITTEN); + applyRects(ring, ringRects(undefined, cell), cell); + return ring; +}; + +describe('height ring bookkeeping', () => { + it('the first window is the whole ring, and standing still rewrites nothing', () => { + expect(ringRects(undefined, { x: 5, z: -3 })).toEqual([{ x: 0, y: 0, w: N, h: N }]); + expect(ringRects({ x: 5, z: -3 }, { x: 5, z: -3 })).toEqual([]); + }); + + it('the window is the N x N block centred on the camera cell, one world cell per texel', () => { + const cam = { x: 1000, z: -777 }; + const o = windowOrigin(cam); + expect(o).toEqual({ x: cam.x - HALF_RING, z: cam.z - HALF_RING }); + const seen = new Set(); + for (let i = 0; i < N; i++) { + const cx = cellAt(o.x, i); + expect(cx).toBeGreaterThanOrEqual(o.x); + expect(cx).toBeLessThan(o.x + N); + expect(((cx % N) + N) % N).toBe(i); // the cell lives at its own residue + seen.add(String(cx)); + } + expect(seen.size).toBe(N); + }); + + it('after any walk of strip rewrites, every texel holds the cell a full fill would put there', () => { + let seed = 11; + const rand = () => (seed = (seed * 16807) % 2147483647) / 2147483647; + let cam: Cell = { x: -3, z: 250 }; // straddles the wrap on both axes + const ring = fill(cam); + for (let step = 0; step < 150; step++) { + // mostly single-cell moves, some multi-cell jumps, some diagonals, some standing still + const jump = rand() < 0.1 ? 40 : 2; + const next = { + x: cam.x + Math.round((rand() - 0.5) * jump), + z: cam.z + Math.round((rand() - 0.5) * jump), + }; + applyRects(ring, ringRects(cam, next), next); + cam = next; + expect(firstDifference(ring, fill(cam))).toBe(-1); + } + }); + + it('writes only what it must: the cells the move admitted, not one texel more', () => { + for (const [dx, dz] of [ + [1, 0], + [-1, 0], + [0, 1], + [0, -1], + [1, 1], + [-2, 3], + ]) { + const prev = { x: N - 1, z: 0 }; // wraps on x for positive dx + const rects = ringRects(prev, { x: prev.x + dx, z: prev.z + dz }); + const touched = new Set(); + for (const r of rects) + for (let y = r.y; y < r.y + r.h; y++) + for (let x = r.x; x < r.x + r.w; x++) touched.add(y * N + x); + const ax = Math.abs(dx); + const az = Math.abs(dz); + expect(touched.size).toBe(N * N - (N - ax) * (N - az)); + } + }); + + it('a move of a whole ring or more is a full rewrite', () => { + expect(ringRects({ x: 0, z: 0 }, { x: N, z: 0 })).toEqual([{ x: 0, y: 0, w: N, h: N }]); + expect(ringRects({ x: 0, z: 0 }, { x: 3, z: -N - 1 })).toEqual([{ x: 0, y: 0, w: N, h: N }]); + }); +}); diff --git a/src/app/features/scene/voxel/ring.ts b/src/app/features/scene/voxel/ring.ts new file mode 100644 index 00000000..bd61cfe5 --- /dev/null +++ b/src/app/features/scene/voxel/ring.ts @@ -0,0 +1,66 @@ +// The height ring's bookkeeping, as pure functions: which texels must be rewritten when the camera +// crosses into another cell. The ring is a torus: world cell (x, z) lives at texel (x mod N, z mod N), +// and the window of cells the camera can see is the N x N block centred on its cell. Moving one +// cell retires one column or row of cells and admits one, and the admitted cells reuse exactly the +// texels the retired ones held. +import { HALF_RING, VOXEL } from './voxelWorld'; + +const N = VOXEL.ring; + +export interface Cell { + x: number; + z: number; +} + +/** Texels to rewrite, in ring coordinates. */ +export interface Rect { + x: number; + y: number; + w: number; + h: number; +} + +/** The window's lowest cell for a camera in `camera`. */ +export const windowOrigin = (camera: Cell): Cell => ({ + x: camera.x - HALF_RING, + z: camera.z - HALF_RING, +}); + +export const mod = (a: number, n: number) => ((a % n) + n) % n; + +/** The world cell texel index `i` holds, along one axis, for a window starting at `origin`. */ +export const cellAt = (origin: number, i: number) => origin + mod(i - origin, N); + +/** `count` consecutive cells from `first`, as runs of ring texels (two when the run wraps). */ +function runs(first: number, count: number): Array<[number, number]> { + const start = mod(first, N); + if (start + count <= N) return [[start, count]]; + return [ + [start, N - start], + [0, start + count - N], + ]; +} + +/** + * The rewrites that take a ring filled for `prev` to one filled for `next`: the whole ring when + * there is no previous window or the move is a full ring or more, else the newly admitted columns + * and rows, and nothing when the cell has not changed. + */ +export function ringRects(prev: Cell | undefined, next: Cell): Rect[] { + if (!prev) return [{ x: 0, y: 0, w: N, h: N }]; + const dx = next.x - prev.x; + const dz = next.z - prev.z; + if (Math.abs(dx) >= N || Math.abs(dz) >= N) return [{ x: 0, y: 0, w: N, h: N }]; + const o0 = windowOrigin(prev); + const o1 = windowOrigin(next); + const out: Rect[] = []; + if (dx !== 0) { + const first = dx > 0 ? o0.x + N : o1.x; + for (const [x, w] of runs(first, Math.abs(dx))) out.push({ x, y: 0, w, h: N }); + } + if (dz !== 0) { + const first = dz > 0 ? o0.z + N : o1.z; + for (const [y, h] of runs(first, Math.abs(dz))) out.push({ x: 0, y, w: N, h }); + } + return out; +} diff --git a/src/app/features/scene/voxel/voxelWorld.ts b/src/app/features/scene/voxel/voxelWorld.ts new file mode 100644 index 00000000..4fbbd226 --- /dev/null +++ b/src/app/features/scene/voxel/voxelWorld.ts @@ -0,0 +1,50 @@ +// The voxel scene's constants. One owner: the shader defines below are generated from this object. +// The terrain itself is the ray-march scene's (../world.ts: fbm plus Phacelle erosion) with the +// plateau mask left out, sampled once per cell into a wrapping ring of heights. +import { terrainBounds } from '../world'; + +export const VOXEL = { + /** Texels per side of the wrapping height ring: world cell (x, z) lives at texel (x mod ring, z mod ring). */ + ring: 256, + /** World units per cell. */ + cell: 8, + /** Furthest sample, in cells from the camera. The ring holds 128 each way; the margin keeps a ray from reading cells the camera has not generated. */ + farCells: 120, + /** Height lookups one column march may spend. */ + maxLookups: 128, + /** First sample depth along the view axis. */ + near: 2, + /** A march step is max(stepMin, depth * stepRel): about a cell up close, coarser far away. */ + stepMin: 4.8, + stepRel: 0.02, + /** Fog: 1 - exp(-distance * fog) of the way to the horizon colour. */ + fog: 0.0016, + /** Camera altitude above the highest possible terrain, so the camera is never inside a column. */ + clearance: 30, + /** Extra altitude the login pull-back climbs. */ + pullClimb: 45, +} as const; + +/** Terrain heights lie in [-heightBound, heightBound] and are stored as 16 bits across that range. */ +export const heightBound = (): number => terrainBounds().maxHeight; + +/** Half the ring, in cells: the camera cell sits at the centre of the window. */ +export const HALF_RING = VOXEL.ring / 2; + +const f = (n: number) => (Number.isInteger(n) ? `${n}.0` : `${n}`); + +/** `#define` lines every voxel stage sees. */ +export function voxelDefines(): string { + return [ + `#define VOX_RING ${VOXEL.ring}`, + `#define VOX_CELL ${f(VOXEL.cell)}`, + `#define VOX_FAR ${f(VOXEL.farCells * VOXEL.cell)}`, + `#define VOX_MAX_LOOKUPS ${VOXEL.maxLookups}`, + `#define VOX_NEAR ${f(VOXEL.near)}`, + `#define VOX_STEP_MIN ${f(VOXEL.stepMin)}`, + `#define VOX_STEP_REL ${f(VOXEL.stepRel)}`, + `#define VOX_HB ${f(heightBound())}`, + `#define VOX_FOG ${VOXEL.fog}`, + '', + ].join('\n'); +}