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
SG9: a video render with 3D in it holds a sample of its frames to the same frames rendered on their own
shinyobjectz15af3be4b1c4
diff --git a/Cargo.lock b/Cargo.lockindex 787a8457..7bd80791 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -13739,6 +13739,7 @@ name = "raea-app-direction"version = "0.1.0"dependencies = ["dunce",+ "image","raea-app-check","raea-app-check-text","raea-app-notes",@@ -13746,6 +13747,7 @@ dependencies = ["raea-core-brief","raea-core-facts","raea-io-home",+ "raea-io-media","raea-io-trace","raea-runtime-bundle","raea-runtime-react",diff --git a/apps/direction/Cargo.toml b/apps/direction/Cargo.tomlindex 70bfc5f0..a9f58517 100644--- a/apps/direction/Cargo.toml+++ b/apps/direction/Cargo.toml@@ -14,6 +14,9 @@ raea-runtime-bundle = { path = "../../runtime/bundle" }raea-core-facts = { path = "../../core/facts" }# a render's record named by when it was (UTC)raea-io-trace = { path = "../../io/trace" }+# frame purity (SG9): the video's frames decoded, the stills read+raea-io-media = { path = "../../io/media", default-features = false, features = ["apple", "soft"] }+image = { version = "0.25", default-features = false, features = ["png"] }serde_json = "1"# `raea check PROJECT | EDIT.tsx` (DR4): the taste files' rules, the floor on a composition's newest render, the# project's compositionsdiff --git a/apps/direction/src/lib.rs b/apps/direction/src/lib.rsindex 349d0789..a26a090b 100644--- a/apps/direction/src/lib.rs+++ b/apps/direction/src/lib.rs@@ -7,6 +7,8 @@ pub use world::{cli, find, Find, USAGE};// how `raea render` ends: its findings counted last, and 1 on an error not let through (DR3)mod rendered;pub use rendered::rendered;+// frame purity at a render's end: a sample of its frames rendered again and held to the video's (SG9)+mod pure;// `raea findings`: the project's record read back, fixed, new and carried (DR3)pub mod findings;diff --git a/apps/direction/src/pure.rs b/apps/direction/src/pure.rsnew file mode 100644index 00000000..6edc4ea2--- /dev/null+++ b/apps/direction/src/pure.rs@@ -0,0 +1,240 @@+//! SG9 (docs/stage-guards.feature): a frame looks the same however it is reached. When a video render with 3D in it ends,+//! a sample of its frames is rendered again by one more raea (`render --at`: each frame reached by a jump, none by the+//! frames before it) and held to the same frame of the video. A patch that differs beyond the encoder's noise means a+//! part kept state from an earlier frame: a shape, words, a colour or another part's row held over (SG1–SG4's faults,+//! and any later one of their kind). That frame is rendered alone (`--frame N`, in its own process) to be sure, and the+//! error names the frame, the patch, the parts under it (the stills' manifest, raea-sys-stage's on_screen) and where+//! the two pictures are kept. A frame that differs only when reached by a jump is the engine's fault, not the+//! composition's: a warning. RAEA_FRAME_PURE=0 skips the check (the stills it renders set it).++use std::path::Path;+use std::process::Command;++use raea_core_facts::{Finding, Level};+use serde_json::Value;++/// Sampled: every this many frames, the last frame, and the frame after each remount (more than 20 parts mounting or+/// unmounting at once, as the render's manifest lists them), for a render of more than MIN_FRAMES+const EVERY: u64 = 300;+const MIN_FRAMES: u64 = 60;+/// at most this many samples, spread evenly+const MOST: usize = 64;+/// A pixel differs when a channel differs by more than this (of 255) through a 3x3 erosion, which drops lone pixels (a+/// glyph's edge noise, the encoder's, its colour bleeding along an edge) and keeps a patch: tools/frame-pure-3d.sh's+/// bar, where a cut letter was 318. The largest channel, not luma: an orange part over a grey floor differs by 68 in+/// luma and 116 in blue, and a part that kept another frame's colour is often as bright as its own+const LEVELS: f32 = 96.0;+/// A frame differs when more of its pixels than this share differ (207 at 1080p), and at least LEAST+const SHARE: f64 = 1e-4;+const LEAST: usize = 64;+/// The flags of the render the stills repeat (each takes a value, then the bare ones): what it draws and at what size+const KEEP: [&str; 9] = ["--composition", "--w", "--h", "--fps", "--frames", "--words", "--perception", "--input", "--stage"];+const KEEP_BARE: [&str; 2] = ["--clay", "--lite"];+const BY: &str = "raea render (frame-pure)";++/// The frames to sample of a render `length` frames long, given its remounts.+pub(crate) fn samples(length: u64, remounts: &[u64]) -> Vec<u64> {+ if length <= MIN_FRAMES {+ return Vec::new();+ }+ let mut s: Vec<u64> = (1..).map(|k| k * EVERY).take_while(|f| *f < length).collect();+ s.push(length - 1);+ s.extend(remounts.iter().map(|f| f + 1).filter(|f| *f < length));+ s.sort_unstable();+ s.dedup();+ // more than MOST: the last of each of MOST even runs, so the last frame stays+ let n = s.len();+ if n > MOST {+ s = s.into_iter().enumerate().filter(|(i, _)| (i + 1) * MOST / n > i * MOST / n).map(|(_, f)| f).collect();+ }+ s+}++/// Where two RGBA frames of one size differ: the count of pixels with a channel off by more than LEVELS through a 3x3+/// erosion (every pixel round it differs too), and their box [x0, y0, x1, y1].+pub(crate) fn patch(a: &[u8], b: &[u8], w: usize, h: usize) -> (usize, [usize; 4]) {+ let d: Vec<f32> = (0..w * h)+ .map(|i| {+ let c = |k: usize| (f32::from(a[i * 4 + k]) - f32::from(b[i * 4 + k])).abs();+ c(0).max(c(1)).max(c(2))+ })+ .collect();+ let (mut n, mut bx) = (0, [usize::MAX, usize::MAX, 0, 0]);+ for y in 1..h.saturating_sub(1) {+ for x in 1..w.saturating_sub(1) {+ if (y - 1..=y + 1).all(|yy| (x - 1..=x + 1).all(|xx| d[yy * w + xx] > LEVELS)) {+ n += 1;+ bx = [bx[0].min(x), bx[1].min(y), bx[2].max(x + 1), bx[3].max(y + 1)];+ }+ }+ }+ (n, if n == 0 { [0; 4] } else { bx })+}++fn differs(n: usize, w: usize, h: usize) -> bool {+ n > LEAST.max((SHARE * (w * h) as f64) as usize)+}++/// The render's own flags the stills repeat.+fn kept(args: &[String]) -> Vec<String> {+ let mut out = Vec::new();+ for (i, a) in args.iter().enumerate() {+ if KEEP.contains(&a.as_str()) {+ out.extend(args.get(i..i + 2).into_iter().flatten().cloned());+ } else if KEEP_BARE.contains(&a.as_str()) {+ out.push(a.clone());+ }+ }+ out+}++/// One more raea rendering `file` at `at` into `dir` (its stills, frame-00000.png on, in `at`'s order, and its+/// manifest); its own errors are let through, since these are pictures to compare, not the render. Stills past 3,600+/// frames make their 3D live at each (render_bundle's LIVE_PAST): 64 of a 13,175-frame film reached by rows went past+/// 30 GB and were killed.+fn stills(file: &str, args: &[String], at: &[u64], dir: &Path) -> Result<Value, String> {+ let me = std::env::current_exe().map_err(|e| e.to_string())?;+ let list: Vec<String> = at.iter().map(u64::to_string).collect();+ std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;+ let manifest = dir.join("stills.json");+ let (flag, out) = if at.len() == 1 { ("--frame", dir.join("frame-00000.png").display().to_string()) } else { ("--at", format!("{}/", dir.display())) };+ let o = Command::new(me).arg("render").arg(file).args(kept(args)).args([flag, &list.join(","), "-o", &out, "--manifest"]).arg(&manifest).env("RAEA_RECORD", "off").env("RAEA_FRAME_PURE", "0").env("RAEA_DESPITE", "all: frame-pure's own stills").output().map_err(|e| e.to_string())?;+ let m = std::fs::read(&manifest).ok().and_then(|b| serde_json::from_slice::<Value>(&b).ok());+ m.ok_or_else(|| format!("the stills didn't render: {}", String::from_utf8_lossy(&o.stderr).lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("no message")))+}++fn png(p: &Path) -> Option<(Vec<u8>, usize, usize)> {+ let img = image::open(p).ok()?.into_rgba8();+ let (w, h) = img.dimensions();+ Some((img.into_raw(), w as usize, h as usize))+}++/// The parts on screen at `frame` whose boxes meet `bx`, most overlap first (the manifest of the frame rendered alone:+/// its `parts` hold that one frame).+fn under(m: &Value, frame: u64, bx: [usize; 4]) -> Vec<String> {+ let at = &m["parts"][0];+ if at["frame"] != frame {+ return Vec::new();+ }+ let b = bx.map(|v| v as f64);+ let mut hit: Vec<(f64, String)> = at["parts"]+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(|p| {+ let r: Vec<f64> = p[1].as_array()?.iter().filter_map(Value::as_f64).collect();+ let r: [f64; 4] = r.try_into().ok()?;+ let over = (b[2].min(r[2]) - b[0].max(r[0])).max(0.0) * (b[3].min(r[3]) - b[1].max(r[1])).max(0.0);+ (over > 0.0).then(|| (over, p[0].as_str().unwrap_or("a part").to_string()))+ })+ .collect();+ hit.sort_by(|a, b| b.0.total_cmp(&a.0));+ hit.into_iter().map(|h| h.1).take(3).collect()+}++/// SG9 on a finished render: its findings, none when it isn't a video with 3D in it of more than MIN_FRAMES.+pub fn check(args: &[String], out: &Path, manifest: &Value) -> Vec<Finding> {+ let (Some(file), true) = (args.get(1), manifest["has3d"].as_bool() == Some(true)) else { return Vec::new() };+ if std::env::var("RAEA_FRAME_PURE").as_deref() == Ok("0") || args.iter().any(|a| a == "--frame" || a == "--at") {+ return Vec::new();+ }+ let remounts: Vec<u64> = manifest["remounts"].as_array().into_iter().flatten().filter_map(Value::as_u64).collect();+ let at = samples(manifest["length"].as_u64().unwrap_or(0), &remounts);+ let fps = manifest["fps"].as_f64().unwrap_or(30.0);+ if at.is_empty() {+ return Vec::new();+ }+ let dir = std::env::temp_dir().join(format!("raea-frame-pure-{}", std::process::id()));+ let found = run(file, args, out, &at, fps, &dir).unwrap_or_else(|e| vec![Finding::new("frame-pure", Level::Note, format!("frame purity wasn't checked: {e}"), BY)]);+ let _ = std::fs::remove_dir_all(&dir);+ found+}++fn run(file: &str, args: &[String], out: &Path, at: &[u64], fps: f64, dir: &Path) -> Result<Vec<Finding>, String> {+ std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;+ stills(file, args, at, &dir.join("at"))?;+ let mut video = raea_io_media::preferred().into_iter().find_map(|b| b.open_video(out).ok()).ok_or_else(|| format!("{}: no decoder opens it", out.display()))?;+ let keep = out.with_extension("frame-pure");+ let mut found = Vec::new();+ for (i, &f) in at.iter().enumerate() {+ let Some((jump, w, h)) = png(&dir.join(format!("at/frame-{i:05}.png"))) else { continue };+ let v = video.frame_at((f as f64 + 0.5) / fps)?;+ if (v.width as usize, v.height as usize) != (w, h) {+ return Err(format!("the video is {}x{}, its stills {w}x{h}", v.width, v.height));+ }+ if !differs(patch(&v.rgba, &jump, w, h).0, w, h) {+ continue;+ }+ // reached by a jump it differs: rendered alone, in its own process, to be sure+ let one = dir.join(format!("alone-{f}"));+ let alone_m = stills(file, args, &[f], &one)?;+ let Some((alone, _, _)) = png(&one.join("frame-00000.png")) else { continue };+ let (n, bx) = patch(&v.rgba, &alone, w, h);+ let parts = under(&alone_m, f, bx);+ let named = if parts.is_empty() { String::new() } else { format!(" over {}", parts.join(", ")) };+ let finding = if differs(n, w, h) {+ std::fs::create_dir_all(&keep).map_err(|e| e.to_string())?;+ let (seq, own) = (keep.join(format!("frame-{f:05}-render.png")), keep.join(format!("frame-{f:05}-alone.png")));+ image::save_buffer(&seq, &v.rgba, w as u32, h as u32, image::ColorType::Rgba8).map_err(|e| e.to_string())?;+ std::fs::copy(one.join("frame-00000.png"), &own).map_err(|e| e.to_string())?;+ let mut x = Finding::new("frame-pure", Level::Error, format!("{n} pixels{named} (x {}-{}, y {}-{}) differ from the frame rendered alone: a part kept an earlier frame's shape, words, colour or row. The two are {} and {}", bx[0], bx[2], bx[1], bx[3], seq.display(), own.display()), BY).frames(f as i64, f as i64 + 1).measure("pixels", n as f64, "px", Some(LEAST.max((SHARE * (w * h) as f64) as usize) as f64));+ for p in &parts {+ x = x.about(p.clone(), None);+ }+ x.fix("find what that part takes from the frames before (a key it keeps, a prop read once), or `raea bug` with both pictures when it's raea's")+ } else {+ Finding::new("frame-pure-jump", Level::Warn, format!("frame {f}{named} differs when the render jumps to it from frame {}, not alone or in sequence: raea's, not the composition's (`raea bug` with this line)", if i > 0 { at[i - 1].to_string() } else { "0".into() }), BY).frames(f as i64, f as i64 + 1)+ };+ found.push(finding);+ }+ Ok(found)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn samples_every_300th_the_last_and_after_each_remount() {+ assert!(samples(60, &[]).is_empty());+ assert_eq!(samples(180, &[]), vec![179]);+ assert_eq!(samples(1000, &[40, 599, 999]), vec![41, 300, 600, 900, 999]);+ let many = samples(1_000_000, &[]);+ assert_eq!((many.len(), many.last()), (MOST, Some(&999_999)));+ }++ #[test]+ fn a_patch_counts_but_lone_pixels_and_noise_dont() {+ let (w, h) = (64, 32);+ let a = vec![40u8; w * h * 4];+ let mut b = a.clone();+ // noise: every pixel off by 20, and lone pixels off by 200+ b.iter_mut().for_each(|v| *v += 20);+ for i in (0..w * h).step_by(7) {+ b[i * 4..i * 4 + 3].copy_from_slice(&[240, 240, 240]);+ }+ assert_eq!(patch(&a, &b, w, h).0, 0);+ // a 10x6 block of words turned white at x 20, y 8: its eroded inside, 8x4+ for y in 8..14 {+ for x in 20..30 {+ b[(y * w + x) * 4..(y * w + x) * 4 + 3].copy_from_slice(&[255, 255, 255]);+ }+ }+ let (n, bx) = patch(&a, &b, w, h);+ assert_eq!(n, 32);+ assert_eq!(bx, [21, 9, 29, 13]);+ }++ #[test]+ fn the_stills_repeat_what_the_render_draws_and_nothing_else() {+ let a: Vec<String> = ["render", "e.tsx", "-o", "out.mp4", "--composition", "k3", "--kbps", "8000", "--clay", "--despite", "type-small", "why", "--frames", "90"].iter().map(|s| s.to_string()).collect();+ assert_eq!(kept(&a), ["--composition", "k3", "--clay", "--frames", "90"]);+ }++ #[test]+ fn the_parts_under_a_patch_most_overlap_first() {+ let m = serde_json::json!({"parts": [{"frame": 600, "parts": [["floor", [0.0, 500.0, 1920.0, 1080.0]], ["counter", [800.0, 300.0, 1000.0, 400.0]], ["sky", [0.0, 0.0, 1920.0, 200.0]]]}]});+ assert_eq!(under(&m, 600, [850, 350, 1000, 520]), ["counter", "floor"]);+ assert!(under(&m, 300, [850, 350, 1000, 520]).is_empty());+ }+}diff --git a/apps/direction/src/rendered.rs b/apps/direction/src/rendered.rsindex 14126a05..6c32a0e1 100644--- a/apps/direction/src/rendered.rs+++ b/apps/direction/src/rendered.rs@@ -47,8 +47,9 @@ pub fn rendered(args: &[String]) -> i32 {if let Some(m) = manifest {if let Some(mut v) = std::fs::read(&m).ok().and_then(|b| serde_json::from_slice::<Value>(&b).ok()) {// a video's text, held to the check's text rules as it finishes, a check's round sooner- if out.as_deref().and_then(|o| o.extension()).is_some_and(|x| x == "mp4" || x == "mov") {- for f in text_found(&v) {+ if let Some(o) = out.as_deref().filter(|o| matches!(o.extension().and_then(|x| x.to_str()), Some("mp4" | "mov"))) {+ // and a sample of its frames rendered again, each held to the video's (SG9, pure.rs)+ for f in text_found(&v).into_iter().chain(crate::pure::check(args, o, &v)) {println!("{}", f.line());found.push(f);}diff --git a/docs/manual/reference/cli/render.md b/docs/manual/reference/cli/render.mdindex 9de671c9..5771261e 100644--- a/docs/manual/reference/cli/render.md+++ b/docs/manual/reference/cli/render.md@@ -41,8 +41,14 @@ frames), or where `--manifest` says. It holds what each frame showed as laid outsize, each video's source and time), the sounds heard and what the render found. `raea check` reads it, and so does[`raea world`](world.md), which measures the output against it when a check asks.-A render checks what it draws: 3D parts passing into each other (the clipping check) and its pictures' exposure-(clipping to white, crushing to black). Each finding is said as it is found, written into the manifest, and+A render checks what it draws: 3D parts passing into each other (the clipping check), how its 3D is staged (3D type+too small or turned to read, parts that snap, a camera that lurches, frames with almost nothing on screen; `raea scene+stage` runs these without drawing) and its pictures' exposure (clipping to white, crushing to black). A video with 3D+in it, longer than 60 frames, is also checked for frame purity: every 300th frame, its last, and the frame after each+change of more than 20 parts are rendered again on their own and held to the video's. A patch that differs is an error+naming the frame and the parts under it, with both pictures kept beside the video (`OUT.frame-pure/`), since a part+that keeps an earlier frame's state draws wrong in the video but right in a still. `RAEA_FRAME_PURE=0` skips it.+Each finding is said as it is found, written into the manifest, andcounted on the last line the command prints (`raea render: 1 error, 0 warns, 0 notes`). An errormakes the render exit 1 once its output is written; `--despite CHECK WHY` lets that check's errors through and putsthe reason in the manifest. A render of a file in a raea project also keeps its findings in the project's recorddiff --git a/docs/stage-guards.feature b/docs/stage-guards.featureindex ffa53c17..a37f2d2b 100644--- a/docs/stage-guards.feature+++ b/docs/stage-guards.feature@@ -241,6 +241,29 @@ Feature: Stage guards: a 3D render an agent can't breakThen any part whose pixels differ beyond the encoder's noise is an error naming the part, the frame and the propsthat differAnd this catches SG1–SG4 and any later fault of the same kind before a person sees it+ # Status 11-21 (branch stage-guards-8): built for a video with 3D in it, more than 60 frames. At the render's end+ # one more raea renders the sample with `--at` (each frame reached by a jump) and each still is held to the+ # video's frame: a channel off by more than 96 levels through a 3x3 erosion (tools/frame-pure-3d.sh's bar, which+ # drops the encoder's and a glyph edge's lone pixels), on more than 1e-4 of the frame. The largest channel, not+ # luma: the positive control (a box moved by a counter outside the frame) put an orange box where the alone frame+ # has grey floor, 68 levels apart in luma and 116 in blue. A frame that differs is rendered+ # alone (`--frame N`, its own process): still different, a `frame-pure` error naming the frame, the patch's box,+ # the parts under it (the still's manifest now lists each frame's parts on screen, raea-sys-stage's on_screen)+ # and the two pictures, kept in OUT.frame-pure/; matching alone, a `frame-pure-jump` warning (raea's fault, not+ # the composition's). The sample is every 300th frame, the last (most history behind it, so a render under 300+ # frames is sampled too) and the frame after each remount, from the manifest's new `remounts`; at most 64.+ # Left: "each chunk's first" (raea render has no chunks of its own); "the props that differ" (React is+ # frame-pure, so both routes hand the engine the same props: what differs is the engine's state, and the+ # error names the parts instead). RAEA_FRAME_PURE=0 skips it. Measured before building, alone (`--frame N`)+ # against the sequence on four real scenes of 91-180 frames: three match exactly (SSIM 1.0); one under Solari+ # GI differs in SSIM (0.97-0.99, the GI's history) with no patch past the bar after frame 0.+ Given the plan+ | crate | file | lines | job |+ | raea-app-direction | apps/direction/src/pure.rs | 230 | the sample, the stills and the alone frame, the patch, the parts under it, the findings |+ | raea-app-direction | apps/direction/src/rendered.rs | +2 | a video render's end runs it beside the text rules |+ | raea-runtime-export | runtime/export/src/scene.rs | +40 | the manifest's `parts` (stills) and `remounts` (longer renders) |+ | raea-runtime-export | runtime/export/src/lib.rs | +4 | write_manifest takes them |+ | raea-sys-stage | systems/stage/src/framing.rs | +12 | on_screen: each part's box on screen, named |Scenario: SG10. 3D type that readsGiven the plandiff --git a/runtime/export/src/lib.rs b/runtime/export/src/lib.rsindex 5415adec..a573582c 100644--- a/runtime/export/src/lib.rs+++ b/runtime/export/src/lib.rs@@ -73,7 +73,12 @@ static MANIFEST: std::sync::Mutex<Option<PathBuf>> = std::sync::Mutex::new(None)fn write_manifest(cx: &mut Ctx, (w, h, fps, length): (u32, u32, f64, i64), found: Vec<raea_core_facts::Finding>, heard: impl FnOnce(&Ctx) -> Value) -> R<()> {let (Some(path), Some(frames)) = (MANIFEST.lock().unwrap().clone(), cx.manifest.take()) else { return Ok(()) };path.parent().map_or(Ok(()), std::fs::create_dir_all).map_err(|e| format!("{}: {e}", path.display()))?;- std::fs::write(&path, json!({"width": w, "height": h, "fps": fps, "length": length, "frames": frames, "findings": raea_core_facts::finding::ranked(found), "sounds": heard(cx), "not_applied": not_applied::seen(), "layers": raea_sys_layers::finish(fps), "has3d": cx.scene3d.is_some() || cx.live3d.is_some()}).to_string()).map_err(|e| format!("{}: {e}", path.display()))+ let mut v = json!({"width": w, "height": h, "fps": fps, "length": length, "frames": frames, "findings": raea_core_facts::finding::ranked(found), "sounds": heard(cx), "not_applied": not_applied::seen(), "layers": raea_sys_layers::finish(fps), "has3d": cx.scene3d.is_some() || cx.live3d.is_some()});+ // the parts SG9 needs (scene.rs's SEEN): stills' parts on screen, a longer render's remounts+ if let (Some(m), Some(Value::Object(seen))) = (v.as_object_mut(), scene::SEEN.lock().unwrap().take()) {+ m.extend(seen);+ }+ std::fs::write(&path, v.to_string()).map_err(|e| format!("{}: {e}", path.display()))}/// `render --stage WxH`: a responsive composition (one that lays out from useVideoConfig) laid out at a stage's size, asdiff --git a/runtime/export/src/scene.rs b/runtime/export/src/scene.rsindex d0416f37..1e6b59aa 100644--- a/runtime/export/src/scene.rs+++ b/runtime/export/src/scene.rs@@ -21,11 +21,49 @@ pub(crate) fn told(frames: &[(i64, Frame)], w: u32, h: u32, fps: f64) -> Vec<raereturn Vec::new();}let (nums, all): (Vec<i64>, _) = (frames.iter().map(|(f, _)| *f).collect(), all_items(frames));+ *SEEN.lock().unwrap() = seen(&all, &nums, w, h);let mut found = if std::env::var("RAEA_CLIP_CHECK").as_deref() == Ok("0") { Vec::new() } else { raea_sys_contact::told(&all, &nums, w, h, fps) };found.extend(raea_sys_stage::told(&all, &nums, w, h, fps));found}+/// A render of at most this many frames is stills (`--frame`, `--at`): its manifest names each frame's parts on screen+const STILLS: usize = 16;+/// More than this many parts mounting or unmounting between two frames is a remount+const REMOUNT: usize = 20;++/// What the manifest says of a render's parts (render.rs's write_manifest takes it): for stills, each frame's parts on+/// screen and their boxes (`parts`); for a longer render, the frames where more than REMOUNT parts mount or unmount+/// (`remounts`). SG9 re-renders the frame after each remount alone and names the parts under a patch that differs.+pub(crate) static SEEN: std::sync::Mutex<Option<serde_json::Value>> = std::sync::Mutex::new(None);++fn seen(all: &[Vec<raea_core_scene::Item>], nums: &[i64], w: u32, h: u32) -> Option<serde_json::Value> {+ if all.len() <= STILLS {+ let parts: Vec<_> = all.iter().zip(nums).map(|(its, f)| serde_json::json!({"frame": f, "parts": raea_sys_stage::on_screen(its, w, h)})).collect();+ return Some(serde_json::json!({"parts": parts}));+ }+ let counts: Vec<_> = all.iter().map(|its| counted(its)).collect();+ let remounts: Vec<i64> = (1..counts.len()).filter(|&k| changed(&counts[k], &counts[k - 1]) > REMOUNT).map(|k| nums[k]).collect();+ Some(serde_json::json!({"remounts": remounts}))+}++type Counted<'a> = std::collections::HashMap<(&'a str, &'a str, u64), i64>;++/// A frame's parts as a count by what they are: kind, name, what they draw.+fn counted(its: &[raea_core_scene::Item]) -> Counted<'_> {+ let mut m = Counted::new();+ for it in its {+ *m.entry((it.kind, raea_core_scene::base_ident(it), raea_core_scene::spawn_sig(it))).or_default() += 1;+ }+ m+}++/// How many parts mount or unmount from one frame's count to the next's.+fn changed(a: &Counted, b: &Counted) -> usize {+ let off = |x: &Counted, y: &Counted| x.iter().map(|(k, n)| (n - y.get(k).copied().unwrap_or(0)).max(0) as usize).sum::<usize>();+ off(a, b) + off(b, a)+}+/// `--frame N`, 0 when it isn't given (scene lint and render --review).pub fn frame_of(args: &[String]) -> Result<i64, String> {match flag(args, "--frame") {diff --git a/systems/stage/src/framing.rs b/systems/stage/src/framing.rsindex 09e06dd6..e8b2395d 100644--- a/systems/stage/src/framing.rs+++ b/systems/stage/src/framing.rs@@ -55,6 +55,18 @@ fn own_box(it: &raea_core_scene::Item, boxes: &mut HashMap<String, Option<(Vec3,}}+/// Each part of known size that shows in a frame: its name as the checks call it, and its box on screen, [x0, y0, x1,+/// y1] in px (SG9 names the parts under a patch that differs between a frame rendered in sequence and alone).+pub fn on_screen(its: &[raea_core_scene::Item], w: u32, h: u32) -> Vec<(String, [f32; 4])> {+ let Some(v) = crate::view::View::of(its, w, h) else { return Vec::new() };+ let mut boxes = HashMap::new();+ let seen = |it: &raea_core_scene::Item, boxes: &mut HashMap<_, _>| {+ let (lo, hi) = own_box(it, boxes)?;+ v.bounds(corners(&it.world, lo, hi)).filter(|b| v.share(*b) > 0.0)+ };+ its.iter().filter_map(|it| Some((called(it), seen(it, &mut boxes)?))).collect()+}+pub(crate) fn check(st: &Stage) -> Vec<Finding> {let n = st.all.len();let mut boxes = HashMap::new();@@ -173,6 +185,16 @@ mod tests {assert!(run(fs).iter().any(|f| f.check == "frame-empty"));}+ #[test]+ fn parts_on_screen_are_named_with_their_boxes() {+ let its = vec![cam([0.0, 0.0, 6.0], [0.0; 3]), cube("dash", [0.0; 3]), cube("gone", [0.0, 0.0, 20.0])];+ let on = super::on_screen(&its, 1920, 1080);+ assert_eq!(on.len(), 1, "{on:?}");+ let (name, b) = &on[0];+ assert!(name.contains("dash"), "{name}");+ assert!(b[0] < 960.0 && b[2] > 960.0 && b[1] < 540.0 && b[3] > 540.0, "{b:?}");+ }+#[test]fn the_shots_subject_half_out_of_frame_is_cut() {// the cube's centre near the frame's right edgediff --git a/systems/stage/src/lib.rs b/systems/stage/src/lib.rsindex 69bd2f45..5ef7288b 100644--- a/systems/stage/src/lib.rs+++ b/systems/stage/src/lib.rs@@ -13,6 +13,7 @@ mod framing;mod motion;mod text;mod view;+pub use framing::on_screen;pub use view::View;/// Who says these findings, in a render.