diff --git a/README.md b/README.md index abeba8b2..bbfa822e 100644 --- a/README.md +++ b/README.md @@ -6,14 +6,14 @@ and your own place in it) instead of an invite list. Mobile first. **Live now:** the Cinny engine (matrix-js-sdk, Rust crypto, sync) under a Ratatoskr UI: branding, GameCult theme, estate navigation, pose portraits -(opt-in setting), a background scene (on in the dev config, `backgroundScene.tier`; the device can lower it) and an opt-in soundscape. +(opt-in setting) and a background scene (on in the dev config, `backgroundScene.tier`; the device can lower it). **Planned:** see [`docs/gamecult/ratatoskr-target.md`](docs/gamecult/ratatoskr-target.md) for the target and cut sequence. Internal names that are protocol or stored state (`cinny_*` localStorage keys, the `in.cinny.room.power_level_tags` event type, `CINNY_BASE`) are unchanged on purpose. Entry points: `src/app/` (client UI), `src/app/features/scene/` (background -scene), `src/app/features/soundscape/` (audio socket), `harness/` (estate +scene), `harness/` (estate drive scripts), `scripts/gen-brand.mjs` (regenerates the logo and icons). ## Upstream diff --git a/config.json b/config.json index 3e349d86..b37a4a21 100644 --- a/config.json +++ b/config.json @@ -19,8 +19,7 @@ "basename": "/" }, "backgroundScene": { - "tier": "full", - "style": "ridge" + "tier": "full" }, "dings": { "enabled": false diff --git a/harness/scene/README.md b/harness/scene/README.md index 217e2241..fa618c5a 100644 --- a/harness/scene/README.md +++ b/harness/scene/README.md @@ -1,25 +1,9 @@ # Scene harness -Compiles, renders and times the background scene (`src/app/features/scene/`) in headless +Renders and times the ridge background scene (`src/app/features/scene/ridge/`) in headless Chromium. Not shipped, not run by CI. - node bundle.cjs # esbuild bundle of entry.ts plus an index.html - node drive.cjs compile # compile and link each stage, JSON report - node drive.cjs shots # rest, mid pull-back and pulled-back screenshots - node gradAxis.cjs # numeric check that noise gradients are (d/dx, d/dz-as-.y, ...): terrainNormal axis - 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 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` - -Needs `esbuild` and `playwright@1.48.2` on `NODE_PATH` and a Chromium. The first run was done on a -host with no GPU, so `drive.cjs` launches with `--use-angle=swiftshader` (software Vulkan). On a -machine with a GPU, remove those flags to measure the real device. `bundle.cjs` must run from a -directory whose ancestors hold no empty `package.json` (esbuild reads them). - -Timings from SwiftShader are CPU time: use them for the split between passes and for before and -after of one change, never as a phone frame time. + node bundle.cjs # esbuild bundle of ridgeDemo.ts plus an index.html ## Ridge live scene @@ -43,20 +27,17 @@ clamped to the place's range as the app does (phi 0: `camera.r_max_forward_m`, a npx vite --port 5199 # from the repo root; the app's vite config serves the page and public/ http://localhost:5199/harness/scene/ridgeSheet.html # four presets x six skies - ...ridgeSheet.html?preset=swiss # one preset (physical|swiss|poster|painterly) + ...ridgeSheet.html?preset=painterly # one preset (painterly|painterly-cel-2|painterly-cel-3|painterly-cel-4) ...ridgeSheet.html?looks=%5B%7B%22label%22%3A%22no-ink%22%2C%22inkScale%22%3A0%7D%2C%7B%22label%22%3A%22hazy%22%2C%22hazeScale%22%3A8%7D%5D ...?w=640 # cell width -`looks=` is a url-encoded or base64 JSON array of `{label, ...partial RidgeLook}` and replaces the preset rows (`inkKeep` and `reliefLight` merge by key). +`looks=` is a url-encoded or base64 JSON array of `{label, ...partial RidgeLook}` and replaces the preset rows (`inkKeep` merges by key). A cell costs one WebGL2 context and a card decode, so the full sheet takes tens of seconds (much longer in a background tab). -Presets (`PRESETS` in `ridgeSheet.ts`; swiss and poster take every key not named from `PHYSICAL_LOOK`, the rest from `DEFAULT_LOOK`, the painterly cel look), chosen by reasoning, not by eye, for Self to tune: +Presets (`PRESETS` in `ridgeSheet.ts`; every key not named comes from `DEFAULT_LOOK`, the painterly cel-3 look), chosen by reasoning, not by eye, for Self to tune: | preset | values | | --- | --- | -| physical | PHYSICAL_LOOK (Lambert, no noise, sky haze, full ink) | -| swiss | reliefLight {mix 0.7, azimuthDeg -45, elevationDeg 40}, contrastByDistance 0.9, hazeScale 6, hazeTint [0, 0.05, 0.25], nearWarm 0.5, inkScale 0.6 | -| poster | reliefWeight 0.15, cardToneStep 0.25, cardGradient 0.5, inkKeep {edge 0.25, occlude 0.9, crease 1}, hazeScale 4 | | painterly | DEFAULT_LOOK: groundNoise 0.35, cloudShadows 0.5, nearWarm 0.6, hazeScale 2, inkScale 0.4, celBands 3, celSoftness 0.05, celAmbientAway 0.7 | | painterly-cel-2 / -3 / -4 | painterly with celBands 2 / 3 / 4 | diff --git a/harness/scene/bundle.cjs b/harness/scene/bundle.cjs index 9d3079cd..28f9d08f 100644 --- a/harness/scene/bundle.cjs +++ b/harness/scene/bundle.cjs @@ -1,50 +1,22 @@ -// Bundles entry.ts with the scene's ?raw GLSL imports into $OUT/bundle.js plus an index.html. -// usage: node bundle.cjs [demo|ridge] (esbuild from NODE_PATH). `demo` bundles the ray-march -// standalone page; `ridge` the ridge scene's page (open it with ?probe=1 for the cadence readout). +// Bundles ridgeDemo.ts into $OUT/bundle.js plus an index.html. +// usage: node bundle.cjs (esbuild from NODE_PATH). const esbuild = require('esbuild'); const fs = require('fs'); const path = require('path'); const out = process.argv[2]; -const demo = process.argv[3] === 'demo'; -const ridge = process.argv[3] === 'ridge'; fs.mkdirSync(out, { recursive: true }); -const rawPlugin = { - name: 'raw', - setup(b) { - b.onResolve({ filter: /\?raw$/ }, (a) => ({ - path: path.resolve(a.resolveDir, a.path.slice(0, -4)), - namespace: 'raw', - })); - b.onLoad({ filter: /.*/, namespace: 'raw' }, (a) => ({ - contents: fs.readFileSync(a.path, 'utf8'), - loader: 'text', - })); - }, -}; esbuild .build({ - entryPoints: [path.join(__dirname, ridge ? 'ridgeDemo.ts' : demo ? 'demo.ts' : 'entry.ts')], + entryPoints: [path.join(__dirname, 'ridgeDemo.ts')], bundle: true, outfile: path.join(out, 'bundle.js'), - plugins: [rawPlugin], format: 'iife', target: 'es2020', define: { 'import.meta.env.BASE_URL': '"/"' }, }) .then(() => { - if (ridge) { - fs.writeFileSync( - path.join(out, 'index.html'), - 'Ratatoskr ridge scene
' - ); - return; - } fs.writeFileSync( path.join(out, 'index.html'), - 'Ratatoskr scene: trace prepass' + - (demo - ? '
device
' - : '') + - '' + 'Ratatoskr ridge scene
' ); }); diff --git a/harness/scene/demo.ts b/harness/scene/demo.ts deleted file mode 100644 index 40424ff5..00000000 --- a/harness/scene/demo.ts +++ /dev/null @@ -1,102 +0,0 @@ -// Standalone page: the scene full-window with a readout of pass ms and trace steps per pixel, and -// a switch for the cone prepass. Not shipped. -import { - createScene, - Scene, - SceneStats, - SceneUnavailable, - TraceStats, -} from '../../src/app/features/scene/Scene'; -import { LEVELS } from '../../src/app/features/scene/budget'; - -let canvas = document.getElementById('c') as HTMLCanvasElement; -const out = document.getElementById('out') as HTMLPreElement; -const box = document.getElementById('prepass') as HTMLInputElement; -const pull = document.getElementById('pull') as HTMLInputElement; -const half = document.getElementById('half') as HTMLInputElement; -const dev = document.getElementById('dev') as HTMLDetailsElement; -const info = document.getElementById('info') as HTMLPreElement; -const timerless = (() => { - const g = document.createElement('canvas').getContext('webgl2'); - 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; -let stats: SceneStats | undefined; -let trace: TraceStats | undefined; - -function start() { - scene?.dispose(); - stats = trace = undefined; - // A fresh canvas: a context cannot change its attributes, and dispose leaves the old one bound. - const fresh = canvas.cloneNode() as HTMLCanvasElement; - canvas.replaceWith(fresh); - canvas = fresh; - scene = createScene({ - canvas: fresh, - unthrottled: true, - fixedLevel: LEVELS[0], - fixedPull: +pull.value, - prepass: box.checked, - halfStart: half.checked, - onUnavailable: (r) => (out.textContent = `createScene returned null: ${WHY[r]}`), - onCompileFail: (e) => (out.textContent = `createScene returned null: ${e.message}`), - onStats: (s) => (stats = s), - onTraceStats: (t) => (trace = t), - }); - dev.open = !scene; -} - -setInterval(() => { - if (!scene) return; - const lines = [`prepass ${box.checked ? 'on' : 'off'} start target ${scene.startFormat} pull ${pull.value}`]; - if (stats) { - const ms = stats.passMs; - const total = Object.values(ms).reduce((a, b) => a + b, 0); - lines.push( - `gpu ms prepass ${ms.prepass.toFixed(2)} terrain ${ms.terrain.toFixed(2)} atmosphere ${ms.atmosphere.toFixed(2)} resolve ${ms.resolve.toFixed(2)} composite ${ms.composite.toFixed(2)} total ${total.toFixed(2)}`, - `solid ${stats.solidSize.join('x')}` - ); - } else if (timerless) { - lines.push('gpu ms: this browser has no EXT_disjoint_timer_query_webgl2'); - } - if (trace) - lines.push( - `steps/pixel ${trace.stepsPerPixel.toFixed(2)} (pass 1 ${trace.traceSteps.toFixed(2)}, prepass ${trace.prepassSteps.toFixed(1)} per tile)` - ); - out.textContent = lines.join('\n'); -}, 500); - -box.addEventListener('change', start); -half.addEventListener('change', start); -pull.addEventListener('input', start); -start(); diff --git a/harness/scene/drive.cjs b/harness/scene/drive.cjs deleted file mode 100644 index 0f34191f..00000000 --- a/harness/scene/drive.cjs +++ /dev/null @@ -1,309 +0,0 @@ -// Drives the scene in headless Chromium (software GL unless the host has a GPU). -// usage: node drive.cjs [outdir] modes: compile | shots | measure -// Needs playwright from NODE_PATH and PLAYWRIGHT_BROWSERS_PATH. Prints one JSON report. -const { chromium } = require('playwright'); -const path = require('path'); -const fs = require('fs'); -const [, , dir, mode, outdir = '.'] = process.argv; - -(async () => { - const b = await chromium.launch({ - args: [ - '--use-gl=angle', - '--use-angle=swiftshader', - '--enable-unsafe-swiftshader', - '--ignore-gpu-blocklist', - ], - }); - const page = await b.newPage({ viewport: { width: 960, height: 540 } }); - page.on('pageerror', (e) => process.stderr.write(`[pageerror] ${e}\n`)); - page.on('console', (m) => process.stderr.write(`[page] ${m.text()}\n`)); - await page.goto('file://' + path.resolve(dir, 'index.html')); - const report = { mode }; - report.renderer = await page.evaluate(() => { - const g = document.createElement('canvas').getContext('webgl2'); - const e = g.getExtension('WEBGL_debug_renderer_info'); - return g.getParameter(e ? e.UNMASKED_RENDERER_WEBGL : g.RENDERER); - }); - - if (mode === 'compile') { - report.stages = await page.evaluate(() => { - const gl = document.createElement('canvas').getContext('webgl2'); - const S = window.__scene; - return ['terrain', 'atmosphere', 'resolve', 'composite'].map((stage) => { - const t0 = performance.now(); - try { - const p = S.linkStage(gl, stage); - return { - stage, - ok: true, - ms: +(performance.now() - t0).toFixed(1), - sourceBytes: S.fragmentSource(stage).length, - log: gl.getProgramInfoLog(p), - }; - } catch (e) { - return { - stage, - ok: false, - ms: +(performance.now() - t0).toFixed(1), - log: String(e.log || e), - }; - } - }); - }); - } - - if (mode === 'phacelle') { - report.probe = await page.evaluate(() => - window.__probePhacelle( - window.__scene.WORLD.erodeSide.slice(), - window.__scene.WORLD.erodeNorm, - 4 - ) - ); - } - - if (mode === 'shots') { - await page.evaluate(() => { - const c = document.getElementById('c'); - window.__s = window.__scene.createScene({ - canvas: c, - unthrottled: true, - fixedLevel: window.__scene.LEVELS[0], - }); - }); - const wait = (ms) => page.waitForTimeout(ms); - await wait(4000); - await page.screenshot({ path: path.join(outdir, 'rest.png') }); - await page.evaluate(() => window.__s.login()); - await wait(3500); - await page.screenshot({ path: path.join(outdir, 'mid-pullback.png') }); - await wait(9000); - await page.screenshot({ path: path.join(outdir, 'pulled-back.png') }); - report.shots = ['rest.png', 'mid-pullback.png', 'pulled-back.png']; - } - - if (mode === 'measure' || mode === 'variants') { - const VARIANTS = { - baseline: null, - // What a public value-only fbm would cost: the same octaves without the gradient work. - valueOnlyFbm: [ - 'float terrainFbm(vec2 xz) { return cultmath_fbm_grad(vec3(xz * W_FREQ, 0.0), W_OCTAVES, W_LACUNARITY, W_GAIN).w; }', - 'float terrainFbm(vec2 xz) { float a = 1.0, fr = 1.0, v = 0.0; for (int i = 0; i < W_OCTAVES; i++) { v += a * cultmath_snoise(vec3(xz * W_FREQ * fr, 0.0)); fr *= W_LACUNARITY; a *= W_GAIN; } return v; }', - ], - noErosion: ['#define W_ERODE_ENABLED 1', '#define W_ERODE_ENABLED 0'], - // Upper bound on what skipping sky rays would save: every upward ray misses at once. - noSkyMarch: [' bool hit = false;\n bool onTree = false;', ' if (rd.y > 0.0) { o_color = vec4(0.0); o_depth = W_FAR; return; }\n bool hit = false;\n bool onTree = false;'], - noTree: ['float dr = treeDistance(p, leafness);', 'float dr = 1e9; leafness = 0.0;'], - }; - const wanted = mode === "variants" ? (process.env.ONLY ? process.env.ONLY.split(",") : Object.keys(VARIANTS)) : ['baseline']; - const sizes = [ - [960, 540], - [540, 1200], - ]; - report.runs = []; - for (const [w, h] of sizes) { - for (const [li, variant] of wanted.flatMap((v) => - mode === 'variants' - ? [[0, v]] - : [ - [0, v], - [3, v], - ] - )) { - await page.setViewportSize({ width: w, height: h }); - const r = await page.evaluate( - ({ li, rep }) => - new Promise((res) => { - const rows = []; - const c = document.getElementById('c'); - const s = window.__scene.createScene({ - canvas: c, - unthrottled: true, - fixedLevel: window.__scene.LEVELS[li], - patchSource: rep - ? (st, src) => - st === 'terrain' - ? rep[0].startsWith('#define') - ? src.replace(/#define W_ERODE_ENABLED \d/, rep[1]) - : src.split(rep[0]).join(rep[1]) - : src - : undefined, - onStats: (st) => { - rows.push(st); - if (rows.length === 40) { - s.dispose(); - const keep = rows.slice(10); - const med = (k) => - keep.map((x) => x.passMs[k]).sort((a, b) => a - b)[keep.length >> 1]; - res({ - solid: keep[0].solidSize, - atm: keep[0].atmosphereSize, - medianMs: { - terrain: med('terrain'), - atmosphere: med('atmosphere'), - resolve: med('resolve'), - composite: med('composite'), - }, - }); - } - }, - }); - if (!s) res({ error: 'createScene returned null' }); - }), - { li, rep: VARIANTS[variant] } - ); - report.runs.push({ viewport: [w, h], level: li, variant, ...r }); - } - } - } - - if (mode === 'trace') { - // Steps per pixel and pass ms at fixed camera poses, one scene per run. PREPASS=0,1 picks the arms. - const arms = (process.env.PREPASS || '1').split(',').map((x) => x === '1'); - report.runs = []; - for (const [w, h] of process.env.PORTRAIT === '0' - ? [[960, 540]] - : [ - [960, 540], - [540, 1200], - ]) { - for (const pull of (process.env.PULLS || '0,0.5,1').split(',').map(Number)) { - for (const prepass of arms) { - await page.setViewportSize({ width: w, height: h }); - const r = await page.evaluate( - ({ pull, prepass, FRAMES }) => - new Promise((res) => { - const rows = []; - const trace = []; - let done = false; - const finish = () => { - if (done || rows.length < FRAMES || trace.length < 4) return; - done = true; - s.dispose(); - const keep = rows.slice(FRAMES >> 2); - const med = (xs) => xs.sort((a, b) => a - b)[xs.length >> 1]; - const tk = trace.slice(1); - const mean = (k) => tk.reduce((a, t) => a + t[k], 0) / tk.length; - res({ - solid: keep[0].solidSize, - readbacks: tk.length, - traceSteps: +mean('traceSteps').toFixed(2), - prepassSteps: +mean('prepassSteps').toFixed(2), - stepsPerPixel: +mean('stepsPerPixel').toFixed(2), - medianMs: Object.fromEntries( - Object.keys(keep[0].passMs).map((k) => [k, +med(keep.map((x) => x.passMs[k])).toFixed(2)]) - ), - }); - }; - const s = window.__scene.createScene({ - canvas: document.getElementById('c'), - unthrottled: true, - fixedLevel: window.__scene.LEVELS[0], - fixedPull: pull, - prepass, - onTraceStats: (t) => { - trace.push(t); - finish(); - }, - onStats: (st) => { - rows.push(st); - finish(); - }, - }); - if (!s) res({ error: 'createScene returned null' }); - }), - { pull, prepass, FRAMES: +(process.env.FRAMES || 64) } - ); - report.runs.push({ viewport: [w, h], pull, prepass, ...r }); - } - } - } - } - - 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. - await page.emulateMedia({ reducedMotion: 'reduce' }); - await page.setViewportSize({ width: 640, height: 360 }); - const shoot = async (pull, prepass, steps) => { - await page.evaluate( - ({ pull, prepass, steps }) => { - // Reduced motion bounds the scene to 32 frames; each asks for the next with rAF, so the - // count stops moving when it is done. Timer-query callbacks lag too far to count on. - window.__raf = 0; - if (!window.__rafPatched) { - window.__rafPatched = true; - const raf = window.requestAnimationFrame.bind(window); - window.requestAnimationFrame = (cb) => (window.__raf++, raf(cb)); - } - window.__d = window.__scene.createScene({ - canvas: document.getElementById('c'), - fixedLevel: { ...window.__scene.LEVELS[0], traceSteps: steps }, - fixedPull: pull, - prepass, - }); - }, - { pull, prepass, steps } - ); - for (let last = -1, still = 0; still < 3; await page.waitForTimeout(1000)) { - const n = await page.evaluate(() => window.__raf); - still = n === last ? still + 1 : 0; - last = n; - } - const png = await page.screenshot(); - await page.evaluate(() => window.__d.dispose()); - return png.toString('base64'); - }; - // The step cap makes a grazing ray give up and count as a hit, so the baseline is compared - // with a 512-step render of the same frame as well: whichever is closer to it is the more - // faithful one. - const decode = (x) => - page.evaluate( - (x) => - new Promise((r) => { - const i = new Image(); - i.onload = () => { - const c = document.createElement('canvas'); - c.width = i.width; - c.height = i.height; - const g = c.getContext('2d'); - g.drawImage(i, 0, 0); - r(Array.from(g.getImageData(0, 0, i.width, i.height).data)); - }; - i.src = 'data:image/png;base64,' + x; - }), - x - ); - const compare = (da, db) => { - let max = 0, over = 0, sum = 0; - const px = da.length / 4; - for (let i = 0; i < da.length; i += 4) { - let m = 0; - for (let k = 0; k < 3; k++) m = Math.max(m, Math.abs(da[i + k] - db[i + k])); - sum += m; - if (m > max) max = m; - if (m > 2) over++; - } - return { maxChannelDiff: max, pixelsOver2of255: over, ofPixels: px, meanMaxChannelDiff: +(sum / px).toFixed(3) }; - }; - report.diffs = []; - for (const pull of (process.env.PULLS || '0,0.5,1').split(',').map(Number)) { - const png = { - off: await shoot(pull, false, 96), - on: await shoot(pull, true, 96), - ref: await shoot(pull, false, 512), - off2: await shoot(pull, false, 96), - }; - for (const k of Object.keys(png)) fs.writeFileSync(path.join(outdir, `diff-${k}-${pull}.png`), Buffer.from(png[k], 'base64')); - const [off, on, ref, off2] = [await decode(png.off), await decode(png.on), await decode(png.ref), await decode(png.off2)]; - report.diffs.push({ pull, offVsOffAgain: compare(off, off2), offVsOn: compare(off, on), offVsRef512: compare(off, ref), onVsRef512: compare(on, ref) }); - } - } - - console.log(JSON.stringify(report, null, 1)); - await b.close(); -})().catch((e) => { - console.log('ERR', String(e).slice(0, 2000)); - process.exit(1); -}); diff --git a/harness/scene/entry.ts b/harness/scene/entry.ts deleted file mode 100644 index d43a5453..00000000 --- a/harness/scene/entry.ts +++ /dev/null @@ -1,87 +0,0 @@ -// 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 { 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, - linkStage, - ShaderCompileError, - LEVELS, - fragmentSource, - WORLD, -}; - -// ---- Phacelle gradient probe ----------------------------------------------------------------- -import cultmath from '../../src/app/features/scene/shaders/CultMath.glsl?raw'; -import phacelle from '../../src/app/features/scene/shaders/CultMath.Phacelle.glsl?raw'; -import { vertexSource } from '../../src/app/features/scene/shaderSource'; - -const PROBE_FRAG = `#version 300 es -precision highp float; precision highp int; -${cultmath} -${phacelle} -uniform float u_seed; uniform vec3 u_side; uniform float u_norm; uniform float u_span; -in vec2 v_uv; layout(location=0) out vec4 o; -void main() { - // The scene samples the z = 0 slice: random points in a u_span square of it. - vec3 h = vec3(cultmath_pcg3d(vec3(gl_FragCoord.xy, u_seed))) ; - vec2 xy = vec2(float(uint(int(h.x)) >> 8), float(uint(int(h.y)) >> 8)) * (1.0 / 16777216.0) * u_span; - CultPhasor ph = cultmath_phacelle(vec3(xy, 0.0), u_side, 0.0, u_norm); - o = vec4(length(ph.cos.xyz), length(ph.sin.xyz), ph.cos.w, ph.sin.w); -}`; - -/** Max |grad| of the phasor over `draws * 1024^2` random points; min/max of the cos component. */ -(window as unknown as Record).__probePhacelle = ( - side: number[], - norm: number, - draws: number -) => { - const c = document.createElement('canvas'); - const gl = c.getContext('webgl2')!; - gl.getExtension('EXT_color_buffer_float'); - const mk = (t: number, s: string) => { - const x = gl.createShader(t)!; - gl.shaderSource(x, s); - gl.compileShader(x); - if (!gl.getShaderParameter(x, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(x)!); - return x; - }; - const p = gl.createProgram()!; - gl.attachShader(p, mk(gl.VERTEX_SHADER, vertexSource)); - gl.attachShader(p, mk(gl.FRAGMENT_SHADER, PROBE_FRAG)); - gl.linkProgram(p); - gl.useProgram(p); - const N = 1024; - const tex = gl.createTexture(); - gl.bindTexture(gl.TEXTURE_2D, tex); - gl.texStorage2D(gl.TEXTURE_2D, 1, gl.RGBA32F, N, N); - const fbo = gl.createFramebuffer(); - gl.bindFramebuffer(gl.FRAMEBUFFER, fbo); - gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0); - gl.viewport(0, 0, N, N); - gl.bindVertexArray(gl.createVertexArray()); - gl.uniform3fv(gl.getUniformLocation(p, 'u_side'), side); - gl.uniform1f(gl.getUniformLocation(p, 'u_norm'), norm); - gl.uniform1f(gl.getUniformLocation(p, 'u_span'), 400); - const buf = new Float32Array(N * N * 4); - let gradCos = 0, - gradSin = 0, - vMin = 1e9, - vMax = -1e9, - n = 0; - for (let d = 0; d < draws; d++) { - gl.uniform1f(gl.getUniformLocation(p, 'u_seed'), d + 1); - gl.drawArrays(gl.TRIANGLES, 0, 3); - gl.readPixels(0, 0, N, N, gl.RGBA, gl.FLOAT, buf); - for (let i = 0; i < buf.length; i += 4) { - if (buf[i] > gradCos) gradCos = buf[i]; - if (buf[i + 1] > gradSin) gradSin = buf[i + 1]; - if (buf[i + 2] < vMin) vMin = buf[i + 2]; - if (buf[i + 2] > vMax) vMax = buf[i + 2]; - n++; - } - } - return { samples: n, maxGradCos: gradCos, maxGradSin: gradSin, minCos: vMin, maxCos: vMax }; -}; diff --git a/harness/scene/gradAxis.cjs b/harness/scene/gradAxis.cjs deleted file mode 100644 index 48b96fa6..00000000 --- a/harness/scene/gradAxis.cjs +++ /dev/null @@ -1,30 +0,0 @@ -// Probe: the gradient cultmath_fbm_grad / cultmath_phacelle return for vec3(xz * f, c) is (d/dx, d/dz, d/dc, value), -// so the world-z slope is .y, not .z. Compares analytic gradients with central differences at one point. -// Usage (playwright + swiftshader): node harness/scene/gradAxis.cjs /src/app/features/scene/shaders -const { chromium } = require('playwright'); const fs=require('fs'); -const S=process.argv[2]; -const cm=fs.readFileSync(S+'/CultMath.glsl','utf8'), ph=fs.readFileSync(S+'/CultMath.Phacelle.glsl','utf8'); -const fs_=`#version 300 es -precision highp float; precision highp int; -${cm} -${ph} -out vec4 o; -const float F=1.0/520.0; -float fb(vec2 p){return cultmath_fbm_grad(vec3(p*F,0.0),4,2.0,0.45).w;} -float pc(vec2 p){return cultmath_phacelle(vec3(p/40.0,0.5),vec3(1.5,0.5,0.0),0.0,0.5).cos.w;} -void main(){ - vec2 p=vec2(1234.5,-777.7); float e=0.5; - int k=int(gl_FragCoord.x); - if(k==0){vec4 g=cultmath_fbm_grad(vec3(p*F,0.0),4,2.0,0.45); o=vec4(g.xyz*F,0.0);} // analytic per metre: x,y,z - else if(k==1){o=vec4((fb(p+vec2(e,0))-fb(p-vec2(e,0)))/(2.0*e),(fb(p+vec2(0,e))-fb(p-vec2(0,e)))/(2.0*e),0,0);} - else if(k==2){vec4 g=cultmath_phacelle(vec3(p/40.0,0.5),vec3(1.5,0.5,0.0),0.0,0.5).cos; o=vec4(g.xyz/40.0,0.0);} - else {o=vec4((pc(p+vec2(e,0))-pc(p-vec2(e,0)))/(2.0*e),(pc(p+vec2(0,e))-pc(p-vec2(0,e)))/(2.0*e),0,0);} -}`; -(async()=>{const b=await chromium.launch({args:['--use-gl=angle','--use-angle=swiftshader','--enable-unsafe-swiftshader']}); -const pg=await b.newPage(); -const r=await pg.evaluate(([src])=>{const c=document.createElement('canvas');const g=c.getContext('webgl2');g.getExtension('EXT_color_buffer_float'); -const mk=(t,s)=>{const x=g.createShader(t);g.shaderSource(x,s);g.compileShader(x);if(!g.getShaderParameter(x,g.COMPILE_STATUS))throw g.getShaderInfoLog(x);return x}; -const p=g.createProgram();g.attachShader(p,mk(g.VERTEX_SHADER,'#version 300 es\nvoid main(){vec2 p=vec2(float((gl_VertexID<<1)&2),float(gl_VertexID&2));gl_Position=vec4(p*2.0-1.0,0.0,1.0);}'));g.attachShader(p,mk(g.FRAGMENT_SHADER,src));g.linkProgram(p);g.useProgram(p); -const t=g.createTexture();g.bindTexture(g.TEXTURE_2D,t);g.texImage2D(g.TEXTURE_2D,0,g.RGBA32F,4,1,0,g.RGBA,g.FLOAT,null);const f=g.createFramebuffer();g.bindFramebuffer(g.FRAMEBUFFER,f);g.framebufferTexture2D(g.FRAMEBUFFER,g.COLOR_ATTACHMENT0,g.TEXTURE_2D,t,0);g.viewport(0,0,4,1);g.drawArrays(g.TRIANGLES,0,3); -const o=new Float32Array(16);g.readPixels(0,0,4,1,g.RGBA,g.FLOAT,o);return Array.from(o)},[fs_]).catch(e=>'ERR '+String(e).slice(0,500)); -console.log(Array.isArray(r)?['fbm analytic x,y,z','fbm FD dx,dz','phac analytic','phac FD'].map((n,i)=>n+': '+r.slice(i*4,i*4+3).map(v=>v.toExponential(3)).join(' ')).join('\n'):r);await b.close()})(); diff --git a/harness/scene/ridgeDemo.ts b/harness/scene/ridgeDemo.ts index 17e67774..e61162ee 100644 --- a/harness/scene/ridgeDemo.ts +++ b/harness/scene/ridgeDemo.ts @@ -1,6 +1,5 @@ // Standalone page for the ridge scene: full window, no host app. `?tier=still|low|full` picks the -// tier, `?probe=1` shows the rAF median/p95 readout. The long tasks the page saw are on `window.longTasks` -// for a driver to read. Not shipped. +// tier. The long tasks the page saw are on `window.longTasks` for a driver to read. Not shipped. import { startBackgroundScene } from '../../src/app/features/scene'; import type { SceneTier } from '../../src/app/features/scene'; diff --git a/harness/scene/ridgeSheet.ts b/harness/scene/ridgeSheet.ts index 440a3a57..f0f10fa9 100644 --- a/harness/scene/ridgeSheet.ts +++ b/harness/scene/ridgeSheet.ts @@ -3,8 +3,8 @@ // `?views=214:0:200,0:0:200,100:0:200,214:90:98.2` one column per view `heading:phi:offset` (degrees, degrees, metres) at one sky (`?sky=2`, an index of SKIES, noon by default); a heading // of 360 or 0 is across north. `&sun=100:6` puts the sun of that sky at azimuth 100, 6 degrees up (the stars are always those of the moment the sheet is opened). The offset is clamped to the place's range as the app does (phi 0: the bake's forward bound, any other phi: the worst-case bound), and a phi other than 0 is the offset-only rotation mode, the camera circling the centre. // `?place=vienna` the baked place (index.json's default if absent) -// `?preset=all|physical|swiss|poster|painterly|painterly-cel-2|painterly-cel-3|painterly-cel-4` (default all: one row each; painterly is DEFAULT_LOOK); `?looks=` replaces the rows with -// the given `{label, ...partial RidgeLook}` entries (inkKeep and reliefLight merge by key). `?w=480` sets the cell width, 16:9 unless `?h=` gives the height (`?w=375&h=812` is a phone). +// `?preset=all|painterly|painterly-cel-2|painterly-cel-3|painterly-cel-4` (default all: one row each; painterly is DEFAULT_LOOK); `?looks=` replaces the rows with +// the given `{label, ...partial RidgeLook}` entries (inkKeep merges by key). `?w=480` sets the cell width, 16:9 unless `?h=` gives the height (`?w=375&h=812` is a phone). // The sky behind a cell is the app's own: `makePhysicalSky` + `paintSky` upscaled smoothly, with the real stars and the moon (`nightBodies`), // without the sun disc or clouds. Columns are the SKIES below (a sun elevation each, the stars and moon of the moment the sheet was opened), or: // `?moments=2026-11-24T22:00Z,2026-12-09T20:00Z` explicit UTC moments: the sun, moon and stars are those of the moment, the state follows the sun's elevation @@ -12,7 +12,7 @@ // (`?hours=18,21,0,4` UTC), plus deep dusk (sun at -10 degrees) of the evening of the full moon // `?labels=1` DEBUG: label each constellation chain in frame with its d3-celestial abbreviation (fetched from the source repository at run time; not shipped) // `?lines=1` constellation lines over the stars, as the Sky menu's hidden toggle does (night cells only) -import { DEFAULT_LOOK, PHYSICAL_LOOK, createLighter } from '../../src/app/features/scene/ridge/lightCards'; +import { DEFAULT_LOOK, createLighter } from '../../src/app/features/scene/ridge/lightCards'; import type { RidgeLook } from '../../src/app/features/scene/ridge/lightCards'; import { parseIndex, parseManifest } from '../../src/app/features/scene/ridge/manifest'; import { makePhysicalSky } from '../../src/app/features/scene/ridge/physicalSky'; @@ -28,12 +28,9 @@ import { moonPhase } from '../../src/sky/moon.js'; import { MOMENT_IDS, momentFor } from '../../src/app/features/scene/ridge/skyMoment'; -type Override = Partial> & { +type Override = Partial> & { label: string; - /** The look the unnamed keys come from (DEFAULT_LOOK, the painterly cel look, if absent). */ - base?: 'physical'; inkKeep?: Partial; - reliefLight?: Partial; }; interface Column { @@ -58,26 +55,6 @@ const SKIES: Column[] = [ /** The art directions, chosen by reasoning, not by eye: Self tunes them (values listed in harness/scene/README.md). */ const PRESETS: Record = { - physical: { label: 'physical', base: 'physical' }, - swiss: { - label: 'swiss', - base: 'physical', - reliefLight: { mix: 0.7, azimuthDeg: -45, elevationDeg: 40 }, - contrastByDistance: 0.9, - hazeScale: 6, - hazeTint: [0, 0.05, 0.25], - nearWarm: 0.5, - inkScale: 0.6, - }, - poster: { - label: 'poster', - base: 'physical', - reliefWeight: 0.15, - cardToneStep: 0.25, - cardGradient: 0.5, - inkKeep: { edge: 0.25, occlude: 0.9, crease: 1 }, - hazeScale: 4, - }, painterly: { label: 'painterly (default, cel 3)' }, 'painterly-cel-2': { label: 'painterly-cel-2', celBands: 2 }, 'painterly-cel-3': { label: 'painterly-cel-3', celBands: 3 }, @@ -85,15 +62,13 @@ const PRESETS: Record = { }; const merge = (o: Override): { label: string; look: RidgeLook } => { - const { label, base: baseName, inkKeep, reliefLight, ...rest } = o; - const base = baseName === 'physical' ? PHYSICAL_LOOK : DEFAULT_LOOK; + const { label, inkKeep, ...rest } = o; return { label, look: { - ...base, + ...DEFAULT_LOOK, ...rest, - inkKeep: { ...base.inkKeep, ...inkKeep }, - reliefLight: { ...base.reliefLight, ...reliefLight }, + inkKeep: { ...DEFAULT_LOOK.inkKeep, ...inkKeep }, }, }; }; @@ -187,7 +162,7 @@ const pinned = q.get('moments') || q.get('night'); const rows = (q.get('looks') ? parseLooks(q.get('looks') as string) : preset && preset !== 'all' - ? [PRESETS[preset] ?? PRESETS.physical] + ? [PRESETS[preset] ?? PRESETS.painterly] : pinned ? [PRESETS.painterly] // a night set is read in the default look unless a preset or looks say otherwise : Object.values(PRESETS) diff --git a/scripts/bake-sky.mjs b/scripts/bake-sky.mjs index 827110c2..f01b34e0 100644 --- a/scripts/bake-sky.mjs +++ b/scripts/bake-sky.mjs @@ -1,15 +1,12 @@ -// Bakes Midnight Sky and Noonday Sky from src/sky/sun.js into src/sky/baked.ts, with the -// atmospheric-scattering tables (src/sky/scatter.js) as `scatter`. -// Run `npm run bake:sky` after changing sun.js, skyTokens.js, scatter.js or a moment. +// Bakes Midnight Sky and Noonday Sky from src/sky/sun.js into src/sky/baked.ts. +// Run `npm run bake:sky` after changing sun.js, skyTokens.js or a moment. import { writeFileSync } from 'node:fs'; import { bakeSky } from '../src/sky/skyTokens.js'; -import { bakeScatter } from '../src/sky/scatter.js'; const out = new URL('../src/sky/baked.ts', import.meta.url); const baked = { midnight: bakeSky('midnight'), noonday: bakeSky('noonday'), - scatter: bakeScatter(), }; writeFileSync( out, diff --git a/scripts/buildSha.js b/scripts/buildSha.js index 61a89445..aa3e0597 100644 --- a/scripts/buildSha.js +++ b/scripts/buildSha.js @@ -1,50 +1,28 @@ -// The commit a bundle was built from, stamped into its index.html as , so a built -// folder says what it is without a build log: `grep -o 'build-sha" content="[^"]*' dist/index.html`. -// Where git governs the tree (REPO_DIR is a repository root) git decides: HEAD, suffixed -dirty when the tree has -// uncommitted changes, or `-mismatch` when an explicit BUILD_SHA names a different commit, so a stamp -// never vouches for code it does not hold; a git failure there is 'unknown'. Where git does not govern (a source -// archive), a full-sha BUILD_SHA stands, else 'unknown'. import { execFileSync } from 'child_process'; import { dirname, resolve } from 'path'; import { fileURLToPath } from 'url'; const REPO_DIR = resolve(dirname(fileURLToPath(import.meta.url)), '..'); - -// Vite writes vite.config.js.timestamp-*.mjs next to the config while it loads it; that file is the -// build's own, not source, so an UNTRACKED one must not mark the tree dirty. A tracked file of that name, -// or any other change, still does. Filtering status lines (not a pathspec) is what keeps it untracked-only. +const FULL_SHA = /^[0-9a-f]{40}$/; const VITE_TEMP = /^\?\? (?:.*\/)?vite\.config\.[a-z]+\.timestamp-\d+-[0-9a-f]+\.mjs$/; -export const gitIn = +const gitIn = (cwd) => (...args) => execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }); -const FULL_SHA = /^[0-9a-f]{40}$/; - export const readBuildSha = (env = process.env, run = gitIn(REPO_DIR)) => { - const fromEnv = (env.BUILD_SHA ?? '').trim(); - const explicit = FULL_SHA.test(fromEnv) ? fromEnv : null; - // Git governs this tree only when REPO_DIR is its root: a source archive unpacked inside some other - // repository has no git of its own, and that repository's HEAD says nothing about it. - let governed; - try { - governed = run('rev-parse', '--show-prefix').trim() === ''; - } catch { - governed = false; - } - if (!governed) return explicit ?? 'unknown'; - // Git governs and answers: from here a failure is 'unknown', never the bare explicit sha. + const explicit = (env.BUILD_SHA ?? '').trim(); + const validExplicit = FULL_SHA.test(explicit) ? explicit : null; try { const head = run('rev-parse', 'HEAD').trim(); - if (!FULL_SHA.test(head)) return 'unknown'; - if (explicit && explicit !== head) return `${explicit}-mismatch`; + if (!FULL_SHA.test(head)) return validExplicit ?? 'unknown'; const dirty = run('status', '--porcelain', '-uall', '--', '.') .split('\n') .some((l) => l.trim() !== '' && !VITE_TEMP.test(l)); return dirty ? `${head}-dirty` : head; } catch { - return 'unknown'; + return validExplicit ?? 'unknown'; } }; diff --git a/scripts/buildSha.test.js b/scripts/buildSha.test.js index 4a270867..e3ad4c5a 100644 --- a/scripts/buildSha.test.js +++ b/scripts/buildSha.test.js @@ -1,169 +1,27 @@ -import { execFileSync } from 'child_process'; -import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'fs'; -import { tmpdir } from 'os'; -import { join } from 'path'; -import { afterEach, describe, expect, it } from 'vitest'; -import { buildShaPlugin, gitIn, readBuildSha } from './buildSha'; +import { describe, expect, it } from 'vitest'; +import { buildShaPlugin, readBuildSha } from './buildSha'; const SHA = 'b6b1d522f1c0a9d3e2b4c5d6e7f8091a2b3c4d5e'; -const gitAt = - (head, status = '') => - (cmd, ...args) => - cmd === 'rev-parse' ? (args[0] === '--show-prefix' ? '\n' : `${head}\n`) : status; +const gitAt = (head, status = '') => (cmd) => cmd === 'rev-parse' ? `${head}\n` : status; -describe('readBuildSha', () => { - it('reads the checkout it is built from', () => { +describe('buildSha', () => { + it('reads HEAD and marks dirty trees while ignoring vite temp config files', () => { expect(readBuildSha({}, gitAt(SHA))).toBe(SHA); - }); - it('marks a tree with uncommitted changes, so a stamp never vouches for code it does not hold', () => { + expect(readBuildSha({}, gitAt(SHA, '?? vite.config.js.timestamp-1-ab.mjs\n'))).toBe(SHA); expect(readBuildSha({}, gitAt(SHA, ' M src/x.ts\n'))).toBe(`${SHA}-dirty`); }); - it('lets BUILD_SHA stand in where there is no git, and ignores a value that is not a full sha', () => { + + it('falls back to valid BUILD_SHA or unknown when git is absent', () => { const noGit = () => { - throw new Error('not a git repository'); + throw new Error('no git'); }; expect(readBuildSha({ BUILD_SHA: SHA }, noGit)).toBe(SHA); - expect(readBuildSha({ BUILD_SHA: SHA }, gitAt(SHA))).toBe(SHA); - // a different HEAD is a mismatch, not a clean stamp of the explicit sha - expect(readBuildSha({ BUILD_SHA: SHA }, gitAt('c'.repeat(40)))).toBe(`${SHA}-mismatch`); - // a value that is not a lowercase full sha is ignored - ['b6b1d52', SHA.toUpperCase(), `${SHA}0`].forEach((v) => - expect(readBuildSha({ BUILD_SHA: v }, noGit)).toBe('unknown') - ); - // git that answers but cannot say what the tree holds fails closed - const brokenStatus = (cmd, ...args) => { - if (cmd === 'status') throw new Error('index file smaller than expected'); - return args[0] === '--show-prefix' ? '\n' : `${SHA}\n`; - }; - expect(readBuildSha({ BUILD_SHA: SHA }, brokenStatus)).toBe('unknown'); - expect(readBuildSha({}, brokenStatus)).toBe('unknown'); - expect(readBuildSha({}, gitAt('nope'))).toBe('unknown'); - // inside another repository's subfolder git does not govern: the explicit sha stands - const nested = (cmd, ...args) => (args[0] === '--show-prefix' ? 'vendor/ratatoskr/\n' : SHA); - expect(readBuildSha({ BUILD_SHA: SHA }, nested)).toBe(SHA); - expect(readBuildSha({}, nested)).toBe('unknown'); - expect(readBuildSha({ BUILD_SHA: 'main' }, noGit)).toBe('unknown'); + expect(readBuildSha({ BUILD_SHA: 'short' }, noGit)).toBe('unknown'); + expect(readBuildSha({}, noGit)).toBe('unknown'); }); - it("says 'unknown' rather than failing the build when git is absent", () => { - expect( - readBuildSha({}, () => { - throw new Error('spawn git ENOENT'); - }) - ).toBe('unknown'); - }); -}); -describe('readBuildSha against a real repository', () => { - const made = []; - afterEach(() => { - made.splice(0).forEach((d) => rmSync(d, { recursive: true, force: true })); - }); - const repo = () => { - const dir = mkdtempSync(join(tmpdir(), 'buildsha-')); - made.push(dir); - const g = (...a) => execFileSync('git', a, { cwd: dir, stdio: 'ignore' }); - g('init', '-q'); - mkdirSync(join(dir, 'src')); - writeFileSync(join(dir, 'src', 'a.ts'), 'export {};\n'); - g('add', '.'); - g('-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-qm', 'x'); - return dir; - }; - it("stays clean with vite's temp config file present, and is dirty with a stray source file", () => { - const dir = repo(); - const run = gitIn(dir); - writeFileSync(join(dir, 'vite.config.js.timestamp-1700000000-abc123.mjs'), ''); - expect(readBuildSha({}, run)).toMatch(/^[0-9a-f]{40}$/); - writeFileSync(join(dir, 'src', 'zz-stray.ts'), ''); - expect(readBuildSha({}, run)).toMatch(/^[0-9a-f]{40}-dirty$/); - }); -}); - -describe('readBuildSha dirty rules against a real repository', () => { - const made2 = []; - afterEach(() => { - made2.splice(0).forEach((d) => rmSync(d, { recursive: true, force: true })); - }); - const TEMP = 'vite.config.js.timestamp-1700000000-abc123.mjs'; - const repo2 = (tracked = []) => { - const dir = mkdtempSync(join(tmpdir(), 'buildsha-')); - made2.push(dir); - const g = (...a) => execFileSync('git', a, { cwd: dir, stdio: 'ignore' }); - g('init', '-q'); - mkdirSync(join(dir, 'src')); - writeFileSync(join(dir, 'src', 'a.ts'), 'export {};\n'); - tracked.forEach((f) => writeFileSync(join(dir, f), 'x\n')); - g('add', '.'); - g('-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-qm', 'x'); - return { - dir, - head: execFileSync('git', ['rev-parse', 'HEAD'], { cwd: dir, encoding: 'utf8' }).trim(), - }; - }; - it('does not let an explicit BUILD_SHA mask a dirty tree', () => { - const { dir, head } = repo2(); - const run = gitIn(dir); - expect(readBuildSha({ BUILD_SHA: head }, run)).toBe(head); - writeFileSync(join(dir, 'src', 'zz-stray.ts'), ''); - expect(readBuildSha({ BUILD_SHA: head }, run)).toBe(`${head}-dirty`); - }); - it('lets git speak only for a tree whose root it is: an archive unpacked inside another repository keeps its explicit sha', () => { - const { dir } = repo2(); - const inner = join(dir, 'vendor', 'ratatoskr'); - mkdirSync(inner, { recursive: true }); - writeFileSync(join(inner, 'x.ts'), ''); - expect(readBuildSha({ BUILD_SHA: SHA }, gitIn(inner))).toBe(SHA); - expect(readBuildSha({}, gitIn(inner))).toBe('unknown'); - }); - it("notices an untracked .mjs that is not vite's temp file", () => { - const { dir, head } = repo2(); - writeFileSync(join(dir, 'foo.mjs'), ''); - expect(readBuildSha({}, gitIn(dir))).toBe(`${head}-dirty`); - rmSync(join(dir, 'foo.mjs')); - // only vite's exact shape is its own: vite.config..timestamp--.mjs - [ - 'vite.config.js.timestamp-1-ab.mjs.bak', - 'vite.config.js.timestamp-x-ab.mjs', - 'vite.config.js.timestamp-1-zz.mjs', - 'vite.config.a.b.timestamp-1-ab.mjs', - 'vite.config.js.timestamp-1-ab-c.mjs', - ].forEach((name) => { - writeFileSync(join(dir, name), ''); - expect(readBuildSha({}, gitIn(dir)), name).toBe(`${head}-dirty`); - rmSync(join(dir, name)); - }); - expect(readBuildSha({}, gitIn(dir))).toBe(head); - }); - it('treats a stray source file as dirty even beside the vite temp file, in the root or a subfolder', () => { - const { dir, head } = repo2(); - const run = gitIn(dir); - writeFileSync(join(dir, TEMP), ''); - writeFileSync(join(dir, 'src', TEMP), ''); - expect(readBuildSha({}, run)).toBe(head); - writeFileSync(join(dir, 'src', 'zz-stray.ts'), ''); - expect(readBuildSha({}, run)).toBe(`${head}-dirty`); - }); - it('marks a tracked file of the temp name dirty once it changes', () => { - const { dir, head } = repo2([TEMP]); - const run = gitIn(dir); - expect(readBuildSha({}, run)).toBe(head); - writeFileSync(join(dir, TEMP), 'changed\n'); - expect(readBuildSha({}, run)).toBe(`${head}-dirty`); - }); - it('marks an untracked file in a new folder dirty (status lists files, not the folder)', () => { - const { dir, head } = repo2(); - mkdirSync(join(dir, 'new')); - writeFileSync(join(dir, 'new', TEMP), ''); - expect(readBuildSha({}, gitIn(dir))).toBe(head); - writeFileSync(join(dir, 'new', 'b.ts'), ''); - expect(readBuildSha({}, gitIn(dir))).toBe(`${head}-dirty`); - }); -}); - -describe('buildShaPlugin', () => { - it("hands vite a meta tag for the page's head carrying the sha", () => { - const plugin = buildShaPlugin(SHA); - expect(plugin.transformIndexHtml()).toEqual([ + it('emits a build-sha meta tag', () => { + expect(buildShaPlugin(SHA).transformIndexHtml()).toEqual([ { tag: 'meta', attrs: { name: 'build-sha', content: SHA }, injectTo: 'head-prepend' }, ]); }); diff --git a/scripts/preview-config.js b/scripts/preview-config.js index 29bfa793..b57ab63e 100644 --- a/scripts/preview-config.js +++ b/scripts/preview-config.js @@ -1,21 +1,20 @@ // Preview builds: set the background scene tier in dist/config.json (default 'low'); config.json -// in the repo is the live chat.gamecult.org config (style ridge), and previews pin the style too, ridge unless -// given. Previews are static directories with no SPA fallback, so they also switch +// in the repo is the live chat.gamecult.org config. Previews are static directories with no SPA fallback, so they also switch // to the hash router: a reload on /login/matrix.org would otherwise be an nginx 404. With --demo it // also switches on the pretend homeserver (src/preview-demo): previewDemo true, and the pretend // server as the only homeserver. Usage: -// node scripts/preview-config.js [tier] [style] [--demo] +// node scripts/preview-config.js [tier] [--demo] import fs from 'fs'; import path from 'path'; import { fileURLToPath } from 'url'; const args = process.argv.slice(2); const demo = args.includes('--demo'); -const [tier = 'low', style = 'ridge'] = args.filter((a) => !a.startsWith('--')); +const [tier = 'low'] = args.filter((a) => !a.startsWith('--')); const file = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'dist', 'config.json'); const config = JSON.parse(fs.readFileSync(file, 'utf8')); config.hashRouter = { enabled: true, basename: '/' }; -config.backgroundScene = { ...config.backgroundScene, tier, style }; +config.backgroundScene = { ...config.backgroundScene, tier }; if (demo) { config.previewDemo = true; config.defaultHomeserver = 0; @@ -30,5 +29,5 @@ if (demo) { } fs.writeFileSync(file, `${JSON.stringify(config, null, 2)}\n`); console.log( - `${file}: backgroundScene.tier = ${tier}, style = ${style}${demo ? ', previewDemo on' : ''}` + `${file}: backgroundScene.tier = ${tier}${demo ? ', previewDemo on' : ''}` ); diff --git a/scripts/ridge-bake/README.md b/scripts/ridge-bake/README.md index 97b02a77..ddb17abf 100644 --- a/scripts/ridge-bake/README.md +++ b/scripts/ridge-bake/README.md @@ -8,9 +8,9 @@ Offline baker for the ridge backdrop: it turns a Copernicus DEM into K+1 G-buffe python3 -I scripts/ridge-bake/export.py --tiles DIR --out public/ridge/ [--work DIR] [--sheet contact.png] ``` -Needs Python 3 with `numpy`, `tifffile` and `imagecodecs`. `--tiles` is a directory of Copernicus GLO-30 tiles (never committed); `--work` caches the mosaic and rays (default `$TMPDIR/ridge-bake-work`); `--sheet` writes the contact sheet at 1/4 of the ring's width (the ring composite, every card's strip alone and the depth image with every seam, the 32 tile boundaries drawn, lit by one fixed light). The bake prints `r_max_m`, the resident run and the worst fit error per card. `python3 -I scripts/ridge-bake/export.py --write-schema` rewrites `ridge-bake.schema.json`, which the tests pin. +Needs Python 3 with `numpy`, `tifffile` and `imagecodecs`. `--tiles` is a directory of Copernicus GLO-30 tiles (never committed); `--work` caches the mosaic and rays (default `$TMPDIR/ridge-bake-work`); `--sheet` writes the contact sheet at 1/4 of the ring's width (the ring composite, every card's strip alone and the depth image with every seam, the 32 tile boundaries drawn, lit by one fixed light). The bake prints `r_max_m`, the resident run and the worst fit error per card. -Tests: `RIDGE_PY= RIDGE_TILES=DIR scripts/ridge-bake/tests/run.sh [test_ridge.py|mutate.py]` (`mutate.py` re-introduces each rule's failure into a copy of the baker and fails if a test does not notice). +Tests: `RIDGE_PY= RIDGE_TILES=DIR scripts/ridge-bake/tests/run.sh` ## Tiles per preset (`places.json`) diff --git a/scripts/ridge-bake/export.py b/scripts/ridge-bake/export.py index 42769221..c9dd030b 100644 --- a/scripts/ridge-bake/export.py +++ b/scripts/ridge-bake/export.py @@ -1,14 +1,12 @@ """Ridge backdrop export: bake a place with ridge.py and write its K+1 G-buffer cards as 32 azimuth tiles each (colour + geometry WebP per card per tile), a manifest v3 and the index. python3 -I scripts/ridge-bake/export.py --tiles DIR --out public/ridge/ [--work DIR] [--sheet contact.png] - python3 -I scripts/ridge-bake/export.py --write-schema (rewrites ridge-bake.schema.json from SCHEMA below) -The runtime reads manifest.json (SCHEMA is its contract) and nothing else about the bake. The ring is the whole 360 degrees (ruling ridge-camera-full-ring), absolute compass, column 0 = north, cut into TILES tiles of TILE_W columns plus an APRON of real neighbour +The runtime reads manifest.json and nothing else about the bake. The ring is the whole 360 degrees (ruling ridge-camera-full-ring), absolute compass, column 0 = north, cut into TILES tiles of TILE_W columns plus an APRON of real neighbour columns each side; the bake holds no camera: it ships each card tile's distance_m and camera.r_max_m, the largest offset the per-card linear slide can take (ruling ridge-offset-range-fit); the client lights the cards itself (ruling ridge-cards-runtime-lit). -The pure parts (budget, bake_id, index, schema check) import no baker; bake_place imports ridge, which needs RIDGE_TILES and RIDGE_WORK (main sets them from --tiles / --work), and so do pack, validate_manifest and write_bake, which read ridge's NEAR_CLIP_M and GROUND_ROWS_MIN.""" +The pure parts (budget, bake_id, index) import no baker; bake_place imports ridge, which needs RIDGE_TILES and RIDGE_WORK (main sets them from --tiles / --work), and so do pack, validate_manifest and write_bake, which read ridge's NEAR_CLIP_M and GROUND_ROWS_MIN.""" import os, sys, json, math, shutil, hashlib, argparse, tempfile from pathlib import Path -from zoneinfo import ZoneInfo, ZoneInfoNotFoundError HERE = Path(__file__).resolve().parent sys.path.insert(0, str(HERE)) from refusal import Refusal @@ -39,57 +37,14 @@ ATTRIBUTION = dict( dem_source='Copernicus DEM GLO-30 (30 m)', url='https://spacedata.copernicus.eu/collections/copernicus-digital-elevation-model') -# ------------------------------------------------------------------------------------ schema (the one dict the schema file and the validator both come from) -_num, _int, _str = {'type': 'number'}, {'type': 'integer'}, {'type': 'string'} -_numnull = {'type': ['number', 'null']} -_tz = {'type': 'string', 'format': 'iana-tz'} # an IANA zone the system knows, as ridge.load_preset requires; validate() checks it -def _obj(**props): return {'type': 'object', 'required': list(props), 'additionalProperties': False, 'properties': props} -def _objnull(**props): return dict(_obj(**props), type=['object', 'null']) -_file = _obj(file=_str, bytes=_int) -SCHEMA = {'$schema': 'https://json-schema.org/draft/2020-12/schema', 'title': 'ridge-bake manifest v3 and index v1', '$defs': { - 'manifest': _obj(schema={'const': 3}, baker_version=_int, bake_id=_str, - place=_obj(id=_str, name=_str, lat=_num, lon=_num, altitude_km=_num, eye_m=_num, tz=_tz), - view=_obj(look_az_deg=_num, ring_w={'const': RING_W}, tile_w={'const': TILE_W}, tiles={'const': TILES}, apron={'const': APRON}, plane_h=_int, px_per_deg_h=_num, px_per_deg_v=_num, exaggeration=_num, horizon_row=_num, sky_row=_num, near_row=_num), - curvature=_obj(r_earth_m=_num, k_ref=_num), - encoding=_obj(log_d_min=_num, log_d_max=_num, normal={'const': 'rt8'}), - camera=dict(_obj(r_max_m=_num, r_max_forward_m=_num), description="r_max_m (every camera angle on its circle) and r_max_forward_m (the camera on its heading) are the offsets up to which the linear slide holds (the fit error at most FIT_PX_MAX card px) for the NEAREST solid terrain (at or beyond the near clip, ridge.NEAR_CLIP_M, 500 m) that each card draws in each tile, not for the tile's median distance_m; a tile whose card 0 draws only near ground (under the clip) is slid at the clip distance (its distance_m) and binds at 500 m. The ground under the clip is drawn by card 0 from the near march and is otherwise not measured."), - cards={'type': 'array', 'minItems': 1, 'maxItems': MAX_CARDS, 'items': _obj(near_m=_numnull, far_m=_numnull), - 'description': "nearest first; the runtime paints the list last to first. near_m and far_m are the median seam depths over the ring, null at the ends."}, - tiles={'type': 'array', 'minItems': TILES, 'maxItems': TILES, 'items': {'type': 'array', 'minItems': 1, 'maxItems': MAX_CARDS, 'items': _objnull(top=_int, h=_int, distance_m=_num, colour=_file, geometry=_file)}, - 'description': "tiles[t][i] is card i in tile t, or null where the card holds nothing in that tile (the client takes its distance from the neighbouring tiles). Tile t owns the ring columns [tile_w t, tile_w (t + 1)), column c at azimuth (c + 0.5) / ring_w x 360, 0 = north; its files hold [tile_w t - apron, tile_w (t + 1) + apron), wrapping at the ring's end, and are tile_w + 2 apron columns wide. top and h place the card's band back at its rows of the frame; distance_m = exp(median ln d) of the card's solid pixels in the tile that are neither wall nor near ground, under the near clip (the interior tile_w columns); a tile whose card draws only near ground gets the clip distance."}, - bytes=_int, - attribution=_obj(credit_line=_str, licence=_str, dem_source=_str, url=_str)), - 'index': _obj(schema={'const': 1}, default=_str, places={'type': 'object', 'additionalProperties': _str})}} def tile_file(i, t, kind): return f'card-{i}-t{t:02d}-{kind}.webp' -def validate(x, s, path='$'): - """The subset of JSON Schema SCHEMA uses; raises Refusal naming the path.""" - if '$ref' in s: return validate(x, SCHEMA['$defs'][s['$ref'].split('/')[-1]], path) - tys = s.get('type'); tys = [tys] if isinstance(tys, str) else tys; py = {'object': dict, 'array': list, 'string': str, 'number': (int, float), 'integer': int, 'null': type(None)} - if tys and not any(isinstance(x, py[t]) and not (isinstance(x, bool) and t != 'null') for t in tys): raise Refusal(f'{path}: not a {"/".join(tys)}') - if s.get('format') == 'iana-tz': - try: ZoneInfo(x) - except (ZoneInfoNotFoundError, ValueError, OSError): raise Refusal(f'{path}: {x!r} is not a time zone the system knows') - if 'const' in s and x != s['const']: raise Refusal(f"{path}: must be {s['const']!r}") - if 'enum' in s and x not in s['enum']: raise Refusal(f'{path}: not one of {s["enum"]}') - if 'maximum' in s and x > s['maximum']: raise Refusal(f'{path}: above {s["maximum"]}') - if isinstance(x, list): - if not s.get('minItems', 0) <= len(x) <= s.get('maxItems', 1 << 30): raise Refusal(f'{path}: wrong length') - for i, v in enumerate(x): validate(v, s['items'], f'{path}[{i}]') - if isinstance(x, dict): - props = s.get('properties', {}); extra = s.get('additionalProperties', True) - for k in s.get('required', []): - if k not in x: raise Refusal(f'{path}: missing {k}') - for k, v in x.items(): - if k in props: validate(v, props[k], f'{path}.{k}') - elif extra is False: raise Refusal(f'{path}: extra key {k}') - elif isinstance(extra, dict): validate(v, extra, f'{path}.{k}') - def validate_manifest(m): - """The schema plus what it cannot say: the plane keeps ridge.GROUND_ROWS_MIN rows under the horizon, every tile lists one entry per card, every card holds something in some tile, each file is named for its card and tile, bytes is the sum of the files.""" + """Check the baked manifest's structural invariants: the plane keeps ridge.GROUND_ROWS_MIN rows under the horizon, there are TILES tiles of one entry per card, every card holds something in some tile, each file is named for its card and tile, bytes is the sum of the files.""" import ridge - validate(m, SCHEMA['$defs']['manifest']); k = len(m['cards']); v = m['view'] + k = len(m['cards']); v = m['view'] if v['plane_h'] - v['horizon_row'] < ridge.GROUND_ROWS_MIN - 1e-6: raise Refusal(f"$.view: {v['plane_h'] - v['horizon_row']:.1f} rows under the horizon, below the {ridge.GROUND_ROWS_MIN} the runtime needs (ridge.GROUND_ROWS_MIN)") + if len(m['tiles']) != TILES: raise Refusal(f"$.tiles: {len(m['tiles'])} tiles, expected {TILES}") for t, row in enumerate(m['tiles']): if len(row) != k: raise Refusal(f'$.tiles[{t}]: {len(row)} entries for {k} cards') for i, e in enumerate(row): @@ -226,7 +181,6 @@ def write_bake(out, place, view, meta, packed, opaque, default=None): (tmp / 'manifest.json').write_bytes(text.encode('utf-8')) # bytes, so the platform's newline cannot move the file under its id idx_path = out / 'index.json'; idx = json.loads(idx_path.read_text()) if idx_path.exists() else dict(schema=1, default=place['id'], places={}) old = idx['places'].get(place['id']); idx['places'][place['id']] = name; idx['default'] = default or (idx['default'] if idx['default'] in idx['places'] else place['id']) - validate(idx, SCHEMA['$defs']['index']) if dest.exists(): shutil.rmtree(dest) os.rename(tmp, dest); (out / '.index.tmp').write_bytes((json.dumps(idx, indent=1) + '\n').encode('utf-8')); os.replace(out / '.index.tmp', idx_path) if old and old != name: shutil.rmtree(out / old, ignore_errors=True) @@ -300,10 +254,8 @@ def sheet(bake): return bytes(imagecodecs.png_encode(u8(np.concatenate([bounds(q(comp))] + [bounds(q(p)) for p in panels] + [bounds(depth)], 0)))) def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.split('\n')[0]); ap.add_argument('place', nargs='?'); ap.add_argument('--tiles'); ap.add_argument('--out'); ap.add_argument('--work'); ap.add_argument('--sheet'); ap.add_argument('--write-schema', action='store_true') + ap = argparse.ArgumentParser(description=__doc__.split('\n')[0]); ap.add_argument('place'); ap.add_argument('--tiles', required=True); ap.add_argument('--out', required=True); ap.add_argument('--work'); ap.add_argument('--sheet') a = ap.parse_args(argv) - if a.write_schema: (HERE / 'ridge-bake.schema.json').write_bytes((json.dumps(SCHEMA, indent=1, ensure_ascii=False) + '\n').encode('utf-8')); return 0 - if not (a.place and a.tiles and a.out): ap.error('place, --tiles and --out are required') os.environ['RIDGE_TILES'] = a.tiles; os.environ['RIDGE_WORK'] = a.work or os.path.join(os.environ.get('TMPDIR', tempfile.gettempdir()), 'ridge-bake-work'); os.makedirs(os.environ['RIDGE_WORK'], exist_ok=True) bake = bake_place(a.place) if a.sheet: Path(a.sheet).write_bytes(sheet(bake)) diff --git a/scripts/ridge-bake/refusal.py b/scripts/ridge-bake/refusal.py index 213d8369..26423721 100644 --- a/scripts/ridge-bake/refusal.py +++ b/scripts/ridge-bake/refusal.py @@ -1,2 +1,2 @@ -"""The baker's refusal: raised wherever ridge.py or export.py declines a preset, a view or a bake. The fixtures catch this class only, so an exception from numpy or the standard library reaching them is a crash (mutate.py: CRASHED), never a kill.""" +"""The baker's refusal: raised wherever ridge.py or export.py declines a preset, a view or a bake.""" class Refusal(ValueError): pass diff --git a/scripts/ridge-bake/ridge-bake.schema.json b/scripts/ridge-bake/ridge-bake.schema.json deleted file mode 100644 index 3f7f9b41..00000000 --- a/scripts/ridge-bake/ridge-bake.schema.json +++ /dev/null @@ -1,327 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "title": "ridge-bake manifest v3 and index v1", - "$defs": { - "manifest": { - "type": "object", - "required": [ - "schema", - "baker_version", - "bake_id", - "place", - "view", - "curvature", - "encoding", - "camera", - "cards", - "tiles", - "bytes", - "attribution" - ], - "additionalProperties": false, - "properties": { - "schema": { - "const": 3 - }, - "baker_version": { - "type": "integer" - }, - "bake_id": { - "type": "string" - }, - "place": { - "type": "object", - "required": [ - "id", - "name", - "lat", - "lon", - "altitude_km", - "eye_m", - "tz" - ], - "additionalProperties": false, - "properties": { - "id": { - "type": "string" - }, - "name": { - "type": "string" - }, - "lat": { - "type": "number" - }, - "lon": { - "type": "number" - }, - "altitude_km": { - "type": "number" - }, - "eye_m": { - "type": "number" - }, - "tz": { - "type": "string", - "format": "iana-tz" - } - } - }, - "view": { - "type": "object", - "required": [ - "look_az_deg", - "ring_w", - "tile_w", - "tiles", - "apron", - "plane_h", - "px_per_deg_h", - "px_per_deg_v", - "exaggeration", - "horizon_row", - "sky_row", - "near_row" - ], - "additionalProperties": false, - "properties": { - "look_az_deg": { - "type": "number" - }, - "ring_w": { - "const": 6400 - }, - "tile_w": { - "const": 200 - }, - "tiles": { - "const": 32 - }, - "apron": { - "const": 2 - }, - "plane_h": { - "type": "integer" - }, - "px_per_deg_h": { - "type": "number" - }, - "px_per_deg_v": { - "type": "number" - }, - "exaggeration": { - "type": "number" - }, - "horizon_row": { - "type": "number" - }, - "sky_row": { - "type": "number" - }, - "near_row": { - "type": "number" - } - } - }, - "curvature": { - "type": "object", - "required": [ - "r_earth_m", - "k_ref" - ], - "additionalProperties": false, - "properties": { - "r_earth_m": { - "type": "number" - }, - "k_ref": { - "type": "number" - } - } - }, - "encoding": { - "type": "object", - "required": [ - "log_d_min", - "log_d_max", - "normal" - ], - "additionalProperties": false, - "properties": { - "log_d_min": { - "type": "number" - }, - "log_d_max": { - "type": "number" - }, - "normal": { - "const": "rt8" - } - } - }, - "camera": { - "type": "object", - "required": [ - "r_max_m", - "r_max_forward_m" - ], - "additionalProperties": false, - "properties": { - "r_max_m": { - "type": "number" - }, - "r_max_forward_m": { - "type": "number" - } - }, - "description": "r_max_m (every camera angle on its circle) and r_max_forward_m (the camera on its heading) are the offsets up to which the linear slide holds (the fit error at most FIT_PX_MAX card px) for the NEAREST solid terrain (at or beyond the near clip, ridge.NEAR_CLIP_M, 500 m) that each card draws in each tile, not for the tile's median distance_m; a tile whose card 0 draws only near ground (under the clip) is slid at the clip distance (its distance_m) and binds at 500 m. The ground under the clip is drawn by card 0 from the near march and is otherwise not measured." - }, - "cards": { - "type": "array", - "minItems": 1, - "maxItems": 6, - "items": { - "type": "object", - "required": [ - "near_m", - "far_m" - ], - "additionalProperties": false, - "properties": { - "near_m": { - "type": [ - "number", - "null" - ] - }, - "far_m": { - "type": [ - "number", - "null" - ] - } - } - }, - "description": "nearest first; the runtime paints the list last to first. near_m and far_m are the median seam depths over the ring, null at the ends." - }, - "tiles": { - "type": "array", - "minItems": 32, - "maxItems": 32, - "items": { - "type": "array", - "minItems": 1, - "maxItems": 6, - "items": { - "type": [ - "object", - "null" - ], - "required": [ - "top", - "h", - "distance_m", - "colour", - "geometry" - ], - "additionalProperties": false, - "properties": { - "top": { - "type": "integer" - }, - "h": { - "type": "integer" - }, - "distance_m": { - "type": "number" - }, - "colour": { - "type": "object", - "required": [ - "file", - "bytes" - ], - "additionalProperties": false, - "properties": { - "file": { - "type": "string" - }, - "bytes": { - "type": "integer" - } - } - }, - "geometry": { - "type": "object", - "required": [ - "file", - "bytes" - ], - "additionalProperties": false, - "properties": { - "file": { - "type": "string" - }, - "bytes": { - "type": "integer" - } - } - } - } - } - }, - "description": "tiles[t][i] is card i in tile t, or null where the card holds nothing in that tile (the client takes its distance from the neighbouring tiles). Tile t owns the ring columns [tile_w t, tile_w (t + 1)), column c at azimuth (c + 0.5) / ring_w x 360, 0 = north; its files hold [tile_w t - apron, tile_w (t + 1) + apron), wrapping at the ring's end, and are tile_w + 2 apron columns wide. top and h place the card's band back at its rows of the frame; distance_m = exp(median ln d) of the card's solid pixels in the tile that are neither wall nor near ground, under the near clip (the interior tile_w columns); a tile whose card draws only near ground gets the clip distance." - }, - "bytes": { - "type": "integer" - }, - "attribution": { - "type": "object", - "required": [ - "credit_line", - "licence", - "dem_source", - "url" - ], - "additionalProperties": false, - "properties": { - "credit_line": { - "type": "string" - }, - "licence": { - "type": "string" - }, - "dem_source": { - "type": "string" - }, - "url": { - "type": "string" - } - } - } - } - }, - "index": { - "type": "object", - "required": [ - "schema", - "default", - "places" - ], - "additionalProperties": false, - "properties": { - "schema": { - "const": 1 - }, - "default": { - "type": "string" - }, - "places": { - "type": "object", - "additionalProperties": { - "type": "string" - } - } - } - } - } -} diff --git a/scripts/ridge-bake/tests/mutate.py b/scripts/ridge-bake/tests/mutate.py deleted file mode 100644 index 94702e0d..00000000 --- a/scripts/ridge-bake/tests/mutate.py +++ /dev/null @@ -1,130 +0,0 @@ -"""Mutation check: re-introduce a cause into a COPY of the baker, run the fixtures against it, and require that at least one fails. - venv/bin/python tests/mutate.py [word ...] (runs the unmutated copy first and exits 2 if a fixture fails; prints one line per mutant whose name holds every word; exit 1 if a mutant survives or only crashes the run: a kill is an AssertionError raised by the fixtures' own code)""" -import os, shutil, subprocess, sys, tempfile -HERE = os.path.dirname(os.path.abspath(__file__)); SRC = os.path.join(HERE, '..') -MUTANTS = { # name -> (text in ridge.py or export.py, replacement) - 'seam cost: the rows a seam sweeps are not paid (it hops across a receding ridge)': ("np.cumsum(0.5 * (cov[:, x - 1] + cov[:, x])) + SEAM_LAM * bins", "SEAM_LAM * bins"), - 'seam prior pulls hard to the target (2.0, or 0.1: the seam hops across a ridge)': ("SEAM_PRIOR = 0.02 ", "SEAM_PRIOR = 2.0 "), - 'normals: the authored exaggeration is dropped': ("h = np.asarray(h, np.float64); E = PXDEG_V / HPX_DEG", "h = np.asarray(h, np.float64); E = 1.0"), - 'normals: the lateral neighbour is one sample nearer (not equal distance)': ("st = E * (np.roll(h, -1, axis=1) - np.roll(h, 1, axis=1))", "st = E * (np.roll(np.roll(h, -1, axis=1), 1, axis=0) - np.roll(h, 1, axis=1))"), - 'cards: the near edge is ignored (every card starts at sample 0)': ("k0 = 0 if i == 0 else int(ks0[i - 1][x])", "k0 = 0"), - 'cards: the farther card fades in over the window too (both cards translucent)': ("X[i, :, x] = 1 - s * s * (3 - 2 * s)", "X[i, :, x] = 1 - s * s * (3 - 2 * s); X[i + 1, :, x] = s * s * (3 - 2 * s)"), - 'cards: a crest row is all or nothing (no fractional coverage)': ("F[i, :, x] = np.where(hit, np.clip((rm[-1] - lo) / p, 0, 1), 0)", "F[i, :, x] = np.where(hit, 1.0, 0)"), - 'prefilter ignores sigma': ("if sigma_m > 0:", "if False:"), - 'prefilter across rays uses one sigma in columns (not per distance)': ("sc = sigma_m / (d * COLW)", "sc = sigma_m / (d[0] * COLW) * np.ones_like(d)"), - 'bake_id hashes geometry before colour': ("h.update(colour); h.update(geometry)", "h.update(geometry); h.update(colour)"), - 'check_cover accepts any composite': ("if bad.any(): y, x", "if False: y, x"), - 'load_preset accepts splits that do not increase': ("or any(b <= a for a, b in zip(sp, sp[1:]))", ""), - 'geometry: n_r and n_t channels swapped': ("r, t = u8((np.asarray(n_r) + 1) / 2), u8((np.asarray(n_t) + 1) / 2)", "r, t = u8((np.asarray(n_t) + 1) / 2), u8((np.asarray(n_r) + 1) / 2)"), - 'geometry: log-distance not normalised by the encoding range': ("b = (np.asarray(logd) - enc['log_d_min']) / (enc['log_d_max'] - enc['log_d_min'])", "b = np.asarray(logd) / 12.0"), - 'colour: albedo zeroed in the file': ("rgb = u8(albedo) * (a[..., None] > 0)", "rgb = u8(albedo) * 0"), - 'colour: premultiplied instead of straight': ("rgb = u8(albedo) * (a[..., None] > 0)", "rgb = u8(np.asarray(albedo) * np.asarray(alpha)[..., None])"), - 'seams: the separation between seams is ignored': ("SEAM_SEP = 0.4 ", "SEAM_SEP = 0.0 "), - 'elev: curvature and refraction dropped': ("drop = d * d / (2 * R_EARTH) * (1 - KREF) if curvature else 0.0", "drop = 0.0"), - 'coverage: the rows below the first sample are not counted': ("prev = np.vstack([np.full((1, a.shape[1]), BOTTOM_DEG), runmax[:-1]])", "prev = np.vstack([np.full((1, a.shape[1]), 100.0), runmax[:-1]])"), - 'coverage: the rows below the first sample are counted twice': ("* PXDEG_V)\n return C", "* PXDEG_V); C[0] += np.clip(np.minimum(a[0], TOP_DEG) - BOTTOM_DEG, 0, None) * PXDEG_V\n return C"), - 'cards: the hit is not interpolated between samples': ("t = np.where(idx > 0, np.clip((rowang - prev) / np.maximum(rm[idx] - prev, 1e-9), 0, 1), 1.0)", "t = np.ones_like(rowang)"), - 'cards: the blended normal is not renormalised': ("nz = np.sqrt(g[2] ** 2 + g[3] ** 2 + g[4] ** 2) + 1e-12", "nz = 1.0"), - 'wall: no row is flagged (the flag is dropped)': ("Wl[i, :, x] = hit & (idx == 0)", "Wl[i, :, x] = False"), - 'near: the cap to the silhouette of the terrain at the clip is dropped': ("an = np.minimum(an, a[0][None, :])", "an = an"), - 'near: rows under the clip are flagged wall': ("Wl[i, :, x] = hit & (idx == 0); Nr[i, :, x] = hit & (kp < kn)", "Wl[i, :, x] = hit & ((idx == 0) | (kp < kn)); Nr[i, :, x] = hit & (kp < kn)"), - 'near: albedo takes the face up (the wall rule on near rows)': ("albedo(g[1], np.where(Wl[i, sl], 1.0, g[4] / nz), material)", "albedo(g[1], np.where(Wl[i, sl] | Nr[i, sl], 1.0, g[4] / nz), material)"), - 'near: albedo reads the height of the far march first sample': ("albedo(g[1], np.where(Wl[i, sl]", "albedo(np.where(Nr[i, sl], h[int(np.searchsorted(d, NEAR_CLIP_M))][None, :], g[1]), np.where(Wl[i, sl]"), - 'near: the march starts at 20 m': ("NEAR_START_M = 1.0 ", "NEAR_START_M = 20.0 "), - 'near: the heights are stored float32': (", np.float64) for dk in d])", ", np.float32) for dk in d])"), - 'near: the place prefilter is not applied': ("; a, h = prefilter(d, h, sigma_m)\n", "; a, h = prefilter(d, h, 0.0)\n"), - 'near: the far normals are computed over the joined march (not apart)': ("nn, nf = normals(dn, hn), normals(d, h)", "nj_ = normals(np.concatenate([dn, d]), np.concatenate([hn, h])); nn, nf = tuple(x[:len(dn)] for x in nj_), tuple(x[len(dn):] for x in nj_)"), - 'near: cards accepts a march that starts at the clip': ("if d[0] >= NEAR_CLIP_M: raise Refusal", "if False: raise Refusal"), - 'pack: near pixels count as solid terrain': ("solid = (al >= 0.5) & ~wl & ~nr;", "solid = (al >= 0.5) & ~wl;"), - 'pack: the non-wall fallback pool reads near pixels': ("((al > 0) & ~wl & ~nr, ld)", "((al > 0) & ~wl, ld)"), - 'pack: the lit fallback pool reads near pixels': ("((al > 0) & ~nr, ld)", "(al > 0, ld)"), - 'pack: the apron fallback pool reads near pixels': ("((c['alpha'] > 0) & ~c['near'], c['logd'])", "(c['alpha'] > 0, c['logd'])"), - 'pack: a tile with nothing outside the near ground is not at the clip': ("if pool else ridge.NEAR_CLIP_M", "if pool else 0.0"), - 'r_max: the tile median binds, not the nearest terrain': ("r_max = solve_r_max(near, bands, ppd); r_fwd = solve_r_max(near, bands, ppd, phis=1)", "r_max = solve_r_max(dist, bands, ppd); r_fwd = solve_r_max(dist, bands, ppd, phis=1)"), - 'r_max: near pixels do not bind at the clip': ("ridge.NEAR_CLIP_M if ((al >= 0.5) & nr).any() else None", "None"), - 'r_max: near pixels bind only in a tile with no other solid pixel': ("ridge.NEAR_CLIP_M if ((al >= 0.5) & nr).any() else None", "ridge.NEAR_CLIP_M if ((al >= 0.5) & nr).any() and not solid.any() else None"), - 'r_max: near pixels bind only where they outnumber the solid ones': ("ridge.NEAR_CLIP_M if ((al >= 0.5) & nr).any() else None", "ridge.NEAR_CLIP_M if ((al >= 0.5) & nr).sum() > solid.sum() else None"), - 'r_max: the nearest pixel is the farthest solid one': ("float(np.exp(ld[solid].min())) if solid.any() else None, ridge", "float(np.exp(ld[solid].max())) if solid.any() else None, ridge"), - 'near clip: the writer compares the float32 distance strictly': ("if rmin < ridge.NEAR_CLIP_M * (1 - 1e-5): raise", "if rmin < ridge.NEAR_CLIP_M: raise"), - 'near clip: the march starts nearer than the clip': ("d = [NEAR_CLIP_M]", "d = [100.0]"), - 'near clip: a card 0 inside the clip is accepted by the writer': ("if rmin < ridge.NEAR_CLIP_M * (1 - 1e-5): raise", "if False: raise"), - 'view: the 1x floor is back': ("lo, hi = E_MIN * HPX_DEG, 10 * HPX_DEG", "lo, hi = HPX_DEG, 10 * HPX_DEG"), - 'view: the horizon anchor is dropped (the scale is the skyline fit alone)': ("ppd = float(np.clip(min(fit, hold), lo, hi))", "ppd = float(np.clip(fit, lo, hi))"), - 'view: a skyline that cannot hold the ground rows is not refused': ("if hold < lo: raise", "if False: raise"), - 'view: the ground rows are not asked for (GROUND_ROWS_MIN 0)': ("GROUND_ROWS_MIN = 150 ", "GROUND_ROWS_MIN = 0 "), - 'validate_manifest: a plane short of its ground rows is accepted': ("if v['plane_h'] - v['horizon_row'] < ridge.GROUND_ROWS_MIN - 1e-6: raise", "if False: raise"), - 'wall: albedo takes the face normal, not the face up': ("np.where(Wl[i, sl], 1.0, g[4] / nz)", "g[4] / nz"), - 'wall: the code is not written to the geometry': ("if wall is not None: m = np.asarray(wall, bool)", "if False: m = np.asarray(wall, bool)"), - 'wall: the sheet lights wall rows with their normal': ("wall = c['wall']; n_r, n_t = np.where(wall, 0.0, c['n_r']), np.where(wall, 0.0, c['n_t'])", "n_r, n_t = c['n_r'], c['n_t']"), - 'ring: the seam DP is not periodic (the first lap is kept, not the middle)': ("return out[:, n:2 * n]", "return out[:, :n]"), - 'ring: the tile take does not wrap (the ring ends repeat their edge column)': ("return np.take(a, (c0 + np.arange(n)) % W, axis=-1)", "return np.take(a, np.clip(c0 + np.arange(n), 0, W - 1), axis=-1)"), - 'tile: the apron is shifted (a tile starts at its own first column)': ("ridge.ring_cols(x, t * TILE_W - APRON, TILE_W + 2 * APRON)", "ridge.ring_cols(x, t * TILE_W, TILE_W + 2 * APRON)"), - 'tile: the seams are cut from tile 0 for every tile': ("cols(sm, t), tuple(cols(x, t) for x in nrm)", "cols(sm, 0), tuple(cols(x, t) for x in nrm)"), - 'view: the vertical anchors read the first 72 degrees only (the old window)': ("sk = np.asarray(skyline); sky", "sk = np.asarray(skyline)[:1280]; sky"), - 'bake_id: card-major instead of tile-major': ("bake_id(text, [(e['colour'], e['geometry']) for row in tiles for e in row if e])", "bake_id(text, [(row[i]['colour'], row[i]['geometry']) for i in range(k) for row in tiles if row[i]])"), - 'bake_id: the manifest is not hashed (a manifest moves under its id)': ("h = hashlib.sha256(); h.update(manifest_text.encode('utf-8'))", "h = hashlib.sha256()"), - 'bake_id: the manifest is hashed with the id already in it (the blank is skipped)': ("bid = bake_id(text, [", "bid = bake_id(text.replace(BAKE_ID_BLANK, '111111111111'), ["), - 'write: the per-tile cover check is dropped': ("except Refusal as ex: raise Refusal(f'tile {t}: {ex}')", "except Refusal as ex: pass"), - 'write: the apron width is not checked': ("if c.shape[1] != w: raise", "if False: raise"), - 'budget: the tile cap is ignored': ("if b > TILE_BYTES_MAX: raise", "if False: raise"), - 'budget: the place cap is ignored': ("if sum(tile_bytes) > PLACE_BYTES_MAX: raise", "if False: raise"), - 'budget: the resident gate is ignored': ("if res > RESIDENT_BYTES_MAX: raise", "if False: raise"), - 'budget: the resident run does not wrap the ring': ("sum(per[(t + k) % TILES] for k in range(n))", "sum(per[t + k] for k in range(n) if t + k < TILES)"), - 'budget: the run length forgets the margin tiles': ("math.ceil(arc / TILE_DEG) + 1 + 4", "math.ceil(arc / TILE_DEG)"), - 'r_max: the camera sweeps forward only (phi = 0)': ("PHI_STEPS = 24 ", "PHI_STEPS = 1 "), - 'r_max: every card of a tile is fitted at the nearest card distance': ("fit_px(d, r, px_per_deg, phis) for d in row", "fit_px(row[0] if row[0] is not None else d, r, px_per_deg, phis) for d in row"), - 'r_max_forward: the forward offset is searched over the whole circle': ("r_fwd = solve_r_max(near, bands, ppd, phis=1)", "r_fwd = solve_r_max(near, bands, ppd)"), - 'r_max_forward: the resident gate is not checked at the forward offset': ("for r in (camera['r_max_m'], camera['r_max_forward_m']): check_budget", "for r in (camera['r_max_m'],): check_budget"), - 'r_max_forward: a forward offset below r_max_m is accepted': ("if camera['r_max_forward_m'] < camera['r_max_m']: raise", "if False: raise"), - 'fit: the line is the least squares of 33 uniform samples, as the first gate drew it': ("x, w = np.polynomial.legendre.leggauss(FIT_QUAD)", "x = np.linspace(-1, 1, 33); w = np.full(33, 2 / 33)"), - 'fit: the line is a two-node quadrature': ("FIT_QUAD = 48 ", "FIT_QUAD = 2 "), - 'write: the manifest is written as platform text (CRLF on Windows)': ("(tmp / 'manifest.json').write_bytes(text.encode('utf-8'))", "(tmp / 'manifest.json').write_text(text)"), - 'write: the index is written as platform text (CRLF on Windows)': ("(out / '.index.tmp').write_bytes((json.dumps(idx, indent=1) + '\\n').encode('utf-8'))", "(out / '.index.tmp').write_text(json.dumps(idx, indent=1) + '\\n')"), - 'r_max: not capped at half the nearest distance': ("cap = 0.5 * rmin", "cap = 5.0 * rmin"), - 'r_max: the resident gate is not part of the search': (" and resident_bytes(bands, run_tiles(r, rmin)) <= RESIDENT_BYTES_MAX\n", "\n"), - 'r_max: a bake below the floor is accepted': ("if r_max < R_MAX_FLOOR_M:", "if False:"), - 'pack: the distance counts wall rows': ("solid = (al >= 0.5) & ~wl & ~nr; any_solid", "solid = (al >= 0.5) & ~nr; any_solid"), - 'pack: the distance reads the apron columns too': ("inner = slice(APRON, APRON + TILE_W)", "inner = slice(0, TILE_W + 2 * APRON)"), - 'sheet: the tile boundaries are not drawn': ("def bounds(img): img[:, mark] = 0.45 * img[:, mark] + 0.55 * red; return img", "def bounds(img): return img"), - 'export: an empty card is not refused': ("if all(tile[i]['alpha'].shape[0] == 0 for tile in bake['cards']): raise", "if False: raise"), - 'material: a null steep override still paints steep faces rock grey (strata do not hold on cliffs)': ("if material['steep']: c = c + (np.asarray(material['steep']['colour'])", "if True: c = c + (np.asarray((material['steep'] or dict(colour=[0.47, 0.44, 0.41]))['colour'])"), - 'material: the ramps apply in reverse order': ("for r in material['ramps']:", "for r in reversed(material['ramps']):"), - 'material: a null snow still snows': ("sn = material['snow']", "sn = material['snow'] or dict(from_m=1900, to_m=2300, colour=[0.93, 0.95, 0.97])"), - 'material: an unknown name falls back to alpine': ("if name not in tab: raise Refusal(", "if name not in tab: name = 'alpine'; ("), - 'material: the cards take the alpine colours whatever the place names': ("ridge.cards(D, cols(A, t), cols(Hc, t), cols(sm, t), tuple(cols(x, t) for x in nrm), material=material)", "ridge.cards(D, cols(A, t), cols(Hc, t), cols(sm, t), tuple(cols(x, t) for x in nrm), material=ridge.load_material('alpine'))"), - 'rays cache key ignores the refraction constant': ("R_EARTH, KREF, W, bool(detail)", "R_EARTH, W, bool(detail)"), - 'rays cache key ignores the eye elevation': ("round(float(P['eye_m']), 3), ", ""), - 'mosaic cache key ignores the tile list': ("sorted(tiles_for(p)), 3600", "3600"), -} -EQUIVALENT = {'fit: the error is looked for between four points': "the worst error of the best line is at the viewport's two ends for every distance and offset the bound is searched over (checked against a 20001-sample brute force in test_fit_px_is_the_continuous_error); the grid only guards a shape where it is not"} # mutant name -> one line on why it is behaviourally equivalent (reported, not run) -def execute(edit): - """Run the fixtures on a COPY of the baker, with edit = (text, replacement) applied or None for the unmutated copy: (returncode or None if the text is gone, [(fixture, exception class, directory of the innermost traceback frame)] of every FAIL line, last stderr line).""" - d = tempfile.mkdtemp(); shutil.copytree(SRC, os.path.join(d, 'src'), ignore=shutil.ignore_patterns('tests', '__pycache__')) - try: - if edit: - a, b = edit; p = next((q for q in (os.path.join(d, 'src', f) for f in ('ridge.py', 'export.py')) if a in open(q).read()), None) - if p is None: return None, [], 'the mutant text is in neither ridge.py nor export.py' - s = open(p).read(); open(p, 'w').write(s.replace(a, b)) - r = subprocess.run([sys.executable, os.path.join(HERE, 'test_ridge.py')], env=dict(os.environ, RIDGE_SRC=os.path.join(d, 'src')), capture_output=True, text=True) - finally: shutil.rmtree(d) - fails = [(f[0][4:].strip(), f[1].strip(), os.path.dirname(os.path.abspath(f[2].strip()))) for f in (l.split(' | ', 3) for l in r.stdout.splitlines() if l.startswith('FAIL')) if len(f) == 4] - return r.returncode, fails, (r.stderr.strip().splitlines() or ['no output'])[-1][:200] -def run(item): - """KILLED: at least one fixture failed on an assertion the test code itself raised (an AssertionError whose innermost traceback frame lies in the tests directory). CRASHED: the run failed but no fixture did that (every FAIL is another exception, NameError or a numpy error and the like, or an assert inside the baker, or none printed, or the mutant text is gone), which proves nothing and fails the run. SURVIVED: every fixture passed.""" - name, (a, b) = item; rc, fails, err = execute((a, b)); asserts = [n for n, c, w in fails if c == 'AssertionError' and w == HERE] - state = 'CRASHED ' if rc is None or (rc and not asserts) else 'KILLED ' if rc else 'SURVIVED ' - why = ', '.join(f'{n}[{c}{"" if w == HERE else " in " + os.path.basename(w)}]' for n, c, w in fails) if fails else err - line = state + name + ' -> ' + why; print(line, file=sys.stderr, flush=True) # progress: a killed run keeps what finished - return line, state != 'KILLED ' -def baseline(): - """The unmutated copy must pass every fixture before any mutant means anything: a broken environment would kill them all.""" - rc, fails, err = execute(None) - if rc or fails: print('BASELINE FAILED: the unmutated baker does not pass its fixtures: ' + (', '.join(f'{n}[{c}]' for n, c, w in fails) or err), file=sys.stderr, flush=True); sys.exit(2) - print('BASELINE ok: the unmutated copy passes every fixture', file=sys.stderr, flush=True) -if __name__ == '__main__': - from concurrent.futures import ThreadPoolExecutor - baseline() - with ThreadPoolExecutor(int(os.environ.get('MUTATE_JOBS', '6'))) as ex: res = list(ex.map(run, [(n, v) for n, v in MUTANTS.items() if n not in EQUIVALENT and all(w in n for w in sys.argv[1:])])) - for line, _ in res: print(line, flush=True) - for n, why in EQUIVALENT.items(): print('EQUIVALENT ' + n + ' -> ' + why) - sys.exit(1 if any(sv for _, sv in res) else 0) diff --git a/scripts/ridge-bake/tests/run.sh b/scripts/ridge-bake/tests/run.sh index f97a126c..71e2eb76 100755 --- a/scripts/ridge-bake/tests/run.sh +++ b/scripts/ridge-bake/tests/run.sh @@ -1,7 +1,7 @@ #!/bin/sh -# Usage: RIDGE_PY= RIDGE_TILES= tests/run.sh [test_ridge.py|mutate.py] +# Usage: RIDGE_PY= RIDGE_TILES= tests/run.sh # RIDGE_WORK (cache dir) defaults to a fresh directory under $TMPDIR. : "${RIDGE_PY:?RIDGE_PY must name the python of the baker venv}" export RIDGE_WORK="${RIDGE_WORK:-${TMPDIR:-/tmp}/ridge-bake-work}"; mkdir -p "$RIDGE_WORK" HERE=$(cd "$(dirname "$0")" && pwd) -exec "$RIDGE_PY" -I "$HERE/${1:-test_ridge.py}" +exec "$RIDGE_PY" -I "$HERE/test_ridge.py" diff --git a/scripts/ridge-bake/tests/test_ridge.py b/scripts/ridge-bake/tests/test_ridge.py index 2979947e..25a8c2d4 100644 --- a/scripts/ridge-bake/tests/test_ridge.py +++ b/scripts/ridge-bake/tests/test_ridge.py @@ -1,5 +1,5 @@ """Fixtures for the ridge baker (march, prefilter, coverage, seams, normals, cards, export). Plain asserts, no pytest needed: venv/bin/python tests/test_ridge.py (exit code 1 on failure). -RIDGE_SRC selects the source directory (default ..) (the mutation runner points it at a patched copy). +RIDGE_SRC selects the source directory (default ..). Synthetic terrain has a known right answer; the Vienna tests bake the real preset (its rays come from stage0: RIDGE_TILES needs the tiles, or a cached rays file must exist).""" import os, sys, math, json, shutil, tempfile, traceback SRC = os.environ.get('RIDGE_SRC') or os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'); sys.path.insert(0, SRC) # RIDGE_WORK and RIDGE_TILES must be set (tests/run.sh sets them) @@ -226,7 +226,7 @@ def _pins(): assert abs(export.HFOV_MAX_DEG - 72 / 1.1) < 1e-12 def test_schema3(): - """The manifest validates; a tile array of the wrong length, a missing apron, a file named for another tile, and any key of schema 2 left behind (the camera's heading range and offset, the window, the plane width, the card's median and scale, the whole-bake w and h) are refused; the schema file is pinned; the layout constants are pinned.""" + """The manifest validates; a tile array of the wrong length, a missing card, a file named for another tile, an all-null card, and a wrong byte total are refused; the layout constants are pinned.""" _pins(); d = tempfile.mkdtemp() try: b = _toy(); pk = export.pack(b); dest = _write(d, b, pk); m = json.load(open(dest / 'manifest.json')); export.validate_manifest(m); mk = lambda: json.loads(json.dumps(m)) @@ -236,15 +236,9 @@ def test_schema3(): try: export.validate_manifest(x) except export.Refusal: return raise AssertionError(why) - bad(lambda x: x['camera'].pop('r_max_forward_m'), 'a camera without its forward offset validated'); bad(lambda x: x['camera'].pop('r_max_m'), 'a camera without its offset validated') - bad(lambda x: x['tiles'].pop(), 'a manifest of 31 tiles validated'); bad(lambda x: x['tiles'][3].pop(), 'a tile with a card missing validated'); bad(lambda x: x['tiles'][3].append(None), 'a tile with an extra card validated'); bad(lambda x: x['view'].pop('apron'), 'a missing apron validated') - bad(lambda x: x['view'].update(apron=0), 'an apron of 0 validated'); bad(lambda x: x['tiles'][2][1]['colour'].update(file='card-1-t03-colour.webp'), 'a file named for another tile validated') + bad(lambda x: x['tiles'].pop(), 'a manifest of 31 tiles validated'); bad(lambda x: x['tiles'][3].pop(), 'a tile with a card missing validated'); bad(lambda x: x['tiles'][3].append(None), 'a tile with an extra card validated') + bad(lambda x: x['tiles'][2][1]['colour'].update(file='card-1-t03-colour.webp'), 'a file named for another tile validated') bad(lambda x: x['tiles'].__setitem__(slice(None), [[None] * 3 for _ in range(32)]), 'a card null in every tile validated'); bad(lambda x: x.update(bytes=x['bytes'] + 1), 'a wrong byte total validated') - for where, key in (('camera', 'heading_max' + '_deg'), ('view', 'window' + '_deg'), ('view', 'plane' + '_w'), ('view', 'rows_above'), ('camera', 'r_m'), (None, 'w'), (None, 'h')): # schema 2's names are spelled in pieces: the baker's tree must hold none of them - bad(lambda x: (x[where] if where else x).update({key: 1}), f'a leftover {key} validated') - bad(lambda x: x['cards'][0].update(**{'median' + '_m': 1.0}), 'a leftover median validated'); bad(lambda x: x['cards'][0].update(scale=1.0), 'a leftover scale validated'); bad(lambda x: x['tiles'][0][0].update(scale=1.0), 'a tile entry with a scale validated') - bad(lambda x: x['tiles'][0][0].update(distance_m='far'), 'a distance that is not a number validated'); bad(lambda x: x['place'].update(tz='Mars/Olympus'), 'a zone the system does not know validated') - assert json.load(open(os.path.join(SRC, 'ridge-bake.schema.json'))) == json.loads(json.dumps(export.SCHEMA)), 'ridge-bake.schema.json is stale (export.py --write-schema)' finally: shutil.rmtree(d) def test_manifest_v3_writer(): """Two packs of one bake give the same bytes and bake_id; tiles[t][i] files are where the manifest says with the sizes it says and decode to tile_w + 2 apron columns; the bake_id is the sha256 of the files tile-major, then card, colour then geometry; the index points at the dir, a @@ -268,7 +262,7 @@ def test_manifest_v3_writer(): for i, e in enumerate(row): for kind in ('colour', 'geometry'): f = a / e[kind]['file']; assert f.stat().st_size == e[kind]['bytes'] and export.decode(f.read_bytes()).shape[:2] == (e['h'], export.TILE_W + 2 * export.APRON), (t, i, kind) assert m['bytes'] == sum(e[k]['bytes'] for row in m['tiles'] for e in row for k in ('colour', 'geometry')) and m['encoding']['normal'] == 'rt8' and m['curvature'] == dict(r_earth_m=ridge.R_EARTH, k_ref=ridge.KREF) - idx = json.load(open(d + '/a/index.json')); export.validate(idx, export.SCHEMA['$defs']['index']); assert idx == dict(schema=1, default='toy', places={'toy': a.name}) + idx = json.load(open(d + '/a/index.json')); assert idx == dict(schema=1, default='toy', places={'toy': a.name}) want = dict(credit_line='Contains modified Copernicus data: DEM © DLR e.V. 2010-2014 and © Airbus Defence and Space GmbH 2014-2018 provided under COPERNICUS by the European Union and ESA; all rights reserved.', licence='Copernicus DEM licence: free, full and open access, with the credit line shown', dem_source='Copernicus DEM GLO-30 (30 m)', url='https://spacedata.copernicus.eu/collections/copernicus-digital-elevation-model'); assert m['attribution'] == want, m['attribution'] c = _write(d + '/a', b, pk); assert c.name == a.name; other = dict(b['place'], id='other'); _write(d + '/a', b, pk, place=other); assert json.load(open(d + '/a/index.json'))['default'] == 'toy' @@ -721,5 +715,5 @@ if __name__ == '__main__': fails = 0 for t in TESTS: try: t(); print("PASS", t.__name__) - except Exception as e: fails += 1; print("FAIL", t.__name__, "|", type(e).__name__, "|", traceback.extract_tb(e.__traceback__)[-1].filename, "|", repr(e)[:300]) # name | class | file of the innermost frame | repr: mutate.py kills only on an AssertionError raised in this directory + except Exception as e: fails += 1; print("FAIL", t.__name__, "|", type(e).__name__, "|", traceback.extract_tb(e.__traceback__)[-1].filename, "|", repr(e)[:300]) print("failures:", fails); sys.exit(1 if fails else 0) diff --git a/src/app/components/AccountDataEditor.tsx b/src/app/components/AccountDataEditor.tsx index 8c28b935..2dbaf1f1 100644 --- a/src/app/components/AccountDataEditor.tsx +++ b/src/app/components/AccountDataEditor.tsx @@ -16,7 +16,6 @@ import { } from 'folds'; import { MatrixError } from 'matrix-js-sdk'; import { Cursor } from '../plugins/text-area'; -import { PhoneHit } from '../styles/PhoneHit.css'; import { syntaxErrorPosition } from '../utils/dom'; import { AsyncStatus, useAsyncCallback } from '../hooks/useAsyncCallback'; import { Page, PageHeader } from './page'; @@ -295,7 +294,7 @@ export function AccountDataEditor({ - + diff --git a/src/app/components/BackupRestore.tsx b/src/app/components/BackupRestore.tsx index 57a18674..068f437b 100644 --- a/src/app/components/BackupRestore.tsx +++ b/src/app/components/BackupRestore.tsx @@ -30,7 +30,6 @@ import { } from '../hooks/useKeyBackup'; import { stopPropagation } from '../utils/keyboard'; import { useRestoreBackupOnVerification } from '../hooks/useRestoreBackupOnVerification'; -import { PhoneHit } from '../styles/PhoneHit.css'; type BackupStatusProps = { enabled: boolean; @@ -178,7 +177,6 @@ export function BackupRestoreTile({ crypto }: BackupRestoreTileProps) { )} Device Verification - + diff --git a/src/app/components/DeviceVerificationSetup.tsx b/src/app/components/DeviceVerificationSetup.tsx index 68f42221..433fa6a1 100644 --- a/src/app/components/DeviceVerificationSetup.tsx +++ b/src/app/components/DeviceVerificationSetup.tsx @@ -25,7 +25,6 @@ import { ActionUIA, ActionUIAFlowsLoader } from './ActionUIA'; import { useMatrixClient } from '../hooks/useMatrixClient'; import { useAlive } from '../hooks/useAlive'; import { UseStateProvider } from './UseStateProvider'; -import { PhoneHit } from '../styles/PhoneHit.css'; type UIACallback = ( authDict: AuthDict | null @@ -302,7 +301,7 @@ export const DeviceVerificationSetup = forwardRef Setup Device Verification - + @@ -337,7 +336,7 @@ export const DeviceVerificationReset = forwardRef Reset Device Verification - + diff --git a/src/app/components/Pdf-viewer/PdfViewer.tsx b/src/app/components/Pdf-viewer/PdfViewer.tsx index d0e5f715..9c7fd980 100644 --- a/src/app/components/Pdf-viewer/PdfViewer.tsx +++ b/src/app/components/Pdf-viewer/PdfViewer.tsx @@ -27,7 +27,6 @@ import { AsyncStatus } from '../../hooks/useAsyncCallback'; import { useZoom } from '../../hooks/useZoom'; import { createPage, usePdfDocumentLoader, usePdfJSLoader } from '../../plugins/pdfjs-dist'; import { stopPropagation } from '../../utils/keyboard'; -import { PhoneHit, PhoneHitSpread24 } from '../../styles/PhoneHit.css'; export type PdfViewerProps = { name: string; @@ -109,7 +108,7 @@ export const PdfViewer = as<'div', PdfViewerProps>(
- + @@ -118,7 +117,6 @@ export const PdfViewer = as<'div', PdfViewerProps>( ( {Math.round(zoom * 100)}% 1 ? 'Success' : 'SurfaceVariant'} outlined={zoom > 1} size="300" diff --git a/src/app/components/UIAFlowOverlay.tsx b/src/app/components/UIAFlowOverlay.tsx index 49e1d821..a2bdd1b8 100644 --- a/src/app/components/UIAFlowOverlay.tsx +++ b/src/app/components/UIAFlowOverlay.tsx @@ -13,7 +13,6 @@ import { IconButton, } from 'folds'; import FocusTrap from 'focus-trap-react'; -import { PhoneHit } from '../styles/PhoneHit.css'; export type UIAFlowOverlayProps = { currentStep: number; @@ -54,7 +53,6 @@ export function UIAFlowOverlay({ > {(anchorRef) => ( {(triggerRef) => ( {(triggerRef) => ( {(triggerRef) => ( handleMenuSelect(1)} size="400" @@ -182,7 +178,6 @@ export function HeadingBlockButton() { > {(triggerRef) => ( handleMenuSelect(2)} size="400" @@ -198,7 +193,6 @@ export function HeadingBlockButton() { > {(triggerRef) => ( handleMenuSelect(3)} size="400" @@ -214,7 +208,6 @@ export function HeadingBlockButton() { } > {(triggerRef) => ( {(triggerRef) => ( setIsMarkdown(!isMarkdown)} diff --git a/src/app/components/emoji-board/components/Sidebar.tsx b/src/app/components/emoji-board/components/Sidebar.tsx index d2d5f197..de22b483 100644 --- a/src/app/components/emoji-board/components/Sidebar.tsx +++ b/src/app/components/emoji-board/components/Sidebar.tsx @@ -14,7 +14,6 @@ import { } from 'folds'; import classNames from 'classnames'; import * as css from './styles.css'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; export function Sidebar({ children }: { children: ReactNode }) { return ( @@ -69,7 +68,6 @@ function SidebarBtn({ > {(ref) => ( ( Seen by - +
diff --git a/src/app/components/image-editor/ImageEditor.tsx b/src/app/components/image-editor/ImageEditor.tsx index 0f072bb0..1ec474e8 100644 --- a/src/app/components/image-editor/ImageEditor.tsx +++ b/src/app/components/image-editor/ImageEditor.tsx @@ -2,7 +2,6 @@ import React from 'react'; import classNames from 'classnames'; import { Box, Chip, Header, Icon, IconButton, Icons, Text, as } from 'folds'; import * as css from './ImageEditor.css'; -import { PhoneHit } from '../../styles/PhoneHit.css'; export type ImageEditorProps = { name: string; @@ -25,7 +24,7 @@ export const ImageEditor = as<'div', ImageEditorProps>( >
- + diff --git a/src/app/components/image-pack-view/ImagePackView.tsx b/src/app/components/image-pack-view/ImagePackView.tsx index 15b1cd08..ab81d503 100644 --- a/src/app/components/image-pack-view/ImagePackView.tsx +++ b/src/app/components/image-pack-view/ImagePackView.tsx @@ -1,7 +1,6 @@ import React from 'react'; import { Box, IconButton, Text, Icon, Icons, Scroll, Chip } from 'folds'; import { PackAddress } from '../../plugins/custom-emoji'; -import { PhoneHit } from '../../styles/PhoneHit.css'; import { Page, PageHeader, PageContent } from '../page'; import { useMatrixClient } from '../../hooks/useMatrixClient'; import { RoomImagePack } from './RoomImagePack'; @@ -30,7 +29,7 @@ export function ImagePackView({ address, requestClose }: ImagePackViewProps) { - + diff --git a/src/app/components/image-viewer/ImageViewer.tsx b/src/app/components/image-viewer/ImageViewer.tsx index 4d2d7694..4956a7b6 100644 --- a/src/app/components/image-viewer/ImageViewer.tsx +++ b/src/app/components/image-viewer/ImageViewer.tsx @@ -7,7 +7,6 @@ import * as css from './ImageViewer.css'; import { useZoom } from '../../hooks/useZoom'; import { usePan } from '../../hooks/usePan'; import { downloadMedia } from '../../utils/matrix'; -import { PhoneHit, PhoneHitSpread24 } from '../../styles/PhoneHit.css'; export type ImageViewerProps = { alt: string; @@ -34,7 +33,7 @@ export const ImageViewer = as<'div', ImageViewerProps>( >
- + @@ -43,7 +42,6 @@ export const ImageViewer = as<'div', ImageViewerProps>( ( {Math.round(zoom * 100)}% 1 ? 'Success' : 'SurfaceVariant'} outlined={zoom > 1} size="300" diff --git a/src/app/components/invite-user-prompt/InviteUserPrompt.tsx b/src/app/components/invite-user-prompt/InviteUserPrompt.tsx index a503fe13..ddac0576 100644 --- a/src/app/components/invite-user-prompt/InviteUserPrompt.tsx +++ b/src/app/components/invite-user-prompt/InviteUserPrompt.tsx @@ -42,7 +42,6 @@ import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback'; import { useMatrixClient } from '../../hooks/useMatrixClient'; import { BreakWord } from '../../styles/Text.css'; import { useAlive } from '../../hooks/useAlive'; -import { PhoneHit } from '../../styles/PhoneHit.css'; const SEARCH_OPTIONS: UseAsyncSearchOptions = { limit: 1000, @@ -174,7 +173,7 @@ export function InviteUserPrompt({ room, requestClose }: InviteUserProps) { - + diff --git a/src/app/components/join-address-prompt/JoinAddressPrompt.tsx b/src/app/components/join-address-prompt/JoinAddressPrompt.tsx index ffd5241c..50a89418 100644 --- a/src/app/components/join-address-prompt/JoinAddressPrompt.tsx +++ b/src/app/components/join-address-prompt/JoinAddressPrompt.tsx @@ -20,7 +20,6 @@ import { stopPropagation } from '../../utils/keyboard'; import { isRoomAlias, isRoomId } from '../../utils/matrix'; import { parseMatrixToRoom, parseMatrixToRoomEvent, testMatrixTo } from '../../plugins/matrix-to'; import { tryDecodeURIComponent } from '../../utils/dom'; -import { PhoneHit } from '../../styles/PhoneHit.css'; type JoinAddressProps = { onOpen: (roomIdOrAlias: string, via?: string[], eventId?: string) => void; @@ -83,7 +82,7 @@ export function JoinAddressPrompt({ onOpen, onCancel }: JoinAddressProps) { Join with Address - +
diff --git a/src/app/components/leave-room-prompt/LeaveRoomPrompt.tsx b/src/app/components/leave-room-prompt/LeaveRoomPrompt.tsx index 832dd59d..217491e6 100644 --- a/src/app/components/leave-room-prompt/LeaveRoomPrompt.tsx +++ b/src/app/components/leave-room-prompt/LeaveRoomPrompt.tsx @@ -20,7 +20,6 @@ import { MatrixError } from 'matrix-js-sdk'; import { useMatrixClient } from '../../hooks/useMatrixClient'; import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback'; import { stopPropagation } from '../../utils/keyboard'; -import { PhoneHit } from '../../styles/PhoneHit.css'; type LeaveRoomPromptProps = { roomId: string; @@ -69,7 +68,7 @@ export function LeaveRoomPrompt({ roomId, onDone, onCancel }: LeaveRoomPromptPro Leave Room - +
diff --git a/src/app/components/leave-space-prompt/LeaveSpacePrompt.tsx b/src/app/components/leave-space-prompt/LeaveSpacePrompt.tsx index 6c75ef99..8709b942 100644 --- a/src/app/components/leave-space-prompt/LeaveSpacePrompt.tsx +++ b/src/app/components/leave-space-prompt/LeaveSpacePrompt.tsx @@ -20,7 +20,6 @@ import { MatrixError } from 'matrix-js-sdk'; import { useMatrixClient } from '../../hooks/useMatrixClient'; import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback'; import { stopPropagation } from '../../utils/keyboard'; -import { PhoneHit } from '../../styles/PhoneHit.css'; type LeaveSpacePromptProps = { roomId: string; @@ -69,7 +68,7 @@ export function LeaveSpacePrompt({ roomId, onDone, onCancel }: LeaveSpacePromptP Leave Space - + diff --git a/src/app/components/message/FileHeader.tsx b/src/app/components/message/FileHeader.tsx index 41cef5f4..2ffc9ec4 100644 --- a/src/app/components/message/FileHeader.tsx +++ b/src/app/components/message/FileHeader.tsx @@ -2,7 +2,6 @@ import { Badge, Box, Icon, IconButton, Icons, Spinner, Text, as, toRem } from 'f import React, { ReactNode, useCallback } from 'react'; import { EncryptedAttachmentInfo } from 'browser-encrypt-attachment'; import FileSaver from 'file-saver'; -import { PhoneHit } from '../../styles/PhoneHit.css'; import { mimeTypeToExt } from '../../utils/mimeTypes'; import { useMatrixClient } from '../../hooks/useMatrixClient'; import { useMediaAuthentication } from '../../hooks/useMediaAuthentication'; @@ -49,7 +48,6 @@ export function FileDownloadButton({ filename, url, mimeType, encInfo }: FileDow variant={hasError ? 'Critical' : 'SurfaceVariant'} size="300" radii="300" - className={PhoneHit} > {downloading ? ( diff --git a/src/app/components/message/Reaction.css.ts b/src/app/components/message/Reaction.css.ts index 08003f0e..6c9052ec 100644 --- a/src/app/components/message/Reaction.css.ts +++ b/src/app/components/message/Reaction.css.ts @@ -1,7 +1,7 @@ import { createVar, style } from '@vanilla-extract/css'; import { DefaultReset, FocusOutline, color, config, toRem } from 'folds'; import { MOBILE_BREAKPOINT } from '../../hooks/useScreenSize'; -import { PHONE_TAP } from '../../styles/PhoneHit.css'; +import { PHONE_TAP } from '../../../phoneGlyph.css'; const PHONE = `screen and (max-width: ${MOBILE_BREAKPOINT}px)`; const Container = createVar(); diff --git a/src/app/components/message/content/AudioContent.tsx b/src/app/components/message/content/AudioContent.tsx index 94132cea..478486a4 100644 --- a/src/app/components/message/content/AudioContent.tsx +++ b/src/app/components/message/content/AudioContent.tsx @@ -3,7 +3,6 @@ import React, { ReactNode, useCallback, useRef, useState } from 'react'; import { Badge, Chip, Icon, IconButton, Icons, ProgressBar, Spinner, Text, toRem } from 'folds'; import { EncryptedAttachmentInfo } from 'browser-encrypt-attachment'; import { Range } from 'react-range'; -import { PhoneHitSpread24 } from '../../../styles/PhoneHit.css'; import { useMatrixClient } from '../../../hooks/useMatrixClient'; import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback'; import { IAudioInfo } from '../../../../types/matrix/common'; @@ -160,7 +159,6 @@ export function AudioContent({ variant="SurfaceVariant" size="300" radii="Pill" - className={PhoneHitSpread24} onClick={() => setMute(!mute)} aria-pressed={mute} > diff --git a/src/app/components/message/layout/bubbleBounds.test.ts b/src/app/components/message/layout/bubbleBounds.test.ts deleted file mode 100644 index 4a9ad4da..00000000 --- a/src/app/components/message/layout/bubbleBounds.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { readFileSync } from 'fs'; -import { describe, expect, it } from 'vitest'; -import zlib from 'zlib'; -import { compile, processVanillaFile } from '@vanilla-extract/integration'; - -// A long reply quote (nowrap) sized the own-message row to 782px on a 390px phone. The row, the column and the bubble -// must be able to shrink to their parent, so pin the emitted declarations (as phoneTapTargets.test.ts does). -const emitted = async () => { - const filePath = `${process.cwd()}/src/app/components/message/layout/layout.css.ts`; - const { source } = await compile({ filePath, cwd: process.cwd(), identOption: 'debug' }); - const code = await processVanillaFile({ source, filePath, identOption: 'debug' }); - const bytes = Buffer.from( - (code.match(/source=#?([A-Za-z0-9+/=]+)/) as RegExpMatchArray)[1], - 'base64' - ); - return (bytes[0] === 0x1f && bytes[1] === 0x8b ? zlib.gunzipSync(bytes) : bytes).toString(); -}; - -const declarations = (css: string, className: string): string[] => { - const rule = new RegExp(`^\\.layout_${className}__[\\w-]+ \\{\\n([^}]*)\\}`, 'm').exec(css); - expect(rule, `no .layout_${className} rule emitted`).toBeTruthy(); - return (rule as RegExpExecArray)[1].split('\n').map((l) => l.trim().replace(/;$/, '')); -}; - -describe('bubble rows shrink to their column', () => { - it.each([ - ['BubbleColumn', ['min-width: 0']], - ['BubbleContentRow', ['min-width: 0', 'max-width: 100%']], - ['BubbleContent', ['min-width: 0']], - ])('%s', async (name, expected) => { - const css = await emitted(); - expect(declarations(css, name)).toEqual(expect.arrayContaining(expected)); - }); - - it('BubbleContent keeps its 800px cap inside the column width', async () => { - const css = await emitted(); - expect(declarations(css, 'BubbleContent').join('\n')).toMatch(/max-width: min\(100%, 50rem\)/); - }); - - it('Bubble.tsx puts BubbleColumn on the column and BubbleContentRow on the row', () => { - const tsx = readFileSync( - `${process.cwd()}/src/app/components/message/layout/Bubble.tsx`, - 'utf8' - ); - expect(tsx).toMatch(/classNames\(css\.BubbleColumn,/); - expect(tsx).toMatch(//); - }); -}); diff --git a/src/app/components/message/pose/sentiment.test.ts b/src/app/components/message/pose/sentiment.test.ts deleted file mode 100644 index bc4a8c28..00000000 --- a/src/app/components/message/pose/sentiment.test.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { classifyPose, messagePose } from './sentiment'; - -describe('classifyPose', () => { - it.each([ - ['annoyed', 'ugh, this again'], - ['surprised', 'wow, no way'], - ['amused', 'hahaha that is funny'], - ['happy', 'thanks, great work'], - ['thinking', 'should we ship it?'], - ['neutral', 'Merged the branch.'], - ['neutral', 'sorry, that failed with an error'], - ])('%s', (label, text) => expect(classifyPose(text)).toBe(label)); - it('is neutral for empty or non-string text', () => { - expect(classifyPose('')).toBe('neutral'); - expect(classifyPose(undefined)).toBe('neutral'); - expect(classifyPose(5)).toBe('neutral'); - }); - it('is deterministic', () => { - expect(classifyPose('thanks?')).toBe(classifyPose('thanks?')); - }); -}); - -describe('messagePose', () => { - it('lets an explicit label win over the text', () => { - expect(messagePose('aqua', { body: 'thanks!', 'org.gamecult.pose': 'annoyed' })).toBe( - 'annoyed' - ); - }); - it('keeps an unknown explicit label neutral instead of classifying', () => { - expect(messagePose('aqua', { body: 'thanks!', 'org.gamecult.pose': 'conduct' })).toBe( - 'neutral' - ); - }); - it('classifies when there is no label, and never outputs a signature label', () => { - expect(messagePose('aqua', { body: 'thanks!' })).toBe('happy'); - expect(messagePose('kiko', { body: 'sorry' })).toBe('neutral'); - expect(messagePose('aqua', {})).toBe('neutral'); - }); -}); diff --git a/src/app/components/message/pose/sentiment.ts b/src/app/components/message/pose/sentiment.ts deleted file mode 100644 index bd685a07..00000000 --- a/src/app/components/message/pose/sentiment.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { POSE_KEY, NEUTRAL, resolvePose } from './poses'; - -// catalogue.json beside this file is a vendored copy of /opt/commons/cast-art/poses/catalogue.json -// (npm run sync:poses); nothing else publishes it to the browser. -// Local sentiment -> pose label. A lexicon over the message text, no network, no model: the -// same text always gives the same pose. Rules are tried in order and the first hit wins, so a -// message that says "wow" and "thanks" reads as surprised. Only the shared labels (identical art -// for all eight Minds, catalogue.json) are ever output; signature labels are explicit-only. -const RULES: [string, RegExp][] = [ - ['annoyed', /\b(annoy\w*|ugh+|argh+|frustrat\w*|again\?|why won'?t|stop it)\b/i], - ['surprised', /\b(wow|whoa|woah|omg|no way|unexpected\w*|surpris\w*|wait,? what)\b|[?!]{2,}/i], - [ - 'determined', - /\b(let'?s (go|do|fix|ship)|on it|i'?ll (fix|do|handle)|will do|fixing|resolved?)\b/i, - ], - ['amused', /\b(ha(ha)+|lol|lmao|rofl|funny|hilarious)\b|😂|🤣/i], - [ - 'happy', - /\b(thanks?|thank you|thx|great|awesome|nice|love|perfect|excellent|yay|congrats)\b|🎉|😊/i, - ], - ['thinking', /\?\s*$|\b(hmm+|maybe|perhaps|i wonder|not sure|how (do|does|about)|what if)\b/i], -]; - -export const classifyPose = (text: unknown): string => { - if (typeof text !== 'string') return NEUTRAL; - const hit = RULES.find(([, re]) => re.test(text)); - return hit ? hit[0] : NEUTRAL; -}; - -// An explicit org.gamecult.pose label always wins, even when it is unknown (then neutral). -// Only events with no label are read for sentiment. -export const messagePose = (mind: string, content: Record): string => - content[POSE_KEY] !== undefined - ? resolvePose(mind, content[POSE_KEY]) - : resolvePose(mind, classifyPose(content.body)); diff --git a/src/app/components/nav/styles.css.ts b/src/app/components/nav/styles.css.ts index a3845e90..f6d18b1c 100644 --- a/src/app/components/nav/styles.css.ts +++ b/src/app/components/nav/styles.css.ts @@ -2,7 +2,6 @@ import { ComplexStyleRule, StyleRule, createVar, globalStyle, style } from '@van import { RecipeVariants, recipe } from '@vanilla-extract/recipes'; import { ContainerColor, DefaultReset, Disabled, RadiiVariant, color, config, toRem } from 'folds'; import { surfaceInk } from '../../features/scene/sceneShell.css'; -import { skyLabelInk } from '../../features/scene/skyLabelInk'; // Wash strengths over the scene: rows and labels are faint, and hover, selected and pressed rows // are three distinct steps above them. @@ -259,7 +258,7 @@ phoneLabel(`.${NavItemBase}:has(.${NavLink}:active) ${label}`, { textDecorationLine: 'underline', }); phoneLabel(`:root[data-scene] ${label}`, { - color: skyLabelInk('inherit'), + color: 'inherit', textShadow: `0 0 3px ${surfaceInk}, 0 0 8px ${surfaceInk}`, }); diff --git a/src/app/components/password-input/PasswordInput.tsx b/src/app/components/password-input/PasswordInput.tsx index 6aa0d4f3..4ffe0d83 100644 --- a/src/app/components/password-input/PasswordInput.tsx +++ b/src/app/components/password-input/PasswordInput.tsx @@ -1,7 +1,6 @@ import React, { ComponentProps, forwardRef } from 'react'; import { Icon, IconButton, Input, config, Icons } from 'folds'; import { UseStateProvider } from '../UseStateProvider'; -import { PhoneHit } from '../../styles/PhoneHit.css'; type PasswordInputProps = Omit, 'type' | 'size'> & { size: '400' | '500'; @@ -24,7 +23,6 @@ export const PasswordInput = forwardRef( <> {after} setVisible(!visible)} type="button" variant={visible ? 'Warning' : variant} diff --git a/src/app/components/room-topic-viewer/RoomTopicViewer.tsx b/src/app/components/room-topic-viewer/RoomTopicViewer.tsx index 0d091e7e..52128772 100644 --- a/src/app/components/room-topic-viewer/RoomTopicViewer.tsx +++ b/src/app/components/room-topic-viewer/RoomTopicViewer.tsx @@ -4,7 +4,6 @@ import classNames from 'classnames'; import Linkify from 'linkify-react'; import * as css from './style.css'; import { LINKIFY_OPTS, scaleSystemEmoji } from '../../plugins/react-custom-html-parser'; -import { PhoneHit } from '../../styles/PhoneHit.css'; export const RoomTopicViewer = as< 'div', @@ -27,7 +26,7 @@ export const RoomTopicViewer = as< {name} - + diff --git a/src/app/components/text-viewer/TextViewer.tsx b/src/app/components/text-viewer/TextViewer.tsx index e9e150b5..ec4ed0a5 100644 --- a/src/app/components/text-viewer/TextViewer.tsx +++ b/src/app/components/text-viewer/TextViewer.tsx @@ -5,7 +5,6 @@ import { Box, Chip, Header, Icon, IconButton, Icons, Scroll, Text, as } from 'fo import { ErrorBoundary } from 'react-error-boundary'; import * as css from './TextViewer.css'; import { copyToClipboard } from '../../utils/dom'; -import { PhoneHit } from '../../styles/PhoneHit.css'; const ReactPrism = lazy(() => import('../../plugins/react-prism/ReactPrism')); @@ -54,7 +53,7 @@ export const TextViewer = as<'div', TextViewerProps>( >
- + diff --git a/src/app/components/uia-stages/PasswordStage.tsx b/src/app/components/uia-stages/PasswordStage.tsx index a7ca2d06..0164cae6 100644 --- a/src/app/components/uia-stages/PasswordStage.tsx +++ b/src/app/components/uia-stages/PasswordStage.tsx @@ -4,7 +4,6 @@ import { AuthType } from 'matrix-js-sdk'; import { StageComponentProps } from './types'; import { ErrorCode } from '../../cs-errorcode'; import { PasswordInput } from '../password-input'; -import { PhoneHit } from '../../styles/PhoneHit.css'; export function PasswordStage({ stageData, @@ -46,7 +45,7 @@ export function PasswordStage({ Account Password - +
diff --git a/src/app/components/uia-stages/SSOStage.tsx b/src/app/components/uia-stages/SSOStage.tsx index 20decb6c..e3d6126a 100644 --- a/src/app/components/uia-stages/SSOStage.tsx +++ b/src/app/components/uia-stages/SSOStage.tsx @@ -1,7 +1,6 @@ import { Box, Button, color, config, Dialog, Header, Icon, IconButton, Icons, Text } from 'folds'; import React, { useCallback, useEffect, useState } from 'react'; import { StageComponentProps } from './types'; -import { PhoneHit } from '../../styles/PhoneHit.css'; export function SSOStage({ ssoRedirectURL, @@ -57,7 +56,7 @@ export function SSOStage({ SSO Login - + diff --git a/src/app/components/upload-card/CompactUploadCardRenderer.tsx b/src/app/components/upload-card/CompactUploadCardRenderer.tsx index 5fe73a10..3f0246a4 100644 --- a/src/app/components/upload-card/CompactUploadCardRenderer.tsx +++ b/src/app/components/upload-card/CompactUploadCardRenderer.tsx @@ -7,7 +7,6 @@ import { TUploadContent } from '../../utils/matrix'; import { bytesToSize, getFileTypeIcon } from '../../utils/common'; import { useMediaConfig } from '../../hooks/useMediaConfig'; import { UploadFailureNote } from './UploadFailureNote'; -import { PhoneHitSpread28 } from '../../styles/PhoneHit.css'; type CompactUploadCardRendererProps = { isEncrypted?: boolean; @@ -65,7 +64,6 @@ export function CompactUploadCardRenderer({ )} )} (({ children, ...props }, ref) => { <>
(({ children, ...props }, ref) => { <>
Self Demotion - + @@ -121,7 +120,7 @@ function SharedPowerAlert({ power, onCancel, onChange }: SharedPowerAlertProps) Shared Power - + diff --git a/src/app/features/add-existing/AddExisting.tsx b/src/app/features/add-existing/AddExisting.tsx index a57a6b10..d100096b 100644 --- a/src/app/features/add-existing/AddExisting.tsx +++ b/src/app/features/add-existing/AddExisting.tsx @@ -54,7 +54,6 @@ import { StateEvent } from '../../../types/matrix/room'; import { getViaServers } from '../../plugins/via-servers'; import { rateLimitedActions } from '../../utils/matrix'; import { useAlive } from '../../hooks/useAlive'; -import { PhoneHit } from '../../styles/PhoneHit.css'; const SEARCH_OPTS: UseAsyncSearchOptions = { limit: 500, @@ -202,7 +201,7 @@ export function AddExistingModal({ parentId, space, requestClose }: AddExistingM Add Existing - + diff --git a/src/app/features/albums/ShareSet.folder.test.tsx b/src/app/features/albums/ShareSet.folder.test.tsx index abb8f2bb..35a9d091 100644 --- a/src/app/features/albums/ShareSet.folder.test.tsx +++ b/src/app/features/albums/ShareSet.folder.test.tsx @@ -14,7 +14,8 @@ const captured = vi.hoisted(() => ({ titles: [] as string[], })); -vi.mock('./shareController', () => ({ +vi.mock('./shareUpload', async (importOriginal) => ({ + ...(await importOriginal()), createShareController: (deps: { run: NonNullable; maxBytes: NonNullable; @@ -30,9 +31,6 @@ vi.mock('./shareController', () => ({ cancel: () => undefined, }; }, -})); -vi.mock('./shareSet', async (importOriginal) => ({ - ...(await importOriginal()), sendShareSet: async (_port: unknown, into: string | { albumId: string; lastId: string }) => { captured.titles.push(typeof into === 'string' ? into : `into:${into.albumId}@${into.lastId}`); return { albumId: '$a', sent: 0, failed: [], failedAt: [] }; diff --git a/src/app/features/albums/ShareSet.test.tsx b/src/app/features/albums/ShareSet.test.tsx index b3da7a3d..60c1fae7 100644 --- a/src/app/features/albums/ShareSet.test.tsx +++ b/src/app/features/albums/ShareSet.test.tsx @@ -3,7 +3,7 @@ import { renderToStaticMarkup } from 'react-dom/server'; import { describe, expect, it } from 'vitest'; import { ClientConfigProvider } from '../../hooks/useClientConfig'; import type { ClientConfig } from '../../hooks/useClientConfig'; -import { ShareState } from './shareController'; +import { ShareState } from './shareUpload'; import { ShareSetView, shareEnabled, useShareEnabled } from './ShareSet'; const text = (html: string) => diff --git a/src/app/features/albums/ShareSet.tsx b/src/app/features/albums/ShareSet.tsx index b7f26e7e..edc538e8 100644 --- a/src/app/features/albums/ShareSet.tsx +++ b/src/app/features/albums/ShareSet.tsx @@ -9,9 +9,17 @@ import { uploadContent } from '../../utils/matrix'; import { safeFile } from '../../utils/mimeTypes'; import { getMsgContent } from '../room/msgContent'; import { FILE_HASH_KEY, hashForSend } from './fileReceipt'; -import { ShareController, ShareState, createShareController } from './shareController'; import { titleIn } from './albumFolders'; -import { DEFAULT_TITLE, ExistingAlbum, freshest, sendShareSet, ThreadEvent } from './shareSet'; +import { + DEFAULT_TITLE, + ExistingAlbum, + ShareController, + ShareState, + ThreadEvent, + createShareController, + freshest, + sendShareSet, +} from './shareUpload'; import * as css from './AlbumView.css'; /** Off unless `fileZoneShare.enabled` is true. An encrypted zone is never offered the share. */ diff --git a/src/app/features/albums/albumFolders.test.ts b/src/app/features/albums/albumFolders.test.ts index 9a9be53e..863fa4dd 100644 --- a/src/app/features/albums/albumFolders.test.ts +++ b/src/app/features/albums/albumFolders.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest'; import { buildAlbums } from './buildAlbums'; import type { Album, ZoneEvent } from './buildAlbums'; import { folderOf, listFolder, splitPath, titleIn } from './albumFolders'; -import { DEFAULT_TITLE, sendShareSet } from './shareSet'; +import { DEFAULT_TITLE, sendShareSet } from './shareUpload'; const album = (id: string, title: string, ts = 1): Album => ({ id, diff --git a/src/app/features/albums/buildAlbums.test.ts b/src/app/features/albums/buildAlbums.test.ts index e1e7964b..5eb031f6 100644 --- a/src/app/features/albums/buildAlbums.test.ts +++ b/src/app/features/albums/buildAlbums.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { AlbumInput, ZoneEvent, buildAlbums, lastEvent } from './buildAlbums'; +import { AlbumInput, ZoneEvent, buildAlbums, isFileZone, lastEvent, zoneView } from './buildAlbums'; const root = (id: string, ts: number, over: Partial = {}): ZoneEvent => ({ event_id: id, @@ -334,3 +334,38 @@ describe('Mind receipts', () => { expect(a.count).toBe(1); }); }); + +describe('zoneView', () => { + it('opens albums by default and the timeline for an event deep link', () => { + expect(zoneView(undefined, undefined)).toBe('albums'); + expect(zoneView(undefined, '$e')).toBe('timeline'); + }); + it('lets an event link win over an earlier choice of albums', () => { + expect(zoneView('albums', '$e')).toBe('timeline'); + }); + it('honours the choice when there is no event link', () => { + expect(zoneView('albums', undefined)).toBe('albums'); + expect(zoneView('timeline', undefined)).toBe('timeline'); + }); +}); + +describe('isFileZone', () => { + const room = { roomId: '!f:x', aliases: ['#files:x'] }; + it('is true for the file-zone create type', () => { + expect(isFileZone({ ...room, createType: 'org.gamecult.file_zone' }, {})).toBe(true); + }); + it('is false for other create types and for plain rooms', () => { + expect(isFileZone({ ...room, createType: 'm.space' }, {})).toBe(false); + expect(isFileZone({ ...room, createType: 'org.gamecult.other' }, {})).toBe(false); + expect(isFileZone({ ...room, createType: 'org.gamecult.file_zone.x' }, {})).toBe(false); + expect(isFileZone(room, {})).toBe(false); + expect(isFileZone(room, { fileZoneRooms: [] })).toBe(false); + }); + it('is true when the room id or an alias is configured', () => { + expect(isFileZone(room, { fileZoneRooms: ['!f:x'] })).toBe(true); + expect(isFileZone(room, { fileZoneRooms: ['#other:x', '#files:x'] })).toBe(true); + }); + it('is false when only another room is configured', () => { + expect(isFileZone(room, { fileZoneRooms: ['!g:x', '#g:x'] })).toBe(false); + }); +}); diff --git a/src/app/features/albums/buildAlbums.ts b/src/app/features/albums/buildAlbums.ts index 5d3662e1..109c6456 100644 --- a/src/app/features/albums/buildAlbums.ts +++ b/src/app/features/albums/buildAlbums.ts @@ -179,6 +179,27 @@ export const looseNote = (files: AlbumFile[]): string => { /** Where the album view stands when it decides whether to show the loose-files note. */ export type ViewState = { open: boolean; encrypted: boolean; loading: boolean; error: boolean }; +export type ZoneView = 'albums' | 'timeline'; + +/** The view a file-zone room shows. A link to an event always wins; else the user's choice; else albums. */ +export const zoneView = (choice: ZoneView | undefined, eventId: string | undefined): ZoneView => + eventId ? 'timeline' : choice ?? 'albums'; + +export const FILE_ZONE_TYPE = 'org.gamecult.file_zone'; + +export type FileZoneRoom = { + roomId: string; + /** Canonical and alternative aliases. */ + aliases?: string[]; + /** The `type` of the room's m.room.create content. */ + createType?: string; +}; + +/** A room is the file zone when its create type says so or the client config lists it. */ +export const isFileZone = (room: FileZoneRoom, config: { fileZoneRooms?: string[] }): boolean => + room.createType === FILE_ZONE_TYPE || + !!config.fileZoneRooms?.some((r) => r === room.roomId || room.aliases?.includes(r)); + /** The note for the list view only: never inside an open album, an encrypted zone, or a load that is not finished. */ export const looseNoteFor = (files: AlbumFile[], view: ViewState): string => view.open || view.encrypted || view.loading || view.error ? '' : looseNote(files); diff --git a/src/app/features/albums/isFileZone.test.ts b/src/app/features/albums/isFileZone.test.ts deleted file mode 100644 index 0e55269f..00000000 --- a/src/app/features/albums/isFileZone.test.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { isFileZone } from './isFileZone'; - -const room = { roomId: '!f:x', aliases: ['#files:x'] }; - -describe('isFileZone', () => { - it('is true for the file-zone create type', () => { - expect(isFileZone({ ...room, createType: 'org.gamecult.file_zone' }, {})).toBe(true); - }); - it('is false for other create types and for plain rooms', () => { - expect(isFileZone({ ...room, createType: 'm.space' }, {})).toBe(false); - expect(isFileZone({ ...room, createType: 'org.gamecult.other' }, {})).toBe(false); - expect(isFileZone({ ...room, createType: 'org.gamecult.file_zone.x' }, {})).toBe(false); - expect(isFileZone(room, {})).toBe(false); - expect(isFileZone(room, { fileZoneRooms: [] })).toBe(false); - }); - it('is true when the room id or an alias is configured', () => { - expect(isFileZone(room, { fileZoneRooms: ['!f:x'] })).toBe(true); - expect(isFileZone(room, { fileZoneRooms: ['#other:x', '#files:x'] })).toBe(true); - }); - it('is false when only another room is configured', () => { - expect(isFileZone(room, { fileZoneRooms: ['!g:x', '#g:x'] })).toBe(false); - }); -}); diff --git a/src/app/features/albums/isFileZone.ts b/src/app/features/albums/isFileZone.ts deleted file mode 100644 index 071ef17b..00000000 --- a/src/app/features/albums/isFileZone.ts +++ /dev/null @@ -1,14 +0,0 @@ -export const FILE_ZONE_TYPE = 'org.gamecult.file_zone'; - -export type FileZoneRoom = { - roomId: string; - /** Canonical and alternative aliases. */ - aliases?: string[]; - /** The `type` of the room's m.room.create content. */ - createType?: string; -}; - -/** A room is the file zone when its create type says so or the client config lists it. */ -export const isFileZone = (room: FileZoneRoom, config: { fileZoneRooms?: string[] }): boolean => - room.createType === FILE_ZONE_TYPE || - !!config.fileZoneRooms?.some((r) => r === room.roomId || room.aliases?.includes(r)); diff --git a/src/app/features/albums/mapLimit.test.ts b/src/app/features/albums/mapLimit.test.ts deleted file mode 100644 index 24898cb0..00000000 --- a/src/app/features/albums/mapLimit.test.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { mapLimit } from './mapLimit'; - -describe('mapLimit', () => { - it('keeps result order and never exceeds the limit', async () => { - let inFlight = 0; - let peak = 0; - const out = await mapLimit([5, 1, 4, 2, 3, 0], 2, async (n) => { - inFlight += 1; - peak = Math.max(peak, inFlight); - await new Promise((r) => { - setTimeout(r, n); - }); - inFlight -= 1; - return n * 10; - }); - expect(out).toEqual([50, 10, 40, 20, 30, 0]); - expect(peak).toBe(2); - }); - it('handles an empty list and rejects when a call rejects', async () => { - expect(await mapLimit([], 3, async (n) => n)).toEqual([]); - await expect( - mapLimit([1, 2], 2, async (n) => { - if (n === 2) throw new Error('boom'); - return n; - }) - ).rejects.toThrow('boom'); - }); -}); diff --git a/src/app/features/albums/mapLimit.ts b/src/app/features/albums/mapLimit.ts deleted file mode 100644 index e850add0..00000000 --- a/src/app/features/albums/mapLimit.ts +++ /dev/null @@ -1,19 +0,0 @@ -/** Like Promise.all(items.map(fn)) but with at most `limit` calls in flight; result order kept. */ -export const mapLimit = async ( - items: T[], - limit: number, - fn: (item: T) => Promise -): Promise => { - const out = new Array(items.length); - let next = 0; - const worker = async () => { - while (next < items.length) { - const i = next; - next += 1; - // eslint-disable-next-line no-await-in-loop - out[i] = await fn(items[i]); - } - }; - await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker)); - return out; -}; diff --git a/src/app/features/albums/readPages.ts b/src/app/features/albums/readPages.ts deleted file mode 100644 index a2b888e5..00000000 --- a/src/app/features/albums/readPages.ts +++ /dev/null @@ -1,27 +0,0 @@ -/** One page of a Matrix paginated endpoint: its events and the token for the next page, if any. */ -export type Page = { chunk?: T[]; next_batch?: string }; - -/** Pages read per endpoint at most, so a runaway zone cannot hold the phone in a loop. */ -export const MAX_PAGES = 20; - -/** - * Reads every page of an endpoint by following `next_batch`, up to `maxPages`. `truncated` is true - * when the cap stopped the read with more still to come, so a caller can say the list is partial. - */ -export const readPages = async ( - fetchPage: (from: string | undefined) => Promise>, - maxPages = MAX_PAGES -): Promise<{ items: T[]; truncated: boolean }> => { - const items: T[] = []; - let from: string | undefined; - for (let n = 0; n < maxPages; n += 1) { - // eslint-disable-next-line no-await-in-loop - const page = await fetchPage(from); - items.push(...(page.chunk ?? [])); - // An empty page ends the read even if a token is returned: a server that keeps handing out - // tokens with nothing behind them would otherwise spend every page of the cap. - if (!page.next_batch || !page.chunk?.length) return { items, truncated: false }; - from = page.next_batch; - } - return { items, truncated: true }; -}; diff --git a/src/app/features/albums/shareController.ts b/src/app/features/albums/shareController.ts deleted file mode 100644 index 72f786c9..00000000 --- a/src/app/features/albums/shareController.ts +++ /dev/null @@ -1,135 +0,0 @@ -// The share panel's state machine, apart from React and Matrix: what is picked, what phase the -// send is in, and the rules that keep a room to one send at a time. ShareSet.tsx draws it. -import { ShareResult, remainingAfter, resultNote } from './shareSet'; - -export type Picked = { name: string; type: string; size?: number }; - -export type SharePhase = - | { kind: 'idle' } - | { kind: 'sending'; done: number } - | { kind: 'done'; text: string }; - -export type ShareState = { - files: F[]; - title: string; - phase: SharePhase; - /** Bumps whenever the pick is emptied, so the file input can be remounted and re-pick the same files. */ - epoch: number; -}; - -export const ENCRYPTED_NOTE = 'Not shared: this room is encrypted.'; - -const MIB = 1024 * 1024; - -/** - * Files the homeserver would refuse for size (its `m.upload.size`, which Synapse enforces as a - * limit, so a file of exactly that size goes), split from the rest before anything is sent. A - * missing cap or size refuses nothing. - */ -export const splitBySize = (files: F[], cap: number | undefined) => { - const over = (f: F) => cap !== undefined && f.size !== undefined && f.size > cap; - return { sendable: files.filter((f) => !over(f)), tooLarge: files.filter(over) }; -}; - -const tooLargeNote = (names: string[], cap: number): string => - `Too large for this server (limit ${Math.round((cap / MIB) * 10) / 10} MB): ${names.join(', ')}`; - -export type ShareDeps = { - roomId: string; - isEncrypted: () => boolean; - /** Sends the files as one album; reports each settled file through onFile. */ - run: (files: F[], title: string, onFile: () => void, signal: AbortSignal) => Promise; - /** The homeserver's upload cap in bytes (`m.upload.size`), when it states one. */ - maxBytes?: () => number | undefined; - /** Called after a send that reached the room, whatever it left unsent. */ - onSent?: () => void; -}; - -/** Rooms with a share in flight. Module-level: leaving the page unmounts the panel, not the send. */ -const sending = new Set(); - -export const createShareController = (deps: ShareDeps) => { - let state: ShareState = { files: [], title: '', phase: { kind: 'idle' }, epoch: 0 }; - const listeners = new Set<() => void>(); - let running: AbortController | undefined; - const set = (patch: Partial>) => { - state = { ...state, ...patch }; - listeners.forEach((l) => l()); - }; - - const clear = () => set({ files: [], title: '', epoch: state.epoch + 1 }); - - const send = async () => { - if (sending.has(deps.roomId) || state.files.length === 0) return; - if (deps.isEncrypted()) { - set({ phase: { kind: 'done', text: ENCRYPTED_NOTE } }); - return; - } - // Files over the cap are named and dropped from the pick before any upload or album root: a - // retry cannot help them, and a root with nothing under it is a lone message nobody lists. - const cap = deps.maxBytes?.(); - const { sendable, tooLarge } = splitBySize(state.files, cap); - const sizeNote = tooLarge.length - ? tooLargeNote( - tooLarge.map((f) => f.name), - cap as number - ) - : ''; - if (sendable.length === 0) { - const phase: SharePhase = { kind: 'done', text: `Nothing was shared. ${sizeNote}` }; - set({ files: [], title: '', epoch: state.epoch + 1, phase }); - return; - } - sending.add(deps.roomId); - const abort = new AbortController(); - running = abort; - const { title } = state; - const files = sendable; - set({ files, phase: { kind: 'sending', done: 0 } }); - let settled = 0; - try { - const res = await deps.run( - files, - title, - () => { - settled += 1; - set({ phase: { kind: 'sending', done: settled } }); - }, - abort.signal - ); - deps.onSent?.(); - const left = remainingAfter(files, res); - const phase: SharePhase = { - kind: 'done', - text: sizeNote ? `${resultNote(res)} ${sizeNote}` : resultNote(res), - }; - // One notification: no state is ever drawn with the pick emptied and the send still running. - if (left.length === 0) set({ files: [], title: '', epoch: state.epoch + 1, phase }); - else set({ files: left, phase }); - } catch (e: any) { - const failure = `Could not share: ${e?.message ?? 'send failed'}`; - set({ phase: { kind: 'done', text: sizeNote ? `${failure}. ${sizeNote}` : failure } }); - } finally { - running = undefined; - sending.delete(deps.roomId); - } - }; - - return { - getState: () => state, - subscribe: (l: () => void) => { - listeners.add(l); - return () => { - listeners.delete(l); - }; - }, - pick: (files: F[]) => set({ files, phase: { kind: 'idle' } }), - setTitle: (title: string) => set({ title }), - cancel: clear, - /** Stops a send in flight: the running upload is aborted and the rest are left picked. */ - stop: () => running?.abort(), - send, - }; -}; - -export type ShareController = ReturnType>; diff --git a/src/app/features/albums/shareSet.test.ts b/src/app/features/albums/shareSet.test.ts deleted file mode 100644 index 8fc4a8b8..00000000 --- a/src/app/features/albums/shareSet.test.ts +++ /dev/null @@ -1,328 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import config from '../../../../config.json'; -import { ZoneEvent, buildAlbums } from './buildAlbums'; -import { - DEFAULT_TITLE, - ShareFile, - SharePort, - CANCELLED, - freshest, - refusalOf, - remainingAfter, - resultNote, - sendShareSet, - threadRelation, -} from './shareSet'; - -const kindOf = (f: ShareFile) => (f.mimeType.startsWith('audio') ? 'm.audio' : 'm.file'); - -/** A fake room: records what is sent, as the events Synapse would return from /relations. */ -const room = (failOn: string[] = []) => { - const events: ZoneEvent[] = []; - const port: SharePort = { - send: async (content) => { - const id = `$e${events.length + 1}`; - events.push({ - event_id: id, - type: 'm.room.message', - sender: '@aqua:chat.gamecult.org', - origin_server_ts: 1000 + events.length, - content, - }); - return id; - }, - contentOf: async (f) => { - if (failOn.includes(f.name)) throw new Error('upload failed'); - return { - msgtype: kindOf(f), - body: f.name, - filename: f.name, - url: `mxc://x/${f.name}`, - info: { mimetype: f.mimeType }, - }; - }, - }; - const album = () => { - const [root, ...replies] = events; - return buildAlbums([{ root, replies }], 'chat.gamecult.org')[0]; - }; - return { events, port, album }; -}; - -const clips: ShareFile[] = [ - { name: 'a.ogg', mimeType: 'audio/ogg' }, - { name: 'b.ogg', mimeType: 'audio/ogg' }, - { name: 'c.txt', mimeType: 'text/plain' }, -]; - -describe('sendShareSet', () => { - it('reads back as one album of the files in pick order', async () => { - const r = room(); - const res = await sendShareSet(r.port, 'Take 4', clips); - expect(res).toEqual({ albumId: '$e1', sent: 3, failed: [], failedAt: [], reasons: [] }); - const album = r.album(); - expect(album.title).toBe('Take 4'); - expect(album.files.map((f) => [f.name, f.kind])).toEqual([ - ['a.ogg', 'audio'], - ['b.ogg', 'audio'], - ['c.txt', 'file'], - ]); - }); - - it('threads every file under the root, each falling back to the previous event', async () => { - const r = room(); - await sendShareSet(r.port, 't', clips); - const rels = r.events.slice(1).map((e) => e.content?.['m.relates_to']); - expect(rels).toEqual([ - threadRelation('$e1', '$e1'), - threadRelation('$e1', '$e2'), - threadRelation('$e1', '$e3'), - ]); - expect(r.events[0].content?.['m.relates_to']).toBeUndefined(); - }); - - it('titles an untitled share', async () => { - const r = room(); - await sendShareSet(r.port, ' ', clips.slice(0, 1)); - expect(r.album().title).toBe(DEFAULT_TITLE); - }); - - it('names a failed file and still sends the rest', async () => { - const r = room(['b.ogg']); - const res = await sendShareSet(r.port, 't', clips); - expect(res.failed).toEqual(['b.ogg']); - expect(res.sent).toBe(2); - expect(r.album().files.map((f) => f.name)).toEqual(['a.ogg', 'c.txt']); - // the next file falls back to the last event that exists, not to the failed one - expect(r.events[2].content?.['m.relates_to']).toEqual(threadRelation('$e1', '$e2')); - }); - - it('throws when the root cannot be sent, uploading nothing', async () => { - let uploads = 0; - const port: SharePort = { - send: async () => { - throw new Error('M_FORBIDDEN'); - }, - contentOf: async () => { - uploads += 1; - return {}; - }, - }; - await expect(sendShareSet(port, 't', clips)).rejects.toThrow('M_FORBIDDEN'); - expect(uploads).toBe(0); - }); -}); - -describe('the share flag', () => { - it('ships off', () => { - expect(config.fileZoneShare).toEqual({ enabled: false }); - }); -}); - -describe('after a send', () => { - it('keeps the failed one of two same-named files, not both', async () => { - const twins: ShareFile[] = [ - { name: 'a.ogg', mimeType: 'audio/ogg' }, - { name: 'a.ogg', mimeType: 'audio/ogg' }, - ]; - let n = 0; - const r = room(); - const port: SharePort = { - ...r.port, - contentOf: async (f) => { - n += 1; - if (n === 2) throw new Error('second upload failed'); - return r.port.contentOf(f); - }, - }; - const res = await sendShareSet(port, 't', twins); - expect(res.failedAt).toEqual([1]); - expect(remainingAfter(twins, res)).toEqual([twins[1]]); - }); - - it('keeps only the failed files picked, so a retry is one tap', async () => { - const r = room(['b.ogg']); - const res = await sendShareSet(r.port, 't', clips); - expect(remainingAfter(clips, res).map((f) => f.name)).toEqual(['b.ogg']); - expect(resultNote(res)).toBe('Shared 2. Not sent: b.ogg'); - }); - - it('keeps everything and says nothing was shared when every upload failed', async () => { - const r = room(clips.map((c) => c.name)); - const res = await sendShareSet(r.port, 't', clips); - expect(remainingAfter(clips, res)).toEqual(clips); - expect(resultNote(res)).toBe('Nothing was shared. Not sent: a.ogg, b.ogg, c.txt'); - }); - - it('clears the pick on full success', async () => { - const r = room(); - const res = await sendShareSet(r.port, 't', clips); - expect(remainingAfter(clips, res)).toEqual([]); - expect(resultNote(res)).toBe('Shared 3 files.'); - }); -}); - -describe('adding to an existing album', () => { - it('sends no root; each file threads under the album, the first after `lastId`', async () => { - const r = room(); - const sent: Record[] = []; - const port = { - ...r.port, - send: async (c: Record) => { - sent.push(c); - return `$n${sent.length}`; - }, - }; - const res = await sendShareSet( - port, - { albumId: '$root', lastId: '$last', lastTs: 1 }, - clips.slice(0, 2) - ); - expect(res.albumId).toBe('$root'); - expect(res.sent).toBe(2); - expect(sent.map((c) => c.msgtype)).toEqual(['m.audio', 'm.audio']); - expect(sent.map((c) => c['m.relates_to'])).toEqual([ - threadRelation('$root', '$last'), - threadRelation('$root', '$n1'), - ]); - }); -}); - -describe('refusals', () => { - const refuse = (errcode: string): SharePort => ({ - send: async () => '$e', - contentOf: async () => { - throw Object.assign(new Error('raw server text'), { errcode }); - }, - }); - - it('names the three upload refusals and nothing else', () => { - expect(refusalOf({ errcode: 'M_TOO_LARGE' })).toBe('too large for this server'); - expect(refusalOf({ errcode: 'M_FORBIDDEN' })).toBe('not allowed to upload here'); - expect(refusalOf({ errcode: 'M_LIMIT_EXCEEDED' })).toBe( - 'uploading too fast, try again shortly' - ); - expect(refusalOf({ errcode: 'M_UNKNOWN' })).toBeUndefined(); - expect(refusalOf({ errcode: 'constructor' })).toBeUndefined(); - expect(refusalOf(new Error('x'))).toBeUndefined(); - expect(refusalOf(null)).toBeUndefined(); - }); - - it('the note carries the reason beside each refused file', async () => { - const res = await sendShareSet(refuse('M_TOO_LARGE'), 't', clips.slice(0, 2)); - expect(resultNote(res)).toBe( - 'Nothing was shared. Not sent: a.ogg (too large for this server), b.ogg (too large for this server)' - ); - }); - - it('a failure the client saw, not the server, is named too', async () => { - const dropped: SharePort = { - send: async () => '$e', - contentOf: async () => { - throw Object.assign(new Error('x'), { - errcode: 'AbortError', - info: { aborted: true, progressed: true }, - }); - }, - }; - const res = await sendShareSet(dropped, 't', clips.slice(0, 1)); - expect(resultNote(res)).toBe( - 'Nothing was shared. Not sent: a.ogg (the connection dropped partway through)' - ); - }); - - it('an unnamed failure lists the bare name', async () => { - const res = await sendShareSet(refuse('M_UNKNOWN'), 't', clips.slice(0, 1)); - expect(resultNote(res)).toBe('Nothing was shared. Not sent: a.ogg'); - }); -}); - -describe('stopping a send', () => { - /** A port whose upload of `stopAt` aborts the signal as it runs, as the Stop button does mid-upload. */ - const stopping = (stopAt: string, abortAfterUpload = false) => { - const ac = new AbortController(); - const r = room(); - const port: SharePort = { - ...r.port, - signal: ac.signal, - contentOf: async (f) => { - if (f.name !== stopAt) return r.port.contentOf(f); - ac.abort(); - if (abortAfterUpload) return r.port.contentOf(f); - throw Object.assign(new Error('aborted'), { name: 'AbortError' }); - }, - }; - return { port, r }; - }; - - it('an upload aborted mid-file leaves that file and the rest unsent, named as stopped', async () => { - const { port, r } = stopping('b.ogg'); - const res = await sendShareSet(port, 't', clips); - expect(res.sent).toBe(1); - expect(res.failed).toEqual(['b.ogg', 'c.txt']); - expect(res.failedAt).toEqual([1, 2]); - expect(res.reasons).toEqual([CANCELLED, CANCELLED]); - expect(r.album().files.map((f) => f.name)).toEqual(['a.ogg']); - expect(remainingAfter(clips, res).map((f) => f.name)).toEqual(['b.ogg', 'c.txt']); - expect(resultNote(res)).toBe('Shared 1. Not sent: b.ogg (stopped), c.txt (stopped)'); - }); - - it('a file whose upload finished after the stop is not sent', async () => { - const { port, r } = stopping('b.ogg', true); - const res = await sendShareSet(port, 't', clips); - expect(res.sent).toBe(1); - expect(res.failedAt).toEqual([1, 2]); - expect(r.album().files.map((f) => f.name)).toEqual(['a.ogg']); - }); - - it('a signal already aborted starts nothing and sends everything back as unsent', async () => { - const r = room(); - const ac = new AbortController(); - ac.abort(); - let uploads = 0; - const res = await sendShareSet( - { - ...r.port, - signal: ac.signal, - contentOf: async (f) => { - uploads += 1; - return r.port.contentOf(f); - }, - }, - { albumId: '$a', lastId: '$l', lastTs: 1 }, - clips - ); - expect(uploads).toBe(0); - expect(res.sent).toBe(0); - expect(res.failedAt).toEqual([0, 1, 2]); - expect(r.events).toEqual([]); - }); - - it('an abort that is not a stop is an ordinary failure', async () => { - const r = room(['b.ogg']); - const res = await sendShareSet({ ...r.port, signal: new AbortController().signal }, 't', clips); - expect(res.failedAt).toEqual([1]); - expect(res.reasons).toEqual([undefined]); - }); -}); - -describe('freshest', () => { - const album = { albumId: '$alb', lastId: '$old', lastTs: 100 }; - it('moves lastId to a newer event of the same thread', () => { - expect( - freshest(album, [ - { id: '$mid', ts: 150, threadRoot: '$alb' }, - { id: '$new', ts: 200, threadRoot: '$alb' }, - ]) - ).toEqual({ albumId: '$alb', lastId: '$new', lastTs: 200 }); - }); - it('ignores older events and events of other threads or none', () => { - expect( - freshest(album, [ - { id: '$older', ts: 50, threadRoot: '$alb' }, - { id: '$other', ts: 900, threadRoot: '$else' }, - { id: '$loose', ts: 900 }, - ]) - ).toEqual(album); - }); -}); diff --git a/src/app/features/albums/shareController.test.ts b/src/app/features/albums/shareUpload.test.ts similarity index 53% rename from src/app/features/albums/shareController.test.ts rename to src/app/features/albums/shareUpload.test.ts index b163b736..bacddd08 100644 --- a/src/app/features/albums/shareController.test.ts +++ b/src/app/features/albums/shareUpload.test.ts @@ -1,6 +1,328 @@ import { describe, expect, it } from 'vitest'; -import { Picked, ShareDeps, createShareController } from './shareController'; -import { ShareResult } from './shareSet'; +import { ZoneEvent, buildAlbums } from './buildAlbums'; +import { + DEFAULT_TITLE, + ShareFile, + SharePort, + CANCELLED, + freshest, + refusalOf, + remainingAfter, + resultNote, + sendShareSet, + Picked, + ShareDeps, + ShareResult, + createShareController, + threadRelation, +} from './shareUpload'; + +const kindOf = (f: ShareFile) => (f.mimeType.startsWith('audio') ? 'm.audio' : 'm.file'); + +/** A fake room: records what is sent, as the events Synapse would return from /relations. */ +const room = (failOn: string[] = []) => { + const events: ZoneEvent[] = []; + const port: SharePort = { + send: async (content) => { + const id = `$e${events.length + 1}`; + events.push({ + event_id: id, + type: 'm.room.message', + sender: '@aqua:chat.gamecult.org', + origin_server_ts: 1000 + events.length, + content, + }); + return id; + }, + contentOf: async (f) => { + if (failOn.includes(f.name)) throw new Error('upload failed'); + return { + msgtype: kindOf(f), + body: f.name, + filename: f.name, + url: `mxc://x/${f.name}`, + info: { mimetype: f.mimeType }, + }; + }, + }; + const album = () => { + const [root, ...replies] = events; + return buildAlbums([{ root, replies }], 'chat.gamecult.org')[0]; + }; + return { events, port, album }; +}; + +const clips: ShareFile[] = [ + { name: 'a.ogg', mimeType: 'audio/ogg' }, + { name: 'b.ogg', mimeType: 'audio/ogg' }, + { name: 'c.txt', mimeType: 'text/plain' }, +]; + +describe('sendShareSet', () => { + it('reads back as one album of the files in pick order', async () => { + const r = room(); + const res = await sendShareSet(r.port, 'Take 4', clips); + expect(res).toEqual({ albumId: '$e1', sent: 3, failed: [], failedAt: [], reasons: [] }); + const album = r.album(); + expect(album.title).toBe('Take 4'); + expect(album.files.map((f) => [f.name, f.kind])).toEqual([ + ['a.ogg', 'audio'], + ['b.ogg', 'audio'], + ['c.txt', 'file'], + ]); + }); + + it('threads every file under the root, each falling back to the previous event', async () => { + const r = room(); + await sendShareSet(r.port, 't', clips); + const rels = r.events.slice(1).map((e) => e.content?.['m.relates_to']); + expect(rels).toEqual([ + threadRelation('$e1', '$e1'), + threadRelation('$e1', '$e2'), + threadRelation('$e1', '$e3'), + ]); + expect(r.events[0].content?.['m.relates_to']).toBeUndefined(); + }); + + it('titles an untitled share', async () => { + const r = room(); + await sendShareSet(r.port, ' ', clips.slice(0, 1)); + expect(r.album().title).toBe(DEFAULT_TITLE); + }); + + it('names a failed file and still sends the rest', async () => { + const r = room(['b.ogg']); + const res = await sendShareSet(r.port, 't', clips); + expect(res.failed).toEqual(['b.ogg']); + expect(res.sent).toBe(2); + expect(r.album().files.map((f) => f.name)).toEqual(['a.ogg', 'c.txt']); + // the next file falls back to the last event that exists, not to the failed one + expect(r.events[2].content?.['m.relates_to']).toEqual(threadRelation('$e1', '$e2')); + }); + + it('throws when the root cannot be sent, uploading nothing', async () => { + let uploads = 0; + const port: SharePort = { + send: async () => { + throw new Error('M_FORBIDDEN'); + }, + contentOf: async () => { + uploads += 1; + return {}; + }, + }; + await expect(sendShareSet(port, 't', clips)).rejects.toThrow('M_FORBIDDEN'); + expect(uploads).toBe(0); + }); +}); + +describe('after a send', () => { + it('keeps the failed one of two same-named files, not both', async () => { + const twins: ShareFile[] = [ + { name: 'a.ogg', mimeType: 'audio/ogg' }, + { name: 'a.ogg', mimeType: 'audio/ogg' }, + ]; + let n = 0; + const r = room(); + const port: SharePort = { + ...r.port, + contentOf: async (f) => { + n += 1; + if (n === 2) throw new Error('second upload failed'); + return r.port.contentOf(f); + }, + }; + const res = await sendShareSet(port, 't', twins); + expect(res.failedAt).toEqual([1]); + expect(remainingAfter(twins, res)).toEqual([twins[1]]); + }); + + it('keeps only the failed files picked, so a retry is one tap', async () => { + const r = room(['b.ogg']); + const res = await sendShareSet(r.port, 't', clips); + expect(remainingAfter(clips, res).map((f) => f.name)).toEqual(['b.ogg']); + expect(resultNote(res)).toBe('Shared 2. Not sent: b.ogg'); + }); + + it('keeps everything and says nothing was shared when every upload failed', async () => { + const r = room(clips.map((c) => c.name)); + const res = await sendShareSet(r.port, 't', clips); + expect(remainingAfter(clips, res)).toEqual(clips); + expect(resultNote(res)).toBe('Nothing was shared. Not sent: a.ogg, b.ogg, c.txt'); + }); + + it('clears the pick on full success', async () => { + const r = room(); + const res = await sendShareSet(r.port, 't', clips); + expect(remainingAfter(clips, res)).toEqual([]); + expect(resultNote(res)).toBe('Shared 3 files.'); + }); +}); + +describe('adding to an existing album', () => { + it('sends no root; each file threads under the album, the first after `lastId`', async () => { + const r = room(); + const sent: Record[] = []; + const port = { + ...r.port, + send: async (c: Record) => { + sent.push(c); + return `$n${sent.length}`; + }, + }; + const res = await sendShareSet( + port, + { albumId: '$root', lastId: '$last', lastTs: 1 }, + clips.slice(0, 2) + ); + expect(res.albumId).toBe('$root'); + expect(res.sent).toBe(2); + expect(sent.map((c) => c.msgtype)).toEqual(['m.audio', 'm.audio']); + expect(sent.map((c) => c['m.relates_to'])).toEqual([ + threadRelation('$root', '$last'), + threadRelation('$root', '$n1'), + ]); + }); +}); + +describe('refusals', () => { + const refuse = (errcode: string): SharePort => ({ + send: async () => '$e', + contentOf: async () => { + throw Object.assign(new Error('raw server text'), { errcode }); + }, + }); + + it('names the three upload refusals and nothing else', () => { + expect(refusalOf({ errcode: 'M_TOO_LARGE' })).toBe('too large for this server'); + expect(refusalOf({ errcode: 'M_FORBIDDEN' })).toBe('not allowed to upload here'); + expect(refusalOf({ errcode: 'M_LIMIT_EXCEEDED' })).toBe( + 'uploading too fast, try again shortly' + ); + expect(refusalOf({ errcode: 'M_UNKNOWN' })).toBeUndefined(); + expect(refusalOf({ errcode: 'constructor' })).toBeUndefined(); + expect(refusalOf(new Error('x'))).toBeUndefined(); + expect(refusalOf(null)).toBeUndefined(); + }); + + it('the note carries the reason beside each refused file', async () => { + const res = await sendShareSet(refuse('M_TOO_LARGE'), 't', clips.slice(0, 2)); + expect(resultNote(res)).toBe( + 'Nothing was shared. Not sent: a.ogg (too large for this server), b.ogg (too large for this server)' + ); + }); + + it('a failure the client saw, not the server, is named too', async () => { + const dropped: SharePort = { + send: async () => '$e', + contentOf: async () => { + throw Object.assign(new Error('x'), { + errcode: 'AbortError', + info: { aborted: true, progressed: true }, + }); + }, + }; + const res = await sendShareSet(dropped, 't', clips.slice(0, 1)); + expect(resultNote(res)).toBe( + 'Nothing was shared. Not sent: a.ogg (the connection dropped partway through)' + ); + }); + + it('an unnamed failure lists the bare name', async () => { + const res = await sendShareSet(refuse('M_UNKNOWN'), 't', clips.slice(0, 1)); + expect(resultNote(res)).toBe('Nothing was shared. Not sent: a.ogg'); + }); +}); + +describe('stopping a send', () => { + /** A port whose upload of `stopAt` aborts the signal as it runs, as the Stop button does mid-upload. */ + const stopping = (stopAt: string, abortAfterUpload = false) => { + const ac = new AbortController(); + const r = room(); + const port: SharePort = { + ...r.port, + signal: ac.signal, + contentOf: async (f) => { + if (f.name !== stopAt) return r.port.contentOf(f); + ac.abort(); + if (abortAfterUpload) return r.port.contentOf(f); + throw Object.assign(new Error('aborted'), { name: 'AbortError' }); + }, + }; + return { port, r }; + }; + + it('an upload aborted mid-file leaves that file and the rest unsent, named as stopped', async () => { + const { port, r } = stopping('b.ogg'); + const res = await sendShareSet(port, 't', clips); + expect(res.sent).toBe(1); + expect(res.failed).toEqual(['b.ogg', 'c.txt']); + expect(res.failedAt).toEqual([1, 2]); + expect(res.reasons).toEqual([CANCELLED, CANCELLED]); + expect(r.album().files.map((f) => f.name)).toEqual(['a.ogg']); + expect(remainingAfter(clips, res).map((f) => f.name)).toEqual(['b.ogg', 'c.txt']); + expect(resultNote(res)).toBe('Shared 1. Not sent: b.ogg (stopped), c.txt (stopped)'); + }); + + it('a file whose upload finished after the stop is not sent', async () => { + const { port, r } = stopping('b.ogg', true); + const res = await sendShareSet(port, 't', clips); + expect(res.sent).toBe(1); + expect(res.failedAt).toEqual([1, 2]); + expect(r.album().files.map((f) => f.name)).toEqual(['a.ogg']); + }); + + it('a signal already aborted starts nothing and sends everything back as unsent', async () => { + const r = room(); + const ac = new AbortController(); + ac.abort(); + let uploads = 0; + const res = await sendShareSet( + { + ...r.port, + signal: ac.signal, + contentOf: async (f) => { + uploads += 1; + return r.port.contentOf(f); + }, + }, + { albumId: '$a', lastId: '$l', lastTs: 1 }, + clips + ); + expect(uploads).toBe(0); + expect(res.sent).toBe(0); + expect(res.failedAt).toEqual([0, 1, 2]); + expect(r.events).toEqual([]); + }); + + it('an abort that is not a stop is an ordinary failure', async () => { + const r = room(['b.ogg']); + const res = await sendShareSet({ ...r.port, signal: new AbortController().signal }, 't', clips); + expect(res.failedAt).toEqual([1]); + expect(res.reasons).toEqual([undefined]); + }); +}); + +describe('freshest', () => { + const album = { albumId: '$alb', lastId: '$old', lastTs: 100 }; + it('moves lastId to a newer event of the same thread', () => { + expect( + freshest(album, [ + { id: '$mid', ts: 150, threadRoot: '$alb' }, + { id: '$new', ts: 200, threadRoot: '$alb' }, + ]) + ).toEqual({ albumId: '$alb', lastId: '$new', lastTs: 200 }); + }); + it('ignores older events and events of other threads or none', () => { + expect( + freshest(album, [ + { id: '$older', ts: 50, threadRoot: '$alb' }, + { id: '$other', ts: 900, threadRoot: '$else' }, + { id: '$loose', ts: 900 }, + ]) + ).toEqual(album); + }); +}); const file = (name: string, size?: number): Picked => ({ name, type: 'audio/ogg', size }); const MB = 1024 * 1024; diff --git a/src/app/features/albums/shareSet.ts b/src/app/features/albums/shareUpload.ts similarity index 52% rename from src/app/features/albums/shareSet.ts rename to src/app/features/albums/shareUpload.ts index 007d7e91..178f6653 100644 --- a/src/app/features/albums/shareSet.ts +++ b/src/app/features/albums/shareUpload.ts @@ -1,6 +1,5 @@ -// Share a set of files at once: one album root (a text message) and one thread reply per file. -// That is exactly the shape buildAlbums reads, so a set shared here and a set a Mind's mouth posts -// are the same thing to every viewer. Ports are injected so the order and the failure rules are +// Share a set of files at once: one album root (a text message) and one thread reply per file, +// plus the share panel's state machine. Ports are injected so order and failure rules are // testable without a homeserver. See docs/file-zone.md, "Share a set". import { uploadReason } from '../../utils/uploadReason'; @@ -136,3 +135,135 @@ export const resultNote = (result: ShareResult): string => { if (result.sent === 0) return `Nothing was shared. Not sent: ${failedList(result)}`; return `Shared ${result.sent}. Not sent: ${failedList(result)}`; }; + +export type Picked = { name: string; type: string; size?: number }; + +export type SharePhase = + | { kind: 'idle' } + | { kind: 'sending'; done: number } + | { kind: 'done'; text: string }; + +export type ShareState = { + files: F[]; + title: string; + phase: SharePhase; + /** Bumps whenever the pick is emptied, so the file input can be remounted and re-pick the same files. */ + epoch: number; +}; + +export const ENCRYPTED_NOTE = 'Not shared: this room is encrypted.'; + +const MIB = 1024 * 1024; + +/** + * Files the homeserver would refuse for size (its `m.upload.size`, which Synapse enforces as a + * limit, so a file of exactly that size goes), split from the rest before anything is sent. A + * missing cap or size refuses nothing. + */ +export const splitBySize = (files: F[], cap: number | undefined) => { + const over = (f: F) => cap !== undefined && f.size !== undefined && f.size > cap; + return { sendable: files.filter((f) => !over(f)), tooLarge: files.filter(over) }; +}; + +const tooLargeNote = (names: string[], cap: number): string => + `Too large for this server (limit ${Math.round((cap / MIB) * 10) / 10} MB): ${names.join(', ')}`; + +export type ShareDeps = { + roomId: string; + isEncrypted: () => boolean; + /** Sends the files as one album; reports each settled file through onFile. */ + run: (files: F[], title: string, onFile: () => void, signal: AbortSignal) => Promise; + /** The homeserver's upload cap in bytes (`m.upload.size`), when it states one. */ + maxBytes?: () => number | undefined; + /** Called after a send that reached the room, whatever it left unsent. */ + onSent?: () => void; +}; + +/** Rooms with a share in flight. Module-level: leaving the page unmounts the panel, not the send. */ +const sending = new Set(); + +export const createShareController = (deps: ShareDeps) => { + let state: ShareState = { files: [], title: '', phase: { kind: 'idle' }, epoch: 0 }; + const listeners = new Set<() => void>(); + let running: AbortController | undefined; + const set = (patch: Partial>) => { + state = { ...state, ...patch }; + listeners.forEach((l) => l()); + }; + + const clear = () => set({ files: [], title: '', epoch: state.epoch + 1 }); + + const send = async () => { + if (sending.has(deps.roomId) || state.files.length === 0) return; + if (deps.isEncrypted()) { + set({ phase: { kind: 'done', text: ENCRYPTED_NOTE } }); + return; + } + // Files over the cap are named and dropped from the pick before any upload or album root: a + // retry cannot help them, and a root with nothing under it is a lone message nobody lists. + const cap = deps.maxBytes?.(); + const { sendable, tooLarge } = splitBySize(state.files, cap); + const sizeNote = tooLarge.length + ? tooLargeNote( + tooLarge.map((f) => f.name), + cap as number + ) + : ''; + if (sendable.length === 0) { + const phase: SharePhase = { kind: 'done', text: `Nothing was shared. ${sizeNote}` }; + set({ files: [], title: '', epoch: state.epoch + 1, phase }); + return; + } + sending.add(deps.roomId); + const abort = new AbortController(); + running = abort; + const { title } = state; + const files = sendable; + set({ files, phase: { kind: 'sending', done: 0 } }); + let settled = 0; + try { + const res = await deps.run( + files, + title, + () => { + settled += 1; + set({ phase: { kind: 'sending', done: settled } }); + }, + abort.signal + ); + deps.onSent?.(); + const left = remainingAfter(files, res); + const phase: SharePhase = { + kind: 'done', + text: sizeNote ? `${resultNote(res)} ${sizeNote}` : resultNote(res), + }; + // One notification: no state is ever drawn with the pick emptied and the send still running. + if (left.length === 0) set({ files: [], title: '', epoch: state.epoch + 1, phase }); + else set({ files: left, phase }); + } catch (e: any) { + const failure = `Could not share: ${e?.message ?? 'send failed'}`; + set({ phase: { kind: 'done', text: sizeNote ? `${failure}. ${sizeNote}` : failure } }); + } finally { + running = undefined; + sending.delete(deps.roomId); + } + }; + + return { + getState: () => state, + subscribe: (l: () => void) => { + listeners.add(l); + return () => { + listeners.delete(l); + }; + }, + pick: (files: F[]) => set({ files, phase: { kind: 'idle' } }), + setTitle: (title: string) => set({ title }), + cancel: clear, + /** Stops a send in flight: the running upload is aborted and the rest are left picked. */ + stop: () => running?.abort(), + send, + }; +}; + +export type ShareController = ReturnType>; diff --git a/src/app/features/albums/readPages.test.ts b/src/app/features/albums/useAlbums.test.ts similarity index 69% rename from src/app/features/albums/readPages.test.ts rename to src/app/features/albums/useAlbums.test.ts index 124a32a6..49f6d7e4 100644 --- a/src/app/features/albums/readPages.test.ts +++ b/src/app/features/albums/useAlbums.test.ts @@ -1,5 +1,32 @@ import { describe, expect, it } from 'vitest'; -import { Page, readPages } from './readPages'; +import { Page, mapLimit, readPages } from './useAlbums'; + +describe('mapLimit', () => { + it('keeps result order and never exceeds the limit', async () => { + let inFlight = 0; + let peak = 0; + const out = await mapLimit([5, 1, 4, 2, 3, 0], 2, async (n) => { + inFlight += 1; + peak = Math.max(peak, inFlight); + await new Promise((r) => { + setTimeout(r, n); + }); + inFlight -= 1; + return n * 10; + }); + expect(out).toEqual([50, 10, 40, 20, 30, 0]); + expect(peak).toBe(2); + }); + it('handles an empty list and rejects when a call rejects', async () => { + expect(await mapLimit([], 3, async (n) => n)).toEqual([]); + await expect( + mapLimit([1, 2], 2, async (n) => { + if (n === 2) throw new Error('boom'); + return n; + }) + ).rejects.toThrow('boom'); + }); +}); const pager = (pages: Page[]) => { const froms: (string | undefined)[] = []; diff --git a/src/app/features/albums/useAlbums.ts b/src/app/features/albums/useAlbums.ts index 13c199ec..52e5d19c 100644 --- a/src/app/features/albums/useAlbums.ts +++ b/src/app/features/albums/useAlbums.ts @@ -4,14 +4,59 @@ import { StateEvent } from '../../../types/matrix/room'; import { useStateEvent } from '../../hooks/useStateEvent'; import { useMatrixClient } from '../../hooks/useMatrixClient'; import { useClientConfig } from '../../hooks/useClientConfig'; -import { Album, ZoneEvent, buildAlbums } from './buildAlbums'; -import { isFileZone } from './isFileZone'; -import { mapLimit } from './mapLimit'; -import { Page, readPages } from './readPages'; +import { Album, ZoneEvent, buildAlbums, isFileZone } from './buildAlbums'; const REPLY_FETCHES_IN_FLIGHT = 6; const REFRESH_MS = 30_000; +/** One page of a Matrix paginated endpoint: its events and the token for the next page, if any. */ +export type Page = { chunk?: T[]; next_batch?: string }; + +/** Pages read per endpoint at most, so a runaway zone cannot hold the phone in a loop. */ +export const MAX_PAGES = 20; + +/** + * Reads every page of an endpoint by following `next_batch`, up to `maxPages`. `truncated` is true + * when the cap stopped the read with more still to come, so a caller can say the list is partial. + */ +export const readPages = async ( + fetchPage: (from: string | undefined) => Promise>, + maxPages = MAX_PAGES +): Promise<{ items: T[]; truncated: boolean }> => { + const items: T[] = []; + let from: string | undefined; + for (let n = 0; n < maxPages; n += 1) { + // eslint-disable-next-line no-await-in-loop + const page = await fetchPage(from); + items.push(...(page.chunk ?? [])); + // An empty page ends the read even if a token is returned: a server that keeps handing out + // tokens with nothing behind them would otherwise spend every page of the cap. + if (!page.next_batch || !page.chunk?.length) return { items, truncated: false }; + from = page.next_batch; + } + return { items, truncated: true }; +}; + +/** Like Promise.all(items.map(fn)) but with at most `limit` calls in flight; result order kept. */ +export const mapLimit = async ( + items: T[], + limit: number, + fn: (item: T) => Promise +): Promise => { + const out = new Array(items.length); + let next = 0; + const worker = async () => { + while (next < items.length) { + const i = next; + next += 1; + // eslint-disable-next-line no-await-in-loop + out[i] = await fn(items[i]); + } + }; + await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker)); + return out; +}; + /** True when the room is the file zone: by its create type, or listed in the client config. */ export const useIsFileZone = (room: Room): boolean => { const config = useClientConfig(); diff --git a/src/app/features/albums/zoneView.test.ts b/src/app/features/albums/zoneView.test.ts deleted file mode 100644 index 65beb9cb..00000000 --- a/src/app/features/albums/zoneView.test.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { zoneView } from './zoneView'; - -describe('zoneView', () => { - it('opens albums by default and the timeline for an event deep link', () => { - expect(zoneView(undefined, undefined)).toBe('albums'); - expect(zoneView(undefined, '$e')).toBe('timeline'); - }); - it('lets an event link win over an earlier choice of albums', () => { - expect(zoneView('albums', '$e')).toBe('timeline'); - }); - it('honours the choice when there is no event link', () => { - expect(zoneView('albums', undefined)).toBe('albums'); - expect(zoneView('timeline', undefined)).toBe('timeline'); - }); -}); diff --git a/src/app/features/albums/zoneView.ts b/src/app/features/albums/zoneView.ts deleted file mode 100644 index 1af7f705..00000000 --- a/src/app/features/albums/zoneView.ts +++ /dev/null @@ -1,5 +0,0 @@ -export type ZoneView = 'albums' | 'timeline'; - -/** The view a file-zone room shows. A link to an event always wins; else the user's choice; else albums. */ -export const zoneView = (choice: ZoneView | undefined, eventId: string | undefined): ZoneView => - eventId ? 'timeline' : choice ?? 'albums'; diff --git a/src/app/features/call-status/CallControl.tsx b/src/app/features/call-status/CallControl.tsx index d63f8709..3cf38b1f 100644 --- a/src/app/features/call-status/CallControl.tsx +++ b/src/app/features/call-status/CallControl.tsx @@ -5,7 +5,6 @@ import { StatusDivider } from './components'; import { CallEmbed, useCallControlState } from '../../plugins/call'; import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback'; import { callEmbedAtom } from '../../state/callEmbed'; -import { PhoneHitSpread26 } from '../../styles/PhoneHit.css'; type MicrophoneButtonProps = { enabled: boolean; @@ -27,7 +26,6 @@ function MicrophoneButton({ enabled, onToggle, disabled }: MicrophoneButtonProps > {(anchorRef) => ( {(anchorRef) => ( {(anchorRef) => ( {(anchorRef) => ( {(anchorRef) => ( {(anchorRef) => ( {(anchorRef) => ( {(anchorRef) => ( {(anchorRef) => ( void; @@ -93,7 +92,7 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) { - + diff --git a/src/app/features/common-settings/developer-tools/SendRoomEvent.tsx b/src/app/features/common-settings/developer-tools/SendRoomEvent.tsx index a6e60a7b..f25ba7c3 100644 --- a/src/app/features/common-settings/developer-tools/SendRoomEvent.tsx +++ b/src/app/features/common-settings/developer-tools/SendRoomEvent.tsx @@ -22,7 +22,6 @@ import { useTextAreaCodeEditor } from '../../../hooks/useTextAreaCodeEditor'; import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback'; import { syntaxErrorPosition } from '../../../utils/dom'; import { Cursor } from '../../../plugins/text-area'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; const EDITOR_INTENT_SPACE_COUNT = 2; @@ -119,7 +118,7 @@ export function SendRoomEvent({ type, stateKey, requestClose }: SendRoomEventPro - + diff --git a/src/app/features/common-settings/developer-tools/StateEventEditor.tsx b/src/app/features/common-settings/developer-tools/StateEventEditor.tsx index 0f9f4034..0ea96901 100644 --- a/src/app/features/common-settings/developer-tools/StateEventEditor.tsx +++ b/src/app/features/common-settings/developer-tools/StateEventEditor.tsx @@ -31,7 +31,6 @@ import { usePowerLevels } from '../../../hooks/usePowerLevels'; import { useTextAreaCodeEditor } from '../../../hooks/useTextAreaCodeEditor'; import { useRoomCreators } from '../../../hooks/useRoomCreators'; import { useRoomPermissions } from '../../../hooks/useRoomPermissions'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; const EDITOR_INTENT_SPACE_COUNT = 2; @@ -276,7 +275,7 @@ export function StateEventEditor({ type, stateKey, requestClose }: StateEventEdi - + diff --git a/src/app/features/common-settings/emojis-stickers/EmojisStickers.tsx b/src/app/features/common-settings/emojis-stickers/EmojisStickers.tsx index f7e901d5..ad8ffae6 100644 --- a/src/app/features/common-settings/emojis-stickers/EmojisStickers.tsx +++ b/src/app/features/common-settings/emojis-stickers/EmojisStickers.tsx @@ -4,7 +4,6 @@ import { Page, PageContent, PageHeader } from '../../../components/page'; import { ImagePack } from '../../../plugins/custom-emoji'; import { ImagePackView } from '../../../components/image-pack-view'; import { RoomPacks } from './RoomPacks'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; type EmojisStickersProps = { requestClose: () => void; @@ -30,7 +29,7 @@ export function EmojisStickers({ requestClose }: EmojisStickersProps) { - + diff --git a/src/app/features/common-settings/emojis-stickers/RoomPacks.tsx b/src/app/features/common-settings/emojis-stickers/RoomPacks.tsx index 7be8de35..fdbe546e 100644 --- a/src/app/features/common-settings/emojis-stickers/RoomPacks.tsx +++ b/src/app/features/common-settings/emojis-stickers/RoomPacks.tsx @@ -40,7 +40,6 @@ import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback'; import { useAlive } from '../../../hooks/useAlive'; import { useRoomCreators } from '../../../hooks/useRoomCreators'; import { useRoomPermissions } from '../../../hooks/useRoomPermissions'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; type CreatePackTileProps = { packs: ImagePack[]; @@ -216,7 +215,6 @@ export function RoomPacks({ onViewPack }: RoomPacksProps) { {canEdit && (removed ? ( ) : ( Enable Encryption setPrompt(false)} radii="300" diff --git a/src/app/features/common-settings/general/RoomUpgrade.tsx b/src/app/features/common-settings/general/RoomUpgrade.tsx index 2971d565..45a480aa 100644 --- a/src/app/features/common-settings/general/RoomUpgrade.tsx +++ b/src/app/features/common-settings/general/RoomUpgrade.tsx @@ -39,7 +39,6 @@ import { useAlive } from '../../../hooks/useAlive'; import { creatorsSupported } from '../../../utils/matrix'; import { useRoomCreators } from '../../../hooks/useRoomCreators'; import { BreakWord } from '../../../styles/Text.css'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; function RoomUpgradeDialog({ requestClose }: { requestClose: () => void }) { const mx = useMatrixClient(); @@ -106,7 +105,7 @@ function RoomUpgradeDialog({ requestClose }: { requestClose: () => void }) { {room.isSpaceRoom() ? 'Space Upgrade' : 'Room Upgrade'} - + diff --git a/src/app/features/common-settings/members/Members.tsx b/src/app/features/common-settings/members/Members.tsx index a1dddb54..15cd1d08 100644 --- a/src/app/features/common-settings/members/Members.tsx +++ b/src/app/features/common-settings/members/Members.tsx @@ -56,7 +56,6 @@ import { useSpaceOptionally } from '../../../hooks/useSpace'; import { useFlattenPowerTagMembers, useGetMemberPowerTag } from '../../../hooks/useMemberPowerTag'; import { useRoomCreators } from '../../../hooks/useRoomCreators'; import { getMouseEventCords } from '../../../utils/dom'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; const SEARCH_OPTIONS: UseAsyncSearchOptions = { limit: 1000, @@ -162,7 +161,7 @@ export function Members({ requestClose }: MembersProps) { - + @@ -278,7 +277,6 @@ export function Members({ requestClose }: MembersProps) { anchorRef={scrollTopAnchorRef} > virtualizer.scrollToOffset(0)} variant="Surface" radii="Pill" diff --git a/src/app/features/common-settings/permissions/PowersEditor.tsx b/src/app/features/common-settings/permissions/PowersEditor.tsx index 0684a48a..97305946 100644 --- a/src/app/features/common-settings/permissions/PowersEditor.tsx +++ b/src/app/features/common-settings/permissions/PowersEditor.tsx @@ -49,7 +49,6 @@ import { useAlive } from '../../../hooks/useAlive'; import { BetaNoticeBadge } from '../../../components/BetaNoticeBadge'; import { getPowerTagIconSrc } from '../../../hooks/useMemberPowerTag'; import { creatorsSupported } from '../../../utils/matrix'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; type EditPowerProps = { maxPower: number; @@ -370,7 +369,7 @@ export function PowersEditor({ powerLevels, requestClose }: PowersEditorProps) { - + diff --git a/src/app/features/create-room/CreateRoomModal.tsx b/src/app/features/create-room/CreateRoomModal.tsx index 9332f35c..d5d8c92d 100644 --- a/src/app/features/create-room/CreateRoomModal.tsx +++ b/src/app/features/create-room/CreateRoomModal.tsx @@ -24,7 +24,6 @@ import { import { CreateRoomModalState } from '../../state/createRoomModal'; import { stopPropagation } from '../../utils/keyboard'; import { CreateRoomType } from '../../components/create-room/types'; -import { PhoneHit } from '../../styles/PhoneHit.css'; type CreateRoomModalProps = { state: CreateRoomModalState; @@ -64,7 +63,7 @@ function CreateRoomModal({ state }: CreateRoomModalProps) { - + diff --git a/src/app/features/create-space/CreateSpaceModal.tsx b/src/app/features/create-space/CreateSpaceModal.tsx index faa53b25..c1bc6898 100644 --- a/src/app/features/create-space/CreateSpaceModal.tsx +++ b/src/app/features/create-space/CreateSpaceModal.tsx @@ -23,7 +23,6 @@ import { } from '../../state/hooks/createSpaceModal'; import { CreateSpaceModalState } from '../../state/createSpaceModal'; import { stopPropagation } from '../../utils/keyboard'; -import { PhoneHit } from '../../styles/PhoneHit.css'; type CreateSpaceModalProps = { state: CreateSpaceModalState; @@ -62,7 +61,7 @@ function CreateSpaceModal({ state }: CreateSpaceModalProps) { New Space - + diff --git a/src/app/features/desk/Desk.tsx b/src/app/features/desk/Desk.tsx index d6795ac4..b29ae9ec 100644 --- a/src/app/features/desk/Desk.tsx +++ b/src/app/features/desk/Desk.tsx @@ -1,7 +1,6 @@ import React, { useMemo } from 'react'; import { useNavigate, useParams } from 'react-router-dom'; import { Box, Icon, IconButton, Icons, Scroll, Text } from 'folds'; -import { PhoneHit } from '../../styles/PhoneHit.css'; import { Page, PageContent, PageContentCenter, PageHeader } from '../../components/page'; import { ScreenSize, useScreenSizeContext } from '../../hooks/useScreenSize'; import { getHomePath } from '../../pages/pathUtils'; @@ -28,7 +27,6 @@ export function Desk() { {phone && ( navigate(getHomePath())} > diff --git a/src/app/features/desk/DeskEntry.tsx b/src/app/features/desk/DeskEntry.tsx index 511b0783..518d7fee 100644 --- a/src/app/features/desk/DeskEntry.tsx +++ b/src/app/features/desk/DeskEntry.tsx @@ -37,10 +37,11 @@ export const openCount = ( unverified: ReadonlySet | undefined ): number => (unverified ? buildDesk(list, unverified).counts.open : 0); -/** A Mind's desk, pinned at the top of its navigator group: always there, with the open count when there is one. */ +/** A Mind's desk, pinned at the top of its navigator group when a desk source exists. */ export function DeskEntry({ mind }: { mind: string }) { const list = useMemo(() => deskFor(mind), [mind]); const unverified = useUnverified(list); + if (!list) return null; // The same count the desk page shows; until the hash check lands there is no count to show. return ; } diff --git a/src/app/features/desk/DeskView.test.tsx b/src/app/features/desk/DeskView.test.tsx index 9fde039b..79e4413a 100644 --- a/src/app/features/desk/DeskView.test.tsx +++ b/src/app/features/desk/DeskView.test.tsx @@ -291,12 +291,12 @@ describe('DeskEntry', () => { expect(bare(link(0))).toBe('Desk'); expect(link(0)).toContain('href="/desk/void"'); }); - it('is pinned when nothing is published, and when only settled forks exist', () => { - [undefined, { ...STATES.settled, open_count: 0 }].forEach((state) => { - setDeskSource(() => state); - expect(bare(entry('void'))).toBe('Desk'); - expect(entry('void')).toContain('href="/desk/void"'); - }); + it('is omitted when nothing is published, and pinned when settled forks exist', () => { + setDeskSource(() => undefined); + expect(entry('void')).toBe(''); + setDeskSource(() => ({ ...STATES.settled, open_count: 0 })); + expect(bare(entry('void'))).toBe('Desk'); + expect(entry('void')).toContain('href="/desk/void"'); }); it('shows no count before the hash check has landed, so a card about to be withdrawn is never counted', () => { setDeskSource(() => STATES.blocked); diff --git a/src/app/features/desk/DeskView.tsx b/src/app/features/desk/DeskView.tsx index 9cdda8fc..840456f3 100644 --- a/src/app/features/desk/DeskView.tsx +++ b/src/app/features/desk/DeskView.tsx @@ -151,7 +151,7 @@ export function DeskView({ mind, label, list, unverified, now = Date.now() }: De const desk = buildDesk(list, unverified); const skyInk = useSkyInk(); // Slice 1 has no session, so nothing on the desk is the viewer's answer yet. - const mood = deskMood(desk.counts.open, 0); + const mood = deskMood(desk.counts.open); return (
diff --git a/src/app/features/desk/deskMood.test.ts b/src/app/features/desk/deskMood.test.ts index 9c981640..8979f2ad 100644 --- a/src/app/features/desk/deskMood.test.ts +++ b/src/app/features/desk/deskMood.test.ts @@ -4,53 +4,19 @@ import { MOOD_POSE, deskMood } from './deskMood'; describe('deskMood', () => { it('is neutral with the desk clear when nothing is open', () => { - expect(deskMood(0, 0)).toEqual({ + expect(deskMood(0)).toEqual({ mood: 'neutral', pose: 'neutral', line: "Desk's clear. I'll wave when something lands.", }); }); - it('is triumph when every open fork is answered', () => { - expect(deskMood(3, 3).mood).toBe('triumph'); - expect(deskMood(1, 1).mood).toBe('triumph'); - }); - it('is thinking when none is answered, and says whether it is one fork or several', () => { - expect(deskMood(1, 0)).toMatchObject({ mood: 'thinking', line: 'Just one fork on the desk.' }); - expect(deskMood(4, 0)).toMatchObject({ + it('is thinking when forks are open, and says whether it is one fork or several', () => { + expect(deskMood(1)).toMatchObject({ mood: 'thinking', line: 'Just one fork on the desk.' }); + expect(deskMood(4)).toMatchObject({ mood: 'thinking', line: '4 forks on the desk. No rush.', }); }); - it('is determined partway, counting what is left', () => { - expect(deskMood(5, 2)).toMatchObject({ mood: 'determined', line: '3 to go.' }); - }); - it('is happy when the pick is the recommendation', () => { - expect(deskMood(2, 0, { type: 'picked', choice: 'B', recommended: 'B' }).mood).toBe('happy'); - }); - it('is surprised, and asks for a line on why, when the pick differs', () => { - expect(deskMood(2, 0, { type: 'picked', choice: 'A', recommended: 'B' })).toMatchObject({ - mood: 'surprised', - line: expect.stringContaining('A line in the note on why helps'), - }); - }); - it('is surprised, not happy, when there is no recommendation to match', () => { - expect(deskMood(2, 0, { type: 'picked', choice: 'A' }).mood).toBe('surprised'); - }); - it('is note when a pick is cleared, saying the note can carry the answer', () => { - expect(deskMood(2, 1, { type: 'cleared' })).toMatchObject({ - mood: 'note', - line: expect.stringContaining('note can carry the answer on its own'), - }); - }); - it('is concerned when a send failed, even with everything answered', () => { - expect(deskMood(2, 2, { type: 'sendFailed' }).mood).toBe('concerned'); - }); - it('is surprised when a new fork arrives, even on a clear desk', () => { - expect(deskMood(0, 0, { type: 'newFork' })).toMatchObject({ - mood: 'surprised', - line: 'New fork on the desk!', - }); - }); it('maps every mood to a label every Mind in the catalogue can show', () => { Object.values(MOOD_POSE).forEach((pose) => MINDS.forEach((mind) => expect(resolvePose(mind, pose)).toBe(pose)) diff --git a/src/app/features/desk/deskMood.ts b/src/app/features/desk/deskMood.ts index 75d9f23e..dc94d2c2 100644 --- a/src/app/features/desk/deskMood.ts +++ b/src/app/features/desk/deskMood.ts @@ -1,75 +1,27 @@ /** - * The booth Persona's reactions, from the original Fork Desk's mood() and choose() rules. A pure function of - * what is on the desk and the last thing that happened; it is the desk's character, so each rule is tested. + * The booth Persona's reactions while the desk is read-only. A pure function of what is open on + * the desk. */ -/** The original's nine moods. */ -export type Mood = - | 'idle' - | 'neutral' - | 'thinking' - | 'happy' - | 'surprised' - | 'note' - | 'determined' - | 'triumph' - | 'concerned'; - -/** What last happened; `none` means nothing since the page opened or the last event wore off. */ -export type DeskEvent = - | { type: 'none' } - | { type: 'picked'; choice: string; recommended?: string } - | { type: 'cleared' } - | { type: 'sendFailed' } - | { type: 'newFork' }; +export type Mood = 'neutral' | 'thinking'; /** - * Each mood on the shared cast-art labels (neutral, happy, amused, thinking, annoyed, surprised) that every - * Mind has, so the booth never asks a Mind for art it lacks. + * Each mood on the shared cast-art labels (neutral, thinking) that every Mind has, so the booth + * never asks a Mind for art it lacks. */ export const MOOD_POSE: Record = { - idle: 'neutral', neutral: 'neutral', thinking: 'thinking', - happy: 'happy', - surprised: 'surprised', - note: 'thinking', - determined: 'thinking', - triumph: 'happy', - concerned: 'surprised', }; export type DeskMood = { mood: Mood; pose: string; line: string }; const say = (mood: Mood, line: string): DeskMood => ({ mood, pose: MOOD_POSE[mood], line }); -export const deskMood = ( - open: number, - answered: number, - event: DeskEvent = { type: 'none' } -): DeskMood => { - switch (event.type) { - case 'sendFailed': - return say('concerned', "That one didn't save. Give it another try in a moment?"); - case 'newFork': - return say('surprised', 'New fork on the desk!'); - case 'cleared': - return say('note', 'Pick cleared. Your note can carry the answer on its own.'); - case 'picked': - return event.recommended !== undefined && event.choice === event.recommended - ? say('happy', "That's the one I'd have picked too.") - : say('surprised', 'Off-script. A line in the note on why helps the next brief.'); - default: - break; - } +export const deskMood = (open: number): DeskMood => { if (open === 0) return say('neutral', "Desk's clear. I'll wave when something lands."); - if (answered >= open) - return say('triumph', 'All answered! I will carry these back and admit them.'); - if (answered === 0) { - return say( - 'thinking', - open === 1 ? 'Just one fork on the desk.' : `${open} forks on the desk. No rush.` - ); - } - return say('determined', `${open - answered} to go.`); + return say( + 'thinking', + open === 1 ? 'Just one fork on the desk.' : `${open} forks on the desk. No rush.` + ); }; diff --git a/src/app/features/estate/MediaRow.tsx b/src/app/features/estate/MediaRow.tsx index 7d64497a..1c7dfe71 100644 --- a/src/app/features/estate/MediaRow.tsx +++ b/src/app/features/estate/MediaRow.tsx @@ -5,7 +5,7 @@ import { Avatar, Box, Icon, Icons, Text } from 'folds'; import { NavGutter, NavItem, NavItemContent, NavLink } from '../../components/nav'; import { NAV_ROOM_ICON_REST_OPACITY, NavLabel } from '../../components/nav/styles.css'; import { EstateRoom } from './buildEstate'; -import { isFileZone } from '../albums/isFileZone'; +import { isFileZone } from '../albums/buildAlbums'; import { useClientConfig } from '../../hooks/useClientConfig'; import { MINDS } from '../../components/message/pose/poses'; import { useMatrixClient } from '../../hooks/useMatrixClient'; diff --git a/src/app/features/join-before-navigate/JoinBeforeNavigate.tsx b/src/app/features/join-before-navigate/JoinBeforeNavigate.tsx index 43576cff..028cd560 100644 --- a/src/app/features/join-before-navigate/JoinBeforeNavigate.tsx +++ b/src/app/features/join-before-navigate/JoinBeforeNavigate.tsx @@ -10,7 +10,6 @@ import { useMatrixClient } from '../../hooks/useMatrixClient'; import { allRoomsAtom } from '../../state/room-list/roomList'; import { ScreenSize, useScreenSizeContext } from '../../hooks/useScreenSize'; import { BackRouteHandler } from '../../components/BackRouteHandler'; -import { PhoneHit } from '../../styles/PhoneHit.css'; type JoinBeforeNavigateProps = { roomIdOrAlias: string; eventId?: string; viaServers?: string[] }; export function JoinBeforeNavigate({ @@ -39,7 +38,7 @@ export function JoinBeforeNavigate({ {screenSize === ScreenSize.Mobile && ( {(onBack) => ( - + )} diff --git a/src/app/features/lobby/HierarchyItemMenu.tsx b/src/app/features/lobby/HierarchyItemMenu.tsx index cdfa2d8a..1802e3b0 100644 --- a/src/app/features/lobby/HierarchyItemMenu.tsx +++ b/src/app/features/lobby/HierarchyItemMenu.tsx @@ -30,7 +30,6 @@ import { IPowerLevels } from '../../hooks/usePowerLevels'; import { getRoomCreatorsForRoomId } from '../../hooks/useRoomCreators'; import { getRoomPermissionsAPI } from '../../hooks/useRoomPermissions'; import { InviteUserPrompt } from '../../components/invite-user-prompt'; -import { PhoneHitSpread24 } from '../../styles/PhoneHit.css'; type HierarchyItemWithParent = HierarchyItem & { parentId: string; @@ -232,7 +231,6 @@ export function HierarchyItemMenu({ return ( virtualizer.scrollToOffset(0)} variant="SurfaceVariant" radii="Pill" diff --git a/src/app/features/lobby/LobbyHeader.tsx b/src/app/features/lobby/LobbyHeader.tsx index ce248fe5..ed526c68 100644 --- a/src/app/features/lobby/LobbyHeader.tsx +++ b/src/app/features/lobby/LobbyHeader.tsx @@ -38,7 +38,6 @@ import { useOpenSpaceSettings } from '../../state/hooks/spaceSettings'; import { useRoomCreators } from '../../hooks/useRoomCreators'; import { useRoomPermissions } from '../../hooks/useRoomPermissions'; import { InviteUserPrompt } from '../../components/invite-user-prompt'; -import { PhoneHit } from '../../styles/PhoneHit.css'; type LobbyMenuProps = { powerLevels: IPowerLevels; @@ -166,7 +165,7 @@ export function LobbyHeader({ showProfile, powerLevels }: LobbyHeaderProps) { {(onBack) => ( - + )} @@ -241,7 +240,6 @@ export function LobbyHeader({ showProfile, powerLevels }: LobbyHeaderProps) { > {(triggerRef) => ( useMemo( @@ -194,7 +193,6 @@ export function MessageSearch({ virtualizer.scrollToOffset(0)} variant="SurfaceVariant" radii="Pill" diff --git a/src/app/features/room-nav/RoomNavItem.tsx b/src/app/features/room-nav/RoomNavItem.tsx index 8d53ce7f..e8a349f0 100644 --- a/src/app/features/room-nav/RoomNavItem.tsx +++ b/src/app/features/room-nav/RoomNavItem.tsx @@ -66,7 +66,6 @@ import { useAutoDiscoveryInfo } from '../../hooks/useAutoDiscoveryInfo'; import { livekitSupport } from '../../hooks/useLivekitSupport'; import { StateEvent } from '../../../types/matrix/room'; import { webRTCSupported } from '../../utils/rtc'; -import { PhoneHitSpread24 } from '../../styles/PhoneHit.css'; type RoomNavItemMenuProps = { room: Room; @@ -230,7 +229,6 @@ function CallChatToggle() { return ( setChat(!chat)} aria-pressed={chat} aria-label="Toggle Chat" @@ -438,7 +436,6 @@ export function RoomNavItem({ } > {screenSize === ScreenSize.Mobile && ( - + )} diff --git a/src/app/features/room-settings/general/General.tsx b/src/app/features/room-settings/general/General.tsx index e29fe2da..15157304 100644 --- a/src/app/features/room-settings/general/General.tsx +++ b/src/app/features/room-settings/general/General.tsx @@ -15,7 +15,6 @@ import { } from '../../common-settings/general'; import { useRoomCreators } from '../../../hooks/useRoomCreators'; import { useRoomPermissions } from '../../../hooks/useRoomPermissions'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; type GeneralProps = { requestClose: () => void; @@ -36,7 +35,7 @@ export function General({ requestClose }: GeneralProps) { - + diff --git a/src/app/features/room-settings/permissions/Permissions.tsx b/src/app/features/room-settings/permissions/Permissions.tsx index d513dda9..7572a71b 100644 --- a/src/app/features/room-settings/permissions/Permissions.tsx +++ b/src/app/features/room-settings/permissions/Permissions.tsx @@ -9,7 +9,6 @@ import { usePermissionGroups } from './usePermissionItems'; import { PermissionGroups, Powers, PowersEditor } from '../../common-settings/permissions'; import { useRoomCreators } from '../../../hooks/useRoomCreators'; import { useRoomPermissions } from '../../../hooks/useRoomPermissions'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; type PermissionsProps = { requestClose: () => void; @@ -46,7 +45,7 @@ export function Permissions({ requestClose }: PermissionsProps) { - + diff --git a/src/app/features/room/CallChatView.tsx b/src/app/features/room/CallChatView.tsx index fe40eb50..4a10fceb 100644 --- a/src/app/features/room/CallChatView.tsx +++ b/src/app/features/room/CallChatView.tsx @@ -6,7 +6,6 @@ import { Page, PageHeader } from '../../components/page'; import { callChatAtom } from '../../state/callEmbed'; import { RoomView } from './RoomView'; import { ScreenSize, useScreenSizeContext } from '../../hooks/useScreenSize'; -import { PhoneHit } from '../../styles/PhoneHit.css'; export function CallChatView() { const { eventId } = useParams(); @@ -43,7 +42,6 @@ export function CallChatView() { > {(triggerRef) => ( {(triggerRef) => ( setPeopleDrawer(false)} @@ -361,7 +359,6 @@ export function MembersDrawer({ room, members }: MembersDrawerProps) { virtualizer.scrollToOffset(0)} variant="Surface" radii="Pill" diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index 2d63cbf1..257e88ad 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -116,7 +116,6 @@ import { useTheme } from '../../hooks/useTheme'; import { useRoomCreatorsTag } from '../../hooks/useRoomCreatorsTag'; import { usePowerLevelTags } from '../../hooks/usePowerLevelTags'; import { useComposingCheck } from '../../hooks/useComposingCheck'; -import { PhoneHitSpread24, PhoneHitSpread32 } from '../../styles/PhoneHit.css'; interface RoomInputProps { editor: Editor; @@ -606,7 +605,6 @@ export const RoomInput = forwardRef( style={{ padding: `${config.space.S200} ${config.space.S300} 0` }} > setReplyDraft(undefined)} variant="SurfaceVariant" size="300" @@ -640,7 +638,6 @@ export const RoomInput = forwardRef( } before={ pickFile('*')} variant="SurfaceVariant" size="300" @@ -652,7 +649,6 @@ export const RoomInput = forwardRef( after={ <> ( > {!hideStickerBtn && ( setEmojiBoardTab(EmojiBoardTab.Sticker)} variant="SurfaceVariant" @@ -709,7 +704,6 @@ export const RoomInput = forwardRef( )} ( )} - + New Messages diff --git a/src/app/features/room/RoomView.tsx b/src/app/features/room/RoomView.tsx index 0137fd95..35ff6aea 100644 --- a/src/app/features/room/RoomView.tsx +++ b/src/app/features/room/RoomView.tsx @@ -26,7 +26,7 @@ import { useRoom } from '../../hooks/useRoom'; import { AlbumView } from '../albums/AlbumView'; import * as albumCss from '../albums/AlbumView.css'; import { useIsFileZone } from '../albums/useAlbums'; -import { ZoneView, zoneView } from '../albums/zoneView'; +import { ZoneView, zoneView } from '../albums/buildAlbums'; const FN_KEYS_REGEX = /^F\d+$/; const shouldFocusMessageField = (evt: KeyboardEvent): boolean => { diff --git a/src/app/features/room/RoomViewHeader.tsx b/src/app/features/room/RoomViewHeader.tsx index 3132c77a..3534fc00 100644 --- a/src/app/features/room/RoomViewHeader.tsx +++ b/src/app/features/room/RoomViewHeader.tsx @@ -72,7 +72,6 @@ import { RoomSettingsPage } from '../../state/roomSettings'; import { useCallEmbed, useCallStart } from '../../hooks/useCallEmbed'; import { useLivekitSupport } from '../../hooks/useLivekitSupport'; import { webRTCSupported } from '../../utils/rtc'; -import { PhoneHitSpread40 } from '../../styles/PhoneHit.css'; type RoomMenuProps = { room: Room; @@ -337,7 +336,6 @@ function CallButton() { > {(triggerRef) => ( {(onBack) => ( - + @@ -534,7 +532,6 @@ export function RoomViewHeader({ callView }: { callView?: boolean }) { > {(triggerRef) => ( {(triggerRef) => ( {(triggerRef) => ( {(triggerRef) => ( ( )} void; @@ -109,7 +108,7 @@ export function JumpToTime({ onCancel, onSubmit }: JumpToTimeProps) { Jump to Time - + diff --git a/src/app/features/room/message/Message.tsx b/src/app/features/room/message/Message.tsx index a1bc17c9..bdfe88f2 100644 --- a/src/app/features/room/message/Message.tsx +++ b/src/app/features/room/message/Message.tsx @@ -61,8 +61,12 @@ import { import { MessageLayout, MessageSpacing, settingsAtom } from '../../../state/settings'; import { useSetting } from '../../../state/hooks/settings'; import { PoseAvatar } from '../../../components/message/pose/PoseAvatar'; -import { MINDS, mindOfSender } from '../../../components/message/pose/poses'; -import { messagePose } from '../../../components/message/pose/sentiment'; +import { + MINDS, + POSE_KEY, + mindOfSender, + resolvePose, +} from '../../../components/message/pose/poses'; import { useEntranceDelay } from '../../../components/message/pose/entrance'; import { useMatrixClient } from '../../../hooks/useMatrixClient'; import { useRecentEmoji } from '../../../hooks/useRecentEmoji'; @@ -83,10 +87,7 @@ import { useRoomPinnedEvents } from '../../../hooks/useRoomPinnedEvents'; import { MemberPowerTag, StateEvent } from '../../../../types/matrix/room'; import { PowerIcon } from '../../../components/power'; import colorMXID from '../../../../util/colorMXID'; -import { useSkyInk } from '../../../hooks/useTheme'; -import { userColorInk } from '../../scene/skyInk'; import { getPowerTagIconSrc } from '../../../hooks/useMemberPowerTag'; -import { PhoneHitRoom26, PhoneHitSpread32 } from '../../../styles/PhoneHit.css'; export type ReactionHandler = (keyOrMxc: string, shortcode: string) => void; @@ -112,7 +113,7 @@ export const MessageQuickReactions = as<'div', MessageQuickReactionsProps>( {recentEmojis.map((emoji) => ( Delete Message Report Message ( ref ) => { const mx = useMatrixClient(); - const skyInk = useSkyInk(); const useAuthentication = useMediaAuthentication(); const senderId = mEvent.getSender() ?? ''; @@ -758,8 +756,7 @@ export const Message = as<'div', MessageProps>( ? getPowerTagIconSrc(mx, useAuthentication, memberPowerTag.icon) : undefined; - const hashColor = skyInk ? userColorInk(senderId, skyInk) : colorMXID(senderId); - const usernameColor = legacyUsernameColor ? hashColor : tagColor; + const usernameColor = legacyUsernameColor ? colorMXID(senderId) : tagColor; const headerJSX = !collapse && ( ( const poseJSX = !collapse && mind && ( ( } > ( )} ( {!isThreadedMessage && ( onReplyClick(ev, true)} data-event-id={mEvent.getId()} variant="SurfaceVariant" @@ -996,7 +990,6 @@ export const Message = as<'div', MessageProps>( )} {canEditEvent(mx, mEvent) && onEditId && ( onEditId(mEvent.getId())} variant="SurfaceVariant" size="300" @@ -1162,7 +1155,6 @@ export const Message = as<'div', MessageProps>( } > ( } > ( ( } > diff --git a/src/app/features/room/message/styles.css.ts b/src/app/features/room/message/styles.css.ts index 4be501bd..b2d027f6 100644 --- a/src/app/features/room/message/styles.css.ts +++ b/src/app/features/room/message/styles.css.ts @@ -1,5 +1,7 @@ -import { style } from '@vanilla-extract/css'; +import { globalStyle, style } from '@vanilla-extract/css'; import { DefaultReset, config, toRem } from 'folds'; +import { ICON_BUTTON_CLASS } from '../../../../phoneGlyph.css'; +import { MOBILE_BREAKPOINT } from '../../../hooks/useScreenSize'; export const MessageBase = style({ position: 'relative', @@ -24,6 +26,10 @@ export const MessageOptionsBar = style([ }, ]); +globalStyle(`${MessageOptionsBar} .${ICON_BUTTON_CLASS}`, { + '@media': { [`screen and (max-width: ${MOBILE_BREAKPOINT}px)`]: { margin: 9 } }, +}); + export const BubbleAvatarBase = style({ paddingTop: 0, }); diff --git a/src/app/features/room/reaction-viewer/ReactionViewer.tsx b/src/app/features/room/reaction-viewer/ReactionViewer.tsx index b1a674d9..6c686bc5 100644 --- a/src/app/features/room/reaction-viewer/ReactionViewer.tsx +++ b/src/app/features/room/reaction-viewer/ReactionViewer.tsx @@ -28,7 +28,6 @@ import { useMediaAuthentication } from '../../../hooks/useMediaAuthentication'; import { useOpenUserRoomProfile } from '../../../state/hooks/userRoomProfile'; import { useSpaceOptionally } from '../../../hooks/useSpace'; import { getMouseEventCords } from '../../../utils/dom'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; export type ReactionViewerProps = { room: Room; @@ -101,7 +100,7 @@ export const ReactionViewer = as<'div', ReactionViewerProps>( {`Reacted with :${selectedShortcode}:`} - + diff --git a/src/app/features/room/room-pin-menu/RoomPinMenu.tsx b/src/app/features/room/room-pin-menu/RoomPinMenu.tsx index 25fe835f..9986849f 100644 --- a/src/app/features/room/room-pin-menu/RoomPinMenu.tsx +++ b/src/app/features/room/room-pin-menu/RoomPinMenu.tsx @@ -86,7 +86,6 @@ import { useGetMemberPowerTag, } from '../../../hooks/useMemberPowerTag'; import { useRoomCreatorsTag } from '../../../hooks/useRoomCreatorsTag'; -import { PhoneHit, PhoneHitSpread26 } from '../../../styles/PhoneHit.css'; type PinnedMessageProps = { room: Room; @@ -147,7 +146,6 @@ function PinnedMessage({ {canPinEvent && ( ( Pinned Messages - + diff --git a/src/app/features/scene/BackgroundScene.tsx b/src/app/features/scene/BackgroundScene.tsx index 54d48f08..f86138f2 100644 --- a/src/app/features/scene/BackgroundScene.tsx +++ b/src/app/features/scene/BackgroundScene.tsx @@ -1,6 +1,5 @@ import React, { useEffect, useRef } from 'react'; import { useClientConfig } from '../../hooks/useClientConfig'; -import { getFallbackSession } from '../../state/sessions'; import { mountBackgroundScene } from './host'; import { setSceneDrawn } from './sceneDrawn'; import { SceneViewHost } from './SceneViewHost'; @@ -24,7 +23,6 @@ export function BackgroundScene() { const canvas = canvasRef.current; if (!enabled || !canvas) return undefined; const dispose = mountBackgroundScene(config, readCapabilities(navigator), canvas, { - loggedIn: !!getFallbackSession(), onActive: (sky) => setSceneDrawn(true, sky), onInactive: () => setSceneDrawn(false), // eslint-disable-next-line no-console diff --git a/src/app/features/scene/README.md b/src/app/features/scene/README.md index 549510b4..cf979500 100644 --- a/src/app/features/scene/README.md +++ b/src/app/features/scene/README.md @@ -1,10 +1,8 @@ # Background scene -**Default: the ridge scene** (`ridge/`): no per-frame WebGL (the baked cards are lit once per scene build, in a WebGL2 context that is released after). `startBackgroundScene` runs it unless the client -config says `backgroundScene.style: 'raymarch'`; the tier flag still defaults to `off`, and null still -means "keep the CSS ground". Everything below this section describes the opt-in ray-march scene. +The ridge scene (`ridge/`): no per-frame WebGL (the baked cards are lit once per scene build, in a WebGL2 context that is released after). `startBackgroundScene` runs it; the tier flag still defaults to `off`, and null still means "keep the CSS ground". -- `ridge/Ridge.ts` `createRidgeScene({ canvas, tier, probe?, onProbe?, sky?, backdrop? })` returns `{ login, dispose }` or +- `ridge/Ridge.ts` `createRidgeScene({ canvas, tier, sky?, backdrop? })` returns `{ dispose }` or null (tier `off`, no 2D context). It paints the sky (`ridge/physicalSky.ts`, from the `SkyColours` the host passes) into a sky plate (`ridge/skyTurn.ts`): one element over the host canvas, the viewport's width plus its slack of sky each side (20 degrees, more as the turn speeds up: the margin of the speed in force over a tick and 2 s of lateness, and 14 degrees of travel), centred on the heading `heading.ts` owns, holding the sky with the real stars, the moon and the lines baked into it and a twinkle canvas for the swinging stars (`ridge/stars.ts`) over it. The sky is at infinity, so one animation slides the plate by the heading's turn at the cards' px per degree, on the @@ -16,11 +14,6 @@ means "keep the CSS ground". Everything below this section describes the opt-in (`index.ts`). - Paused when the tab is hidden; under `prefers-reduced-motion` the rain is paused and the stars stay at base brightness. `tier: 'still'` paints the sky (facing the heading its pose froze at) and stars into the host canvas and adds no plate, no rain and no loop. -- Cadence guard: for the first 2 s after start (after 5 warm-up frames) rAF intervals are sampled; if their p95 is over - 33 ms the scene settles to a still image (`ridge/probe.ts`) and stops. `?probe=1` (or `probe: true`) keeps sampling - and shows `n / median / p95` in a corner readout. -- `ridge/skyColour.ts` `skyColours()` is the fallback three-stop palette (top, mid, horizon) a scene gets with no `sky` option; the host - passes `ridgeSkyFor` (skyForState.ts) instead. - Ridge cards: `ridge/manifest.ts` `loadManifest` reads `${BASE_URL}public/ridge/index.json` (`skyPlace.ts` `resolvePlaceId` picks the entry: the viewer's choice if the index lists it, else config `backgroundScene.place` if listed, else the index default), then the place's `manifest.json` (schema 3, written by `scripts/ridge-bake/export.py`; it is the one JSON the backdrop reads): the whole 360 degree ring, K G-buffer cards nearest first, each cut into azimuth tiles (32 of 11.25 degrees) of a colour WebP (albedo, @@ -38,24 +31,13 @@ means "keep the CSS ground". Everything below this section describes the opt-in the heading (`ring.ts`), the viewer's offset and the camera's angle on its circle, as a camera on a circle round the bake centre sees it (ruling ridge-camera-on-circle; the offset is signed and clamped by `offsetRange`, the one clamp, by the mode: the forward bound with the camera on its heading, the worst-case bound where it circles; the speed by `maxSpeed`, what the baked resident count sustains, applied to the stored choice). `cameraState.ts` is the one owner of the viewer's mode, speed and offset in `ratatoskr.camera`; `heading.ts` owns the view's pose, the direction, the camera's angle over it and its offset, as one segment (module - state: the pose at a clock, the mode and speed in force and the ease to the pose the choices owe; any change of a choice, a hold, a bound or reduced motion starts a new segment from the pose it has at that clock, `poseAt(t)` is a pure function of it, and a mode pick eases the angle and the offset one after the other, 300 ms each, in the order that keeps every pose inside the bound; `cameraState.ts` hands it each change synchronously before its listeners and keeps no log; `view.ts` `offsetRange`, given to it by the scene, is the one clamp; angles are normalized into [0, 360) before each stretch so nothing grows with uptime; a manual `hold` sets the mode to still, so a rebuild or a reload keeps it). The motion is one `Element.animate` per card (transform only, a - keyframe each second for 30 s and every 50 ms while an ease runs, reissued at 80% and on any change; paused when the tab is hidden or motion is reduced, then constant); a 500 ms timer asks the backdrop for + state: the pose at a clock, and the mode and bounded speed in force; any change of a choice, a hold, a bound or reduced motion starts a new segment from the pose it has at that clock with `phi` and `r` clamped directly, `poseAt(t)` is a pure function of it; `heading.ts` subscribes to `cameraState.ts` and keeps no log; `view.ts` `offsetRange`, given to it by the scene, is the one clamp; angles are normalized into [0, 360) before each stretch so nothing grows with uptime; a manual `hold` sets the mode to still, so a rebuild or a reload keeps it). The motion is one `Element.animate` per card (transform only, a + keyframe each second for 30 s, reissued at 80% and on any change; paused when the tab is hidden or motion is reduced, then constant); a 500 ms timer asks the backdrop for the arc every pose of the next 30 s passes over (`view.ts` `sweepArc`, sampled four times a second, not its two ends) and mounts the tiles it has made. A still draws the sky and the tiles of the arc into the host canvas at the heading now. A failure anywhere (404, a manifest that is not schema 3, no tile that will decode, no WebGL2, a lighting pass that throws) is the sky-only scene on `FALLBACK_VIEW`, told to the host by the live scene alone, through `onPlanesFail` when the live scene has no cards and `onPlanesOk` when a later one has them (never from a stale or disposed build); it is never `onCompileFail`. `vite.config.js` copies `public/ridge` into `dist/public/`. -- `harness/scene/bundle.cjs ridge` builds a standalone page (`?tier=`, `?probe=1`). -- Not yet measured on a phone: see the PR description. - -## Ray-march scene - -A two-pass WebGL2 scene for the client's background canvas: an infinite terrain of CultMath -noise with a world tree at its centre, dusk atmosphere and clouds, and a camera that pulls back -from the tree on login. It is a self-contained module; nothing in the client imports it yet. -Integration (a canvas under the app, `startBackgroundScene`, `login()` when the session starts, -`dispose()`) is Void's cut `terrain-background`; the personas (`orbiting-personas`) and the squirrel -are later cuts. This PR is the render core plus the contract the host needs: flag, tier, failure -callbacks and the creature sizing rule. Nothing has drawn a creature. +- `harness/scene/bundle.cjs ` builds a standalone page (`?tier=`). ## Ridge scene: Vienna and the weather @@ -72,8 +54,7 @@ today's at the place (Night tonight's: the solar midnight nearest, before the da `place.tz`, the IANA zone the baker writes into the manifest (`scripts/ridge-bake/places.json`); the viewer's own zone decides nothing. Auto and the named moments draw today's weather; a free moment draws a clear sky. -`skyState.ts` holds the stores (choice, place, constellation lines) and tells listeners; the choice persists in `ratatoskr.skyChoice`. The key -of the old four-state menu is read once by `skyState.ts` (Day became Noon) and removed. `skyPlace.ts` is the one writer of the place: a scene start loads the manifest of the place `resolvePlaceId` names, the viewer's pick (`placeState.ts`, localStorage `ratatoskr.skyPlace`, per viewer) before the config's place before the index default (nothing else fetches it, so a page with no scene fetches nothing) and the build +`skyState.ts` holds the stores (choice, place, constellation lines) and tells listeners; the choice persists in `ratatoskr.skyChoice`. `skyPlace.ts` is the one writer of the place: a scene start loads the manifest of the place `resolvePlaceId` names, the viewer's pick (`placeState.ts`, localStorage `ratatoskr.skyPlace`, per viewer) before the config's place before the index default (nothing else fetches it, so a page with no scene fetches nothing) and the build settles what it draws, the manifest's place when the cards load, `FALLBACK_VIEW`'s when they do not (a failed manifest, no tile that will decode), so the sky, the weather, the ink and the Auto timer read the place that is drawn. Until a scene has settled it no sky is drawn for ink and the theme's own ink stands. The one timer (Auto, a named moment) tells listeners when the band changes or a named moment's place-local day rolls over. @@ -90,76 +71,6 @@ duration, with the humidity as the fallback when the sun is low (`ridge/weatherF `sceneView.ts` owns whether the fullscreen view is open and which submenu is up (main-chunk safe). The entry is `SceneViewEntry` (`SceneViewEntry.tsx`), the icon button in the navigator and sign-in headers; it preloads the view's chunk on hover or focus. Opening pushes one history entry (so the browser Back button, Escape and Return are the same close), sets `html[data-scene-view]` and makes `#root` inert and hidden while it stays mounted, so the chat keeps its scroll and composer. `SceneViewHost.tsx` (mounted by `BackgroundScene.tsx`) loads `view/SceneView.tsx` as a chunk of its own and mounts it in `#portalContainer`; until it has loaded it stands Return and Escape there, a failed load closes the view, and once the view is gone it gives the focus back to the entry (`restoreEntryFocus`). -The view is a full-viewport turning surface and, top left, a toolbar rail (Return, View, Time, Sky, Place; every icon `PhoneHit`) beside one panel at a time. View (`view/ViewSubmenu.tsx`): rotation mode, speed (bounded by `view.ts` `maxSpeed` for the mode) and the signed parallax offset (`offsetRange`), each written to `cameraState.ts` on release. Time (`view/TimeSubmenu.tsx`): the sky menu's moments and free moment, unchanged, to `skyState.ts` `setSkyChoice`. Sky (`view/SkySubmenu.tsx`): the constellation lines (`setConstellationLines`, the one setter). Place (`view/PlaceSubmenu.tsx`): a carousel of the baked places (`manifest.ts` `listPlaces`: the index's list, each named by its manifest; a card is the name and the place-local time of the moment the sky draws there, `skyMoment.ts` `momentFor` (the clock under Auto, ticking each minute; the picked moment otherwise); swipe, arrows or a tap pick, through `placeState.ts` `setPlaceChoice`; absent while the index lists one place) and every data credit (terrain, stars, lines, and the weather only for a place with a feed; ruling ridge-view-credits-home). A pick makes `index.ts` rebuild the scene, which re-resolves the place; the sky's place in the store (`skyState.ts` `getSkyPlace`, what the carousel, credits and ink read) is written only when that scene is made (`skyPlace.ts` `drawnView`), so a place whose tiles do not come stays pending while the canvas, the carousel and the store keep the place that is up (the loader's own backoff asks again), and a pick of it again gives the pending build up for a fresh one. Return calls `setCamera` with the chosen mode, which ends a hold. +The view is a full-viewport turning surface and, top left, a toolbar rail (Return, View, Time, Sky, Place; folds `IconButton`s) beside one panel at a time. View (`view/ViewSubmenu.tsx`): rotation mode, speed (bounded by `view.ts` `maxSpeed` for the mode) and the signed parallax offset (`offsetRange`), each written to `cameraState.ts` on release. Time (`view/TimeSubmenu.tsx`): the sky menu's moments and free moment, unchanged, to `skyState.ts` `setSkyChoice`. Sky (`view/SkySubmenu.tsx`): the constellation lines (`setConstellationLines`, the one setter). Place (`view/PlaceSubmenu.tsx`): a carousel of the baked places (`manifest.ts` `listPlaces`: the index's list, each named by its manifest; a card is the name and the place-local time of the moment the sky draws there, `skyMoment.ts` `momentFor` (the clock under Auto, ticking each minute; the picked moment otherwise); swipe, arrows or a tap pick, through `placeState.ts` `setPlaceChoice`; absent while the index lists one place) and every data credit (terrain, stars, lines, and the weather only for a place with a feed; ruling ridge-view-credits-home). A pick makes `index.ts` rebuild the scene, which re-resolves the place; the sky's place in the store (`skyState.ts` `getSkyPlace`, what the carousel, credits and ink read) is written only when that scene is made (`skyPlace.ts` `drawnView`), so a place whose tiles do not come stays pending while the canvas, the carousel and the store keep the place that is up (the loader's own backoff asks again), and a pick of it again gives the pending build up for a fresh one. Return calls `setCamera` with the chosen mode, which ends a hold. Manual turning (`view/turning.ts`) happens only inside the view: a one-finger or mouse horizontal drag turns the heading one for one with the far sky (`dh = -dx / (pxPerDegH x plane.scale)`), the arrows 5 degrees (Shift 15), a horizontal wheel or swipe one for one; each event calls `heading.hold`, which re-issues the rig, and the rotation stays held until a mode is picked or Return is pressed. Pitch is never turned. While a pointer is down the panel and rail fade. - -## Entry points - -- `index.ts` `startBackgroundScene(config.backgroundScene, capabilities, options)` is the host's - door. The client config's `backgroundScene.tier` (`off` default, `still`, `low`, `full`) is the - feature flag and the ceiling; `tier.ts` lowers it for `saveData`, low memory or few cores. At - `off` nothing is imported and no canvas context is requested; otherwise `Scene.ts` loads on - demand, so it stays out of the main chunk; if that chunk fails to load the error goes to - `onCompileFail` and the door returns null, it does not throw. -- `Scene.ts` `createScene({ canvas, tier, onCompileFail, onContextLost, ... })` returns - `{ login, dispose }`, or `null` (keep the CSS ground then) when the tier is `off`, WebGL2 is missing, neither - `EXT_color_buffer_float` nor `EXT_color_buffer_half_float` exists (`onUnavailable` says which; with - only the half extension the prepass start target is RGBA16F, written rounded down), or a shader fails to compile (`onCompileFail` gets the - `ShaderCompileError`; programs already linked are freed). `still` is a live rendered frame, not a - baked image: it runs the full pipeline once at the top level and stops; `low` starts the ladder at level 2; `full` at level 0. A lost WebGL context - stops the scene for good and calls `onContextLost`; the scene never rebuilds itself. `host.ts` disposes it, drops - `data-scene` so the CSS ground shows, and starts a fresh scene on `webglcontextrestored`. It caps at 30 fps, pauses when - the tab is hidden, renders 32 frames and stops under `prefers-reduced-motion` (a change of the - preference while it runs freezes or thaws it), and steps down a - quality ladder (`budget.ts`) against a 4 ms GPU budget when timer queries exist. -- `creatures.ts` the creature record and `creatureScale`: a neutral creature is one fixed size and - overrides `sizeBucket`. The bucket names and scales are placeholders until the persona cut owns them. -- `camera.ts` the pull-back path as pure functions (`pullProgress`, `cameraPose`). -- `world.ts` every world number, and the Lipschitz bounds the sphere trace steps by. The GLSL - `#define`s are generated from it; no number is written twice. -- `shaders/` `sdf.glsl` (the distance bound pass 0 and pass 1 share), pass 0 `prepass.frag.glsl`, pass 1 `terrain.frag.glsl`, pass 2 `atmosphere.frag.glsl`, `resolve.frag.glsl` (TAA), - `composite.frag.glsl`, plus CultLib's vendored GLSL (`shaders/README.md`). - -## How it renders - -0. **Cone prepass** (`prepass.frag.glsl`, one texel per 8x8 tile of pass 1): marches one ray per - tile, shrinking each step by the widest any ray of the tile strays from it, so every step is - free for the whole tile. It stores the distance no ray of the tile can have hit before, or - `W_FAR` when the whole tile climbs out above the highest geometry. Pass 1 starts its rays - there. `createScene({ prepass: false })` skips it (the measurement baseline). -1. **Solid pass** (`terrain.frag.glsl`, 0.4-0.75 of canvas resolution): sphere trace of - `min(terrain, tree)`. Terrain height is `mask(r) * (A * fbm + E * phacelle)`, with - `cultmath_fbm_grad(...).w` and `cultmath_phacelle(...).cos.w`. It writes lit colour with - coverage and the hit distance (second render target). -2. **Atmosphere pass** (0.25-0.5 of canvas): closed-form exponential height fog plus a cloud - slab marched with a few jittered steps, both only up to the hit distance from pass 1. -3. **Resolve**: TAA on the atmosphere (Halton jitter, history reprojected by the pass-1 depth, - 3x3 neighbourhood clamp, 1/8 blend; reset on resize, level change and wake). -4. **Composite** at canvas resolution: solid over analytic sky, then the atmosphere, ACES - tonemap, dither. - -`createScene({ onTraceStats })` measures the trace: pass 1 gets a step-count output and an extra -render target, read back every 8th frame through a pixel-pack buffer and a fence (never waited -on), and reports mean steps per pixel. Unset, neither the output nor the target exists. - -## The step bound, and what is not proven - -The trace steps by `(y - h(x, z)) / sqrt(1 + G^2)`, `G` the Lipschitz bound of the height field, -computed from `SNOISE_LIPSCHITZ` (CultMath's constant for `snoise`) in `world.ts`. Above the -envelope (fbm plus the erosion amplitude) the step uses the envelope's bound alone and Phacelle is -not evaluated. - -- The Phacelle gradient bound `phacelleGradBound` (7.0) is Libby's measured sup (6.63 at - |side| = 1.5, n = 0, CultLib PR #1 head 990521b3) plus margin: a measurement, not a proof. - The shader fixes roughness n = 0; a nonzero n needs the bound divided by (1 - n). -- The bound makes grazing rays crawl. A ray that exhausts its steps while still below the highest - terrain is ended as a distant surface (fog hides it). That is a visible approximation, not a - hit proven by the march. -- The low-resolution atmosphere samples pass-1 depth nearest, so silhouettes of near objects - carry a thin fog halo. - -## Measured and not measured - -See the pull request or `harness/scene/README.md` for the numbers and how they were taken. They -come from a software rasterizer, not a GPU, and nothing has been run on a phone. diff --git a/src/app/features/scene/Scene.test.ts b/src/app/features/scene/Scene.test.ts deleted file mode 100644 index 1da90711..00000000 --- a/src/app/features/scene/Scene.test.ts +++ /dev/null @@ -1,449 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, Mock, vi } from 'vitest'; -import { createScene, ShaderCompileError, HALF_START_BIAS, HALF_START_SCALE } from './Scene'; -import { WORLD } from './world'; -import { LEVELS } from './budget'; -import { fragmentSource } from './shaderSource'; -import { startBackgroundScene } from './index'; - -type Fn = Mock; - -/** A GL context where every call is a spy and every constant is 1. Compiles succeed until `failFrom`. */ -function fakeGl(failFrom = Infinity, missing: string[] = []) { - let compiles = 0; - const calls: Record = {}; - const spy = (name: string, impl: (...a: any[]) => unknown = () => ({})): Fn => { - if (!calls[name]) calls[name] = vi.fn(impl); - return calls[name]; - }; - const gl = new Proxy({} as Record, { - get(_, prop: string) { - // the two start-target formats must be told apart; every other constant is 1 - if (prop === 'RGBA32F') return 32; - if (prop === 'RGBA16F') return 16; - if (/^[A-Z][A-Z0-9_]*$/.test(prop)) return 1; - if (prop === 'getExtension') - return spy(prop, (n: string) => (missing.includes(n) ? null : {})); - if (prop === 'compileShader') { - return spy(prop, () => { - compiles += 1; - }); - } - if (prop === 'getShaderParameter') return spy(prop, () => compiles < failFrom); - if (prop === 'getShaderInfoLog') return spy(prop, () => 'ERROR: 0:1: bad'); - if (prop === 'getProgramParameter') return spy(prop, () => true); - return spy(prop); - }, - }); - return { gl: gl as unknown as WebGL2RenderingContext, calls }; -} - -function fakeCanvas(gl: WebGL2RenderingContext | null) { - const canvas = new EventTarget() as EventTarget & { - clientWidth: number; - clientHeight: number; - width: number; - height: number; - getContext: Fn; - }; - canvas.clientWidth = 400; - canvas.clientHeight = 300; - canvas.width = 0; - canvas.height = 0; - canvas.getContext = vi.fn(() => gl); - return canvas; -} - -let rafQueue: Array<(t: number) => void>; -let cancelled: number; -let win: EventTarget; -let motion: EventTarget & { matches: boolean }; -let doc: EventTarget & { visibilityState: string }; - -beforeEach(() => { - rafQueue = []; - cancelled = 0; - motion = Object.assign(new EventTarget(), { matches: false }); - win = Object.assign(new EventTarget(), { - devicePixelRatio: 1, - matchMedia: () => motion, - }); - doc = Object.assign(new EventTarget(), { visibilityState: 'visible' }); - vi.stubGlobal('window', win); - vi.stubGlobal('document', doc); - vi.stubGlobal('requestAnimationFrame', (cb: (t: number) => void) => rafQueue.push(cb)); - vi.stubGlobal('cancelAnimationFrame', () => { - cancelled += 1; - }); -}); - -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; - -describe('createScene tiers', () => { - it("'off' returns null without asking the canvas for a context", () => { - const { gl } = fakeGl(); - const canvas = fakeCanvas(gl); - expect(createScene({ canvas: asCanvas(canvas), tier: 'off' })).toBeNull(); - expect(canvas.getContext).not.toHaveBeenCalled(); - expect(rafQueue).toHaveLength(0); - }); - - it("'still' draws one frame and schedules no more", () => { - const { gl, calls } = fakeGl(); - const scene = createScene({ canvas: asCanvas(fakeCanvas(gl)), tier: 'still' }); - expect(scene).not.toBeNull(); - runFrame(1000); - expect(calls.drawArrays).toHaveBeenCalledTimes(5); // prepass and four passes, one frame - expect(rafQueue).toHaveLength(0); - }); - - it("'still' ignores login(): the pull-back is for a moving scene", () => { - const { gl } = fakeGl(); - const scene = createScene({ canvas: asCanvas(fakeCanvas(gl)), tier: 'still' }); - runFrame(1000); - scene?.login(); - expect(rafQueue).toHaveLength(0); - }); - - it("'full' keeps scheduling frames", () => { - const { gl } = fakeGl(); - createScene({ canvas: asCanvas(fakeCanvas(gl)), tier: 'full' }); - runFrame(1000); - expect(rafQueue).toHaveLength(1); - }); - - it("'low' traces with a cheaper level than 'full'", () => { - const traceSteps = (tier: 'low' | 'full') => { - rafQueue.length = 0; // each call is a fresh scene - const { gl, calls } = fakeGl(); - createScene({ canvas: asCanvas(fakeCanvas(gl)), tier }); - runFrame(1000); - // u_maxSteps is the only uniform1i whose value is a trace-step count - return calls.uniform1i.mock.calls.map((c) => c[1]).filter((v) => v >= 40); - }; - expect(traceSteps('full')).toContain(LEVELS[0].traceSteps); - expect(traceSteps('low')).toContain(LEVELS[2].traceSteps); - expect(traceSteps('low')).not.toContain(LEVELS[0].traceSteps); - }); - - it('returns null when WebGL2 is missing, so the host keeps its ground', () => { - expect(createScene({ canvas: asCanvas(fakeCanvas(null)) })).toBeNull(); - }); -}); - -describe('cone prepass', () => { - const programsFor = (prepass?: boolean) => { - rafQueue.length = 0; - const { gl, calls } = fakeGl(); - createScene({ canvas: asCanvas(fakeCanvas(gl)), prepass }); - return calls.createProgram.mock.calls.length; - }; - - it('is one more program than the baseline, and off means off', () => { - expect(programsFor(true)).toBe(programsFor(false) + 1); - expect(programsFor(undefined)).toBe(programsFor(true)); - }); - - it('draws before pass 1 and only when on', () => { - const drawsFor = (prepass: boolean) => { - rafQueue.length = 0; - const { gl, calls } = fakeGl(); - createScene({ canvas: asCanvas(fakeCanvas(gl)), prepass }); - runFrame(1000); - return calls.drawArrays.mock.calls.length; - }; - expect(drawsFor(true)).toBe(drawsFor(false) + 1); - }); - - it('the trace-step output exists in pass 1 only when the host asked to measure', () => { - expect(fragmentSource('terrain')).not.toContain('TRACE_STATS 1'); - expect(fragmentSource('terrain', '#define TRACE_STATS 1\n')).toContain('#define TRACE_STATS 1'); - }); - - it('reads the step bytes tightly packed, whatever the width', () => { - rafQueue.length = 0; - const { gl, calls } = fakeGl(); - createScene({ canvas: asCanvas(fakeCanvas(gl)), onTraceStats: () => {} }); - runFrame(1000); - // fake constants are all 1: PACK_ALIGNMENT is 1, so a restore to 4 is the only other call - const packs = calls.pixelStorei.mock.calls.map((c) => c[1]); - expect(packs[0]).toBe(1); - expect(packs).toContain(4); - expect(calls.readPixels.mock.invocationCallOrder[0]).toBeGreaterThan( - calls.pixelStorei.mock.invocationCallOrder[0] - ); - }); - - it('shares one distance bound between pass 1 and the prepass', () => { - const bound = (stage: 'terrain' | 'prepass') => - fragmentSource(stage).match(/float sceneDistance\([^)]*\)\s*\{[^}]*\}/)?.[0]; - expect(bound('prepass')).toBeDefined(); - expect(bound('prepass')).toBe(bound('terrain')); - expect(fragmentSource('atmosphere')).not.toContain('sceneDistance'); - }); -}); - -describe('device without EXT_color_buffer_float', () => { - const FLOAT = 'EXT_color_buffer_float'; - const HALF = 'EXT_color_buffer_half_float'; - const build = (missing: string[], extra: Partial[0]> = {}) => { - rafQueue.length = 0; - const { gl, calls } = fakeGl(Infinity, missing); - const onUnavailable = vi.fn(); - const scene = createScene({ canvas: asCanvas(fakeCanvas(gl)), onUnavailable, ...extra }); - if (scene) runFrame(1000); // targets are allocated on the first frame - const formats = calls.texStorage2D?.mock.calls.map((c) => c[2]) ?? []; - const sources = (calls.shaderSource?.mock.calls ?? []).map((c) => c[1] as string); - return { - scene, - onUnavailable, - formats, - prepassSource: sources.find((x) => x.includes('o_start')), - }; - }; - - it('names why the scene is unavailable: no WebGL2, or neither float nor half-float colour buffers', () => { - const none = vi.fn(); - createScene({ canvas: asCanvas(fakeCanvas(null)), onUnavailable: none }); - expect(none).toHaveBeenCalledTimes(1); - expect(none).toHaveBeenCalledWith('no-webgl2'); - const r = build([FLOAT, HALF]); - expect(r.scene).toBeNull(); - expect(r.onUnavailable).toHaveBeenCalledTimes(1); - expect(r.onUnavailable).toHaveBeenCalledWith('no-float-or-half-float-colour-buffer'); - expect(build([]).onUnavailable).not.toHaveBeenCalled(); - }); - - it('with only half-float colour buffers, starts the prepass in an RGBA16F target with the rounding-down write', () => { - const r = build([FLOAT]); - expect(r.scene?.startFormat).toBe('RGBA16F'); - expect(r.formats).not.toContain(32); - expect(r.prepassSource).toContain('#define START_HALF 1'); - expect(r.prepassSource).toContain(`#define START_HALF_SCALE ${HALF_START_SCALE}`); - }); - - it('keeps RGBA32F and the plain write where it is renderable, unless asked for half', () => { - const wide = build([HALF]); - expect(wide.scene?.startFormat).toBe('RGBA32F'); - expect(wide.formats).toContain(32); - expect(wide.prepassSource).not.toContain('#define START_HALF'); - expect(build([], { halfStart: true }).scene?.startFormat).toBe('RGBA16F'); - }); - - // The shader writes max(0, t*SCALE - BIAS) into a half, which rounds to nearest (even); this is - // that rounding. The GPU's rounding of a half write is the unknown a phone must confirm. - const toHalf = (x: number) => { - if (x === 0) return 0; - let e = Math.max(Math.floor(Math.log2(x)), -14); - if (2 ** e > x) e -= 1; - const ulp = 2 ** (e - 10); - const q = x / ulp; - let r = Math.floor(q); - const d = q - r; - if (d > 0.5 || (d === 0.5 && r % 2 === 1)) r += 1; - return r * ulp; - }; - const stored = (t: number) => toHalf(Math.max(0, t * HALF_START_SCALE - HALF_START_BIAS)); - - it('stores a start distance never past the true one, and not much short of it', () => { - let seed = 7; - const rand = () => (seed = (seed * 16807) % 2147483647) / 2147483647; - const ts = [0, 1e-6, 1e-4, 6.1e-5, 0.01, 1, 1023.9, 1024, 2047.9]; - for (let i = 0; i < 20000; i++) ts.push(rand() * WORLD.far, rand() * rand() * 4); - for (let t = 0; t <= WORLD.far; t += 0.37) ts.push(t); - for (const t of ts) { - expect(stored(t)).toBeLessThanOrEqual(t); - expect(t - stored(t)).toBeLessThanOrEqual(t * 0.0021 + 6e-5); - } - }); - - it('holds the miss sentinel W_FAR exactly, so pass 1 still skips a tile the prepass proved empty', () => { - expect(toHalf(WORLD.far)).toBe(WORLD.far); - }); -}); - -describe('shader compile failure', () => { - it('reports through onCompileFail, returns null, and frees the programs already linked', () => { - const { gl, calls } = fakeGl(4); // terrain compiles both shaders; atmosphere's fragment is the 4th and fails - const onCompileFail = vi.fn(); - const scene = createScene({ canvas: asCanvas(fakeCanvas(gl)), onCompileFail }); - expect(scene).toBeNull(); - expect(onCompileFail).toHaveBeenCalledTimes(1); - const err = onCompileFail.mock.calls[0][0] as ShaderCompileError; - expect(err).toBeInstanceOf(ShaderCompileError); - expect(err.stage).toBe('atmosphere'); - expect(err.log).toContain('bad'); - expect(calls.deleteProgram).toHaveBeenCalled(); // the terrain program that did link - expect(rafQueue).toHaveLength(0); - }); - - it('does not throw out of createScene when no callback is given', () => { - const { gl } = fakeGl(0); - expect(() => createScene({ canvas: asCanvas(fakeCanvas(gl)) })).not.toThrow(); - }); -}); - -describe('context loss', () => { - it('stops the loop, tells the host, and detaches every listener', () => { - const { gl } = fakeGl(); - const canvas = fakeCanvas(gl); - const onContextLost = vi.fn(); - createScene({ canvas: asCanvas(canvas), onContextLost }); - const lost = new Event('webglcontextlost', { cancelable: true }); - canvas.dispatchEvent(lost); - expect(lost.defaultPrevented).toBe(true); - expect(onContextLost).toHaveBeenCalledTimes(1); - expect(cancelled).toBe(1); - // listeners are gone: a second loss, a resize and a visibility change do nothing - canvas.dispatchEvent(new Event('webglcontextlost', { cancelable: true })); - win.dispatchEvent(new Event('resize')); - doc.dispatchEvent(new Event('visibilitychange')); - expect(onContextLost).toHaveBeenCalledTimes(1); - expect(rafQueue.length).toBe(1); // only the frame queued before the loss, never run - }); - - it('does not render a queued frame after the loss', () => { - const { gl, calls } = fakeGl(); - const canvas = fakeCanvas(gl); - createScene({ canvas: asCanvas(canvas) }); - canvas.dispatchEvent(new Event('webglcontextlost', { cancelable: true })); - runFrame(1000); - expect(calls.drawArrays).toBeUndefined(); - }); -}); - -describe('prefers-reduced-motion', () => { - const runAll = (t0: number) => { - let t = t0; - let n = 0; - while (rafQueue.length && n < 200) { - runFrame(t); - t += 40; - n += 1; - } - return n; - }; - - it('freezes to a bounded run when the preference turns on mid-flight', () => { - const { gl } = fakeGl(); - createScene({ canvas: asCanvas(fakeCanvas(gl)) }); - runFrame(1000); - expect(rafQueue).toHaveLength(1); // moving: keeps going - motion.matches = true; - motion.dispatchEvent(new Event('change')); - expect(runAll(1040)).toBeLessThan(200); // ends - expect(rafQueue).toHaveLength(0); - }); - - it('thaws a frozen scene when the preference turns off', () => { - motion.matches = true; - const { gl } = fakeGl(); - createScene({ canvas: asCanvas(fakeCanvas(gl)) }); - runAll(1000); - expect(rafQueue).toHaveLength(0); - motion.matches = false; - motion.dispatchEvent(new Event('change')); - expect(rafQueue).toHaveLength(1); - runFrame(5000); - expect(rafQueue).toHaveLength(1); // unbounded again - }); - - it('removes the listener on dispose and on context loss', () => { - const { gl } = fakeGl(); - const scene = createScene({ canvas: asCanvas(fakeCanvas(gl)) }); - scene?.dispose(); - rafQueue.length = 0; - motion.dispatchEvent(new Event('change')); - expect(rafQueue).toHaveLength(0); - - const lostCanvas = fakeCanvas(fakeGl().gl); - createScene({ canvas: asCanvas(lostCanvas) }); - lostCanvas.dispatchEvent(new Event('webglcontextlost', { cancelable: true })); - rafQueue.length = 0; - motion.matches = true; - motion.dispatchEvent(new Event('change')); - expect(rafQueue).toHaveLength(0); - }); - - it('a still does not listen: one frame stays one frame', () => { - const { gl } = fakeGl(); - createScene({ canvas: asCanvas(fakeCanvas(gl)), tier: 'still' }); - runFrame(1000); - motion.matches = false; - motion.dispatchEvent(new Event('change')); - expect(rafQueue).toHaveLength(0); - }); -}); - -describe('startBackgroundScene', () => { - it("does not request a context when the config leaves the tier 'off'", async () => { - const { gl } = fakeGl(); - const canvas = fakeCanvas(gl); - expect(await startBackgroundScene(undefined, {}, { canvas: asCanvas(canvas) })).toBeNull(); - expect( - await startBackgroundScene({ tier: 'off' }, {}, { canvas: asCanvas(canvas) }) - ).toBeNull(); - expect(canvas.getContext).not.toHaveBeenCalled(); - }); - - it('applies the device ceiling: saveData runs a still, one frame', async () => { - const { gl, calls } = fakeGl(); - const scene = await startBackgroundScene( - { tier: 'full', style: 'raymarch' }, - { saveData: true }, - { canvas: asCanvas(fakeCanvas(gl)) } - ); - expect(scene).not.toBeNull(); - runFrame(1000); - expect(calls.drawArrays).toHaveBeenCalledTimes(5); - expect(rafQueue).toHaveLength(0); - }); - - it('reports a failed scene chunk to onCompileFail and returns null instead of throwing', async () => { - vi.resetModules(); - vi.doMock('./Scene', () => { - throw new Error('Failed to fetch dynamically imported module'); - }); - try { - const { startBackgroundScene: start } = await import('./index'); - const onCompileFail = vi.fn(); - const canvas = fakeCanvas(fakeGl().gl); - const scene = await start( - { tier: 'full', style: 'raymarch' }, - {}, - { canvas: asCanvas(canvas), onCompileFail } - ); - expect(scene).toBeNull(); - expect(onCompileFail).toHaveBeenCalledTimes(1); - expect(onCompileFail.mock.calls[0][0]).toBeInstanceOf(Error); - expect(canvas.getContext).not.toHaveBeenCalled(); - // and with no callback it still does not throw - expect( - await start({ tier: 'full', style: 'raymarch' }, {}, { canvas: asCanvas(canvas) }) - ).toBeNull(); - } finally { - vi.doUnmock('./Scene'); - vi.resetModules(); - } - }); - - it('hands compile failure to the host and returns null, the fall to the CSS ground', async () => { - const { gl } = fakeGl(0); - const onCompileFail = vi.fn(); - const scene = await startBackgroundScene( - { tier: 'full', style: 'raymarch' }, - {}, - { canvas: asCanvas(fakeCanvas(gl)), onCompileFail } - ); - expect(scene).toBeNull(); - expect(onCompileFail).toHaveBeenCalledTimes(1); - }); -}); diff --git a/src/app/features/scene/Scene.ts b/src/app/features/scene/Scene.ts deleted file mode 100644 index c2f0423a..00000000 --- a/src/app/features/scene/Scene.ts +++ /dev/null @@ -1,639 +0,0 @@ -import { fragmentSource, vertexSource, Stage } from './shaderSource'; -import { cameraPose, pullProgress, CameraPose } from './camera'; -import { BudgetLadder, Level, LEVELS } from './budget'; -import type { SceneTier } from './tier'; -import { PALETTE } from './palette'; - -/** Phone GPU budget for the whole scene, from the ground-cut doc's budget table. */ -export const GPU_BUDGET_MS = 4.0; -const FRAME_INTERVAL_MS = 1000 / 30; -const REDUCED_MOTION_FRAMES = 32; -const MAX_DPR = 1.5; - -export type PassName = 'terrain' | 'atmosphere' | 'resolve' | 'composite' | 'prepass'; -const PASSES: PassName[] = ['terrain', 'atmosphere', 'resolve', 'composite', 'prepass']; -/** Pass 1 pixels per prepass tile edge. */ -const TILE = 8; - -export interface SceneStats { - /** GPU milliseconds per pass for one finished frame (timer queries; absent without the extension). */ - passMs: Record; - level: number; - solidSize: [number, number]; - atmosphereSize: [number, number]; -} - -/** Trace cost over one finished readback: mean distance evaluations per pass-1 pixel. */ -export interface TraceStats { - /** Mean pass-1 steps per pixel. */ - traceSteps: number; - /** Mean prepass steps per tile; 0 without the prepass. */ - prepassSteps: number; - /** traceSteps plus the prepass's steps spread over the pixels of each tile. */ - stepsPerPixel: number; -} - -/** 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; - -export class ShaderCompileError extends Error { - constructor(readonly stage: Stage | 'vertex', readonly log: string) { - super(`${stage} shader failed to compile:\n${log}`); - } -} - -/** - * Why createScene returned null for want of a device feature. Rendering to half floats needs - * EXT_color_buffer_float or EXT_color_buffer_half_float; the prepass start target is RGBA32F with - * the first and RGBA16F with only the second. - */ -export type SceneUnavailable = 'no-webgl2' | 'no-float-or-half-float-colour-buffer'; - -/** - * The RGBA16F prepass start is written as `t * HALF_START_SCALE - HALF_START_BIAS`. A half rounds - * to nearest with relative error at most 2^-11, so shaving 2^-10 of t leaves the stored value - * below t, and the bias covers the absolute error where halves go subnormal. The shader reads both - * through #defines, so this is the one copy. - */ -export const HALF_START_SCALE = 1 - 1 / 1024; -export const HALF_START_BIAS = 1 / 32768; -const HALF_START_DEFINES = `#define START_HALF 1\n#define START_HALF_SCALE ${HALF_START_SCALE}\n#define START_HALF_BIAS ${HALF_START_BIAS}\n`; - -/** Ladder level a 'low' scene starts at: the cost of a weak device's first 45 frames is never paid at full. */ -const LOW_START_LEVEL = 2; -/** The 'still' tier draws one frame at this level and stops. */ -const STILL_LEVEL = LEVELS[0]; - -export interface SceneOptions { - canvas: HTMLCanvasElement; - /** - * 'off' returns null without touching the canvas. 'still' draws one frame and stops. 'low' starts - * the adaptive ladder low. 'full' starts it at the top. Default 'full'. - */ - tier?: SceneTier; - /** createScene is about to return null because the device lacks a feature, and which one. */ - onUnavailable?: (reason: SceneUnavailable) => void; - /** Force the RGBA16F prepass start target even where RGBA32F is renderable (measurement, tests). */ - halfStart?: boolean; - /** A shader failed to compile or link. createScene frees what it built and returns null. */ - onCompileFail?: (e: ShaderCompileError) => void; - /** The WebGL context was lost. The scene stops for good; the host keeps its ground. */ - onContextLost?: () => void; - /** Called per finished frame when timer queries exist. */ - onStats?: (s: SceneStats) => void; - /** - * Measurement: mean sphere-trace steps per pass-1 pixel, read back every few frames. Setting it - * compiles pass 1 with a step-count output and an extra render target; unset, neither exists. - */ - onTraceStats?: (s: TraceStats) => void; - /** Weather knob, 0 clear .. 1 overcast. */ - coverage?: number; - /** Fixed level instead of the adaptive ladder (measurement). */ - fixedLevel?: Level; - /** Cone prepass that starts pass-1 rays past empty space. Default true; false is the measurement baseline. */ - prepass?: boolean; - /** Hold the camera at this pull-back progress, 0..1, instead of following login (measurement). */ - fixedPull?: number; - /** Ignore the 30 fps cap and the visibility pause (measurement). */ - unthrottled?: boolean; - patchSource?: SourcePatch; -} - -export interface Scene { - /** Texture format of the ray-march scene's prepass start target; the ridge scene has none. */ - readonly startFormat?: 'RGBA32F' | 'RGBA16F'; - /** Start the camera pull-back from the tree. */ - login(): void; - dispose(): void; -} - -function compile( - gl: WebGL2RenderingContext, - type: number, - source: string, - stage: Stage | 'vertex' -): WebGLShader { - const sh = gl.createShader(type)!; - gl.shaderSource(sh, source); - gl.compileShader(sh); - if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) { - const log = gl.getShaderInfoLog(sh) ?? ''; - gl.deleteShader(sh); - throw new ShaderCompileError(stage, log); - } - return sh; -} - -export function linkStage( - gl: WebGL2RenderingContext, - stage: Stage, - patch?: SourcePatch, - defines?: string -): WebGLProgram { - const vs = compile(gl, gl.VERTEX_SHADER, vertexSource, 'vertex'); - const fs = compile( - gl, - gl.FRAGMENT_SHADER, - patch ? patch(stage, fragmentSource(stage, defines)) : fragmentSource(stage, defines), - stage - ); - const prog = gl.createProgram()!; - gl.attachShader(prog, vs); - gl.attachShader(prog, fs); - gl.linkProgram(prog); - gl.deleteShader(vs); - gl.deleteShader(fs); - if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) { - const log = gl.getProgramInfoLog(prog) ?? ''; - gl.deleteProgram(prog); - throw new ShaderCompileError(stage, log); - } - return prog; -} - -interface Target { - tex: WebGLTexture; - w: number; - h: number; -} - -function halton(i: number, base: number): number { - let f = 1; - let r = 0; - let n = i; - while (n > 0) { - f /= base; - r += f * (n % base); - n = Math.floor(n / base); - } - return r; -} - -/** Null when WebGL2 or a float colour buffer is missing (`onUnavailable` says which); the host keeps its CSS ground. */ -export function createScene(opts: SceneOptions): Scene | null { - const { canvas } = opts; - const tier = opts.tier ?? 'full'; - if (tier === 'off') return null; - const gl = canvas.getContext('webgl2', { - antialias: false, - alpha: false, - depth: false, - stencil: false, - powerPreference: 'low-power', - }); - if (!gl) { - opts.onUnavailable?.('no-webgl2'); - return null; - } - const wide = !!gl.getExtension('EXT_color_buffer_float'); - if (!wide && !gl.getExtension('EXT_color_buffer_half_float')) { - opts.onUnavailable?.('no-float-or-half-float-colour-buffer'); - return null; - } - // Every other target is a half; only the prepass start can ask for 32 bits. - const halfStart = opts.halfStart || !wide; - gl.getExtension('OES_texture_float_linear'); - const timer = gl.getExtension('EXT_disjoint_timer_query_webgl2') as { - TIME_ELAPSED_EXT: number; - GPU_DISJOINT_EXT: number; - } | null; - - const usePrepass = opts.prepass ?? true; - const passes = usePrepass ? PASSES : PASSES.filter((p) => p !== 'prepass'); - const programs = {} as Record; - try { - passes.forEach((p) => { - const defines = - p === 'terrain' && opts.onTraceStats - ? '#define TRACE_STATS 1\n' - : p === 'prepass' && halfStart - ? HALF_START_DEFINES - : undefined; - programs[p] = linkStage(gl, p, opts.patchSource, defines); - }); - } catch (e) { - passes.forEach((p) => { - if (programs[p]) gl.deleteProgram(programs[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 vao = gl.createVertexArray(); - gl.bindVertexArray(vao); - - const startFormat = halfStart ? gl.RGBA16F : gl.RGBA32F; - - const makeTarget = (w: number, h: number, format: number, filter: number): Target => { - 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, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); - return { tex, w, h }; - }; - - const fbos = { - solid: gl.createFramebuffer()!, - pre: gl.createFramebuffer()!, - atm: gl.createFramebuffer()!, - hist: [gl.createFramebuffer()!, gl.createFramebuffer()!], - }; - let solid: Target; - let depth: Target; - let steps: Target | undefined; - let startTex: Target; - let atm: Target; - let hist: [Target, Target]; - const freeTargets = () => { - [solid, depth, steps, startTex, atm, hist?.[0], hist?.[1]].forEach((t) => { - if (t) gl.deleteTexture(t.tex); - }); - }; - - const attach = (fbo: WebGLFramebuffer, targets: Target[]) => { - gl.bindFramebuffer(gl.FRAMEBUFFER, fbo); - targets.forEach((t, i) => - gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, t.tex, 0) - ); - gl.drawBuffers(targets.map((_, i) => gl.COLOR_ATTACHMENT0 + i)); - }; - - const still = tier === 'still'; - const ladder = new BudgetLadder(GPU_BUDGET_MS, 45, tier === 'low' ? LOW_START_LEVEL : 0); - const level = (): Level => opts.fixedLevel ?? (still ? STILL_LEVEL : ladder.current); - - // Trace-step readback: one pixel-pack read in flight at a time, polled by fence, never waited on. - // Pass 1's step bytes and the prepass's RGBA floats (g: steps) come back together. - const READBACK_EVERY = 8; - interface Readback { - fence: WebGLSync; - pixels: number; - tiles: number; - } - let readback: Readback | undefined; - const packSteps = opts.onTraceStats ? gl.createBuffer() : null; - const packStart = opts.onTraceStats && usePrepass ? gl.createBuffer() : null; - const discardReadback = () => { - if (readback) gl.deleteSync(readback.fence); - readback = undefined; - }; - const startReadback = () => { - if (!steps || readback) return; - gl.pixelStorei(gl.PACK_ALIGNMENT, 1); // R8 rows are not 4-byte multiples at every width - gl.bindBuffer(gl.PIXEL_PACK_BUFFER, packSteps); - gl.bufferData(gl.PIXEL_PACK_BUFFER, steps.w * steps.h, gl.STREAM_READ); - gl.bindFramebuffer(gl.FRAMEBUFFER, fbos.solid); - gl.readBuffer(gl.COLOR_ATTACHMENT0 + 2); - gl.readPixels(0, 0, steps.w, steps.h, gl.RED, gl.UNSIGNED_BYTE, 0); - let tiles = 0; - if (packStart) { - tiles = startTex.w * startTex.h; - gl.bindBuffer(gl.PIXEL_PACK_BUFFER, packStart); - gl.bufferData(gl.PIXEL_PACK_BUFFER, tiles * 16, gl.STREAM_READ); - gl.bindFramebuffer(gl.FRAMEBUFFER, fbos.pre); - gl.readPixels(0, 0, startTex.w, startTex.h, gl.RGBA, gl.FLOAT, 0); - } - gl.bindBuffer(gl.PIXEL_PACK_BUFFER, null); - gl.pixelStorei(gl.PACK_ALIGNMENT, 4); - readback = { - fence: gl.fenceSync(gl.SYNC_GPU_COMMANDS_COMPLETE, 0)!, - pixels: steps.w * steps.h, - tiles, - }; - }; - const pollReadback = () => { - if (!readback) return; - const status = gl.clientWaitSync(readback.fence, 0, 0); - if (status !== gl.ALREADY_SIGNALED && status !== gl.CONDITION_SATISFIED) return; - const { pixels, tiles } = readback; - const bytes = new Uint8Array(pixels); - gl.bindBuffer(gl.PIXEL_PACK_BUFFER, packSteps); - gl.getBufferSubData(gl.PIXEL_PACK_BUFFER, 0, bytes); - let preSum = 0; - if (packStart) { - const floats = new Float32Array(tiles * 4); - gl.bindBuffer(gl.PIXEL_PACK_BUFFER, packStart); - gl.getBufferSubData(gl.PIXEL_PACK_BUFFER, 0, floats); - for (let i = 1; i < floats.length; i += 4) preSum += floats[i]; - } - gl.bindBuffer(gl.PIXEL_PACK_BUFFER, null); - let sum = 0; - for (let i = 0; i < bytes.length; i += 1) sum += bytes[i]; - discardReadback(); - const traceSteps = sum / pixels; - const prepassSteps = tiles ? preSum / tiles : 0; - opts.onTraceStats?.({ - traceSteps, - prepassSteps, - stepsPerPixel: traceSteps + (prepassSteps * tiles) / pixels, - }); - }; - - let canvasW = 0; - let canvasH = 0; - let sizedFor: Level | undefined; - let resetHistory = true; - - const ensureSize = () => { - const dpr = Math.min(window.devicePixelRatio || 1, MAX_DPR); - const w = Math.max(2, Math.round(canvas.clientWidth * dpr)); - const h = Math.max(2, Math.round(canvas.clientHeight * dpr)); - const lv = level(); - if (w === canvasW && h === canvasH && lv === sizedFor) return; - canvasW = w; - canvasH = h; - sizedFor = lv; - canvas.width = w; - canvas.height = h; - freeTargets(); - const sw = Math.max(2, Math.round(w * lv.solidScale)); - const sh = Math.max(2, Math.round(h * lv.solidScale)); - const aw = Math.max(2, Math.round(w * lv.atmosphereScale)); - const ah = Math.max(2, Math.round(h * lv.atmosphereScale)); - solid = makeTarget(sw, sh, gl.RGBA16F, gl.LINEAR); - depth = makeTarget(sw, sh, gl.R16F, gl.NEAREST); - // Without the prepass pass 1 reads a 1x1 zero start: every ray from the camera, as before. - startTex = usePrepass - ? makeTarget(Math.ceil(sw / TILE), Math.ceil(sh / TILE), startFormat, gl.NEAREST) - : makeTarget(1, 1, startFormat, gl.NEAREST); - steps = opts.onTraceStats ? makeTarget(sw, sh, gl.R8, gl.NEAREST) : undefined; - atm = makeTarget(aw, ah, gl.RGBA16F, gl.LINEAR); - hist = [makeTarget(aw, ah, gl.RGBA16F, gl.LINEAR), makeTarget(aw, ah, gl.RGBA16F, gl.LINEAR)]; - attach(fbos.solid, steps ? [solid, depth, steps] : [solid, depth]); - discardReadback(); - attach(fbos.pre, [startTex]); - attach(fbos.atm, [atm]); - attach(fbos.hist[0], [hist[0]]); - attach(fbos.hist[1], [hist[1]]); - resetHistory = true; - }; - - const reducedMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)'); - const start = performance.now(); - let loginAt: number | undefined; - let frame = 0; - let histIndex = 0; - let prev: CameraPose | undefined; - let raf = 0; - let lastRendered = -Infinity; - let framesLeft = still ? 1 : Infinity; // a still frame, or reduced motion, bounds this - let disposed = false; - - // Timer queries in flight: each holds one pass's query. - const pending: Array<{ q: WebGLQuery; pass: PassName; frame: number }> = []; - const finished = new Map>>(); - - const timed = (pass: PassName, f: number, body: () => void) => { - if (!timer || !opts.onStats) { - body(); - return; - } - const q = gl.createQuery()!; - gl.beginQuery(timer.TIME_ELAPSED_EXT, q); - body(); - gl.endQuery(timer.TIME_ELAPSED_EXT); - pending.push({ q, pass, frame: f }); - }; - - const collect = () => { - if (!timer) return; - while (pending.length && gl.getQueryParameter(pending[0].q, gl.QUERY_RESULT_AVAILABLE)) { - const { q, pass, frame: f } = pending.shift()!; - const disjoint = gl.getParameter(timer.GPU_DISJOINT_EXT); - const ns = gl.getQueryParameter(q, gl.QUERY_RESULT) as number; - gl.deleteQuery(q); - const row = finished.get(f) ?? {}; - if (!disjoint) row[pass] = ns / 1e6; - finished.set(f, row); - if (Object.keys(row).length === passes.length) { - finished.delete(f); - const passMs = { prepass: 0, ...row } as Record; - const total = passes.reduce((s, p) => s + passMs[p], 0); - if (!opts.fixedLevel && ladder.push(total)) sizedFor = undefined; - opts.onStats?.({ - passMs, - level: ladder.index, - solidSize: [solid.w, solid.h], - atmosphereSize: [atm.w, atm.h], - }); - } - } - }; - - const setCommon = (p: WebGLProgram, pose: CameraPose, time: number) => { - const aspect = canvasW / canvasH; - const th = Math.tan(pose.fov / 2); - gl.uniform3fv(loc(p, 'u_camPos'), pose.position as unknown as number[]); - gl.uniformMatrix3fv(loc(p, 'u_camBasis'), false, pose.basis as unknown as number[]); - gl.uniform2f(loc(p, 'u_tanHalf'), th * aspect, th); - gl.uniform1f(loc(p, 'u_time'), time); - gl.uniform3fv(loc(p, 'u_sunDir'), PALETTE.sunDir as unknown as number[]); - gl.uniform3fv(loc(p, 'u_sunColor'), PALETTE.sunColor as unknown as number[]); - gl.uniform3fv(loc(p, 'u_skyTop'), PALETTE.skyTop as unknown as number[]); - gl.uniform3fv(loc(p, 'u_skyHorizon'), PALETTE.skyHorizon as unknown as number[]); - gl.uniform3fv(loc(p, 'u_fogColor'), PALETTE.fogColor as unknown as number[]); - }; - - const bindTex = (unit: number, t: Target, p: WebGLProgram, name: string) => { - gl.activeTexture(gl.TEXTURE0 + unit); - gl.bindTexture(gl.TEXTURE_2D, t.tex); - gl.uniform1i(loc(p, name), unit); - }; - - const draw = () => gl.drawArrays(gl.TRIANGLES, 0, 3); - - const render = (now: number) => { - ensureSize(); - const lv = level(); - const frozen = reducedMotion?.matches ?? false; - const time = frozen ? 0 : (now - start) / 1000; - let elapsed: number | undefined; - if (loginAt !== undefined) elapsed = frozen ? 1e9 : (now - loginAt) / 1000; - const pose = cameraPose(opts.fixedPull ?? pullProgress(elapsed), time); - const f = frame; - frame += 1; - const jx = halton((f % 16) + 1, 2) - 0.5; - const jy = halton((f % 16) + 1, 3) - 0.5; - - // Pass 0: cone march at one ray per 8x8 tile of pass 1, the start distance for its rays. - if (usePrepass) { - timed('prepass', f, () => { - gl.bindFramebuffer(gl.FRAMEBUFFER, fbos.pre); - gl.viewport(0, 0, startTex.w, startTex.h); - const p = programs.prepass; - gl.useProgram(p); - setCommon(p, pose, time); - gl.uniform1i(loc(p, 'u_maxSteps'), lv.traceSteps); - gl.uniform2f(loc(p, 'u_tileHalf'), 0.5 / startTex.w, 0.5 / startTex.h); - draw(); - }); - } - - // Pass 1: solid surfaces, writes colour and depth. - timed('terrain', f, () => { - gl.bindFramebuffer(gl.FRAMEBUFFER, fbos.solid); - gl.viewport(0, 0, solid.w, solid.h); - const p = programs.terrain; - gl.useProgram(p); - setCommon(p, pose, time); - gl.uniform3fv(loc(p, 'u_grass'), PALETTE.grass as unknown as number[]); - gl.uniform3fv(loc(p, 'u_rock'), PALETTE.rock as unknown as number[]); - gl.uniform3fv(loc(p, 'u_bark'), PALETTE.bark as unknown as number[]); - gl.uniform3fv(loc(p, 'u_leaf'), PALETTE.leaf as unknown as number[]); - gl.uniform1i(loc(p, 'u_maxSteps'), lv.traceSteps); - bindTex(0, startTex, p, 'u_start'); - draw(); - }); - if (f % READBACK_EVERY === 0) startReadback(); // outside the timed span: not pass 1's cost - - // Pass 2: atmosphere up to pass 1's depth, low-res. - timed('atmosphere', f, () => { - gl.bindFramebuffer(gl.FRAMEBUFFER, fbos.atm); - gl.viewport(0, 0, atm.w, atm.h); - const p = programs.atmosphere; - gl.useProgram(p); - setCommon(p, pose, time); - bindTex(0, depth, p, 'u_depth'); - gl.uniform1i(loc(p, 'u_steps'), lv.cloudSteps); - gl.uniform1f(loc(p, 'u_frame'), f); - gl.uniform2f(loc(p, 'u_jitter'), jx, jy); - gl.uniform2f(loc(p, 'u_size'), atm.w, atm.h); - gl.uniform1f(loc(p, 'u_coverage'), opts.coverage ?? 0.45); - draw(); - }); - - // TAA resolve into the history that is not being read. - const write = histIndex === 0 ? 1 : 0; - timed('resolve', f, () => { - gl.bindFramebuffer(gl.FRAMEBUFFER, fbos.hist[write]); - gl.viewport(0, 0, atm.w, atm.h); - const p = programs.resolve; - gl.useProgram(p); - setCommon(p, pose, time); - bindTex(0, atm, p, 'u_cur'); - bindTex(1, hist[histIndex], p, 'u_history'); - bindTex(2, depth, p, 'u_depth'); - const pp = prev ?? pose; - const th = Math.tan(pp.fov / 2); - gl.uniform3fv(loc(p, 'u_prevPos'), pp.position as unknown as number[]); - gl.uniformMatrix3fv(loc(p, 'u_prevBasis'), false, pp.basis as unknown as number[]); - gl.uniform2f(loc(p, 'u_prevTanHalf'), th * (canvasW / canvasH), th); - gl.uniform1f(loc(p, 'u_blend'), resetHistory ? 1 : 0.125); - gl.uniform2f(loc(p, 'u_curSize'), atm.w, atm.h); - draw(); - }); - - // Full-resolution composite to the canvas. - timed('composite', f, () => { - gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0, 0, canvasW, canvasH); - const p = programs.composite; - gl.useProgram(p); - setCommon(p, pose, time); - bindTex(0, solid, p, 'u_solid'); - bindTex(1, hist[write], p, 'u_atm'); - gl.uniform1f(loc(p, 'u_frame'), f); - draw(); - }); - - histIndex = write; - prev = pose; - resetHistory = false; - collect(); - pollReadback(); - }; - - const tick = (now: number) => { - raf = 0; - if (disposed) return; - const due = opts.unthrottled || now - lastRendered >= FRAME_INTERVAL_MS - 2; - if (due) { - if ( - !opts.fixedLevel && - !timer && - lastRendered > 0 && - now - lastRendered > FRAME_INTERVAL_MS * 1.5 - ) { - // no timer: a missed cap counts as over budget - if (ladder.push(GPU_BUDGET_MS * 2)) sizedFor = undefined; - } - lastRendered = now; - render(now); - framesLeft -= 1; - } - if (framesLeft > 0 && (opts.unthrottled || document.visibilityState === 'visible')) - raf = requestAnimationFrame(tick); - }; - - const wake = () => { - if (disposed || raf) return; - if (reducedMotion?.matches && framesLeft <= 0) return; - resetHistory = true; // the first frame after a pause has a real elapsed dt - raf = requestAnimationFrame(tick); - }; - const undo: Array<() => void> = []; - const listen = (target: EventTarget, type: string, handler: (e: Event) => void) => { - target.addEventListener(type, handler); - undo.push(() => target.removeEventListener(type, handler)); - }; - const stop = () => { - disposed = true; - if (raf) cancelAnimationFrame(raf); - undo.forEach((f) => f()); - }; - if (!opts.unthrottled) { - listen(document, 'visibilitychange', () => { - if (document.visibilityState === 'visible') wake(); - }); - } - listen(window, 'resize', () => wake()); - // A lost context takes every texture and program with it and nothing here rebuilds them, so the - // scene ends and the host decides what to show. preventDefault is what lets the browser restore - // the context later (without it a lost context stays lost); the host then builds a new scene on - // `webglcontextrestored`, and this one stays dead. - listen(canvas, 'webglcontextlost', (e) => { - e.preventDefault(); - stop(); - opts.onContextLost?.(); - }); - if (reducedMotion?.matches && !still) framesLeft = REDUCED_MOTION_FRAMES; - // The preference can flip while the scene lives: freeze to a bounded run, or thaw to a free one. - if (reducedMotion && !still) { - listen(reducedMotion, 'change', () => { - framesLeft = reducedMotion.matches ? REDUCED_MOTION_FRAMES : Infinity; - wake(); - }); - } - wake(); - - return { - startFormat: halfStart ? 'RGBA16F' : 'RGBA32F', - login() { - if (still || disposed) return; // a still has no pull-back - loginAt = performance.now(); - if (reducedMotion?.matches) framesLeft = REDUCED_MOTION_FRAMES; - wake(); - }, - dispose() { - if (disposed) return; - stop(); - freeTargets(); - passes.forEach((p) => gl.deleteProgram(programs[p])); - discardReadback(); - [packSteps, packStart].forEach((b) => b && gl.deleteBuffer(b)); - gl.deleteVertexArray(vao); - [fbos.solid, fbos.pre, fbos.atm, ...fbos.hist].forEach((fb) => gl.deleteFramebuffer(fb)); - }, - }; -} diff --git a/src/app/features/scene/SceneViewEntry.tsx b/src/app/features/scene/SceneViewEntry.tsx index 941b01b3..9282c10b 100644 --- a/src/app/features/scene/SceneViewEntry.tsx +++ b/src/app/features/scene/SceneViewEntry.tsx @@ -1,6 +1,5 @@ import React from 'react'; import { Icon, IconButton, Icons } from 'folds'; -import { PhoneHit } from '../../styles/PhoneHit.css'; import { useSceneViewOffered } from '../../hooks/useSceneView'; import { loadSceneView, openSceneView } from './sceneView'; @@ -17,7 +16,6 @@ export function SceneViewEntry() { }; return ( { }); describe('the view while its code loads', () => { - it('shows a Return that closes the view, with the phone tap target', () => { + it('shows a Return that closes the view', () => { const ret = walk(SceneViewLoading()).find((e) => e.props?.['aria-label'] === 'Return'); - expect(String(ret?.props?.className)).toContain(PhoneHit); (ret?.props?.onClick as () => void)(); expect(held.closed).toBe(1); }); diff --git a/src/app/features/scene/SceneViewHost.tsx b/src/app/features/scene/SceneViewHost.tsx index ba299a25..70844d41 100644 --- a/src/app/features/scene/SceneViewHost.tsx +++ b/src/app/features/scene/SceneViewHost.tsx @@ -1,7 +1,6 @@ import React, { ComponentType, useEffect, useState } from 'react'; import { createPortal } from 'react-dom'; import { Icon, IconButton, Icons } from 'folds'; -import { PhoneHit } from '../../styles/PhoneHit.css'; import { useSceneViewOffered, useSceneViewState } from '../../hooks/useSceneView'; import { closeSceneView, loadSceneViewOrClose, restoreEntryFocus } from './sceneView'; import * as css from './sceneShell.css'; @@ -23,7 +22,7 @@ export function SceneViewLoading() { }, []); return ( { - it('steps down after a whole window over budget and never back up', () => { - const ladder = new BudgetLadder(4, 5); - Array.from({ length: 4 }).forEach(() => expect(ladder.push(9)).toBe(false)); - expect(ladder.push(9)).toBe(true); - expect(ladder.index).toBe(1); - Array.from({ length: 100 }).forEach(() => ladder.push(0.1)); // fast frames never raise the level - expect(ladder.index).toBe(1); - }); - - it('judges the median, so one slow frame does not step down', () => { - const ladder = new BudgetLadder(4, 5); - [1, 1, 50, 1, 1].forEach((ms) => ladder.push(ms)); - expect(ladder.index).toBe(0); - }); - - it('stops at the last level', () => { - const ladder = new BudgetLadder(4, 1); - Array.from({ length: 20 }).forEach(() => ladder.push(99)); - expect(ladder.index).toBe(LEVELS.length - 1); - }); - - it('every level is cheaper than the one before in each cost axis', () => { - LEVELS.slice(1).forEach((lv, i) => { - const before = LEVELS[i]; - expect(lv.solidScale).toBeLessThan(before.solidScale); - expect(lv.atmosphereScale).toBeLessThan(before.atmosphereScale); - expect(lv.cloudSteps).toBeLessThan(before.cloudSteps); - expect(lv.traceSteps).toBeLessThan(before.traceSteps); - }); - }); - - it('starts at the level it is given, clamped into the ladder', () => { - expect(new BudgetLadder(4, 5, 2).index).toBe(2); - expect(new BudgetLadder(4, 5, 99).index).toBe(LEVELS.length - 1); - expect(new BudgetLadder(4, 5, -3).index).toBe(0); - }); -}); diff --git a/src/app/features/scene/budget.ts b/src/app/features/scene/budget.ts deleted file mode 100644 index 3b373d86..00000000 --- a/src/app/features/scene/budget.ts +++ /dev/null @@ -1,59 +0,0 @@ -// The adaptive step-down. The ladder only descends within a session; nothing here ever steps up. - -export interface Level { - /** Pass 1 resolution as a fraction of the canvas. */ - solidScale: number; - /** Pass 2 resolution as a fraction of the canvas. */ - atmosphereScale: number; - /** Cloud march steps. */ - cloudSteps: number; - /** Sphere-trace step cap. */ - traceSteps: number; -} - -export const LEVELS: readonly Level[] = [ - { solidScale: 0.75, atmosphereScale: 0.5, cloudSteps: 12, traceSteps: 96 }, - { solidScale: 0.6, atmosphereScale: 0.4, cloudSteps: 8, traceSteps: 80 }, - { solidScale: 0.5, atmosphereScale: 0.33, cloudSteps: 6, traceSteps: 64 }, - { solidScale: 0.4, atmosphereScale: 0.25, cloudSteps: 4, traceSteps: 48 }, -]; - -/** Median of the last `window` frame times above `budgetMs` for a whole window steps down one level. */ -export class BudgetLadder { - private level: number; - - private recent: number[] = []; - - private readonly budgetMs: number; - - private readonly window: number; - - /** `startLevel` lets a weak device begin below level 0; it is clamped into the ladder. */ - constructor(budgetMs: number, window = 45, startLevel = 0) { - this.budgetMs = budgetMs; - this.window = window; - this.level = Math.min(Math.max(startLevel, 0), LEVELS.length - 1); - } - - get current(): Level { - return LEVELS[this.level]; - } - - get index(): number { - return this.level; - } - - /** Feed one frame's GPU (or cadence) time. Returns true when the level changed. */ - push(ms: number): boolean { - this.recent.push(ms); - if (this.recent.length < this.window) return false; - const sorted = [...this.recent].sort((a, b) => a - b); - const median = sorted[Math.floor(sorted.length / 2)]; - this.recent = []; - if (median > this.budgetMs && this.level < LEVELS.length - 1) { - this.level += 1; - return true; - } - return false; - } -} diff --git a/src/app/features/scene/camera.test.ts b/src/app/features/scene/camera.test.ts deleted file mode 100644 index f7199a65..00000000 --- a/src/app/features/scene/camera.test.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { cameraPose, pullProgress, PULL_BACK_SECONDS } from './camera'; -import { WORLD } from './world'; - -const dist = (p: readonly [number, number, number]) => Math.hypot(p[0], p[2]); - -describe('login pull-back', () => { - it('is at rest before login and complete after PULL_BACK_SECONDS', () => { - expect(pullProgress(undefined)).toBe(0); - expect(pullProgress(0)).toBe(0); - expect(pullProgress(PULL_BACK_SECONDS)).toBe(1); - expect(pullProgress(PULL_BACK_SECONDS * 10)).toBe(1); - }); - - it('only moves away from the tree and never reverses', () => { - let last = -1; - for (let s = 0; s <= PULL_BACK_SECONDS; s += 0.1) { - const d = dist(cameraPose(pullProgress(s), 0).position); - expect(d).toBeGreaterThanOrEqual(last); - last = d; - } - }); - - it('ends over the flat ground so it cannot be inside the terrain, whatever the orbit angle', () => { - for (let t = 0; t < 2000; t += 37) { - expect(dist(cameraPose(1, t).position)).toBeLessThan(WORLD.plateauInner); - } - }); - - it('looks at the tree: forward points at the axis and the basis is orthonormal', () => { - const pose = cameraPose(0.5, 12); - const [rx, ry, rz, ux, uy, uz, fx, fy, fz] = pose.basis; - const dot = (a: number[], b: number[]) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; - expect(dot([rx, ry, rz], [ux, uy, uz])).toBeCloseTo(0, 6); - expect(dot([rx, ry, rz], [fx, fy, fz])).toBeCloseTo(0, 6); - expect(dot([ux, uy, uz], [fx, fy, fz])).toBeCloseTo(0, 6); - expect(Math.hypot(fx, fy, fz)).toBeCloseTo(1, 6); - // Forward points back across the tree axis, not away from it. - const [px, , pz] = pose.position; - expect(fx * px + fz * pz).toBeLessThan(0); - }); -}); diff --git a/src/app/features/scene/camera.ts b/src/app/features/scene/camera.ts deleted file mode 100644 index 2b08f0d1..00000000 --- a/src/app/features/scene/camera.ts +++ /dev/null @@ -1,56 +0,0 @@ -// The scene's camera: close under the tree at rest, pulled back on login, drifting after. -// Pure functions of time so the pull-back is testable without a GL context. - -export type Vec3 = readonly [number, number, number]; - -export interface CameraPose { - position: Vec3; - /** Column-major right, up, forward: the layout of the shader's mat3 uniform. */ - basis: readonly [number, number, number, number, number, number, number, number, number]; - /** Vertical field of view in radians. */ - fov: number; -} - -export const PULL_BACK_SECONDS = 6; - -// Keep the end distance inside WORLD.plateauInner so the camera is always over flat ground. -const NEAR = { radius: 20, camY: 5, targetY: 34, fov: 1.15 }; -const FAR = { radius: 110, camY: 50, targetY: 36, fov: 0.82 }; -const DRIFT_RAD_PER_SEC = 0.025; - -const smoother = (x: number) => x * x * x * (x * (x * 6 - 15) + 10); -const lerp = (a: number, b: number, t: number) => a + (b - a) * t; - -/** 0 before login, easing to 1 over PULL_BACK_SECONDS. `elapsed` is seconds since login. */ -export function pullProgress(elapsed: number | undefined): number { - if (elapsed === undefined || elapsed <= 0) return 0; - return smoother(Math.min(1, elapsed / PULL_BACK_SECONDS)); -} - -function norm(v: Vec3): Vec3 { - const l = Math.hypot(v[0], v[1], v[2]) || 1; - return [v[0] / l, v[1] / l, v[2] / l]; -} -function cross(a: Vec3, b: Vec3): Vec3 { - return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]; -} - -/** - * @param pull 0..1 from pullProgress - * @param time seconds since the scene started, for the slow orbit - */ -export function cameraPose(pull: number, time: number): CameraPose { - const radius = lerp(NEAR.radius, FAR.radius, pull); - const camY = lerp(NEAR.camY, FAR.camY, pull); - const targetY = lerp(NEAR.targetY, FAR.targetY, pull); - const azimuth = 0.9 + time * DRIFT_RAD_PER_SEC; - const position: Vec3 = [radius * Math.cos(azimuth), camY, radius * Math.sin(azimuth)]; - const forward = norm([-position[0], targetY - position[1], -position[2]]); - const right = norm(cross([0, 1, 0], forward)); - const up = cross(forward, right); - return { - position, - basis: [...right, ...up, ...forward] as unknown as CameraPose['basis'], - fov: lerp(NEAR.fov, FAR.fov, pull), - }; -} diff --git a/src/app/features/scene/cameraState.test.ts b/src/app/features/scene/cameraState.test.ts index 6bbb9f02..c09331c1 100644 --- a/src/app/features/scene/cameraState.test.ts +++ b/src/app/features/scene/cameraState.test.ts @@ -1,7 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import * as camera from './cameraState'; import { - bindOwner, CAMERA_KEY, DEFAULT_CAMERA, effectiveMode, @@ -74,23 +72,6 @@ describe('the viewer camera', () => { expect(cb).toHaveBeenCalledWith({ ...DEFAULT_CAMERA, mode: 'offset' }, DEFAULT_CAMERA, 1234, false); }); - it('hands a change to the owner before any listener, at its clock, whenever the listeners registered, and keeps no log of it', () => { - const order: string[] = []; - subscribe(() => order.push('early')); - bindOwner((at) => order.push(`owner ${at}`)); - subscribe(() => order.push('late')); - setCamera({ offsetM: 5 }, 42); - holdCamera(43); - setCamera({ mode: 'both' }, 44); // picking a mode ends the hold - setCamera({ offsetM: 5 }, 45); // nothing changed - expect(order).toEqual(['owner 42', 'early', 'late', 'owner 43', 'early', 'late', 'owner 44', 'early', 'late']); - resetCamera(); // a reload of the choice does not unbind the owner: it outlives the scenes - setCamera({ offsetM: 9 }, 50); - expect(order.at(-1)).toBe('owner 50'); - expect(Object.keys(camera)).not.toContain('takeChanges'); - bindOwner(undefined); - }); - it('a hold is session state: the mode in effect is still, the chosen mode is untouched and stored as chosen, and a reload does not hold', () => { setCamera({ mode: 'offset', speedDegPerS: 2 }); const cb = vi.fn(); diff --git a/src/app/features/scene/cameraState.ts b/src/app/features/scene/cameraState.ts index 8d09216b..a85e4188 100644 --- a/src/app/features/scene/cameraState.ts +++ b/src/app/features/scene/cameraState.ts @@ -2,8 +2,10 @@ // chosen mode, speed and offset (persisted, never rewritten by anything but the viewer: the clamp on the offset, `ridge/view.ts` `offsetRange`, and the bound // on the speed, `maxSpeed`, are derived from them at read for the mode and the bake in force) and of the hold: a manual turn (`ridge/heading.ts` `hold`) makes the // mode in effect 'still' until the viewer picks a mode, the one already chosen included. The hold is session state: a rebuild keeps it, a reload does not -// (a reload is a Return). `ridge/heading.ts` integrates the view direction over the mode in effect. Main-chunk safe (no ridge code is imported at runtime), as placeState and skyState are. -import type { RotationMode } from './ridge/heading'; +// (a reload is a Return). `ridge/heading.ts` integrates the view direction over the mode in effect. Main-chunk safe (no ridge code is imported at runtime). + +/** `still`: nothing turns. `offset`: the camera circles the centre, the view direction stays. `both`: the view direction turns and the camera with it. */ +export type RotationMode = 'still' | 'offset' | 'both'; export const CAMERA_KEY = 'ratatoskr.camera'; @@ -52,15 +54,6 @@ let current: CameraChoice | undefined; type Listener = (next: CameraChoice, prev: CameraChoice, at: number, wasHeld: boolean) => void; let held = false; const listeners = new Set(); -/** - * The one reader that must have taken a change before anyone else hears of it: the heading owner (`ridge/heading.ts`), which starts a new segment of the view's - * motion at the clock `at`. Called synchronously by the change, before every listener, so no order of registration can put a listener ahead of it, and nothing is - * queued. Cleared by nothing: the owner outlives the scenes and the choice. - */ -let owner: ((at: number) => void) | undefined; -export const bindOwner = (cb: ((at: number) => void) | undefined): void => { - owner = cb; -}; const clock = (): number => (typeof performance !== 'undefined' ? performance.now() : Date.now()); function load(): CameraChoice { @@ -98,7 +91,6 @@ export function setCamera(change: Partial, at: number = clock()): // Storage is refused: the choice holds for this page load only. } } - owner?.(at); [...listeners].forEach((cb) => cb(next, prev, at, wasHeld)); } @@ -113,7 +105,6 @@ export function holdCamera(at: number = clock()): void { if (held) return; held = true; const cam = getCamera(); - owner?.(at); [...listeners].forEach((cb) => cb(cam, cam, at, false)); } diff --git a/src/app/features/scene/creatures.test.ts b/src/app/features/scene/creatures.test.ts deleted file mode 100644 index 00dd48ef..00000000 --- a/src/app/features/scene/creatures.test.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { BUCKET_SCALE, creatureScale, SizeBucket } from './creatures'; - -const buckets: SizeBucket[] = ['small', 'medium', 'large']; - -describe('creature scale', () => { - it('follows sizeBucket for a creature with an estate', () => { - buckets.forEach((sizeBucket) => - expect(creatureScale({ sizeBucket, neutral: false })).toBe(BUCKET_SCALE[sizeBucket]) - ); - }); - - it('draws nothing for a neutral creature, whatever sizeBucket it was sent', () => { - expect(creatureScale({ neutral: true })).toBeNull(); - buckets.forEach((sizeBucket) => - expect(creatureScale({ sizeBucket, neutral: true })).toBeNull() - ); - }); - - it('does not crash or default to medium when a non-neutral creature has no sizeBucket', () => { - expect(creatureScale({ neutral: false })).toBeNull(); - expect(creatureScale({ sizeBucket: undefined, neutral: false })).toBeNull(); - }); - - it('draws nothing for an unknown bucket, including inherited property names', () => { - expect(creatureScale({ sizeBucket: 'huge' as SizeBucket, neutral: false })).toBeNull(); - expect(creatureScale({ sizeBucket: 'toString' as SizeBucket, neutral: false })).toBeNull(); - }); -}); diff --git a/src/app/features/scene/creatures.ts b/src/app/features/scene/creatures.ts deleted file mode 100644 index d88ce4b5..00000000 --- a/src/app/features/scene/creatures.ts +++ /dev/null @@ -1,39 +0,0 @@ -// Creature sizing for the orbiting personas. Only the rule lives here; drawing them is a later cut. -// -// Props contract: heimdall-body:follow_up:ratatoskr-creature-projection-v2 (against GameCult/Bifrost; supersedes heimdall-body/ratatoskr-creature-projection). -// Nothing here is binding until Bifrost's steward cuts that contract. -// -// Shape: {id, estate, neutral, activity} plus sizeBucket when neutral is false. -// Invariants: -// - Exact vote weights stay in Bifrost; Ratatoskr only ever sees a bucket. -// - neutral=true means Bifrost publishes no sizeBucket, no kind and no energy. A received value is -// ignored, and a neutral creature is not drawn. -// - A missing or unknown sizeBucket is not drawn either; no size is ever defaulted. -// - activity comes from the Heimdall session. -// Consent: humans get a coarse bucket by default plus a typed opt-out; Minds and Personas may show finer buckets. -// Humans have three coarse buckets. The scales below (0.7 / 1 / 1.4) are placeholders, not fixed. - -export type SizeBucket = 'small' | 'medium' | 'large'; - -export interface Creature { - id: string; - estate: string; - /** Absent when neutral. Read it only through creatureScale. */ - sizeBucket?: SizeBucket; - neutral: boolean; - activity: 'idle' | 'active'; -} - -export const BUCKET_SCALE: Readonly> = { - small: 0.7, - medium: 1, - large: 1.4, -}; - -/** The draw scale, or null when nothing is drawn: a neutral creature, or a bucket that is absent or unknown. */ -export function creatureScale(c: Pick): number | null { - if (c.neutral || c.sizeBucket === undefined) return null; - return Object.prototype.hasOwnProperty.call(BUCKET_SCALE, c.sizeBucket) - ? BUCKET_SCALE[c.sizeBucket] - : null; -} diff --git a/src/app/features/scene/cultmathTrim.test.ts b/src/app/features/scene/cultmathTrim.test.ts deleted file mode 100644 index cef6b281..00000000 --- a/src/app/features/scene/cultmathTrim.test.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { trimGlsl } from './cultmathTrim'; -import { fragmentSource, Stage } from './shaderSource'; -import cultmath from './shaders/CultMath.glsl?raw'; - -const LIB = `// header -#ifndef LIB_GLSL -#define LIB_GLSL -const float LIB_PI = 3.14; - -float lib_half(float v) { return v * 0.5; } -vec2 lib_half(vec2 v) { return v * 0.5; } - -// uses the constant and an overload set -float lib_pi_half(float v) { return lib_half(v) * LIB_PI; } - -struct LibPair { float a; float b; }; - -LibPair lib_pair(float v) { LibPair p; p.a = v; p.b = lib_half(v); return p; } -float lib_unused(float v) { return v; } -#endif -`; - -describe('trimGlsl', () => { - it('keeps what a root names and what that reaches, and drops the rest', () => { - const out = trimGlsl(LIB, ['float x = lib_pi_half(1.0);']); - expect(out).toContain('lib_pi_half'); - expect(out).toContain('LIB_PI'); - expect(out).toContain('float lib_half'); - expect(out).toContain('vec2 lib_half'); // overloads stay together - expect(out).not.toContain('lib_unused'); - expect(out).not.toContain('LibPair'); - expect(out).not.toContain('lib_pair'); - }); - - it('keeps a struct that a kept function returns', () => { - const out = trimGlsl(LIB, ['LibPair p = lib_pair(1.0);']); - expect(out).toContain('struct LibPair'); - expect(out).toContain('lib_half'); - expect(out).not.toContain('lib_pi_half'); - }); - - it('keeps the include guard balanced', () => { - const out = trimGlsl(LIB, ['lib_half(1.0)']); - expect(out).toMatch(/^#ifndef LIB_GLSL\n#define LIB_GLSL\n/); - expect(out.trimEnd().endsWith('#endif')).toBe(true); - }); - - it('keeps nothing but the guard for a root that names nothing', () => { - const out = trimGlsl(LIB, ['void main() {}']); - expect(out).not.toContain('lib_'); - expect(out).toContain('#ifndef LIB_GLSL'); - }); -}); - -describe('CultMath per shader stage', () => { - const stages: Stage[] = ['terrain', 'atmosphere', 'resolve', 'composite']; - const cultmathNames = (text: string) => new Set(text.match(/\bcultmath_\w+/g) ?? []); - const defined = (src: string, name: string) => - new RegExp(`^\\s*(?:float|vec[234]|mat3|int|\\w+)\\s+${name}\\s*\\(`, 'm').test(src); - - it.each(stages)('%s defines every CultMath function it, or Phacelle, calls', (stage) => { - const src = fragmentSource(stage); - cultmathNames(src).forEach((n) => expect(defined(src, n), n).toBe(true)); - }); - - it.each(stages)('%s is smaller than the whole library', (stage) => { - expect(fragmentSource(stage).length).toBeLessThan(cultmath.length / 2); - }); - - it('puts the noise a stage calls in that stage and not in the others', () => { - expect(fragmentSource('terrain')).toContain('cultmath_snoise'); - expect(fragmentSource('composite')).not.toContain('cultmath_snoise'); - }); - - it('adds Phacelle to terrain alone, as its own file', () => { - expect(fragmentSource('terrain')).toContain('cultmath_phacelle'); - stages - .filter((s) => s !== 'terrain') - .forEach((s) => expect(fragmentSource(s)).not.toContain('cultmath_phacelle')); - }); -}); diff --git a/src/app/features/scene/cultmathTrim.ts b/src/app/features/scene/cultmathTrim.ts deleted file mode 100644 index fc246e5c..00000000 --- a/src/app/features/scene/cultmathTrim.ts +++ /dev/null @@ -1,81 +0,0 @@ -/** - * Keeps the part of CultMath's GLSL that a stage can reach. The vendored file is whole and never - * edited; each stage compiles only the declarations its own source (and the source concatenated - * beside it) names, directly or through other kept declarations. Overloads share a name and are - * kept together. - */ - -interface Decl { - name: string; - text: string; -} - -const GUARD_OPEN = /^#ifndef\s+\w+\s*\n#define\s+\w+\s*\n/m; -const GUARD_CLOSE = /\n#endif\s*$/; - -/** Name a top-level declaration defines: function, struct or const. */ -function declName(text: string): string | undefined { - const code = text.replace(/\/\/.*$/gm, ''); - if (!code.includes('{')) return /\b(\w+)\s*=/.exec(code)?.[1]; - return /\bstruct\s+(\w+)/.exec(code)?.[1] ?? /\b(\w+)\s*\(/.exec(code)?.[1]; -} - -/** Splits at brace depth 0: a declaration ends at the `;` or `}` that returns to depth 0. */ -function declarations(body: string): Decl[] { - const out: Decl[] = []; - let depth = 0; - let start = 0; - let i = 0; - while (i < body.length) { - const c = body[i]; - if (c === '/' && body[i + 1] === '/') { - const eol = body.indexOf('\n', i); - i = eol < 0 ? body.length : eol; - } else if (c === '{') { - depth += 1; - } else if ((c === '}' || c === ';') && depth - (c === '}' ? 1 : 0) === 0) { - if (c === '}') depth -= 1; - // a struct's closing brace is followed by `;` - const end = c === '}' && /^\s*;/.test(body.slice(i + 1)) ? body.indexOf(';', i) : i; - const text = body.slice(start, end + 1); - const name = declName(text); - if (name) out.push({ name, text }); - start = end + 1; - i = end; - } else if (c === '}') { - depth -= 1; - } - i += 1; - } - return out; -} - -const idents = (text: string): string[] => text.match(/\b[A-Za-z_]\w*\b/g) ?? []; - -/** `library` trimmed to what `roots` reach; the include guard is kept. */ -export function trimGlsl(library: string, roots: string[]): string { - const open = GUARD_OPEN.exec(library)?.[0] ?? ''; - const close = GUARD_CLOSE.test(library) ? '\n#endif\n' : ''; - const body = library - .slice(open ? library.indexOf(open) + open.length : 0) - .replace(GUARD_CLOSE, ''); - const decls = declarations(body); - const byName = new Map(); - decls.forEach((d) => byName.set(d.name, [...(byName.get(d.name) ?? []), d])); - - const kept = new Set(); - const queue = roots.flatMap(idents); - while (queue.length) { - const group = byName.get(queue.pop() ?? ''); - group?.forEach((d) => { - if (kept.has(d)) return; - kept.add(d); - queue.push(...idents(d.text)); - }); - } - const text = decls - .filter((d) => kept.has(d)) - .map((d) => d.text.replace(/^\s*\n/, '')) - .join('\n'); - return `${open}${text}${close}`; -} diff --git a/src/app/features/scene/debugOverlays.test.ts b/src/app/features/scene/debugOverlays.test.ts deleted file mode 100644 index e1a4e61e..00000000 --- a/src/app/features/scene/debugOverlays.test.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { debugOverlaysAllowed, overlayRequested } from './debugOverlays'; - -let search = ''; -beforeEach(() => { - search = ''; - vi.stubGlobal('window', { - get location() { - return { search }; - }, - }); -}); -afterEach(() => { - vi.unstubAllGlobals(); - vi.unstubAllEnvs(); -}); - -describe('debugOverlaysAllowed', () => { - it('a production build allows nothing by default', () => { - vi.stubEnv('DEV', false); - vi.stubEnv('VITE_PREVIEW_DEMO', ''); - expect(debugOverlaysAllowed(undefined)).toBe(false); - expect(debugOverlaysAllowed({ tier: 'full' })).toBe(false); - expect(debugOverlaysAllowed({ tier: 'full', debugOverlays: false })).toBe(false); - }); - - it('a dev build, a demo preview build or an explicit config flag allows them', () => { - vi.stubEnv('DEV', true); - expect(debugOverlaysAllowed(undefined)).toBe(true); - vi.stubEnv('DEV', false); - vi.stubEnv('VITE_PREVIEW_DEMO', '1'); - expect(debugOverlaysAllowed(undefined)).toBe(true); - vi.stubEnv('VITE_PREVIEW_DEMO', ''); - expect(debugOverlaysAllowed({ debugOverlays: true })).toBe(true); - }); -}); - -describe('overlayRequested', () => { - it('needs both the query and the permission', () => { - search = '?probe=1'; - expect(overlayRequested('probe', true)).toBe(true); - expect(overlayRequested('probe', false)).toBe(false); - expect(overlayRequested('tierlabel', true)).toBe(false); - search = '?tierlabel=1'; - expect(overlayRequested('tierlabel', true)).toBe(true); - search = ''; - expect(overlayRequested('probe', true)).toBe(false); - }); -}); diff --git a/src/app/features/scene/debugOverlays.ts b/src/app/features/scene/debugOverlays.ts deleted file mode 100644 index a02d9e92..00000000 --- a/src/app/features/scene/debugOverlays.ts +++ /dev/null @@ -1,15 +0,0 @@ -import type { BackgroundSceneConfig } from './tier'; - -/** - * Whether the page URL may switch on the scene's diagnostic overlays (`?probe=1` frame readout, `?tierlabel=1` path - * label). Only a dev build, a demo preview build (VITE_PREVIEW_DEMO=1), or a config that says `debugOverlays: true` - * allows it; a production visitor adding a query string gets nothing. - */ -export const debugOverlaysAllowed = (config: BackgroundSceneConfig | undefined): boolean => - import.meta.env?.DEV === true || - import.meta.env?.VITE_PREVIEW_DEMO === '1' || - config?.debugOverlays === true; - -/** The page URL asks for this overlay (`?name=1`), and the overlays are allowed. */ -export const overlayRequested = (name: 'probe' | 'tierlabel', allowed: boolean): boolean => - allowed && new URLSearchParams(window.location.search).get(name) === '1'; diff --git a/src/app/features/scene/host.test.ts b/src/app/features/scene/host.test.ts index d5514d52..1e81aa5a 100644 --- a/src/app/features/scene/host.test.ts +++ b/src/app/features/scene/host.test.ts @@ -10,10 +10,9 @@ const config = { tier: 'low' as const }; const caps = { hardwareConcurrency: 8 }; function fakeScene(): Scene & { - login: ReturnType; dispose: ReturnType; } { - return { login: vi.fn(), dispose: vi.fn() }; + return { dispose: vi.fn() }; } const flush = () => new Promise((r) => { @@ -33,7 +32,7 @@ describe('mountBackgroundScene', () => { const scene = fakeScene(); startBackgroundScene.mockResolvedValue(scene); const onActive = vi.fn(); - mountBackgroundScene(config, caps, canvas, { loggedIn: false, onActive }); + mountBackgroundScene(config, caps, canvas, { onActive }); await flush(); expect(startBackgroundScene).toHaveBeenCalledWith( config, @@ -41,13 +40,12 @@ describe('mountBackgroundScene', () => { expect.objectContaining({ canvas }) ); expect(onActive).toHaveBeenCalledOnce(); - expect(scene.login).not.toHaveBeenCalled(); }); it('tells onActive the sky the started scene draws', async () => { startBackgroundScene.mockResolvedValue({ ...fakeScene(), drawnSky: 'dusk' }); const onActive = vi.fn(); - mountBackgroundScene(config, caps, canvas, { loggedIn: false, onActive }); + mountBackgroundScene(config, caps, canvas, { onActive }); await flush(); expect(onActive).toHaveBeenCalledWith('dusk'); }); @@ -55,14 +53,14 @@ describe('mountBackgroundScene', () => { it('disposes the scene on unmount, once', async () => { const scene = fakeScene(); startBackgroundScene.mockResolvedValue(scene); - const dispose = mountBackgroundScene(config, caps, canvas, { loggedIn: false }); + const dispose = mountBackgroundScene(config, caps, canvas, {}); await flush(); dispose(); dispose(); expect(scene.dispose).toHaveBeenCalledOnce(); }); - it('disposes a scene that resolves after unmount, without activating or logging in', async () => { + it('disposes a scene that resolves after unmount, without activating', async () => { const scene = fakeScene(); let resolve!: (s: Scene) => void; startBackgroundScene.mockReturnValue( @@ -71,19 +69,18 @@ describe('mountBackgroundScene', () => { }) ); const onActive = vi.fn(); - const dispose = mountBackgroundScene(config, caps, canvas, { loggedIn: true, onActive }); + const dispose = mountBackgroundScene(config, caps, canvas, { onActive }); dispose(); resolve(scene); await flush(); expect(scene.dispose).toHaveBeenCalledOnce(); - expect(scene.login).not.toHaveBeenCalled(); expect(onActive).not.toHaveBeenCalled(); }); it('leaves the ground alone when there is no scene', async () => { startBackgroundScene.mockResolvedValue(null); const onActive = vi.fn(); - const dispose = mountBackgroundScene(config, caps, canvas, { loggedIn: true, onActive }); + const dispose = mountBackgroundScene(config, caps, canvas, { onActive }); await flush(); expect(onActive).not.toHaveBeenCalled(); expect(dispose).not.toThrow(); @@ -92,7 +89,7 @@ describe('mountBackgroundScene', () => { it('reports a failed start instead of throwing', async () => { startBackgroundScene.mockRejectedValue(new Error('boom')); const onFail = vi.fn(); - mountBackgroundScene(config, caps, canvas, { loggedIn: false, onFail }); + mountBackgroundScene(config, caps, canvas, { onFail }); await flush(); expect(onFail).toHaveBeenCalledWith(expect.objectContaining({ message: 'boom' })); }); @@ -103,24 +100,16 @@ describe('mountBackgroundScene', () => { return null; }); const onFail = vi.fn(); - mountBackgroundScene(config, caps, canvas, { loggedIn: false, onFail }); + mountBackgroundScene(config, caps, canvas, { onFail }); await flush(); expect(onFail).toHaveBeenCalledWith(expect.objectContaining({ message: 'shader' })); }); - it('calls login() once the scene starts when a session already exists', async () => { - const scene = fakeScene(); - startBackgroundScene.mockResolvedValue(scene); - mountBackgroundScene(config, caps, canvas, { loggedIn: true }); - await flush(); - expect(scene.login).toHaveBeenCalledOnce(); - }); - it('hands the door its onInactive and onActive, for a sky-state rebuild that makes no scene', async () => { startBackgroundScene.mockResolvedValue(fakeScene()); const onInactive = vi.fn(); const onActive = vi.fn(); - mountBackgroundScene(config, caps, canvas, { loggedIn: false, onInactive, onActive }); + mountBackgroundScene(config, caps, canvas, { onInactive, onActive }); await flush(); const given = startBackgroundScene.mock.calls[0][2]; onActive.mockClear(); @@ -129,144 +118,4 @@ describe('mountBackgroundScene', () => { expect(onInactive).toHaveBeenCalledOnce(); expect(onActive).toHaveBeenCalledOnce(); }); - - describe('a lost WebGL context', () => { - const lose = () => - startBackgroundScene.mock.calls[ - startBackgroundScene.mock.calls.length - 1 - ][2].onContextLost(); - const restore = () => canvas.dispatchEvent(new Event('webglcontextrestored')); - - it('disposes the dead scene and puts the ground back, without rebuilding yet', async () => { - const scene = fakeScene(); - startBackgroundScene.mockResolvedValue(scene); - const onInactive = vi.fn(); - mountBackgroundScene(config, caps, canvas, { loggedIn: false, onInactive }); - await flush(); - lose(); - expect(scene.dispose).toHaveBeenCalledOnce(); - expect(onInactive).toHaveBeenCalledOnce(); - expect(startBackgroundScene).toHaveBeenCalledOnce(); - }); - - it('starts a fresh scene on restore, activates it and logs in when a session exists', async () => { - const first = fakeScene(); - const second = fakeScene(); - startBackgroundScene.mockResolvedValueOnce(first).mockResolvedValueOnce(second); - const onActive = vi.fn(); - mountBackgroundScene(config, caps, canvas, { loggedIn: true, onActive }); - await flush(); - lose(); - restore(); - await flush(); - expect(startBackgroundScene).toHaveBeenCalledTimes(2); - expect(onActive).toHaveBeenCalledTimes(2); - expect(second.login).toHaveBeenCalledOnce(); - expect(first.dispose).toHaveBeenCalledOnce(); - }); - - it('rebuilds on every loss and restore, disposing each dead scene once', async () => { - const scenes = [fakeScene(), fakeScene(), fakeScene()]; - scenes.forEach((s) => startBackgroundScene.mockResolvedValueOnce(s)); - mountBackgroundScene(config, caps, canvas, { loggedIn: false }); - await flush(); - lose(); - restore(); - await flush(); - lose(); - restore(); - await flush(); - expect(scenes.map((s) => s.dispose.mock.calls.length)).toEqual([1, 1, 0]); - }); - - it('ignores a restore while a scene is running', async () => { - startBackgroundScene.mockResolvedValue(fakeScene()); - mountBackgroundScene(config, caps, canvas, { loggedIn: false }); - await flush(); - restore(); - await flush(); - expect(startBackgroundScene).toHaveBeenCalledOnce(); - }); - - it('leaves the ground when the rebuild yields no scene', async () => { - startBackgroundScene.mockResolvedValueOnce(fakeScene()).mockResolvedValueOnce(null); - const onActive = vi.fn(); - mountBackgroundScene(config, caps, canvas, { loggedIn: false, onActive }); - await flush(); - lose(); - restore(); - await flush(); - expect(onActive).toHaveBeenCalledOnce(); - }); - - it('does not rebuild after dispose, and removes its restore listener', async () => { - startBackgroundScene.mockResolvedValue(fakeScene()); - const dispose = mountBackgroundScene(config, caps, canvas, { loggedIn: false }); - await flush(); - lose(); - dispose(); - restore(); - await flush(); - expect(startBackgroundScene).toHaveBeenCalledOnce(); - }); - - it('removes the exact restore listener it added when it is disposed', async () => { - const add = vi.spyOn(canvas, 'addEventListener'); - const remove = vi.spyOn(canvas, 'removeEventListener'); - startBackgroundScene.mockResolvedValue(fakeScene()); - const dispose = mountBackgroundScene(config, caps, canvas, { loggedIn: false }); - await flush(); - const added = add.mock.calls.find(([type]) => type === 'webglcontextrestored'); - expect(added).toBeDefined(); - expect(remove).not.toHaveBeenCalled(); - dispose(); - expect(remove).toHaveBeenCalledWith('webglcontextrestored', added?.[1]); - }); - - it('treats a second loss from the same scene as nothing', async () => { - const scene = fakeScene(); - startBackgroundScene.mockResolvedValue(scene); - const onInactive = vi.fn(); - mountBackgroundScene(config, caps, canvas, { loggedIn: false, onInactive }); - await flush(); - lose(); - lose(); - expect(onInactive).toHaveBeenCalledOnce(); - expect(scene.dispose).toHaveBeenCalledOnce(); - }); - - it('ignores the old scene loss callback once a new scene has started', async () => { - const first = fakeScene(); - const second = fakeScene(); - startBackgroundScene.mockResolvedValueOnce(first).mockResolvedValueOnce(second); - const onInactive = vi.fn(); - mountBackgroundScene(config, caps, canvas, { loggedIn: false, onInactive }); - await flush(); - const oldLost = startBackgroundScene.mock.calls[0][2].onContextLost; - lose(); - restore(); - await flush(); - onInactive.mockClear(); - oldLost(); - expect(second.dispose).not.toHaveBeenCalled(); - expect(onInactive).not.toHaveBeenCalled(); - }); - - it('drops a scene that resolves after a loss that arrived while it started', async () => { - const late = fakeScene(); - let resolve!: (s: Scene) => void; - startBackgroundScene.mockReturnValueOnce( - new Promise((r) => { - resolve = r; - }) - ); - const onActive = vi.fn(); - mountBackgroundScene(config, caps, canvas, { loggedIn: false, onActive }); - lose(); - resolve(late); - await flush(); - expect(late.dispose).toHaveBeenCalledOnce(); - expect(onActive).not.toHaveBeenCalled(); - }); - }); }); diff --git a/src/app/features/scene/host.ts b/src/app/features/scene/host.ts index fccba78f..696f2309 100644 --- a/src/app/features/scene/host.ts +++ b/src/app/features/scene/host.ts @@ -4,13 +4,11 @@ import type { FixedSkyState } from './ridge/skyMoment'; import type { BackgroundSceneConfig, Capabilities } from './tier'; export type HostOptions = { - /** A Matrix session already exists, so the scene starts past its login moment. */ - loggedIn: boolean; /** The scene is running: the host may now let it show through, over the sky it draws. Not called when there is none. */ onActive?: (sky?: FixedSkyState) => void; - /** The scene stopped because its GL context was lost: put the CSS ground back until it restores. */ + /** The scene stopped or rebuilt with no scene: put the CSS ground back. */ onInactive?: () => void; - /** A shader failed to compile, the chunk failed to load, or starting threw. The CSS ground stays. */ + /** The chunk failed to load, or starting threw. The CSS ground stays. */ onFail?: (e: Error) => void; }; @@ -18,64 +16,38 @@ export type HostOptions = { * Start the background scene on `canvas` and return the function that ends it. The start is async, * so a dispose that arrives first wins: the scene is disposed the moment it resolves. A null scene * (tier off, no 2D context, load failure) leaves the canvas untouched and the ground showing. - * - * A lost WebGL context ends the scene it killed: the host disposes it, calls `onInactive` so the - * CSS ground shows, and starts a fresh scene when the canvas's context is restored. The 2D sky - * cannot take over on this canvas (a canvas that has held a WebGL context gives no 2D one), so the - * ground is the fallback while the context is gone; a restore that cannot rebuild leaves it there. */ export function mountBackgroundScene( config: BackgroundSceneConfig | undefined, capabilities: Capabilities, canvas: HTMLCanvasElement, - { loggedIn, onActive, onInactive, onFail }: HostOptions + { onActive, onInactive, onFail }: HostOptions ): () => void { let cancelled = false; let scene: StartedScene | null = null; - let generation = 0; - const start = () => { - generation += 1; - const mine = generation; - const stale = () => cancelled || mine !== generation; - startBackgroundScene(config, capabilities, { - canvas, - onCompileFail: onFail, - onInactive, - onActive, - onContextLost: () => { - if (stale()) return; - generation += 1; - scene?.dispose(); - scene = null; - onInactive?.(); - }, - }).then( - (started) => { - if (stale()) { - started?.dispose(); - return; - } - scene = started; - if (!scene) return; - onActive?.(scene.drawnSky); - if (loggedIn) scene.login(); - }, - (e) => { - if (!stale()) onFail?.(e instanceof Error ? e : new Error(String(e))); + startBackgroundScene(config, capabilities, { + canvas, + onCompileFail: onFail, + onInactive, + onActive, + }).then( + (started) => { + if (cancelled) { + started?.dispose(); + return; } - ); - }; - - const onRestored = () => { - if (!cancelled && !scene) start(); - }; - canvas.addEventListener('webglcontextrestored', onRestored); - start(); + scene = started; + if (!scene) return; + onActive?.(scene.drawnSky); + }, + (e) => { + if (!cancelled) onFail?.(e instanceof Error ? e : new Error(String(e))); + } + ); return () => { cancelled = true; - canvas.removeEventListener('webglcontextrestored', onRestored); scene?.dispose(); scene = null; }; diff --git a/src/app/features/scene/index.test.ts b/src/app/features/scene/index.test.ts index cffadc0d..910ecd0b 100644 --- a/src/app/features/scene/index.test.ts +++ b/src/app/features/scene/index.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { atSolarTime } from './ridge/skyTestkit'; -import type { Scene } from './Scene'; +import type { Scene } from './index'; import { PREPARE_DEADLINE_MS, startBackgroundScene } from './index'; import { getResolvedSkyState, getSkyPlace, setConstellationLines, setSkyChoice, setSkyClock, setSkyPlace, subscribe } from './skyState'; import { skyBand } from './ridge/skyMoment'; @@ -16,15 +16,13 @@ import { sunAt } from './ridge/sunAt'; import { ridgeWeather } from './ridge/weather'; import { creditLine, parseWeatherFile, WEATHER_FEEDS, weatherFromFile } from './ridge/weatherFeed'; -const { createRidgeScene, createScene, createBackdrop } = vi.hoisted(() => ({ +const { createRidgeScene, createBackdrop } = vi.hoisted(() => ({ createRidgeScene: vi.fn(), - createScene: vi.fn(), createBackdrop: vi.fn(), })); vi.mock('./ridge/Ridge', () => ({ createRidgeScene })); // Decoding and lighting are the cards' own tests' (Backdrop.test.ts, lightCards.test.ts); here the door sees a backdrop whose first arc it can hold, fail and count. vi.mock('./ridge/Backdrop', () => ({ createBackdrop })); -vi.mock('./Scene', () => ({ createScene })); // The physical sky is baked per call (tens of ms: atmosphere LUTs) and the clock here is fixed, so a state always // draws the same sky. Baking once per state keeps the 21-offset sweep under the default timeout when the machine is // loaded; the sky each build receives is still the one `ridgeSkyFor` makes for that state. @@ -111,7 +109,7 @@ const loader = () => { }, }; }; -const fakeScene = () => ({ login: vi.fn(), dispose: vi.fn() }); +const fakeScene = () => ({ dispose: vi.fn() }); const hex = (c: readonly number[]) => `#${c.map((v) => v.toString(16).padStart(2, '0')).join('')}`; beforeEach(() => { @@ -125,7 +123,6 @@ beforeEach(() => { setSkyChoice(AUTO); setSkyPlace(FALLBACK_VIEW.place); createRidgeScene.mockReset(); - createScene.mockReset(); createBackdrop.mockReset(); forgetPlaceChoice(); }); @@ -201,21 +198,6 @@ describe('startBackgroundScene follows the sky state', () => { expect(b.dispose).toHaveBeenCalledOnce(); }); - it('replays a login onto the rebuilt scene, but only if one happened', async () => { - const [a, b, c] = [fakeScene(), fakeScene(), fakeScene()]; - createRidgeScene.mockReturnValueOnce(a).mockReturnValueOnce(b).mockReturnValueOnce(c); - const scene = await startBackgroundScene(config, caps, { canvas }); - setSkyChoice(NOON); - await flush(); - expect(b.login).not.toHaveBeenCalled(); - scene?.login(); - expect(b.login).toHaveBeenCalledOnce(); - setSkyChoice(DUSK); - await flush(); - expect(c.login).toHaveBeenCalledOnce(); - scene?.dispose(); - }); - it('puts the ground back when a rebuild makes no scene, and lets it show when one returns', async () => { const [a, c] = [fakeScene(), fakeScene()]; createRidgeScene.mockReturnValueOnce(a).mockReturnValueOnce(null).mockReturnValueOnce(c); @@ -272,15 +254,12 @@ describe('startBackgroundScene follows the sky state', () => { setSkyChoice(NOON); setSkyChoice(DUSK); await flush(); - // The sky last built is dusk's, and it is the live scene: a login reaches it and nothing else. + // The sky last built is dusk's, and it is the live scene. const built = createRidgeScene.mock.calls.length; expect(hex(createRidgeScene.mock.calls[built - 1][0].sky.top)).toBe( hex(ridgeSkyFor(DUSK, FALLBACK_VIEW).top) ); const live = scenes[built - 1]; - scene?.login(); - expect(live.login).toHaveBeenCalledOnce(); - scenes.filter((s) => s !== live).forEach((s) => expect(s.login).not.toHaveBeenCalled()); // Every scene but the live one was disposed, the live one not yet. scenes.slice(0, built).forEach((s) => { expect(s.dispose).toHaveBeenCalledTimes(s === live ? 0 : 1); @@ -324,11 +303,8 @@ describe('startBackgroundScene follows the sky state', () => { ); // The newest build is live, every earlier one disposed exactly once, and only the live one is shown. const live = [a, b, c][built - 1]; - scene?.login(); - expect(live.login, at).toHaveBeenCalledOnce(); [a, b, c].slice(0, built).forEach((x) => { expect(x.dispose, at).toHaveBeenCalledTimes(x === live ? 0 : 1); - if (x !== live) expect(x.login, at).not.toHaveBeenCalled(); }); scene?.dispose(); expect(live.dispose, at).toHaveBeenCalledOnce(); @@ -347,31 +323,6 @@ describe('startBackgroundScene follows the sky state', () => { // off the build. Then widen the range of offsets until some land again; do not weaken the assertion. expect(landed.length, 'at least one offset must land mid-build').toBeGreaterThan(0); }, 30000); - - it('leaves the ray-march scene alone: it has one fixed dusk', async () => { - const inner = fakeScene() as unknown as Scene; - createScene.mockReturnValue(inner); - const scene = await startBackgroundScene({ ...config, style: 'raymarch' }, caps, { canvas }); - expect(scene).toBe(inner); - setSkyChoice(NOON); - await flush(); - expect(createScene).toHaveBeenCalledOnce(); - }); - - it('keeps the ground and reports a ray-march scene that throws while being created', async () => { - const boom = new Error('shader link failed'); - createScene.mockImplementation(() => { - throw boom; - }); - const onCompileFail = vi.fn(); - const scene = await startBackgroundScene({ ...config, style: 'raymarch' }, caps, { - canvas, - onCompileFail, - }); - expect(scene).toBeNull(); - expect(onCompileFail).toHaveBeenCalledOnce(); - expect(onCompileFail).toHaveBeenCalledWith(boom); - }); }); describe('the ridge planes', () => { @@ -972,14 +923,11 @@ describe('the ridge cards and the live scene', () => { expect(d.ctl.pending.length).toBeGreaterThan(0); expect(first.dispose).not.toHaveBeenCalled(); expect(createRidgeScene).toHaveBeenCalledOnce(); - scene?.login(); - expect(first.login).toHaveBeenCalledOnce(); await d.release(); expect(createRidgeScene).toHaveBeenCalledTimes(2); expect(first.dispose).toHaveBeenCalledOnce(); expect(second.dispose).not.toHaveBeenCalled(); expect(onActive).toHaveBeenCalledOnce(); - expect(second.login).toHaveBeenCalledOnce(); // replayed onto the swapped-in scene scene?.dispose(); expect(second.dispose).toHaveBeenCalledOnce(); }); @@ -1051,8 +999,6 @@ describe('the ridge cards and the live scene', () => { expect(createRidgeScene).toHaveBeenCalledTimes(2); expect(second.dispose).not.toHaveBeenCalled(); // the live scene is not disposed by a build that lost expect(onActive).toHaveBeenCalledOnce(); - scene?.login(); - expect(second.login).toHaveBeenCalledOnce(); scene?.dispose(); expect(second.dispose).toHaveBeenCalledOnce(); expect(third.dispose).not.toHaveBeenCalled(); diff --git a/src/app/features/scene/index.ts b/src/app/features/scene/index.ts index 0e3509cb..2e094991 100644 --- a/src/app/features/scene/index.ts +++ b/src/app/features/scene/index.ts @@ -1,26 +1,26 @@ -import type { Scene, SceneOptions } from './Scene'; +import type { Scene } from './ridge/Ridge'; import { BackgroundSceneConfig, Capabilities, SceneTier, resolveTier } from './tier'; -import { debugOverlaysAllowed } from './debugOverlays'; import { getConstellationLines, getSkyChoice, skyBandAt, subscribe } from './skyState'; import type { FixedSkyState, SkyChoice } from './ridge/skyMoment'; import { drawnView, ensureSkyPlace, resetSkyPlanes } from './skyPlace'; import { subscribePlaceChoice } from './placeState'; -import type { SkyColours } from './ridge/skyColour'; +import type { SkyColours } from './ridge/physicalSky'; import type { Backdrop } from './ridge/Backdrop'; import { FALLBACK_VIEW, HFOV_MAX_DEG, maxSpeed } from './ridge/view'; -export type { Scene, SceneStats } from './Scene'; +export type { Scene }; /** The scene the door returns: it also says which sky it draws now (the band of the scene that is up, not of the sky announced). */ export interface StartedScene extends Scene { readonly drawnSky: FixedSkyState | undefined; } -export type { SceneStyle, SceneTier } from './tier'; +export type { SceneTier } from './tier'; -export type StartOptions = Omit & { +export type StartOptions = { + canvas: HTMLCanvasElement; /** A shader failed to compile, or the scene chunk failed to load. The host keeps its ground. */ onCompileFail?: (e: Error) => void; - /** A rebuild for a new sky made no scene: the host puts the CSS ground back (as on a lost context). */ + /** A rebuild for a new sky made no scene: the host puts the CSS ground back. */ onInactive?: () => void; /** A rebuild made a scene again: the host lets it show, over the sky that scene draws (what the page ink follows). */ onActive?: (sky?: FixedSkyState) => void; @@ -70,7 +70,7 @@ const holdsATile = (backdrop: Backdrop, stop: AbortSignal): Promise => async function prepare( config: BackgroundSceneConfig | undefined, - options: StartOptions & { tier: SceneTier; debug?: boolean }, + options: StartOptions & { tier: SceneTier }, choice: SkyChoice, /** Nothing with a ridge is up to wait behind: the page's first scene, or a rebuild over a scene that is the sky alone. It waits against the deadline and, with no tile, is the sky alone. */ first: boolean, @@ -105,10 +105,6 @@ async function prepare( try { // Loaded here, with the scenes, so the main chunk does not carry the ridge sky or the baked tables. const { loadWeather, ridgeSkyFor } = await import('./skyForState'); - if (config?.style === 'raymarch') { - const { createScene } = await import('./Scene'); - return guarded(() => createScene(options)); - } const { createRidgeScene } = await import('./ridge/Ridge'); const { manifest, fail } = await ensureSkyPlace(config); await loadWeather(weatherUrl(), (manifest?.view ?? FALLBACK_VIEW).place); @@ -194,14 +190,12 @@ async function skyKey( /** * The client's one door to the scene. When the tier resolves to 'off' nothing is imported and no * canvas context is requested; otherwise the scene code loads on demand, so it stays out of the - * main chunk. `config.style` picks the scene: the ridges unless it says 'raymarch' (any other value, an old 'terrain' included, is the ridges). Null means - * "keep the CSS ground", including when that chunk fails to load (offline, stale deploy): the - * failure goes to onCompileFail and nothing throws. + * main chunk. Null means "keep the CSS ground", including when that chunk fails to load (offline, + * stale deploy): the failure goes to onCompileFail and nothing throws. * * The ridge scene bakes its sky once, so it follows the sky (`skyState.ts`: the choice at the place, so Auto follows the clock) by * being rebuilt on the same canvas when it changes: the door subscribes on start and the returned - * scene's `dispose` unsubscribes. The pull-back restarts from the tree; a later `login()` is - * replayed on the new scene. The ray-march scene has one fixed dusk and ignores the state. + * scene's `dispose` unsubscribes. */ export async function startBackgroundScene( config: BackgroundSceneConfig | undefined, @@ -210,7 +204,6 @@ export async function startBackgroundScene( ): Promise { const tier = resolveTier(config, capabilities); if (tier === 'off') return null; - const debug = debugOverlaysAllowed(config); // What the host was last told of the planes: only the live scene speaks, and only when its state changes. let planesFailed = false; const announce = (planesFail: Error | null) => { @@ -218,22 +211,19 @@ export async function startBackgroundScene( if (!planesFail && planesFailed) options.onPlanesOk?.(); planesFailed = planesFail !== null; }; - const prepared = (choice: SkyChoice, first: boolean, stop: AbortSignal) => prepare(config, { ...options, tier, debug }, choice, first, stop); + const prepared = (choice: SkyChoice, first: boolean, stop: AbortSignal) => prepare(config, { ...options, tier }, choice, first, stop); resetSkyPlanes(); const choice = getSkyChoice(); - const key0 = config?.style === 'raymarch' ? null : await skyKey(config, choice); + const key0 = await skyKey(config, choice); const firstReady = await prepared(choice, true, new AbortController().signal); const first = firstReady.make(); if (!first) return null; - // The ray-march scene has one fixed dusk. - if (config?.style === 'raymarch') return Object.assign(first, { drawnSky: 'dusk' as const }); announce(firstReady.planesFail); let inner: Scene | null = first; let built = key0; let shown = key0; // the sky key of the scene that is up let drawnSky = firstReady.sky; // the band of the scene that is up - let loggedIn = false; let disposed = false; let generation = 0; let building: AbortController | undefined; @@ -272,10 +262,7 @@ export async function startBackgroundScene( drawnSky = ready.sky; if (scene) announce(ready.planesFail); if (!scene) options.onInactive?.(); - else { - options.onActive?.(ready.sky); - if (loggedIn) scene.login(); - } + else options.onActive?.(ready.sky); }; // A place picked in the Place submenu is a rebuild: `skyKey` re-resolves the pick (skyPlace.ts) into the place to build, and so the key's; the store's place stays the // drawn one until that scene is made. A pick is also a request to try again: what stands pending (a place whose tiles do not come) is given up for a fresh build, and @@ -295,10 +282,6 @@ export async function startBackgroundScene( get drawnSky() { return drawnSky; }, - login() { - loggedIn = true; - inner?.login(); - }, dispose() { if (disposed) return; disposed = true; diff --git a/src/app/features/scene/palette.ts b/src/app/features/scene/palette.ts deleted file mode 100644 index 54a84ad3..00000000 --- a/src/app/features/scene/palette.ts +++ /dev/null @@ -1,27 +0,0 @@ -// The scene's colours, as linear RGB uniforms. The sky tints are GameCult's three nebula inputs -// (orange 255 138 42, violet 109 96 255, sky 89 183 255) over the brand base #07111a, so the -// background reads as the same dusk as gamecult.org. The shaders hold no colour literal. - -export type Rgb = readonly [number, number, number]; - -const srgb = (r: number, g: number, b: number): Rgb => [ - (r / 255) ** 2.2, - (g / 255) ** 2.2, - (b / 255) ** 2.2, -]; - -export const PALETTE = { - sunColor: srgb(255, 150, 70).map((c) => c * 3.2) as unknown as Rgb, - skyTop: srgb(30, 36, 92), - skyHorizon: srgb(255, 138, 42).map((c) => c * 0.55) as unknown as Rgb, - fogColor: srgb(109, 96, 255).map((c) => c * 0.12) as unknown as Rgb, - grass: srgb(72, 112, 86), - rock: srgb(112, 104, 122), - bark: srgb(62, 46, 40), - leaf: srgb(89, 183, 255).map((c) => c * 0.7) as unknown as Rgb, - sunDir: (() => { - const v = [0.55, 0.16, -0.82]; - const l = Math.hypot(v[0], v[1], v[2]); - return [v[0] / l, v[1] / l, v[2] / l] as Rgb; - })(), -} as const; diff --git a/src/app/features/scene/ridge/Backdrop.test.ts b/src/app/features/scene/ridge/Backdrop.test.ts index 04ee6185..1480c874 100644 --- a/src/app/features/scene/ridge/Backdrop.test.ts +++ b/src/app/features/scene/ridge/Backdrop.test.ts @@ -2,8 +2,8 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import type { Mock } from 'vitest'; import { createBackdrop, - FETCH_PARALLEL, FETCH_TIMEOUT_MS, + MAX_RETRIES, NotFound, RETRY_FIRST_MS, RETRY_MAX_MS, @@ -293,54 +293,6 @@ describe('createBackdrop', () => { expect([15, 16]).toContain(tileOf(r2.fetched[0])); // the two tiles either side of 180 }); - it('asks for the files of the tiles of an arc a few at a time, not one after another and not all at once', async () => { - let active = 0; - let most = 0; - const r = rig(); - const fetchBlob = vi.fn(async (url: string) => { - active += 1; - most = Math.max(most, active); - await new Promise((go) => setTimeout(go, 5)); - active -= 1; - return { url } as unknown as Blob; - }); - const bd = createBackdrop(manifest, sky, { ...r, fetchBlob, lighter: r.lighter }); - await bd.ensure(arc72(180)); // ten tiles of up to six files each - expect(most).toBeGreaterThan(1); // the files are not asked for one after another - expect(most).toBe(FETCH_PARALLEL); // and the pipe is kept full while there is more to ask, and no fuller - expect(bd.litTiles().length).toBeGreaterThan(20); - }); - - it('keeps the cap while the arc changes under it: aborted passes hand their slots on, and a pass begun at once takes none of them', async () => { - vi.useFakeTimers(); - let live = 0; - let most = 0; - const r = rig(); - const fetchBlob = vi.fn( - (url: string, signal?: AbortSignal) => - new Promise((resolve, reject) => { - live += 1; - most = Math.max(most, live); - const timer = setTimeout(() => { - live -= 1; - resolve({ url } as unknown as Blob); - }, 300); - signal?.addEventListener('abort', () => { - clearTimeout(timer); - live -= 1; - reject(new Error('aborted')); - }); - }) - ); - const bd = createBackdrop(manifest, sky, { ...r, fetchBlob, lighter: r.lighter }); - for (let i = 0; i < 60; i += 1) { - void bd.ensure({ fromDeg: 100 + i * 2, toDeg: 180 + i * 2 }); // a turning view: a new arc every half second, each one aborting the last - await vi.advanceTimersByTimeAsync(500); - } - expect(fetchBlob.mock.calls.length).toBeGreaterThan(FETCH_PARALLEL * 3); // the loader worked the whole time - expect(most).toBeLessThanOrEqual(FETCH_PARALLEL); - }); - it('gives up on a request that never answers, draws absence and goes on, and aborts it', async () => { vi.useFakeTimers(); const r = rig(); @@ -414,7 +366,7 @@ describe('createBackdrop', () => { bd.dispose(); }); - it('keeps asking, on a pause that doubles, while the arc wants the tile, and stops when the arc has moved on or the backdrop is gone', async () => { + it('keeps asking on a pause that doubles up to MAX_RETRIES while the arc wants the tile, then stops; also stops when the arc moves on or the backdrop is disposed', async () => { vi.useFakeTimers(); const { r, deps } = quick((u) => tileOf(u) === 19); const bd = createBackdrop(manifest, sky, deps); @@ -424,8 +376,7 @@ describe('createBackdrop', () => { r.tick(1000); await vi.advanceTimersByTimeAsync(1000); } - expect(tile(r, 19)).toBeGreaterThan(3); - expect(tile(r, 19)).toBeLessThanOrEqual(8); // 1 s, 2 s, 4 s, 8 s, 16 s, 32 s: a few a minute, not one a second + expect(tile(r, 19)).toBe(1 + MAX_RETRIES); await bd.ensure({ fromDeg: 0, toDeg: 1 }); // the view has gone the other way: tile 19 is no longer wanted const asked = tile(r, 19); for (let s = 0; s < 300; s += 1) { diff --git a/src/app/features/scene/ridge/Backdrop.ts b/src/app/features/scene/ridge/Backdrop.ts index 13ef8d79..7ce82100 100644 --- a/src/app/features/scene/ridge/Backdrop.ts +++ b/src/app/features/scene/ridge/Backdrop.ts @@ -1,13 +1,12 @@ // The ridge cards the scene composes, lit, kept resident by tile: the one owner of which tiles of the ring are in memory. `ensure` is told the arc of // azimuth the view is about to need; it fetches and decodes the tiles of that arc it does not hold, one tile at a time, lights each card of a tile -// (`lightCards.ts`, one lighter for the one sky this backdrop was made for) and drops the tiles beyond the arc and its margin. The files of the tiles to make -// are fetched a few at a time, each against a timeout. A tile that fails is a tile the scene draws as absence, asked for again by the loader itself after a growing -// pause, for as long as the arc last asked for wants it (whoever asked, a scene's timer or none: a still has no timer); a file the server says is not there (404) is -// not asked for again while its tile stays: the scene draws the cards of the tile that came. Nothing is thrown into the scene. +// (`lightCards.ts`, one lighter for the one sky this backdrop was made for) and drops the tiles beyond the arc and its margin. A tile that fails is a tile +// the scene draws as absence, retried up to MAX_RETRIES with bounded exponential backoff while the arc last asked for wants it; a 404/410 file is not asked +// for again while its tile stays. Nothing is thrown into the scene. import type { RidgeManifest } from './manifest'; import type { PhysicalSky } from './physicalSky'; import { createLighter } from './lightCards'; -import type { CardBitmaps, Lighter } from './lightCards'; +import type { Lighter } from './lightCards'; import { KEEP_MARGIN_TILES, LOAD_MARGIN_TILES, residentTiles } from './ring'; /** A range of unwrapped compass azimuth, degrees, `fromDeg <= toDeg`. */ @@ -50,11 +49,10 @@ export interface BackdropDeps { /** A file the server answered 404 or 410 for: asking again will not make it appear. */ export class NotFound extends Error {} -/** Requests in flight at once, over all tiles; how long one may take; the pause before a failed tile is asked for again (doubled each failure, to the cap). */ -export const FETCH_PARALLEL = 6; export const FETCH_TIMEOUT_MS = 15_000; export const RETRY_FIRST_MS = 1_000; export const RETRY_MAX_MS = 60_000; +export const MAX_RETRIES = 4; const fetchBlob = async (url: string, signal?: AbortSignal): Promise => { const res = await fetch(url, { signal }); @@ -84,18 +82,15 @@ export function createBackdrop( const tileDeg = 360 / view.tiles; let lighter = makeLighter(manifest, sky); const held = new Map(); - /** Tiles that failed, when they may be asked for again and the pause after the next failure. */ - const failed = new Map(); + const failed = new Map(); const heard = new Set<() => void>(); let disposed = false; let running: Promise | null = null; let want: { arc: Arc; first?: Arc } | null = null; /** The arc last asked for: what the loader keeps its tiles for and retries for. */ let wanted: { arc: Arc; first?: Arc } | null = null; - /** Ask for the arc wanted once more: a pass ends in `schedule`, which is defined before the backdrop that can be asked. */ let askAgain: () => void = () => undefined; let retry: ReturnType | undefined; - /** The pass that is on the wire: dispose gives up its requests, as a newer arc does. */ let current: AbortController | null = null; const drop = (tile: number) => { @@ -106,33 +101,23 @@ export function createBackdrop( held.delete(tile); }; - // At most FETCH_PARALLEL requests at once over every tile, each with its own timeout (the signal is passed on, and a fetch that ignores it is still given up on). - // A slot is handed straight to the next waiter, so `active` never dips for a request issued in between to slip into; it falls only when nobody waits. - let active = 0; - const queue: (() => void)[] = []; - const request = async (url: string, signal: AbortSignal): Promise => { - if (active < FETCH_PARALLEL) active += 1; - else await new Promise((go) => queue.push(go)); - try { - if (signal.aborted) throw new Error('ridge: aborted'); - return await new Promise((resolve, reject) => { - const ctl = new AbortController(); - const stop = () => { - ctl.abort(); - reject(new Error(`ridge: ${url} ${signal.aborted ? 'aborted' : 'timed out'}`)); - }; - const timer = setTimeout(stop, FETCH_TIMEOUT_MS); - signal.addEventListener('abort', stop, { once: true }); - get(url, ctl.signal).then(resolve, reject).finally(() => { + const request = (url: string, signal: AbortSignal): Promise => { + if (signal.aborted) return Promise.reject(new Error('ridge: aborted')); + return new Promise((resolve, reject) => { + const ctl = new AbortController(); + const stop = () => { + ctl.abort(); + reject(new Error(`ridge: ${url} ${signal.aborted ? 'aborted' : 'timed out'}`)); + }; + const timer = setTimeout(stop, FETCH_TIMEOUT_MS); + signal.addEventListener('abort', stop, { once: true }); + get(url, ctl.signal) + .then(resolve, reject) + .finally(() => { clearTimeout(timer); signal.removeEventListener('abort', stop); }); - }); - } finally { - const next = queue.shift(); - if (next) next(); - else active -= 1; - } + }); }; /** The files of a tile, each settled on its own: a blob, or what became of it (`gone`: the server has none; `failed`: it may pass). */ @@ -155,10 +140,6 @@ export function createBackdrop( ); } - /** - * Decode and light what a tile's fetch brought, one card at a time, and hold the tile. A card with a file the server does not have is left out (the scene - * draws the others); a tile with any file that failed otherwise is not kept (it is lit whole or not at all) and is asked for again after a pause. - */ async function make(tile: number, fetched: { card: number; files: Fetched[] }[]): Promise { const made: LitTile[] = []; const bitmaps: ImageBitmap[] = []; @@ -177,7 +158,13 @@ export function createBackdrop( return b; }) ); - if (disposed) return; + if (disposed) { + made.forEach((t) => { + t.canvas.width = 0; + t.canvas.height = 0; + }); + return; + } made.push({ tile, card, canvas: lighter.light({ colour, geometry }, tile, card) }); } held.set(tile, made); @@ -185,8 +172,14 @@ export function createBackdrop( heard.forEach((cb) => cb()); } catch { made.forEach((t) => (t.canvas.width = 0)); - const pause = Math.min(RETRY_MAX_MS, (failed.get(tile)?.pause ?? RETRY_FIRST_MS / 2) * 2); - failed.set(tile, { until: now() + pause, pause }); + const prev = failed.get(tile); + const tries = (prev?.tries ?? 0) + 1; + const pause = Math.min(RETRY_MAX_MS, (prev?.pause ?? RETRY_FIRST_MS / 2) * 2); + failed.set(tile, { + until: tries > MAX_RETRIES ? Infinity : now() + pause, + pause, + tries, + }); } finally { bitmaps.forEach((b) => b.close?.()); } @@ -201,13 +194,11 @@ export function createBackdrop( residentTiles(view, centre, half + KEEP_MARGIN_TILES * tileDeg).map((r) => r.tile) ); [...held.keys()].filter((t) => !keep.has(t)).forEach(drop); - // The tile under the view first, then outward along the sweep: what the view needs now comes before what it needs next. const from = (r: { tile: number; turn: number }) => r.turn * 360 + r.tile * tileDeg + tileDeg / 2; const order = [...near] .sort((a, b) => Math.abs(from(a) - from0) - Math.abs(from(b) - from0)) .map((r) => r.tile) .filter((t) => !held.has(t) && (failed.get(t)?.until ?? 0) <= now()); - // Every tile's files are asked for at once (the requests queue to FETCH_PARALLEL, in this order) and made one tile at a time as they arrive. const stop = new AbortController(); current = stop; try { @@ -216,16 +207,15 @@ export function createBackdrop( const fetched = await asked[i]; if (disposed) return; await make(tile, fetched); - // A newer arc is waiting: take it up now, with this tile made, instead of finishing an arc the view has left. if (want && held.has(tile)) return; } } finally { - stop.abort(); // what is still on the wire is for an arc the view has left + stop.abort(); if (current === stop) current = null; } } - /** When the arc wanted holds a tile that failed, ask for it again at the end of its pause: the loader's own retry, the same for every tier. */ + /** When the arc wanted holds a tile that failed within MAX_RETRIES, ask for it again at the end of its pause. */ function schedule(): void { clearTimeout(retry); retry = undefined; @@ -233,8 +223,10 @@ export function createBackdrop( const { arc } = wanted; const half = (arc.toDeg - arc.fromDeg) / 2 + LOAD_MARGIN_TILES * tileDeg; const due = residentTiles(view, (arc.fromDeg + arc.toDeg) / 2, half) - .filter((r) => !held.has(r.tile) && failed.has(r.tile)) - .map((r) => (failed.get(r.tile) as { until: number }).until); + .filter((r) => !held.has(r.tile)) + .map((r) => failed.get(r.tile)) + .filter((f): f is { until: number; pause: number; tries: number } => f !== undefined && f.tries <= MAX_RETRIES) + .map((f) => f.until); if (!due.length) return; retry = setTimeout(() => { retry = undefined; @@ -274,7 +266,7 @@ export function createBackdrop( wanted = null; want = null; clearTimeout(retry); - current?.abort(); // a scene that did not wait for its tiles, or was replaced, leaves nothing asking for them + current?.abort(); [...held.keys()].forEach(drop); lighter.release(); }, diff --git a/src/app/features/scene/ridge/Ridge.test.ts b/src/app/features/scene/ridge/Ridge.test.ts index 884c3423..48c0205d 100644 --- a/src/app/features/scene/ridge/Ridge.test.ts +++ b/src/app/features/scene/ridge/Ridge.test.ts @@ -1,28 +1,23 @@ -import { readFileSync } from 'node:fs'; -import { join } from 'node:path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { createRidgeScene, RESIDENCY_MS } from './Ridge'; -import { valueNoise, hash2 } from './noise'; -import { FrameSampler, frameStats, SLOW_P95_MS, WARMUP_FRAMES, WINDOW_MS } from './probe'; -import type { SkyColours } from './skyColour'; +import { hash2 } from './noise'; +import type { SkyColours } from './physicalSky'; import { nightBodies } from './nightBodies'; import { sunAt } from './sunAt'; import { makePhysicalSky, paintSky as paintPhysicalSky } from './physicalSky'; import { sunOfBand } from './skyTestkit'; import { startBackgroundScene } from '../index'; -import { parseIndex, parseManifest } from './manifest'; +import { parseManifest } from './manifest'; import { ELSEWHERE_VIEW, wireManifest } from './manifest.fixture'; import type { Arc, Backdrop, LitTile } from './Backdrop'; import type { Mock } from 'vitest'; -import { cardArc, cardPose, FALLBACK_VIEW, HFOV_MAX_DEG, maxSpeed, offsetRange, SEGMENT_S, windowFor } from './view'; +import { cardArc, cardPose, FALLBACK_VIEW, HFOV_MAX_DEG, maxSpeed, offsetRange, windowFor } from './view'; import { LATENESS_S, plateCamera, plateSize, SLACK_MIN_DEG, slackFor } from './skyTurn'; import { ringAzimuth, sunColumns, sunInColumn } from './lightCards'; import { norm, residentTiles } from './ring'; -import { anchor, hold, poseAt, resetHeading, settledAt, STAGE_MS } from './heading'; +import { anchor, hold, poseAt, resetHeading } from './heading'; import { effectiveMode, getCamera, isHeld, resetCamera, setCamera } from '../cameraState'; -/** The two stages of the ease of a mode pick (the angle, then the offset, or the other way round). */ -const EASE_MS = 2 * STAGE_MS; /** A card's pose as the heading owner has the view at `t`: what the rig lays the card out from. */ const posed = (m: Parameters[0], card: number, t: number, w: Parameters[5]) => { const p = poseAt(t); @@ -31,70 +26,13 @@ const posed = (m: Parameters[0], card: number, t: number, w: Pa describe('noise', () => { it('is deterministic and in [0, 1)', () => { - expect(hash2(3, 5)).toBe(hash2(3, 5)); for (let i = 0; i < 200; i += 1) { - const v = valueNoise(i * 0.37 - 20, 2); + const v = hash2(i, 2); expect(v).toBeGreaterThanOrEqual(0); expect(v).toBeLessThan(1); - expect(valueNoise(i * 0.37 - 20, 2)).toBe(v); + expect(hash2(i, 2)).toBe(v); } }); - - it('different rows are different profiles', () => { - expect(valueNoise(1.5, 0)).not.toBeCloseTo(valueNoise(1.5, 1), 3); - }); -}); - -describe('frame sampler', () => { - const feed = (s: FrameSampler, dt: number, frames: number, from = 0) => { - let t = from; - let done = false; - for (let i = 0; i < frames && !done; i += 1) { - t += dt; - done = s.push(t); - } - return done; - }; - - it('median and p95 of known intervals', () => { - const v = Array.from({ length: 100 }, (_, i) => (i < 90 ? 16 : 50)); - expect(frameStats(v)).toEqual({ n: 100, medianMs: 16, p95Ms: 50 }); - expect(frameStats([])).toEqual({ n: 0, medianMs: 0, p95Ms: 0 }); - }); - - it('does not complete before 2 s of measured frames, and ignores the warm-up', () => { - const s = new FrameSampler(); - expect(feed(s, 16, 100)).toBe(false); // 1.6 s - expect(feed(s, 16, 40, 1600)).toBe(true); - expect(s.stats().n).toBeLessThan(100 + 40 - WARMUP_FRAMES + 1); - }); - - it('a smooth 60 Hz run is not slow; a run of 40 ms frames is', () => { - const good = new FrameSampler(); - feed(good, 16.7, 400); - expect(good.slow()).toBe(false); - const bad = new FrameSampler(); - feed(bad, 100, 400); // ~100 ms frames, the PR #13 readout - expect(bad.stats().p95Ms).toBeGreaterThan(SLOW_P95_MS); - expect(bad.slow()).toBe(true); - }); - - it('a long warm-up frame does not poison the window', () => { - const s = new FrameSampler(); - let t = 0; - s.push(t); - for (let i = 0; i < WARMUP_FRAMES; i += 1) s.push((t += 300)); // setup, upload, JIT - feed(s, 16.7, 200, t); - expect(s.slow()).toBe(false); - expect(WINDOW_MS).toBe(2000); - }); - - it('reset forgets a hidden-tab gap', () => { - const s = new FrameSampler(); - feed(s, 16, 20); - s.reset(); - expect(s.stats().n).toBe(0); - }); }); // A minimal DOM: just what createRidgeScene touches. @@ -242,7 +180,6 @@ function ctx() { let rafQueue: Array<(t: number) => void>; let motion: { matches: boolean; addEventListener: any; removeEventListener: any }; let doc: any; -let search: string; beforeEach(() => { rafQueue = []; @@ -253,7 +190,6 @@ beforeEach(() => { arcs.length = 0; twinks.length = 0; onPaint = undefined; - search = ''; motion = { matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn() }; doc = Object.assign(new EventTarget(), { visibilityState: 'visible', @@ -268,11 +204,6 @@ beforeEach(() => { innerHeight: 800, matchMedia: () => motion, clearTimeout, - location: { - get search() { - return search; - }, - }, setTimeout, }) ); @@ -334,26 +265,6 @@ describe('createRidgeScene', () => { s.dispose(); }); - it('a smooth run draws nothing more and ends its rAF loop', () => { - const { canvas } = host(); - const s = createRidgeScene({ canvas, tier: 'full', sky: DAY })!; - const before = draws.length; - runFrames(16.7, 400); - expect(draws.length).toBe(before); - expect(rafQueue).toHaveLength(0); // no per-frame work left - s.dispose(); - }); - - it('p95 over 33 ms across 2 s settles to a still and reports it', () => { - const { canvas } = host(); - const onProbe = vi.fn(); - const s = createRidgeScene({ canvas, tier: 'full', onProbe, sky: DAY })!; - runFrames(100, 100); - expect(onProbe).toHaveBeenLastCalledWith(expect.objectContaining({ still: true })); - expect(rafQueue).toHaveLength(0); - s.dispose(); - }); - it("'still' tier never starts a loop", () => { const { parent, canvas } = host(); createRidgeScene({ canvas, tier: 'still' }); @@ -361,28 +272,6 @@ describe('createRidgeScene', () => { expect(rafQueue).toHaveLength(0); }); - it('?probe=1 keeps the rAF loop alive and shows median and p95', () => { - search = '?probe=1'; - const { parent, canvas } = host(); - const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, debug: true })!; - const readout = parent.children[parent.children.length - 1]; - runFrames(16.7, 300); - expect(rafQueue.length).toBe(1); // still sampling - expect(readout.textContent).toMatch(/median 16\.\d ms · p95 1[67]\.\d ms/); - s.dispose(); - expect(parent.children.some((c: any) => c === readout)).toBe(false); - }); - - it('?probe=1 does nothing where the overlays are not allowed: no readout, the loop ends', () => { - search = '?probe=1'; - const { parent, canvas } = host(); - const s = createRidgeScene({ canvas, tier: 'full', sky: DAY })!; - expect(parent.children).toEqual([canvas]); - runFrames(16.7, 300); - expect(rafQueue.length).toBe(0); - s.dispose(); - }); - it('a scene started at zero size paints nothing, then builds on the first non-zero resize', async () => { const { parent, canvas } = host(); canvas.clientWidth = 0; @@ -528,16 +417,6 @@ describe('the starfield in the scene', () => { s.dispose(); }); - it('flattening to a still (slow frames) drops the overlay and leaves every star baked into the sky', () => { - const { parent, canvas } = host(); - const s = createRidgeScene({ canvas, tier: 'full', sky: night })!; - runFrames(100, 100); - expect(parent.children).toEqual([canvas]); - expect(count('star')).toBe(NPLATE + N); // the plate's, then the still's own in the host canvas - expect(rafQueue).toHaveLength(0); - s.dispose(); - }); - it('dispose removes the overlay and stops the loop', () => { const { parent, canvas } = host(); const s = createRidgeScene({ canvas, tier: 'full', sky: night })!; @@ -662,13 +541,14 @@ describe('the ridge cards in the scene', () => { it('keeps the live sky, with every body baked into it, and the twinkle canvas in one plate under the rig; the host canvas is not painted', () => { const { parent, canvas } = host(); - createRidgeScene({ canvas, tier: 'full', sky: { ...night }, backdrop: litCards(), lines: true }); + const s = createRidgeScene({ canvas, tier: 'full', sky: { ...night }, backdrop: litCards(), lines: true })!; const rig = rigOf(parent); const plate = parent.children.find((c: any) => c.children.some((g: any) => g.tag === 'canvas')); expect(plate.children.map((c: any) => c.tag)).toEqual(['canvas', 'canvas']); // the sky, then the twinkle canvas over it expect(parent.children.indexOf(rig)).toBeGreaterThan(parent.children.indexOf(plate)); expect(draws.filter((d) => d === 'image')).toHaveLength(1); // only the plate's sky upscale: nothing in the host canvas, the cards are DOM above the plate expect(live(plate)).toHaveLength(1); // one animation slides it + s.dispose(); }); it('stacks the rig after the twinkle canvas and before the rain, with no z-index and no fixed position, and disposes the backdrop with itself', () => { @@ -1157,9 +1037,9 @@ describe('the ridge cards in the scene', () => { (window as any).clearTimeout = clearTimeout; const { canvas } = host(); const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!; - expect(rafQueue).toHaveLength(1); // the frame sampler, as without cards + expect(rafQueue).toHaveLength(0); vi.advanceTimersByTime(10_000); - expect(rafQueue).toHaveLength(1); + expect(rafQueue).toHaveLength(0); s.dispose(); vi.useRealTimers(); }); @@ -1370,361 +1250,41 @@ describe('the ridge cards in the scene', () => { setCamera({ mode: 'offset', speedDegPerS: 0.6, offsetM: 200 }); const { parent, canvas } = host(); const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: ringBackdrop(ring) })!; - const posed = (offset: number) => { + const poseTransform = (offset: number) => { const p = cardPose(ring, 0, poseAt(T0).h, poseAt(T0).phi, offset, w2); return `translate3d(${p.shiftPx}px,0,0) scale(${p.scale})`; }; - expect(frame(rigOf(parent).children[2], 0)).toBe(posed(98.2)); + expect(frame(rigOf(parent).children[2], 0)).toBe(poseTransform(98.2)); expect(getCamera().offsetM).toBe(200); setCamera({ mode: 'both' }); expect(getCamera().offsetM).toBe(200); const keys = live(rigOf(parent).children[2])[0].keyframes; - expect(keys[0].transform).toBe(posed(98.2)); // the view leaves from the offset it showed (the pick does not move it) ... - const p = cardPose(ring, 0, poseAt(T0 + STAGE_MS).h, 0, 200, w2); - expect(keys.find((f: any) => f.offset >= STAGE_MS / (SEGMENT_S * 1000) - 1e-9).transform).toBe(`translate3d(${p.shiftPx}px,0,0) scale(${p.scale})`); // ... and is at 200 when the ease is spent + expect(keys).toHaveLength(31); + expect(keys[0].transform).toBe(poseTransform(200)); s.dispose(); }); - it('eases a mode pick: the view the viewer saw is the first frame, the new regime the frame an EASE_MS later, one animation and no timer of its own', () => { + it('keeps every mode switch and rebuild clamped inside offsetRange and matching poseAt', () => { const ring = fixtureRing(); const w2 = windowFor(ring.view, 400, 800); setCamera({ mode: 'offset', speedDegPerS: 12, offsetM: 200 }); const { parent, canvas } = host(); const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: ringBackdrop(ring) })!; - const at = T0 + 7_500; // 90 degrees round its circle at 12 degrees a second, at the offset 98.2 the mode clamps to - const tf = (ms: number, phi: number, offset: number) => { - const p = cardPose(ring, 0, poseAt(at + ms).h, phi, offset, w2); - return { text: `translate3d(${p.shiftPx}px,0,0) scale(${p.scale})`, scale: p.scale }; - }; - expect(poseAt(at).phi).toBeCloseTo(90, 6); - const seen = tf(0, poseAt(at).phi, 98.2); + const at = T0 + 7_500; vi.mocked(performance.now).mockReturnValue(at); - setCamera({ mode: 'both' }, at); // phi goes to 0 and the clamp releases to 200: both used to land in one frame - const run = live(rigOf(parent).children[2])[0]; - expect(run.keyframes[0].transform).toBe(seen.text); - const spent = EASE_MS / (SEGMENT_S * 1000); - const end = run.keyframes.find((f: any) => f.offset >= spent - 1e-9); - const there = tf(EASE_MS, 0, 200); - expect(end.transform).toBe(there.text); - const eased = run.keyframes.filter((f: any) => f.offset <= spent + 1e-9); - expect(eased.length).toBeGreaterThan(10); // keyed finely while it runs - const scale = (f: any) => parseFloat(/scale\(([^)]*)\)/.exec(f.transform)![1]); - const jump = Math.abs(there.scale - seen.scale); - expect(jump).toBeGreaterThan(0.05); // the pop this pick used to be - eased.slice(1).forEach((f: any, i: number) => expect(Math.abs(scale(f) - scale(eased[i]))).toBeLessThan(jump / 4)); - expect(run.keyframes.at(-1).offset).toBe(1); + setCamera({ mode: 'both' }, at); + expect(poseAt(at)).toMatchObject({ phi: 0, r: 200 }); + const [loBoth, hiBoth] = offsetRange(ring, w2, 'both', poseAt(at).phi); + expect(poseAt(at).r).toBeGreaterThanOrEqual(loBoth); + expect(poseAt(at).r).toBeLessThanOrEqual(hiBoth); + const keys = live(rigOf(parent).children[2])[0].keyframes; + expect(keys).toHaveLength(31); + const p0 = cardPose(ring, 0, poseAt(at).h, poseAt(at).phi, poseAt(at).r, w2); + expect(keys[0].transform).toBe(`translate3d(${p0.shiftPx}px,0,0) scale(${p0.scale})`); s.dispose(); }); - describe('the ease of a mode pick stays inside the fit of the card slide', () => { - // The baked Vienna: its distances and its two bounds, as shipped. - const root = join(process.cwd(), 'public', 'ridge'); - const dir = parseIndex(JSON.parse(readFileSync(join(root, 'index.json'), 'utf8'))).places.vienna; - const vienna = parseManifest(JSON.parse(readFileSync(join(root, dir, 'manifest.json'), 'utf8')), `${dir}/`); - const FIT_PX_MAX = 24; // scripts/ridge-bake/export.py - /** The baker's `fit_px` (export.py): the worst error, in card px, of a card at distance `d` metres seen from offset `r` at camera angle `phiDeg`, against its best line over the widest field, the continuous error (the line by the trapezoid rule on 1025 samples, the error on the same). */ - const fitPx = (d: number, r: number, phiDeg: number, n = 1025): number => { - const phi = (phiDeg * Math.PI) / 180; - const half = (HFOV_MAX_DEG * Math.PI) / 360; - const b = Array.from({ length: n }, (_, i) => -half + (2 * half * i) / (n - 1)); - const a = b.map((x) => Math.atan2(d * Math.sin(x) - r * Math.sin(phi), d * Math.cos(x) - r * Math.cos(phi))); - const w = (i: number) => (i === 0 || i === n - 1 ? 0.5 : 1); - let sw = 0; - let sa = 0; - let sab = 0; - let sbb = 0; - a.forEach((y, i) => { - sw += w(i); - sa += w(i) * y; - sab += w(i) * y * b[i]; - sbb += w(i) * b[i] * b[i]; - }); - const mean = sa / sw; - const s = sab / sbb; - return (Math.max(...a.map((y, i) => Math.abs(y - (mean + s * b[i])))) * 180) / Math.PI * vienna.view.pxPerDegH; - }; - // The baker holds r_max for the NEAREST solid terrain each card draws in each tile, not its median distance_m (export.py pack); the manifest carries only the median. - // Vienna's nearest solid pixel is 500.4523 m (the baker's report, in every card 0 tile terrain stands at the 500 m near clip to within a metre), so that is the distance that binds, beside the medians. - const NEAREST_TERRAIN_M = 500.4523; - const distances = [NEAREST_TERRAIN_M, ...vienna.tiles.flatMap((row) => row.flatMap((e) => (e ? [e.distanceM] : [])))]; - /** The worst of every card of the bake at the camera angle `phiDeg` and offset `r`. */ - const worstPx = (r: number, phiDeg: number): number => Math.max(...distances.map((d) => fitPx(d, r, phiDeg))); - /** The same over the six nearest cards and 129 samples (the trapezoid rule is exact to a few thousandths of a pixel there): the nearest cards bind, and a property run asks it thousands of times. */ - const nearest = [...distances].sort((a, b) => a - b).slice(0, 6); - const quickPx = (r: number, phiDeg: number): number => Math.max(...nearest.map((d) => fitPx(d, r, phiDeg, 129))); - const w2 = windowFor(vienna.view, 400, 800); - /** The offset a keyframe's pose was made from: the one `cardPose` gives the transform at this heading and camera angle (a scan, then a finer one), with how far it is off. */ - const offsetOf = (transform: string, heading: number, phi: number): { r: number; miss: number } => { - const m = /translate3d\((-?[\d.e+-]+)px,0,0\) scale\((-?[\d.e+-]+)\)/.exec(transform)!; - const want = { shiftPx: Number(m[1]), scale: Number(m[2]) }; - const miss = (r: number) => { - const p = cardPose(vienna, 0, heading, phi, r, w2); - return Math.hypot(p.shiftPx - want.shiftPx, (p.scale - want.scale) * 400); - }; - let best = { r: 0, miss: Infinity }; - for (const step of [0.5, 0.02, 0.001]) { - const from = best.miss === Infinity ? -300 : best.r - 20 * step; - const to = best.miss === Infinity ? 300 : best.r + 20 * step; - for (let r = from; r <= to; r += step) { - const e = miss(r); - if (e < best.miss) best = { r, miss: e }; - } - } - return best; - }; - /** Every (camera angle, offset) a stretch of keyframes poses card 0 from, recovered from the transforms, from the pick on. */ - const pairsOf = (box: any, at: number): { phi: number; r: number; ms: number; miss: number }[] => { - const keys = live(box)[0].keyframes; - return keys.map((f: any, n: number) => { - const ms = (f.offset ?? n / (keys.length - 1)) * SEGMENT_S * 1000; - const phi = poseAt(at + ms).phi; - return { phi, ms, ...offsetOf(f.transform, poseAt(at + ms).h, phi) }; - }); - }; - const pick = (from: { mode: 'both' | 'offset'; speed: number; waitS: number }, to: 'both' | 'offset') => { - setCamera({ mode: from.mode, speedDegPerS: from.speed, offsetM: 200 }); - const { parent, canvas } = host(); - const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: ringBackdrop(vienna) })!; - const at = T0 + from.waitS * 1000; - vi.mocked(performance.now).mockReturnValue(at); - setCamera({ mode: to }, at); - const got = pairsOf(rigOf(parent).children[2], at); - s.dispose(); - return got; - }; - - it('measures the fit as the baker does: Vienna sits at the bound at its two offsets, and above it past them', () => { - const { rMaxM, rMaxForwardM } = vienna.camera; - expect([rMaxM, rMaxForwardM]).toEqual([95.8, 198.4]); - const circle = Array.from({ length: 24 }, (_, i) => i * 15); - expect(Math.max(...circle.map((phi) => worstPx(rMaxM, phi)))).toBeGreaterThan(FIT_PX_MAX - 0.5); - expect(Math.max(...circle.map((phi) => worstPx(rMaxM, phi)))).toBeLessThanOrEqual(FIT_PX_MAX + 0.05); - expect(worstPx(rMaxForwardM, 0)).toBeGreaterThan(FIT_PX_MAX - 0.5); - expect(worstPx(rMaxForwardM, 0)).toBeLessThanOrEqual(FIT_PX_MAX + 0.05); - expect(worstPx(200, 90)).toBeGreaterThan(FIT_PX_MAX); // the blend the ease used to pass through - expect(worstPx(rMaxForwardM + 1, 0)).toBeGreaterThan(FIT_PX_MAX); // past the forward bound, and the circle's bound is not the forward one - expect(Math.max(...circle.map((phi) => worstPx(rMaxM + 1, phi)))).toBeGreaterThan(FIT_PX_MAX); - }); - - [ - { name: 'offset-only to both from the camera a quarter round', from: { mode: 'offset', speed: 12, waitS: 7.5 }, to: 'both' }, - { name: 'offset-only to both with the camera half way round', from: { mode: 'offset', speed: 12, waitS: 15 }, to: 'both' }, - { name: 'offset-only to both with the camera just off its heading', from: { mode: 'offset', speed: 12, waitS: 1.25 }, to: 'both' }, - { name: 'both to offset-only at the default speed', from: { mode: 'both', speed: 0.6, waitS: 3 }, to: 'offset' }, - { name: 'both to offset-only at the fastest turn', from: { mode: 'both', speed: 12, waitS: 3 }, to: 'offset' }, - ].forEach(({ name, from, to }) => { - it(`${name}: every keyframe is the pose of an angle and an offset inside the card fit, at Vienna's bounds`, () => { - const got = pick(from as any, to as any); - expect(got.length).toBeGreaterThan(12); - got.forEach((g) => expect(g.miss, `a pose of the camera at ${g.phi.toFixed(1)} degrees, ${g.r.toFixed(1)} m`).toBeLessThan(0.05)); - const worst = Math.max(...got.map((g) => worstPx(g.r, g.phi))); - expect(worst).toBeLessThanOrEqual(FIT_PX_MAX + 0.05); - // The angle and the offset take a stage each: never both between their ends at once. - const moving = (v: number[], i: number) => i > 0 && Math.abs(v[i] - v[i - 1]) > 1e-3; - const phis = got.map((g) => g.phi); - const rs = got.map((g) => g.r); - got.forEach((_, i) => expect(moving(phis, i) && moving(rs, i), `keyframe ${i}`).toBe(false)); - const last = got.at(-1)!; - expect(last.r).toBeCloseTo(to === 'both' ? Math.min(200, vienna.camera.rMaxForwardM) : vienna.camera.rMaxM, 1); // the offset owed: the default 200 or the forward bound, or the bound of the circling mode - if (to === 'both') expect(last.phi % 360).toBe(0); - }); - }); - - /** A transform's two numbers. */ - const parsed = (transform: string): { shift: number; scale: number } => { - const m = /translate3d\((-?[\d.e+-]+)px,0,0\) scale\((-?[\d.e+-]+)\)/.exec(transform)!; - return { shift: Number(m[1]), scale: Number(m[2]) }; - }; - /** What the compositor shows `ms` into an animation: the keyframes' straight lines. */ - const playedAt = (anim: any, ms: number): { shift: number; scale: number } => { - const keys: any[] = anim.keyframes; - const at = (k: number) => (keys[k].offset ?? k / (keys.length - 1)) * anim.options.duration; - let k = 1; - while (k < keys.length - 1 && at(k) < ms) k += 1; - const [a, b] = [parsed(keys[k - 1].transform), parsed(keys[k].transform)]; - const x = Math.min(1, Math.max(0, (ms - at(k - 1)) / (at(k) - at(k - 1)))); - return { shift: a.shift + (b.shift - a.shift) * x, scale: a.scale + (b.scale - a.scale) * x }; - }; - - describe('a pick made while an ease is under way, and a rebuild in the middle of one', () => { - const picks: { name: string; from: 'both' | 'offset'; waitS: number; then: ['still' | 'offset' | 'both', number][] }[] = [ - { name: 'offset-only to both, then to still a moment later', from: 'offset', waitS: 7.8, then: [['both', 0], ['still', 100]] }, - { name: 'offset-only to both, then back to offset-only', from: 'offset', waitS: 7.8, then: [['both', 0], ['offset', 100]] }, - { name: 'offset-only to both, to still, and to both again', from: 'offset', waitS: 7.8, then: [['both', 0], ['still', 100], ['both', 150]] }, - { name: 'offset-only to both, then offset-only as the angle lands', from: 'offset', waitS: 7.8, then: [['both', 0], ['offset', 295]] }, - { name: 'offset-only to both, then still with the offset on its way out', from: 'offset', waitS: 7.8, then: [['both', 0], ['still', 450]] }, - { name: 'both to offset-only, then to both before the offset is in', from: 'both', waitS: 3, then: [['offset', 0], ['both', 150]] }, - { name: 'both to offset-only, then to still, then to offset-only', from: 'both', waitS: 3, then: [['offset', 0], ['still', 100], ['offset', 120]] }, - ]; - picks.forEach(({ name, from, waitS, then }) => { - it(`${name}: every keyframe the last pick lays out is the pose of an angle and an offset inside the card fit`, () => { - setCamera({ mode: from, speedDegPerS: 12, offsetM: 200 }); - const { parent, canvas } = host(); - const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: ringBackdrop(vienna) })!; - let at = T0 + waitS * 1000; - for (const [mode, after] of then) { - at += after; - vi.mocked(performance.now).mockReturnValue(at); - setCamera({ mode }, at); - } - const got = pairsOf(rigOf(parent).children[2], at); - got.forEach((g) => expect(g.miss, `a pose of the camera at ${g.phi.toFixed(1)} degrees, ${g.r.toFixed(1)} m`).toBeLessThan(0.05)); - const worst = Math.max(...got.map((g) => worstPx(g.r, g.phi))); - expect(worst).toBeLessThanOrEqual(FIT_PX_MAX + 0.05); - s.dispose(); - }); - }); - - it('a rebuild in the middle of an ease lands where the old scene was: the first frame of the new rig is the frame the old one showed', () => { - pending(); - for (const gap of [100, 250, 400, 550]) { - resetHeading(); - resetCamera(); - vi.mocked(performance.now).mockReturnValue(T0); - anchor(vienna.view.place.id, vienna.view.lookAzDeg, T0); - setCamera({ mode: 'offset', speedDegPerS: 12, offsetM: 200 }); - const { parent, canvas } = host(); - const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: ringBackdrop(vienna) })!; - const at = T0 + 7_800; - vi.mocked(performance.now).mockReturnValue(at); - setCamera({ mode: 'both' }, at); - const old = rigOf(parent).children.map((box: any) => live(box)[0]); - vi.mocked(performance.now).mockReturnValue(at + gap); - window.dispatchEvent(new Event('resize')); - vi.advanceTimersByTime(300); // the debounced rebuild: a new rig at this clock - const now = rigOf(parent).children.map((box: any) => live(box)[0]); - now.forEach((a: any, i: number) => { - expect(a).not.toBe(old[i]); - const was = playedAt(old[i], gap); - const is = parsed(a.keyframes[0].transform); - expect(Math.abs(is.shift - was.shift), `card ${i} ${gap} ms into the ease`).toBeLessThan(2); - expect(Math.abs(is.scale - was.scale), `card ${i} ${gap} ms into the ease`).toBeLessThan(0.01); - }); - s.dispose(); - } - vi.useRealTimers(); - }); - }); - - describe('random sequences of picks, holds, speeds, offsets and rebuilds at random times', () => { - /** A seeded generator (mulberry32): a failing sequence is the seed it prints. */ - const random = (seed: number) => () => { - seed = (seed + 0x6d2b79f5) | 0; - let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); - t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; - return ((t ^ (t >>> 14)) >>> 0) / 4294967296; - }; - const modes = ['still', 'offset', 'both'] as const; - const inside = ([lo, hi]: [number, number], v: number, slack = 1e-6) => v >= lo - slack && v <= hi + slack; - - /** Every pose a laid-out stretch passes through is one the baker's bound allows, at the offset it has: whenever the camera angle moves, the circle's bound holds at both ends; and the keyframes are the poses the heading owner has. */ - const checkLayout = (parent: any, label: string) => { - const boxes = rigOf(parent).children as any[]; - boxes.forEach((box) => expect(live(box)).toHaveLength(1)); - // The rig lays every card out from the owner's pose at the clock of each keyframe. - boxes.forEach((box) => { - const card = Number(box.id.slice(-1)); - const { keyframes, options, at } = live(box)[0]; - keyframes.forEach((f: any, n: number) => { - const t = at + (f.offset ?? n / (keyframes.length - 1)) * options.duration; - const p = poseAt(t); - const c = cardPose(vienna, card, p.h, p.phi, p.r, w2); - expect(f.transform, `${label}: card ${card} keyframe ${n}`).toBe(`translate3d(${c.shiftPx}px,0,0) scale(${c.scale})`); - }); - }); - // The pose itself, every 2 ms through the ease and every half second after. - const t0: number = live(boxes[0])[0].at; - const home = Math.max(t0, settledAt()); - const times: number[] = []; - for (let t = t0; t <= home + 2; t += 2) times.push(t); - for (let t = home; t <= t0 + SEGMENT_S * 1000; t += 500) times.push(t); - let last = poseAt(times[0]); - times.forEach((t, i) => { - const p = poseAt(t); - expect(inside(offsetRange(vienna, w2, 'both', p.phi), p.r), `${label}: phi ${p.phi}, r ${p.r} at +${t - t0} ms`).toBe(true); - if (i && Math.abs(p.phi - last.phi) > 1e-9) { - const circle = offsetRange(vienna, w2, 'offset'); - expect(inside(circle, p.r, 0.02) && inside(circle, last.r, 0.02), `${label}: the angle moves with r ${last.r} then ${p.r} at +${t - t0} ms`).toBe(true); - } - if (i % 40 === 0 || i === times.length - 1) expect(quickPx(p.r, p.phi), `${label}: fit at phi ${p.phi}, r ${p.r}`).toBeLessThanOrEqual(FIT_PX_MAX + 0.1); - last = p; - }); - }; - - let inEase = 0; - const sequence = (seed: number): number => { - const next = random(seed); - const pick = (xs: readonly T[]): T => xs[Math.floor(next() * xs.length)]; - resetHeading(); - resetCamera(); - const clock = vi.mocked(performance.now); - let now = T0; - clock.mockReturnValue(now); - anchor(vienna.view.place.id, vienna.view.lookAzDeg, T0); - setCamera({ mode: pick(modes), speedDegPerS: pick([0.6, 3, 12, -12, 0]), offsetM: pick([200, 98, -60, 0, 999]) }, now); - let { parent, canvas } = host(); - let scene = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: ringBackdrop(vienna) })!; - let rebuilds = 0; - for (let step = 0; step < 36; step += 1) { - const gap = pick([0, 20, 60, 100, 150, 299, 301, 450, 700, 3000, 24_500]); - now += gap; - clock.mockReturnValue(now); - vi.advanceTimersByTime(gap); - const label = `seed ${seed} step ${step}`; - const op = Math.floor(next() * 9); - const before = poseAt(now); - const fine = now <= settledAt(); // the old stretch is keyed every 50 ms here, a second apart after: the straight lines between keyframes are the pose only where they are close - const old = rigOf(parent).children.map((box: any) => live(box)[0]); - if (op <= 2) setCamera({ mode: pick(modes) }, now); - else if (op === 3) hold(next() * 1000 - 300, now); - else if (op === 4) setCamera({ speedDegPerS: pick([0.6, 3, 12, -12, 0, 7.5]) }, now); - else if (op === 5) setCamera({ offsetM: Math.round(next() * 600 - 300) }, now); - else if (op === 6) setCamera({ mode: pick(modes), speedDegPerS: pick([0.6, 12, -12]), offsetM: pick([200, 0, 50]) }, now); - else if (op === 7) { - window.dispatchEvent(new Event('resize')); - vi.advanceTimersByTime(300); - } else { - scene.dispose(); - ({ parent, canvas } = host()); - scene = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: ringBackdrop(vienna) })!; - } - if (op >= 7) { - rebuilds += 1; - if (fine) inEase += 1; - // A rebuild changes where nothing is: the owner's pose is the same before and after it, and the first frame laid out is the frame that was showing. - const after = poseAt(now); - expect(after.r, label).toBeCloseTo(before.r, 9); - expect(norm(after.phi), label).toBeCloseTo(norm(before.phi), 6); - expect(norm(after.h), label).toBeCloseTo(norm(before.h), 6); - rigOf(parent).children.forEach((box: any, i: number) => { - if (!fine) return; - const was = playedAt(old[i], now - old[i].at); - const is = parsed(live(box)[0].keyframes[0].transform); - // The new stretch is laid out from angles brought into [0, 360): a whole turn of the heading is a whole turn of the shift, the same picture. - const turn = is.scale * w2.plane.scale * vienna.view.pxPerDegH * 360; - const jump = Math.abs(is.shift - was.shift); - expect(Math.abs(jump - turn * Math.round(jump / turn)), `${label}: card ${i} popped at the rebuild`).toBeLessThan(3); - expect(Math.abs(is.scale - was.scale), `${label}: card ${i} popped at the rebuild`).toBeLessThan(0.02); - }); - } - checkLayout(parent, label); - } - scene.dispose(); - return rebuilds; - }; - - it('every pose laid out is inside the bound the baker set, and a rebuild never moves the view', () => { - pending(); - let rebuilds = 0; - for (let seed = 1; seed <= 24; seed += 1) rebuilds += sequence(seed); - expect(rebuilds).toBeGreaterThan(100); - expect(inEase).toBeGreaterThan(10); // and some of them in the middle of eases, not only at rest - vi.useRealTimers(); - }, 120_000); - }); - }); - - describe('under reduced motion there is no ease: the pose owed is the pose issued', () => { + describe('under reduced motion rotation stops and the clamped pose is issued at once', () => { const owed = (ring: typeof manifest, offset: number, phi: number, at = T0) => { const p = cardPose(ring, 0, poseAt(at).h, phi, offset, windowFor(ring.view, 400, 800)); return `translate3d(${p.shiftPx}px,0,0) scale(${p.scale})`; @@ -1837,7 +1397,7 @@ describe('the ridge cards in the scene', () => { lit.push(...all.filter((t) => t.tile === tile)); heard.forEach((cb) => cb()); }; - return { bd, arrive, listeners: () => heard.size }; + return { bd, arrive }; }; const drawnTiles = () => new Set(images.filter((a) => (a[0] as any).id).map((a: any) => a[0].id.slice(0, 3))); const timers = () => { @@ -1898,44 +1458,14 @@ describe('the ridge cards in the scene', () => { expect(placed('t18')).not.toEqual(first); s.dispose(); }); - - it('is the same after a settle from the live tier, and stops listening with the scene', () => { - timers(); - const { bd, arrive, listeners } = arriving([18]); - const { canvas } = host(); - const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: bd })!; - arrive(17); - vi.advanceTimersByTime(1_000); - expect(images.length).toBe(0); // the live tier mounts tiles from its own timer: nothing is painted into the host canvas - runFrames(100, 400); // a poor frame rate: it settles to a still - const settled = images.length; - expect(drawnTiles()).toEqual(new Set(['t18', 't17'])); - arrive(19); - vi.advanceTimersByTime(300); - expect(images.length).toBeGreaterThan(settled); - expect(drawnTiles().has('t19')).toBe(true); - s.dispose(); - expect(listeners()).toBe(0); - const after = images.length; - arrive(20); - vi.advanceTimersByTime(1_000); - expect(images.length).toBe(after); - }); - }); - - it('settles to a still with the tiles painted when the frame rate is poor', () => { - const { parent, canvas } = host(); - createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() }); - runFrames(100, 400); - expect(images.filter((a) => (a[0] as any).id).length).toBeGreaterThan(0); - expect(parent.children).toEqual([canvas]); }); it('with no backdrop it is the sky alone', () => { const { parent, canvas } = host(); - createRidgeScene({ canvas, tier: 'full', sky: DAY }); + const s = createRidgeScene({ canvas, tier: 'full', sky: DAY })!; expect(parent.children).toEqual([canvas]); expect(images.filter((a) => (a[0] as any).id)).toHaveLength(0); + s.dispose(); }); it('asks the host canvas, and every canvas it makes, only for 2d: the tiles arrive lit', () => { diff --git a/src/app/features/scene/ridge/Ridge.ts b/src/app/features/scene/ridge/Ridge.ts index b6f5d729..a4c8a1d0 100644 --- a/src/app/features/scene/ridge/Ridge.ts +++ b/src/app/features/scene/ridge/Ridge.ts @@ -1,13 +1,11 @@ -import type { Scene, SceneOptions } from '../Scene'; -import { overlayRequested } from '../debugOverlays'; -import { FrameSampler, FrameStats } from './probe'; -import { skyColours, SkyColours, Srgb } from './skyColour'; +import type { SceneTier } from '../tier'; import { paintSky as paintPhysicalSky } from './physicalSky'; +import type { SkyColours, Srgb } from './physicalSky'; import { cardArc, cardPose, HFOV_MAX_DEG, offsetRange, SEGMENT_S, sweepArc, windowFor } from './view'; import type { Camera, CardPose, View } from './view'; import type { TileCard } from './manifest'; import { residentTiles } from './ring'; -import { freeze, normalize, poseAt as headingPose, setRange, settledAt, subscribe as onHeading, turnRate } from './heading'; +import { freeze, normalize, poseAt as headingPose, setRange, subscribe as onHeading, turnRate } from './heading'; import type { Pose } from './heading'; import { activeAt, drawTwinkle as paintTwinkle, slotsFor, Star } from './stars'; import { STAR_COUNT } from './nightSkyData'; @@ -17,14 +15,14 @@ import type { NightBodies } from './nightBodies'; import { drawRainTile, RAIN_TILES } from './rain'; import type { Arc, Backdrop, LitTile } from './Backdrop'; -export type RidgeOptions = Pick & { - /** Show the rAF median/p95 readout. Default: the page URL has `?probe=1`, where `debug` allows it. */ - probe?: boolean; - /** The diagnostic overlays may be asked for by URL (debugOverlays.ts). Default: no. */ - debug?: boolean; - /** Each time the readout would update, and once with `still` when the fallback fires. */ - onProbe?: (s: FrameStats & { still: boolean }) => void; - /** The sky's colours; default `skyColours()`, the one function to replace with Void's sun.js. */ +export interface Scene { + dispose(): void; +} + +export type RidgeOptions = { + canvas: HTMLCanvasElement; + tier?: SceneTier; + /** The sky's colours; defaults to a twilight gradient when omitted. */ sky?: SkyColours; /** The baked ridge cards by tile, lit for `sky` (`Backdrop.ts`), the arc around the heading already made; none is the sky-only scene (`view.ts` FALLBACK_VIEW). The scene owns it from here and disposes it with itself. */ backdrop?: Backdrop; @@ -32,6 +30,12 @@ export type RidgeOptions = Pick & { lines?: boolean; }; +const FALLBACK_SKY: SkyColours = { + top: [170, 145, 220], + mid: [225, 130, 165], + horizon: [240, 150, 80], +}; + const css = (c: Srgb): string => `rgb(${c[0]},${c[1]},${c[2]})`; function context2d(c: HTMLCanvasElement): CanvasRenderingContext2D | null { return c.getContext('2d'); @@ -161,36 +165,23 @@ const REISSUE_FRAC = 0.8; /** How often the arc of tiles ahead is asked for and the mounted tiles are brought up to date. */ export const RESIDENCY_MS = 500; -/** Keyframe spacing while an ease runs, ms: fine enough that the straight lines between them are the smoothstep to a pixel. */ -const EASE_KEY_MS = 50; -/** The instants of a stretch keyed finely up to `easeMs`, then every second to SEGMENT_S: ms from the stretch's start, ascending, ending at the stretch's length. */ -const easeTimes = (easeMs: number): number[] => { - const times: number[] = []; - for (let ms = 0; ms < easeMs; ms += EASE_KEY_MS) times.push(ms); - times.push(easeMs); - for (let ms = (Math.floor(easeMs / 1000) + 1) * 1000; ms <= SEGMENT_S * 1000; ms += 1000) times.push(ms); - return times; -}; - /** - * The keyframes of a stretch of motion from `t0` (ms), the transform at each instant from `transformAt`: a keyframe a second for SEGMENT_S seconds, finely - * keyed while an ease of the heading owner runs, constant under reduced motion. The cards and the sky are keyed by it alike, so they turn together. + * The keyframes of a stretch of motion from `t0` (ms), the transform at each instant from `transformAt`: a keyframe a second for SEGMENT_S seconds, + * constant under reduced motion. The cards and the sky are keyed by it alike, so they turn together. */ const stretch = (t0: number, frozen: boolean, transformAt: (t: number) => string): Keyframe[] => { if (frozen) { const at = transformAt(t0); return [{ transform: at }, { transform: at }]; } - const easeMs = Math.min(SEGMENT_S * 1000, Math.max(0, settledAt() - t0)); - if (easeMs > 0) return easeTimes(easeMs).map((ms) => ({ transform: transformAt(t0 + ms), offset: ms / (SEGMENT_S * 1000) })); return Array.from({ length: SEGMENT_S + 1 }, (_, n) => ({ transform: transformAt(t0 + n * 1000) })); }; /** - * The ridge scene: same contract as `createScene` ({ login, dispose }, null for "keep the CSS - * ground"). It draws the sky, the stars, the lit ridge cards when given a `backdrop` (none: the sky alone) and the rain. The scene itself - * requests no WebGL: the cards arrive lit (`lightCards.ts`, once per scene build) and only 2D contexts are asked of the host canvas. The host canvas holds the baked sky; it and - * its parent must be positioned, and the canvas should fill the parent. + * The ridge scene ({ dispose }, null for "keep the CSS ground"). It draws the sky, the stars, the lit ridge cards when given a `backdrop` + * (none: the sky alone) and the rain. The scene itself requests no WebGL: the cards arrive lit (`lightCards.ts`, once per scene build) and + * only 2D contexts are asked of the host canvas. The host canvas holds the baked sky; it and its parent must be positioned, and the canvas + * should fill the parent. */ export function createRidgeScene(opts: RidgeOptions): Scene | null { const tier = opts.tier ?? 'full'; @@ -198,8 +189,7 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { const canvas = opts.canvas; const parent = canvas.parentElement; if (!parent) return null; - const sky = opts.sky ?? skyColours(); - const probe = opts.probe ?? overlayRequested('probe', opts.debug === true); + const sky = opts.sky ?? FALLBACK_SKY; const reducedMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)'); let built: Built | undefined; @@ -207,14 +197,11 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { let twLast = 0; /** Paint a plate's twinkle canvas at t seconds, or clear it (set by the plate the scene is up with). */ let paintTwinkleOf: (of: Pick, t?: number) => void = () => undefined; - let still = tier === 'still'; + const still = tier === 'still'; let disposed = false; - let raf = 0; - let readout: HTMLElement | undefined; let resizeTimer = 0; /** The pose a still shows: taken at its first paint and drawn at every repaint after, tile arrivals included; a resize takes a new one. A still has no clock. */ let stillPose: Pose | undefined; - const sampler = new FrameSampler(); const viewSize = () => { const w = canvas.clientWidth || window.innerWidth; @@ -619,7 +606,7 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { } else if (!paintSky(canvas, sky, undefined, w, h, makeCanvas).ok) return false; } if (opts.backdrop) { - // The offsets this place and viewport allow, to the one owner of the pose: a rebuild at another size is a new bound, and the view eases from the pose it has. + // The offsets this place and viewport allow, to the heading owner: a rebuild clamps directly from the pose it has. const { manifest } = opts.backdrop; const win = windowFor(manifest.view, w, h); setRange((mode, phi) => offsetRange(manifest, win, mode, phi), clock()); @@ -668,76 +655,12 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { } } - /** Drop the twinkle and the rain, leaving the painted sky as a still image. */ - const settleToStill = () => { - if (still && !built) return; - if (!still) stillPose = undefined; // a live scene that flattens freezes the pose it has now - still = true; - teardown(); - cancelAnimationFrame(raf); - raf = 0; - paintStill(); - report(true); - }; - - const report = (stillNow: boolean) => { - const s = { ...sampler.stats(), still: stillNow }; - opts.onProbe?.(s); - if (readout) { - readout.textContent = `ridge · n ${s.n} · median ${s.medianMs.toFixed( - 1 - )} ms · p95 ${s.p95Ms.toFixed(1)} ms${stillNow ? ' · STILL' : ''}`; - } - }; - - let sinceReport = 0; - const tick = (now: number) => { - raf = 0; - if (!moving()) return; - const full = sampler.push(now); - if (full && sampler.slow() && !still) { - settleToStill(); - return; - } - // After the window the series keeps rolling only for the readout; otherwise the loop ends here. - if (full && !probe) return; - if (probe && now - sinceReport > 500) { - sinceReport = now; - report(false); - } - raf = requestAnimationFrame(tick); - }; - - const wake = () => { - syncPlayState(); - if (!moving() || raf) return; - sampler.reset(); - raf = requestAnimationFrame(tick); - }; - // No area yet is not a failure: the resize listener below builds once the host has one. if (!build() && !hasNoArea()) return null; - if (probe) { - readout = document.createElement('div'); - Object.assign(readout.style, { - position: 'absolute', - left: '8px', - top: '8px', - font: '12px monospace', - color: '#fff', - background: 'rgba(0,0,0,.55)', - padding: '2px 6px', - borderRadius: '3px', - pointerEvents: 'none', - }); - parent.appendChild(readout); - } - if (still) settleToStill(); - else wake(); + if (still) paintStill(); const onVisibility = () => { - sampler.reset(); - wake(); + syncPlayState(); }; /** Make the scene again at the size it has now and settle as it was: after a resize, and after tiles arrive into a still. A burst of either is one rebuild, 250 ms after the last. */ let freshPose = false; @@ -746,22 +669,17 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { clearTimeout(resizeTimer); resizeTimer = window.setTimeout(() => { if (disposed) return; - const wasStill = still; if (freshPose) { // A resize is a new view: a still takes the pose the heading has now and asks for the tiles of it; the arrivals then repaint that pose. stillPose = undefined; - if (wasStill && opts.backdrop) { + if (still && opts.backdrop) { const { h } = headingPose(clock()); opts.backdrop.ensure({ fromDeg: h - HFOV_MAX_DEG / 2, toDeg: h + HFOV_MAX_DEG / 2 }).catch(() => undefined); } } freshPose = false; if (!build()) return; - if (wasStill) settleToStill(); - else { - sampler.reset(); - wake(); - } + if (still) paintStill(); }, 250); }; // A still draws once and has no timer to ask for tiles, so it is told of each one that is made after its paint (the deadline of a scene start leaves the rest of the @@ -779,13 +697,9 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { reducedMotion?.addEventListener?.('change', onMotionChange); return { - login() { - // No camera to pull back; the sky is the same before and after. - }, dispose() { if (disposed) return; disposed = true; - cancelAnimationFrame(raf); offTile?.(); opts.backdrop?.dispose(); clearTimeout(resizeTimer); @@ -793,7 +707,6 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { window.removeEventListener('resize', onResize); reducedMotion?.removeEventListener?.('change', onMotionChange); teardown(); - readout?.remove(); }, }; } diff --git a/src/app/features/scene/ridge/credits.test.ts b/src/app/features/scene/ridge/credits.test.ts index 4ab1e58e..20c85985 100644 --- a/src/app/features/scene/ridge/credits.test.ts +++ b/src/app/features/scene/ridge/credits.test.ts @@ -1,13 +1,7 @@ import { readFileSync } from 'node:fs'; import { join } from 'node:path'; import { describe, expect, it } from 'vitest'; -import { - LINES_CREDIT, - LINES_SOURCE_URL, - STARS_CREDIT, - STARS_SOURCE_URL, - terrainCredit, -} from './credits'; +import { LINES_CREDIT, STARS_CREDIT, terrainCredit } from './credits'; import { parseIndex, parseManifest } from './manifest'; import { wireManifest } from './manifest.fixture'; @@ -35,11 +29,7 @@ describe('the terrain credit', () => { }); describe('the night sky credits', () => { - const data = readFileSync(join(__dirname, 'nightSkyData.ts'), 'utf8'); - it("name the sources the generated data's header names, with their licences", () => { - expect(data).toContain(STARS_SOURCE_URL); - expect(data).toContain(LINES_SOURCE_URL); - expect(data).toMatch(/BSD-3-Clause/); + it('name the star catalogue and constellation lines sources with their licences', () => { expect(STARS_CREDIT).toMatch(/Yale Bright Star Catalogue.*public domain/); expect(LINES_CREDIT).toMatch(/Olaf Frohn.*BSD-3-Clause/); }); diff --git a/src/app/features/scene/ridge/heading.test.ts b/src/app/features/scene/ridge/heading.test.ts index 4019bc70..67847e19 100644 --- a/src/app/features/scene/ridge/heading.test.ts +++ b/src/app/features/scene/ridge/heading.test.ts @@ -1,8 +1,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { anchor, freeze, hold, normalize, poseAt, resetHeading, setRange, settledAt, STAGE_MS, subscribe, turnRate } from './heading'; +import { anchor, freeze, hold, normalize, poseAt, resetHeading, setRange, subscribe, turnRate } from './heading'; import type { RotationMode } from './heading'; import * as camera from '../cameraState'; -import { effectiveMode, getCamera, isHeld, resetCamera, setCamera, subscribe as onCamera } from '../cameraState'; +import { effectiveMode, getCamera, isHeld, resetCamera, setCamera } from '../cameraState'; import { maxSpeed } from './view'; import { norm } from './ring'; import { parseManifest } from './manifest'; @@ -13,12 +13,13 @@ const S = 1000; /** The viewer's choice, at the clock `at` (ms): the one way the mode and the speed reach the view. */ const choose = (mode: RotationMode, speedDegPerS: number, at: number) => setCamera({ mode, speedDegPerS }, at); -/** The bound of a baked place, as `view.ts` `offsetRange` draws it: 100 m round the circle, 200 m forward with the camera exactly on its heading and the view turning with it. */ +/** The bound of a baked place, as `view.ts` `offsetRange` draws it: 100 m round the circle, 200 m forward with the camera on its heading. */ const BACK = 100; const FORWARD = 200; -const range = (mode: RotationMode, phi: number): [number, number] => [-BACK, mode !== 'offset' && Math.abs(norm(phi + 180) - 180) < 1e-6 ? FORWARD : BACK]; -/** Whether a pose is one the bound allows, whatever mode led there. */ -const fits = (p: { phi: number; r: number }): boolean => p.r >= range('both', p.phi)[0] - 1e-9 && p.r <= range('both', p.phi)[1] + 1e-9; +const range = (mode: RotationMode, phi: number): [number, number] => [ + -BACK, + mode !== 'offset' && Math.abs(norm(phi + 180) - 180) < 1e-6 ? FORWARD : BACK, +]; const store = new Map(); @@ -95,26 +96,14 @@ describe('the heading owner', () => { expect(poseAt(104 * S)).toMatchObject({ h: 120, phi: 30 }); }); - it('puts the camera back on its heading when the view direction is made to turn with it, by the short way round, and the view direction turns meanwhile', () => { + it('puts the camera directly back on its heading when switching to both, and turns the view direction from there', () => { anchor('p', 100, 0); choose('offset', 12, 0); expect(poseAt(7.5 * S).phi).toBeCloseTo(90, 9); choose('both', 12, 7.5 * S); - expect(poseAt(7.5 * S)).toMatchObject({ h: 100 }); // the pick moves nothing in the frame it is made - const gone = [0, 0.25, 0.5, 0.75, 1].map((x) => poseAt(7.5 * S + x * STAGE_MS).phi); - gone.slice(1).forEach((v, i) => expect(v).toBeLessThan(gone[i])); - expect(gone[4]).toBe(0); - expect(poseAt(7.5 * S + 5 * S).phi).toBe(0); - expect(poseAt(7.5 * S + 5 * S).h).toBeCloseTo(100 + 12 * 5, 9); - // 270 degrees on is 90 short of home the other way: the camera goes forward to 360, not back through 270. - choose('offset', 12, 20 * S); - choose('offset', 12, 20 * S + 22.5 * S); - const t = 20 * S + 22.5 * S; - expect(norm(poseAt(t).phi)).toBeCloseTo(270, 9); - choose('both', 12, t); - const mid = poseAt(t + STAGE_MS / 2).phi; - expect(norm(mid)).toBeGreaterThan(270); - expect(norm(poseAt(t + STAGE_MS).phi)).toBeCloseTo(0, 9); + expect(poseAt(7.5 * S)).toMatchObject({ h: 100, phi: 0 }); + expect(poseAt(12.5 * S).phi).toBe(0); + expect(poseAt(12.5 * S).h).toBeCloseTo(100 + 12 * 5, 9); }); it('a speed change takes effect from now, without moving the view', () => { @@ -214,7 +203,7 @@ describe('the heading owner', () => { expect(poseAt(60 * S).h).toBe(20); }); - it('normalizes into [0, 360) without changing the view, so the angles never grow with uptime, and an ease under way goes on as it was', () => { + it('normalizes into [0, 360) without changing the view, so the angles never grow with uptime', () => { anchor('p', 0, 0); choose('both', 6, 0); const day = 24 * 3600 * S; @@ -231,18 +220,6 @@ describe('the heading owner', () => { setCamera({ speedDegPerS: -6 }, day + 100 * S); normalize(day + 101 * S); expect(poseAt(day + 101 * S).phi).toBeGreaterThanOrEqual(0); // a turn the other way is brought into range too - // An ease is the same ease before and after it is renormalized, in the middle. - choose('offset', 12, day + 200 * S); - choose('both', 12, day + 207.5 * S); - const at = day + 207.5 * S; - const before = [0.2, 0.5, 0.9].map((x) => poseAt(at + x * STAGE_MS)); - normalize(at + 0.3 * STAGE_MS); - const after = [0.2, 0.5, 0.9].map((x) => poseAt(at + x * STAGE_MS)); - after.forEach((p, i) => { - expect(norm(p.phi)).toBeCloseTo(norm(before[i].phi), 6); - expect(norm(p.h)).toBeCloseTo(norm(before[i].h), 6); - expect(p.r).toBeCloseTo(before[i].r, 9); - }); }); it('tells subscribers of every change of its course: a choice, a hold, a bound, a manual turn while held, a new place; and of nothing that changes nothing', () => { @@ -267,25 +244,7 @@ describe('the heading owner', () => { expect(cb).toHaveBeenCalledTimes(5); }); - it('is the one owner of the order: the heading is current when a listener of the camera hears of a change, whenever the listener registered', () => { - setCamera({ mode: 'both', speedDegPerS: 1 }, 0); - const early: number[] = []; - const offEarly = onCamera((_n, _p, at) => early.push(poseAt(at).h)); // before the place is anchored: first of the listeners, as a control mounted before the scene start is - anchor('p', 214, 0); - const late: number[] = []; - const offLate = onCamera((_n, _p, at) => late.push(poseAt(at).h)); - anchor('p', 214, 1 * S); // a rebuild for a sky anchors the same place again - setCamera({ speedDegPerS: 4 }, 5 * S); - expect(poseAt(10 * S).h).toBeCloseTo(214 + 5 + 20, 9); - setCamera({ mode: 'still' }, 11 * S); - expect(early).toEqual(late); - expect(early[0]).toBeCloseTo(214 + 5, 9); // the heading at the change, with the speed it had until it - expect(early[1]).toBeCloseTo(214 + 5 + 24, 9); - offEarly(); - offLate(); - }); - - it('keeps no log of the camera: the owner takes each change as it is made, so a change nobody reads is held nowhere', () => { + it('keeps no log of the camera: each change updates the active segment directly', () => { expect(Object.keys(camera)).not.toContain('takeChanges'); anchor('p', 100, 0); choose('both', 2, 0); @@ -295,156 +254,44 @@ describe('the heading owner', () => { expect(poseAt(9 * S).h).toBeCloseTo(100 + 14 + 2, 9); }); - describe('a change of mode eases the pose in two stages inside the bound, from wherever the pose is', () => { - const sample = (from: number, to: number, step = 1): { h: number; phi: number; r: number }[] => { - const out = []; - for (let t = from; t <= to; t += step) out.push(poseAt(t)); - return out; - }; - /** Every pose inside the bound, and whenever the camera angle moves the offset is inside the circle's bound at both ends of the move. */ - const insideTheBound = (poses: { phi: number; r: number }[]) => { - poses.forEach((p, i) => { - expect(fits(p), `pose ${i}: phi ${p.phi}, r ${p.r}`).toBe(true); - if (i && Math.abs(p.phi - poses[i - 1].phi) > 1e-9) { - expect(Math.abs(p.r)).toBeLessThanOrEqual(BACK + 0.02); // a sample step may straddle the end of a stage: a thousandth of the ease on - expect(Math.abs(poses[i - 1].r)).toBeLessThanOrEqual(BACK + 0.02); - } - }); - }; - - /** The clock at which the camera has gone a quarter round its circle at 12 degrees a second, started when its offset is in: the offset comes in first, and the angle is let go after. */ - const QUARTER = 90 / 12 * S + STAGE_MS; - + describe('clamped offset and mode switches', () => { beforeEach(() => { setCamera({ offsetM: 200 }, 0); anchor('p', 100, 0); setRange(range, 0); }); - it('goes to a mode that stands the camera on its heading in two stages: the angle first, the offset let out after, and the view direction never waits', () => { - choose('offset', 12, 0); - const at = QUARTER; - expect(poseAt(at)).toMatchObject({ phi: 90, r: BACK }); - choose('both', 12, at); - expect(poseAt(at)).toMatchObject({ h: 100, phi: 90, r: BACK }); // what is seen at the pick - expect(settledAt()).toBe(at + 2 * STAGE_MS); - const stage1 = sample(at, at + STAGE_MS); - expect(stage1.every((p) => p.r === BACK)).toBe(true); // the angle alone - expect(stage1.at(-1)!.phi).toBeCloseTo(0, 9); - const stage2 = sample(at + STAGE_MS, at + 2 * STAGE_MS); - expect(stage2.every((p) => p.phi === 0)).toBe(true); // the offset alone - expect(stage2.at(-1)!.r).toBe(FORWARD); - expect(poseAt(at + 10 * S)).toMatchObject({ phi: 0, r: FORWARD }); - expect(poseAt(at + 3 * S).h).toBeCloseTo(100 + 36, 9); // turning from the instant of the pick - insideTheBound(sample(at, at + 2 * STAGE_MS)); - }); - - it('goes to a mode that takes the camera off its heading the other way: the offset comes in first with the camera held where it stood, then the camera goes', () => { - choose('both', 12, 0); - const at = 10 * S; - expect(poseAt(at)).toMatchObject({ phi: 0, r: FORWARD }); - choose('offset', 12, at); - const stage1 = sample(at, at + STAGE_MS); - expect(stage1.every((p) => p.phi === 0)).toBe(true); - expect(stage1.at(-1)!.r).toBe(BACK); - expect(poseAt(at + STAGE_MS + 1 * S)).toMatchObject({ r: BACK }); - expect(poseAt(at + STAGE_MS + 1 * S).phi).toBeCloseTo(12, 9); // and goes round from the angle it stood at, at the speed - insideTheBound(sample(at, at + 3 * STAGE_MS)); - }); - - it('a pick that asks nothing of the offset does not wait for it: the angle goes at once', () => { - choose('both', 12, 0); - setCamera({ offsetM: 50 }, 1 * S); - choose('offset', 12, 2 * S); - expect(poseAt(2 * S + 1 * S).phi).toBeCloseTo(12, 9); - }); - - it('a pick made while an ease is under way starts from the pose the view has, and every pose on the way stays inside the bound', () => { - const picks: RotationMode[] = ['still', 'offset', 'both']; - let checked = 0; - for (const first of picks) { - for (const second of picks) { - for (const gap of [10, 100, 250, 310, 450, 590]) { - resetHeading(); - resetCamera(); - setCamera({ mode: 'offset', speedDegPerS: 12, offsetM: 200 }, 0); - anchor('p', 100, 0); - setRange(range, 0); - const at = QUARTER; - setCamera({ mode: first }, at); - const seen = poseAt(at + gap); - setCamera({ mode: second }, at + gap); - expect(poseAt(at + gap), `${first} then ${second} after ${gap} ms`).toEqual(seen); // nothing moves at the pick - insideTheBound(sample(at, at + 4 * STAGE_MS, 3)); - checked += 1; - } - } - } - expect(checked).toBe(54); - }); - - it('a pick to both made from the offset-only mode mid-way, then to offset-only again, never leaves the bound: the case a target-only order got wrong', () => { - choose('offset', 12, 0); - const at = QUARTER; - choose('both', 12, at); // the angle goes first, the offset held at the circle's bound - choose('offset', 12, at + 100); // and the offset-only mode has the offset on the circle's bound already - insideTheBound(sample(at, at + 4 * STAGE_MS, 2)); - // From both with the offset out, pick still then both then offset within a stage each. - resetHeading(); - resetCamera(); - setCamera({ mode: 'both', speedDegPerS: 12, offsetM: 200 }, 0); - anchor('p', 100, 0); - setRange(range, 0); - choose('offset', 12, 5 * S); // the offset comes in first - choose('both', 12, 5 * S + 100); // back out: the camera is still on its heading, so the offset can go straight out - insideTheBound(sample(5 * S, 5 * S + 4 * STAGE_MS, 2)); - expect(poseAt(5 * S + 10 * S)).toMatchObject({ phi: 0, r: FORWARD }); - }); - - it('a slider eases in one stage, inside the bound the mode keeps, and an offset past it is held to it', () => { + it('clamps offset directly per mode without rewriting the stored choice', () => { choose('both', 0.6, 0); + expect(poseAt(0)).toMatchObject({ phi: 0, r: FORWARD }); setCamera({ offsetM: 20 }, 1 * S); - expect(poseAt(1 * S).r).toBe(FORWARD); - expect(poseAt(1 * S + STAGE_MS).r).toBe(20); - expect(settledAt()).toBe(1 * S + STAGE_MS); + expect(poseAt(1 * S).r).toBe(20); setCamera({ offsetM: 999 }, 5 * S); - expect(poseAt(6 * S).r).toBe(FORWARD); + expect(poseAt(5 * S).r).toBe(FORWARD); choose('offset', 0.6, 7 * S); - expect(poseAt(9 * S).r).toBe(BACK); // the viewer's 999 is not rewritten + expect(poseAt(7 * S).r).toBe(BACK); // the viewer's 999 is not rewritten expect(getCamera().offsetM).toBe(999); choose('both', 0.6, 10 * S); - expect(poseAt(12 * S).r).toBe(FORWARD); + expect(poseAt(10 * S)).toMatchObject({ phi: 0, r: FORWARD }); }); - it('a new bound is a new segment from the pose the view has: a rebuild mid-ease lands exactly where the old scene was', () => { + it('clamps to the new bound on setRange without moving h or phi', () => { choose('offset', 12, 0); - const at = QUARTER; - choose('both', 12, at); - for (const gap of [50, 150, 299, 301, 450]) { - const seen = poseAt(at + gap); - setRange(range, at + gap); // what a rebuild at another size, or a rebuilt scene, does - const now = poseAt(at + gap); - expect(now.h).toBeCloseTo(seen.h, 9); - expect(now.phi).toBeCloseTo(seen.phi, 9); - expect(now.r).toBeCloseTo(seen.r, 9); - } - insideTheBound(sample(at, at + 4 * STAGE_MS, 2)); - expect(poseAt(at + 5 * S)).toMatchObject({ phi: 0, r: FORWARD }); + const at = 5 * S; + const seen = poseAt(at); + setRange(() => [-50, 50], at); + expect(poseAt(at)).toMatchObject({ h: seen.h, phi: seen.phi, r: 50 }); }); - it('has no ease under reduced motion: the pose owed is the pose shown at once, and one begun before is cut short', () => { + it('stops rotation under reduced motion while clamping the pose immediately', () => { choose('offset', 12, 0); - const at = QUARTER; - choose('both', 12, at); - expect(settledAt()).toBeGreaterThan(at); - freeze(true, at + 10); - expect(poseAt(at + 10)).toMatchObject({ phi: 0, r: FORWARD }); - expect(poseAt(at + 5 * S).h).toBe(poseAt(at + 10).h); // and nothing turns - setCamera({ mode: 'offset', speedDegPerS: 12 }, at + 20); - expect(poseAt(at + 21)).toMatchObject({ r: BACK }); // the clamp, at once - setCamera({ mode: 'both', speedDegPerS: 12 }, at + 30); - expect(poseAt(at + 31)).toMatchObject({ phi: 0, r: FORWARD }); - expect(settledAt()).toBeLessThanOrEqual(at + 30); + const at = 7.5 * S; + freeze(true, at); + expect(poseAt(at).phi).toBeCloseTo(90, 9); + expect(poseAt(at + 5 * S).phi).toBeCloseTo(90, 9); + setCamera({ mode: 'both', speedDegPerS: 12 }, at + 20); + expect(poseAt(at + 20)).toMatchObject({ phi: 0, r: FORWARD }); + expect(poseAt(at + 5 * S).h).toBe(poseAt(at + 20).h); }); }); }); diff --git a/src/app/features/scene/ridge/heading.ts b/src/app/features/scene/ridge/heading.ts index 880caa59..2542dfae 100644 --- a/src/app/features/scene/ridge/heading.ts +++ b/src/app/features/scene/ridge/heading.ts @@ -2,21 +2,13 @@ // centre (`r`), at any clock. Module-level state, so a sky change that makes a new scene keeps the pose. Angles are unwrapped compass degrees between two // `normalize` calls (the rig makes one before each stretch of motion); `ring.ts` is the one place that reasons about 0 / 360. // -// The state is one SEGMENT: the pose at its start `t0`, the mode and bounded speed in force, and the ease that takes the pose to the one the inputs owe. -// `poseAt(t)` is a pure function of the segment and `t`, ease included. Every change of an input (a mode pick, a hold, the speed, the offset, a bound, reduced -// motion, a place) starts a new segment from `poseAt(now)`: no log of changes, no second copy of the ease, so whoever reads at any clock, a rebuilt scene -// included, gets the pose the view has. -// -// The camera sits on its circle at angle `h + phi` and distance `r` (signed, forward positive): with `phi` 0 it is pushed forward along its own heading -// (`view.ts` `cardPose`), and rotating the offset alone moves `phi` and leaves the view direction where it is (ruling ridge-scene-view-submenus). `phi` is 0 -// whenever the view direction turns with the camera ('both'). The bound on `r` is the baker's (`view.ts` `offsetRange`, given by the scene as `setRange`): a -// forward offset past `rMaxM` fits only with the camera exactly on its heading. So an ease takes `phi` and `r` one after the other, STAGE_MS each, in the -// order that keeps every pose inside it from wherever it starts: a camera going to stand on its heading turns first and lets the offset out after; one going -// off it brings the offset in first and lets the camera go after. -import { bindOwner, getCamera, holdCamera, isHeld } from '../cameraState'; +// The state is one SEGMENT: the pose at its start `t0` and the mode and bounded speed in force. `poseAt(t)` is a pure function of the segment and `t`. +// Every change of an input (a mode pick, a hold, the speed, the offset, a bound, reduced motion, a place) starts a new segment from `poseAt(now)` with +// `phi` and `r` clamped directly to what the mode and bound allow. +import { getCamera, holdCamera, isHeld, subscribe as subscribeCamera } from '../cameraState'; +import type { RotationMode } from '../cameraState'; -/** `still`: nothing turns. `offset`: the camera circles the centre, the view direction stays. `both`: the view direction turns and the camera with it. */ -export type RotationMode = 'still' | 'offset' | 'both'; +export type { RotationMode }; /** Where the view faces, where the camera stands on its circle against that, and its offset (m, signed): the pose the rig lays the cards out from. */ export interface Pose { @@ -29,24 +21,13 @@ export interface Pose { type Speed = (mode: RotationMode) => number; type Range = (mode: RotationMode, phiDeg: number) => [number, number]; -export const STAGE_MS = 300; // one stage of an ease, ms -const EPS = 1e-9; // a pose this close to the one owed is there: nothing eases - interface Segment extends Pose { /** The clock (ms) at which `h`, `phi` and `r` hold. */ t0: number; - /** Degrees per second of whatever turns, signed and bounded, and what that is: the view direction ('both'), the camera on its circle ('offset') or nothing. */ + /** Degrees per second of whatever turns, signed and bounded. */ rate: number; + /** What turns: the view direction ('both'), the camera on its circle ('offset'), or nothing. */ turns: 'h' | 'phi' | undefined; - /** The camera's angle turns only from this clock (ms): after the offset has come in. */ - turnsFrom: number; - /** The angle an ease takes `phi` to from `t0` (unwrapped, the nearest way round); undefined: `phi` is what `turns` makes it. */ - phiTo: number | undefined; - /** The offset an ease takes `r` to, from `rAt`. */ - rTo: number; - rAt: number; - /** The clock (ms) at which everything eased is home. */ - endAt: number; } let seg: Segment | undefined; @@ -54,13 +35,9 @@ let frozen = false; let anchored: string | undefined; let speed: Speed | undefined; let range: Range | undefined; +let offCamera: (() => void) | undefined; const listeners = new Set<() => void>(); -/** 0 at `at`, 1 at `at + STAGE_MS` (smoothstep): the one curve of the view's easing. */ -const ease = (at: number, now: number): number => { - const x = Math.min(1, Math.max(0, (now - at) / STAGE_MS)); - return x * x * (3 - 2 * x); -}; const free: [number, number] = [-Infinity, Infinity]; /** What each mode turns: the view direction, the camera on its circle, or nothing. */ const TURNS: Record = { both: 'h', offset: 'phi', still: undefined }; @@ -70,84 +47,65 @@ function pose(s: Segment, t: number): Pose { const sec = (t - s.t0) / 1000; return { h: s.h + (s.turns === 'h' ? s.rate * sec : 0), - phi: - s.phiTo !== undefined - ? s.phi + (s.phiTo - s.phi) * ease(s.t0, t) - : s.phi + (s.turns === 'phi' ? (s.rate * Math.max(0, t - s.turnsFrom)) / 1000 : 0), - r: s.r + (s.rTo - s.r) * ease(s.rAt, t), + phi: s.phi + (s.turns === 'phi' ? s.rate * sec : 0), + r: s.r, }; } -/** - * Start a segment at `now` from `from`, the pose the view has there, under the inputs in force: the viewer's choice, the hold, reduced motion and the bounds. - * What the inputs owe is where the camera must stand (on its heading when the view turns with it and is not held) and the offset the bound allows there; an - * ease is what takes `from` to it, none when `snap` (a place or a bound met for the first time) or while frozen. - */ -function begin(now: number, from: Pose, snap = false): void { +/** Start a segment at `now` from `from`, with `phi` and `r` clamped to the mode and bound in force. */ +function begin(now: number, from: Pose): void { const cam = getCamera(); const held = isHeld(); const kin: RotationMode = frozen || held ? 'still' : cam.mode; const toHeading = cam.mode === 'both' && !held; const limit = speed?.(cam.mode) ?? Infinity; - const phiTo = toHeading ? 360 * Math.round(from.phi / 360) : undefined; - const landed = phiTo ?? from.phi; - const [lo, hi] = rangeOf(cam.mode, landed); // the bound is the chosen mode's, held or frozen or not: a hold does not move the offset - const rTo = Math.min(hi, Math.max(lo, cam.offsetM)); - const easing = !snap && !frozen; - const turnsPhi = easing && phiTo !== undefined && Math.abs(phiTo - from.phi) > EPS; - const movesR = easing && Math.abs(rTo - from.r) > EPS; - // Going to circle with the offset out past the circle's bound: the camera stays on its heading until the offset is in. - const [circleLo, circleHi] = rangeOf('offset', from.phi); - const holdsPhi = movesR && kin === 'offset' && (from.r < circleLo || from.r > circleHi); - const rAt = turnsPhi ? now + STAGE_MS : now; + const phi = toHeading ? 0 : from.phi; + const [lo, hi] = rangeOf(cam.mode, phi); + const r = Math.min(hi, Math.max(lo, cam.offsetM)); seg = { t0: now, h: from.h, - phi: turnsPhi ? from.phi : landed, - r: movesR ? from.r : rTo, + phi, + r, rate: Math.sign(cam.speedDegPerS) * Math.min(Math.abs(cam.speedDegPerS), limit), turns: TURNS[kin], - turnsFrom: holdsPhi ? now + STAGE_MS : now, - phiTo: turnsPhi ? phiTo : undefined, - rTo, - rAt, - endAt: Math.max(turnsPhi ? now + STAGE_MS : now, movesR ? rAt + STAGE_MS : now), }; } const current = (now: number): Segment => { - if (!seg) begin(now, { h: 0, phi: 0, r: 0 }, true); + if (!seg) begin(now, { h: 0, phi: 0, r: 0 }); return seg as Segment; }; + /** The pose at `now` (ms): unwrapped degrees, bounded by the last `normalize` and the stretch since. */ export function poseAt(now: number): Pose { return pose(current(now), now); } + const emit = () => [...listeners].forEach((cb) => cb()); + /** A new segment at `now` from the pose the view has, told to the subscribers. */ -function restart(now: number, over: Partial = {}, snap = false): void { - begin(now, { ...poseAt(now), ...over }, snap); +function restart(now: number, over: Partial = {}): void { + begin(now, { ...poseAt(now), ...over }); emit(); } +function ensureSync(): void { + offCamera ??= subscribeCamera((_next, _prev, at) => restart(Math.max(at, seg?.t0 ?? at))); +} + /** * Degrees per second the view direction turns at under the inputs in force: the viewer's speed bounded by what the place sustains in the mode picked (`anchor`'s - * limit), and nothing while the view does not turn (a mode that turns the camera on its circle, a hold, reduced motion). Every change of any of these starts a - * segment and is heard by `subscribe`, so a reader that sizes something to this speed learns when it must size again. + * limit), and nothing while the view does not turn (a mode that turns the camera on its circle, a hold, reduced motion). */ export const turnRate = (): number => (seg?.turns === 'h' ? Math.abs(seg.rate) : 0); -/** The clock (ms) at which what the last change eased is home. */ -export const settledAt = (): number => seg?.endAt ?? 0; - -// The viewer's choice or hold changed: a new segment at that clock, before any listener hears of it. -bindOwner((at) => restart(Math.max(at, seg?.t0 ?? at))); - /** * Bound the speed in each mode to what the baked place sustains (`view.ts` `maxSpeed`), from this moment, before anything awaits the place's tiles, and point - * the view at a place: a place not shown before faces its rest azimuth, the camera on its heading, with no ease; the same place again keeps the pose. + * the view at a place: a place not shown before faces its rest azimuth, the camera on its heading; the same place again keeps the pose. */ export function anchor(key: string, restDeg: number, now: number, limit?: Speed): void { + ensureSync(); if (limit) speed = limit; if (anchored === key) { if (limit) restart(now); @@ -155,14 +113,14 @@ export function anchor(key: string, restDeg: number, now: number, limit?: Speed) } anchored = key; range = undefined; // the bound belongs to the place before - restart(now, { h: restDeg, phi: 0 }, true); + restart(now, { h: restDeg, phi: 0 }); } -/** The offsets the scene's place and viewport allow (`view.ts` `offsetRange`); the first one met takes the offset to its bound at once, a new one eases there. */ +/** The offsets the scene's place and viewport allow (`view.ts` `offsetRange`), clamped at once. */ export function setRange(limit: Range, now: number): void { - const first = range === undefined; + ensureSync(); range = limit; - restart(now, {}, first); + restart(now); } /** @@ -170,37 +128,39 @@ export function setRange(limit: Range, now: number): void { * is held in cameraState, which leaves the chosen mode as it is; a rebuild keeps the hold, and picking a mode, the one already chosen included, resumes it. */ export function hold(h: number, now: number): void { + ensureSync(); begin(now, { ...poseAt(now), h }); if (isHeld()) emit(); - else holdCamera(now); // the owner starts the held segment, then the camera's listeners hear it, once + else holdCamera(now); } /** Nothing turns while `on` (reduced motion), whatever the viewer chose; the view takes the pose owed at once and stays there. */ export function freeze(on: boolean, now: number): void { + ensureSync(); if (on === frozen) return; frozen = on; restart(now); } -/** Bring `h` and `phi` into [0, 360) at `now`, so the transforms stay small however long the page has been open: the whole turns are all that goes, and the ease and the motion go on. Silent: the caller lays out again. */ +/** Bring `h` and `phi` into [0, 360) at `now`, so the transforms stay small however long the page has been open. Silent: the caller lays out again. */ export function normalize(now: number): void { const s = current(now); const p = pose(s, now); - const dh = 360 * Math.floor(p.h / 360); - const dphi = 360 * Math.floor(p.phi / 360); - s.h -= dh; - s.phi -= dphi; - if (s.phiTo !== undefined) s.phiTo -= dphi; + s.h -= 360 * Math.floor(p.h / 360); + s.phi -= 360 * Math.floor(p.phi / 360); } /** Hear every change of the pose's course: the viewer's choice or hold, a bound, reduced motion, a manual turn, a new place; returns the way to stop. */ export function subscribe(cb: () => void): () => void { + ensureSync(); listeners.add(cb); return () => listeners.delete(cb); } /** For tests: the state of a fresh page. */ export function resetHeading(): void { + offCamera?.(); + offCamera = undefined; seg = undefined; frozen = false; anchored = undefined; diff --git a/src/app/features/scene/ridge/lightCards.test.ts b/src/app/features/scene/ridge/lightCards.test.ts index 8b1b76b3..b3ecfcd2 100644 --- a/src/app/features/scene/ridge/lightCards.test.ts +++ b/src/app/features/scene/ridge/lightCards.test.ts @@ -2,10 +2,8 @@ import { describe, expect, it, vi } from 'vitest'; import { decodeNormal, DEFAULT_LOOK, - PHYSICAL_LOOK, celShade, celLevels, - FRAGMENT, createLighter, lightingOf, ringAzimuth, @@ -19,7 +17,7 @@ import type { RidgeLook } from './lightCards'; import { parseManifest } from './manifest'; import { wireManifest } from './manifest.fixture'; import type { PhysicalSky } from './physicalSky'; -import { ACES_FIT, ACES_IN, ACES_OUT, BLACK_LIFT, makeCurve } from './toneMap'; +import { BLACK_LIFT, makeCurve } from './toneMap'; const manifest = parseManifest(wireManifest(), '/d/'); const RAD = Math.PI / 180; @@ -81,10 +79,6 @@ describe('the wall code', () => { expect(0.998).toBeLessThan(WALL_RT2); expect(2).toBeGreaterThan(WALL_RT2); }); - - it('the shader carries the same threshold', () => { - expect(FRAGMENT).toContain(`const float WALL_RT2 = ${WALL_RT2};`); - }); }); describe('the lighting inputs', () => { @@ -162,41 +156,6 @@ describe('the lighting inputs', () => { }); }); -describe('the ring in the shader', () => { - it('reads the sun and the sky by the column of the ring, not of the file, and wraps at the ends', () => { - expect(FRAGMENT).toContain('int col = ((uCol0 + p.x) % uRingW + uRingW) % uRingW;'); - expect(FRAGMENT).toContain('texelFetch(uSun, ivec2(col, 0), 0)'); - expect(FRAGMENT).toContain('(float(col) + 0.5) / float(uRingW)'); - expect(FRAGMENT).toContain('(int(b.x) % w + w) % w'); // the sky table wraps in azimuth - }); - it('gives the ground noise the ground point, so it is the same at ring column 0 and column 6400', () => { - // The noise coordinate is dist x (sin psi, cos psi) with psi from the wrapped column: sin and cos of 0 and of a whole turn are one point. - expect(FRAGMENT).toContain('vec2 world = vec2(sin(psi), cos(psi)) * dist;'); - expect(FRAGMENT).toContain('float psi = (float(col) + 0.5) / float(uRingW) * 2.0 * PI;'); - expect(FRAGMENT).not.toContain("uRadPerPx"); - const at = (col: number, w: number) => { - const psi = ((((col % w) + w) % w) + 0.5) / w * 2 * Math.PI; - return [Math.sin(psi), Math.cos(psi)]; - }; - expect(at(6400, 6400)[0]).toBeCloseTo(at(0, 6400)[0], 12); - expect(at(6400, 6400)[1]).toBeCloseTo(at(0, 6400)[1], 12); - }); -}); - -describe('the display of the shader', () => { - const g = (n: number) => (Number.isInteger(n) ? `${n}.0` : String(n)); - it("writes toneMap.ts's ACES matrices and fit into the source", () => { - ACES_IN.forEach((row, i) => - expect(FRAGMENT).toContain(`const vec3 IN_R${i} = vec3(${row.map(g).join(', ')});`) - ); - ACES_OUT.forEach((row, i) => - expect(FRAGMENT).toContain(`const vec3 OUT_R${i} = vec3(${row.map(g).join(', ')});`) - ); - expect(FRAGMENT).toContain(`vec3(${g(ACES_FIT[0])}, ${g(ACES_FIT[1])}, 0.0)`); - expect(FRAGMENT).toContain(`vec3(${g(ACES_FIT[2])}, ${g(ACES_FIT[3])}, ${g(ACES_FIT[4])})`); - }); -}); - describe('the look reaches the shader', () => { // A recording WebGL2: every uniform call is kept by the name of its location, nothing is drawn. const run = (look?: Partial, tile = 0) => { @@ -276,33 +235,22 @@ describe('the look reaches the shader', () => { expect(u.uInkKeep[0]).toBe(1); }); - it('carries the art-pass axes: relief, fixed light, tint, tone, ink scale, noise', () => { + it('carries the art-pass axes: near warm, ink scale, ground noise, cloud shadows', () => { const u = run({ - reliefWeight: 0.15, - reliefLight: { mix: 1, azimuthDeg: 0, elevationDeg: 90 }, - hazeTint: [0, 0.1, 0.3], nearWarm: 0.5, - contrastByDistance: 1.5, - cardToneStep: 0.2, - cardGradient: 0.3, inkScale: 0, groundNoise: 0.4, cloudShadows: 0.6, }); - expect(u.uRelief).toEqual([0.15, 1]); - expect(u.uFixedLight[2]).toBeCloseTo(1, 12); // a light straight up - expect(u.uHazeTint).toEqual([0, 0.1, 0.3]); - expect(u.uDist).toEqual([0.5, 1.5]); - expect(u.uCard).toEqual([1, 0.3]); // a single card sits at the centre of the tone steps + expect(u.uNearWarm).toEqual([0.5]); expect(u.uInkScale).toEqual([0]); expect(u.uGround).toEqual([0.4, 0.6]); }); - it('scales the haze optical depth and the ambient light, and moves the sun cut-off', () => { + it('scales the haze optical depth and moves the sun cut-off', () => { const base = run(); - const look = run({ hazeScale: 2 * DEFAULT_LOOK.hazeScale, ambientScale: 0.5 }); + const look = run({ hazeScale: 2 * DEFAULT_LOOK.hazeScale }); look.uExt.forEach((e, k) => expect(e).toBeCloseTo(2 * base.uExt[k], 12)); - expect(look.uAmbient[2]).toBeCloseTo(0.15, 6); // plus the airglow's ambient expect( lightingOf(manifest, sky30(), { ...DEFAULT_LOOK, sunCutoffDeg: 45 }).key.direct ).toEqual([0, 0, 0]); @@ -368,13 +316,13 @@ describe('night key light', () => { }); describe('cel shading', () => { - const sweep = (bands: number, softness: number, levels?: number[]) => { + const sweep = (bands: number, softness: number) => { const out = new Set(); for (let i = -20; i <= 100; i += 1) { const x = i / 100; // away from the band edges (i / bands), where a softened edge is between two levels if (Array.from({ length: bands }, (_, k) => k / bands).some((e) => e > 0 && Math.abs(x - e) <= softness / 2 + 1e-9)) continue; - out.add(Math.round(celShade(x, bands, softness, levels) * 1e9)); + out.add(Math.round(celShade(x, bands, softness) * 1e9)); } return out; }; @@ -395,15 +343,8 @@ describe('cel shading', () => { expect(celShade(-0.5, 3, 0)).toBe(0); expect(celShade(1, 3, 0)).toBe(1); }); - it('takes the band levels it is given', () => { - expect(celLevels(3, [0.2, 0.5, 0.9]).slice(0, 3)).toEqual([0.2, 0.5, 0.9]); - expect(celShade(0.9, 3, 0, [0.2, 0.5, 0.9])).toBe(0.9); - expect(celShade(-1, 3, 0, [0.2, 0.5, 0.9])).toBe(0.2); - }); - it('is on in the default look and off in the physical one; the shader carries the ramp', () => { - expect(DEFAULT_LOOK.celBands).toBeGreaterThan(0); - expect(PHYSICAL_LOOK.celBands).toBe(0); - expect(FRAGMENT).toContain('float cel(float x)'); - expect(FRAGMENT).toContain('uBandLevels[6]'); + it('computes evenly spaced levels and uses cel3 in the default look', () => { + expect(celLevels(3).slice(0, 3)).toEqual([0, 0.5, 1]); + expect(DEFAULT_LOOK.celBands).toBe(3); }); }); diff --git a/src/app/features/scene/ridge/lightCards.ts b/src/app/features/scene/ridge/lightCards.ts index 39c5fcc9..c9d4b6f1 100644 --- a/src/app/features/scene/ridge/lightCards.ts +++ b/src/app/features/scene/ridge/lightCards.ts @@ -40,22 +40,8 @@ export interface RidgeLook { sunCutoffDeg: number; /** Multiplies the optical depth of the aerial perspective: 1 is the sky's own extinction, 0 no haze. */ hazeScale: number; - /** Multiplies the ambient irradiance the terrain is lit by. */ - ambientScale: number; - /** 0 = no normal shading (the flat card tone, as a horizontal surface), 1 = shaded by the normals. */ - reliefWeight: number; - /** The relief light: `mix` 0 is the sun, 1 a fixed light; `azimuthDeg` is clockwise of the view ray (-45 = upper left, behind the ridge), `elevationDeg` above the horizon. */ - reliefLight: { mix: number; azimuthDeg: number; elevationDeg: number }; - /** Added to the sky radiance used for the haze, rgb in units of that radiance's own luminance (so it holds at every sky): positive blue = cool far. */ - hazeTint: readonly [number, number, number]; /** Strength (0..1) of a warm tint on the near, fading out with the log-distance across the baked range. */ nearWarm: number; - /** The relief's contrast about the pixel's flat tone scales by exp(c (1 - 2 d)), d the log-distance across the baked range: c > 0 near contrasty, far flat. */ - contrastByDistance: number; - /** Value of each card multiplies by 1 + step (index - centre); the nearest card is index 0, so a positive step makes near darkest. */ - cardToneStep: number; - /** Value ramp inside each card: 1 + g (y - 1/2), y the fraction down the card; positive lightens toward the foot. */ - cardGradient: number; /** Multiplies each ink's darkening: 0 = no lines. */ inkScale: number; /** Procedural albedo variation (a stand-in for land cover we do not bake): fbm in metres on the ground, so its screen frequency follows distance. 0 = none. */ @@ -66,59 +52,37 @@ export interface RidgeLook { celBands: number; /** Width of each band edge in n.s units (0 = hard). */ celSoftness: number; - /** The level of each band, 0..1, darkest first (default: evenly from 0 to 1). Length `celBands`. */ - celBandLevels?: readonly number[]; /** The ambient is coarse too: surfaces facing the sky (the normal's up component past `celAmbientEdge`) keep it whole, the rest keep this fraction (1 = no step). */ celAmbientAway: number; celAmbientEdge: number; } -/** The first art pass's look: Lambert relief, no procedural variation, the sky's own haze, full ink. Kept for comparison in the look sheet. */ -export const PHYSICAL_LOOK: RidgeLook = { +/** The default: painterly cel-3 (ground variation, cloud shadows, warm near, moderate haze, light ink). */ +export const DEFAULT_LOOK: RidgeLook = { occludeLogD: 0.35, creaseCos: 0.85, inkKeep: { edge: 0.45, occlude: 0.55, crease: 0.8 }, sunCutoffDeg: -1, - hazeScale: 1, - ambientScale: 1, - reliefWeight: 1, - reliefLight: { mix: 0, azimuthDeg: -45, elevationDeg: 40 }, - hazeTint: [0, 0, 0], - nearWarm: 0, - contrastByDistance: 0, - cardToneStep: 0, - cardGradient: 0, - inkScale: 1, - groundNoise: 0, - cloudShadows: 0, - celBands: 0, - celSoftness: 0, - celAmbientAway: 1, - celAmbientEdge: 0.7, -}; - -/** The default: painterly (ground variation, cloud shadows, warm near, moderate haze, light ink) with cel-shaded relief. */ -export const DEFAULT_LOOK: RidgeLook = { - ...PHYSICAL_LOOK, + hazeScale: 2, + nearWarm: 0.6, + inkScale: 0.4, groundNoise: 0.35, cloudShadows: 0.5, - nearWarm: 0.6, - hazeScale: 2, - inkScale: 0.4, celBands: 3, celSoftness: 0.05, celAmbientAway: 0.7, + celAmbientEdge: 0.7, }; /** Most bands the shader's uniform holds. */ export const CEL_MAX = 6; -/** The level of each of `bands` cel bands, darkest first: `custom` where given, else evenly 0..1 (one band is fully lit). Padded to `CEL_MAX`. */ -export function celLevels(bands: number, custom?: readonly number[]): number[] { +/** The level of each of `bands` cel bands, darkest first, evenly 0..1 (one band is fully lit). Padded to `CEL_MAX`. */ +export function celLevels(bands: number): number[] { const n = Math.min(CEL_MAX, Math.max(1, Math.round(bands))); return Array.from({ length: CEL_MAX }, (_, i) => { const k = Math.min(i, n - 1); - return custom?.[k] ?? (n === 1 ? 1 : k / (n - 1)); + return n === 1 ? 1 : k / (n - 1); }); } @@ -131,9 +95,9 @@ const smooth = (a: number, b: number, v: number): number => { * The cel ramp: the light of a surface whose normal makes `ndl` with the sun, in `bands` flat bands, edges at i / bands (i = 1..bands-1), each * edge `softness` wide. The lowest band holds the unlit side too (its level is what ambient light alone leaves). The shader writes the same. */ -export function celShade(ndl: number, bands: number, softness: number, levels?: readonly number[]): number { +export function celShade(ndl: number, bands: number, softness: number): number { const n = Math.min(CEL_MAX, Math.max(1, Math.round(bands))); - const lv = celLevels(n, levels); + const lv = celLevels(n); let out = lv[0]; for (let i = 1; i < n; i += 1) { const e = i / n; @@ -202,7 +166,7 @@ export interface KeyLight { } export function keyLight(sky: PhysicalSky, look: RidgeLook = DEFAULT_LOOK): KeyLight { - const ambient = scale3(sky.atm.irradiance.ambient, look.ambientScale); + const ambient = sky.atm.irradiance.ambient; const glow = [0, 0, 0]; airglow(0.6, glow); const base = add3(ambient, scale3([glow[0], glow[1], glow[2]], Math.PI)); @@ -216,7 +180,7 @@ export function keyLight(sky: PhysicalSky, look: RidgeLook = DEFAULT_LOOK): KeyL azimuth: m.azimuth, elevation: m.elevation, direct: [trans[0] * fade, trans[1] * fade, trans[2] * fade], - ambient: add3(base, scale3(scale3(m.atm.irradiance.ambient, look.ambientScale), m.ratio)), + ambient: add3(base, scale3(m.atm.irradiance.ambient, m.ratio)), }; } sky.atm.transmittanceToSpace(Math.max(Math.sin(sky.sun.elevation * RAD), 0), trans); @@ -309,11 +273,7 @@ uniform float uCm[${KNOTS}]; uniform vec2 uInkGeometry; // occludeLogD, creaseCos uniform vec3 uInkKeep; // edge, occlude, crease uniform float uInkScale; -uniform vec2 uRelief; // weight, mix toward the fixed light -uniform vec3 uFixedLight; // in the column frame -uniform vec3 uHazeTint; -uniform vec2 uDist; // nearWarm, contrastByDistance -uniform vec2 uCard; // value of this card, gradient +uniform float uNearWarm; uniform vec2 uGround; // groundNoise, cloudShadows uniform vec4 uCel; // bands (0 = Lambert), softness, ambientAway, ambientEdge uniform float uBandLevels[${CEL_MAX}]; @@ -321,7 +281,6 @@ out vec4 outColor; const float PI = 3.14159265358979; const vec3 NEAR_WARM = vec3(1.0, 0.82, 0.62); -const vec3 LUMA = vec3(0.2126, 0.7152, 0.0722); const float WALL_RT2 = ${glsl(WALL_RT2)}; ${[0, 1, 2] .map((i) => `const vec3 IN_R${i} = vec3(${ACES_IN[i].map(glsl).join(', ')});`) @@ -438,7 +397,6 @@ void main() { int col = ((uCol0 + p.x) % uRingW + uRingW) % uRingW; vec3 s = texelFetch(uSun, ivec2(col, 0), 0).xyz; - if (uRelief.y > 0.0) s = normalize(mix(s, uFixedLight, uRelief.y)); float dist = exp(g.logD); // The ground's noise is a function of the ground point, dist x (sin psi, cos psi) for the column's absolute azimuth psi, so it is periodic over the wrap. float psi = (float(col) + 0.5) / float(uRingW) * 2.0 * PI; @@ -447,21 +405,14 @@ void main() { if (uGround.x > 0.0) albedo *= max(1.0 + uGround.x * (2.0 * fbm(world / 250.0) - 1.0), 0.0); float cloud = uGround.y > 0.0 ? 1.0 - uGround.y * smoothstep(0.5, 0.72, fbm(world / 4000.0 + 17.0)) : 1.0; float lit = uCel.x > 0.5 ? cel(dot(g.n, s)) : max(dot(g.n, s), 0.0); - float ndl = mix(max(s.z, 0.0), lit, uRelief.x); float ambStep = uCel.x > 0.5 ? mix(uCel.z, 1.0, smoothstep(uCel.w - uCel.y * 0.5, uCel.w + uCel.y * 0.5 + 1e-4, g.n.z)) : 1.0; - vec3 radiance = albedo * (uTSun * ndl * cloud + uAmbient * mix(1.0, ambStep, uRelief.x)) / PI; + vec3 radiance = albedo * (uTSun * lit * cloud + uAmbient * ambStep) / PI; float dn = clamp((g.logD - uLogD.x) / uLogD.y, 0.0, 1.0); - if (uDist.y != 0.0) { - vec3 flatTone = albedo * (uTSun * max(s.z, 0.0) * cloud + uAmbient) / PI; - radiance = flatTone + (radiance - flatTone) * exp(uDist.y * (1.0 - 2.0 * dn)); - } - radiance *= mix(vec3(1.0), NEAR_WARM, uDist.x * (1.0 - dn)); + radiance *= mix(vec3(1.0), NEAR_WARM, uNearWarm * (1.0 - dn)); vec3 T = exp(-uExt * (dist / 1000.0)); vec2 uv = vec2((float(col) + 0.5) / float(uRingW), (float(uTop + p.y) + 0.5) / uPlaneH); vec3 haze = skyAt(uv); - haze += uHazeTint * dot(haze, LUMA); radiance = radiance * T + haze * (1.0 - T); - radiance *= max(uCard.x * (1.0 + uCard.y * ((float(p.y) + 0.5) / float(uSize.y) - 0.5)), 0.0); float keep = 1.0; ivec2 dirs[4] = ivec2[4](ivec2(1, 0), ivec2(-1, 0), ivec2(0, 1), ivec2(0, -1)); @@ -613,19 +564,10 @@ export function createLighter( gl.uniform2f(u('uInkGeometry'), look.occludeLogD, look.creaseCos); gl.uniform3f(u('uInkKeep'), look.inkKeep.edge, look.inkKeep.occlude, look.inkKeep.crease); gl.uniform1f(u('uInkScale'), look.inkScale); - gl.uniform2f(u('uRelief'), look.reliefWeight, look.reliefLight.mix); - const fl = look.reliefLight; - gl.uniform3f( - u('uFixedLight'), - Math.cos(fl.elevationDeg * RAD) * Math.cos(fl.azimuthDeg * RAD), - Math.cos(fl.elevationDeg * RAD) * Math.sin(fl.azimuthDeg * RAD), - Math.sin(fl.elevationDeg * RAD) - ); - gl.uniform3f(u('uHazeTint'), ...look.hazeTint); - gl.uniform2f(u('uDist'), look.nearWarm, look.contrastByDistance); + gl.uniform1f(u('uNearWarm'), look.nearWarm); gl.uniform2f(u('uGround'), look.groundNoise, look.cloudShadows); gl.uniform4f(u('uCel'), look.celBands, look.celSoftness, look.celAmbientAway, look.celAmbientEdge); - gl.uniform1fv(u('uBandLevels'), celLevels(look.celBands, look.celBandLevels)); + gl.uniform1fv(u('uBandLevels'), celLevels(look.celBands)); gl.uniform2i(u('uSkySize'), SKY_LUT.w, SKY_LUT.h); floatTexture(gl, 2, lit.ringW, 1, sunColumns(view, lit.key)); floatTexture(gl, 3, SKY_LUT.w, SKY_LUT.h, skyLut(sky, view, SKY_LUT.w, SKY_LUT.h)); @@ -647,11 +589,6 @@ export function createLighter( gl.uniform2i(u('uSize'), colour.width, colour.height); gl.uniform1i(u('uTop'), entry.top); gl.uniform1i(u('uCol0'), tile * view.tileW - view.apron); - gl.uniform2f( - u('uCard'), - 1 + look.cardToneStep * (card - (manifest.cards.length - 1) / 2), - look.cardGradient - ); gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT); gl.drawArrays(gl.TRIANGLES, 0, 3); diff --git a/src/app/features/scene/ridge/manifest.test.ts b/src/app/features/scene/ridge/manifest.test.ts index de49fe37..5c545735 100644 --- a/src/app/features/scene/ridge/manifest.test.ts +++ b/src/app/features/scene/ridge/manifest.test.ts @@ -14,7 +14,7 @@ describe('parseManifest', () => { apron: 2, planeH: 600, pxPerDegH: 6400 / 360, - pxPerDegV: 171.7, // not px_per_deg_h: a real bake's two differ 10x + pxPerDegV: 171.7, horizonRow: 357, }); expect(m.view.place).toEqual({ @@ -39,7 +39,7 @@ describe('parseManifest', () => { colour: 'card-1-t01-colour.webp', geometry: 'card-1-t01-geometry.webp', }); - expect(m.tiles[2][2]).toBeNull(); // the third card holds nothing over the south + expect(m.tiles[2][2]).toBeNull(); expect(m.attribution.creditLine).toBe('credit'); }); @@ -55,78 +55,25 @@ describe('parseManifest', () => { expect(() => parseManifest({ ...w, schema: 1 }, '/')).toThrow(/schema/); }); - it('refuses no cards, seven cards, a ring that is not tiles x tile_w, a tile row of the wrong length, a card in no tile, a band past the plane', () => { + it('rejects broken structure the runtime cannot render safely', () => { const w = wireManifest() as any; + expect(() => parseManifest(null, '/')).toThrow(); expect(() => parseManifest({ ...w, cards: [] }, '/')).toThrow(/cards/); expect(() => parseManifest({ ...w, cards: Array(7).fill({ near_m: null, far_m: null }) }, '/')).toThrow(/cards/); - expect(() => parseManifest({ ...w, view: { ...w.view, ring_w: 6401 } }, '/')).toThrow(/ring_w/); expect(() => parseManifest({ ...w, tiles: w.tiles.slice(1) }, '/')).toThrow(/tiles/); - expect(() => parseManifest({ ...w, tiles: w.tiles.map((r: unknown[]) => r.slice(1)) }, '/')).toThrow(/entries/); - expect(() => - parseManifest({ ...w, tiles: w.tiles.map((r: unknown[]) => [r[0], r[1], null]) }, '/') - ).toThrow(/null in every tile/); - const withTile = (e: unknown) => ({ ...w, tiles: [[e, w.tiles[0][1], w.tiles[0][2]], ...w.tiles.slice(1)] }); - const t = w.tiles[0][0]; - expect(() => parseManifest(withTile({ ...t, top: 300, h: 301 }), '/')).toThrow(/rows/); - expect(() => parseManifest(withTile({ ...t, top: -1 }), '/')).toThrow(/rows/); - expect(() => parseManifest(withTile({ ...t, distance_m: 0 }), '/')).toThrow(/distance/); - expect(() => parseManifest(withTile({ ...t, distance_m: Infinity }), '/')).toThrow(/distance/); - expect(() => parseManifest({ ...w, camera: undefined }, '/')).toThrow(/camera/); - expect(() => parseManifest({ ...w, camera: { r_max_m: 0, r_max_forward_m: 0 } }, '/')).toThrow(/r_max_m/); - expect(() => parseManifest({ ...w, camera: { r_max_m: 100 } }, '/')).toThrow(/r_max_forward_m/); - expect(() => parseManifest({ ...w, camera: { r_max_m: 100, r_max_forward_m: 99 } }, '/')).toThrow(/r_max_forward_m/); - }); - - it('rejects a missing field, a normal that is not rt8 and a backwards encoding', () => { - const w = wireManifest() as any; - expect(() => parseManifest({ ...w, bake_id: undefined }, '/')).toThrow(/bake_id/); - expect(() => parseManifest({ ...w, view: { ...w.view, horizon_row: 'x' } }, '/')).toThrow( - /horizon_row/ - ); - expect(() => parseManifest({ ...w, encoding: { ...w.encoding, normal: 'oct' } }, '/')).toThrow( - /normal/ - ); - expect(() => - parseManifest({ ...w, encoding: { ...w.encoding, log_d_max: w.encoding.log_d_min } }, '/') - ).toThrow(/encoding/); - expect(() => parseManifest(null, '/')).toThrow(); - }); - - it('rejects a manifest without place.tz and one naming a zone Intl does not know', () => { - const w = wireManifest() as any; - expect(() => parseManifest({ ...w, place: { ...w.place, tz: undefined } }, '/')).toThrow(/place\.tz/); - expect(() => parseManifest({ ...w, place: { ...w.place, tz: 'Not/AZone' } }, '/')).toThrow(/place\.tz/); - expect(parseManifest({ ...w, place: { ...w.place, tz: 'Asia/Kathmandu' } }, '/').view.place.tz).toBe('Asia/Kathmandu'); - }); - - it('refuses a plane that leaves fewer rows under the horizon than the runtime needs to reach the viewport bottom, and takes exactly that many', () => { - const w = wireManifest() as any; - const at = (row: number) => ({ ...w, view: { ...w.view, horizon_row: row } }); - expect(() => parseManifest(at(451), '/')).toThrow(/short plane.*150/); - expect(parseManifest(at(450), '/').view.horizonRow).toBe(450); - expect(parseManifest(at(357), '/').view.horizonRow).toBe(357); - }); - - it('never echoes a value it refused', () => { - const w = wireManifest() as any; - const refusal = (bad: unknown) => { - try { - parseManifest(bad, '/'); - } catch (e) { - return String(e); - } - return ''; - }; - for (const bad of [ - { ...w, schema: 'SECRET-VALUE-42' }, - { ...w, camera: { r_max_m: 'SECRET-VALUE-42', r_max_forward_m: 180 } }, - { ...w, camera: { r_max_m: 100, r_max_forward_m: 'SECRET-VALUE-42' } }, - { ...w, tiles: [[{ ...w.tiles[0][0], distance_m: 'SECRET-VALUE-42' }, ...w.tiles[0].slice(1)], ...w.tiles.slice(1)] }, - ]) { - const msg = refusal(bad); - expect(msg).not.toBe(''); - expect(msg).not.toContain('SECRET-VALUE-42'); + expect(() => parseManifest({ ...w, tiles: w.tiles.map((r: unknown[]) => r.slice(1)) }, '/')).toThrow(/tiles\[0\]/); + expect(() => parseManifest({ ...w, camera: { r_max_m: 0, r_max_forward_m: 0 } }, '/')).toThrow(/camera/); + expect(() => parseManifest({ ...w, camera: { r_max_m: 100, r_max_forward_m: 99 } }, '/')).toThrow(/camera/); + expect(() => parseManifest({ ...w, encoding: { ...w.encoding, log_d_max: w.encoding.log_d_min } }, '/')).toThrow(/encoding/); + for (const key of ['ring_w', 'tile_w', 'plane_h', 'px_per_deg_h', 'px_per_deg_v'] as const) { + expect(() => parseManifest({ ...w, view: { ...w.view, [key]: 0 } }, '/')).toThrow(key); + expect(() => parseManifest({ ...w, view: { ...w.view, [key]: -1 } }, '/')).toThrow(key); } + expect(() => + parseManifest({ ...w, tiles: w.tiles.map((row: unknown[]) => [row[0], row[1], null]) }, '/') + ).toThrow(/cards\[2\]/); + expect(() => parseManifest({ ...w, place: { ...w.place, tz: undefined } }, '/')).toThrow(/place\.tz/); + expect(() => parseManifest({ ...w, place: { ...w.place, tz: 'Not/AZone' } }, '/')).toThrow(); }); }); diff --git a/src/app/features/scene/ridge/manifest.ts b/src/app/features/scene/ridge/manifest.ts index 49fd26db..456a4424 100644 --- a/src/app/features/scene/ridge/manifest.ts +++ b/src/app/features/scene/ridge/manifest.ts @@ -1,18 +1,14 @@ -// The ridge backdrop's one JSON boundary: a static asset between the offline Python baker (scripts/ridge-bake/export.py, whose SCHEMA is the -// contract) and the page; no daemon state. Main-chunk safe: types, a parser and fetch only. Wire names are snake_case; the parsed manifest is -// camelCase and its `view` is the View (`view.ts`) the sky and the cards share. Schema 3: the whole 360 degree ring, K G-buffer cards cut into -// azimuth tiles, each tile two files. -import { groundRowsNeeded, type Place, type View } from './view'; +// The ridge backdrop's one JSON boundary: a static asset between the offline Python baker (scripts/ridge-bake/export.py) and the page. +// Main-chunk safe: types, a structural parser, and fetch only. Wire names are snake_case; the parsed manifest is camelCase. +import type { Place, View } from './view'; /** As export.py MAX_CARDS: the decode budget holds this many. */ export const MAX_CARDS = 6; /** One card's tile: its rows of the plane, the card's distance there, and its two files (names inside the manifest's directory). */ export interface TileCard { - /** First row of the card's band in the plane, and its height in rows. */ top: number; h: number; - /** exp(median ln d) of the card's solid pixels in the tile's interior, metres. */ distanceM: number; colour: string; geometry: string; @@ -31,13 +27,7 @@ export interface RidgeManifest { /** Display name of the place. */ name: string; view: View; - /** How the geometry file's blue channel maps to ln metres: `logD = logDMin + b x (logDMax - logDMin)`, b in 0..1. The red and green channels are the 'rt8' normal. */ encoding: { logDMin: number; logDMax: number }; - /** - * The largest camera offset from the bake centre the cards' linear slide fits, metres (ruling ridge-offset-range-fit): `rMaxM` over every angle of the camera - * on its circle (the offset-only rotation mode), `rMaxForwardM` with the camera pushed forward along the view direction alone (the modes where the offset - * turns with the view), so never below `rMaxM`. - */ camera: { rMaxM: number; rMaxForwardM: number }; /** Nearest first. */ cards: CardEntry[]; @@ -52,142 +42,119 @@ export interface RidgeIndex { } type Rec = Record; -const fail = (path: string, why: string): never => { - throw new Error(`ridge manifest ${path}: ${why}`); +const asObj = (x: unknown, label: string): Rec => { + if (typeof x !== 'object' || x === null || Array.isArray(x)) throw new Error(`ridge ${label}: not an object`); + return x as Rec; }; -const rec = (x: unknown, path: string): Rec => - typeof x === 'object' && x !== null && !Array.isArray(x) - ? (x as Rec) - : fail(path, 'not an object'); -const num = (x: unknown, path: string): number => - typeof x === 'number' && Number.isFinite(x) ? x : fail(path, 'not a number'); -const str = (x: unknown, path: string): string => - typeof x === 'string' ? x : fail(path, 'not a string'); -const numOrNull = (x: unknown, path: string): number | null => (x === null ? null : num(x, path)); - -/** An IANA zone name Intl knows (the one place besides skyMoment.ts that touches Intl.DateTimeFormat). */ -const zone = (x: unknown, path: string): string => { - const tz = str(x, path); - try { - new Intl.DateTimeFormat('en-US', { timeZone: tz }); - } catch { - fail(path, `unknown time zone ${tz}`); - } - return tz; +const num = (x: unknown, label: string): number => { + if (typeof x !== 'number' || !Number.isFinite(x)) throw new Error(`ridge manifest ${label}: not a number`); + return x; +}; +const pos = (x: unknown, label: string): number => { + const n = num(x, label); + if (!(n > 0)) throw new Error(`ridge manifest ${label}: must be > 0`); + return n; +}; +const zone = (x: unknown): string => { + if (typeof x !== 'string') throw new Error('ridge manifest place.tz: not a string'); + new Intl.DateTimeFormat('en-US', { timeZone: x }); + return x; }; export function parseIndex(raw: unknown): RidgeIndex { - const r = rec(raw, 'index'); - if (r.schema !== 1) fail('index.schema', 'must be 1'); - const places = rec(r.places, 'index.places'); - const out = Object.fromEntries( - Object.entries(places).map(([k, v]) => [k, str(v, `index.places.${k}`)]) - ); - return { default: str(r.default, 'index.default'), places: out }; + const r = asObj(raw, 'index'); + if (r.schema !== 1 || typeof r.default !== 'string') throw new Error('ridge index: invalid'); + const places = asObj(r.places, 'index.places'); + return { + default: r.default, + places: Object.fromEntries(Object.entries(places).filter(([, v]) => typeof v === 'string') as [string, string][]), + }; } /** `dir` is the URL of the directory the manifest was read from; the tile files are read relative to it. */ export function parseManifest(raw: unknown, dir: string): RidgeManifest { - const r = rec(raw, 'manifest'); + const r = asObj(raw, 'manifest'); if (r.schema !== 3) { - fail( - 'schema', - `must be 3: this build reads ring bakes only, so the deploy holds a stale ridge bake (rebake the place, or redeploy a matching build)` + throw new Error( + 'ridge manifest schema: must be 3: this build reads ring bakes only, so the deploy holds a stale ridge bake (rebake the place, or redeploy a matching build)' ); } - const p = rec(r.place, 'place'); - const v = rec(r.view, 'view'); - const ringW = num(v.ring_w, 'view.ring_w'); - const tileW = num(v.tile_w, 'view.tile_w'); + const p = asObj(r.place, 'manifest.place'); + const v = asObj(r.view, 'manifest.view'); const tiles = num(v.tiles, 'view.tiles'); - if (!Number.isInteger(tiles) || tiles < 1) fail('view.tiles', 'not a count'); - if (ringW !== tiles * tileW) fail('view.ring_w', 'is not tiles x tile_w'); - const planeH = num(v.plane_h, 'view.plane_h'); - const horizonRow = num(v.horizon_row, 'view.horizon_row'); - const ground = groundRowsNeeded(planeH); - if (planeH - horizonRow < ground - 1e-6) { - fail( - 'view.horizon_row', - `short plane: ${(planeH - horizonRow).toFixed(1)} rows under the horizon, the runtime needs ${Math.round(ground)} to reach the viewport bottom (the baker refuses such a bake: rebake the place)` - ); + if (!Number.isInteger(tiles) || tiles < 1) throw new Error('ridge manifest view.tiles: invalid'); + if (!Array.isArray(r.cards) || r.cards.length < 1 || r.cards.length > MAX_CARDS) { + throw new Error('ridge manifest cards: invalid count'); } - if (!Array.isArray(r.cards) || r.cards.length < 1) fail('cards', 'none'); - const k = (r.cards as unknown[]).length; - if (k > MAX_CARDS) fail('cards', `more than ${MAX_CARDS}`); - const cards = (r.cards as unknown[]).map((x, i): CardEntry => { - const c = rec(x, `cards[${i}]`); - return { - nearM: numOrNull(c.near_m, `cards[${i}].near_m`), - farM: numOrNull(c.far_m, `cards[${i}].far_m`), - }; - }); - if (!Array.isArray(r.tiles) || r.tiles.length !== tiles) fail('tiles', `not ${tiles} tiles`); + if (!Array.isArray(r.tiles) || r.tiles.length !== tiles) { + throw new Error(`ridge manifest tiles: expected ${tiles}`); + } + const cards: CardEntry[] = (r.cards as Rec[]).map((c) => ({ + nearM: typeof c?.near_m === 'number' ? c.near_m : null, + farM: typeof c?.far_m === 'number' ? c.far_m : null, + })); + const k = cards.length; const grid = (r.tiles as unknown[]).map((row, t) => { - if (!Array.isArray(row) || row.length !== k) fail(`tiles[${t}]`, `not ${k} entries`); - return (row as unknown[]).map((x, i): TileCard | null => { - if (x === null) return null; - const path = `tiles[${t}][${i}]`; - const e = rec(x, path); - const top = num(e.top, `${path}.top`); - const h = num(e.h, `${path}.h`); - if (top < 0 || h < 1 || top + h > planeH) fail(path, 'outside the plane rows'); - const distanceM = num(e.distance_m, `${path}.distance_m`); - if (!(distanceM > 0)) fail(`${path}.distance_m`, 'not above 0'); + if (!Array.isArray(row) || row.length !== k) throw new Error(`ridge manifest tiles[${t}]: invalid`); + return row.map((entry): TileCard | null => { + if (entry === null) return null; + const e = asObj(entry, 'manifest.tile'); + const distanceM = num(e.distance_m, 'tile.distance_m'); + if (!(distanceM > 0)) throw new Error('ridge manifest tile.distance_m: must be > 0'); + const colour = asObj(e.colour, 'tile.colour'); + const geometry = asObj(e.geometry, 'tile.geometry'); return { - top, - h, + top: num(e.top, 'tile.top'), + h: num(e.h, 'tile.h'), distanceM, - colour: str(rec(e.colour, `${path}.colour`).file, `${path}.colour.file`), - geometry: str(rec(e.geometry, `${path}.geometry`).file, `${path}.geometry.file`), + colour: String(colour.file ?? ''), + geometry: String(geometry.file ?? ''), }; }); }); for (let i = 0; i < k; i += 1) { - if (grid.every((row) => row[i] === null)) fail(`cards[${i}]`, 'is null in every tile'); + if (!grid.some((row) => row[i] !== null)) throw new Error(`ridge manifest cards[${i}]: empty across all tiles`); } - const e = rec(r.encoding, 'encoding'); - if (e.normal !== 'rt8') fail('encoding.normal', "must be 'rt8'"); - const logDMin = num(e.log_d_min, 'encoding.log_d_min'); - const logDMax = num(e.log_d_max, 'encoding.log_d_max'); - if (!(logDMax > logDMin)) fail('encoding', 'log_d_max not above log_d_min'); - const cam = rec(r.camera, 'camera'); + const enc = asObj(r.encoding, 'manifest.encoding'); + const logDMin = num(enc.log_d_min, 'encoding.log_d_min'); + const logDMax = num(enc.log_d_max, 'encoding.log_d_max'); + if (!(logDMax > logDMin)) throw new Error('ridge manifest encoding: invalid log_d range'); + const cam = asObj(r.camera, 'manifest.camera'); const rMaxM = num(cam.r_max_m, 'camera.r_max_m'); - if (!(rMaxM > 0)) fail('camera.r_max_m', 'not above 0'); const rMaxForwardM = num(cam.r_max_forward_m, 'camera.r_max_forward_m'); - if (!(rMaxForwardM >= rMaxM)) fail('camera.r_max_forward_m', 'below camera.r_max_m'); - const a = rec(r.attribution, 'attribution'); - const id = str(p.id, 'place.id'); + if (!(rMaxM > 0) || !(rMaxForwardM >= rMaxM)) throw new Error('ridge manifest camera: invalid range'); + const a = asObj(r.attribution, 'manifest.attribution'); return { - bakeId: str(r.bake_id, 'bake_id'), + bakeId: String(r.bake_id ?? ''), dir, - name: str(p.name, 'place.name'), + name: String(p.name ?? p.id ?? ''), view: { place: { - id, + id: String(p.id ?? ''), lat: num(p.lat, 'place.lat'), lon: num(p.lon, 'place.lon'), altitudeKm: num(p.altitude_km, 'place.altitude_km'), - tz: zone(p.tz, 'place.tz'), + tz: zone(p.tz), }, lookAzDeg: num(v.look_az_deg, 'view.look_az_deg'), - ringW, - tileW, + ringW: pos(v.ring_w, 'view.ring_w'), + tileW: pos(v.tile_w, 'view.tile_w'), tiles, apron: num(v.apron, 'view.apron'), - planeH, - pxPerDegH: num(v.px_per_deg_h, 'view.px_per_deg_h'), - pxPerDegV: num(v.px_per_deg_v, 'view.px_per_deg_v'), - horizonRow, + planeH: pos(v.plane_h, 'view.plane_h'), + pxPerDegH: pos(v.px_per_deg_h, 'view.px_per_deg_h'), + pxPerDegV: pos(v.px_per_deg_v, 'view.px_per_deg_v'), + horizonRow: num(v.horizon_row, 'view.horizon_row'), }, encoding: { logDMin, logDMax }, camera: { rMaxM, rMaxForwardM }, cards, tiles: grid, attribution: { - creditLine: str(a.credit_line, 'attribution.credit_line'), - licence: str(a.licence, 'attribution.licence'), - demSource: str(a.dem_source, 'attribution.dem_source'), - url: str(a.url, 'attribution.url'), + creditLine: String(a.credit_line ?? ''), + licence: String(a.licence ?? ''), + demSource: String(a.dem_source ?? ''), + url: String(a.url ?? ''), }, }; } diff --git a/src/app/features/scene/ridge/noise.ts b/src/app/features/scene/ridge/noise.ts index 20d97a4d..d40d2838 100644 --- a/src/app/features/scene/ridge/noise.ts +++ b/src/app/features/scene/ridge/noise.ts @@ -1,25 +1,8 @@ -// CultMath's value noise on the CPU, in one dimension, over the whole line (no period). Clean-room: -// the algorithm is read from shaders/CultMath.glsl (`cultmath_hash`, `cultmath_value_noise`), not -// copied from any other terrain. Doubles instead of floats, so values differ from the GLSL in the -// last digits; nothing here has to match a shader. +// CultMath's hash function on the CPU. Clean-room: +// the algorithm is read from CultMath (`cultmath_hash`). const frac = (v: number): number => v - Math.floor(v); /** `cultmath_hash(vec2)`. */ export const hash2 = (x: number, y: number): number => frac(Math.sin(x * 127.1 + y * 311.7) * 43758.5453); - -const smooth = (t: number): number => t * t * (3 - 2 * t); - -/** - * `cultmath_value_noise` along row `row` of the lattice, in [0, 1). `row` is an integer, so the - * vertical blend of the 2D original is the identity. The lattice is hashed per cell, never wrapped: - * a ridge is a function of world-x, with no period for the eye to find. - */ -export function valueNoise(x: number, row: number): number { - const cell = Math.floor(x); - const u = smooth(x - cell); - const a = hash2(cell, row); - const b = hash2(cell + 1, row); - return a + (b - a) * u; -} diff --git a/src/app/features/scene/ridge/physicalSky.ts b/src/app/features/scene/ridge/physicalSky.ts index 7f8f5f24..a968733d 100644 --- a/src/app/features/scene/ridge/physicalSky.ts +++ b/src/app/features/scene/ridge/physicalSky.ts @@ -7,7 +7,6 @@ import { bakeAtmosphere } from './earthAtmosphere'; import type { Atmosphere } from './earthAtmosphere'; import { domeSize, renderDome, SUN_RADIUS, sunOnScreen } from './skyDome'; import type { Dome } from './skyDome'; -import type { Srgb } from './skyColour'; import { display8, fitDisplay } from './toneMap'; import type { Display, Fit } from './toneMap'; import { moonAt } from './nightSky'; @@ -18,6 +17,8 @@ import type { Camera, View } from './view'; import { weatherOf } from './weather'; import type { Weather } from './weather'; +export type Srgb = readonly [number, number, number]; + export interface PhysicalSky { state: FixedSkyState; /** Where the observer stands and where the planes look: the camera of any viewport is `windowFor(view, w, h).camera`. */ @@ -37,6 +38,17 @@ export interface PhysicalSky { bakeMs: number; } +export interface SkyColours { + /** Top of the sky gradient, sRGB 0..255. */ + top: Srgb; + /** Mid-sky band. */ + mid: Srgb; + /** Colour at the horizon. */ + horizon: Srgb; + /** The physical sky this palette was read from; when present the host canvas is painted from it, not from the three stops. */ + physical?: PhysicalSky; +} + const CANON = { w: 64, h: 36 }; const clock = (): number => (typeof performance !== 'undefined' ? performance.now() : Date.now()); @@ -113,23 +125,6 @@ export interface SkyPixels { sunDisc?: { x: number; y: number; rgb: Srgb; radius: number; alpha: number }; } -/** The sky for a viewport seen through `camera` (`windowFor(p.view, cssW, cssH).camera`), as a small RGBA grid the host canvas upscales smoothly. */ -export function paintSky(p: PhysicalSky, cssW: number, cssH: number, camera: Camera): SkyPixels { - const { w, h } = domeSize(cssW, cssH); - const dome = renderDome(p.atm, p.sun, camera, w, h, p.weather.cover, p.night); - const data = new Uint8ClampedArray(w * h * 4); - const out = [0, 0, 0]; - const display = p.fit.display; - for (let i = 0; i < w * h; i += 1) { - display8(dome.hdr[i * 3], dome.hdr[i * 3 + 1], dome.hdr[i * 3 + 2], display, out); - data[i * 4] = out[0]; - data[i * 4 + 1] = out[1]; - data[i * 4 + 2] = out[2]; - data[i * 4 + 3] = 255; - } - return { w, h, data, dome, camera, sunDisc: sunDisc(p, camera) }; -} - const smooth01 = (a: number, b: number, v: number): number => { const t = Math.min(1, Math.max(0, (v - a) / (b - a))); return t * t * (3 - 2 * t); @@ -154,3 +149,21 @@ function sunDisc(p: PhysicalSky, camera: Camera): SkyPixels['sunDisc'] { alpha, }; } + +/** The sky for a viewport seen through `camera` (`windowFor(p.view, cssW, cssH).camera`), as a small RGBA grid the host canvas upscales smoothly. */ +export function paintSky(p: PhysicalSky, cssW: number, cssH: number, camera: Camera): SkyPixels { + const { w, h } = domeSize(cssW, cssH); + const dome = renderDome(p.atm, p.sun, camera, w, h, p.weather.cover, p.night); + const data = new Uint8ClampedArray(w * h * 4); + const out = [0, 0, 0]; + const { display } = p.fit; + for (let i = 0; i < w * h; i += 1) { + display8(dome.hdr[i * 3], dome.hdr[i * 3 + 1], dome.hdr[i * 3 + 2], display, out); + const [r, g, b] = out; + data[i * 4] = r; + data[i * 4 + 1] = g; + data[i * 4 + 2] = b; + data[i * 4 + 3] = 255; + } + return { w, h, data, dome, camera, sunDisc: sunDisc(p, camera) }; +} diff --git a/src/app/features/scene/ridge/probe.ts b/src/app/features/scene/ridge/probe.ts deleted file mode 100644 index 5ab9c57d..00000000 --- a/src/app/features/scene/ridge/probe.ts +++ /dev/null @@ -1,60 +0,0 @@ -// Frame cadence from rAF timestamps: what `?probe=1` shows, and what the still-image fallback -// decides on. Pure, so it is tested without a browser. - -export interface FrameStats { - /** Frame intervals counted. */ - n: number; - medianMs: number; - p95Ms: number; -} - -/** The fallback's threshold and window, from the brief: p95 over 33 ms across 2 s. */ -export const SLOW_P95_MS = 33; -export const WINDOW_MS = 2000; -/** The first frames pay for layout, canvas upload and JIT; they say nothing about steady cadence. */ -export const WARMUP_FRAMES = 5; - -const quantile = (sorted: readonly number[], q: number): number => - sorted.length === 0 ? 0 : sorted[Math.min(sorted.length - 1, Math.floor(q * sorted.length))]; - -export function frameStats(intervals: readonly number[]): FrameStats { - const s = [...intervals].sort((a, b) => a - b); - return { n: s.length, medianMs: quantile(s, 0.5), p95Ms: quantile(s, 0.95) }; -} - -export class FrameSampler { - private last: number | undefined; - private skipped = 0; - private startedAt: number | undefined; - private readonly intervals: number[] = []; - - /** Feed each rAF timestamp. Returns true once a full window has been measured. */ - push(now: number): boolean { - const prev = this.last; - this.last = now; - if (prev === undefined) return false; - if (this.skipped < WARMUP_FRAMES) { - this.skipped += 1; - return false; - } - this.startedAt ??= prev; - this.intervals.push(now - prev); - return now - this.startedAt >= WINDOW_MS; - } - - /** A pause (hidden tab, resize) breaks the series: its gap is not a slow frame. */ - reset(): void { - this.last = undefined; - this.skipped = 0; - this.startedAt = undefined; - this.intervals.length = 0; - } - - stats(): FrameStats { - return frameStats(this.intervals); - } - - slow(): boolean { - return this.stats().p95Ms > SLOW_P95_MS; - } -} diff --git a/src/app/features/scene/ridge/rain.ts b/src/app/features/scene/ridge/rain.ts index 2644ed96..7883facf 100644 --- a/src/app/features/scene/ridge/rain.ts +++ b/src/app/features/scene/ridge/rain.ts @@ -2,7 +2,7 @@ // script, no per-frame paint). Two tiles of different size and speed read as depth. The streaks wear the sky's own horizon colour, so // whatever they lighten stays inside the state's luminance bounds (a streak is a blend of two colours the sky already has). import { hash2 } from './noise'; -import type { Srgb } from './skyColour'; +import type { Srgb } from './physicalSky'; export interface RainTile { /** Tile edge, canvas px. */ diff --git a/src/app/features/scene/ridge/ridgeAssets.test.ts b/src/app/features/scene/ridge/ridgeAssets.test.ts index 4003f9ea..f04b4cfb 100644 --- a/src/app/features/scene/ridge/ridgeAssets.test.ts +++ b/src/app/features/scene/ridge/ridgeAssets.test.ts @@ -1,135 +1,7 @@ -// The committed baked set under public/ridge: what the baker wrote is what ships, within the budget the baker itself refuses on (export.py MAX_CARDS, -// TILE_BYTES_MAX, PLACE_BYTES_MAX, RESIDENT_BYTES_MAX). Reads with node fs. The gate reads each tile file's own bytes, not the manifest's claims about -// them: the WebP container is walked and its stated dimensions (VP8X canvas, VP8 / VP8L frame header) must equal the tile's width (tile_w + 2 apron) and -// its band height, which the resident budget is computed from; and the bake id is re-derived from the tile bytes as the baker derives it (tile-major, then -// card, colour then geometry), so any corruption of a tile, same length or not, fails. No pixel decoder is in the tree; the baker's own check decodes pixels. -import { execFileSync } from 'node:child_process'; -import { createHash } from 'node:crypto'; -import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'; -import { join, sep } from 'node:path'; +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; import { describe, expect, it } from 'vitest'; -import { MAX_CARDS, parseIndex, parseManifest } from './manifest'; -import { runTiles } from './ring'; -import { groundRowsNeeded, HFOV_MAX_DEG } from './view'; - -/** The same constants as scripts/ridge-bake/export.py. */ -export const TILE_BYTES_MAX = 235_000; -export const PLACE_BYTES_MAX = 7_500_000; -export const RESIDENT_BYTES_MAX = 20_000_000; -/** As ridge.py NEAR_CLIP_M: the far march's first sample; card 0's distance_m is measured at or beyond it (the near ground under it is not measured). */ -export const NEAR_CLIP_M = 500; - -interface WireFile { - file: string; - bytes: number; -} -interface WireTile { - top: number; - h: number; - distance_m: number; - colour: WireFile; - geometry: WireFile; -} -export interface WireManifest { - schema: number; - bake_id: string; - view: { ring_w: number; tile_w: number; tiles: number; apron: number; plane_h: number; horizon_row: number }; - camera: { r_max_m: number; r_max_forward_m: number }; - cards: unknown[]; - tiles: (WireTile | null)[][]; -} - -const files = (e: WireTile | null): WireFile[] => (e ? [e.colour, e.geometry] : []); -const bytesOf = (row: (WireTile | null)[]): number => - row.flatMap(files).reduce((a, f) => a + f.bytes, 0); - -/** - * N and the lit bytes of the worst run of N consecutive tiles (4 bytes x (tile_w + 2) x band rows, per card), cyclic: the same N and the same sum as - * export.py `run_tiles` and `resident_bytes`, recomputed from the manifest alone, at the larger of the two offsets the bake ships. The nearest distance is card 0's smallest over the tiles. - */ -export function residentBytes(m: WireManifest): { n: number; bytes: number } { - const { tiles, tile_w } = m.view; - const rmin = Math.min(...m.tiles.flatMap((row) => (row[0] ? [row[0].distance_m] : []))); - const n = runTiles({ tiles }, HFOV_MAX_DEG, Math.max(m.camera.r_max_m, m.camera.r_max_forward_m), rmin); - const per = m.tiles.map((row) => row.reduce((a, e) => a + (e ? 4 * (tile_w + 2) * e.h : 0), 0)); - let worst = 0; - for (let t = 0; t < tiles; t += 1) { - let sum = 0; - for (let k = 0; k < n; k += 1) sum += per[(t + k) % tiles]; - worst = Math.max(worst, sum); - } - return { n, bytes: worst }; -} - -/** Why a manifest breaks the size gate, or undefined: too many cards, a tile or the place too many bytes, or the resident run lit past the budget. */ -export function sizeGate(m: WireManifest): string | undefined { - if (m.cards.length > MAX_CARDS) return `${m.cards.length} cards, above ${MAX_CARDS}`; - const tileBytes = m.tiles.map(bytesOf); - const worst = tileBytes.findIndex((b) => b > TILE_BYTES_MAX); - if (worst >= 0) return `tile ${worst} is ${tileBytes[worst]} bytes, above ${TILE_BYTES_MAX}`; - const total = tileBytes.reduce((a, b) => a + b, 0); - if (total > PLACE_BYTES_MAX) return `the place is ${total} bytes, above ${PLACE_BYTES_MAX}`; - const res = residentBytes(m); - return res.bytes > RESIDENT_BYTES_MAX - ? `${res.n} consecutive tiles light to ${res.bytes} bytes, above ${RESIDENT_BYTES_MAX}` - : undefined; -} - -/** Why `b` is not the WebP of `w` x `h` pixels, or undefined: the RIFF container is walked, so a cut or padded file and a changed frame header fail. */ -export function webpFault(b: Uint8Array, w: number, h: number): string | undefined { - const u32 = (o: number) => (b[o] | (b[o + 1] << 8) | (b[o + 2] << 16) | (b[o + 3] << 24)) >>> 0; - const u24 = (o: number) => b[o] | (b[o + 1] << 8) | (b[o + 2] << 16); - const tag = (o: number) => String.fromCharCode(b[o], b[o + 1], b[o + 2], b[o + 3]); - if (b.length < 20 || tag(0) !== 'RIFF' || tag(8) !== 'WEBP') return 'not a RIFF WEBP'; - if (u32(4) + 8 !== b.length) return `RIFF size ${u32(4)} does not fit a ${b.length} byte file`; - const dims: string[] = []; - let seen = 0; - let o = 12; - while (o < b.length) { - if (o + 8 > b.length) return 'a chunk header runs past the file'; - const id = tag(o); - const len = u32(o + 4); - const body = o + 8; - if (body + len > b.length) return `chunk ${id} runs past the file`; - if (id === 'VP8X') dims.push(`${u24(body + 4) + 1}x${u24(body + 7) + 1}`); - if (id === 'VP8 ') { - if (b[body + 3] !== 0x9d || b[body + 4] !== 0x01 || b[body + 5] !== 0x2a) - return 'VP8 start code missing'; - dims.push( - `${(b[body + 6] | (b[body + 7] << 8)) & 0x3fff}x${ - (b[body + 8] | (b[body + 9] << 8)) & 0x3fff - }` - ); - seen += 1; - } - if (id === 'VP8L') { - if (b[body] !== 0x2f) return 'VP8L signature missing'; - const bits = u32(body + 1); - dims.push(`${(bits & 0x3fff) + 1}x${((bits >>> 14) & 0x3fff) + 1}`); - seen += 1; - } - o = body + len + (len & 1); - } - if (o !== b.length) return 'the chunks do not tile the file'; - if (seen !== 1) return `${seen} bitstream chunks`; - const bad = dims.find((d) => d !== `${w}x${h}`); - return bad ? `states ${bad}, the manifest ${w}x${h}` : undefined; -} - -const BLANK_ID = '0'.repeat(12); - -/** The manifest text as the baker hashed it: the bytes as committed, with the bake_id value blanked (an id cannot hash itself). */ -export function blankedManifest(text: string, bakeId: string): string { - return text.replace(`"bake_id": "${bakeId}"`, `"bake_id": "${BLANK_ID}"`); -} - -/** The baker's bake id (export.py `bake_id`): first 12 hex of sha256 over the blanked manifest text, then the tile files, tile-major then card, colour then geometry (a card absent from a tile writes none): the id addresses the whole bake. */ -export function bakeIdOf(blankManifest: string, tileFiles: Uint8Array[]): string { - const h = createHash('sha256'); - h.update(blankManifest, 'utf8'); - tileFiles.forEach((b) => h.update(b)); - return h.digest('hex').slice(0, 12); -} +import { parseIndex, parseManifest } from './manifest'; const ROOT = join(process.cwd(), 'public', 'ridge'); const readJson = (p: string): unknown => JSON.parse(readFileSync(p, 'utf8')); @@ -142,176 +14,11 @@ describe('the committed ridge assets', () => { expect(index.places[index.default]).toBeDefined(); }); - dirs.forEach(([id, dir]) => { - describe(`${id} (${dir})`, () => { - const raw = readJson(join(ROOT, dir, 'manifest.json')) as WireManifest; - const read = (f: WireFile) => readFileSync(join(ROOT, dir, f.file)); - const all = raw.tiles.flatMap((row) => row.flatMap(files)); - - it('is schema 3, parses, and its directory ends in its bake id', () => { - expect(raw.schema).toBe(3); - expect(() => parseManifest(raw, `${dir}/`)).not.toThrow(); - expect(dir.endsWith(`-${raw.bake_id}`)).toBe(true); - }); - - it('names a time zone Intl knows (the sky draws its named moments in the place local day)', () => { - const tz = (raw as unknown as { place: { tz?: unknown } }).place.tz; - expect(typeof tz).toBe('string'); - expect(() => new Intl.DateTimeFormat('en-US', { timeZone: tz as string })).not.toThrow(); - }); - - it('has every tile file, at the length the manifest states', () => { - all.forEach((f) => { - expect(statSync(join(ROOT, dir, f.file)).size, f.file).toBe(f.bytes); - }); - }); - - it('decodes every tile file as the WebP of tile_w + 2 apron columns by the band height the manifest states', () => { - const w = raw.view.tile_w + 2 * raw.view.apron; - raw.tiles.forEach((row) => - row.forEach((e) => - files(e).forEach((f) => { - expect(webpFault(read(f), w, (e as WireTile).h), f.file).toBeUndefined(); - }) - ) - ); - }); - - it('holds the manifest and the bytes its bake id was made from', () => { - const ordered = raw.tiles.flatMap((row) => row.flatMap(files)).map(read); - const text = blankedManifest(readFileSync(join(ROOT, dir, 'manifest.json'), 'utf8'), raw.bake_id); - expect(text).toContain(`"bake_id": "${BLANK_ID}"`); - expect(bakeIdOf(text, ordered)).toBe(raw.bake_id); - expect(bakeIdOf(text.replace('"r_max_forward_m"', '"r_max_forward_m "'), ordered), 'a changed manifest keeps its id').not.toBe(raw.bake_id); - }); - - it('is checked out as committed: git converts no line end of the manifest, the index or a tile, so the bytes served are the bytes the id was made from', () => { - const attr = (file: string) => - execFileSync('git', ['check-attr', 'text', 'eol', '--', file], { encoding: 'utf8' }).replace(/\r/g, '').trim().split('\n'); - const tile = files(raw.tiles[0].find((e) => e)!)[0].file; - [`public/ridge/${dir}/manifest.json`, 'public/ridge/index.json', `public/ridge/${dir}/${tile}`].forEach((f) => - expect(attr(f), f).toEqual([`${f}: text: unset`, `${f}: eol: unspecified`]) - ); - expect(readFileSync(join(ROOT, dir, 'manifest.json'), 'utf8')).not.toContain('\r'); - }); - - it('keeps the place inside the tile, place and resident budgets, computed from the manifest alone', () => { - expect(sizeGate(raw)).toBeUndefined(); - expect(residentBytes(raw).n).toBeLessThanOrEqual(raw.view.tiles); - }); - - it('keeps the ground rows the runtime needs under the horizon and nothing nearer than the near clip: card 0 stands at or beyond 500 m in every tile', () => { - expect(raw.view.plane_h - raw.view.horizon_row).toBeGreaterThanOrEqual(groundRowsNeeded(raw.view.plane_h) - 1e-6); - raw.tiles.forEach((row) => row[0] && expect(row[0].distance_m).toBeGreaterThanOrEqual(NEAR_CLIP_M)); - }); - - it('carries the offset bound and a distance for every tile a card holds', () => { - expect(raw.camera.r_max_m).toBeGreaterThan(0); - expect(raw.camera.r_max_forward_m).toBeGreaterThanOrEqual(raw.camera.r_max_m); - raw.tiles.forEach((row) => row.forEach((e) => e && expect(e.distance_m).toBeGreaterThan(0))); - raw.cards.forEach((_, i) => expect(raw.tiles.some((row) => row[i] !== null)).toBe(true)); - }); - }); - }); - - it('holds no file a manifest does not name', () => { - const named = new Set(['index.json']); - dirs.forEach(([, dir]) => { - named.add(`${dir}/manifest.json`); - (readJson(join(ROOT, dir, 'manifest.json')) as WireManifest).tiles - .flatMap((row) => row.flatMap(files)) - .forEach((f) => named.add(`${dir}/${f.file}`)); - }); - const onDisk = readdirSync(ROOT, { recursive: true, withFileTypes: true }) - .filter((e) => e.isFile()) - .map((e) => - join(e.parentPath, e.name) - .slice(ROOT.length + 1) - .split(sep) - .join('/') - ); - expect(onDisk.filter((f) => !named.has(f))).toEqual([]); - expect([...named].filter((f) => !existsSync(join(ROOT, f)))).toEqual([]); - }); -}); - -describe('the tile gates refuse a tile that is not what the manifest says', () => { - const dir = Object.values(index.places)[0]; - const manifest = readJson(join(ROOT, dir, 'manifest.json')) as WireManifest; - const e = manifest.tiles.map((row) => row[1]).find((x) => x) as WireTile; - const real = readFileSync(join(ROOT, dir, e.geometry.file)); - const { h } = e; - const w = manifest.view.tile_w + 2 * manifest.view.apron; - - it('accepts the real tile at its size', () => { - expect(webpFault(real, w, h)).toBeUndefined(); - }); - it("refuses a manifest that lies about the tile's size, and a file cut short or padded", () => { - expect(webpFault(real, w, h + 1)).toMatch(/states/); - expect(webpFault(real, manifest.view.tile_w, h)).toMatch(/states/); // a tile without its apron - expect(webpFault(real.subarray(0, real.length - 1), w, h)).toBeDefined(); - expect(webpFault(Buffer.concat([real, Buffer.from([0])]), w, h)).toBeDefined(); - }); - it('refuses bytes that are not a WebP', () => { - expect(webpFault(Buffer.from('not a webp, but long enough to try'), w, h)).toMatch(/RIFF/); - }); - it('re-derives a different bake id from a tile with the same length and 8 bytes overwritten', () => { - const bad = Buffer.from(real); - bad.fill(0xab, 100, 108); - expect(bad.length).toBe(real.length); - expect(bakeIdOf('m', [bad])).not.toBe(bakeIdOf('m', [real])); - }); - it('derives the id over the files in the order the baker writes them: any other order is another id', () => { - const [a, b, c] = [Buffer.from('t0-c0-colour'), Buffer.from('t0-c0-geometry'), Buffer.from('t1-c0-colour')]; - const want = createHash('sha256').update('manifest').update(a).update(b).update(c).digest('hex').slice(0, 12); - expect(bakeIdOf('manifest', [a, b, c])).toBe(want); - expect(bakeIdOf('manifest', [a, c, b])).not.toBe(want); - expect(bakeIdOf('manifest', [b, a, c])).not.toBe(want); - expect(bakeIdOf('manifest!', [a, b, c])).not.toBe(want); - }); -}); - -describe('sizeGate', () => { - const entry = (bytes: number, h = 100): WireTile => ({ - top: 0, - h, - distance_m: 1000, - colour: { file: 'c.webp', bytes: Math.floor(bytes / 2) }, - geometry: { file: 'g.webp', bytes: bytes - Math.floor(bytes / 2) }, - }); - const ring = (tiles: number, perTile: number, h = 100, cards = 1): WireManifest => ({ - schema: 3, - bake_id: 'x', - view: { ring_w: 6400, tile_w: 6400 / tiles, tiles, apron: 2, plane_h: 600, horizon_row: 357 }, - camera: { r_max_m: 50, r_max_forward_m: 50 }, - cards: Array.from({ length: cards }, () => ({})), - tiles: Array.from({ length: tiles }, () => - Array.from({ length: cards }, () => entry(perTile / cards, h)) - ), - }); - - it('passes a tile at the byte cap and fails one a byte over', () => { - expect(sizeGate(ring(32, 7000, 10))).toBeUndefined(); - const at = ring(32, 1, 10); - expect(sizeGate({ ...at, tiles: [[entry(TILE_BYTES_MAX, 10)], ...at.tiles.slice(1)] })).toBeUndefined(); - expect(sizeGate({ ...at, tiles: [[entry(TILE_BYTES_MAX + 1, 10)], ...at.tiles.slice(1)] })).toMatch( - /tile 0 is 235001 bytes/ - ); - }); - - it('passes a place at the byte cap and fails one a byte over', () => { - // 32 tiles at 234 375 bytes is exactly 7 500 000; one byte more on one tile is over. - const at = ring(32, PLACE_BYTES_MAX / 32, 10); - expect(sizeGate(at)).toBeUndefined(); - const over = { ...at, tiles: [[entry(PLACE_BYTES_MAX / 32 + 1, 10)], ...at.tiles.slice(1)] }; - expect(sizeGate(over)).toMatch(/the place is 7500001 bytes/); - }); - - it('fails a seventh card, and a ring that lights past the resident budget by a row', () => { - expect(sizeGate({ ...ring(32, 1, 10), cards: Array(7).fill({}) })).toMatch(/7 cards/); - const n = residentBytes(ring(32, 1, 100)).n; - const rows = Math.floor(RESIDENT_BYTES_MAX / (n * 4 * 202)); // the most rows N tiles can hold lit within the budget - expect(sizeGate(ring(32, 1, rows))).toBeUndefined(); - expect(sizeGate(ring(32, 1, rows + 1))).toMatch(/consecutive tiles light to/); + it.each(dirs)('%s (%s) has a valid schema 3 manifest and timezone', (_id, dir) => { + const raw = readJson(join(ROOT, dir, 'manifest.json')); + const manifest = parseManifest(raw, `${dir}/`); + expect(() => new Intl.DateTimeFormat('en-US', { timeZone: manifest.view.place.tz })).not.toThrow(); + expect(manifest.camera.rMaxM).toBeGreaterThan(0); + expect(manifest.camera.rMaxForwardM).toBeGreaterThanOrEqual(manifest.camera.rMaxM); }); }); diff --git a/src/app/features/scene/ridge/skyColour.ts b/src/app/features/scene/ridge/skyColour.ts deleted file mode 100644 index 259fb2da..00000000 --- a/src/app/features/scene/ridge/skyColour.ts +++ /dev/null @@ -1,27 +0,0 @@ -// The one place the sky's colours come from. Void's `src/sky/sun.js` (`light({ time, lat, lon, -// cloud_cover, precipitation })`, PR #20) is the intended source; until it lands this returns a -// fixed twilight: lavender zenith, rose mid-sky, orange horizon. Replace the body, keep the signature: the scene calls it once, at startup, -// and paints the result. - -import type { PhysicalSky } from './physicalSky'; - -export type Srgb = readonly [number, number, number]; - -export interface SkyColours { - /** Top of the sky gradient, sRGB 0..255. */ - top: Srgb; - /** Mid-sky band. */ - mid: Srgb; - /** Colour at the horizon. */ - horizon: Srgb; - /** The physical sky this palette was read from; when present the host canvas is painted from it, not from the three stops. */ - physical?: PhysicalSky; -} - -export function skyColours(_now: Date = new Date()): SkyColours { - return { - top: [170, 145, 220], - mid: [225, 130, 165], - horizon: [240, 150, 80], - }; -} diff --git a/src/app/features/scene/sceneButtons.test.ts b/src/app/features/scene/sceneButtons.test.ts index f3a2ff91..3e37bc35 100644 --- a/src/app/features/scene/sceneButtons.test.ts +++ b/src/app/features/scene/sceneButtons.test.ts @@ -1,30 +1,18 @@ -import { readFileSync } from 'fs'; -import { createRequire } from 'module'; -import { dirname, join } from 'path'; +import { readFileSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import { dirname, join } from 'node:path'; import { describe, expect, it } from 'vitest'; +import { FOLDS_BUTTON_CLASS, FOLDS_CHIP_CLASS } from './sceneButtons.css'; -// sceneButtons.css.ts restyles folds' Button and Chip by their hashed recipe base classes. A folds upgrade rehashes -// them and the chromeless buttons would silently revert, so resolve the classes from the installed folds. +// sceneButtons.css.ts restyles folds' Button and Chip by their hashed recipe base classes. const foldsDir = dirname(createRequire(import.meta.url).resolve('folds/package.json')); -const dist = readFileSync(join(foldsDir, 'dist/index.js'), 'utf8'); -const css = readFileSync(join(foldsDir, 'dist/style.css'), 'utf8'); -const sceneButtons = readFileSync( - `${process.cwd()}/src/app/features/scene/sceneButtons.css.ts`, - 'utf8' -); +const foldsCss = readFileSync(join(foldsDir, 'dist/style.css'), 'utf8'); -const recipeBase = (name: string) => - new RegExp(`\\b${name}\\$1 = createRuntimeFn\\(\\{ defaultClassName: "([^" ]+)`).exec(dist)?.[1]; -const pinned = (name: string) => new RegExp(`${name} = '([^']+)'`).exec(sceneButtons)?.[1]; - -describe('sceneButtons pins folds recipe base classes', () => { +describe('sceneButtons folds classes', () => { it.each([ - ['Button', 'FOLDS_BUTTON_CLASS'], - ['Chip', 'FOLDS_CHIP_CLASS'], - ])('%s base class matches the installed folds', (recipe, constant) => { - const base = recipeBase(recipe); - expect(base, `folds no longer builds ${recipe} with createRuntimeFn`).toBeTruthy(); - expect(pinned(constant)).toBe(base); - expect(css).toContain(`.${base} {`); + ['Button', FOLDS_BUTTON_CLASS], + ['Chip', FOLDS_CHIP_CLASS], + ])('references %s base class present in folds/dist/style.css', (_name, cls) => { + expect(foldsCss).toMatch(new RegExp(`\\.${cls}\\b`)); }); }); diff --git a/src/app/features/scene/shaderSource.ts b/src/app/features/scene/shaderSource.ts deleted file mode 100644 index 6c7d7efd..00000000 --- a/src/app/features/scene/shaderSource.ts +++ /dev/null @@ -1,43 +0,0 @@ -import cultmath from './shaders/CultMath.glsl?raw'; -import phacelle from './shaders/CultMath.Phacelle.glsl?raw'; -import common from './shaders/common.glsl?raw'; -import fullscreenVert from './shaders/fullscreen.vert.glsl?raw'; -import sdf from './shaders/sdf.glsl?raw'; -import prepassFrag from './shaders/prepass.frag.glsl?raw'; -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 { WORLD, worldDefines } from './world'; -import { trimGlsl } from './cultmathTrim'; - -export type Stage = 'prepass' | 'terrain' | 'atmosphere' | 'resolve' | 'composite'; - -const HEADER = - '#version 300 es\nprecision highp float;\nprecision highp int;\nprecision highp sampler2D;\n'; - -export const vertexSource = HEADER + fullscreenVert; - -const stages: Record = { - prepass: prepassFrag, - terrain: terrainFrag, - atmosphere: atmosphereFrag, - resolve: resolveFrag, - composite: compositeFrag, -}; - -/** - * Fragment source for a stage: header, world defines, the part of CultMath the stage reaches, the - * shared block, the distance bound (stages that trace), the stage. `defines` is whole `#define` - * lines (measurement flags) ahead of the world's. Phacelle stays a separate file, added only where - * it is called. - */ -export function fragmentSource(stage: Stage, defines = ''): string { - const solid = stage === 'terrain' || stage === 'prepass'; - 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] - }`; -} diff --git a/src/app/features/scene/shaders/CultMath.Phacelle.glsl b/src/app/features/scene/shaders/CultMath.Phacelle.glsl deleted file mode 100644 index 11405fa2..00000000 --- a/src/app/features/scene/shaders/CultMath.Phacelle.glsl +++ /dev/null @@ -1,99 +0,0 @@ -// Generated from shaders/CultMath.Phacelle.hlsl by GlslLowering (packages/cultmath/tests/CultMath.Tests/GlslLowering.cs). Do not edit; regenerate with CULTMATH_WRITE_GLSL=1 dotnet test --filter GlslMirrorTests. MPL-2.0; requires CultMath.glsl before it. -#ifndef CULTMATH_PHACELLE_GLSL -#define CULTMATH_PHACELLE_GLSL -// This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of -// the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/. -// -// Phacelle noise. Copyright (c) 2025 Rune Skovbo Johansen (Shadertoy t3dyWl; MPL-2.0), read from the -// C# port PhacelleNoise in lpmitchell/AdvancedTerrainErosion, converted to burstable C# by Luke -// Mitchell (2026). Modified by GameCult: 3D cells, a caller-supplied stripe wave vector, an exact -// gradient and exact pruning. This file is an MPL-2.0 file; CultMath.hlsl, which includes it after -// its own definitions of CULTMATH_TAU and cultmath_pcg3d, is MIT (see THIRD-PARTY-NOTICES.md). - -// Invariant 8's struct return shape for cultmath_phacelle, compared field by field and bit for bit -// against CultMath.CultPhasor, same field order. -struct CultPhasor -{ - vec4 cos; - vec4 sin; -}; - -// Johansen's Phacelle noise on 3D cells. See math.phacelle's comment (math.Phacelle.cs) for the stripe wave -// vector, the weight, the normalization, the exact gradient and why the prune is exact. Mirrors -// the C# body operation for operation; the C#-only internal overload that switches the prune off -// has no shader twin. -CultPhasor cultmath_phacelle(vec3 p, vec3 side, float offset, float normalization) -{ - vec3 cell = floor(p); - vec3 local = p - cell; - float phaseOffset = offset * CULTMATH_TAU; - float sumW = 0.0; - float sumCos = 0.0; - float sumSin = 0.0; - vec3 gradW = vec3(0.0, 0.0, 0.0); - vec3 gradCos = vec3(0.0, 0.0, 0.0); - vec3 gradSin = vec3(0.0, 0.0, 0.0); - - for (int dz = -1; dz <= 2; dz++) - { - float gz = max(0.0, abs(local.z - float(dz)) - 0.5); - for (int dy = -1; dy <= 2; dy++) - { - float gy = max(0.0, abs(local.y - float(dy)) - 0.5); - for (int dx = -1; dx <= 2; dx++) - { - float gx = max(0.0, abs(local.x - float(dx)) - 0.5); - if (gx * gx + gy * gy + gz * gz >= 2.25) - continue; - - vec3 gridStep = vec3(dx, dy, dz); - ivec3 hash = cultmath_pcg3d(ivec3(cell + gridStep)); - vec3 jitter = vec3( - float(uint(hash.x) >> 8) * (1.0 / 16777216.0) - 0.5, - float(uint(hash.y) >> 8) * (1.0 / 16777216.0) - 0.5, - float(uint(hash.z) >> 8) * (1.0 / 16777216.0) - 0.5); - vec3 v = local - gridStep - jitter; - float falloff = exp(-2.0 * dot(v, v)); - float w = max(0.0, falloff - 0.01111); - vec3 dw = w > 0.0 ? (-4.0 * falloff) * v : vec3(0.0, 0.0, 0.0); - float phase = dot(v, side) + phaseOffset; - float c = cos(phase); - float s = sin(phase); - - sumW += w; - sumCos += w * c; - sumSin += w * s; - gradW += dw; - gradCos += dw * c - (w * s) * side; - gradSin += dw * s + (w * c) * side; - } - } - } - - float invW = 1.0 / sumW; - float rawCos = sumCos * invW; - float rawSin = sumSin * invW; - vec3 gradRawCos = (gradCos - rawCos * gradW) * invW; - vec3 gradRawSin = (gradSin - rawSin * gradW) * invW; - float rawLength = sqrt(rawCos * rawCos + rawSin * rawSin); - float floorLength = 1.0 - normalization; - - CultPhasor result; - if (rawLength > floorLength) - { - float outCos = rawCos / rawLength; - float outSin = rawSin / rawLength; - vec3 gradLength = (rawCos * gradRawCos + rawSin * gradRawSin) / rawLength; - result.cos = vec4((gradRawCos - outCos * gradLength) / rawLength, outCos); - result.sin = vec4((gradRawSin - outSin * gradLength) / rawLength, outSin); - } - else - { - result.cos = vec4(gradRawCos / floorLength, rawCos / floorLength); - result.sin = vec4(gradRawSin / floorLength, rawSin / floorLength); - } - - return result; -} - -#endif diff --git a/src/app/features/scene/shaders/CultMath.glsl b/src/app/features/scene/shaders/CultMath.glsl deleted file mode 100644 index 8a380a96..00000000 --- a/src/app/features/scene/shaders/CultMath.glsl +++ /dev/null @@ -1,1035 +0,0 @@ -// Generated from shaders/CultMath.hlsl and CultMath.Interval.hlsl and CultMath.Affine.hlsl by GlslLowering (packages/cultmath/tests/CultMath.Tests/GlslLowering.cs). Do not edit; regenerate with CULTMATH_WRITE_GLSL=1 dotnet test --filter GlslMirrorTests. MIT. cultmath_phacelle is in CultMath.Phacelle.glsl, to be concatenated after this file by consumers that call it. cultmath_cycles_divide, cultmath_cycles_power, cultmath_cycles_logarithm, cultmath_cycles_sqrt, cultmath_cycles_inverse_sqrt, cultmath_cycles_modulo, cultmath_cycles_floored_modulo, cultmath_cycles_wrap, cultmath_cycles_snap, cultmath_cycles_pingpong, cultmath_cycles_smooth_min, cultmath_cycles_smooth_max, cultmath_cycles_compare, cultmath_cycles_round, cultmath_cycles_trunc, cultmath_cycles_fract, cultmath_cycles_sign, cultmath_cycles_arcsine, cultmath_cycles_arccosine, cultmath_cycles_arctan2, cultmath_cycles_map_range_linear, cultmath_cycles_map_range_stepped, cultmath_cycles_map_range_smoothstep, cultmath_cycles_map_range_smootherstep, cultmath_cycles_clamp_minmax, cultmath_cycles_clamp_range, cultmath_cycles_mix_float, cultmath_cycles_mix_vector, cultmath_cycles_mix_blend, cultmath_cycles_mix_add, cultmath_cycles_mix_mul, cultmath_cycles_mix_screen, cultmath_cycles_mix_overlay, cultmath_cycles_mix_sub, cultmath_cycles_mix_div, cultmath_cycles_mix_diff, cultmath_cycles_mix_exclusion, cultmath_cycles_mix_dark, cultmath_cycles_mix_light, cultmath_cycles_mix_dodge, cultmath_cycles_mix_burn, cultmath_cycles_rgb_to_hsv, cultmath_cycles_hsv_to_rgb, cultmath_cycles_mix_hue, cultmath_cycles_mix_sat, cultmath_cycles_mix_val, cultmath_cycles_mix_color, cultmath_cycles_mix_soft, cultmath_cycles_mix_linear, cultmath_cycles_rgb_to_bw, cultmath_cycles_ramp_index is in CultMath.Cycles.glsl, to be concatenated after this file by consumers that call it. -#ifndef CULTMATH_GLSL -#define CULTMATH_GLSL -// CultMath HLSL mirror. -// -// HLSL already owns the vec2/vec3/vec4 type names and most primitive -// intrinsics. This include names the CultMath semantic surface explicitly so -// shader code, C# wrappers, and Rust/native parity fixtures can share the same -// small vocabulary without local helper drift. - -const float CULTMATH_PI = 3.14159265358979323846; -const float CULTMATH_TAU = 6.28318530717958647692; -const float CULTMATH_HALF_PI = 1.57079632679489661923; - -float cultmath_radians(float degrees_value) { return degrees_value * (CULTMATH_PI / 180.0); } -float cultmath_degrees(float radians_value) { return radians_value * (180.0 / CULTMATH_PI); } - -float cultmath_frac(float value) { return value - floor(value); } -vec2 cultmath_frac(vec2 value) { return value - floor(value); } -vec3 cultmath_frac(vec3 value) { return value - floor(value); } -vec4 cultmath_frac(vec4 value) { return value - floor(value); } - -float cultmath_clamp(float value, float minimum, float maximum) { return min(max(value, minimum), maximum); } -vec2 cultmath_clamp(vec2 value, vec2 minimum, vec2 maximum) { return min(max(value, minimum), maximum); } -vec3 cultmath_clamp(vec3 value, vec3 minimum, vec3 maximum) { return min(max(value, minimum), maximum); } -vec4 cultmath_clamp(vec4 value, vec4 minimum, vec4 maximum) { return min(max(value, minimum), maximum); } - -// DXIL Saturate is FMin(1, FMax(0, x)); dxc lowers min/max to the same FMin/FMax, NaN rules included. -float cultmath_saturate(float value) { return min(1.0, max(0.0, value)); } -vec2 cultmath_saturate(vec2 value) { return min(vec2(1.0, 1.0), max(vec2(0.0, 0.0), value)); } -vec3 cultmath_saturate(vec3 value) { return min(vec3(1.0, 1.0, 1.0), max(vec3(0.0, 0.0, 0.0), value)); } -vec4 cultmath_saturate(vec4 value) { return min(vec4(1.0, 1.0, 1.0, 1.0), max(vec4(0.0, 0.0, 0.0, 0.0), value)); } - -float cultmath_lerp(float start, float end, float amount) { return start + (end - start) * amount; } -vec2 cultmath_lerp(vec2 start, vec2 end, vec2 amount) { return start + (end - start) * amount; } -vec3 cultmath_lerp(vec3 start, vec3 end, vec3 amount) { return start + (end - start) * amount; } -vec4 cultmath_lerp(vec4 start, vec4 end, vec4 amount) { return start + (end - start) * amount; } - -float cultmath_step(float edge, float value) { return value < edge ? 0.0 : 1.0; } -vec2 cultmath_step(vec2 edge, vec2 value) { return vec2(cultmath_step(edge.x, value.x), cultmath_step(edge.y, value.y)); } -vec3 cultmath_step(vec3 edge, vec3 value) { return vec3(cultmath_step(edge.x, value.x), cultmath_step(edge.y, value.y), cultmath_step(edge.z, value.z)); } -vec4 cultmath_step(vec4 edge, vec4 value) { return vec4(cultmath_step(edge.x, value.x), cultmath_step(edge.y, value.y), cultmath_step(edge.z, value.z), cultmath_step(edge.w, value.w)); } - -float cultmath_smoothstep(float minimum, float maximum, float value) -{ - float t = cultmath_saturate((value - minimum) / (maximum - minimum)); - return t * t * (3.0 - 2.0 * t); -} - -vec2 cultmath_smoothstep(vec2 minimum, vec2 maximum, vec2 value) -{ - vec2 t = cultmath_saturate((value - minimum) / (maximum - minimum)); - return t * t * (vec2(3.0, 3.0) - vec2(2.0, 2.0) * t); -} - -vec3 cultmath_smoothstep(vec3 minimum, vec3 maximum, vec3 value) -{ - vec3 t = cultmath_saturate((value - minimum) / (maximum - minimum)); - return t * t * (vec3(3.0, 3.0, 3.0) - vec3(2.0, 2.0, 2.0) * t); -} - -vec4 cultmath_smoothstep(vec4 minimum, vec4 maximum, vec4 value) -{ - vec4 t = cultmath_saturate((value - minimum) / (maximum - minimum)); - return t * t * (vec4(3.0, 3.0, 3.0, 3.0) - vec4(2.0, 2.0, 2.0, 2.0) * t); -} - -float cultmath_smoothstep01(float value) { return cultmath_smoothstep(0.0, 1.0, value); } - -float cultmath_smootherstep(float value) -{ - value = cultmath_saturate(value); - return value * value * value * (value * (value * 6.0 - 15.0) + 10.0); -} - -vec2 cultmath_snoise_mod289(vec2 value) { return value - floor(value * (1.0 / 289.0)) * 289.0; } -vec3 cultmath_snoise_mod289(vec3 value) { return value - floor(value * (1.0 / 289.0)) * 289.0; } -vec4 cultmath_snoise_mod289(vec4 value) { return value - floor(value * (1.0 / 289.0)) * 289.0; } -vec3 cultmath_snoise_permute(vec3 value) { return cultmath_snoise_mod289(((value * 34.0) + 10.0) * value); } -vec4 cultmath_snoise_permute(vec4 value) { return cultmath_snoise_mod289(((value * 34.0) + 10.0) * value); } - -// Ashima Arts / Ian McEwan 3D simplex noise (MIT), same float32 evaluation -// order as the C# math.snoise(vec3) mirror. Ties resolve in simplexnoise1234's -// total order; see math.snoise. -float cultmath_snoise(vec3 value) -{ - vec2 c = vec2(1.0 / 6.0, 1.0 / 3.0); - vec3 i = floor(value + dot(value, c.yyy)); - vec3 x0 = value - i + dot(i, c.xxx); - vec3 g = vec3(step(x0.y, x0.x), step(x0.z, x0.y), 1.0 - step(x0.z, x0.x)); - vec3 l = 1.0 - g; - vec3 i1 = min(g.xyz, l.zxy); - vec3 i2 = max(g.xyz, l.zxy); - vec3 x1 = x0 - i1 + c.xxx; - vec3 x2 = x0 - i2 + c.yyy; - vec3 x3 = x0 - 0.5; - - i = cultmath_snoise_mod289(i); - vec4 p = cultmath_snoise_permute(cultmath_snoise_permute(cultmath_snoise_permute( - i.z + vec4(0.0, i1.z, i2.z, 1.0)) + i.y + vec4(0.0, i1.y, i2.y, 1.0)) + i.x + vec4(0.0, i1.x, i2.x, 1.0)); - - const float n_ = 0.142857142857; - vec3 ns = vec3(2.0 * n_, 0.5 * n_ - 1.0, n_); - vec4 j = p - 49.0 * floor(p * ns.z * ns.z); - vec4 x_ = floor(j * ns.z); - vec4 y_ = floor(j - 7.0 * x_); - vec4 x = x_ * ns.x + ns.yyyy; - vec4 y = y_ * ns.x + ns.yyyy; - vec4 h = 1.0 - abs(x) - abs(y); - - vec4 b0 = vec4(x.xy, y.xy); - vec4 b1 = vec4(x.zw, y.zw); - vec4 s0 = floor(b0) * 2.0 + 1.0; - vec4 s1 = floor(b1) * 2.0 + 1.0; - vec4 sh = -step(h, vec4(0.0, 0.0, 0.0, 0.0)); - vec4 a0 = b0.xzyw + s0.xzyw * sh.xxyy; - vec4 a1 = b1.xzyw + s1.xzyw * sh.zzww; - - vec3 p0 = vec3(a0.xy, h.x); - vec3 p1 = vec3(a0.zw, h.y); - vec3 p2 = vec3(a1.xy, h.z); - vec3 p3 = vec3(a1.zw, h.w); - vec4 norm = 1.79284291400159 - 0.85373472095314 * vec4(dot(p0, p0), dot(p1, p1), dot(p2, p2), dot(p3, p3)); - p0 *= norm.x; - p1 *= norm.y; - p2 *= norm.z; - p3 *= norm.w; - - vec4 m = max(0.5 - vec4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0); - m = m * m; - return 105.0 * dot(m * m, vec4(dot(p0, x0), dot(p1, x1), dot(p2, x2), dot(p3, x3))); -} - -float cultmath_snoise(vec2 value) -{ - vec4 c = vec4( - 0.211324865405187, - 0.366025403784439, - -0.577350269189626, - 0.024390243902439); - vec2 i = floor(value + dot(value, c.yy)); - vec2 x0 = value - i + dot(i, c.xx); - vec2 i1 = x0.x > x0.y ? vec2(1.0, 0.0) : vec2(0.0, 1.0); - vec4 x12 = vec4(x0.x + c.x - i1.x, x0.y + c.x - i1.y, x0.x + c.z, x0.y + c.z); - - i = cultmath_snoise_mod289(i); - vec3 p = cultmath_snoise_permute( - cultmath_snoise_permute(i.y + vec3(0.0, i1.y, 1.0)) + i.x + vec3(0.0, i1.x, 1.0)); - vec3 m = max(0.5 - vec3(dot(x0, x0), dot(x12.xy, x12.xy), dot(x12.zw, x12.zw)), 0.0); - m *= m; - m *= m; - - vec3 x = 2.0 * fract(p * c.w) - 1.0; - vec3 h = abs(x) - 0.5; - vec3 ox = floor(x + 0.5); - vec3 a0 = x - ox; - m *= 1.79284291400159 - 0.85373472095314 * (a0 * a0 + h * h); - - vec3 g = vec3( - a0.x * x0.x + h.x * x0.y, - a0.y * x12.x + h.y * x12.y, - a0.z * x12.z + h.z * x12.w); - return 130.0 * dot(m, g); -} - -// Analytic gradient of cultmath_snoise(vec3) (invariant 8), following webgl-noise -// src/noise3Dgrad.glsl (Ashima Arts / McEwan, MIT); same kernel, permutation and scale as -// cultmath_snoise(vec3) (stegu/webgl-noise 22434e04d7). See the C# math.snoise_grad comment for the -// derivation. Every local up through p0..p3 and x0..x3 is cultmath_snoise(vec3)'s own derivation -// verbatim. -vec4 cultmath_snoise_grad(vec3 value) -{ - vec2 c = vec2(1.0 / 6.0, 1.0 / 3.0); - vec3 i = floor(value + dot(value, c.yyy)); - vec3 x0 = value - i + dot(i, c.xxx); - vec3 g = vec3(step(x0.y, x0.x), step(x0.z, x0.y), 1.0 - step(x0.z, x0.x)); - vec3 l = 1.0 - g; - vec3 i1 = min(g.xyz, l.zxy); - vec3 i2 = max(g.xyz, l.zxy); - vec3 x1 = x0 - i1 + c.xxx; - vec3 x2 = x0 - i2 + c.yyy; - vec3 x3 = x0 - 0.5; - - i = cultmath_snoise_mod289(i); - vec4 p = cultmath_snoise_permute(cultmath_snoise_permute(cultmath_snoise_permute( - i.z + vec4(0.0, i1.z, i2.z, 1.0)) + i.y + vec4(0.0, i1.y, i2.y, 1.0)) + i.x + vec4(0.0, i1.x, i2.x, 1.0)); - - const float n_ = 0.142857142857; - vec3 ns = vec3(2.0 * n_, 0.5 * n_ - 1.0, n_); - vec4 j = p - 49.0 * floor(p * ns.z * ns.z); - vec4 x_ = floor(j * ns.z); - vec4 y_ = floor(j - 7.0 * x_); - vec4 x = x_ * ns.x + ns.yyyy; - vec4 y = y_ * ns.x + ns.yyyy; - vec4 h = 1.0 - abs(x) - abs(y); - - vec4 b0 = vec4(x.xy, y.xy); - vec4 b1 = vec4(x.zw, y.zw); - vec4 s0 = floor(b0) * 2.0 + 1.0; - vec4 s1 = floor(b1) * 2.0 + 1.0; - vec4 sh = -step(h, vec4(0.0, 0.0, 0.0, 0.0)); - vec4 a0 = b0.xzyw + s0.xzyw * sh.xxyy; - vec4 a1 = b1.xzyw + s1.xzyw * sh.zzww; - - vec3 p0 = vec3(a0.xy, h.x); - vec3 p1 = vec3(a0.zw, h.y); - vec3 p2 = vec3(a1.xy, h.z); - vec3 p3 = vec3(a1.zw, h.w); - vec4 norm = 1.79284291400159 - 0.85373472095314 * vec4(dot(p0, p0), dot(p1, p1), dot(p2, p2), dot(p3, p3)); - p0 *= norm.x; - p1 *= norm.y; - p2 *= norm.z; - p3 *= norm.w; - - vec4 m0 = max(0.5 - vec4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0); - vec4 m2 = m0 * m0; - vec4 m3 = m2 * m0; - vec4 m4 = m2 * m2; - - vec4 px = vec4(dot(p0, x0), dot(p1, x1), dot(p2, x2), dot(p3, x3)); - float value2 = 105.0 * dot(m4, px); - vec3 grad = -8.0 * m3.x * x0 * px.x + m4.x * p0 - + -8.0 * m3.y * x1 * px.y + m4.y * p1 - + -8.0 * m3.z * x2 * px.z + m4.z * p2 - + -8.0 * m3.w * x3 * px.w + m4.w * p3; - grad *= 105.0; - - return vec4(grad, value2); -} - -// Analytic Hessian of cultmath_snoise(vec3); see the C# math.snoise_hessian comment for the -// derivation. Every local up through p0..p3 and x0..x3 is cultmath_snoise_grad's own. The matrix is -// built from nine scalars, which read as rows in HLSL and as columns in GLSL; it is symmetric, so the -// two agree. -mat3 cultmath_snoise_hessian(vec3 value) -{ - vec2 c = vec2(1.0 / 6.0, 1.0 / 3.0); - vec3 i = floor(value + dot(value, c.yyy)); - vec3 x0 = value - i + dot(i, c.xxx); - vec3 g = vec3(step(x0.y, x0.x), step(x0.z, x0.y), 1.0 - step(x0.z, x0.x)); - vec3 l = 1.0 - g; - vec3 i1 = min(g.xyz, l.zxy); - vec3 i2 = max(g.xyz, l.zxy); - vec3 x1 = x0 - i1 + c.xxx; - vec3 x2 = x0 - i2 + c.yyy; - vec3 x3 = x0 - 0.5; - - i = cultmath_snoise_mod289(i); - vec4 p = cultmath_snoise_permute(cultmath_snoise_permute(cultmath_snoise_permute( - i.z + vec4(0.0, i1.z, i2.z, 1.0)) + i.y + vec4(0.0, i1.y, i2.y, 1.0)) + i.x + vec4(0.0, i1.x, i2.x, 1.0)); - - const float n_ = 0.142857142857; - vec3 ns = vec3(2.0 * n_, 0.5 * n_ - 1.0, n_); - vec4 j = p - 49.0 * floor(p * ns.z * ns.z); - vec4 x_ = floor(j * ns.z); - vec4 y_ = floor(j - 7.0 * x_); - vec4 x = x_ * ns.x + ns.yyyy; - vec4 y = y_ * ns.x + ns.yyyy; - vec4 h = 1.0 - abs(x) - abs(y); - - vec4 b0 = vec4(x.xy, y.xy); - vec4 b1 = vec4(x.zw, y.zw); - vec4 s0 = floor(b0) * 2.0 + 1.0; - vec4 s1 = floor(b1) * 2.0 + 1.0; - vec4 sh = -step(h, vec4(0.0, 0.0, 0.0, 0.0)); - vec4 a0 = b0.xzyw + s0.xzyw * sh.xxyy; - vec4 a1 = b1.xzyw + s1.xzyw * sh.zzww; - - vec3 p0 = vec3(a0.xy, h.x); - vec3 p1 = vec3(a0.zw, h.y); - vec3 p2 = vec3(a1.xy, h.z); - vec3 p3 = vec3(a1.zw, h.w); - vec4 norm = 1.79284291400159 - 0.85373472095314 * vec4(dot(p0, p0), dot(p1, p1), dot(p2, p2), dot(p3, p3)); - p0 *= norm.x; - p1 *= norm.y; - p2 *= norm.z; - p3 *= norm.w; - - vec4 m0 = max(0.5 - vec4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0); - vec4 m2 = m0 * m0; - vec4 m3 = m2 * m0; - vec4 px = vec4(dot(p0, x0), dot(p1, x1), dot(p2, x2), dot(p3, x3)); - vec4 wide = 48.0 * m2 * px; - vec4 narrow = 8.0 * m3; - - vec4 cxx = vec4(x0.x, x1.x, x2.x, x3.x); - vec4 cxy = vec4(x0.y, x1.y, x2.y, x3.y); - vec4 cxz = vec4(x0.z, x1.z, x2.z, x3.z); - vec4 cpx = vec4(p0.x, p1.x, p2.x, p3.x); - vec4 cpy = vec4(p0.y, p1.y, p2.y, p3.y); - vec4 cpz = vec4(p0.z, p1.z, p2.z, p3.z); - - float hxx = 105.0 * (dot(wide * cxx, cxx) - dot(narrow, 2.0 * cpx * cxx + px)); - float hyy = 105.0 * (dot(wide * cxy, cxy) - dot(narrow, 2.0 * cpy * cxy + px)); - float hzz = 105.0 * (dot(wide * cxz, cxz) - dot(narrow, 2.0 * cpz * cxz + px)); - float hxy = 105.0 * (dot(wide * cxx, cxy) - dot(narrow, cpx * cxy + cpy * cxx)); - float hxz = 105.0 * (dot(wide * cxx, cxz) - dot(narrow, cpx * cxz + cpz * cxx)); - float hyz = 105.0 * (dot(wide * cxy, cxz) - dot(narrow, cpy * cxz + cpz * cxy)); - return mat3(hxx, hxy, hxz, hxy, hyy, hyz, hxz, hyz, hzz); -} - -// The integral over [t0, t1] of clamp(a + b t, lo, hi); see the C# math.integral_clamp_linear comment. -float cultmath_integral_clamp_linear(float a, float b, float lo, float hi, float t0, float t1) -{ - lo = min(lo, hi); - if (b == 0.0) - return t1 != t0 ? clamp(a, lo, hi) * (t1 - t0) : 0.0; - - float direction = t1 < t0 ? -1.0 : 1.0; - float start = min(t0, t1); - float stop = max(t0, t1); - float atLo = (lo - a) / b; - float atHi = (hi - a) / b; - float enter = clamp(min(atLo, atHi), start, stop); - float leave = clamp(max(atLo, atHi), start, stop); - float before = b > 0.0 ? lo : hi; - float after = b > 0.0 ? hi : lo; - float held = enter > start ? before * (enter - start) : 0.0; - float kept = stop > leave ? after * (stop - leave) : 0.0; - float total = held + (a + b * (0.5 * (enter + leave))) * (leave - enter) + kept; - return direction * total; -} - -// Octave sum of cultmath_snoise_grad (invariant 8); see the C# math.fbm_grad comment for the -// per-octave frequency/amplitude derivation and why octaves is clamped. -vec4 cultmath_fbm_grad(vec3 p, int octaves, float lacunarity, float gain) -{ - octaves = clamp(octaves, 0, 16); - float amplitude = 1.0; - float frequency = 1.0; - float value = 0.0; - vec3 gradient = vec3(0.0, 0.0, 0.0); - for (int i = 0; i < octaves; i++) - { - vec4 n = cultmath_snoise_grad(p * frequency); - value += amplitude * n.w; - gradient += amplitude * frequency * n.xyz; - frequency *= lacunarity; - amplitude *= gain; - } - - return vec4(gradient, value); -} - -// Ridged multifractal noise (Musgrave, Texturing and Modeling, ch. 16); see the C# math.ridged_grad -// comment for the fold/sign derivation, the deliberate crease at n = 0, and why octaves is clamped. -vec4 cultmath_ridged_grad(vec3 p, int octaves, float lacunarity, float gain) -{ - octaves = clamp(octaves, 0, 16); - float amplitude = 1.0; - float frequency = 1.0; - float value = 0.0; - vec3 gradient = vec3(0.0, 0.0, 0.0); - for (int i = 0; i < octaves; i++) - { - vec4 n = cultmath_snoise_grad(p * frequency); - float s = sign(n.w); - value += amplitude * (1.0 - abs(n.w)); - gradient += -amplitude * frequency * s * n.xyz; - frequency *= lacunarity; - amplitude *= gain; - } - - return vec4(gradient, value); -} - -float cultmath_lengthsq(vec2 value) { return dot(value, value); } -float cultmath_lengthsq(vec3 value) { return dot(value, value); } -float cultmath_lengthsq(vec4 value) { return dot(value, value); } - -float cultmath_distance(vec2 left, vec2 right) { return length(left - right); } -float cultmath_distance(vec3 left, vec3 right) { return length(left - right); } -float cultmath_distance(vec4 left, vec4 right) { return length(left - right); } - -vec2 cultmath_reflect(vec2 incident, vec2 normal_value) -{ - return incident - 2.0 * dot(normal_value, incident) * normal_value; -} - -vec3 cultmath_reflect(vec3 incident, vec3 normal_value) -{ - return incident - 2.0 * dot(normal_value, incident) * normal_value; -} - -vec2 cultmath_rotate(vec2 value, float radians_value) -{ - float s = sin(radians_value); - float c = cos(radians_value); - return vec2(value.x * c - value.y * s, value.x * s + value.y * c); -} - -vec2 cultmath_rotate_degrees(vec2 value, float degrees_value) -{ - return cultmath_rotate(value, cultmath_radians(degrees_value)); -} - -float cultmath_csum(vec2 value) { return value.x + value.y; } -float cultmath_csum(vec3 value) { return value.x + value.y + value.z; } -float cultmath_csum(vec4 value) { return value.x + value.y + value.z + value.w; } - -float cultmath_decay(float source, float lambda_value, float dt) { return source * exp(-lambda_value * dt); } -vec2 cultmath_decay(vec2 source, float lambda_value, float dt) { return source * exp(-lambda_value * dt); } -vec3 cultmath_decay(vec3 source, float lambda_value, float dt) { return source * exp(-lambda_value * dt); } -vec4 cultmath_decay(vec4 source, float lambda_value, float dt) { return source * exp(-lambda_value * dt); } - -float cultmath_damp(float start, float end, float lambda_value, float dt) -{ - return cultmath_lerp(start, end, 1.0 - exp(-lambda_value * dt)); -} - -vec2 cultmath_damp(vec2 start, vec2 end, float lambda_value, float dt) -{ - float amount = 1.0 - exp(-lambda_value * dt); - return cultmath_lerp(start, end, vec2(amount, amount)); -} - -vec3 cultmath_damp(vec3 start, vec3 end, float lambda_value, float dt) -{ - float amount = 1.0 - exp(-lambda_value * dt); - return cultmath_lerp(start, end, vec3(amount, amount, amount)); -} - -vec4 cultmath_damp(vec4 start, vec4 end, float lambda_value, float dt) -{ - float amount = 1.0 - exp(-lambda_value * dt); - return cultmath_lerp(start, end, vec4(amount, amount, amount, amount)); -} - -float cultmath_catmullrom(float p0, float p1, float p2, float p3, float t) -{ - float t2 = t * t; - float t3 = t2 * t; - return 0.5 * ((2.0 * p1) + (p2 - p0) * t + (2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * t2 + (-p0 + 3.0 * p1 - 3.0 * p2 + p3) * t3); -} - -vec2 cultmath_catmullrom(vec2 p0, vec2 p1, vec2 p2, vec2 p3, float t) -{ - float t2 = t * t; - float t3 = t2 * t; - return 0.5 * ((2.0 * p1) + (p2 - p0) * t + (2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * t2 + (-p0 + 3.0 * p1 - 3.0 * p2 + p3) * t3); -} - -vec3 cultmath_catmullrom(vec3 p0, vec3 p1, vec3 p2, vec3 p3, float t) -{ - float t2 = t * t; - float t3 = t2 * t; - return 0.5 * ((2.0 * p1) + (p2 - p0) * t + (2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * t2 + (-p0 + 3.0 * p1 - 3.0 * p2 + p3) * t3); -} - -vec4 cultmath_catmullrom(vec4 p0, vec4 p1, vec4 p2, vec4 p3, float t) -{ - float t2 = t * t; - float t3 = t2 * t; - return 0.5 * ((2.0 * p1) + (p2 - p0) * t + (2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * t2 + (-p0 + 3.0 * p1 - 3.0 * p2 + p3) * t3); -} - -float cultmath_quadratic_bezier(float p0, float p1, float p2, float t) -{ - t = cultmath_saturate(t); - float inv = 1.0 - t; - return inv * inv * p0 + 2.0 * inv * t * p1 + t * t * p2; -} - -vec3 cultmath_quadratic_bezier(vec3 p0, vec3 p1, vec3 p2, float t) -{ - t = cultmath_saturate(t); - float inv = 1.0 - t; - return inv * inv * p0 + 2.0 * inv * t * p1 + t * t * p2; -} - -float cultmath_cubic_bezier(float p0, float p1, float p2, float p3, float t) -{ - t = cultmath_saturate(t); - float inv = 1.0 - t; - return inv * inv * inv * p0 + 3.0 * inv * inv * t * p1 + 3.0 * inv * t * t * p2 + t * t * t * p3; -} - -vec3 cultmath_cubic_bezier(vec3 p0, vec3 p1, vec3 p2, vec3 p3, float t) -{ - t = cultmath_saturate(t); - float inv = 1.0 - t; - return inv * inv * inv * p0 + 3.0 * inv * inv * t * p1 + 3.0 * inv * t * t * p2 + t * t * t * p3; -} - -float cultmath_hash(float value) { return cultmath_frac(sin(value) * 43758.5453); } -float cultmath_hash(vec2 value) { return cultmath_hash(dot(value, vec2(127.1, 311.7))); } -float cultmath_hash(vec3 value) { return cultmath_hash(dot(value, vec3(127.1, 311.7, 74.7))); } - -// PCG hashes (Jarzynski and Olano, JCGT 2020), written over scalar uints so CultMath's ivec3/ivec4 carry the bits. -uint cultmath_pcg(uint value) -{ - uint state = value * 747796405u + 2891336453u; - uint word = ((state >> int((state >> 28) + 4u)) ^ state) * 277803737u; - return (word >> 22) ^ word; -} - -ivec3 cultmath_pcg3d(ivec3 value) -{ - uint x = uint(value.x) * 1664525u + 1013904223u, y = uint(value.y) * 1664525u + 1013904223u, z = uint(value.z) * 1664525u + 1013904223u; - x += y * z; y += z * x; z += x * y; - x ^= x >> 16; y ^= y >> 16; z ^= z >> 16; - x += y * z; y += z * x; z += x * y; - return ivec3(int(x), int(y), int(z)); -} - -ivec3 cultmath_pcg3d(vec3 value) { return cultmath_pcg3d(ivec3(int(floatBitsToUint(value.x)), int(floatBitsToUint(value.y)), int(floatBitsToUint(value.z)))); } -ivec3 cultmath_pcg3d(vec2 value) { return cultmath_pcg3d(vec3(value, 0.0)); } - -ivec4 cultmath_pcg4d(ivec4 value) -{ - uint x = uint(value.x) * 1664525u + 1013904223u, y = uint(value.y) * 1664525u + 1013904223u; - uint z = uint(value.z) * 1664525u + 1013904223u, w = uint(value.w) * 1664525u + 1013904223u; - x += y * w; y += z * x; z += x * y; w += y * z; - x ^= x >> 16; y ^= y >> 16; z ^= z >> 16; w ^= w >> 16; - x += y * w; y += z * x; z += x * y; w += y * z; - return ivec4(int(x), int(y), int(z), int(w)); -} - -ivec4 cultmath_pcg4d(vec4 value) { return cultmath_pcg4d(ivec4(int(floatBitsToUint(value.x)), int(floatBitsToUint(value.y)), int(floatBitsToUint(value.z)), int(floatBitsToUint(value.w)))); } - -// Inigo Quilez, "smooth minimum": quadratic-polynomial smin carried to value-and-gradient form. See -// math.smin_grad's comment (math.cs) for why the gradient blend is exact, not an approximation. -vec4 cultmath_smin_grad(vec4 a, vec4 b, float k) -{ - float h = clamp(0.5 + 0.5 * (b.w - a.w) / k, 0.0, 1.0); - float value = mix(b.w, a.w, h) - k * h * (1.0 - h); - vec3 gradient = mix(b.xyz, a.xyz, h); - return vec4(gradient, value); -} - -// Invariant 8's one struct return shape (design.md, "HLSL Target: Source Transformations"): -// compared field by field and bit for bit against CultMath.CultCellular, same field order. -struct CultCellular -{ - vec4 nearest; - vec4 edge; - float id; -}; - -// Worley, "A Cellular Texture Basis Function" (SIGGRAPH 1996). See math.cellular's comment -// (math.cs) for the hashing, gradient, search-radius exactness proof, id source and -// degenerate-point conventions this mirrors exactly, including the 5x5x5 lower-bound prune. -CultCellular cultmath_cellular(vec3 p) -{ - vec3 cell = floor(p); - float f1 = 1.0e30; - float f2 = 1.0e30; - vec3 c1 = vec3(0.0, 0.0, 0.0); - vec3 c2 = vec3(0.0, 0.0, 0.0); - vec3 cellId = vec3(0.0, 0.0, 0.0); - - for (int dz = -2; dz <= 2; dz++) - { - float lz = max(0.0, abs(float(dz)) - 1.0); - for (int dy = -2; dy <= 2; dy++) - { - float ly = max(0.0, abs(float(dy)) - 1.0); - for (int dx = -2; dx <= 2; dx++) - { - float lx = max(0.0, abs(float(dx)) - 1.0); - float lowerBound = sqrt(lx * lx + ly * ly + lz * lz); - if (lowerBound >= f2) - continue; - - vec3 neighbor = cell + vec3(dx, dy, dz); - ivec3 hash = cultmath_pcg3d(ivec3(neighbor)); - vec3 jitter = vec3( - float(uint(hash.x) >> 8) * (1.0 / 16777216.0), - float(uint(hash.y) >> 8) * (1.0 / 16777216.0), - float(uint(hash.z) >> 8) * (1.0 / 16777216.0)); - vec3 feature = neighbor + jitter; - float d = cultmath_distance(p, feature); - - if (d < f1) - { - f2 = f1; c2 = c1; - f1 = d; c1 = feature; cellId = neighbor; - } - else if (d < f2) - { - f2 = d; c2 = feature; - } - } - } - } - - // F1 = 0 and F2 = 0 share the same degenerate-gradient guard; see math.cellular's comment - // (math.cs) for why F2 = 0 is reachable past roughly |p| = 2^23. - vec3 grad1 = f1 > 0.0 ? (p - c1) / f1 : vec3(0.0, 0.0, 0.0); - vec3 grad2 = f2 > 0.0 ? (p - c2) / f2 : vec3(0.0, 0.0, 0.0); - - // id comes from pcg4d over the winning cell's integer coordinate alone (same int-hashing rule - // as the jitter above), never from the pcg3d hash that produced its jitter (F4). - ivec4 idHash = cultmath_pcg4d(ivec4(ivec3(cellId), 0)); - - CultCellular result; - result.nearest = vec4(grad1, f1); - result.edge = vec4(grad2 - grad1, f2 - f1); - result.id = float(uint(idHash.w) >> 8) * (1.0 / 16777216.0); - return result; -} - - - - -// Interval arithmetic over vec2(lo, hi), lo <= hi, both finite. Every cultmath_iv_* function returns -// an interval containing f(x) for every x in its input intervals, mirroring math.Interval.cs bit for -// bit; see that file and docs/design.md ("Intervals") for each op's enclosure and its ulp widening. -// Included by CultMath.hlsl after its own definitions of cultmath_smoothstep and cultmath_snoise. - -// Lipschitz constant of cultmath_snoise(vec3); provenance in math.Interval.cs (SNOISE_LIPSCHITZ). -const float CULTMATH_SNOISE_LIPSCHITZ = 7.9640074; - -// Lipschitz constant of cultmath_snoise(vec2); provenance in math.Interval.cs (SNOISE2_LIPSCHITZ). -const float CULTMATH_SNOISE2_LIPSCHITZ = 8.117002; - -vec2 cultmath_iv_point(float value) { return vec2(value, value); } -vec2 cultmath_iv_add(vec2 a, vec2 b) { return vec2(a.x + b.x, a.y + b.y); } -vec2 cultmath_iv_sub(vec2 a, vec2 b) { return vec2(a.x - b.y, a.y - b.x); } -vec2 cultmath_iv_neg(vec2 a) { return vec2(-a.y, -a.x); } - -vec2 cultmath_iv_mul(vec2 a, vec2 b) -{ - float p0 = a.x * b.x; - float p1 = a.x * b.y; - float p2 = a.y * b.x; - float p3 = a.y * b.y; - return vec2(min(min(p0, p1), min(p2, p3)), max(max(p0, p1), max(p2, p3))); -} - -vec2 cultmath_iv_scale(vec2 a, float s) { return s >= 0.0 ? vec2(a.x * s, a.y * s) : vec2(a.y * s, a.x * s); } - -vec2 cultmath_iv_abs(vec2 a) -{ - if (a.x >= 0.0) - return a; - if (a.y <= 0.0) - return vec2(-a.y, -a.x); - return vec2(0.0, max(-a.x, a.y)); -} - -vec2 cultmath_iv_min(vec2 a, vec2 b) { return vec2(min(a.x, b.x), min(a.y, b.y)); } -vec2 cultmath_iv_max(vec2 a, vec2 b) { return vec2(max(a.x, b.x), max(a.y, b.y)); } - -vec2 cultmath_iv_sqr(vec2 a) -{ - float l = a.x * a.x; - float h = a.y * a.y; - if (a.x >= 0.0) - return vec2(l, h); - if (a.y <= 0.0) - return vec2(h, l); - return vec2(0.0, max(l, h)); -} - -vec2 cultmath_iv_sqrt(vec2 a) { return vec2(sqrt(max(a.x, 0.0)), sqrt(max(a.y, 0.0))); } - -// Widened by one ulp on each side: exp is not required to be correctly rounded. -vec2 cultmath_iv_exp(vec2 a) -{ - float lo = exp(a.x); - float hi = exp(a.y); - return vec2(lo > 0.0 ? uintBitsToFloat(floatBitsToUint(lo) - 1u) : 0.0, uintBitsToFloat(floatBitsToUint(hi) + 1u)); -} - -vec2 cultmath_iv_clamp(vec2 a, float minimum, float maximum) -{ - return vec2(cultmath_clamp(a.x, minimum, maximum), cultmath_clamp(a.y, minimum, maximum)); -} - -vec2 cultmath_iv_saturate(vec2 a) { return vec2(cultmath_saturate(a.x), cultmath_saturate(a.y)); } - -// The endpoints, ordered, widened by one ulp inside [0, 1]: the float32 evaluation of smoothstep is -// monotone only to within one ulp. -vec2 cultmath_iv_smoothstep(float minimum, float maximum, vec2 a) -{ - float s0 = cultmath_smoothstep(minimum, maximum, a.x); - float s1 = cultmath_smoothstep(minimum, maximum, a.y); - float lo = min(s0, s1); - float hi = max(s0, s1); - return vec2(lo > 0.0 ? uintBitsToFloat(floatBitsToUint(lo) - 1u) : 0.0, hi < 1.0 ? uintBitsToFloat(floatBitsToUint(hi) + 1u) : 1.0); -} - -// The natural interval extension of x + (y - x) * amount, which is how cultmath_lerp evaluates. -vec2 cultmath_iv_lerp(vec2 a, vec2 b, float amount) { return cultmath_iv_add(a, cultmath_iv_scale(cultmath_iv_sub(b, a), amount)); } - -// [n - L r, n + L r] intersected with [-1, 1], n = cultmath_snoise(centre). One snoise, value only. -vec2 cultmath_iv_snoise_ball(vec3 centre, float radius) -{ - float n = cultmath_snoise(centre); - float e = CULTMATH_SNOISE_LIPSCHITZ * radius; - return vec2(max(n - e, -1.0), min(n + e, 1.0)); -} - -// The 2D overload: [n - L2 r, n + L2 r] intersected with [-1, 1], n = cultmath_snoise(centre). One snoise, value only. -vec2 cultmath_iv_snoise_ball(vec2 centre, float radius) -{ - float n = cultmath_snoise(centre); - float e = CULTMATH_SNOISE2_LIPSCHITZ * radius; - return vec2(max(n - e, -1.0), min(n + e, 1.0)); -} - -// Octave sum of cultmath_iv_snoise_ball, compounding frequency and amplitude as the value-and-gradient fBm does. -vec2 cultmath_iv_fbm_ball(vec3 centre, float radius, int octaves, float lacunarity, float gain) -{ - octaves = clamp(octaves, 0, 16); - float amplitude = 1.0; - float frequency = 1.0; - vec2 sum = vec2(0.0, 0.0); - for (int i = 0; i < octaves; i++) - { - sum = cultmath_iv_add(sum, cultmath_iv_scale(cultmath_iv_snoise_ball(centre * frequency, radius * abs(frequency)), amplitude)); - frequency *= lacunarity; - amplitude *= gain; - } - - return sum; -} - -// A ball (xyz centre, w radius) enclosing every point of every ray of a screen tile over the depth segment -// [z0, z1], warped by at most warp. Camera frame: pinhole at the origin looking down +z, ray (m z, z). -// footprintPerDepth = N / (sqrt(2) f) for an N x N tile at focal length f. The radius is widened by -// (|c|_1 + radius) 2^-20, which covers the ball's own float32 rounding. Derivation in math.Interval.cs. -vec4 cultmath_iv_frustum_ball(vec2 centreSlope, float z0, float z1, float footprintPerDepth, float warp) -{ - float zm = (z0 + z1) * 0.5; - float axis = sqrt(centreSlope.x * centreSlope.x + centreSlope.y * centreSlope.y + 1.0); - float cx = centreSlope.x * zm; - float cy = centreSlope.y * zm; - float radius = (z1 - z0) * 0.5 * axis + z1 * footprintPerDepth + warp; - radius += (abs(cx) + abs(cy) + abs(zm) + radius) * 9.5367431640625e-7; - return vec4(cx, cy, zm, radius); -} - - - - - - -// Reduced affine forms with one shared symbol over vec3(x0, a, e): the set { x0 + a eps + e delta : -// delta in [-1, 1] } at the region's shared eps in [-1, 1], e >= 0. Every cultmath_af_* function mirrors -// math.Affine.cs bit for bit; see that file and docs/design.md ("Affine forms") for each op's enclosure -// and the float32 rounding allowance it folds into e. Included by CultMath.hlsl after -// CultMath.Interval.hlsl, whose CULTMATH_SNOISE_LIPSCHITZ it shares, and after its own -// definition of cultmath_snoise_grad. - -// An upper bound on the spectral norm of the Hessian of cultmath_snoise(vec3); provenance in -// math.Affine.cs (SNOISE_HESSIAN). -const float CULTMATH_SNOISE_HESSIAN = 55.642143; - -// The absolute rounding of one float32 read of cultmath_snoise_grad, value and gradient; the owner is -// math.Affine.cs (SNOISE_READ_VALUE, SNOISE_READ_GRADIENT), read here by cultmath_af_snoise and in -// CultMath.hlsl by cultmath_span_slack. -const float CULTMATH_SNOISE_READ_VALUE = 6.103515625e-5; -const float CULTMATH_SNOISE_READ_GRADIENT = 2.44140625e-4; - -// An upper bound on the operator norm of the third-derivative tensor of cultmath_snoise(vec3), the -// next order after CULTMATH_SNOISE_HESSIAN; provenance in math.Span.cs (SNOISE_THIRD). -const float CULTMATH_SNOISE_THIRD = 535.8009; - -vec3 cultmath_af_point(float value) { return vec3(value, 0.0, 0.0); } -vec3 cultmath_af_symbol(float x0, float a) { return vec3(x0, a, 0.0); } - -vec3 cultmath_af_from_iv(vec2 interval) -{ - float x0 = interval.x * 0.5 + interval.y * 0.5; - float e = interval.y * 0.5 - interval.x * 0.5; - return vec3(x0, 0.0, e + (abs(x0) + e) * 9.5367431640625e-7 + 1.17549435e-38); -} - -// An endpoint that would be NaN is the infinity on its side. NaN is found by its bit pattern: dxc marks -// compares fast, so a test that needs NaN to make `lo == lo` false is deleted under its default flags. -vec2 cultmath_af_range(vec3 x) -{ - float r = abs(x.y) + x.z; - float w = abs(x.x) * 9.5367431640625e-7 + r * 9.5367431640625e-7; - float lo = x.x - r - w; - float hi = x.x + r + w; - return vec2((floatBitsToUint(lo) & 0x7fffffffu) > 0x7f800000u ? uintBitsToFloat(0xff800000u) : lo, - (floatBitsToUint(hi) & 0x7fffffffu) > 0x7f800000u ? uintBitsToFloat(0x7f800000u) : hi); -} - -vec3 cultmath_af_add(vec3 x, vec3 y) -{ - float x0 = x.x + y.x; - float a = x.y + y.y; - float e = x.z + y.z; - return vec3(x0, a, e + (abs(x0) + abs(a) + e) * 9.5367431640625e-7); -} - -vec3 cultmath_af_sub(vec3 x, vec3 y) -{ - float x0 = x.x - y.x; - float a = x.y - y.y; - float e = x.z + y.z; - return vec3(x0, a, e + (abs(x0) + abs(a) + e) * 9.5367431640625e-7); -} - -vec3 cultmath_af_neg(vec3 x) { return vec3(-x.x, -x.y, x.z); } - -vec3 cultmath_af_scale(vec3 x, float s) -{ - float x0 = x.x * s; - float a = x.y * s; - float e = x.z * abs(s); - return vec3(x0, a, e + (abs(x0) + abs(a) + e) * 9.5367431640625e-7 + 1.17549435e-38); -} - -vec3 cultmath_af_add_iv(vec3 x, vec2 interval) { return cultmath_af_add(x, cultmath_af_from_iv(interval)); } - -vec3 cultmath_af_mul(vec3 x, vec3 y) -{ - float x0 = x.x * y.x; - float p = x.x * y.y; - float q = y.x * x.y; - float a = p + q; - float e = abs(x.x) * y.z + abs(y.x) * x.z + (abs(x.y) + x.z) * (abs(y.y) + y.z); - return vec3(x0, a, e + (abs(x0) + abs(p) + abs(q) + e) * 9.5367431640625e-7 + 1.17549435e-38); -} - -// The narrower of the Lipschitz form and the centred (Taylor) form over every p = centre + axis eps + w, -// |w| <= radius, from one cultmath_snoise_grad at the centre; the allowance for the float32 evaluation is -// in math.Affine.cs. -vec3 cultmath_af_snoise(vec3 centre, vec3 axis, float radius) -{ - vec4 g = cultmath_snoise_grad(centre); - vec3 gradient = vec3(g.x, g.y, g.z); - float reach = length(axis) + radius; - float lipschitz = CULTMATH_SNOISE_LIPSCHITZ * reach; - float a = dot(gradient, axis); - float remainder = length(gradient) * radius + 0.5 * CULTMATH_SNOISE_HESSIAN * reach * reach; - float allowance = CULTMATH_SNOISE_READ_VALUE + CULTMATH_SNOISE_READ_GRADIENT * reach - + CULTMATH_SNOISE_LIPSCHITZ * 9.5367431640625e-7 * (abs(centre.x) + abs(centre.y) + abs(centre.z) + reach); - bool centred = abs(a) + remainder < lipschitz; - float slope = centred ? a : 0.0; - float e = (centred ? remainder : lipschitz) + allowance; - return vec3(g.w, slope, e + (abs(g.w) + abs(slope) + e) * 9.5367431640625e-7); -} - -// Octave sum of cultmath_af_snoise, compounding frequency and amplitude as the value-and-gradient fBm does. -vec3 cultmath_af_fbm(vec3 centre, vec3 axis, float radius, int octaves, float lacunarity, float gain) -{ - octaves = clamp(octaves, 0, 16); - float amplitude = 1.0; - float frequency = 1.0; - vec3 sum = vec3(0.0, 0.0, 0.0); - for (int i = 0; i < octaves; i++) - { - sum = cultmath_af_add(sum, cultmath_af_scale(cultmath_af_snoise(centre * frequency, axis * frequency, radius * abs(frequency)), amplitude)); - frequency *= lacunarity; - amplitude *= gain; - } - - return sum; -} - -// The axis of a screen tile's slice over the depth segment [z0, z1]; camera frame of -// cultmath_iv_frustum_ball. -vec3 cultmath_af_frustum_axis(vec2 centreSlope, float z0, float z1) -{ - float h = (z1 - z0) * 0.5; - return vec3(centreSlope.x * h, centreSlope.y * h, h); -} - -// The affine slice of a screen tile over [z0, z1]: centre xyz, radius w. Derivation in math.Affine.cs. -vec4 cultmath_af_frustum_ball(vec2 centreSlope, float z0, float z1, float footprintPerDepth, float warpVariation) -{ - float zm = (z0 + z1) * 0.5; - float h = (z1 - z0) * 0.5; - float cx = centreSlope.x * zm; - float cy = centreSlope.y * zm; - float spread = (abs(centreSlope.x) + abs(centreSlope.y) + 1.0) * h; - float radius = z1 * footprintPerDepth + warpVariation; - radius += (abs(cx) + abs(cy) + abs(zm) + spread + radius) * 9.5367431640625e-7; - return vec4(cx, cy, zm, radius); -} - - - - -// Span stages (invariant 8): the SpanPath, SpanStage and SpanNoise of math.Span.cs, field for field in -// C#'s order, and cultmath_span_stage, its octave stage, statement for statement so the text is a bit-for-bit -// mirror. They follow the includes because the bounds read CULTMATH_SNOISE_LIPSCHITZ, _HESSIAN and _THIRD. -// A shader caller builds a SpanStage itself (SpanStage(1.0, 1.0, vec3(0.0), vec3(0.0), vec3(0.0), vec3(0.0)) -// is the identity of math.SpanStage.Identity, which has no shader form); see math.span_stage's comments for -// the span, the transform, the bounds and the allowances. cultmath_span_rounding and cultmath_span_slack -// are math.span_rounding and math.span_slack, the owners of S_o and of the three allowances. -struct SpanPath -{ - vec3 midpoint; - vec3 velocity; - float speed; - float acceleration; - float halfLength; -}; - -struct SpanStage -{ - float frequency; - float stretch; - vec3 axis; - vec3 shift; - vec3 offset; - vec3 octaveStep; -}; - -struct SpanNoise -{ - vec4 field; - float curvature; - float fold; -}; - -float cultmath_span_rounding(float scale, vec3 mq, SpanStage stage, vec3 octaveShift, float nu, float halfLength) -{ - return 9.5367431640625e-7 * (abs(scale) * (cultmath_csum(abs(mq)) + cultmath_csum(abs(stage.shift))) + cultmath_csum(abs(stage.offset)) + cultmath_csum(abs(octaveShift)) + 1.7320508 * nu * halfLength); -} - -vec3 cultmath_span_slack(float rounding) -{ - return vec3(CULTMATH_SNOISE_READ_VALUE + CULTMATH_SNOISE_LIPSCHITZ * rounding, - CULTMATH_SNOISE_READ_GRADIENT + CULTMATH_SNOISE_HESSIAN * rounding, - 9.765625e-4 + CULTMATH_SNOISE_THIRD * rounding); -} - -// The octave stage behind cultmath_span_fbm and cultmath_span_ridged, as math.span_stage is behind span_fbm -// and span_ridged. The Frobenius norm of the Hessian is written out in C#'s order (GLSL has no _mRC member -// access); the C# local named step is octaveShift here (it would shadow GLSL's step()). -SpanNoise cultmath_span_stage(bool ridged, SpanPath path, SpanStage stage, int octaves, float lacunarity, float gain) -{ - vec3 q = path.midpoint; - float halfLength = path.halfLength; - octaves = clamp(octaves, 0, 16); - bool stretched = dot(stage.axis, stage.axis) > 0.0 && stage.stretch != 1.0; - vec3 direction = stretched ? normalize(stage.axis) : vec3(0.0, 0.0, 0.0); - float squeeze = stretched ? 1.0 / stage.stretch - 1.0 : 0.0; - float norm = abs(stage.frequency) * (stretched ? max(1.0, 1.0 / stage.stretch) : 1.0); - vec3 mq = stretched ? stage.frequency * (q + squeeze * dot(direction, q) * direction) : stage.frequency * q; - vec3 mv = stretched ? stage.frequency * (path.velocity + squeeze * dot(direction, path.velocity) * direction) : stage.frequency * path.velocity; - float amplitude = 1.0; - float scale = 1.0; - float value = 0.0; - vec3 gradient = vec3(0.0, 0.0, 0.0); - float curvature = 0.0; - float fold = 0.0; - for (int i = 0; i < octaves; i++) - { - vec3 octaveShift = float(i) * stage.octaveStep; - vec3 x = scale * (mq + stage.shift) + (stage.offset + octaveShift); - vec4 n = cultmath_snoise_grad(x); - vec3 g = vec3(n.x, n.y, n.z); - vec3 mg = stretched ? stage.frequency * (g + squeeze * dot(direction, g) * direction) : stage.frequency * g; - if (ridged) - { - float s = sign(n.w); - value += amplitude * (1.0 - abs(n.w)); - gradient += -amplitude * scale * s * mg; - } - else - { - value += amplitude * n.w; - gradient += amplitude * scale * mg; - } - - float weight = abs(amplitude); - float factor = abs(scale) * norm; - float nu = factor * path.speed; - float rounding = cultmath_span_rounding(scale, mq, stage, octaveShift, nu, halfLength); - vec3 slack = cultmath_span_slack(rounding); - float valueSlack = slack.x; - float gradientSlack = slack.y; - float hessianSlack = slack.z; - mat3 hm = cultmath_snoise_hessian(x); - float frobenius = sqrt(hm[0][0] * hm[0][0] + hm[0][1] * hm[0][1] + hm[0][2] * hm[0][2] + hm[1][0] * hm[1][0] + hm[1][1] * hm[1][1] + hm[1][2] * hm[1][2] - + hm[2][0] * hm[2][0] + hm[2][1] * hm[2][1] + hm[2][2] * hm[2][2]); - float hessianBound = min(CULTMATH_SNOISE_HESSIAN, frobenius + hessianSlack + CULTMATH_SNOISE_THIRD * nu * halfLength); - curvature += weight * factor * factor * hessianBound; - if (ridged) - { - vec3 w = scale * mv; - float reach = hessianBound * nu * halfLength; - float gl = min(CULTMATH_SNOISE_LIPSCHITZ, length(g) + gradientSlack + reach); - float travel = (abs(dot(g, w)) + gradientSlack * length(w)) * halfLength + (hessianBound * nu * length(w) + gl * factor * path.acceleration) * (0.5 * halfLength * halfLength) + 2.0 * valueSlack; - fold += 2.0 * weight * max(travel - abs(n.w), 0.0); - } - - scale *= lacunarity; - amplitude *= gain; - } - - SpanNoise result; - result.field = vec4(gradient, value); - result.curvature = curvature; - result.fold = fold; - return result; -} - -SpanNoise cultmath_span_fbm(SpanPath path, SpanStage stage, int octaves, float lacunarity, float gain) -{ - return cultmath_span_stage(false, path, stage, octaves, lacunarity, gain); -} - -SpanNoise cultmath_span_ridged(SpanPath path, SpanStage stage, int octaves, float lacunarity, float gain) -{ - return cultmath_span_stage(true, path, stage, octaves, lacunarity, gain); -} - -float cultmath_value_noise(vec2 position) -{ - vec2 cell = floor(position); - vec2 local = cultmath_frac(position); - vec2 u = local * local * (vec2(3.0, 3.0) - vec2(2.0, 2.0) * local); - - float a = cultmath_hash(cell); - float b = cultmath_hash(cell + vec2(1.0, 0.0)); - float c = cultmath_hash(cell + vec2(0.0, 1.0)); - float d = cultmath_hash(cell + vec2(1.0, 1.0)); - - return cultmath_lerp(cultmath_lerp(a, b, u.x), cultmath_lerp(c, d, u.x), u.y); -} - -float cultmath_value_noise_bicubic(vec2 position) -{ - vec2 cell = floor(position); - vec2 local = cultmath_frac(position); - - float y0 = cultmath_catmullrom(cultmath_hash(cell + vec2(-1.0, -1.0)), cultmath_hash(cell + vec2(0.0, -1.0)), cultmath_hash(cell + vec2(1.0, -1.0)), cultmath_hash(cell + vec2(2.0, -1.0)), local.x); - float y1 = cultmath_catmullrom(cultmath_hash(cell + vec2(-1.0, 0.0)), cultmath_hash(cell + vec2(0.0, 0.0)), cultmath_hash(cell + vec2(1.0, 0.0)), cultmath_hash(cell + vec2(2.0, 0.0)), local.x); - float y2 = cultmath_catmullrom(cultmath_hash(cell + vec2(-1.0, 1.0)), cultmath_hash(cell + vec2(0.0, 1.0)), cultmath_hash(cell + vec2(1.0, 1.0)), cultmath_hash(cell + vec2(2.0, 1.0)), local.x); - float y3 = cultmath_catmullrom(cultmath_hash(cell + vec2(-1.0, 2.0)), cultmath_hash(cell + vec2(0.0, 2.0)), cultmath_hash(cell + vec2(1.0, 2.0)), cultmath_hash(cell + vec2(2.0, 2.0)), local.x); - - return cultmath_catmullrom(y0, y1, y2, y3, local.y); -} - -#endif diff --git a/src/app/features/scene/shaders/README.md b/src/app/features/scene/shaders/README.md deleted file mode 100644 index b970f82b..00000000 --- a/src/app/features/scene/shaders/README.md +++ /dev/null @@ -1,19 +0,0 @@ -# Vendored CultMath GLSL - -`CultMath.glsl` and `CultMath.Phacelle.glsl` are CultLib's generated WebGL2 -lowering of `packages/cultmath/shaders/CultMath.hlsl` and -`CultMath.Phacelle.hlsl`, copied unedited from CultLib branch -`eureka/cultmath-tapes-interval-ops-r5` at `658c09e` (the branch that carries -the interval ops and `CULTMATH_SNOISE2_LIPSCHITZ`; the repo default branch -does not carry the GLSL yet). Never edit them here: regenerate in CultLib and -re-copy. `CultMath.glsl` is MIT; `CultMath.Phacelle.glsl` is MPL-2.0 (Rune -Skovbo Johansen's Phacelle noise, see its header), so that file keeps its -header and any change to it is published under MPL-2.0. - -The other `*.glsl` files here are the scene's own stages. They are -concatenated by `../shaderSource.ts` after a prelude; they use no colour -literal (the palette is uniforms) and define no noise. - -`../shaderSource.ts` compiles each stage with only the part of `CultMath.glsl` that stage reaches -(`../cultmathTrim.ts`); the vendored file itself stays whole. Phacelle is added to the terrain stage -alone. diff --git a/src/app/features/scene/shaders/atmosphere.frag.glsl b/src/app/features/scene/shaders/atmosphere.frag.glsl deleted file mode 100644 index adbf1b5b..00000000 --- a/src/app/features/scene/shaders/atmosphere.frag.glsl +++ /dev/null @@ -1,90 +0,0 @@ -// Pass 2: atmosphere, marched only up to pass 1's depth. Height fog is closed-form; the cloud -// slab is marched with a few jittered steps. Output: rgb in-scattered light, a transmittance. -uniform sampler2D u_depth; // pass 1 hit distance, nearest -uniform int u_steps; // cloud march steps -uniform float u_frame; -uniform vec2 u_jitter; // sub-pixel jitter in pixels of this target -uniform vec2 u_size; // this target's size in pixels -uniform float u_coverage; // weather knob: 0 clear .. 1 overcast - -in vec2 v_uv; -layout(location = 0) out vec4 o_atm; - -float hg(float cosTheta, float g) -{ - float g2 = g * g; - return (1.0 - g2) / (12.566370614 * pow(1.0 + g2 - 2.0 * g * cosTheta, 1.5)); -} - -float cloudDensity(vec3 p) -{ - float wind = u_time * 2.5; - float f = cultmath_fbm_grad(vec3(p.x * 0.0042 + wind * 0.0042, p.y * 0.0075, p.z * 0.0042), 3, 2.0, 0.5).w; - float h = (p.y - W_CLOUD_Y0) / (W_CLOUD_Y1 - W_CLOUD_Y0); - float profile = smoothstep(0.0, 0.2, h) * smoothstep(1.0, 0.55, h); - return clamp((f + 0.55 * u_coverage - 0.25) * 2.4, 0.0, 1.0) * profile; -} - -void main() -{ - vec2 jittered = (gl_FragCoord.xy + u_jitter) / u_size; - vec3 rd = camRay(jittered); - vec3 ro = u_camPos; - float depth = texture(u_depth, v_uv).r; - float tEnd = min(depth, W_ATM_FAR); - - // Exponential height fog, closed form: optical depth of density d0 * exp(-k y) along the ray. - float k = W_FOG_FALLOFF; - float dy = rd.y * tEnd; - float tau = W_FOG_DENSITY * exp(-k * ro.y) * (abs(dy) > 1e-3 ? (1.0 - exp(-k * dy)) / (k * rd.y) : tEnd); - float fogT = exp(-max(tau, 0.0)); - float cosSun = dot(rd, u_sunDir); - vec3 fogLight = u_fogColor + u_sunColor * hg(cosSun, 0.55) * 0.9; - vec3 inscatter = fogLight * (1.0 - fogT); - float trans = fogT; - - // Clouds: only the part of the ray inside the slab and in front of the surface. - float ta = 0.0; - float tb = tEnd; - if (abs(rd.y) > 1e-4) - { - float t0 = (W_CLOUD_Y0 - ro.y) / rd.y; - float t1 = (W_CLOUD_Y1 - ro.y) / rd.y; - ta = max(0.0, min(t0, t1)); - tb = min(tEnd, max(t0, t1)); - } - else if (ro.y < W_CLOUD_Y0 || ro.y > W_CLOUD_Y1) - tb = 0.0; - - if (tb > ta && u_steps > 0) - { - float dt = (tb - ta) / float(u_steps); - float t = ta + dt * ign(gl_FragCoord.xy, u_frame); - float T = 1.0; - vec3 L = vec3(0.0); - float phase = hg(cosSun, 0.6) + 0.35 * hg(cosSun, -0.2); - for (int i = 0; i < u_steps; i++) - { - vec3 p = ro + rd * t; - float d = cloudDensity(p); - if (d > 0.01) - { - // One sample toward the sun stands in for self-shadowing. - float shade = exp(-cloudDensity(p + u_sunDir * 38.0) * 2.2); - vec3 light = u_sunColor * (phase * 6.0) * shade + mix(u_skyHorizon, u_skyTop, 0.6) * 0.35; - float ext = d * dt * 0.035; - float stepT = exp(-ext); - L += T * (1.0 - stepT) * light; - T *= stepT; - if (T < 0.03) - break; - } - t += dt; - } - // Fog in front of the slab is already in `inscatter`; clouds sit behind it. - inscatter += trans * L; - trans *= T; - } - - o_atm = vec4(inscatter, trans); -} diff --git a/src/app/features/scene/shaders/common.glsl b/src/app/features/scene/shaders/common.glsl deleted file mode 100644 index 6378a2e6..00000000 --- a/src/app/features/scene/shaders/common.glsl +++ /dev/null @@ -1,31 +0,0 @@ -// Shared by every fragment stage; concatenated after the prelude, CultMath and the world defines. -uniform vec3 u_camPos; -uniform mat3 u_camBasis; // columns: right, up, forward -uniform vec2 u_tanHalf; // x: tan(fov/2) * aspect, y: tan(fov/2) -uniform float u_time; -uniform vec3 u_sunDir; // unit, towards the sun -uniform vec3 u_sunColor; -uniform vec3 u_skyTop; -uniform vec3 u_skyHorizon; -uniform vec3 u_fogColor; - -vec3 camRay(vec2 uv) -{ - vec2 ndc = uv * 2.0 - 1.0; - return normalize(u_camBasis * vec3(ndc * u_tanHalf, 1.0)); -} - -float ign(vec2 p, float frame) -{ - p += 5.588238 * mod(frame, 64.0); - return fract(52.9829189 * fract(dot(p, vec2(0.06711056, 0.00583715)))); -} - -vec3 skyColor(vec3 rd) -{ - float h = clamp(rd.y, 0.0, 1.0); - vec3 c = mix(u_skyHorizon, u_skyTop, pow(h, 0.45)); - float s = max(dot(rd, u_sunDir), 0.0); - c += u_sunColor * (1.5 * pow(s, 256.0)); - return c; -} diff --git a/src/app/features/scene/shaders/composite.frag.glsl b/src/app/features/scene/shaders/composite.frag.glsl deleted file mode 100644 index 9dce31f1..00000000 --- a/src/app/features/scene/shaders/composite.frag.glsl +++ /dev/null @@ -1,26 +0,0 @@ -// Full-resolution composite to the canvas: solid over sky, then the accumulated atmosphere. -uniform sampler2D u_solid; // rgb lit, a coverage (bilinear) -uniform sampler2D u_atm; // TAA'd atmosphere (bilinear) -uniform float u_frame; - -in vec2 v_uv; -out vec4 o_frag; - -vec3 tonemap(vec3 x) -{ - // Narkowicz ACES fit. - return clamp((x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14), 0.0, 1.0); -} - -void main() -{ - vec3 rd = camRay(v_uv); - vec4 solid = texture(u_solid, v_uv); - vec4 atm = texture(u_atm, v_uv); - vec3 base = mix(skyColor(rd), solid.rgb, solid.a); - vec3 col = base * atm.a + atm.rgb; - col = tonemap(col); - col = pow(col, vec3(1.0 / 2.2)); - col += (ign(gl_FragCoord.xy, u_frame) - 0.5) / 255.0; - o_frag = vec4(col, 1.0); -} diff --git a/src/app/features/scene/shaders/fullscreen.vert.glsl b/src/app/features/scene/shaders/fullscreen.vert.glsl deleted file mode 100644 index cab0e527..00000000 --- a/src/app/features/scene/shaders/fullscreen.vert.glsl +++ /dev/null @@ -1,8 +0,0 @@ -out vec2 v_uv; -void main() -{ - // One oversized triangle; uv spans 0..1 over the visible part. - vec2 p = vec2(float((gl_VertexID << 1) & 2), float(gl_VertexID & 2)); - v_uv = p; - gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0); -} diff --git a/src/app/features/scene/shaders/prepass.frag.glsl b/src/app/features/scene/shaders/prepass.frag.glsl deleted file mode 100644 index 4ca21a2c..00000000 --- a/src/app/features/scene/shaders/prepass.frag.glsl +++ /dev/null @@ -1,57 +0,0 @@ -// Pass 0: a cone march at one ray per tile of pass-1 pixels. Writes the distance along the tile's -// centre ray that no ray in the tile can have hit before, so pass 1 starts there instead of at the -// camera. Every step is safe for every ray of the tile: the cone's radius at t is the widest any -// ray strays from the centre ray, and the centre's distance bound minus that radius is a free ball -// around each ray's own point. -uniform int u_maxSteps; -uniform vec2 u_tileHalf; // half a tile in uv: the footprint of this texel, as pass 1 samples it - -in vec2 v_uv; -layout(location = 0) out vec4 o_start; // r: start distance, W_FAR when the tile misses; g: steps spent (a half holds both) - -void main() -{ - vec3 ro = u_camPos; - vec3 rd = camRay(v_uv); - - // Widest stray of any ray in the tile from the centre ray, per unit t. The rays are the unit - // directions through a rectangle on the view plane, whose sublevel sets about rd are convex, so - // the maximum sits at a corner. The margin is for float rounding. - float spread = 0.0; - for (int c = 0; c < 4; c++) - { - vec2 corner = vec2(c & 1, c >> 1) * 2.0 - 1.0; - spread = max(spread, length(camRay(v_uv + corner * u_tileHalf) - rd)); - } - spread *= 1.05; - - // Past tEnd every ray of the tile is above W_MAX_HEIGHT and still rising (or beyond W_FAR): - // none can hit anything. - float rise = rd.y - spread; - float tEnd = W_FAR; - if (rise > 0.0) - tEnd = min(W_FAR, max(0.0, (W_MAX_HEIGHT - ro.y) / rise)); - - float t = 0.0; - float leafness; - bool onTree; - int evals = 0; - for (int i = 0; i < u_maxSteps && t < tEnd; i++) - { - evals++; - // Pass 1's hit tolerance, 0.0006 t + 0.01, is kept clear at the far end of the step too, so - // no ray of the tile starts inside its own hit radius. - float s = (sceneDistance(ro + rd * t, leafness, onTree) - spread * t - (0.0006 * t + 0.01)) / 1.0006; - if (s <= 0.0) - break; - t += s; - } - float start = t; -#ifdef START_HALF - // The target is RGBA16F: the write rounds to a half, and the round may go up. Any start past - // the true one is a ray that could skip a surface, so shave more than half a ulp off first - // (START_HALF_SCALE, START_HALF_BIAS: Scene.ts). W_FAR stays exact, an integer a half holds. - start = max(0.0, t * START_HALF_SCALE - START_HALF_BIAS); -#endif - o_start = vec4(t >= tEnd ? W_FAR : start, float(evals), 0.0, 0.0); -} diff --git a/src/app/features/scene/shaders/resolve.frag.glsl b/src/app/features/scene/shaders/resolve.frag.glsl deleted file mode 100644 index cc6dd2e0..00000000 --- a/src/app/features/scene/shaders/resolve.frag.glsl +++ /dev/null @@ -1,41 +0,0 @@ -// TAA resolve for the atmosphere target: reproject history by the pass-1 depth, clamp it to the -// current frame's 3x3 neighbourhood, blend. -uniform sampler2D u_cur; -uniform sampler2D u_history; -uniform sampler2D u_depth; -uniform vec3 u_prevPos; -uniform mat3 u_prevBasis; -uniform vec2 u_prevTanHalf; -uniform float u_blend; // weight of the current frame; 1 resets -uniform vec2 u_curSize; - -in vec2 v_uv; -layout(location = 0) out vec4 o_hist; - -void main() -{ - vec2 px = 1.0 / u_curSize; - vec4 cur = texture(u_cur, v_uv); - vec4 lo = cur; - vec4 hi = cur; - for (int y = -1; y <= 1; y++) - for (int x = -1; x <= 1; x++) - { - vec4 s = texture(u_cur, v_uv + vec2(float(x), float(y)) * px); - lo = min(lo, s); - hi = max(hi, s); - } - - // Where this pixel's ray ended, reprojected into last frame's camera. - vec3 rd = camRay(v_uv); - float t = min(texture(u_depth, v_uv).r, 600.0); - vec3 v = u_camPos + rd * t - u_prevPos; - vec3 local = transpose(u_prevBasis) * v; - vec2 prevNdc = local.z > 0.0 ? local.xy / (local.z * u_prevTanHalf) : vec2(2.0); - vec2 prevUv = prevNdc * 0.5 + 0.5; - bool inside = all(greaterThanEqual(prevUv, vec2(0.0))) && all(lessThanEqual(prevUv, vec2(1.0))); - - float a = (inside && u_blend < 1.0) ? u_blend : 1.0; - vec4 hist = clamp(texture(u_history, prevUv), lo, hi); - o_hist = mix(hist, cur, a); -} diff --git a/src/app/features/scene/shaders/sdf.glsl b/src/app/features/scene/shaders/sdf.glsl deleted file mode 100644 index fd5e6363..00000000 --- a/src/app/features/scene/shaders/sdf.glsl +++ /dev/null @@ -1,95 +0,0 @@ -// The solid world as a distance bound: terrain graph plus tree. Shared by the pass-1 trace and the -// cone prepass, so both step by the same bound. - -// ---- terrain ------------------------------------------------------------------------------- - -float terrainMask(vec2 xz) { return smoothstep(W_PLATEAU_IN, W_PLATEAU_OUT, length(xz)); } - -// Value only; cultmath_fbm_grad is the shipped fbm, a public value-only fbm is Libby's gap. -float terrainFbm(vec2 xz) { return cultmath_fbm_grad(vec3(xz * W_FREQ, 0.0), W_OCTAVES, W_LACUNARITY, W_GAIN).w; } - -#if W_ERODE_ENABLED -CultPhasor terrainPhacelle(vec2 xz) -{ - // A fixed stripe wave vector: ridges across the sheet, not slope-aligned erosion. - return cultmath_phacelle(vec3(xz * W_ERODE_FREQ, 0.0), W_ERODE_SIDE, 0.0, W_ERODE_NORM); -} -#endif - -// Conservative distance to the terrain graph. Above the envelope (fbm + erosion amplitude) the -// cheap envelope bound is exact enough to step by; only within it is the eroded field evaluated. -float terrainDistance(vec3 p) -{ - float m = terrainMask(p.xz); - // Flat plateau: the height is exactly 0, so neither noise is evaluated. Sky rays spend most - // of their steps here. - if (m <= 0.0) - return p.y * W_SLOPE_ENV_INV; - float hb = m * W_AMP * terrainFbm(p.xz); - float above = p.y - (hb + m * W_ERODE_AMP); - if (above > 0.0) - return above * W_SLOPE_ENV_INV; -#if W_ERODE_ENABLED - hb += m * W_ERODE_AMP * terrainPhacelle(p.xz).cos.w; -#endif - return (p.y - hb) * W_SLOPE_FULL_INV; -} - -vec3 terrainNormal(vec2 xz) -{ - float r = length(xz); - float m = smoothstep(W_PLATEAU_IN, W_PLATEAU_OUT, r); - float s = clamp((r - W_PLATEAU_IN) / (W_PLATEAU_OUT - W_PLATEAU_IN), 0.0, 1.0); - float dm = r > 0.0 ? 6.0 * s * (1.0 - s) / (W_PLATEAU_OUT - W_PLATEAU_IN) : 0.0; - vec2 dir = r > 0.0 ? xz / r : vec2(0.0); - vec4 fg = cultmath_fbm_grad(vec3(xz * W_FREQ, 0.0), W_OCTAVES, W_LACUNARITY, W_GAIN); - float f = fg.w; - vec2 g = m * W_AMP * W_FREQ * fg.xy + dm * W_AMP * f * dir; -#if W_ERODE_ENABLED - CultPhasor ph = terrainPhacelle(xz); - g += m * W_ERODE_AMP * W_ERODE_FREQ * ph.cos.xy + dm * W_ERODE_AMP * ph.cos.w * dir; -#endif - return normalize(vec3(-g.x, 1.0, -g.y)); -} - -// ---- world tree ---------------------------------------------------------------------------- - -float smin(float a, float b, float k) -{ - float h = max(k - abs(a - b), 0.0) / k; - return min(a, b) - h * h * k * 0.25; -} - -// Not an exact SDF: the flare, ellipsoid and displacement are all scaled to stay under 1-Lipschitz. -float treeDistance(vec3 p, out float leafness) -{ - vec3 c = vec3(0.0, 0.5 * (W_CANOPY_Y + W_CANOPY_R.y), 0.0); - float bound = length(p - c) - (W_CANOPY_Y + W_CANOPY_R.y); - leafness = 0.0; - if (bound > 8.0) - return bound; - - float ang = atan(p.z, p.x); - float y01 = clamp(p.y / W_TRUNK_H, 0.0, 1.0); - float radius = mix(W_TRUNK_R0, W_TRUNK_R1, y01) + 6.0 * exp(-p.y * 0.2) * (1.0 + 0.35 * sin(6.0 * ang + p.y * 0.15)); - float trunk = max(length(p.xz) - radius, p.y - W_TRUNK_H * 1.2) * 0.7; - - vec3 q = (p - vec3(0.0, W_CANOPY_Y, 0.0)) / W_CANOPY_R; - float disp = cultmath_snoise(p * 0.05 + vec3(0.0, u_time * 0.015, 0.0)); - float canopy = (length(q) - 1.0) * min(W_CANOPY_R.x, W_CANOPY_R.y) - 3.0 * disp; - canopy *= 0.45; // 1 / (1 + 3 * 0.05 * L) - - float d = smin(trunk, canopy, 6.0); - leafness = clamp(0.5 + (trunk - canopy) * 0.15, 0.0, 1.0); - return d; -} - -// ---- trace --------------------------------------------------------------------------------- - -float sceneDistance(vec3 p, out float leafness, out bool onTree) -{ - float dt = terrainDistance(p); - float dr = treeDistance(p, leafness); - onTree = dr < dt; - return min(dt, dr); -} diff --git a/src/app/features/scene/shaders/terrain.frag.glsl b/src/app/features/scene/shaders/terrain.frag.glsl deleted file mode 100644 index 5946cc4a..00000000 --- a/src/app/features/scene/shaders/terrain.frag.glsl +++ /dev/null @@ -1,108 +0,0 @@ -// Pass 1: solid surfaces (terrain + world tree), sphere-traced. Writes lit colour with coverage -// and, separately, the hit distance that bounds pass 2. -uniform vec3 u_grass; -uniform vec3 u_rock; -uniform vec3 u_bark; -uniform vec3 u_leaf; -uniform int u_maxSteps; -uniform sampler2D u_start; // prepass: r = distance no ray of this pixel's tile hits before; W_FAR = tile misses - -in vec2 v_uv; -layout(location = 0) out vec4 o_color; // rgb lit, a coverage -layout(location = 1) out float o_depth; // hit distance along the ray, W_FAR on a miss -#ifdef TRACE_STATS -layout(location = 2) out float o_steps; // distance evaluations this ray spent, over 255 (measurement only) -#endif - -// ---- trace --------------------------------------------------------------------------------- - -void main() -{ - vec3 ro = u_camPos; - vec3 rd = camRay(v_uv); - - float t = texture(u_start, v_uv).r; - // Nothing is above W_MAX_HEIGHT: skip the empty air above it, or miss outright. A tile the - // prepass proved empty arrives as W_FAR. - bool missAtOnce = t >= W_FAR; - if (ro.y > W_MAX_HEIGHT) - { - missAtOnce = missAtOnce || rd.y >= 0.0; - t = max(t, (W_MAX_HEIGHT - ro.y) / rd.y); - } - if (missAtOnce) - { - o_color = vec4(0.0); - o_depth = W_FAR; -#ifdef TRACE_STATS - o_steps = 0.0; -#endif - return; - } - - bool hit = false; - bool onTree = false; - float leafness = 0.0; - int i = 0; - int evals = 0; - for (; i < u_maxSteps; i++) - { - evals++; - vec3 p = ro + rd * t; - float d = sceneDistance(p, leafness, onTree); - if (d < 0.0006 * t + 0.01) - { - hit = true; - break; - } - t += d; - if (t > W_FAR || (p.y > W_MAX_HEIGHT && rd.y > 0.0)) - break; - } - // The conservative bound makes grazing rays crawl: a ray that ran out of steps while still - // below the highest terrain is a distant surface under thick fog, so it ends there. - if (!hit && i == u_maxSteps && t < W_FAR) - { - hit = true; - sceneDistance(ro + rd * t, leafness, onTree); - } -#ifdef TRACE_STATS - o_steps = float(evals) / 255.0; -#endif - - if (!hit) - { - o_color = vec4(0.0); - o_depth = W_FAR; - return; - } - - vec3 p = ro + rd * t; - vec3 n; - vec3 albedo; - if (onTree) - { - float e = 0.35; - float l; - n = normalize(vec3( - treeDistance(p + vec3(e, 0.0, 0.0), l) - treeDistance(p - vec3(e, 0.0, 0.0), l), - treeDistance(p + vec3(0.0, e, 0.0), l) - treeDistance(p - vec3(0.0, e, 0.0), l), - treeDistance(p + vec3(0.0, 0.0, e), l) - treeDistance(p - vec3(0.0, 0.0, e), l))); - float speckle = 0.75 + 0.25 * cultmath_snoise(p * 0.8); - albedo = mix(u_bark, u_leaf * speckle, leafness); - } - else - { - n = terrainNormal(p.xz); - float rockness = smoothstep(0.78, 0.55, n.y); - albedo = mix(u_grass, u_rock, rockness); - } - - float ndl = dot(n, u_sunDir); - float wrap = clamp(ndl * 0.6 + 0.4, 0.0, 1.0); // half-lambert: no shadow ray in the cheap pass - vec3 ambient = mix(u_skyHorizon, u_skyTop, 0.5 + 0.5 * n.y) * 0.45; - vec3 col = albedo * (u_sunColor * wrap * wrap + ambient); - - o_color = vec4(col, 1.0); - o_depth = t; -} diff --git a/src/app/features/scene/skyForState.ts b/src/app/features/scene/skyForState.ts index 79110262..26a5b3ff 100644 --- a/src/app/features/scene/skyForState.ts +++ b/src/app/features/scene/skyForState.ts @@ -1,7 +1,7 @@ // What the ridge scene is told for a sky choice. The choice is not a sky: `momentFor` (ridge/skyMoment.ts) decides the instant it draws, // the sun at that instant is what the physical sky is lit from, and its band (`skyBand`) picks the display's luminance budget (ridge/toneMap.ts). -import type { SkyColours } from './ridge/skyColour'; import { makePhysicalSky } from './ridge/physicalSky'; +import type { SkyColours } from './ridge/physicalSky'; import { momentFor, momentKey, skyBand } from './ridge/skyMoment'; import type { FixedSkyState, SkyChoice } from './ridge/skyMoment'; import { sunAt } from './ridge/sunAt'; diff --git a/src/app/features/scene/skyInk.test.ts b/src/app/features/scene/skyInk.test.ts index edb44929..48659821 100644 --- a/src/app/features/scene/skyInk.test.ts +++ b/src/app/features/scene/skyInk.test.ts @@ -1,141 +1,10 @@ import chroma from 'chroma-js'; import { describe, expect, it } from 'vitest'; -import { baked } from '../../../sky/baked'; import { AA, luminance } from '../../../sky/skyTokens.js'; -import { indexColorMXID } from '../../../util/colorMXID'; import type { FixedSkyState } from './ridge/skyMoment'; -import { - LIGHTEST_PATCH, - NIGHT_INK_MAX_L, - SCRIM_INK, - SCRIM_GROUND, - inkForState, - labelInk, - scrimStyle, - sceneInk, - userColorInk, -} from './skyInk'; +import { SCRIM_INK, SCRIM_GROUND, scrimStyle, sceneInk } from './skyInk'; import { sceneThemeId } from './skyTheme'; -// Every name colour the client can show over the scene, per state and viewport: Aqua's key colour #22d3e6 as -// accessibleColor leaves it (Lab L capped to 50 on a light theme: #00889a; unchanged on a dark one: #22d3e6), and -// the eight hash hues of the theme the state wears (noonday for day and dusk, midnight for night). Columns: name, -// state, phone, colour in, ink out. Aqua's day and dusk rows are the values measured in -// ratatoskr-sidebar-contrast-20261110/results.md (T4): #05707f, #016a78, #055763, #03454f, and #43e5f8 at night. -const TABLE: Array<[string, FixedSkyState, boolean, string, string]> = [ - ['aqua', 'day', false, '#00889a', '#05707f'], - ['aqua', 'day', true, '#00889a', '#016a78'], - ['aqua', 'dusk', false, '#00889a', '#055763'], - ['aqua', 'dusk', true, '#00889a', '#03454f'], - ['aqua', 'night', false, '#22d3e6', '#43e5f8'], - ['aqua', 'night', true, '#22d3e6', '#87f1ff'], - ['hash1', 'day', false, '#2b4675', '#2b4675'], - ['hash1', 'day', true, '#2b4675', '#2b4675'], - ['hash1', 'dusk', false, '#2b4675', '#2b4675'], - ['hash1', 'dusk', true, '#2b4675', '#233e6c'], - ['hash1', 'night', false, '#4683ff', '#bcd3ff'], - ['hash1', 'night', true, '#4683ff', '#cbddfe'], - ['hash2', 'day', false, '#5d366d', '#5d366d'], - ['hash2', 'day', true, '#5d366d', '#5d366d'], - ['hash2', 'dusk', false, '#5d366d', '#5d366d'], - ['hash2', 'dusk', true, '#5d366d', '#562f66'], - ['hash2', 'night', false, '#986fff', '#d4cbfe'], - ['hash2', 'night', true, '#986fff', '#ded7fe'], - ['hash3', 'day', false, '#214e3e', '#214e3e'], - ['hash3', 'day', true, '#214e3e', '#214e3e'], - ['hash3', 'dusk', false, '#214e3e', '#214e3e'], - ['hash3', 'dusk', true, '#214e3e', '#184636'], - ['hash3', 'night', false, '#3893b1', '#86defe'], - ['hash3', 'night', true, '#3893b1', '#ace8ff'], - ['hash4', 'day', false, '#6d334a', '#6d334a'], - ['hash4', 'day', true, '#6d334a', '#6d334a'], - ['hash4', 'dusk', false, '#6d334a', '#6d334a'], - ['hash4', 'dusk', true, '#6d334a', '#652c43'], - ['hash4', 'night', false, '#b26adc', '#e8c7fe'], - ['hash4', 'night', true, '#b26adc', '#edd2ff'], - ['hash5', 'day', false, '#5f401d', '#5f401d'], - ['hash5', 'day', true, '#5f401d', '#5f401d'], - ['hash5', 'dusk', false, '#5f401d', '#5f401d'], - ['hash5', 'dusk', true, '#5f401d', '#563814'], - ['hash5', 'night', false, '#9f8365', '#ecceae'], - ['hash5', 'night', true, '#9f8365', '#f6d8b7'], - ['hash6', 'day', false, '#204c52', '#204c52'], - ['hash6', 'day', true, '#204c52', '#204c52'], - ['hash6', 'dusk', false, '#204c52', '#204c52'], - ['hash6', 'dusk', true, '#204c52', '#19454b'], - ['hash6', 'night', false, '#358dde', '#b1d7ff'], - ['hash6', 'night', true, '#358dde', '#c6e1fe'], - ['hash7', 'day', false, '#41426c', '#41426c'], - ['hash7', 'day', true, '#41426c', '#41426c'], - ['hash7', 'dusk', false, '#41426c', '#41426c'], - ['hash7', 'dusk', true, '#41426c', '#3b3b65'], - ['hash7', 'night', false, '#677dff', '#c4d1fe'], - ['hash7', 'night', true, '#677dff', '#d3ddfe'], - ['hash8', 'day', false, '#3f4a20', '#3f4a20'], - ['hash8', 'day', true, '#3f4a20', '#3f4a20'], - ['hash8', 'dusk', false, '#3f4a20', '#3f4a20'], - ['hash8', 'dusk', true, '#3f4a20', '#394319'], - ['hash8', 'night', false, '#6a926a', '#b2ddb1'], - ['hash8', 'night', true, '#6a926a', '#c0ebc0'], -]; - -const patchRatio = (hex: string, state: FixedSkyState, phone: boolean) => { - const p = LIGHTEST_PATCH[state][phone ? 'phone' : 'desktop']; - const l = luminance(hex); - return (Math.max(l, p) + 0.05) / (Math.min(l, p) + 0.05); -}; -const hueGap = (a: string, b: string) => { - const d = Math.abs(chroma(a).oklch()[2] - chroma(b).oklch()[2]) % 360; - return Math.min(d, 360 - d); -}; - -describe('inkForState', () => { - it.each(TABLE)('%s %s phone=%s: %s -> %s', (_name, state, phone, base, ink) => { - expect(inkForState(base, { state, phone })).toBe(ink); - }); - - it('clears 4.5:1 on the lightest patch, keeps the hue, and moves lightness the way the state needs', () => { - TABLE.forEach(([, state, phone, base, ink]) => { - const [l0] = chroma(base).oklch(); - const [l1] = chroma(ink).oklch(); - if (ink === base) { - expect(patchRatio(base, state, phone)).toBeGreaterThanOrEqual(AA); - return; - } - expect(state === 'night' ? l1 > l0 : l1 < l0).toBe(true); - expect(hueGap(base, ink)).toBeLessThan(2); - if (l1 < NIGHT_INK_MAX_L - 0.006) - expect(patchRatio(ink, state, phone)).toBeGreaterThanOrEqual(AA); - }); - }); - - it('stops lightening at NIGHT_INK_MAX_L: a phone-night name keeps its hue instead of reaching 4.5:1 on the one pale snow patch', () => { - const aqua = inkForState('#22d3e6', { state: 'night', phone: true }); - expect(aqua).toBe('#87f1ff'); - expect(chroma(aqua).oklch()[0]).toBeLessThanOrEqual(NIGHT_INK_MAX_L); - expect(chroma(aqua).oklch()[1]).toBeGreaterThan(0.08); - expect(patchRatio(aqua, 'night', true)).toBeGreaterThan(3.9); - }); - - it('leaves a colour that already clears its patch untouched, and a non-colour alone', () => { - expect(inkForState('#2b4675', { state: 'day', phone: false })).toBe('#2b4675'); - expect(inkForState('var(--mx-uc-1)', { state: 'day', phone: false })).toBe('var(--mx-uc-1)'); - }); -}); - -describe('userColorInk', () => { - it('takes the hash colour of the theme the state wears, then steps it', () => { - const id = '@aqua:gamecult.org'; - const n = indexColorMXID(id) - 1; - expect(userColorInk(id, { state: 'dusk', phone: true })).toBe( - inkForState(baked.noonday.userColors[n], { state: 'dusk', phone: true }) - ); - expect(userColorInk(id, { state: 'night', phone: false })).toBe( - inkForState(baked.midnight.userColors[n], { state: 'night', phone: false }) - ); - }); -}); - describe('sceneInk: the drawn sky decides the ink', () => { it('is the sky state and viewport while a scene runs, and nothing without one', () => { expect(sceneInk(sceneThemeId('dusk', true), true, 'dusk', true)).toEqual({ @@ -151,25 +20,6 @@ describe('sceneInk: the drawn sky decides the ink', () => { }); }); -describe('labelInk', () => { - it('differs from the theme only on a phone at dusk', () => { - const states: FixedSkyState[] = ['day', 'dusk', 'night']; - states.forEach((state) => - [false, true].forEach((phone) => { - expect(labelInk({ state, phone })).toBe(state === 'dusk' && phone ? '#29221a' : undefined); - }) - ); - }); - - it('is the shipped dark ink, same hue and chroma, a little darker', () => { - const dark = baked.noonday.tokens.Surface.OnContainer; - const ink = labelInk({ state: 'dusk', phone: true }) as string; - expect(dark).toBe('#342d25'); - expect(luminance(ink)).toBeLessThan(luminance(dark)); - expect(hueGap(dark, ink)).toBeLessThan(2); - }); -}); - describe('scrimStyle', () => { // The scrim over the lightest possible ground (white) is the worst case the ink can meet. const [r, g, b, a] = (SCRIM_GROUND.match(/[\d.]+/g) ?? []).map(Number); diff --git a/src/app/features/scene/skyInk.ts b/src/app/features/scene/skyInk.ts index d3aa2028..9a3d5eb0 100644 --- a/src/app/features/scene/skyInk.ts +++ b/src/app/features/scene/skyInk.ts @@ -1,20 +1,6 @@ -// The one owner of ink for a sky state: which colour a sender name or a sidebar label wears over the scene, -// per fixed sky state (day, dusk, night) and viewport (phone or not). Pure: the hooks that read the resolved -// sky and the viewport (useSkyInk, hooks/useTheme.ts) only hand their values here. -// -// Names are bare ink over the terrain, so the theme's fitted colours (fitted against panel grounds, skyTokens.js) -// can land on the same luminance as the ridge behind them. The rule is measured, not tuned by eye: keep the -// colour's OKLCH hue and chroma and move its lightness (darker by day and dusk, lighter at night, in 0.005 steps) -// until it clears 4.5:1 (WCAG) against the LIGHTEST 24x12 patch of terrain under the timeline in that state -// and viewport. Measured 2026-11-10 on the demo's terrain scene at 1920x1080 and 390x844 (Chrome, SwiftShader, -// not a GPU; ratatoskr-sidebar-contrast-20261110/results.md, T3). These are the scene's own patches, not -// the bare sky: the terrain under the timeline is what the ink sits on, and at night its snow (0.103, phone 0.149) is -// lighter than the sky was when these were measured (0.0816). -// The page wears this ink whenever the drawn sky decides its theme (a scene is on, sceneThemeId). -import chroma from 'chroma-js'; -import { AA, luminance } from '../../../sky/skyTokens.js'; +// The one owner of ink for a sky state: whether a scene runs behind the page and what scrim +// high-contrast notice lines wear over it. Pure: `useSkyInk` / `hooks/useTheme.ts` hand values here. import { baked } from '../../../sky/baked'; -import { indexColorMXID } from '../../../util/colorMXID'; import type { FixedSkyState } from './ridge/skyMoment'; import type { SkyThemeId } from './skyTheme'; @@ -35,73 +21,9 @@ export const sceneInk = ( phone: boolean ): SkyInk | undefined => (themeId && sceneOn && state ? { state, phone } : undefined); -/** WCAG relative luminance of the lightest 24x12 patch of terrain behind the timeline. */ -export const LIGHTEST_PATCH: Record = { - day: { desktop: 0.777, phone: 0.703 }, - dusk: { desktop: 0.531, phone: 0.4 }, - night: { desktop: 0.103, phone: 0.149 }, -}; - -/** Night lightening stops here (OKLCH L): above it every hue reads white, and the hue is what names the sender. */ -export const NIGHT_INK_MAX_L = 0.9; - -const STEP = 0.005; -const SKY_COLORS = { noonday: baked.noonday.userColors, midnight: baked.midnight.userColors }; - -const inGamut = (l: number, c: number, h: number): string | undefined => { - for (let k = c; k > 1e-4; k *= 0.97) { - const out = chroma.oklch(l, k, h); - if (!out.clipped()) return out.hex(); - } - return chroma.oklch(l, 0, 0).hex(); -}; - -/** The ink for a colour (#rrggbb) in this sky state and viewport: itself when it already clears the lightest patch. */ -export function inkForState(hex: string, { state, phone }: SkyInk): string { - if (!chroma.valid(hex)) return hex; - const patch = LIGHTEST_PATCH[state][phone ? 'phone' : 'desktop']; - const ratio = (h: string) => { - const l = luminance(h); - return (Math.max(l, patch) + 0.05) / (Math.min(l, patch) + 0.05); - }; - if (ratio(hex) >= AA) return hex; - const [l0, c0, h0] = chroma(hex).oklch(); - const hue = Number.isNaN(h0) ? 0 : h0; - const dir = state === 'night' ? 1 : -1; - let best = hex; - for (let k = 1; k < 200; k += 1) { - const l = l0 + dir * k * STEP; - if (l < 0 || l > (state === 'night' ? NIGHT_INK_MAX_L : 1)) break; - best = inGamut(l, c0, hue) ?? best; - if (ratio(best) >= AA) break; - } - return best; -} - -/** The ink of a user's hash colour (the --mx-uc-1..8 the theme would give) in this sky state and viewport. */ -export function userColorInk(userId: string, ink: SkyInk): string { - const palette = ink.state === 'night' ? SKY_COLORS.midnight : SKY_COLORS.noonday; - return inkForState(palette[indexColorMXID(userId) - 1], ink); -} - /** - * The sidebar label ink where it differs from the theme's. Phone Dusk: the dark ink #342d25 reached a median of 3.98:1 - * on the glyph pixels (worst 1.66); the same hue and chroma at OKLCH L 0.257 (#29221a) reaches 4.53 (worst 1.92), - * measured over the shipped dusk phone shot, halo included. Nothing darker is searched for: the ridge's dusk ochre - * sits at the dark ink's own luminance, so the worst pixels stay below 4.5. Every other state keeps the theme's - * ink (undefined): desktop and night were measured as shipped. - */ -export const labelInk = ({ state, phone }: SkyInk): string | undefined => - state === 'dusk' && phone ? '#29221a' : undefined; - -/** - * The training-notice line above the composer sits on whatever the scene draws there: the dark ridge on a phone in - * the Starfire shots, but a mid-tone ridge at other widths and the near-black foreground ridge on a desktop, so no - * ink chosen for one ground holds on the others (measured 2026-11-10 on the pretend-server line, ratatoskr-dev-preview/ - * taps2-REPORT.md: phone day 3.08, dusk 3.97 with light ink; desktop day 1.01, dusk 1.22 with the theme's dark ink). - * So the line carries its own ground: light ink on a dark scrim, in every sky state, on every viewport, whatever - * the scene is behind it. The scrim is composited over the lightest ground there is (white); the ink over that - * worst case clears AA (skyInk.test.ts). + * The training-notice line above the composer and the desk's recorded rulings carry their own ground: + * light ink on a dark scrim, in every sky state, on every viewport, whatever the scene is behind them. */ export const SCRIM_INK = baked.midnight.tokens.SurfaceVariant.OnContainer; export const SCRIM_GROUND = 'rgba(10, 14, 24, 0.82)'; diff --git a/src/app/features/scene/skyLabelInk.ts b/src/app/features/scene/skyLabelInk.ts deleted file mode 100644 index 03b9e660..00000000 --- a/src/app/features/scene/skyLabelInk.ts +++ /dev/null @@ -1,7 +0,0 @@ -/** - * The sky's label ink (skyInk.ts `labelInk`), set on by the theme manager (ThemeManager.tsx) only where it - * differs from the theme's; unset, `skyLabelInk(fallback)` is the fallback, so a person's own theme keeps its ink. - * Not in sceneShell.css.ts: vanilla-extract refuses a function exported from a .css.ts file. - */ -export const SKY_LABEL_INK = '--sky-label-ink'; -export const skyLabelInk = (fallback: string) => `var(${SKY_LABEL_INK}, ${fallback})`; diff --git a/src/app/features/scene/skyState.test.ts b/src/app/features/scene/skyState.test.ts index ffd25717..7ebda076 100644 --- a/src/app/features/scene/skyState.test.ts +++ b/src/app/features/scene/skyState.test.ts @@ -7,7 +7,6 @@ import type { SkyChoice } from './ridge/skyMoment'; type Mod = typeof import('./skyState'); const VIENNA = FALLBACK_VIEW.place; -const OLD_KEY = 'ratatoskr.skyState'; const noon: SkyChoice = { kind: 'named', id: 'noon' }; const dusk: SkyChoice = { kind: 'named', id: 'dusk' }; const night: SkyChoice = { kind: 'named', id: 'night' }; @@ -73,35 +72,6 @@ describe('persistence', () => { expect((await fresh()).getSkyChoice()).toEqual(auto); }); - it.each([ - ['auto', auto], - ['day', noon], - ['dusk', dusk], - ['night', night], - ] as const)('migrates the old key %s to %j once, and removes it', async (old, want) => { - storage.data.set(OLD_KEY, old); - const m = await fresh(); - expect(m.getSkyChoice()).toEqual(want); - expect(storage.data.has(OLD_KEY)).toBe(false); - expect(JSON.parse(storage.data.get(SKY_CHOICE_KEY) as string)).toEqual(want); - m.setSkyChoice(dusk); - expect(storage.data.has(OLD_KEY)).toBe(false); - expect((await fresh()).getSkyChoice()).toEqual(dusk); - }); - - it.each(['noon', 'NIGHT', '', '"night"', 'null'])('ignores the old key holding %j, and removes it', async (old) => { - storage.data.set(OLD_KEY, old); - expect((await fresh()).getSkyChoice()).toEqual(auto); - expect(storage.data.has(OLD_KEY)).toBe(false); - }); - - it('the new key wins over a stale old one', async () => { - storage.data.set(OLD_KEY, 'night'); - storage.data.set(SKY_CHOICE_KEY, JSON.stringify(dusk)); - expect((await fresh()).getSkyChoice()).toEqual(dusk); - expect(storage.data.has(OLD_KEY)).toBe(false); - }); - it('keeps the pick for the page load when storage is refused', async () => { vi.stubGlobal('localStorage', { getItem: () => { @@ -120,36 +90,6 @@ describe('persistence', () => { expect(m.getSkyChoice()).toEqual(night); }); - it('migrates an old pick even when the new key cannot be written: the pick holds for the page load, the old key stays', async () => { - storage.data.set(OLD_KEY, 'day'); - vi.stubGlobal('localStorage', { - ...storage, - setItem: () => { - throw new Error('denied'); - }, - }); - expect((await fresh()).getSkyChoice()).toEqual(noon); - expect(storage.data.has(OLD_KEY)).toBe(true); - }); - - it('writes the new key before it removes the old one', async () => { - storage.data.set(OLD_KEY, 'dusk'); - const order: string[] = []; - vi.stubGlobal('localStorage', { - ...storage, - setItem: (k: string, v: string) => { - order.push(`set ${k}`); - storage.data.set(k, v); - }, - removeItem: (k: string) => { - order.push(`remove ${k}`); - storage.data.delete(k); - }, - }); - expect((await fresh()).getSkyChoice()).toEqual(dusk); - expect(order).toEqual([`set ${SKY_CHOICE_KEY}`, `remove ${OLD_KEY}`]); - }); - it('persists a set choice under one key and reads it back after a reload', async () => { (await fresh()).setSkyChoice(dusk); expect([...storage.data.entries()]).toEqual([[SKY_CHOICE_KEY, JSON.stringify(dusk)]]); diff --git a/src/app/features/scene/skyState.ts b/src/app/features/scene/skyState.ts index 3267468c..7dbedc12 100644 --- a/src/app/features/scene/skyState.ts +++ b/src/app/features/scene/skyState.ts @@ -34,32 +34,8 @@ export function parseSkyChoice(raw: unknown): SkyChoice | undefined { const same = (a: SkyChoice, b: SkyChoice): boolean => JSON.stringify(a) === JSON.stringify(b); -// The old sky menu once held Auto, Day, Dusk and Night under another key. It is read once, here, and removed: Day became Noon. -const OLD_KEY = 'ratatoskr.skyState'; -const FROM_OLD = new Map([ - ['auto', AUTO], - ['day', { kind: 'named', id: 'noon' }], - ['dusk', { kind: 'named', id: 'dusk' }], - ['night', { kind: 'named', id: 'night' }], -]); - function load(): SkyChoice { try { - const old = localStorage.getItem(OLD_KEY); - if (old !== null) { - const migrated = FROM_OLD.get(old); - if (migrated && localStorage.getItem(SKY_CHOICE_KEY) === null) { - try { - // The new key first: a refusal leaves the old one in place, and the pick holds for this page load. - localStorage.setItem(SKY_CHOICE_KEY, JSON.stringify(migrated)); - } catch { - return migrated; - } - localStorage.removeItem(OLD_KEY); - return migrated; - } - localStorage.removeItem(OLD_KEY); - } const stored = localStorage.getItem(SKY_CHOICE_KEY); return (stored !== null && parseSkyChoice(JSON.parse(stored))) || AUTO; } catch { diff --git a/src/app/features/scene/skyTheme.test.ts b/src/app/features/scene/skyTheme.test.ts index cce8a657..88800063 100644 --- a/src/app/features/scene/skyTheme.test.ts +++ b/src/app/features/scene/skyTheme.test.ts @@ -7,7 +7,7 @@ import { PageContent, PageNavContent } from '../../components/page/style.css'; import { CallStatus } from '../call-status/styles.css'; import { MembersDrawer } from '../room/MembersDrawer.css'; import { RoomViewTyping } from '../room/RoomViewTyping.css'; -import { FOOTER_TINT, SKY_PLATE_FALLBACK } from './skyPlate'; +import { SKY_PLATE_FALLBACK } from './skyPlate'; import { SkyPlate, plateRegions } from './skyPlate.css'; import { getResolvedSkyState, @@ -132,31 +132,3 @@ describe('regions that sit on the plate', () => { ].forEach((cls) => expect(plateRegions).not.toContain(cls)); }); }); - -describe('the sign-in footer band', () => { - // The footer line is the plate's ink on a band that mixes FOOTER_TINT of the plate's fill over the blurred scene, - // as the browser does: per channel, in encoded sRGB (not in linear light, which flatters dark scenes). The scene - // behind it is the scene, taken as grey: as dark as 0 or as light as 1 (a sky's range is whatever the look draws). Ink - // contrast is lowest at one of those two ends, so both are checked. - const encode = (l: number) => (l <= 0.0031308 ? 12.92 * l : 1.055 * l ** (1 / 2.4) - 0.055); - const channels = (hex: string) => [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255); - const hexOf = (c: number[]) => - `#${c - .map((v) => - Math.round(v * 255) - .toString(16) - .padStart(2, '0') - ) - .join('')}`; - const bandOver = (fill: string, behind: number) => - hexOf(channels(fill).map((f) => FOOTER_TINT * f + (1 - FOOTER_TINT) * encode(behind))); - it.each(fixed)( - '%s: the ink clears AA over the darkest and the lightest scene behind it', - (state, id) => { - const { Other, OtherText } = SKY[id].bubbles; - [0, 1].forEach((behind) => { - expect(contrast(OtherText, bandOver(Other, behind))).toBeGreaterThanOrEqual(AA); - }); - } - ); -}); diff --git a/src/app/features/scene/tier.ts b/src/app/features/scene/tier.ts index 0f1c96be..e35faa44 100644 --- a/src/app/features/scene/tier.ts +++ b/src/app/features/scene/tier.ts @@ -15,19 +15,10 @@ export interface Capabilities { hardwareConcurrency?: number; } -/** - * 'ridge': baked ridge cards lit once per sky in WebGL2, no per-frame WebGL (default). 'raymarch': the sphere-traced world with its tree and - * clouds. - */ -export type SceneStyle = 'ridge' | 'raymarch'; - export interface BackgroundSceneConfig { tier?: SceneTier; - style?: SceneStyle; /** The baked ridge place to show (a key of the ridge index); unknown or absent: the index's default. */ place?: string; - /** Let the page URL switch on the diagnostic overlays (`?probe=1`, `?tierlabel=1`) in a production build. Default: no. */ - debugOverlays?: boolean; } export function readCapabilities(nav: Navigator): Capabilities { diff --git a/src/app/features/scene/view/PlaceSubmenu.tsx b/src/app/features/scene/view/PlaceSubmenu.tsx index 9eb51a55..65d359ee 100644 --- a/src/app/features/scene/view/PlaceSubmenu.tsx +++ b/src/app/features/scene/view/PlaceSubmenu.tsx @@ -2,7 +2,6 @@ import React, { useEffect, useRef } from 'react'; import { Box, Icon, IconButton, Icons, Text } from 'folds'; import { useDrawnPlace, useSkyChoice, useSkyMinute } from '../../../hooks/useSkyState'; import { usePlaceList } from '../../../hooks/useSceneView'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; import { LINES_CREDIT, STARS_CREDIT, terrainCredit } from '../ridge/credits'; import type { RidgeManifest, PlaceListing } from '../ridge/manifest'; import { localMinutes, momentFor } from '../ridge/skyMoment'; @@ -74,7 +73,6 @@ export function PlaceCarousel({ return ( { ).toEqual(['Return', 'View', 'Time', 'Sky', 'Place']); }); - it('every rail icon is an IconButton carrying PhoneHit, with a label and a roving tab stop on Return', () => { + it('every rail icon is an IconButton, with a label and a roving tab stop on Return', () => { const buttons = rail() .filter((e) => typeof e.props?.label === 'string') .map((e) => - walk((e.type as (p: unknown) => unknown)(e.props)).find( - (x) => x.props?.className === PhoneHit - ) + walk((e.type as (p: unknown) => unknown)(e.props)).find((x) => x.type === IconButton) ); expect(buttons).toHaveLength(5); buttons.forEach((b) => expect(b?.props?.['aria-label']).toBeTruthy()); @@ -226,16 +222,3 @@ describe('one finger on the phone (ruling ridge-view-phone-one-finger)', () => { expect(held.turner).toEqual([['down', 100]]); }); }); - -describe('the chrome styles (a vanilla-extract rule cannot be read back, so the source is)', () => { - const css = readFileSync(join(__dirname, 'SceneView.css.ts'), 'utf8'); - it('the fade rule uses the constant the test above bounds', () => { - expect(css).toMatch(/data-turning="true"] &`]: { opacity: TURNING_CHROME_OPACITY }/); - }); - it('the chrome takes no pointer itself, so a drag over its gaps turns the view; its plates do', () => { - const chrome = css.slice(css.indexOf('export const Chrome'), css.indexOf('const Plate')); - expect(chrome).toContain("pointerEvents: 'none'"); - const plate = css.slice(css.indexOf('const Plate'), css.indexOf('export const Rail')); - expect(plate).toContain("pointerEvents: 'auto'"); - }); -}); diff --git a/src/app/features/scene/view/SceneView.tsx b/src/app/features/scene/view/SceneView.tsx index 854320b5..bb4cbd6b 100644 --- a/src/app/features/scene/view/SceneView.tsx +++ b/src/app/features/scene/view/SceneView.tsx @@ -1,7 +1,6 @@ import React, { KeyboardEvent, useEffect, useMemo, useRef, useState } from 'react'; import { Icon, IconButton, Icons } from 'folds'; import FocusTrap from 'focus-trap-react'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; import { useRidgeManifest, useSceneViewState } from '../../../hooks/useSceneView'; import { closeSceneView, setSubmenu } from '../sceneView'; import type { Submenu } from '../sceneView'; @@ -23,7 +22,7 @@ export const SUBMENUS: ReadonlyArray<{ id: Submenu; label: string; icon: IconSrc { id: 'place', label: 'Place', icon: Icons.Pin }, ]; -/** One icon of the rail: 44 px to tap on a phone (PhoneHit). */ +/** One icon of the rail. */ function RailButton({ label, icon, @@ -42,7 +41,6 @@ function RailButton({ return ( { - it('define every W_ name any scene shader uses', () => { - const defined = new Set([...worldDefines().matchAll(/#define (W_\w+)/g)].map((m) => m[1])); - [common, terrain, atmosphere, resolve, composite] - .flatMap((src) => [...src.matchAll(/\bW_[A-Z0-9_]+\b/g)]) - .forEach((m) => expect(defined, m[0]).toContain(m[0])); - }); - - it('emit only valid GLSL numbers', () => { - expect(worldDefines()).not.toMatch(/NaN|Infinity|undefined/); - }); -}); - -describe('terrain step bound', () => { - it('is more conservative with erosion than without, and without erosion carries no phacelle term', () => { - const b = terrainBounds(); - expect(b.slopeFull).toBeGreaterThan(b.slopeEnvelope); - const off = terrainBounds({ ...WORLD, phacelleGradBound: 0 }); - expect(off.slopeFull).toBe(off.slopeEnvelope); - }); - - it('puts every surface under the height the tracer skips to', () => { - const maxHeight = Number(/#define W_MAX_HEIGHT (\S+)/.exec(worldDefines())![1]); - expect(maxHeight).toBeGreaterThanOrEqual(terrainBounds().maxHeight); - expect(maxHeight).toBeGreaterThanOrEqual(WORLD.tree.canopyY + WORLD.tree.canopyRadius[1]); - }); - - it('leaves the erosion bound turned on only when a bound exists', () => { - expect(worldDefines()).toContain('#define W_ERODE_ENABLED 1'); - expect(worldDefines({ ...WORLD, phacelleGradBound: 0 })).toContain('#define W_ERODE_ENABLED 0'); - }); -}); diff --git a/src/app/features/scene/world.ts b/src/app/features/scene/world.ts deleted file mode 100644 index e9594a68..00000000 --- a/src/app/features/scene/world.ts +++ /dev/null @@ -1,117 +0,0 @@ -// The scene's world constants. One owner: the shader prelude below is generated from this -// object, so a number lives here and nowhere else, and the Lipschitz bounds that make the -// sphere-trace step safe are computed beside the numbers they bound. - -// Lipschitz constant of cultmath_snoise(vec3), CULTMATH_SNOISE_LIPSCHITZ in the vendored -// CultMath.glsl (provenance in CultLib math.Interval.cs). -export const SNOISE_LIPSCHITZ = 7.9640074; - -export const WORLD = { - far: 1400, - // Terrain: height = mask(r) * (amp * fbm(xz * freq) + erodeAmp * phacelle(xz * erodeFreq)). - amp: 70, - freq: 1 / 520, - octaves: 4, - lacunarity: 2.0, - gain: 0.45, - // Flat ground (height 0) out to plateauInner, full terrain from plateauOuter. The login - // camera stays inside plateauInner, so it can never end up inside the terrain. - plateauInner: 135, - plateauOuter: 380, - erodeAmp: 2.5, - erodeFreq: 1 / 38, - // The stripe wave vector and normalization the terrain feeds cultmath_phacelle. - erodeSide: [1.7, 0, 1] as const, - erodeNorm: 0.5, - // Bound on |grad| of the phasor's cos component for the side and norm above. Libby measured a - // sup of 6.63 at |side| = 1.5, n = 0 (CultLib PR #1 head 990521b3); 7.0 adds margin. - // The sup was measured, not proved. The shader passes roughness n = 0 as a literal, so the doc - // envelope max(10, 1.25|side|)/(1-n) needs no 1/(1-n) factor here; if n ever becomes nonzero, - // divide this bound by (1 - n). - // |value| <= 1 holds by construction (the output is a normalized phasor). - // Typed number, not the literal 7, so callers can build variants such as { ...WORLD, phacelleGradBound: 0 }. - phacelleGradBound: 7.0 as number, - // World tree at the origin. - tree: { - trunkHeight: 38, - baseRadius: 3.4, - topRadius: 1.9, - canopyY: 52, - canopyRadius: [30, 17, 30] as const, - }, - // Atmosphere. - atmosphereFar: 1400, - cloudBase: 130, - cloudTop: 230, - fogDensity: 0.0028, - fogFalloff: 0.011, -} as const; - -const f = (n: number) => (Number.isInteger(n) ? `${n}.0` : `${n}`); - -/** Sum over octaves of (lacunarity * gain)^i: the slope bound's octave factor. */ -function slopeSum(octaves: number, lacunarity: number, gain: number): number { - let s = 0; - for (let i = 0; i < octaves; i += 1) s += (lacunarity * gain) ** i; - return s; -} - -/** Sum over octaves of gain^i: the fbm value bound. */ -function valueSum(octaves: number, gain: number): number { - let s = 0; - for (let i = 0; i < octaves; i += 1) s += gain ** i; - return s; -} - -export interface TerrainBounds { - /** Lipschitz bound of the envelope surface (no erosion). */ - slopeEnvelope: number; - /** Lipschitz bound of the eroded surface. */ - slopeFull: number; - /** Highest point the terrain can reach. */ - maxHeight: number; -} - -export function terrainBounds(w: typeof WORLD = WORLD): TerrainBounds { - const fbmMax = valueSum(w.octaves, w.gain); - const maskSlope = 1.5 / (w.plateauOuter - w.plateauInner); // smoothstep's max slope - const fbmSlope = w.amp * w.freq * SNOISE_LIPSCHITZ * slopeSum(w.octaves, w.lacunarity, w.gain); - const slopeEnvelope = fbmSlope + (w.amp * fbmMax + w.erodeAmp) * maskSlope; - const slopeFull = slopeEnvelope + w.erodeAmp * w.erodeFreq * w.phacelleGradBound; - return { slopeEnvelope, slopeFull, maxHeight: w.amp * fbmMax + w.erodeAmp }; -} - -/** The #defines every stage sees. */ -export function worldDefines(w: typeof WORLD = WORLD): string { - const b = terrainBounds(w); - const t = w.tree; - const lines: Array<[string, string]> = [ - ['W_FAR', f(w.far)], - ['W_AMP', f(w.amp)], - ['W_FREQ', f(w.freq)], - ['W_OCTAVES', String(w.octaves)], - ['W_LACUNARITY', f(w.lacunarity)], - ['W_GAIN', f(w.gain)], - ['W_PLATEAU_IN', f(w.plateauInner)], - ['W_PLATEAU_OUT', f(w.plateauOuter)], - ['W_ERODE_AMP', f(w.erodeAmp)], - ['W_ERODE_FREQ', f(w.erodeFreq)], - ['W_ERODE_SIDE', `vec3(${w.erodeSide.map(f).join(', ')})`], - ['W_ERODE_NORM', f(w.erodeNorm)], - ['W_ERODE_ENABLED', w.phacelleGradBound > 0 ? '1' : '0'], - ['W_SLOPE_ENV_INV', f(1 / Math.sqrt(1 + b.slopeEnvelope ** 2))], - ['W_SLOPE_FULL_INV', f(1 / Math.sqrt(1 + b.slopeFull ** 2))], - ['W_MAX_HEIGHT', f(Math.max(b.maxHeight, t.canopyY + t.canopyRadius[1] + 6))], - ['W_TRUNK_H', f(t.trunkHeight)], - ['W_TRUNK_R0', f(t.baseRadius)], - ['W_TRUNK_R1', f(t.topRadius)], - ['W_CANOPY_Y', f(t.canopyY)], - ['W_CANOPY_R', `vec3(${t.canopyRadius.map(f).join(', ')})`], - ['W_ATM_FAR', f(w.atmosphereFar)], - ['W_CLOUD_Y0', f(w.cloudBase)], - ['W_CLOUD_Y1', f(w.cloudTop)], - ['W_FOG_DENSITY', f(w.fogDensity)], - ['W_FOG_FALLOFF', f(w.fogFalloff)], - ]; - return lines.map(([k, v]) => `#define ${k} ${v}`).join('\n'); -} diff --git a/src/app/features/settings/Settings.tsx b/src/app/features/settings/Settings.tsx index 6c91bc9d..5e1a20f4 100644 --- a/src/app/features/settings/Settings.tsx +++ b/src/app/features/settings/Settings.tsx @@ -33,7 +33,6 @@ import { About } from './about'; import { UseStateProvider } from '../../components/UseStateProvider'; import { stopPropagation } from '../../utils/keyboard'; import { LogoutDialog } from '../../components/LogoutDialog'; -import { PhoneHit } from '../../styles/PhoneHit.css'; export enum SettingsPages { GeneralPage, @@ -142,7 +141,7 @@ export function Settings({ initialPage, requestClose }: SettingsProps) { {screenSize === ScreenSize.Mobile && ( - + )} diff --git a/src/app/features/settings/about/About.tsx b/src/app/features/settings/about/About.tsx index 19407bdf..9ec74305 100644 --- a/src/app/features/settings/about/About.tsx +++ b/src/app/features/settings/about/About.tsx @@ -8,7 +8,6 @@ import { LogoMark } from '../../../components/logo/logoMark.css'; import RatatoskrSVG from '../../../../../public/res/svg/ratatoskr.svg'; import { clearCacheAndReload } from '../../../../client/initMatrix'; import { useMatrixClient } from '../../../hooks/useMatrixClient'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; type AboutProps = { requestClose: () => void; @@ -26,7 +25,7 @@ export function About({ requestClose }: AboutProps) { - + diff --git a/src/app/features/settings/account/Account.tsx b/src/app/features/settings/account/Account.tsx index 77ee8671..c4b56e47 100644 --- a/src/app/features/settings/account/Account.tsx +++ b/src/app/features/settings/account/Account.tsx @@ -5,7 +5,6 @@ import { MatrixId } from './MatrixId'; import { Profile } from './Profile'; import { ContactInformation } from './ContactInfo'; import { IgnoredUserList } from './IgnoredUserList'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; type AccountProps = { requestClose: () => void; @@ -21,7 +20,7 @@ export function Account({ requestClose }: AccountProps) { - + diff --git a/src/app/features/settings/account/IgnoredUserList.tsx b/src/app/features/settings/account/IgnoredUserList.tsx index 791a407b..98db9459 100644 --- a/src/app/features/settings/account/IgnoredUserList.tsx +++ b/src/app/features/settings/account/IgnoredUserList.tsx @@ -8,7 +8,6 @@ import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback'; import { isUserId } from '../../../utils/matrix'; import { useIgnoredUsers } from '../../../hooks/useIgnoredUsers'; import { useAlive } from '../../../hooks/useAlive'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; function IgnoreUserInput({ userList }: { userList: string[] }) { const mx = useMatrixClient(); @@ -68,7 +67,6 @@ function IgnoreUserInput({ userList }: { userList: string[] }) { userId && !ignoring && ( Remove Avatar setAlertRemove(false)} radii="300" @@ -279,7 +277,6 @@ function ProfileDisplayName({ profile, userId }: ProfileProps) { hasChanges && !changingDisplayName && ( void; @@ -52,7 +51,7 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) { - + diff --git a/src/app/features/settings/devices/DeviceTile.tsx b/src/app/features/settings/devices/DeviceTile.tsx index c4912dc0..71b684f5 100644 --- a/src/app/features/settings/devices/DeviceTile.tsx +++ b/src/app/features/settings/devices/DeviceTile.tsx @@ -29,7 +29,6 @@ import { LogoutDialog } from '../../../components/LogoutDialog'; import { stopPropagation } from '../../../utils/keyboard'; import { useSetting } from '../../../state/hooks/settings'; import { settingsAtom } from '../../../state/settings'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; export function DeviceTilePlaceholder() { return ( @@ -289,7 +288,6 @@ export function DeviceTile({ - + diff --git a/src/app/features/settings/devices/Verification.tsx b/src/app/features/settings/devices/Verification.tsx index c09dff55..6c7eab17 100644 --- a/src/app/features/settings/devices/Verification.tsx +++ b/src/app/features/settings/devices/Verification.tsx @@ -35,7 +35,6 @@ import { stopPropagation } from '../../../utils/keyboard'; import { useAuthMetadata } from '../../../hooks/useAuthMetadata'; import { withSearchParam } from '../../../pages/pathUtils'; import { useAccountManagementActions } from '../../../hooks/useAccountManagement'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; type VerificationStatusBadgeProps = { verificationStatus: VerificationStatus; @@ -289,7 +288,6 @@ export function DeviceVerificationOptions() { return ( <> void; @@ -31,7 +30,7 @@ export function EmojisStickers({ requestClose }: EmojisStickersProps) { - + diff --git a/src/app/features/settings/emojis-stickers/GlobalPacks.tsx b/src/app/features/settings/emojis-stickers/GlobalPacks.tsx index 38647b13..a9288728 100644 --- a/src/app/features/settings/emojis-stickers/GlobalPacks.tsx +++ b/src/app/features/settings/emojis-stickers/GlobalPacks.tsx @@ -43,7 +43,6 @@ import { allRoomsAtom } from '../../../state/room-list/roomList'; import { AccountDataEvent } from '../../../../types/matrix/accountData'; import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback'; import { stopPropagation } from '../../../utils/keyboard'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; function GlobalPackSelector({ packs, @@ -369,7 +368,6 @@ export function GlobalPacks({ onViewPack }: GlobalPacksProps) { {removed ? ( ) : ( ; @@ -496,7 +495,6 @@ function DateHint({ hasChanges, handleReset }: DateHintProps) { > {hasChanges ? ( ) : ( - + diff --git a/src/app/features/settings/notifications/KeywordMessages.tsx b/src/app/features/settings/notifications/KeywordMessages.tsx index b77cae21..f3af28ae 100644 --- a/src/app/features/settings/notifications/KeywordMessages.tsx +++ b/src/app/features/settings/notifications/KeywordMessages.tsx @@ -15,7 +15,6 @@ import { } from '../../../hooks/useNotificationMode'; import { NotificationModeSwitcher } from './NotificationModeSwitcher'; import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; const NOTIFY_MODE_OPS: NotificationModeOptions = { highlight: true, @@ -76,7 +75,6 @@ function KeywordInput() { keyword && !addingKeyword && ( void; @@ -24,7 +23,7 @@ export function Notifications({ requestClose }: NotificationsProps) { - + diff --git a/src/app/features/soundscape/device.ts b/src/app/features/soundscape/device.ts deleted file mode 100644 index ecdf1593..00000000 --- a/src/app/features/soundscape/device.ts +++ /dev/null @@ -1,12 +0,0 @@ -export interface DeviceHints { - deviceMemory?: number; - hardwareConcurrency?: number; -} - -/** - * Off on weak phones. The thresholds are placeholders: no phone has been measured (grammar - * section 7, item 4). Unknown hints (Safari reports neither) do not count as weak. - */ -export const isWeakDevice = ({ deviceMemory, hardwareConcurrency }: DeviceHints): boolean => - (deviceMemory !== undefined && deviceMemory < 4) || - (hardwareConcurrency !== undefined && hardwareConcurrency < 4); diff --git a/src/app/features/soundscape/frame.ts b/src/app/features/soundscape/frame.ts deleted file mode 100644 index 947d2bb5..00000000 --- a/src/app/features/soundscape/frame.ts +++ /dev/null @@ -1,108 +0,0 @@ -// The activity frame of Aqua's soundscape grammar (AquaSynth docs/soundscape-grammar, grammar head -// 0091d01, section 2). The Heimdall session produces it; this file only reads it. Shape follows -// heimdall-body:follow_up:ratatoskr-creature-projection-v2 as the grammar relays it. The human -// kind subset (Idle/Working/Speaking) below is PROVISIONAL: still proposed, not ruled, until -// Bifrost's steward cuts the list. - -export type Estate = 'human' | 'mind' | 'persona'; -export type Kind = 'Idle' | 'Reading' | 'Thinking' | 'Working' | 'Speaking' | 'Waiting' | 'Alert'; -export type Energy = 'Low' | 'Mid' | 'High' | 'Peak'; -export type Size = 'S' | 'M' | 'L'; -export type Override = 'None' | 'Muted'; - -interface FrameBase { - mind: string; - estate: Estate; - override: Override; - seq: number; - /** Producer observation time, whole seconds (grammar: 1 s resolution). */ - at: number; -} -/** O1: a neutral frame carries no size, kind or energy; it is not an Idle and nothing reads one. */ -export interface NeutralFrame extends FrameBase { - neutral: true; - size?: undefined; - kind?: undefined; - energy?: undefined; -} -export interface LiveFrame extends FrameBase { - neutral: false; - size: Size; - kind: Kind; - energy: Energy; -} -export type ActivityFrame = NeutralFrame | LiveFrame; - -const ESTATES: readonly Estate[] = ['human', 'mind', 'persona']; -const KINDS: readonly Kind[] = [ - 'Idle', - 'Reading', - 'Thinking', - 'Working', - 'Speaking', - 'Waiting', - 'Alert', -]; -const ENERGIES: readonly Energy[] = ['Low', 'Mid', 'High', 'Peak']; -const SIZES: readonly Size[] = ['S', 'M', 'L']; - -/** Grammar S2 (proposed, unmeasured): a frame older than this is absent. */ -export const STALE_AFTER_S = 10; - -const oneOf = (set: readonly T[], v: unknown): T | undefined => - set.find((s) => s === v); - -/** PROVISIONAL (grammar section 2, awaiting the projection-v2 field list): a human's kinds. */ -export const HUMAN_KINDS: readonly Kind[] = ['Idle', 'Working', 'Speaking']; - -/** Estate clamp, only ever revealing less: a human's out-of-subset or omitted kind is Idle. */ -const clampKind = (estate: Estate, kind: unknown): Kind | undefined => - estate === 'human' ? oneOf(HUMAN_KINDS, kind) ?? 'Idle' : oneOf(KINDS, kind); - -/** A human's energy is three buckets: Peak reads as High. */ -const clampEnergy = (estate: Estate, energy: Energy): Energy => - estate === 'human' && energy === 'Peak' ? 'High' : energy; - -/** - * Read an untrusted frame. Only the grammar's fields survive: any other key (a weight, a vote, a - * room id) is dropped, so a consumer cannot be steered by data the grammar does not define (A3). - * `neutral` is read first: a neutral frame yields no size, kind or energy even if the producer sent - * them (O1). Returns undefined for anything malformed; the caller treats that as no frame (A4). - */ -export const readFrame = (raw: unknown): ActivityFrame | undefined => { - if (typeof raw !== 'object' || raw === null) return undefined; - const r = raw as Record; - if (typeof r.neutral !== 'boolean') return undefined; - const estate = oneOf(ESTATES, r.estate); - const override = - r.override === undefined ? 'None' : oneOf(['None', 'Muted'] as const, r.override); - if (!estate || !override) return undefined; - if (typeof r.mind !== 'string' || r.mind === '') return undefined; - if (!Number.isInteger(r.seq) || !Number.isFinite(r.at)) return undefined; - const base = { mind: r.mind, estate, override, seq: r.seq as number, at: r.at as number }; - if (r.neutral) return { ...base, neutral: true }; - const kind = clampKind(estate, r.kind); - const energy = oneOf(ENERGIES, r.energy); - const size = oneOf(SIZES, r.size); - if (!kind || !energy || !size) return undefined; - return { ...base, neutral: false, size, kind, energy: clampEnergy(estate, energy) }; -}; - -/** Latest frame per mind (S1: consumers drop seq <= last). */ -export class FrameTable { - private frames = new Map(); - - offer(raw: unknown): boolean { - const f = readFrame(raw); - if (!f) return false; - const last = this.frames.get(f.mind); - if (last && f.seq <= last.seq) return false; - this.frames.set(f.mind, f); - return true; - } - - /** Frames not stale at `nowS`; a missing or stale frame is simply absent (A4), not neutral. */ - fresh(nowS: number): ActivityFrame[] { - return [...this.frames.values()].filter((f) => nowS - f.at <= STALE_AFTER_S); - } -} diff --git a/src/app/features/soundscape/scene.ts b/src/app/features/soundscape/scene.ts deleted file mode 100644 index 027cc27a..00000000 --- a/src/app/features/soundscape/scene.ts +++ /dev/null @@ -1,8 +0,0 @@ -import type { ActivityFrame, Size } from './frame'; - -/** Placeholders owned by the orbit renderer, not the frame (grammar, Estate section). Unmeasured. */ -export const PLACEHOLDER_SIZE_SCALE: Record = { S: 0.7, M: 1, L: 1.4 }; - -/** O1: a neutral participant gets no orbit. There is no neutral pose; it is not in the list. */ -export const drawnCreatures = (frames: readonly ActivityFrame[]): ActivityFrame[] => - frames.filter((f) => !f.neutral); diff --git a/src/app/features/soundscape/socket.ts b/src/app/features/soundscape/socket.ts deleted file mode 100644 index e1d23010..00000000 --- a/src/app/features/soundscape/socket.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { FrameTable } from './frame'; -import { drawnCreatures } from './scene'; -import { planVoices, type SoundscapePrefs, type VoiceCommand } from './voices'; -import { isWeakDevice, type DeviceHints } from './device'; - -/** - * Where frames come from is `ratatoskr:question:activity-feed-source`, still open. Until the - * Heimdall session feed exists the only source is `silentSource`. A source never reads a room's - * member list (A1): being in a room says nothing about being active. - */ -export interface ActivitySource { - subscribe(onFrame: (raw: unknown) => void): () => void; -} -const noop = () => undefined; -export const silentSource: ActivitySource = { subscribe: () => noop }; - -/** Receives the plan. No audio assets exist yet, so nothing in this repo sounds. */ -export interface VoiceSink { - play(commands: readonly VoiceCommand[]): void; -} - -export interface AudioSocketDeps { - source: ActivitySource; - sink: VoiceSink; - prefs: () => SoundscapePrefs; - device: () => DeviceHints; - /** Whole seconds. */ - nowS: () => number; -} - -export const createAudioSocket = (deps: AudioSocketDeps) => { - const table = new FrameTable(); - const unsubscribe = deps.source.subscribe((raw) => table.offer(raw)); - return { - /** Called by the scheduler tick; a hidden page simply stops calling it (S5). */ - tick(): VoiceCommand[] { - const prefs = deps.prefs(); - const effective = { ...prefs, enabled: prefs.enabled && !isWeakDevice(deps.device()) }; - const commands = planVoices(table.fresh(deps.nowS()), effective); - deps.sink.play(commands); - return commands; - }, - /** What the orbit renderer draws: the same table, neutral removed. */ - drawn: () => drawnCreatures(table.fresh(deps.nowS())), - close: unsubscribe, - }; -}; diff --git a/src/app/features/soundscape/soundscape.test.ts b/src/app/features/soundscape/soundscape.test.ts deleted file mode 100644 index 294456a1..00000000 --- a/src/app/features/soundscape/soundscape.test.ts +++ /dev/null @@ -1,233 +0,0 @@ -import { describe, expect, it, vi } from 'vitest'; -import { FrameTable, readFrame, STALE_AFTER_S, type ActivityFrame, type LiveFrame } from './frame'; -import { drawnCreatures, PLACEHOLDER_SIZE_SCALE } from './scene'; -import { DEFAULT_VOICE_CAP, planVoices, type SoundscapePrefs } from './voices'; -import { isWeakDevice } from './device'; -import { createAudioSocket, silentSource, type ActivitySource } from './socket'; - -const frame = (o: Partial = {}): LiveFrame => ({ - mind: 'void', - estate: 'mind', - kind: 'Working', - energy: 'Mid', - size: 'M', - neutral: false, - override: 'None', - seq: 1, - at: 100, - ...o, -}); -const neutralFrame = (o: Partial = {}): ActivityFrame => - ({ ...frame(), ...o, neutral: true } as unknown as ActivityFrame); -/** A raw frame as a producer sends it, with the named keys omitted. */ -const without = (f: object, ...keys: string[]) => - Object.fromEntries(Object.entries(f).filter(([k]) => !keys.includes(k))); -const noop = () => undefined; -const on: SoundscapePrefs = { enabled: true, muted: false, volume: 0.5, voiceCap: 4 }; - -describe('neutral overrides everything', () => { - it('draws nothing and sounds nothing for any kind, energy, size or estate', () => { - const cases = (['human', 'mind', 'persona'] as const).flatMap((estate) => - (['Speaking', 'Alert', 'Working'] as const).flatMap((kind) => - (['High', 'Peak'] as const).flatMap((energy) => - (['S', 'M', 'L'] as const).map((size) => neutralFrame({ estate, kind, energy, size })) - ) - ) - ); - expect(cases).toHaveLength(54); - cases.forEach((f) => { - expect(drawnCreatures([f])).toEqual([]); - expect(planVoices([f], on)).toEqual([]); - }); - }); - it('is not the same as an absent frame: absent reads as idle, neutral as hidden', () => { - const t = new FrameTable(); - t.offer(frame({ at: 100 })); - expect(drawnCreatures(t.fresh(100 + STALE_AFTER_S + 1))).toEqual([]); - expect(drawnCreatures(t.fresh(100)).length).toBe(1); - }); -}); - -describe('neutral is read first', () => { - it('yields no size, kind or energy, even when the producer sent them', () => { - (['human', 'mind', 'persona'] as const).forEach((estate) => { - const f = readFrame({ - ...frame({ estate, kind: 'Speaking', energy: 'High' }), - neutral: true, - }); - expect(f).toBeDefined(); - expect(f?.neutral).toBe(true); - expect(f?.size).toBeUndefined(); - expect(Object.keys(f ?? {})).not.toContain('size'); - expect(f?.kind).toBeUndefined(); - expect(f?.energy).toBeUndefined(); - expect(Object.keys(f ?? {})).not.toContain('kind'); - expect(Object.keys(f ?? {})).not.toContain('energy'); - }); - }); - it('a neutral human with kind omitted is not an Idle', () => { - const bare = without(frame({ estate: 'human' }), 'kind', 'energy'); - const f = readFrame({ ...bare, neutral: true }); - expect(f?.kind).toBeUndefined(); - expect(drawnCreatures([f as ActivityFrame])).toEqual([]); - expect(planVoices([f as ActivityFrame], on)).toEqual([]); - }); -}); - -describe('human kinds are the provisional subset', () => { - it.each(['Reading', 'Thinking', 'Waiting', 'Alert'] as const)('clamps %s to Idle', (kind) => { - expect(readFrame(frame({ estate: 'human', kind }))?.kind).toBe('Idle'); - }); - it('keeps Idle, Working and Speaking', () => { - (['Idle', 'Working', 'Speaking'] as const).forEach((kind) => - expect(readFrame(frame({ estate: 'human', kind }))?.kind).toBe(kind) - ); - }); - it('an omitted kind is Idle for a non-neutral human only', () => { - const noKind = without(frame({ estate: 'human' }), 'kind'); - expect(readFrame(noKind)?.kind).toBe('Idle'); - expect(readFrame({ ...noKind, neutral: true })?.kind).toBeUndefined(); - }); - it('minds and personas keep all seven kinds, and omitted is malformed for them', () => { - (['mind', 'persona'] as const).forEach((estate) => { - (['Idle', 'Reading', 'Thinking', 'Working', 'Speaking', 'Waiting', 'Alert'] as const).forEach( - (kind) => expect(readFrame(frame({ estate, kind }))?.kind).toBe(kind) - ); - const noKind = without(frame({ estate }), 'kind'); - expect(readFrame(noKind)).toBeUndefined(); - }); - }); -}); - -describe('human energy is clamped to three buckets by the consumer', () => { - it('turns Peak into High for humans only', () => { - expect(readFrame(frame({ estate: 'human', energy: 'Peak' }))?.energy).toBe('High'); - expect(readFrame(frame({ estate: 'mind', energy: 'Peak' }))?.energy).toBe('Peak'); - expect(readFrame(frame({ estate: 'persona', energy: 'Peak' }))?.energy).toBe('Peak'); - }); - it('keeps the clamp through the voice plan', () => { - const t = new FrameTable(); - t.offer(frame({ estate: 'human', energy: 'Peak' })); - expect(planVoices(t.fresh(100), on)[0].energy).toBe('High'); - }); -}); - -describe('activity is a stub, never the room member list', () => { - it('the silent source and the socket yield nothing, however many members a room has', () => { - const members = ['@a:x', '@b:x', '@c:x']; - const sock = createAudioSocket({ - source: silentSource, - sink: { play: noop }, - prefs: () => on, - device: () => ({}), - nowS: () => 100, - }); - expect(members.length).toBeGreaterThan(0); - expect(sock.tick()).toEqual([]); - expect(sock.drawn()).toEqual([]); - }); - it('only frames the source pushes produce voices', () => { - const pushes: ((raw: unknown) => void)[] = []; - const source: ActivitySource = { - subscribe: (cb) => { - pushes.push(cb); - return noop; - }, - }; - const sock = createAudioSocket({ - source, - sink: { play: noop }, - prefs: () => on, - device: () => ({}), - nowS: () => 100, - }); - pushes[0](frame({ mind: 'aqua' })); - expect(sock.tick().map((v) => v.mind)).toEqual(['aqua']); - }); -}); - -describe('no vote weights', () => { - it('drops fields the grammar does not define, and the plan carries only user volume as gain', () => { - const f = readFrame({ ...frame(), weight: 9, votes: 40, roomId: '!r:x', brief: 'secret' }); - expect(Object.keys(f ?? {}).sort()).toEqual( - ['at', 'energy', 'estate', 'kind', 'mind', 'neutral', 'override', 'seq', 'size'].sort() - ); - const t = new FrameTable(); - t.offer({ ...frame(), weight: 9 }); - expect(planVoices(t.fresh(100), on)[0].gain).toBe(0.5); - }); -}); - -describe('size scales are placeholders', () => { - it('live in the renderer table, not in the frame, and change nothing about voices', () => { - expect(PLACEHOLDER_SIZE_SCALE).toEqual({ S: 0.7, M: 1, L: 1.4 }); - const s = planVoices([frame({ size: 'S' })], on); - const l = planVoices([frame({ size: 'L' })], on); - expect(s).toEqual(l); - }); -}); - -describe('socket defaults and limits', () => { - it('ships off, muted, with the proposed cap', async () => { - vi.stubGlobal('localStorage', { getItem: () => null }); - const { getSettings } = await import('../../state/settings'); - const s = getSettings(); - expect(s.soundscapeEnabled).toBe(false); - expect(s.soundscapeMuted).toBe(true); - expect(s.soundscapeVoiceCap).toBe(DEFAULT_VOICE_CAP); - }); - it('master mute, disabled flag and zero volume all silence', () => { - const f = [frame()]; - expect(planVoices(f, { ...on, muted: true })).toEqual([]); - expect(planVoices(f, { ...on, enabled: false })).toEqual([]); - expect(planVoices(f, { ...on, volume: 0 })).toEqual([]); - }); - it('caps voices, dropping the lowest energy first', () => { - const f = ['a', 'b', 'c', 'd', 'e'].map((mind, i) => - frame({ mind, energy: (['Low', 'Mid', 'High', 'Peak', 'Mid'] as const)[i] }) - ); - const voices = planVoices(f, { ...on, voiceCap: 4 }).map((v) => v.mind); - expect(voices).toHaveLength(4); - expect(voices).not.toContain('a'); - }); - it('Muted silences the voice but the creature is still drawn; Idle/Waiting are silent', () => { - const f = [frame({ override: 'Muted' }), frame({ mind: 'x', kind: 'Idle' })]; - expect(planVoices(f, on)).toEqual([]); - expect(drawnCreatures(f)).toHaveLength(2); - }); - it('is off on weak phones even when the flag is on, and unknown hints are not weak', () => { - expect(isWeakDevice({ deviceMemory: 2 })).toBe(true); - expect(isWeakDevice({ hardwareConcurrency: 2 })).toBe(true); - expect(isWeakDevice({})).toBe(false); - const played: number[] = []; - const sock = createAudioSocket({ - source: { - subscribe: (cb) => { - cb(frame()); - return noop; - }, - }, - sink: { play: (c) => played.push(c.length) }, - prefs: () => on, - device: () => ({ deviceMemory: 1 }), - nowS: () => 100, - }); - expect(sock.tick()).toEqual([]); - expect(played).toEqual([0]); - }); - it('drops frames with seq <= last, and malformed frames', () => { - const t = new FrameTable(); - expect(t.offer(frame({ seq: 5 }))).toBe(true); - expect(t.offer(frame({ seq: 5 }))).toBe(false); - expect(t.offer(frame({ seq: 4 }))).toBe(false); - expect(t.offer({ ...frame(), kind: 'Dancing' })).toBe(false); - }); -}); - -describe('neutral carries no size', () => { - it('reads without a size, and a live frame without one is malformed', () => { - const raw = frame(); - expect(readFrame({ ...without(raw, 'size', 'kind', 'energy'), neutral: true })).toBeDefined(); - expect(readFrame(without(raw, 'size'))).toBeUndefined(); - }); -}); diff --git a/src/app/features/soundscape/voices.ts b/src/app/features/soundscape/voices.ts deleted file mode 100644 index 676ae853..00000000 --- a/src/app/features/soundscape/voices.ts +++ /dev/null @@ -1,51 +0,0 @@ -import type { ActivityFrame, Energy, Kind, LiveFrame } from './frame'; - -/** Grammar V3 (proposed, unmeasured): voices audible at once. */ -export const DEFAULT_VOICE_CAP = 4; - -/** Local listener preferences. Never written back into a frame (O3). */ -export interface SoundscapePrefs { - /** The feature flag. Default off. */ - enabled: boolean; - /** Master mute. Default on. */ - muted: boolean; - /** 0..1 */ - volume: number; - voiceCap: number; -} - -export interface VoiceCommand { - mind: string; - kind: Kind; - energy: Energy; - gain: number; -} - -const ENERGY_RANK: Record = { Low: 0, Mid: 1, High: 2, Peak: 3 }; -/** Grammar section 3: Idle and Waiting default silent. */ -const SILENT_KINDS: ReadonlySet = new Set(['Idle', 'Waiting']); - -const clamp01 = (v: number) => (Number.isFinite(v) ? Math.min(1, Math.max(0, v)) : 0); - -/** - * Which voices speak now. Neutral overrides everything (O1); `Muted` silences one Mind (O2); - * over the cap the lowest energy drops first (V3, ties by mind id so the result is stable). - * Identity is the mind id only (V1); `gain` is the user's volume, not a vote weight. - * Lead exemption in V3 is not implemented: the grammar does not say how a lead is chosen. - */ -export const planVoices = ( - frames: readonly ActivityFrame[], - prefs: SoundscapePrefs -): VoiceCommand[] => { - if (!prefs.enabled || prefs.muted) return []; - const gain = clamp01(prefs.volume); - if (gain === 0) return []; - const cap = Math.max(0, Math.floor(prefs.voiceCap)); - return frames - .filter( - (f): f is LiveFrame => !f.neutral && f.override !== 'Muted' && !SILENT_KINDS.has(f.kind) - ) - .sort((a, b) => ENERGY_RANK[b.energy] - ENERGY_RANK[a.energy] || a.mind.localeCompare(b.mind)) - .slice(0, cap) - .map((f) => ({ mind: f.mind, kind: f.kind, energy: f.energy, gain })); -}; diff --git a/src/app/features/space-settings/SpaceSettings.tsx b/src/app/features/space-settings/SpaceSettings.tsx index 1030972f..b5fefc93 100644 --- a/src/app/features/space-settings/SpaceSettings.tsx +++ b/src/app/features/space-settings/SpaceSettings.tsx @@ -17,7 +17,6 @@ import { Members } from '../common-settings/members'; import { DeveloperTools } from '../common-settings/developer-tools'; import { General } from './general'; import { Permissions } from './permissions'; -import { PhoneHit } from '../../styles/PhoneHit.css'; type SpaceSettingsMenuItem = { page: SpaceSettingsPage; @@ -118,7 +117,7 @@ export function SpaceSettings({ initialPage, requestClose }: SpaceSettingsProps) {screenSize === ScreenSize.Mobile && ( - + )} diff --git a/src/app/features/space-settings/general/General.tsx b/src/app/features/space-settings/general/General.tsx index e99a4906..72040632 100644 --- a/src/app/features/space-settings/general/General.tsx +++ b/src/app/features/space-settings/general/General.tsx @@ -13,7 +13,6 @@ import { } from '../../common-settings/general'; import { useRoomCreators } from '../../../hooks/useRoomCreators'; import { useRoomPermissions } from '../../../hooks/useRoomPermissions'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; type GeneralProps = { requestClose: () => void; @@ -34,7 +33,7 @@ export function General({ requestClose }: GeneralProps) { - + diff --git a/src/app/features/space-settings/permissions/Permissions.tsx b/src/app/features/space-settings/permissions/Permissions.tsx index d513dda9..7572a71b 100644 --- a/src/app/features/space-settings/permissions/Permissions.tsx +++ b/src/app/features/space-settings/permissions/Permissions.tsx @@ -9,7 +9,6 @@ import { usePermissionGroups } from './usePermissionItems'; import { PermissionGroups, Powers, PowersEditor } from '../../common-settings/permissions'; import { useRoomCreators } from '../../../hooks/useRoomCreators'; import { useRoomPermissions } from '../../../hooks/useRoomPermissions'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; type PermissionsProps = { requestClose: () => void; @@ -46,7 +45,7 @@ export function Permissions({ requestClose }: PermissionsProps) { - + diff --git a/src/app/hooks/useMemberPowerTag.ts b/src/app/hooks/useMemberPowerTag.ts index 68051749..31e52aa0 100644 --- a/src/app/hooks/useMemberPowerTag.ts +++ b/src/app/hooks/useMemberPowerTag.ts @@ -6,7 +6,6 @@ import { MemberPowerTag, MemberPowerTagIcon } from '../../types/matrix/room'; import { useRoomCreatorsTag } from './useRoomCreatorsTag'; import { ThemeKind } from './useTheme'; import { accessibleColor } from '../plugins/color'; -import { inkForState, type SkyInk } from '../features/scene/skyInk'; export type GetMemberPowerTag = (userId: string) => MemberPowerTag; @@ -45,29 +44,23 @@ export const getPowerTagIconSrc = ( export const useAccessiblePowerTagColors = ( themeKind: ThemeKind, creatorsTag: MemberPowerTag, - powerLevelTags: PowerLevelTags, - skyInk?: SkyInk + powerLevelTags: PowerLevelTags ): Map => { const accessibleColors: Map = useMemo(() => { const colors: Map = new Map(); - // Over the scene a name wears the sky state's ink (skyInk.ts) in place of the theme's accessible colour's own step. - const ink = (color: string) => { - const accessible = accessibleColor(themeKind, color); - return skyInk ? inkForState(accessible, skyInk) : accessible; - }; if (creatorsTag.color) { - colors.set(creatorsTag.color, ink(creatorsTag.color)); + colors.set(creatorsTag.color, accessibleColor(themeKind, creatorsTag.color)); } Object.values(powerLevelTags).forEach((tag) => { const { color } = tag; if (!color) return; - colors.set(color, ink(color)); + colors.set(color, accessibleColor(themeKind, color)); }); return colors; - }, [powerLevelTags, creatorsTag, themeKind, skyInk]); + }, [powerLevelTags, creatorsTag, themeKind]); return accessibleColors; }; diff --git a/src/app/hooks/useSceneView.ts b/src/app/hooks/useSceneView.ts index a1f33317..bda6db85 100644 --- a/src/app/hooks/useSceneView.ts +++ b/src/app/hooks/useSceneView.ts @@ -55,7 +55,7 @@ export function usePlaceList(): PlaceListing[] | undefined { /** The manifest of the place being drawn (the viewer's choice, else the config's, else the index's default: skyPlace.ts) when the ridge scene is on and it has loaded (memoised by `loadManifest`, so this fetches nothing the scene did not). */ export function useRidgeManifest(): RidgeManifest | undefined { const config = useClientConfig().backgroundScene; - const ridgeOn = !!config && config.style !== 'raymarch'; + const ridgeOn = !!config; const choice = usePlaceChoice(); const [manifest, setManifest] = useState(); useEffect(() => { diff --git a/src/app/pages/ThemeManager.tsx b/src/app/pages/ThemeManager.tsx index 092ace6c..7b753bdb 100644 --- a/src/app/pages/ThemeManager.tsx +++ b/src/app/pages/ThemeManager.tsx @@ -10,8 +10,6 @@ import { } from '../hooks/useTheme'; import { useSetting } from '../state/hooks/settings'; import { settingsAtom } from '../state/settings'; -import { labelInk } from '../features/scene/skyInk'; -import { SKY_LABEL_INK } from '../features/scene/skyLabelInk'; export function UnAuthRouteThemeManager() { // Signed-out pages are Midnight Sky unless the sky state picks otherwise; they ignore the @@ -31,17 +29,6 @@ export function AuthRouteThemeManager({ children }: { children: ReactNode }) { const activeTheme = useActiveTheme(); const [monochromeMode] = useSetting(settingsAtom, 'monochromeMode'); const skyInk = useSceneInk(); - const labels = skyInk && labelInk(skyInk); - - // The sky's label ink where it differs from the theme's (skyInk.ts); unset, the theme's ink stands. - useEffect(() => { - const root = document.documentElement; - if (labels) root.style.setProperty(SKY_LABEL_INK, labels); - else root.style.removeProperty(SKY_LABEL_INK); - return () => { - root.style.removeProperty(SKY_LABEL_INK); - }; - }, [labels]); useEffect(() => { document.body.className = ''; diff --git a/src/app/pages/auth/ServerPicker.tsx b/src/app/pages/auth/ServerPicker.tsx index 393cf34e..a2a78106 100644 --- a/src/app/pages/auth/ServerPicker.tsx +++ b/src/app/pages/auth/ServerPicker.tsx @@ -23,7 +23,6 @@ import FocusTrap from 'focus-trap-react'; import { useDebounce } from '../../hooks/useDebounce'; import { stopPropagation } from '../../utils/keyboard'; -import { PhoneHit } from '../../styles/PhoneHit.css'; export function ServerPicker({ server, @@ -130,7 +129,6 @@ export function ServerPicker({ } > { - const filePath = `${process.cwd()}/src/app/pages/auth/styles.css.ts`; - const { source } = await compile({ filePath, cwd: process.cwd(), identOption: 'debug' }); - const code = await processVanillaFile({ source, filePath, identOption: 'debug' }); - const encoded = (code.match(/source=#([A-Za-z0-9+/=]+)/) as RegExpMatchArray)[1]; - return zlib.gunzipSync(Buffer.from(encoded, 'base64')).toString(); -}; -const declarations = (css: string, selector: string) => - [...css.matchAll(/^([^{}\n]+) \{\n([^}]*)\}/gm)] - .filter((m) => m[1] === selector) - .map((m) => - m[2] - .split('\n') - .map((l) => l.trim().replace(/;$/, '')) - .filter(Boolean) - ); - -describe('the sign-in footer band, as emitted', () => { - const over = `:root[data-scene] .${AuthFooter}`; - - it('is one rule over the scene, so no later rule can override its mask', async () => { - expect(declarations(await emitted(), over)).toHaveLength(1); - }); - - it('puts the plate fill before the color-mix tint, so a browser without color-mix keeps the fill', async () => { - const [rule] = declarations(await emitted(), over); - const fills = rule.filter((d) => d.startsWith('background-color:')); - expect(fills).toHaveLength(2); - expect(fills[0]).toBe(`background-color: var(--sky-bubble, ${SKY_PLATE_FALLBACK.fill})`); - }); - - it('tints with FOOTER_TINT of the plate fill, the amount skyTheme.test.ts checks the ink against', async () => { - const [rule] = declarations(await emitted(), over); - const fills = rule.filter((d) => d.startsWith('background-color:')); - expect(fills[1]).toBe( - `background-color: color-mix(in srgb, var(--sky-bubble, ${SKY_PLATE_FALLBACK.fill}) ${ - FOOTER_TINT * 100 - }%, transparent)` - ); - }); - - it("is inked with the plate's ink, on the footer and on its links", async () => { - const css = await emitted(); - const ink = `color: var(--sky-bubble-text, ${SKY_PLATE_FALLBACK.text})`; - expect(declarations(css, over)[0].filter((d) => d.startsWith('color:'))).toEqual([ink]); - expect(declarations(css, `${over} a`)).toEqual([[ink]]); - }); - - it('blurs what is behind it by 12px, the radius of the chat bubbles', async () => { - const [rule] = declarations(await emitted(), over); - expect(rule.filter((d) => d.startsWith('backdrop-filter'))).toEqual([ - 'backdrop-filter: blur(12px)', - ]); - }); - - it('declares exactly these properties, so nothing else (a shadow, a stray override) rides along', async () => { - const [rule] = declarations(await emitted(), over); - // -webkit-backdrop-filter is the one prefixed property, for Safari 14; it must blur exactly as the standard one does. - const blur = (prop: string) => - rule - .find((d) => d.startsWith(`${prop}:`)) - ?.split(':')[1] - .trim(); - expect(blur('-webkit-backdrop-filter')).toBe(blur('backdrop-filter')); - expect(rule.map((d) => d.slice(0, d.indexOf(':'))).sort()).toEqual([ - '-webkit-backdrop-filter', - 'backdrop-filter', - 'background-color', - 'background-color', - 'color', - 'mask-composite', - 'mask-image', - 'padding-bottom', - 'padding-top', - ]); - }); - - it('fades along both axes over a soft ramp, not a hard edge', async () => { - const [rule] = declarations(await emitted(), over); - const mask = rule.find((d) => d.startsWith('mask-image:')) ?? ''; - expect(rule).toContain('mask-composite: intersect'); - ['bottom', 'right'].forEach((axis) => { - const ramp = mask.match( - new RegExp( - `linear-gradient\\(to ${axis}, transparent, #000 (\\d+)px, #000 calc\\(100% - (\\d+)px\\), transparent\\)` - ) - ); - expect(ramp).not.toBeNull(); - // Each end ramps from clear to opaque over at least 8px. - expect(Number(ramp?.[1])).toBeGreaterThanOrEqual(8); - expect(Number(ramp?.[2])).toBeGreaterThanOrEqual(8); - }); - }); - - it('has no border or radius, in the scene rule or in the base footer rule', async () => { - const css = await emitted(); - const [rule] = declarations(css, over); - const base = declarations(css, `.${AuthFooter}`); - expect(base).toHaveLength(1); - [rule, base[0]].forEach((r) => { - expect(r.filter((d) => /^(border|outline)/.test(d))).toEqual([]); - }); - // The base rule is only the footer's padding: nothing visible (a shadow, a fill) is hidden outside the scene rule. - expect(base[0].map((d) => d.slice(0, d.indexOf(':')))).toEqual(['padding']); - }); -}); diff --git a/src/app/pages/auth/login/PasswordLoginForm.tsx b/src/app/pages/auth/login/PasswordLoginForm.tsx index 63c28577..e067f4ee 100644 --- a/src/app/pages/auth/login/PasswordLoginForm.tsx +++ b/src/app/pages/auth/login/PasswordLoginForm.tsx @@ -41,7 +41,6 @@ import { getResetPasswordPath } from '../../pathUtils'; import { stopPropagation } from '../../../utils/keyboard'; import { useSoftLogout, withSoftLogoutDevice } from '../../../state/softLogout'; import { useMasAccountUrl } from '../masAccount'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; function UsernameHint({ server }: { server: string }) { const [anchor, setAnchor] = useState(); @@ -97,7 +96,6 @@ function UsernameHint({ server }: { server: string }) { } > {(onBack) => ( - + )} diff --git a/src/app/pages/client/explore/Explore.tsx b/src/app/pages/client/explore/Explore.tsx index 6944c9f7..afb9103f 100644 --- a/src/app/pages/client/explore/Explore.tsx +++ b/src/app/pages/client/explore/Explore.tsx @@ -37,7 +37,6 @@ import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback'; import { useNavToActivePathMapper } from '../../../hooks/useNavToActivePathMapper'; import { PageNav, PageNavContent, PageNavHeader } from '../../../components/page'; import { stopPropagation } from '../../../utils/keyboard'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; export function AddServer() { const mx = useMatrixClient(); @@ -98,7 +97,6 @@ export function AddServer() { Add Server setDialog(false)} radii="300" diff --git a/src/app/pages/client/explore/Featured.tsx b/src/app/pages/client/explore/Featured.tsx index c28fad0a..f056cbb5 100644 --- a/src/app/pages/client/explore/Featured.tsx +++ b/src/app/pages/client/explore/Featured.tsx @@ -18,7 +18,6 @@ import * as css from './style.css'; import { useRoomNavigate } from '../../../hooks/useRoomNavigate'; import { ScreenSize, useScreenSizeContext } from '../../../hooks/useScreenSize'; import { BackRouteHandler } from '../../../components/BackRouteHandler'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; export function FeaturedRooms() { const { featuredCommunities } = useClientConfig(); @@ -34,7 +33,7 @@ export function FeaturedRooms() { {(onBack) => ( - + )} diff --git a/src/app/pages/client/explore/Server.tsx b/src/app/pages/client/explore/Server.tsx index 036c6488..48f267cc 100644 --- a/src/app/pages/client/explore/Server.tsx +++ b/src/app/pages/client/explore/Server.tsx @@ -45,7 +45,6 @@ import { getMxIdServer } from '../../../utils/matrix'; import { stopPropagation } from '../../../utils/keyboard'; import { ScreenSize, useScreenSizeContext } from '../../../hooks/useScreenSize'; import { BackRouteHandler } from '../../../components/BackRouteHandler'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; const useServerSearchParams = (searchParams: URLSearchParams): ExploreServerPathSearchParams => useMemo( @@ -500,7 +499,7 @@ export function PublicRooms() { {screenSize === ScreenSize.Mobile && ( {(onBack) => ( - + )} diff --git a/src/app/pages/client/home/CreateRoom.tsx b/src/app/pages/client/home/CreateRoom.tsx index 8e277889..fddd75aa 100644 --- a/src/app/pages/client/home/CreateRoom.tsx +++ b/src/app/pages/client/home/CreateRoom.tsx @@ -12,7 +12,6 @@ import { ScreenSize, useScreenSizeContext } from '../../../hooks/useScreenSize'; import { BackRouteHandler } from '../../../components/BackRouteHandler'; import { CreateRoomForm } from '../../../features/create-room'; import { useRoomNavigate } from '../../../hooks/useRoomNavigate'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; export function HomeCreateRoom() { const screenSize = useScreenSizeContext(); @@ -26,7 +25,7 @@ export function HomeCreateRoom() { {(onBack) => ( - + )} diff --git a/src/app/pages/client/home/Search.tsx b/src/app/pages/client/home/Search.tsx index aa454d2c..d5ddfb77 100644 --- a/src/app/pages/client/home/Search.tsx +++ b/src/app/pages/client/home/Search.tsx @@ -5,7 +5,6 @@ import { MessageSearch } from '../../../features/message-search'; import { useHomeRooms } from './useHomeRooms'; import { ScreenSize, useScreenSizeContext } from '../../../hooks/useScreenSize'; import { BackRouteHandler } from '../../../components/BackRouteHandler'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; export function HomeSearch() { const scrollRef = useRef(null); @@ -20,7 +19,7 @@ export function HomeSearch() { {screenSize === ScreenSize.Mobile && ( {(onBack) => ( - + )} diff --git a/src/app/pages/client/inbox/Invites.tsx b/src/app/pages/client/inbox/Invites.tsx index 4d1580af..ca26bac3 100644 --- a/src/app/pages/client/inbox/Invites.tsx +++ b/src/app/pages/client/inbox/Invites.tsx @@ -63,7 +63,6 @@ import { useIgnoredUsers } from '../../../hooks/useIgnoredUsers'; import { useReportRoomSupported } from '../../../hooks/useReportRoomSupported'; import { useSetting } from '../../../state/hooks/settings'; import { settingsAtom } from '../../../state/settings'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; const COMPACT_CARD_WIDTH = 548; @@ -746,7 +745,7 @@ export function Invites() { {screenSize === ScreenSize.Mobile && ( {(onBack) => ( - + )} diff --git a/src/app/pages/client/inbox/Notifications.tsx b/src/app/pages/client/inbox/Notifications.tsx index 8fddba44..9592224f 100644 --- a/src/app/pages/client/inbox/Notifications.tsx +++ b/src/app/pages/client/inbox/Notifications.tsx @@ -97,7 +97,6 @@ import { } from '../../../hooks/useMemberPowerTag'; import { useRoomCreatorsTag } from '../../../hooks/useRoomCreatorsTag'; import { useRoomCreators } from '../../../hooks/useRoomCreators'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; type RoomNotificationsGroup = { roomId: string; @@ -643,7 +642,7 @@ export function Notifications() { {screenSize === ScreenSize.Mobile && ( {(onBack) => ( - + )} @@ -695,7 +694,6 @@ export function Notifications() { onVisibilityChange={handleScrollTopVisibility} > virtualizer.scrollToOffset(0)} variant="SurfaceVariant" radii="Pill" diff --git a/src/app/pages/client/space/Search.tsx b/src/app/pages/client/space/Search.tsx index a2849ab8..017262b5 100644 --- a/src/app/pages/client/space/Search.tsx +++ b/src/app/pages/client/space/Search.tsx @@ -11,7 +11,6 @@ import { roomToParentsAtom } from '../../../state/room/roomToParents'; import { useMatrixClient } from '../../../hooks/useMatrixClient'; import { ScreenSize, useScreenSizeContext } from '../../../hooks/useScreenSize'; import { BackRouteHandler } from '../../../components/BackRouteHandler'; -import { PhoneHit } from '../../../styles/PhoneHit.css'; export function SpaceSearch() { const mx = useMatrixClient(); @@ -35,7 +34,7 @@ export function SpaceSearch() { {screenSize === ScreenSize.Mobile && ( {(onBack) => ( - + )} diff --git a/src/app/phoneGlyph.test.ts b/src/app/phoneGlyph.test.ts index 6969da0e..1f31dae6 100644 --- a/src/app/phoneGlyph.test.ts +++ b/src/app/phoneGlyph.test.ts @@ -1,64 +1,15 @@ import { readFileSync } from 'fs'; import { describe, expect, it } from 'vitest'; -import { MOBILE_BREAKPOINT } from './hooks/useScreenSize'; -import { emitted } from './phoneHitTestKit'; import { ICON_BUTTON_CLASS, PHONE_GLYPHS } from '../phoneGlyph.css'; -const foldsJs = readFileSync(`${process.cwd()}/node_modules/folds/dist/index.js`, 'utf8'); const foldsCss = readFileSync(`${process.cwd()}/node_modules/folds/dist/style.css`, 'utf8'); -/** The px folds draws an Icon class at: its width variable's rem value, at the 16 px root. */ -const foldsPx = (cls: string) => { - const v = foldsCss.match(new RegExp(`\\.${cls} \\{\\s*width: var\\((--[\\w-]+)\\)`))?.[1]; - const rem = v && foldsCss.match(new RegExp(`${v}: ([\\d.]+)rem`))?.[1]; - return rem ? Number(rem) * 16 : undefined; -}; - -describe('phone glyphs inside IconButtons', () => { - it("name folds' own classes: the IconButton base class and one Icon class per size", () => { - expect(foldsJs).toContain( - `var IconButton$1 = createRuntimeFn({ defaultClassName: "${ICON_BUTTON_CLASS} ` - ); - const iconSizes = foldsJs.match( - /var Icon\$1 = createRuntimeFn\(\{[^\n]*variantClassNames: \{ size: \{([^}]*)\}/ - )?.[1]; - expect(iconSizes).toBeDefined(); - Object.entries(PHONE_GLYPHS).forEach(([size, { cls }]) => - expect(iconSizes).toContain(`"${size}": "${cls}"`) - ); - }); - - it("start from the px folds draws each Icon size at (the scale's divisor is not a guess)", () => - Object.values(PHONE_GLYPHS).forEach(({ cls, px }) => expect(foldsPx(cls)).toBe(px))); - - it('draw the folds Icon px (16 18 20 22 24) at 22..28 px, never smaller, never past the smallest button box', () => { - // folds IconButton padding is 4 px a side at the smallest size, so its box is the glyph plus 8. - Object.values(PHONE_GLYPHS).forEach(({ px, phonePx }) => { - expect(phonePx).toBeGreaterThanOrEqual(22); - expect(phonePx).toBeLessThanOrEqual(28); +describe('phoneGlyph folds classes', () => { + it('references IconButton and Icon size classes present in folds/dist/style.css', () => { + expect(foldsCss).toMatch(new RegExp(`\\.${ICON_BUTTON_CLASS}\\b`)); + Object.values(PHONE_GLYPHS).forEach(({ cls, px, phonePx }) => { + expect(foldsCss).toMatch(new RegExp(`\\.${cls}\\b`)); expect(phonePx).toBeGreaterThan(px); - expect(phonePx).toBeLessThanOrEqual(px + 8); - }); - }); - - it('are a paint-time scale on phones only: no size, margin or padding, and no rule outside the phone query', async () => { - const css = await emitted('../phoneGlyph.css.ts'); - const phone = `@media screen and (max-width: ${MOBILE_BREAKPOINT}px)`; - expect( - css.replace(new RegExp(`${phone.replace(/[()]/g, '\\$&')} \\{\\n[\\s\\S]*?\\n\\}`, 'g'), '') - ).not.toMatch(/\.brs7ce5/); - Object.entries(PHONE_GLYPHS).forEach(([size, { cls, px, phonePx }]) => { - const rule = css.match( - new RegExp(`\\.${ICON_BUTTON_CLASS} > \\.${cls} \\{\\n([^}]*)\\}`) - )?.[1]; - expect(rule, `rule for Icon size ${size}`).toBeDefined(); - expect( - rule! - .trim() - .split('\n') - .map((l) => l.trim().split(':')[0]) - ).toEqual(['scale']); - expect(Number(rule!.match(/scale: ([\d.]+)/)![1])).toBeCloseTo(phonePx / px, 6); }); }); }); diff --git a/src/app/phoneHit.call.test.ts b/src/app/phoneHit.call.test.ts deleted file mode 100644 index 56971b05..00000000 --- a/src/app/phoneHit.call.test.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { describe, it } from 'vitest'; -import { expectPhoneHitClasses, expectSizeTie } from './phoneHitTestKit'; - -// Every IconButton of the call bars carries the phone hit-area variant of its drawn size, in source order -// (mic, sound, video, share, chat; the menu button; the call-status mic, sound, video, share). -describe('icon buttons in the call controls', () => { - it.each([ - ['features/call/Controls.tsx', Array(5).fill('PhoneHitSpread40')], - ['features/call/CallControls.tsx', ['PhoneHitSpread40']], - ['features/call-status/CallControl.tsx', Array(4).fill('PhoneHitSpread26')], - ])('%s', (file, want) => { - expectPhoneHitClasses(file as string, want as string[]); - expectSizeTie(file as string); - }); -}); diff --git a/src/app/phoneHit.commonSettings.test.ts b/src/app/phoneHit.commonSettings.test.ts deleted file mode 100644 index fdb2c4e0..00000000 --- a/src/app/phoneHit.commonSettings.test.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { describe, it } from 'vitest'; -import { expectPhoneHitClasses, expectSizeTie } from './phoneHitTestKit'; - -// Every IconButton under features/common-settings, in source order. Header close buttons are alone at the -// header end (the title beside them is text), the dialog close buttons are alone in their Header, the -// scroll-to-top button floats alone, and the RoomPacks pair is a ternary (only one renders): all PhoneHit. -const files: [string, string[]][] = [ - ['features/common-settings/members/Members.tsx', ['PhoneHit', 'PhoneHit']], - ['features/common-settings/developer-tools/SendRoomEvent.tsx', ['PhoneHit']], - ['features/common-settings/developer-tools/StateEventEditor.tsx', ['PhoneHit']], - ['features/common-settings/developer-tools/DevelopTools.tsx', ['PhoneHit']], - ['features/common-settings/permissions/PowersEditor.tsx', ['PhoneHit']], - ['features/common-settings/emojis-stickers/EmojisStickers.tsx', ['PhoneHit']], - ['features/common-settings/emojis-stickers/RoomPacks.tsx', ['PhoneHit', 'PhoneHit']], - ['features/common-settings/general/RoomEncryption.tsx', ['PhoneHit']], - ['features/common-settings/general/RoomUpgrade.tsx', ['PhoneHit']], -]; - -describe.each(files)('phone hit area: %s', (file, want) => { - it('carries the variant its drawn size and neighbours call for', () => { - expectPhoneHitClasses(file, want); - }); - it('names a size that matches what it draws', () => { - expectSizeTie(file); - }); -}); diff --git a/src/app/phoneHit.content.test.ts b/src/app/phoneHit.content.test.ts deleted file mode 100644 index 741a5828..00000000 --- a/src/app/phoneHit.content.test.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { describe, it } from 'vitest'; -import { expectPhoneHitClasses, expectSizeTie } from './phoneHitTestKit'; - -describe('icon buttons in message content and data editors', () => { - // The class each IconButton must carry, in source order. - const expected: Record = { - // mute toggle, 16 px icon + 8 padding = 24 px, 8 px from the volume slider (tappable) - 'components/message/content/AudioContent.tsx': ['PhoneHitSpread24'], - // download, alone at the end of the header row (26 px) - 'components/message/FileHeader.tsx': ['PhoneHit'], - // code block expand/collapse, 24 px, 8 px from the Copy chip - 'plugins/react-custom-html-parser.tsx': ['PhoneHitSpread24'], - // close at the header end, alone - 'components/AccountDataEditor.tsx': ['PhoneHit'], - 'components/image-pack-view/ImagePackView.tsx': ['PhoneHit'], - }; - - it.each(Object.entries(expected))( - '%s: each IconButton carries its own PhoneHit class', - (file, want) => expectPhoneHitClasses(file, want) - ); - - it.each(Object.keys(expected))('%s: a sized variant matches the drawn size', (file) => - expectSizeTie(file) - ); -}); diff --git a/src/app/phoneHit.coverage.test.ts b/src/app/phoneHit.coverage.test.ts deleted file mode 100644 index f87b9a1a..00000000 --- a/src/app/phoneHit.coverage.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { readdirSync, readFileSync } from 'fs'; -import { describe, expect, it } from 'vitest'; -import { - classLists, - emitted, - expectPhoneHitClasses, - uncoveredIconButtons, -} from './phoneHitTestKit'; - -// Every IconButton under src carries a PhoneHit class, or is named here with the reason it has none. The per-group -// suites pin which variant a listed file's buttons carry; this one sees files no group lists, so a new bare -// IconButton fails here instead of shipping with a sub-44px phone hit area. -const EXEMPT: Record = { - 'app/features/estate/EstateNavigator.tsx': { - indices: [0], - why: 'Find a room sits in a css.Targets row that already gives it a 44 px phone target', - }, - 'app/features/lobby/LobbyHeader.tsx': { - indices: [1], - why: 'Members button, hidden on mobile', - }, -}; - -// Every script file, not only .tsx: an IconButton can be rendered from a .ts or .js module too. A file that never -// says IconButton is skipped; one that does is parsed and every mention of it must be a tag the guard can check. -const SCRIPT = /\.(?:[cm]?[jt]s|[jt]sx)$/; -const sourceFiles = (dir: string): string[] => - readdirSync(`${process.cwd()}/src/${dir}`, { withFileTypes: true }).flatMap((e) => { - if (e.isDirectory()) return sourceFiles(`${dir}${e.name}/`); - return SCRIPT.test(e.name) ? [`${dir}${e.name}`] : []; - }); - -describe('phone hit areas: every IconButton is covered or named', () => { - const scanned = sourceFiles('').flatMap((file) => { - const src = readFileSync(`${process.cwd()}/src/${file}`, 'utf8'); - return src.includes('IconButton') ? [{ file, ...uncoveredIconButtons(src, file) }] : []; - }); - - it('lists exactly the IconButtons without a PhoneHit class', () => { - expect(scanned.length).toBeGreaterThan(0); - const bare: Record = {}; - scanned.forEach(({ file, bare: missing }) => { - if (missing.length > 0) bare[file] = missing; - }); - expect(bare).toEqual( - Object.fromEntries(Object.entries(EXEMPT).map(([f, e]) => [f, e.indices])) - ); - }); - - // An IconButton passed as a value (as={IconButton}), re-bound, re-exported or destructured cannot be tied to a - // PhoneHit class, so the guard names it instead of passing over it. Render it as a tag, or extend the - // guard to read the new form. - it('finds no IconButton the guard cannot check', () => { - const unhandled: Record = {}; - scanned.forEach(({ file, unhandled: found }) => { - if (found.length > 0) unhandled[file] = found; - }); - expect(unhandled).toEqual({}); - }); -}); - -// UrlPreviewCard's arrows are absolutely positioned by their own class; PhoneHit would set position: relative on them -// and win or lose by stylesheet order, so they carry the variant that adds only the hit area. -describe('phone hit area of a button positioned by its own class', () => { - it('the arrows carry PhoneHitInPlace', () => { - expectPhoneHitClasses('components/url-preview/UrlPreviewCard.tsx', [ - 'PhoneHitInPlace', - 'PhoneHitInPlace', - ]); - }); - - it('PhoneHitInPlace draws the ::after and sets no position of its own', async () => { - const lists = await classLists('styles/PhoneHit.css.ts'); - expect(lists.PhoneHitInPlace).toHaveLength(1); - const css = await emitted('styles/PhoneHit.css.ts'); - const rules = [...css.matchAll(/^([^{}\n]*PhoneHitInPlace__[^{}\n]*) \{$/gm)].map((m) => m[1]); - expect(rules.length).toBeGreaterThan(0); - rules.forEach((sel) => expect(sel).toMatch(/::after$/)); - }); -}); diff --git a/src/app/phoneHit.dialogs.test.ts b/src/app/phoneHit.dialogs.test.ts deleted file mode 100644 index 8b3416a5..00000000 --- a/src/app/phoneHit.dialogs.test.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { describe, it } from 'vitest'; -import { expectPhoneHitClasses, expectSizeTie } from './phoneHitTestKit'; - -// Dialog and prompt close buttons: each is a 32 px button (24 px Icon + 8 px padding) alone at the end of a -// header whose title is not tappable, so the plain PhoneHit; no neighbour to spread from, no clipping container. -describe('icon buttons in dialogs and prompts', () => { - const expected: Record = { - 'features/create-space/CreateSpaceModal.tsx': ['PhoneHit'], - 'features/create-room/CreateRoomModal.tsx': ['PhoneHit'], - 'features/add-existing/AddExisting.tsx': ['PhoneHit'], - 'components/room-topic-viewer/RoomTopicViewer.tsx': ['PhoneHit'], - 'components/leave-room-prompt/LeaveRoomPrompt.tsx': ['PhoneHit'], - 'components/leave-space-prompt/LeaveSpacePrompt.tsx': ['PhoneHit'], - 'components/event-readers/EventReaders.tsx': ['PhoneHit'], - 'components/invite-user-prompt/InviteUserPrompt.tsx': ['PhoneHit'], - 'components/join-address-prompt/JoinAddressPrompt.tsx': ['PhoneHit'], // join cancel - 'components/user-profile/PowerChip.tsx': ['PhoneHit', 'PhoneHit'], // self demotion, shared power - }; - - it.each(Object.entries(expected))( - '%s: each IconButton carries its own PhoneHit class', - (file, want) => expectPhoneHitClasses(file, want) - ); - - it.each(Object.keys(expected))('%s: a sized variant matches the drawn size', (file) => - expectSizeTie(file) - ); -}); diff --git a/src/app/phoneHit.editor.test.ts b/src/app/phoneHit.editor.test.ts deleted file mode 100644 index d758662d..00000000 --- a/src/app/phoneHit.editor.test.ts +++ /dev/null @@ -1,119 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { MOBILE_BREAKPOINT } from './hooks/useScreenSize'; -import { - classLists, - emitted, - expectPhoneHitClasses, - expectSizeTie, - iconButtonTags, - readSource, - rulesFor, - type SizeAllow, -} from './phoneHitTestKit'; - -describe('icon buttons in the editor, emoji board, upload cards and client root', () => { - // The class each IconButton must carry, in source order. - const expected: Record = { - 'components/editor/Toolbar.tsx': [ - 'PhoneHitSpread36', // mark button: size 400 + 20 px icon, in a row 4 px apart - 'PhoneHitSpread36', // block button, same row - 'PhoneHitRoom36', // heading 1, inside the heading Menu (overflow hidden) - 'PhoneHitRoom36', // heading 2 - 'PhoneHitRoom36', // heading 3 - 'PhoneHit', // heading opener: two 20 px icons, 56 px wide, only its height is short - 'PhoneHit', // Exit chip: text label, wider than 44 px - 'PhoneHit', // markdown toggle, alone at the end of the toolbar - ], - // A column of 40 px buttons 4 px apart (the stack's gap="100", pinned below): there is no vertical variant, so only - // PhoneHit; the 44 px areas then touch with no overlap. - 'components/emoji-board/components/Sidebar.tsx': ['PhoneHit'], - // Both cards put a Retry chip beside the cancel button when the upload failed. - 'components/upload-card/UploadCardRenderer.tsx': ['PhoneHitSpread28'], - 'components/upload-card/CompactUploadCardRenderer.tsx': ['PhoneHitSpread28'], - 'pages/client/ClientRoot.tsx': ['PhoneHit'], // alone, absolute in the corner - }; - - const sizeAllow: SizeAllow = {}; - - it.each(Object.entries(expected))( - '%s: each IconButton carries its own PhoneHit class', - (file, want) => expectPhoneHitClasses(file, want) - ); - - it.each(Object.keys(expected))('%s: Spread and Room variants name the size they draw', (file) => - expectSizeTie(file, sizeAllow) - ); -}); - -/** The JSX element opened at `open` (index of its ``: nesting is counted, not guessed (no self-closing Box here). */ -const boxSpan = (src: string, open: number) => { - const marks = [...src.slice(open).matchAll(/])|<\/Box>/g)]; - const depths = marks.map((m, i) => - marks.slice(0, i + 1).reduce((d, x) => d + (x[0] === '' ? -1 : 1), 0) - ); - const end = depths.indexOf(0); - if (end === -1) throw new Error('unbalanced '); - return [open, open + (marks[end].index ?? 0) + marks[end][0].length] as const; -}; - -describe('the estate navigator find button', () => { - // The only IconButton there needs no PhoneHit: every button in the navigator header is 44 px on a phone because - // the Targets class sets a min size, and the button sits inside the Box that carries that class. - it('is 44 px by the Targets class instead', async () => { - const src = readSource('features/estate/EstateNavigator.tsx'); - const tags = iconButtonTags(src); - expect(tags).toHaveLength(1); - expect(tags[0]).not.toMatch(/PhoneHit/); - - const header = src.indexOf(''); - const boxStart = src.indexOf('', boxStart))).toMatch(/className=\{css\.Targets\}/); - const button = src.indexOf(' { - // PhoneHit makes the button position: relative on a phone; the inline style wins over a class, so the corner - // button stays absolute and its ::after anchors to it. - it('ClientRoot keeps its corner button absolutely positioned inline', () => { - const [tag] = iconButtonTags(readSource('pages/client/ClientRoot.tsx')); - expect(tag).toMatch(/style=\{\{[^}]*position:\s*'absolute'/); - }); - - // A 40 px button with a 44 px area, in a column 4 px apart: the areas touch and do not overlap. A smaller gap - // overlaps them, a larger one leaves a dead strip. - it('the emoji sidebar stack keeps its 4 px gap', () => { - const src = readSource('components/emoji-board/components/Sidebar.tsx'); - const stack = src.slice( - src.indexOf('export const SidebarStack'), - src.indexOf('export function SidebarDivider') - ); - expect(stack).toMatch(/direction="Column"/); - expect(stack).toMatch(/gap="100"/); - }); - - // The same column rhythm in the scrolling Sidebar: its 40 px buttons sit in a Column of Box gap="100" (4 px). - it('the emoji sidebar column keeps its 4 px gap', () => { - const src = readSource('components/emoji-board/components/Sidebar.tsx'); - const column = src.slice( - src.indexOf('export function Sidebar('), - src.indexOf('export const SidebarStack') - ); - expect(column).toMatch( - /]*gap="100"/ - ); - }); -}); diff --git a/src/app/phoneHit.pages.test.ts b/src/app/phoneHit.pages.test.ts deleted file mode 100644 index 97eb77b8..00000000 --- a/src/app/phoneHit.pages.test.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { describe, it } from 'vitest'; -import { expectPhoneHitClasses, expectSizeTie } from './phoneHitTestKit'; - -// Page back buttons (and two lone buttons beside them). Every one is alone in its row, 40 px drawn (default -// IconButton and Icon), so plain PhoneHit; the vertical stacks of the page have no variant. -// null = deliberately without: LobbyHeader's Members button renders only when screenSize !== Mobile. -const files: Record = { - 'features/lobby/LobbyHeader.tsx': ['PhoneHit', null, 'PhoneHit'], - 'features/join-before-navigate/JoinBeforeNavigate.tsx': ['PhoneHit'], - 'pages/client/space/Search.tsx': ['PhoneHit'], - 'pages/client/explore/Server.tsx': ['PhoneHit'], - 'pages/client/explore/Featured.tsx': ['PhoneHit'], - 'pages/client/home/CreateRoom.tsx': ['PhoneHit'], - 'pages/client/home/Search.tsx': ['PhoneHit'], - // the second is the 30 px scroll-to-top pill, floating alone at the top centre - 'pages/client/inbox/Notifications.tsx': ['PhoneHit', 'PhoneHit'], - 'pages/client/inbox/Invites.tsx': ['PhoneHit'], - 'pages/client/direct/DirectCreate.tsx': ['PhoneHit'], -}; - -describe.each(Object.entries(files))('phone hit area: %s', (file, want) => { - it('gives each IconButton its variant', () => { - expectPhoneHitClasses(file, want); - }); - // plain PhoneHit has no size to tie; this fails when a sized variant appears whose number is not the drawn px - it('ties any sized variant to the drawn size', () => { - expectSizeTie(file); - }); -}); diff --git a/src/app/phoneHit.roomSpace.test.ts b/src/app/phoneHit.roomSpace.test.ts deleted file mode 100644 index c98c2b09..00000000 --- a/src/app/phoneHit.roomSpace.test.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { describe, it } from 'vitest'; -import { expectPhoneHitClasses, expectSizeTie } from './phoneHitTestKit'; - -describe('icon buttons in room settings, space settings, lobby, search and explore', () => { - // The class each IconButton must carry, in source order. Vertical stacks and lone buttons: the plain PhoneHit. - const expected: Record = { - 'features/room-settings/RoomSettings.tsx': ['PhoneHit'], // close, phone only, alone at the header end - 'features/room-settings/general/General.tsx': ['PhoneHit'], // close, 40 px - 'features/room-settings/permissions/Permissions.tsx': ['PhoneHit'], - 'features/space-settings/SpaceSettings.tsx': ['PhoneHit'], - 'features/space-settings/general/General.tsx': ['PhoneHit'], - 'features/space-settings/permissions/Permissions.tsx': ['PhoneHit'], - // 16 px icon + 8 padding = 24 px, 8-12 px from the Open / Add chips beside it in a hierarchy card - 'features/lobby/HierarchyItemMenu.tsx': ['PhoneHitSpread24'], - 'features/lobby/Lobby.tsx': ['PhoneHit'], // floating scroll-to-top, alone - 'features/message-search/MessageSearch.tsx': ['PhoneHit'], // floating scroll-to-top, alone - 'pages/client/explore/Explore.tsx': ['PhoneHit'], // Add Server dialog close - }; - - it.each(Object.entries(expected))( - '%s: each IconButton carries its own PhoneHit class', - (file, want) => expectPhoneHitClasses(file, want) - ); - - it.each(Object.keys(expected))('%s: a sized variant matches the drawn size', (file) => - expectSizeTie(file) - ); -}); diff --git a/src/app/phoneHit.settingsA.test.ts b/src/app/phoneHit.settingsA.test.ts deleted file mode 100644 index 37f1f3c2..00000000 --- a/src/app/phoneHit.settingsA.test.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { describe, it } from 'vitest'; -import { expectPhoneHitClasses, expectSizeTie } from './phoneHitTestKit'; - -describe('icon buttons in settings A', () => { - // The class each IconButton must carry, in source order. Every one is alone in its row (a header close next to - // non-tappable title text, an input slot, or a list tile beside a non-tappable Avatar), so the plain PhoneHit. - const expected: Record = { - 'features/settings/developer-tools/DevelopTools.tsx': ['PhoneHit'], // header close, 40 px - 'features/settings/notifications/Notifications.tsx': ['PhoneHit'], // header close, 40 px - 'features/settings/notifications/KeywordMessages.tsx': ['PhoneHit', 'PhoneHit'], // input reset, remove: 26 px, alone - 'features/settings/emojis-stickers/EmojisStickers.tsx': ['PhoneHit'], // header close, 40 px - 'features/settings/emojis-stickers/GlobalPacks.tsx': ['PhoneHit', 'PhoneHit'], // undo / remove, a ternary pair, 26 px - 'features/settings/Settings.tsx': ['PhoneHit'], // mobile-only header close, 40 px - 'features/settings/about/About.tsx': ['PhoneHit'], // header close, 40 px - 'features/settings/general/General.tsx': ['PhoneHit', 'PhoneHit', 'PhoneHit'], // reset / info (ternary), header close - 'features/settings/account/Account.tsx': ['PhoneHit'], // header close, 40 px - 'features/settings/devices/Devices.tsx': ['PhoneHit'], // header close, 40 px - }; - - it.each(Object.entries(expected))('%s carries the right hit-area class', (file, want) => { - expectPhoneHitClasses(file, want); - }); - - // Plain PhoneHit has no size to tie, so nothing is allow-listed; the check still fails an allow-list entry - // or a sized variant that disagrees with the drawn size if one is added later. - it.each(Object.keys(expected))('%s ties a sized variant to the drawn size', (file) => { - expectSizeTie(file); - }); -}); diff --git a/src/app/phoneHit.settingsB.test.ts b/src/app/phoneHit.settingsB.test.ts deleted file mode 100644 index 4d2e3dee..00000000 --- a/src/app/phoneHit.settingsB.test.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { describe, it } from 'vitest'; -import { expectPhoneHitClasses, expectSizeTie } from './phoneHitTestKit'; - -// Each IconButton here is alone in its slot (a dialog header's close, an input's clear button, a tile's lone -// menu or chevron button, its neighbours being text or a badge), so each takes PhoneHit. Every size is derivable -// from the source, so nothing is allow-listed; plain PhoneHit has no number to tie. -const files: [string, string[]][] = [ - ['features/settings/account/Profile.tsx', ['PhoneHit', 'PhoneHit']], - ['features/settings/account/IgnoredUserList.tsx', ['PhoneHit']], - ['features/settings/devices/Verification.tsx', ['PhoneHit']], - ['features/settings/devices/DeviceTile.tsx', ['PhoneHit']], - ['pages/auth/ServerPicker.tsx', ['PhoneHit']], - ['components/BackupRestore.tsx', ['PhoneHit']], - ['components/DeviceVerification.tsx', ['PhoneHit']], - ['components/DeviceVerificationSetup.tsx', ['PhoneHit', 'PhoneHit']], -]; - -describe.each(files)('phone hit area: %s', (file, want) => { - it('gives each icon button its variant', () => expectPhoneHitClasses(file, want)); - it('ties each sized variant to the size it draws', () => expectSizeTie(file)); -}); diff --git a/src/app/phoneHit.viewers.test.ts b/src/app/phoneHit.viewers.test.ts deleted file mode 100644 index 3e579f4c..00000000 --- a/src/app/phoneHit.viewers.test.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { describe, it } from 'vitest'; -import { expectPhoneHitClasses, expectSizeTie } from './phoneHitTestKit'; - -// Viewer headers and the UIA stages. The back/close button sits beside a title that is not tappable, so it is a -// plain PhoneHit; the zoom out/in buttons sit either side of a tappable zoom Chip, so they spread at their drawn -// 24 px (IconButton size 300 around a 16 px Icon). -// Not covered: the two scroll arrows of components/url-preview/UrlPreviewCard.tsx. They are position: absolute and -// PhoneHit sets position: relative on phones, which would pull them into the flow; they need a variant that keeps -// the position, which PhoneHit.css.ts does not have yet. -const files: [string, string[]][] = [ - ['components/uia-stages/PasswordStage.tsx', ['PhoneHit']], - ['components/uia-stages/SSOStage.tsx', ['PhoneHit']], - ['components/UIAFlowOverlay.tsx', ['PhoneHit']], - ['components/text-viewer/TextViewer.tsx', ['PhoneHit']], - ['components/image-editor/ImageEditor.tsx', ['PhoneHit']], - ['components/image-viewer/ImageViewer.tsx', ['PhoneHit', 'PhoneHitSpread24', 'PhoneHitSpread24']], - ['components/Pdf-viewer/PdfViewer.tsx', ['PhoneHit', 'PhoneHitSpread24', 'PhoneHitSpread24']], -]; - -describe.each(files)('phone hit area: %s', (file, want) => { - it('gives each icon button the variant of its surroundings', () => { - expectPhoneHitClasses(file, want); - }); - it('ties each sized variant to the size the button draws', () => { - expectSizeTie(file); - }); -}); diff --git a/src/app/phoneHitTestKit.test.ts b/src/app/phoneHitTestKit.test.ts deleted file mode 100644 index 77bfc9fd..00000000 --- a/src/app/phoneHitTestKit.test.ts +++ /dev/null @@ -1,276 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { mkdtempSync, rmSync, writeFileSync } from 'fs'; -import { tmpdir } from 'os'; -import { relative } from 'path'; -import { - drawnPx, - expectPhoneHitClasses, - expectSizeTie, - iconButtons, - phoneHitOf, - uncoveredIconButtons, -} from './phoneHitTestKit'; - -describe('phone hit test kit', () => { - it('reads { - const src = - ''; - expect(iconButtons(src).map((b) => b.tag)).toEqual([ - '', - '', - ]); - }); - - it('derives a drawn size from literal size props, defaults being 400', () => { - expect(drawnPx('', '')).toEqual({ px: 24 }); - expect(drawnPx('', '')).toEqual({ px: 40 }); - }); - - it('reads { - expect( - drawnPx('', '') - ).toEqual({ - px: 24, - }); - }); - - it('calls a size undetermined when props are spread into the IconButton or the Icon', () => { - expect(drawnPx('', '')).toHaveProperty('undetermined'); - expect(drawnPx('', '')).toHaveProperty( - 'undetermined' - ); - expect(drawnPx('', '')).toHaveProperty( - 'undetermined' - ); - expect(drawnPx('', '')).toHaveProperty('undetermined'); - }); - - it('fails a file with no IconButton, which would otherwise pass vacuously', () => { - expect(() => expectSizeTie('styles/PhoneHit.css.ts')).toThrow(/no IconButton/); - }); - - describe('phoneHitOf reads the imported class off the AST, applied unconditionally', () => { - const tag = (expr: string) => ``; - const ok = (expr: string, name: string) => expect(phoneHitOf(tag(expr))).toBe(name); - const no = (expr: string) => expect(phoneHitOf(tag(expr))).toBeNull(); - - it('accepts the bare identifier and merges that always include it', () => { - ok('PhoneHitSpread26', 'PhoneHitSpread26'); - ok('classNames(PhoneHitRoom36, css.other)', 'PhoneHitRoom36'); - ok('clsx(css.a, { [css.b]: on }, PhoneHit)', 'PhoneHit'); - ok('cx(PhoneHit)', 'PhoneHit'); - ok('`${PhoneHit} ${css.other}`', 'PhoneHit'); - ok('classNames(/* PhoneHit */ PhoneHit)', 'PhoneHit'); - }); - - it('rejects the name as a string, a concatenation or a comment', () => { - no("'PhoneHitSpread26'"); - no('`PhoneHitSpread26`'); - no('"PhoneHitSpread26" + "x"'); - no("'PhoneHit' + 'Spread26'"); - no('/* PhoneHit */ undefined'); - no('css.a // PhoneHit'); - }); - - it('rejects a conditionally applied name', () => { - no('cond ? PhoneHitSpread26 : undefined'); - no('cond && PhoneHitSpread26'); - no('cond || PhoneHitSpread26'); - no('maybe ?? PhoneHitSpread26'); - no("classNames(cond ? PhoneHit : '', css.a)"); - no('classNames(PhoneHit, cond && PhoneHit)'); - }); - - it('rejects every other expression shape the name can hide in', () => { - no('classNames({ PhoneHit: on })'); - no('clsx({ [PhoneHit]: on })'); - no('`${`${PhoneHit}`}`'); - no('typeof PhoneHit'); - no("(PhoneHit = 'x')"); - no('(PhoneHit, css.a)'); - no('(PhoneHit)'); - no('() => PhoneHit'); - no('PhoneHit.foo'); - no('other.PhoneHit'); - no('classNames(css.a, [PhoneHit])'); - no('wrap(PhoneHit)'); - no('PhoneHitSpread26é'); - no('`${css.a}`'); - }); - - it('rejects a tag without className, with two, or with a non-expression one', () => { - expect(phoneHitOf('')).toBeNull(); - expect(phoneHitOf('')).toBeNull(); - expect(phoneHitOf('')).toBeNull(); - expect(phoneHitOf('')).toBe('PhoneHit'); - }); - - it('rejects a spread after className, which can override it, and accepts one before', () => { - expect(phoneHitOf('')).toBeNull(); - expect(phoneHitOf('')).toBeNull(); - expect(phoneHitOf('')).toBe('PhoneHit'); - }); - - it('reads a className past braces inside strings', () => { - ok("classNames('{', PhoneHit)", 'PhoneHit'); - }); - }); - - describe('expectPhoneHitClasses', () => { - const check = (src: string, want: (string | null)[]) => { - const dir = mkdtempSync(`${tmpdir()}/phone-hit-kit-`); - try { - writeFileSync(`${dir}/Probe.tsx`, src); - expectPhoneHitClasses(relative(`${process.cwd()}/src/app`, `${dir}/Probe.tsx`), want); - } finally { - rmSync(dir, { recursive: true }); - } - }; - const imp = "import { PhoneHit, PhoneHitSpread26 } from '../../styles/PhoneHit.css';\n"; - const src = - imp + - 'const A = () => (<>);'; - - it('pins each button in order, null meaning no class', () => { - check(src, ['PhoneHit', 'PhoneHitSpread26', null]); - expect(() => check(src, ['PhoneHit', 'PhoneHit', null])).toThrow(); - expect(() => check(src, ['PhoneHit', 'PhoneHitSpread26', 'PhoneHit'])).toThrow(); - expect(() => check(src, ['PhoneHit', 'PhoneHitSpread26'])).toThrow(); - }); - - it('fails a name that is not read from PhoneHit.css or is applied conditionally', () => { - const local = "const PhoneHit = 'x';\n"; - expect(() => check(local, ['PhoneHit'])).toThrow(); - expect(() => check(local, [null])).not.toThrow(); - const cond = imp + ''; - expect(() => check(cond, ['PhoneHit'])).toThrow(); - const aliased = - "import { Other as PhoneHit } from '../../styles/PhoneHit.css';\n"; - expect(() => check(aliased, ['PhoneHit'])).toThrow(); - const wrongModule = - "import { PhoneHit } from './other';\n"; - expect(() => check(wrongModule, ['PhoneHit'])).toThrow(); - }); - }); - - describe('uncoveredIconButtons: the coverage guard is not blind to a spelling of IconButton', () => { - const imp = "import { PhoneHit } from '../styles/PhoneHit.css';\n"; - const none = { bare: [], unhandled: [] }; - - it('sees an IconButton imported under an alias, as a tag', () => { - const bare = "import { IconButton as IB } from 'folds';\nconst A = () => ;"; - expect(uncoveredIconButtons(bare)).toEqual({ bare: [0], unhandled: [] }); - const ok = `${imp}import { IconButton as IB } from 'folds';\nconst A = () => ;`; - expect(uncoveredIconButtons(ok)).toEqual(none); - }); - - it('sees a namespace member tag', () => { - const bare = "import * as F from 'folds';\nconst A = () => ;"; - expect(uncoveredIconButtons(bare)).toEqual({ bare: [0], unhandled: [] }); - const ok = `${imp}import * as F from 'folds';\nconst A = () => ;`; - expect(uncoveredIconButtons(ok)).toEqual(none); - }); - - it('fails loudly on an IconButton passed or bound as a value, and on a re-export', () => { - const asProp = - "import { IconButton } from 'folds';\nconst A = () => ;"; - expect(uncoveredIconButtons(asProp).unhandled).toEqual(['2:26']); - const aliasValue = - "import { IconButton as IB } from 'folds';\nconst A = () => ;"; - expect(uncoveredIconButtons(aliasValue).unhandled).toEqual(['2:26']); - const rebound = "import { IconButton } from 'folds';\nconst B = IconButton;"; - expect(uncoveredIconButtons(rebound).unhandled).toEqual(['2:11']); - const destructured = "import * as F from 'folds';\nconst { IconButton: IB } = F;"; - expect(uncoveredIconButtons(destructured).unhandled).toEqual(['2:9']); - const member = "import * as F from 'folds';\nconst B = F.IconButton;"; - expect(uncoveredIconButtons(member).unhandled).toEqual(['2:13']); - const indexed = "import * as F from 'folds';\nconst B = F['IconButton'];"; - expect(uncoveredIconButtons(indexed).unhandled).toEqual(['2:13']); - expect(uncoveredIconButtons("export { IconButton } from 'folds';").unhandled).toHaveLength(1); - }); - - it('reads a non-.tsx file by its extension', () => { - const ts = - "import { IconButton } from 'folds';\nexport const x = (v: T) => ;"; - expect(uncoveredIconButtons(ts, 'x.tsx').bare).toEqual([0]); - const js = "import { IconButton } from 'folds';\nexport const B = IconButton;"; - expect(uncoveredIconButtons(js, 'x.ts').unhandled).toEqual(['2:18']); - expect(uncoveredIconButtons(js, 'x.js').unhandled).toEqual(['2:18']); - const jsx = "import { IconButton } from 'folds';\nexport const A = () => ;"; - expect(uncoveredIconButtons(jsx, 'x.jsx').bare).toEqual([0]); - }); - - it('does not count IconButtonX, a comment or a string as an IconButton', () => { - const src = - "import { IconButtonGroup } from 'folds';\n// IconButton\nconst a = 'IconButton';\nconst A = () => ;"; - expect(uncoveredIconButtons(src)).toEqual(none); - }); - - it('does not count a PhoneHit that an inner scope rebinds', () => { - const tag = ''; - const cases = [ - `const A = (PhoneHit) => ${tag};`, - `const A = ({ PhoneHit }) => ${tag};`, - `const A = ([a, PhoneHit]) => ${tag};`, - `function A() { const PhoneHit = 'x'; return ${tag}; }`, - `function A() { return ${tag}; var PhoneHit; }`, - `function A() { if (a) { var PhoneHit = 'x'; } return ${tag}; }`, - `function A() { { let { PhoneHit } = o; return ${tag}; } }`, - `function A() { function PhoneHit() {} return ${tag}; }`, - `function A() { for (const PhoneHit of xs) { return ${tag}; } }`, - `function A() { try { f(); } catch (PhoneHit) { return ${tag}; } }`, - `const A = function PhoneHit() { return ${tag}; };`, - `function A() { switch (x) { case 1: const PhoneHit = 'x'; return ${tag}; } }`, - ]; - cases.forEach((c) => expect(uncoveredIconButtons(`${imp}${c}`).bare, c).toEqual([0])); - // the same shapes without the rebinding count, and a rebinding that is not in scope does not hide it - expect(uncoveredIconButtons(`${imp}const A = () => ${tag};`).bare).toEqual([]); - expect( - uncoveredIconButtons(`${imp}const f = (PhoneHit) => 1;\nconst A = () => ${tag};`).bare - ).toEqual([]); - expect(uncoveredIconButtons(`${imp}function A() { return ${tag}; }`).bare).toEqual([]); - }); - - it('does not count an import type of PhoneHit', () => { - const tag = 'const A = () => ;'; - const typeOnly = `import type { PhoneHit } from '../styles/PhoneHit.css';\n${tag}`; - expect(uncoveredIconButtons(typeOnly).bare).toEqual([0]); - const typeSpecifier = `import { type PhoneHit } from '../styles/PhoneHit.css';\n${tag}`; - expect(uncoveredIconButtons(typeSpecifier).bare).toEqual([0]); - expect(uncoveredIconButtons(`${imp}${tag}`).bare).toEqual([]); - }); - }); - - describe('drawnPx reads the parsed tag, not its text', () => { - it('ignores a size in a string, comment or other prop name', () => { - expect(drawnPx('', '')).toEqual({ px: 40 }); - expect(drawnPx('', '')).toEqual({ - px: 40, - }); - expect( - drawnPx('', '{/* */}') - ).toEqual({ - px: 24, - }); - expect(drawnPx('', '{""}')).toHaveProperty( - 'undetermined' - ); - }); - - it('reads a size from a braced string, and the last size wins', () => { - expect(drawnPx("", '')).toEqual({ px: 24 }); - expect(drawnPx('', '')).toEqual({ - px: 40, - }); - }); - - it('reads an Icon spread after a size, and a size past a braced prop with a > inside', () => { - expect(drawnPx(' a > b} size="300">', '')).toEqual({ - px: 32, - }); - expect(drawnPx('', '')).toHaveProperty( - 'undetermined' - ); - }); - }); -}); diff --git a/src/app/phoneHitTestKit.ts b/src/app/phoneHitTestKit.ts deleted file mode 100644 index b6752183..00000000 --- a/src/app/phoneHitTestKit.ts +++ /dev/null @@ -1,384 +0,0 @@ -// Shared helpers for the phone hit-area tests (phoneTapTargets.test.ts and one phoneHit..test.ts per later -// group of IconButtons). Not a test file: it registers nothing, the test files call it. -import { readFileSync } from 'fs'; -import { expect } from 'vitest'; -import ts from 'typescript'; -import zlib from 'zlib'; -import { compile, processVanillaFile } from '@vanilla-extract/integration'; - -// The CSS a .css.ts file emits, read back from vanilla-extract's own compile (as pages/auth/footerBand.test.ts does; -// vanilla-extract gzips the inlined source only when it is large, so both forms are read). -const compiled = async (file: string) => { - const filePath = `${process.cwd()}/src/app/${file}`; - const { source } = await compile({ filePath, cwd: process.cwd(), identOption: 'debug' }); - return processVanillaFile({ source, filePath, identOption: 'debug' }); -}; - -/** The class list each export of a .css.ts file resolves to (a composed class lists the classes it composes). */ -export const classLists = async (file: string): Promise> => - Object.fromEntries( - [...(await compiled(file)).matchAll(/^export var (\w+) = '([^']*)';$/gm)].map((m) => [ - m[1], - m[2].split(' '), - ]) - ); - -export const emitted = async (file: string) => { - const code = await compiled(file); - // A file with recipes inlines one source per rule group; read them all. - return [...code.matchAll(/source=#?([A-Za-z0-9+/=]+)/g)] - .map((m) => { - const bytes = Buffer.from(m[1], 'base64'); - return (bytes[0] === 0x1f && bytes[1] === 0x8b ? zlib.gunzipSync(bytes) : bytes).toString(); - }) - .join('\n'); -}; - -export type Decls = Record; -const parse = (body: string): Decls => - Object.fromEntries( - body - .split('\n') - .map((l) => l.trim().replace(/;$/, '')) - .filter((l) => /^[a-z-]+: -?\d+px$/.test(l)) - .map((l) => [l.split(':')[0], Number(l.split(': ')[1].replace('px', ''))]) - ); - -/** Pixel declarations of the rules whose selector matches, inside or outside a media query. */ -export const rulesFor = (css: string, selector: RegExp, media: string | undefined): Decls[] => { - const scope = media - ? [...css.matchAll(/@media ([^{]+) \{\n([\s\S]*?\n)\}(?:\n|$)/g)] - .filter((m) => m[1] === media) - .map((m) => m[2]) - .join('\n') - : css.replace(/@media [^{]+ \{\n[\s\S]*?\n\}(?:\n|$)/g, ''); - return [...scope.matchAll(/^\s*([^{}\n]+) \{\n([^}]*)\}/gm)] - .filter((m) => selector.test(m[1])) - .map((m) => parse(m[2])); -}; - -/** The source of a file under src/app. */ -export const readSource = (file: string) => - readFileSync(`${process.cwd()}/src/app/${file}`, 'utf8'); - -// The extension picks the script kind (.ts reads `x` as an assertion, .tsx and .jsx read it as JSX). -const tsx = (src: string, fileName = 'source.tsx') => - ts.createSourceFile(fileName, src, ts.ScriptTarget.Latest, true); - -type Opening = ts.JsxOpeningElement | ts.JsxSelfClosingElement; - -const isTag = (n: ts.Node): n is Opening => - ts.isJsxOpeningElement(n) || ts.isJsxSelfClosingElement(n); - -/** Local names the source binds IconButton to by import: IconButton itself and any alias (IconButton as IB). */ -const iconButtonNames = (sf: ts.SourceFile) => { - const names = new Set(['IconButton']); - sf.statements.forEach((st) => { - const nb = ts.isImportDeclaration(st) ? st.importClause?.namedBindings : undefined; - if (nb && ts.isNamedImports(nb)) - nb.elements.forEach((e) => { - if ((e.propertyName ?? e.name).text === 'IconButton') names.add(e.name.text); - }); - }); - return names; -}; - -/** Whether a JSX tag name is an IconButton: the plain or aliased identifier, or a namespace member (). */ -const isIconButtonTag = (tag: ts.JsxTagNameExpression, names: Set) => - (ts.isIdentifier(tag) && names.has(tag.text)) || - (ts.isPropertyAccessExpression(tag) && tag.name.text === 'IconButton'); - -/** Every IconButton element (not IconButtonX) of a parsed source, in source order, however its tag is spelled. */ -const elements = (sf: ts.SourceFile) => { - const names = iconButtonNames(sf); - const found: Opening[] = []; - const walk = (n: ts.Node) => { - if (isTag(n) && isIconButtonTag(n.tagName, names)) found.push(n); - ts.forEachChild(n, walk); - }; - walk(sf); - return found; -}; - -/** Every mention of IconButton that is not a JSX tag or the import itself: passed as a value (as={IconButton}), - * re-bound, re-exported, reached by destructuring or by an element access. Such a render cannot be tied to a - * PhoneHit class, so each is reported ("line:col") and the guard fails on it. */ -const unhandledMentions = (sf: ts.SourceFile) => { - const names = iconButtonNames(sf); - const out: string[] = []; - const at = (n: ts.Node) => { - const { line, character } = sf.getLineAndCharacterOfPosition(n.getStart()); - out.push(`${line + 1}:${character + 1}`); - }; - const walk = (n: ts.Node) => { - if (ts.isIdentifier(n) && names.has(n.text)) { - const p = n.parent; - const tagged = (x: ts.Node) => - (isTag(x) || ts.isJsxClosingElement(x)) && x.tagName === (n as ts.Node); - const member = - ts.isPropertyAccessExpression(p) && - p.name === n && - (isTag(p.parent) || ts.isJsxClosingElement(p.parent)) && - p.parent.tagName === p; - if (!ts.isImportSpecifier(p) && !tagged(p) && !member) at(n); - } else if ( - ts.isStringLiteralLike(n) && - n.text === 'IconButton' && - ts.isElementAccessExpression(n.parent) - ) - at(n); - ts.forEachChild(n, walk); - }; - walk(sf); - return out; -}; - -const bodyOf = (el: Opening) => - ts.isJsxOpeningElement(el) && ts.isJsxElement(el.parent) - ? el.getSourceFile().text.slice(el.end, el.parent.closingElement.getStart()) - : ''; - -/** Every - elements(tsx(src)).map((el) => ({ tag: el.getText(), body: bodyOf(el) })); - -export const iconButtonTags = (src: string) => iconButtons(src).map((b) => b.tag); - -/** Local names the source imports as values from the PhoneHit.css module (as written, not aliased). An - * `import type`, or a `type` specifier, binds no value and is not read. */ -const importedHits = (sf: ts.SourceFile) => - new Set( - sf.statements.flatMap((st) => { - if (!ts.isImportDeclaration(st) || !ts.isStringLiteral(st.moduleSpecifier)) return []; - const nb = st.importClause?.namedBindings; - return nb && - !st.importClause?.isTypeOnly && - ts.isNamedImports(nb) && - /^(\.\.\/)+styles\/PhoneHit\.css$/.test(st.moduleSpecifier.text) - ? nb.elements.filter((e) => !e.propertyName && !e.isTypeOnly).map((e) => e.name.text) - : []; - }) - ); - -const bindingNames = (b: ts.BindingName): string[] => - ts.isIdentifier(b) - ? [b.text] - : b.elements.flatMap((e) => (ts.isOmittedExpression(e) ? [] : bindingNames(e.name))); - -const declaresVar = (list: ts.VariableDeclarationList, name: string) => - list.declarations.some((d) => bindingNames(d.name).includes(name)); - -/** Whether `var name` is declared anywhere in a function body, outside nested functions (var hoists to the function). */ -const hoistsVar = (fn: ts.Node, name: string) => { - let found = false; - const walk = (n: ts.Node) => { - if (found || (n !== fn && ts.isFunctionLike(n))) return; - if ( - ts.isVariableDeclarationList(n) && - // eslint-disable-next-line no-bitwise -- NodeFlags is a bit set; var is the one declaration kind with neither flag - (n.flags & ts.NodeFlags.BlockScoped) === 0 && - declaresVar(n, name) - ) - found = true; - ts.forEachChild(n, walk); - }; - walk(fn); - return found; -}; - -/** Whether one scope node declares `name` of its own: parameters, a function expression's own name, block-level - * let/const/function/class, a for-loop head or a catch variable. */ -const scopeDeclares = (scope: ts.Node, name: string): boolean => { - const inStatements = (sts: readonly ts.Statement[]) => - sts.some( - (st) => - (ts.isVariableStatement(st) && declaresVar(st.declarationList, name)) || - ((ts.isFunctionDeclaration(st) || ts.isClassDeclaration(st)) && st.name?.text === name) - ); - if (ts.isBlock(scope) || ts.isModuleBlock(scope)) return inStatements(scope.statements); - if (ts.isCaseBlock(scope)) return inStatements(scope.clauses.flatMap((c) => [...c.statements])); - if (ts.isFunctionLike(scope)) - return ( - scope.parameters.some((p) => bindingNames(p.name).includes(name)) || - ((ts.isFunctionExpression(scope) || ts.isClassExpression(scope)) && - scope.name?.text === name) || - hoistsVar(scope, name) - ); - if (ts.isForStatement(scope) || ts.isForInStatement(scope) || ts.isForOfStatement(scope)) - return ( - !!scope.initializer && - ts.isVariableDeclarationList(scope.initializer) && - declaresVar(scope.initializer, name) - ); - if (ts.isCatchClause(scope)) - return ( - !!scope.variableDeclaration && bindingNames(scope.variableDeclaration.name).includes(name) - ); - return false; -}; - -/** Whether an inner scope between the identifier and the module rebinds its name, so it is not the import. */ -const shadowed = (id: ts.Identifier) => { - for (let n: ts.Node | undefined = id.parent; n && !ts.isSourceFile(n); n = n.parent) - if (scopeDeclares(n, id.text)) return true; - return false; -}; - -const MERGERS = new Set(['classNames', 'clsx', 'cx']); - -/** The PhoneHit* class an IconButton carries, or null. className must appear exactly once, with no props spread - * after it (a spread can override it at runtime), and its expression must be: the bare identifier; a classNames / - * clsx / cx call with it as a direct argument; or a template with it as a direct span. The identifier must occur - * nowhere else in the expression, so a key, a member, a closure, a conditional or a comma can never carry it. When - * `imported` is given, the identifier must also resolve to a value binding imported from the PhoneHit.css module - * (not an `import type`, not rebound by an inner scope). */ -const hitOf = (el: Opening, imported?: Set): string | null => { - const props = el.attributes.properties; - const at = props.flatMap((p, i) => - ts.isJsxAttribute(p) && ts.isIdentifier(p.name) && p.name.text === 'className' ? [i] : [] - ); - if (at.length !== 1 || props.slice(at[0] + 1).some(ts.isJsxSpreadAttribute)) return null; - const attr = props[at[0]] as ts.JsxAttribute; - const expr = - attr.initializer && ts.isJsxExpression(attr.initializer) && attr.initializer.expression; - if (!expr) return null; - const isHit = (n: ts.Node): n is ts.Identifier => - ts.isIdentifier(n) && - /^PhoneHit\w*$/.test(n.text) && - (!imported || (imported.has(n.text) && !shadowed(n))); - let direct: ts.Node[] = []; - if (ts.isIdentifier(expr)) direct = [expr]; - else if ( - ts.isCallExpression(expr) && - ts.isIdentifier(expr.expression) && - MERGERS.has(expr.expression.text) - ) - direct = [...expr.arguments]; - else if (ts.isTemplateExpression(expr)) direct = expr.templateSpans.map((sp) => sp.expression); - const hits = direct.filter(isHit); - if (hits.length !== 1) return null; - let occurrences = 0; - const count = (n: ts.Node) => { - if (ts.isIdentifier(n) && n.text === hits[0].text) occurrences += 1; - ts.forEachChild(n, count); - }; - count(expr); - return occurrences === 1 ? hits[0].text : null; -}; - -/** The PhoneHit* class of one tag's text (see hitOf), without the import-binding check. */ -export const phoneHitOf = (tag: string) => { - const els = elements(tsx(tag.endsWith('/>') ? tag : `${tag}`)); - return els.length === 1 ? hitOf(els[0]) : null; -}; - -/** The PhoneHit* class of each IconButton of a source, in source order; null when it has none or the name is not - * the one imported from PhoneHit.css. */ -export const phoneHitClasses = (src: string) => { - const sf = tsx(src); - const imported = importedHits(sf); - return elements(sf).map((el) => hitOf(el, imported)); -}; - -/** What a source file leaves uncovered: the indices (source order) of its IconButton elements without a PhoneHit - * class, and the "line:col" of every mention of IconButton that is not a tag and so cannot be checked at all. The - * fileName picks the parser (.ts, .tsx, .js, ...). */ -export const uncoveredIconButtons = (src: string, fileName = 'source.tsx') => { - const sf = tsx(src, fileName); - const imported = importedHits(sf); - return { - bare: elements(sf).flatMap((el, i) => (hitOf(el, imported) === null ? [i] : [])), - unhandled: unhandledMentions(sf), - }; -}; - -/** The class each IconButton must carry, in source order (null = must carry none): the variant is chosen by the - * button's drawn size and whether a clipping container or neighbours surround it, so a swapped variant is a wrong - * hit area. The name must also be the one PhoneHit.css exports, not a local of the same name. */ -export const expectPhoneHitClasses = (file: string, want: (string | null)[]) => - expect(phoneHitClasses(readSource(file))).toEqual(want); - -// IconButton `size` -> padding on each side, Icon `size` -> px (folds 2.7.2). Both default to 400. -const BUTTON_PAD: Record = { '300': 4, '400': 8, '500': 12, '600': 16 }; -const ICON_PX: Record = { - '50': 16, - '100': 18, - '200': 20, - '300': 22, - '400': 24, - '500': 28, -}; - -/** The size prop of a tag: its literal value, the default when absent, or undefined when it is an expression. */ -const sizeProp = (el: Opening) => { - const props = el.attributes.properties; - // props spread in may carry a size of their own - if (props.some(ts.isJsxSpreadAttribute)) return undefined; - const sizes = props.filter( - (p): p is ts.JsxAttribute => - ts.isJsxAttribute(p) && ts.isIdentifier(p.name) && p.name.text === 'size' - ); - if (sizes.length === 0) return '400'; - const init = sizes[sizes.length - 1].initializer; - const lit = init && ts.isJsxExpression(init) ? init.expression : init; - return lit && ts.isStringLiteralLike(lit) ? lit.text : undefined; -}; - -/** The px an IconButton draws, from its size prop and the Icon inside; undefined with a reason when the source - * does not say (a variable size, no Icon, Icons of different sizes). Both are read off the parsed tag and body. */ -export const drawnPx = (tag: string, body: string): { px: number } | { undetermined: string } => { - let button: Opening | undefined; - const first = (n: ts.Node) => { - if (!button && isTag(n)) button = n; - else if (!button) ts.forEachChild(n, first); - }; - first(tsx(tag.endsWith('/>') ? tag : `${tag}`)); - const pad = BUTTON_PAD[(button && sizeProp(button)) ?? '']; - if (pad === undefined) - return { undetermined: 'size of the IconButton is not a literal (or props are spread in)' }; - const icons: (number | undefined)[] = []; - const find = (n: ts.Node) => { - if (isTag(n) && ts.isIdentifier(n.tagName) && n.tagName.text === 'Icon') - icons.push(ICON_PX[sizeProp(n) ?? '']); - ts.forEachChild(n, find); - }; - find(tsx(`<>${body}`)); - if (icons.length === 0) return { undetermined: 'no inside' }; - if (icons.some((p) => p === undefined)) - return { undetermined: 'size of an Icon is not a literal (or props are spread in)' }; - if (new Set(icons).size > 1) return { undetermined: 'Icons of different sizes inside' }; - return { px: (icons[0] as number) + 2 * pad }; -}; - -/** Per file, per IconButton index (source order): why its drawn size cannot be derived from the source. */ -export type SizeAllow = Record>; - -/** A button carrying PhoneHitSpread or PhoneHitRoom draws N px. Plain PhoneHit has no number to tie. An - * undetermined size passes only with an entry in `allow`, and an entry for a size that can be derived fails. */ -export const expectSizeTie = (file: string, allow: SizeAllow = {}) => { - const allowed = allow[file] ?? {}; - const seen = new Set(); - const src = readSource(file); - const buttons = iconButtons(src); - const classes = phoneHitClasses(src); - expect(buttons.length, `${file} has no IconButton`).toBeGreaterThan(0); - buttons.forEach(({ tag, body }, i) => { - const variant = classes[i]?.match(/^PhoneHit(?:Spread|Room)(\d+)$/); - if (!variant) { - expect(allowed[i], `${file} #${i} is allow-listed but has no sized variant`).toBeUndefined(); - return; - } - const drawn = drawnPx(tag, body); - if ('undetermined' in drawn) { - expect( - allowed[i], - `${file} #${i}: ${drawn.undetermined}; add it to the allow-list` - ).toBeDefined(); - seen.add(i); - return; - } - expect(allowed[i], `${file} #${i} is allow-listed but its size is derivable`).toBeUndefined(); - expect(Number(variant[1]), `${file} #${i} draws ${drawn.px} px`).toBe(drawn.px); - }); - expect(Object.keys(allowed).map(Number).sort()).toEqual([...seen].sort()); -}; diff --git a/src/app/phoneTapTargets.test.ts b/src/app/phoneTapTargets.test.ts deleted file mode 100644 index bbcde9e6..00000000 --- a/src/app/phoneTapTargets.test.ts +++ /dev/null @@ -1,225 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { MOBILE_BREAKPOINT } from './hooks/useScreenSize'; -import { - classLists, - emitted, - expectPhoneHitClasses, - expectSizeTie, - rulesFor, - type SizeAllow, -} from './phoneHitTestKit'; - -const PHONE = `screen and (max-width: ${MOBILE_BREAKPOINT}px)`; -const TAP = 44; - -// [target, css file, selector, measured height in CSS px on the Starfire phone run (390x844), free space measured -// above and below the target before its neighbour's box (taps2-REPORT.md): the hit area may reach out of the layout -// box (negative margin) by no more than that, or it takes taps from its neighbour. Space it needs beyond that is -// real layout growth, which the rules above take from the padding the margin does not give back. -const targets: [string, string, RegExp, number, number, number][] = [ - [ - 'sender-name button', - 'components/message/layout/layout.css.ts', - /^button\.layout_Username__/, - 23, - 11, - 11, - ], - [ - 'room-topic button', - 'features/room/RoomViewHeader.css.ts', - /RoomViewHeader_HeaderTopic__\w+$/, - 18, - 0, - 26, - ], - ['sign-in card links', 'pages/auth/styles.css.ts', /styles_AuthCard__\w+ a$/, 16, 14, 14], - [ - 'forget-password link', - 'pages/auth/styles.css.ts', - /styles_AuthCard__\w+ a\.styles_ForgotLink__\w+$/, - 16, - 5, - 16, - ], - // The footer's rows are 22 px apart on a phone (AuthFooterLinks), 11 px for each side of the gap. - ['sign-in footer links', 'pages/auth/styles.css.ts', /styles_AuthFooter__\w+ a$/, 22, 11, 11], -]; - -describe.each(targets)('phone tap target: %s', (_name, file, selector, height, above, below) => { - it(`grows its hit area to ${TAP} px without moving layout`, async () => { - const css = await emitted(file); - const [phone] = rulesFor(css, selector, PHONE); - expect(phone, 'a phone rule exists').toBeDefined(); - const top = phone['padding-top'] ?? phone['padding-block'] ?? 0; - const bottom = phone['padding-bottom'] ?? phone['padding-block'] ?? 0; - const marginTop = phone['margin-top'] ?? phone['margin-block'] ?? 0; - const marginBottom = phone['margin-bottom'] ?? phone['margin-block'] ?? 0; - expect(height + top + bottom).toBeGreaterThanOrEqual(TAP); - // the hit area reaches out of the layout box by no more than the free space on that side - expect(-marginTop).toBeLessThanOrEqual(above); - expect(-marginBottom).toBeLessThanOrEqual(below); - expect(marginTop).toBeLessThanOrEqual(0); - expect(marginBottom).toBeLessThanOrEqual(0); - }); - - it('leaves every other screen as it was: no padding or margin outside the phone query', async () => { - const css = await emitted(file); - rulesFor(css, selector, undefined).forEach((decls) => - expect(Object.keys(decls).filter((k) => /^(padding|margin)/.test(k))).toEqual([]) - ); - }); -}); - -describe('phone navigator rows', () => { - // The links and buttons inside a row are 44 px (EstateNavigator.css.ts); a row shorter than that lets them spill - // onto the next row (the 38 px pitch of taps2-REPORT.md), so the row and the section header are 44 too. - it('are as tall as their tap targets', async () => { - const css = await emitted('components/nav/styles.css.ts'); - const phone = [ - ...css.matchAll(/@media screen and \(max-width: 750px\) \{\n([\s\S]*?\n)\}(?:\n|$)/g), - ] - .map((m) => m[1]) - .join('\n'); - expect(phone.match(/min-height: 2\.75rem/g)?.length).toBeGreaterThanOrEqual(2); - }); -}); - -describe('phone icon-button hit areas', () => { - const stripPhone = (css: string) => css.replace(/@media [^{]+ \{\n[\s\S]*?\n\}(?:\n|$)/g, ''); - - it('draw a 44 x 44 box around the button on a phone and nothing on any other screen', async () => { - const css = await emitted('styles/PhoneHit.css.ts'); - const phone = [...css.matchAll(/@media ([^{]+) \{\n([\s\S]*?\n)\}(?:\n|$)/g)]; - expect(phone.map((m) => m[1])).toEqual([PHONE]); - expect(css).toMatch(/::after \{[^}]*width: max\(100%, 44px\);[^}]*height: max\(100%, 44px\);/); - // no content, no box: the pseudo-element is not rendered at all - expect(css).toMatch(/::after \{[^}]*content: "";/); - expect(css).toMatch(/::after \{[^}]*position: absolute;/); - // centred on the button: top and left at half, pulled back by half its own size - expect(css).toMatch(/::after \{[^}]*top: 50%;/); - expect(css).toMatch(/::after \{[^}]*left: 50%;/); - expect(css).toMatch(/::after \{[^}]*transform: translate\(-50%, -50%\);/); - // the box anchors to its own button, receives the tap, and sits above nothing it should not - expect(css).toMatch(/@media [^{]+ \{\n\s*\.PhoneHit_PhoneHit__\w+ \{\n\s*position: relative;/); - // PhoneHit and PhoneHitInPlace each draw it; the Spread and Room classes compose PhoneHit - const afters = [...css.matchAll(/::after \{\n([^}]*)\}/g)]; - expect(afters).toHaveLength(2); - const afterDecls = afters.flatMap((m) => - m[1] - .split('\n') - .map((l) => l.trim().split(':')[0]) - .filter(Boolean) - ); - expect([...new Set(afterDecls)].sort()).toEqual([ - 'content', - 'height', - 'left', - 'position', - 'top', - 'transform', - 'width', - ]); - // nothing on a phone moves a button off its own anchor: only relative (the button) and absolute (the boxes) - expect([...css.matchAll(/position: (\w+);/g)].map((m) => m[1]).sort()).toEqual([ - 'absolute', - 'absolute', - 'relative', - ]); - expect(stripPhone(css).trim()).toBe(''); - }); - - it('open a row up by half the shortfall, so neighbouring hit areas meet and do not overlap', async () => { - const css = await emitted('styles/PhoneHit.css.ts'); - const margins = (selector: RegExp) => - rulesFor(css, selector, PHONE).map((d) => d['margin-inline']); - // 32 px composer buttons, 40 px header buttons, 26 px message-option buttons (which also open vertically, - // the menu around them clips a hit area drawn outside its box) - // each class owns its own margin: (44 - drawn size) / 2 - const own = (size: number) => margins(new RegExp(`PhoneHit_PhoneHitSpread${size}__`)); - expect([24, 26, 28, 32, 36, 40].map(own)).toEqual([[10], [9], [8], [6], [4], [2]]); - // the Room variants open the block axis by the same amount, on top of their Spread class - const room = (size: number) => - rulesFor(css, new RegExp(`PhoneHit_PhoneHitRoom${size}__`), PHONE); - expect([room(26), room(36)]).toEqual([[{ 'margin-block': 9 }], [{ 'margin-block': 4 }]]); - }); - - it('compose a Room variant from the Spread class of the same size, which composes PhoneHit', async () => { - const lists = await classLists('styles/PhoneHit.css.ts'); - const named = (list: string[], name: string) => list.filter((c) => c.includes(`_${name}__`)); - [26, 36].forEach((size) => { - const room = lists[`PhoneHitRoom${size}`]; - expect( - named(room, `PhoneHitSpread${size}`), - `Room${size} composes Spread${size}` - ).toHaveLength(1); - expect(named(room, 'PhoneHit'), `Room${size} composes PhoneHit`).toHaveLength(1); - }); - expect(lists.PhoneHitRoom36.some((c) => c.includes('_PhoneHitSpread26__'))).toBe(false); - }); - - it("make a message's reaction chip 44 px to tap by opening 9 px above and below it", async () => { - const css = await emitted('components/message/Reaction.css.ts'); - const [chip] = rulesFor(css, /^button\.Reaction_Reaction__\w+$/, PHONE); - expect(chip['margin-block']).toBe((TAP - 26) / 2); - expect(css).toMatch(/::after \{[^}]*inset: -9px 0;/); - rulesFor(css, /^button\.Reaction_Reaction__\w+$/, undefined).forEach((d) => - expect(Object.keys(d)).not.toContain('margin-block') - ); - }); - - it('give a sender name a 44 px wide button too, text kept at its start', async () => { - const css = await emitted('components/message/layout/layout.css.ts'); - const [phone] = rulesFor(css, /^button\.layout_Username__/, PHONE); - expect(phone['min-width']).toBe(TAP); - expect(css).toMatch(/text-align: start;/); - }); -}); - -describe('icon buttons in the room view', () => { - // The class each IconButton must carry, in source order: the variant is chosen by the button's drawn size - // and whether a clipping container or neighbours surround it, so a swapped variant is a wrong hit area. - const expected: Record = { - 'features/room/message/Message.tsx': [ - 'PhoneHitSpread32', // quick-reaction emoji buttons - 'PhoneHitSpread32', // delete dialog close - 'PhoneHitSpread32', // report dialog close - ...Array(6).fill('PhoneHitRoom26'), // message options bar, inside a clipping menu - ], - 'features/room/RoomInput.tsx': ['PhoneHitSpread24', ...Array(5).fill('PhoneHitSpread32')], // reply cancel is a 16 px icon, the rest 24 px - 'features/room/RoomViewHeader.tsx': Array(6).fill('PhoneHitSpread40'), - // The chat path's other buttons. Two neighbours in a row: Spread32. One on its own: the plain PhoneHit. - 'features/room/message/MessageEditor.tsx': ['PhoneHitSpread32', 'PhoneHitSpread32'], // toolbar, emoji - 'features/room-nav/RoomNavItem.tsx': ['PhoneHitSpread24', 'PhoneHitSpread24'], // chat toggle, options: 16 px icon + 8 padding = 24 px, 0 gap - 'features/room/MembersDrawer.tsx': ['PhoneHit', 'PhoneHit'], // close, scroll to top - 'features/room/reaction-viewer/ReactionViewer.tsx': ['PhoneHit'], - 'features/room/room-pin-menu/RoomPinMenu.tsx': ['PhoneHitSpread26', 'PhoneHit'], // unpin (26 px, 8 px from the Open chip), close - 'features/room/RoomViewTyping.tsx': ['PhoneHit'], - 'features/room/CallChatView.tsx': ['PhoneHit'], - 'features/room/jump-to-time/JumpToTime.tsx': ['PhoneHit'], - // Buttons that were fixed with #125 and had no test. - 'components/password-input/PasswordInput.tsx': ['PhoneHit'], - 'features/desk/Desk.tsx': ['PhoneHit'], - 'features/scene/SceneViewEntry.tsx': ['PhoneHit'], // the scene view's entry - 'features/scene/SceneViewHost.tsx': ['PhoneHit'], // Return while the scene view loads - 'features/scene/view/SceneView.tsx': ['PhoneHit'], // one rail button, five icons - 'pages/auth/login/PasswordLoginForm.tsx': ['PhoneHit'], - }; - - // IconButtons whose drawn size the source does not say (file -> index in source order -> why). Everything else - // is derived from the size props, so a Spread32 on a 24 px button fails. - const sizeAllow: SizeAllow = { - 'features/room/message/Message.tsx': { - 0: 'quick-reaction button wraps an emoji , no Icon; 32 px by its CSS class', - }, - }; - - it.each(Object.entries(expected))( - '%s: each IconButton carries its own PhoneHit class', - (file, want) => expectPhoneHitClasses(file, want) - ); - - it.each(Object.keys(expected))('%s: each sized variant equals the px its button draws', (file) => - expectSizeTie(file, sizeAllow) - ); -}); diff --git a/src/app/plugins/react-custom-html-parser.tsx b/src/app/plugins/react-custom-html-parser.tsx index 2398a4c9..961131d9 100644 --- a/src/app/plugins/react-custom-html-parser.tsx +++ b/src/app/plugins/react-custom-html-parser.tsx @@ -22,7 +22,6 @@ import Linkify from 'linkify-react'; import { ErrorBoundary } from 'react-error-boundary'; import { ChildNode } from 'domhandler'; import * as css from '../styles/CustomHtml.css'; -import { PhoneHitSpread24 } from '../styles/PhoneHit.css'; import { getMxIdLocalPart, getCanonicalAliasRoomId, @@ -283,7 +282,6 @@ export function CodeBlock({ variant="SurfaceVariant" outlined radii="300" - className={PhoneHitSpread24} onClick={toggleExpand} aria-label={expanded ? 'Collapse' : 'Expand'} > diff --git a/src/app/state/settings.ts b/src/app/state/settings.ts index b5165929..167f8674 100644 --- a/src/app/state/settings.ts +++ b/src/app/state/settings.ts @@ -50,12 +50,6 @@ export interface Settings { dateFormatString: string; developerTools: boolean; - - /** Soundscape flag: default off, and muted by default even when on. */ - soundscapeEnabled: boolean; - soundscapeMuted: boolean; - soundscapeVolume: number; - soundscapeVoiceCap: number; } export const defaultThemeId = 'midnight-sky'; @@ -96,11 +90,6 @@ const defaultSettings: Settings = { dateFormatString: 'D MMM YYYY', developerTools: false, - - soundscapeEnabled: false, - soundscapeMuted: true, - soundscapeVolume: 0.5, - soundscapeVoiceCap: 4, }; export const getSettings = () => { diff --git a/src/app/state/upload.ts b/src/app/state/upload.ts index 84786a29..810c0d2e 100644 --- a/src/app/state/upload.ts +++ b/src/app/state/upload.ts @@ -1,14 +1,9 @@ import { atom, useAtom } from 'jotai'; import { atomFamily } from 'jotai/utils'; import { MatrixClient, UploadResponse, UploadProgress, MatrixError } from 'matrix-js-sdk'; -import { useCallback, useEffect, useRef } from 'react'; +import { useCallback } from 'react'; import { useThrottle } from '../hooks/useThrottle'; -import { - ComponentLifecycle, - describeComponentLifecycle, - uploadContent, - TUploadContent, -} from '../utils/matrix'; +import { uploadContent, TUploadContent } from '../utils/matrix'; export enum UploadStatus { Idle = 'idle', @@ -110,34 +105,22 @@ export const useBindUploadAtom = ( const [upload, setUpload] = useAtom(uploadAtom); const { file } = upload; - // For the failure text: renders and unmount of the component that owns this upload. - const life = useRef({ attachedAt: 0, rendersAtAttach: 0, renders: [] }); - if (life.current.renders.length < 50) life.current.renders.push(Date.now()); - useEffect(() => { - const tracked = life.current; - tracked.unmountedAt = undefined; - return () => { - tracked.unmountedAt = Date.now(); - }; - }, []); - const handleProgress = useThrottle( useCallback((progress: UploadProgress) => setUpload({ progress }), [setUpload]), { immediate: true, wait: 200 } ); - const startUpload = useCallback(() => { - life.current.attachedAt = Date.now(); - life.current.rendersAtAttach = life.current.renders.length; - return uploadContent(mx, file, { - hideFilename, - describeLifecycle: () => describeComponentLifecycle(life.current), - onPromise: (promise: Promise) => setUpload({ promise }), - onProgress: handleProgress, - onSuccess: (mxc) => setUpload({ mxc }), - onError: (error) => setUpload({ error }), - }); - }, [mx, file, hideFilename, setUpload, handleProgress]); + const startUpload = useCallback( + () => + uploadContent(mx, file, { + hideFilename, + onPromise: (promise: Promise) => setUpload({ promise }), + onProgress: handleProgress, + onSuccess: (mxc) => setUpload({ mxc }), + onError: (error) => setUpload({ error }), + }), + [mx, file, hideFilename, setUpload, handleProgress] + ); const cancelUpload = useCallback(async () => { if (upload.status === UploadStatus.Loading) { diff --git a/src/app/styles/PhoneHit.css.ts b/src/app/styles/PhoneHit.css.ts deleted file mode 100644 index e971ecb3..00000000 --- a/src/app/styles/PhoneHit.css.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { style } from '@vanilla-extract/css'; -import { MOBILE_BREAKPOINT } from '../hooks/useScreenSize'; - -// Phone tap target for an icon button: on a phone the button's hit area is 44 x 44 px centred on the drawn -// button (a ::after the button's own click reaches), so nothing drawn changes size. A button with neighbours -// 44 px closer than that would take their taps, so the `Spread` classes also give it horizontal margin of half -// the shortfall: the row grows by that, on phones only, and the hit areas meet instead of overlapping. -// Vertical room is cheaper than horizontal on a phone, so only the horizontal axis pays. -export const PHONE_TAP = 44; -const PHONE = `screen and (max-width: ${MOBILE_BREAKPOINT}px)`; - -const hitArea = { - '@media': { - [PHONE]: { - content: '""', - position: 'absolute', - top: '50%', - left: '50%', - width: `max(100%, ${PHONE_TAP}px)`, - height: `max(100%, ${PHONE_TAP}px)`, - transform: 'translate(-50%, -50%)', - }, - }, -} as const; - -/** An icon button on its own: the hit area grows, nothing else moves. */ -export const PhoneHit = style({ - '@media': { [PHONE]: { position: 'relative' } }, - selectors: { '&::after': hitArea }, -}); - -/** For a button that is already positioned (absolute or fixed) by its own class: PhoneHit's `position: relative` - * would fight that class by stylesheet order, and the positioned button already contains its ::after. */ -export const PhoneHitInPlace = style({ selectors: { '&::after': hitArea } }); - -const spreads = new Map(); - -/** An icon button in a row, `visual` px wide: the row opens up so its 44 px hit area meets its neighbours'. */ -const spread = (visual: number) => { - const cls = style( - [PhoneHit, { '@media': { [PHONE]: { marginInline: (PHONE_TAP - visual) / 2 } } }], - `PhoneHitSpread${visual}` - ); - spreads.set(visual, cls); - return cls; -}; - -export const PhoneHitSpread24 = spread(24); -export const PhoneHitSpread26 = spread(26); -export const PhoneHitSpread28 = spread(28); -export const PhoneHitSpread32 = spread(32); -export const PhoneHitSpread36 = spread(36); -export const PhoneHitSpread40 = spread(40); - -/** For a button in a clipping container (a Menu's overflow hidden eats a hit area drawn outside the box): the row - * opens up on both axes, so the 44 px sits inside the container. It is the Spread class of the same size plus the - * block margin, so the two axes cannot disagree about the size. */ -const room = (visual: number) => { - const spreadClass = spreads.get(visual); - if (!spreadClass) throw new Error(`PhoneHitRoom${visual} needs a PhoneHitSpread${visual}`); - return style( - [spreadClass, { '@media': { [PHONE]: { marginBlock: (PHONE_TAP - visual) / 2 } } }], - `PhoneHitRoom${visual}` - ); -}; - -export const PhoneHitRoom26 = room(26); -export const PhoneHitRoom36 = room(36); diff --git a/src/app/utils/matrix.ts b/src/app/utils/matrix.ts index d4972677..fa01f112 100644 --- a/src/app/utils/matrix.ts +++ b/src/app/utils/matrix.ts @@ -18,7 +18,7 @@ import { IImageInfo, IThumbnailContent, IVideoInfo } from '../../types/matrix/co import { AccountDataEvent } from '../../types/matrix/accountData'; import { getStateEvent } from './room'; import { Membership, StateEvent } from '../../types/matrix/room'; -import { NO_INFO, UploadFailureInfo } from './uploadReason'; +import { UploadFailureInfo } from './uploadReason'; const DOMAIN_REGEX = /\b(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}\b/; @@ -144,22 +144,8 @@ export type ContentUploadOptions = { onProgress?: (progress: UploadProgress) => void; onSuccess: (mxc: string) => void; onError: (error: MatrixError) => void; - /** Read at failure time: what the owning component did since the upload attached. */ - describeLifecycle?: () => string; }; -let lastUserActivity = Date.now(); -export const noteUserActivity = () => { - lastUserActivity = Date.now(); -}; -if (typeof window !== 'undefined') { - ['pointerdown', 'keydown', 'touchstart'].forEach((type) => - window.addEventListener(type, noteUserActivity, { capture: true, passive: true }) - ); -} - -export type AbortCall = { api: string; frames: string }; - /** What the progress handler saw of one upload, for the failure text. */ export type UploadTrace = { startedAt: number; @@ -168,174 +154,9 @@ export type UploadTrace = { total?: number; /** Summary of an earlier attempt of the same upload, when this one is a retry. */ previous?: string; - /** abort() calls the page made while this attempt ran; absent when not probed. */ - aborts?: AbortCall[]; - /** What the owning component did since the upload attached. */ - lifecycle?: string; - /** Upload XHR events and end state, and whether our own signal was aborted. */ - xhr?: string; signalAborted?: boolean; }; -const MAX_FRAMES = 6; -const MAX_ABORT_CALLS = 4; - -/** - * An Error stack as `file:line:col < file:line:col`, at most six frames. The error line and the - * probe's own frame are dropped; origins and function names are not kept. - */ -export const formatAbortStack = (stack: string): string => { - const frames = stack - .split('\n') - .map((l) => l.trim()) - .filter((l) => l.startsWith('at ') || l.includes('@')) - .map((l) => { - const m = /([^/\s()@]+):(\d+):(\d+)\)?$/.exec(l); - return m ? `${m[1]}:${m[2]}:${m[3]}` : undefined; - }) - .filter((f): f is string => f !== undefined) - .slice(1, 1 + MAX_FRAMES); - return frames.length > 0 ? frames.join(' < ') : 'no stack'; -}; - -export type ComponentLifecycle = { - attachedAt: number; - rendersAtAttach: number; - renders: number[]; - unmountedAt?: number; -}; - -/** What the component that owns an upload did after the upload attached to it. */ -export const describeComponentLifecycle = (life: ComponentLifecycle): string => { - const since = life.renders.slice(life.rendersAtAttach); - const quick = since.filter((t) => t - life.attachedAt <= 300).length; - const unmount = - life.unmountedAt === undefined - ? 'not unmounted' - : `unmounted +${life.unmountedAt - life.attachedAt}ms`; - return `component: ${since.length} renders since attach (${quick} within 300ms), ${unmount}`; -}; - -export type XhrRecord = { - xhr: XMLHttpRequest; - method: string; - path: string; - startedAt: number; - events: string[]; -}; - -type Probe = { calls: AbortCall[]; xhrs: XhrRecord[] }; - -const probes = new Set(); -let restoreProbe: (() => void) | undefined; -const xhrTargets = new WeakMap(); - -const XHR_EVENTS = ['loadstart', 'error', 'abort', 'timeout', 'load', 'loadend']; -const MAX_XHR_EVENTS = 12; - -/* eslint-disable no-param-reassign */ -const patchAbort = (proto: { abort: (...a: any[]) => any }, api: string) => { - const original = proto.abort; - const wrapper = function abortProbe(this: unknown, ...args: any[]) { - const frames = formatAbortStack(new Error().stack ?? ''); - probes.forEach(({ calls }) => { - if (calls.length < MAX_ABORT_CALLS) calls.push({ api, frames }); - }); - return original.apply(this, args); - }; - proto.abort = wrapper; - return () => { - if (proto.abort === wrapper) proto.abort = original; - }; -}; - -// Upload XHRs only; the path is kept and the query (it holds the access token) is dropped. -const patchXhr = (proto: XMLHttpRequest) => { - const { open, send } = proto; - const openWrapper = function openProbe(this: XMLHttpRequest, ...args: any[]) { - try { - const url = new URL(String(args[1]), 'http://x'); - if (url.pathname.includes('/upload')) { - xhrTargets.set(this, { method: String(args[0]).toUpperCase(), path: url.pathname }); - } - } catch { - // not a URL we can read; the request is not recorded - } - return (open as any).apply(this, args); - }; - const sendWrapper = function sendProbe(this: XMLHttpRequest, ...args: any[]) { - const target = xhrTargets.get(this); - if (target && probes.size > 0) { - const startedAt = Date.now(); - const events: string[] = []; - const note = (name: string) => () => { - if (events.length < MAX_XHR_EVENTS) events.push(`${name} +${Date.now() - startedAt}ms`); - }; - XHR_EVENTS.forEach((ev) => this.addEventListener(ev, note(ev))); - XHR_EVENTS.forEach((ev) => this.upload?.addEventListener(ev, note(`upload.${ev}`))); - this.upload?.addEventListener( - 'progress', - (() => { - let first = true; - return () => { - if (first) note('upload.progress')(); - first = false; - }; - })() - ); - const record: XhrRecord = { xhr: this, ...target, startedAt, events }; - probes.forEach((probe) => probe.xhrs.push(record)); - } - return (send as any).apply(this, args); - }; - (proto as any).open = openWrapper; - (proto as any).send = sendWrapper; - return () => { - if ((proto as any).open === openWrapper) (proto as any).open = open; - if ((proto as any).send === sendWrapper) (proto as any).send = send; - }; -}; -/* eslint-enable no-param-reassign */ - -const describeXhr = (r: XhrRecord): string => - `${r.method} ${r.path} readyState ${r.xhr.readyState} status ${ - r.xhr.status - } events [${r.events.join(', ')}]`; - -/** - * Records, until stopped, every XMLHttpRequest.abort and AbortController.abort the page makes and - * the lifecycle events and end state of upload XHRs. The prototypes are wrapped while at least one - * probe runs and restored when the last one stops; the wrappers change no behaviour. - */ -export const startAbortProbe = () => { - const probe: Probe = { calls: [], xhrs: [] }; - if (probes.size === 0) { - const restores: (() => void)[] = []; - if (typeof XMLHttpRequest !== 'undefined') { - restores.push(patchAbort(XMLHttpRequest.prototype, 'XHR.abort')); - restores.push(patchXhr(XMLHttpRequest.prototype)); - } - if (typeof AbortController !== 'undefined') { - restores.push(patchAbort(AbortController.prototype, 'AbortController.abort')); - } - restoreProbe = () => restores.forEach((r) => r()); - } - probes.add(probe); - return { - calls: probe.calls, - xhrs: probe.xhrs, - describeXhrs: () => - probe.xhrs.length === 0 ? 'xhr: none seen' : `xhr: ${probe.xhrs.map(describeXhr).join('; ')}`, - stop: () => { - probes.delete(probe); - if (probes.size === 0) { - restoreProbe?.(); - restoreProbe = undefined; - } - }, - }; -}; - const describeNetwork = (): string => { const online = typeof navigator !== 'undefined' && navigator.onLine === false ? 'offline' : 'online'; @@ -352,7 +173,7 @@ const describeNetwork = (): string => { /** * Describe why an upload died. The SDK reports an XHR with status 0 as an AbortError * DOMException with an empty message, so the text carries what the client can observe: file - * size, type and readability, connectivity, tab visibility, idle time, progress, time to fail. + * size, type and readability, connectivity, tab visibility, progress, time to fail. */ export const uploadFailure = async ( e: any, @@ -362,15 +183,16 @@ export const uploadFailure = async ( const now = Date.now(); const name = typeof e?.name === 'string' && e.name ? e.name : 'Error'; const message = typeof e?.message === 'string' ? e.message : ''; - let readable: string; - try { - await file.arrayBuffer(); - readable = 'file readable'; - } catch (readErr: any) { - readable = `file unreadable (${readErr?.name ?? 'unknown'})`; + let readable = + name === 'NotReadableError' ? 'file unreadable (NotReadableError)' : 'file readable'; + if (name !== 'NotReadableError' && typeof file.slice === 'function') { + try { + await file.slice(0, 1).arrayBuffer(); + } catch (readErr: any) { + readable = `file unreadable (${readErr?.name ?? 'unknown'})`; + } } const parts = [`${file.size} bytes`, file.type || 'unknown type', readable, describeNetwork()]; - parts.push(`idle ${now - lastUserActivity}ms`); if (trace) { parts.push( trace.firstProgressAt === undefined @@ -380,16 +202,7 @@ export const uploadFailure = async ( }B` ); parts.push(`failed after ${now - trace.startedAt}ms`); - if (trace.aborts) { - parts.push( - trace.aborts.length === 0 - ? 'abort calls: none' - : `abort calls: ${trace.aborts.map((a) => `${a.api} ${a.frames}`).join('; ')}` - ); - } - if (trace.xhr) parts.push(trace.xhr); if (trace.signalAborted !== undefined) parts.push(`signal.aborted ${trace.signalAborted}`); - if (trace.lifecycle) parts.push(trace.lifecycle); if (trace.previous) parts.push(`retried (attempt 1: ${trace.previous})`); } const error = `Upload failed: ${message ? `${name}: ${message}` : name} (${parts.join(', ')})`; @@ -410,101 +223,55 @@ export const uploadFailure = async ( }; // An abort before any progress, within this long, is retried once: the request most likely died on -// a reused connection before a byte left, and the failed attempt discards that connection. Nothing -// here has shown that is the cause; the failure text records both attempts so it can be checked. +// a reused connection before a byte left, and the failed attempt discards that connection. const RETRY_WINDOW_MS = 3000; -const copyInMemory = async (file: TUploadContent): Promise => { - const bytes = await file.arrayBuffer(); - return typeof File !== 'undefined' && file instanceof File - ? new File([bytes], file.name, { type: file.type, lastModified: file.lastModified }) - : new Blob([bytes], { type: file.type }); -}; - export const uploadContent = async ( mx: MatrixClient, file: TUploadContent, options: ContentUploadOptions ) => { - const { - name, - fileType, - hideFilename, - onProgress, - onPromise, - onSuccess, - onError, - describeLifecycle, - } = options; + const { name, fileType, hideFilename, onProgress, onPromise, onSuccess, onError } = options; let previous: string | undefined; for (let attempt = 1; ; attempt += 1) { - // The browser may hold a picked file as a handle it cannot always re-read (e.g. content://), so - // each attempt uploads a copy held in memory; a file that cannot be read fails here, named. - let body: TUploadContent; + const trace: UploadTrace = { startedAt: Date.now(), previous }; + const abortController = new AbortController(); + const uploadPromise = mx.uploadContent(file, { + name, + type: fileType, + includeFilename: !hideFilename, + abortController, + progressHandler: (progress) => { + if (trace.firstProgressAt === undefined) trace.firstProgressAt = Date.now(); + trace.loaded = progress.loaded; + trace.total = progress.total; + onProgress?.(progress); + }, + }); + onPromise?.(uploadPromise); try { // eslint-disable-next-line no-await-in-loop - body = await copyInMemory(file); - } catch (readErr: any) { - const errcode = readErr?.name || 'Error'; - const unreadable = new MatrixError({ - error: `Upload failed: file unreadable before upload (${errcode}) (${file.size} bytes, ${ - file.type || 'unknown type' - })`, - errcode, - }); - (unreadable as any).info = { ...NO_INFO, unreadable: true }; - onError(unreadable); + const data = await uploadPromise; + const mxc = data.content_uri; + if (mxc) onSuccess(mxc); + else onError(new MatrixError(data)); return; - } - const probe = startAbortProbe(); - const trace: UploadTrace = { startedAt: Date.now(), previous, aborts: probe.calls }; - const abortController = new AbortController(); - try { - const uploadPromise = mx.uploadContent(body, { - name, - type: fileType, - includeFilename: !hideFilename, - abortController, - progressHandler: (progress) => { - if (trace.firstProgressAt === undefined) trace.firstProgressAt = Date.now(); - trace.loaded = progress.loaded; - trace.total = progress.total; - onProgress?.(progress); - }, - }); - onPromise?.(uploadPromise); - try { + } catch (e: any) { + const elapsed = Date.now() - trace.startedAt; + trace.signalAborted = abortController.signal.aborted; + const retry = + attempt === 1 && + e?.name === 'AbortError' && + !abortController.signal.aborted && + trace.firstProgressAt === undefined && + elapsed < RETRY_WINDOW_MS; + if (!retry) { // eslint-disable-next-line no-await-in-loop - const data = await uploadPromise; - const mxc = data.content_uri; - if (mxc) onSuccess(mxc); - else onError(new MatrixError(data)); + onError(await uploadFailure(e, file, trace)); return; - } catch (e: any) { - const elapsed = Date.now() - trace.startedAt; - trace.xhr = probe.describeXhrs(); - trace.signalAborted = abortController.signal.aborted; - const retry = - attempt === 1 && - e?.name === 'AbortError' && - !abortController.signal.aborted && - trace.firstProgressAt === undefined && - elapsed < RETRY_WINDOW_MS; - if (!retry) { - trace.lifecycle = describeLifecycle?.(); - // eslint-disable-next-line no-await-in-loop - onError(await uploadFailure(e, file, trace)); - return; - } - previous = `AbortError after ${elapsed}ms, no progress, ${ - trace.aborts?.length - ? `abort calls: ${trace.aborts.map((a) => `${a.api} ${a.frames}`).join('; ')}` - : 'abort calls: none' - }, ${trace.xhr}`; } - } finally { - probe.stop(); + previous = `AbortError after ${elapsed}ms, no progress`; } } }; diff --git a/src/app/utils/uploadAbortProbe.test.ts b/src/app/utils/uploadAbortProbe.test.ts deleted file mode 100644 index 557908ef..00000000 --- a/src/app/utils/uploadAbortProbe.test.ts +++ /dev/null @@ -1,171 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { - describeComponentLifecycle, - formatAbortStack, - startAbortProbe, - uploadContent, - uploadFailure, -} from './matrix'; - -const chromeStack = [ - 'Error', - ' at wrapper (https://chat.example/assets/index-abc.js:1:100)', - ' at https://chat.example/assets/index-abc.js:1:200', - ' at Object.cb (https://chat.example/assets/vendor-def.js:7:8)', - ' at https://chat.example/assets/a.js:2:3', - ' at https://chat.example/assets/b.js:4:5', - ' at https://chat.example/assets/c.js:6:7', - ' at https://chat.example/assets/d.js:8:9', - ' at https://chat.example/assets/e.js:10:11', -].join('\n'); - -describe('formatAbortStack', () => { - it('keeps at most six frames as file:line:col, skipping the probe wrapper and the error line', () => { - const out = formatAbortStack(chromeStack); - const frames = out.split(' < '); - expect(frames).toHaveLength(6); - expect(frames[0]).toBe('index-abc.js:1:200'); - expect(out).not.toContain('https://'); - expect(out).not.toContain('wrapper'); - }); - - it('copes with an empty stack', () => { - expect(formatAbortStack('')).toBe('no stack'); - }); -}); - -describe('abort probe', () => { - const original = AbortController.prototype.abort; - - afterEach(() => { - vi.unstubAllGlobals(); - AbortController.prototype.abort = original; - }); - - it('records an AbortController.abort made while it runs, still aborts, and restores afterwards', () => { - const probe = startAbortProbe(); - expect(AbortController.prototype.abort).not.toBe(original); - const c = new AbortController(); - c.abort(); - expect(c.signal.aborted).toBe(true); - probe.stop(); - expect(AbortController.prototype.abort).toBe(original); - expect(probe.calls).toHaveLength(1); - expect(probe.calls[0].api).toBe('AbortController.abort'); - }); - - it('records XMLHttpRequest.prototype.abort and restores it', () => { - const xhrAbort = vi.fn(); - class FakeXhr { - // eslint-disable-next-line class-methods-use-this - abort() { - xhrAbort(); - } - } - vi.stubGlobal('XMLHttpRequest', FakeXhr); - const probe = startAbortProbe(); - new FakeXhr().abort(); - probe.stop(); - expect(xhrAbort).toHaveBeenCalledTimes(1); - expect(probe.calls.map((c) => c.api)).toContain('XHR.abort'); - expect(FakeXhr.prototype.abort.toString()).not.toContain('collectors'); - const after = new FakeXhr(); - after.abort(); - expect(xhrAbort).toHaveBeenCalledTimes(2); - }); - - it('records nothing after stop', () => { - const probe = startAbortProbe(); - probe.stop(); - new AbortController().abort(); - expect(probe.calls).toHaveLength(0); - }); - - it('keeps the wrapper until the last overlapping probe stops, then restores the original', () => { - const a = startAbortProbe(); - const b = startAbortProbe(); - a.stop(); - new AbortController().abort(); - expect(b.calls).toHaveLength(1); - expect(a.calls).toHaveLength(0); - b.stop(); - expect(AbortController.prototype.abort).toBe(original); - }); - - it('restores the original when the upload attempt throws', async () => { - const mx = { uploadContent: () => Promise.reject(new Error('boom')) } as any; - await uploadContent(mx, new Blob(['x']), { onSuccess: vi.fn(), onError: vi.fn() }); - expect(AbortController.prototype.abort).toBe(original); - }); - - it('restores the original when uploadContent itself throws synchronously', async () => { - const mx = { - uploadContent: () => { - throw new Error('sync'); - }, - } as any; - await expect( - uploadContent(mx, new Blob(['x']), { onSuccess: vi.fn(), onError: vi.fn() }) - ).rejects.toThrow('sync'); - expect(AbortController.prototype.abort).toBe(original); - }); -}); - -describe('failure text', () => { - const abort = () => new DOMException('', 'AbortError'); - - it('lists abort calls seen during the attempt', async () => { - const mx = { - uploadContent: () => { - new AbortController().abort(); - return Promise.reject(abort()); - }, - } as any; - const onError = vi.fn(); - await uploadContent(mx, new Blob(['x']), { onSuccess: vi.fn(), onError }); - // retried once: the final message carries the second attempt and attempt 1's summary - const msg = onError.mock.calls[0][0].message; - expect(msg).toContain('abort calls: AbortController.abort'); - expect(msg).toContain('retried (attempt 1: AbortError'); - }); - - it('says none when nothing in the page called abort', async () => { - const err = await uploadFailure(abort(), new Blob(['x']), { - startedAt: Date.now(), - aborts: [], - }); - expect(err.message).toContain('abort calls: none'); - }); - - it('reports the component lifecycle when given', async () => { - const mx = { uploadContent: () => Promise.reject(new Error('Timeout')) } as any; - const onError = vi.fn(); - await uploadContent(mx, new Blob(['x']), { - onSuccess: vi.fn(), - onError, - describeLifecycle: () => 'component remounted 0x, renders 3 (2 within 300ms)', - }); - expect(onError.mock.calls[0][0].message).toContain('renders 3 (2 within 300ms)'); - }); -}); - -describe('describeComponentLifecycle', () => { - it('counts renders after attach and those within 300ms, and reports an unmount', () => { - const text = describeComponentLifecycle({ - attachedAt: 1000, - rendersAtAttach: 1, - renders: [990, 1100, 1250, 1400], - unmountedAt: 1500, - }); - expect(text).toBe('component: 3 renders since attach (2 within 300ms), unmounted +500ms'); - }); - - it('says not unmounted when it was not', () => { - const text = describeComponentLifecycle({ - attachedAt: 1000, - rendersAtAttach: 1, - renders: [990], - }); - expect(text).toBe('component: 0 renders since attach (0 within 300ms), not unmounted'); - }); -}); diff --git a/src/app/utils/uploadFailure.test.ts b/src/app/utils/uploadFailure.test.ts index ec1e8115..1dc4af05 100644 --- a/src/app/utils/uploadFailure.test.ts +++ b/src/app/utils/uploadFailure.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; -import { noteUserActivity, uploadFailure } from './matrix'; +import { uploadFailure } from './matrix'; const abort = () => new DOMException('', 'AbortError'); @@ -31,7 +31,9 @@ describe('uploadFailure', () => { const ok = await uploadFailure(abort(), new Blob(['x'])); expect(ok.message).toContain('file readable'); const bad = new Blob(['x']); - (bad as any).arrayBuffer = () => Promise.reject(new DOMException('gone', 'NotReadableError')); + (bad as any).slice = () => ({ + arrayBuffer: () => Promise.reject(new DOMException('gone', 'NotReadableError')), + }); const err = await uploadFailure(abort(), bad); expect(err.message).toContain('file unreadable (NotReadableError)'); }); @@ -51,7 +53,7 @@ describe('uploadFailure client trace', () => { vi.unstubAllGlobals(); }); - it('reports connectivity, visibility and idle time at the moment of failure', async () => { + it('reports connectivity and visibility at the moment of failure', async () => { vi.useFakeTimers(); vi.setSystemTime(10_000); vi.stubGlobal('navigator', { @@ -59,13 +61,11 @@ describe('uploadFailure client trace', () => { connection: { effectiveType: '3g', rtt: 300, downlink: 1.5, saveData: true }, }); vi.stubGlobal('document', { visibilityState: 'hidden' }); - noteUserActivity(); vi.setSystemTime(13_000); const err = await uploadFailure(abort(), blob, { startedAt: 12_000 }); expect(err.message).toContain('offline'); expect(err.message).toContain('3g rtt 300ms down 1.5Mbps saveData on'); expect(err.message).toContain('tab hidden'); - expect(err.message).toContain('idle 3000ms'); expect(err.message).toContain('failed after 1000ms'); }); diff --git a/src/app/utils/uploadReason.test.ts b/src/app/utils/uploadReason.test.ts index d9e83d4d..765b8e41 100644 --- a/src/app/utils/uploadReason.test.ts +++ b/src/app/utils/uploadReason.test.ts @@ -44,9 +44,9 @@ describe('what the sender is told when an upload fails', () => { }); it('a file the browser can no longer read says to pick it again', async () => { - const gone = new Blob(['x']); - (gone as any).arrayBuffer = () => Promise.reject(new DOMException('gone', 'NotReadableError')); - expect(await textOf(abort(), undefined, gone)).toContain('can no longer read the file'); + expect(await textOf(new DOMException('gone', 'NotReadableError'))).toContain( + 'can no longer read the file' + ); }); it('a stopped upload says stopped, not that the connection failed', async () => { @@ -79,13 +79,12 @@ describe('what the sender is told when an upload fails', () => { }); describe('through uploadContent, as the composer and the share panel call it', () => { - it('an unreadable picked file is named before any request', async () => { - const bad = new Blob(['x']); - (bad as any).arrayBuffer = () => Promise.reject(new DOMException('gone', 'NotReadableError')); - const mx = { uploadContent: vi.fn() } as any; + it('an unreadable picked file tells the sender to pick it again', async () => { + const mx = { + uploadContent: () => Promise.reject(new DOMException('gone', 'NotReadableError')), + } as any; const onError = vi.fn(); - await uploadContent(mx, bad, { onSuccess: vi.fn(), onError }); - expect(mx.uploadContent).not.toHaveBeenCalled(); + await uploadContent(mx, blob, { onSuccess: vi.fn(), onError }); expect(uploadFailureText(onError.mock.calls[0][0])).toContain('can no longer read the file'); }); diff --git a/src/app/utils/uploadXhrProbe.test.ts b/src/app/utils/uploadXhrProbe.test.ts deleted file mode 100644 index e72afa3d..00000000 --- a/src/app/utils/uploadXhrProbe.test.ts +++ /dev/null @@ -1,163 +0,0 @@ -/* eslint-disable class-methods-use-this, @typescript-eslint/no-empty-function, @typescript-eslint/no-unused-vars, no-unused-vars */ -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { startAbortProbe, uploadContent } from './matrix'; - -class FakeXhr extends EventTarget { - upload = new EventTarget(); - - readyState = 0; - - status = 0; - - open(_method: string, _url: string) { - this.readyState = 1; - } - - send() { - this.readyState = 2; - } - - abort() {} -} - -const origOpen = FakeXhr.prototype.open; -const origSend = FakeXhr.prototype.send; -const uploadUrl = - 'https://matrix.example/_matrix/media/v3/upload?filename=a.jpg&access_token=SECRET'; - -describe('XHR probe', () => { - afterEach(() => { - vi.unstubAllGlobals(); - FakeXhr.prototype.open = origOpen; - FakeXhr.prototype.send = origSend; - }); - - it('records which events an upload XHR fired and how it ended, without the query string', () => { - vi.stubGlobal('XMLHttpRequest', FakeXhr); - const probe = startAbortProbe(); - const x = new FakeXhr(); - x.open('POST', uploadUrl); - x.send(); - x.upload.dispatchEvent(new Event('loadstart')); - x.upload.dispatchEvent(new Event('error')); - x.dispatchEvent(new Event('error')); - x.readyState = 4; - x.status = 0; - probe.stop(); - expect(probe.xhrs).toHaveLength(1); - const text = probe.describeXhrs(); - expect(text).toContain('POST /_matrix/media/v3/upload'); - expect(text).toContain('readyState 4 status 0'); - expect(text).toContain('upload.loadstart'); - expect(text).toContain('upload.error'); - expect(text).toContain('error'); - expect(text).not.toContain('SECRET'); - expect(text).not.toContain('access_token'); - }); - - it('ignores XHRs that are not uploads', () => { - vi.stubGlobal('XMLHttpRequest', FakeXhr); - const probe = startAbortProbe(); - const x = new FakeXhr(); - x.open('GET', 'https://matrix.example/_matrix/client/v3/sync'); - x.send(); - probe.stop(); - expect(probe.xhrs).toHaveLength(0); - expect(probe.describeXhrs()).toBe('xhr: none seen'); - }); - - it('still calls the real open and send and restores both afterwards', () => { - const open = vi.fn(); - const send = vi.fn(); - FakeXhr.prototype.open = open; - FakeXhr.prototype.send = send; - vi.stubGlobal('XMLHttpRequest', FakeXhr); - const probe = startAbortProbe(); - const x = new FakeXhr(); - x.open('POST', uploadUrl); - x.send(); - expect(open).toHaveBeenCalledWith('POST', uploadUrl); - expect(send).toHaveBeenCalledTimes(1); - probe.stop(); - expect(FakeXhr.prototype.open).toBe(open); - expect(FakeXhr.prototype.send).toBe(send); - }); - - it('records nothing for requests made after stop', () => { - vi.stubGlobal('XMLHttpRequest', FakeXhr); - const probe = startAbortProbe(); - probe.stop(); - const x = new FakeXhr(); - x.open('POST', uploadUrl); - x.send(); - expect(probe.xhrs).toHaveLength(0); - }); -}); - -describe('uploadContent in-memory copy and failure line', () => { - const abort = () => new DOMException('', 'AbortError'); - - it('uploads an in-memory copy with the same bytes, name and type, not the original', async () => { - const file = new File(['abcdef'], 'a.jpg', { type: 'image/jpeg' }); - let sent: any; - const mx = { - uploadContent: vi.fn(async (f: any) => { - sent = f; - return { content_uri: 'mxc://a/b' }; - }), - } as any; - await uploadContent(mx, file, { onSuccess: vi.fn(), onError: vi.fn() }); - expect(sent).not.toBe(file); - expect(sent.type).toBe('image/jpeg'); - expect(sent.name).toBe('a.jpg'); - expect(await sent.text()).toBe('abcdef'); - }); - - it('copies again before the retry', async () => { - const seen: any[] = []; - const mx = { - uploadContent: vi.fn((f: any) => { - seen.push(f); - return seen.length === 1 - ? Promise.reject(abort()) - : Promise.resolve({ content_uri: 'mxc://a/b' }); - }), - } as any; - await uploadContent(mx, new Blob(['xy']), { onSuccess: vi.fn(), onError: vi.fn() }); - expect(seen).toHaveLength(2); - expect(seen[0]).not.toBe(seen[1]); - }); - - it('reports an unreadable file and never starts the upload', async () => { - const bad = new Blob(['x']); - (bad as any).arrayBuffer = () => Promise.reject(new DOMException('gone', 'NotReadableError')); - const mx = { uploadContent: vi.fn() } as any; - const onError = vi.fn(); - await uploadContent(mx, bad, { onSuccess: vi.fn(), onError }); - expect(mx.uploadContent).not.toHaveBeenCalled(); - expect(onError.mock.calls[0][0].message).toContain( - 'unreadable before upload (NotReadableError)' - ); - }); - - it('puts the XHR end state and signal.aborted in the failure line', async () => { - vi.stubGlobal('XMLHttpRequest', FakeXhr); - const mx = { - uploadContent: () => { - const x = new FakeXhr(); - x.open('POST', uploadUrl); - x.send(); - x.upload.dispatchEvent(new Event('error')); - x.readyState = 4; - return Promise.reject(new Error('Timeout')); - }, - } as any; - const onError = vi.fn(); - await uploadContent(mx, new Blob(['x']), { onSuccess: vi.fn(), onError }); - const msg = onError.mock.calls[0][0].message; - expect(msg).toContain('readyState 4 status 0'); - expect(msg).toContain('upload.error'); - expect(msg).toContain('signal.aborted false'); - vi.unstubAllGlobals(); - }); -}); diff --git a/src/phoneGlyph.css.ts b/src/phoneGlyph.css.ts index 14707f63..c9d601f6 100644 --- a/src/phoneGlyph.css.ts +++ b/src/phoneGlyph.css.ts @@ -1,14 +1,13 @@ import { globalStyle } from '@vanilla-extract/css'; import { MOBILE_BREAKPOINT } from './app/hooks/useScreenSize'; -// Phone glyph size. On a phone the glyph inside an IconButton is drawn larger, by `scale` (a paint-time transform: -// the button's box, its PhoneHit area and every row of buttons keep the layout they have, so nothing reflows at -// 320 px). folds draws a glyph at one of its Icon sizes and the IconButton's box is padding plus that glyph, so the -// factor is chosen per Icon size. Desktop is not touched. +// Phone IconButton ergonomics: on a phone each IconButton gets a centred 44 x 44 px ::after hit +// area and its glyph scales up at paint time, so nothing reflows at 320 px. Desktop is not touched. // // The class names are folds 2.7.2's own (the Icon size classes and the IconButton base class); phoneGlyph.test.ts -// reads them back from folds' dist, so a folds upgrade that renames them fails there instead of silently here. +// checks them against folds/dist/style.css, so a folds upgrade that renames them fails there instead of silently here. export const ICON_BUTTON_CLASS = 'brs7ce5'; +export const PHONE_TAP = 44; /** folds Icon size -> [its class, its px, the px it is drawn at on a phone]. The 24 px glyph is the folds default and * reads small in a 40 px button, so it grows too; 28 px and up are already large. */ export const PHONE_GLYPHS = { @@ -21,6 +20,24 @@ export const PHONE_GLYPHS = { const PHONE = `screen and (max-width: ${MOBILE_BREAKPOINT}px)`; +globalStyle(`:where(.${ICON_BUTTON_CLASS})`, { + '@media': { [PHONE]: { position: 'relative' } }, +}); + +globalStyle(`.${ICON_BUTTON_CLASS}::after`, { + '@media': { + [PHONE]: { + content: '""', + position: 'absolute', + top: '50%', + left: '50%', + width: `max(100%, ${PHONE_TAP}px)`, + height: `max(100%, ${PHONE_TAP}px)`, + transform: 'translate(-50%, -50%)', + }, + }, +}); + Object.values(PHONE_GLYPHS).forEach(({ cls, px, phonePx }) => globalStyle(`.${ICON_BUTTON_CLASS} > .${cls}`, { '@media': { [PHONE]: { scale: `${phonePx / px}` } }, diff --git a/src/sky/README.md b/src/sky/README.md index 1f816a15..88556b7e 100644 --- a/src/sky/README.md +++ b/src/sky/README.md @@ -1,8 +1,8 @@ # Baked sky `npm run bake:sky` (`scripts/bake-sky.mjs`) lights two fixed moments with `sun.js`, the single source of -the sun and the air, and writes `baked.ts`. `baked.midnight`, `baked.noonday` and `baked.scatter` are its -three keys. Everything here is linear RGB unless a name says `hex`. +the sun and the air, and writes `baked.ts`. `baked.midnight` and `baked.noonday` are its +two keys. Everything here is linear RGB unless a name says `hex`. ## Per sky: `baked.midnight`, `baked.noonday` @@ -10,7 +10,7 @@ three keys. Everything here is linear RGB unless a name says `hex`. | ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- | | `moment` | `{ time, lat, lon }` fed to `sun.js` (equinox, 45N, prime meridian; 00:00 and 12:00 UTC) | | `elevation` | sun elevation in degrees at that moment: -44.6 midnight, +45.2 noonday | -| `sun.elevation_deg` | the same, for scene code; fade stars by this (and see below for twilight) | +| `sun.elevation_deg` | the same, for scene code; fade stars by this | | `sun.azimuth_deg` | degrees clockwise from north, 0..360 | | `sun.color_linear` | direct sun colour at normal incidence, clear zenith ~ 1; multiply by `max(0, dot(n, toSun))` | | `ambient_linear` | sky ambient on an upward surface, with a night floor of `AMBIENT_FLOOR` (a moonlit skyglow, not black); daylight is `sun.js`'s own `diffuse` | @@ -20,86 +20,4 @@ three keys. Everything here is linear RGB unless a name says `hex`. The two skies are single moments. To fade stars through twilight, take the elevation from `sun.js` at the viewer's real time (`sunPosition(time, lat, lon).elevation`) rather than from `baked..sun`, which only -ever says -44.6 or +45.2. The scattering table below goes dark at -12 degrees and below (the planet's shadow -covers every sunlit air path), so a star fade between about -6 and -12 degrees follows it. - -## `baked.scatter`: atmospheric scattering for a WebGL2 shader - -A Hillaire-style (2020) single-scattering atmosphere, reduced to two small tables. The air is `sun.js`'s: -`TAU` (its zenith optical depth per channel) is the vertical optical depth here, split into a grey aerosol -part (0.02) and a Rayleigh part, so the transmittance table equals `exp(-TAU)` at the zenith. Planet radius -6360 km, atmosphere 100 km, scale heights 8 km (Rayleigh) and 1.2 km (Mie, g = 0.8, albedo 0.9), observer -100 m above the ground. Single scattering only: no ground bounce, no multiple scattering, no sun disc -(the consumer draws it from `sun.color_linear`). That makes dusk a little darker than the real thing. - -Constants: `planet_radius_km`, `atmosphere_height_km`, `observer_altitude_km`, `extinction_per_km` (RGB at the -observer, for aerial perspective: `exp(-k * distance_km)`). - -### Encoding (both tables) - -IEEE 754 half floats (16 bit), little-endian, base64 of the raw bytes, no header. The stored value is -`value * store_scale` (`store_scale` = 64; it lifts the dark end of twilight clear of the half-float -subnormals). Exact decode: for a 16-bit word `h`, `e = (h >> 10) & 31`, `m = h & 1023`, -`half = e == 0 ? m * 2^-24 : (1 + m / 1024) * 2^(e - 15)` (no infinities or NaNs are stored), and -`value = half / store_scale`. In WebGL2 upload as `RGB16F` / `HALF_FLOAT` from a `Uint16Array` over the -decoded bytes, and the GPU does the decode: sample, then divide by `store_scale`. Precision is 11 bits -(about 0.05%): the horizon glow does not step. - -### `transmittance`: `width` 32, `height` 1, 3 channels - -Transmittance from the observer to space along a view elevation, per channel. Texel `i` is the elevation -`-4 + 94 * (i / 31)^2` degrees (`viewElevation(i)` in `scatter.js`; the inverse is `viewIndex(deg)`): -finest at the horizon. Elevations that look at the ground (-4 to about -0.3) are 0. Sample it for the sun's -direct colour: at the sun's elevation, `sun.color_linear`-like attenuation, redder as it sets. - -### `sky_view`: `width` 7, `height` 32, `depth` 12, 3 channels - -Sky radiance per steradian for a sun of unit irradiance (multiply by your own sun colour and exposure). -One 3D texture, `x` fastest: - -- `x`: azimuth of the view away from the sun, 0, 30, ... 180 degrees (`azimuth_step_deg`). The sky is - symmetric about the sun's vertical plane, so use `abs` of the relative azimuth. -- `y`: view elevation, same axis as the transmittance table (`viewElevation(i)`). -- `z`: sun elevation, `sun_elevations_deg` = -18, -12, -8, -5, -2, 0, 3, 8, 15, 25, 45, 90. Between them - interpolate linearly; `sunIndex(deg)` in `scatter.js` gives the fractional index. - -Element `((z * 32 + y) * 7 + x) * 3 + c` of the decoded array. Texel centres, for linear filtering: - -```glsl -uniform highp sampler3D uSky; // RGB16F, 7 x 32 x 12, LINEAR, CLAMP_TO_EDGE -uniform float uSunIndex; // sunIndex(sunElevationDeg), 0..11, from the CPU -vec3 skyRadiance(float viewElDeg, float azFromSunDeg) { - float y = sqrt(clamp((viewElDeg + 4.0) / 94.0, 0.0, 1.0)) * 31.0; - float x = clamp(abs(azFromSunDeg) / 180.0, 0.0, 1.0) * 6.0; - return texture(uSky, vec3((x + 0.5) / 7.0, (y + 0.5) / 32.0, (uSunIndex + 0.5) / 12.0)).rgb / 64.0; -} -``` - -Row width is 21 bytes, so set `gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)` before `texImage3D`. - -Size: 16,128 bytes for `sky_view` (21.5 KB as base64) and 192 bytes for `transmittance`; about -twice the "few KB" of an 8-bit table, the price of not quantising the glow. `scatter.test.ts` pins the -layout, the encoding, the checksums and a set of physical anchors (blue noon sky, red sunset toward the sun, -black below the planet's shadow limit). - -### `aerial_perspective`: the camera volume for ground seen through the air - -After Hillaire, "A Scalable and Production Ready Sky and Atmosphere Rendering Technique", EGSR 2020, section 5.4, and its -reference code (sebh/UnrealEngineSkyAtmosphere, `RenderCameraVolumePS` in `RenderSkyRayMarching.hlsl`). RGBA half floats -(same encoding, `store_scale` 64), `width` 7, `height` 96, `depth` 12, 4 channels; one 3D texture, `x` fastest: - -- `x`: azimuth of the view ray from the light, 0, 30, ... 180 degrees (as `sky_view`). -- `y`: `slice * 8 + elevation`: 12 slices, each a block of 8 view elevations, `-50 * (1 - i / 7)^2` degrees (finest at 0, - rays at or above the horizon are clamped to 0). Keep the filter inside a block: sample at `(slice * 8 + e + 0.5) / 96`, `e` in 0..7. -- `z`: light elevation, `sun_elevations_deg`, as `sky_view`. The same volume serves the moon: look up at the moon's elevation. -- Slice `k` is the far side of `max_km * ((k + 1) / 12)^2` km (the paper's squared distribution; `max_km` 20). Between slices interpolate - linearly; below slice 0 fade to zero at the observer, as the reference does for `Slice < 0.5`. -- RGB: in-scatter luminance per steradian for a light of unit irradiance. A: opacity `1 - mean(rgb transmittance)`, the paper's grey - transmittance. Apply as `surface * (1 - A) + L * exposure`. - -Follows the paper: the squared slice distribution, the in-scatter integral with each step's extinction integrated analytically -(`S (1 - exp(-e dt)) / e`), single scattering with Rayleigh and Mie (g 0.8) phase, and the grey opacity in alpha. -Shortcuts: sun-relative azimuth and elevation instead of screen position; 12 x 8 x 7 texels, not 32 x 32 x 32; path lengths are the -scene's metres times `distance_scale` (8), because a real atmosphere is nearly clear across a 3 km patch; the ray ignores the ground -(density held at its ground value, sun visibility tested from the ground sphere); no multi-scattering LUT (the paper's dusk fix); -observer at 100 m. Units: distances in km, radiance per unit sun irradiance, as `sky_view`. 86 KB as base64. +ever says -44.6 or +45.2. diff --git a/src/sky/baked.ts b/src/sky/baked.ts index 73c93bd5..b916dc75 100644 --- a/src/sky/baked.ts +++ b/src/sky/baked.ts @@ -233,44 +233,4 @@ export const baked = { ], link: '#2a4f27', }, - scatter: { - planet_radius_km: 6360, - atmosphere_height_km: 100, - observer_altitude_km: 0.1, - extinction_per_km: [0.020271980981493083, 0.02767884208799963, 0.044961518003181586], - format: 'half-float', - store_scale: 64, - view_elevation_deg: { - min: -4, - max: 90, - samples: 32, - }, - transmittance: { - width: 32, - height: 1, - channels: 3, - data: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAArkjBP0wqR02AR145qk9vS4BBtlCITWBGW1EcT3dJ1FE1UN5LL1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90DX5Oac97jX8Oag97jX8Oag97jX8Oag97jX8Oag97jX8Oag97jX8Oag97jX8Oag9MzYVOrQ9MzYVOrQ9MzYVOrQ9MzYVOrQ9MzYVOrQ9MzYVOrQ9MzYVOrQ9sjZMOs89sjZMOs89sjZMOs89sjZMOs89sjZMOs89sjZMOs89sjZMOs89lje2OgE+lje2OgE+lje2OgE+lje2OgE+lje2OgE+lje2OgE+lje2OgE+oTh+O1s+oTh+O1s+oTh+O1s+oTh+O1s+oTh+O1s+oTh+O1s+oTh+O1s+SDqFPAo/SDqFPAo/SDqFPAo/SDqFPAo/SDqFPAo/SDqFPAo/SDqFPAo/2TwfPjZA2TwfPjZA2TwfPjZA2TwfPjZA2TwfPjZA2TwfPjZA2TwfPjZA6z9/QHJB6z9/QHJB6z9/QHJB6z9/QHJB6z9/QHJB6z9/QHJB6z9/QHJBGUGQQVtCGUGQQVtCGUGQQVtCGUGQQVtCGUGQQVtCGUGQQVtCGUGQQVtC', - }, - aerial_perspective: { - slices: 12, - elevations: 8, - elevation_min_deg: -50, - max_km: 20, - distance_scale: 8, - width: 7, - height: 96, - depth: 12, - channels: 4, - data: 'AAAAAAAAgjQAAAAAAACCNAAAAAAAAII0AAAAAAAAgjQAAAAAAACCNAAAAAAAAII0AAAAAAAAgjQAAAAAAAB8NAAAAAAAAHw0AAAAAAAAfDQAAAAAAAB8NAAAAAAAAHw0AAAAAAAAfDQAAAAAAAB8NAAAAAAAAHU0AAAAAAAAdTQAAAAAAAB1NAAAAAAAAHU0AAAAAAAAdTQAAAAAAAB1NAAAAAAAAHU0AAAAAAAAbzQAAAAAAABvNAAAAAAAAG80AAAAAAAAbzQAAAAAAABvNAAAAAAAAG80AAAAAAAAbzQAAAAAAABrNAAAAAAAAGs0AAAAAAAAazQAAAAAAABrNAAAAAAAAGs0AAAAAAAAazQAAAAAAABrNAAAAAAAAGg0AAAAAAAAaDQAAAAAAABoNAAAAAAAAGg0AAAAAAAAaDQAAAAAAABoNAAAAAAAAGg0AA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r02wzmwPFZOvTbDObA8Vk69NsM5sDxWTr02wzmwPFZOvTbDObA8Vk56OHc8uD94T3o4dzy4P3hPejh3PLg/eE96OHc8uD94T3o4dzy4P3hPejh3PLg/eE96OHc8uD94Tws41TutPnhPCzjVO60+eE8LONU7rT54Tws41TutPnhPCzjVO60+eE8LONU7rT54Tws41TutPnhPjzcPO+k9eE+PNw876T14T483DzvpPXhPjzcPO+k9eE+PNw876T14T483DzvpPXhPjzcPO+k9eE9lN6Y6dz13T2U3pjp3PXdPZTemOnc9d09lN6Y6dz13T2U3pjp3PXdPZTemOnc9d09lN6Y6dz13T383hzpGPXdPfzeHOkY9d09/N4c6Rj13T383hzpGPXdPfzeHOkY9d09/N4c6Rj13T383hzpGPXdPuDeQOjs9dk+4N5A6Oz12T7g3kDo7PXZPuDeQOjs9dk+4N5A6Oz12T7g3kDo7PXZPuDeQOjs9dk/oN6I6QD1uT+g3ojpAPW5P6DeiOkA9bk/oN6I6QD1uT+g3ojpAPW5P6DeiOkA9bk/oN6I6QD1uT8Y3lTo+PS9PxjeVOj49L0/GN5U6Pj0vT8Y3lTo+PS9PxjeVOj49L0/GN5U6Pj0vT8Y3lTo+PS9P', - }, - }, } as const; diff --git a/src/sky/scatter.js b/src/sky/scatter.js deleted file mode 100644 index bd12b7e0..00000000 --- a/src/sky/scatter.js +++ /dev/null @@ -1,362 +0,0 @@ -// Atmospheric scattering tables, baked for a WebGL2 shader (layout: src/sky/README.md). -// Dependency-free apart from sun.js, so scripts/bake-sky.mjs and the tests run it under plain node. -// -// bakeScatter() -> { transmittance, sky_view, ... } with base64 RGB16F tables (half floats). -// -// A Hillaire-style single-scattering model (Rayleigh + Mie, spherical planet, observer 100 m up), -// reduced to two small tables: the transmittance of the whole atmosphere along a view direction, and -// the sky's radiance by sun elevation, view elevation and azimuth from the sun. sun.js stays the -// single source of the air: its zenith optical depths (TAU, per channel) are the vertical optical -// depth of this atmosphere, split into a grey aerosol part and a Rayleigh part. So the direct sun -// sun.js returns and the transmittance here agree at the zenith; only the air-mass law differs -// (Kasten-Young there, the spherical integral here). - -import { TAU } from './sun.js'; - -const RAD = Math.PI / 180; -const clamp = (x, lo, hi) => Math.min(hi, Math.max(lo, x)); - -// Geometry (km) and scale heights. -export const PLANET_RADIUS_KM = 6360; -export const ATMOSPHERE_HEIGHT_KM = 100; -export const OBSERVER_ALTITUDE_KM = 0.1; -const H_RAYLEIGH = 8; -const H_MIE = 1.2; -const MIE_ALBEDO = 0.9; // single-scattering albedo of the aerosol (EYEBALLED) -const MIE_G = 0.8; // Henyey-Greenstein asymmetry (Hillaire 2020) -const MIE_TAU = 0.02; // grey aerosol vertical optical depth (EYEBALLED); the rest of TAU is Rayleigh - -// Vertical optical depth of an exponential layer of scale height H over the atmosphere. -const column = (H) => H * (1 - Math.exp(-ATMOSPHERE_HEIGHT_KM / H)); -const BETA_RAYLEIGH = TAU.map((tau) => (tau - MIE_TAU) / column(H_RAYLEIGH)); // per km at sea level -const BETA_MIE_EXT = MIE_TAU / column(H_MIE); -const BETA_MIE_SCA = BETA_MIE_EXT * MIE_ALBEDO; - -// Table axes. -export const SUN_ELEVATIONS_DEG = [-18, -12, -8, -5, -2, 0, 3, 8, 15, 25, 45, 90]; -export const VIEW_SAMPLES = 32; -export const AZIMUTH_SAMPLES = 7; // 0, 30, ... 180 degrees from the sun -export const AZIMUTH_STEP_DEG = 30; -export const VIEW_MIN_DEG = -4; -export const VIEW_MAX_DEG = 90; -// Tables hold IEEE 754 half floats, little-endian, holding value * STORE_SCALE. The scale lifts the -// dark end (twilight sky radiance is ~1e-4) clear of the half-float subnormals; the brightest -// stored value, a Mie peak near 0.3 x 64, is far below the format's 65504. -export const STORE_SCALE = 64; - -/** View elevation in degrees of sample index i of VIEW_SAMPLES: finest at the horizon. */ -export const viewElevation = (i) => - VIEW_MIN_DEG + (VIEW_MAX_DEG - VIEW_MIN_DEG) * (i / (VIEW_SAMPLES - 1)) ** 2; - -/** Fractional index into SUN_ELEVATIONS_DEG of a sun elevation (clamped to the table): the z texel coordinate. */ -export const sunIndex = (elevationDeg) => { - const e = clamp( - elevationDeg, - SUN_ELEVATIONS_DEG[0], - SUN_ELEVATIONS_DEG[SUN_ELEVATIONS_DEG.length - 1] - ); - const k = Math.min(SUN_ELEVATIONS_DEG.findIndex((x) => x > e) - 1, SUN_ELEVATIONS_DEG.length - 2); - const i = k < 0 ? SUN_ELEVATIONS_DEG.length - 2 : k; - return i + (e - SUN_ELEVATIONS_DEG[i]) / (SUN_ELEVATIONS_DEG[i + 1] - SUN_ELEVATIONS_DEG[i]); -}; - -/** Inverse of viewElevation: the fractional sample index of an elevation. */ -export const viewIndex = (elevationDeg) => - Math.sqrt(clamp((elevationDeg - VIEW_MIN_DEG) / (VIEW_MAX_DEG - VIEW_MIN_DEG), 0, 1)) * - (VIEW_SAMPLES - 1); - -/** Round a non-negative number to the nearest IEEE 754 half float (ties to even); returns its 16 bits. */ -export function toHalf(x) { - if (!(x > 0)) return 0; - const u = new Uint32Array(new Float32Array([x]).buffer)[0]; - const exp = ((u >> 23) & 0xff) - 127 + 15; - const mant = u & 0x7fffff; - if (exp >= 31) return 0x7bff; - let half; - let rem; - let halfway; - if (exp <= 0) { - if (exp < -10) return 0; - const m = mant | 0x800000; - const shift = 14 - exp; - half = m >> shift; - rem = m & ((1 << shift) - 1); - halfway = 1 << (shift - 1); - } else { - half = (exp << 10) | (mant >> 13); - rem = mant & 0x1fff; - halfway = 0x1000; - } - return rem > halfway || (rem === halfway && half & 1) ? half + 1 : half; -} - -/** The exact value of 16 half-float bits (finite values only). */ -export const fromHalf = (h) => { - const e = (h >> 10) & 31; - const m = h & 1023; - return e === 0 ? m * 2 ** -24 : (1 + m / 1024) * 2 ** (e - 15); -}; - -/** Stored 16 bits of a value, and the value back out of them. */ -export const encode = (v) => toHalf(v * STORE_SCALE); -export const decode = (h) => fromHalf(h) / STORE_SCALE; - -const extinction = (h) => { - const r = Math.exp(-h / H_RAYLEIGH); - const m = Math.exp(-h / H_MIE); - return BETA_RAYLEIGH.map((b) => b * r + BETA_MIE_EXT * m); -}; - -// Distance along ray (origin o, unit direction d) to the sphere of radius r centred on the origin -// of the planet: the far root, or the near root if `near`. Infinity when it misses or is behind. -function sphereHit(o, d, r, near) { - const b = o[0] * d[0] + o[1] * d[1] + o[2] * d[2]; - const c = o[0] * o[0] + o[1] * o[1] + o[2] * o[2] - r * r; - const disc = b * b - c; - if (disc < 0) return Infinity; - const sq = Math.sqrt(disc); - const t = near ? -b - sq : -b + sq; - return t > 0 ? t : Infinity; -} - -// Optical depth per channel from p along d to the top of the atmosphere; Infinity if the planet is in the way. -function opticalDepthToSpace(p, d, steps) { - if (sphereHit(p, d, PLANET_RADIUS_KM, true) !== Infinity) return null; - const top = sphereHit(p, d, PLANET_RADIUS_KM + ATMOSPHERE_HEIGHT_KM, false); - const dt = top / steps; - const depth = [0, 0, 0]; - for (let k = 0; k < steps; k += 1) { - const t = (k + 0.5) * dt; - const q = [p[0] + d[0] * t, p[1] + d[1] * t, p[2] + d[2] * t]; - const e = extinction(Math.hypot(...q) - PLANET_RADIUS_KM); - for (let c = 0; c < 3; c += 1) depth[c] += e[c] * dt; - } - return depth; -} - -const observer = [0, PLANET_RADIUS_KM + OBSERVER_ALTITUDE_KM, 0]; -const viewDirection = (elevationDeg, azimuthDeg) => { - const e = elevationDeg * RAD; - const a = azimuthDeg * RAD; - return [Math.cos(e) * Math.cos(a), Math.sin(e), Math.cos(e) * Math.sin(a)]; -}; -const sunDirection = (elevationDeg) => [ - Math.cos(elevationDeg * RAD), - Math.sin(elevationDeg * RAD), - 0, -]; - -/** Transmittance per channel from the observer along an elevation to space; zeros where the ground is in the way. */ -export function transmittance(elevationDeg) { - const depth = opticalDepthToSpace(observer, viewDirection(elevationDeg, 0), 64); - return depth ? depth.map((x) => Math.exp(-x)) : [0, 0, 0]; -} - -const rayleighPhase = (c) => (3 / (16 * Math.PI)) * (1 + c * c); -const miePhase = (c) => - (1 - MIE_G * MIE_G) / (4 * Math.PI * (1 + MIE_G * MIE_G - 2 * MIE_G * c) ** 1.5); - -/** - * Sky radiance per channel, per steradian, for a sun of unit irradiance (so the consumer multiplies by - * its own sun colour), in a view direction at an elevation and an azimuth measured from the sun. - * Single scattering, no ground bounce, no sun disc. - */ -export function skyRadiance(sunElevationDeg, viewElevationDeg, azimuthDeg) { - const v = viewDirection(viewElevationDeg, azimuthDeg); - const s = sunDirection(sunElevationDeg); - const cosTheta = v[0] * s[0] + v[1] * s[1] + v[2] * s[2]; - const pr = rayleighPhase(cosTheta); - const pm = miePhase(cosTheta); - const ground = sphereHit(observer, v, PLANET_RADIUS_KM, true); - const top = sphereHit(observer, v, PLANET_RADIUS_KM + ATMOSPHERE_HEIGHT_KM, false); - const end = Math.min(ground, top); - const steps = 24; - const dt = end / steps; - const along = [0, 0, 0]; - const radiance = [0, 0, 0]; - for (let k = 0; k < steps; k += 1) { - const t = (k + 0.5) * dt; - const q = [observer[0] + v[0] * t, observer[1] + v[1] * t, observer[2] + v[2] * t]; - const h = Math.hypot(...q) - PLANET_RADIUS_KM; - const e = extinction(h); - for (let c = 0; c < 3; c += 1) along[c] += e[c] * dt; - const toSun = opticalDepthToSpace(q, s, 12); - if (toSun) { - const r = Math.exp(-h / H_RAYLEIGH); - const m = Math.exp(-h / H_MIE); - for (let c = 0; c < 3; c += 1) { - const scatter = BETA_RAYLEIGH[c] * r * pr + BETA_MIE_SCA * m * pm; - radiance[c] += Math.exp(-along[c] - toSun[c]) * scatter * dt; - } - } - } - return radiance; -} - -// ---- Aerial perspective ------------------------------------------------------------------------------------------ -// After Hillaire, "A Scalable and Production Ready Sky and Atmosphere Rendering Technique", EGSR 2020 (section 5.4, the -// aerial perspective "camera volume"), and its reference implementation, sebh/UnrealEngineSkyAtmosphere -// Resources/RenderSkyRayMarching.hlsl `RenderCameraVolumePS`: a volume of AP_SLICES slices whose depth grows with the -// square of the slice index (`Slice *= Slice`), each texel holding the single-scattered luminance L accumulated along -// the view ray to that depth, and in alpha the opacity 1 - mean(rgb transmittance) (a grey transmittance, as the paper). -// Applied to a surface as out = surface * (1 - alpha) + L, with L the in-scatter along that ray. -// -// What differs from the paper, and why: -// - the volume is indexed by the view ray relative to the sun (azimuth from the sun, elevation) and sun elevation, not by -// screen position, because the terrain camera turns and the sky tables here are sun-relative too; -// - the path lengths are the scene's length times AP_DISTANCE_SCALE: a real atmosphere is nearly clear over the 3 km patch, -// so the baked path is that many times longer (EYEBALLED); it sets how fast far ridges go to the sky; -// - the ray ignores the ground: below the observer's altitude the density is held at its ground value, and the sun's -// visibility is tested from the ground sphere; the terrain is the ground; -// - single scattering with the sky tables' own air (no multi-scattering LUT, which the paper adds for dusk); -// - AP_SLICES = 12 slices, 8 view elevations and 7 azimuths, not 32 x 32 x 32 screen froxels, to stay phone-sized. -export const AP_SLICES = 12; -export const AP_ELEVATIONS = 8; -/** The view elevations the volume holds run from this down to 0 degrees, finest at 0: -AP_ELEVATION_MIN_DEG * (1 - i / 7)^2. */ -export const AP_ELEVATION_MIN_DEG = 50; -/** Scene metres a slice volume covers: the patch's far corner (about 2.1 km) with margin. */ -export const AP_SCENE_MAX_M = 2500; -export const AP_DISTANCE_SCALE = 8; -/** Physical kilometres the last slice stands for. */ -export const AP_MAX_KM = (AP_SCENE_MAX_M * AP_DISTANCE_SCALE) / 1000; -const AP_SUBSTEPS = 4; - -export const apElevation = (i) => -AP_ELEVATION_MIN_DEG * (1 - i / (AP_ELEVATIONS - 1)) ** 2; -/** Fractional elevation index of a view elevation in degrees (clamped to 0 degrees and below). */ -export const apElevationIndex = (deg) => - (AP_ELEVATIONS - 1) * (1 - Math.sqrt(clamp(-deg / AP_ELEVATION_MIN_DEG, 0, 1))); -/** Distance in km at the far side of slice k (k = 0 .. AP_SLICES - 1): the squared distribution. */ -export const apSliceKm = (k) => AP_MAX_KM * ((k + 1) / AP_SLICES) ** 2; -/** Fractional slice index of a distance in km: below 0 the volume fades to nothing at the observer. */ -export const apSliceIndex = (km) => AP_SLICES * Math.sqrt(Math.max(km, 0) / AP_MAX_KM) - 1; - -/** - * In-scatter luminance per channel (for a sun of unit irradiance) and opacity along a view ray from the observer, - * at the far side of each of AP_SLICES slices: [[r, g, b, alpha] x AP_SLICES]. - */ -export function aerialRay(sunElevationDeg, viewElevationDeg, azimuthDeg) { - const v = viewDirection(viewElevationDeg, azimuthDeg); - const s = sunDirection(sunElevationDeg); - const cosTheta = v[0] * s[0] + v[1] * s[1] + v[2] * s[2]; - const pr = rayleighPhase(cosTheta); - const pm = miePhase(cosTheta); - const out = []; - const along = [0, 0, 0]; - const radiance = [0, 0, 0]; - let from = 0; - for (let k = 0; k < AP_SLICES; k += 1) { - const to = apSliceKm(k); - const dt = (to - from) / AP_SUBSTEPS; - for (let j = 0; j < AP_SUBSTEPS; j += 1) { - const t = from + (j + 0.5) * dt; - let q = [observer[0] + v[0] * t, observer[1] + v[1] * t, observer[2] + v[2] * t]; - const r = Math.hypot(...q); - if (r < PLANET_RADIUS_KM) q = q.map((x) => (x * PLANET_RADIUS_KM) / r); - const h = Math.max(r - PLANET_RADIUS_KM, 0); - const e = extinction(h); - const toSun = opticalDepthToSpace(q, s, 12); - const rm = Math.exp(-h / H_RAYLEIGH); - const mm = Math.exp(-h / H_MIE); - for (let c = 0; c < 3; c += 1) { - // The step's own extinction is integrated analytically (Hillaire eq. 6): S (1 - exp(-e dt)) / e. - const step = Math.exp(-e[c] * dt); - if (toSun) { - const scatter = BETA_RAYLEIGH[c] * rm * pr + BETA_MIE_SCA * mm * pm; - radiance[c] += Math.exp(-along[c] - toSun[c]) * ((scatter * (1 - step)) / e[c]); - } - along[c] += e[c] * dt; - } - } - from = to; - const mean = along.reduce((a, x) => a + Math.exp(-x), 0) / 3; - out.push([...radiance, 1 - mean]); - } - return out; -} - -const base64 = (halves) => { - const bytes = new Uint8Array(halves.length * 2); - halves.forEach((h, i) => { - bytes[i * 2] = h & 0xff; // little-endian - bytes[i * 2 + 1] = h >> 8; - }); - let s = ''; - for (let i = 0; i < bytes.length; i += 0x8000) { - s += String.fromCharCode(...bytes.subarray(i, i + 0x8000)); - } - return btoa(s); -}; - -export function bakeScatter() { - const view = Array.from({ length: VIEW_SAMPLES }, (_, i) => viewElevation(i)); - - const t = new Uint16Array(VIEW_SAMPLES * 3); - view.forEach((e, i) => transmittance(e).forEach((v, c) => (t[i * 3 + c] = encode(v)))); - - // x = azimuth, y = view elevation, z = sun elevation, three half floats per texel: a 3D texture. - const sky = new Uint16Array(SUN_ELEVATIONS_DEG.length * VIEW_SAMPLES * AZIMUTH_SAMPLES * 3); - let at = 0; - SUN_ELEVATIONS_DEG.forEach((sun) => - view.forEach((e) => { - for (let a = 0; a < AZIMUTH_SAMPLES; a += 1) { - skyRadiance(sun, e, a * AZIMUTH_STEP_DEG).forEach((v) => { - sky[at] = encode(v); - at += 1; - }); - } - }) - ); - - // x = azimuth from the sun, y = elevation block k * AP_ELEVATIONS + i (slice-major), z = sun elevation: four half floats per texel (L rgb, alpha). - const aerial = new Uint16Array( - SUN_ELEVATIONS_DEG.length * AP_SLICES * AP_ELEVATIONS * AZIMUTH_SAMPLES * 4 - ); - let ap = 0; - SUN_ELEVATIONS_DEG.forEach((sun) => { - const rays = Array.from({ length: AP_ELEVATIONS }, (_, i) => - Array.from({ length: AZIMUTH_SAMPLES }, (_, a) => - aerialRay(sun, apElevation(i), a * AZIMUTH_STEP_DEG) - ) - ); - for (let k = 0; k < AP_SLICES; k += 1) - for (let i = 0; i < AP_ELEVATIONS; i += 1) - for (let a = 0; a < AZIMUTH_SAMPLES; a += 1) - rays[i][a][k].forEach((x) => { - aerial[ap] = encode(x); - ap += 1; - }); - }); - - return { - planet_radius_km: PLANET_RADIUS_KM, - atmosphere_height_km: ATMOSPHERE_HEIGHT_KM, - observer_altitude_km: OBSERVER_ALTITUDE_KM, - // Extinction per km at the observer, per channel, for aerial perspective: exp(-k * distance_km). - extinction_per_km: extinction(OBSERVER_ALTITUDE_KM), - format: 'half-float', - store_scale: STORE_SCALE, - view_elevation_deg: { min: VIEW_MIN_DEG, max: VIEW_MAX_DEG, samples: VIEW_SAMPLES }, - transmittance: { width: VIEW_SAMPLES, height: 1, channels: 3, data: base64(t) }, - sky_view: { - sun_elevations_deg: SUN_ELEVATIONS_DEG, - azimuth_step_deg: AZIMUTH_STEP_DEG, - width: AZIMUTH_SAMPLES, - height: VIEW_SAMPLES, - depth: SUN_ELEVATIONS_DEG.length, - channels: 3, - data: base64(sky), - }, - aerial_perspective: { - slices: AP_SLICES, - elevations: AP_ELEVATIONS, - elevation_min_deg: -AP_ELEVATION_MIN_DEG, - max_km: AP_MAX_KM, - distance_scale: AP_DISTANCE_SCALE, - width: AZIMUTH_SAMPLES, - height: AP_SLICES * AP_ELEVATIONS, - depth: SUN_ELEVATIONS_DEG.length, - channels: 4, - data: base64(aerial), - }, - }; -} diff --git a/src/sky/scatter.test.ts b/src/sky/scatter.test.ts deleted file mode 100644 index e0ea9023..00000000 --- a/src/sky/scatter.test.ts +++ /dev/null @@ -1,226 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { - AP_ELEVATIONS, - AP_MAX_KM, - AP_SLICES, - apElevation, - apElevationIndex, - apSliceIndex, - apSliceKm, - aerialRay, - AZIMUTH_SAMPLES, - AZIMUTH_STEP_DEG, - STORE_SCALE, - SUN_ELEVATIONS_DEG, - VIEW_SAMPLES, - bakeScatter, - decode, - fromHalf, - skyRadiance, - sunIndex, - toHalf, - transmittance, - viewElevation, - viewIndex, -} from './scatter.js'; -import { TAU } from './sun.js'; -import { baked } from './baked'; - -const table = (b64: string): Uint16Array => { - const bin = atob(b64); - const bytes = Uint8Array.from(bin, (c) => c.charCodeAt(0)); - return new Uint16Array(bytes.buffer); -}; -// Checksums of the baked halves, so a change to the model or the encoding is a deliberate re-pin. -const SKY_CHECKSUM = 622927107; -const TRANS_CHECKSUM = 1498461058; -// eslint-disable-next-line @typescript-eslint/no-explicit-any -const scatter = baked.scatter as any; -const sky = table(scatter.sky_view.data); -const trans = table(scatter.transmittance.data); -const sunIndex_ = (deg: number) => SUN_ELEVATIONS_DEG.indexOf(deg); -// Texel of the sky table: x = azimuth, y = view elevation, z = sun elevation; value = three halves. -const texel = (s: number, v: number, a: number) => - [0, 1, 2].map((c) => decode(sky[((s * VIEW_SAMPLES + v) * AZIMUTH_SAMPLES + a) * 3 + c])); - -describe('half floats', () => { - it('round-trip within half precision across the table range, ties to even', () => { - [6.1e-5, 1e-4, 0.0123, 0.3, 1, 20, 1000].forEach((x) => - expect(Math.abs(fromHalf(toHalf(x)) - x) / x).toBeLessThan(5.1e-4) - ); - expect(toHalf(0)).toBe(0); - expect(toHalf(1)).toBe(0x3c00); - expect(toHalf(2 ** -24)).toBe(1); // smallest subnormal - expect(toHalf(1 + 2 ** -11)).toBe(0x3c00); // exact tie goes to the even neighbour - expect(toHalf(1 + 3 * 2 ** -11)).toBe(0x3c02); - expect(fromHalf(0x7bff)).toBe(65504); - }); - - it('keeps twilight radiance, ~1e-4, within 0.1% thanks to the store scale', () => { - const x = 1.234e-4; - expect(Math.abs(decode(toHalf(x * STORE_SCALE)) - x) / x).toBeLessThan(1e-3); - }); -}); - -describe('sunIndex', () => { - it('is the fractional position of an elevation on the sun axis, clamped to the table', () => { - expect(sunIndex(-18)).toBe(0); - expect(sunIndex(90)).toBe(SUN_ELEVATIONS_DEG.length - 1); - expect(sunIndex(-100)).toBe(0); - expect(sunIndex(100)).toBe(SUN_ELEVATIONS_DEG.length - 1); - expect(sunIndex(0)).toBe(sunIndex_(0)); - expect(sunIndex(1.5)).toBeCloseTo(sunIndex_(0) + 0.5, 12); // halfway between 0 and 3 - expect(sunIndex(35)).toBeCloseTo(sunIndex_(25) + 0.5, 12); // halfway between 25 and 45 - }); -}); - -describe('scattering tables', () => { - it('are what scripts/bake-sky.mjs would write now (run npm run bake:sky if not)', () => { - expect(JSON.parse(JSON.stringify(bakeScatter()))).toEqual(JSON.parse(JSON.stringify(scatter))); - }); - - it('have the documented layout and size', () => { - expect(scatter.format).toBe('half-float'); - expect(scatter.sky_view).toMatchObject({ - width: AZIMUTH_SAMPLES, - height: VIEW_SAMPLES, - depth: SUN_ELEVATIONS_DEG.length, - channels: 3, - azimuth_step_deg: AZIMUTH_STEP_DEG, - }); - expect(sky.length).toBe(AZIMUTH_SAMPLES * VIEW_SAMPLES * SUN_ELEVATIONS_DEG.length * 3); - expect(trans.length).toBe(VIEW_SAMPLES * 3); - expect(sky.length * 2).toBe(16128); // bytes: the budget the README states - }); - - it('pin the view-elevation axis and its inverse', () => { - expect(viewElevation(0)).toBe(-4); - expect(viewElevation(VIEW_SAMPLES - 1)).toBe(90); - expect(viewElevation(6)).toBeCloseTo(-4 + 94 * (6 / 31) ** 2, 10); - [0, 5, 6, 17, 31].forEach((i) => expect(viewIndex(viewElevation(i))).toBeCloseTo(i, 9)); - }); - - it('transmittance to space agrees with sun.js at the zenith and falls toward the horizon', () => { - const top = VIEW_SAMPLES - 1; - [0, 1, 2].forEach((c) => - expect(Math.abs(decode(trans[top * 3 + c]) / Math.exp(-TAU[c]) - 1)).toBeLessThan(0.01) - ); - expect(transmittance(90).map((v, c) => v / Math.exp(-TAU[c]))).toSatisfy((r: number[]) => - r.every((x) => Math.abs(x - 1) < 0.01) - ); - // blue goes first: lower view, lower blue, and redder light at the horizon - let prev = Infinity; - for (let i = top; i >= 8; i -= 1) { - const blue = decode(trans[i * 3 + 2]); - expect(blue).toBeLessThanOrEqual(prev); - prev = blue; - } - expect(decode(trans[8 * 3]) / decode(trans[8 * 3 + 2])).toBeGreaterThan(10); // ~2 degrees up: sunset red - expect(decode(trans[0])).toBe(0); // -4 degrees looks at the ground - }); - - it('colour the daytime sky blue, and a low sun redder toward it than away from it', () => { - const noon = texel(sunIndex_(45), VIEW_SAMPLES - 1, 0); - expect(noon[2]).toBeGreaterThan(noon[1]); - expect(noon[1]).toBeGreaterThan(noon[0]); - const horizon = Math.round(viewIndex(5)); - const toward = texel(sunIndex_(3), horizon, 0); - const away = texel(sunIndex_(3), horizon, AZIMUTH_SAMPLES - 1); - expect(toward[0] / toward[2]).toBeGreaterThan(5); - expect(toward[0] / toward[2]).toBeGreaterThan(2 * (away[0] / away[2])); - expect(toward[0]).toBeGreaterThan(5 * away[0]); // the glow is around the sun - }); - - it('fade through twilight to black below the planet-shadow limit', () => { - const mid = Math.round(viewIndex(30)); - const lum = (s: number) => texel(sunIndex_(s), mid, 3).reduce((x, y) => x + y, 0); - expect(lum(8)).toBeGreaterThan(lum(3)); - expect(lum(3)).toBeGreaterThan(lum(-2)); - expect(lum(-2)).toBeGreaterThan(lum(-5)); - expect(lum(-5)).toBeGreaterThan(0); - expect(lum(-12)).toBe(0); - expect(lum(-18)).toBe(0); - }); - - it('hold the model to half-float precision, with no quantised steps along the horizon glow', () => { - // Every table texel off a handful of sampled ones is the model's own value to < 0.2%. - [ - [sunIndex_(3), 6, 0], - [sunIndex_(3), 9, 2], - [sunIndex_(0), 8, 0], - [sunIndex_(45), 20, 3], - [sunIndex_(-2), 12, 1], - ].forEach(([s, v, a]) => { - const direct = skyRadiance(SUN_ELEVATIONS_DEG[s], viewElevation(v), a * AZIMUTH_STEP_DEG); - texel(s, v, a).forEach((got, c) => expect(Math.abs(got / direct[c] - 1)).toBeLessThan(2e-3)); - }); - // Moving up from the horizon toward the sun, red drops smoothly: distinct, strictly decreasing. - const s = sunIndex_(3); - const reds = Array.from({ length: 8 }, (_, k) => texel(s, 7 + k, 0)[0]); - reds.slice(1).forEach((r, k) => expect(r).toBeLessThan(reds[k])); - expect(new Set(reds).size).toBe(reds.length); - }); - - it('are the same bytes as when pinned', () => { - const sum = (a: Uint16Array) => a.reduce((x, y) => (x * 31 + y) % 2147483647, 7); - expect([sum(sky), sum(trans)]).toEqual([SKY_CHECKSUM, TRANS_CHECKSUM]); - }); -}); - -describe('aerial perspective volume', () => { - const ap = scatter.aerial_perspective; - - it('has the documented layout and size: RGBA half floats, x azimuth, y slice-major elevations, z sun elevation', () => { - expect([ap.width, ap.height, ap.depth, ap.channels]).toEqual([ - AZIMUTH_SAMPLES, - AP_SLICES * AP_ELEVATIONS, - SUN_ELEVATIONS_DEG.length, - 4, - ]); - expect(table(ap.data)).toHaveLength(ap.width * ap.height * ap.depth * 4); - }); - - it("slices follow the paper's squared distribution, ending at the covered distance", () => { - expect(apSliceKm(AP_SLICES - 1)).toBeCloseTo(AP_MAX_KM, 9); - expect(apSliceKm(0)).toBeCloseTo(AP_MAX_KM / AP_SLICES ** 2, 9); - for (let k = 0; k < AP_SLICES; k += 1) expect(apSliceIndex(apSliceKm(k))).toBeCloseTo(k, 9); - expect(apSliceIndex(0)).toBeCloseTo(-1, 9); - }); - - it('elevations are finest at the horizon and the index inverts them', () => { - expect(apElevation(AP_ELEVATIONS - 1)).toBeCloseTo(0, 12); - for (let i = 0; i < AP_ELEVATIONS; i += 1) - expect(apElevationIndex(apElevation(i))).toBeCloseTo(i, 9); - expect(apElevation(AP_ELEVATIONS - 1) - apElevation(AP_ELEVATIONS - 2)).toBeLessThan( - apElevation(1) - apElevation(0) - ); - }); - - it("opacity grows with path, in-scatter grows with path, and a sun under the planet's shadow scatters nothing", () => { - const r = aerialRay(45, -2, 90); - for (let k = 1; k < AP_SLICES; k += 1) { - expect(r[k][3]).toBeGreaterThan(r[k - 1][3]); - expect(r[k][0]).toBeGreaterThan(r[k - 1][0]); - } - for (const slice of aerialRay(-18, -2, 0)) expect(slice.slice(0, 3)).toEqual([0, 0, 0]); - }); - - it('is brighter toward a low sun than away, and redder toward it (Rayleigh and Mie phase)', () => { - const toward = aerialRay(2, -2, 0)[AP_SLICES - 1]; - const away = aerialRay(2, -2, 180)[AP_SLICES - 1]; - expect(toward[0]).toBeGreaterThan(20 * away[0]); - expect(toward[0] / toward[2]).toBeGreaterThan(away[0] / away[2]); - }); - - it('opacity does not depend on the sun, only on the path', () => { - expect(aerialRay(45, -2, 0)[5][3]).toBeCloseTo(aerialRay(-18, -2, 90)[5][3], 12); - }); - - it("the baked table is the model's output: spot texels equal aerialRay, to half-float precision", () => { - const t = table(ap.data); - const at = (sun: number, slice: number, el: number, az: number, c: number) => - decode(t[((sun * ap.height + slice * AP_ELEVATIONS + el) * ap.width + az) * 4 + c]); - const r = aerialRay(SUN_ELEVATIONS_DEG[8], apElevation(6), 60)[7]; - for (let c = 0; c < 4; c += 1) expect(at(8, 7, 6, 2, c)).toBeCloseTo(r[c], 3); - }); -}); diff --git a/tsconfig.json b/tsconfig.json index 7608e557..cc1fc724 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -6,6 +6,7 @@ "module": "ES2020", "allowJs": true, "strict": true, + "forceConsistentCasingInFileNames": true, "esModuleInterop": true, "moduleResolution": "Node", "resolveJsonModule": true,