Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
DN0: raea bench denoise draws each case on each denoiser (off, MetalFX; raea's own and DLSS-RR say why they can't run yet) and scores it against the same frames path-traced: LDR-FLIP written from the paper, RMSE, bias in stops, blotches (a mid band's error), flicker as the error's second difference against the truth's shot, a whole-frame spike, lag after a disocclusion or a light going out, a still's and a live frame's cost, and how many of MetalFX's numbers each meets
shinyobjectz138676198199
diff --git a/Cargo.lock b/Cargo.lockindex 0f519a09..70e4287e 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -14288,6 +14288,7 @@ dependencies = ["raea-core-animate","raea-core-brief","raea-core-program",+ "raea-denoise-bench","raea-io-home","raea-io-media","raea-io-npm",@@ -14471,6 +14472,16 @@ dependencies = ["bevy",]+[[package]]+name = "raea-denoise-bench"+version = "0.1.0"+dependencies = [+ "image",+ "raea-light",+ "raea-runtime-bundle",+ "serde_json",+]+[[package]]name = "raea-gpu-device"version = "0.1.0"diff --git a/Cargo.toml b/Cargo.tomlindex 0135c774..e786664e 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -168,6 +168,7 @@ members = ["tools/perceive","engine/render","engine/render/raytrace",+ "engine/render/denoise/bench","engine/seedling","engine/web","runtime/react",diff --git a/bench/denoise/.gitignore b/bench/denoise/.gitignorenew file mode 100644index 00000000..a1e03960--- /dev/null+++ b/bench/denoise/.gitignore@@ -0,0 +1 @@+runs/diff --git a/bench/denoise/cases.json b/bench/denoise/cases.jsonnew file mode 100644index 00000000..49fd3f54--- /dev/null+++ b/bench/denoise/cases.json@@ -0,0 +1,166 @@+{+ "about": "raea bench denoise's cases (docs/denoise.feature DN0). The small ones are cases/cases.tsx at 960x540; doorway-mall is MALL RAT's take t1 (Raea/anchor-tenant, the exposed view: the take's exposure and white balance after the denoiser, no lens or tape, 1440x1080 at 60 fps; the clean view delivers means of 2-12 of 255, too few levels to measure), through the dead wing's doorway onto a wet floor lit through roof holes, 15.5-20.5 s, where MetalFX shimmered at 32/16 spp. Events are frames inside each shot where its history breaks on purpose; the lag counts the frames to settle after each.",+ "scenes": [+ {+ "name": "dark-gain",+ "dir": "cases",+ "file": "cases.tsx",+ "composition": "dark-gain",+ "stills": [+ 30+ ],+ "shot": [+ 20,+ 31+ ]+ },+ {+ "name": "waxed-floor",+ "dir": "cases",+ "file": "cases.tsx",+ "composition": "waxed-floor",+ "stills": [+ 30+ ],+ "shot": [+ 20,+ 31+ ]+ },+ {+ "name": "doorway",+ "dir": "cases",+ "file": "cases.tsx",+ "composition": "doorway",+ "stills": [+ 30+ ],+ "shot": [+ 10,+ 27+ ],+ "events": [+ {+ "at": 15,+ "what": "disocclusion"+ }+ ]+ },+ {+ "name": "whip-pan",+ "dir": "cases",+ "file": "cases.tsx",+ "composition": "whip-pan",+ "stills": [+ 30+ ],+ "shot": [+ 10,+ 29+ ],+ "events": [+ {+ "at": 18,+ "what": "disocclusion"+ }+ ]+ },+ {+ "name": "neon",+ "dir": "cases",+ "file": "cases.tsx",+ "composition": "neon",+ "stills": [+ 30+ ],+ "shot": [+ 20,+ 31+ ]+ },+ {+ "name": "foliage",+ "dir": "cases",+ "file": "cases.tsx",+ "composition": "foliage",+ "stills": [+ 30+ ],+ "shot": [+ 20,+ 31+ ]+ },+ {+ "name": "fog",+ "dir": "cases",+ "file": "cases.tsx",+ "composition": "fog",+ "stills": [+ 30+ ],+ "shot": [+ 20,+ 31+ ]+ },+ {+ "name": "mirror",+ "dir": "cases",+ "file": "cases.tsx",+ "composition": "mirror",+ "stills": [+ 30+ ],+ "shot": [+ 20,+ 31+ ]+ },+ {+ "name": "light-off",+ "dir": "cases",+ "file": "cases.tsx",+ "composition": "light-off",+ "stills": [+ 30+ ],+ "shot": [+ 10,+ 27+ ],+ "events": [+ {+ "at": 15,+ "what": "light"+ }+ ]+ },+ {+ "name": "cost",+ "dir": "cases",+ "file": "cases.tsx",+ "composition": "cost",+ "stills": [],+ "reference": false,+ "why": "the frame's cost at 1920x1080 only: its picture is waxed-floor's",+ "live": true+ },+ {+ "name": "doorway-mall",+ "dir": "~/Documents/raea/raea/projects/anchor-tenant",+ "file": "compositions/shots.tsx",+ "composition": "t1-view",+ "stills": [+ 1020,+ 1140+ ],+ "shot": [+ 1080,+ 1091+ ],+ "live_why": "a film's take; the cost is the cost case's",+ "about": "t1's own SolariLighting draws it (32/16 spp, raised 11-24 for the doorway): RAEA_LIGHT=solari leaves a camera's SolariLighting as the composition has it. Frames count from the trimmed take; the doorway stretch is 930-1230"+ }+ ]+}diff --git a/bench/denoise/cases/cases.tsx b/bench/denoise/cases/cases.tsxnew file mode 100644index 00000000..da8aa770--- /dev/null+++ b/bench/denoise/cases/cases.tsx@@ -0,0 +1,131 @@+// raea bench denoise's small cases (docs/denoise.feature DN0): one closed room, 8 m wide, 3 high and 12 deep, with a+// door to a second room behind its far wall, each composition a thing denoisers get wrong. Every case is Solari-lit,+// so the bench's truth (RAEA_LIGHT=pathtracer) draws the same scene converged. 960x540 at 30 fps; "cost" is the same+// hall at 1920x1080, played live for a frame's cost.+import { AbsoluteFill, Composition, registerRoot, useCurrentFrame } from "raea";+import { ToneMapping } from "raea/3d";+import { Grade } from "raea/post_process";+import { StandardMaterial, VolumetricFog, FogVolume } from "raea/pbr";+import { Cuboid, Mesh3d } from "raea/mesh";+import { DirectionalLight, SolariLighting } from "raea/light";+import { LinearRgba } from "raea/color";+import { Transform } from "raea/transform";+import { Camera3d } from "raea/camera";++type V3 = [number, number, number];+type Box = { name: string; min: V3; max: V3; color?: string; rough?: number; metal?: number; glow?: V3 };++// the room's shell: 20 cm boxes, the far wall (z -12) with a door 1.2 m wide and 2.2 high into the back room+const SHELL: Box[] = [+ { name: "floor", min: [-4.2, -0.2, -20.2], max: [4.2, 0, 0.2], color: "#8a8276" },+ { name: "ceiling", min: [-4.2, 3, -20.2], max: [4.2, 3.2, 0.2] },+ { name: "wall-l", min: [-4.2, 0, -20.2], max: [-4, 3, 0.2] },+ { name: "wall-near", min: [-4.2, 0, 0], max: [4.2, 3, 0.2] },+ { name: "wall-back", min: [-4.2, 0, -20.2], max: [4.2, 3, -20] },+ { name: "mid-l", min: [-4, 0, -12.2], max: [-0.6, 3, -12] },+ { name: "mid-r", min: [0.6, 0, -12.2], max: [4, 3, -12] },+ { name: "mid-top", min: [-0.6, 2.2, -12.2], max: [0.6, 3, -12] },+ // the right wall with a window from z -9 to -5, 1 to 2.2 m up+ { name: "wall-r-low", min: [4, 0, -20.2], max: [4.2, 1, 0.2] },+ { name: "wall-r-high", min: [4, 2.2, -20.2], max: [4.2, 3, 0.2] },+ { name: "wall-r-back", min: [4, 1, -20.2], max: [4.2, 2.2, -9] },+ { name: "wall-r-front", min: [4, 1, -5], max: [4.2, 2.2, 0.2] },+];+// things to light and reflect: crates, a column, a coloured panel+const PROPS: Box[] = [+ { name: "crate-a", min: [-3, 0, -8], max: [-2, 1, -7], color: "#b04a32" },+ { name: "crate-b", min: [1.5, 0, -10], max: [2.7, 0.8, -8.8], color: "#3a6ea8" },+ { name: "column", min: [-0.3, 0, -5.3], max: [0.3, 3, -4.7] },+ { name: "panel", min: [-3.95, 0.6, -4], max: [-3.9, 1.8, -2], color: "#d8b13a" },+];+// the back room's light: a ceiling panel seen through the door+const BACK_LAMP: Box = { name: "back-lamp", min: [-1, 2.95, -17], max: [1, 3, -15], color: "#ffffff", glow: [900, 860, 780] };+// the hall's ceiling tubes+const TUBES: Box[] = [-2, 2].flatMap((x) => [-3, -8].map((z) => ({ name: `tube-${x}-${z}`, min: [x - 0.06, 2.96, z - 1] as V3, max: [x + 0.06, 3, z + 1] as V3, color: "#ffffff", glow: [2600, 2700, 2500] as V3 })));++function Part({ b, k = 1 }: { b: Box; k?: number }) {+ const c: V3 = [(b.min[0] + b.max[0]) / 2, (b.min[1] + b.max[1]) / 2, (b.min[2] + b.max[2]) / 2];+ const half: V3 = [(b.max[0] - b.min[0]) / 2, (b.max[1] - b.min[1]) / 2, (b.max[2] - b.min[2]) / 2];+ const g = b.glow ? new LinearRgba(b.glow[0] * k, b.glow[1] * k, b.glow[2] * k, 1) : undefined;+ return (+ <Mesh3d name={b.name} castShadow={!b.glow} transform={Transform.fromXyz(...c)}>+ <Cuboid half_size={half} />+ <StandardMaterial base_color={b.color ?? "#d6d0c2"} perceptual_roughness={b.rough ?? 0.75} metallic={b.metal ?? 0} {...(g ? { emissive: g } : {})} />+ </Mesh3d>+ );+}++type Case = {+ cam: (f: number) => Transform;+ extra?: Box[];+ floor?: Partial<Box>;+ tubes?: (f: number) => number;+ sun?: boolean;+ fog?: boolean;+ gain?: number;+ hide?: (f: number) => string[];+};++// a slow dolly down the hall, looking at the door+const dolly = (f: number) => Transform.fromXyz(1.5, 1.6, -1 - f * 0.03).lookingAt([0, 1.2, -16]);+const still = () => Transform.fromXyz(2.8, 1.6, -1.5).lookingAt([-1, 1, -11]);++// leaves: thin blades in a grid in front of the window, each turned by its place+const LEAVES: Box[] = Array.from({ length: 120 }, (_, i) => {+ const x = 3.2 + (i % 4) * 0.18, y = 0.9 + Math.floor(i / 4) % 10 * 0.13, z = -8.8 + Math.floor(i / 40) * 1.3 + ((i * 7) % 11) * 0.09;+ return { name: `leaf-${i}`, min: [x, y, z] as V3, max: [x + 0.12, y + 0.015, z + 0.05] as V3, color: "#3f6b2a", rough: 0.6 };+});++const CASES: Record<string, Case> = {+ // a dark room lifted 3 stops (18 dB) in the grade, as a camcorder's gain lifts it: only the back room's lamp, dimmed+ "dark-gain": { cam: still, tubes: () => 0, gain: 3 },+ // a waxed floor reflecting the tubes, the crates and the door+ "waxed-floor": { cam: dolly, floor: { color: "#5a544c", rough: 0.08 } },+ // still camera; at frame 15 the door's slab is gone, and the back room is seen at once (a disocclusion)+ doorway: { cam: still, extra: [{ name: "door", min: [-0.6, 0, -12.15], max: [0.6, 2.2, -12.05], color: "#5b4a3a" }], hide: (f) => (f >= 15 ? ["door"] : []) },+ // a whip pan: 100 degrees in 6 frames (12-17), then held+ "whip-pan": { cam: (f) => { const t = Math.min(1, Math.max(0, (f - 12) / 6)); const a = -0.5 + t * 1.75; return Transform.fromXyz(0, 1.6, -6).lookingAt([Math.sin(a) * 5, 1.4, -6 - Math.cos(a) * 5]); } },+ // neon: the tubes off, three thin saturated signs in a dark hall+ neon: { cam: dolly, tubes: () => 0, extra: [+ { name: "sign-r", min: [-3.95, 1.9, -9], max: [-3.9, 1.95, -6], color: "#ffffff", glow: [1800, 120, 260] },+ { name: "sign-g", min: [-3.95, 1.5, -9], max: [-3.9, 1.55, -6], color: "#ffffff", glow: [100, 1600, 400] },+ { name: "sign-b", min: [3.9, 2.3, -11], max: [3.95, 2.35, -7], color: "#ffffff", glow: [160, 300, 2200] },+ ] },+ // foliage: 120 leaves in front of a sunlit window+ foliage: { cam: (f) => Transform.fromXyz(1, 1.5, -3 - f * 0.02).lookingAt([4, 1.5, -7.5]), extra: LEAVES, sun: true, tubes: () => 0.2 },+ // a sunbeam through the window in dusty air+ fog: { cam: still, sun: true, fog: true, tubes: () => 0.2 },+ // a mirror on the left wall, the camera moving past it+ mirror: { cam: (f) => Transform.fromXyz(1.5, 1.6, -2 - f * 0.04).lookingAt([-4, 1.4, -7]), extra: [{ name: "mirror", min: [-3.95, 0.5, -9], max: [-3.9, 2.5, -5], color: "#ffffff", rough: 0, metal: 1 }] },+ // the tubes switched off at frame 15; the back room's lamp stays on+ "light-off": { cam: still, tubes: (f) => (f >= 15 ? 0 : 1) },+};++function Room({ c }: { c: Case }) {+ const f = useCurrentFrame();+ const hidden = c.hide?.(f) ?? [];+ const k = c.tubes?.(f) ?? 1;+ const shell = SHELL.map((b) => (b.name === "floor" ? { ...b, ...c.floor } : b));+ return (+ <AbsoluteFill style={{ background: "#000000" }}>+ <Camera3d transform={c.cam(f)} projection={{ Perspective: { fov: (60 * Math.PI) / 180 } }}>+ <SolariLighting bounces={3} />+ </Camera3d>+ <ToneMapping mode="agx" />+ {c.gain ? <Grade exposure={c.gain} /> : null}+ {c.sun ? <DirectionalLight illuminance={50000} shadow_maps_enabled volumetric={!!c.fog} transform={Transform.fromXyz(20, 8, -4).lookingAt([0, 0, -7])} /> : null}+ {c.fog ? <VolumetricFog /> : null}+ {c.fog ? <FogVolume name="dust" position={[0, 1.5, -6]} scale={[8, 3, 12]} density={0.08} /> : null}+ {[...shell, ...PROPS, ...(c.extra ?? [])].filter((b) => !hidden.includes(b.name)).map((b) => <Part key={b.name} b={b} />)}+ {k > 0 ? TUBES.map((b) => <Part key={b.name} b={b} k={k} />) : null}+ <Part b={BACK_LAMP} k={c.tubes && k === 0 && !c.gain ? 1 : c.gain ? 0.05 : 1} />+ </AbsoluteFill>+ );+}++registerRoot(() => (+ <>+ {Object.entries(CASES).map(([id, c]) => <Composition key={id} id={id} component={() => <Room c={c} />} width={960} height={540} fps={30} durationInFrames={40} />)}+ <Composition id="cost" component={() => <Room c={CASES["waxed-floor"]} />} width={1920} height={1080} fps={30} durationInFrames={240} />+ </>+));diff --git a/docs/denoise.feature b/docs/denoise.featureindex cafa9816..c0ef0164 100644--- a/docs/denoise.feature+++ b/docs/denoise.feature@@ -13,9 +13,9 @@ Feature: raea Denoise: one denoiser and upscaler raea owns, on every OS and GPUEvery number this feature sets comes from DN0's bench, measured; none is guessed here.- One denoiser for both renderers. docs/realism.feature plans raea Light (LT13 retires Solari) with "a denoiser slot"+ One denoiser for both renderers. docs/realism.feature plans raealism (LT13 retires Solari) with "a denoiser slot"on Windows and Linux (LT12), OIDN on the film tier (LT19), and docs/bake.feature cleans lightmaps (BK4). This feature- is that slot and that OIDN: DN1's inputs are written by whichever renderer draws the view (Solari today, raea Light+ is that slot and that OIDN: DN1's inputs are written by whichever renderer draws the view (Solari today, raealismlater), DN10's OIDN is the one LT19 and BK4 call, and the temporal parts reuse raea's steady filter(raea-sys-post steady.rs: its jitter, its YCoCg clip) rather than a second copy.@@ -33,14 +33,15 @@ Feature: raea Denoise: one denoiser and upscaler raea owns, on every OS and GPUtools/cycles-port where the path tracer differsWhen `raea bench denoise [--backend raea|metalfx|dlss|off] [CASE...]` renders every caseThen it reports, per case and backend: FLIP and RMSE against the truth; bias (mean light against the truth);- flicker (a frame against the last warped by motion, on surfaces that hold still); blotches (residual energy+ flicker (the error's change frame to frame against the truth's own shot, so motion cancels); a whole-frame+ spike (one frame's mean light lifted or dropped alone); blotches (residual energybelow 1/16 of the frame's width); lag (frames to settle after a disocclusion and after a light goes out);and ms a frame at 1080p on the GPU it ran onAnd MetalFX's numbers on the Mac are the first bar: DN8 makes raea's the default when it meets themAnd the plan:| crate | file | lines | job |- | raea-denoise-bench | engine/render/denoise/bench/src/lib.rs | 200 | the cases, the truth, the runs |- | raea-denoise-bench | engine/render/denoise/bench/src/metrics.rs | 300 | FLIP, RMSE, bias, flicker, blotch, lag |+ | raea-denoise-bench | engine/render/denoise/bench/src/lib.rs | 250 | the cases, the truth, the runs |+ | raea-denoise-bench | engine/render/denoise/bench/src/metrics.rs | 380 | FLIP, RMSE, bias, flicker, spike, blotch, lag || raea-denoise-bench | engine/render/denoise/bench/src/report.rs | 150 | the table and its JSON |Rule: One set of inputsdiff --git a/docs/manual/reference/cli/bench.md b/docs/manual/reference/cli/bench.mdnew file mode 100644index 00000000..027609fa--- /dev/null+++ b/docs/manual/reference/cli/bench.md@@ -0,0 +1,58 @@+---+title: "raea bench"+summary: "Each case on each denoiser against its converged truth: FLIP, RMSE, bias, flicker, blotches, lag after a disocclusion or a light going out, a frame's cost, and how many of MetalFX's numbers each meets."+order: 49+sources: ["engine/cli/src/cli.rs", "engine/render/denoise/bench/src/lib.rs", "engine/render/denoise/bench/src/metrics.rs", "engine/render/denoise/bench/src/report.rs"]+---++Each case on each denoiser against its converged truth: FLIP, RMSE, bias, flicker, blotches, lag after a disocclusion or a light going out, a frame's cost, and how many of MetalFX's numbers each meets.++`raea bench denoise` holds each denoiser to the same truth (docs/denoise.feature DN0). Every case is drawn with+Solari on each backend and against its reference: the same frames path-traced, each drawn `--spp` times so it+converges (raea light check's reference, kept between runs until `--fresh`). Each backend draws 16 frames before+each still and each shot, so its history is its own. For each case and backend it reports:++- FLIP (LDR-FLIP, written from Andersson et al. 2020, at 67 pixels a degree), RMSE, and the bias in stops (brighter+ is positive), the mean over the case's stills;+- blotches: the soft low-frequency patches a denoiser leaves, as the error in stops of the band between a 2-pixel and+ a 1/64-of-the-width blur;+- flicker over a short shot: the error's second difference in time against the same shot path-traced, so motion+ cancels and only light that changes when the truth doesn't counts. A whole-frame spike is the worst frame whose+ mean light jumps alone;+- the lag at each of the case's events (a disocclusion, a light going out): frames until the error settles back+ within 1.25 times what it was before;+- what a still costs, and, for a case that says `"live"`, what a frame costs played live.++Against MetalFX, the first bar on the Mac, the table says how many of its numbers each backend meets.++The backends are `off` (Solari with no denoiser), `metalfx` (the Mac's MetalFX denoised scaler), `raea` (raea's own,+DN1-DN8) and `dlss` (DLSS Ray Reconstruction, DN8, on an NVIDIA RTX machine). One that can't run here is reported+with why. The cases are raea light check's scene file with `"events": [{ "at": FRAME, "what": "disocclusion" }]`+inside each shot; bench/denoise/cases.json is the default, and a relative `dir` is the file's own folder's.++```sh+raea bench denoise --backend metalfx,off+raea bench denoise doorway mirror --backend off --spp 512 -o out/denoise/+```++<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->++## Usage++```sh+raea bench denoise [--backend raea,metalfx,dlss,off] [CASE...] [--cases FILE] [-o DIR] [--spp N] [--fresh] (each case on each denoiser against its converged truth: FLIP, RMSE, bias, flicker, blotches, lag after a disocclusion or a light going out, a frame's cost, and how many of MetalFX's numbers each meets; DIR/report.json)+```++Headless: it needs nothing running and opens no window. Takes any number of arguments besides its flags.++## Flags++| Flag | Takes | What it does |+| --- | --- | --- |+| `--backend` | `raea,metalfx,dlss,off` | the backends to run, comma-separated (all four by default) |+| `--cases` | `FILE` | the cases file (bench/denoise/cases.json) |+| `--fresh` | – | path-trace the truth again, not the kept one |+| `--spp` | `N` | the truth's samples a frame, where a case doesn't set `"spp"` (256) |+| `-o` | `DIR` | where the frames and report.json go (runs/ beside the cases file) |++<!-- generated:end -->diff --git a/docs/manual/reference/cli/doctor.md b/docs/manual/reference/cli/doctor.mdindex bb7b9fb0..3b1009f2 100644--- a/docs/manual/reference/cli/doctor.md+++ b/docs/manual/reference/cli/doctor.md@@ -1,7 +1,7 @@---title: "raea doctor"summary: "Find what doesn't match this version of raea: old brief files, an older workspace format, an agent's stale skill."-order: 52+order: 53sources: ["apps/workspace/src/doctor.rs"]---diff --git a/docs/manual/reference/cli/hook.md b/docs/manual/reference/cli/hook.mdindex e0c5bf33..4205ba48 100644--- a/docs/manual/reference/cli/hook.md+++ b/docs/manual/reference/cli/hook.md@@ -1,7 +1,7 @@---title: "raea hook"summary: "Every agent's tool hooks: media opened in the Mac's viewer goes to raea show, and the quick check after a composition is saved."-order: 53+order: 54sources: ["apps/check/src/hook.rs", "apps/tools/src/agent_hooks.rs"]---diff --git a/docs/manual/reference/cli/index.md b/docs/manual/reference/cli/index.mdindex 8ae64636..2c4c9adf 100644--- a/docs/manual/reference/cli/index.md+++ b/docs/manual/reference/cli/index.md@@ -70,6 +70,7 @@ What's wrong before anyone watches it.| [`raea findings`](findings.md) | What each render and check found, read back from the project's record: fixed, new and carried since the one before. || [`raea scene`](scene.md) | Find floating, sunk and clipping 3D parts, say what each part rests on, meter a shot's light, and hold every frame to the stage checks a render runs. || [`raea light`](light.md) | Measure a scene's light on each light path against its path-traced reference: distance in stops, the worst tile, flicker and cost. |+| [`raea bench`](bench.md) | Each case on each denoiser against its converged truth: FLIP, RMSE, bias, flicker, blotches, lag after a disocclusion or a light going out, a frame's cost, and how many of MetalFX's numbers each meets. || [`raea world`](world.md) | A frame as one world: its layers, text, 3D parts, camera, shots, clips, cues and lines as entities, queried across media. || [`raea solid`](solid.md) | Measure, view and export a solid: parts built from code with exact volumes, joints and parameters. || [`raea next`](next.md) | The two or three most useful next steps for a project, read from its brief, compositions, renders and checks. |diff --git a/docs/manual/reference/cli/next.md b/docs/manual/reference/cli/next.mdindex f94f6519..3047dd23 100644--- a/docs/manual/reference/cli/next.md+++ b/docs/manual/reference/cli/next.md@@ -1,7 +1,7 @@---title: "raea next"summary: "The two or three most useful next steps for a project, read from its brief, compositions, renders and checks."-order: 51+order: 52sources: ["apps/workspace/src/next.rs", "core/facts/src/record.rs"]---diff --git a/docs/manual/reference/cli/solid.md b/docs/manual/reference/cli/solid.mdindex 3a5aba19..ed88bcf7 100644--- a/docs/manual/reference/cli/solid.md+++ b/docs/manual/reference/cli/solid.md@@ -1,7 +1,7 @@---title: "raea solid"summary: "Measure, view and export a solid: parts built from code with exact volumes, joints and parameters."-order: 50+order: 51sources: ["apps/solid/src/lib.rs", "apps/solid/src/export.rs"]---diff --git a/docs/manual/reference/cli/traces.md b/docs/manual/reference/cli/traces.mdindex a22b0452..fa556829 100644--- a/docs/manual/reference/cli/traces.md+++ b/docs/manual/reference/cli/traces.md@@ -1,7 +1,7 @@---title: "raea traces"summary: "List the sessions raea apps left, newest first, with how each ended and its glitches, or tell one in full."-order: 54+order: 55sources: ["engine/cli/src/cli.rs", "io/trace/src"]---diff --git a/docs/manual/reference/cli/world.md b/docs/manual/reference/cli/world.mdindex bc7964bb..fe631e8e 100644--- a/docs/manual/reference/cli/world.md+++ b/docs/manual/reference/cli/world.md@@ -1,7 +1,7 @@---title: "raea world"summary: "A frame as one world: its layers, text, 3D parts, camera, shots, clips, cues and lines as entities, queried across media."-order: 49+order: 50sources: ["apps/direction/src/world.rs", "runtime/world/src/lib.rs", "core/facts/src/components.rs"]---diff --git a/engine/cli/Cargo.toml b/engine/cli/Cargo.tomlindex 26db2339..6025afd3 100644--- a/engine/cli/Cargo.toml+++ b/engine/cli/Cargo.toml@@ -52,6 +52,8 @@ serde_json = "1"raea-neural = { path = "../neural" }# `raea light check` (docs/realism.feature LT1)raea-light = { path = "../light" }+# `raea bench denoise`: each denoiser against its converged truth (docs/denoise.feature DN0)+raea-denoise-bench = { path = "../render/denoise/bench" }# `raea fix`: a problem looked up in raea's own fixes and the library of community ones the release shipsraea-sys-fixes = { path = "../../systems/fixes" }regex = "1"diff --git a/engine/cli/src/cli.rs b/engine/cli/src/cli.rsindex 83c96962..afa929ed 100644--- a/engine/cli/src/cli.rs+++ b/engine/cli/src/cli.rs@@ -147,7 +147,7 @@ pub fn run(args: &[String]) -> R<String> {let usage = format!("{usage}\n raea spec FILE.ts [--as brief|script|taste|parts] (a spec's default export as JSON, checked against its schema: brief.ts, script.ts, taste.ts, NAME.parts.ts)\n raea workspace init [NAME] [--layout LAYOUT] | raea workspace adopt DIR [--name NAME] | raea workspace [--json] (a workspace: a git repo of projects under raea.root, ~/Documents/raea unless git config says)\n raea project new NAME [--storage inline|submodule] | raea project split NAME [--remote URL] | raea project join NAME | raea project [--json] (a project in the workspace: its folder, brief.ts, media/, out/; split and join keep its history)\n raea check EDIT.tsx --quick [--shape S] [--platform P] [--taste T] [-o check.json] (three stills of a composition checked for text: clipped, cramped, safe areas, sizes; about a second)\n raea hook [claude|codex|gemini|kimi] (every agent's tool hooks, which raea skills install adds: before a shell command, media opened in the Mac's viewer while the raea app is installed is stopped once for raea show (the same command again goes through); after a save, the quick check on a composition)\n raea next [DIR] (the two or three useful next steps for the project, from its brief, compositions, renders and checks)\n raea doctor [--fix] [DIR] (what doesn't match this raea: old brief files, an older workspace format, an agent's skill from another version)\n raea app run|check|bundle APP.tsx [--target web|native] [--size WxH] [--script steps.json] [--png DIR] [-o App.app] (a TSX app on @raea/ui: its window, the headless check, a Mac app; web is Blitz on Bevy, native is Rune; the app's `export const app` sets the target, web when it doesn't; raea rune ... is --target native)\n {}\n {}\n {} ({})\n {}\n {}\n {}", skill::USAGE, tools::blender::USAGE, tools::motion::SETUP_USAGE, tools::motion::SETUP_ABOUT, raea_app_engines::godot::USAGE, raea_app_engines::shot::USAGE, raea_app_engines::round::USAGE);let (export_game, capcut, layers, xml, scene, physics, splat, wear, bake) = (raea_app_game::USAGE, raea_app_capcut::USAGE, raea_app_layers::USAGE, raea_app_layers::USAGE_XML, raea_app_scene::USAGE, motion::physics::USAGE, tools::splat::USAGE, raea_runtime_wear::USAGE, raea_app_lightbake::USAGE);let apps = format!(" {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n", raea_app_direction::check::USAGE, raea_app_check::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, raea_app_ask::USAGE, raea_app_make::USAGE, raea_app_direction::USAGE, raea_app_direction::findings::USAGE, raea_app_notes::USAGE, raea_app_fingerprint::USAGE, raea_sys_index::cli::USAGE);- return Ok(format!("raea: renders, plays and checks raea compositions (React and TypeScript) on the GPU.\n\nusage: {usage}\n raea init (a project's files where they're missing: edit.tsx, cuts.ts, components/, AGENTS.md)\n raea cut TAKE \"line\" ... | --at A-B ... [--append] (cuts.ts and words.json: a take under media/ cut in the pauses around each line it says, transcribed first if it has no TAKE.words.json; or at those seconds)\n raea frame TAKE [--at S] (how a take fits the edit: a talking take for <FaceFrame>, a screen for <ScreenFit>, from where its face is)\n raea component list | raea component add NAME ... [--shared] [--force] | raea part list | raea part add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; raea part is its old name)\n raea brand DOMAIN|URL (the brand kit read from its website on this machine: brand/brand.css, brand/brand.json, BRAND.md, logos in media/brand; says when a plain fetch saw too little)\n raea guide [NAME] (craft, the floor read before any edit; the modes: pitch, explain, story, play, tool; motion, music, layout and the rest; bevy and bevy/NAME for 3D)\n raea context PROJECT (what to read before working on a project: taste, brief, look, the floor and its modes' guides)\n{apps} raea play EDIT.tsx [--input | --input-script KEYS.json] [--size WxH] [--seconds N|end] (a game, live; also: --input-log FILE --offscreen --snapshot T FILE --json FILE --seek F FILE --pick X,Y --view YAW,PITCH,DISTANCE --scrub N --baked --autoplay --no-vsync --master --3d)\n {export_game} (a game as a program of its own: a Mac app or a command)\n {capcut}\n {layers}\n {xml}\n {scene} (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)\n {physics} (the bakes <Physics> and <Goo> make)\n {bake}\n {wear} (a .glb's weathering causes for raea/wear: the model with a second UV set and its cause maps, made once in the asset store)\n {splat} (footage trained into a Gaussian splat for <Splat>; setup installs its tools)\n raea run SCRIPT.ts (a TypeScript program on the engine, headless: its default export is called, what it prints is the answer; a check like a room's checkLayout; also: --timeout S)\n raea gen image|video|music|sfx|speech|mesh|text \"PROMPT\" | gen plan|run FLOW.ts|FLOW.json | gen comfy import|export|run|schema FILE | gen models | gen balance (generated media through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI; ComfyUI workflows both ways: raea gen alone lists its flags)\n {neural_usage} (DLSS 5 neural rendering on a `render --aov` folder, with its motion and depth: your own MLX-DLSS build and weights, RAEA_MLXDLSS and RAEA_DLSS_MODEL)\n {light_usage} (each scene on each light path against its path-traced reference: distance in stops, the worst tile, a moving shot's flicker, a frame's cost; DIR/report.json)\n raea mezz [--check] PATH... (an intra-only ProRes copy of each long-GOP source over 1080p, for smooth scrubbing; --check says which would get one)\n raea traces [show [N|last|DIR]] (the sessions raea left, newest first: how each ended, its glitches; show tells one in full)"));+ return Ok(format!("raea: renders, plays and checks raea compositions (React and TypeScript) on the GPU.\n\nusage: {usage}\n raea init (a project's files where they're missing: edit.tsx, cuts.ts, components/, AGENTS.md)\n raea cut TAKE \"line\" ... | --at A-B ... [--append] (cuts.ts and words.json: a take under media/ cut in the pauses around each line it says, transcribed first if it has no TAKE.words.json; or at those seconds)\n raea frame TAKE [--at S] (how a take fits the edit: a talking take for <FaceFrame>, a screen for <ScreenFit>, from where its face is)\n raea component list | raea component add NAME ... [--shared] [--force] | raea part list | raea part add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; raea part is its old name)\n raea brand DOMAIN|URL (the brand kit read from its website on this machine: brand/brand.css, brand/brand.json, BRAND.md, logos in media/brand; says when a plain fetch saw too little)\n raea guide [NAME] (craft, the floor read before any edit; the modes: pitch, explain, story, play, tool; motion, music, layout and the rest; bevy and bevy/NAME for 3D)\n raea context PROJECT (what to read before working on a project: taste, brief, look, the floor and its modes' guides)\n{apps} raea play EDIT.tsx [--input | --input-script KEYS.json] [--size WxH] [--seconds N|end] (a game, live; also: --input-log FILE --offscreen --snapshot T FILE --json FILE --seek F FILE --pick X,Y --view YAW,PITCH,DISTANCE --scrub N --baked --autoplay --no-vsync --master --3d)\n {export_game} (a game as a program of its own: a Mac app or a command)\n {capcut}\n {layers}\n {xml}\n {scene} (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)\n {physics} (the bakes <Physics> and <Goo> make)\n {bake}\n {wear} (a .glb's weathering causes for raea/wear: the model with a second UV set and its cause maps, made once in the asset store)\n {splat} (footage trained into a Gaussian splat for <Splat>; setup installs its tools)\n raea run SCRIPT.ts (a TypeScript program on the engine, headless: its default export is called, what it prints is the answer; a check like a room's checkLayout; also: --timeout S)\n raea gen image|video|music|sfx|speech|mesh|text \"PROMPT\" | gen plan|run FLOW.ts|FLOW.json | gen comfy import|export|run|schema FILE | gen models | gen balance (generated media through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI; ComfyUI workflows both ways: raea gen alone lists its flags)\n {neural_usage} (DLSS 5 neural rendering on a `render --aov` folder, with its motion and depth: your own MLX-DLSS build and weights, RAEA_MLXDLSS and RAEA_DLSS_MODEL)\n {light_usage} (each scene on each light path against its path-traced reference: distance in stops, the worst tile, a moving shot's flicker, a frame's cost; DIR/report.json)\n {} (each case on each denoiser against its converged truth: FLIP, RMSE, bias, flicker, blotches, lag after a disocclusion or a light going out, a frame's cost, and how many of MetalFX's numbers each meets; DIR/report.json)\n raea mezz [--check] PATH... (an intra-only ProRes copy of each long-GOP source over 1080p, for smooth scrubbing; --check says which would get one)\n raea traces [show [N|last|DIR]] (the sessions raea left, newest first: how each ended, its glitches; show tells one in full)", raea_denoise_bench::USAGE));}// `--version`: the release's version, which a skill's front matter names (docs/skills.feature SK6)if args.len() == 1 && matches!(args[0].as_str(), "--version" | "-V") {@@ -243,10 +243,11 @@ pub fn run(args: &[String]) -> R<String> {if args.first().map(String::as_str) == Some("neural") {return neural::neural(&args[1..]);}- // `light check SCENES.json -o DIR`: raea Light's bar (docs/realism.feature LT1)+ // `light check SCENES.json -o DIR`: raealism's bar (docs/realism.feature LT1)if args.first().map(String::as_str) == Some("light") {return light::light(&args[1..]);}+ if args.first().map(String::as_str) == Some("bench") { return raea_denoise_bench::cli(&args[1..]); } // `bench denoise`: each denoiser against its converged truth (DN0)if args.first().map(String::as_str) == Some("mezz") {return mezz(&args[1..]);}diff --git a/engine/light/src/lib.rs b/engine/light/src/lib.rsindex acfcc0a0..ced86219 100644--- a/engine/light/src/lib.rs+++ b/engine/light/src/lib.rs@@ -1,4 +1,4 @@-//! `raea light check SCENES.json -o DIR` (docs/realism.feature LT1): the bar raea Light is measured by. Each scene+//! `raea light check SCENES.json -o DIR` (docs/realism.feature LT1): the bar raealism is measured by. Each scene//! is rendered on each light path (RAEA_LIGHT, engine/render/raytrace force.rs) and against its reference, the path//! tracer held RAEA_LIGHT_SPP draws a frame: how far each path's stills are from it in stops (mean, bias, worst tile),//! how much its moving shot flickers against the shot path-traced (each path drawing the 16 frames before a still@@ -25,7 +25,7 @@ pub const USAGE: &str = "raea light check SCENES.json -o DIR [--scene NAME] [--p/// of SSAO (on a camera with <AmbientOcclusion>; on any other it draws as raster).const PATHS: [&str; 4] = ["raster", "traced-ao", "solari", "gi"];-/// The switches a path is drawn with (the reference is `pathtracer`). `gi` is raster with raea GI's probes traced+/// The switches a path is drawn with (the reference is `pathtracer`). `gi` is raster with raealism's probes traced/// (systems/rt gi.rs; RAEA_GI_RAYS and the rest pass through from the check's own environment).fn switches(path: &str) -> Vec<(&'static str, String)> {match path {@@ -35,17 +35,18 @@ fn switches(path: &str) -> Vec<(&'static str, String)> {}}-struct Scene {- name: String,- dir: PathBuf,- file: String,- composition: String,- stills: Vec<i64>,- shot: Option<(i64, i64)>,- reference: Result<(), String>,- live: Result<(), String>,- size: (i64, i64),- spp: Option<u32>,+/// A scene of SCENES.json (the module's doc); raea bench denoise (engine/render/denoise/bench) reads its cases the same way.+pub struct Scene {+ pub name: String,+ pub dir: PathBuf,+ pub file: String,+ pub composition: String,+ pub stills: Vec<i64>,+ pub shot: Option<(i64, i64)>,+ pub reference: Result<(), String>,+ pub live: Result<(), String>,+ pub size: (i64, i64),+ pub spp: Option<u32>,}/// How long a live play runs, in seconds, its first second not counted.@@ -58,7 +59,14 @@ fn home(p: &str) -> PathBuf {}}-fn scenes(path: &Path) -> R<Vec<Scene>> {+impl Scene {+ /// Every frame of its shot, first to last+ pub fn shot_frames(&self) -> Option<Vec<i64>> {+ self.shot.map(|(a, b)| (a..=b).collect())+ }+}++pub fn scenes(path: &Path) -> R<Vec<Scene>> {let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;let v: Value = serde_json::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))?;let list = v["scenes"].as_array().ok_or(format!("{}: no \"scenes\" list", path.display()))?;@@ -79,15 +87,23 @@ fn scenes(path: &Path) -> R<Vec<Scene>> {/// Frames `at` of a scene drawn on `path` into `out` (frame-00000.png onward, in `at`'s order), by this raea; the/// seconds it took.fn render(scene: &Scene, path: &str, spp: u32, at: &[i64], out: &Path) -> R<f64> {+ let mut env = switches(path);+ env.push(("RAEA_LIGHT_SPP", spp.to_string()));+ render_with(scene, path, &env, at, out)+}++/// Frames `at` of a scene drawn under the switches `env` into `out`, `label` naming the run in an error; the seconds it+/// took. `label` "pathtracer" is the truth.+pub fn render_with(scene: &Scene, label: &str, env: &[(&str, String)], at: &[i64], out: &Path) -> R<f64> {std::fs::create_dir_all(out).map_err(|e| format!("{}: {e}", out.display()))?;let exe = std::env::current_exe().map_err(|e| e.to_string())?;let at: Vec<String> = at.iter().map(i64::to_string).collect();let t = Instant::now();let mut cmd = std::process::Command::new(exe);- cmd.current_dir(&scene.dir).envs(switches(path)).env("RAEA_LIGHT_SPP", spp.to_string());+ cmd.current_dir(&scene.dir).envs(env.iter().map(|(k, v)| (*k, v)));// the truth is never steadied: RAEA_STEADY's jitter moved the path-traced shot's frames by part of a pixel each,// and that read as the paths' flicker (FLOOR3's reference 0.478 stops of its own against 0.101)- if path == "pathtracer" {+ if label == "pathtracer" {cmd.env_remove("RAEA_STEADY");}let run = cmd@@ -98,7 +114,7 @@ fn render(scene: &Scene, path: &str, spp: u32, at: &[i64], out: &Path) -> R<f64>if !run.status.success() {let err = String::from_utf8_lossy(&run.stderr);let last: Vec<&str> = err.lines().rev().take(4).collect();- return Err(format!("{} on {path}: render failed: {}", scene.name, last.into_iter().rev().collect::<Vec<_>>().join(" | ")));+ return Err(format!("{} on {label}: render failed: {}", scene.name, last.into_iter().rev().collect::<Vec<_>>().join(" | ")));}Ok(t.elapsed().as_secs_f64())}@@ -107,6 +123,11 @@ fn render(scene: &Scene, path: &str, spp: u32, at: &[i64], out: &Path) -> R<f64>/// a frame costs, from play's report (DIR/PATH-live-WxH.json): the frames presented a second as milliseconds a frame,/// and each frame's work at the median and the 99th percentile; on `gi`, the probe pass's own GPU time (RAEA_GI_STATS).fn live(scene: &Scene, path: &str, size: (i64, i64), out: &Path) -> R<Value> {+ live_with(scene, path, &switches(path), size, out)+}++/// The same, under the switches `env`, `path` naming its report (DIR/PATH-live-WxH.json).+pub fn live_with(scene: &Scene, path: &str, env: &[(&str, String)], size: (i64, i64), out: &Path) -> R<Value> {let exe = std::env::current_exe().map_err(|e| e.to_string())?;let size = format!("{}x{}", size.0, size.1);let json_out = out.join(format!("{path}-live-{size}.json"));@@ -114,7 +135,7 @@ fn live(scene: &Scene, path: &str, size: (i64, i64), out: &Path) -> R<Value> {let _ = std::fs::remove_file(&gi_out);let run = std::process::Command::new(exe).current_dir(&scene.dir)- .envs(switches(path))+ .envs(env.iter().map(|(k, v)| (*k, v))).env("RAEA_GI_STATS", &gi_out).env("RAEA_AUDIO_MUTE", "1").args(["play", &scene.file, "--offscreen", "--no-vsync", "--3d", "--seconds", LIVE_SECONDS, "--size", &size, "--json"])@@ -136,18 +157,42 @@ fn live(scene: &Scene, path: &str, size: (i64, i64), out: &Path) -> R<Value> {}/// The frames written to `dir` at these places in its render-fn frames(dir: &Path, at: impl IntoIterator<Item = usize>) -> R<Vec<metric::Luma>> {- at.into_iter().map(|k| metric::load(&dir.join(format!("frame-{k:05}.png")))).collect()+pub fn frames(dir: &Path, at: impl IntoIterator<Item = usize>) -> R<Vec<metric::Luma>> {+ frames_with(dir, at, metric::load)+}++/// The same, each read by `load` (raea bench denoise reads them as colour)+pub fn frames_with<T>(dir: &Path, at: impl IntoIterator<Item = usize>, load: fn(&Path) -> R<T>) -> R<Vec<T>> {+ at.into_iter().map(|k| load(&dir.join(format!("frame-{k:05}.png")))).collect()+}++/// A table's cell: the number at `k`, to three places, or "-"+pub fn cell(v: &Value, k: &str) -> String {+ v[k].as_f64().map_or("-".to_string(), |x| format!("{x:.3}"))+}++/// A comma-separated `name` flag's values, each one of `all` (all of them when it isn't given); `what` says what they are+pub fn list_flag(args: &[String], name: &str, all: &[&str], what: &str) -> R<Vec<String>> {+ let v: Vec<String> = flag(args, name).map_or_else(|| all.iter().copied().map(String::from).collect(), |p| p.split(',').map(String::from).collect());+ match v.iter().find(|p| all.iter().all(|a| a != p)) {+ Some(p) => Err(format!("{name}: {p} isn't {what} ({})", all.join(", "))),+ None => Ok(v),+ }+}++/// --spp N, the truth's samples a pixel (256)+pub fn spp(args: &[String]) -> R<u32> {+ Ok(flag(args, "--spp").map(|v| v.parse().map_err(|_| format!("--spp {v}: a count of samples"))).transpose()?.unwrap_or(256))}/// frames drawn before each measured frame that doesn't follow the one before it, and not measured, so whatever/// keeps a past (raea's temporal filter, the GI's caches) has its own, as it does in play: from a cold start a/// filter's first frames average one, two, three frames-const BEFORE: i64 = 16;+pub const BEFORE: i64 = 16;/// `at` with BEFORE frames drawn before each of its frames that doesn't follow the one before, and where each of/// `at`'s frames lands in that render-fn with_before(at: &[i64]) -> (Vec<i64>, Vec<usize>) {+pub fn with_before(at: &[i64]) -> (Vec<i64>, Vec<usize>) {let (mut all, mut place) = (Vec::new(), Vec::new());for &f in at {if all.last() != Some(&(f - 1)) {@@ -165,7 +210,7 @@ fn round(x: f32, k: f32) -> f64 {/// Frames `at` path-traced at `spp` into `dir`, kept from an earlier check when it made the same frames of the same/// composition at the same samples (DIR/made.json) and --fresh isn't given; the frames, and how they were had.-fn reference(scene: &Scene, spp: u32, at: &[i64], dir: &Path, fresh: bool) -> R<(Vec<metric::Luma>, Value)> {+pub fn reference(scene: &Scene, spp: u32, at: &[i64], dir: &Path, fresh: bool) -> R<(Vec<metric::Luma>, Value)> {let made = json!({ "file": scene.file, "composition": scene.composition, "frames": at, "spp": spp });let kept = std::fs::read_to_string(dir.join("made.json")).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok());let how = if !fresh && kept.as_ref() == Some(&made) {@@ -183,7 +228,7 @@ fn reference(scene: &Scene, spp: u32, at: &[i64], dir: &Path, fresh: bool) -> R<fn check(scene: &Scene, paths: &[String], spp: u32, out: &Path, fresh: bool) -> R<Value> {let root = out.join(&scene.name);let spp = scene.spp.unwrap_or(spp);- let shot: Option<Vec<i64>> = scene.shot.map(|(a, b)| (a..=b).collect());+ let shot = scene.shot_frames();let mut report = json!({ "name": scene.name, "stills": scene.stills, "shot": shot, "paths": {} });let (reference, ref_shot) = match &scene.reference {Err(why) => {@@ -249,7 +294,7 @@ fn table(reports: &[Value]) -> String {let name = r["name"].as_str().unwrap_or("");let Some(paths) = r["paths"].as_object() else { continue };for (p, v) in paths {- let f = |k: &str| v[k].as_f64().map_or("-".to_string(), |x| format!("{x:.3}"));+ let f = |k: &str| cell(v, k);let ms = |k: &str| v["live"][k]["ms_a_frame"].as_f64().map_or("-".to_string(), |x| format!("{x:.1}"));// the cache's passes and the screen's (its probes, their filter, the screen), each a medianlet g = &v["live"]["full"]["gi"];@@ -270,11 +315,8 @@ pub fn light(args: &[String]) -> R<String> {let list = scenes(Path::new(&args[1]))?;let out = PathBuf::from(flag(args, "-o").ok_or(format!("usage: {USAGE}"))?);let only = flag(args, "--scene");- let paths: Vec<String> = flag(args, "--paths").map_or_else(|| PATHS.map(String::from).to_vec(), |p| p.split(',').map(String::from).collect());- if let Some(p) = paths.iter().find(|p| !PATHS.contains(&p.as_str())) {- return Err(format!("--paths: {p} isn't a light path to check ({})", PATHS.join(", ")));- }- let spp: u32 = flag(args, "--spp").map(|v| v.parse().map_err(|_| format!("--spp {v}: a count of samples"))).transpose()?.unwrap_or(256);+ let paths = list_flag(args, "--paths", &PATHS, "a light path to check")?;+ let spp = spp(args)?;let fresh = args.iter().any(|a| a == "--fresh");let mut reports = Vec::new();for s in list.iter().filter(|s| match &only { Some(o) => *o == s.name, None => true }) {diff --git a/engine/light/src/metric.rs b/engine/light/src/metric.rsindex 2f67a891..c8e4b70b 100644--- a/engine/light/src/metric.rs+++ b/engine/light/src/metric.rs@@ -23,7 +23,8 @@ pub const TILE: usize = 64;/// The side of the squares the distance compares, in pixels.pub const BLOCK: usize = 8;-fn linear(c: u8) -> f32 {+/// An 8-bit sRGB value as linear light+pub fn linear(c: u8) -> f32 {let v = c as f32 / 255.0;if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }}diff --git a/engine/render/denoise/bench/Cargo.toml b/engine/render/denoise/bench/Cargo.tomlnew file mode 100644index 00000000..9d39a903--- /dev/null+++ b/engine/render/denoise/bench/Cargo.toml@@ -0,0 +1,15 @@+[package]+name = "raea-denoise-bench"+version = "0.1.0"+edition = "2024"+license = "FSL-1.1-ALv2"+publish = false+description = "raea bench denoise: each case on each denoiser against its converged truth: FLIP, RMSE, bias, flicker, blotches, lag and a frame's cost (docs/denoise.feature DN0)"++[dependencies]+image = { version = "0.25", default-features = false, features = ["png"] }+serde_json = "1"+# the CLI's flag reader and result type+raea-runtime-bundle = { path = "../../../../runtime/bundle" }+# raea light check's runner (a scene's frames under switches, its path-traced truth kept between runs) and its stops+raea-light = { path = "../../../light" }diff --git a/engine/render/denoise/bench/src/lib.rs b/engine/render/denoise/bench/src/lib.rsnew file mode 100644index 00000000..768c7fbe--- /dev/null+++ b/engine/render/denoise/bench/src/lib.rs@@ -0,0 +1,214 @@+//! `raea bench denoise [--backend raea|metalfx|dlss|off] [CASE...]` (docs/denoise.feature DN0): every case on every+//! denoiser against its converged truth, so each backend has numbers to meet and MetalFX's on the Mac are the first bar.+//!+//! The cases are raea light check's scenes (raea_light::scenes: name, dir, file, composition, stills, shot, live,+//! size, spp), from bench/denoise/cases.json by default (--cases FILE; a relative dir is the file's own folder's), each+//! with "events": [{ "at": FRAME, "what": "disocclusion" | "light" }] inside its shot for the lag. The truth is the path+//! tracer held RAEA_LIGHT_SPP draws a frame (raea_light::reference, kept between runs unless --fresh). Each backend+//! draws a case's stills and shot with 16 frames before each (raea_light::with_before), so its history is its own,+//! then is scored (metrics.rs) and, where the case says "live", played at its size for a frame's cost. The report is+//! DIR/report.json and a table (report.rs); DIR is --o, else runs/ beside the cases file.++pub mod metrics;+pub mod report;++use raea_light::{metric, Scene};+use raea_runtime_bundle::{flag, R};+use serde_json::{json, Value};+use std::path::{Path, PathBuf};++pub const USAGE: &str = "raea bench denoise [--backend raea,metalfx,dlss,off] [CASE...] [--cases FILE] [-o DIR] [--spp N] [--fresh]";++/// The backends, in the order DN8's switch names them+pub const BACKENDS: [&str; 4] = ["raea", "metalfx", "dlss", "off"];++/// The switches a backend draws with, or why it can't run here yet. Every one traces with Solari (RAEA_LIGHT).+pub fn switches(backend: &str) -> Result<Vec<(&'static str, String)>, String> {+ let solari = |denoise: &str| Ok(vec![("RAEA_LIGHT", "solari".to_string()), ("RAEA_SOLARI_DENOISE", denoise.to_string())]);+ match backend {+ "off" => solari("0"),+ "metalfx" if cfg!(target_os = "macos") => solari("1"),+ "metalfx" => Err("MetalFX runs on the Mac only".into()),+ "raea" => Err("not built yet: raea's own denoiser is DN1-DN8".into()),+ "dlss" => Err("not wired yet (DN8): DLSS-RR needs the `dlss` build on an NVIDIA RTX machine".into()),+ b => Err(format!("{b} isn't a backend ({})", BACKENDS.join(", "))),+ }+}++/// A case: its scene, and the frames in its shot where its history is broken on purpose+pub struct Case {+ pub scene: Scene,+ pub events: Vec<(i64, String)>,+}++pub fn cases(path: &Path) -> R<Vec<Case>> {+ let base = path.parent().unwrap_or(Path::new("."));+ let v: Value = serde_json::from_str(&std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?).map_err(|e| format!("{}: {e}", path.display()))?;+ let scenes = raea_light::scenes(path)?;+ scenes+ .into_iter()+ .zip(v["scenes"].as_array().into_iter().flatten())+ .map(|(mut scene, s)| {+ if scene.dir.is_relative() {+ scene.dir = base.join(&scene.dir);+ }+ let events: Vec<(i64, String)> = s["events"].as_array().into_iter().flatten().filter_map(|e| Some((e["at"].as_i64()?, e["what"].as_str().unwrap_or("event").to_string()))).collect();+ if let Some(&(at, _)) = events.iter().find(|(at, _)| !scene.shot.is_some_and(|(a, b)| (a + 1..=b).contains(at))) {+ return Err(format!("{}: {}'s event at frame {at} isn't inside its shot, after its first frame", path.display(), scene.name));+ }+ Ok(Case { scene, events })+ })+ .collect()+}++fn round(x: f32, k: f32) -> Value {+ json!(((x * k).round() / k) as f64)+}++/// The stills' numbers' mean, rounded+fn over(v: &[f32], k: f32) -> Value {+ round(v.iter().sum::<f32>() / v.len().max(1) as f32, k)+}++/// One case: its truth, then each backend against it+fn run(case: &Case, backends: &[String], spp: u32, out: &Path, fresh: bool) -> R<Value> {+ let s = &case.scene;+ let root = out.join(&s.name);+ let spp = s.spp.unwrap_or(spp);+ let shot = s.shot_frames();+ let mut report = json!({ "name": s.name, "stills": s.stills, "shot": shot, "events": case.events.iter().map(|(at, what)| json!({"at": at, "what": what})).collect::<Vec<_>>(), "backends": {} });+ let truth = match &s.reference {+ Err(why) => {+ report["truth"] = json!({ "made": false, "why": why });+ None+ }+ Ok(()) => {+ let (_, how) = raea_light::reference(s, spp, &s.stills, &root.join("truth"), fresh)?;+ let stills = raea_light::frames_with(&root.join("truth"), 0..s.stills.len(), metrics::load)?;+ report["truth"] = json!({ "made": true, "stills": how });+ let shot = match &shot {+ Some(at) => {+ let (frames, how) = raea_light::reference(s, spp, at, &root.join("truth-shot"), fresh)?;+ report["truth"]["shot"] = how;+ Some(frames)+ }+ None => None,+ };+ Some((stills, shot))+ }+ };+ for b in backends {+ let env = match switches(b) {+ Ok(env) => env,+ Err(why) => {+ report["backends"][b] = json!({ "ran": false, "why": why });+ continue;+ }+ };+ let dir = root.join(b);+ let (all, place) = raea_light::with_before(&s.stills);+ let secs = raea_light::render_with(s, b, &env, &all, &dir)?;+ let mut r = json!({ "ran": true, "seconds_a_still": round(secs as f32 / all.len().max(1) as f32, 100.0) });+ if let Some((refs, ref_shot)) = &truth {+ let got = raea_light::frames_with(&dir, place, metrics::load)?;+ let per = |f: fn(&metrics::Rgb, &metrics::Rgb) -> Result<f32, String>| got.iter().zip(refs).map(|(a, t)| f(a, t)).collect::<R<Vec<f32>>>();+ let (flip, rmse, bias, blotch) = (per(metrics::flip)?, per(metrics::rmse)?, per(metrics::bias)?, per(metrics::blotch)?);+ r["flip"] = over(&flip, 10000.0);+ r["rmse"] = over(&rmse, 10000.0);+ r["bias_stops"] = over(&bias, 1000.0);+ r["blotch_stops"] = over(&blotch, 1000.0);+ r["per_still"] = json!((0..got.len()).map(|k| json!({ "flip": round(flip[k], 10000.0), "rmse": round(rmse[k], 10000.0), "bias": round(bias[k], 1000.0), "blotch": round(blotch[k], 1000.0) })).collect::<Vec<_>>());+ if let (Some(at), Some(ref_shot)) = (&shot, ref_shot) {+ let sdir = root.join(format!("{b}-shot"));+ let (all, place) = raea_light::with_before(at);+ raea_light::render_with(s, b, &env, &all, &sdir)?;+ let frames = raea_light::frames(&sdir, place)?;+ r["flicker_stops"] = json!(metric::error_flicker(&frames, ref_shot)?.map(|f| round(f, 1000.0)));+ r["spike_stops"] = json!(metrics::spike(&frames, ref_shot).map(|f| round(f, 1000.0)));+ let errors: Vec<f32> = frames.iter().zip(ref_shot).map(|(a, t)| metric::distance(a, t).map(|d| d.mean)).collect::<R<_>>()?;+ r["shot_error_stops"] = json!(errors.iter().map(|&e| round(e, 1000.0)).collect::<Vec<_>>());+ let first = at[0];+ r["lag"] = json!(case.events.iter().map(|(ev, what)| json!({ "at": ev, "what": what, "frames": metrics::lag(&errors, (ev - first) as usize) })).collect::<Vec<_>>());+ }+ }+ r["live"] = match &s.live {+ Ok(()) => raea_light::live_with(s, b, &env, s.size, &root)?,+ Err(why) => json!({ "measured": false, "why": why }),+ };+ report["backends"][b] = r;+ }+ Ok(report)+}++/// The positional CASE names: what isn't a flag or a flag's value+fn names(args: &[String]) -> Vec<String> {+ let mut out = Vec::new();+ let mut it = args.iter();+ while let Some(a) = it.next() {+ match a.as_str() {+ "-o" | "--cases" | "--backend" | "--spp" => {+ it.next();+ }+ a if a.starts_with('-') => {}+ a => out.push(a.to_string()),+ }+ }+ out+}++/// `raea bench denoise ...` (args after `bench`)+pub fn cli(args: &[String]) -> R<String> {+ if args.first().map(String::as_str) != Some("denoise") {+ return Err(format!("usage: {USAGE}"));+ }+ let args = &args[1..];+ let file = PathBuf::from(flag(args, "--cases").unwrap_or_else(|| "bench/denoise/cases.json".into()));+ let list = cases(&file)?;+ let out = flag(args, "-o").map_or_else(|| file.parent().unwrap_or(Path::new(".")).join("runs"), PathBuf::from);+ let backends = raea_light::list_flag(args, "--backend", &BACKENDS, "a backend")?;+ let spp = raea_light::spp(args)?;+ let only = names(args);+ if let Some(n) = only.iter().find(|n| !list.iter().any(|c| &c.scene.name == *n)) {+ return Err(format!("no case named {n} in {} ({})", file.display(), list.iter().map(|c| c.scene.name.as_str()).collect::<Vec<_>>().join(", ")));+ }+ let fresh = args.iter().any(|a| a == "--fresh");+ let mut reports = Vec::new();+ for c in list.iter().filter(|c| only.is_empty() || only.contains(&c.scene.name)) {+ eprintln!("raea bench denoise: {} ...", c.scene.name);+ reports.push(run(c, &backends, spp, &out, fresh)?);+ }+ report::write(&reports, &out)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn names_skip_flags_and_their_values() {+ let a: Vec<String> = ["doorway", "--backend", "off", "-o", "x", "mirror", "--fresh"].map(String::from).to_vec();+ assert_eq!(names(&a), vec!["doorway", "mirror"]);+ }++ #[test]+ fn backends_that_cant_run_say_why() {+ assert!(switches("raea").unwrap_err().contains("DN1"));+ assert!(switches("dlss").unwrap_err().contains("NVIDIA"));+ assert_eq!(switches("off").unwrap()[1], ("RAEA_SOLARI_DENOISE", "0".to_string()));+ assert!(switches("nope").is_err());+ }++ #[test]+ fn a_case_file_reads_its_events_and_its_folder() {+ let d = std::env::temp_dir().join(format!("raea-dn0-{}", std::process::id()));+ std::fs::create_dir_all(&d).unwrap();+ let f = d.join("cases.json");+ std::fs::write(&f, r#"{"scenes":[{"name":"a","dir":"cases","file":"a.tsx","composition":"a","stills":[3],"shot":[0,9],"events":[{"at":5,"what":"light"}]}]}"#).unwrap();+ let c = cases(&f).unwrap();+ assert_eq!(c[0].events, vec![(5, "light".to_string())]);+ assert_eq!(c[0].scene.dir, d.join("cases"));+ std::fs::write(&f, r#"{"scenes":[{"name":"a","dir":"cases","file":"a.tsx","composition":"a","stills":[3],"shot":[0,9],"events":[{"at":12}]}]}"#).unwrap();+ assert!(cases(&f).is_err());+ std::fs::remove_dir_all(&d).unwrap();+ }+}diff --git a/engine/render/denoise/bench/src/metrics.rs b/engine/render/denoise/bench/src/metrics.rsnew file mode 100644index 00000000..e18418a6--- /dev/null+++ b/engine/render/denoise/bench/src/metrics.rs@@ -0,0 +1,337 @@+//! The bench's numbers (docs/denoise.feature DN0), each a frame against its truth, both as delivered (8-bit sRGB PNGs+//! after tone mapping):+//! - FLIP: LDR-FLIP's mean, written from the paper (Andersson et al., "FLIP: A Difference Evaluator for Alternating+//! Images", HPG 2020) at its default viewing (0.7 m from a 0.7 m wide, 3840 px monitor: 67 pixels a degree);+//! - RMSE of the sRGB values, 0 to 1;+//! - bias: the frame's mean luminance against the truth's, in stops (brighter is positive): a denoiser's floor;+//! - blotches: the residual's mid band, in stops: log luminance between a 2 px and a width/64 Gaussian (features up to+//! about 1/16 of the frame's width), the frame's band against the truth's, mean absolute;+//! - lag: frames after an event (a disocclusion, a light going out) until a frame's error settles back.+//! Flicker is raea light check's (raea_light::metric::error_flicker): the error's second difference in time against+//! the truth's own shot, so motion and fades cancel and what's left is light that changes when the truth doesn't.++use std::path::Path;++/// A frame as linear RGB, row by row, with its 8-bit sRGB values kept for RMSE.+pub struct Rgb {+ pub w: usize,+ pub h: usize,+ pub lin: Vec<[f32; 3]>,+ pub srgb: Vec<[f32; 3]>,+}++impl Rgb {+ /// A frame from its 8-bit sRGB pixels+ pub fn of(w: usize, h: usize, px: impl Iterator<Item = [u8; 3]>) -> Rgb {+ let lut: Vec<f32> = (0..=255u8).map(raea_light::metric::linear).collect();+ let (lin, srgb) = px.map(|c| (c.map(|v| lut[v as usize]), c.map(|v| v as f32 / 255.0))).unzip();+ Rgb { w, h, lin, srgb }+ }+}++pub fn load(p: &Path) -> Result<Rgb, String> {+ let img = image::open(p).map_err(|e| format!("{}: {e}", p.display()))?.to_rgb8();+ Ok(Rgb::of(img.width() as usize, img.height() as usize, img.pixels().map(|px| px.0)))+}++fn same(a: &Rgb, b: &Rgb) -> Result<(), String> {+ if (a.w, a.h) != (b.w, b.h) {+ return Err(format!("sizes differ: {}x{} against the truth's {}x{}", a.w, a.h, b.w, b.h));+ }+ Ok(())+}++/// Rec. 709's luminance weights+const Y709: [f32; 3] = [0.2126, 0.7152, 0.0722];++fn luma(c: &[f32; 3]) -> f32 {+ c.iter().zip(Y709).map(|(c, w)| c * w).sum()+}++pub fn rmse(a: &Rgb, truth: &Rgb) -> Result<f32, String> {+ same(a, truth)?;+ let s: f64 = a.srgb.iter().zip(&truth.srgb).map(|(p, q)| (0..3).map(|k| ((p[k] - q[k]) as f64).powi(2)).sum::<f64>()).sum();+ Ok((s / (3 * a.srgb.len()).max(1) as f64).sqrt() as f32)+}++/// The darkest luminance a stop is measured from (raea light's floor, about sRGB 8/255).+const FLOOR: f32 = 0.0025;++pub fn bias(a: &Rgb, truth: &Rgb) -> Result<f32, String> {+ same(a, truth)?;+ let mean = |x: &Rgb| x.lin.iter().map(|c| luma(c) as f64).sum::<f64>() / x.lin.len().max(1) as f64;+ Ok(((mean(a) as f32).max(FLOOR) / (mean(truth) as f32).max(FLOOR)).log2())+}++/// A plane filtered by the separable kernel `k` (odd length, centred), its edges clamped.+fn convolve(p: &[f32], w: usize, h: usize, kx: &[f32], ky: &[f32]) -> Vec<f32> {+ let (rx, ry) = ((kx.len() / 2) as isize, (ky.len() / 2) as isize);+ let at = |v: isize, n: usize| v.clamp(0, n as isize - 1) as usize;+ let mut t = vec![0.0; w * h];+ for y in 0..h {+ for x in 0..w {+ t[y * w + x] = kx.iter().enumerate().map(|(i, k)| k * p[y * w + at(x as isize + i as isize - rx, w)]).sum();+ }+ }+ let mut o = vec![0.0; w * h];+ for y in 0..h {+ for x in 0..w {+ o[y * w + x] = ky.iter().enumerate().map(|(i, k)| k * t[at(y as isize + i as isize - ry, h) * w + x]).sum();+ }+ }+ o+}++/// A kernel scaled to sum to 1+fn unit(k: Vec<f32>) -> Vec<f32> {+ let s: f32 = k.iter().sum();+ k.into_iter().map(|v| v / s).collect()+}++/// A Gaussian's weights out to 3 sigma, at least one pixel either side, not normalized+fn bell(sigma: f32) -> Vec<f32> {+ let r = (3.0 * sigma).ceil().max(1.0) as isize;+ let k = -0.5 / (sigma * sigma);+ (-r..=r).map(|x| (k * (x * x) as f32).exp()).collect()+}++fn gaussian(sigma: f32) -> Vec<f32> {+ unit(bell(sigma))+}++pub fn blotch(a: &Rgb, truth: &Rgb) -> Result<f32, String> {+ same(a, truth)?;+ let (w, h) = (a.w, a.h);+ let (fine, coarse) = (gaussian(2.0), gaussian((w as f32 / 64.0).max(3.0)));+ let band = |x: &Rgb| {+ let l: Vec<f32> = x.lin.iter().map(|c| luma(c).max(FLOOR).log2()).collect();+ let (f, c) = (convolve(&l, w, h, &fine, &fine), convolve(&l, w, h, &coarse, &coarse));+ f.into_iter().zip(c).map(|(f, c)| f - c).collect::<Vec<f32>>()+ };+ let (p, q) = (band(a), band(truth));+ Ok((p.iter().zip(&q).map(|(p, q)| (p - q).abs() as f64).sum::<f64>() / p.len().max(1) as f64) as f32)+}++/// Frames after `event` until the error settles: the first frame from which every later one is within 25% (and 0.02)+/// of the error before the event (the median of those frames). None when it never settles in the shot or there's no+/// frame before the event to settle to.+pub fn lag(errors: &[f32], event: usize) -> Option<usize> {+ let mut before: Vec<f32> = errors.get(..event)?.to_vec();+ if before.is_empty() || event >= errors.len() {+ return None;+ }+ before.sort_by(f32::total_cmp);+ let settled = before[before.len() / 2];+ let ok = |e: f32| e <= (settled * 1.25).max(settled + 0.02);+ let after = &errors[event..];+ let last_bad = after.iter().rposition(|&e| !ok(e));+ match last_bad {+ None => Some(0),+ Some(k) if k + 1 < after.len() => Some(k + 1),+ Some(_) => None,+ }+}++/// The worst whole-frame spike in a shot, in stops: each frame's mean light against the mean of the frames either side+/// (m[k] - (m[k-1] + m[k+1]) / 2, in log2), less the truth's own at that frame, so a fade or a cut in the truth counts+/// for nothing and a frame the denoiser lifts or drops alone counts in full. Per-pixel flicker averages such a flash+/// away. Fewer than three frames measure nothing.+pub fn spike(frames: &[raea_light::metric::Luma], truth: &[raea_light::metric::Luma]) -> Option<f32> {+ let m = |f: &raea_light::metric::Luma| ((f.y.iter().map(|&v| v as f64).sum::<f64>() / f.y.len().max(1) as f64) as f32).max(FLOOR).log2();+ let (a, t): (Vec<f32>, Vec<f32>) = (frames.iter().map(m).collect(), truth.iter().map(m).collect());+ let d2 = |v: &[f32], k: usize| v[k] - 0.5 * (v[k - 1] + v[k + 1]);+ (a.len() >= 3 && a.len() == t.len()).then(|| (1..a.len() - 1).map(|k| (d2(&a, k) - d2(&t, k)).abs()).fold(0.0, f32::max))+}++// LDR-FLIP (the paper's section 4, its constants)+const PPD: f32 = 0.7 * 3840.0 / 0.7 * std::f32::consts::PI / 180.0;+const QC: f32 = 0.7;+const QF: f32 = 0.5;+const PC: f32 = 0.4;+const PT: f32 = 0.95;+/// sRGB's linear RGB to XYZ (D65), and back+const TO_XYZ: [[f32; 3]; 3] = [[0.4124564, 0.3575761, 0.1804375], [0.2126729, 0.7151522, 0.0721750], [0.0193339, 0.1191920, 0.9503041]];+const TO_RGB: [[f32; 3]; 3] = [[3.2404542, -1.5371385, -0.4985314], [-0.9692660, 1.8760108, 0.0415560], [0.0556434, -0.2040259, 1.0572252]];+const WHITE: [f32; 3] = [0.95047, 1.0, 1.08883];++fn mul(m: &[[f32; 3]; 3], v: [f32; 3]) -> [f32; 3] {+ let mut o = [0.0; 3];+ for (o, row) in o.iter_mut().zip(m) {+ *o = row[0] * v[0] + row[1] * v[1] + row[2] * v[2];+ }+ o+}++fn ycxcz(rgb: [f32; 3]) -> [f32; 3] {+ let x = mul(&TO_XYZ, rgb);+ let (xn, yn, zn) = (x[0] / WHITE[0], x[1] / WHITE[1], x[2] / WHITE[2]);+ [116.0 * yn - 16.0, 500.0 * (xn - yn), 200.0 * (yn - zn)]+}++fn ycxcz_to_rgb(c: [f32; 3]) -> [f32; 3] {+ let yn = (c[0] + 16.0) / 116.0;+ let xyz = [(c[1] / 500.0 + yn) * WHITE[0], yn * WHITE[1], (yn - c[2] / 200.0) * WHITE[2]];+ mul(&TO_RGB, xyz).map(|v| v.clamp(0.0, 1.0))+}++/// Hunt-adjusted L*a*b* of a linear RGB colour+fn hunt_lab(rgb: [f32; 3]) -> [f32; 3] {+ let x = mul(&TO_XYZ, rgb);+ let f = |t: f32| if t > (6.0f32 / 29.0).powi(3) { t.cbrt() } else { t / (3.0 * (6.0f32 / 29.0).powi(2)) + 4.0 / 29.0 };+ let (fx, fy, fz) = (f(x[0] / WHITE[0]), f(x[1] / WHITE[1]), f(x[2] / WHITE[2]));+ let l = 116.0 * fy - 16.0;+ [l, 0.01 * l * 500.0 * (fx - fy), 0.01 * l * 200.0 * (fy - fz)]+}++fn hyab(a: [f32; 3], b: [f32; 3]) -> f32 {+ (a[0] - b[0]).abs() + ((a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2)).sqrt()+}++/// The contrast sensitivity kernel of one opponent channel (a sum of two Gaussians, in degrees), normalized+fn csf(a1: f32, b1: f32, a2: f32, b2: f32) -> Vec<f32> {+ let r = (3.0 * (b1.max(b2) / (2.0 * std::f32::consts::PI.powi(2))).sqrt() * PPD).ceil() as isize;+ let pi2 = std::f32::consts::PI.powi(2);+ unit((-r..=r).map(|i| (i as f32 / PPD).powi(2)).map(|x2| a1 * (std::f32::consts::PI / b1).sqrt() * (-pi2 * x2 / b1).exp() + a2 * (std::f32::consts::PI / b2).sqrt() * (-pi2 * x2 / b2).exp()).collect())+}++/// The feature detectors' 1-D parts: a Gaussian and its first and second derivatives at the paper's 0.082 degrees+fn feature_kernels() -> (Vec<f32>, Vec<f32>, Vec<f32>) {+ let sd = 0.5 * 0.082 * PPD;+ let g = bell(sd);+ let r = (g.len() / 2) as isize;+ let d1: Vec<f32> = (-r..=r).zip(&g).map(|(x, g)| -(x as f32) * g).collect();+ let d2: Vec<f32> = (-r..=r).zip(&g).map(|(x, g)| ((x * x) as f32 / (sd * sd) - 1.0) * g).collect();+ (g, d1, d2)+}++/// A 2-D kernel's separable parts scaled so its positive weights sum to 1 and its negative to -1 (the paper's+/// normalization), given the 2-D sums each sign would have+fn signed_norm(along: &[f32], across: &[f32]) -> (Vec<f32>, Vec<f32>) {+ let (mut pos, mut neg) = (0.0f32, 0.0f32);+ for a in along {+ for b in across {+ let v = a * b;+ if v > 0.0 { pos += v } else { neg -= v }+ }+ }+ let gs: f32 = across.iter().sum();+ let across: Vec<f32> = across.iter().map(|v| v / gs).collect();+ let (p, n) = (pos / gs, neg / gs);+ (along.iter().map(|v| if *v > 0.0 { v / p } else { v / n.max(1e-12) }).collect(), across)+}++/// The edge and point strength at each pixel of a plane+fn features(y: &[f32], w: usize, h: usize) -> (Vec<f32>, Vec<f32>) {+ let (g, d1, d2) = feature_kernels();+ let (e1, eg) = signed_norm(&d1, &g);+ let (p1, pg) = signed_norm(&d2, &g);+ let (ex, ey) = (convolve(y, w, h, &e1, &eg), convolve(y, w, h, &eg, &e1));+ let (px, py) = (convolve(y, w, h, &p1, &pg), convolve(y, w, h, &pg, &p1));+ let m = |a: Vec<f32>, b: Vec<f32>| a.into_iter().zip(b).map(|(a, b)| a.hypot(b)).collect::<Vec<f32>>();+ (m(ex, ey), m(px, py))+}++/// LDR-FLIP's mean over the frame (0 the same, 1 the most different)+pub fn flip(a: &Rgb, truth: &Rgb) -> Result<f32, String> {+ same(a, truth)?;+ let (w, h) = (a.w, a.h);+ let kernels = [csf(1.0, 0.0047, 0.0, 1e-5), csf(1.0, 0.0053, 0.0, 1e-5), csf(34.1, 0.04, 13.5, 0.025)];+ // the colour pipeline: each opponent channel filtered as the eye sees it, back to RGB, then Hunt-adjusted Lab+ let filtered = |x: &Rgb| {+ let ch: Vec<[f32; 3]> = x.lin.iter().map(|c| ycxcz(*c)).collect();+ let planes: Vec<Vec<f32>> = (0..3).map(|k| convolve(&ch.iter().map(|c| c[k]).collect::<Vec<_>>(), w, h, &kernels[k], &kernels[k])).collect();+ (0..w * h).map(|i| hunt_lab(ycxcz_to_rgb([planes[0][i], planes[1][i], planes[2][i]]))).collect::<Vec<[f32; 3]>>()+ };+ let (fa, ft) = (filtered(a), filtered(truth));+ let cmax = hyab(hunt_lab([0.0, 1.0, 0.0]), hunt_lab([0.0, 0.0, 1.0])).powf(QC);+ // the feature pipeline, on the achromatic channel normalized to 0..1+ let ach = |x: &Rgb| x.lin.iter().map(|c| (ycxcz(*c)[0] + 16.0) / 116.0).collect::<Vec<f32>>();+ let ((ea, pa), (et, pt)) = (features(&ach(a), w, h), features(&ach(truth), w, h));+ let mut sum = 0.0f64;+ for i in 0..w * h {+ let d = hyab(fa[i], ft[i]).powf(QC);+ let ec = if d < PC * cmax { PT / (PC * cmax) * d } else { PT + (d - PC * cmax) / (cmax - PC * cmax) * (1.0 - PT) };+ let ef = (std::f32::consts::FRAC_1_SQRT_2 * (ea[i] - et[i]).abs().max((pa[i] - pt[i]).abs())).powf(QF);+ sum += ec.min(1.0).powf(1.0 - ef) as f64;+ }+ Ok((sum / (w * h).max(1) as f64) as f32)+}++#[cfg(test)]+mod tests {+ use super::*;++ fn q(v: f32) -> u8 {+ (v.clamp(0.0, 1.0) * 255.0).round() as u8+ }++ fn flat(w: usize, h: usize, c: [f32; 3]) -> Rgb {+ Rgb::of(w, h, std::iter::repeat_n(c.map(q), w * h))+ }++ fn noisy(base: &Rgb, amp: f32, seed: u32) -> Rgb {+ let mut s = seed;+ Rgb::of(base.w, base.h, base.srgb.iter().map(|c| {+ s = s.wrapping_mul(1664525).wrapping_add(1013904223);+ let n = ((s >> 8) as f32 / (1u32 << 24) as f32 - 0.5) * 2.0 * amp;+ c.map(|v| q(v + n))+ }))+ }++ #[test]+ fn a_frame_against_itself_is_no_error() {+ let a = noisy(&flat(48, 32, [0.4, 0.5, 0.3]), 0.2, 7);+ assert!(flip(&a, &a).unwrap() < 1e-6);+ assert_eq!(rmse(&a, &a).unwrap(), 0.0);+ assert!(bias(&a, &a).unwrap().abs() < 1e-6 && blotch(&a, &a).unwrap() < 1e-6);+ }++ #[test]+ fn more_noise_is_more_flip_and_black_against_white_is_near_one() {+ let base = flat(48, 32, [0.5, 0.5, 0.5]);+ let (lo, hi) = (flip(&noisy(&base, 0.05, 1), &base).unwrap(), flip(&noisy(&base, 0.3, 1), &base).unwrap());+ assert!(lo < hi, "{lo} {hi}");+ let bw = flip(&flat(32, 32, [0.0; 3]), &flat(32, 32, [1.0; 3])).unwrap();+ assert!(bw > 0.9, "{bw}");+ }++ #[test]+ fn twice_the_light_is_one_stop_of_bias() {+ let (a, b) = (flat(8, 8, [0.4; 3]), flat(8, 8, [0.2; 3]));+ let (la, lb) = (luma(&a.lin[0]), luma(&b.lin[0]));+ let want = (la / lb).log2();+ assert!((bias(&a, &b).unwrap() - want).abs() < 1e-4);+ }++ #[test]+ fn a_soft_blob_is_a_blotch_and_fine_grain_less_so() {+ // 640 wide, so the band runs from 2 px to 10 px: a wall of soft blotches 12 px across against per-pixel grain+ let (w, h) = (640, 320);+ let base = flat(w, h, [0.5; 3]);+ let tau = std::f32::consts::TAU;+ let blob = Rgb::of(w, h, (0..w * h).map(|i| [q(0.5 + 0.05 * (tau * (i % w) as f32 / 24.0).sin() * (tau * (i / w) as f32 / 24.0).sin()); 3]));+ let grain = noisy(&base, 0.02, 3);+ let (b, g) = (blotch(&blob, &base).unwrap(), blotch(&grain, &base).unwrap());+ assert!(b > g, "blob {b} grain {g}");+ }++ #[test]+ fn a_frame_lifted_alone_is_a_spike_and_a_fade_is_not() {+ let f = |v: f32| raea_light::metric::Luma { w: 4, h: 4, y: vec![v; 16] };+ let fade: Vec<_> = (0..6).map(|k| f(0.1 * 1.2f32.powi(k))).collect();+ let mut flash: Vec<_> = (0..6).map(|_| f(0.1)).collect();+ flash[3] = f(0.2);+ assert!(spike(&fade, &fade).unwrap() < 1e-5);+ assert!((spike(&flash, &fade).unwrap() - 1.0).abs() < 0.05);+ }++ #[test]+ fn lag_counts_the_frames_to_settle() {+ // settled at 0.1, an event at frame 4, three frames to come back+ let e = [0.1, 0.1, 0.11, 0.1, 0.9, 0.5, 0.2, 0.11, 0.1, 0.1];+ assert_eq!(lag(&e, 4), Some(3));+ assert_eq!(lag(&[0.1, 0.1, 0.1, 0.1], 2), Some(0));+ assert_eq!(lag(&[0.1, 0.1, 0.9, 0.9], 2), None);+ assert_eq!(lag(&[0.9, 0.1], 0), None);+ }+}diff --git a/engine/render/denoise/bench/src/report.rs b/engine/render/denoise/bench/src/report.rsnew file mode 100644index 00000000..741f0fc8--- /dev/null+++ b/engine/render/denoise/bench/src/report.rs@@ -0,0 +1,73 @@+//! The bench's table and its JSON (docs/denoise.feature DN0): a line a case and backend, and against MetalFX, the first+//! bar, how many of its six numbers (FLIP, flicker, the worst whole-frame spike, blotches, |bias|, the worst lag) each backend meets on that case.++use raea_runtime_bundle::R;+use serde_json::{json, Value};+use std::path::Path;++/// The numbers the bar compares, each smaller is better (bias by its size)+const BAR: [&str; 5] = ["flip", "flicker_stops", "spike_stops", "blotch_stops", "bias_stops"];++fn worst_lag(v: &Value) -> Option<f64> {+ let lags = v["lag"].as_array()?;+ // an event that never settled in the shot counts as the longest lag there is+ lags.iter().fold(None, |worst: Option<f64>, l| Some(worst.unwrap_or(0.0).max(l["frames"].as_f64().unwrap_or(f64::INFINITY))))+}++/// Of the bar's numbers this backend and MetalFX both have on a case, how many it meets (no worse), and of how many+pub fn against(v: &Value, metalfx: &Value) -> Option<(usize, usize)> {+ if v["ran"] != json!(true) || metalfx["ran"] != json!(true) {+ return None;+ }+ let mut pairs: Vec<(f64, f64)> = BAR.iter().filter_map(|k| Some((v[*k].as_f64()?.abs(), metalfx[*k].as_f64()?.abs()))).collect();+ if let (Some(a), Some(b)) = (worst_lag(v), worst_lag(metalfx)) {+ pairs.push((a, b));+ }+ (!pairs.is_empty()).then(|| (pairs.iter().filter(|(a, b)| a <= b).count(), pairs.len()))+}++/// The table a person reads+pub fn table(reports: &[Value]) -> String {+ let mut s = format!("{:<14} {:<8} {:>7} {:>7} {:>7} {:>8} {:>7} {:>7} {:>5} {:>8} {:>8} {:>8}\n", "case", "backend", "flip", "rmse", "bias", "flicker", "spike", "blotch", "lag", "s/still", "live ms", "metalfx");+ for r in reports {+ let name = r["name"].as_str().unwrap_or("");+ let Some(bs) = r["backends"].as_object() else { continue };+ for (b, v) in bs {+ if v["ran"] != json!(true) {+ s += &format!("{name:<14} {b:<8} (not run: {})\n", v["why"].as_str().unwrap_or(""));+ continue;+ }+ let f = |k: &str| raea_light::cell(v, k);+ let lag = worst_lag(v).map_or("-".to_string(), |l| if l.is_finite() { format!("{l}") } else { "never".into() });+ let live = v["live"]["ms_a_frame"].as_f64().map_or("-".to_string(), |x| format!("{x:.1}"));+ let bar = if b == "metalfx" { "bar".to_string() } else { against(v, &bs.get("metalfx").cloned().unwrap_or_default()).map_or("-".to_string(), |(m, n)| format!("{m}/{n}")) };+ s += &format!("{name:<14} {b:<8} {:>7} {:>7} {:>7} {:>8} {:>7} {:>7} {lag:>5} {:>8} {live:>8} {bar:>8}\n", f("flip"), f("rmse"), f("bias_stops"), f("flicker_stops"), f("spike_stops"), f("blotch_stops"), f("seconds_a_still"));+ }+ if r["truth"]["made"] == json!(false) {+ s += &format!("{name:<14} (no truth: {})\n", r["truth"]["why"].as_str().unwrap_or(""));+ }+ }+ s+}++/// DIR/report.json, and the table with where it went+pub fn write(reports: &[Value], out: &Path) -> R<String> {+ std::fs::create_dir_all(out).map_err(|e| format!("{}: {e}", out.display()))?;+ let path = out.join("report.json");+ std::fs::write(&path, serde_json::to_string_pretty(&json!({ "cases": reports })).unwrap_or_default()).map_err(|e| format!("{}: {e}", path.display()))?;+ Ok(format!("{}raea bench denoise: wrote {}", table(reports), path.display()))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_backend_is_held_to_metalfx_number_by_number() {+ let m = json!({ "ran": true, "flip": 0.10, "flicker_stops": 0.05, "blotch_stops": 0.02, "bias_stops": -0.1, "lag": [{ "frames": 6 }] });+ let r = json!({ "ran": true, "flip": 0.09, "flicker_stops": 0.06, "blotch_stops": 0.02, "bias_stops": 0.05, "lag": [{ "frames": null }] });+ // flip, blotch and |bias| met; flicker and the lag (never settled) not+ assert_eq!(against(&r, &m), Some((3, 5)));+ assert_eq!(against(&json!({ "ran": false }), &m), None);+ }+}diff --git a/tools/layers.toml b/tools/layers.tomlindex 05e59d26..22f61f95 100644--- a/tools/layers.toml+++ b/tools/layers.toml@@ -86,8 +86,10 @@ raea-sys-parity = "systems" # the parity probe, in raea's App and the examples'raea-bench-swatch = "systems" # a Blitz widget fixture (bench/bridge/swatch) the plugin catalog declares: a leaf on vendored crates, so a runtime crate may build it inraea-render = "runtime"raea-render-raytrace = "runtime"-# `raea light check`: raea Light's measures (docs/realism.feature LT1)+# `raea light check`: raealism's measures (docs/realism.feature LT1)raea-light = "runtime"+# `raea bench denoise`: each denoiser against its converged truth (docs/denoise.feature DN0), on raea light's runner+raea-denoise-bench = "runtime"raea-bevy-plugins = "runtime"raea-bevy-calls = "runtime"raea-bevy-adapters = "runtime"diff --git a/tools/manual-ref/cli.ts b/tools/manual-ref/cli.tsindex e5f49a5e..d7134fcb 100644--- a/tools/manual-ref/cli.ts+++ b/tools/manual-ref/cli.ts@@ -27,7 +27,7 @@ const verbs: Verb[] = JSON.parse(run(["help", "--json"])).verbsconst GROUPS: [string, string, string[]][] = [["Make", "Render, play and package what you wrote.", ["render", "play", "export-game", "export", "bundle", "app", "run"]],["Projects", "The workspace, its projects and what a project holds.", ["init", "workspace", "project", "spec", "component", "part", "add", "brand", "library", "index"]],- ["Check", "What's wrong before anyone watches it.", ["check", "judge", "make", "fingerprint", "findings", "scene", "light", "world", "solid", "next", "doctor", "hook", "traces"]],+ ["Check", "What's wrong before anyone watches it.", ["check", "judge", "make", "fingerprint", "findings", "scene", "light", "bench", "world", "solid", "next", "doctor", "hook", "traces"]],["Footage", "Takes, cuts and the camera, from your own media.", ["media", "cut", "frame", "track", "splat", "mezz", "neural"]],["Sound", "Music read, foley and instruments made on this machine.", ["song", "sounds", "sao", "tokensynth", "setup-audio"]],["Generate and 3D tools", "Generated media, physics, light and weathering bakes, clothes and motion for SOMA's body, Blender and Godot.", ["gen", "physics", "bake", "wear", "clothes", "motion", "blender", "godot"]],