Skip to content

armgit / raea

Public Imported from GitHub
0

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.

LT1: raea light check, the bar raea Light is measured by

shinyobjectz2161a524ab21
diff --git a/Cargo.lock b/Cargo.lock
index a1bd6812..07b24fc4 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -14248,6 +14248,7 @@ dependencies = [
"raea-io-media",
"raea-io-npm",
"raea-io-trace",
+ "raea-light",
"raea-native",
"raea-neural",
"raea-render",
@@ -14687,6 +14688,15 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "raea-light"
+version = "0.1.0"
+dependencies = [
+ "image",
+ "raea-runtime-bundle",
+ "serde_json",
+]
+
[[package]]
name = "raea-modules"
version = "0.1.0"
diff --git a/Cargo.toml b/Cargo.toml
index d6e82584..cad8a417 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -39,6 +39,7 @@ members = [
"engine/bundle",
"engine/cli",
"engine/neural",
+ "engine/light",
"engine/modules",
"engine/native",
"io/npm",
diff --git a/bench/light/scenes.json b/bench/light/scenes.json
new file mode 100644
index 00000000..5cedbb43
--- /dev/null
+++ b/bench/light/scenes.json
@@ -0,0 +1,65 @@
+{
+ "about": "raea Light's reference scenes (docs/realism.feature LT1), for `raea light check bench/light/scenes.json -o DIR`",
+ "scenes": [
+ {
+ "name": "gambit-street",
+ "dir": "~/Studio/raea/projects/gambit",
+ "file": "compositions/people-ingame.tsx",
+ "composition": "people-ingame",
+ "stills": [
+ 0,
+ 1,
+ 5,
+ 6,
+ 10,
+ 11,
+ 15,
+ 16
+ ],
+ "reference": false,
+ "why": "its city is drawn by shader hooks the path tracer can't run and its people aren't traced (M3, M5): after LT2, LT3 and LT5"
+ },
+ {
+ "name": "floor3-room",
+ "dir": "~/Studio/raea/projects/floor3",
+ "file": "compositions/floor3.tsx",
+ "composition": "floor3",
+ "stills": [
+ 300,
+ 900
+ ],
+ "shot": [
+ 600,
+ 630
+ ]
+ },
+ {
+ "name": "kitchen",
+ "dir": "~/Studio/raea/projects/gambit",
+ "file": "compositions/fp-lab-table.tsx",
+ "composition": "fp-lab-table-coat-gloves-day",
+ "stills": [
+ 48,
+ 200
+ ],
+ "shot": [
+ 100,
+ 124
+ ]
+ },
+ {
+ "name": "glade",
+ "dir": "~/Studio/raea/projects/stay",
+ "file": "v3/film.tsx",
+ "composition": "v3-wide",
+ "stills": [
+ 0,
+ 40
+ ],
+ "shot": [
+ 10,
+ 34
+ ]
+ }
+ ]
+}
diff --git a/docs/manual/reference/cli/doctor.md b/docs/manual/reference/cli/doctor.md
index 007c05f0..8f1ea7fb 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: 50
+order: 51
sources: ["apps/workspace/src/doctor.rs"]
---
diff --git a/docs/manual/reference/cli/hook.md b/docs/manual/reference/cli/hook.md
index c35f5df9..a9ab4922 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: 51
+order: 52
sources: ["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.md
index def379f1..0728e153 100644
--- a/docs/manual/reference/cli/index.md
+++ b/docs/manual/reference/cli/index.md
@@ -69,6 +69,7 @@ What's wrong before anyone watches it.
| [`raea fingerprint`](fingerprint.md) | A person's sense of good work, learned on this Mac: axes with small heads over on-device encoders that score a render moment by moment and say what they can't judge yet. |
| [`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, and meter a shot's light. |
+| [`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 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/light.md b/docs/manual/reference/cli/light.md
new file mode 100644
index 00000000..085a9738
--- /dev/null
+++ b/docs/manual/reference/cli/light.md
@@ -0,0 +1,47 @@
+---
+title: "raea light"
+summary: "Measure a scene's light on each light path against its path-traced reference: distance in stops, the worst tile, flicker and cost."
+order: 47
+sources: ["engine/light/src/lib.rs", "engine/light/src/metric.rs", "engine/render/raytrace/src/force.rs"]
+---
+
+`raea light check` is the bar raea's lighting is held to (docs/realism.feature LT1). Each scene in a list is
+rendered on each light path, raster and Solari, and against its reference: the same frames path-traced, each drawn
+`--spp` times so it converges. For each path it reports how far the stills are from the reference in stops (the
+mean, the bias, brighter positive, and the worst 64-pixel tile), how much a moving shot flickers (each pixel's
+second difference in time, in 8-bit steps), and what a frame costs. A reference is made once and kept until
+`--fresh`.
+
+The scenes are a JSON file: `{ "scenes": [{ "name", "dir", "file", "composition", "stills": [frames], "shot":
+[first, last], "reference": false, "why": "..." }] }`. `dir` is the scene's project (renders run there), `file` its
+composition in it; a scene whose reference can't be made yet says so with `"reference": false` and why.
+
+Any render takes the same switches: `RAEA_LIGHT=raster|solari|pathtracer` puts every 3D camera on that path,
+whatever the composition asks, and `RAEA_LIGHT_SPP=N` draws each frame N times.
+
+```sh
+raea light check bench/light/scenes.json -o out/light/
+raea light check bench/light/scenes.json -o out/light/ --scene kitchen --paths solari --spp 512 --fresh
+```
+
+<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->
+
+## Usage
+
+```sh
+raea light check SCENES.json -o DIR [--scene NAME] [--paths raster,solari] [--spp N] [--fresh] (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)
+```
+
+Headless: it needs nothing running and opens no window. Takes up to 2 arguments besides its flags.
+
+## Flags
+
+| Flag | Takes | What it does |
+| --- | --- | --- |
+| `--fresh` | – | Make the references again, even where they're kept from an earlier check. |
+| `--paths` | `raster,solari` | The light paths to measure, comma-separated (both by default). |
+| `--scene` | `NAME` | Check only the scene with this name. |
+| `--spp` | `N` | How many times each reference frame is path-traced: its samples a pixel (256 by default). |
+| `-o` | `DIR` | The folder for each scene's frames and report.json. |
+
+<!-- generated:end -->
diff --git a/docs/manual/reference/cli/next.md b/docs/manual/reference/cli/next.md
index b2bb8b87..f2a3806b 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: 49
+order: 50
sources: ["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.md
index 33a55002..54544a0f 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: 48
+order: 49
sources: ["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.md
index fde68b69..d72d1384 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: 52
+order: 53
sources: ["engine/cli/src/cli.rs", "io/trace/src"]
---
diff --git a/docs/manual/reference/cli/world.md b/docs/manual/reference/cli/world.md
index 442ad03e..c2f90cab 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: 47
+order: 48
sources: ["apps/direction/src/world.rs", "runtime/world/src/lib.rs", "core/facts/src/components.rs"]
---
diff --git a/docs/realism.feature b/docs/realism.feature
index 81974704..ffcd3ce9 100644
--- a/docs/realism.feature
+++ b/docs/realism.feature
@@ -88,7 +88,8 @@ Feature: raea Light: one realism system for shading, ray tracing and occlusion,
made by hand), in the same units and exposure, so switching paths doesn't change brightness.
D11. One set of units: lux, cd/m², EV, and one exposure model for every path. 11-17's captured environment had
to be scaled 1.36, 0.13, 0.02 and 0.006 per sky to match the flat ambient: a sign there's no shared model.
- D12. One owner (proposed 11-17: the session that wrote this file, until the orchestrator or Shane names one). A change to
+ D12. One owner: the session that wrote this file, on lane `realism` (Shane adopted the file 11-17 and set its goal:
+ every LT @done with its numbers). A change to
light, shadow, occlusion or a shading model lands with before and after on the reference scenes (LT1).
Background:
@@ -99,8 +100,10 @@ Feature: raea Light: one realism system for shading, ray tracing and occlusion,
Rule: The bar first
Scenario: LT1. Reference scenes, a reference frame for each, and the numbers
- Given four scenes: gambit's people-ingame (the street and faces, four skies), the FLOOR3 room (interior, light
- jumps), the kitchen (contact shadows and occlusion) and the glade (foliage, sun through leaves)
+ Given four scenes (bench/light/scenes.json): gambit's people-ingame (the street and faces, four skies), the FLOOR3
+ room (interior, light jumps), a kitchen (gambit's first-person table, fp-lab-table: contact shadows and occlusion;
+ the anything film's kitchen doesn't render on 11-17, every composition in content/anything throwing "Can't find
+ variable: raea" before its first frame) and the glade (foliage, sun through leaves)
Then each has a converged <Pathtracer> frame as its reference, in the same units and exposure; gambit's, whose
world is drawn by hooks the path tracer can't run (M5), only once LT2 and LT3 put them in the traced path
And `raea light check` renders each with the current path and reports distance to the reference (mean and
diff --git a/engine/cli/Cargo.toml b/engine/cli/Cargo.toml
index 92a5bb67..7cee4147 100644
--- a/engine/cli/Cargo.toml
+++ b/engine/cli/Cargo.toml
@@ -48,6 +48,8 @@ serde = "1"
serde_json = "1"
# `raea neural` (docs/raytracing.feature RT2)
raea-neural = { path = "../neural" }
+# `raea light check` (docs/realism.feature LT1)
+raea-light = { path = "../light" }
regex = "1"
# the app crates' verbs: `raea check`, `raea ci`, and the local tools' (sao, tokensynth, setup-audio, sounds, splat)
raea-app-check = { path = "../../apps/check" }
diff --git a/engine/cli/src/cli.rs b/engine/cli/src/cli.rs
index 3ed05852..def57121 100644
--- a/engine/cli/src/cli.rs
+++ b/engine/cli/src/cli.rs
@@ -128,6 +128,7 @@ pub fn run(args: &[String]) -> R<String> {
}
if args.is_empty() || matches!(args[0].as_str(), "help" | "--help" | "-h") {
let neural_usage = neural::USAGE;
+ let light_usage = light::USAGE;
let was = IN_HELP.replace(true);
let usage = run(&["render".to_string()]).err().unwrap_or_default();
IN_HELP.set(was);
@@ -145,7 +146,7 @@ pub fn run(args: &[String]) -> R<String> {
let usage = format!("{usage}\n raea spec FILE.ts [--as brief|script|taste|plan|controller] (a spec's default export as JSON, checked against its schema: brief.ts, script.ts, taste.ts, plan.ts, controllers/ID.ts)\n raea workspace init [NAME] [--layout LAYOUT] | raea workspace adopt DIR [--name NAME] | raea workspace [--json] (a workspace: a git repo of projects and controllers 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 controller ls [--json] | raea controller get PATH [--json] | raea controller set PATH VALUE [--project] [--by NAME] | raea controller write FILE.ts [--by NAME] | raea controller rm ID [--by NAME] (the workspace's controllers, controllers/ID.ts; PATH is controller.group.field; every change a commit)\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, scene, physics, splat) = (raea_app_game::USAGE, raea_app_capcut::USAGE, export::SCENE_USAGE, motion::physics::USAGE, tools::splat::USAGE);
let apps = format!(" {}\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_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 {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 {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 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 {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 {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)"));
}
// `--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") {
@@ -242,6 +243,10 @@ 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)
+ if args.first().map(String::as_str) == Some("light") {
+ return light::light(&args[1..]);
+ }
if args.first().map(String::as_str) == Some("mezz") {
return mezz(&args[1..]);
}
diff --git a/engine/cli/src/lib.rs b/engine/cli/src/lib.rs
index 01043bfb..39e10cfc 100644
--- a/engine/cli/src/lib.rs
+++ b/engine/cli/src/lib.rs
@@ -9,6 +9,7 @@ use raea_runtime_export::{self as export, *};
use raea_app_tools as tools;
use serde_json::json;
use raea_neural as neural;
+use raea_light as light;
mod cli;
mod guide;
diff --git a/engine/light/Cargo.toml b/engine/light/Cargo.toml
new file mode 100644
index 00000000..66d7b317
--- /dev/null
+++ b/engine/light/Cargo.toml
@@ -0,0 +1,13 @@
+[package]
+name = "raea-light"
+version = "0.1.0"
+edition = "2024"
+license = "FSL-1.1-ALv2"
+publish = false
+description = "raea light check: each scene on each light path against its path-traced reference, in stops (docs/realism.feature LT1)"
+
+[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" }
diff --git a/engine/light/src/lib.rs b/engine/light/src/lib.rs
new file mode 100644
index 00000000..b4803458
--- /dev/null
+++ b/engine/light/src/lib.rs
@@ -0,0 +1,174 @@
+//! `raea light check SCENES.json -o DIR` (docs/realism.feature LT1): the bar raea Light 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, and what a frame costs. The numbers go to DIR/report.json and a table.
+//!
+//! A scene in SCENES.json: { "name", "dir" (its project, where its renders run; ~ is the home folder), "file" (in dir),
+//! "composition", "stills": [frame, ...], "shot": [first, last] (optional), "reference": false (optional: its
+//! reference can't be made yet, and why, in "why") }.
+
+pub mod metric;
+
+use raea_runtime_bundle::{flag, R};
+use serde_json::{json, Value};
+use std::path::{Path, PathBuf};
+use std::time::Instant;
+
+pub const USAGE: &str = "raea light check SCENES.json -o DIR [--scene NAME] [--paths raster,solari] [--spp N] [--fresh]";
+
+/// The light paths a check compares, as RAEA_LIGHT names them.
+const PATHS: [&str; 2] = ["raster", "solari"];
+
+struct Scene {
+ name: String,
+ dir: PathBuf,
+ file: String,
+ composition: String,
+ stills: Vec<i64>,
+ shot: Option<(i64, i64)>,
+ reference: Result<(), String>,
+}
+
+fn home(p: &str) -> PathBuf {
+ match (p.strip_prefix("~/"), std::env::var_os("HOME")) {
+ (Some(rest), Some(h)) => PathBuf::from(h).join(rest),
+ _ => PathBuf::from(p),
+ }
+}
+
+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()))?;
+ list.iter()
+ .map(|s| {
+ let text = |k: &str| s[k].as_str().map(str::to_string).ok_or(format!("{}: a scene without \"{k}\"", path.display()));
+ let frames = |k: &str| s[k].as_array().map(|a| a.iter().filter_map(Value::as_i64).collect::<Vec<_>>());
+ let shot = frames("shot").filter(|f| f.len() == 2).map(|f| (f[0], f[1]));
+ let reference = if s["reference"] == json!(false) { Err(s["why"].as_str().unwrap_or("not yet").to_string()) } else { Ok(()) };
+ Ok(Scene { name: text("name")?, dir: home(&text("dir")?), file: text("file")?, composition: text("composition")?, stills: frames("stills").unwrap_or_default(), shot, reference })
+ })
+ .collect()
+}
+
+/// 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> {
+ 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 run = std::process::Command::new(exe)
+ .current_dir(&scene.dir)
+ .env("RAEA_LIGHT", path)
+ .env("RAEA_LIGHT_SPP", spp.to_string())
+ .args(["render", &scene.file, "--composition", &scene.composition, "--at", &at.join(","), "-o"])
+ .arg(format!("{}/", out.display()))
+ .output()
+ .map_err(|e| e.to_string())?;
+ 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(" | ")));
+ }
+ Ok(t.elapsed().as_secs_f64())
+}
+
+fn frames(dir: &Path, n: usize) -> R<Vec<metric::Luma>> {
+ (0..n).map(|k| metric::load(&dir.join(format!("frame-{k:05}.png")))).collect()
+}
+
+fn round(x: f32, k: f32) -> f64 {
+ ((x * k).round() / k) as f64
+}
+
+/// One scene: its reference (made once, kept unless --fresh), then each path's stills against it and its shot.
+fn check(scene: &Scene, paths: &[String], spp: u32, out: &Path, fresh: bool) -> R<Value> {
+ let root = out.join(&scene.name);
+ let ref_dir = root.join("reference");
+ let mut report = json!({ "name": scene.name, "stills": scene.stills, "paths": {} });
+ let reference = match &scene.reference {
+ Err(why) => {
+ report["reference"] = json!({ "made": false, "why": why });
+ None
+ }
+ Ok(()) => {
+ if fresh || !ref_dir.join("frame-00000.png").is_file() {
+ let s = render(scene, "pathtracer", spp, &scene.stills, &ref_dir)?;
+ report["reference"] = json!({ "made": true, "spp": spp, "seconds": round(s as f32, 10.0) });
+ } else {
+ report["reference"] = json!({ "made": true, "kept": true });
+ }
+ Some(frames(&ref_dir, scene.stills.len())?)
+ }
+ };
+ for path in paths {
+ let dir = root.join(path);
+ let secs = render(scene, path, 1, &scene.stills, &dir)?;
+ let mut r = json!({ "seconds_a_still": round(secs as f32 / scene.stills.len().max(1) as f32, 100.0) });
+ if let Some(refs) = &reference {
+ let got = frames(&dir, scene.stills.len())?;
+ let d: Vec<metric::Distance> = got.iter().zip(refs).map(|(a, b)| metric::distance(a, b)).collect::<R<_>>()?;
+ let n = d.len().max(1) as f32;
+ r["mean_stops"] = json!(round(d.iter().map(|x| x.mean).sum::<f32>() / n, 1000.0));
+ r["bias_stops"] = json!(round(d.iter().map(|x| x.bias).sum::<f32>() / n, 1000.0));
+ r["worst_tile_stops"] = json!(round(d.iter().map(|x| x.worst).fold(0.0, f32::max), 1000.0));
+ r["per_still"] = json!(d.iter().map(|x| json!({ "mean": round(x.mean, 1000.0), "bias": round(x.bias, 1000.0), "worst": round(x.worst, 1000.0), "worst_tile": [x.worst_at.0, x.worst_at.1] })).collect::<Vec<_>>());
+ }
+ if let Some((a, b)) = scene.shot {
+ let at: Vec<i64> = (a..=b).collect();
+ let shot = root.join(format!("{path}-shot"));
+ let secs = render(scene, path, 1, &at, &shot)?;
+ r["flicker"] = json!(metric::flicker(&frames(&shot, at.len())?).map(|f| round(f, 1000.0)));
+ r["seconds_a_shot_frame"] = json!(round(secs as f32 / at.len() as f32, 100.0));
+ }
+ // the live frame time is measured in play, not here: LT1 leaves it to `raea play`'s own numbers
+ r["live_ms"] = Value::Null;
+ report["paths"][path] = r;
+ }
+ Ok(report)
+}
+
+/// The table a person reads: a line a scene and path.
+fn table(reports: &[Value]) -> String {
+ let mut s = format!("{:<18} {:<8} {:>7} {:>7} {:>7} {:>8} {:>8}\n", "scene", "path", "mean", "bias", "worst", "flicker", "s/still");
+ for r in reports {
+ 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}"));
+ s += &format!("{name:<18} {p:<8} {:>7} {:>7} {:>7} {:>8} {:>8}\n", f("mean_stops"), f("bias_stops"), f("worst_tile_stops"), f("flicker"), f("seconds_a_still"));
+ }
+ if r["reference"]["made"] == json!(false) {
+ s += &format!("{name:<18} (no reference: {})\n", r["reference"]["why"].as_str().unwrap_or(""));
+ }
+ }
+ s
+}
+
+pub fn light(args: &[String]) -> R<String> {
+ if args.first().map(String::as_str) != Some("check") || args.len() < 2 {
+ return Err(format!("usage: {USAGE}"));
+ }
+ 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.iter().map(|p| p.to_string()).collect(), |p| p.split(',').map(str::to_string).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 (raster, solari)"));
+ }
+ let spp: u32 = flag(args, "--spp").map(|v| v.parse().map_err(|_| format!("--spp {v}: a count of samples"))).transpose()?.unwrap_or(256);
+ let fresh = args.iter().any(|a| a == "--fresh");
+ let mut reports = Vec::new();
+ for s in list.iter().filter(|s| only.as_deref().is_none_or(|o| o == s.name)) {
+ eprintln!("raea light: {} ...", s.name);
+ reports.push(check(s, &paths, spp, &out, fresh)?);
+ }
+ if reports.is_empty() {
+ return Err(format!("no scene named {}", only.unwrap_or_default()));
+ }
+ std::fs::create_dir_all(&out).map_err(|e| e.to_string())?;
+ let report = json!({ "scenes": reports });
+ std::fs::write(out.join("report.json"), serde_json::to_string_pretty(&report).unwrap_or_default()).map_err(|e| e.to_string())?;
+ Ok(format!("{}{}", table(&reports), format_args!("raea light: wrote {}", out.join("report.json").display())))
+}
diff --git a/engine/light/src/metric.rs b/engine/light/src/metric.rs
new file mode 100644
index 00000000..5bb8893d
--- /dev/null
+++ b/engine/light/src/metric.rs
@@ -0,0 +1,116 @@
+//! The bar's numbers (docs/realism.feature LT1): how far a frame's light is from its reference, in stops, and how much
+//! a moving shot flickers.
+//!
+//! Both read the frames as they're delivered (8-bit sRGB after tone mapping), each pixel's luminance made linear
+//! again (Rec. 709 weights). A stop is a factor of two in that luminance; pixels darker than FLOOR are compared at
+//! FLOOR, so the noise in near-black doesn't count as error.
+
+use std::path::Path;
+
+/// A frame's linear luminance, row by row, and its size.
+pub struct Luma {
+ pub w: usize,
+ pub h: usize,
+ pub y: Vec<f32>,
+}
+
+/// The darkest luminance a stop is measured from (about sRGB 8/255).
+const FLOOR: f32 = 0.0025;
+/// The side of the squares the worst tile is found among, in pixels.
+pub const TILE: usize = 64;
+
+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) }
+}
+
+pub fn load(p: &Path) -> Result<Luma, String> {
+ let img = image::open(p).map_err(|e| format!("{}: {e}", p.display()))?.to_rgb8();
+ let (w, h) = (img.width() as usize, img.height() as usize);
+ let lut: Vec<f32> = (0..=255u8).map(linear).collect();
+ let y = img.pixels().map(|px| 0.2126 * lut[px[0] as usize] + 0.7152 * lut[px[1] as usize] + 0.0722 * lut[px[2] as usize]).collect();
+ Ok(Luma { w, h, y })
+}
+
+/// A frame against its reference: the mean distance in stops, the mean signed (brighter is positive), and the worst
+/// tile's mean distance with where that tile is (its column and row, in tiles).
+#[derive(Debug, Clone, Copy)]
+pub struct Distance {
+ pub mean: f32,
+ pub bias: f32,
+ pub worst: f32,
+ pub worst_at: (usize, usize),
+}
+
+pub fn distance(a: &Luma, reference: &Luma) -> Result<Distance, String> {
+ if (a.w, a.h) != (reference.w, reference.h) {
+ return Err(format!("sizes differ: {}x{} against the reference's {}x{}", a.w, a.h, reference.w, reference.h));
+ }
+ let (tw, th) = (a.w.div_ceil(TILE), a.h.div_ceil(TILE));
+ let mut tiles = vec![(0.0f64, 0usize); tw * th];
+ let (mut sum, mut signed) = (0.0f64, 0.0f64);
+ for (i, (&p, &r)) in a.y.iter().zip(&reference.y).enumerate() {
+ let d = (p.max(FLOOR) / r.max(FLOOR)).log2() as f64;
+ sum += d.abs();
+ signed += d;
+ let t = &mut tiles[(i / a.w / TILE) * tw + (i % a.w) / TILE];
+ t.0 += d.abs();
+ t.1 += 1;
+ }
+ let n = a.y.len().max(1) as f64;
+ let (k, worst) = tiles.iter().enumerate().map(|(k, (s, c))| (k, s / (*c).max(1) as f64)).fold((0, 0.0), |b, t| if t.1 > b.1 { t } else { b });
+ Ok(Distance { mean: (sum / n) as f32, bias: (signed / n) as f32, worst: worst as f32, worst_at: (k % tw, k / tw) })
+}
+
+/// Flicker over a moving shot: each pixel's second difference in time (this frame against the mean of the frames
+/// either side, so steady motion and steady fades count for nothing), averaged, in 8-bit sRGB steps of luminance.
+/// The frames in order; fewer than three measure nothing.
+pub fn flicker(frames: &[Luma]) -> Option<f32> {
+ if frames.len() < 3 {
+ return None;
+ }
+ let srgb = |v: f32| if v <= 0.0031308 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 } * 255.0;
+ let mut total = 0.0f64;
+ for t in 1..frames.len() - 1 {
+ let (p, c, n) = (&frames[t - 1].y, &frames[t].y, &frames[t + 1].y);
+ let s: f64 = c.iter().zip(p).zip(n).map(|((&c, &p), &n)| (2.0 * srgb(c) - srgb(p) - srgb(n)).abs() as f64).sum();
+ total += s / c.len().max(1) as f64;
+ }
+ Some((total / (frames.len() - 2) as f64) as f32)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn flat(v: f32) -> Luma {
+ Luma { w: 128, h: 64, y: vec![v; 128 * 64] }
+ }
+
+ #[test]
+ fn a_frame_twice_as_bright_is_one_stop_brighter() {
+ let d = distance(&flat(0.4), &flat(0.2)).unwrap();
+ assert!((d.mean - 1.0).abs() < 1e-5 && (d.bias - 1.0).abs() < 1e-5 && (d.worst - 1.0).abs() < 1e-5);
+ }
+
+ #[test]
+ fn the_worst_tile_is_found() {
+ let mut a = flat(0.2);
+ for y in 0..64 {
+ for x in 64..128 {
+ a.y[y * 128 + x] = 0.1;
+ }
+ }
+ let d = distance(&a, &flat(0.2)).unwrap();
+ assert_eq!(d.worst_at, (1, 0));
+ assert!((d.worst - 1.0).abs() < 1e-5 && (d.mean - 0.5).abs() < 1e-5 && (d.bias + 0.5).abs() < 1e-5);
+ }
+
+ #[test]
+ fn a_steady_fade_doesnt_flicker_and_a_blink_does() {
+ let fade: Vec<Luma> = (0..5).map(|k| flat(0.1 + 0.02 * k as f32)).collect();
+ let blink: Vec<Luma> = (0..5).map(|k| flat(if k % 2 == 0 { 0.1 } else { 0.2 })).collect();
+ assert!(flicker(&fade).unwrap() < 1.0);
+ assert!(flicker(&blink).unwrap() > 20.0);
+ }
+}
diff --git a/engine/render/raytrace/src/force.rs b/engine/render/raytrace/src/force.rs
new file mode 100644
index 00000000..cb72dd81
--- /dev/null
+++ b/engine/render/raytrace/src/force.rs
@@ -0,0 +1,64 @@
+//! RAEA_LIGHT (docs/realism.feature LT1): one light path for every 3D camera, whatever the composition asks, so a
+//! scene can be measured on each path without editing it. `raster` takes SolariLighting and Pathtracer off the
+//! cameras; `solari` puts SolariLighting (Bevy's defaults) on each camera in place of a Pathtracer; `pathtracer`
+//! puts Pathtracer on each in place of SolariLighting, for the reference frame (with RAEA_LIGHT_SPP, runtime/export
+//! bevy_frame.rs draws each frame that many times, so it converges). Unset, nothing changes.
+
+use bevy::prelude::*;
+use bevy::solari::pathtracer::Pathtracer;
+use bevy::solari::prelude::SolariLighting;
+
+/// The light path RAEA_LIGHT asks for.
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub enum Path {
+ Raster,
+ Solari,
+ Pathtracer,
+}
+
+/// RAEA_LIGHT's path, if it names one (anything else is said once and ignored).
+pub fn forced() -> Option<Path> {
+ static ON: std::sync::OnceLock<Option<Path>> = std::sync::OnceLock::new();
+ *ON.get_or_init(|| match std::env::var("RAEA_LIGHT").as_deref() {
+ Ok("raster") => Some(Path::Raster),
+ Ok("solari") => Some(Path::Solari),
+ Ok("pathtracer") => Some(Path::Pathtracer),
+ Ok("") | Err(_) => None,
+ Ok(other) => {
+ eprintln!("raea: RAEA_LIGHT={other} isn't a light path (raster, solari or pathtracer); left as the composition has it");
+ None
+ }
+ })
+}
+
+/// Whether the forced path needs Solari's plugins, whatever the program asks.
+pub fn needs_solari() -> bool {
+ matches!(forced(), Some(Path::Solari | Path::Pathtracer))
+}
+
+pub fn add(app: &mut App) {
+ if forced().is_some() {
+ // before Solari's own camera setup (solari.rs `cameras`, in PostUpdate), so a forced camera is set up the frame
+ // it's forced
+ app.add_systems(PreUpdate, cameras);
+ }
+}
+
+/// Every 3D camera on the forced path.
+fn cameras(mut cmd: Commands, q: Query<(Entity, Has<SolariLighting>, Has<Pathtracer>), With<Camera3d>>) {
+ let Some(path) = forced() else { return };
+ for (e, solari, traced) in &q {
+ match path {
+ Path::Raster if solari || traced => {
+ cmd.entity(e).remove::<(SolariLighting, Pathtracer)>();
+ }
+ Path::Solari if !solari || traced => {
+ cmd.entity(e).remove::<Pathtracer>().insert_if_new(SolariLighting::default());
+ }
+ Path::Pathtracer if !traced || solari => {
+ cmd.entity(e).remove::<SolariLighting>().insert_if_new(Pathtracer::default());
+ }
+ _ => {}
+ }
+ }
+}
diff --git a/engine/render/raytrace/src/lib.rs b/engine/render/raytrace/src/lib.rs
index 04cc3b12..e4eafce5 100644
--- a/engine/render/raytrace/src/lib.rs
+++ b/engine/render/raytrace/src/lib.rs
@@ -8,12 +8,19 @@ use std::collections::HashMap;
mod solari;
#[cfg(target_os = "macos")]
mod metalfx;
+// RAEA_LIGHT: one light path for every camera (docs/realism.feature LT1)
+pub mod force;
-pub use solari::add;
+/// Solari's plugins, and RAEA_LIGHT's camera override when it names a path.
+pub fn add(app: &mut App) {
+ solari::add(app);
+ force::add(app);
+}
-/// The program asks for Solari: a camera's SolariLighting or Pathtracer component (`prog` is raea-render's Program).
+/// The program asks for Solari (a camera's SolariLighting or Pathtracer component; `prog` is raea-render's Program),
+/// or RAEA_LIGHT forces it.
pub fn wanted(prog: &impl std::fmt::Debug) -> bool {
- format!("{prog:?}").contains("bevy_solari::")
+ force::needs_solari() || format!("{prog:?}").contains("bevy_solari::")
}
/// After app.finish(): MetalFX's denoiser after Solari's lighting, on the Mac; nothing elsewhere.
diff --git a/runtime/export/src/bevy_frame.rs b/runtime/export/src/bevy_frame.rs
index 6889db08..259d7671 100644
--- a/runtime/export/src/bevy_frame.rs
+++ b/runtime/export/src/bevy_frame.rs
@@ -80,7 +80,11 @@ pub(crate) fn bevy_over_3d(world: &mut World, page: &mut raea_runtime_page::Bevy
let view = if page.has_slot() { None } else { page.view_box() };
e.set_view_box(view);
let mats = page.set_ui_materials(e.world_mut())?;
- // one draw a frame, as the fed render draws it (drawn again, a frame's auto exposure and temporal passes move on)
+ // one draw a frame, as the fed render draws it (drawn again, a frame's auto exposure and temporal passes move on);
+ // RAEA_LIGHT_SPP=N draws it N times, the last kept, so a path-traced reference converges (docs/realism.feature LT1)
+ for _ in 1..spp() {
+ e.draw(cx.now);
+ }
e.draw(cx.now);
raea_sys_frame::gpu::said(e.world_mut(), cx.now)?;
let px = if mats { page.read_ui_materials(e.world()).and_then(|_| page.frame())? } else { px };
@@ -321,3 +325,9 @@ pub(crate) fn page_dump(frame: i64, px: &[u8], w: u32, h: u32, boxes: Option<Vec
}
Ok(())
}
+
+/// RAEA_LIGHT_SPP: how many times each frame's 3D is drawn (1 unset): a path tracer's samples a pixel, one a draw
+fn spp() -> u32 {
+ static N: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
+ *N.get_or_init(|| std::env::var("RAEA_LIGHT_SPP").ok().and_then(|v| v.parse().ok()).filter(|n| *n >= 1).unwrap_or(1))
+}
diff --git a/tools/manual-ref/cli.ts b/tools/manual-ref/cli.ts
index 0c05f46b..faec6ad7 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"])).verbs
const 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", "controller", "spec", "component", "part", "add", "brand", "library", "index"]],
- ["Check", "What's wrong before anyone watches it.", ["check", "judge", "fingerprint", "findings", "scene", "world", "solid", "next", "doctor", "hook", "traces"]],
+ ["Check", "What's wrong before anyone watches it.", ["check", "judge", "fingerprint", "findings", "scene", "light", "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 bakes, clothes and motion for SOMA's body, Blender and Godot.", ["gen", "physics", "clothes", "motion", "blender", "godot"]],