From 2f970a649e1e0194b068de510e569ce42e4b37ee Mon Sep 17 00:00:00 2001 From: Nibu Date: Wed, 4 Nov 2026 23:26:44 +0000 Subject: [PATCH] scene: voxel terrain drawn as painter's-order instanced strips The fullscreen fragment march is replaced by one instance per screen column and depth step, drawn far to near with no depth test. The vertex shader fetches the strip's height and its nearer neighbour's from the RG8 ring (vertex texture fetch, WebGL2 core) and emits a quad from the projected top down to the nearer top, or the screen bottom for the first strip; the fragment is a flat colour by height, slope and fog. Strips nearer than any terrain could reach the screen are not drawn, and strips past a column's far plane are clipped. The drawing buffer is a fixed pixel budget in the canvas's aspect, 320x180 by default, with the ladder below it. The ring, its generation pass, the baked sky, the createScene contract and the flag are unchanged; the sky is now a small backdrop pass. FrameStats gains vertices and ring lookups per frame; the measuring pass counts fragments per pixel (overdraw) instead of march lookups. Harness: drive.cjs voxel takes SIZES, a voxelshots mode takes screenshots. Co-Authored-By: Claude Sonnet 5.5 --- harness/scene/README.md | 3 +- harness/scene/bundle.cjs | 2 +- harness/scene/drive.cjs | 154 ++++++++++++------ harness/scene/voxelDemo.ts | 9 +- src/app/features/scene/README.md | 38 +++-- src/app/features/scene/Scene.ts | 8 +- src/app/features/scene/link.ts | 4 +- src/app/features/scene/shaderSource.ts | 14 ++ .../features/scene/shaders/voxel.frag.glsl | 95 +---------- .../scene/shaders/voxelBackdrop.frag.glsl | 22 +++ .../scene/shaders/voxelStrips.vert.glsl | 95 +++++++++++ src/app/features/scene/voxel/Voxel.test.ts | 80 +++++++-- src/app/features/scene/voxel/Voxel.ts | 115 +++++++++---- .../features/scene/voxel/voxelWorld.test.ts | 46 ++++++ src/app/features/scene/voxel/voxelWorld.ts | 71 +++++++- 15 files changed, 539 insertions(+), 217 deletions(-) create mode 100644 src/app/features/scene/shaders/voxelBackdrop.frag.glsl create mode 100644 src/app/features/scene/shaders/voxelStrips.vert.glsl create mode 100644 src/app/features/scene/voxel/voxelWorld.test.ts diff --git a/harness/scene/README.md b/harness/scene/README.md index f6f5cf40..158c0f12 100644 --- a/harness/scene/README.md +++ b/harness/scene/README.md @@ -9,7 +9,8 @@ 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 voxel # voxel scene: lookups, vertices, overdraw, ms per frame at fixed poses and buffer sizes, POSES=pull:seconds SIZES=320x180,160x90 (BUFFER=canvas for a scene whose buffer is the canvas) + node drive.cjs voxelshots # voxel scene screenshots at the same SIZES and POSES 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 189318ca..9fade865 100644 --- a/harness/scene/bundle.cjs +++ b/harness/scene/bundle.cjs @@ -36,7 +36,7 @@ esbuild path.join(out, 'index.html'), 'Ratatoskr scene' + (voxel - ? '
device
' + ? '
device
' : demo ? '
device
' : '') + diff --git a/harness/scene/drive.cjs b/harness/scene/drive.cjs index 64889b8c..eb781250 100644 --- a/harness/scene/drive.cjs +++ b/harness/scene/drive.cjs @@ -1,5 +1,5 @@ // Drives the scene in headless Chromium (software GL unless the host has a GPU). -// usage: node drive.cjs [outdir] modes: compile | shots | measure +// usage: node drive.cjs [outdir] modes: compile | shots | measure | voxel | voxelshots // Needs playwright from NODE_PATH and PLAYWRIGHT_BROWSERS_PATH. Prints one JSON report. const { chromium } = require('playwright'); const path = require('path'); @@ -222,60 +222,112 @@ 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. + // The voxel scene at fixed poses (POSES=pull:seconds,...) and internal buffer sizes + // (SIZES=320x180,160x90): the viewport is set to the size, and the scale to the fraction of the + // 320x180 pixel budget that makes the drawing buffer that size (BUFFER=canvas: scale 1, for a scene + // whose buffer is the canvas), so a scene whose buffer follows the + // canvas (the march) and one whose buffer follows the budget (the strips) draw the same pixels. + // Per run: lookups per pixel and per frame, vertices, fragment overdraw where the scene reports + // it, and the median ms to draw one frame (a one-texel sync read). + const BUDGET = 320 * 180; report.runs = []; - for (const [w, h] of process.env.PORTRAIT === '0' - ? [[960, 540]] - : [ - [960, 540], - [540, 1200], - ]) { + for (const size of (process.env.SIZES || '320x180,256x144,160x90,162x360').split(',')) { + const [w, h] = size.split('x').map(Number); + const scale = process.env.BUFFER === 'canvas' ? 1 : +Math.sqrt((w * h) / BUDGET).toFixed(6); 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); - }, + await page.setViewportSize({ width: w, height: h }); + const [pull, t] = pose.split(':').map(Number); + const r = await page.evaluate( + ({ pull, t, scale, READS }) => + new Promise((res) => { + const ms = []; + const looks = []; + const over = []; + let frame; + const done = () => { + s.dispose(); + const med = (xs) => xs.sort((a, b) => a - b)[xs.length >> 1]; + const mean = (xs) => +(xs.reduce((a, b) => a + b, 0) / xs.length).toFixed(2); + res({ + size: frame.size, + readbacks: looks.length, + lookupsPerPixel: mean(looks.slice(1)), + overdraw: over.length ? mean(over.slice(1)) : undefined, + vertices: frame.vertices, + lookupsPerFrame: frame.lookups, + medianRenderMs: +med(ms.slice(1)).toFixed(1), }); - 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()); - }); + }; + 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 (x.overdraw !== undefined) over.push(x.overdraw); + if (looks.length >= READS) done(); + }, + onFrameStats: (x) => { + frame = x; + if (x.renderMs !== undefined) ms.push(x.renderMs); + }, + }); + if (!s) res({ error: 'createVoxelScene returned null' }); + }), + { pull, t, scale, READS: +(process.env.READS || 16) } + ); + report.runs.push({ viewport: [w, h], pull, t, scale, ...r }); + await page.evaluate(() => { + const c = document.getElementById('c'); + c.replaceWith(c.cloneNode()); + }); + } + } + } + + if (mode === 'voxelshots') { + // Screenshots of the voxel scene at SIZES and POSES, the viewport equal to the drawing buffer + // (see the voxel mode), one PNG each: vox-x--.png in outdir. + const BUDGET = 320 * 180; + report.shots = []; + for (const size of (process.env.SIZES || '320x180').split(',')) { + const [w, h] = size.split('x').map(Number); + const scale = process.env.BUFFER === 'canvas' ? 1 : +Math.sqrt((w * h) / BUDGET).toFixed(6); + for (const pose of (process.env.POSES || '0:0,0:60,1:60').split(',')) { + await page.setViewportSize({ width: w, height: h }); + const [pull, t] = pose.split(':').map(Number); + const ok = await page.evaluate( + ({ pull, t, scale }) => + new Promise((res) => { + let n = 0; + const s = window.__scene.createVoxelScene({ + canvas: document.getElementById('c'), + unthrottled: true, + fixedPull: pull, + clock: () => t, + fixedLevel: { solidScale: scale }, + onFrameStats: () => { + if (++n === 3) res(true); + }, + }); + window.__v = s; + if (!s) res(false); + }), + { pull, t, scale } + ); + const file = `vox-${size}-${pull}-${t}.png`; + if (ok) { + await page.waitForTimeout(100); + await page.screenshot({ path: path.join(outdir, file) }); + report.shots.push(file); } + await page.evaluate(() => { + window.__v?.dispose(); + const c = document.getElementById('c'); + c.replaceWith(c.cloneNode()); + }); } } } diff --git a/harness/scene/voxelDemo.ts b/harness/scene/voxelDemo.ts index ca046d11..1f97d66d 100644 --- a/harness/scene/voxelDemo.ts +++ b/harness/scene/voxelDemo.ts @@ -1,5 +1,5 @@ -// 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. +// Standalone page: the voxel scene full-window with a readout of ring lookups per frame, vertices, +// fragment overdraw 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'; @@ -55,10 +55,11 @@ setInterval(() => { 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}` + `frame ms ${cadence.toFixed(1)} (cadence; the cap is 33.3) buffer ${frames.size.join('x')} at scale ${frames.scale}`, + `lookups/frame ${frames.lookups} vertices/frame ${frames.vertices}` ); } - if (trace) lines.push(`lookups/pixel ${trace.traceSteps.toFixed(2)} draw ms ${drawMs?.toFixed(1)} (one frame in 8, synced)`); + if (trace) lines.push(`lookups/pixel ${trace.traceSteps.toFixed(2)} overdraw ${trace.overdraw?.toFixed(2)} fragments/pixel 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); diff --git a/src/app/features/scene/README.md b/src/app/features/scene/README.md index 07d8028e..b37b76f0 100644 --- a/src/app/features/scene/README.md +++ b/src/app/features/scene/README.md @@ -78,7 +78,8 @@ not evaluated. `voxel/Voxel.ts` `createVoxelScene` takes the same options and returns the same `{ login, dispose }` as `createScene`, so the door swaps one for the other. It is the cheap background: WebGL2 core -only (no extension is requested, no float target is allocated), one fullscreen pass. +only (no extension is requested, no float target is allocated). It draws the terrain painter's order, +as instanced vertical strips, instead of marching a ray per pixel. - A wrapping ring of 256 x 256 world cells (8 units each) around the camera, in an RG8 texture holding a 16-bit height per cell. Cell (x, z) lives at texel (x mod 256, z mod 256). When the @@ -87,24 +88,35 @@ only (no extension is requested, no float target is allocated), one fullscreen p Phacelle per texel, the ray-march scene's terrain without its plateau mask. A cell's height is a pure function of the cell, so the order of writes cannot change the ring. A move of a whole ring or more, or the first frame, rewrites all of it. -- `shaders/voxel.frag.glsl`: per pixel below the horizon, march the screen column from the camera - outward, one lookup per step (steps grow with depth, at most 128, none past 120 cells), and stop - at the first column whose top reaches the pixel. The camera flies above the highest terrain, so - sky pixels spend no lookups and the march starts where a pixel first could be covered. That is - the image a running-horizon column renderer paints, found per pixel instead of carrying the - horizon between pixels, which one fullscreen pass cannot do. +- `shaders/voxelStrips.vert.glsl` draws the terrain: one instance is a screen column (one buffer + pixel wide) at one depth step, and the host draws the steps far to near with no depth buffer + and no blending, so a nearer strip overwrites what it hides. A strip's vertices fetch its height + and its nearer neighbour's from the ring (vertex texture fetch, core WebGL2) and project them + with the shear `y = horizon + (h - camY) / (z * tanHalf.y)`; the quad runs from its own top + down to the nearer neighbour's top (the screen bottom for the first strip drawn), and collapses + when the neighbour is higher. Colour is chosen once per strip, by height, slope along the view + ray and fog, and leaves as a flat varying (the last vertex of each strip triangle is a top + vertex); `shaders/voxel.frag.glsl` writes it with a dither. Depths follow `voxelWorld.ts` + `stepDepth` (about a cell up close, 2% of the depth far away; the same closed form in GLSL and + TypeScript), strips nearer than any terrain could reach the screen are not drawn, and strips + past a column's far plane (120 cells) are clipped in the vertex shader. +- `shaders/voxelBackdrop.frag.glsl` is the sky behind the strips, one fullscreen triangle. +- The drawing buffer is a fixed pixel budget in the canvas's aspect, 320 x 180 at the top of the + ladder; CSS scales it up. One column per buffer pixel, so the strip count follows the width. - The sky is baked once into RGBA8 (`voxelSky.frag.glsl`, gradient plus cloud bands) and sampled - by azimuth and elevation. The CSS ground stays the fallback: `createVoxelScene` returns null + by azimuth and elevation (the strips' vertex shader samples the horizon row for fog). The CSS ground stays the fallback: `createVoxelScene` returns null where `createScene` would, and says why through `onUnavailable`. - Resolution adapts through the drawing-buffer size, not extra targets: `BudgetLadder` over - `SCALE_LEVELS` steps down when the median frame time misses the 30 fps cap, using only + `SCALE_LEVELS` (1, 0.8, 0.64, 0.5 of the side of the 320 x 180 budget) steps down when the median frame time misses the 30 fps cap, using only `requestAnimationFrame` cadence, since timer queries are an extension. - `rails.ts` is the camera: a straight rail with the yaw wandering either side and sway, constant altitude above the terrain; `login()` lifts and tips it down. -- Measurement without extensions: `onFrameStats` gives the cadence and the buffer size; setting - `onTraceStats` makes one frame in eight draw a second, off-screen copy with lookup counts in - alpha and read it back (lookups per pixel), after timing the first draw with a one-texel - synchronous read. `harness/scene` has `drive.cjs voxel` and a standalone page. +- Measurement without extensions: `onFrameStats` gives the cadence, the buffer size, the vertices + submitted and the ring lookups the frame costs (two per shaded strip vertex, counted on the host + from the same schedule the shader runs). Setting `onTraceStats` makes one frame in eight time + the draw with a one-texel synchronous read, then draw the strips again off screen, each fragment + adding one count, and read that back: lookups per pixel, and fragment overdraw per pixel. + `harness/scene` has `drive.cjs voxel`, `voxelshots` and a standalone page. ## Measured and not measured diff --git a/src/app/features/scene/Scene.ts b/src/app/features/scene/Scene.ts index 49eb8ece..5d15efaf 100644 --- a/src/app/features/scene/Scene.ts +++ b/src/app/features/scene/Scene.ts @@ -32,9 +32,13 @@ export interface FrameStats { /** Drawing-buffer size as a fraction of the canvas's CSS size times device pixel ratio. */ scale: number; size: [number, number]; + /** Vertices submitted this frame (the strips, 4 each, plus the sky triangle). */ + vertices: number; + /** Height-ring lookups this frame: the vertex shader's, two per shaded strip vertex. */ + lookups: number; } -/** Trace cost over one finished readback: mean distance evaluations per pass-1 pixel. */ +/** Trace cost over one finished readback: mean distance evaluations per pass-1 pixel (the voxel scene: ring lookups per pixel). */ export interface TraceStats { /** Mean pass-1 steps per pixel. */ traceSteps: number; @@ -42,6 +46,8 @@ export interface TraceStats { prepassSteps: number; /** traceSteps plus the prepass's steps spread over the pixels of each tile. */ stepsPerPixel: number; + /** Voxel strips: mean fragments the strips shade per pixel (the painter's overdraw); the sky's one is not counted. */ + overdraw?: number; } /** diff --git a/src/app/features/scene/link.ts b/src/app/features/scene/link.ts index 2590ec3c..c0e2c238 100644 --- a/src/app/features/scene/link.ts +++ b/src/app/features/scene/link.ts @@ -1,5 +1,5 @@ // Compiling and linking a stage: the one place a shader failure becomes a ShaderCompileError. -import { fragmentSource, vertexSource, Stage } from './shaderSource'; +import { fragmentSource, vertexSourceFor, Stage } from './shaderSource'; /** Measurement seam: the harness rewrites a stage's source to time a variant. Never set in the client. */ export type SourcePatch = (stage: Stage, source: string) => string; @@ -33,7 +33,7 @@ export function linkStage( patch?: SourcePatch, defines?: string ): WebGLProgram { - const vs = compile(gl, gl.VERTEX_SHADER, vertexSource, 'vertex'); + const vs = compile(gl, gl.VERTEX_SHADER, vertexSourceFor(stage, defines), 'vertex'); const fs = compile( gl, gl.FRAGMENT_SHADER, diff --git a/src/app/features/scene/shaderSource.ts b/src/app/features/scene/shaderSource.ts index 5e569364..de03430d 100644 --- a/src/app/features/scene/shaderSource.ts +++ b/src/app/features/scene/shaderSource.ts @@ -10,6 +10,8 @@ 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 voxelBackdropFrag from './shaders/voxelBackdrop.frag.glsl?raw'; +import voxelStripsVert from './shaders/voxelStrips.vert.glsl?raw'; import voxelFrag from './shaders/voxel.frag.glsl?raw'; import { WORLD, worldDefines } from './world'; import { trimGlsl } from './cultmathTrim'; @@ -22,6 +24,7 @@ export type Stage = | 'composite' | 'voxelHeight' | 'voxelSky' + | 'voxelBackdrop' | 'voxel'; const HEADER = @@ -29,6 +32,16 @@ const HEADER = export const vertexSource = HEADER + fullscreenVert; +/** + * Vertex source for a stage: the fullscreen triangle, except the voxel strips, which have a vertex + * shader of their own (it reads the height ring and the shared block). + */ +export function vertexSourceFor(stage: Stage, defines = ''): string { + return stage === 'voxel' + ? `${HEADER}${defines}\n${common}\n${voxelStripsVert}` + : vertexSource; +} + const stages: Record = { prepass: prepassFrag, terrain: terrainFrag, @@ -37,6 +50,7 @@ const stages: Record = { composite: compositeFrag, voxelHeight: voxelHeightFrag, voxelSky: voxelSkyFrag, + voxelBackdrop: voxelBackdropFrag, voxel: voxelFrag, }; diff --git a/src/app/features/scene/shaders/voxel.frag.glsl b/src/app/features/scene/shaders/voxel.frag.glsl index 93c162f7..bb1ff20b 100644 --- a/src/app/features/scene/shaders/voxel.frag.glsl +++ b/src/app/features/scene/shaders/voxel.frag.glsl @@ -1,94 +1,17 @@ -// 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; +// A strip's fragment: the flat colour its vertex shader chose, dithered against banding. With +// TRACE_STATS, each fragment instead adds one count to red (the host blends additively), so the +// target reads back as fragments per pixel. 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)); -} +flat in vec3 v_color; +layout(location = 0) out vec4 o_color; 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; + o_color = vec4(1.0 / 255.0, 0.0, 0.0, 1.0); +#else + float dither = (ign(gl_FragCoord.xy, u_frame) - 0.5) / 255.0; + o_color = vec4(v_color + dither, 1.0); #endif } diff --git a/src/app/features/scene/shaders/voxelBackdrop.frag.glsl b/src/app/features/scene/shaders/voxelBackdrop.frag.glsl new file mode 100644 index 00000000..3b9d0d29 --- /dev/null +++ b/src/app/features/scene/shaders/voxelBackdrop.frag.glsl @@ -0,0 +1,22 @@ +// The sky behind the strips, one fullscreen triangle: the baked sky by azimuth and elevation above +// the horizon. Below the horizon it is the horizon colour, which is what shows past the last strip. +uniform sampler2D u_sky; // baked sky, gamma-encoded +// u_tanHalf comes 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 float u_frame; + +in vec2 v_uv; +layout(location = 0) out vec4 o_color; + +void main() +{ + vec2 ndc = v_uv * 2.0 - 1.0; + vec2 d = u_fwd + u_right * (ndc.x * u_tanHalf.x); + float rel = ndc.y - u_horizon; + float el = rel > 0.0 ? atan(rel * u_tanHalf.y, length(d)) : 0.0; + vec3 c = texture(u_sky, vec2(atan(d.y, d.x) * 0.15915494 + 0.5, el * 0.63661977)).rgb; + float dither = (ign(gl_FragCoord.xy, u_frame) - 0.5) / 255.0; + o_color = vec4(c + dither, 1.0); +} diff --git a/src/app/features/scene/shaders/voxelStrips.vert.glsl b/src/app/features/scene/shaders/voxelStrips.vert.glsl new file mode 100644 index 00000000..dade8d92 --- /dev/null +++ b/src/app/features/scene/shaders/voxelStrips.vert.glsl @@ -0,0 +1,95 @@ +// The terrain, painter's order. One instance is one strip: a screen column (one pixel wide) at one +// depth step. The host draws steps far to near with no depth test, so a nearer strip overwrites +// what it hides, which is the classic voxel renderer's occlusion without a running horizon. +// +// Projection is a shear: 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 strip runs from its own top down to the top of +// the next nearer strip, or to the screen bottom for the first. Where the nearer top is higher the +// quad is upside down, but it then lies below that nearer top, and the nearer strips drawn after +// it cover everything below their tops, so no test for "hidden" is needed and no vertex has to +// read both heights to place itself. No pixel below a strip's top is left unpainted either: +// the nearer strips cover the rest. +// +// Four vertices (a triangle strip): 0,1 are the bottom edge, 2,3 the top edge, 0,2 the left side. +// A bottom vertex reads the nearer neighbour's height; a top vertex its own. The colour is +// computed on the top vertices (which also read the neighbour's, for the slope) and leaves as a +// flat varying; the provoking vertex of a GL ES triangle is its last, which for both triangles of +// the strip is a top vertex. +uniform sampler2D u_height; // RG8, the ring of 16-bit heights +uniform sampler2D u_sky; // baked sky, gamma-encoded +// u_camPos, u_tanHalf (x: tan(fov/2) * aspect, y: tan(fov/2)) and the palette 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 int u_columns; // screen columns, one per drawing-buffer pixel +uniform int u_firstStep; // nearest step drawn; its strips run to the screen bottom + +flat out vec3 v_color; // gamma-encoded + +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); +} + +// The closed form of z += max(VOX_STEP_MIN, z * VOX_STEP_REL) from VOX_NEAR; voxelWorld.ts has the same. +float stepDepth(int k) +{ + return k <= VOX_LINEAR + ? VOX_NEAR + float(k) * VOX_STEP_MIN + : VOX_GROW_FROM * pow(1.0 + VOX_STEP_REL, float(k - VOX_LINEAR)); +} + +void main() +{ + int strip = gl_InstanceID; + bool top = gl_VertexID >= 2; + float side = float(gl_VertexID & 1) * 2.0 - 1.0; + int column = strip % u_columns; + int k = VOX_STEPS - 1 - strip / u_columns; // far to near + + float cx = (float(column) + 0.5) / float(u_columns) * 2.0 - 1.0; + vec2 d = u_fwd + u_right * (cx * u_tanHalf.x); // ground direction per unit of view depth + float dl = length(d); + float z = stepDepth(k); + v_color = vec3(0.0); + gl_Position = vec4(cx + side / float(u_columns), -1.0, 0.0, 1.0); + if (z * dl >= VOX_FAR) + { + gl_Position = vec4(2.0, 2.0, 2.0, 1.0); // outside the column's far plane: clipped + return; + } + + int kp = max(k - 1, 0); + // The nearer neighbour's depth, without a second pow: one growth step back, or one linear step. + float zp = k > VOX_LINEAR + 1 ? z * (1.0 / (1.0 + VOX_STEP_REL)) : VOX_NEAR + float(kp) * VOX_STEP_MIN; + vec2 cam = u_camPos.xz; + vec2 base = cam * (1.0 / VOX_CELL); + vec2 dcell = d * (1.0 / VOX_CELL); + if (!top) + { + // Bottom edge: the nearer strip's top. If that is higher than this strip's own top the quad is + // upside down, but it then lies below the nearer top, where nearer strips are drawn over it. + float hp = cellHeight(ivec2(floor(base + dcell * zp))); + float yNear = k == u_firstStep ? -1.0 : u_horizon + (hp - u_camPos.y) / (zp * u_tanHalf.y); + gl_Position.y = clamp(yNear, -1.0, 1.0); + return; + } + float h = cellHeight(ivec2(floor(base + dcell * z))); + gl_Position.y = clamp(u_horizon + (h - u_camPos.y) / (z * u_tanHalf.y), -1.0, 1.0); + // Colour by height and slope along the view ray, then fog toward the sky's horizon colour. + float hp = cellHeight(ivec2(floor(base + dcell * zp))); + float slope = (h - hp) / max((z - zp) * dl, 1e-3); + vec2 dn = d / dl; + vec3 n = normalize(vec3(-slope * dn.x, 1.0, -slope * dn.y)); + 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)); + vec3 col = albedo * (u_skyTop * 5.0 + u_fogColor * 2.0 + u_sunColor * (0.3 * lit)); + float az = atan(d.y, d.x); + vec3 horizonCol = pow(textureLod(u_sky, vec2(az * 0.15915494 + 0.5, 0.0), 0.0).rgb, vec3(2.2)); + col = mix(col, horizonCol * 0.6 + u_fogColor, 1.0 - exp(-z * dl * VOX_FOG)); + v_color = pow(clamp(col, 0.0, 1.0), vec3(1.0 / 2.2)); +} diff --git a/src/app/features/scene/voxel/Voxel.test.ts b/src/app/features/scene/voxel/Voxel.test.ts index acadfefc..4077e2b0 100644 --- a/src/app/features/scene/voxel/Voxel.test.ts +++ b/src/app/features/scene/voxel/Voxel.test.ts @@ -1,10 +1,10 @@ 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 { fragmentSource, vertexSourceFor } from '../shaderSource'; import { startBackgroundScene } from '../index'; import { createVoxelScene, SCALE_LEVELS } from './Voxel'; -import { VOXEL, voxelDefines } from './voxelWorld'; +import { STEPS, VOXEL, voxelDefines } from './voxelWorld'; const N = VOXEL.ring; let rafQueue: Array<(t: number) => void>; @@ -94,10 +94,11 @@ describe('voxel scene contract', () => { }); describe('voxel ring generation', () => { - it('the first frame bakes the sky, fills the whole ring once, and draws the terrain', () => { + it('the first frame bakes the sky, fills the whole ring once, and draws backdrop then strips', () => { const { calls } = build(); runFrame(1000); - expect(calls.drawArrays).toHaveBeenCalledTimes(3); + expect(calls.drawArrays).toHaveBeenCalledTimes(3); // sky bake, ring fill, backdrop + expect(calls.drawArraysInstanced).toHaveBeenCalledTimes(1); expect(calls.scissor.mock.calls).toEqual([[0, 0, N, N]]); }); @@ -105,7 +106,8 @@ describe('voxel ring generation', () => { const { calls } = build(); runFrame(1000); runFrame(1034); - expect(calls.drawArrays).toHaveBeenCalledTimes(4); // one more draw: the terrain + expect(calls.drawArrays).toHaveBeenCalledTimes(4); // one more backdrop + expect(calls.drawArraysInstanced).toHaveBeenCalledTimes(2); expect(calls.scissor).toHaveBeenCalledTimes(1); }); @@ -131,8 +133,39 @@ describe('voxel ring generation', () => { }); }); +describe('voxel draw pass', () => { + it('draws one instance per column and step, four vertices each, with no depth buffer', () => { + const { calls, canvas } = build(); + runFrame(1000); + const [mode, first, count, instances] = calls.drawArraysInstanced.mock.calls[0]; + expect(count).toBe(4); + expect(first).toBe(0); + expect(mode).toBeDefined(); + expect(instances % canvas.width).toBe(0); // whole columns + expect(instances / canvas.width).toBeLessThanOrEqual(STEPS); + expect(instances / canvas.width).toBeGreaterThan(STEPS / 2); // the near steps below the screen are skipped, not most of them + expect(canvas.getContext.mock.calls[0][1].depth).toBe(false); // no depth buffer: order is the draw order + }); + + it('the drawing buffer is the pixel budget in the canvas aspect, 320x180 at 16:9', () => { + const wide = build(); + wide.canvas.clientWidth = 1280; + wide.canvas.clientHeight = 720; + runFrame(1000); + expect([wide.canvas.width, wide.canvas.height]).toEqual([320, 180]); + rafQueue.length = 0; + const tall = build(); + tall.canvas.clientWidth = 360; + tall.canvas.clientHeight = 800; + runFrame(1034); + expect(tall.canvas.width * tall.canvas.height).toBeGreaterThan(VOXEL.pixels * 0.98); + expect(tall.canvas.width * tall.canvas.height).toBeLessThan(VOXEL.pixels * 1.02); + expect(tall.canvas.height / tall.canvas.width).toBeCloseTo(800 / 360, 1); + }); +}); + describe('voxel measurement and adaptation', () => { - it('reads lookups per pixel back from alpha and times the draw, only when asked', () => { + it('reads fragment counts back and times the draw, only when asked', () => { const plain = build(); runFrame(1000); expect(plain.calls.readPixels).toBeUndefined(); @@ -144,35 +177,47 @@ describe('voxel measurement and adaptation', () => { 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(onTraceStats.mock.calls[0][0].overdraw).toBe(0); // the fake GL shaded nothing 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); + const stats = onFrameStats.mock.calls[0][0]; + expect(stats.frameMs).toBe(34); + expect(stats.vertices).toBeGreaterThan(0); + expect(stats.lookups).toBeGreaterThan(0); + expect(stats.lookups).toBeLessThanOrEqual(stats.vertices * 2); }); 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)); + const widthAt = (level: number) => + Math.round(Math.sqrt(VOXEL.pixels * (400 / 300)) * SCALE_LEVELS[level].scale); + expect(canvas.width).toBe(widthAt(0)); for (let i = 0; i < 60; i++) runFrame((now += 100)); - expect(canvas.width).toBe(Math.round(400 * SCALE_LEVELS[1].scale)); + expect(canvas.width).toBe(widthAt(1)); for (let i = 0; i < 200; i++) runFrame((now += 10)); - expect(canvas.width).toBe(Math.round(400 * SCALE_LEVELS[1].scale)); + expect(canvas.width).toBe(widthAt(1)); }); 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)); + expect(canvas.width).toBe( + Math.round(Math.sqrt(VOXEL.pixels * (400 / 300)) * SCALE_LEVELS[1].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('the strips read the ring in the vertex shader and use no extension', () => { + const vs = vertexSourceFor('voxel', voxelDefines()); + expect(vs).toContain('texelFetch(u_height'); + expect(vs).toContain(`#define VOX_STEPS ${STEPS}`); + expect(vs).not.toContain('#extension'); + const fs = fragmentSource('voxel', voxelDefines()); + expect(fs).not.toContain('texelFetch'); // the fragment is a flat colour + expect(fs).not.toContain('#extension'); }); it('ring generation is a pure function of the cell and uses the shipped terrain', () => { @@ -185,7 +230,7 @@ describe('voxel shaders', () => { }); describe('the door picks the style', () => { - it('voxel by default: one frame is sky, ring and terrain, three draws', async () => { + it('voxel by default: one frame is sky, ring and backdrop, then the strips', async () => { const { gl, calls } = fakeGl(); const scene = await startBackgroundScene( { tier: 'still' }, @@ -195,6 +240,7 @@ describe('the door picks the style', () => { expect(scene).not.toBeNull(); runFrame(1000); expect(calls.drawArrays).toHaveBeenCalledTimes(3); + expect(calls.drawArraysInstanced).toHaveBeenCalledTimes(1); }); it("'raymarch' keeps the sphere-traced scene", async () => { diff --git a/src/app/features/scene/voxel/Voxel.ts b/src/app/features/scene/voxel/Voxel.ts index bcfc94b7..bf265a9a 100644 --- a/src/app/features/scene/voxel/Voxel.ts +++ b/src/app/features/scene/voxel/Voxel.ts @@ -1,7 +1,8 @@ -// 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. +// The voxel terrain scene: a wrapping ring of cell heights around the camera, drawn painter's order +// as instanced vertical strips over a baked sky. 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 that the +// strips' vertex shader reads; the sky is baked once into RGBA8; the drawing buffer is a fixed pixel +// budget (320x180 at the top of the ladder) in the canvas's aspect, and CSS scales it up. import type { FrameStats, Scene, SceneOptions } from '../Scene'; import { BudgetLadder } from '../budget'; import { pullProgress } from '../camera'; @@ -10,29 +11,36 @@ import { linkStage, ShaderCompileError } from '../link'; import { PALETTE } from '../palette'; import { Cell, ringRects, windowOrigin } from './ring'; import { voxelPose } from './rails'; -import { VOXEL, voxelDefines } from './voxelWorld'; +import { + firstStep, + liveStrips, + LOOKUPS_PER_STRIP, + STEPS, + VERTICES_PER_STRIP, + 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. */ +/** Measurement readback of fragment counts, 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. */ + /** Drawing-buffer side as a fraction of the default's: pixels = VOXEL.pixels * scale^2, in the canvas's aspect. */ scale: number; } /** Cheapest last. The ladder only descends. */ export const SCALE_LEVELS: readonly ScaleLevel[] = [ - { scale: 0.75 }, - { scale: 0.6 }, + { scale: 1 }, + { scale: 0.8 }, + { scale: 0.64 }, { scale: 0.5 }, - { scale: 0.4 }, ]; -const LOW_START_LEVEL = 2; +const LOW_START_LEVEL = 1; export function createVoxelScene(opts: SceneOptions): Scene | null { const { canvas } = opts; @@ -52,13 +60,14 @@ export function createVoxelScene(opts: SceneOptions): Scene | null { 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'; + // `counted` is the strip pass with each fragment writing one count; it exists only for a + // measuring scene, which draws it blended to an offscreen target. + type Name = 'height' | 'sky' | 'backdrop' | 'voxel' | 'counted'; const programs = {} as Record; - const sources: Array<[Name, 'voxelHeight' | 'voxelSky' | 'voxel', string]> = [ + const sources: Array<[Name, 'voxelHeight' | 'voxelSky' | 'voxelBackdrop' | 'voxel', string]> = [ ['height', 'voxelHeight', ''], ['sky', 'voxelSky', ''], + ['backdrop', 'voxelBackdrop', ''], ['voxel', 'voxel', ''], ]; if (measuring) sources.push(['counted', 'voxel', '#define TRACE_STATS 1\n']); @@ -156,15 +165,19 @@ export function createVoxelScene(opts: SceneOptions): Scene | null { SCALE_LEVELS ); const scale = () => (opts.fixedLevel ? opts.fixedLevel.solidScale : ladder.current.scale); + const FALLBACK_ASPECT = 16 / 9; 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)); + const aspect = + canvas.clientWidth > 0 && canvas.clientHeight > 0 + ? canvas.clientWidth / canvas.clientHeight + : FALLBACK_ASPECT; + const w = Math.max(2, Math.round(Math.sqrt(VOXEL.pixels * aspect) * s)); + const h = Math.max(2, Math.round(Math.sqrt(VOXEL.pixels / aspect) * s)); if (w === canvasW && h === canvasH) return; canvasW = w; canvasH = h; @@ -209,10 +222,18 @@ export function createVoxelScene(opts: SceneOptions): Scene | null { const [px, py, pz] = pose.position; generate({ x: Math.floor(px / VOXEL.cell), z: Math.floor(pz / VOXEL.cell) }); + const tanY = Math.tan(pose.fov / 2); + const tanX = tanY * (canvasW / canvasH); + // The shear: the horizon sits above the centre by the amount the camera looks down. + const horizon = -Math.tan(pose.pitch) / tanY; + const first = firstStep(py, horizon, tanY); + const instances = canvasW * (STEPS - first); + const vertices = instances * VERTICES_PER_STRIP + 3; + const lookups = liveStrips(canvasW, first, tanX) * LOOKUPS_PER_STRIP; + const timed = measuring && frame % READBACK_EVERY === 0; const t0 = timed ? performance.now() : 0; - const drawTerrain = (p: WebGLProgram) => { - gl.viewport(0, 0, canvasW, canvasH); + const bindWorld = (p: WebGLProgram) => { gl.useProgram(p); palette(p); vec3(p, 'u_grass', PALETTE.grass); @@ -220,21 +241,28 @@ export function createVoxelScene(opts: SceneOptions): Scene | null { 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.uniform2f(loc(p, 'u_tanHalf'), tanX, tanY); + gl.uniform1f(loc(p, 'u_horizon'), horizon); gl.uniform1f(loc(p, 'u_frame'), frame); + gl.uniform1i(loc(p, 'u_columns'), canvasW); + gl.uniform1i(loc(p, 'u_firstStep'), first); 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(); + }; + // Far to near, no depth test, no blending: the later strip is the nearer one and overwrites. + const drawStrips = (p: WebGLProgram) => { + bindWorld(p); + gl.drawArraysInstanced(gl.TRIANGLE_STRIP, 0, VERTICES_PER_STRIP, instances); }; gl.bindFramebuffer(gl.FRAMEBUFFER, null); - drawTerrain(programs.voxel); + gl.viewport(0, 0, canvasW, canvasH); + bindWorld(programs.backdrop); + draw(); + drawStrips(programs.voxel); let renderMs: number | undefined; if (timed) { @@ -242,21 +270,39 @@ export function createVoxelScene(opts: SceneOptions): Scene | null { // 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. + // Then the strips again, off screen, each fragment adding one to red, and read back. if (counted.w !== canvasW || counted.h !== canvasH) resizeCounted(); - gl.bindFramebuffer(gl.FRAMEBUFFER, counted.fbo); - drawTerrain(programs.counted); + gl.bindFramebuffer(gl.FRAMEBUFFER, counted.fbo ?? null); + gl.viewport(0, 0, canvasW, canvasH); + gl.clearColor(0, 0, 0, 0); + gl.clear(gl.COLOR_BUFFER_BIT); + gl.enable(gl.BLEND); + gl.blendFunc(gl.ONE, gl.ONE); + drawStrips(programs.counted); + gl.disable(gl.BLEND); 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 }); + for (let i = 0; i < px4.length; i += 4) sum += px4[i]; + const perPixel = lookups / (canvasW * canvasH); + opts.onTraceStats?.({ + traceSteps: perPixel, + prepassSteps: 0, + stepsPerPixel: perPixel, + overdraw: sum / (canvasW * canvasH), + }); } if (prevNow !== undefined) { const frameMs = now - prevNow; - opts.onFrameStats?.({ frameMs, renderMs, scale: sizedFor, size: [canvasW, canvasH] }); + opts.onFrameStats?.({ + frameMs, + renderMs, + scale: sizedFor, + size: [canvasW, canvasH], + vertices, + lookups, + }); if (!opts.fixedLevel && ladder.push(frameMs)) canvasW = 0; // resize on the next frame } prevNow = now; @@ -279,6 +325,7 @@ export function createVoxelScene(opts: SceneOptions): Scene | null { if (counted.fbo) gl.deleteFramebuffer(counted.fbo); if (measuring) gl.deleteProgram(programs.counted); gl.deleteProgram(programs.height); + gl.deleteProgram(programs.backdrop); gl.deleteProgram(programs.voxel); gl.deleteVertexArray(vao); }, diff --git a/src/app/features/scene/voxel/voxelWorld.test.ts b/src/app/features/scene/voxel/voxelWorld.test.ts new file mode 100644 index 00000000..5b22b8f3 --- /dev/null +++ b/src/app/features/scene/voxel/voxelWorld.test.ts @@ -0,0 +1,46 @@ +import { describe, expect, it } from 'vitest'; +import { firstStep, heightBound, liveStrips, STEPS, stepDepth, VOXEL } from './voxelWorld'; + +describe('the strip schedule', () => { + it('is the closed form of z += max(stepMin, z * stepRel) from near', () => { + let z: number = VOXEL.near; + for (let k = 0; k < STEPS; k++) { + expect(stepDepth(k)).toBeCloseTo(z, 6); + z += Math.max(VOXEL.stepMin, z * VOXEL.stepRel); + } + }); + + it('covers every depth short of the far distance and no further', () => { + const far = VOXEL.farCells * VOXEL.cell; + expect(stepDepth(STEPS - 1)).toBeLessThan(far); + expect(stepDepth(STEPS)).toBeGreaterThanOrEqual(far); + }); +}); + +describe('where the strips begin', () => { + const camY = heightBound() + VOXEL.clearance; + const tanY = Math.tan(0.5); + const topAt = (k: number, h: number, horizon: number) => + horizon + (h - camY) / (stepDepth(k) * tanY); + + it('skips only strips whose every possible top is below the screen', () => { + const horizon = 0.2; + const first = firstStep(camY, horizon, tanY); + expect(first).toBeGreaterThan(0); + expect(topAt(first - 1, heightBound(), horizon)).toBeLessThan(-1); + expect(topAt(first, heightBound(), horizon)).toBeGreaterThanOrEqual(-1 - 1e-9); + }); + + it('starts nearer when the camera is lower or the view steeper', () => { + expect(firstStep(camY + 45, 0.3, tanY)).toBeGreaterThan(firstStep(camY, 0.3, tanY)); + expect(firstStep(camY, 0.5, tanY)).toBeLessThan(firstStep(camY, 0.1, tanY)); + }); +}); + +describe('strips a frame shades', () => { + it('loses the far corners of a wide view to the far plane, and nothing of a narrow one', () => { + const wide = liveStrips(320, 10, 1.0); + expect(wide).toBeLessThan(liveStrips(320, 10, 0.01)); + expect(liveStrips(320, 10, 0.01)).toBeCloseTo(320 * (STEPS - 10), -3); + }); +}); diff --git a/src/app/features/scene/voxel/voxelWorld.ts b/src/app/features/scene/voxel/voxelWorld.ts index 4fbbd226..ab02fcd1 100644 --- a/src/app/features/scene/voxel/voxelWorld.ts +++ b/src/app/features/scene/voxel/voxelWorld.ts @@ -10,13 +10,13 @@ export const VOXEL = { 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. */ + /** First strip 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, + /** A strip step is max(stepMin, depth * stepRel): about a cell up close, coarser far away. */ + stepMin: 8, + stepRel: 0.03, + /** Pixel budget of the drawing buffer at scale 1 (320x180); the buffer takes the canvas's aspect. */ + pixels: 320 * 180, /** 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. */ @@ -31,6 +31,61 @@ 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; +/** + * The strip schedule, one copy for the shader and the host. Depth k along the view axis is + * near + k * stepMin while a step is the minimum one, then grows by (1 + stepRel) per strip: the + * closed form of z += max(stepMin, z * stepRel), so a vertex shader can evaluate any k directly. + */ +const LINEAR_STEPS = Math.ceil((VOXEL.stepMin / VOXEL.stepRel - VOXEL.near) / VOXEL.stepMin); +const GROW_FROM = VOXEL.near + LINEAR_STEPS * VOXEL.stepMin; + +export const stepDepth = (k: number): number => + k <= LINEAR_STEPS + ? VOXEL.near + k * VOXEL.stepMin + : GROW_FROM * (1 + VOXEL.stepRel) ** (k - LINEAR_STEPS); + +/** Strips per column: the first k whose depth reaches the far distance on the view axis (a column's own far is nearer). */ +export const STEPS = (() => { + let k = 0; + while (stepDepth(k) < VOXEL.farCells * VOXEL.cell) k += 1; + return k; +})(); + +/** The farthest depth a column with ground direction length `dl` draws to: its far plane is a distance, not a depth. */ +const columnReach = (dl: number) => (VOXEL.farCells * VOXEL.cell) / dl; + +/** + * Where the strips begin for a camera at `camY` with the horizon at `horizon` (ndc). Terrain tops + * at most heightBound high, so a strip nearer than this projects entirely below the screen; the + * first strip drawn runs down to the screen bottom instead of to its nearer neighbour's top. + */ +export function firstStep(camY: number, horizon: number, tanY: number): number { + const reach = (camY - heightBound()) / ((1 + horizon) * tanY); + let k = 0; + while (k < STEPS - 1 && stepDepth(k) < reach) k += 1; + return k; +} + +/** How many strips a frame shades: those from `first` out, per column, that lie inside the column's far plane. */ +export function liveStrips(columns: number, first: number, tanX: number): number { + let n = 0; + for (let c = 0; c < columns; c++) { + const x = ((c + 0.5) / columns) * 2 - 1; + const reach = columnReach(Math.hypot(1, x * tanX)); + let k = first; + while (k < STEPS && stepDepth(k) < reach) k += 1; + n += k - first; + } + return n; +} + +/** + * Ring lookups per live strip: each bottom vertex reads the nearer neighbour's height, each top + * vertex its own, and the two top vertices that carry the strip's colour read the neighbour's too. + */ +export const LOOKUPS_PER_STRIP = 6; +export const VERTICES_PER_STRIP = 4; + const f = (n: number) => (Number.isInteger(n) ? `${n}.0` : `${n}`); /** `#define` lines every voxel stage sees. */ @@ -39,7 +94,9 @@ export function voxelDefines(): string { `#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_STEPS ${STEPS}`, + `#define VOX_LINEAR ${LINEAR_STEPS}`, + `#define VOX_GROW_FROM ${f(GROW_FROM)}`, `#define VOX_NEAR ${f(VOXEL.near)}`, `#define VOX_STEP_MIN ${f(VOXEL.stepMin)}`, `#define VOX_STEP_REL ${f(VOXEL.stepRel)}`,