Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
DR4: a check is a system, and raea's own are written the same way. `raea check PROJECT|EDIT.tsx` runs every rule that applies to each composition: raea's floor on its newest render, the person's taste, and the workspace's and the project's controller rule fields. It reads the frames each check ranges over (all, cuts, lines, once or a list) into worlds once, runs raea's named checks in Rust (apps/direction systems.rs) and a project's .ts checks in the JS host (raea/check: check({ id, text, needs, level, frames }, (world, frame, values) => ...) and found(...), with the components' types generated from core/facts), and keeps the findings in the project's record. A check that needs a render and has none waits, and says what for; a check that throws, or a rule file raea can't read, is a finding. `raea check VIDEO.mp4` is the floor as before.
shinyobjectz973ee00accf3
diff --git a/Cargo.lock b/Cargo.lockindex a86199ce..d2fef105 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -13612,9 +13612,13 @@ dependencies = [name = "raea-app-direction"version = "0.1.0"dependencies = [+ "raea-app-check",+ "raea-app-registry",+ "raea-core-brief","raea-core-facts","raea-io-trace","raea-runtime-bundle",+ "raea-runtime-react","raea-runtime-world","serde_json",]@@ -13741,6 +13745,7 @@ dependencies = [name = "raea-app-workspace"version = "0.1.0"dependencies = [+ "raea-app-check","raea-app-registry","raea-core-brief","raea-core-facts",diff --git a/apps/check/src/lib.rs b/apps/check/src/lib.rsindex d9bfab1f..debd10f5 100644--- a/apps/check/src/lib.rs+++ b/apps/check/src/lib.rs@@ -40,18 +40,30 @@ struct Issue {/// `raea check …` with the person's taste, none or more (taste.ts and the kinds beside it, which the raea CLI evaluates: it owns the engine):/// its rules' checks hold the export to the person's own lines.pub fn cli_with(args: &[String], tastes: Vec<raea_core_brief::Taste>) -> i32 {- match run(args, tastes) {+ said(run(args, tastes), "REFUSED ")+}++/// A check's report printed, and its exit code: 1 when it found an error, 2 when it couldn't check (said after+/// `refused`). `raea check EDIT.tsx` (apps/direction) ends the same way.+pub fn said(ran: R<(String, bool)>, refused: &str) -> i32 {+ match ran {Ok((report, bad)) => {println!("{report}");i32::from(bad)}Err(e) => {- eprintln!("REFUSED {e}");+ eprintln!("{refused}{e}");2}}}+/// A command's words: its arguments that are neither flags nor a flag's value (`takes`: the flags that take one).+/// What `raea check` checks is its first; `raea workspace` and `raea project` read theirs the same way.+pub fn words<'a>(args: &'a [String], takes: &[&str]) -> Vec<&'a str> {+ args.iter().enumerate().filter(|(i, a)| !a.starts_with('-') && !(*i > 0 && takes.contains(&args[i - 1].as_str()))).map(|(_, a)| a.as_str()).collect()+}+fn flag<'a>(args: &'a [String], name: &str) -> Option<&'a str> {args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).map(String::as_str)}@@ -61,14 +73,14 @@ pub const USAGE: &str = "raea check VIDEO.mp4 [--manifest render.json] [--words/// A rule from the person's taste: a form raea can measure, its value, and the taste line it stands for.#[derive(Clone, Debug, PartialEq)]struct Taste {- form: String,+ form: &'static str,value: f64,line: String,}/// The checks among a person's taste rules (taste.ts and its kinds), each with the line it stands for.fn taste_rules(tastes: &[raea_core_brief::Taste]) -> Vec<Taste> {- tastes.iter().flat_map(|t| &t.sections).flat_map(|s| &s.rules).filter_map(|r| r.check.map(|c| Taste { form: c.form().to_string(), value: c.value(), line: r.text.clone() })).collect()+ tastes.iter().flat_map(|t| &t.sections).flat_map(|s| &s.rules).filter_map(|r| r.check.map(|c| Taste { form: c.form(), value: c.value(), line: r.text.clone() })).collect()}fn taste_of<'a>(rules: &'a [Taste], form: &str) -> Option<&'a Taste> {@@ -83,7 +95,7 @@ fn taste_text(rules: &[Taste], runs: &[Run], w: f64, h: f64, issues: &mut Vec<Isfor t in runs {let [x, y, bw, bh] = t.box_;let q = quote(&t.text);- let why = match r.form.as_str() {+ let why = match r.form {"text-hold" if t.to - t.from + 0.05 < r.value => Some(format!("{q} is on for {:.1} s, under your {:.1} s", t.to - t.from, r.value)),"text-above" if y + bh > h * r.value / 100.0 + 1.0 => Some(format!("{q} reaches {:.0}% down the frame, below your {:.0}%", (y + bh) / h * 100.0, r.value)),"text-below" if y < h * r.value / 100.0 - 1.0 => Some(format!("{q} starts {:.0}% down the frame, above your {:.0}%", y / h * 100.0, r.value)),@@ -95,7 +107,7 @@ fn taste_text(rules: &[Taste], runs: &[Run], w: f64, h: f64, issues: &mut Vec<Is};if let Some(why) = why {broke += 1;- issues.push(Issue { rule: "taste", p: 1, at: Some(t.from), says: format!("{why} (\"{}\")", r.line) });+ issues.push(Issue { rule: r.form, p: 1, at: Some(t.from), says: format!("{why} (\"{}\")", r.line) });}}if broke == 0 && r.form.starts_with("text-") {@@ -108,14 +120,28 @@ fn taste_text(rules: &[Taste], runs: &[Run], w: f64, h: f64, issues: &mut Vec<Isconst TAKES: [&str; 7] = ["--manifest", "--words", "--perception", "--shape", "--platform", "--taste", "-o"];fn run(args: &[String], tastes: Vec<raea_core_brief::Taste>) -> R<(String, bool)> {- let video = args.iter().enumerate().find(|(i, a)| !a.starts_with('-') && !(*i > 0 && TAKES.contains(&args[i - 1].as_str()))).map(|(_, a)| a.clone()).ok_or(USAGE)?;+ let (video, issues, passed, fps) = measured(args, taste_rules(&tastes))?;+ report(&video, issues, Vec::new(), passed, flag(args, "-o"), fps)+}++/// raea's floor on a video (`args` as raea check takes them) as Findings, printed and kept nowhere: `raea check+/// EDIT.tsx` runs it on the composition's newest render beside its other checks (apps/direction, DR4). `held`: the+/// rules of the named checks it measures on the video itself (loudness, still-max), each its form, value and line.+pub fn floor(args: &[String], held: &[(&'static str, f64, String)]) -> R<Vec<Finding>> {+ let held = held.iter().map(|(form, value, line)| Taste { form: *form, value: *value, line: line.clone() }).collect();+ let (_, issues, _, fps) = measured(args, held)?;+ Ok(findings_of(issues, Vec::new(), fps))+}++/// The video's issues and what passed, measured, and its frame rate.+fn measured(args: &[String], taste: Vec<Taste>) -> R<(String, Vec<Issue>, Vec<String>, f64)> {+ let video = words(args, &TAKES).first().map(|v| v.to_string()).ok_or(USAGE)?;if !std::path::Path::new(&video).exists() {return Err(format!("no file at {video}\n{USAGE}"));}let probe = Probe::of(&video)?;let mut issues = Vec::new();let mut passed = Vec::new();- let taste = taste_rules(&tastes);let manifest: Option<Value> = match flag(args, "--manifest") {Some(m) => Some(serde_json::from_str(&std::fs::read_to_string(m).map_err(|e| format!("{m}: {e}"))?).map_err(|e| format!("{m}: {e}"))?),None => None,@@ -144,16 +170,14 @@ fn run(args: &[String], tastes: Vec<raea_core_brief::Taste>) -> R<(String, bool)face_cover(&runs, &faces, &mut issues, &mut passed);}}-- report(&video, issues, Vec::new(), passed, flag(args, "-o"), fps)+ Ok((video, issues, passed, fps))}/// The issues as Findings (docs/direction.feature DR3: P0 and P1 errors, P2 a warn, P3 a note; a time is its frame at-/// `fps`), with `more` (a render's own), worst first then by time; written to -o as JSON when asked, and the report's-/// text with the count last. True when an error is among them.-fn report(video: &str, mut issues: Vec<Issue>, more: Vec<Finding>, passed: Vec<String>, out: Option<&str>, fps: f64) -> R<(String, bool)> {+/// `fps`), with `more` (a render's own), worst first then by time.+fn findings_of(mut issues: Vec<Issue>, more: Vec<Finding>, fps: f64) -> Vec<Finding> {issues.sort_by(|a, b| a.p.cmp(&b.p).then(a.at.unwrap_or(0.0).total_cmp(&b.at.unwrap_or(0.0))));- let found = finding::ranked(+ finding::ranked(issues.iter().map(|i| {@@ -169,7 +193,13 @@ fn report(video: &str, mut issues: Vec<Issue>, more: Vec<Finding>, passed: Vec<S}).chain(more).collect(),- );+ )+}++/// The findings (`findings_of`), written to -o as JSON when asked, and the report's text with the count last. True+/// when an error is among them.+fn report(video: &str, issues: Vec<Issue>, more: Vec<Finding>, passed: Vec<String>, out: Option<&str>, fps: f64) -> R<(String, bool)> {+ let found = findings_of(issues, more, fps);let bad = found.iter().any(|f| f.level == Level::Error);if let Some(out) = out {let j = json!({"file": video, "fps": fps, "findings": found, "passed": passed});diff --git a/apps/check/src/sound.rs b/apps/check/src/sound.rsindex e10b6d78..0e06cc7b 100644--- a/apps/check/src/sound.rs+++ b/apps/check/src/sound.rs@@ -214,7 +214,7 @@ pub(crate) fn loudness(video: &str, taste: Option<&Taste>, issues: &mut Vec<Issuok = false;let says = format!("{i:.1} LUFS integrated; master at {target} (±1) with <Mix lufs={{{target}}} />");issues.push(match taste {- Some(t) => Issue { rule: "taste", p: 1, at: None, says: format!("{says} (\"{}\")", t.line) },+ Some(t) => Issue { rule: t.form, p: 1, at: None, says: format!("{says} (\"{}\")", t.line) },None => Issue { rule: "loudness", p: 1, at: None, says },});}@@ -256,7 +256,7 @@ pub(crate) fn freezes(video: &str, probe: &Probe, taste: Option<&Taste>, issues:for &(s, d) in &stretches {let says = format!("nothing changes for {d:.1} s; give it a reason to hold, or cut it shorter");issues.push(match taste {- Some(t) => Issue { rule: "taste", p: 1, at: Some(s), says: format!("{says} (\"{}\")", t.line) },+ Some(t) => Issue { rule: t.form, p: 1, at: Some(s), says: format!("{says} (\"{}\")", t.line) },None => Issue { rule: "frozen", p: if d >= 6.0 || d >= probe.duration * 0.5 { 1 } else { 2 }, at: Some(s), says },});}diff --git a/apps/check/src/tests.rs b/apps/check/src/tests.rsindex f4797b5a..496c69bc 100644--- a/apps/check/src/tests.rs+++ b/apps/check/src/tests.rs@@ -64,8 +64,8 @@ fn taste_checks_hold_text_to_the_persons_line() {]}]})).unwrap();let rules = taste_rules(&[taste]);assert_eq!(rules, vec![- Taste { form: "text-above".into(), value: 62.0, line: "Captions sit clear of the bottom.".into() },- Taste { form: "text-hold".into(), value: 2.0, line: "Text holds two seconds".into() },+ Taste { form: "text-above", value: 62.0, line: "Captions sit clear of the bottom.".into() },+ Taste { form: "text-hold", value: 2.0, line: "Text holds two seconds".into() },]);let low = Run { text: "Render anything.".into(), from: 1.0, to: 4.0, box_: [800.0, 800.0, 300.0, 60.0], boxes: vec![[800.0, 800.0, 300.0, 60.0]], color: String::new(), size: 48.0 };let high = Run { text: "raea".into(), from: 5.0, to: 6.0, box_: [800.0, 300.0, 300.0, 60.0], boxes: vec![[800.0, 300.0, 300.0, 60.0]], color: String::new(), size: 48.0 };@@ -73,7 +73,7 @@ fn taste_checks_hold_text_to_the_persons_line() {taste_text(&rules, &[low, high], 1920.0, 1080.0, &mut issues, &mut passed);let says: Vec<_> = issues.iter().map(|i| (i.rule, i.p, i.at)).collect();// the low caption breaks the placement line (860 of 1080 is 80%); the short one breaks the hold- assert_eq!(says, vec![("taste", 1, Some(1.0)), ("taste", 1, Some(5.0))]);+ assert_eq!(says, vec![("text-above", 1, Some(1.0)), ("text-hold", 1, Some(5.0))], "a taste line is the named check of its form (DR4)");}/// `RAEA_CHECK_ARGS="film.mp4 --manifest film.render.json --taste DIR" cargo test -p raea-runtime-react --libdiff --git a/apps/direction/Cargo.toml b/apps/direction/Cargo.tomlindex a1090a54..c7ddace8 100644--- a/apps/direction/Cargo.toml+++ b/apps/direction/Cargo.toml@@ -13,3 +13,10 @@ raea-core-facts = { path = "../../core/facts" }# a render's record named by when it was (UTC)raea-io-trace = { path = "../../io/trace" }serde_json = "1"+# `raea check PROJECT | EDIT.tsx` (DR4): taste and controllers' rules, the floor on a composition's newest render, the+# project's compositions+raea-core-brief = { path = "../../core/brief" }+raea-app-check = { path = "../check" }+raea-app-registry = { path = "../workspace/registry" }+# a TS check's run printing nothing to the terminal (its ECHO)+raea-runtime-react = { path = "../../runtime/react", default-features = false }diff --git a/apps/direction/src/check.rs b/apps/direction/src/check.rsnew file mode 100644index 00000000..32dd6c74--- /dev/null+++ b/apps/direction/src/check.rs@@ -0,0 +1,302 @@+//! `raea check PROJECT|EDIT.tsx` (docs/direction.feature DR4): every check that applies, run over each+//! composition's worlds. The rules come from raea's floor, the person's taste (and the workspace's), and the+//! workspace's and the project's controllers; each is one of raea's named checks (systems.rs) or a project's TS check+//! (ts.rs), and where it was written changes nothing about how it runs. A check that needs a render runs on the+//! composition's newest render; with none, it waits, and the command says what for. `raea check VIDEO.mp4` is the+//! floor alone (apps/check).++use std::path::{Path, PathBuf};++use raea_core_brief::{controller, taste};+use raea_core_facts::{finding, record, Facts, Finding, Level, Rule};+use raea_runtime_bundle::flag;+use raea_runtime_world::{Ask, Render};+use serde_json::{json, Value};++use crate::systems::{self, Frames};+use crate::ts;++type R<T> = Result<T, String>;++pub const USAGE: &str = "raea check [PROJECT|EDIT.tsx] [--composition ID] [--only ID] [--taste T] [--render OUT | --no-render] [--json] (every check that applies to each composition, over its frames: raea's floor on its newest render, the person's taste, the workspace's and the project's rules (a controller's rule fields: one of raea's checks by name, or a project's .ts check); what needs a render and has none waits, and says so)";++/// The flags raea check takes with a value (its own, and the floor's on a video).+const TAKES: [&str; 10] = ["--composition", "--only", "--taste", "--render", "--manifest", "--words", "--perception", "--shape", "--platform", "-o"];++/// What the CLI lends `raea check`: its TS evaluator and headless run, and the taste kinds a mode needs (as `raea+/// context` reads the person's taste).+pub struct Host {+ pub ts: ts::Host,+ pub kinds: fn(&str) -> &'static [&'static str],+}++/// The person's taste folder: RAEA_TASTE, else ~/.raea/taste.+pub fn taste_dir() -> Option<PathBuf> {+ std::env::var_os("RAEA_TASTE").map(PathBuf::from).or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".raea/taste")))+}++/// The .ts files `--taste` names: the file, or every .ts in the folder.+pub fn taste_files(args: &[String]) -> Vec<PathBuf> {+ let Some(t) = flag(args, "--taste").map(PathBuf::from) else { return vec![] };+ if t.extension().is_some_and(|x| x == "ts") {+ return vec![t];+ }+ let mut v: Vec<PathBuf> = std::fs::read_dir(&t).into_iter().flatten().filter_map(|e| e.ok().map(|e| e.path())).filter(|f| f.extension().is_some_and(|x| x == "ts")).collect();+ v.sort();+ v+}++/// The taste files a project is held to: `--taste`'s when given, else the person's taste.ts (RAEA_TASTE, or+/// ~/.raea/taste) and the kinds its brief's modes need, then the workspace's house rules.+fn tastes(project: &Path, given: Vec<PathBuf>, host: &Host) -> Vec<PathBuf> {+ if !given.is_empty() {+ return given;+ }+ let mut out = Vec::new();+ if let Some(dir) = taste_dir().filter(|d| d.join("taste.ts").is_file()) {+ out.push(dir.join("taste.ts"));+ let brief: Value = (host.ts.eval)(&project.join("brief.ts")).ok().and_then(|j| serde_json::from_str(&j).ok()).unwrap_or_default();+ for m in brief["mode"].as_array().into_iter().flatten().filter_map(Value::as_str) {+ for f in (host.kinds)(&m.trim().to_ascii_lowercase()).iter().map(|k| dir.join(format!("{k}.ts"))) {+ if f.is_file() && !out.contains(&f) {+ out.push(f);+ }+ }+ }+ }+ out.extend(record::up(project, ".raea/workspace").map(|ws| ws.join("taste.ts")).filter(|f| f.is_file()));+ out+}++/// One rule as it runs: a named check, or a project's check file's declaration.+enum How {+ Named(systems::Named),+ File(ts::Meta),+}++/// Every rule `project` is held to (`given`: `--taste`'s files), and a finding for each file of rules raea couldn't+/// read.+fn rules(project: &Path, given: Vec<PathBuf>, host: &Host) -> (Vec<Rule>, Vec<Finding>) {+ let mut out = vec![Rule::named("floor", "raea's floor", Default::default(), Level::Error, "raea")];+ let mut bad = Vec::new();+ let name = |f: &Path| f.strip_prefix(project).unwrap_or(f).display().to_string();+ for f in tastes(project, given, host) {+ match (host.ts.eval)(&f).and_then(|j| raea_core_brief::read::<taste::Taste>(&name(&f), &j)) {+ Ok(t) => out.extend(t.sections.iter().flat_map(|s| &s.rules).filter_map(|r| Some(Rule::of_taste(&r.text, r.check?, &name(&f))))),+ Err(e) => bad.push(Finding::new("taste", Level::Error, format!("raea can't read it: {e}"), "raea check").about(name(&f), None)),+ }+ }+ let ws = record::up(project, ".raea/workspace");+ for (dir, scope) in ws.iter().map(|w| (w.join("controllers"), "workspace")).chain([(project.join("controllers"), "project")]) {+ // a workspace's own folder is its project's too: read once+ if scope == "project" && ws.as_deref() == Some(project) {+ continue;+ }+ let mut files: Vec<PathBuf> = std::fs::read_dir(&dir).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "ts")).collect();+ files.sort();+ for f in files {+ match (host.ts.eval)(&f).and_then(|j| controller::of_json(&j)) {+ // a check's path made plain (no `..`), as its import will name it+ Ok(c) => out.extend(Rule::of_controller(&c, &dir, &format!("{scope} {}", name(&f))).into_iter().map(|r| match r.file() {+ Some(p) => Rule { check: raea_runtime_bundle::normalize(p).display().to_string(), ..r },+ None => r,+ })),+ Err(e) => bad.push(Finding::new("controller", Level::Error, format!("raea can't read it: {e}"), "raea check").about(name(&f), None)),+ }+ }+ }+ (out, bad)+}++/// The compositions `target` names: each (its file, its id when the file registers several).+fn compositions(target: &Path, args: &[String]) -> R<Vec<(PathBuf, Option<String>)>> {+ let one = flag(args, "--composition");+ let (dir, file) = if target.is_dir() { (target.to_path_buf(), None) } else { (target.parent().unwrap_or(Path::new(".")).to_path_buf(), Some(target.canonicalize().map_err(|e| format!("{}: {e}", target.display()))?)) };+ let reg = raea_app_registry::scan(&dir, &[]);+ let mut out: Vec<(PathBuf, Option<String>)> = Vec::new();+ for c in ®.compositions {+ let path = reg.dir.join(&c.file);+ let path = path.canonicalize().unwrap_or(path);+ let id = (c.how == raea_app_registry::How::Registered).then(|| c.id.clone());+ if file.as_ref().is_none_or(|f| *f == path) && one.as_ref().is_none_or(|o| Some(o) == id.as_ref()) {+ out.push((path, id));+ }+ }+ if out.is_empty() {+ match (file, one) {+ // a file the scan didn't register (outside a project): itself+ (Some(f), one) => out.push((f, one)),+ (None, one) => return Err(format!("no composition in {}{}", dir.display(), one.map(|o| format!(" named {o}")).unwrap_or_default())),+ }+ }+ Ok(out)+}++/// What one composition's checks found, and each check that waits, with what for.+struct Checked {+ file: PathBuf,+ id: Option<String>,+ found: Vec<Finding>,+ waits: Vec<(String, String)>,+}++/// One composition checked against `rules` (`--only`'s already picked).+fn check_one(tsx: &Path, id: Option<String>, rules: &[Rule], args: &[String], host: &Host) -> R<Checked> {+ let named = systems::named();+ let mut found = Vec::new();+ let mut hows = Vec::new();+ for r in rules {+ match r.file() {+ Some(f) => match ts::meta(f, &host.ts) {+ Ok(m) => hows.push((r, How::File(m))),+ Err(e) => found.push(Finding::new(&r.id, Level::Error, e, &r.by)),+ },+ None => match named.iter().find(|n| n.name == r.check) {+ Some(n) => hows.push((r, How::Named(n.clone()))),+ None => found.push(Finding::new(&r.id, Level::Error, format!("raea has no check named {} (its checks: {}, or a .ts check's path)", r.check, named.iter().map(|n| n.name).collect::<Vec<_>>().join(", ")), &r.by)),+ },+ }+ }+ let frames: Vec<&Frames> = hows.iter().map(|(_, h)| match h { How::Named(n) => &n.frames, How::File(m) => &m.frames }).collect();+ // every frame when a check ranges over them (cuts and lines are found in them), else the frames named and the first+ let whole = frames.iter().any(|f| f.whole());+ let mut asked: Vec<i64> = if whole { Vec::new() } else { frames.iter().flat_map(|f| if let Frames::At(v) = f { v.clone() } else { vec![] }).chain([0]).collect() };+ asked.sort();+ asked.dedup();+ // the render joins the first frame (what it is, or that there is none) and where a TS check needs it+ let join_all = hows.iter().any(|(_, h)| matches!(h, How::File(m) if m.render && m.frames.whole()));+ let join_on = (!join_all).then(|| hows.iter().flat_map(|(_, h)| match h { How::File(m) if m.render => if let Frames::At(v) = &m.frames { v.clone() } else { vec![] }, _ => vec![] }).chain([0]).collect());+ let render_how = match (flag(args, "--render"), args.iter().any(|a| a == "--no-render")) {+ (Some(o), _) => Render::From(o.into()),+ (None, true) => Render::Off,+ (None, false) => Render::Newest,+ };+ let mut opts_args = vec![tsx.display().to_string()];+ if let Some(i) = &id {+ opts_args.extend(["--composition".to_string(), i.clone()]);+ }+ let opts = raea_runtime_bundle::comp_opts(&opts_args)?;+ let worlds = raea_runtime_world::read(tsx, &opts, &Ask { frames: asked, layout: true, render: render_how, join_on })?;+ let rendered = worlds.first().and_then(|w| w.resources.get("Rendered")).cloned();+ let mut waits = Vec::new();+ let needs = |w: &mut Vec<(String, String)>, r: &Rule| w.push((r.id.clone(), "a render (raea render EDIT.tsx)".into()));+ if let Some(r) = rendered.as_ref().filter(|r| r["stale"] == true) {+ found.push(Finding::new("render", Level::Note, "the newest render is older than the composition's last change: what it measured may have moved", "raea check").about(r["out"].as_str().unwrap_or("").to_string(), None));+ }+ // raea's named checks: the text forms over every frame; the floor (and the loudness and stillness it measures) on the render+ // the forms the floor measures on the video (each its form, value and line), and where each was written+ let (mut held, mut bys) = (Vec::new(), Vec::new());+ let mut floor = false;+ for (r, h) in &hows {+ let How::Named(n) = h else { continue };+ match n.name {+ "floor" => floor = true,+ "loudness" | "still-max" => {+ held.push((n.name, r.number("value").unwrap_or(if n.name == "loudness" { -14.0 } else { 3.0 }), r.text.clone()));+ bys.push(r.by.clone());+ }+ _ => found.extend(systems::text(r, &worlds)),+ }+ }+ if floor || !held.is_empty() {+ match &rendered {+ Some(r) if is_video(r["out"].as_str().unwrap_or("")) => {+ let a = [r["out"].as_str().unwrap_or("").to_string(), "--manifest".into(), r["manifest"].as_str().unwrap_or("").to_string()];+ for mut f in raea_app_check::floor(&a, &held)? {+ match held.iter().position(|h| h.0 == f.check) {+ Some(k) => f.by = bys[k].clone(),+ None if !floor => continue,+ None => f.by = "raea".into(),+ }+ found.push(f);+ }+ }+ Some(_) => waits.extend(hows.iter().filter(|(_, h)| matches!(h, How::Named(n) if n.render)).map(|(r, _)| (r.id.clone(), "a video render (its render is stills)".to_string()))),+ None => hows.iter().filter(|(_, h)| matches!(h, How::Named(n) if n.render)).for_each(|(r, _)| needs(&mut waits, r)),+ }+ }+ // the project's own checks, in one run+ let mut files: Vec<PathBuf> = Vec::new();+ let mut plan = Vec::new();+ for (r, h) in &hows {+ let How::File(m) = h else { continue };+ if m.render && rendered.is_none() {+ needs(&mut waits, r);+ continue;+ }+ let k = files.iter().position(|f| *f == m.file).unwrap_or_else(|| {+ files.push(m.file.clone());+ files.len() - 1+ });+ let mut on = m.frames.pick(&worlds);+ if let (true, Some(j)) = (m.render, &join_on_of(&worlds)) {+ on.retain(|f| j.contains(f));+ }+ plan.push(ts::Planned { check: k, frames: on, values: r.values.clone(), level: r.level, by: r.by.clone() });+ }+ found.extend(ts::run(&files, &plan, &worlds, &host.ts)?);+ Ok(Checked { file: tsx.to_path_buf(), id, found: finding::ranked(found), waits })+}++/// The frames the render joined (each with what it rendered, or says it waits), or None when it joined none.+fn join_on_of(worlds: &[Facts]) -> Option<Vec<i64>> {+ let on: Vec<i64> = worlds.iter().filter(|w| w.resources.contains_key("Rendered")).map(|w| w.frame).collect();+ (!on.is_empty()).then_some(on)+}++/// Whether `raea check`'s arguments name a file that isn't a composition (a video, a still: the floor alone, apps/check)+/// rather than a project, a folder or an EDIT.tsx.+pub fn of_video(args: &[String]) -> bool {+ raea_app_check::words(args, &TAKES).first().is_some_and(|a| !a.ends_with(".tsx") && !Path::new(a).is_dir())+}++fn is_video(out: &str) -> bool {+ Path::new(out).extension().and_then(|x| x.to_str()).is_some_and(|x| matches!(x.to_ascii_lowercase().as_str(), "mp4" | "mov"))+}++/// `raea check PROJECT|EDIT.tsx ...`: the report, and whether an error is among what it found.+pub fn check(args: &[String], host: &Host) -> R<(String, bool)> {+ let target = raea_app_check::words(args, &TAKES).first().map_or_else(|| PathBuf::from("."), PathBuf::from);+ // the folder it is in, made whole (`lyric.tsx`'s is the empty path): a rule's check is a path from it+ let here = if target.is_dir() { target.clone() } else { target.parent().filter(|p| !p.as_os_str().is_empty()).map_or_else(|| PathBuf::from("."), Path::to_path_buf) };+ let here = here.canonicalize().map_err(|e| format!("{}: {e}", here.display()))?;+ let project = record::up(&here, ".raea/project").unwrap_or(here);+ let (mut rules, unread) = rules(&project, taste_files(args), host);+ if let Some(only) = flag(args, "--only") {+ rules.retain(|r| r.id == only);+ if rules.is_empty() {+ return Err(format!("--only {only}: no rule here has that id"));+ }+ }+ let mut all = Vec::new();+ for (tsx, id) in compositions(&target, args)? {+ all.push(check_one(&tsx, id, &rules, args, host)?);+ }+ let stamp = raea_io_trace::utc(std::time::SystemTime::now()).1;+ let mut bad = unread.iter().any(|f| f.level == Level::Error);+ if args.iter().any(|a| a == "--json") {+ let v: Vec<Value> = all.iter().map(|c| json!({"file": c.file, "composition": c.id, "findings": c.found, "waits": c.waits.iter().map(|(r, w)| json!({"rule": r, "for": w})).collect::<Vec<_>>()})).collect();+ bad |= all.iter().any(|c| c.found.iter().any(|f| f.level == Level::Error));+ return Ok((serde_json::to_string_pretty(&json!({"unread": unread, "compositions": v})).unwrap_or_default(), bad));+ }+ let mut out: Vec<String> = unread.iter().map(Finding::line).collect();+ let mut every = unread.clone();+ for c in &all {+ out.push(format!("raea check {}{}", c.file.display(), c.id.as_ref().map(|i| format!(" ({i})")).unwrap_or_default()));+ out.extend(c.found.iter().map(Finding::line));+ out.extend(c.waits.iter().map(|(r, w)| format!("waits {r}: needs {w}")));+ // kept in its project's record (DR3), what raea findings and raea next read+ if let Some(e) = record::keep("raea check", &c.file, None, &c.found, vec![], &stamp) {+ out.push(format!("raea check: kept in the project's record as {} (raea findings reads it)", e.id));+ }+ bad |= c.found.iter().any(|f| f.level == Level::Error);+ every.extend(c.found.iter().cloned());+ }+ out.push(format!("raea check: {}", finding::count(&every)));+ Ok((out.join("\n"), bad))+}++/// `raea check ...`: its exit code (1 on an error found, 2 when it couldn't check).+pub fn cli(args: &[String], host: &Host) -> i32 {+ raea_app_check::said(check(args, host), "raea check: ")+}diff --git a/apps/direction/src/lib.rs b/apps/direction/src/lib.rsindex 236e1a2a..19fc533c 100644--- a/apps/direction/src/lib.rs+++ b/apps/direction/src/lib.rs@@ -10,3 +10,8 @@ pub use rendered::rendered;// `raea findings`: the project's record read back, fixed, new and carried (DR3)pub mod findings;++// `raea check PROJECT | EDIT.tsx`: every rule's check, raea's named ones and a project's TS ones, over the worlds (DR4)+pub mod check;+pub mod systems;+pub mod ts;diff --git a/apps/direction/src/systems.rs b/apps/direction/src/systems.rsnew file mode 100644index 00000000..4c46a1e9--- /dev/null+++ b/apps/direction/src/systems.rs@@ -0,0 +1,178 @@+//! raea's own checks by name (docs/direction.feature DR4): each a system over a composition's worlds, held to its+//! rule's values, as a project's TS check is (sdk/raea/src/check.ts). Taste's six forms are six of them, with the same+//! names and values: the four text forms run over every frame's Text with no render; loudness and still-max are+//! measured on the newest render itself, in the floor's pass (`floor`: raea check's floor on that render).++use std::collections::BTreeMap;++use raea_core_facts::{Facts, Finding, Rule, Source, Text};++/// Where a check runs: every frame; the frame before each cut and the cut's first frame; every frame a line is+/// said or sung on; once, on the first frame; or these.+#[derive(Debug, Clone, PartialEq)]+pub enum Frames {+ All,+ Cuts,+ Lines,+ Once,+ At(Vec<i64>),+}++impl Frames {+ /// As a check file declares it ("all", "cuts", "lines", "once" or a list of frames).+ pub fn of(v: &serde_json::Value) -> Result<Frames, String> {+ match v {+ serde_json::Value::Null => Ok(Frames::All),+ serde_json::Value::String(s) => match s.as_str() {+ "all" => Ok(Frames::All),+ "cuts" => Ok(Frames::Cuts),+ "lines" => Ok(Frames::Lines),+ "once" => Ok(Frames::Once),+ o => Err(format!("frames is \"all\", \"cuts\", \"lines\", \"once\" or a list of frames, not \"{o}\"")),+ },+ serde_json::Value::Array(a) => a.iter().map(|f| f.as_i64().ok_or("frames lists frame numbers")).collect::<Result<_, _>>().map(Frames::At).map_err(str::to_string),+ o => Err(format!("frames is \"all\", \"cuts\", \"lines\", \"once\" or a list of frames, not {o}")),+ }+ }++ /// Whether running here needs the frames of the whole piece read (cuts and lines are found in them).+ pub fn whole(&self) -> bool {+ matches!(self, Frames::All | Frames::Cuts | Frames::Lines)+ }++ /// The frames of `worlds` (every frame read, in order) it runs on.+ pub fn pick(&self, worlds: &[Facts]) -> Vec<i64> {+ let first = worlds.first().map_or(0, |w| w.frame);+ match self {+ Frames::All => worlds.iter().map(|w| w.frame).collect(),+ Frames::Once => vec![first],+ Frames::At(v) => v.clone(),+ Frames::Lines => worlds.iter().filter(|w| !w.find(&["Line"]).is_empty()).map(|w| w.frame).collect(),+ Frames::Cuts => {+ let mut cuts: Vec<i64> = worlds.iter().flat_map(|w| w.find(&["Shot"]).into_iter().filter_map(|e| e.components["Shot"]["from"].as_i64())).filter(|f| *f > first).collect();+ cuts.sort();+ cuts.dedup();+ cuts.into_iter().flat_map(|c| [c - 1, c]).collect()+ }+ }+ }+}++/// One of raea's checks: its name, whether it needs a render, where it runs, and its line when no rule gives one.+#[derive(Debug, Clone)]+pub struct Named {+ pub name: &'static str,+ pub render: bool,+ pub frames: Frames,+ pub text: &'static str,+}++/// raea's named checks.+pub fn named() -> Vec<Named> {+ let n = |name, render, frames, text| Named { name, render, frames, text };+ vec![+ n("text-hold", false, Frames::All, "text holds long enough to read"),+ n("text-above", false, Frames::All, "text sits above a line down the frame"),+ n("text-below", false, Frames::All, "text sits below a line down the frame"),+ n("text-margin", false, Frames::All, "text keeps a margin from the frame's edges"),+ n("loudness", true, Frames::Once, "the mix is at its loudness"),+ n("still-max", true, Frames::Once, "the picture is never still for too long"),+ n("floor", true, Frames::Once, "raea's floor: what every finished piece must meet"),+ ]+}++/// A text's identity across frames: its layer key, else its words.+fn ident(f: &Facts, e: u32, t: &Text) -> (String, Option<String>) {+ let key = f.get::<Source>(e).and_then(|s| s.key);+ (key.clone().unwrap_or_else(|| t.words.clone()), key)+}++/// A run of frames on which one text measures past its rule: the text, its key, the frames (end exclusive) and the+/// worst measure in the run.+#[derive(Debug, Clone, PartialEq)]+pub struct Run {+ pub words: String,+ pub key: Option<String>,+ pub from: i64,+ pub to: i64,+ pub value: f64,+}++/// Each text's runs of frames on which `bad` gives a measure, the worst of each run by `worse`.+fn runs(worlds: &[Facts], bad: impl Fn(&Facts, &Text) -> Option<f64>, worse: fn(f64, f64) -> bool) -> Vec<Run> {+ let mut open: BTreeMap<String, Run> = BTreeMap::new();+ let mut done = Vec::new();+ for w in worlds {+ for e in w.find(&["Text"]) {+ let Some(t) = w.get::<Text>(e.id) else { continue };+ let Some(v) = bad(w, &t) else { continue };+ let (id, key) = ident(w, e.id, &t);+ match open.get_mut(&id) {+ Some(r) if r.to == w.frame => {+ r.to = w.frame + 1;+ if worse(v, r.value) {+ r.value = v;+ }+ }+ _ => {+ if let Some(r) = open.insert(id, Run { words: t.words.clone(), key, from: w.frame, to: w.frame + 1, value: v }) {+ done.push(r);+ }+ }+ }+ }+ }+ done.extend(open.into_values());+ done.sort_by_key(|r| (r.from, r.words.clone()));+ done+}++fn quote(s: &str) -> String {+ let s: String = s.split_whitespace().collect::<Vec<_>>().join(" ");+ if s.chars().count() > 40 { format!("\"{}…\"", s.chars().take(39).collect::<String>()) } else { format!("\"{s}\"") }+}++/// A text form's findings over `worlds` (every frame of the composition, in order), held to `rule`'s `value`.+pub fn text(rule: &Rule, worlds: &[Facts]) -> Vec<Finding> {+ let level = rule.level.unwrap_or(raea_core_facts::Level::Error);+ let Some(v) = rule.number("value") else {+ return vec![Finding::new(&rule.id, level, format!("{} needs a value (values: {{ value: N }})", rule.check), &rule.by)];+ };+ let Some(first) = worlds.first() else { return Vec::new() };+ let (w, h, fps) = (first.width as f64, first.height as f64, first.fps);+ // the runs of text past the line across the frame at `v`%: by its edge `k` (1 its top, 3 its bottom), below the+ // line (`down`) or above it+ let past = |k: usize, down: bool| {+ let worse: fn(f64, f64) -> bool = if down { |a, b| a > b } else { |a, b| a < b };+ // a pixel past it, so text that only touches the line holds it+ let line = v + (if down { 100.0 } else { -100.0 }) / h;+ runs(worlds, move |_, t| t.box_.map(|b| b[k] * 100.0).filter(|y| worse(*y, line)), worse)+ };+ // the runs that break the form, each with its measure as its value; what's said of one ({n} its measure, {v} the+ // rule's); and the unit+ let (got, says, unit): (Vec<Run>, &str, &str) = match rule.check.as_str() {+ "text-hold" => {+ let on = runs(worlds, |_, _| Some(0.0), |_, _| false).into_iter().map(|r| Run { value: (r.to - r.from) as f64 / fps, ..r });+ (on.filter(|r| r.value + 0.05 < v).collect(), "is on for {n} s, under {v} s", "s")+ }+ "text-above" => (past(3, true), "reaches {n}% down the frame, below {v}%", "%"),+ "text-below" => (past(1, false), "starts {n}% down the frame, above {v}%", "%"),+ "text-margin" => {+ let s = w.min(h) / 1080.0;+ let margin = move |b: [f64; 4]| (b[0] * w).min(b[1] * h).min(w - b[2] * w).min(h - b[3] * h) / s;+ (runs(worlds, |_, t| t.box_.map(margin).filter(|m| m + 1.0 < v), |a, b| a < b), "is {n} px from the edge, inside {v}", "px")+ }+ other => return vec![Finding::new(&rule.id, level, format!("{other} isn't a text check"), &rule.by)],+ };+ let shown = |x: f64| if unit == "s" { format!("{x:.1}") } else { format!("{x:.0}") };+ got.iter()+ .map(|r| {+ let said = format!("{} {}", quote(&r.words), says.replace("{n}", &shown(r.value)).replace("{v}", &shown(v)));+ let said = if rule.text.is_empty() { said } else { format!("{said} (\"{}\")", rule.text) };+ Finding::new(&rule.id, level, said, &rule.by).about(r.words.clone(), r.key.clone()).frames(r.from, r.to).measure(&rule.check, (r.value * 10.0).round() / 10.0, unit, Some(v))+ })+ .collect()+}++#[cfg(test)]+mod tests;diff --git a/apps/direction/src/systems/tests.rs b/apps/direction/src/systems/tests.rsnew file mode 100644index 00000000..b3efd8fd--- /dev/null+++ b/apps/direction/src/systems/tests.rs@@ -0,0 +1,75 @@+use super::*;+use raea_core_facts::{Level, Shot};+use serde_json::{json, Map, Value};++/// Frames 0..n of a 1080x1920 piece at 30 fps, each holding the texts `on(frame)` gives (words, box).+fn piece(n: i64, on: impl Fn(i64) -> Vec<(&'static str, [f64; 4])>) -> Vec<Facts> {+ (0..n)+ .map(|f| {+ let mut w = Facts::new(f, 1080, 1920, 30.0);+ for (words, b) in on(f) {+ let e = w.spawn(None);+ w.put(e, &Text { words: words.into(), font: None, size: Some(64.0), box_: Some(b), extruded: 0.0, lines: Some(1), needs: None });+ }+ w+ })+ .collect()+}++fn rule(check: &str, v: f64) -> Rule {+ Rule::named(check, "", Map::from_iter([("value".to_string(), Value::from(v))]), Level::Error, "taste taste.ts")+}++#[test]+fn a_text_on_too_briefly_is_found_once_over_its_frames() {+ // "GO" is on frames 10 to 24 (half a second), "STAY" all 90+ let w = piece(90, |f| {+ let mut v = vec![("STAY", [0.1, 0.1, 0.9, 0.2])];+ if (10..25).contains(&f) {+ v.push(("GO", [0.1, 0.5, 0.9, 0.6]));+ }+ v+ });+ let got = text(&rule("text-hold", 2.0), &w);+ assert_eq!(got.len(), 1, "{got:?}");+ assert_eq!((got[0].frames, got[0].about[0].name.as_str()), (Some([10, 25]), "GO"));+ assert!(got[0].says.starts_with("\"GO\" is on for 0.5 s, under 2.0 s"), "{}", got[0].says);+ assert_eq!(got[0].measure.as_ref().map(|m| (m.value, m.limit)), Some((0.5, Some(2.0))));+}++#[test]+fn placement_and_margin_name_the_worst_frame_of_a_run() {+ // a caption whose bottom slides down from 70% to 85% over frames 0 to 30+ let w = piece(31, |f| vec![("SALE", [0.2, 0.6, 0.8, 0.70 + 0.005 * f as f64])]);+ let above = text(&rule("text-above", 80.0), &w);+ assert_eq!(above.len(), 1);+ assert_eq!(above[0].frames, Some([21, 31]), "past 80% from frame 21: {above:?}");+ assert!(above[0].says.contains("reaches 85% down the frame, below 80%"), "{}", above[0].says);+ assert!(text(&rule("text-below", 50.0), &w).is_empty(), "it starts at 60%, below 50%");+ // 0.2 of 1080 is 216 px from the left and right; the bottom is 0.15 of 1920 = 288 px at its lowest+ assert!(text(&rule("text-margin", 200.0), &w).is_empty());+ assert_eq!(text(&rule("text-margin", 250.0), &w).len(), 1);+}++#[test]+fn a_rule_with_no_value_says_so() {+ let r = Rule { level: Some(Level::Warn), ..Rule::named("text-hold", "", Map::new(), Level::Error, "project controllers/rules.ts") };+ let got = text(&r, &piece(3, |_| vec![]));+ assert_eq!((got.len(), got[0].level), (1, Level::Warn));+ assert!(got[0].says.contains("needs a value"));+}++#[test]+fn cuts_are_the_frame_before_and_the_first_frame_of_each_shot_after_the_first() {+ let mut w = piece(60, |_| vec![]);+ for f in &mut w {+ let (from, to) = if f.frame < 20 { (0, Some(20)) } else { (20, None) };+ let e = f.spawn(None);+ f.put(e, &Shot { name: None, from, to });+ }+ assert_eq!(Frames::Cuts.pick(&w), vec![19, 20]);+ assert_eq!(Frames::Once.pick(&w), vec![0]);+ assert_eq!(Frames::of(&json!("lines")).unwrap(), Frames::Lines);+ assert_eq!(Frames::of(&json!([3, 4])).unwrap(), Frames::At(vec![3, 4]));+ assert!(Frames::of(&json!("every")).unwrap_err().contains("not \"every\""));+}diff --git a/apps/direction/src/ts.rs b/apps/direction/src/ts.rsnew file mode 100644index 00000000..8a640630--- /dev/null+++ b/apps/direction/src/ts.rs@@ -0,0 +1,105 @@+//! A project's own checks in TypeScript (sdk/raea/src/check.ts, DR4): each file's declaration read first (its id,+//! line, what it needs and where it runs), then one run of every planned check over the worlds it ranges over, in the+//! engine's V8 with nothing drawn. raea/check's `runChecks` runs them; what they found comes back as Findings.++use std::path::{Path, PathBuf};++use raea_core_facts::{Facts, Finding, Level};+use serde_json::{json, Value};++use crate::systems::Frames;++type R<T> = Result<T, String>;++/// What the CLI lends a check: its evaluator of a .ts module's default export (as JSON), and its headless run of a+/// bundle (exit code and what it printed).+pub struct Host {+ pub eval: fn(&Path) -> R<String>,+ pub run: fn(&Path, f64) -> R<(i32, String)>,+}++/// A check file's declaration.+#[derive(Debug, Clone)]+pub struct Meta {+ pub file: PathBuf,+ pub id: String,+ pub text: String,+ pub render: bool,+ pub level: Level,+ pub frames: Frames,+}++/// The declaration of the check `file`'s default export is.+pub fn meta(file: &Path, host: &Host) -> R<Meta> {+ let name = file.display();+ let v: Value = serde_json::from_str(&(host.eval)(file)?).map_err(|e| format!("{name}: {e}"))?;+ let s = |k: &str| v[k].as_str().map(str::to_string);+ let id = s("id").ok_or_else(|| format!("{name}: its default export isn't a check({{ id, text }}, system) from \"raea/check\""))?;+ let render = match v["needs"].as_str() {+ None => false,+ Some("render") => true,+ Some(o) => return Err(format!("{name}: a check needs \"render\" or nothing, not \"{o}\"")),+ };+ let level = match s("level").as_deref() {+ None => Level::Error,+ Some(w @ ("error" | "warn" | "note")) => Level::of_word(w),+ Some(o) => return Err(format!("{name}: a check's level is error, warn or note, not \"{o}\"")),+ };+ let frames = Frames::of(&v["frames"]).map_err(|e| format!("{name}: {e}"))?;+ Ok(Meta { file: file.to_path_buf(), id, text: s("text").unwrap_or_default(), render, level, frames })+}++/// One planned run: the check (its index in `files`), its frames, and its rule's values, level (None: the check's+/// own) and `by`.+pub struct Planned {+ pub check: usize,+ pub frames: Vec<i64>,+ pub values: serde_json::Map<String, Value>,+ pub level: Option<Level>,+ pub by: String,+}++/// Every planned check run on its frames of `worlds`, in one bundle: what each found (its rule's level where the+/// finding names none, its `by` the rule's), and a finding for each check that threw.+pub fn run(files: &[PathBuf], plan: &[Planned], worlds: &[Facts], host: &Host) -> R<Vec<Finding>> {+ if plan.is_empty() {+ return Ok(Vec::new());+ }+ let work = std::env::temp_dir().join(format!("raea-check-{}", std::process::id()));+ std::fs::create_dir_all(&work).map_err(|e| e.to_string())?;+ let data = work.join("worlds.json");+ std::fs::write(&data, serde_json::to_string(worlds).map_err(|e| e.to_string())?).map_err(|e| e.to_string())?;+ let imports: String = files.iter().enumerate().map(|(i, f)| format!("import c{i} from {:?};\n", f.canonicalize().unwrap_or_else(|_| f.clone()).display().to_string())).collect();+ let checks = (0..files.len()).map(|i| format!("c{i}")).collect::<Vec<_>>().join(", ");+ let planned: Vec<Value> = plan.iter().map(|p| json!({"check": p.check, "frames": p.frames, "values": p.values, "level": p.level, "by": p.by})).collect();+ let entry = format!(+ "import {{ declared, runChecks }} from \"raea/check\";\n{imports}import worlds from {data:?};\nconst call = (globalThis as any).__raea_call;\n\+ try {{ const checks = [{checks}]; declared(checks); const r = runChecks(checks, {plan}, worlds as any); call(\"print\", JSON.stringify({{ text: JSON.stringify(r) }})); call(\"done\", JSON.stringify({{ code: 0 }})); }}\n\+ catch (e: any) {{ call(\"print\", JSON.stringify({{ text: \"error: \" + (e && e.message ? e.message : String(e)) }})); call(\"done\", JSON.stringify({{ code: 1 }})); }}\n",+ data = data.display().to_string(),+ plan = Value::Array(planned),+ );+ let js = work.join("checks.js");+ let ran = raea_runtime_bundle::bundle_entry(&entry, &js, &[]).and_then(|_| {+ // what the checks print is raea's to read: nothing reaches the terminal+ let echo = raea_runtime_react::native::ECHO.swap(false, std::sync::atomic::Ordering::Relaxed);+ let ran = (host.run)(&js, 120.0);+ raea_runtime_react::native::ECHO.store(echo, std::sync::atomic::Ordering::Relaxed);+ ran+ });+ let _ = std::fs::remove_dir_all(&work);+ let (code, printed) = ran?;+ let last = printed.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("");+ if code != 0 {+ return Err(format!("the project's checks: {}", last.strip_prefix("error: ").unwrap_or(last)));+ }+ let got: Value = serde_json::from_str(last).map_err(|e| format!("the project's checks printed {last:?}: {e}"))?;+ // a finding that doesn't read is said as it came, never dropped+ let unread = |f: &Value| Finding::new(f["check"].as_str().unwrap_or("check"), Level::Error, format!("a finding raea couldn't read: {f}"), "raea check");+ let mut out: Vec<Finding> = got["findings"].as_array().into_iter().flatten().map(|f| Finding::read(f).unwrap_or_else(|| unread(f))).collect();+ for t in got["threw"].as_array().into_iter().flatten() {+ let id = t["check"].as_str().unwrap_or("check");+ out.push(Finding::new(id, Level::Error, format!("the check threw {}", t["says"].as_str().unwrap_or("")), "raea check").fix("fix the check: it ran on none of the frames after this one"));+ }+ Ok(out)+}diff --git a/apps/direction/src/world.rs b/apps/direction/src/world.rsindex 7123a766..425ca125 100644--- a/apps/direction/src/world.rs+++ b/apps/direction/src/world.rs@@ -153,7 +153,7 @@ fn render(args: &[String]) -> Result<Render, String> {fn run(args: &[String]) -> Result<String, String> {let edit = args.iter().find(|a| a.ends_with(".tsx")).ok_or(USAGE)?;let q = flag(args, "--find").as_deref().map(Find::parse).transpose()?;- let ask = Ask { frames: frames(args)?, layout: !args.iter().any(|a| a == "--no-layout"), render: render(args)? };+ let ask = Ask { frames: frames(args)?, layout: !args.iter().any(|a| a == "--no-layout"), render: render(args)?, join_on: None };let worlds = raea_runtime_world::read(std::path::Path::new(edit), &raea_runtime_bundle::comp_opts(args)?, &ask)?;if args.iter().any(|a| a == "--json") {let one = |w: &Facts| match &q {@@ -197,7 +197,7 @@ mod tests {w.put(scene, &Layer { medium: Medium::Scene3d, order: 0, opacity: 1.0, blend: None });let sign = w.spawn(Some(scene));w.put(sign, &Text { words: "OPEN".into(), font: None, size: None, box_: None, extruded: 0.2, lines: Some(1), needs: None });- w.put(sign, &Part { kind: "text3d".into(), name: "sign".into(), tags: vec![], at: [0.0; 3], rotation: [0.0, 0.0, 0.0, 1.0], scale: [1.0; 3], min: None, max: None, triangles: None, src: None, material: None, color: None });+ w.put(sign, &Part { kind: "text3d".into(), name: "sign".into(), tags: vec![], at: [0.0; 3], rotation: [0.0, 0.0, 0.0, 1.0], scale: [1.0; 3], min: None, max: None, own: None, triangles: None, src: None, material: None, color: None });let hidden = w.spawn(None);w.put(hidden, &Layer { medium: Medium::Type2d, order: 3, opacity: 1.0, blend: None });w.put(hidden, &Text { words: "UNDER".into(), font: None, size: None, box_: None, extruded: 0.0, lines: None, needs: None });diff --git a/apps/workspace/Cargo.toml b/apps/workspace/Cargo.tomlindex 1518c24d..1f40125b 100644--- a/apps/workspace/Cargo.toml+++ b/apps/workspace/Cargo.toml@@ -14,3 +14,5 @@ serde_json = "1"raea-app-registry = { path = "registry" }# the project's record of what renders and checks found, which raea next reads (docs/direction.feature DR3)raea-core-facts = { path = "../../core/facts" }+# a command's words (its arguments that aren't flags or their values), read as raea check reads them+raea-app-check = { path = "../check" }diff --git a/apps/workspace/src/controllers.rs b/apps/workspace/src/controllers.rsindex 83bceeb6..308f134a 100644--- a/apps/workspace/src/controllers.rs+++ b/apps/workspace/src/controllers.rs@@ -22,8 +22,7 @@ pub fn load(ws: &Path, eval: Eval) -> R<Vec<(PathBuf, Controller)>> {}fn read(f: &Path, eval: Eval) -> R<Controller> {- let raw: serde_json::Value = serde_json::from_str(&eval(f)?).map_err(|e| format!("{}: {e}", f.display()))?;- ctl::normalize(&raw).map_err(|e| format!("{}: {e}", f.display()))+ ctl::of_json(&eval(f)?).map_err(|e| format!("{}: {e}", f.display()))}/// The module a controller is kept as.diff --git a/apps/workspace/src/workspace.rs b/apps/workspace/src/workspace.rsindex 91808bfc..b4fa8dae 100644--- a/apps/workspace/src/workspace.rs+++ b/apps/workspace/src/workspace.rs@@ -65,8 +65,7 @@ pub(crate) fn flag<'a>(args: &'a [String], name: &str) -> Option<&'a str> {/// The words of a command that aren't flags or a flag's value.fn words(args: &[String]) -> Vec<&str> {- let takes = ["--layout", "--storage", "--name", "--remote"];- args.iter().enumerate().filter(|(i, a)| !a.starts_with("--") && !(*i > 0 && takes.contains(&args[i - 1].as_str()))).map(|(_, a)| a.as_str()).collect()+ raea_app_check::words(args, &["--layout", "--storage", "--name", "--remote"])}// a name as a folder (slug), and the nearest folder holding a marker (up): the registry's, which reads controller idsdiff --git a/bench/direction/proof/ad-cheat.tsx b/bench/direction/proof/ad-cheat.tsxnew file mode 100644index 00000000..a82fea17--- /dev/null+++ b/bench/direction/proof/ad-cheat.tsx@@ -0,0 +1,16 @@+// DR4's proof, the ad's cheat: the caption's box is set to end above the band (70 px tall at 640 px, 74% down), but+// its words wrap past it to about 85%. A check of the element's box passes it; checks/caption.ts reads the words'+// own box and must fail it.+import { AbsoluteFill, Composition, registerRoot } from "raea";++function Ad() {+ return (+ <AbsoluteFill style={{ background: "#f4e9d8" }}>+ <div style={{ position: "absolute", left: 60, top: 640, width: 380, height: 70, fontSize: 44, fontWeight: 700, color: "#222" }}>+ Fresh bread every morning, baked in the shop since six+ </div>+ </AbsoluteFill>+ );+}++registerRoot(() => <Composition id="ad-cheat" component={Ad} width={540} height={960} fps={30} durationInFrames={90} />);diff --git a/bench/direction/proof/ad.tsx b/bench/direction/proof/ad.tsxnew file mode 100644index 00000000..fde0f1cf--- /dev/null+++ b/bench/direction/proof/ad.tsx@@ -0,0 +1,13 @@+// DR4's proof, the vertical ad as asked: its caption well above the platform's button band (from 80% down).+// checks/caption.ts holds it.+import { AbsoluteFill, Composition, registerRoot } from "raea";++function Ad() {+ return (+ <AbsoluteFill style={{ background: "#f4e9d8" }}>+ <div style={{ position: "absolute", left: 60, top: 560, width: 380, fontSize: 44, fontWeight: 700, color: "#222" }}>Fresh bread, every morning</div>+ </AbsoluteFill>+ );+}++registerRoot(() => <Composition id="ad" component={Ad} width={540} height={960} fps={30} durationInFrames={90} />);diff --git a/bench/direction/proof/checks/caption.ts b/bench/direction/proof/checks/caption.tsnew file mode 100644index 00000000..5a9e67c1--- /dev/null+++ b/bench/direction/proof/checks/caption.ts@@ -0,0 +1,14 @@+// A caption clears the platform's button band (DR4's fourth proof: a vertical ad). Every frame's 2D text, by the box+// its words were laid in: no render needed. `band`: where the band starts, down the frame (0.8 when unset).+import { check, found, type Layer, type Text } from "raea/check";++export default check({ id: "caption", text: "a caption clears the platform's button band" }, (world, _frame, values) => {+ const band = Number(values.band ?? 0.8);+ for (const t of world.find({ with: ["Text", "Layer"] })) {+ if (world.component<Layer>(t, "Layer")!.medium !== "2d-type") continue;+ const box = world.component<Text>(t, "Text")!.box;+ if (box && box[3] > band) {+ found({ about: [t], says: `the caption reaches ${Math.round(box[3] * 100)}% down the frame, into the button band from ${Math.round(band * 100)}%`, measure: { name: "bottom", value: Math.round(box[3] * 100), unit: "%", limit: Math.round(band * 100) } });+ }+ }+});diff --git a/bench/direction/proof/checks/cue.ts b/bench/direction/proof/checks/cue.tsnew file mode 100644index 00000000..cdde3855--- /dev/null+++ b/bench/direction/proof/checks/cue.ts@@ -0,0 +1,16 @@+// A cue is heard within a frame of where it is placed (DR4's third proof: a mix). It reads each cue's Onset, measured+// on the render's mix, so it needs a render. That the cue is placed on its cause (a hit, a door) is DR21's CausedBy;+// this holds the half the mix alone can: a cue whose sound starts late, or never, is found.+import { check, found, type Onset } from "raea/check";++export default check({ id: "cue", text: "a cue is heard within a frame of where it is placed", needs: "render" }, (world) => {+ const fps = world.resource<{ fps: number }>("Frame")!.fps;+ const limit = Math.round(1000 / fps);+ for (const c of world.find({ with: ["Cue", "Onset"] })) {+ const o = world.component<Onset>(c, "Onset")!;+ if (o.late_ms == null) found({ about: [c], says: "nothing is heard where the cue is placed" });+ else if (Math.abs(o.late_ms) > limit) {+ found({ about: [c], says: `it is heard ${Math.abs(o.late_ms)} ms ${o.late_ms > 0 ? "after" : "before"} where it is placed`, measure: { name: "late", value: o.late_ms, unit: "ms", limit } });+ }+ }+});diff --git a/bench/direction/proof/checks/cut.ts b/bench/direction/proof/checks/cut.tsnew file mode 100644index 00000000..a70818dc--- /dev/null+++ b/bench/direction/proof/checks/cut.ts@@ -0,0 +1,23 @@+// A cut lands on a word's end (DR4's second proof: a footage edit). At each cut it reads the outgoing clip's last frame+// and the incoming clip's first against the words their take's transcript has: a cut through a word is found. No+// render: the edit and the transcript say it all.+import { check, found, type Clip } from "raea/check";++export default check({ id: "cut", text: "a cut lands on a word's end", frames: "cuts" }, (world, frame) => {+ const fps = world.resource<{ fps: number }>("Frame")!.fps;+ const tol = 1 / fps;+ for (const c of world.find({ with: ["Clip"] })) {+ const clip = world.component<Clip>(c, "Clip")!;+ // where this clip is cut, if it is cut on this frame: its out on its last frame, its in on its first+ const last = clip.out != null && frame === clip.at + Math.round((clip.out - clip.in) * fps) - 1;+ const points: [string, number][] = [];+ if (last) points.push(["out of", clip.out!]);+ if (frame === clip.at && clip.in > 0) points.push(["into", clip.in]);+ for (const [how, at] of points) {+ const through = clip.words.find((w) => w.start + tol < at && at < w.end - tol);+ if (through) {+ found({ about: [c], says: `the cut ${how} the take at ${at.toFixed(2)} s falls inside "${through.text}" (${through.start.toFixed(2)} to ${through.end.toFixed(2)} s)`, measure: { name: "into the word", value: Math.round((at - through.start) * 1000), unit: "ms" }, fix: `cut at ${through.end.toFixed(2)} s, its end` });+ }+ }+ }+});diff --git a/bench/direction/proof/checks/lyric.ts b/bench/direction/proof/checks/lyric.tsnew file mode 100644index 00000000..f2df3815--- /dev/null+++ b/bench/direction/proof/checks/lyric.ts@@ -0,0 +1,23 @@+// A sung line is 2D type, inside the frame, with the subject in front of it (docs/direction.feature DR4's first proof:+// a React layer over footage). It runs where a line is sung and reads what covers it, so it needs a render with+// --layers; the line's text is the Text whose words a Line on the frame sings.+import { check, found, type Covers, type Layer, type Line, type Text } from "raea/check";++const plain = (s: string) => s.replace(/[^a-z0-9 ]/gi, "").replace(/\s+/g, " ").trim().toLowerCase();++export default check({ id: "lyric", text: "a sung line is 2D type, inside the frame, with the subject in front of it", needs: "render", frames: "lines" }, (world, _frame, values) => {+ const sung = world.find({ with: ["Line"] }).map((l) => plain(world.component<Line>(l, "Line")!.text));+ const margin = Number(values.margin ?? 0.03);+ for (const t of world.find({ with: ["Text"] })) {+ const text = world.component<Text>(t, "Text")!;+ if (!sung.includes(plain(text.words))) continue;+ const layer = world.component<Layer>(t, "Layer");+ if (layer?.medium !== "2d-type" || text.extruded > 0) {+ found({ about: [t], says: `the line is ${layer?.medium ?? "3d"} type${text.extruded > 0 ? `, ${text.extruded} m deep` : ""}: it is to be flat 2D type` });+ }+ const b = text.box;+ if (b && (b[0] < margin || b[1] < margin || b[2] > 1 - margin || b[3] > 1 - margin)) found({ about: [t], says: "the line runs to the frame's edge" });+ const covered = world.find({ with: ["Covers"] }).some((c) => (world.component<Covers>(c, "Covers") ?? []).some((x) => x.layer === t && x.share > 0));+ if (!covered) found({ about: [t], says: "nothing is in front of the line: the subject is to mask it" });+ }+});diff --git a/bench/direction/proof/checks/rider.ts b/bench/direction/proof/checks/rider.tsnew file mode 100644index 00000000..9d7a1be1--- /dev/null+++ b/bench/direction/proof/checks/rider.ts@@ -0,0 +1,65 @@+// A rider turns with its seat and is in no part of it (DR4's fifth proof: a 3D scene). The parts are named in the+// rule's values (`rider`; `seat`, and every part whose name starts with it is the seat's); their rotations are+// compared, and each part's own box, turned as it is, is tested against the rider's. That the rider rides the seat+// is DR16's Rides; until then the rule names them.+import { check, found, type Part } from "raea/check";++type V = number[];+const dot = (u: V, v: V) => u[0] * v[0] + u[1] * v[1] + u[2] * v[2];+const cross = (u: V, v: V) => [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]];++/** The angle between two rotations (x, y, z, w), in degrees. */+const turn = (a: V, b: V) => (2 * Math.acos(Math.min(1, Math.abs(a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]))) * 180) / Math.PI;++/** A part as a box turned as it is: its centre, its axes and its half sizes along them, in world metres. A part with+ * no box of its own is its world box. */+function box(p: Part): { c: V; axes: V[]; half: V } | null {+ if (!p.own) return p.min && p.max ? { c: [0, 1, 2].map((k) => (p.min![k] + p.max![k]) / 2), axes: [[1, 0, 0], [0, 1, 0], [0, 0, 1]], half: [0, 1, 2].map((k) => (p.max![k] - p.min![k]) / 2) } : null;+ const [lo, hi] = p.own;+ const [x, y, z, w] = p.rotation;+ // v turned by the part's rotation+ const rot = (v: V) => {+ const t = [2 * (y * v[2] - z * v[1]), 2 * (z * v[0] - x * v[2]), 2 * (x * v[1] - y * v[0])];+ return [v[0] + w * t[0] + (y * t[2] - z * t[1]), v[1] + w * t[1] + (z * t[0] - x * t[2]), v[2] + w * t[2] + (x * t[1] - y * t[0])];+ };+ const c = rot([0, 1, 2].map((k) => ((lo[k] + hi[k]) / 2) * p.scale[k])).map((v, k) => v + p.at[k]);+ return { c, axes: [[1, 0, 0], [0, 1, 0], [0, 0, 1]].map(rot), half: [0, 1, 2].map((k) => (Math.abs(hi[k] - lo[k]) / 2) * Math.abs(p.scale[k])) };+}++/** How far two turned boxes are in each other: the least overlap along the axes that could part them (0: apart). */+function depth(a: NonNullable<ReturnType<typeof box>>, b: NonNullable<ReturnType<typeof box>>): number {+ const d = [0, 1, 2].map((k) => b.c[k] - a.c[k]);+ const axes = [...a.axes, ...b.axes, ...a.axes.flatMap((u) => b.axes.map((v) => cross(u, v)))];+ let least = Infinity;+ for (const ax of axes) {+ const len = Math.hypot(ax[0], ax[1], ax[2]);+ if (len < 1e-9) continue;+ const n = ax.map((v) => v / len);+ const reach = (o: typeof a) => o.half.reduce((s, h, k) => s + h * Math.abs(dot(o.axes[k], n)), 0);+ const overlap = reach(a) + reach(b) - Math.abs(dot(d, n));+ if (overlap <= 0) return 0;+ least = Math.min(least, overlap);+ }+ return least;+}++export default check({ id: "rider", text: "a rider turns with its seat and is in no part of it" }, (world, _frame, values) => {+ const parts = world.find({ with: ["Part"] });+ const part = (id: number) => world.component<Part>(id, "Part")!;+ const rider = parts.find((p) => part(p).name === String(values.rider));+ const seat = parts.find((p) => part(p).name === String(values.seat));+ // a piece with neither has no rider to hold; one without the other is a name gone wrong+ if (rider == null && seat == null) return;+ if (rider == null || seat == null) return found({ says: `there's no part named ${rider == null ? values.rider : values.seat} on this frame` });+ const deg = turn(part(rider).rotation, part(seat).rotation);+ const most = Number(values.turn ?? 0.5);+ if (deg > most) found({ about: [rider, seat], says: `the rider is turned ${deg.toFixed(1)} degrees from its seat`, measure: { name: "turn", value: Math.round(deg * 10) / 10, unit: "deg", limit: most } });+ const into = Number(values.into ?? 0.01);+ const r = box(part(rider));+ for (const s of parts.filter((p) => p !== rider && part(p).name.startsWith(String(values.seat)))) {+ const q = box(part(s));+ if (!r || !q) continue;+ const cm = depth(r, q);+ if (cm > into) found({ about: [rider, s], says: `the rider is ${Math.round(cm * 100)} cm into ${part(s).name}`, measure: { name: "into", value: Math.round(cm * 100), unit: "cm", limit: Math.round(into * 100) } });+ }+});diff --git a/bench/direction/proof/controllers/rules.ts b/bench/direction/proof/controllers/rules.tsnew file mode 100644index 00000000..39245a63--- /dev/null+++ b/bench/direction/proof/controllers/rules.ts@@ -0,0 +1,19 @@+// The proof project's rules (docs/direction.feature DR4): each a rule field naming the check that holds it, a .ts+// check by its path from here, with its values. `raea check FILE.tsx --only ID` runs one.+import { controller } from "raea/brief";++export default controller({+ title: "Proof rules",+ groups: [+ {+ title: "What the pieces are held to",+ fields: [+ { label: "Sung lines are flat 2D type, inside the frame, behind the subject", type: "rule", check: "../checks/lyric.ts" },+ { label: "Cuts land on a word's end", type: "rule", check: "../checks/cut.ts" },+ { label: "Cues are heard where they are placed", type: "rule", check: "../checks/cue.ts" },+ { label: "Captions clear the button band", type: "rule", check: "../checks/caption.ts", values: { band: 0.8 } },+ { label: "The rider turns with its seat and is in no part of it", type: "rule", check: "../checks/rider.ts", values: { rider: "rider", seat: "seat" } },+ ],+ },+ ],+});diff --git a/bench/direction/proof/cut-cheat.tsx b/bench/direction/proof/cut-cheat.tsxnew file mode 100644index 00000000..2228b71f--- /dev/null+++ b/bench/direction/proof/cut-cheat.tsx@@ -0,0 +1,18 @@+// DR4's proof, the edit's cheat: the same two pieces with the same length of shot, the first cut out of the take in+// the middle of "two" (1.5 s) and the second into it in the middle of "three" (2.5 s). checks/cut.ts must fail it.+import { AbsoluteFill, Composition, Sequence, Video, registerRoot } from "raea";++function Edit() {+ return (+ <AbsoluteFill style={{ background: "#000" }}>+ <Sequence from={0} durationInFrames={45} name="a">+ <Video src="media/take.mp4" startFrom={0} endAt={45} style={{ width: 540, height: 960 }} />+ </Sequence>+ <Sequence from={45} durationInFrames={15} name="b">+ <Video src="media/take.mp4" startFrom={75} endAt={90} style={{ width: 540, height: 960 }} />+ </Sequence>+ </AbsoluteFill>+ );+}++registerRoot(() => <Composition id="cut-cheat" component={Edit} width={540} height={960} fps={30} durationInFrames={60} />);diff --git a/bench/direction/proof/cut.tsx b/bench/direction/proof/cut.tsxnew file mode 100644index 00000000..3cdc3f4d--- /dev/null+++ b/bench/direction/proof/cut.tsx@@ -0,0 +1,18 @@+// DR4's proof, the edit as asked: two pieces of one take, cut between its words (media/take.words.json: "one" ends+// at 0.95 s, "two" runs 1.05 to 1.90, "three" starts at 2.05). checks/cut.ts holds it.+import { AbsoluteFill, Composition, Sequence, Video, registerRoot } from "raea";++function Edit() {+ return (+ <AbsoluteFill style={{ background: "#000" }}>+ <Sequence from={0} durationInFrames={30} name="a">+ <Video src="media/take.mp4" startFrom={0} endAt={30} style={{ width: 540, height: 960 }} />+ </Sequence>+ <Sequence from={30} durationInFrames={30} name="b">+ <Video src="media/take.mp4" startFrom={60} endAt={90} style={{ width: 540, height: 960 }} />+ </Sequence>+ </AbsoluteFill>+ );+}++registerRoot(() => <Composition id="cut" component={Edit} width={540} height={960} fps={30} durationInFrames={60} />);diff --git a/bench/direction/proof/lyric-cheat.tsx b/bench/direction/proof/lyric-cheat.tsxnew file mode 100644index 00000000..2c6cdc59--- /dev/null+++ b/bench/direction/proof/lyric-cheat.tsx@@ -0,0 +1,25 @@+// DR4's proof, the lyric's cheat: the line "made 2D" by leaving it 3D type with a hair of depth, facing the camera so+// it looks flat, and nothing in front of it. (No footage: a page layer is drawn over the 3D, and would hide the line.)+// checks/lyric.ts must fail it.+import { AbsoluteFill, Composition, registerRoot } from "raea";+import { Text3D } from "raea/3d";+import { Camera3d } from "raea/camera";+import { DirectionalLight } from "raea/light";+import { Mesh3d } from "raea/mesh";+import { StandardMaterial } from "raea/pbr";+import { Transform } from "raea/transform";++function Lyric() {+ return (+ <AbsoluteFill style={{ background: "#16202e" }}>+ <Camera3d transform={Transform.fromXyz(0, 0, 6).lookingAt([0, 0, 0])} />+ <DirectionalLight illuminance={9000} transform={Transform.fromXyz(0, 2, 6).lookingAt([0, 0, 0])} />+ <Mesh3d name="line" transform={Transform.fromXyz(0, 1, 0)}>+ <Text3D size={0.25} depth={0.002}>OUT OF THE GREY</Text3D>+ <StandardMaterial base_color="#ffffff" />+ </Mesh3d>+ </AbsoluteFill>+ );+}++registerRoot(() => <Composition id="lyric-cheat" component={Lyric} width={540} height={960} fps={30} durationInFrames={60} />);diff --git a/bench/direction/proof/lyric.tsx b/bench/direction/proof/lyric.tsxnew file mode 100644index 00000000..0d47bac5--- /dev/null+++ b/bench/direction/proof/lyric.tsx@@ -0,0 +1,15 @@+// DR4's proof, the lyric as asked: footage, the sung line over it as flat 2D type inside the frame, and the subject+// (a cutout standing in for a person) in front of part of it. checks/lyric.ts holds it.+import { AbsoluteFill, Composition, Video, registerRoot } from "raea";++function Lyric() {+ return (+ <AbsoluteFill style={{ background: "#000" }}>+ <Video src="media/take.mp4" muted style={{ position: "absolute", left: 0, top: 0, width: 540, height: 960 }} />+ <div style={{ position: "absolute", left: 60, top: 300, width: 420, fontSize: 64, fontWeight: 800, color: "#ffffff", lineHeight: 1.1 }}>OUT OF THE GREY</div>+ <div style={{ position: "absolute", left: 220, top: 250, width: 180, height: 710, borderRadius: "90px 90px 0 0", background: "#2b2b2b" }} />+ </AbsoluteFill>+ );+}++registerRoot(() => <Composition id="lyric" component={Lyric} width={540} height={960} fps={30} durationInFrames={60} />);diff --git a/bench/direction/proof/mix-cheat.tsx b/bench/direction/proof/mix-cheat.tsxnew file mode 100644index 00000000..69cb94e3--- /dev/null+++ b/bench/direction/proof/mix-cheat.tsx@@ -0,0 +1,16 @@+// DR4's proof, the mix's cheat: the beep placed on the same frame, but its file starts with 150 ms of silence, so it is+// heard four frames late. The placement reads right; the render doesn't. checks/cue.ts must fail it.+import { AbsoluteFill, Audio, Composition, Sequence, registerRoot, useCurrentFrame } from "raea";++function Mix() {+ const f = useCurrentFrame();+ return (+ <AbsoluteFill style={{ background: f < 30 ? "#203040" : "#e0e0e0" }}>+ <Sequence from={30} name="beep" layout="none">+ <Audio src="media/late-beep.wav" />+ </Sequence>+ </AbsoluteFill>+ );+}++registerRoot(() => <Composition id="mix-cheat" component={Mix} width={540} height={960} fps={30} durationInFrames={60} />);diff --git a/bench/direction/proof/mix.tsx b/bench/direction/proof/mix.tsxnew file mode 100644index 00000000..2fd68d6b--- /dev/null+++ b/bench/direction/proof/mix.tsx@@ -0,0 +1,15 @@+// DR4's proof, the mix as asked: a beep placed at 1 s, whose sound starts at once. checks/cue.ts holds it on the render.+import { AbsoluteFill, Audio, Composition, Sequence, registerRoot, useCurrentFrame } from "raea";++function Mix() {+ const f = useCurrentFrame();+ return (+ <AbsoluteFill style={{ background: f < 30 ? "#203040" : "#e0e0e0" }}>+ <Sequence from={30} name="beep" layout="none">+ <Audio src="media/beep.wav" />+ </Sequence>+ </AbsoluteFill>+ );+}++registerRoot(() => <Composition id="mix" component={Mix} width={540} height={960} fps={30} durationInFrames={60} />);diff --git a/bench/direction/proof/proof.sh b/bench/direction/proof/proof.shnew file mode 100644index 00000000..335728c7--- /dev/null+++ b/bench/direction/proof/proof.sh@@ -0,0 +1,71 @@+#!/usr/bin/env bash+# DR4's proof (docs/direction.feature): five checks written as systems over the world (checks/*.ts, none importing+# Bevy), each run by `raea check` on a piece that holds it and on a cheat that must fail it, and a taste line run as+# the named check of its form beside them. Its media are made here with ffmpeg (nothing downloaded); the two pieces+# whose checks need a render are rendered first. Every case runs in a copy, so the bench folder stays clean.+#+# RAEA_BIN=path/to/raea bash bench/direction/proof/proof.sh+set -uo pipefail+here=$(cd "$(dirname "$0")" && pwd)+raea=${RAEA_BIN:-raea}+work=$(mktemp -d "${TMPDIR:-/tmp}/raea-dr4-proof.XXXXXX")+# KEEP=1 keeps the copy (its renders, logs and record) and says where+if [ -n "${KEEP:-}" ]; then trap 'echo "proof: kept $work"' EXIT; else trap 'rm -rf "$work"' EXIT; fi+cp -R "$here/." "$work/"+mkdir -p "$work/.raea" "$work/media" "$work/out"+: >"$work/.raea/project"+cd "$work" || exit 2++ff() { ffmpeg -hide_banner -loglevel error -y "$@" || { echo "proof: ffmpeg failed: $*"; exit 2; }; }+# a 4 s take with a tone, and its words ("one" to 0.95 s, "two" 1.05 to 1.90, "three" 2.05 to 2.95, "four" from 3.05)+ff -f lavfi -i "testsrc2=size=540x960:rate=30:duration=4" -f lavfi -i "sine=frequency=220:duration=4" -c:v libx264 -pix_fmt yuv420p -c:a aac -shortest media/take.mp4+printf '[{"text":"one","start":0.10,"end":0.95},{"text":"two","start":1.05,"end":1.90},{"text":"three","start":2.05,"end":2.95},{"text":"four","start":3.05,"end":3.90}]\n' >media/take.words.json+# a beep that starts at once, and the same beep after 150 ms of silence+ff -f lavfi -i "sine=frequency=880:duration=0.3" media/beep.wav+ff -f lavfi -i "anullsrc=r=44100:cl=mono:d=0.15" -f lavfi -i "sine=frequency=880:duration=0.3:sample_rate=44100" -filter_complex "[0][1]concat=n=2:v=0:a=1" media/late-beep.wav++for p in lyric lyric-cheat; do "$raea" render "$p.tsx" -o "out/$p.mp4" --layers >"out/$p.log" 2>&1 || { echo "proof: raea render $p.tsx failed:"; tail -5 "out/$p.log"; exit 2; }; done+for p in mix mix-cheat; do "$raea" render "$p.tsx" -o "out/$p.mp4" >"out/$p.log" 2>&1 || { echo "proof: raea render $p.tsx failed:"; tail -5 "out/$p.log"; exit 2; }; done++bad=0+# FILE ID WANT [FLAGS...]: `raea check FILE --only ID` finds nothing (WANT none) or something (WANT some), waits for+# nothing, and every finding it prints is shown+case_() {+ local file=$1 id=$2 want=$3+ shift 3+ local out+ out=$("$raea" check "$file" --only "$id" --json "$@" 2>"out/$file.$id.err")+ local code=$?+ if [ $code -eq 2 ] || ! jq -e .compositions >/dev/null 2>&1 <<<"$out"; then+ echo "FAIL $file --only $id: raea check couldn't check it (exit $code): $(tail -3 "out/$file.$id.err") $(head -c 300 <<<"$out")"+ bad=$((bad + 1))+ return+ fi+ local n waits+ n=$(jq '[.compositions[].findings[]] | length' <<<"$out")+ waits=$(jq -r '[.compositions[].waits[] | "\(.rule) waits for \(.for)"] | join("; ")' <<<"$out")+ local ok=1+ { [ "$want" = none ] && [ "$n" -ne 0 ]; } && ok=0+ { [ "$want" = some ] && [ "$n" -eq 0 ]; } && ok=0+ [ -n "$waits" ] && ok=0+ [ $ok -eq 1 ] || bad=$((bad + 1))+ printf '%s %s --only %s: %s finding(s)%s\n' "$([ $ok -eq 1 ] && echo "ok " || echo FAIL)" "$file" "$id" "$n" "${waits:+, $waits}"+ jq -r '.compositions[].findings[] | " \(.level) \(.check) \(.frames // "" | tostring): \(.says)"' <<<"$out"+}++case_ lyric.tsx lyric none+case_ lyric-cheat.tsx lyric some+case_ cut.tsx cut none+case_ cut-cheat.tsx cut some+case_ mix.tsx cue none+case_ mix-cheat.tsx cue some+case_ ad.tsx caption none+case_ ad-cheat.tsx caption some+case_ ride.tsx rider none+case_ ride-cheat.tsx rider some+# a taste line is a named check of its form, run beside the project's own+case_ ad.tsx text-above none --taste taste.ts+case_ ad-cheat.tsx text-above some --taste taste.ts++if [ $bad -eq 0 ]; then echo "proof: every case as expected"; else echo "proof: $bad case(s) wrong"; fi+exit $((bad > 0))diff --git a/bench/direction/proof/ride-cheat.tsx b/bench/direction/proof/ride-cheat.tsxnew file mode 100644index 00000000..52c94486--- /dev/null+++ b/bench/direction/proof/ride-cheat.tsx@@ -0,0 +1,10 @@+// DR4's proof, the 3D scene's cheat: the rider turned with the seat (so a check of the angle alone passes), but pushed+// back into the seat's back (seat.tsx). checks/rider.ts must fail it.+import { Composition, registerRoot, useCurrentFrame } from "raea";+import { Seat } from "./seat";++function Ride() {+ return <Seat yaw={0.3 + useCurrentFrame() * 0.01} rider={[0, 0.35, -0.15]} />;+}++registerRoot(() => <Composition id="ride-cheat" component={Ride} width={540} height={960} fps={30} durationInFrames={30} />);diff --git a/bench/direction/proof/ride.tsx b/bench/direction/proof/ride.tsxnew file mode 100644index 00000000..56f679f6--- /dev/null+++ b/bench/direction/proof/ride.tsx@@ -0,0 +1,10 @@+// DR4's proof, the 3D scene as asked: a seat turning, and a rider on it that turns with it and sits forward, clear of+// the back (seat.tsx). checks/rider.ts holds it, with the parts named in controllers/rules.ts.+import { Composition, registerRoot, useCurrentFrame } from "raea";+import { Seat } from "./seat";++function Ride() {+ return <Seat yaw={0.3 + useCurrentFrame() * 0.01} rider={[0, 0.35, 0.25]} />;+}++registerRoot(() => <Composition id="ride" component={Ride} width={540} height={960} fps={30} durationInFrames={30} />);diff --git a/bench/direction/proof/seat.tsx b/bench/direction/proof/seat.tsxnew file mode 100644index 00000000..2d85fc53--- /dev/null+++ b/bench/direction/proof/seat.tsx@@ -0,0 +1,32 @@+// DR4's proof's 3D scene, shared by ride.tsx and ride-cheat.tsx: a seat (its base and back) turned by `yaw`, and a+// rider on it at `rider` in the seat's own space.+import { AbsoluteFill } from "raea";+import { Camera3d } from "raea/camera";+import { DirectionalLight } from "raea/light";+import { Cuboid, Mesh3d } from "raea/mesh";+import { StandardMaterial } from "raea/pbr";+import { Quat, Transform } from "raea/transform";++/** A point `[x, y, z]` of the seat's own space, turned by `yaw` about its base at (0, 0.5, 0). */+const on = (yaw: number, [x, y, z]: number[]) => Transform.fromXyz(x * Math.cos(yaw) + z * Math.sin(yaw), 0.5 + y, -x * Math.sin(yaw) + z * Math.cos(yaw)).withRotation(Quat.fromEuler("XYZ", 0, yaw, 0));++export function Seat({ yaw, rider }: { yaw: number; rider: number[] }) {+ return (+ <AbsoluteFill style={{ background: "#1d2430" }}>+ <Camera3d transform={Transform.fromXyz(2.5, 2, 4).lookingAt([0, 0.8, 0])} />+ <DirectionalLight illuminance={9000} transform={Transform.fromXyz(2, 4, 6).lookingAt([0, 0, 0])} />+ <Mesh3d name="seat" transform={on(yaw, [0, 0, 0])}>+ <Cuboid half_size={[0.3, 0.05, 0.3]} />+ <StandardMaterial base_color="#8a5a3c" />+ </Mesh3d>+ <Mesh3d name="seat-back" transform={on(yaw, [0, 0.45, -0.25])}>+ <Cuboid half_size={[0.3, 0.4, 0.05]} />+ <StandardMaterial base_color="#8a5a3c" />+ </Mesh3d>+ <Mesh3d name="rider" transform={on(yaw, rider)}>+ <Cuboid half_size={[0.2, 0.3, 0.15]} />+ <StandardMaterial base_color="#3fa7ff" />+ </Mesh3d>+ </AbsoluteFill>+ );+}diff --git a/bench/direction/proof/taste.ts b/bench/direction/proof/taste.tsnew file mode 100644index 00000000..6ca422ab--- /dev/null+++ b/bench/direction/proof/taste.ts@@ -0,0 +1,8 @@+// The proof's taste (passed with --taste): one line raea measures, run as the named check of its form (text-above)+// beside the project's own checks.+import { taste } from "raea/brief";++export default taste({+ title: "Proof taste",+ sections: [{ heading: "Text", rules: [{ text: "Captions sit above three quarters of the frame.", check: { form: "text-above", value: 75 } }] }],+});diff --git a/bench/direction/proof/words.json b/bench/direction/proof/words.jsonnew file mode 100644index 00000000..a5282f9c--- /dev/null+++ b/bench/direction/proof/words.json@@ -0,0 +1,6 @@+[+ { "text": "OUT", "start": 0.2, "end": 0.5 },+ { "text": "OF", "start": 0.5, "end": 0.7 },+ { "text": "THE", "start": 0.7, "end": 0.9 },+ { "text": "GREY.", "start": 0.9, "end": 1.8 }+]diff --git a/core/brief/src/controller.rs b/core/brief/src/controller.rsindex 0e9e3524..2be4d60e 100644--- a/core/brief/src/controller.rs+++ b/core/brief/src/controller.rs@@ -190,6 +190,11 @@ pub fn normalize(raw: &Value) -> Result<Controller, String> {Ok(Controller { id, title, help: text(o, "help"), groups })}+/// A controller from its module's default export as JSON (what `raea spec` prints), checked as `normalize` does.+pub fn of_json(json: &str) -> Result<Controller, String> {+ normalize(&serde_json::from_str(json).map_err(|e| e.to_string())?)+}+/// A value checked against its field: the same type, a choice among its options, a number within its range. The/// value as it's kept (a workflow's steps filled in, a list's strings trimmed).pub fn check_value(f: &Field, v: &Value) -> Result<Value, String> {diff --git a/core/facts/src/components.rs b/core/facts/src/components.rsindex b3284a53..d40852bf 100644--- a/core/facts/src/components.rs+++ b/core/facts/src/components.rs@@ -154,6 +154,9 @@ pub struct Part {/// its world box, low corner then high (None: a kind raea doesn't measure, or a file it can't read)pub min: Option<[f64; 3]>,pub max: Option<[f64; 3]>,+ /// its own box, in its own space before its transform (low corner, high corner): with at, rotation and scale,+ /// exactly where it is, turned as it is; its world box is the box around that (None as its world box)+ pub own: Option<[[f64; 3]; 2]>,pub triangles: Option<u32>,/// a model's filepub src: Option<String>,@@ -234,9 +237,10 @@ pub struct Line {pub needs: Option<String>,}-/// The components' TypeScript declarations, for a check's types (sdk/raea/src/check.ts is generated from these).+/// The components' TypeScript declarations, for a check's types (sdk/raea/src/facts.gen.ts, which raea/check+/// re-exports). A frame is a number in TypeScript, as it is in the world's JSON.pub fn declarations() -> Vec<String> {- let cfg = Config::default();+ let cfg = Config::default().with_large_int("number");macro_rules! decls { ($($t:ty),*) => { vec![$(format!("export {}", <$t as TS>::decl(&cfg))),*] }; }use crate::rendered::*;decls!(Source, Medium, Layer, Text, Part, Camera, Shot, Word, Clip, Cue, Line, Contrast, Picture, Onset, Covered, Covers, Mix, Rendered, Waits, crate::Level, crate::About, crate::Measure, crate::Finding)@@ -275,5 +279,17 @@ mod tests {assert!(d.contains(&format!("type {name} ")), "no declaration for {name}: {d}");}assert!(d.contains("\"2d-type\""), "the medium's words are the person's: {d}");+ assert!(!d.contains("bigint"), "a frame is a number in TypeScript: {d}");+ }++ #[test]+ fn declarations_match_the_committed_file() {+ let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../sdk/raea/src/facts.gen.ts");+ let now = format!("// Generated from raea-core-facts (core/facts) by its `declarations`; edit the Rust, not this.\n\n{}\n", declarations().join("\n\n"));+ if std::env::var_os("RAEA_WRITE").is_some() {+ std::fs::write(path, &now).unwrap();+ }+ let committed = std::fs::read_to_string(path).unwrap_or_default();+ assert!(committed == now, "sdk/raea/src/facts.gen.ts is out of date: RAEA_WRITE=1 cargo test -p raea-core-facts");}}diff --git a/core/facts/src/rule.rs b/core/facts/src/rule.rsindex 8abd6b47..2b158427 100644--- a/core/facts/src/rule.rs+++ b/core/facts/src/rule.rs@@ -4,7 +4,7 @@//! changes nothing about how it runs: it is only said, as its findings' `by`. A taste file's six forms are six of//! raea's named checks with the same names and values, so every taste file reads as it did.-use std::path::{Path, PathBuf};+use std::path::Path;use raea_core_brief::{controller, taste};use serde::{Deserialize, Serialize};@@ -22,7 +22,9 @@ pub struct Rule {pub check: String,#[serde(default, skip_serializing_if = "Map::is_empty")]pub values: Map<String, Value>,- pub level: Level,+ /// how bad what it finds is (None: the check's own level, else an error)+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub level: Option<Level>,/// where it was written: "raea", or "taste", "workspace" or "project" and the filepub by: String,}@@ -30,7 +32,7 @@ pub struct Rule {impl Rule {/// One of raea's checks by `name`, held to `values`.pub fn named(name: &str, text: &str, values: Map<String, Value>, level: Level, by: &str) -> Rule {- Rule { id: name.into(), text: text.into(), check: name.into(), values, level, by: by.into() }+ Rule { id: name.into(), text: text.into(), check: name.into(), values, level: Some(level), by: by.into() }}/// The project's .ts check this rule runs, when it runs one.@@ -50,21 +52,22 @@ impl Rule {Rule::named(c.form(), text, values, Level::Error, &format!("taste {file}"))}- /// A controller's rule fields, each a rule: a path from `dir` (the controller's folder) made whole, the field's- /// label its words. `by`: "workspace" or "project", with the controller's file.+ /// A controller's rule fields, each a rule: a check's path joined to `dir` (the controller's folder; its `..`+ /// steps are the caller's to take), the field's label its words. `by`: "workspace" or "project", with the+ /// controller's file.pub fn of_controller(c: &controller::Controller, dir: &Path, by: &str) -> Vec<Rule> {let mut out = Vec::new();for f in c.groups.iter().flat_map(|g| &g.fields) {let controller::Kind::Rule { check, values, level } = &f.kind else { continue };let (check, id) = match check.ends_with(".ts") {true => {- let path: PathBuf = dir.join(check);+ let path = dir.join(check);let id = path.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();(path.display().to_string(), id)}false => (check.clone(), check.clone()),};- let level = level.as_deref().map_or(Level::Error, Level::of_word);+ let level = level.as_deref().map(Level::of_word);out.push(Rule { id, text: f.label.clone(), check, values: values.clone().unwrap_or_default(), level, by: by.into() });}out@@ -78,7 +81,7 @@ mod tests {#[test]fn a_taste_form_is_the_named_check_of_the_same_name_and_value() {let r = Rule::of_taste("Captions sit clear of the bottom.", taste::Check::TextAbove(62.0), "taste.ts");- assert_eq!((r.id.as_str(), r.check.as_str(), r.number("value"), r.level), ("text-above", "text-above", Some(62.0), Level::Error));+ assert_eq!((r.id.as_str(), r.check.as_str(), r.number("value"), r.level), ("text-above", "text-above", Some(62.0), Some(Level::Error)));assert!(r.file().is_none() && r.by == "taste taste.ts");}@@ -91,7 +94,7 @@ mod tests {let c = controller::normalize(&raw).unwrap();let rs = Rule::of_controller(&c, Path::new("/p/controllers"), "project controllers/rules.ts");assert_eq!(rs.len(), 2, "a toggle is no rule");- assert_eq!((rs[0].id.as_str(), rs[0].file(), rs[0].level), ("clear", Some(Path::new("/p/controllers/../checks/clear.ts")), Level::Warn));- assert_eq!((rs[1].check.as_str(), rs[1].number("value"), rs[1].level), ("loudness", Some(-14.0), Level::Error));+ assert_eq!((rs[0].id.as_str(), rs[0].file(), rs[0].level), ("clear", Some(Path::new("/p/controllers/../checks/clear.ts")), Some(Level::Warn)));+ assert_eq!((rs[1].check.as_str(), rs[1].number("value"), rs[1].level), ("loudness", Some(-14.0), None));}}diff --git a/docs/direction.feature b/docs/direction.featureindex 7b10fd8b..f4606ed7 100644--- a/docs/direction.feature+++ b/docs/direction.feature@@ -137,6 +137,8 @@ Feature: Direction that holds: one world of facts, findings and rules, so a perscame from; raea's own checks stay in Rust and are registered under the same namesAnd a controller gains one field type, `rule`: `{ text, check, level }`, the check a name (one of raea's) withits values or a path to a project check; a project rule is a controller with rule fields+ # Fixed in the code (DR4): the field's words are its `label`, as every controller field's are, and its values are+ # a field of their own: `{ label, type: "rule", check, values?, level? }`.And the taste file's six forms become six of raea's named checks (same names, same values), so`{ form: "text-above", value: 62 }` still reads and no taste file changesAnd the stages are recorded in .raea/project (`[stage] components = passed <sha>` ...), set by the stage's@@ -327,20 +329,74 @@ Feature: Direction that holds: one world of facts, findings and rules, so a pers# turning the camera away doesn't read as a fix.And `raea next` reads from it (not from a check.json's modified time, as next.rs does now)- @needs:DR1,DR3+ @needs:DR1,DR3 @doneScenario: DR4. A check is a system; raea's own are written the same way+ # Status 11-10: built. A rule is a line and the check that holds it (core/facts rule.rs): one of raea's checks by+ # name with its values, or a project's .ts check by its path. A controller field of type `rule` ({ label, check,+ # values?, level? }) is one; taste's six forms are six named checks with the same names and values. `raea check+ # PROJECT|EDIT.tsx` gathers every rule that applies (raea's floor, the person's taste, the workspace's and the+ # project's controllers), plans the frames each reads, reads those frames' worlds once (DR1, joined with the+ # newest render: DR2), runs raea's named checks in Rust and the project's in raea's JS host (sdk/raea check.ts,+ # imported as raea/check), and keeps the findings in the project's record (DR3). A check that needs a render and+ # has none waits, and the report says what for. A check that throws, a rule file that can't be read and a+ # check's output that can't be read are each a finding, never dropped. `raea check VIDEO.mp4` is the floor, as+ # before. The manual's raea check page has the project form and a check written out.+ # The proof, bench/direction/proof/proof.sh (release binary, M5 Pro; its media made with ffmpeg, nothing+ # downloaded): five checks that import nothing of Bevy's, each run on a piece that holds it (0 findings each) and+ # on a cheat that must fail it. The lyric cheat sets the line as 3D type 0.002 m deep, facing the camera so its+ # frame reads as flat type (seen), with nothing in front: "3d type, 0.002 m deep" and "nothing is in front of the+ # line", frames 6-54. The cut cheat cuts at 1.50 s and 2.50 s, inside "two" and "three": two errors. The mix cheat+ # places a beep that starts after 150 ms of silence: "heard 150 ms after where it is placed". The ad cheat's+ # caption overflows a fixed-height box to 89% down the frame, past the band from 80%. The ride cheat turns the+ # rider with its seat but sets it 10 cm into the seat's back: "10 cm into seat-back", as the geometry has it. And+ # a taste line (text-above 75%, passed with --taste) fails the ad cheat at 89% as the named check of its form.+ # Twelve cases, all as expected, in 18.8 s with the four renders they need.+ # Found and fixed on the way: a text's box was its element's even when its words were drawn past it (the caption+ # cheat passed: engine/page's manifest now grows the box over its lines); a word a cut passes through was in+ # neither clip's words (the cut cheat passed); a part's world box is the box around it as turned, so a rider on a+ # turned seat read as inside its back (a Part now has its `own` box before its transform); a relative+ # EDIT.tsx found no project (its parent is ""); the help's flag check refused --only, and read `[A | B]` as two+ # arguments.+ # Proved by tests in raea-app-direction (9), raea-core-facts (11: the generated TS types match the committed+ # file), raea-runtime-world (12), raea-app-check (27), raea-core-brief (11), raea-app-workspace (7), raea-page+ # (7), and the proof.+ # Not seen, or left: of the proof's renders I looked at one frame each of the lyric and its cheat; the others+ # were not watched, and the mix was not listened to (the cue's 150 ms is the onset measure). A check whose file+ # fails as its bundle loads is a finding only after the JS host's 120 s limit. A composition's newest render is+ # found by its file, size and rate, so two compositions of one file with the same size share one. The cue check+ # tests placement only: what causes a cue is DR21's CausedBy. The rider check names its parts in the rule's+ # values until DR16's Rides says it. Shane's taste files have no line with a check today, so his taste adds no+ # rule to a run until one does.Given the plan| crate | file | lines | job || raea-app-direction | apps/direction/src/systems.rs | 300 | raea's checks registered by name with their values; a project's TS checks run beside them || raea-core-facts | core/facts/src/rule.rs | 180 | Rule: text, check (a name and values, or a path), level; taste's Check as six of them |- And sdk/raea/src/check.ts (about 220 lines): `check({ id, text, needs, level }, (world, frame) => ...)`,- `found(...)`, and the components' types generated from core/facts (ts-rs, as core/brief's are)- Then `raea check [PROJECT | EDIT.tsx | VIDEO.mp4] [--stage S] [--only ID] [--json]` runs every check that- applies: raea's floor, the person's taste, the workspace's and the project's rules, the project's notes+ | raea-app-direction | apps/direction/src/check.rs | 320 | `raea check PROJECT|EDIT.tsx`: the rules that apply, the frames each reads, the worlds read once, the report and the record |+ | raea-app-direction | apps/direction/src/ts.rs | 140 | a project's TS checks bundled with raea/check and run on the worlds in raea's JS host |+ | raea-core-brief | core/brief/src/controller.rs | 240 | the controller field type `rule` |+ # Fixed in the code (DR4): the plan had systems.rs run the project's TS checks too. The command (which rules+ # apply, which frames to read) and the call into the JS host are files of their own, so systems.rs holds raea's+ # named checks alone. The field type `rule` is DR8's in its plan (rule_field.rs), but `raea check` can't run a+ # project's rules until a controller can hold one, so it is built here, in controller.rs beside the other kinds.+ And sdk/raea/src/check.ts (about 220 lines): `check({ id, text, needs, level, frames }, (world, frame, values)+ => ...)`, `found(...)`, and the components' types generated from core/facts (ts-rs, as core/brief's are)+ # Fixed in the code (DR4): the system was `(world, frame)`. A rule carries values (the caption band's 0.8, the+ # rider's part names), and a check reads them from its third argument, so one check file serves rules with+ # different limits. The types are generated to sdk/raea/src/facts.gen.ts; a test fails when they differ.+ Then `raea check [PROJECT|EDIT.tsx] [--composition ID] [--only ID] [--taste T] [--render OUT | --no-render]+ [--json]` runs every check that applies: raea's floor, the person's taste, the workspace's and the project's+ rules+ # Fixed in the code (DR4): this line had `--stage S`, "the project's notes" and VIDEO.mp4 as a third form. Stages+ # are DR10's and notes DR5's and DR6's: until then there is no stage for --stage to pick and no note to run, so+ # each joins `raea check` in its own scenario (DR6 and DR10 now say so). A video has no composition to read into a+ # world, so `raea check VIDEO.mp4` stays apps/check's floor, and a project's floor runs on its newest video render.+ # --composition picks one of a file's compositions; --render and --no-render are DR2's, as `raea world` has them.And a check says whether it needs a render (`needs: "render"`); on a project or composition with no render,`raea check` runs the checks that need none and lists each that waits, with what it waits for (DR2's Waits)- And a check is told once what it ranges over (`frames: "all" | "cuts" | "lines" | [..]`) and is run there; it- finds entities, measures, and calls `found(...)`; it never prints+ And a check is told once what it ranges over (`frames: "all" | "cuts" | "lines" | "once" | [..]`) and is run+ there; it finds entities, measures, and calls `found(...)`; it never prints+ # Fixed in the code (DR4): "once" is added, for a check of the whole piece (the floor, loudness, a still's longest+ # hold): it runs on one world, which holds the render's resources.And the same check text reads for a mesh and for a caption: `world.find({ with: ["Text", "Layer"] })`And proved in small on 11-10 (bench/direction/proto/world.ts, plain bun, raea/ecs as it is today, no engine):one world holding a 2D lyric layer, a 3D rider and seat, a footage cut and a sound cue; four checks as@@ -381,6 +437,7 @@ Feature: Direction that holds: one world of facts, findings and rules, so a persThen an ask's check is a system (DR4) written in the note's file or named from raea's, and `raea notes check`must show it failing on the work as it stands before the work may change (a check that already passes isrefused: it isn't measuring the ask)+ And `raea check` runs the project's notes' checks with its rules (moved here from DR4, which has no notes to run)And each finding carries the ask that asked for it (`by`), so two asks that use one named check are toldapart (the prototype counted both asks' findings against each until it did)And where the ask can't be measured, its proof is a clip: `proof: { shot | frames, sign: true }`; it passes only@@ -411,8 +468,10 @@ Feature: Direction that holds: one world of facts, findings and rules, so a persScenario: DR8. A note's check climbs to a rule, and to tasteGiven the plan| crate | file | lines | job |- | raea-core-brief | core/brief/src/rule_field.rs | 90 | a controller field of type `rule` (controller.rs's Kind gains it) |- | raea-app-workspace | apps/workspace/src/rules.rs | 80 | rule fields read as checks; `raea notes keep ID --as project, workspace or taste` |+ | raea-app-workspace | apps/workspace/src/rules.rs | 80 | `raea notes keep ID --as project, workspace or taste` |+ # Fixed in the code (DR4): the field type `rule` and reading rule fields as checks were planned here+ # (rule_field.rs, and rules.rs's first job). `raea check` needed both to run a project's rules, so DR4 built them:+ # Kind::Rule in core/brief controller.rs, and the rules read in apps/direction check.rs.Then `raea notes keep` moves a note's check to controllers/<id>.ts as a rule field (project or workspace), orto the person's taste as a rule; the note keeps a pointer; the check's text is not copiedAnd the taste loop (docs/craft-system.md J) proposes this when a correction repeats, as it does now, and now@@ -439,6 +498,7 @@ Feature: Direction that holds: one world of facts, findings and rules, so a persAnd each stage closes by its review (`raea stage review components` ...), which runs that stage's checks andmakes what a person looks at (a sheet for components, clips for the rest); the person's yes, or the checksalone where the brief says so, records it in .raea/project+ And `raea check --stage S` runs that stage's checks alone (moved here from DR4, which has no stages to pick)And `raea next` names the open stage and its first failing check, and no longer says "stills to look at first"And starting a later stage's work on a failing earlier one is a finding at every render, not a refusal of thefile save: a camera can be sketched early, but nothing with a camera can be posteddiff --git a/docs/manual/reference/cli/check.md b/docs/manual/reference/cli/check.mdindex b59117f5..f6d20f11 100644--- a/docs/manual/reference/cli/check.md+++ b/docs/manual/reference/cli/check.md@@ -1,8 +1,8 @@---title: "raea check"-summary: "Check a composition's text in a second, or an export against the floor: text, contrast, safe areas, freezes, flashing, cues and loudness."+summary: "Check a composition's text in a second, a project against every rule it holds, or an export against the floor: text, contrast, safe areas, freezes, flashing, cues and loudness."order: 42-sources: ["apps/check/src/lib.rs", "apps/check/src/quick.rs"]+sources: ["apps/check/src/lib.rs", "apps/check/src/quick.rs", "apps/direction/src/check.rs", "sdk/raea/src/check.ts"]---`raea check` has two speeds. On a composition with `--quick`, it renders three stills and measures the text:@@ -25,12 +25,46 @@ the platform's buttons, captions held too briefly and caption contrast. The tranword and music fighting the voice; the perception adds text over a face. A taste file adds the person's own rules,each an error when broken, since their rule beats the floor's default.+## Every rule a project holds++On a project, or a composition's file, with no `--quick`, `raea check` runs every rule that applies to each+composition: raea's floor on its newest render, your taste's measurable lines, and the rules in the workspace's and+the project's controllers. A rule is a controller field of type `rule`: its words, and the check that holds it,+either one of raea's by name with its values or a `.ts` check of your own.++```ts+// controllers/rules.ts+{ label: "Captions clear the button band", type: "rule", check: "../checks/caption.ts", values: { band: 0.8 } }+```++A check is a system over the composition's world, the same world `raea world` prints, so it reads a caption, a+footage cut, a cue and a 3D part the same way. It says which frames it ranges over and whether it needs a render, and+calls `found` for each thing that breaks the rule; it never prints.++```ts+// checks/caption.ts+import { check, found, type Layer, type Text } from "raea/check";++export default check({ id: "caption", text: "a caption clears the platform's button band" }, (world, _frame, values) => {+ const band = Number(values.band ?? 0.8);+ for (const t of world.find({ with: ["Text", "Layer"] })) {+ if (world.component<Layer>(t, "Layer")!.medium !== "2d-type") continue;+ const box = world.component<Text>(t, "Text")!.box; // in frame fractions: left, top, right, bottom+ if (box && box[3] > band) found({ about: [t], says: `the caption reaches ${Math.round(box[3] * 100)}% down the frame` });+ }+});+```++What needs a render and has none waits, and the report says what it waits for. A render older than the composition's+last change is still joined, with a note that what it measured may have moved.+<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->## Usage```shraea check EDIT.tsx --quick [--shape S] [--platform P] [--taste T] [-o check.json] (three stills of a composition checked for text: clipped, cramped, safe areas, sizes; about a second)+raea check [PROJECT|EDIT.tsx] [--composition ID] [--only ID] [--taste T] [--render OUT | --no-render] [--json] (every check that applies to each composition, over its frames: raea's floor on its newest render, the person's taste, the workspace's and the project's rules (a controller's rule fields: one of raea's checks by name, or a project's .ts check); what needs a render and has none waits, and says so)raea check VIDEO.mp4 [--manifest render.json] [--words W.json] [--perception P.json] [--shape 16:9|9:16|4:5|1:1] [--platform tiktok|reels|shorts] [--taste taste.ts|DIR] [-o check.json] (an export against the floor: clipped text, contrast, safe areas, freezes, flashing, cues, loudness, blotching, a placeholder brand kit; its findings errors, warns and notes)```@@ -40,10 +74,15 @@ Headless: it needs nothing running and opens no window. Takes up to 1 argument b| Flag | Takes | What it does || --- | --- | --- |+| `--composition` | `ID` | Check one composition of the file or project instead of every one. |+| `--json` | – | Print the findings as JSON (one Finding each, as the project's record keeps them) instead of lines. || `--manifest` | `render.json` | The manifest `raea render --manifest` wrote for this export: where each element was on each frame, for the text, contrast and safe-area checks. |+| `--no-render` | – | Join no render: run only the checks that need none, and list the rest as waiting. |+| `--only` | `ID` | Run one rule's check: a check of raea's by name (`text-above`) or a project check's id (its `check({ id })`). || `--perception` | `P.json` | Where the face is on each frame (the `perception.json` `raea cut` writes), to find text over a face. || `--platform` | `P` | Check the safe areas against this platform's buttons and captions. || `--quick` | – | Check a composition's text from three stills instead of checking an export. |+| `--render` | `OUT` | Join this render instead of the composition's newest in the project's record. || `--shape` | `S` | The delivery's aspect ratio, for its safe areas. || `--taste` | `T` | The person's taste files: the rules in them that carry a `check` are applied too. || `--words` | `W.json` | The transcript, to check cues against their words and the voice against the music. |diff --git a/docs/manual/reference/cli/index.md b/docs/manual/reference/cli/index.mdindex bb2b399c..951e5fd9 100644--- a/docs/manual/reference/cli/index.md+++ b/docs/manual/reference/cli/index.md@@ -61,7 +61,7 @@ What's wrong before anyone watches it.| Verb | What it does || --- | --- |-| [`raea check`](check.md) | Check a composition's text in a second, or an export against the floor: text, contrast, safe areas, freezes, flashing, cues and loudness. |+| [`raea check`](check.md) | Check a composition's text in a second, a project against every rule it holds, or an export against the floor: text, contrast, safe areas, freezes, flashing, cues and loudness. || [`raea judge`](judge.md) | Judge a 3D scene's review sheets blind, by a model on a frozen rubric or a fresh agent session, with the pass decided in code. || [`raea findings`](findings.md) | What each render and check found, read back from the project's record: fixed, new and carried since the one before. || [`raea scene`](scene.md) | Find floating, sunk and clipping 3D parts, say what each part rests on, and meter a shot's light. |diff --git a/engine/cli/src/cli.rs b/engine/cli/src/cli.rsindex 7b133e49..6cc68efe 100644--- a/engine/cli/src/cli.rs+++ b/engine/cli/src/cli.rs@@ -131,7 +131,7 @@ pub fn run(args: &[String]) -> R<String> {// a workspace's files and specs (docs/projects.feature), listed under render's usage like librarylet usage = format!("{usage}\n raea spec FILE.ts [--as brief|script|taste|plan|controller] (a spec's default export as JSON, checked against its schema: brief.ts, script.ts, taste.ts, plan.ts, controllers/ID.ts)\n raea workspace init [NAME] [--layout LAYOUT] | raea workspace adopt DIR [--name NAME] | raea workspace [--json] (a workspace: a git repo of projects and controllers under raea.root, ~/Documents/raea unless git config says)\n raea project new NAME [--storage inline|submodule] | raea project split NAME [--remote URL] | raea project join NAME | raea project [--json] (a project in the workspace: its folder, brief.ts, media/, out/; split and join keep its history)\n raea controller ls [--json] | raea controller get PATH [--json] | raea controller set PATH VALUE [--project] [--by NAME] | raea controller write FILE.ts [--by NAME] | raea controller rm ID [--by NAME] (the workspace's controllers, controllers/ID.ts; PATH is controller.group.field; every change a commit)\n raea check EDIT.tsx --quick [--shape S] [--platform P] [--taste T] [-o check.json] (three stills of a composition checked for text: clipped, cramped, safe areas, sizes; about a second)\n raea hook [claude|codex|gemini|kimi] (every agent's tool hooks, which raea skills install adds: before a shell command, media opened in the Mac's viewer while the raea app is installed is stopped once for raea show (the same command again goes through); after a save, the quick check on a composition)\n raea next [DIR] (the two or three useful next steps for the project, from its brief, compositions, renders and checks)\n raea doctor [--fix] [DIR] (what doesn't match this raea: old brief files, an older workspace format, an agent's skill from another version)\n raea app run|check|bundle APP.tsx [--target web|native] [--size WxH] [--script steps.json] [--png DIR] [-o App.app] (a TSX app on @raea/ui: its window, the headless check, a Mac app; web is Blitz on Bevy, native is Rune; the app's `export const app` sets the target, web when it doesn't; raea rune ... is --target native)\n {}\n {}", skill::USAGE, tools::blender::USAGE);let (export_game, scene, physics, splat) = (raea_app_game::USAGE, export::SCENE_USAGE, motion::physics::USAGE, tools::splat::USAGE);- let apps = format!(" {}\n {}\n {}\n {}\n {}\n", raea_app_check::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, raea_app_direction::USAGE, raea_app_direction::findings::USAGE);+ let apps = format!(" {}\n {}\n {}\n {}\n {}\n {}\n", raea_app_direction::check::USAGE, raea_app_check::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, raea_app_direction::USAGE, raea_app_direction::findings::USAGE);return Ok(format!("raea: renders, plays and checks raea compositions (React and TypeScript) on the GPU.\n\nusage: {usage}\n raea init (a project's files where they're missing: edit.tsx, cuts.ts, components/, AGENTS.md)\n raea cut TAKE \"line\" ... | --at A-B ... [--append] (cuts.ts and words.json: a take under media/ cut in the pauses around each line it says, transcribed first if it has no TAKE.words.json; or at those seconds)\n raea frame TAKE [--at S] (how a take fits the edit: a talking take for <FaceFrame>, a screen for <ScreenFit>, from where its face is)\n raea part list | raea part add NAME ... [--force] (a ready part copied into components/, yours to change)\n raea brand DOMAIN|URL (the brand kit read from its website on this machine: brand/brand.css, brand/brand.json, BRAND.md, logos in media/brand; says when a plain fetch saw too little)\n raea guide [NAME] (craft, the floor read before any edit; the modes: pitch, explain, story, play, tool; motion, music, layout and the rest; bevy and bevy/NAME for 3D)\n raea context PROJECT (what to read before working on a project: taste, brief, look, the floor and its modes' guides)\n{apps} raea play EDIT.tsx [--input | --input-script KEYS.json] [--size WxH] [--seconds N|end] (a game, live; also: --input-log FILE --offscreen --snapshot T FILE --json FILE --seek F FILE --pick X,Y --view YAW,PITCH,DISTANCE --scrub N --baked --autoplay --no-vsync --master --3d)\n {export_game} (a game as a program of its own: a Mac app or a command)\n {scene} (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)\n {physics} (the bakes <Physics> and <Goo> make)\n {splat} (footage trained into a Gaussian splat for <Splat>; setup installs its tools)\n raea run SCRIPT.ts (a TypeScript program on the engine, headless: its default export is called, what it prints is the answer; a check like a room's checkLayout; also: --timeout S)\n raea gen image|video|music|sfx|speech|mesh|text \"PROMPT\" | gen plan|run FLOW.ts|FLOW.json | gen comfy import|export|run|schema FILE | gen models | gen balance (generated media through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI; ComfyUI workflows both ways: raea gen alone lists its flags)\n {neural_usage} (DLSS 5 neural rendering on a `render --aov` folder, with its motion and depth: your own MLX-DLSS build and weights, RAEA_MLXDLSS and RAEA_DLSS_MODEL)\n raea mezz [--check] PATH... (an intra-only ProRes copy of each long-GOP source over 1080p, for smooth scrubbing; --check says which would get one)\n raea traces [show [N|last|DIR]] (the sessions raea left, newest first: how each ended, its glitches; show tells one in full)"));}// `--version`: the release's version, which a skill's front matter names (docs/skills.feature SK6)@@ -199,6 +199,11 @@ pub fn run(args: &[String]) -> R<String> {if args[0] == "hook" {return raea_app_check::hook::hook(&args[1..]);}+ // `check PROJECT|EDIT.tsx`: every rule's check over the compositions' worlds (DR4); a video is the floor alone+ if args[0] == "check" && !raea_app_direction::check::of_video(&args[1..]) {+ let ts = raea_app_direction::ts::Host { eval: spec::spec_json, run: run_bundle };+ std::process::exit(raea_app_direction::check::cli(&args[1..], &raea_app_direction::check::Host { ts, kinds: taste_kinds }));+ }if args[0] == "check" {std::process::exit(raea_app_check::cli_with(&args[1..], spec::tastes_ts(args)?));}diff --git a/engine/cli/src/guide.rs b/engine/cli/src/guide.rsindex 191b5eb3..61d41334 100644--- a/engine/cli/src/guide.rs+++ b/engine/cli/src/guide.rs@@ -62,7 +62,7 @@ pub fn context(project: Option<&str>) -> R<String> {let brief_path = brief_at(project)?;let spec::Loaded { path: brief_path, text: brief, title, modes, more: subs, look, .. } = spec::load_brief_ts(&brief_path)?;let dir = brief_path.parent().unwrap_or(Path::new(".")).to_path_buf();- let taste_dir = std::env::var_os("RAEA_TASTE").map(PathBuf::from).or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".raea/taste")));+ let taste_dir = raea_app_direction::check::taste_dir();// a cheap doctor (file reads and git config): CONTEXT_STALE when this project or the agent's skill is from another raealet stale = raea_app_workspace::doctor::findings(&dir, &skill::agents(), &skill::version());let stale = match stale.first() {diff --git a/engine/cli/src/lib.rs b/engine/cli/src/lib.rsindex e05c8caf..01043bfb 100644--- a/engine/cli/src/lib.rs+++ b/engine/cli/src/lib.rs@@ -32,7 +32,7 @@ pub fn main() -> i32 {match args.first().map(String::as_str) {// `check VIDEO.mp4 …`: the floor's measurable lines on an export, ranked P0-P3// (with --taste or --quick, through the engine, which evaluates the taste.ts files or renders stills: `check` here)- Some("check") if !args.iter().any(|a| a == "--taste" || a == "--quick") => raea_app_check::cli_with(&args[1..], Vec::new()),+ Some("check") if !args.iter().any(|a| a == "--taste" || a == "--quick") && raea_app_direction::check::of_video(&args[1..]) => raea_app_check::cli_with(&args[1..], Vec::new()),// `ci …`: the gates' sound measurements and lightspeed's process measurementsSome("ci") => raea_app_ci::cli(&args[1..]),_ => {diff --git a/engine/cli/src/spec.rs b/engine/cli/src/spec.rsindex 70931024..1348dfd2 100644--- a/engine/cli/src/spec.rs+++ b/engine/cli/src/spec.rs@@ -83,20 +83,9 @@ pub fn taste_file(dir: &Path, name: &str) -> Option<(PathBuf, String)> {})}-/// The .ts files `--taste` names: the file, or every .ts in the folder.-fn taste_ts_files(args: &[String]) -> Vec<PathBuf> {- let Some(t) = args.iter().position(|a| a == "--taste").and_then(|i| args.get(i + 1)).map(PathBuf::from) else { return vec![] };- if t.extension().is_some_and(|x| x == "ts") {- return vec![t];- }- let mut v: Vec<PathBuf> = std::fs::read_dir(&t).into_iter().flatten().filter_map(|e| e.ok().map(|e| e.path())).filter(|f| f.extension().is_some_and(|x| x == "ts")).collect();- v.sort();- v-}-/// `--taste`'s .ts files, each checked as Taste.pub fn tastes_ts(args: &[String]) -> R<Vec<schema::Taste>> {- taste_ts_files(args).iter().map(|f| read_spec(f)).collect()+ raea_app_direction::check::taste_files(args).iter().map(|f| read_spec(f)).collect()}/// `raea spec FILE.ts [--as KIND]`: the default export as JSON, checked as KIND (by default from the file's name:diff --git a/engine/cli/src/tests.rs b/engine/cli/src/tests.rsindex 58e68685..f40668ed 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_direction::USAGE, raea_app_game::USAGE, raea_runtime_export::SCENE_USAGE, motion::physics::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_direction::check::USAGE, raea_app_direction::USAGE, raea_app_game::USAGE, raea_runtime_export::SCENE_USAGE, motion::physics::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/engine/page/src/motion/manifest.rs b/engine/page/src/motion/manifest.rsindex 2bf48ae9..7c43665f 100644--- a/engine/page/src/motion/manifest.rs+++ b/engine/page/src/motion/manifest.rs@@ -113,7 +113,17 @@ impl BlitzPage {TextAlignKeyword::Justify => "justify",_ => "left",};- let mut t = json!({"text": words, "box": [r(b.x), r(b.y), r(b.width), r(b.height)], "opacity": (alpha(owner) * 100.0).round() / 100.0,+ // words set in an element shorter or narrower than they are (a fixed height, overflow visible) are drawn+ // past it: the text's box is where they are, so it grows to cover its lines (DR4's caption cheat)+ let (mut w, mut h) = (b.width, b.height);+ if let Some(l) = node.element_data().and_then(|e| e.inline_layout_data.as_ref()) {+ let (fl, scale) = (node.final_layout(), doc.viewport().scale() as f64);+ // the element's own size to its bounding rect's (a transform scales one into the other)+ let (fx, fy) = (b.width / (fl.size.width as f64).max(1e-6), b.height / (fl.size.height as f64).max(1e-6));+ w = w.max(((fl.border.left + fl.padding.left) as f64 + l.layout.width() as f64 / scale) * fx);+ h = h.max(((fl.border.top + fl.padding.top) as f64 + l.layout.height() as f64 / scale) * fy);+ }+ let mut t = json!({"text": words, "box": [r(b.x), r(b.y), r(w), r(h)], "opacity": (alpha(owner) * 100.0).round() / 100.0,"color": color, "size": font.font_size.computed_size().px() as f64, "weight": font.font_weight.value() as f64, "align": align});// its first named face and how many lines it was set on (docs/direction.feature DR1's Text)if let Some(f) = font.font_family.families.iter().find_map(|f| match f { style::values::computed::font::SingleFontFamily::FamilyName(n) => Some(n.name.to_string()), _ => None }) {diff --git a/runtime/world/src/lib.rs b/runtime/world/src/lib.rsindex d253ce58..7b2b1d15 100644--- a/runtime/world/src/lib.rs+++ b/runtime/world/src/lib.rs@@ -28,10 +28,14 @@ type R<T> = Result<T, String>;/// What a read is asked for: the frames, and whether the page is laid out (without it, its text carries/// `needs: "render"`, as no box or size is known).pub struct Ask {+ /// none: every frame of the composition (`raea check`'s checks that range over all of them)pub frames: Vec<i64>,pub layout: bool,/// which render's facts join the world (DR2)pub render: Render,+ /// the frames it joins (None: every frame asked); `raea check` joins it only where a check needs a render, as a+ /// text's contrast is measured on each frame it joins+ pub join_on: Option<BTreeSet<i64>>,}/// One stepped frame: its 3D, its React tree, and its page as laid out.@@ -72,7 +76,8 @@ fn stepped(js: &Path, tsx: &Path, ask: &Ask, words: Option<&Value>) -> R<Vec<Facif let Some(f) = ask.frames.iter().find(|f| **f < 0 || **f >= length) {return Err(format!("there's no frame {f}: the composition has frames 0 to {}", length - 1));}- let wanted: BTreeSet<i64> = ask.frames.iter().copied().collect();+ let asked: Vec<i64> = if ask.frames.is_empty() { (0..length).collect() } else { ask.frames.clone() };+ let wanted: BTreeSet<i64> = asked.iter().copied().collect();// and each one's next frame, for what moves (the camera's velocity)let all: BTreeSet<i64> = wanted.iter().flat_map(|&f| [f, f + 1]).filter(|f| *f < length).collect();let mut page = page::Page::new(ask.layout, w, h, dir);@@ -88,8 +93,7 @@ fn stepped(js: &Path, tsx: &Path, ask: &Ask, words: Option<&Value>) -> R<Vec<Fac}let lines = timeline::project_lines(words, dir, fps);let mut render = renders::find(&ask.render, tsx, (w, h, fps));- let worlds = ask- .frames+ let worlds = asked.iter().map(|&f| {let now = &snaps[&f];@@ -99,7 +103,7 @@ fn stepped(js: &Path, tsx: &Path, ask: &Ask, words: Option<&Value>) -> R<Vec<Factimeline::put(&mut facts, &now.tree, now.laid.as_ref(), (w, h, fps), dir, &mut order);timeline::put_lines(&mut facts, &lines, &now.tree, f, fps);// what only a render knows, or what waits for one (DR2)- if ask.render != Render::Off {+ if ask.render != Render::Off && ask.join_on.as_ref().is_none_or(|on| on.contains(&f)) {renders::join(&mut facts, render.as_mut(), &now.tree);}factsdiff --git a/runtime/world/src/scene.rs b/runtime/world/src/scene.rsindex d9e69554..8af7c45b 100644--- a/runtime/world/src/scene.rs+++ b/runtime/world/src/scene.rs@@ -48,10 +48,13 @@ pub(crate) fn part(it: &Item) -> Part {let (scale, rot, at) = it.world.to_scale_rotation_translation();let tris = raea_core_scene::own_tris(it).ok();let (mut lo, mut hi, mut n) = (Vec3::splat(f32::MAX), Vec3::splat(f32::MIN), 0u32);+ let (mut own_lo, mut own_hi) = (lo, hi);for (_, ts) in tris.iter().flat_map(|t| t.0.iter()) {for t in ts {n += 1;- for p in t.map(|p| it.world.transform_point3(p)) {+ for &p in t {+ (own_lo, own_hi) = (own_lo.min(p), own_hi.max(p));+ let p = it.world.transform_point3(p);(lo, hi) = (lo.min(p), hi.max(p));}}@@ -66,6 +69,7 @@ pub(crate) fn part(it: &Item) -> Part {scale: f3(scale),min: (n > 0).then(|| f3(lo)),max: (n > 0).then(|| f3(hi)),+ own: (n > 0).then(|| [f3(own_lo), f3(own_hi)]),triangles: tris.is_some().then_some(n),src: it.props.get("src").and_then(Value::as_str).map(str::to_string),material: material.map(|m| m.kind.to_string()),diff --git a/runtime/world/src/timeline.rs b/runtime/world/src/timeline.rsindex 538f9f16..05a4d030 100644--- a/runtime/world/src/timeline.rs+++ b/runtime/world/src/timeline.rs@@ -242,7 +242,8 @@ pub(crate) fn put(facts: &mut Facts, tree: &[El], laid: Option<&Value>, (w, h, f/// The words a take's transcript (TAKE.words.json, beside it) has between `from` and `out` seconds of the take.fn list_words(take: &Path, fps: f64, from: f64, out: Option<f64>) -> Vec<Word> {- words(&take.with_extension("words.json"), fps).into_iter().filter(|w| w.start >= from && out.is_none_or(|o| w.start < o)).collect()+ // any word the clip holds part of: one its in or out point cuts through is in it (a check of where a cut lands reads it)+ words(&take.with_extension("words.json"), fps).into_iter().filter(|w| w.end > from && out.is_none_or(|o| w.start < o)).collect()}#[cfg(test)]diff --git a/sdk/raea/src/check.ts b/sdk/raea/src/check.tsnew file mode 100644index 00000000..3a5f7e58--- /dev/null+++ b/sdk/raea/src/check.ts@@ -0,0 +1,183 @@+// raea/check: a check is a system over the world (docs/direction.feature DR4). `raea check` reads each composition's+// frames into worlds holding the components `raea world` prints (raea-core-facts; their types are facts.gen.ts,+// generated from the Rust), joins the composition's newest render, and runs every check that applies on the frames it+// says it ranges over. A check finds entities, measures, and calls `found`; it never prints. raea's own checks are+// the same thing written in Rust, run under the same names, and a check reads the same for a mesh, a caption, a cut+// or a cue: nothing here is 3D's.+//+// // checks/clear.ts, run by a rule a controller holds:+// // { label: "Captions clear the button band", type: "rule", check: "../checks/clear.ts", values: { band: 0.8 } }+// import { check, found, type Text } from "raea/check";+// export default check({ id: "caption-clear", text: "Captions clear the button band" }, (world, frame, values) => {+// for (const t of world.find({ with: ["Text", "Layer"] })) {+// const box = world.component<Text>(t, "Text")?.box;+// if (box && box[3] > Number(values.band ?? 0.8)) found({ about: [t], says: "the caption runs into the button band" });+// }+// });++import { createWorld, type World } from "@raea/app/ecs";+import type { About, Finding, Level, Measure } from "./facts.gen";++export type * from "./facts.gen";+export type { World };++/** The frames a check runs on: every frame; the first frame of each shot after the first, and the frame before it;+ * every frame a line is said or sung on; once, on the first frame (for what is the piece's, as its mix); or these. */+export type Frames = "all" | "cuts" | "lines" | "once" | number[];++export interface CheckMeta {+ /** what `raea check --only` names, and its findings' check */+ id: string;+ /** the line it holds the work to */+ text: string;+ /** "render": it reads what only a render has (Contrast, Picture, Mix, Onset, Covers); with none, it waits for one */+ needs?: "render";+ /** how bad what it finds is, where a finding doesn't say (error when unset) */+ level?: Level;+ /** where it runs ("all" when unset) */+ frames?: Frames;+}++/** A rule's values for its check (a controller's `values`). */+export type Values = Record<string, number | string | boolean>;+/** The system: a frame's world, the frame, and the rule's values. */+export type CheckFn = (world: World, frame: number, values: Values) => void;+export interface Check extends CheckMeta {+ run: CheckFn;+}++/** A check: what it holds the work to, and the system that finds where the work doesn't hold. */+export function check(meta: CheckMeta, run: CheckFn): Check {+ return { ...meta, run };+}++/** What a check found: the entities it is about, what it says, and, where they aren't the check's or the frame's,+ * its level and frames (its first, and the frame after its last); the number it turns on and the fix, when there+ * are. */+export interface Found {+ about?: number[];+ says: string;+ level?: Level;+ frames?: [number, number];+ measure?: Omit<Measure, "limit"> & { limit?: number };+ fix?: string;+}++let running: { world: World; frame: number; check: Check; plan: Planned; out: Finding[] } | null = null;++/** Says what the running check found. Only inside a check's system, as raea check runs it. */+export function found(f: Found): void {+ if (!running) throw new Error("found() is for a check's system: raea check runs it on each frame");+ const { world, frame, check: c, plan, out } = running;+ out.push({+ check: c.id,+ // the finding's own level, else its rule's, else the check's+ level: f.level ?? plan.level ?? c.level ?? "error",+ about: (f.about ?? []).map((id) => aboutOf(world, id)),+ frames: f.frames ?? [frame, frame + 1],+ says: f.says,+ measure: f.measure ? { ...f.measure, limit: f.measure.limit ?? null } : null,+ fix: f.fix ?? null,+ by: plan.by ?? "",+ } as Finding);+}++/** An entity as a finding names it: its words, its part's or shot's name, its sound, its component; its layer key. */+function aboutOf(world: World, id: number): About {+ const c = world.components(id) as Record<string, Record<string, unknown> | undefined>;+ const name = [c.Text?.words, c.Part?.name, c.Shot?.name, c.Cue?.source, c.Clip?.source, c.Source?.component].find((v) => typeof v === "string" && v);+ const key = c.Source?.key;+ return { name: String(name ?? `entity ${id}`), ...(typeof key === "string" ? { key } : {}) } as About;+}++/** A frame's facts as `raea world --json` prints them. */+export interface Facts {+ frame: number;+ width: number;+ height: number;+ fps: number;+ entities: { id: number; parent?: number | null; components: Record<string, unknown> }[];+ resources?: Record<string, unknown>;+}++/** A frame's facts as a raea/ecs world: the same components, the frame's size and rate as the `Frame` resource, and+ * what the render added as resources. An entity's references to others (a Covered's `layer`, a relation's `to`)+ * are its id in this world. */+export function worldOf(facts: Facts): World {+ const w = createWorld({ native: false });+ const ids = new Map<number, number>();+ for (const e of facts.entities) ids.set(e.id, w.add({}, e.parent != null && ids.has(e.parent) ? { parent: ids.get(e.parent) } : {}));+ const to = (v: unknown): unknown => {+ if (Array.isArray(v)) return v.map(to);+ if (!v || typeof v !== "object") return v;+ const o = { ...(v as Record<string, unknown>) };+ for (const k of ["layer", "to"]) if (typeof o[k] === "number" && ids.has(o[k] as number)) o[k] = ids.get(o[k] as number);+ return o;+ };+ for (const e of facts.entities) w.insert(ids.get(e.id)!, Object.fromEntries(Object.entries(e.components).map(([k, v]) => [k, to(v)])));+ w.resource("Frame", { frame: facts.frame, width: facts.width, height: facts.height, fps: facts.fps });+ for (const [k, v] of Object.entries(facts.resources ?? {})) w.resource(k, v);+ return w;+}++/** Each check's declaration, as raea check reads it before it reads any frame. */+export function declared(checks: Check[]): CheckMeta[] {+ return checks.map((c, i) => {+ if (!c || typeof c.run !== "function") throw new Error(`check ${i + 1}: its file's default export isn't a check({ id, text }, system)`);+ return { id: c.id, text: c.text, needs: c.needs, level: c.level ?? "error", frames: c.frames ?? "all" };+ });+}++/** Which check runs on which frames with which values, as raea check plans it from a rule: the rule's level (none:+ * the check's own) and where the rule was written. */+export interface Planned {+ check: number;+ frames: number[];+ values: Values;+ level?: Level | null;+ by?: string;+}++/** Every planned check run on its frames' worlds: what they found, a run of frames finding the same thing as one+ * finding over those frames, and each check that threw, with what it threw. */+export function runChecks(checks: Check[], plan: Planned[], worlds: Facts[]): { findings: Finding[]; threw: { check: string; says: string }[] } {+ const out: Finding[] = [];+ const threw: { check: string; says: string }[] = [];+ for (const facts of worlds) {+ const here = plan.filter((p) => p.frames.includes(facts.frame));+ if (!here.length) continue;+ const world = worldOf(facts);+ for (const p of here) {+ const c = checks[p.check];+ running = { world, frame: facts.frame, check: c, plan: p, out };+ try {+ c.run(world, facts.frame, p.values);+ } catch (e) {+ if (!threw.some((t) => t.check === c.id)) threw.push({ check: c.id, says: `at frame ${facts.frame}: ${e instanceof Error ? e.message : String(e)}` });+ } finally {+ running = null;+ }+ }+ }+ return { findings: joined(out), threw };+}++/** Findings that say the same about the same on frames one after another, as one over all of them. */+function joined(fs: Finding[]): Finding[] {+ const out: Finding[] = [];+ const last = new Map<string, Finding>();+ for (const f of fs) {+ const k = JSON.stringify([f.check, f.level, f.says, f.about, f.measure, f.fix, f.by]);+ const prev = last.get(k);+ const [a, b] = (f.frames ?? [0, 0]) as [number, number];+ const pf = prev?.frames as [number, number] | undefined;+ // a run's end is the frame after its last, so the next frame starts where it ends+ if (prev && pf && a <= pf[1]) {+ prev.frames = [pf[0], Math.max(pf[1], b)] as Finding["frames"];+ continue;+ }+ out.push(f);+ last.set(k, f);+ }+ return out;+}diff --git a/sdk/raea/src/facts.gen.ts b/sdk/raea/src/facts.gen.tsnew file mode 100644index 00000000..a7c5b108--- /dev/null+++ b/sdk/raea/src/facts.gen.ts@@ -0,0 +1,128 @@+// Generated from raea-core-facts (core/facts) by its `declarations`; edit the Rust, not this.++export type Source = { file?: string, line?: number, component?: string,+/**+ * the layer key as the engine has it+ */+key?: string, };++export type Medium = "2d-type" | "2d-graphic" | "3d" | "footage" | "page";++export type Layer = { medium: Medium,+/**+ * its place in the stack, 0 at the back+ */+order: number, opacity: number,+/**+ * how it blends with what's under it (CSS mix-blend-mode), when not normally+ */+blend?: string, };++export type Text = { words: string, font?: string,+/**+ * its letters' height in px of a frame 1080 on its short side (None: not laid out without a render)+ */+size?: number,+/**+ * its box in the frame, each 0 to 1: x0, y0, x1, y1 (None: not laid out without a render)+ */+box?: [number, number, number, number], extruded: number,+/**+ * how many lines it was set on (None: not laid out)+ */+lines?: number,+/**+ * what it needs before `size` and `box` are known ("render"), when they aren't+ */+needs?: string, };++export type Part = {+/**+ * what draws it: "mesh", "model", "text3d" ...+ */+kind: string,+/**+ * its name in the scene (`<Mesh3d name>`), or what it draws+ */+name: string,+/**+ * its taxonomy tags (a component's `meta`, DR11), none until it has one+ */+tags: Array<string>,+/**+ * its world position, rotation (x, y, z, w) and scale+ */+at: [number, number, number], rotation: [number, number, number, number], scale: [number, number, number],+/**+ * its world box, low corner then high (None: a kind raea doesn't measure, or a file it can't read)+ */+min?: [number, number, number], max?: [number, number, number],+/**+ * its own box, in its own space before its transform (low corner, high corner): with at, rotation and scale,+ * exactly where it is, turned as it is; its world box is the box around that (None as its world box)+ */+own?: [[number, number, number], [number, number, number]], triangles?: number,+/**+ * a model's file+ */+src?: string,+/**+ * what its surface is (the material's kind: "standard", "paint" ...) and its base colour, when it says one+ */+material?: string, color?: string, };++export type Camera = { eye: [number, number, number], look: [number, number, number],+/**+ * vertical field of view in degrees (a perspective camera)+ */+fov?: number,+/**+ * the height it sees in metres (an orthographic camera)+ */+ortho?: number, near: number, far: number,+/**+ * how its eye moves, metres a second, to the next frame (its move: still, a push, a pan's arc)+ */+velocity?: [number, number, number], };++export type Shot = { name?: string, from: number,+/**+ * None: it runs to the end+ */+to?: number, };++export type Word = { text: string, start: number, end: number, };++export type Clip = { source: string, hash?: string, time?: number, in: number, out?: number, at: number, words: Array<Word>, };++export type Cue = { source: string, at: number, gain?: number, bus?: string, };++export type Line = { text: string, from: number, to?: number, words: Array<Word>, needs?: string, };++export type Contrast = { ratio: number, };++export type Picture = { luma: number, motion?: number, frames?: number, };++export type Onset = { at?: number, late_ms?: number, };++export type Covered = { layer: number, share: number, };++export type Covers = Array<Covered>;++export type Mix = { lufs?: number, peak?: number, };++export type Rendered = { out: string, manifest: string, record?: string, stale: boolean, };++export type Waits = { [key in string]: string };++export type Level = "error" | "warn" | "note";++export type About = { name: string, key?: string, };++export type Measure = { name: string, value: number, unit: string, limit?: number, };++export type Finding = { check: string, level: Level, about: Array<About>,+/**+ * from its first frame to the frame after its last; None when it is about the whole piece+ */+frames: [number, number] | null, says: string, measure: Measure | null, fix: string | null, by: string, };