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.

SG4a: the end checks run as the frames come

shinyobjectz3c8fc66bc0af
diff --git a/Cargo.lock b/Cargo.lock
index aad1f5b8..742e4935 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -14603,17 +14603,6 @@ dependencies = [
"url",
]
-[[package]]
-name = "raea-io-kept"
-version = "0.1.0"
-dependencies = [
- "bevy",
- "raea-core-scene",
- "raea-io-home",
- "serde",
- "serde_json",
-]
-
[[package]]
name = "raea-io-media"
version = "0.1.0"
@@ -15266,6 +15255,17 @@ dependencies = [
"wgpu",
]
+[[package]]
+name = "raea-runtime-endchecks"
+version = "0.1.0"
+dependencies = [
+ "raea-core-facts",
+ "raea-core-scene",
+ "raea-sys-contact",
+ "raea-sys-stage",
+ "serde_json",
+]
+
[[package]]
name = "raea-runtime-export"
version = "0.1.0"
@@ -15280,7 +15280,6 @@ dependencies = [
"raea-gpu-device",
"raea-io-alpha",
"raea-io-assets",
- "raea-io-kept",
"raea-io-media",
"raea-io-net",
"raea-io-trace",
@@ -15288,6 +15287,7 @@ dependencies = [
"raea-render",
"raea-runtime-bake",
"raea-runtime-encode",
+ "raea-runtime-endchecks",
"raea-runtime-page",
"raea-runtime-pagestore",
"raea-runtime-react",
diff --git a/Cargo.toml b/Cargo.toml
index e0721d41..0298d0bc 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -60,7 +60,6 @@ members = [
"engine/page/window",
"io/trace",
"io/codec",
- "io/kept",
"io/media",
"io/assets",
"io/clef",
@@ -187,6 +186,7 @@ members = [
"runtime/wear",
"runtime/canvas",
"runtime/export",
+ "runtime/endchecks",
"runtime/live",
"runtime/page",
"runtime/appscreen",
diff --git a/core/scene/src/lib.rs b/core/scene/src/lib.rs
index b328a381..7b0d77fe 100644
--- a/core/scene/src/lib.rs
+++ b/core/scene/src/lib.rs
@@ -111,18 +111,13 @@ pub fn spans_of(all: &[Vec<Item>], kinds: &[&str]) -> Vec<(String, Span)> {
let mut order: Vec<String> = Vec::new();
let mut by: BTreeMap<String, Span> = BTreeMap::new();
for (i, its) in all.iter().enumerate() {
- let mut seen: BTreeMap<String, usize> = BTreeMap::new();
- for it in its.iter().filter(|it| kinds.contains(&it.kind)).cloned() {
- let base = format!("{}|{}{}", it.kind, base_ident(&it), surface_ident(&it));
- let k = seen.entry(base.clone()).or_insert(0);
- let id = format!("{base}#{k}");
- *k += 1;
+ for (id, it) in ids_of(its, kinds) {
let span = by.entry(id.clone()).or_insert_with(|| {
order.push(id.clone());
Span { first: i, items: Vec::new() }
});
span.items.resize(i - span.first, None);
- span.items.push(Some(it));
+ span.items.push(Some(it.clone()));
}
}
order.into_iter().map(|id| {
@@ -131,6 +126,23 @@ pub fn spans_of(all: &[Vec<Item>], kinds: &[&str]) -> Vec<(String, Span)> {
}).collect()
}
+/// A frame's parts of these kinds, each with its id as spans_of names it across frames: its kind, what it is and draws,
+/// and which of the frame's parts alike it is (#0, #1, ...). A check taking frames as they come (raea-sys-contact's
+/// Clipping) follows a part from frame to frame by it.
+pub fn ids_of<'a>(its: &'a [Item], kinds: &[&str]) -> Vec<(String, &'a Item)> {
+ let mut seen: BTreeMap<String, usize> = BTreeMap::new();
+ its.iter()
+ .filter(|it| kinds.contains(&it.kind))
+ .map(|it| {
+ let base = format!("{}|{}{}", it.kind, base_ident(it), surface_ident(it));
+ let k = seen.entry(base.clone()).or_insert(0);
+ let id = format!("{base}#{k}");
+ *k += 1;
+ (id, it)
+ })
+ .collect()
+}
+
/// `tracks` over items already walked: only the parts of these kinds are copied, a slot for every frame
pub fn tracks_of(all: &[Vec<Item>], kinds: &[&str]) -> Vec<(String, Vec<Option<Item>>)> {
spans_of(all, kinds)
diff --git a/docs/linux.feature b/docs/linux.feature
index 6886c529..f53f7ab7 100644
--- a/docs/linux.feature
+++ b/docs/linux.feature
@@ -140,7 +140,7 @@ Feature: The Linux engine, as fast as it can be in the cloud
Given the plan
| crate | file | lines | job |
| raea-sys-contact | systems/contact/src/broad.rs | 160 | a broad phase before the voxels: parts whose boxes don't touch on a frame are never voxelized or tested; a part's voxels kept by its shape and scale, so an unchanged part is voxelized once a render |
- | raea-sys-contact | systems/contact/src/lib.rs | 500 | the frames checked in parallel (frames are pure), on the cores the render leaves idle |
+ | raea-sys-contact | systems/contact/src/clip.rs | 178 | the frames checked on the cores the render leaves idle: Clipping takes each frame as it's drawn since SG4a (docs/stage-guards.feature), so off the render's thread |
Then edit.tsx's clipping check takes at most its frames' own time (from 96.1 s), and RR0's film's at most 300 ms
And a render's wall with the check on is within 3% of RAEA_CLIP_CHECK=0
And the findings are identical on the RR0 film, edit.tsx and the contact fixtures (systems/contact's tests)
diff --git a/docs/stage-guards.feature b/docs/stage-guards.feature
index 9783829d..70e95f23 100644
--- a/docs/stage-guards.feature
+++ b/docs/stage-guards.feature
@@ -193,6 +193,19 @@ Feature: Stage guards: a 3D render an agent can't break
| raea-io-trace | io/trace/src/lib.rs | +20 | give_back: the allocator's freed memory returned to the system now |
| raea-io-home | io/home/src/lib.rs | +15 | scratch_file: a temp file gone when raea is (the encoder's samples, Kept's parts) |
| raea-io-codec | io/codec/src/samples.rs | 0 | Samples' temp file from scratch_file (8 lines shorter) |
+ | raea-core-scene | core/scene/src/lib.rs | +12 | ids_of: a frame's parts with the ids spans_of follows them by; spans_of built on it |
+ | raea-sys-stage | systems/stage/src/lib.rs | +51 | Staging: the staging checks fed a frame at a time (push), their findings at the end; told and check_with feed it |
+ | raea-sys-stage | systems/stage/src/text.rs | +9 | Texts: each block of words' frames kept as they come |
+ | raea-sys-stage | systems/stage/src/motion.rs | +12 | Snaps: each named part's size and place on screen kept as they come |
+ | raea-sys-stage | systems/stage/src/framing.rs | +14 | Framing: each frame's share covered, whether it can be judged, and its subject, as they come |
+ | raea-sys-stage | systems/stage/src/page.rs | +10 | Over: the page's words over the parts, as the frames come |
+ | raea-sys-stage | systems/stage/src/manifest.rs | +28 | Mounts: what the manifest says of the parts, a frame at a time |
+ | raea-sys-contact | systems/contact/src/clip.rs | +175 | Clipping: each frame's pairs tested as it comes; an overlap's two parts and solids kept for its sentence |
+ | raea-sys-contact | systems/contact/src/solid.rs | +27 | Held: a part's solid made as it first shows, let go once it's been gone 120 frames (made again if it comes back) |
+ | raea-sys-contact | systems/contact/src/lib.rs | 0 | deepest, shared by the clipping check and the lint; the slice check and told gone (116 lines shorter) |
+ | raea-runtime-endchecks | runtime/endchecks/src/lib.rs | +55 | EndChecks: the clipping check, the staging and the parts on screen fed each frame's parts as it's drawn |
+ | raea-runtime-export | runtime/export/src/fed.rs | +3 | a live render's frames go to EndChecks as they're drawn |
+ | raea-runtime-export | runtime/export/src/scene.rs | 0 | a still's frames go to EndChecks one at a time, its parts made and let go (3 lines shorter) |
Then a 13,000-frame 3D render's memory stays within 10% of its first minute's
# Status 11-21 (branch stage-guards-8): the film (13,175 frames, 7:19) renders whole with every end check on, at
# a 9.4 to 13.6 GB peak. Before, memguard killed it past 24 GB (28 to 33 GB) after its last frame. Four causes,
@@ -270,6 +283,17 @@ Feature: Stage guards: a 3D render an agent can't break
# frames grow 27%, most of it its later scenes' own (2.07 to 2.55 GB in the 1,000 frames from 5:33). The end
# checks hold every frame's parts and each part's solid over its frames (the clipping check's 4.7 GB resident
# peak); flat needs them to run as the frames come.
+ # Branch stage-guards-21: the end checks run as the frames come. raea-sys-stage's Staging and raea-sys-contact's
+ # Clipping take each frame's parts as it's drawn (raea-runtime-endchecks hands them in) and keep only what their
+ # verdicts read: each frame's camera, each block of words' and each named part's place on screen, each frame's
+ # cover and subject, the words over parts, and the solids of the parts on screen (a part's let go once it's been
+ # gone 120 frames, an overlap's kept until it's said; the pair tests reused are the last frame's alone). Nothing
+ # keeps a render's parts now: raea-io-kept is gone. The film: the same 439 errors, 705 warns and 47 notes, in the
+ # same order; the end checks take 0.6 s (22.7 s: their work is done as the frames come); a 4.06 GB resident peak
+ # (4.76). The control: its end checks add nothing, 1.32 GB after its last frame and after them (they rose to 1.52
+ # GB before). Still not met: the frames grow. The control's 1.06 GB at frame 1,000 is 1.32 GB at 13,000 (+25%;
+ # +20% over frame 2,000), as before; the film's frames now carry the clipping check's solids for the parts on
+ # screen, 2.31 GB at frame 1,000 and 2.91 GB at 13,000 (+26%), 4.13 GB in its densest minute (frame 5,000).
Rule: The SDK stops allowing it
diff --git a/engine/cli/src/lib.rs b/engine/cli/src/lib.rs
index 39e10cfc..b2247e90 100644
--- a/engine/cli/src/lib.rs
+++ b/engine/cli/src/lib.rs
@@ -5,7 +5,7 @@ use std::collections::HashMap;
use std::path::{Path, PathBuf};
use raea_runtime_react::scene::{self as motion, *};
-use raea_runtime_export::{self as export, *};
+use raea_runtime_export::*;
use raea_app_tools as tools;
use serde_json::json;
use raea_neural as neural;
diff --git a/engine/cli/src/tests.rs b/engine/cli/src/tests.rs
index 9af6b7b0..ea52522a 100644
--- a/engine/cli/src/tests.rs
+++ b/engine/cli/src/tests.rs
@@ -32,7 +32,7 @@ fn help_lists_every_verb() {
let listed = |v: &str| [format!("raea {v} "), format!("raea {v}\n"), format!("| {v} ")].iter().any(|l| help.contains(l.as_str()));
let missing: Vec<_> = verbs.iter().filter(|v| !listed(v) && !unlisted.contains(&v.as_str())).collect();
assert!(missing.is_empty(), "not in raea help: {missing:?}");
- for usage in [raea_app_check::USAGE, raea_app_ask::USAGE, raea_app_direction::check::USAGE, raea_app_direction::USAGE, raea_app_notes::USAGE, raea_app_game::USAGE, raea_runtime_export::SCENE_USAGE, motion::physics::USAGE, raea_runtime_wear::USAGE, tools::splat::USAGE, tools::sound::SAO_USAGE, tools::sound::TOKENSYNTH_USAGE, tools::song::USAGE, motion::track::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, tools::blender::USAGE] {
+ for usage in [raea_app_check::USAGE, raea_app_ask::USAGE, raea_app_direction::check::USAGE, raea_app_direction::USAGE, raea_app_notes::USAGE, raea_app_game::USAGE, raea_app_scene::USAGE, motion::physics::USAGE, raea_runtime_wear::USAGE, tools::splat::USAGE, tools::sound::SAO_USAGE, tools::sound::TOKENSYNTH_USAGE, tools::song::USAGE, motion::track::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, tools::blender::USAGE] {
assert!(help.contains(usage), "{usage}");
}
}
diff --git a/io/kept/Cargo.toml b/io/kept/Cargo.toml
deleted file mode 100644
index 0ef901f5..00000000
--- a/io/kept/Cargo.toml
+++ /dev/null
@@ -1,15 +0,0 @@
-[package]
-name = "raea-io-kept"
-version = "0.1.0"
-edition = "2024"
-license = "FSL-1.1-ALv2"
-publish = false
-description = "A long render's 3D parts kept on disk as its frames come, each props map written once by its content, read back for the checks at its end"
-
-[dependencies]
-bevy = { version = "=0.20.0", default-features = false, features = ["std"] }
-serde = { version = "1", features = ["derive"] }
-serde_json = "1"
-raea-core-scene = { path = "../../core/scene" }
-# the temp file the parts go to, gone when raea is
-raea-io-home = { path = "../home" }
diff --git a/io/kept/src/lib.rs b/io/kept/src/lib.rs
deleted file mode 100644
index 24a5b59f..00000000
--- a/io/kept/src/lib.rs
+++ /dev/null
@@ -1,245 +0,0 @@
-//! A long render's 3D parts kept on disk as its frames come, for the checks at its end (docs/stage-guards.feature
-//! SG4a). Each frame's scene was held in memory to the end: a 7-minute film grew by about 29 KB a frame (each changed
-//! part's props, its node and its parent's list), most of what still grew with the frame count. Each frame's parts go to
-//! a temp file instead: each props map, string and material is written once by its content (a part unchanged since the
-//! frame before is known by its pointer and not written again), and the parts read back at the end share equal
-//! contents. The file is gone when raea is (unlinked once open on unix, delete-on-close on Windows), as the encoders'
-//! samples are (raea-io-codec samples.rs).
-//!
-//! A part's place is its matrix: the props' own place (PLACE) is kept only for a camera, the one part the checks read it
-//! from (systems/stage view.rs, systems/contact seen.rs). A part that moves each frame has the same props otherwise,
-//! so its frames share one map: the one-scene control's 48 moving boxes were 1.35 GB of maps read back, one a frame.
-
-use std::collections::HashMap;
-use std::hash::{Hash, Hasher};
-use std::io::{BufRead, Seek, Write};
-use std::sync::{Arc, Mutex};
-
-use bevy::math::Mat4;
-use raea_core_scene::{Item, Node3};
-use serde_json::{Map, Value, json};
-
-type R<T> = Result<T, String>;
-type Props = Arc<Map<String, Value>>;
-/// a shared value's pointers: what (0 props, 1 a string, 2 a material) and up to three of its Arcs
-type Key = (u8, usize, usize, usize);
-/// a part's own place in its props, left out but for a camera's
-const PLACE: [&str; 4] = ["position", "rotation", "scale", "quaternion"];
-
-/// What a part held the frame before: kept for the frame, so its pointer isn't another value's (held, never read).
-#[allow(dead_code)]
-enum Held {
- Props(Props),
- Str(Arc<str>),
- Node(Node3),
-}
-
-/// Every frame's parts, on disk.
-pub struct Kept {
- file: std::io::BufWriter<std::fs::File>,
- frames: usize,
- /// the frame before's shared values, by pointer, with their ids
- last: HashMap<Key, (String, Held)>,
-}
-
-impl Kept {
- pub fn new() -> R<Kept> {
- let f = raea_io_home::scratch_file("kept")?;
- Ok(Kept { file: std::io::BufWriter::with_capacity(1 << 20, f), frames: 0, last: HashMap::new() })
- }
-
- /// The next frame's parts.
- pub fn put(&mut self, items: &[Item]) -> R<()> {
- let mut now: HashMap<Key, (String, Held)> = HashMap::with_capacity(self.last.len());
- let mut defs = String::new();
- let mut row = Vec::with_capacity(items.len());
- for it in items {
- let props = &it.props;
- let p = self.id((0, Arc::as_ptr(props) as *const () as usize, 0, 0), &mut now, &mut defs, || {
- let text = if it.kind != "camera" && PLACE.iter().any(|k| props.contains_key(*k)) {
- serde_json::to_string(&Placeless(props))
- } else {
- serde_json::to_string(&**props)
- };
- (Held::Props(props.clone()), text.unwrap_or_default())
- });
- let s = it.shape.as_ref().map(|s| self.string(s, &mut now, &mut defs));
- let a = it.at.as_ref().map(|s| self.string(s, &mut now, &mut defs));
- let m = it.material.as_ref().map(|n| {
- let key = (2, Arc::as_ptr(&n.props) as *const () as usize, Arc::as_ptr(&n.kids) as *const () as usize, Arc::as_ptr(&n.kind) as *const () as usize);
- self.id(key, &mut now, &mut defs, || (Held::Node(n.clone()), node_json(n).to_string()))
- });
- let world: Vec<u32> = it.world.to_cols_array().iter().map(|v| v.to_bits()).collect();
- row.push(json!([it.kind, p, s, a, m, world]));
- }
- self.last = now;
- defs.push_str(&json!({ "f": row }).to_string());
- defs.push('\n');
- self.file.write_all(defs.as_bytes()).map_err(|e| format!("keeping a frame's parts on disk: {e}"))?;
- self.frames += 1;
- Ok(())
- }
-
- /// Frames given so far.
- pub fn len(&self) -> usize {
- self.frames
- }
-
- pub fn is_empty(&self) -> bool {
- self.frames == 0
- }
-
- /// Every frame's parts, as they were given, equal props, strings and materials shared. A frame's line is read
- /// into the parts alone and a definition only when its id is new: each line parsed whole into JSON values left
- /// 2.7 GB of the film's memory freed but not yet given back at the checks' start.
- pub fn read(self) -> R<Vec<Vec<Item>>> {
- let bad = |e: String| format!("reading the kept parts back: {e}");
- let mut f = self.file.into_inner().map_err(|e| bad(e.to_string()))?;
- f.seek(std::io::SeekFrom::Start(0)).map_err(|e| bad(e.to_string()))?;
- let (mut props, mut strs, mut nodes) = (HashMap::<String, Props>::new(), HashMap::<String, Arc<str>>::new(), HashMap::<String, Node3>::new());
- let mut out = Vec::with_capacity(self.frames);
- for line in std::io::BufReader::new(f).lines() {
- let line = line.map_err(|e| bad(e.to_string()))?;
- if line.starts_with("{\"f\":") {
- let fr: Frame = serde_json::from_str(&line).map_err(|e| bad(e.to_string()))?;
- out.push(fr.f.iter().map(|r| item(r, &props, &strs, &nodes)).collect::<R<Vec<_>>>().map_err(bad)?);
- continue;
- }
- // {"p":"<id>","v":<value>}, as `id` writes it
- let (Some(tag), Some(id), Some(v)) = (line.get(2..3), line.get(6..38), line.get(44..line.len().saturating_sub(1))) else { return Err(bad("a line that isn't a part or a definition".into())) };
- let json = |e: serde_json::Error| bad(e.to_string());
- match tag {
- "p" if !props.contains_key(id) => drop(props.insert(id.into(), Arc::new(serde_json::from_str(v).map_err(json)?))),
- "s" if !strs.contains_key(id) => drop(strs.insert(id.into(), Arc::from(serde_json::from_str::<String>(v).map_err(json)?))),
- "m" if !nodes.contains_key(id) => drop(nodes.insert(id.into(), node_of(&serde_json::from_str(v).map_err(json)?).map_err(bad)?)),
- _ => {}
- }
- }
- if out.len() != self.frames {
- return Err(bad(format!("{} frames back of {}", out.len(), self.frames)));
- }
- Ok(out)
- }
-
- fn string(&mut self, s: &Arc<str>, now: &mut HashMap<Key, (String, Held)>, defs: &mut String) -> String {
- let key = (1, Arc::as_ptr(s) as *const () as usize, s.len(), 0);
- self.id(key, now, defs, || (Held::Str(s.clone()), serde_json::to_string(&**s).unwrap_or_default()))
- }
-
- /// A shared value's id: the one it had this frame or the frame before (same pointer), else its content's, its
- /// definition written ahead of the frame.
- fn id(&mut self, key: Key, now: &mut HashMap<Key, (String, Held)>, defs: &mut String, made: impl FnOnce() -> (Held, String)) -> String {
- if let Some((id, _)) = now.get(&key) {
- return id.clone();
- }
- let (id, held) = self.last.remove(&key).unwrap_or_else(|| {
- let (held, text) = made();
- let id = id_of(&text);
- let tag = ["p", "s", "m"][key.0 as usize];
- defs.push_str(&format!("{{\"{tag}\":\"{id}\",\"v\":{text}}}\n"));
- (id, held)
- });
- now.insert(key, (id.clone(), held));
- id
- }
-}
-
-/// A part's props without its own place (PLACE), written as they are otherwise.
-struct Placeless<'a>(&'a Map<String, Value>);
-
-impl serde::Serialize for Placeless<'_> {
- fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
- s.collect_map(self.0.iter().filter(|(k, _)| !PLACE.contains(&k.as_str())))
- }
-}
-
-/// 128 bits of a value's text: two SipHashes with fixed keys, told apart by a first byte.
-fn id_of(text: &str) -> String {
- let half = |k: u8| {
- let mut h = std::collections::hash_map::DefaultHasher::new();
- k.hash(&mut h);
- text.hash(&mut h);
- h.finish()
- };
- format!("{:016x}{:016x}", half(0), half(1))
-}
-
-fn node_json(n: &Node3) -> Value {
- json!({ "k": &*n.kind, "p": &*n.props, "s": n.shape.as_deref(), "a": n.at.as_deref(), "c": n.kids.iter().map(node_json).collect::<Vec<_>>() })
-}
-
-fn node_of(v: &Value) -> R<Node3> {
- let Some(Value::Object(p)) = v.get("p") else { return Err("a material without props".into()) };
- let kids = v.get("c").and_then(Value::as_array).map_or(Ok(Vec::new()), |c| c.iter().map(node_of).collect::<R<Vec<_>>>())?;
- let s = |k: &str| v.get(k).and_then(Value::as_str).map(Arc::from);
- Ok(Node3 { kind: s("k").unwrap_or_else(|| Arc::from("")), props: Arc::new(p.clone()), shape: s("s"), at: s("a"), kids: kids.into() })
-}
-
-/// A frame's line: its parts, each its kind, the ids of its props, shape, placements and material, and its place's
-/// 16 numbers as bits.
-#[derive(serde::Deserialize)]
-struct Frame<'a> {
- #[serde(borrow)]
- f: Vec<Row<'a>>,
-}
-
-#[derive(serde::Deserialize)]
-struct Row<'a>(&'a str, &'a str, Option<&'a str>, Option<&'a str>, Option<&'a str>, [u32; 16]);
-
-fn item(r: &Row, props: &HashMap<String, Props>, strs: &HashMap<String, Arc<str>>, nodes: &HashMap<String, Node3>) -> R<Item> {
- let p = props.get(r.1).ok_or("a part whose props weren't written")?.clone();
- let (shape, at, material) = (named(strs, r.2, "shape")?, named(strs, r.3, "placements")?, named(nodes, r.4, "material")?);
- Ok(Item { kind: kind_of(r.0), props: p, shape, at, material, world: Mat4::from_cols_array(&r.5.map(f32::from_bits)) })
-}
-
-/// What an id names, None for no id; an id that wasn't written is an error saying which of the part's it was.
-fn named<T: Clone>(m: &HashMap<String, T>, id: Option<&str>, what: &str) -> R<Option<T>> {
- id.map(|id| m.get(id).cloned().ok_or(format!("a part whose {what} wasn't written"))).transpose()
-}
-
-/// A part's kind as the static name items_of gives it: the kinds are few, each kept once.
-fn kind_of(k: &str) -> &'static str {
- static KINDS: Mutex<Vec<&'static str>> = Mutex::new(Vec::new());
- let mut ks = KINDS.lock().unwrap();
- if let Some(s) = ks.iter().find(|s| **s == k) {
- return s;
- }
- let s: &'static str = Box::leak(k.to_string().into_boxed_str());
- ks.push(s);
- s
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- fn part(kind: &'static str, props: &Props, shape: Option<&Arc<str>>, x: f32) -> Item {
- let material = Some(Node3 { kind: Arc::from("meshStandardMaterial"), props: Arc::new(json!({"color": "#ff7a00"}).as_object().unwrap().clone()), shape: None, at: None, kids: Vec::new().into() });
- Item { kind, props: props.clone(), shape: shape.cloned(), at: None, material, world: Mat4::from_translation(bevy::math::Vec3::new(x, 0.1, -2.0)) }
- }
-
- #[test]
- fn parts_come_back_as_they_went_with_equal_props_shared() {
- let still: Props = Arc::new(json!({"name": "floor", "position": [0, 0, 0]}).as_object().unwrap().clone());
- let shape: Arc<str> = Arc::from("box(4, 0.1, 4)");
- let mut k = Kept::new().unwrap();
- // the floor unchanged across three frames; a card and a camera whose props are made again each frame as they move
- for x in [0.5f32, 0.75, 0.5] {
- let card: Props = Arc::new(json!({"name": "card", "position": [x, 1, 0], "rotation": [0, x, 0]}).as_object().unwrap().clone());
- let cam: Props = Arc::new(json!({"position": [x, 1, 5], "fov": 40}).as_object().unwrap().clone());
- k.put(&[part("mesh", &still, Some(&shape), 0.0), part("panel", &card, None, x), part("camera", &cam, None, 0.0)]).unwrap();
- }
- assert_eq!(k.len(), 3);
- let back = k.read().unwrap();
- assert_eq!(back.len(), 3);
- assert_eq!((back[1][0].kind, back[1][1].kind), ("mesh", "panel"));
- assert!(Arc::ptr_eq(&back[0][0].props, &back[2][0].props), "one floor's props, not three");
- assert_eq!(*back[2][0].props, *json!({"name": "floor"}).as_object().unwrap(), "a part's place is its matrix");
- assert!(Arc::ptr_eq(&back[0][1].props, &back[1][1].props) && Arc::ptr_eq(&back[1][1].props, &back[2][1].props), "a moving card's frames share one map");
- assert_eq!(back[1][2].props["position"][0], json!(0.75), "a camera keeps its own place: the checks read it");
- assert!(Arc::ptr_eq(&back[0][2].props, &back[2][2].props) && !Arc::ptr_eq(&back[0][2].props, &back[1][2].props));
- assert_eq!(back[0][0].shape.as_deref(), Some("box(4, 0.1, 4)"));
- assert_eq!(back[1][1].world.to_cols_array().map(f32::to_bits), Mat4::from_translation(bevy::math::Vec3::new(0.75, 0.1, -2.0)).to_cols_array().map(f32::to_bits));
- assert_eq!(back[2][1].material.as_ref().map(|m| m.props["color"].clone()), Some(json!("#ff7a00")));
- }
-}
diff --git a/runtime/endchecks/Cargo.toml b/runtime/endchecks/Cargo.toml
new file mode 100644
index 00000000..1a604545
--- /dev/null
+++ b/runtime/endchecks/Cargo.toml
@@ -0,0 +1,14 @@
+[package]
+name = "raea-runtime-endchecks"
+version = "0.1.0"
+edition = "2024"
+license = "FSL-1.1-ALv2"
+publish = false
+description = "A render's end checks as its frames come: raea-sys-contact's clipping, raea-sys-stage's staging and the manifest's word on the parts, each frame's parts read and let go"
+
+[dependencies]
+raea-core-scene = { path = "../../core/scene" }
+raea-core-facts = { path = "../../core/facts" }
+raea-sys-contact = { path = "../../systems/contact" }
+raea-sys-stage = { path = "../../systems/stage" }
+serde_json = "1"
diff --git a/runtime/endchecks/src/lib.rs b/runtime/endchecks/src/lib.rs
new file mode 100644
index 00000000..836ad13b
--- /dev/null
+++ b/runtime/endchecks/src/lib.rs
@@ -0,0 +1,55 @@
+//! A render's end checks as its frames come (docs/stage-guards.feature SG4a): each frame's parts read into what the
+//! clipping check (raea-sys-contact; RAEA_CLIP_CHECK=0 skips it), the staging (raea-sys-stage; RAEA_STAGE_CHECK=0) and
+//! the manifest's word on the parts (raea_sys_stage::Mounts) keep of them, and let go, so a long render never holds its
+//! frames' parts for its checks. raea-runtime-export hands each frame in as it's drawn, and a still's at its end.
+
+use raea_core_facts::Finding;
+use raea_core_scene::Item;
+use serde_json::Value;
+
+pub struct EndChecks {
+ clip: Option<raea_sys_contact::Clipping>,
+ stage: Option<raea_sys_stage::Staging>,
+ mounts: raea_sys_stage::Mounts,
+ any: bool,
+ parts: usize,
+}
+
+impl EndChecks {
+ pub fn new(w: u32, h: u32, fps: f64) -> EndChecks {
+ let on = |k: &str| std::env::var(k).as_deref() != Ok("0");
+ let (clip, stage) = (on("RAEA_CLIP_CHECK").then(|| raea_sys_contact::Clipping::new(w, h, fps)), on("RAEA_STAGE_CHECK").then(|| raea_sys_stage::Staging::new(w, h, fps)));
+ EndChecks { clip, stage, mounts: raea_sys_stage::Mounts::new(w, h), any: false, parts: 0 }
+ }
+
+ /// The next frame (its number, `frame`): its parts, and its page where the manifest has it.
+ pub fn push(&mut self, frame: i64, its: &[Item], page: Option<&raea_sys_stage::Page>) {
+ (self.any, self.parts) = (self.any || !its.is_empty(), self.parts + its.len());
+ if let Some(c) = &mut self.clip {
+ c.push(frame, its);
+ }
+ if let Some(s) = &mut self.stage {
+ s.push(frame, its, page);
+ }
+ self.mounts.push(frame, its);
+ }
+
+ /// The findings, each said on stderr, and what the manifest says of the parts (none when no frame had any); `mark`
+ /// after each step (raea-render's mem_mark: the footprint, with RAEA_MEM_MARKS).
+ pub fn told(self, mark: impl Fn(&str)) -> (Vec<Finding>, Option<Value>) {
+ if !self.any {
+ return (Vec::new(), None);
+ }
+ mark(&format!("end checks: each frame's parts checked as they came, {} in all", self.parts));
+ let seen = self.mounts.value();
+ mark("end checks: what's on screen");
+ let mut found = self.clip.map_or_else(Vec::new, raea_sys_contact::Clipping::told);
+ mark("end checks: clipping");
+ found.extend(self.stage.map_or_else(Vec::new, raea_sys_stage::Staging::told));
+ mark("end checks: staging");
+ // the clipping check's solids, kept for the process, aren't needed again by a render
+ raea_sys_contact::forget();
+ mark("end checks: done, their solids let go");
+ (found, Some(seen))
+ }
+}
diff --git a/runtime/export/Cargo.toml b/runtime/export/Cargo.toml
index 3c3321d2..b4972ca7 100644
--- a/runtime/export/Cargo.toml
+++ b/runtime/export/Cargo.toml
@@ -32,11 +32,12 @@ raea-io-media = { path = "../../io/media", default-features = false, features =
raea-io-alpha = { path = "../../io/alpha" }
raea-core-program = { path = "../../core/program" }
raea-core-scene = { path = "../../core/scene" }
-raea-io-kept = { path = "../../io/kept" }
raea-runtime-scene = { path = "../scene" }
raea-sys-contact = { path = "../../systems/contact" }
# the staging checks a render runs at its end (docs/stage-guards.feature SG10-SG14)
raea-sys-stage = { path = "../../systems/stage" }
+# the end checks as the frames come (SG4a)
+raea-runtime-endchecks = { path = "../endchecks" }
# a render's findings, in one shape (docs/direction.feature DR3)
raea-core-facts = { path = "../../core/facts" }
raea-sys-light-meter = { path = "../../systems/light-meter" }
diff --git a/runtime/export/src/fed.rs b/runtime/export/src/fed.rs
index d35363ab..ee6f179f 100644
--- a/runtime/export/src/fed.rs
+++ b/runtime/export/src/fed.rs
@@ -220,8 +220,8 @@ pub(crate) fn render_fed(app: &mut App, js: &Path, w: u32, h: u32, fps: f64, tot
let dir = cx.dir.to_path_buf();
// the sound bounced as the frames come, on its own thread (it was mixed after the last frame: 3 s on the export)
let streamer = std::cell::RefCell::new(Some(raea_sys_mix::offline::Streamer::start(fps, total.max(0) as usize)));
- // a video's 3D made live keeps each frame's parts for its end checks on disk, not its scene in memory (SG4a)
- let kept = std::cell::RefCell::new(LIVE_CLIPS.load(std::sync::atomic::Ordering::Relaxed).then(raea_io_kept::Kept::new).transpose()?);
+ // a video's 3D made live is checked as its frames come, each frame's parts let go once read (SG4a)
+ let ends = std::cell::RefCell::new(LIVE_CLIPS.load(std::sync::atomic::Ordering::Relaxed).then(|| raea_runtime_endchecks::EndChecks::new(w, h, fps)));
let t0 = std::time::Instant::now();
let pic = raea_core_program::ir::Program { fps, width: w, height: h, frames: total, ..Default::default() };
let frame_log = std::env::var_os("RAEA_FRAME_LOG").map(PathBuf::from);
@@ -279,8 +279,11 @@ pub(crate) fn render_fed(app: &mut App, js: &Path, w: u32, h: u32, fps: f64, tot
fr = raea_gpu_device::check::fed_checked(f, fr, raea_sys_page::wait_drawn, raea_sys_page::redraw_full, || { cx.manifest.as_mut().map(|m| m.pop()); bevy_fed(app.world_mut(), bevy, cx, &page, fps) })?;
// a shot starts here (an outermost Sequence, a camera cut): the video's next segment does too (RR3)
cuts.find(f, raea_runtime_page::shot_starts(app.world_mut()), matches!(&cx.scene3d, Some(e) if raea_sys_frame::shots::Cut::at(e.world(), f)));
- // a video's 3D made live keeps each frame's parts (`kept`) for the checks at its end
- if let Some(k) = kept.borrow_mut().as_mut() { k.put(&raea_runtime_scene::items_of(&scene_of(app.world_mut())))?; }
+ // a video's 3D made live: this frame's parts to the end checks (`ends`), with its page (the manifest's newest)
+ if let Some(e) = ends.borrow_mut().as_mut() {
+ let page = cx.manifest.as_deref().map(|m| raea_sys_stage::pages(&m[m.len().saturating_sub(4)..], &[f], w, h).remove(0));
+ e.push(f, &raea_runtime_scene::items_of(&scene_of(app.world_mut())), page.as_ref());
+ }
if cx.scene3d.is_none() && cx.live3d.is_none() && !cx.scene.is_empty() && BEVY_3D_PROBE.load(std::sync::atomic::Ordering::Relaxed) {
return Err(FED_3D.into());
}
@@ -338,9 +341,9 @@ pub(crate) fn render_fed(app: &mut App, js: &Path, w: u32, h: u32, fps: f64, tot
let n = frames.borrow().len();
// 3D parts passing through each other on screen: on stderr, and in the manifest for the legacy app's checks
let found = FED_CLIPPING.lock().unwrap().take().and_then(|t| t.join().ok());
- let clipping = match (found, kept.into_inner()) {
+ let clipping = match (found, ends.into_inner()) {
(Some(found), _) => found,
- (None, Some(k)) => scene::checked(frames.borrow().iter().map(|(f, _)| *f).zip(k.read()?).collect(), cx.manifest.as_deref(), w, h, fps),
+ (None, Some(e)) => scene::ended(e),
(None, None) => scene::told_taking(&mut frames.borrow_mut(), cx.manifest.as_deref(), w, h, fps),
};
write_manifest(cx, (w, h, fps, total), clipping, |cx| heard(&frames.borrow(), &notes.borrow(), cx, fps))?;
diff --git a/runtime/export/src/scene.rs b/runtime/export/src/scene.rs
index 897485c0..f53b25df 100644
--- a/runtime/export/src/scene.rs
+++ b/runtime/export/src/scene.rs
@@ -14,37 +14,35 @@ pub fn all_items(frames: &[(i64, Frame)]) -> Vec<Vec<raea_core_scene::Item>> {
frames.iter().map(|(_, f)| items(f)).collect()
}
-/// raea_sys_contact::told on a render's frames, the parts that clip where the camera sees them (RAEA_CLIP_CHECK=0 skips
-/// it), and raea_sys_stage::told, the staging (RAEA_STAGE_CHECK=0), each said on stderr. `page` is the manifest's
-/// frames (each one's words in the page, which the staging holds off the parts: SG11), None where they aren't known.
+/// The end checks (raea-runtime-endchecks) on a render's frames, each said on stderr: the parts that clip where the
+/// camera sees them and the staging. `page` is the manifest's frames (each one's words in the page, which the staging
+/// holds off the parts: SG11), None where they aren't known.
pub(crate) fn told(frames: &[(i64, Frame)], page: Option<&[serde_json::Value]>, w: u32, h: u32, fps: f64) -> Vec<raea_core_facts::Finding> {
- checked(frames.iter().map(|(n, f)| (*n, raea_runtime_scene::items_of(&f.scene))).collect(), page, w, h, fps)
+ let nums = frames.iter().map(|f| f.0).collect();
+ checked(nums, frames.iter().map(|f| raea_runtime_scene::items_of(&f.1.scene)), page, w, h, fps)
}
-/// told for frames nothing reads the 3D of after: each frame's scene let go as its parts are made, so the end checks
-/// don't hold every frame's scene and every frame's parts at once (SG4a)
+/// told for frames nothing reads the 3D of after: each frame's scene let go as its parts are checked (SG4a)
pub(crate) fn told_taking(frames: &mut [(i64, Frame)], page: Option<&[serde_json::Value]>, w: u32, h: u32, fps: f64) -> Vec<raea_core_facts::Finding> {
- checked(frames.iter_mut().map(|(n, f)| (*n, raea_runtime_scene::items_of(&std::mem::take(&mut f.scene)))).collect(), page, w, h, fps)
+ let nums = frames.iter().map(|f| f.0).collect();
+ checked(nums, frames.iter_mut().map(|(_, f)| raea_runtime_scene::items_of(&std::mem::take(&mut f.scene))), page, w, h, fps)
}
-pub(crate) fn checked(frames: Vec<(i64, Vec<raea_core_scene::Item>)>, page: Option<&[serde_json::Value]>, w: u32, h: u32, fps: f64) -> Vec<raea_core_facts::Finding> {
- if frames.iter().all(|(_, its)| its.is_empty()) {
- return Vec::new();
+fn checked(nums: Vec<i64>, items: impl Iterator<Item = Vec<raea_core_scene::Item>>, page: Option<&[serde_json::Value]>, w: u32, h: u32, fps: f64) -> Vec<raea_core_facts::Finding> {
+ let pages = page.map(|p| raea_sys_stage::pages(p, &nums, w, h));
+ let mut e = raea_runtime_endchecks::EndChecks::new(w, h, fps);
+ for (k, its) in items.enumerate() {
+ e.push(nums[k], &its, pages.as_ref().and_then(|p| p.get(k)));
+ }
+ ended(e)
+}
+
+/// The end checks' findings, a memory mark after each step; what they say of the parts, in SEEN.
+pub(crate) fn ended(e: raea_runtime_endchecks::EndChecks) -> Vec<raea_core_facts::Finding> {
+ let (found, seen) = e.told(raea_render::engine::mem_mark);
+ if seen.is_some() {
+ *SEEN.lock().unwrap() = seen;
}
- // RAEA_MEM_MARKS: the footprint after each end step (raea-render's mem_mark)
- let mark = raea_render::engine::mem_mark;
- mark(&format!("end checks: each frame's parts made, {} in all", frames.iter().map(|(_, its)| its.len()).sum::<usize>()));
- let (nums, all): (Vec<i64>, Vec<_>) = frames.into_iter().unzip();
- *SEEN.lock().unwrap() = Some(raea_sys_stage::seen(&all, &nums, w, h));
- mark("end checks: what's on screen");
- 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) };
- mark("end checks: clipping");
- found.extend(raea_sys_stage::told(&all, &nums, &page.map_or_else(Vec::new, |p| raea_sys_stage::pages(p, &nums, w, h)), w, h, fps));
- mark("end checks: staging");
- // the clipping check's solids, kept for the process, aren't needed again by a render
- raea_sys_contact::forget();
- drop(all);
- mark("end checks: done, their parts and solids let go");
found
}
diff --git a/systems/contact/src/clip.rs b/systems/contact/src/clip.rs
new file mode 100644
index 00000000..ed3c16b6
--- /dev/null
+++ b/systems/contact/src/clip.rs
@@ -0,0 +1,175 @@
+//! The clipping check as a render's frames come (docs/stage-guards.feature SG4a): each frame's parts tested as it
+//! comes and let go, so a long render's check never holds its frames' parts. A part is followed from frame to frame by
+//! its id (raea_core_scene::ids_of, as spans_of names it); what an overlap's sentence needs (its two parts at its deepest
+//! frame, their solids) is kept as it's found.
+
+use std::collections::HashMap;
+
+use bevy::math::{Mat4, Vec3};
+use serde_json::{Value, json};
+
+use raea_core_scene::{Item, excused, ids_of, label};
+
+use super::{Hit, clear_move, deepest, scale_of, world_box};
+use crate::seen::shows;
+use crate::solid::{Held, occluders};
+
+type Pair = (usize, usize);
+/// An overlap on one frame: the frame, the hit, and its two parts there.
+type At = (usize, Hit, Item, Item);
+
+/// The clipping check a frame at a time: push each frame's parts in order, then `check` (or `told`) once.
+pub struct Clipping {
+ w: u32,
+ h: u32,
+ fps: f64,
+ nums: Vec<i64>,
+ /// each part's index, numbered as parts first show
+ ids: HashMap<String, usize>,
+ held: Held,
+ /// each pair's test on the frame before, reused while neither part moves (the camera may still have); only the
+ /// last frame's pairs are kept, so a long render's cache holds one frame's
+ last: HashMap<Pair, (Mat4, Mat4, Option<Hit>)>,
+ /// the parts in an overlap still to be said, whose solids are kept for its sentence
+ pinned: Vec<bool>,
+ /// each pair's shown stretches (frames in a row) as they come: first, last, and the deepest hit (seam let go)
+ found: HashMap<Pair, Vec<(usize, usize, At)>>,
+ /// overlaps no frame shows (off frame, behind something): first and last frame, and the first frame's hit
+ hidden: HashMap<Pair, (usize, usize, At)>,
+}
+
+impl Clipping {
+ pub fn new(w: u32, h: u32, fps: f64) -> Clipping {
+ Clipping { w, h, fps, nums: Vec::new(), ids: HashMap::new(), held: Held::default(), last: HashMap::new(), pinned: Vec::new(), found: HashMap::new(), hidden: HashMap::new() }
+ }
+
+ /// The next frame (its number, `frame`) and its parts: the parts' world boxes swept along x for the pairs that
+ /// meet, each pair tested.
+ pub fn push(&mut self, frame: i64, its: &[Item]) {
+ let k = self.nums.len();
+ self.nums.push(frame);
+ let mut here: Vec<(usize, &Item)> = Vec::new();
+ for (id, it) in ids_of(its, &["mesh", "model"]) {
+ let next = self.ids.len();
+ here.push((*self.ids.entry(id).or_insert(next), it));
+ }
+ here.sort_by_key(|h| h.0);
+ self.held.at(k, &here);
+ let solids = &self.held.solids;
+ let item = |i: usize| here[here.binary_search_by_key(&i, |h| h.0).unwrap()].1;
+ let mut boxes: Vec<(usize, Vec3, Vec3)> = Vec::new();
+ for &(i, it) in &here {
+ let Some(ss) = &solids[i] else { continue };
+ if excused(it) {
+ continue;
+ }
+ let (mut lo, mut hi) = (Vec3::splat(f32::MAX), Vec3::splat(f32::MIN));
+ for s in ss.iter() {
+ let (l, h) = world_box(s, &it.world);
+ lo = lo.min(l);
+ hi = hi.max(h);
+ }
+ boxes.push((i, lo, hi));
+ }
+ boxes.sort_by(|x, y| x.1.x.total_cmp(&y.1.x));
+ let mut occ = None;
+ let mut tested: HashMap<Pair, (Mat4, Mat4, Option<Hit>)> = HashMap::new();
+ for (n, &(i0, lo0, hi0)) in boxes.iter().enumerate() {
+ for &(j0, lo1, hi1) in &boxes[n + 1..] {
+ if lo1.x > hi0.x {
+ break;
+ }
+ if lo0.cmpgt(hi1).any() || lo1.cmpgt(hi0).any() {
+ continue;
+ }
+ let (i, j) = (i0.min(j0), i0.max(j0));
+ let (a, b) = (solids[i].as_ref().unwrap(), solids[j].as_ref().unwrap());
+ let (pa, pb) = (item(i), item(j));
+ let (wa, wb) = (pa.world, pb.world);
+ let r = match self.last.get(&(i, j)) {
+ Some((la, lb, r)) if *la == wa && *lb == wb => r.clone(),
+ _ => deepest(a, &wa, b, &wb),
+ };
+ tested.insert((i, j), (wa, wb, r.clone()));
+ let Some(mut hit) = r else { continue };
+ self.pinned.resize(self.pinned.len().max(j + 1), false);
+ (self.pinned[i], self.pinned[j]) = (true, true);
+ let (sa, sb) = (&a[hit.pieces.0], &b[hit.pieces.1]);
+ let skip = 3.0 * (sa.cell * scale_of(&wa)).max(sb.cell * scale_of(&wb));
+ if shows(its, &std::mem::take(&mut hit.seam), occ.get_or_insert_with(|| occluders(&here, solids)), skip, self.w as f32, self.h as f32) {
+ let runs = self.found.entry((i, j)).or_default();
+ match runs.last_mut() {
+ Some(run) if run.1 + 1 == k => {
+ run.1 = k;
+ // the deepest, the last of equals (as max_by took it)
+ if hit.depth >= run.2.1.depth {
+ run.2 = (k, hit, pa.clone(), pb.clone());
+ }
+ }
+ _ => runs.push((k, k, (k, hit, pa.clone(), pb.clone()))),
+ }
+ } else {
+ self.hidden.entry((i, j)).or_insert_with(|| (k, k, (k, hit, pa.clone(), pb.clone()))).1 = k;
+ }
+ }
+ }
+ self.last = tested;
+ let pinned = &self.pinned;
+ self.held.after(k, |i| pinned.get(i).copied().unwrap_or(false));
+ }
+
+ /// The overlaps the frames show: each with a sentence (for the agent) and its numbers (for the manifest).
+ pub fn check(self) -> Vec<Value> {
+ let Clipping { fps, nums, held, found, hidden, .. } = self;
+ // unseen on every frame: still said, so a clip turned away from reads as hidden, not fixed (DR3, DR9's cheats)
+ let mut unseen: Vec<_> = hidden.into_iter().filter(|(p, _)| !found.contains_key(p)).collect();
+ unseen.sort_by_key(|(p, (k, _, _))| (*k, *p));
+ let mut spans: Vec<_> = found.into_iter().collect();
+ spans.sort_by_key(|(p, g)| (g[0].0, *p));
+ let clock = |f: i64| {
+ let s = f as f64 / fps;
+ format!("{}:{:04.1}", (s / 60.0) as i64, s % 60.0)
+ };
+ let mut out = Vec::new();
+ // one overlap said, over frames f0 to f1 (`seen`: its seam on screen, else said as standing in the scene unseen)
+ let mut say = |i: usize, j: usize, (_, hit, pa, pb): &At, f0: i64, f1: i64, seen: bool| {
+ let (sa, sb) = (held.solids[i].as_ref().unwrap(), held.solids[j].as_ref().unwrap());
+ let (la, lb) = (label(pa, &sa[hit.pieces.0].name), label(pb, &sb[hit.pieces.1].name));
+ let (small, big) = if hit.small_first { (la, lb) } else { (lb, la) };
+ // out the shortest way: the smallest move along a world axis (not down) that leaves no piece in the other's
+ let (axis, step) = clear_move(&sa[..], &pa.world, &sb[..], &pb.world, hit.small_first);
+ let axis_name = ["x", "y", "z"][axis];
+ let when = if f0 == f1 { clock(f0) } else { format!("{}–{}", clock(f0), clock(f1)) };
+ let shows = if seen { "and the seam shows" } else { "where no frame shows it (off frame or behind something), so it stands in the scene unseen" };
+ let says = format!(
+ "{when} {small} passes {:.2} m into {big} ({:.0}% of it inside), {shows}: move {small} {step:+.2} along world {axis_name} (or move {big}), or give it allowOverlap if it's meant to",
+ hit.depth, hit.share * 100.0
+ );
+ out.push(json!({"from": f0, "to": f1, "part": small, "into": big, "depth": (hit.depth * 1000.0).round() / 1000.0, "share": (hit.share * 1000.0).round() / 1000.0, "move": {"axis": axis_name, "by": (step * 1000.0).round() / 1000.0}, "seen": seen, "says": says}));
+ };
+ for ((i, j), runs) in spans {
+ for (first, last, at) in runs {
+ say(i, j, &at, nums[first], nums[last], true);
+ }
+ }
+ for ((i, j), (k0, k1, at)) in unseen {
+ say(i, j, &at, nums[k0], nums[k1], false);
+ }
+ out
+ }
+
+ /// `check`'s overlaps as Findings (DR3), each said on stderr (what an agent driving raea reads) as it's returned
+ /// for the manifest.
+ pub fn told(self) -> Vec<raea_core_facts::Finding> {
+ let t = std::time::Instant::now();
+ let found = crate::clip_findings(&self.check(), "raea render");
+ for f in &found {
+ eprintln!("raea: {}", f.line());
+ }
+ raea_core_facts::finding::said(&found);
+ if raea_io_trace::stat("RAEA_TIMES") {
+ eprintln!("raea times: the clipping check {:.0} ms", t.elapsed().as_secs_f64() * 1e3);
+ }
+ found
+ }
+}
diff --git a/systems/contact/src/lib.rs b/systems/contact/src/lib.rs
index 690cb3c7..cac2a365 100644
--- a/systems/contact/src/lib.rs
+++ b/systems/contact/src/lib.rs
@@ -17,9 +17,9 @@ use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, Mutex, OnceLock};
use bevy::math::{Mat4, Vec3};
-use serde_json::{json, Value};
+use serde_json::Value;
-use raea_core_scene::{Item, Span, excused, gltf_tris, label, spans_of, src_path, vec3};
+use raea_core_scene::{Item, excused, gltf_tris, src_path, vec3};
// what each part rests on, and the parts that float, sink or clip (`raea scene lint|explain`)
pub mod lint;
@@ -31,12 +31,17 @@ pub use assets::assets;
mod found;
pub use found::{clip_findings, lint_findings};
+// the check a frame at a time, as a render's frames come (SG4a)
+mod clip;
+pub use clip::Clipping;
+
mod model;
pub use model::{bounds, facing, forget, seat_facing};
mod solid;
use solid::*;
mod seen;
+#[cfg(test)]
use seen::*;
/// Cells along a part's longest side.
@@ -259,126 +264,20 @@ fn volume(a: &Solid, wa: &Mat4, b: &Solid, wb: &Mat4) -> Option<Hit> {
Some(Hit { depth, share, small_first, pieces: (0, 0), seam })
}
-/// The overlaps a render shows: each with a sentence (for the agent) and its numbers (for the manifest). `all` is each
-/// frame's parts, `frames` the frames' numbers.
-pub fn check(all: &[Vec<Item>], frames: &[i64], w: u32, h: u32, fps: f64) -> Vec<Value> {
- // each part over the frames it's in (spans, not a slot per frame: SG4a); placed(i, k): part i's place on frame k
- let parts: Vec<(String, Span)> = spans_of(all, &["mesh", "model"]);
- // each part's solid held over its frames only (Held, SG4a)
- let mut held = Held::new(&parts, frames.len());
- let placed = |i: usize, k: usize| parts[i].1.at(k).map_or(Mat4::IDENTITY, |it| it.world);
- // frame by frame: the parts' world boxes swept along x for the pairs that meet, each pair's test reused while
- // neither part moves (the camera may still have)
- let mut last: HashMap<(usize, usize), (Mat4, Mat4, Option<Hit>)> = HashMap::new();
- // each pair's shown stretches (frames in a row) as they come: first, last, and the deepest hit (seam let go)
- let mut found: HashMap<(usize, usize), Vec<(usize, usize, (usize, Hit))>> = HashMap::new();
- // overlaps no frame shows (off frame, behind something): first and last frame, and the first frame's hit
- let mut hidden: HashMap<(usize, usize), (usize, usize, Hit)> = HashMap::new();
- for k in 0..frames.len() {
- held.at(&parts, k);
- let solids = &held.solids;
- let mut boxes: Vec<(usize, Vec3, Vec3)> = Vec::new();
- for (i, (_, tr)) in parts.iter().enumerate() {
- let (Some(it), Some(ss)) = (tr.at(k), &solids[i]) else { continue };
- if excused(it) {
- continue;
- }
- let w = it.world;
- let (mut lo, mut hi) = (Vec3::splat(f32::MAX), Vec3::splat(f32::MIN));
- for s in ss.iter() {
- let (l, h) = world_box(s, &w);
- lo = lo.min(l);
- hi = hi.max(h);
- }
- boxes.push((i, lo, hi));
- }
- boxes.sort_by(|x, y| x.1.x.total_cmp(&y.1.x));
- let mut occ: Option<Vec<(&Solid, Mat4)>> = None;
- for (n, &(i0, lo0, hi0)) in boxes.iter().enumerate() {
- for &(j0, lo1, hi1) in &boxes[n + 1..] {
- if lo1.x > hi0.x {
- break;
- }
- if lo0.cmpgt(hi1).any() || lo1.cmpgt(hi0).any() {
- continue;
- }
- let (i, j) = (i0.min(j0), i0.max(j0));
- let (a, b) = (solids[i].as_ref().unwrap(), solids[j].as_ref().unwrap());
- let (wa, wb) = (placed(i, k), placed(j, k));
- let r = match last.get(&(i, j)) {
- Some((la, lb, r)) if *la == wa && *lb == wb => r.clone(),
- _ => {
- let mut best: Option<Hit> = None;
- for (pa, sa) in a.iter().enumerate() {
- for (pb, sb) in b.iter().enumerate() {
- if let Some(mut hit) = test(sa, &wa, sb, &wb) {
- if best.as_ref().is_none_or(|b| hit.depth > b.depth) {
- hit.pieces = (pa, pb);
- best = Some(hit);
- }
- }
- }
- }
- best
- }
- };
- last.insert((i, j), (wa, wb, r.clone()));
- if let Some(mut hit) = r {
- let (sa, sb) = (&a[hit.pieces.0], &b[hit.pieces.1]);
- let skip = 3.0 * (sa.cell * scale_of(&wa)).max(sb.cell * scale_of(&wb));
- if shows(&all[k], &std::mem::take(&mut hit.seam), occ.get_or_insert_with(|| occluders(&parts, solids, k)), skip, w as f32, h as f32) {
- let runs = found.entry((i, j)).or_default();
- match runs.last_mut() {
- Some(run) if run.1 + 1 == k => {
- run.1 = k;
- // the deepest, the last of equals (as max_by took it)
- if hit.depth >= run.2.1.depth { run.2 = (k, hit) }
- }
- _ => runs.push((k, k, (k, hit))),
- }
- } else {
- hidden.entry((i, j)).or_insert((k, k, hit)).1 = k;
- }
- }
+/// The deepest overlap of any piece of one part (`a`, its solids at `wa`) in any of the other's, and which two pieces.
+fn deepest(a: &[Solid], wa: &Mat4, b: &[Solid], wb: &Mat4) -> Option<Hit> {
+ let mut best: Option<Hit> = None;
+ for (na, sa) in a.iter().enumerate() {
+ for (nb, sb) in b.iter().enumerate() {
+ if let Some(mut hit) = test(sa, wa, sb, wb)
+ && best.as_ref().is_none_or(|b| hit.depth > b.depth)
+ {
+ hit.pieces = (na, nb);
+ best = Some(hit);
}
}
- held.after(k, |i| found.keys().chain(hidden.keys()).any(|&(a, b)| a == i || b == i));
- }
- // unseen on every frame: still said, so a clip turned away from reads as hidden, not fixed (DR3, DR9's cheats)
- let mut unseen: Vec<_> = hidden.into_iter().filter(|(p, _)| !found.contains_key(p)).collect();
- unseen.sort_by_key(|(p, (k, _, _))| (*k, *p));
- let mut spans: Vec<_> = found.into_iter().collect();
- spans.sort_by_key(|(p, g)| (g[0].0, *p));
- let clock = |f: i64| {
- let s = f as f64 / fps;
- format!("{}:{:04.1}", (s / 60.0) as i64, s % 60.0)
- };
- let mut out = Vec::new();
- // one overlap said, over frames f0 to f1 (`seen`: its seam on screen, else said as standing in the scene unseen)
- let mut say = |i: usize, j: usize, k: usize, hit: &Hit, f0: i64, f1: i64, seen: bool| {
- let (pa, pb, sa, sb) = (parts[i].1.at(k).unwrap(), parts[j].1.at(k).unwrap(), held.solids[i].as_ref().unwrap(), held.solids[j].as_ref().unwrap());
- let (la, lb) = (label(pa, &sa[hit.pieces.0].name), label(pb, &sb[hit.pieces.1].name));
- let (small, big) = if hit.small_first { (la, lb) } else { (lb, la) };
- // out the shortest way: the smallest move along a world axis (not down) that leaves no piece in the other's
- let (axis, step) = clear_move(&sa[..], &pa.world, &sb[..], &pb.world, hit.small_first);
- let axis_name = ["x", "y", "z"][axis];
- let when = if f0 == f1 { clock(f0) } else { format!("{}–{}", clock(f0), clock(f1)) };
- let shows = if seen { "and the seam shows" } else { "where no frame shows it (off frame or behind something), so it stands in the scene unseen" };
- let says = format!(
- "{when} {small} passes {:.2} m into {big} ({:.0}% of it inside), {shows}: move {small} {step:+.2} along world {axis_name} (or move {big}), or give it allowOverlap if it's meant to",
- hit.depth, hit.share * 100.0
- );
- out.push(json!({"from": f0, "to": f1, "part": small, "into": big, "depth": (hit.depth * 1000.0).round() / 1000.0, "share": (hit.share * 1000.0).round() / 1000.0, "move": {"axis": axis_name, "by": (step * 1000.0).round() / 1000.0}, "seen": seen, "says": says}));
- };
- for ((i, j), runs) in spans {
- for (first, last, (k, hit)) in runs {
- say(i, j, k, &hit, frames[first], frames[last], true);
- }
- }
- for ((i, j), (k0, k1, hit)) in unseen {
- say(i, j, k0, &hit, frames[k0], frames[k1], false);
}
- out
+ best
}
/// The shortest move of one part (the first if `move_a`) along a world axis (+x, -x, +y, +z, -z) that leaves no piece
@@ -405,21 +304,6 @@ fn clear_move(a: &[Solid], wa: &Mat4, b: &[Solid], wb: &Mat4, move_a: bool) -> (
if best.1 == f32::MAX { (1, reach) } else { best }
}
-/// `check`'s overlaps as Findings (DR3), each said on stderr (what an agent driving raea reads) as it's returned for
-/// the manifest.
-pub fn told(all: &[Vec<Item>], frames: &[i64], w: u32, h: u32, fps: f64) -> Vec<raea_core_facts::Finding> {
- let t = std::time::Instant::now();
- let found = clip_findings(&check(all, frames, w, h, fps), "raea render");
- for f in &found {
- eprintln!("raea: {}", f.line());
- }
- raea_core_facts::finding::said(&found);
- if raea_io_trace::stat("RAEA_TIMES") {
- eprintln!("raea times: the clipping check {:.0} ms", t.elapsed().as_secs_f64() * 1e3);
- }
- found
-}
-
#[cfg(test)]
mod tests {
use super::*;
diff --git a/systems/contact/src/lint.rs b/systems/contact/src/lint.rs
index 7db4b8ed..3b44cd16 100644
--- a/systems/contact/src/lint.rs
+++ b/systems/contact/src/lint.rs
@@ -16,7 +16,7 @@ use serde_json::{json, Value};
use raea_core_scene::{Item, Part, base_ident, label, parts_of, ray_tri};
-use super::{solid_of, test};
+use super::solid_of;
/// A gap under this (metres) is contact: a part sitting on its surface.
const TOUCH: f32 = 0.002;
@@ -398,18 +398,7 @@ pub fn lint(now: &[Item], next: &[Item]) -> (Vec<Value>, usize) {
continue;
}
let (Some(a), Some(b)) = (&solids[i], &solids[j]) else { continue };
- let mut best: Option<super::Hit> = None;
- for (pa, sa) in a.iter().enumerate() {
- for (pb, sb) in b.iter().enumerate() {
- if let Some(mut h) = test(sa, &items[i].world, sb, &items[j].world) {
- if best.as_ref().is_none_or(|b| h.depth > b.depth) {
- h.pieces = (pa, pb);
- best = Some(h);
- }
- }
- }
- }
- if let Some(h) = best {
+ if let Some(h) = super::deepest(a, &items[i].world, b, &items[j].world) {
let (la, lb) = (label(&items[i], &a[h.pieces.0].name), label(&items[j], &b[h.pieces.1].name));
let (small, big) = if h.small_first { (la, lb) } else { (lb, la) };
errors += 1;
diff --git a/systems/contact/src/solid.rs b/systems/contact/src/solid.rs
index 56aa2475..81524ee1 100644
--- a/systems/contact/src/solid.rs
+++ b/systems/contact/src/solid.rs
@@ -253,32 +253,42 @@ fn make(it: &Item, key: &str) -> Result<Arc<Vec<Solid>>, String> {
if solids.is_empty() { Err("it has no volume".to_string()) } else { Ok(Arc::new(solids)) }
}
-/// The parts' solids over a check's frames (`check`): a shape's made at its part's first frame, shared by the parts
-/// holding it, and let go after the last of them; a model's from the process's cache (its file, a few at most). A
-/// film's shapes change as its words and parts do: a 13,175-frame film's 1,323 shapes held at once were 2.9 GB of cells
-/// at its end, its render's peak (docs/stage-guards.feature SG4a).
+/// The parts' solids as a render's frames come (Clipping): a shape's made when its part first shows, shared by the parts
+/// holding it, and let go once its part has been gone GONE frames (made again from the part's first frame if it comes
+/// back: the same cells); a model's from the process's cache (its file, a few at most). A film's shapes change as its
+/// words and parts do: a 13,175-frame film's 1,323 shapes held at once were 2.9 GB of cells at its end, its render's
+/// peak (docs/stage-guards.feature SG4a).
+#[derive(Default)]
pub(crate) struct Held {
pub(crate) solids: Vec<Option<Arc<Vec<Solid>>>>,
- /// the parts that start on each frame, and those whose last frame it is
- starts: Vec<Vec<usize>>,
- ends: Vec<Vec<usize>>,
+ /// each part's first item (what its solid is made from), whether that failed, and the last frame it was in
+ first: Vec<Item>,
+ failed: Vec<bool>,
+ seen: Vec<usize>,
+ /// the parts holding a solid
+ holding: Vec<usize>,
shared: HashMap<String, Result<std::sync::Weak<Vec<Solid>>, String>>,
}
-impl Held {
- pub(crate) fn new(parts: &[(String, Span)], frames: usize) -> Held {
- let (mut starts, mut ends) = (vec![Vec::new(); frames], vec![Vec::new(); frames]);
- for (i, (_, s)) in parts.iter().enumerate() {
- starts[s.first].push(i);
- ends[s.first + s.items.len() - 1].push(i);
- }
- Held { solids: vec![None; parts.len()], starts, ends, shared: HashMap::new() }
- }
+/// A part gone this many frames lets its solid go.
+pub(crate) const GONE: usize = 120;
- /// Frame k's new parts' solids.
- pub(crate) fn at(&mut self, parts: &[(String, Span)], k: usize) {
- for &i in &self.starts[k] {
- let Some(it) = parts[i].1.items.iter().flatten().next() else { continue };
+impl Held {
+ /// Frame k's parts (each part's index, numbered as they first show, and its item there): their solids made where
+ /// they have none.
+ pub(crate) fn at(&mut self, k: usize, here: &[(usize, &Item)]) {
+ for &(i, it) in here {
+ if i == self.solids.len() {
+ self.solids.push(None);
+ self.first.push(it.clone());
+ self.failed.push(false);
+ self.seen.push(k);
+ }
+ self.seen[i] = k;
+ if self.solids[i].is_some() || self.failed[i] {
+ continue;
+ }
+ let it = &self.first[i];
let key = key_of(it);
let had = match self.shared.get(&key) {
Some(Ok(w)) => w.upgrade().map(Ok),
@@ -290,24 +300,32 @@ impl Held {
self.shared.insert(key, s.as_ref().map(Arc::downgrade).map_err(Clone::clone));
s
});
+ self.failed[i] = s.is_err();
self.solids[i] = s.ok();
+ if self.solids[i].is_some() {
+ self.holding.push(i);
+ }
}
}
- /// After frame k: the solids of the parts it was the last frame of let go, but those `keep` names (an overlap still
- /// to be said with their pieces' names).
+ /// After frame k: the solids of the parts gone GONE frames let go, but those `keep` names (an overlap still to be
+ /// said with their pieces' names).
pub(crate) fn after(&mut self, k: usize, keep: impl Fn(usize) -> bool) {
- for &i in &self.ends[k] {
- if !keep(i) {
- self.solids[i] = None;
+ let (solids, seen) = (&mut self.solids, &self.seen);
+ self.holding.retain(|&i| {
+ let gone = k >= seen[i] + GONE && !keep(i);
+ if gone {
+ solids[i] = None;
}
- }
+ !gone
+ });
}
}
-/// The pieces that hide others on frame k: every checked part there, see-through ones left out.
-pub(crate) fn occluders<'a>(parts: &'a [(String, Span)], solids: &'a [Option<Arc<Vec<Solid>>>], k: usize) -> Vec<(&'a Solid, Mat4)> {
- parts.iter().enumerate().filter_map(|(i, (_, tr))| Some((tr.at(k)?, solids[i].as_ref()?)))
+/// The pieces that hide others on a frame: every checked part in it (`here`: each part's index and item), see-through
+/// ones left out.
+pub(crate) fn occluders<'a>(here: &[(usize, &'a Item)], solids: &'a [Option<Arc<Vec<Solid>>>]) -> Vec<(&'a Solid, Mat4)> {
+ here.iter().filter_map(|&(i, it)| Some((it, solids[i].as_ref()?)))
.filter(|(it, _)| !excused(it) || it.props.get("allowOverlap").and_then(Value::as_bool) == Some(true))
.flat_map(|(it, ss)| ss.iter().map(move |s| (s, it.world)))
.collect()
@@ -322,22 +340,28 @@ mod tests {
}
#[test]
- fn a_shape_is_held_over_its_parts_frames_only() {
- let (a, b) = ("box(1, 1, 1)", "box(2, 1, 1)");
- // parts: a#0 on frames 0-1, a#1 on frame 0, b#0 on frames 1-2
- let all = vec![vec![mesh(a), mesh(a)], vec![mesh(a), mesh(b)], vec![mesh(b)]];
- let parts = spans_of(&all, &["mesh"]);
- let mut held = Held::new(&parts, all.len());
- held.at(&parts, 0);
+ fn a_shape_is_held_while_its_parts_show() {
+ let (a, b) = (mesh("box(1, 1, 1)"), mesh("box(2, 1, 1)"));
+ let mut held = Held::default();
+ held.at(0, &[(0, &a), (1, &a)]);
assert!(Arc::ptr_eq(held.solids[0].as_ref().unwrap(), held.solids[1].as_ref().unwrap()), "one shape's parts share its solid");
held.after(0, |_| false);
- assert!(held.solids[0].is_some() && held.solids[1].is_none(), "a#1's last frame was 0");
- held.at(&parts, 1);
- held.after(1, |_| false);
- assert!(held.solids[0].is_none() && held.solids[2].is_some());
- assert!(held.shared["mesh:box(1, 1, 1)"].as_ref().is_ok_and(|w| w.upgrade().is_none()), "let go once no part holds it");
- held.at(&parts, 2);
- held.after(2, |i| i == 2);
+ assert!(held.solids[1].is_some(), "held while its part may come back");
+ // part 1 gone GONE frames: let go; part 0, still showing, keeps the shape
+ for k in 1..=GONE {
+ held.at(k, &[(0, &a), (2, &b)]);
+ held.after(k, |_| false);
+ }
+ assert!(held.solids[1].is_none() && held.solids[0].is_some() && held.solids[2].is_some());
+ // back: the shape's solid again, the one part 0 holds
+ held.at(GONE + 1, &[(1, &a)]);
+ assert!(Arc::ptr_eq(held.solids[1].as_ref().unwrap(), held.solids[0].as_ref().unwrap()));
+ for k in GONE + 2..=3 * GONE {
+ held.at(k, &[]);
+ held.after(k, |i| i == 2);
+ }
assert!(held.solids[2].is_some(), "kept for an overlap still to be said");
+ assert!(held.solids[0].is_none() && held.solids[1].is_none());
+ assert!(held.shared["mesh:box(1, 1, 1)"].as_ref().is_ok_and(|w| w.upgrade().is_none()), "let go once no part holds it");
}
}
diff --git a/systems/stage/src/framing.rs b/systems/stage/src/framing.rs
index 62ae8f6f..38745ece 100644
--- a/systems/stage/src/framing.rs
+++ b/systems/stage/src/framing.rs
@@ -7,8 +7,8 @@ use std::collections::HashMap;
use bevy::math::Vec3;
use raea_core_facts::{Finding, Level};
-use super::{Stage, called, num, runs, scale_of};
-use crate::view::corners;
+use super::{Item, Stage, called, num, runs, scale_of};
+use crate::view::{View, corners};
/// Under this share of the frame showing any part is an empty frame
const EMPTY: f32 = 0.08;
@@ -117,16 +117,27 @@ fn mark(grid: &mut [bool], b: [f32; 4], w: f32, h: f32) {
}
}
-pub(crate) fn check(st: &Stage, page: &[crate::Page]) -> Vec<Finding> {
- let n = st.all.len();
- let mut boxes = HashMap::new();
- // each frame: the share covered, whether it can be judged (no part of unknown size in view, no footage or 2D
- // over the 3D), and its subject: (name, its box on screen, the share of its box outside the frame)
- let mut covered = vec![1.0f32; n];
- let mut judged = vec![false; n];
- let mut subject: Vec<Option<(String, f32, bool)>> = vec![None; n];
- for (k, its) in st.all.iter().enumerate() {
- let Some(v) = st.views[k] else { continue };
+/// Each frame as it comes: the share covered, whether it can be judged (no part of unknown size in view, no footage or
+/// 2D over the 3D), and its subject: (name, the share of its box outside the frame, whether it could fit).
+#[derive(Default)]
+pub(crate) struct Framing {
+ boxes: HashMap<String, Option<(Vec3, Vec3)>>,
+ covered: Vec<f32>,
+ judged: Vec<bool>,
+ subject: Vec<Option<(String, f32, bool)>>,
+}
+
+impl Framing {
+ /// A frame's parts through its camera `v`, and what its page draws over them, on a w x h frame.
+ pub(crate) fn push(&mut self, _k: usize, its: &[Item], v: Option<View>, page: Option<&crate::Page>, w: f32, h: f32) {
+ let (c, j, s) = v.map_or((1.0, false, None), |v| self.frame(its, v, page, w, h));
+ self.covered.push(c);
+ self.judged.push(j);
+ self.subject.push(s);
+ }
+
+ fn frame(&mut self, its: &[Item], v: View, page: Option<&crate::Page>, w: f32, h: f32) -> (f32, bool, Option<(String, f32, bool)>) {
+ let boxes = &mut self.boxes;
let mut grid = vec![false; GX * GY];
let mut sure = true;
let mut best: Option<(String, f32, f32, bool)> = None;
@@ -136,21 +147,21 @@ pub(crate) fn check(st: &Stage, page: &[crate::Page]) -> Vec<Finding> {
sure = false;
continue;
}
- let Some((lo, hi)) = own_box(it, &mut boxes) else {
+ let Some((lo, hi)) = own_box(it, boxes) else {
// a model or other part of unknown size: judged only when its origin is well out of view
if matches!(it.kind, "model" | "entity" | "fire") {
if let Some([x, y, _]) = v.project(super::origin(it)) {
- if x > -0.5 * st.w && x < 1.5 * st.w && y > -0.5 * st.h && y < 1.5 * st.h {
+ if x > -0.5 * w && x < 1.5 * w && y > -0.5 * h && y < 1.5 * h {
sure = false;
}
}
}
// its file's box fills what it shows, a floor's or terrain's left out as a slab mesh's is; across the
// camera's plane (a room model round it: Stay's pool) it may fill the view
- let model = (it.kind == "model").then(|| model_box(it, &mut boxes)).flatten();
+ let model = (it.kind == "model").then(|| model_box(it, boxes)).flatten();
if let Some((lo, hi)) = model.filter(|(lo, hi)| !backdrop(it, *lo, *hi) || standing(it, *lo, *hi)) {
match v.bounds(corners(&it.world, lo, hi)) {
- Some(b) if v.share(b) > 0.0 => mark(&mut grid, b, st.w, st.h),
+ Some(b) if v.share(b) > 0.0 => mark(&mut grid, b, w, h),
Some(_) => {}
None => sure &= corners(&it.world, lo, hi).into_iter().all(|p| v.project(p).is_none()),
}
@@ -169,9 +180,9 @@ pub(crate) fn check(st: &Stage, page: &[crate::Page]) -> Vec<Finding> {
continue;
};
let inside = v.share(b);
- let whole = ((b[2] - b[0]) * (b[3] - b[1]) / (st.w * st.h)).max(1e-9);
+ let whole = ((b[2] - b[0]) * (b[3] - b[1]) / (w * h)).max(1e-9);
if inside > 0.0 {
- mark(&mut grid, b, st.w, st.h);
+ mark(&mut grid, b, w, h);
}
// a wall fills the frame but isn't its subject
if wall {
@@ -179,36 +190,39 @@ pub(crate) fn check(st: &Stage, page: &[crate::Page]) -> Vec<Finding> {
}
// the subject: the named part showing most, when it could fit in the frame
if it.props.get("name").is_some() && inside > 0.0 && best.as_ref().is_none_or(|s| inside > s.1) {
- let fits = b[2] - b[0] < 0.9 * st.w && b[3] - b[1] < 0.9 * st.h;
+ let fits = b[2] - b[0] < 0.9 * w && b[3] - b[1] < 0.9 * h;
best = Some((called(it), inside, 1.0 - inside / whole, fits && scale_of(it) > 0.0));
}
}
// the page's words and videos fill the frame too: a headline over an empty 3D isn't an empty frame
- for b in page.get(k).into_iter().flat_map(|p| p.words.iter().map(|w| w.bx).chain(p.videos.iter().copied()).chain(p.pictures.iter().copied())) {
- mark(&mut grid, b, st.w, st.h);
+ for b in page.into_iter().flat_map(|p| p.words.iter().map(|w| w.bx).chain(p.videos.iter().copied()).chain(p.pictures.iter().copied())) {
+ mark(&mut grid, b, w, h);
}
- covered[k] = grid.iter().filter(|c| **c).count() as f32 / (GX * GY) as f32;
- judged[k] = sure;
- subject[k] = best.map(|(name, _, out, fits)| (name, out, fits));
+ (grid.iter().filter(|c| **c).count() as f32 / (GX * GY) as f32, sure, best.map(|(name, _, out, fits)| (name, out, fits)))
}
- let mut out = Vec::new();
- let total = st.secs(0, n.saturating_sub(1).max(0));
- for (a, b) in runs(st, n, |k| judged[k] && covered[k] < EMPTY) {
- let (t0, t1) = ((st.frames[a] - st.frames[0]) as f64 / st.fps, (st.frames[b] - st.frames[0] + 1) as f64 / st.fps);
- if st.secs(a, b) >= EMPTY_SECS && t0 > FADE_SECS && t1 < total - FADE_SECS {
- let least = covered[a..=b].iter().copied().fold(1.0, f32::min);
- let says = format!("almost nothing is on screen from {} to {} ({:.0}% of the frame shows any part)", st.at(a), st.at(b), least * 100.0);
- out.push(st.finding("frame-empty", Level::Error, a, b, says).fix("aim the camera at what the shot is about, or bring it into the frame"));
+
+ /// SG14 over the frames given.
+ pub(crate) fn check(self, st: &Stage) -> Vec<Finding> {
+ let (n, covered, judged, subject) = (st.len(), self.covered, self.judged, self.subject);
+ let mut out = Vec::new();
+ let total = st.secs(0, n.saturating_sub(1).max(0));
+ for (a, b) in runs(st, n, |k| judged[k] && covered[k] < EMPTY) {
+ let (t0, t1) = ((st.frames[a] - st.frames[0]) as f64 / st.fps, (st.frames[b] - st.frames[0] + 1) as f64 / st.fps);
+ if st.secs(a, b) >= EMPTY_SECS && t0 > FADE_SECS && t1 < total - FADE_SECS {
+ let least = covered[a..=b].iter().copied().fold(1.0, f32::min);
+ let says = format!("almost nothing is on screen from {} to {} ({:.0}% of the frame shows any part)", st.at(a), st.at(b), least * 100.0);
+ out.push(st.finding("frame-empty", Level::Error, a, b, says).fix("aim the camera at what the shot is about, or bring it into the frame"));
+ }
}
- }
- for (a, b) in runs(st, n, |k| subject[k].as_ref().is_some_and(|(_, out, fits)| *fits && *out > CUT_LO && *out < CUT_HI)) {
- let names: Vec<&str> = subject[a..=b].iter().filter_map(|s| s.as_ref().map(|s| s.0.as_str())).collect();
- if b + 1 - a > CUT_FRAMES && names.windows(2).all(|w| w[0] == w[1]) {
- let says = format!("'{}', the part the shot shows most, is cut by the frame's edge from {} to {}", names[0], st.at(a), st.at(b));
- out.push(st.finding("subject-cut", Level::Warn, a, b, says).fix("frame it whole (move the camera back or aim it), or move in until the cut is plainly meant"));
+ for (a, b) in runs(st, n, |k| subject[k].as_ref().is_some_and(|(_, out, fits)| *fits && *out > CUT_LO && *out < CUT_HI)) {
+ let names: Vec<&str> = subject[a..=b].iter().filter_map(|s| s.as_ref().map(|s| s.0.as_str())).collect();
+ if b + 1 - a > CUT_FRAMES && names.windows(2).all(|w| w[0] == w[1]) {
+ let says = format!("'{}', the part the shot shows most, is cut by the frame's edge from {} to {}", names[0], st.at(a), st.at(b));
+ out.push(st.finding("subject-cut", Level::Warn, a, b, says).fix("frame it whole (move the camera back or aim it), or move in until the cut is plainly meant"));
+ }
}
+ out
}
- out
}
#[cfg(test)]
diff --git a/systems/stage/src/lib.rs b/systems/stage/src/lib.rs
index 981e4ae1..4441adbc 100644
--- a/systems/stage/src/lib.rs
+++ b/systems/stage/src/lib.rs
@@ -2,7 +2,9 @@
//! that can't be read, parts that snap, a camera that lurches or reverses, and frames with nothing composed in them.
//! Each reads the parts every frame holds (raea_core_scene's items, as raea-sys-contact does) through the frame's
//! camera, and reports the part, the frames and the fix. They read the scene, not the pixels, so they run without
-//! drawing (`raea scene stage`) as well as at the end of every render.
+//! drawing (`raea scene stage`) as well as at the end of every render. A render hands them its frames as they come
+//! (Staging): each frame is read into what the checks keep of it (its camera, its words' sizes, its named parts' places,
+//! how much of it is covered) and let go, so a long render's checks never hold its frames' parts (SG4a).
use bevy::math::Vec3;
use raea_core_facts::{Finding, Level};
@@ -16,7 +18,7 @@ mod page;
mod text;
mod view;
pub use framing::on_screen;
-pub use manifest::{pages, seen};
+pub use manifest::{Mounts, pages, seen};
pub use page::{Page, Words};
pub use view::View;
@@ -26,19 +28,7 @@ pub const BY: &str = "raea render";
/// The checks on a render's frames, said on stderr and kept with its findings (RAEA_STAGE_CHECK=0 skips them). `page` is
/// what each frame's page draws over its 3D (SG11, SG14), none when it isn't known.
pub fn told(all: &[Vec<Item>], frames: &[i64], page: &[Page], w: u32, h: u32, fps: f64) -> Vec<Finding> {
- if std::env::var("RAEA_STAGE_CHECK").as_deref() == Ok("0") || all.iter().all(|its| its.is_empty()) {
- return Vec::new();
- }
- let t = std::time::Instant::now();
- let found = check_with(all, frames, page, w, h, fps, BY);
- for f in &found {
- eprintln!("raea: {}", f.line());
- }
- raea_core_facts::finding::said(&found);
- if std::env::var_os("RAEA_TIMES").is_some() {
- eprintln!("raea times: the stage checks {:.0} ms", t.elapsed().as_secs_f64() * 1e3);
- }
- found
+ pushed(all, frames, page, w, h, fps).told()
}
/// Every stage check on the frames (`all[k]` is frame `frames[k]`'s parts), worst first.
@@ -49,13 +39,76 @@ pub fn check(all: &[Vec<Item>], frames: &[i64], w: u32, h: u32, fps: f64, by: &s
/// check, with what each frame's page draws (`page[k]`, frame `frames[k]`'s): its words held off the parts (SG11),
/// and its words and videos filling the frame (SG14).
pub fn check_with(all: &[Vec<Item>], frames: &[i64], page: &[Page], w: u32, h: u32, fps: f64, by: &str) -> Vec<Finding> {
- let st = Stage::new(all, frames, w, h, fps, by);
- let mut out = text::check(&st);
- out.extend(motion::camera(&st));
- out.extend(motion::snaps(&st));
- out.extend(framing::check(&st, page));
- out.extend(page::check(&st, page));
- raea_core_facts::finding::ranked(merged(out))
+ pushed(all, frames, page, w, h, fps).findings(by)
+}
+
+fn pushed(all: &[Vec<Item>], frames: &[i64], page: &[Page], w: u32, h: u32, fps: f64) -> Staging {
+ let mut s = Staging::new(w, h, fps);
+ for (k, its) in all.iter().enumerate() {
+ s.push(frames[k], its, page.get(k));
+ }
+ s
+}
+
+/// The stage checks as a render's frames come: each frame read into what the checks keep of it, then let go (SG4a).
+pub struct Staging {
+ frames: Vec<i64>,
+ views: Vec<Option<View>>,
+ w: u32,
+ h: u32,
+ fps: f64,
+ any: bool,
+ texts: text::Texts,
+ snaps: motion::Snaps,
+ framing: framing::Framing,
+ over: page::Over,
+}
+
+impl Staging {
+ pub fn new(w: u32, h: u32, fps: f64) -> Staging {
+ Staging { frames: Vec::new(), views: Vec::new(), w, h, fps, any: false, texts: Default::default(), snaps: Default::default(), framing: Default::default(), over: Default::default() }
+ }
+
+ /// The next frame (its number, `frame`): its parts, and what its page draws over them where that's known.
+ pub fn push(&mut self, frame: i64, its: &[Item], page: Option<&Page>) {
+ let (k, v, w, h) = (self.frames.len(), View::of(its, self.w, self.h), self.w as f32, self.h as f32);
+ self.any |= !its.is_empty();
+ self.texts.push(k, its, v);
+ self.snaps.push(k, its, v, w, h);
+ self.framing.push(k, its, v, page, w, h);
+ self.over.push(k, its, v, page, w, h);
+ self.frames.push(frame);
+ self.views.push(v);
+ }
+
+ /// The findings, said on stderr and kept with the render's (RAEA_STAGE_CHECK=0 skips them).
+ pub fn told(self) -> Vec<Finding> {
+ if std::env::var("RAEA_STAGE_CHECK").as_deref() == Ok("0") || !self.any {
+ return Vec::new();
+ }
+ let t = std::time::Instant::now();
+ let found = self.findings(BY);
+ for f in &found {
+ eprintln!("raea: {}", f.line());
+ }
+ raea_core_facts::finding::said(&found);
+ if std::env::var_os("RAEA_TIMES").is_some() {
+ eprintln!("raea times: the stage checks {:.0} ms", t.elapsed().as_secs_f64() * 1e3);
+ }
+ found
+ }
+
+ /// Every stage check on the frames given, worst first.
+ pub fn findings(self, by: &str) -> Vec<Finding> {
+ let cut = motion::cuts(&self.views, &self.frames);
+ let st = Stage { frames: self.frames, views: self.views, cut, w: self.w as f32, h: self.h as f32, fps: self.fps.max(1.0), by };
+ let mut out = self.texts.check(&st);
+ out.extend(motion::camera(&st));
+ out.extend(self.snaps.check(&st));
+ out.extend(self.framing.check(&st));
+ out.extend(self.over.check(&st));
+ raea_core_facts::finding::ranked(merged(out))
+ }
}
/// Findings of one check over the same frames as one, the others named after it: a code listing's twenty lines too
@@ -78,10 +131,9 @@ fn merged(fs: Vec<Finding>) -> Vec<Finding> {
out
}
-/// The frames as the checks read them: each one's parts and camera, and where the shots cut.
+/// The frames as the checks read them once all have come: each one's number and camera, and where the shots cut.
pub(crate) struct Stage<'a> {
- pub all: &'a [Vec<Item>],
- pub frames: &'a [i64],
+ pub frames: Vec<i64>,
pub views: Vec<Option<View>>,
/// cut[k]: frame k starts a new shot (the first frame, a gap in the frames, a camera jump or a new camera)
pub cut: Vec<bool>,
@@ -91,11 +143,10 @@ pub(crate) struct Stage<'a> {
pub by: &'a str,
}
-impl<'a> Stage<'a> {
- fn new(all: &'a [Vec<Item>], frames: &'a [i64], w: u32, h: u32, fps: f64, by: &'a str) -> Stage<'a> {
- let views: Vec<Option<View>> = all.iter().map(|its| View::of(its, w, h)).collect();
- let cut = motion::cuts(&views, frames);
- Stage { all, frames, views, cut, w: w as f32, h: h as f32, fps: fps.max(1.0), by }
+impl Stage<'_> {
+ /// How many frames.
+ pub fn len(&self) -> usize {
+ self.frames.len()
}
/// A finding about frames `a..=b` (indices into the frames), at `level`.
diff --git a/systems/stage/src/manifest.rs b/systems/stage/src/manifest.rs
index 180168d8..494bb37a 100644
--- a/systems/stage/src/manifest.rs
+++ b/systems/stage/src/manifest.rs
@@ -46,29 +46,57 @@ pub fn pages(frames: &[Value], nums: &[i64], w: u32, h: u32) -> Vec<Page> {
/// 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 fn seen(all: &[Vec<Item>], nums: &[i64], w: u32, h: u32) -> Value {
- if all.len() <= STILLS {
- let parts: Vec<_> = all.iter().zip(nums).map(|(its, f)| json!({"frame": f, "parts": crate::on_screen(its, w, h)})).collect();
- return json!({"parts": parts});
- }
- // each frame's count against the one before, one count held at a time (a film's 13,175 at once were a GB)
- let (mut before, mut remounts) = (None, Vec::new());
+ let mut m = Mounts::new(w, h);
for (its, f) in all.iter().zip(nums) {
+ m.push(*f, its);
+ }
+ m.value()
+}
+
+/// seen as a render's frames come: each frame's count against the one before, one count held at a time (a film's
+/// 13,175 at once were a GB), and each frame's parts on screen while it may still be stills.
+pub struct Mounts {
+ w: u32,
+ h: u32,
+ n: usize,
+ stills: Vec<Value>,
+ before: Option<Counted>,
+ remounts: Vec<i64>,
+}
+
+impl Mounts {
+ pub fn new(w: u32, h: u32) -> Mounts {
+ Mounts { w, h, n: 0, stills: Vec::new(), before: None, remounts: Vec::new() }
+ }
+
+ /// The next frame (its number, `frame`) and its parts.
+ pub fn push(&mut self, frame: i64, its: &[Item]) {
+ if self.n < STILLS {
+ self.stills.push(json!({"frame": frame, "parts": crate::on_screen(its, self.w, self.h)}));
+ } else {
+ self.stills.clear();
+ }
let now = counted(its);
- if before.as_ref().is_some_and(|b| changed(&now, b) > REMOUNT) {
- remounts.push(*f);
+ if self.before.as_ref().is_some_and(|b| changed(&now, b) > REMOUNT) {
+ self.remounts.push(frame);
}
- before = Some(now);
+ self.before = Some(now);
+ self.n += 1;
+ }
+
+ /// What the manifest says: stills' parts on screen, a longer render's remounts.
+ pub fn value(self) -> Value {
+ if self.n <= STILLS { json!({"parts": self.stills}) } else { json!({"remounts": self.remounts}) }
}
- json!({"remounts": remounts})
}
-type Counted<'a> = HashMap<(&'a str, &'a str, u64), i64>;
+type Counted = HashMap<(&'static str, String, u64), i64>;
/// A frame's parts as a count by what they are: kind, name, what they draw.
-fn counted(its: &[Item]) -> Counted<'_> {
+fn counted(its: &[Item]) -> Counted {
let mut m = Counted::new();
for it in its {
- *m.entry((it.kind, base_ident(it), spawn_sig(it))).or_default() += 1;
+ *m.entry((it.kind, base_ident(it).to_string(), spawn_sig(it))).or_default() += 1;
}
m
}
diff --git a/systems/stage/src/motion.rs b/systems/stage/src/motion.rs
index 4dce7741..27405e97 100644
--- a/systems/stage/src/motion.rs
+++ b/systems/stage/src/motion.rs
@@ -6,7 +6,7 @@ use std::collections::{BTreeMap, HashMap};
use bevy::math::Vec3;
use raea_core_facts::{Finding, Level};
-use super::{Stage, View, called, num, origin, scale_of};
+use super::{Item, Stage, View, called, num, origin, scale_of};
/// A cut: the eye jumps or the view turns this many times its neighbours' step in one frame (and past a floor)
const CUT_RATIO: f32 = 8.0;
@@ -216,13 +216,20 @@ fn reach(it: &raea_core_scene::Item, boxes: &mut HashMap<String, Option<f32>>) -
/// SG12: a named part whose size or place on screen jumps in one frame, alone (no cut, no steady move either side),
/// and a line drawn as a growing chain of parts named NAME-i.
-pub(crate) fn snaps(st: &Stage) -> Vec<Finding> {
- let mut boxes = HashMap::new();
- // each named part's screen size (px) and centre, by frame, a run for each of what it is: new words or a new shape
- // is the part spawned again (SG1), new content and no snap (a counter's words growing as its number does)
- let mut by: BTreeMap<(String, u64), Vec<(usize, f32, [f32; 2])>> = BTreeMap::new();
- let mut chains: BTreeMap<String, (usize, usize, usize)> = BTreeMap::new();
- for (k, its) in st.all.iter().enumerate() {
+#[derive(Default)]
+pub(crate) struct Snaps {
+ boxes: HashMap<String, Option<f32>>,
+ /// each named part's screen size (px) and centre, by frame, a run for each of what it is: new words or a new shape
+ /// is the part spawned again (SG1), new content and no snap (a counter's words growing as its number does)
+ by: BTreeMap<(String, u64), Vec<(usize, f32, [f32; 2])>>,
+ /// each chain's first frame, and its fewest and most links
+ chains: BTreeMap<String, (usize, usize, usize)>,
+}
+
+impl Snaps {
+ /// Frame k's named parts, through its camera `v`, on a w x h frame.
+ pub(crate) fn push(&mut self, k: usize, its: &[Item], v: Option<View>, w: f32, h: f32) {
+ let (boxes, by, chains) = (&mut self.boxes, &mut self.by, &mut self.chains);
let mut links: HashMap<String, usize> = HashMap::new();
for it in its.iter() {
let Some(name) = it.props.get("name").and_then(serde_json::Value::as_str) else { continue };
@@ -231,9 +238,9 @@ pub(crate) fn snaps(st: &Stage) -> Vec<Finding> {
*links.entry(stem.to_string()).or_default() += 1;
}
}
- let (Some(v), Some(r)) = (st.views[k], reach(it, &mut boxes).filter(|r| *r <= BIG_REACH)) else { continue };
+ let (Some(v), Some(r)) = (v, reach(it, boxes).filter(|r| *r <= BIG_REACH)) else { continue };
let Some([x, y, depth]) = v.project(origin(it)) else { continue };
- if x < 0.0 || x > st.w || y < 0.0 || y > st.h {
+ if x < 0.0 || x > w || y < 0.0 || y > h {
continue;
}
by.entry((called(it), raea_core_scene::spawn_sig(it))).or_default().push((k, r * v.focal / depth, [x, y]));
@@ -244,44 +251,49 @@ pub(crate) fn snaps(st: &Stage) -> Vec<Finding> {
c.2 = c.2.max(n);
}
}
- let mut out: Vec<(usize, Finding)> = Vec::new();
- for ((name, _), seen) in &by {
- // a name several items carry in one frame has no one size to follow
- let frames: std::collections::HashSet<usize> = seen.iter().map(|s| s.0).collect();
- if frames.len() < seen.len() {
- continue;
- }
- // a step's size change (log ratio) and travel (share of the width), for consecutive frames in one shot
- let step = |i: usize| -> Option<(f32, f32)> {
- let (a, b) = (seen.get(i.checked_sub(1)?)?, seen.get(i)?);
- (b.0 == a.0 + 1 && !st.cut[b.0]).then(|| ((b.1 / a.1.max(1e-3)).ln().abs(), ((b.2[0] - a.2[0]).powi(2) + (b.2[1] - a.2[1]).powi(2)).sqrt() / st.w))
- };
- for i in 1..seen.len() {
- // steady frames on both sides: a part coming in (a pop, a fade up) has none before it
- let (Some((ds, dm)), Some(before), Some(after)) = (step(i), step(i - 1), step(i + 1)) else { continue };
- let side = |f: fn((f32, f32)) -> f32| f(before).max(f(after));
- let k = seen[i].0;
- if ds > SNAP_SIZE.ln() && ds > 3.0 * side(|s| s.0) && seen[i].1.max(seen[i - 1].1) > 4.0 {
- let says = format!("'{name}' snaps from {:.0} px to {:.0} px on screen at {} with no cut", seen[i - 1].1, seen[i].1, st.at(k));
- out.push((k, st.finding("part-snap", Level::Error, k - 1, k, says).fix("animate the change over frames, or cut to it; a part that comes in a frame late or at another's place is drawn from a stale frame (raea render's frame purity)")));
- } else if dm > SNAP_MOVE && dm > 3.0 * side(|s| s.1) {
- let says = format!("'{name}' jumps {:.0}% of the frame's width at {} with no cut", dm * 100.0, st.at(k));
- out.push((k, st.finding("part-snap", Level::Warn, k - 1, k, says).fix("move it over frames, or cut; check it isn't placed from another part's frame")));
+
+ /// SG12 over the frames given.
+ pub(crate) fn check(self, st: &Stage) -> Vec<Finding> {
+ let (by, chains) = (self.by, self.chains);
+ let mut out: Vec<(usize, Finding)> = Vec::new();
+ for ((name, _), seen) in &by {
+ // a name several items carry in one frame has no one size to follow
+ let frames: std::collections::HashSet<usize> = seen.iter().map(|s| s.0).collect();
+ if frames.len() < seen.len() {
+ continue;
+ }
+ // a step's size change (log ratio) and travel (share of the width), for consecutive frames in one shot
+ let step = |i: usize| -> Option<(f32, f32)> {
+ let (a, b) = (seen.get(i.checked_sub(1)?)?, seen.get(i)?);
+ (b.0 == a.0 + 1 && !st.cut[b.0]).then(|| ((b.1 / a.1.max(1e-3)).ln().abs(), ((b.2[0] - a.2[0]).powi(2) + (b.2[1] - a.2[1]).powi(2)).sqrt() / st.w))
+ };
+ for i in 1..seen.len() {
+ // steady frames on both sides: a part coming in (a pop, a fade up) has none before it
+ let (Some((ds, dm)), Some(before), Some(after)) = (step(i), step(i - 1), step(i + 1)) else { continue };
+ let side = |f: fn((f32, f32)) -> f32| f(before).max(f(after));
+ let k = seen[i].0;
+ if ds > SNAP_SIZE.ln() && ds > 3.0 * side(|s| s.0) && seen[i].1.max(seen[i - 1].1) > 4.0 {
+ let says = format!("'{name}' snaps from {:.0} px to {:.0} px on screen at {} with no cut", seen[i - 1].1, seen[i].1, st.at(k));
+ out.push((k, st.finding("part-snap", Level::Error, k - 1, k, says).fix("animate the change over frames, or cut to it; a part that comes in a frame late or at another's place is drawn from a stale frame (raea render's frame purity)")));
+ } else if dm > SNAP_MOVE && dm > 3.0 * side(|s| s.1) {
+ let says = format!("'{name}' jumps {:.0}% of the frame's width at {} with no cut", dm * 100.0, st.at(k));
+ out.push((k, st.finding("part-snap", Level::Warn, k - 1, k, says).fix("move it over frames, or cut; check it isn't placed from another part's frame")));
+ }
}
}
- }
- let mut at: HashMap<usize, usize> = HashMap::new();
- for (k, _) in &out {
- *at.entry(*k).or_default() += 1;
- }
- let mut out: Vec<Finding> = out.into_iter().filter(|(k, _)| at[k] < EDIT_PARTS).map(|(_, f)| f).collect();
- for (stem, (k, least, most)) in chains {
- if most > CHAIN && most > least {
- let says = format!("a line made of {most} parts ('{stem}-0' to '{stem}-{}'), mounted a part at a time as it grows", most - 1);
- out.push(st.finding("line-of-parts", Level::Warn, k, k, says).fix("draw it as one Line3d or Tube (raea/mesh) and animate its `p`"));
+ let mut at: HashMap<usize, usize> = HashMap::new();
+ for (k, _) in &out {
+ *at.entry(*k).or_default() += 1;
}
+ let mut out: Vec<Finding> = out.into_iter().filter(|(k, _)| at[k] < EDIT_PARTS).map(|(_, f)| f).collect();
+ for (stem, (k, least, most)) in chains {
+ if most > CHAIN && most > least {
+ let says = format!("a line made of {most} parts ('{stem}-0' to '{stem}-{}'), mounted a part at a time as it grows", most - 1);
+ out.push(st.finding("line-of-parts", Level::Warn, k, k, says).fix("draw it as one Line3d or Tube (raea/mesh) and animate its `p`"));
+ }
+ }
+ out
}
- out
}
#[cfg(test)]
diff --git a/systems/stage/src/page.rs b/systems/stage/src/page.rs
index fd153aac..56a36249 100644
--- a/systems/stage/src/page.rs
+++ b/systems/stage/src/page.rs
@@ -8,9 +8,9 @@ use std::collections::HashMap;
use raea_core_facts::{Finding, Level};
use serde_json::Value;
-use super::{Stage, called, runs};
+use super::{Item, Stage, called, runs};
use crate::framing::{backdrop, own_box};
-use crate::view::corners;
+use crate::view::{View, corners};
/// Words in the page on one frame: what they say, their box on screen ([x0, y0, x1, y1] in px), and whether they
/// may sit on a part (an element they're in says data-allow-overlap).
@@ -44,19 +44,25 @@ fn short(t: &str) -> String {
s
}
-pub(crate) fn check(st: &Stage, page: &[Page]) -> Vec<Finding> {
- let mut boxes = HashMap::new();
- // each words' frames over a part past SHARE, and on each the parts it covers with their shares
- let mut over: HashMap<String, HashMap<usize, Vec<(String, f32)>>> = HashMap::new();
- for (k, its) in st.all.iter().enumerate() {
- let (Some(v), Some(words)) = (st.views[k], page.get(k).map(|p| &p.words).filter(|w| !w.is_empty())) else { continue };
+/// Each words' frames over a part past SHARE as the frames come, and on each the parts it covers with their shares.
+#[derive(Default)]
+pub(crate) struct Over {
+ boxes: HashMap<String, Option<(bevy::math::Vec3, bevy::math::Vec3)>>,
+ over: HashMap<String, HashMap<usize, Vec<(String, f32)>>>,
+}
+
+impl Over {
+ /// Frame k's parts through its camera `v`, and its page's words over them, on a w x h frame.
+ pub(crate) fn push(&mut self, k: usize, its: &[Item], v: Option<View>, page: Option<&Page>, w: f32, h: f32) {
+ let (Some(v), Some(words)) = (v, page.map(|p| &p.words).filter(|w| !w.is_empty())) else { return };
+ let (boxes, over) = (&mut self.boxes, &mut self.over);
for it in its {
if it.props.get("allowOverlap").and_then(Value::as_bool) == Some(true) {
continue;
}
- let Some((lo, hi)) = own_box(it, &mut boxes).filter(|(lo, hi)| !backdrop(it, *lo, *hi)) else { continue };
+ let Some((lo, hi)) = own_box(it, boxes).filter(|(lo, hi)| !backdrop(it, *lo, *hi)) else { continue };
let Some(b) = v.bounds(corners(&it.world, lo, hi)) else { continue };
- let b = [b[0].max(0.0), b[1].max(0.0), b[2].min(st.w), b[3].min(st.h)];
+ let b = [b[0].max(0.0), b[1].max(0.0), b[2].min(w), b[3].min(h)];
let area = (b[2] - b[0]) * (b[3] - b[1]);
if !(area > 1.0) {
continue;
@@ -69,31 +75,35 @@ pub(crate) fn check(st: &Stage, page: &[Page]) -> Vec<Finding> {
}
}
}
- // said in the order they start (a HashMap's order changed from run to run)
- let mut over: Vec<_> = over.into_iter().collect();
- over.sort_by_key(|(text, at)| (at.keys().min().copied(), text.clone()));
- let mut out = Vec::new();
- for (text, at) in over {
- for (a, b) in runs(st, st.all.len(), |k| at.contains_key(&k)) {
- if st.secs(a, b) < SECS && !st.alone(a) {
- continue;
- }
- // the parts it covers over the run, the most covered first: one fault, however many parts are under it
- let mut most: Vec<(String, f32)> = Vec::new();
- for (name, share) in (a..=b).filter_map(|k| at.get(&k)).flatten() {
- match most.iter_mut().find(|m| m.0 == *name) {
- Some(m) => m.1 = m.1.max(*share),
- None => most.push((name.clone(), *share)),
+
+ /// SG11 over the frames given.
+ pub(crate) fn check(self, st: &Stage) -> Vec<Finding> {
+ // said in the order they start (a HashMap's order changed from run to run)
+ let mut over: Vec<_> = self.over.into_iter().collect();
+ over.sort_by_key(|(text, at)| (at.keys().min().copied(), text.clone()));
+ let mut out = Vec::new();
+ for (text, at) in over {
+ for (a, b) in runs(st, st.len(), |k| at.contains_key(&k)) {
+ if st.secs(a, b) < SECS && !st.alone(a) {
+ continue;
+ }
+ // the parts it covers over the run, the most covered first: one fault, however many parts are under it
+ let mut most: Vec<(String, f32)> = Vec::new();
+ for (name, share) in (a..=b).filter_map(|k| at.get(&k)).flatten() {
+ match most.iter_mut().find(|m| m.0 == *name) {
+ Some(m) => m.1 = m.1.max(*share),
+ None => most.push((name.clone(), *share)),
+ }
}
+ most.sort_by(|x, y| y.1.total_cmp(&x.1));
+ let named: Vec<String> = most.iter().take(3).map(|(n, s)| format!("'{n}' ({:.0}%)", s * 100.0)).collect();
+ let more = if most.len() > 3 { format!(" and {} more", most.len() - 3) } else { String::new() };
+ let says = format!("'{}' in the page covers {}{more} from {} to {}", short(&text), named.join(", "), st.at(a), st.at(b));
+ out.push(st.finding("type-over-part", Level::Error, a, b, says).fix("move the words off it, or beside it with a Label (raea/camera) that points at it; words meant to sit on it go in an element with data-allow-overlap"));
}
- most.sort_by(|x, y| y.1.total_cmp(&x.1));
- let named: Vec<String> = most.iter().take(3).map(|(n, s)| format!("'{n}' ({:.0}%)", s * 100.0)).collect();
- let more = if most.len() > 3 { format!(" and {} more", most.len() - 3) } else { String::new() };
- let says = format!("'{}' in the page covers {}{more} from {} to {}", short(&text), named.join(", "), st.at(a), st.at(b));
- out.push(st.finding("type-over-part", Level::Error, a, b, says).fix("move the words off it, or beside it with a Label (raea/camera) that points at it; words meant to sit on it go in an element with data-allow-overlap"));
}
+ out
}
- out
}
#[cfg(test)]
diff --git a/systems/stage/src/text.rs b/systems/stage/src/text.rs
index 65efd608..d7dc2a9a 100644
--- a/systems/stage/src/text.rs
+++ b/systems/stage/src/text.rs
@@ -9,8 +9,8 @@ use bevy::math::Vec3;
use raea_core_facts::{Finding, Level};
use serde_json::Value;
-use super::{Stage, called, num, origin, runs};
-use crate::view::corners;
+use super::{Item, Stage, called, num, origin, runs};
+use crate::view::{View, corners};
/// A capital's height, as a share of the em (Inter's is 0.727; most text faces 0.66 to 0.75)
const CAP: f32 = 0.7;
@@ -49,12 +49,17 @@ struct Seen {
whole: bool,
}
-pub(crate) fn check(st: &Stage) -> Vec<Finding> {
- let min_cap = MIN_CAP * st.h / 1080.0;
- // each block's frames, by what it's called, in frame order
- let mut by: BTreeMap<String, (Vec<Seen>, usize, bool)> = BTreeMap::new();
- for (k, its) in st.all.iter().enumerate() {
- let Some(v) = st.views[k] else { continue };
+/// Each block's frames as they come, by what it's called, in frame order (and its words' count, and whether it reveals).
+#[derive(Default)]
+pub(crate) struct Texts {
+ by: BTreeMap<String, (Vec<Seen>, usize, bool)>,
+}
+
+impl Texts {
+ /// Frame k's blocks of words, through its camera `v`.
+ pub(crate) fn push(&mut self, k: usize, its: &[Item], v: Option<View>) {
+ let Some(v) = v else { return };
+ let by = &mut self.by;
for it in its.iter().filter(|i| i.kind == "text") {
if it.props.get("read").and_then(Value::as_bool) == Some(false) {
continue;
@@ -84,57 +89,61 @@ pub(crate) fn check(st: &Stage) -> Vec<Finding> {
e.0.push(Seen { k, cap, turn, b, c: [cx, cy], shown, whole });
}
}
- let mut out = Vec::new();
- for (name, (seen, words, has_at)) in &by {
- // the frames it's up and in frame
- let up: Vec<&Seen> = seen.iter().filter(|s| s.shown && in_frame(st, s.c)).collect();
- // the frames of a run (up is in frame order)
- let during = |a: usize, b: usize| up.iter().skip_while(move |s| s.k < a).take_while(move |s| s.k <= b);
- let lasting = |bad: &dyn Fn(&Seen) -> bool| -> Vec<(usize, usize)> {
- let flagged: std::collections::HashSet<usize> = up.iter().filter(|s| bad(s)).map(|s| s.k).collect();
- runs(st, st.all.len(), |k| flagged.contains(&k)).into_iter().filter(|(a, b)| st.secs(*a, *b) >= LASTS || (a == b && st.alone(*a))).collect()
- };
- for (a, b) in lasting(&|s| s.cap < min_cap) {
- let least = during(a, b).map(|s| s.cap).fold(f32::MAX, f32::min);
- let f = st.finding("type-small", Level::Error, a, b, format!("the words '{name}' stand {least:.0} px high on screen from {} to {} (capitals at least {min_cap:.0} px at this frame size)", st.at(a), st.at(b)));
- out.push(fix(f, "bring the camera nearer, or make its size larger: a label that points at a part reads better as page type laid over the frame; scenery nobody is meant to read takes read={false}", least, min_cap, "px"));
- }
- for (a, b) in lasting(&|s| s.turn > MAX_TURN) {
- let most = during(a, b).map(|s| s.turn).fold(0.0, f32::max);
- let says = if most > 90.0 { format!("the words '{name}' are seen from behind (turned {most:.0}°) from {} to {}", st.at(a), st.at(b)) } else { format!("the words '{name}' are turned {most:.0}° from the camera from {} to {} (at most {MAX_TURN:.0}°), so they read squashed", st.at(a), st.at(b)) };
- let level = if most > TURN_ERROR { Level::Error } else { Level::Warn };
- out.push(fix(st.finding("type-angle", level, a, b, says), "turn the words to face the camera (their rotation), or move the camera round to face them", most, MAX_TURN, "°"));
- }
- let (mx, my) = (SAFE * st.w, SAFE * st.h);
- for (a, b) in lasting(&|s| s.whole && s.b.is_some_and(|b| b[0] < mx || b[1] < my || b[2] > st.w - mx || b[3] > st.h - my)) {
- let f = st.finding("type-safe", Level::Warn, a, b, format!("the words '{name}' run outside the title-safe area from {} to {}", st.at(a), st.at(b)));
- out.push(f.fix("move them in, or the camera back, so the whole block sits inside 5% of each edge"));
- }
- // its reveal: never started while it's in frame, or never finished before it goes (out of view with frames still
- // stepped after: a still's few frames end, the words don't go); only over frames all stepped (stills far apart
- // say nothing of what came between)
- let in_view: Vec<&Seen> = seen.iter().filter(|s| in_frame(st, s.c)).collect();
- if let (Some(f), Some(l)) = (in_view.first(), in_view.last()) && st.stepped(f.k, l.k) {
- let long = st.secs(f.k, l.k) >= 1.0;
- if *has_at && long && in_view.iter().all(|s| !s.shown) {
- let f = st.finding("type-reveal", Level::Error, f.k, l.k, format!("the words '{name}' are never shown: their reveal (`at`) never starts while they're up, {} to {}", st.at(f.k), st.at(l.k)));
- out.push(f.fix("give `at` in the frames of the Sequence they play in (useCurrentFrame), never a frame of another clock"));
- } else if l.k + 1 < st.all.len() && in_view.iter().any(|s| s.shown) && !in_view.iter().any(|s| s.whole) {
- let f = st.finding("type-reveal", Level::Error, f.k, l.k, format!("the words '{name}' never finish their reveal before they go ({} to {})", st.at(f.k), st.at(l.k)));
- out.push(f.fix("start the reveal earlier, make it quicker (`each`), or keep the words up longer"));
+
+ pub(crate) fn check(self, st: &Stage) -> Vec<Finding> {
+ let min_cap = MIN_CAP * st.h / 1080.0;
+ let mut out = Vec::new();
+ for (name, (seen, words, has_at)) in &self.by {
+ // the frames it's up and in frame
+ let up: Vec<&Seen> = seen.iter().filter(|s| s.shown && in_frame(st, s.c)).collect();
+ // the frames of a run (up is in frame order)
+ let during = |a: usize, b: usize| up.iter().skip_while(move |s| s.k < a).take_while(move |s| s.k <= b);
+ let lasting = |bad: &dyn Fn(&Seen) -> bool| -> Vec<(usize, usize)> {
+ let flagged: std::collections::HashSet<usize> = up.iter().filter(|s| bad(s)).map(|s| s.k).collect();
+ runs(st, st.len(), |k| flagged.contains(&k)).into_iter().filter(|(a, b)| st.secs(*a, *b) >= LASTS || (a == b && st.alone(*a))).collect()
+ };
+ for (a, b) in lasting(&|s| s.cap < min_cap) {
+ let least = during(a, b).map(|s| s.cap).fold(f32::MAX, f32::min);
+ let f = st.finding("type-small", Level::Error, a, b, format!("the words '{name}' stand {least:.0} px high on screen from {} to {} (capitals at least {min_cap:.0} px at this frame size)", st.at(a), st.at(b)));
+ out.push(fix(f, "bring the camera nearer, or make its size larger: a label that points at a part reads better as page type laid over the frame; scenery nobody is meant to read takes read={false}", least, min_cap, "px"));
}
- }
- // read: still, whole, big enough and facing the camera for their reading time, all told
- let need = *words as f64 / 3.0 + 0.5;
- let readable = up.windows(2).filter(|w| w[0].k + 1 == w[1].k && !st.cut[w[1].k] && readable(st, w[0], w[1], min_cap)).count() as f64 / st.fps;
- if let (Some(f), Some(l)) = (up.first(), up.last()) && st.stepped(f.k, l.k) {
- if readable + 1e-9 < need && up.iter().any(|s| s.whole) {
- let f = st.finding("type-time", Level::Warn, f.k, l.k, format!("the words '{name}' can be read for {readable:.1} s; their {words} words need {need:.1} s (words ÷ 3 a second, plus 0.5 s)"));
- out.push(fix(f, "hold them still, whole and facing the camera longer before they or the camera move", readable as f32, need as f32, "s"));
+ for (a, b) in lasting(&|s| s.turn > MAX_TURN) {
+ let most = during(a, b).map(|s| s.turn).fold(0.0, f32::max);
+ let says = if most > 90.0 { format!("the words '{name}' are seen from behind (turned {most:.0}°) from {} to {}", st.at(a), st.at(b)) } else { format!("the words '{name}' are turned {most:.0}° from the camera from {} to {} (at most {MAX_TURN:.0}°), so they read squashed", st.at(a), st.at(b)) };
+ let level = if most > TURN_ERROR { Level::Error } else { Level::Warn };
+ out.push(fix(st.finding("type-angle", level, a, b, says), "turn the words to face the camera (their rotation), or move the camera round to face them", most, MAX_TURN, "°"));
+ }
+ let (mx, my) = (SAFE * st.w, SAFE * st.h);
+ for (a, b) in lasting(&|s| s.whole && s.b.is_some_and(|b| b[0] < mx || b[1] < my || b[2] > st.w - mx || b[3] > st.h - my)) {
+ let f = st.finding("type-safe", Level::Warn, a, b, format!("the words '{name}' run outside the title-safe area from {} to {}", st.at(a), st.at(b)));
+ out.push(f.fix("move them in, or the camera back, so the whole block sits inside 5% of each edge"));
+ }
+ // its reveal: never started while it's in frame, or never finished before it goes (out of view with frames still
+ // stepped after: a still's few frames end, the words don't go); only over frames all stepped (stills far apart
+ // say nothing of what came between)
+ let in_view: Vec<&Seen> = seen.iter().filter(|s| in_frame(st, s.c)).collect();
+ if let (Some(f), Some(l)) = (in_view.first(), in_view.last()) && st.stepped(f.k, l.k) {
+ let long = st.secs(f.k, l.k) >= 1.0;
+ if *has_at && long && in_view.iter().all(|s| !s.shown) {
+ let f = st.finding("type-reveal", Level::Error, f.k, l.k, format!("the words '{name}' are never shown: their reveal (`at`) never starts while they're up, {} to {}", st.at(f.k), st.at(l.k)));
+ out.push(f.fix("give `at` in the frames of the Sequence they play in (useCurrentFrame), never a frame of another clock"));
+ } else if l.k + 1 < st.len() && in_view.iter().any(|s| s.shown) && !in_view.iter().any(|s| s.whole) {
+ let f = st.finding("type-reveal", Level::Error, f.k, l.k, format!("the words '{name}' never finish their reveal before they go ({} to {})", st.at(f.k), st.at(l.k)));
+ out.push(f.fix("start the reveal earlier, make it quicker (`each`), or keep the words up longer"));
+ }
+ }
+ // read: still, whole, big enough and facing the camera for their reading time, all told
+ let need = *words as f64 / 3.0 + 0.5;
+ let readable = up.windows(2).filter(|w| w[0].k + 1 == w[1].k && !st.cut[w[1].k] && readable(st, w[0], w[1], min_cap)).count() as f64 / st.fps;
+ if let (Some(f), Some(l)) = (up.first(), up.last()) && st.stepped(f.k, l.k) {
+ if readable + 1e-9 < need && up.iter().any(|s| s.whole) {
+ let f = st.finding("type-time", Level::Warn, f.k, l.k, format!("the words '{name}' can be read for {readable:.1} s; their {words} words need {need:.1} s (words ÷ 3 a second, plus 0.5 s)"));
+ out.push(fix(f, "hold them still, whole and facing the camera longer before they or the camera move", readable as f32, need as f32, "s"));
+ }
}
}
+ out
}
- out
}
fn in_frame(st: &Stage, c: [f32; 2]) -> bool {
diff --git a/tools/layers.toml b/tools/layers.toml
index 0b7b57f0..127c91b0 100644
--- a/tools/layers.toml
+++ b/tools/layers.toml
@@ -33,7 +33,6 @@ raea-io-gen-core = "io"
raea-io-gen-fit = "io"
raea-io-home = "io"
raea-io-codec = "io"
-raea-io-kept = "io"
raea-io-soft = "io"
raea-io-av1 = "io"
raea-io-ffmpeg = "io"
@@ -180,6 +179,7 @@ raea-runtime-sound = "runtime"
raea-runtime-view = "runtime"
raea-runtime-world = "runtime"
raea-runtime-encode = "runtime"
+raea-runtime-endchecks = "runtime"
raea-runtime-plugins = "runtime"
raea-runtime-live = "runtime"
raea-runtime-look = "runtime"