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
raea e699cf684509a8bbada118cc302c56e99065a680
shinyobjectz1dff4f0aa8bb
diff --git a/.gitignore b/.gitignoreindex 6aed7ec8..6e24ab4c 100644--- a/.gitignore+++ b/.gitignore@@ -88,3 +88,13 @@ engine/media/real/# phase-9 run material (footage frames, transcripts, briefs) is client data: it lives in ~/films/parts-9e/, never in gitdocs/craft/phase9/++.projects/cache+.projects/vault+.projects/state.test.json+.projects/state.local.test.json+.env+.env.*+!.env.example+# a session's throwaway scripts beside the SDK (sdk/raea/.scratch-N/), never committed+sdk/raea/.scratch-*/diff --git a/Cargo.lock b/Cargo.lockindex f0bcd261..c7314f56 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -11193,6 +11193,17 @@ dependencies = ["objc2-foundation 0.3.2",]+[[package]]+name = "objc2-metal-fx"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2db6f3a9d3b07481d9e5884f592aff6fd3f99e155423d1d1af3977e77a90ea0e"+dependencies = [+ "objc2 0.6.5",+ "objc2-foundation 0.3.2",+ "objc2-metal 0.3.2",+]+[[package]]name = "objc2-quartz-core"version = "0.2.2"@@ -13295,6 +13306,7 @@ checksum = "019b4b213425016d7d84a153c4c73afb0946fbb4840e4eece7ba8848b9d6da22"name = "raea-app-check"version = "0.1.0"dependencies = [+ "raea-core-brief","serde_json",]@@ -13360,6 +13372,7 @@ name = "raea-app-tools"version = "0.1.0"dependencies = ["raea-io-assets",+ "raea-io-gen","raea-io-home","raea-io-media","raea-runtime-bundle",@@ -13367,6 +13380,14 @@ dependencies = ["serde_json",]+[[package]]+name = "raea-app-workspace"+version = "0.1.0"+dependencies = [+ "raea-core-brief",+ "serde_json",+]+[[package]]name = "raea-bench-swatch"version = "0.1.0"@@ -13415,6 +13436,7 @@ dependencies = ["bevy_trauma_shake","bevy_tweening","fastnoise-lite",+ "moonshine-save","noise","noisy_bevy","serde",@@ -13470,13 +13492,13 @@ dependencies = ["lightyear","lightyear_core","mock_instant",- "moonshine-save","noisy_bevy","raea-bench-swatch","raea-bevy-adapters","raea-bevy-calls","raea-bevy-world","raea-core-calls",+ "raea-io-home","raea-runtime-plugins","raea-sys-page","rand_pcg",@@ -13567,15 +13589,18 @@ dependencies = ["raea-app-media","raea-app-play","raea-app-tools",+ "raea-app-workspace","raea-bevy-plugins","raea-core-alloc","raea-core-animate",+ "raea-core-brief","raea-core-program","raea-io-home","raea-io-media","raea-io-npm","raea-io-trace","raea-native",+ "raea-neural","raea-render","raea-runtime-bake","raea-runtime-export",@@ -13584,6 +13609,7 @@ dependencies = ["raea-runtime-react","raea-runtime-sound","regex",+ "serde","serde_json","wsx",]@@ -13760,6 +13786,34 @@ dependencies = ["serde_json",]+[[package]]+name = "raea-io-gen"+version = "0.1.0"+dependencies = [+ "image",+ "raea-io-gen-comfy",+ "raea-io-gen-core",+ "raea-io-home",+ "serde_json",+]++[[package]]+name = "raea-io-gen-comfy"+version = "0.1.0"+dependencies = [+ "raea-io-gen-core",+ "serde_json",+]++[[package]]+name = "raea-io-gen-core"+version = "0.1.0"+dependencies = [+ "raea-io-home",+ "serde_json",+ "sha2 0.10.9",+]+[[package]]name = "raea-io-home"version = "0.1.0"@@ -13804,6 +13858,7 @@ dependencies = ["indexmap","junction","libc",+ "raea-io-home","reqwest","serde","serde_json",@@ -13820,6 +13875,7 @@ dependencies = ["flate2","htmd","raea-core-calls",+ "raea-io-home","raea-io-net","rusqlite","serde_json",@@ -13876,6 +13932,14 @@ dependencies = ["url",]+[[package]]+name = "raea-neural"+version = "0.1.0"+dependencies = [+ "image",+ "raea-runtime-bundle",+]+[[package]]name = "raea-page"version = "0.1.0"@@ -13888,6 +13952,7 @@ dependencies = ["raea-gpu-device","raea-io-media","raea-runtime-dom",+ "raea-runtime-edit","raea-runtime-input","raea-runtime-js","raea-runtime-plugins",@@ -13910,27 +13975,56 @@ dependencies = ["blitz-dom","blitz-traits","image",- "raea-gpu-device","raea-io-media","raea-page",- "raea-runtime-bake",+ "raea-page-stage",+ "raea-page-window","raea-runtime-dom","raea-runtime-input","raea-runtime-js",- "raea-runtime-live",- "raea-runtime-react",- "raea-runtime-sound",+ "raea-runtime-plugins","raea-runtime-view","raea-sys-a11y","raea-sys-fonts","raea-sys-page",- "raea-sys-tweak","serde_json","stylo","tiny_http",+]++[[package]]+name = "raea-page-stage"+version = "0.1.0"+dependencies = [+ "bevy",+ "blitz-dom",+ "raea-gpu-device",+ "raea-runtime-bake",+ "raea-runtime-dom",+ "raea-runtime-js",+ "raea-runtime-live",+ "raea-runtime-react",+ "raea-runtime-sound",+ "raea-sys-page",+ "raea-sys-tweak",+ "serde_json","wgpu",]+[[package]]+name = "raea-page-window"+version = "0.1.0"+dependencies = [+ "bevy",+ "block2 0.6.2",+ "objc2 0.6.5",+ "objc2-app-kit 0.3.2",+ "objc2-foundation 0.3.2",+ "raea-runtime-js",+ "raw-window-handle",+ "serde_json",+]+[[package]]name = "raea-perceive"version = "0.1.0"@@ -13957,6 +14051,7 @@ dependencies = ["raea-gpu-device","raea-io-media","raea-io-trace",+ "raea-render-raytrace","raea-runtime-gpuframe","raea-runtime-plugins","raea-runtime-scene3d",@@ -13988,6 +14083,17 @@ dependencies = ["wgpu",]+[[package]]+name = "raea-render-raytrace"+version = "0.1.0"+dependencies = [+ "bevy",+ "objc2 0.6.5",+ "objc2-metal 0.3.2",+ "objc2-metal-fx",+ "wgpu",+]+[[package]]name = "raea-runtime-bake"version = "0.1.0"@@ -14022,6 +14128,7 @@ dependencies = ["bevy","image","manifold-rust",+ "raea-core-scene","raea-core-shape","raea-io-media","raea-io-net",@@ -14054,6 +14161,19 @@ dependencies = ["vello",]+[[package]]+name = "raea-runtime-edit"+version = "0.1.0"+dependencies = [+ "bevy",+ "blitz-dom",+ "parley",+ "raea-runtime-dom",+ "raea-runtime-js",+ "raea-sys-page",+ "serde_json",+]+[[package]]name = "raea-runtime-encode"version = "0.1.0"@@ -14141,8 +14261,10 @@ dependencies = ["bevy","raea-bevy-world","raea-core-wire",+ "raea-io-home","raea-io-media","raea-io-net",+ "raea-runtime-bundle","raea-runtime-jsengine","serde","serde_json",@@ -14415,6 +14537,7 @@ dependencies = ["resvg","serde_json","tiny-skia 0.12.0",+ "ttf-parser","usvg",]@@ -14658,6 +14781,7 @@ dependencies = ["anyhow","half","ort",+ "raea-io-home","ureq 2.12.1",]@@ -14706,6 +14830,7 @@ version = "0.1.0"dependencies = ["image","ocrs",+ "raea-io-home","raea-sys-layout","raea-sys-vision","rten",diff --git a/Cargo.toml b/Cargo.tomlindex bb015d6e..994496b0 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -25,15 +25,21 @@ members = ["engine/bevy-world","engine/bundle","engine/cli",+ "engine/neural","engine/modules","engine/native","io/npm","engine/page","engine/page/host",+ "engine/page/stage",+ "engine/page/window","io/trace","io/codec","io/media","io/assets",+ "io/gen",+ "io/gen-comfy",+ "io/gen-core","io/home","io/soft","io/av1",@@ -87,12 +93,14 @@ members = ["systems/image","runtime/twins","runtime/dom",+ "runtime/edit","runtime/view","runtime/encode","runtime/plugins","runtime/input","tools/perceive","engine/render",+ "engine/render/raytrace","engine/seedling","runtime/react","bench/bridge",@@ -109,6 +117,7 @@ members = ["runtime/scene","runtime/shared","apps/check",+ "apps/workspace","apps/ci","apps/tools","apps/media",diff --git a/README.md b/README.mdindex 8a436037..538ecdf0 100644--- a/README.md+++ b/README.md@@ -111,8 +111,11 @@ cargo build --release -p raea-cli --no-default-featurestarget/release/raea render sdk/react/bench/games/pong/edit.tsx -o pong.mp4```-`--no-default-features` builds the public engine. The default features add raea's hosted services, which aren't-part of this repository. [docs/settings.md](docs/settings.md) lists the settings raea reads.+`--no-default-features` builds the public engine, as the releases are. The default features add one hosted service,+Content Credentials signed by raea's signing server, which isn't part of this repository. raea sends nothing on its+own: no telemetry, crash reports or update checks. What reaches the network is what you ask for (a remote URL in a+composition, a model downloaded on first use, a `raea gen` step on a provider you hold a key for), and `RAEA_OFFLINE=1`+refuses all of it. [docs/settings.md](docs/settings.md) lists the settings raea reads.## What's in herediff --git a/apps/check/Cargo.toml b/apps/check/Cargo.tomlindex d2827139..5bb7e74a 100644--- a/apps/check/Cargo.toml+++ b/apps/check/Cargo.toml@@ -7,4 +7,6 @@ publish = falsedescription = "`raea check`: the floor's measurable lines on an export, ranked P0-P3"[dependencies]+# taste.ts rules, as the raea CLI evaluates them (docs/projects.feature PJ0)+raea-core-brief = { path = "../../core/brief" }serde_json = "1"diff --git a/apps/check/src/lib.rs b/apps/check/src/lib.rsindex 40eb61ef..020eb6f0 100644--- a/apps/check/src/lib.rs+++ b/apps/check/src/lib.rs@@ -7,9 +7,9 @@//! manifest (`raea render … --manifest render.json`): text clipped off the frame, text in the platform's UI zones,//! text held too briefly to read, caption contrast against the pixels behind it. With the transcript too: captions//! that come on away from the word they carry. With the face's place (`--perception`, the perception.json `raea cut`-//! writes): text over more than 8% of the face. With `--taste FILE|DIR`: the person's own mechanical rules, from the-//! `## Checks` section of their taste briefs (`- text-above 62%: Captions sit clear of the bottom.`), each a P1 when-//! broken, since the person's rule beats the floor's default (docs/craft-system.md, J). Exits 1 when a P0 or P1 is found.+//! writes): text over more than 8% of the face. With `--taste taste.ts|DIR`: the person's own mechanical rules, the+//! rules in their taste.ts files that carry a check (`{ text: "Captions sit clear of the bottom.", check: { form:+//! "text-above", value: 62 } }`), each a P1 when broken, since the person's rule beats the floor's default (docs/craft-system.md, J). Exits 1 when a P0 or P1 is found.use serde_json::{Value, json};use std::collections::BTreeMap;use std::process::Command;@@ -20,6 +20,7 @@ mod picture;use picture::*;mod text;use text::*;+pub mod quick;#[cfg(test)]mod tests;@@ -33,8 +34,10 @@ struct Issue {says: String,}-pub fn cli(args: &[String]) -> i32 {- match run(args) {+/// `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) {Ok((report, bad)) => {println!("{report}");i32::from(bad)@@ -50,7 +53,7 @@ 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)}-pub const USAGE: &str = "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 FILE|DIR] [-o check.json] (an export against the floor: clipped text, contrast, safe areas, freezes, cues, loudness, blotching, a placeholder brand kit; P0-P3)";+pub const USAGE: &str = "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, cues, loudness, blotching, a placeholder brand kit; P0-P3)";/// 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)]@@ -60,56 +63,9 @@ struct Taste {line: String,}-/// the forms a taste check can take, and what each measures (apps/app/host/taste.ts offers the Director these)-pub const TASTE_FORMS: [(&str, &str); 6] = [- ("text-hold", "S: every text holds at least S seconds"),- ("text-above", "P%: every text's bottom edge sits above P% of the frame's height"),- ("text-below", "P%: every text's top edge sits below P% of the frame's height"),- ("text-margin", "N: every text keeps N px (at 1080 on the short side) from each edge"),- ("loudness", "L: integrated loudness within 1 LU of L LUFS (instead of -14)"),- ("still-max", "S: nothing holds still longer than S seconds (instead of 3)"),-];--/// The `## Checks` lines of a taste brief, or of every `.brief` in a folder. A form raea doesn't know is skipped and-/// named, so a hand-written line never breaks a check.-fn taste_rules(path: &str) -> R<(Vec<Taste>, Vec<String>)> {- let p = std::path::Path::new(path);- let files: Vec<std::path::PathBuf> = if p.is_dir() {- let mut v: Vec<_> = std::fs::read_dir(p).map_err(|e| format!("{path}: {e}"))?.filter_map(|e| e.ok().map(|e| e.path())).filter(|f| f.extension().is_some_and(|x| x == "brief")).collect();- v.sort();- v- } else {- vec![p.to_path_buf()]- };- let (mut rules, mut skipped) = (Vec::new(), Vec::new());- for f in files {- let text = std::fs::read_to_string(&f).map_err(|e| format!("{}: {e}", f.display()))?;- let (r, s) = parse_taste(&text);- rules.extend(r);- skipped.extend(s);- }- Ok((rules, skipped))-}--fn parse_taste(text: &str) -> (Vec<Taste>, Vec<String>) {- let (mut rules, mut skipped, mut on) = (Vec::new(), Vec::new(), false);- for l in text.lines() {- let t = l.trim();- if let Some(h) = t.strip_prefix("## ") {- on = h.trim().eq_ignore_ascii_case("checks");- continue;- }- let Some(item) = t.strip_prefix("- ").filter(|_| on) else { continue };- let (rule, line) = item.split_once(':').map(|(a, b)| (a.trim(), b.trim())).unwrap_or((item, ""));- let mut words = rule.split_whitespace();- let form = words.next().unwrap_or("").to_lowercase();- let value = words.next().map(|v| v.trim_end_matches(|c: char| c.is_alphabetic() || c == '%')).and_then(|v| v.parse::<f64>().ok());- match value {- Some(value) if TASTE_FORMS.iter().any(|(f, _)| *f == form) => rules.push(Taste { form, value, line: if line.is_empty() { rule.to_string() } else { line.to_string() } }),- _ => skipped.push(rule.to_string()),- }- }- (rules, skipped)+/// 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()}fn taste_of<'a>(rules: &'a [Taste], form: &str) -> Option<&'a Taste> {@@ -148,7 +104,7 @@ fn taste_text(rules: &[Taste], runs: &[Run], w: f64, h: f64, issues: &mut Vec<Is/// the flags `raea check` takes, each with a valueconst TAKES: [&str; 7] = ["--manifest", "--words", "--perception", "--shape", "--platform", "--taste", "-o"];-fn run(args: &[String]) -> R<(String, bool)> {+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)?;if !std::path::Path::new(&video).exists() {return Err(format!("no file at {video}\n{USAGE}"));@@ -156,14 +112,7 @@ fn run(args: &[String]) -> R<(String, bool)> {let probe = Probe::of(&video)?;let mut issues = Vec::new();let mut passed = Vec::new();- let (taste, skipped) = match flag(args, "--taste") {- Some(t) if std::path::Path::new(t).exists() => taste_rules(t)?,- _ => (Vec::new(), Vec::new()),- };- for s in skipped {- passed.push(format!("taste: \"{s}\" isn't a form raea measures; kept as a line, not checked"));- }-+ 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,@@ -192,9 +141,14 @@ fn run(args: &[String]) -> R<(String, bool)> {}}+ report(&video, issues, passed, flag(args, "-o"))+}++/// The issues ranked, written to -o as JSON when asked, and the report's text; true when a P0 or P1 is among them.+fn report(video: &str, mut issues: Vec<Issue>, passed: Vec<String>, out: Option<&str>) -> R<(String, bool)> {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 bad = issues.iter().any(|i| i.p <= 1);- if let Some(out) = flag(args, "-o") {+ if let Some(out) = out {let j = json!({"file": video,"issues": issues.iter().map(|i| json!({"rule": i.rule, "p": format!("P{}", i.p), "at": i.at, "says": i.says})).collect::<Vec<_>>(),diff --git a/apps/check/src/quick.rs b/apps/check/src/quick.rsnew file mode 100644index 00000000..2d163812--- /dev/null+++ b/apps/check/src/quick.rs@@ -0,0 +1,87 @@+//! `raea check EDIT.tsx --quick` and `raea hook claude` (docs/skills.feature SK10). The quick check renders three stills+//! of a composition (a quarter in, the middle, the last frame) with their manifest, about a second, and runs the full+//! check's text rules and the person's text taste on it: clipped and cramped text, safe areas, sizes. The hook is+//! Claude Code's PostToolUse command (`raea skills install --agent claude` adds it): after a .tsx that registers a root+//! is written, the quick check's findings go back to the agent; a clean check says nothing.+use super::*;+use std::path::Path;++/// The composition's length in frames, read from its source (the first `durationInFrames={N}`), 90 without one.+fn frames(src: &str) -> u64 {+ src.split("durationInFrames={").nth(1).and_then(|r| r.split('}').next()).and_then(|n| n.trim().parse().ok()).unwrap_or(90)+}++/// `raea check EDIT.tsx --quick [--shape S] [--platform P] [-o check.json]`: (report, P0 or P1 found). `tastes` are the+/// person's, evaluated by the raea CLI when --taste names them.+pub fn quick(args: &[String], tastes: Vec<raea_core_brief::Taste>) -> R<(String, bool)> {+ let file = args.iter().find(|a| a.ends_with(".tsx")).ok_or("raea check --quick takes a composition: EDIT.tsx")?;+ let src = std::fs::read_to_string(file).map_err(|e| format!("{file}: {e}"))?;+ let n = frames(&src).max(1);+ let at = format!("{},{},{}", n / 4, n / 2, n - 1);+ let tmp = std::env::temp_dir().join(format!("raea-quick-{}", std::process::id()));+ std::fs::create_dir_all(&tmp).map_err(|e| format!("{}: {e}", tmp.display()))?;+ let manifest = tmp.join("render.json");+ let me = std::env::current_exe().map_err(|e| e.to_string())?;+ let out = std::process::Command::new(me).arg("render").arg(file).args(["--at", &at, "-o"]).arg(format!("{}/", tmp.display())).arg("--manifest").arg(&manifest).output().map_err(|e| e.to_string())?;+ let result = if out.status.success() {+ on_manifest(file, &manifest, args, tastes)+ } else {+ // a render that fails is the finding: the agent sees why+ let (err, out) = (String::from_utf8_lossy(&out.stderr), String::from_utf8_lossy(&out.stdout));+ let mut why = Vec::new();+ for line in err.lines().chain(out.lines()) {+ if line.contains("REFUSED") || line.contains("rror") {+ why.push(line);+ }+ }+ let why = why.join("\n");+ Ok((format!("raea check {file}: it doesn't render\nP0 render {why}"), true))+ };+ let _ = std::fs::remove_dir_all(&tmp);+ result+}++/// `raea hook claude`: Claude Code's PostToolUse input on stdin; for a saved composition, the quick check's findings as+/// the hook's additionalContext. Anything else, or a clean check, prints nothing.+pub fn hook(args: &[String]) -> R<String> {+ if args.first().map(String::as_str) != Some("claude") {+ return Err("usage: raea hook claude (Claude Code's PostToolUse hook; raea skills install --agent claude adds it)".into());+ }+ let mut input = String::new();+ std::io::Read::read_to_string(&mut std::io::stdin(), &mut input).map_err(|e| e.to_string())?;+ let v: serde_json::Value = serde_json::from_str(&input).unwrap_or_default();+ let path = v["tool_input"]["file_path"].as_str().unwrap_or_default();+ let composition = path.ends_with(".tsx") && std::fs::read_to_string(path).map(|t| t.contains("registerRoot")).unwrap_or(false);+ if !composition {+ return Ok(String::new());+ }+ let (report, _) = quick(&[path.to_string()], Vec::new())?;+ if report.lines().nth(1).is_none_or(|l| l.starts_with("ok ")) {+ return Ok(String::new());+ }+ let found: Vec<&str> = report.lines().filter(|l| !l.starts_with("ok ")).collect();+ Ok(json!({"hookSpecificOutput": {"hookEventName": "PostToolUse", "additionalContext": format!("raea check --quick after this save:\n{}", found.join("\n"))}}).to_string())+}++/// `raea check --quick`'s half (docs/skills.feature SK10): the text rules and the person's text taste on the manifest+/// of a few stills (`raea render EDIT.tsx --at ... --manifest`), no video. What it can't see (contrast, freezes,+/// sound, blotching) waits for the full check on the export.+fn on_manifest(file: &str, manifest: &Path, args: &[String], tastes: Vec<raea_core_brief::Taste>) -> R<(String, bool)> {+ let at = manifest.display();+ let m: Value = serde_json::from_str(&std::fs::read_to_string(manifest).map_err(|e| format!("{at}: {e}"))?).map_err(|e| format!("{at}: {e}"))?;+ let (mut issues, mut passed) = (Vec::new(), Vec::new());+ let runs = text_runs(&m);+ let (w, h) = (m["width"].as_f64().unwrap_or(1080.0), m["height"].as_f64().unwrap_or(1920.0));+ text_rules(&runs, None, w, h, flag(args, "--shape"), flag(args, "--platform"), &mut issues, &mut passed);+ taste_text(&taste_rules(&tastes), &runs, w, h, &mut issues, &mut passed);+ report(file, issues, passed, flag(args, "-o"))+}++#[cfg(test)]+mod tests {+ #[test]+ fn frames_come_from_the_source() {+ assert_eq!(super::frames("<Composition durationInFrames={240} fps={30} />"), 240);+ assert_eq!(super::frames("no composition"), 90);+ }+}diff --git a/apps/check/src/sound.rs b/apps/check/src/sound.rsindex e6ebcee8..8c7e61f2 100644--- a/apps/check/src/sound.rs+++ b/apps/check/src/sound.rs@@ -23,8 +23,10 @@ pub(crate) fn pct(v: &[f64], q: f64) -> f64 {s[lo] + (s[hi] - s[lo]) * (r - lo as f64)}-/// Each 10 ms step's level in dB, for the whole mix and in three bands (low < 500 Hz, mid to 4 kHz, high to 12 kHz):-/// a bed that stops under a voice shows in the band the voice doesn't fill (a projector's clatter in the highs)+/// Each 10 ms step's level in dBFS, for the whole mix and in three bands (low < 500 Hz, mid to 4 kHz, high to 12 kHz):+/// a bed that stops under a voice shows in the band the voice doesn't fill (a projector's clatter in the highs). A band's+/// level is its share of the step's mean square (Parseval, undoing the Hann window's power), so a tone reads the same in+/// its band as in the mixpub(crate) fn levels(x: &[f32]) -> (Vec<f64>, [Vec<f64>; 3]) {use std::f64::consts::PI;let n = x.len() / HOP;@@ -38,6 +40,8 @@ pub(crate) fn levels(x: &[f32]) -> (Vec<f64>, [Vec<f64>; 3]) {let bins: Vec<(usize, Vec<(f64, f64)>)> = (0..=HOP / 2).filter_map(|k| Some((band(k)?, (0..HOP).map(|i| (-2.0 * PI * ((k * i) % HOP) as f64 / HOP as f64).sin_cos()).collect()))).collect();+ // one-sided bins (no DC or Nyquist in any band) count twice; the window keeps mean(w²) of the power+ let scale = 2.0 / (HOP * HOP) as f64 / (hann.iter().map(|h| h * h).sum::<f64>() / HOP as f64);let (mut rms, mut bands) = (Vec::with_capacity(n), [Vec::with_capacity(n), Vec::with_capacity(n), Vec::with_capacity(n)]);for f in x.chunks_exact(HOP) {let ms = f.iter().map(|&v| (v as f64).powi(2)).sum::<f64>() / HOP as f64;@@ -49,17 +53,22 @@ pub(crate) fn levels(x: &[f32]) -> (Vec<f64>, [Vec<f64>; 3]) {e[*b] += re * re + im * im;}for b in 0..3 {- bands[b].push(10.0 * (e[b] / HOP as f64 + 1e-12).log10());+ bands[b].push(10.0 * (e[b] * scale + 1e-18).log10());}}(rms, bands)}/// Dead stops: a steady sound (a bed: a projector, rain, room tone, a held chord) that goes in one 10 ms step instead of-/// fading. Steady: over the second before, its level smoothed to 50 ms varies by under 3 dB (a voice or music with-/// phrases never holds that still). The stop: down 12 dB or more in one step, and the 300 ms after it DROP dB under the-/// bed. In the whole mix or one band, so a bed that stops under a voice shows where the voice doesn't cover it.+/// fading. Steady: over the second before, its level smoothed to 50 ms varies by under 3 dB. The stop: down 12 dB or more+/// in one step, from within AT dB of the bed one or two steps before (a fade that has already brought it down isn't a+/// stop), to DROP dB under the bed by the next step (gone, not a voice's tail that comes back up), and the 300 ms after it+/// DROP dB under the bed. In the whole mix or one band, so a bed that stops under a voice shows where the voice doesn't+/// cover it. Dense speech can pass for steady in the lows (its pitch fills them evenly), but a word ends in a tail that+/// rises again after the first drop, where a cut source is gone in one step.pub(crate) fn dead_stops(rms: &[f64], bands: &[Vec<f64>; 3]) -> Vec<(f64, String)> {+ /// dB under the bed the sound may be just before it stops+ const AT: f64 = 6.0;let mut found: Vec<(f64, String)> = Vec::new();let n = rms.len();for (name, lv) in [("the mix", rms), ("the lows", &bands[0][..]), ("the mids", &bands[1][..]), ("the highs", &bands[2][..])] {@@ -71,10 +80,13 @@ pub(crate) fn dead_stops(rms: &[f64], bands: &[Vec<f64>; 3]) -> Vec<(f64, Stringlet pre = &sm[i - 100..i - 2];let (bed, mean) = (pct(pre, 50.0), pre.iter().sum::<f64>() / pre.len() as f64);let sd = (pre.iter().map(|v| (v - mean).powi(2)).sum::<f64>() / pre.len() as f64).sqrt();- let floor = if name == "the mix" { -50.0 } else { -65.0 };+ // under this nobody hears it stop+ let floor = if name == "the mix" { -50.0 } else { -80.0 };let at = i as f64 * HOP as f64 / SR as f64;- if bed > floor && sd < 3.0 && bed - pct(&lv[i..i + 30], 10.0) >= DROP && !found.iter().any(|(t, _)| (t - at).abs() < 0.5) {- found.push((at, format!("{name}: a steady sound at {bed:.0} dB stops dead in 10 ms: its source ran out (make it as long as its Sequence), or a Sequence cut it with no fadeOut")));+ let was_up = lv[i - 1].max(lv[i - 2]) >= bed - AT;+ let gone = lv[i + 1] <= bed - DROP && bed - pct(&lv[i..i + 30], 10.0) >= DROP;+ if bed > floor && sd < 3.0 && was_up && gone && !found.iter().any(|(t, _)| (t - at).abs() < 0.5) {+ found.push((at, format!("{name}: a steady sound at {bed:.0} dBFS stops dead in 10 ms: its source ran out (make it as long as its Sequence), or a Sequence cut it with no fadeOut or one too short to hear (fade a bed out over 100 ms or more)")));}}}diff --git a/apps/check/src/testdata/its-a-race-12s.levels b/apps/check/src/testdata/its-a-race-12s.levelsnew file mode 100644index 00000000..c0fd6459--- /dev/null+++ b/apps/check/src/testdata/its-a-race-12s.levels@@ -0,0 +1,6 @@+# its-a-race (raea 0.1.0-canary.2, Linux export), 12.00-14.00 s: each 10 ms step's level in dBFS, one line per track:+# the mix, the lows, the mids, the highs. The voice ends "thing." at 13.36 s and pauses; nothing is cut there.+-9.4 -9.8 -10.1 -9.6 -9.2 -10.6 -11.9 -11.6 -10.1 -11.4 -11.0 -12.3 -10.0 -12.4 -12.2 -11.9 -11.6 -14.0 -16.2 -19.8 -17.9 -18.8 -22.8 -23.0 -25.0 -27.5 -26.2 -27.7 -30.9 -25.5 -17.2 -12.1 -11.3 -11.6 -12.3 -12.5 -12.2 -11.0 -12.4 -12.0 -12.5 -12.5 -12.3 -11.7 -12.8 -11.9 -12.1 -12.9 -12.4 -11.4 -11.1 -10.2 -11.2 -12.2 -11.8 -11.6 -12.7 -11.6 -12.0 -13.0 -13.1 -12.1 -13.8 -13.2 -14.3 -16.3 -19.5 -17.7 -17.0 -19.2 -16.0 -12.7 -12.9 -13.2 -15.4 -15.0 -15.6 -18.1 -19.1 -16.3 -17.9 -22.2 -28.5 -27.6 -28.4 -26.2 -12.5 -13.3 -12.2 -13.1 -12.3 -13.4 -14.6 -15.2 -12.2 -13.0 -12.4 -13.1 -13.3 -11.8 -13.2 -14.1 -11.5 -14.8 -16.7 -16.5 -16.2 -17.0 -19.1 -21.8 -22.1 -22.2 -22.3 -16.9 -12.7 -11.9 -14.7 -13.1 -12.9 -13.9 -16.6 -15.8 -14.9 -15.1 -18.6 -15.9 -17.3 -18.9 -15.6 -19.4 -21.3 -16.8 -18.7 -22.6 -17.7 -19.1 -27.5 -28.1 -29.8 -41.1 -35.5 -37.2 -39.2 -40.4 -40.4 -39.4 -47.0 -39.7 -40.4 -51.7 -42.6 -44.1 -46.9 -48.2 -51.3 -48.3 -54.1 -54.6 -55.0 -50.8 -54.1 -51.6 -55.5 -53.5 -51.7 -54.7 -51.8 -55.6 -57.5 -54.8 -51.2 -54.0 -51.8 -51.8 -47.9 -50.9 -51.1 -47.9 -53.1 -50.0 -46.5 -49.4 -49.4 -48.3 -55.7 -51.1 -48.7 -58.9 -54.4 -54.6 -50.3 -51.6 -58.0 -60.7 -60.2 -56.3 -58.9 -55.1 -48.8 -48.3+-14.9 -13.6 -13.9 -11.8 -10.1 -11.9 -13.2 -13.9 -13.7 -14.6 -14.1 -15.8 -17.2 -14.8 -13.9 -15.5 -13.5 -13.1 -16.6 -21.9 -21.1 -20.4 -23.3 -22.7 -28.8 -27.3 -26.5 -29.2 -35.7 -27.5 -22.6 -22.5 -19.2 -18.5 -19.7 -20.1 -17.9 -17.9 -15.1 -15.8 -15.0 -13.3 -12.8 -13.5 -13.7 -13.6 -16.6 -18.3 -17.9 -17.1 -17.1 -18.0 -16.5 -14.8 -15.7 -15.5 -16.9 -15.5 -15.9 -16.3 -16.4 -15.2 -15.0 -13.5 -15.7 -16.3 -23.9 -18.8 -18.5 -23.4 -18.3 -14.9 -16.9 -17.7 -16.7 -14.8 -15.0 -18.9 -21.1 -15.8 -16.0 -21.6 -29.5 -28.3 -27.8 -29.9 -10.9 -13.0 -12.6 -15.2 -15.0 -15.2 -15.6 -16.4 -10.9 -11.7 -13.4 -16.4 -17.2 -16.1 -13.2 -12.7 -11.2 -14.8 -20.7 -20.7 -15.1 -16.6 -20.0 -21.9 -21.4 -21.1 -24.0 -20.7 -14.1 -12.1 -14.9 -13.9 -15.8 -17.8 -18.0 -17.5 -18.0 -17.0 -19.3 -18.6 -19.4 -17.7 -15.2 -19.0 -21.7 -16.0 -21.9 -26.4 -17.1 -18.4 -30.6 -32.5 -28.5 -40.9 -36.5 -39.9 -42.0 -41.9 -39.9 -38.6 -48.0 -39.9 -41.4 -51.5 -41.3 -44.6 -49.2 -51.7 -51.6 -46.6 -55.4 -54.4 -57.2 -51.8 -53.6 -54.4 -67.4 -54.8 -52.1 -59.4 -52.1 -60.5 -57.8 -56.5 -50.9 -55.9 -56.8 -54.8 -50.8 -52.6 -53.3 -48.0 -51.4 -50.9 -49.4 -53.1 -50.5 -48.2 -60.7 -51.3 -48.6 -57.8 -54.4 -56.1 -50.3 -53.1 -61.4 -63.3 -63.1 -55.4 -63.0 -64.0 -49.9 -47.3+-12.0 -10.4 -12.3 -11.7 -10.7 -10.7 -14.9 -14.4 -12.3 -16.6 -13.5 -14.5 -11.1 -16.7 -15.5 -18.9 -13.4 -22.6 -23.6 -21.8 -26.7 -20.9 -28.7 -30.7 -30.0 -33.2 -34.9 -34.4 -36.3 -31.4 -24.7 -16.0 -10.5 -9.2 -9.7 -10.8 -12.7 -15.1 -19.7 -17.3 -19.4 -19.3 -20.1 -19.5 -21.5 -19.3 -18.7 -18.7 -15.4 -13.5 -14.9 -12.2 -15.0 -15.6 -14.6 -13.9 -16.5 -13.7 -13.6 -15.2 -14.7 -13.5 -16.3 -19.3 -20.2 -19.0 -23.1 -24.0 -23.2 -23.2 -17.9 -13.7 -16.6 -17.8 -22.7 -24.8 -28.6 -28.2 -32.4 -34.7 -34.6 -36.6 -38.0 -40.1 -42.3 -35.2 -23.1 -16.8 -16.8 -18.0 -18.1 -23.6 -26.2 -29.0 -29.4 -35.4 -27.7 -27.3 -21.4 -26.4 -28.5 -27.2 -31.6 -32.5 -31.8 -36.6 -30.0 -35.9 -34.5 -38.9 -46.2 -36.8 -36.4 -28.6 -24.0 -19.9 -20.8 -18.7 -14.8 -20.7 -21.7 -21.0 -17.7 -24.2 -26.8 -25.9 -25.1 -35.3 -33.6 -35.9 -31.9 -33.1 -37.1 -37.0 -39.4 -41.9 -41.4 -41.3 -44.5 -52.1 -49.2 -51.5 -50.8 -55.7 -54.8 -54.7 -59.0 -53.6 -56.8 -62.2 -59.4 -59.3 -58.9 -61.8 -63.8 -64.5 -65.8 -59.9 -62.2 -60.3 -64.8 -63.2 -62.9 -61.9 -64.4 -68.0 -64.8 -63.3 -65.8 -65.6 -60.6 -59.4 -60.2 -62.9 -61.1 -65.1 -61.8 -61.2 -63.9 -60.1 -60.1 -63.2 -64.3 -62.1 -64.6 -58.1 -62.4 -63.1 -60.3 -64.0 -65.1 -66.5 -64.5 -64.1 -61.3 -63.4 -63.7 -64.4 -61.6 -61.3+-67.9 -67.4 -67.8 -66.7 -64.9 -65.1 -68.8 -66.5 -65.0 -67.2 -65.0 -68.4 -65.1 -63.2 -62.2 -64.6 -69.9 -69.5 -65.1 -59.3 -71.5 -71.7 -73.7 -70.1 -73.6 -71.9 -70.5 -68.0 -64.9 -59.0 -52.7 -48.0 -46.1 -43.3 -46.8 -49.0 -48.5 -45.5 -46.1 -48.9 -42.3 -48.5 -48.3 -53.6 -53.2 -52.8 -47.4 -44.4 -54.5 -56.1 -56.2 -54.6 -52.5 -53.6 -53.8 -57.0 -54.5 -55.2 -54.0 -53.7 -51.1 -59.0 -56.1 -55.7 -57.7 -58.6 -64.5 -65.6 -64.7 -66.6 -61.2 -51.6 -49.8 -51.2 -54.4 -58.5 -57.3 -62.0 -59.5 -58.1 -51.3 -45.8 -48.4 -47.1 -45.8 -50.3 -46.3 -42.4 -42.0 -47.7 -51.6 -52.3 -56.7 -59.0 -61.9 -65.4 -64.7 -63.4 -59.2 -58.6 -54.0 -55.7 -53.6 -47.1 -44.8 -41.1 -44.5 -41.3 -44.8 -43.8 -45.0 -46.5 -47.4 -48.1 -52.2 -52.5 -53.3 -54.0 -57.1 -58.2 -61.1 -60.7 -60.3 -59.0 -57.6 -59.4 -62.1 -66.4 -65.6 -68.2 -66.6 -66.0 -72.4 -68.6 -68.9 -72.2 -73.0 -71.9 -75.4 -73.8 -73.7 -76.3 -74.6 -77.1 -76.4 -76.4 -75.2 -76.3 -75.4 -76.6 -77.8 -77.1 -74.6 -76.5 -74.6 -77.6 -76.2 -77.3 -74.8 -78.0 -76.6 -79.6 -80.0 -77.4 -75.6 -77.0 -76.9 -75.9 -77.0 -76.4 -76.4 -76.5 -78.2 -77.6 -76.1 -77.6 -77.7 -76.8 -76.7 -77.5 -76.9 -77.7 -75.2 -76.9 -78.1 -76.3 -76.9 -78.3 -79.3 -78.9 -77.1 -76.9 -79.3 -77.4 -78.4 -77.1 -76.3 -77.9 -76.2 -76.3diff --git a/apps/check/src/tests.rs b/apps/check/src/tests.rsindex 1f1deea2..b9b0970b 100644--- a/apps/check/src/tests.rs+++ b/apps/check/src/tests.rs@@ -56,14 +56,17 @@ fn flat_dark_is_clean_and_stepped_dark_is_blotchy() {}#[test]-fn taste_checks_read_their_section_and_hold_text_to_the_persons_line() {- let brief = "# Shane's taste\n\n## Always\n- text-above 60%: not a check here\n\n## Checks\n- text-above 62%: Captions sit clear of the bottom.\n- glow-free: no glow\n- text-hold 2 s\n";- let (rules, skipped) = parse_taste(brief);+fn taste_checks_hold_text_to_the_persons_line() {+ let taste: raea_core_brief::Taste = serde_json::from_value(json!({"title": "Shane's taste", "sections": [{"heading": "Always", "rules": [+ {"text": "Captions sit clear of the bottom.", "check": {"form": "text-above", "value": 62.0}},+ {"text": "No glow"},+ {"text": "Text holds two seconds", "check": {"form": "text-hold", "value": 2.0}},+ ]}]})).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-hold 2 s".into() },+ Taste { form: "text-hold".into(), value: 2.0, line: "Text holds two seconds".into() },]);- assert_eq!(skipped, vec!["glow-free".to_string()]);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 };let (mut issues, mut passed) = (vec![], vec![]);@@ -79,7 +82,7 @@ fn taste_checks_read_their_section_and_hold_text_to_the_persons_line() {#[ignore]fn on_a_real_export() {let args: Vec<String> = std::env::var("RAEA_CHECK_ARGS").expect("RAEA_CHECK_ARGS").split_whitespace().map(String::from).collect();- let code = cli(&args);+ let code = cli_with(&args, Vec::new());println!("exit {code}");}@@ -103,6 +106,45 @@ fn a_steady_sound_that_stops_dead_is_found_and_a_faded_one_isnt() {let faded: Vec<f32> = tone(4.0, &[(0.0, 3.0, -20.0)]).into_iter().enumerate().map(|(i, v)| v * (1.0 - ((i as f32 / SR as f32) - 2.0).clamp(0.0, 1.0))).collect();let (rms, bands) = levels(&faded);assert!(dead_stops(&rms, &bands).is_empty());+ // a source cut partway through a 10 ms step is as dead+ let cut: Vec<f32> = tone(4.0, &[(0.0, 2.0 + 117.0 / SR as f64, -20.0)]);+ let (rms, bands) = levels(&cut);+ assert_eq!(dead_stops(&rms, &bands).len(), 1);+ // a 100 ms fadeOut is a fade, though its last step falls into silence+ let short: Vec<f32> = tone(4.0, &[(0.0, 2.0, -20.0)]).into_iter().enumerate().map(|(i, v)| v * ((2.0 - i as f32 / SR as f32) / 0.1).clamp(0.0, 1.0)).collect();+ let (rms, bands) = levels(&short);+ assert!(dead_stops(&rms, &bands).is_empty(), "{:?}", dead_stops(&rms, &bands));+}++#[test]+fn bands_read_in_dbfs() {+ // a tone in the middle of its band reads there what it reads in the mix: -20 dBFS peak is -23 dBFS RMS+ let sine = |hz: f64| (0..SR).map(|i| (0.1 * (2.0 * std::f64::consts::PI * hz * i as f64 / SR as f64).sin()) as f32).collect::<Vec<_>>();+ for (hz, band) in [(200.0, 0), (2000.0, 1), (8000.0, 2)] {+ let (rms, bands) = levels(&sine(hz));+ assert!((rms[50] + 23.0).abs() < 0.1, "{}", rms[50]);+ assert!((bands[band][50] - rms[50]).abs() < 0.2, "{hz} Hz: band {} vs the mix {}", bands[band][50], rms[50]);+ }+}++#[test]+fn a_voice_that_ends_a_sentence_isnt_a_dead_stop() {+ // its-a-race at 12-14 s: "AI became a thing." ends at 13.36 s and the speaker pauses. Its lows held within 2.6 dB over+ // the second before and fell 12 dB in one step, so they read as a bed cut dead ("a steady sound at -0 dB", before the+ // bands read in dBFS), but the mix follows the source there and the word's tail comes back up after the first drop+ let tracks: Vec<Vec<f64>> = include_str!("testdata/its-a-race-12s.levels")+ .lines()+ .filter(|l| !l.starts_with('#'))+ .map(|l| l.split_whitespace().map(|v| v.parse().unwrap()).collect())+ .collect();+ let bands = [tracks[1].clone(), tracks[2].clone(), tracks[3].clone()];+ let stops = dead_stops(&tracks[0], &bands);+ assert!(stops.is_empty(), "{stops:?}");+ // the same voice with a bed under it that's cut at 13.6 s: that one is still found+ let bed = 10f64.powf(-30.0 / 10.0);+ let highs: Vec<f64> = tracks[3].iter().enumerate().map(|(i, v)| 10.0 * (10f64.powf(v / 10.0) + if i < 160 { bed } else { 0.0 }).log10()).collect();+ let found = dead_stops(&tracks[0], &[tracks[1].clone(), tracks[2].clone(), highs]);+ assert!(found.iter().any(|(at, says)| (at - 1.6).abs() < 0.02 && says.starts_with("the highs")), "{found:?}");}#[test]diff --git a/apps/game/src/gather.rs b/apps/game/src/gather.rsindex cc956575..a67533dc 100644--- a/apps/game/src/gather.rs+++ b/apps/game/src/gather.rs@@ -94,7 +94,7 @@ pub(crate) fn gather(bundle: &mut String, dir: &Path, game: &Path, got: &mut Gatlet decoded = raea_io_net::percent_decode_str(s);let mut cands: Vec<PathBuf> = Vec::new();if let Some(rest) = decoded.strip_prefix("/media/") {- cands.push(dir.join("media").join(rest));+ cands.push(raea_runtime_react::scene::media_path(dir, &format!("/media/{rest}")));}if decoded.starts_with('/') {cands.push(PathBuf::from(&decoded));diff --git a/apps/tools/Cargo.toml b/apps/tools/Cargo.tomlindex ad8d04a1..4214cadd 100644--- a/apps/tools/Cargo.toml+++ b/apps/tools/Cargo.toml@@ -4,7 +4,7 @@ version = "0.1.0"edition = "2024"license = "FSL-1.1-ALv2"publish = false-description = "The `raea` verbs that run raea's local model tools: sao, tokensynth, setup-audio, sounds, splat and song"+description = "The `raea` verbs that run raea's model tools: sao, tokensynth, setup-audio, sounds, splat, song and gen"[features]# a made sound signed as generated (raea's own API; the public engine goes without)@@ -12,6 +12,8 @@ service = [][dependencies]raea-io-assets = { path = "../../io/assets" }+# generation flows: made.app, fal, Replicate, OpenRouter, Modal, ComfyUI (`raea gen`)+raea-io-gen = { path = "../../io/gen" }raea-io-home = { path = "../../io/home" }raea-io-media = { path = "../../io/media", default-features = false }serde_json = "1"diff --git a/apps/tools/src/agent_mcp.rs b/apps/tools/src/agent_mcp.rsnew file mode 100644index 00000000..a4758091--- /dev/null+++ b/apps/tools/src/agent_mcp.rs@@ -0,0 +1,174 @@+//! The MCP servers `raea skills install` offers an agent (docs/skills.feature SK11): today `blender`, which drives a+//! running Blender through the MCP for Blender add-on (`raea setup blender` installs it). Each agent keeps MCP servers+//! in its own place; a server already registered under the name is left as the person set it.+use serde_json::{json, Value};+use std::path::{Path, PathBuf};+use std::process::Command;++/// The blender MCP server: uv runs it, so nothing is installed until an agent starts it.+const NAME: &str = "blender";+const CMD: &str = "uvx";+const ARGS: [&str; 1] = ["mcp-for-blender"];++type R<T> = Result<T, String>;++/// The person's home folder (HOME, or USERPROFILE on Windows).+pub fn user_home() -> R<PathBuf> {+ std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from).ok_or_else(|| "no home folder (HOME)".into())+}++/// The JSON file holding `mcpServers` for agents configured that way (Kimi Code, Gemini CLI, Claude Code's own file).+fn json_file(agent: &str) -> R<Option<PathBuf>> {+ let h = user_home()?;+ Ok(match agent {+ "claude" => Some(h.join(".claude.json")),+ "kimi" => Some(std::env::var_os("KIMI_CODE_HOME").filter(|v| !v.is_empty()).map(PathBuf::from).unwrap_or_else(|| h.join(".kimi-code")).join("mcp.json")),+ "gemini" => Some(h.join(".gemini/settings.json")),+ _ => None,+ })+}++/// Adds `blender` to a JSON config's `mcpServers` unless one is there; true when it added.+pub fn add_json(path: &Path) -> R<bool> {+ let mut doc: Value = match std::fs::read_to_string(path) {+ Ok(t) if !t.trim().is_empty() => serde_json::from_str(&t).map_err(|e| format!("{}: {e}", path.display()))?,+ _ => json!({}),+ };+ let servers = doc.as_object_mut().ok_or_else(|| format!("{} isn't a JSON object", path.display()))?.entry("mcpServers").or_insert_with(|| json!({}));+ let servers = servers.as_object_mut().ok_or_else(|| format!("{}: mcpServers isn't an object", path.display()))?;+ if servers.contains_key(NAME) {+ return Ok(false);+ }+ servers.insert(NAME.into(), json!({"command": CMD, "args": ARGS}));+ if let Some(dir) = path.parent() {+ std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;+ }+ let tmp = path.with_extension("raea-tmp");+ std::fs::write(&tmp, serde_json::to_string_pretty(&doc).unwrap_or_default() + "\n").map_err(|e| format!("{}: {e}", tmp.display()))?;+ std::fs::rename(&tmp, path).map_err(|e| format!("{}: {e}", path.display()))?;+ Ok(true)+}++/// Adds a `[mcp_servers.blender]` table to Codex's config.toml unless one is there; true when it added.+pub fn add_toml(path: &Path) -> R<bool> {+ let text = std::fs::read_to_string(path).unwrap_or_default();+ if text.lines().any(|l| l.trim() == format!("[mcp_servers.{NAME}]")) {+ return Ok(false);+ }+ let args = ARGS.iter().map(|a| format!("{a:?}")).collect::<Vec<_>>().join(", ");+ let sep = if text.is_empty() || text.ends_with("\n\n") { "" } else if text.ends_with('\n') { "\n" } else { "\n\n" };+ if let Some(dir) = path.parent() {+ std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;+ }+ std::fs::write(path, format!("{text}{sep}[mcp_servers.{NAME}]\ncommand = {CMD:?}\nargs = [{args}]\n")).map_err(|e| format!("{}: {e}", path.display()))?;+ Ok(true)+}++/// Registers the blender MCP server for an agent; the line says what happened. Claude Code rewrites ~/.claude.json while+/// it runs, so its own `claude mcp add` is used when `claude` is on PATH.+pub fn offer(agent: &str) -> R<String> {+ let line = |added: bool, at: &Path| if added { format!("{}: MCP server {NAME} added", at.display()) } else { format!("{}: MCP server {NAME} already there", at.display()) };+ if agent == "codex" {+ let p = user_home()?.join(".codex/config.toml");+ return Ok(line(add_toml(&p)?, &p));+ }+ let p = json_file(agent)?.ok_or_else(|| format!("no agent {agent:?}"))?;+ if agent == "claude" {+ let listed = Command::new("claude").args(["mcp", "get", NAME]).output();+ match listed {+ Ok(o) if o.status.success() => return Ok(line(false, &p)),+ Ok(_) => {+ let o = Command::new("claude").args(["mcp", "add", "--scope", "user", NAME, "--", CMD]).args(ARGS).output().map_err(|e| e.to_string())?;+ if !o.status.success() {+ return Err(format!("claude mcp add {NAME}: {}", String::from_utf8_lossy(&o.stderr).trim()));+ }+ return Ok(line(true, &p));+ }+ Err(_) => {} // no claude on PATH: write its file+ }+ }+ Ok(line(add_json(&p)?, &p))+}++/// A hook entry raea added (its command is `raea hook ...`).+fn ours(hook: &Value) -> bool {+ hook["command"].as_str().unwrap_or("").starts_with("raea hook")+}++/// Claude Code's PostToolUse hook running `raea hook claude` after a file is written, in its settings.json, unless one+/// is there; true when it added. Its findings reach the agent as the hook's additionalContext.+pub fn claude_hook(settings: &Path) -> R<bool> {+ let mut doc: Value = match std::fs::read_to_string(settings) {+ Ok(t) if !t.trim().is_empty() => serde_json::from_str(&t).map_err(|e| format!("{}: {e}", settings.display()))?,+ _ => json!({}),+ };+ let post = doc.as_object_mut().ok_or("settings.json isn't an object")?.entry("hooks").or_insert_with(|| json!({})).as_object_mut().ok_or("settings.json: hooks isn't an object")?.entry("PostToolUse").or_insert_with(|| json!([]));+ let list = post.as_array_mut().ok_or("settings.json: hooks.PostToolUse isn't a list")?;+ if list.iter().any(|m| m["hooks"].as_array().into_iter().flatten().any(ours)) {+ return Ok(false);+ }+ list.push(json!({"matcher": "Write|Edit|MultiEdit", "hooks": [{"type": "command", "command": "raea hook claude", "timeout": 60}]}));+ let tmp = settings.with_extension("raea-tmp");+ std::fs::write(&tmp, serde_json::to_string_pretty(&doc).unwrap_or_default() + "\n").map_err(|e| format!("{}: {e}", tmp.display()))?;+ std::fs::rename(&tmp, settings).map_err(|e| format!("{}: {e}", settings.display()))?;+ Ok(true)+}++/// A move's guide as a skill of its own, named for the move: its description from the guide's first paragraph.+pub fn pin(to: &Path, mv: &str, v: &str) -> R<String> {+ let guide = raea_io_home::home().join("sdk/guides/craft/verbs").join(format!("{mv}.md"));+ let no = format!("no move {mv:?}: `raea guide` lists them");+ if mv.is_empty() || !mv.chars().all(|c| c.is_ascii_lowercase()) {+ return Err(no);+ }+ let text = std::fs::read_to_string(&guide).map_err(|_| no)?;+ let first = text.split("\n\n").nth(1).unwrap_or_default().replace('\n', " ");+ let md = format!("---\nname: {mv}\ndescription: raea's {mv} move, for a note on a raea piece. {}\nversion: {v}\n---\n\n# {mv}\n\nRun `raea guide {mv}` and follow it on the part or moment the note names. Answer the person in their words, never with the move's name. The raea skill has the rest.\n", first.replace(':', " -"));+ let dir = to.join(mv);+ std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;+ std::fs::write(dir.join("SKILL.md"), md).map_err(|e| e.to_string())?;+ Ok(format!("{}: /{mv} pinned\n", dir.display()))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn adds_once_and_keeps_what_was_there() {+ let d = std::env::temp_dir().join(format!("raea-agent-mcp-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&d);+ let j = d.join("kimi/mcp.json");+ assert!(add_json(&j).unwrap());+ assert!(!add_json(&j).unwrap());+ std::fs::write(&j, r#"{"theme":"dark","mcpServers":{"blender":{"command":"mine"}}}"#).unwrap();+ assert!(!add_json(&j).unwrap());+ let kept: Value = serde_json::from_str(&std::fs::read_to_string(&j).unwrap()).unwrap();+ assert_eq!(kept["mcpServers"]["blender"]["command"], "mine");+ let t = d.join("codex/config.toml");+ std::fs::create_dir_all(t.parent().unwrap()).unwrap();+ std::fs::write(&t, "model = \"x\"\n").unwrap();+ assert!(add_toml(&t).unwrap());+ assert!(!add_toml(&t).unwrap());+ assert_eq!(std::fs::read_to_string(&t).unwrap(), "model = \"x\"\n\n[mcp_servers.blender]\ncommand = \"uvx\"\nargs = [\"mcp-for-blender\"]\n");+ let h = d.join("claude/settings.json");+ std::fs::create_dir_all(h.parent().unwrap()).unwrap();+ std::fs::write(&h, r#"{"model":"x","hooks":{"PostToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"other"}]}]}}"#).unwrap();+ assert!(claude_hook(&h).unwrap());+ assert!(!claude_hook(&h).unwrap());+ let v: Value = serde_json::from_str(&std::fs::read_to_string(&h).unwrap()).unwrap();+ assert_eq!(v["hooks"]["PostToolUse"].as_array().unwrap().len(), 2);+ assert_eq!(v["model"], "x");+ let _ = std::fs::remove_dir_all(&d);+ }++ #[test]+ fn a_pinned_move_is_a_skill_of_its_own() {+ let d = std::env::temp_dir().join(format!("raea-pin-{}", std::process::id()));+ assert!(pin(&d, "quieter", "9.9").unwrap().contains("/quieter pinned"));+ let md = std::fs::read_to_string(d.join("quieter/SKILL.md")).unwrap();+ assert!(md.starts_with("---\nname: quieter\ndescription: raea's quieter move") && md.contains("\nversion: 9.9\n---\n") && md.contains("raea guide quieter"), "{md}");+ assert!(pin(&d, "../x", "1").is_err() && pin(&d, "nomove", "1").is_err());+ let _ = std::fs::remove_dir_all(&d);+ }+}diff --git a/apps/tools/src/blender.rs b/apps/tools/src/blender.rsnew file mode 100644index 00000000..3af96b14--- /dev/null+++ b/apps/tools/src/blender.rs@@ -0,0 +1,225 @@+//! `raea setup blender` and `raea blender run` (docs/skills.feature SK11). Blender is GPL, so raea never bundles it: it+//! finds the person's Blender, or downloads the current LTS from blender.org into ~/.raea/tools/blender, and runs it as+//! its own program. The setup also installs the MCP for Blender add-on (github.com/ahujasid/mcp-for-blender, MIT) into+//! that Blender, so an agent's `blender` MCP server (raea skills install adds it) can drive a running Blender.+use std::path::{Path, PathBuf};+use std::process::Command;++type R<T> = Result<T, String>;++pub const USAGE: &str = "raea setup blender [--check] [--download] (find Blender or download the LTS into ~/.raea/tools/blender, and install its MCP add-on)\n raea blender run SCRIPT.py [ARGS...] (blender --background --python SCRIPT.py -- ARGS, headless)";++/// The LTS series raea downloads; the newest patch in blender.org/release/Blender<LTS>/ is taken. Moved when Blender+/// ships a new LTS (blender.org/download/lts).+const LTS: &str = "5.2";++/// Where raea keeps the Blender it downloads.+fn own_dir() -> R<PathBuf> {+ Ok(crate::agent_mcp::user_home()?.join(".raea/tools/blender"))+}++/// The Blender binary inside raea's own download, per platform.+fn own_binary() -> R<PathBuf> {+ let d = own_dir()?;+ Ok(if cfg!(target_os = "macos") { d.join("Blender.app/Contents/MacOS/Blender") } else if cfg!(windows) { d.join("blender.exe") } else { d.join("blender") })+}++fn on_path(name: &str) -> Option<PathBuf> {+ std::env::split_paths(&std::env::var_os("PATH")?).map(|d| d.join(name)).find(|p| p.is_file())+}++/// The Blender to use and where it came from: `git config --global raea.blender`, raea's own download, the usual app+/// folders, then PATH.+pub fn find() -> Option<(PathBuf, &'static str)> {+ let configured = run(Command::new("git").args(["config", "--global", "raea.blender"]), "git config").ok().map(|out| PathBuf::from(out.trim()));+ if let Some(p) = configured.filter(|p| p.is_file()) {+ return Some((p, "raea.blender in git config"));+ }+ if let Some(p) = own_binary().ok().filter(|p| p.is_file()) {+ return Some((p, "raea's download"));+ }+ let mut apps = vec![PathBuf::from("/Applications/Blender.app/Contents/MacOS/Blender")];+ if let Ok(h) = crate::agent_mcp::user_home() {+ apps.push(h.join("Applications/Blender.app/Contents/MacOS/Blender"));+ }+ if let Some(p) = apps.into_iter().find(|p| cfg!(target_os = "macos") && p.is_file()) {+ return Some((p, "Applications"));+ }+ on_path(if cfg!(windows) { "blender.exe" } else { "blender" }).map(|p| (p, "PATH"))+}++/// `blender --version`'s first line ("Blender 5.2.1 LTS").+fn version(bin: &Path) -> R<String> {+ let o = Command::new(bin).arg("--version").output().map_err(|e| format!("{}: {e}", bin.display()))?;+ String::from_utf8_lossy(&o.stdout).lines().find(|l| l.starts_with("Blender ")).map(str::to_string).ok_or_else(|| format!("{} --version printed no version", bin.display()))+}++fn run(cmd: &mut Command, what: &str) -> R<String> {+ let o = cmd.output().map_err(|e| format!("{what}: {e}"))?;+ if !o.status.success() {+ return Err(format!("{what} failed: {}{}", String::from_utf8_lossy(&o.stderr).trim(), String::from_utf8_lossy(&o.stdout).trim()));+ }+ Ok(String::from_utf8_lossy(&o.stdout).into_owned())+}++/// This platform's file name in a release folder, for a version.+fn asset(v: &str) -> R<String> {+ match (std::env::consts::OS, std::env::consts::ARCH) {+ ("macos", "aarch64") => Ok(format!("blender-{v}-macos-arm64.dmg")),+ ("macos", _) => Ok(format!("blender-{v}-macos-x64.dmg")),+ ("linux", "x86_64") => Ok(format!("blender-{v}-linux-x64.tar.xz")),+ ("windows", "aarch64") => Ok(format!("blender-{v}-windows-arm64.zip")),+ ("windows", _) => Ok(format!("blender-{v}-windows-x64.zip")),+ (os, arch) => Err(format!("blender.org has no build for {os} {arch}: install Blender yourself and `git config --global raea.blender PATH`")),+ }+}++/// The newest patch of the LTS series in a release folder's listing.+fn newest(listing: &str) -> Option<String> {+ let pre = format!("blender-{LTS}.");+ let mut best: Option<(u32, String)> = None;+ for part in listing.split(&pre).skip(1) {+ let digits: String = part.chars().take_while(char::is_ascii_digit).collect();+ if let Ok(n) = digits.parse::<u32>() {+ if part[digits.len()..].starts_with('-') && best.as_ref().map_or(true, |(b, _)| n > *b) {+ best = Some((n, format!("{LTS}.{n}")));+ }+ }+ }+ best.map(|(_, v)| v)+}++fn sha256(file: &Path) -> R<String> {+ let out = if cfg!(windows) {+ run(Command::new("certutil").arg("-hashfile").arg(file).arg("SHA256"), "certutil")?.lines().nth(1).unwrap_or_default().replace(' ', "")+ } else {+ run(Command::new("shasum").args(["-a", "256"]).arg(file), "shasum")?.split_whitespace().next().unwrap_or_default().to_string()+ };+ Ok(out.to_lowercase())+}++/// Downloads the LTS into ~/.raea/tools/blender, checked against blender.org's sha256 list, and returns its binary.+fn download() -> R<(PathBuf, String)> {+ let base = format!("https://download.blender.org/release/Blender{LTS}/");+ let listing = run(Command::new("curl").args(["-fsSL", &base]), "curl")?;+ let v = newest(&listing).ok_or_else(|| format!("no Blender {LTS} release listed at {base}"))?;+ let name = asset(&v)?;+ let dir = own_dir()?;+ let tmp = dir.with_file_name("blender.download");+ let _ = std::fs::remove_dir_all(&tmp);+ std::fs::create_dir_all(&tmp).map_err(|e| format!("{}: {e}", tmp.display()))?;+ let file = tmp.join(&name);+ run(Command::new("curl").args(["-fL", "--retry", "3", "-o"]).arg(&file).arg(format!("{base}{name}")), "downloading Blender")?;+ let sums = run(Command::new("curl").args(["-fsSL", &format!("{base}blender-{v}.sha256")]), "curl")?;+ let want = sums.lines().find(|l| l.ends_with(&name)).and_then(|l| l.split_whitespace().next()).ok_or_else(|| format!("blender-{v}.sha256 doesn't list {name}"))?.to_lowercase();+ if sha256(&file)? != want {+ return Err(format!("{name} doesn't match blender.org's sha256; nothing installed (it's in {})", tmp.display()));+ }+ let unpacked = tmp.join("unpacked");+ std::fs::create_dir_all(&unpacked).map_err(|e| e.to_string())?;+ if name.ends_with(".dmg") {+ let mnt = tmp.join("mnt");+ run(Command::new("hdiutil").args(["attach", "-nobrowse", "-readonly", "-mountpoint"]).arg(&mnt).arg(&file), "hdiutil attach")?;+ let copied = run(Command::new("ditto").arg(mnt.join("Blender.app")).arg(unpacked.join("Blender.app")), "copying Blender.app");+ let _ = Command::new("hdiutil").args(["detach", "-quiet"]).arg(&mnt).status();+ copied?;+ } else {+ // tar unpacks .tar.xz on Linux and .zip on Windows 10 and 11; both hold one top folder+ run(Command::new("tar").arg("-xf").arg(&file).arg("-C").arg(&unpacked).args(if cfg!(windows) { vec![] } else { vec!["--strip-components=1"] }), "unpacking Blender")?;+ if cfg!(windows) {+ let top = std::fs::read_dir(&unpacked).map_err(|e| e.to_string())?.flatten().find(|e| e.path().is_dir()).ok_or("the zip held no folder")?.path();+ let flat = tmp.join("flat");+ std::fs::rename(&top, &flat).map_err(|e| e.to_string())?;+ std::fs::remove_dir_all(&unpacked).map_err(|e| e.to_string())?;+ std::fs::rename(&flat, &unpacked).map_err(|e| e.to_string())?;+ }+ }+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::rename(&unpacked, &dir).map_err(|e| format!("{}: {e}", dir.display()))?;+ let _ = std::fs::remove_dir_all(&tmp);+ Ok((own_binary()?, format!("downloaded Blender {v} LTS from blender.org")))+}++/// Python run inside Blender (background): prints the user add-ons folder, or whether the add-on is enabled.+const ADDONS_DIR: &str = "import bpy; print('RAEA_ADDONS=' + bpy.utils.user_resource('SCRIPTS', path='addons', create=True))";+const ENABLE: &str = "import addon_utils, bpy; addon_utils.enable('blender_mcp', default_set=True, persistent=True); bpy.ops.wm.save_userpref(); print('RAEA_ENABLED=' + str(addon_utils.check('blender_mcp')[1]))";+const CHECK: &str = "import addon_utils; print('RAEA_ENABLED=' + str(addon_utils.check('blender_mcp')[1]))";++fn py(bin: &Path, code: &str, key: &str) -> R<String> {+ let out = run(Command::new(bin).args(["--background", "--factory-startup", "--python-expr", code]), "blender")?;+ out.lines().find_map(|l| l.strip_prefix(key)).map(str::to_string).ok_or_else(|| format!("blender printed no {key}"))+}++/// The add-on: uvx mcp-for-blender's own installer writes it into this Blender's add-ons folder, then Blender enables it.+fn addon(bin: &Path, check: bool) -> R<String> {+ // --factory-startup skips the person's add-ons for speed, so the check reads the saved preferences instead+ let state = |b: &Path| run(Command::new(b).args(["--background", "--python-expr", CHECK]), "blender").map(|o| o.contains("RAEA_ENABLED=True"));+ if state(bin)? {+ return Ok("MCP add-on enabled".into());+ }+ if check {+ return Ok("MCP add-on not installed: raea setup blender installs it".into());+ }+ let uvx = on_path(if cfg!(windows) { "uvx.exe" } else { "uvx" }).ok_or("the MCP add-on comes from uv's uvx: install uv (https://docs.astral.sh/uv/getting-started/installation/), then run raea setup blender again")?;+ let dir = py(bin, ADDONS_DIR, "RAEA_ADDONS=")?;+ run(Command::new(&uvx).args(["mcp-for-blender", "install-addon", "--addons-dir", &dir]), "uvx mcp-for-blender install-addon")?;+ let on = run(Command::new(bin).args(["--background", "--python-expr", ENABLE]), "blender")?;+ if !on.contains("RAEA_ENABLED=True") {+ return Err(format!("the add-on is in {dir} but Blender didn't enable it: enable \"MCP for Blender\" in Preferences > Add-ons"));+ }+ Ok(format!("MCP add-on installed now ({dir})"))+}++/// `raea setup blender [--check] [--download]`.+pub fn setup(args: &[String]) -> R<String> {+ let check = args.iter().any(|a| a == "--check");+ let fresh = args.iter().any(|a| a == "--download");+ let (bin, from) = match find().filter(|_| !fresh) {+ Some((b, f)) => (b, f.to_string()),+ None if check => return Ok(format!("CHECKED no Blender found (raea.blender, {}, PATH): raea setup blender downloads Blender {LTS} LTS", own_dir()?.display())),+ None => {+ let (b, f) = download()?;+ run(Command::new("git").args(["config", "--global", "raea.blender"]).arg(&b), "git config")?;+ (b, f)+ }+ };+ let v = version(&bin)?;+ let add = addon(&bin, check)?;+ let head = if check { "CHECKED " } else { "APPLIED " };+ Ok(format!("{head} {v} ({from})\n {}\n {add}\n headless: raea blender run SCRIPT.py; live: start Blender and the agent's `blender` MCP server connects (raea skills install adds it)", bin.display()))+}++/// `raea blender run SCRIPT.py [ARGS...]`: the script in a windowless Blender, its args after `--` (sys.argv), its+/// output passed through. Exits as Blender's Python did: --python-exit-code makes an uncaught error fail the run.+pub fn blender(args: &[String]) -> R<String> {+ if args.get(1).map(String::as_str) != Some("run") {+ return Err(format!("usage: {USAGE}"));+ }+ let script = args.get(2).ok_or_else(|| format!("which script: {USAGE}"))?;+ if !Path::new(script).is_file() {+ return Err(format!("no script {script}"));+ }+ let (bin, _) = find().ok_or("no Blender: raea setup blender finds or downloads one")?;+ let st = Command::new(&bin).args(["--background", "--factory-startup", "--python-exit-code", "1", "--python", script, "--"]).args(&args[3..]).status().map_err(|e| format!("{}: {e}", bin.display()))?;+ if !st.success() {+ return Err(format!("{script} failed in Blender ({st})"));+ }+ Ok(String::new())+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn newest_takes_the_highest_patch_of_the_lts() {+ let listing = format!("<a href=\"blender-{LTS}.0-linux-x64.tar.xz\"> <a href=\"blender-{LTS}.12-macos-arm64.dmg\"> <a href=\"blender-{LTS}.3-windows-x64.zip\"> blender-{LTS}.9.sha256 blender-{LTS}.99beta");+ assert_eq!(newest(&listing), Some(format!("{LTS}.12")));+ assert_eq!(newest("nothing here"), None);+ }++ #[test]+ fn every_supported_platform_names_one_file() {+ assert!(asset("5.2.1").unwrap().starts_with("blender-5.2.1-"));+ }+}diff --git a/apps/tools/src/generate.rs b/apps/tools/src/generate.rsnew file mode 100644index 00000000..d932f642--- /dev/null+++ b/apps/tools/src/generate.rs@@ -0,0 +1,53 @@+//! `raea gen …` (raea-io-gen's verbs), with raea's own local models as the flow's `local:` backend: sao for sound+//! effects, made through the edit's asset store as a render would.++use std::path::{Path, PathBuf};++use raea_io_gen::flow::Step;+use serde_json::json;++struct Local;++impl raea_io_gen::run::Local for Local {+ fn names(&self) -> Vec<String> {+ vec!["sao".to_string()]+ }++ fn make(&self, name: &str, step: &Step, dir: &Path, key: &str) -> Result<PathBuf, String> {+ let text = |k: &str| step.inputs.get(k).and_then(|v| v.as_str()).unwrap_or("").to_string();+ let (prompt, params) = match name {+ "sao" => (text("prompt"), json!({"seconds": step.inputs.get("seconds").and_then(|v| v.as_f64()).unwrap_or(2.0)})),+ _ => return Err(format!("no local model `{name}` (this host runs sao)")),+ };+ let store = raea_io_assets::Store { dir: dir.join("assets") };+ let seed = step.inputs.get("seed").and_then(|v| v.as_u64()).unwrap_or(1);+ let a = store.make(name, &prompt, seed, ¶ms)?;+ let out = dir.join(format!("{key}.{}", a.ext));+ std::fs::copy(store.path(&a), &out).map_err(|e| format!("{}: {e}", out.display()))?;+ Ok(out)+ }+}++pub fn generate(args: &[String]) -> Result<String, String> {+ raea_io_gen::cli::command(&args[1..], Some(&Local))+}++#[cfg(test)]+mod tests {+ // GN14: a flow's sfx step on this Mac's sao, through `raea gen run` as the CLI calls it. It runs the model (about 2+ // GB, installed on first use), so it's ignored by default: cargo test -p raea-app-tools generate -- --ignored+ #[test]+ #[ignore]+ fn sfx_step_runs_on_sao() {+ let dir = std::env::temp_dir().join(format!("raea-gen-sao-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let flow = dir.join("flow.json");+ std::fs::write(&flow, r#"{"flow":1,"steps":{"knock":{"op":"audio.sfx","in":{"prompt":"three firm knocks on a wooden door, close, dry room","seconds":2}}},"out":["knock"]}"#).unwrap();+ // as engine/cli hands it over: the verb first+ let args: Vec<String> = ["gen", "run", flow.to_str().unwrap(), "-o", dir.to_str().unwrap()].iter().map(|s| s.to_string()).collect();+ let out = super::generate(&args).unwrap();+ assert!(out.contains("local:sao"), "{out}");+ let wav = dir.join("knock.wav");+ assert!(std::fs::metadata(&wav).unwrap().len() > 10_000, "{}", wav.display());+ }+}diff --git a/apps/tools/src/lib.rs b/apps/tools/src/lib.rsindex 35f18311..f6341669 100644--- a/apps/tools/src/lib.rs+++ b/apps/tools/src/lib.rs@@ -1,7 +1,14 @@//! The verbs that run raea's local tools: sound (`raea sao`, `tokensynth`, `setup-audio`, `sounds`: foley and an//! instrument's notes made by local models, and the open sample libraries), `raea splat` (footage trained into a-//! Gaussian splat) and `raea song` (a song's energy map, apps/tools/src/song.rs).+//! Gaussian splat), `raea song` (a song's energy map, apps/tools/src/song.rs) and `raea gen` (generation flows on+//! made.app, fal, Replicate, OpenRouter, Modal and ComfyUI, with sao as the local model: apps/tools/src/generate.rs).+pub mod generate;pub mod song;pub mod sound;pub mod splat;++/// the MCP servers `raea skills install` offers an agent (blender, for a running Blender)+pub mod agent_mcp;+/// `raea setup blender` and `raea blender run`+pub mod blender;diff --git a/apps/tools/src/sound/library.rs b/apps/tools/src/sound/library.rsindex 2d700be6..cac20db5 100644--- a/apps/tools/src/sound/library.rs+++ b/apps/tools/src/sound/library.rs@@ -86,6 +86,7 @@ pub(crate) fn fetch(url: &str, cached: &Path) -> R<()> {if cached.exists() {return Ok(());}+ raea_io_home::offline(&format!("the sample library file {url}"))?;std::fs::create_dir_all(cached.parent().unwrap()).map_err(|e| e.to_string())?;let part = cached.with_extension("part");let o = std::process::Command::new("curl").args(["-fsSL", "--retry", "2", "-o"]).arg(&part).arg(url).output().map_err(|e| format!("curl: {e}"))?;diff --git a/apps/workspace/Cargo.toml b/apps/workspace/Cargo.tomlnew file mode 100644index 00000000..fe1799cf--- /dev/null+++ b/apps/workspace/Cargo.toml@@ -0,0 +1,12 @@+[package]+name = "raea-app-workspace"+version = "0.1.0"+edition = "2024"+license = "FSL-1.1-ALv2"+publish = false+description = "`raea workspace`, `raea project` and `raea controller`: a workspace's folders, projects and controllers, each change a commit"++[dependencies]+# the controller schema (core/brief controller.rs): a controller file is checked and normalized against it+raea-core-brief = { path = "../../core/brief" }+serde_json = "1"diff --git a/apps/workspace/src/controllers.rs b/apps/workspace/src/controllers.rsnew file mode 100644index 00000000..c2e0fb1f--- /dev/null+++ b/apps/workspace/src/controllers.rs@@ -0,0 +1,209 @@+//! A workspace's controllers on disk (docs/projects.feature PJ2): controllers/<id>.ts, each `export default+//! controller({...})` from "raea/brief", checked by core/brief's normalize. A project overrides a field's value in its+//! .raea/project (`[controller "delivery.format"] aspect-ratio = 16:9`), so the project's value wins, as git config's+//! own scopes do. Every change is a commit by who made it ("you", or the agent's name with --by).+use super::*;+use raea_core_brief::controller::{self as ctl, Controller, Field, Kind};++use std::process::Command;++const USAGE: &str = "usage: raea controller ls [--json] | get PATH [--json] | set PATH VALUE [--project] [--by NAME] | write FILE.ts [--by NAME] | rm ID [--by NAME]\n (PATH is controller.group.field; a VALUE is JSON for numbers, toggles and lists, else text)";++fn workspace_dir() -> R<PathBuf> {+ let here = std::env::current_dir().map_err(|e| e.to_string())?;+ workspace::up(&here, ".raea/workspace").ok_or_else(|| "not in a workspace: raea workspace init NAME makes one".to_string())+}++/// Every controller in the workspace, checked, in file order.+pub fn load(ws: &Path, eval: Eval) -> R<Vec<(PathBuf, Controller)>> {+ let mut files: Vec<PathBuf> = std::fs::read_dir(ws.join("controllers")).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "ts")).collect();+ files.sort();+ files.into_iter().map(|f| read(&f, eval).map(|c| (f, c))).collect()+}++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()))+}++/// The module a controller is kept as.+pub fn module(c: &Controller) -> String {+ format!("import {{ controller }} from \"raea/brief\";\n\nexport default controller({});\n", ts_literal(&serde_json::to_value(c).unwrap_or_default(), 0))+}++/// A field's value as JSON (its kind's `value`).+fn value_of(f: &Field) -> serde_json::Value {+ serde_json::to_value(&f.kind).ok().and_then(|v| v.get("value").cloned()).unwrap_or_default()+}++/// The git-config key for a field's override: `controller.<controller>.<group>.<field>`, which git reads as section+/// controller, subsection "<controller>.<group>", key <field>.+fn key(path: &str) -> String {+ format!("controller.{path}")+}++/// A value as typed on the command line or kept in git config: JSON when it parses as JSON of the field's kind, else+/// the text itself (a choice, a text field).+fn parse(f: &Field, s: &str) -> R<serde_json::Value> {+ let v = match (&f.kind, serde_json::from_str::<serde_json::Value>(s)) {+ (Kind::Text { .. } | Kind::Choice { .. }, Ok(serde_json::Value::String(t))) => serde_json::Value::String(t),+ (Kind::Text { .. } | Kind::Choice { .. }, _) => serde_json::Value::String(s.to_string()),+ (_, Ok(v)) => v,+ (_, Err(_)) => serde_json::Value::String(s.to_string()),+ };+ ctl::check_value(f, &v)+}++/// The overrides of the project `from` is in, by path.+fn overrides(from: &Path) -> Vec<(String, String)> {+ let Some(p) = workspace::up(from, ".raea/project") else { return vec![] };+ let text = workspace::config(Some(&p.join(".raea/project")), &["--get-regexp", "^controller\\."]).unwrap_or_default();+ text.lines().filter_map(|l| l.split_once(' ')).map(|(k, v)| (k.trim_start_matches("controller.").to_string(), v.to_string())).collect()+}++fn commit(ws: &Path, paths: &[&Path], what: &str, by: &str) -> R<()> {+ let mut add = Command::new("git");+ add.arg("-C").arg(ws).args(["add", "-A", "--"]).args(paths);+ add.status().map_err(|e| format!("git: {e}"))?;+ let ok = Command::new("git").arg("-C").arg(ws).args(["-c", &format!("user.name={by}"), "commit", "-q", "-m", &format!("{by}: {what}"), "--"]).args(paths).status().map_err(|e| format!("git: {e}"))?;+ if ok.success() { Ok(()) } else { Err(format!("couldn't commit {what}")) }+}++/// `raea controller …`, its specs evaluated by `eval`+pub fn controller(args: &[String], eval: Eval) -> R<String> {+ let json_out = args.iter().any(|a| a == "--json");+ let by = workspace::flag(args, "--by").unwrap_or("you").trim_start_matches('@').to_string();+ let w: Vec<&str> = args.iter().enumerate().filter(|(i, a)| !a.starts_with("--") && !(*i > 0 && args[i - 1] == "--by")).map(|(_, a)| a.as_str()).collect();+ let ws = workspace_dir()?;+ match w.as_slice() {+ ["ls"] | [] => ls(&ws, json_out, eval),+ ["get", path] => get(&ws, path, json_out, eval),+ ["set", path, value] => set(&ws, path, value, args.iter().any(|a| a == "--project"), &by, eval),+ ["write", file] => write(&ws, Path::new(file), &by, eval),+ ["rm", id] => rm(&ws, id, &by),+ _ => Err(USAGE.into()),+ }+}++/// The controllers as `raea controller ls` prints them, with the overrides of the project `from` is in: what `raea+/// context` shows an agent. None outside a workspace or when it has no controllers.+pub fn summary(from: &Path, eval: Eval) -> Option<String> {+ let ws = workspace::up(from, ".raea/workspace")?;+ load(&ws, eval).ok().filter(|cs| !cs.is_empty())?;+ ls_from(&ws, from, false, eval).ok()+}++fn ls(ws: &Path, json_out: bool, eval: Eval) -> R<String> {+ ls_from(ws, &std::env::current_dir().map_err(|e| e.to_string())?, json_out, eval)+}++fn ls_from(ws: &Path, from: &Path, json_out: bool, eval: Eval) -> R<String> {+ let cs = load(ws, eval)?;+ let over = overrides(from);+ let mut rows = vec![];+ for (_, c) in &cs {+ for g in &c.groups {+ for f in &g.fields {+ let path = format!("{}.{}.{}", c.id, g.id, f.id);+ let mine = over.iter().find(|(k, _)| *k == path).and_then(|(_, v)| parse(f, v).ok());+ rows.push((path, f, mine.clone().unwrap_or_else(|| value_of(f)), mine.is_some()));+ }+ }+ }+ if json_out {+ let fields: Vec<_> = rows.iter().map(|(p, f, v, o)| json!({"path": p, "label": f.label, "type": serde_json::to_value(&f.kind).ok().and_then(|k| k.get("type").cloned()), "value": v, "project": o})).collect();+ let list: Vec<_> = cs.iter().map(|(_, c)| serde_json::to_value(c).map(|v| tidy_deep(&v)).unwrap_or_default()).collect();+ return Ok(json!({"controllers": list, "fields": fields}).to_string());+ }+ if cs.is_empty() {+ return Ok("no controllers yet: raea controller write FILE.ts adds one (`export default controller({ title, groups })` from \"raea/brief\")".into());+ }+ let mut out = String::new();+ for (_, c) in &cs {+ out.push_str(&format!("{} ({})\n", c.title, c.id));+ for (p, f, v, o) in rows.iter().filter(|r| r.0.starts_with(&format!("{}.", c.id))) {+ out.push_str(&format!(" {p} {}: {}{}\n", f.label, tidy(v), if *o { " (this project)" } else { "" }));+ }+ }+ Ok(out.trim_end().to_string())+}++/// Where a path's field is: its controller, group and field, by index.+fn locate(cs: &[(PathBuf, Controller)], path: &str) -> R<(usize, usize, usize)> {+ let mut p = path.splitn(3, '.');+ let (c, g, f) = (p.next().unwrap_or(""), p.next().unwrap_or(""), p.next().unwrap_or(""));+ let ci = cs.iter().position(|x| x.1.id == c);+ let gi = ci.and_then(|ci| cs[ci].1.groups.iter().position(|y| y.id == g));+ let fi = ci.zip(gi).and_then(|(ci, gi)| cs[ci].1.groups[gi].fields.iter().position(|z| z.id == f));+ match (ci, gi, fi) {+ (Some(c), Some(g), Some(f)) => Ok((c, g, f)),+ _ => Err(format!("no field at {path}: raea controller ls lists the paths (controller.group.field)")),+ }+}++fn find<'a>(cs: &'a [(PathBuf, Controller)], path: &str) -> R<&'a Field> {+ let (c, g, f) = locate(cs, path)?;+ Ok(&cs[c].1.groups[g].fields[f])+}++fn get(ws: &Path, path: &str, json_out: bool, eval: Eval) -> R<String> {+ let cs = load(ws, eval)?;+ let f = find(&cs, path)?;+ let here = std::env::current_dir().map_err(|e| e.to_string())?;+ let mine = overrides(&here).into_iter().find(|(k, _)| k == path).map(|(_, v)| parse(f, &v)).transpose()?;+ let v = mine.clone().unwrap_or_else(|| value_of(f));+ let v = tidy(&v);+ Ok(if json_out { json!({"path": path, "value": v, "project": mine.is_some()}).to_string() } else { v.to_string() })+}++fn set(ws: &Path, path: &str, value: &str, project: bool, by: &str, eval: Eval) -> R<String> {+ let mut cs = load(ws, eval)?;+ let v = parse(find(&cs, path)?, value)?;+ if project {+ let here = std::env::current_dir().map_err(|e| e.to_string())?;+ let p = workspace::up(&here, ".raea/project").ok_or("--project: not in a project")?;+ let text = match &v {+ serde_json::Value::String(s) => s.clone(),+ v => v.to_string(),+ };+ let file = p.join(".raea/project");+ workspace::set(&file, &key(path), &text)?;+ // a submodule project is its own repo; an inline one commits in the workspace+ let repo = if p.join(".git").exists() { p.clone() } else { ws.to_path_buf() };+ commit(&repo, &[&file], &format!("{path} = {text} for this project"), by)?;+ return Ok(format!("{path} = {text} (this project)"));+ }+ let (c, g, f) = locate(&cs, path)?;+ let (file, ctrl) = &mut cs[c];+ let field = &mut ctrl.groups[g].fields[f];+ let mut kind = serde_json::to_value(&field.kind).map_err(|e| e.to_string())?;+ kind["value"] = v.clone();+ field.kind = serde_json::from_value(kind).map_err(|e| e.to_string())?;+ std::fs::write(&*file, module(ctrl)).map_err(|e| format!("{}: {e}", file.display()))?;+ let file = file.clone();+ let v = tidy(&v);+ let said = v.as_str().map(String::from).unwrap_or_else(|| v.to_string());+ commit(ws, &[&file], &format!("{path} = {said}"), by)?;+ Ok(format!("{path} = {v}"))+}++fn write(ws: &Path, file: &Path, by: &str, eval: Eval) -> R<String> {+ let c = read(file, eval)?;+ let to = ws.join("controllers").join(format!("{}.ts", c.id));+ let new = !to.exists();+ std::fs::create_dir_all(ws.join("controllers")).map_err(|e| e.to_string())?;+ std::fs::write(&to, module(&c)).map_err(|e| format!("{}: {e}", to.display()))?;+ commit(ws, &[&to], &format!("{} controller {}", if new { "add" } else { "rewrite" }, c.id), by)?;+ let n = |k: usize, what: &str| format!("{k} {what}{}", if k == 1 { "" } else { "s" });+ Ok(format!("{}: {} ({}, {})", to.display(), c.title, n(c.groups.len(), "group"), n(c.groups.iter().map(|g| g.fields.len()).sum(), "field")))+}++fn rm(ws: &Path, id: &str, by: &str) -> R<String> {+ let file = ws.join("controllers").join(format!("{id}.ts"));+ if !file.is_file() {+ return Err(format!("no controller {id}: raea controller ls lists them"));+ }+ std::fs::remove_file(&file).map_err(|e| format!("{}: {e}", file.display()))?;+ commit(ws, &[&file], &format!("remove controller {id}"), by)?;+ Ok(format!("removed {id} (git revert brings it back)"))+}diff --git a/apps/workspace/src/doctor.rs b/apps/workspace/src/doctor.rsnew file mode 100644index 00000000..a2e14113--- /dev/null+++ b/apps/workspace/src/doctor.rs@@ -0,0 +1,138 @@+//! `raea doctor [--fix]` (docs/skills.feature SK10): drift between a project's files and what this raea reads. Old brief+//! files raea no longer reads, a workspace or project file missing what this version writes (or not included from the+//! repo's git config), and an agent's copy of the raea skill from another version. `raea context` runs the same checks+//! and prints CONTEXT_STALE when any finds something, so they stay cheap: file reads and git config, no engine.+use super::*;+use crate::workspace::{get, git, include, new_id, set};++/// One thing doctor found, and whether `--fix` can fix it.+pub struct Finding {+ pub says: String,+ fix: Fix,+}++enum Fix {+ No,+ /// a key missing from a git-config file: (file, key, value)+ Set(PathBuf, String, String),+ /// the include in a repo's config that makes `git config` read its committed file: (repo, file)+ Include(PathBuf, PathBuf),+ /// an agent's skills reinstalled from this raea+ Skills(String),+}++impl Finding {+ pub fn fixable(&self) -> bool {+ !matches!(self.fix, Fix::No)+ }+}++/// Old brief files under a folder (raea reads only brief.ts, script.ts and taste.ts since 11-05), a few levels down.+fn old_briefs(dir: &Path, depth: usize, out: &mut Vec<Finding>) {+ let Ok(rd) = std::fs::read_dir(dir) else { return };+ for e in rd.flatten() {+ let p = e.path();+ let name = e.file_name().to_string_lossy().into_owned();+ if p.is_dir() {+ if depth > 0 && !name.starts_with('.') && name != "node_modules" && name != "media" && name != "out" {+ old_briefs(&p, depth - 1, out);+ }+ } else if [".brief", ".board"].iter().any(|x| name.ends_with(x)) {+ out.push(Finding { says: format!("{}: an old brief file, which raea no longer reads; rewrite it as brief.ts (export default brief({{...}}) from \"raea/brief\") and delete it", p.display()), fix: Fix::No });+ }+ }+}++/// A committed git-config file's keys this version writes, and its include from the repo's config.+fn format(repo: &Path, file: &Path, keys: &[(&str, String)], out: &mut Vec<Finding>) {+ for (k, v) in keys {+ if get(file, k).is_none() {+ out.push(Finding { says: format!("{}: no {k} (an older format); --fix sets it to {v}", file.display()), fix: Fix::Set(file.to_path_buf(), k.to_string(), v.clone()) });+ }+ }+ // only a folder that is its own repo includes its file (a workspace, a split project); an inline project shares+ // the workspace's repo, whose config must not take one project's keys+ let own = git(repo, &["rev-parse", "--show-toplevel"]).ok().and_then(|t| Path::new(&t).canonicalize().ok()) == repo.canonicalize().ok();+ let first = keys.first().map(|(k, _)| *k).unwrap_or_default();+ let read = git(repo, &["config", first]).ok().filter(|v| !v.is_empty());+ if own && read.is_none() && get(file, first).is_some() {+ out.push(Finding { says: format!("{}: git config doesn't read it (no include in the repo's config); --fix adds it", file.display()), fix: Fix::Include(repo.to_path_buf(), file.to_path_buf()) });+ }+}++/// The `version:` in a SKILL.md's front matter.+fn skill_version(md: &Path) -> Option<String> {+ let text = std::fs::read_to_string(md).ok()?;+ let front = text.strip_prefix("---\n")?.split("\n---\n").next()?;+ front.lines().find_map(|l| l.strip_prefix("version:")).map(|v| v.trim().to_string())+}++/// What doctor finds from a folder: `skills` are (agent, its skills folder), `version` this raea's.+pub fn findings(from: &Path, skills: &[(&str, PathBuf)], version: &str) -> Vec<Finding> {+ let mut out = Vec::new();+ let ws = up(from, ".raea/workspace");+ let project = up(from, ".raea/project");+ let base = project.clone().or_else(|| ws.clone()).unwrap_or_else(|| from.to_path_buf());+ old_briefs(&base, if project.is_some() { 2 } else { 1 }, &mut out);+ if let Some(ws) = &ws {+ let name = ws.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();+ let keys = [("workspace.id", new_id("ws")), ("workspace.name", name), ("workspace.layout", "monorepo".to_string())];+ format(ws, &ws.join(".raea/workspace"), &keys, &mut out);+ }+ if let Some(p) = &project {+ let name = p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();+ let keys = [("project.id", new_id("pj")), ("project.name", name)];+ format(p, &p.join(".raea/project"), &keys, &mut out);+ }+ for (agent, dir) in skills {+ let md = dir.join("raea/SKILL.md");+ if !md.is_file() {+ continue;+ }+ let have = skill_version(&md).unwrap_or_else(|| "unversioned".into());+ if have != version {+ out.push(Finding { says: format!("{}: the raea skill {agent} reads is {have}, this raea is {version}; --fix reinstalls it", md.display()), fix: Fix::Skills(agent.to_string()) });+ }+ }+ out+}++/// `raea doctor [--fix] [DIR]`: what it found and, with --fix, what it fixed. `reinstall` puts an agent's skills back+/// (the raea CLI's `skills install`).+pub fn doctor(args: &[String], skills: &[(&str, PathBuf)], version: &str, reinstall: &dyn Fn(&str) -> R<String>) -> R<String> {+ let fix = args.iter().any(|a| a == "--fix");+ let from = PathBuf::from(args.iter().find(|a| !a.starts_with("--")).map(String::as_str).unwrap_or("."));+ let found = findings(&from, skills, version);+ if found.is_empty() {+ return Ok("CHECKED nothing to fix: this folder's files and the agents' raea skill match this raea".into());+ }+ let mut lines = Vec::new();+ let mut fixed = 0;+ for f in &found {+ let done = match (&f.fix, fix) {+ (Fix::Set(file, k, v), true) => set(file, k, v).map(|_| true),+ (Fix::Include(repo, file), true) => include(repo, file).map(|_| true),+ (Fix::Skills(agent), true) => reinstall(agent).map(|_| true),+ _ => Ok(false),+ };+ match done {+ Ok(true) => {+ fixed += 1;+ lines.push(format!(" fixed {}", f.says));+ }+ Ok(false) => lines.push(format!(" {} {}", if f.fixable() { "fix " } else { "by hand" }, f.says)),+ Err(e) => lines.push(format!(" failed {}: {e}", f.says)),+ }+ }+ // a workspace's own files changed: commit them, as every change raea makes there is+ if fix && fixed > 0 {+ for marker in [".raea/workspace", ".raea/project"] {+ if let Some(repo) = up(&from, marker) {+ let _ = crate::workspace::commit(&repo, &[marker], "doctor --fix");+ }+ }+ }+ let can = found.iter().filter(|f| f.fixable()).count();+ let head = if fix { format!("APPLIED {fixed} of {} fixed", found.len()) } else { format!("CHECKED {} to fix ({can} by raea doctor --fix)", found.len()) };+ Ok(format!("{head}\n{}", lines.join("\n")))+}diff --git a/apps/workspace/src/lib.rs b/apps/workspace/src/lib.rsnew file mode 100644index 00000000..b42a1f21--- /dev/null+++ b/apps/workspace/src/lib.rs@@ -0,0 +1,25 @@+//! A workspace's folders and files (docs/projects.feature PJ1-PJ4): `raea workspace`, `raea project` (with split and+//! join) and `raea controller`. A workspace is a git repo raea changes by commits; its controllers are spec modules,+//! which the raea CLI evaluates on the engine and hands in as an `Eval`, so this crate needs no engine of its own.+use std::path::{Path, PathBuf};++use serde_json::json;++mod controllers;+pub mod doctor;+mod literal;+pub mod next;+mod storage;+mod workspace;++pub use controllers::{controller, module, summary};+pub use literal::{tidy, tidy_deep, ts_literal};+pub use workspace::{project, projects, root, slug, up, workspace};++pub type R<T> = Result<T, String>;++/// A spec module's default export as JSON: the raea CLI's spec_json, which runs it on the engine.+pub type Eval = fn(&Path) -> R<String>;++#[cfg(test)]+mod tests;diff --git a/apps/workspace/src/literal.rs b/apps/workspace/src/literal.rsnew file mode 100644index 00000000..ee908400--- /dev/null+++ b/apps/workspace/src/literal.rs@@ -0,0 +1,37 @@+//! Spec modules as raea writes them: a value as a TypeScript literal, and whole numbers kept whole.+/// A value as a TypeScript literal for a spec module: unquoted keys where they can be, nulls and empty lists left out.+pub fn ts_literal(v: &serde_json::Value, indent: usize) -> String {+ use serde_json::Value;+ let (pad, end) = (" ".repeat(indent + 1), " ".repeat(indent));+ match v {+ Value::Array(a) if a.iter().all(Value::is_string) && v.to_string().len() < 70 => format!("[{}]", a.iter().map(Value::to_string).collect::<Vec<_>>().join(", ")),+ Value::Array(a) => format!("[\n{}{end}]", a.iter().map(|x| format!("{pad}{},\n", ts_literal(x, indent + 1))).collect::<String>()),+ Value::Object(o) => {+ let ident = |k: &str| k.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_') && k.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');+ let kept = o.iter().filter(|(_, x)| !x.is_null() && !x.as_array().is_some_and(Vec::is_empty));+ let body: String = kept.map(|(k, x)| format!("{pad}{}: {},\n", if ident(k) { k.clone() } else { Value::String(k.clone()).to_string() }, ts_literal(x, indent + 1))).collect();+ format!("{{\n{body}{end}}}")+ }+ v => tidy(v).to_string(),+ }+}++/// A number that's whole (as f64 values from Rust are, 45.0) written as an integer.+pub fn tidy(v: &serde_json::Value) -> serde_json::Value {+ match v.as_f64() {+ Some(n) if v.is_f64() && n.fract() == 0.0 && n.abs() < 1e15 => serde_json::Value::from(n as i64),+ _ => match v {+ serde_json::Value::Array(a) => serde_json::Value::Array(a.iter().map(tidy).collect()),+ v => v.clone(),+ },+ }+}++/// `tidy` through a whole value: objects and arrays too.+pub fn tidy_deep(v: &serde_json::Value) -> serde_json::Value {+ match v {+ serde_json::Value::Object(o) => serde_json::Value::Object(o.iter().filter(|(_, x)| !x.is_null()).map(|(k, x)| (k.clone(), tidy_deep(x))).collect()),+ serde_json::Value::Array(a) => serde_json::Value::Array(a.iter().map(tidy_deep).collect()),+ v => tidy(v),+ }+}diff --git a/apps/workspace/src/next.rs b/apps/workspace/src/next.rsnew file mode 100644index 00000000..88edd868--- /dev/null+++ b/apps/workspace/src/next.rs@@ -0,0 +1,86 @@+//! `raea next` (docs/skills.feature SK10): the two or three useful next steps for a project, read from its files: the+//! brief (what it still needs, from the raea CLI's brief doctor), the storyboard its modes want, its compositions, its+//! renders in out/ and their checks (`raea check ... -o out/NAME.check.json`). A menu for the agent or the person to+//! pick from; nothing runs.+use super::*;+use std::time::SystemTime;++/// What the raea CLI read from the project's brief.+pub struct Brief {+ /// what the brief still needs (empty when it's shaped)+ pub needs: Vec<String>,+ pub modes: Vec<String>,+}++fn modified(p: &Path) -> SystemTime {+ std::fs::metadata(p).and_then(|m| m.modified()).unwrap_or(SystemTime::UNIX_EPOCH)+}++fn files(dir: &Path, ext: &str) -> Vec<PathBuf> {+ let mut v: Vec<PathBuf> = std::fs::read_dir(dir).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.is_file() && p.to_string_lossy().ends_with(ext)).collect();+ v.sort_by_key(|p| std::cmp::Reverse(modified(p)));+ v+}++fn name(p: &Path) -> String {+ let full = p.to_string_lossy();+ full.rsplit(['/', '\\']).next().unwrap_or_default().to_string()+}++/// The P0 and P1 issues a check file holds, as its lines.+fn blocking(check: &Path) -> Vec<String> {+ let Ok(j) = std::fs::read_to_string(check).map_err(drop).and_then(|t| serde_json::from_str::<serde_json::Value>(&t).map_err(drop)) else { return vec![] };+ let mut out = Vec::new();+ for i in j["issues"].as_array().into_iter().flatten() {+ if let (Some(p @ ("P0" | "P1")), Some(says)) = (i["p"].as_str(), i["says"].as_str()) {+ out.push(format!("{p} {says}"));+ }+ }+ out+}++/// The steps, most useful first, at most three. `stale` is what `raea doctor` found here.+pub fn steps(dir: &Path, brief: &Brief, stale: usize) -> Vec<String> {+ let mut out = Vec::new();+ if stale > 0 {+ out.push(format!("raea doctor: {stale} thing(s) in this project's files or your raea skill don't match this raea (`raea doctor --fix`)"));+ }+ if let Some(first) = brief.needs.first() {+ out.push(format!("shape the brief: {first} (ask the person, or write your best guess and add it to `assumed`)"));+ }+ let boarded = brief.modes.iter().any(|m| ["pitch", "explain", "story"].contains(&m.as_str()));+ let scripts = files(dir, ".script.ts");+ if boarded && scripts.is_empty() {+ out.push("plan it: write the storyboard as NAME.script.ts beside the brief (`raea spec NAME.script.ts` checks it) and wait for the person's approval".into());+ }+ let comps: Vec<PathBuf> = files(dir, ".tsx").into_iter().filter(|p| std::fs::read_to_string(p).map(|t| t.contains("registerRoot")).unwrap_or(false)).collect();+ let renders = files(&dir.join("out"), ".mp4");+ match (comps.first(), renders.first()) {+ (None, _) => out.push("make the first item: one .tsx whose root registers a Composition (`raea guide craft` first)".into()),+ (Some(c), None) => out.push(format!("render {}: stills to look at first (`raea render {} --at 0,45,89 -o frames/`), then the video into out/", name(c), name(c))),+ (Some(c), Some(r)) if modified(c) > modified(r) => out.push(format!("render again: {} changed after {}", name(c), name(r))),+ (_, Some(r)) => {+ let check = r.with_extension("check.json");+ if !check.is_file() || modified(&check) < modified(r) {+ out.push(format!("check {}: `raea check out/{} -o out/{}` (add --manifest when the render wrote one)", name(r), name(r), name(&check)));+ } else {+ match blocking(&check).first() {+ Some(issue) => out.push(format!("polish {}: {issue} (`raea guide polish`)", name(r))),+ None => out.push(format!("show {}: post it to the project's feed (feed_post), or give the person its path, and read their notes", name(r))),+ }+ }+ }+ }+ out.truncate(3);+ out+}++/// `raea next`'s text.+pub fn text(dir: &Path, brief: &Brief, stale: usize) -> String {+ let s = steps(dir, brief, stale);+ let mut t = format!("raea next: {}\n", dir.display());+ for (i, line) in s.iter().enumerate() {+ t.push_str(&format!("{}. {line}\n", i + 1));+ }+ t.trim_end().to_string()+}diff --git a/apps/workspace/src/storage.rs b/apps/workspace/src/storage.rsnew file mode 100644index 00000000..4b9ac8c1--- /dev/null+++ b/apps/workspace/src/storage.rs@@ -0,0 +1,95 @@+//! A project changing storage with its history (docs/projects.feature PJ4): `raea project split NAME` makes an inline+//! project its own repo, a submodule, from `git subtree split` (its commits, rewritten to the folder); `raea project+//! join NAME` brings a submodule back in as a folder, its history merged under projects/NAME (`git subtree add`).+//! .raea/workspace and .gitmodules change in the same commit.+use super::*;+use workspace::{commit, get, git, include, set};++fn workspace_and(name: &str) -> R<(PathBuf, String, PathBuf)> {+ let here = std::env::current_dir().map_err(|e| e.to_string())?;+ let ws = workspace::up(&here, ".raea/workspace").ok_or("not in a workspace")?;+ let key = workspace::slug(name);+ let rel = get(&ws.join(".raea/workspace"), &format!("project.{key}.path")).ok_or_else(|| format!("no project {name} in this workspace: raea workspace lists them"))?;+ let dir = ws.join(&rel);+ Ok((ws, rel, dir))+}++fn storage_of(ws: &Path, name: &str) -> String {+ get(&ws.join(".raea/workspace"), &format!("project.{}.storage", workspace::slug(name))).unwrap_or_else(|| "inline".into())+}++fn clean(ws: &Path) -> R<()> {+ if !git(ws, &["status", "--porcelain", "--untracked-files=no"])?.is_empty() {+ return Err("the workspace has changes not yet committed: commit or drop them first, so the move is one change".into());+ }+ Ok(())+}++/// `raea project split NAME [--remote URL]`: an inline project made a submodule, its history kept.+pub fn split(name: &str, remote: Option<&str>) -> R<String> {+ let (ws, rel, dir) = workspace_and(name)?;+ if storage_of(&ws, name) == "submodule" {+ return Err(format!("{name} is a submodule already"));+ }+ clean(&ws)?;+ let branch = format!("raea-split-{}", workspace::slug(name));+ let tip = git(&ws, &["subtree", "split", "-q", &format!("--prefix={rel}"), "-b", &branch])?;+ let n = git(&ws, &["rev-list", "--count", &branch])?;+ // the project's folder leaves the workspace's tree, then comes back as its own repo with that history+ git(&ws, &["rm", "-r", "-q", "--", &rel])?;+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;+ git(&dir, &["init", "-q"])?;+ git(&dir, &["fetch", "-q", &ws.to_string_lossy(), &branch])?;+ git(&dir, &["reset", "-q", "--hard", "FETCH_HEAD"])?;+ git(&ws, &["branch", "-q", "-D", &branch])?;+ if Path::new(&dir.join(".gitattributes")).is_file() || ws.join(".gitattributes").is_file() {+ // media stays in LFS: the workspace's attributes come along+ let _ = std::fs::copy(ws.join(".gitattributes"), dir.join(".gitattributes"));+ let _ = git(&dir, &["add", ".gitattributes"]).and_then(|_| git(&dir, &["commit", "-q", "-m", "raea: LFS for media/ and out/", "--", ".gitattributes"]));+ }+ let url = match remote {+ Some(u) => {+ git(&dir, &["remote", "add", "origin", u])?;+ git(&dir, &["push", "-q", "-u", "origin", "HEAD"])?;+ u.to_string()+ }+ None => format!("./{rel}"),+ };+ git(&ws, &["-c", "protocol.file.allow=always", "submodule", "add", "-q", &url, &rel])?;+ set(&ws.join(".raea/workspace"), &format!("project.{}.storage", workspace::slug(name)), "submodule")?;+ include(&dir, &dir.join(".raea/project"))?;+ commit(&ws, &[".raea/workspace", ".gitmodules", &rel], &format!("project {name} split into its own repo ({n} commits kept)"))?;+ Ok(format!("{}: {name} is a submodule now, its own repo with {n} commits (tip {})", dir.display(), &tip[..tip.len().min(9)]))+}++/// `raea project join NAME`: a submodule brought back in as a folder, its history merged under its path.+pub fn join(name: &str) -> R<String> {+ let (ws, rel, dir) = workspace_and(name)?;+ if storage_of(&ws, name) != "submodule" {+ return Err(format!("{name} is a folder in the workspace already"));+ }+ clean(&ws)?;+ if !git(&dir, &["status", "--porcelain"])?.is_empty() {+ return Err(format!("{name} has changes not yet committed: commit them first, so they come along"));+ }+ // the submodule's repo is kept aside while its folder leaves, then its history comes in under the same path+ let aside = std::env::temp_dir().join(format!("raea-join-{}-{}", workspace::slug(name), std::process::id()));+ let _ = std::fs::remove_dir_all(&aside);+ git(&ws, &["clone", "-q", "--no-local", &dir.to_string_lossy(), &aside.to_string_lossy()])?;+ git(&ws, &["submodule", "deinit", "-q", "-f", "--", &rel])?;+ git(&ws, &["rm", "-q", "-f", "--", &rel])?;+ let modules = PathBuf::from(git(&ws, &["rev-parse", "--path-format=absolute", "--git-common-dir"])?).join("modules").join(&rel);+ let _ = std::fs::remove_dir_all(&modules);+ let _ = std::fs::remove_dir_all(&dir);+ set(&ws.join(".raea/workspace"), &format!("project.{}.storage", workspace::slug(name)), "inline")?;+ let gitmodules = ws.join(".gitmodules");+ let mut paths = vec![".raea/workspace"];+ if gitmodules.is_file() {+ paths.push(".gitmodules");+ }+ commit(&ws, &paths, &format!("project {name} leaves its submodule"))?;+ git(&ws, &["subtree", "add", "-q", &format!("--prefix={rel}"), &aside.to_string_lossy(), "HEAD", "-m", &format!("raea: project {name} joined, its history under {rel}")])?;+ let _ = std::fs::remove_dir_all(&aside);+ Ok(format!("{}: {name} is a folder in the workspace now, its history merged", dir.display()))+}diff --git a/apps/workspace/src/tests.rs b/apps/workspace/src/tests.rsnew file mode 100644index 00000000..6dbc449f--- /dev/null+++ b/apps/workspace/src/tests.rs@@ -0,0 +1,73 @@+use super::*;++#[test]+fn a_name_is_its_folder() {+ assert_eq!(slug("Shane's Studio"), "shane-s-studio");+ assert_eq!(slug(" CJ / Reel 2 "), "cj-reel-2");+}++#[test]+fn a_spec_module_is_tidy_typescript() {+ // keys unquoted where they can be, nulls and empty lists left out, whole numbers whole, short string lists inline+ let v = json!({"id": "delivery", "help": null, "tags": [], "n": 45.0, "options": ["9:16", "16:9"], "odd-key": 1});+ assert_eq!(ts_literal(&v, 0), "{\n id: \"delivery\",\n n: 45,\n \"odd-key\": 1,\n options: [\"9:16\", \"16:9\"],\n}");+}++#[test]+fn up_finds_the_nearest_marker() {+ let root = std::env::temp_dir().canonicalize().unwrap().join(format!("raea-ws-up-{}", std::process::id()));+ let deep = root.join("projects/launch/media");+ std::fs::create_dir_all(&deep).unwrap();+ std::fs::create_dir_all(root.join(".raea")).unwrap();+ std::fs::write(root.join(".raea/workspace"), "").unwrap();+ assert_eq!(up(&deep, ".raea/workspace").as_deref(), Some(root.as_path()));+ assert_eq!(up(&deep, ".raea/project"), None);+ let _ = std::fs::remove_dir_all(&root);+}++fn scratch(name: &str) -> PathBuf {+ let d = std::env::temp_dir().join(format!("raea-ws-{name}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&d);+ std::fs::create_dir_all(&d).unwrap();+ d+}++#[test]+fn next_walks_a_project_from_brief_to_show() {+ let d = scratch("next");+ let shaped = next::Brief { needs: vec![], modes: vec!["tool".into()] };+ let unshaped = next::Brief { needs: vec!["who it's for (audience)".into()], modes: vec!["pitch".into()] };+ let s = next::steps(&d, &unshaped, 0);+ assert!(s[0].starts_with("shape the brief: who it's for") && s[1].starts_with("plan it") && s[2].starts_with("make the first item"), "{s:?}");+ assert!(next::steps(&d, &shaped, 2)[0].starts_with("raea doctor: 2"));+ std::fs::write(d.join("piece.tsx"), "registerRoot(() => null)").unwrap();+ assert!(next::steps(&d, &shaped, 0)[0].starts_with("render piece.tsx"));+ std::fs::create_dir_all(d.join("out")).unwrap();+ std::thread::sleep(std::time::Duration::from_millis(20));+ std::fs::write(d.join("out/piece.mp4"), "").unwrap();+ assert!(next::steps(&d, &shaped, 0)[0].starts_with("check piece.mp4"));+ std::thread::sleep(std::time::Duration::from_millis(20));+ std::fs::write(d.join("out/piece.check.json"), r#"{"issues":[{"p":"P1","says":"text clipped at 2 s"}]}"#).unwrap();+ assert_eq!(next::steps(&d, &shaped, 0)[0], "polish piece.mp4: P1 text clipped at 2 s (`raea guide polish`)");+ std::fs::write(d.join("out/piece.check.json"), r#"{"issues":[{"p":"P3","says":"minor"}]}"#).unwrap();+ assert!(next::steps(&d, &shaped, 0)[0].starts_with("show piece.mp4"));+ let _ = std::fs::remove_dir_all(&d);+}++#[test]+fn doctor_finds_old_briefs_and_old_skills() {+ let d = scratch("doctor");+ std::fs::write(d.join("acme.brief"), "title: x").unwrap();+ std::fs::create_dir_all(d.join("skills/raea")).unwrap();+ std::fs::write(d.join("skills/raea/SKILL.md"), "---\nname: raea\nversion: 0.0.1\n---\n").unwrap();+ let skills = [("claude", d.join("skills"))];+ let found = doctor::findings(&d, &skills, "0.0.2");+ assert_eq!(found.len(), 2, "{:?}", found.iter().map(|f| &f.says).collect::<Vec<_>>());+ assert!(found[0].says.contains("acme.brief") && !found[0].fixable());+ assert!(found[1].says.contains("is 0.0.1, this raea is 0.0.2") && found[1].fixable());+ assert!(doctor::findings(&d, &skills, "0.0.1").len() == 1);+ let reinstalled = std::cell::Cell::new(false);+ let out = doctor::doctor(&["--fix".into(), d.display().to_string()], &skills, "0.0.2", &|a| { reinstalled.set(a == "claude"); Ok(String::new()) }).unwrap();+ assert!(reinstalled.get() && out.starts_with("APPLIED 1 of 2 fixed"), "{out}");+ let _ = std::fs::remove_dir_all(&d);+}diff --git a/apps/workspace/src/workspace.rs b/apps/workspace/src/workspace.rsnew file mode 100644index 00000000..377d9e2f--- /dev/null+++ b/apps/workspace/src/workspace.rs@@ -0,0 +1,359 @@+//! Workspaces and projects on disk (docs/projects.feature PJ1). A workspace is a git repo holding .raea/workspace, a+//! git-config file that is committed, and projects/<name>/, each holding .raea/project. raea writes an include into+//! the repo's own .git/config, so `git config workspace.layout` answers from the committed file; git never loads a+//! committed config by itself. Every change raea makes here is a commit.+use super::*;+use std::process::Command;++const USAGE: &str = "usage: raea workspace [--json] | raea workspace init [NAME] [--layout monorepo|submodules] | raea workspace adopt DIR [--name NAME] [--layout monorepo|submodules]\n raea project [--json] | raea project new NAME [--storage inline|submodule] | raea project split NAME [--remote URL] | raea project join NAME";++pub(crate) fn git(dir: &Path, args: &[&str]) -> R<String> {+ let out = Command::new("git").arg("-C").arg(dir).args(args).output().map_err(|e| format!("git: {e}"))?;+ if !out.status.success() {+ return Err(format!("git {}: {}", args.join(" "), String::from_utf8_lossy(&out.stderr).trim()));+ }+ Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())+}++/// `git config` on a file (or the global config when `file` is None), its output trimmed; Err when git says no.+pub(crate) fn config(file: Option<&Path>, args: &[&str]) -> R<String> {+ let mut c = Command::new("git");+ c.arg("config");+ if let Some(f) = file {+ c.arg("-f").arg(f);+ }+ let out = c.args(args).output().map_err(|e| format!("git: {e}"))?;+ if !out.status.success() {+ return Err(format!("git config {}: {}", args.join(" "), String::from_utf8_lossy(&out.stderr).trim()));+ }+ Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())+}++/// A git-config file's value, None when unset.+pub(crate) fn get(file: &Path, key: &str) -> Option<String> {+ config(Some(file), &[key]).ok().filter(|v| !v.is_empty())+}++pub(crate) fn set(file: &Path, key: &str, value: &str) -> R<()> {+ let dir = file.parent().unwrap_or(Path::new("."));+ std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;+ config(Some(file), &[key, value]).map(drop)+}++/// Every key of a git-config file, in order, as (key, value).+fn all(file: &Path) -> Vec<(String, String)> {+ let list = config(Some(file), &["--list", "-z"]).unwrap_or_default();+ list.split('\0').filter_map(|e| e.split_once('\n')).map(|(k, v)| (k.to_string(), v.to_string())).collect()+}++/// The value after `name` in args.+pub(crate) 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)+}++/// 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()+}++/// A name as a folder: lowercase, dashes.+pub fn slug(s: &str) -> String {+ let mut out = String::new();+ for c in s.trim().to_lowercase().chars() {+ if c.is_ascii_alphanumeric() {+ out.push(c);+ } else if !out.is_empty() && !out.ends_with('-') {+ out.push('-');+ }+ }+ out.trim_end_matches('-').to_string()+}++/// A new id: the prefix and eight hex digits from the clock and the process.+pub(crate) fn new_id(prefix: &str) -> String {+ let t = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0);+ format!("{prefix}_{:08x}", (t as u64 ^ (std::process::id() as u64) << 20) as u32)+}++/// Where workspaces live on this machine: `git config --global raea.root`, else ~/Studio.+pub fn root() -> PathBuf {+ let set = config(None, &["--global", "raea.root"]).ok().filter(|s| !s.is_empty());+ let home = std::env::var_os("HOME").map(PathBuf::from).unwrap_or_default();+ match set {+ Some(s) if s.starts_with("~/") => home.join(&s[2..]),+ Some(s) => PathBuf::from(s),+ None => home.join("Studio"),+ }+}++/// The nearest folder at or above `from` that holds `marker` (.raea/workspace, .raea/project).+pub fn up(from: &Path, marker: &str) -> Option<PathBuf> {+ let from = from.canonicalize().ok()?;+ from.ancestors().find(|d| d.join(marker).is_file()).map(Path::to_path_buf)+}++/// The include in a repo's own config that makes `git config` read a committed file. Idempotent; the path is relative+/// to the config file, which for a submodule lives under the workspace's .git/modules.+pub(crate) fn include(repo: &Path, file: &Path) -> R<()> {+ let cfg = PathBuf::from(git(repo, &["rev-parse", "--path-format=absolute", "--git-path", "config"])?);+ let file = file.canonicalize().map_err(|e| format!("{}: {e}", file.display()))?;+ let rel = relative(cfg.parent().unwrap_or(Path::new("/")), &file);+ let have = config(Some(&cfg), &["--get-all", "include.path"]).unwrap_or_default();+ if have.lines().any(|l| l.trim() == rel) {+ return Ok(());+ }+ config(Some(&cfg), &["--add", "include.path", &rel]).map(drop)+}++fn relative(from: &Path, to: &Path) -> String {+ let (a, b): (Vec<_>, Vec<_>) = (from.components().collect(), to.components().collect());+ let same = a.iter().zip(&b).take_while(|(x, y)| x == y).count();+ let mut out: Vec<String> = std::iter::repeat_n("..".to_string(), a.len() - same).collect();+ out.extend(b[same..].iter().map(|c| c.as_os_str().to_string_lossy().into_owned()));+ out.join("/")+}++fn write_new(path: &Path, text: &str) -> R<()> {+ if path.exists() {+ return Ok(());+ }+ if let Some(d) = path.parent() {+ std::fs::create_dir_all(d).map_err(|e| format!("{}: {e}", d.display()))?;+ }+ std::fs::write(path, text).map_err(|e| format!("{}: {e}", path.display()))+}++/// A commit of these paths, when they changed: "raea: what".+pub(crate) fn commit(repo: &Path, paths: &[&str], what: &str) -> R<()> {+ let mut add = vec!["add", "--"];+ add.extend(paths);+ git(repo, &add)?;+ if git(repo, &["diff", "--cached", "--quiet"]).is_ok() {+ return Ok(());+ }+ git(repo, &["commit", "-q", "-m", &format!("raea: {what}"), "--"]).map(|_| ())+}++const AGENTS_PROJECT: &str = "# Agents\n\nRun `raea context .` here before any work: the taste, this project's brief.ts and script.ts, its look and the guides\nits modes need, in the order to read them. Specs are TypeScript (`export default brief({...})` from \"raea/brief\").\n";++/// `raea workspace …`+pub fn workspace(args: &[String]) -> R<String> {+ let w = words(args);+ match w.first().copied() {+ None => show_workspace(args.iter().any(|a| a == "--json")),+ Some("init") => init(w.get(1).copied(), flag(args, "--layout")),+ Some("adopt") => adopt(Path::new(w.get(1).ok_or(USAGE)?), flag(args, "--name"), flag(args, "--layout")),+ Some(v) => Err(format!("raea workspace has no {v:?}\n{USAGE}")),+ }+}++fn layout_of(l: Option<&str>) -> R<&str> {+ match l.unwrap_or("monorepo") {+ l @ ("monorepo" | "submodules") => Ok(l),+ l => Err(format!("a layout is monorepo or submodules, not {l:?}")),+ }+}++/// `init` in a workspace makes it work after a clone (the includes again, for it and its submodule projects); `init+/// NAME` elsewhere makes a new workspace under raea.root.+fn init(name: Option<&str>, layout: Option<&str>) -> R<String> {+ let here = std::env::current_dir().map_err(|e| e.to_string())?;+ if let Some(ws) = up(&here, ".raea/workspace").filter(|_| name.is_none()) {+ include(&ws, &ws.join(".raea/workspace"))?;+ let mut fixed = 0;+ for (_, path, storage) in projects(&ws) {+ let dir = ws.join(&path);+ if storage == "submodule" && dir.join(".git").exists() && dir.join(".raea/project").is_file() {+ include(&dir, &dir.join(".raea/project"))?;+ fixed += 1;+ }+ }+ return Ok(format!("{}: git config reads .raea/workspace{}", ws.display(), match fixed { 0 => String::new(), 1 => " and a submodule project's .raea/project".into(), n => format!(" and {n} submodule projects' .raea/project") }));+ }+ let name = name.ok_or(USAGE)?;+ let dir = root().join(slug(name));+ if dir.join(".raea/workspace").is_file() {+ return Err(format!("{} is a workspace already: `cd` there and `raea workspace init` re-adds its includes", dir.display()));+ }+ make_workspace(&dir, name, layout_of(layout)?)?;+ Ok(format!("{}: workspace {name:?} ({}); next: cd there, raea project new NAME", dir.display(), layout_of(layout)?))+}++/// An existing folder made a workspace in place: git when it isn't a repo, .raea/workspace, and each folder in it+/// holding a brief.ts registered as an inline project. Nothing is moved or deleted.+fn adopt(dir: &Path, name: Option<&str>, layout: Option<&str>) -> R<String> {+ let dir = dir.canonicalize().map_err(|e| format!("{}: {e}", dir.display()))?;+ let name = name.map(String::from).unwrap_or_else(|| dir.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default());+ make_workspace(&dir, &name, layout_of(layout)?)?;+ let mut found = vec![];+ for base in [dir.clone(), dir.join("projects")] {+ for e in std::fs::read_dir(&base).into_iter().flatten().flatten() {+ let p = e.path();+ if p.join("brief.ts").is_file() && !p.join(".raea/project").is_file() {+ let rel = relative(&dir, &p);+ register(&dir, &p, &rel, "inline")?;+ found.push(rel);+ }+ }+ }+ let mut paths = vec![".raea/workspace"];+ let projs: Vec<String> = found.iter().map(|r| format!("{r}/.raea/project")).collect();+ paths.extend(projs.iter().map(String::as_str));+ commit(&dir, &paths, &format!("adopt {name} as a workspace ({})", count(found.len())))?;+ Ok(format!("{}: workspace {name:?}, {}{}", dir.display(), count(found.len()), if found.is_empty() { String::new() } else { format!(": {}", found.join(", ")) }))+}++fn count(n: usize) -> String {+ if n == 1 { "1 project".into() } else { format!("{n} projects") }+}++fn make_workspace(dir: &Path, name: &str, layout: &str) -> R<()> {+ // never a workspace in another repo's own folder (on a case-insensitive disk ~/Raea is ~/raea, raea's checkout); a+ // repo further up, as a home folder kept in git, is fine: the workspace is a repo of its own inside it+ let parent = dir.parent().unwrap_or(Path::new("/"));+ if !dir.join(".git").exists() && parent.exists() {+ let top = git(parent, &["rev-parse", "--show-toplevel"]).ok().map(PathBuf::from);+ if top.is_some_and(|t| t.canonicalize().ok() == parent.canonicalize().ok()) {+ return Err(format!("{} would be a folder of the git repo {}: set where workspaces go, `git config --global raea.root ~/Studio`", dir.display(), parent.display()));+ }+ }+ std::fs::create_dir_all(dir.join("projects")).map_err(|e| format!("{}: {e}", dir.display()))?;+ if !dir.join(".git").exists() {+ git(dir, &["init", "-q"])?;+ }+ let file = dir.join(".raea/workspace");+ if get(&file, "workspace.id").is_none() {+ set(&file, "workspace.id", &new_id("ws"))?;+ }+ set(&file, "workspace.name", name)?;+ set(&file, "workspace.layout", layout)?;+ include(dir, &file)?;+ write_new(&dir.join("controllers/.gitkeep"), "")?;+ write_new(&dir.join("projects/.gitkeep"), "")?;+ write_new(&dir.join("taste.ts"), &format!("import {{ taste }} from \"raea/brief\";\n\n// {name}'s house rules: every project here follows them, after the person's own taste.\nexport default taste({{\n title: {:?},\n sections: [],\n}});\n", format!("{name}: house rules")))?;+ write_new(&dir.join(".gitattributes"), "media/** filter=lfs diff=lfs merge=lfs -text\nout/** filter=lfs diff=lfs merge=lfs -text\n")?;+ commit(dir, &[".raea/workspace", "controllers/.gitkeep", "projects/.gitkeep", "taste.ts", ".gitattributes"], &format!("workspace {name}"))+}++/// The workspace's projects: (name, path, storage), from .raea/workspace.+pub fn projects(ws: &Path) -> Vec<(String, String, String)> {+ let mut out: Vec<(String, String, String)> = vec![];+ for (k, v) in all(&ws.join(".raea/workspace")) {+ let Some(rest) = k.strip_prefix("project.") else { continue };+ let Some((name, key)) = rest.rsplit_once('.') else { continue };+ let at = out.iter().position(|p| p.0 == name).unwrap_or_else(|| {+ out.push((name.to_string(), format!("projects/{name}"), "inline".into()));+ out.len() - 1+ });+ match key {+ "path" => out[at].1 = v,+ "storage" => out[at].2 = v,+ _ => {}+ }+ }+ out+}++/// A project's own .raea/project, and its line in the workspace's.+fn register(ws: &Path, dir: &Path, rel: &str, storage: &str) -> R<String> {+ let name = dir.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();+ let file = dir.join(".raea/project");+ let id = get(&file, "project.id").unwrap_or_else(|| new_id("pj"));+ set(&file, "project.id", &id)?;+ set(&file, "project.name", &name)?;+ let wsf = ws.join(".raea/workspace");+ set(&wsf, &format!("project.{name}.path"), rel)?;+ set(&wsf, &format!("project.{name}.id"), &id)?;+ set(&wsf, &format!("project.{name}.storage"), storage)?;+ Ok(id)+}++fn show_workspace(json_out: bool) -> R<String> {+ let here = std::env::current_dir().map_err(|e| e.to_string())?;+ let ws = up(&here, ".raea/workspace").ok_or("not in a workspace: raea workspace init NAME makes one (under `git config --global raea.root`, else ~/Studio)")?;+ let file = ws.join(".raea/workspace");+ let ps = projects(&ws);+ if json_out {+ let projects: Vec<_> = ps.iter().map(|(n, p, s)| json!({"name": n, "path": p, "storage": s, "id": get(&file, &format!("project.{n}.id"))})).collect();+ return Ok(json!({"path": ws, "id": get(&file, "workspace.id"), "name": get(&file, "workspace.name"), "layout": get(&file, "workspace.layout"), "projects": projects}).to_string());+ }+ let mut out = format!("{} ({}, {})\n{}\n", get(&file, "workspace.name").unwrap_or_default(), get(&file, "workspace.id").unwrap_or_default(), get(&file, "workspace.layout").unwrap_or_default(), ws.display());+ for (n, p, s) in &ps {+ out.push_str(&format!(" {n} {p} {s}\n"));+ }+ Ok(out.trim_end().to_string())+}++/// `raea project …`+pub fn project(args: &[String]) -> R<String> {+ let w = words(args);+ match w.first().copied() {+ None => show_project(args.iter().any(|a| a == "--json")),+ Some("new") => new_project(w.get(1).ok_or(USAGE)?, flag(args, "--storage")),+ Some("split") => storage::split(w.get(1).ok_or(USAGE)?, flag(args, "--remote")),+ Some("join") => storage::join(w.get(1).ok_or(USAGE)?),+ Some(v) => Err(format!("raea project has no {v:?}\n{USAGE}")),+ }+}++fn new_project(name: &str, storage: Option<&str>) -> R<String> {+ let here = std::env::current_dir().map_err(|e| e.to_string())?;+ let ws = up(&here, ".raea/workspace").ok_or("not in a workspace: raea workspace init NAME makes one")?;+ let slugged = slug(name);+ if slugged.is_empty() {+ return Err(format!("{name:?} has no letters or digits to name a folder by"));+ }+ let rel = format!("projects/{slugged}");+ let dir = ws.join(&rel);+ if dir.join(".raea/project").is_file() {+ return Err(format!("{} is a project already", dir.display()));+ }+ let layout = get(&ws.join(".raea/workspace"), "workspace.layout").unwrap_or_else(|| "monorepo".into());+ let storage = match storage.unwrap_or(if layout == "submodules" { "submodule" } else { "inline" }) {+ s @ ("inline" | "submodule") => s,+ s => return Err(format!("a project's storage is inline or submodule, not {s:?}")),+ };+ std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;+ write_new(&dir.join("brief.ts"), &format!("import {{ brief }} from \"raea/brief\";\n\nexport default brief({{\n title: {name:?},\n}});\n"))?;+ write_new(&dir.join("AGENTS.md"), AGENTS_PROJECT)?;+ for d in ["media", "brand", "out"] {+ write_new(&dir.join(d).join(".gitkeep"), "")?;+ }+ let id = register(&ws, &dir, &rel, storage)?;+ let files = [".raea/project", "brief.ts", "AGENTS.md", "media/.gitkeep", "brand/.gitkeep", "out/.gitkeep"];+ if storage == "submodule" {+ git(&dir, &["init", "-q"])?;+ commit(&dir, &files, &format!("project {name}"))?;+ // the project's own repo, added where it stands; its url is the folder until it has a remote of its own+ git(&ws, &["-c", "protocol.file.allow=always", "submodule", "add", "-q", &format!("./{rel}"), &rel])?;+ include(&dir, &dir.join(".raea/project"))?;+ commit(&ws, &[".raea/workspace", ".gitmodules", &rel], &format!("project {name} (submodule)"))?;+ } else {+ let paths: Vec<String> = files.iter().map(|f| format!("{rel}/{f}")).collect();+ let mut all_paths: Vec<&str> = vec![".raea/workspace"];+ all_paths.extend(paths.iter().map(String::as_str));+ commit(&ws, &all_paths, &format!("project {name}"))?;+ }+ Ok(format!("{}: project {name:?} ({id}, {storage}); next: shape brief.ts, then raea context .", dir.display()))+}++fn show_project(json_out: bool) -> R<String> {+ let here = std::env::current_dir().map_err(|e| e.to_string())?;+ let dir = up(&here, ".raea/project").ok_or("not in a project: raea project new NAME (in a workspace) makes one")?;+ let file = dir.join(".raea/project");+ let ws = up(&dir, ".raea/workspace").filter(|w| *w != dir);+ let overrides: Vec<(String, String)> = all(&file).into_iter().filter(|(k, _)| k.starts_with("controller.")).collect();+ if json_out {+ let o: serde_json::Map<String, serde_json::Value> = overrides.iter().map(|(k, v)| (k.trim_start_matches("controller.").to_string(), json!(v))).collect();+ return Ok(json!({"path": dir, "id": get(&file, "project.id"), "name": get(&file, "project.name"), "workspace": ws, "controllers": o}).to_string());+ }+ let mut out = format!("{} ({})\n{}\n", get(&file, "project.name").unwrap_or_default(), get(&file, "project.id").unwrap_or_default(), dir.display());+ if let Some(ws) = &ws {+ out.push_str(&format!("in workspace {}\n", ws.display()));+ }+ for (k, v) in overrides {+ out.push_str(&format!(" {} = {v}\n", k.trim_start_matches("controller.")));+ }+ Ok(out.trim_end().to_string())+}diff --git a/core/brief/src/controller.rs b/core/brief/src/controller.rsnew file mode 100644index 00000000..0807670d--- /dev/null+++ b/core/brief/src/controller.rs@@ -0,0 +1,201 @@+//! A workspace's controllers: settings its Director puts together with the person, out of a small set of parts. A+//! controller has groups, a group has typed fields, and every agent in the workspace works to the values (`describe`).+//! The agent writes one as `controllers/<id>.ts` (`export default controller({...})`, docs/projects.feature PJ2);+//! `normalize` checks it and fills in ids, with errors in a sentence the agent can act on. The same contract as+//! apps/app src/controllers/types.ts, whose page reads these types.++use serde::{Deserialize, Serialize};+use serde_json::{Map, Value};+use ts_rs::TS;++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]+#[ts(optional_fields)]+pub struct Controller {+ pub id: String,+ pub title: String,+ #[serde(skip_serializing_if = "Option::is_none")] pub help: Option<String>,+ pub groups: Vec<Group>,+}++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]+#[ts(optional_fields)]+pub struct Group {+ pub id: String,+ pub title: String,+ #[serde(skip_serializing_if = "Option::is_none")] pub help: Option<String>,+ pub fields: Vec<Field>,+}++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]+#[ts(optional_fields)]+pub struct Field {+ pub id: String,+ pub label: String,+ #[serde(skip_serializing_if = "Option::is_none")] pub help: Option<String>,+ #[serde(flatten)]+ #[ts(flatten)]+ pub kind: Kind,+}++/// One step of a workflow field: who does it (an agent's name, or "you" for the person) and where a failure goes back to.+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]+#[ts(optional_fields)]+pub struct Step {+ pub name: String,+ #[serde(skip_serializing_if = "Option::is_none")] pub by: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")] pub back: Option<String>,+}++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]+#[serde(tag = "type", rename_all = "lowercase")]+#[ts(optional_fields)]+pub enum Kind {+ Toggle { value: bool },+ Choice { options: Vec<String>, value: String },+ Number { value: f64, #[serde(skip_serializing_if = "Option::is_none")] unit: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] min: Option<f64>, #[serde(skip_serializing_if = "Option::is_none")] max: Option<f64>, #[serde(skip_serializing_if = "Option::is_none")] step: Option<f64> },+ Text { value: String, #[serde(skip_serializing_if = "Option::is_none")] placeholder: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] multiline: Option<bool> },+ List { value: Vec<String>, #[serde(skip_serializing_if = "Option::is_none")] placeholder: Option<String> },+ Agents { value: Vec<String> },+ Channels { value: Vec<String> },+ /// steps in order; `channels` run it (all of them when unset)+ Workflow { value: Vec<Step>, #[serde(skip_serializing_if = "Option::is_none")] channels: Option<Vec<String>> },+ /// MCP servers: URLs, commands or GitHub repos, given to every agent's session+ Servers { value: Vec<String> },+ /// skills: links to SKILL.md, read into every agent's context+ Skills { value: Vec<String> },+}++const TYPES: &str = "toggle, choice, number, text, list, agents, channels, workflow, servers, skills";++fn slug(s: &str) -> String {+ let mut out = String::new();+ for c in s.to_lowercase().chars() {+ if c.is_ascii_alphanumeric() {+ out.push(c);+ } else if !out.ends_with('-') {+ out.push('-');+ }+ }+ let out: String = out.trim_matches('-').chars().take(48).collect();+ if out.is_empty() { "x".into() } else { out.trim_end_matches('-').into() }+}++fn is_id(s: &str) -> bool {+ let b = s.as_bytes();+ !b.is_empty() && b.len() <= 48 && b[0].is_ascii_lowercase() && b.iter().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || *c == b'-')+}++fn text(o: &Map<String, Value>, k: &str) -> Option<String> {+ o.get(k).and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).map(String::from)+}++fn id_of(o: &Map<String, Value>, fallback: &str) -> String {+ o.get("id").and_then(Value::as_str).filter(|s| is_id(s)).map(String::from).unwrap_or_else(|| slug(fallback))+}++fn strings(v: Option<&Value>, what: &str) -> Result<Vec<String>, String> {+ match v {+ None | Some(Value::Null) => Ok(vec![]),+ Some(Value::Array(a)) if a.iter().all(Value::is_string) => {+ Ok(a.iter().filter_map(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).map(String::from).collect())+ }+ _ => Err(format!("{what} must be a list of strings")),+ }+}++fn number(o: &Map<String, Value>, k: &str) -> Option<f64> {+ o.get(k).and_then(Value::as_f64).filter(|n| n.is_finite())+}++fn steps(v: Option<&Value>, at: &str) -> Result<Vec<Step>, String> {+ let Some(Value::Array(a)) = v else { return Err(format!("{at}: a workflow's value is a list of steps: {{ name, by?, back? }}")) };+ a.iter()+ .enumerate()+ .map(|(i, s)| {+ let o = s.as_object().ok_or_else(|| format!("{at}: step {} needs a name", i + 1))?;+ let name = text(o, "name").ok_or_else(|| format!("{at}: step {} needs a name", i + 1))?;+ Ok(Step { name, by: text(o, "by").map(|b| b.trim_start_matches('@').to_string()), back: text(o, "back") })+ })+ .collect()+}++/// A field as the agent wrote it, checked and filled in; an error names the field and what it needs.+pub fn normalize_field(raw: &Value, at: &str) -> Result<Field, String> {+ let o = raw.as_object().ok_or_else(|| format!("{at}: a field is an object"))?;+ let label = text(o, "label").ok_or_else(|| format!("{at}: a field needs a label"))?;+ let id = id_of(o, &label);+ let w = format!("{at}.{id}");+ let value = o.get("value");+ let kind = match o.get("type").and_then(Value::as_str) {+ Some("toggle") => Kind::Toggle { value: value == Some(&Value::Bool(true)) },+ Some("choice") => {+ let options = strings(o.get("options"), &format!("{w}: options"))?;+ if options.len() < 2 {+ return Err(format!("{w}: a choice needs at least two options"));+ }+ let value = value.and_then(Value::as_str).filter(|v| options.iter().any(|x| x == v)).map(String::from).unwrap_or_else(|| options[0].clone());+ Kind::Choice { options, value }+ }+ Some("number") => Kind::Number { value: number(o, "value").unwrap_or(0.0), unit: o.get("unit").and_then(Value::as_str).map(String::from), min: number(o, "min"), max: number(o, "max"), step: number(o, "step") },+ Some("text") => Kind::Text { value: value.and_then(Value::as_str).unwrap_or("").into(), placeholder: o.get("placeholder").and_then(Value::as_str).map(String::from), multiline: Some(o.get("multiline") == Some(&Value::Bool(true))) },+ Some("list") => Kind::List { value: strings(value, &format!("{w}: value"))?, placeholder: o.get("placeholder").and_then(Value::as_str).map(String::from) },+ Some("agents") => Kind::Agents { value: strings(value, &format!("{w}: value"))? },+ Some("channels") => Kind::Channels { value: strings(value, &format!("{w}: value"))? },+ Some("servers") => Kind::Servers { value: strings(value, &format!("{w}: value"))? },+ Some("skills") => Kind::Skills { value: strings(value, &format!("{w}: value"))? },+ Some("workflow") => Kind::Workflow { value: steps(value, &w)?, channels: o.get("channels").map(|c| strings(Some(c), &format!("{w}: channels"))).transpose()? },+ _ => return Err(format!("{w}: type must be one of {TYPES}")),+ };+ Ok(Field { id, label, help: text(o, "help"), kind })+}++/// A controller as the agent wrote it (a module's default export, as JSON), checked: ids filled in from titles, each+/// field's value of its type.+pub fn normalize(raw: &Value) -> Result<Controller, String> {+ let o = raw.as_object().filter(|o| text(o, "title").is_some()).ok_or("a controller needs a title")?;+ let title = text(o, "title").unwrap_or_default();+ let id = id_of(o, &title);+ let gs = o.get("groups").and_then(Value::as_array).filter(|g| !g.is_empty()).ok_or_else(|| format!("{id}: a controller needs groups: [{{ title, fields: [...] }}]"))?;+ let mut groups = vec![];+ for (i, g) in gs.iter().enumerate() {+ let g = g.as_object().filter(|g| text(g, "title").is_some()).ok_or_else(|| format!("{id}: group {} needs a title", i + 1))?;+ let gtitle = text(g, "title").unwrap_or_default();+ let gid = id_of(g, >itle);+ let at = format!("{id}.{gid}");+ let fs = g.get("fields").and_then(Value::as_array).ok_or_else(|| format!("{at}: a group needs fields"))?;+ let fields = fs.iter().map(|f| normalize_field(f, &at)).collect::<Result<Vec<_>, _>>()?;+ if let Some(d) = fields.iter().enumerate().find(|(j, f)| fields.iter().position(|x| x.id == f.id) != Some(*j)) {+ return Err(format!("{at}: two fields are called {}", d.1.id));+ }+ groups.push(Group { id: gid, title: gtitle, help: text(g, "help"), fields });+ }+ Ok(Controller { id, title, help: text(o, "help"), groups })+}++/// 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> {+ let w = &f.label;+ match &f.kind {+ Kind::Toggle { .. } => v.as_bool().map(Value::Bool).ok_or_else(|| format!("{w} is on or off: true or false")),+ Kind::Choice { options, .. } => v.as_str().filter(|s| options.iter().any(|o| o == s)).map(|s| Value::String(s.into())).ok_or_else(|| format!("{w} is one of: {}", options.join(", "))),+ Kind::Number { min, max, .. } => {+ let n = v.as_f64().filter(|n| n.is_finite()).ok_or_else(|| format!("{w} is a number"))?;+ if min.is_some_and(|m| n < m) || max.is_some_and(|m| n > m) {+ let (lo, hi) = (min.map_or("-∞".into(), |m| m.to_string()), max.map_or("∞".into(), |m| m.to_string()));+ return Err(format!("{w} is between {lo} and {hi}"));+ }+ Ok(v.clone())+ }+ Kind::Text { .. } => v.as_str().map(|s| Value::String(s.into())).ok_or_else(|| format!("{w} is text")),+ Kind::Workflow { .. } => Ok(serde_json::to_value(steps(Some(v), w)?).unwrap_or_default()),+ _ => Ok(serde_json::to_value(strings(Some(v), w)?).unwrap_or_default()),+ }+}++/// The field at a path (controller.group.field) among the controllers.+pub fn field<'a>(cs: &'a [Controller], path: &str) -> Option<&'a Field> {+ let mut p = path.splitn(3, '.');+ let (c, g, f) = (p.next()?, p.next()?, p.next()?);+ cs.iter().find(|x| x.id == c)?.groups.iter().find(|x| x.id == g)?.fields.iter().find(|x| x.id == f)+}diff --git a/core/brief/src/lib.rs b/core/brief/src/lib.rsindex a0b035a5..b0a1c96b 100644--- a/core/brief/src/lib.rs+++ b/core/brief/src/lib.rs@@ -4,11 +4,13 @@//! types (`declarations`), so what tsc checks is exactly what this crate reads.pub mod brief;+pub mod controller;pub mod plan;pub mod script;pub mod taste;pub use brief::Brief;+pub use controller::Controller;pub use plan::Plan;pub use script::Script;pub use taste::Taste;@@ -26,7 +28,8 @@ macro_rules! decls {($cfg:ident; $($t:ty),* $(,)?) => { vec![$(format!("export {}", <$t as TS>::decl(&$cfg))),*] };}-/// The TypeScript declarations of every schema, one file's worth (core/brief/brief.d.ts is this, checked by a test).+/// The TypeScript declarations of every schema, one file's worth: sdk/raea/src/brief.gen.ts is this, checked by a test, and+/// `raea/brief` (sdk/raea/src/brief.ts) types its builders with it, so the declarations ship with the SDK.pub fn declarations() -> String {let cfg = Config::new();let mut out = vec!["// Generated from raea-core-brief (core/brief) by its `declarations`; edit the Rust, not this.".to_string()];@@ -35,6 +38,7 @@ pub fn declarations() -> String {script::Script, script::Scene, script::Beat, script::Line,taste::Taste, taste::TasteSection, taste::Rule, taste::Check,plan::Plan, plan::Concept, plan::Level, plan::Count, plan::Part,+ controller::Controller, controller::Group, controller::Field, controller::Kind, controller::Step,));out.join("\n\n") + "\n"}diff --git a/core/brief/src/tests.rs b/core/brief/src/tests.rsindex 4c4ea73d..775bbb5e 100644--- a/core/brief/src/tests.rs+++ b/core/brief/src/tests.rs@@ -2,13 +2,13 @@ use super::*;#[test]fn declarations_match_the_committed_file() {- let path = concat!(env!("CARGO_MANIFEST_DIR"), "/brief.d.ts");+ let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../sdk/raea/src/brief.gen.ts");let now = declarations();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, "core/brief/brief.d.ts is out of date: RAEA_WRITE=1 cargo test -p raea-core-brief");+ assert!(committed == now, "sdk/raea/src/brief.gen.ts is out of date: RAEA_WRITE=1 cargo test -p raea-core-brief");}#[test]@@ -75,3 +75,45 @@ fn a_close_view_needs_tertiary_detail() {"parts": {"body": {"role": "body", "level": "primary"}, "rocker": {"role": "rocker", "level": "secondary", "parent": "body", "count": 2}}}"#).unwrap();assert!(plan::check(&p).iter().any(|m| m.contains("tertiary")));}++const DELIVERY: &str = r#"{"title": "Delivery", "help": "What every final keeps", "groups": [{"title": "Format", "fields": [+ {"label": "Aspect ratio", "type": "choice", "options": ["9:16", "4:5", "1:1"], "value": "9:16"},+ {"label": "Loudness", "type": "number", "value": -14, "unit": "LUFS", "min": -30, "max": 0},+ {"label": "Burn in captions", "type": "toggle", "value": true},+ {"label": "Steps", "type": "workflow", "value": [{"name": "Cut", "by": "@cutter"}, {"name": "Review", "by": "you", "back": "Cut"}]}]}]}"#;++#[test]+fn a_controller_fills_ids_from_titles_and_labels() {+ let c = controller::normalize(&serde_json::from_str(DELIVERY).unwrap()).unwrap();+ assert_eq!(c.id, "delivery");+ assert_eq!(c.groups[0].id, "format");+ let ids: Vec<_> = c.groups[0].fields.iter().map(|f| f.id.as_str()).collect();+ assert_eq!(ids, ["aspect-ratio", "loudness", "burn-in-captions", "steps"]);+ let controller::Kind::Workflow { value, .. } = &c.groups[0].fields[3].kind else { panic!("a workflow") };+ assert_eq!(value[0].by.as_deref(), Some("cutter"));+ // what it writes back reads as the same controller (the page's types are these)+ let again = controller::normalize(&serde_json::to_value(&c).unwrap()).unwrap();+ assert_eq!(again, c);+}++#[test]+fn a_controller_says_what_is_wrong_in_a_sentence_the_agent_can_act_on() {+ let bad = |j: &str| controller::normalize(&serde_json::from_str(j).unwrap()).unwrap_err();+ assert!(bad(r#"{"title": "X", "groups": [{"title": "G", "fields": [{"label": "A", "type": "slider"}]}]}"#).contains("type must be one of"));+ assert!(bad(r#"{"title": "X", "groups": [{"title": "G", "fields": [{"label": "A", "type": "choice", "options": ["one"]}]}]}"#).contains("at least two options"));+ assert!(bad(r#"{"title": "X"}"#).contains("needs groups"));+ assert!(bad(r#"{"groups": []}"#).contains("needs a title"));+ assert!(bad(r#"{"title": "X", "groups": [{"title": "G", "fields": [{"label": "A", "type": "toggle"}, {"label": "a", "type": "toggle"}]}]}"#).contains("two fields are called a"));+}++#[test]+fn a_value_is_checked_against_its_field() {+ let c = controller::normalize(&serde_json::from_str(DELIVERY).unwrap()).unwrap();+ let cs = [c];+ let f = |p: &str| controller::field(&cs, p).unwrap();+ assert!(controller::check_value(f("delivery.format.loudness"), &serde_json::json!(-16)).is_ok());+ assert!(controller::check_value(f("delivery.format.loudness"), &serde_json::json!(4)).unwrap_err().contains("between -30 and 0"));+ assert!(controller::check_value(f("delivery.format.aspect-ratio"), &serde_json::json!("16:9")).unwrap_err().contains("one of: 9:16, 4:5, 1:1"));+ assert!(controller::check_value(f("delivery.format.burn-in-captions"), &serde_json::json!("yes")).is_err());+ assert!(controller::field(&cs, "delivery.format.nope").is_none());+}diff --git a/core/k/kernels/composite.k b/core/k/kernels/composite.kindex 01e739f2..b03db4cc 100644--- a/core/k/kernels/composite.k+++ b/core/k/kernels/composite.k@@ -9,6 +9,7 @@ bg:tex[T;x;y]r:and[bg;255]g:and[shr[bg;8];255]b:and[shr[bg;16];255]+a:and[shr[bg;24];255]/ clip slot 0on0:word[C;0]bx0:word[C;1]@@ -62,6 +63,7 @@ bb0:clamp[shr[k0+(541*cu0)+128;8];0;255]r:shr[(am0*rr0)+((256-am0)*r);8]g:shr[(am0*gg0)+((256-am0)*g);8]b:shr[(am0*bb0)+((256-am0)*b);8]+a:shr[(am0*255)+((256-am0)*a);8]end/ clip slot 1on1:word[C;12]@@ -116,6 +118,7 @@ bb1:clamp[shr[k1+(541*cu1)+128;8];0;255]r:shr[(am1*rr1)+((256-am1)*r);8]g:shr[(am1*gg1)+((256-am1)*g);8]b:shr[(am1*bb1)+((256-am1)*b);8]+a:shr[(am1*255)+((256-am1)*a);8]end/ clip slot 2on2:word[C;24]@@ -170,6 +173,7 @@ bb2:clamp[shr[k2+(541*cu2)+128;8];0;255]r:shr[(am2*rr2)+((256-am2)*r);8]g:shr[(am2*gg2)+((256-am2)*g);8]b:shr[(am2*bb2)+((256-am2)*b);8]+a:shr[(am2*255)+((256-am2)*a);8]end/ clip slot 3on3:word[C;36]@@ -224,6 +228,7 @@ bb3:clamp[shr[k3+(541*cu3)+128;8];0;255]r:shr[(am3*rr3)+((256-am3)*r);8]g:shr[(am3*gg3)+((256-am3)*g);8]b:shr[(am3*bb3)+((256-am3)*b);8]+a:shr[(am3*255)+((256-am3)*a);8]end/ the overlay, premultiplied: o + below * (255 - a) / 255o:word[O;i]@@ -231,4 +236,5 @@ oa:and[shr[o;24];255]r:and[o;255]+((r*(255-oa))+127)%255g:and[shr[o;8];255]+((g*(255-oa))+127)%255b:and[shr[o;16];255]+((b*(255-oa))+127)%255-px:pack[r;g;b;255]+a:oa+((a*(255-oa))+127)%255+px:pack[r;g;b;a]diff --git a/core/k/kernels/composite_tex.k b/core/k/kernels/composite_tex.kindex 514d12f8..9e624b9a 100644--- a/core/k/kernels/composite_tex.k+++ b/core/k/kernels/composite_tex.k@@ -8,6 +8,7 @@ bg:tex[T;x;y]r:and[bg;255]g:and[shr[bg;8];255]b:and[shr[bg;16];255]+a:and[shr[bg;24];255]/ clip slot 0on0:word[C;0]bx0:word[C;1]@@ -60,6 +61,7 @@ bb0:clamp[shr[k0+(541*cu0)+128;8];0;255]r:shr[(am0*rr0)+((256-am0)*r);8]g:shr[(am0*gg0)+((256-am0)*g);8]b:shr[(am0*bb0)+((256-am0)*b);8]+a:shr[(am0*255)+((256-am0)*a);8]end/ clip slot 1on1:word[C;12]@@ -113,6 +115,7 @@ bb1:clamp[shr[k1+(541*cu1)+128;8];0;255]r:shr[(am1*rr1)+((256-am1)*r);8]g:shr[(am1*gg1)+((256-am1)*g);8]b:shr[(am1*bb1)+((256-am1)*b);8]+a:shr[(am1*255)+((256-am1)*a);8]end/ clip slot 2on2:word[C;24]@@ -166,6 +169,7 @@ bb2:clamp[shr[k2+(541*cu2)+128;8];0;255]r:shr[(am2*rr2)+((256-am2)*r);8]g:shr[(am2*gg2)+((256-am2)*g);8]b:shr[(am2*bb2)+((256-am2)*b);8]+a:shr[(am2*255)+((256-am2)*a);8]end/ clip slot 3on3:word[C;36]@@ -219,6 +223,7 @@ bb3:clamp[shr[k3+(541*cu3)+128;8];0;255]r:shr[(am3*rr3)+((256-am3)*r);8]g:shr[(am3*gg3)+((256-am3)*g);8]b:shr[(am3*bb3)+((256-am3)*b);8]+a:shr[(am3*255)+((256-am3)*a);8]end/ the overlay, premultiplied: o + below * (255 - a) / 255o:word[O;i]@@ -226,4 +231,5 @@ oa:and[shr[o;24];255]r:and[o;255]+((r*(255-oa))+127)%255g:and[shr[o;8];255]+((g*(255-oa))+127)%255b:and[shr[o;16];255]+((b*(255-oa))+127)%255-px:pack[r;g;b;255]+a:oa+((a*(255-oa))+127)%255+px:pack[r;g;b;a]diff --git a/core/k/kernels/gen.py b/core/k/kernels/gen.pyindex 2682976c..d3a7a562 100644--- a/core/k/kernels/gen.py+++ b/core/k/kernels/gen.py@@ -9,7 +9,10 @@ L = ["/ The frame on the GPU: the camera's target T is the background (clear col"/ Luma and chroma are bilinear; YUV is BT.709 limited range in 8.8 fixed point. One RGBA word per pixel.","x:i!w", "y:i%w","bg:tex[T;x;y]",- "r:and[bg;255]", "g:and[shr[bg;8];255]", "b:and[shr[bg;16];255]"]+ "r:and[bg;255]", "g:and[shr[bg;8];255]", "b:and[shr[bg;16];255]",+ # coverage, carried so a transparent clear (render --alpha) stays transparent where nothing is drawn; over an+ # opaque background every step below keeps it 255, so those frames are the same pixels as before+ "a:and[shr[bg;24];255]"]for s in range(SLOTS):P, c = f"P{s}", lambda k: f"word[C;{s * 12 + k}]"L += [f"/ clip slot {s}",@@ -46,13 +49,15 @@ for s in range(SLOTS):f"r:shr[(am{s}*rr{s})+((256-am{s})*r);8]",f"g:shr[(am{s}*gg{s})+((256-am{s})*g);8]",f"b:shr[(am{s}*bb{s})+((256-am{s})*b);8]",+ f"a:shr[(am{s}*255)+((256-am{s})*a);8]","end"]L += ["/ the overlay, premultiplied: o + below * (255 - a) / 255","o:word[O;i]", "oa:and[shr[o;24];255]","r:and[o;255]+((r*(255-oa))+127)%255","g:and[shr[o;8];255]+((g*(255-oa))+127)%255","b:and[shr[o;16];255]+((b*(255-oa))+127)%255",- "px:pack[r;g;b;255]"]+ "a:oa+((a*(255-oa))+127)%255",+ "px:pack[r;g;b;a]"]open("kernels/composite.k", "w").write("\n".join(L) + "\n")# composite_tex.k: the same, with each slot's planes as textures, as VideoToolbox's IOSurface-backed buffers wrapdiff --git a/core/scene/src/media.rs b/core/scene/src/media.rsindex d99bb642..86300515 100644--- a/core/scene/src/media.rs+++ b/core/scene/src/media.rs@@ -44,11 +44,32 @@ pub fn decoded(src: &str) -> String {String::from_utf8(out).unwrap_or_else(|_| s.to_string())}-/// A media src as a file: a path from staticFile (/media/x under the edit's folder), absolute, or relative to it.+/// The project an edit belongs to: the nearest folder at or above the edit's holding space.json (an object's folder,+/// docs/sdk.feature S5a, whose edit is src/main.tsx), else the edit's own folder. Remembered per folder, since media+/// paths are resolved every frame.+pub fn project_dir(dir: &Path) -> PathBuf {+ static SEEN: std::sync::Mutex<Option<std::collections::HashMap<PathBuf, PathBuf>>> = std::sync::Mutex::new(None);+ let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner());+ let seen = seen.get_or_insert_with(Default::default);+ if let Some(p) = seen.get(dir) {+ return p.clone();+ }+ let p = dir.ancestors().find(|d| d.join("space.json").is_file()).unwrap_or(dir).to_path_buf();+ seen.insert(dir.to_path_buf(), p.clone());+ p+}++/// A media src as a file: a path from staticFile (/media/x: the project's media/, then its assets/, as Bevy's assets+/// folder; the edit's own media/ first when the edit isn't the project's folder), absolute, or relative to the edit.pub fn media_path(dir: &Path, src: &str) -> PathBuf {if let Some(rest) = src.strip_prefix("/media/") {- let p = dir.join("media").join(rest);- if p.exists() {+ let project = project_dir(dir);+ let mut tried = vec![dir.join("media")];+ if project != dir {+ tried.push(project.join("media"));+ }+ tried.push(project.join("assets"));+ if let Some(p) = tried.iter().map(|d| d.join(rest)).find(|p| p.exists()) {return p;}}@@ -58,3 +79,36 @@ pub fn media_path(dir: &Path, src: &str) -> PathBuf {}dir.join(src.trim_start_matches('/'))}++#[cfg(test)]+mod tests {+ use super::*;++ // an object's folder (S5a): space.json at its root, the edit in src/, files in assets/ or media/+ #[test]+ fn media_from_the_project() {+ let root = std::env::temp_dir().join(format!("raea-media-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&root);+ let src = root.join("src");+ for d in [&src, &root.join("assets"), &root.join("media"), &src.join("media")] {+ std::fs::create_dir_all(d).unwrap();+ }+ std::fs::write(root.join("space.json"), "{}").unwrap();+ for f in ["assets/a.png", "assets/b.png", "media/b.png", "src/media/c.png", "assets/c.png"] {+ std::fs::write(root.join(f), "").unwrap();+ }+ assert_eq!(project_dir(&src), root);+ assert_eq!(media_path(&src, "/media/a.png"), root.join("assets/a.png"));+ assert_eq!(media_path(&src, "/media/b.png"), root.join("media/b.png"));+ assert_eq!(media_path(&src, "/media/c.png"), src.join("media/c.png"));+ // missing: where it was always looked for+ assert_eq!(media_path(&src, "/media/d.png"), src.join("media/d.png"));+ // no space.json above: the edit's folder is the project, its assets/ after its media/+ let plain = root.join("plain");+ std::fs::create_dir_all(plain.join("assets")).unwrap();+ std::fs::write(plain.join("assets/e.png"), "").unwrap();+ std::fs::remove_file(root.join("space.json")).unwrap();+ assert_eq!(media_path(&plain, "/media/e.png"), plain.join("assets/e.png"));+ let _ = std::fs::remove_dir_all(&root);+ }+}diff --git a/docs/bevy-upgrade.md b/docs/bevy-upgrade.mdindex 56b5a59a..c2b00826 100644--- a/docs/bevy-upgrade.md+++ b/docs/bevy-upgrade.md@@ -15,9 +15,10 @@ pinned in rust-toolchain.toml at the root (1.97.1, what 0.20 was ported and veriin every checkout and on the CI runner; Homebrew's rust is uninstalled so nothing on PATH comes ahead of them. A bumpthat needs a newer rustc moves that pin in the same branch.-## The pipeline: three subagents+## The pipeline: three lanes-When a Bevy release comes out, run these three in order (they live in .claude/agents/, and each reads this file):+When a Bevy release comes out, run these three in order as lanes, `tools/agents/agent start bevy-scout` and so on (their briefs+are docs/handoff/bevy-{scout,porter,verifier}.md, and each reads this file):1. **bevy-scout** (read-only): can raea move yet? It compares crates.io against the pins, names the plugins thathaven't caught up, picks out the migration-guide items that hit raea's code, and checks whether upstream now coversdiff --git a/docs/settings.md b/docs/settings.mdindex f46c9001..0291d6a6 100644--- a/docs/settings.md+++ b/docs/settings.md@@ -8,6 +8,18 @@ which setting is missing.mkdir -p ~/.raea && touch ~/.raea/env && chmod 600 ~/.raea/env```+## Network++| Setting | What |+|---|---|+| `RAEA_OFFLINE=1` | raea makes no network requests: a remote URL not already in raea's cache, a model or sample library not yet installed, a composition's own `fetch()` or WebSocket, Bevy's http asset source and every `raea gen` step are refused with what wanted out. What's on disk keeps working |++## Generation (`raea gen`, optional)++| Setting | What |+|---|---|+| `FISH_API_KEY` | Your Fish Audio key, for an `audio.speech` step on `fish:<model>` (`fish:` alone is s2.1-pro); a plan quotes Fish's price for the words first |+## Local audio modelsTwo models make sound on your Mac, free, with no account. Each installs itself the first time a composition or adiff --git a/engine/bevy-calls/Cargo.toml b/engine/bevy-calls/Cargo.tomlindex 13313fde..46d203b0 100644--- a/engine/bevy-calls/Cargo.toml+++ b/engine/bevy-calls/Cargo.toml@@ -25,6 +25,7 @@ fastnoise-lite = { version = "=1.1.1", optional = true, default-features = falsenoisy_bevy = { version = "=0.15.0", optional = true, default-features = false, features = ["cpu", "gpu"] }bevy_northstar = { version = "=0.8.0", optional = true, default-features = false, features = ["parallel"] }bevy_quinnet = { version = "=0.22.0", optional = true, default-features = false, features = ["client", "server", "shared-client-id", "recv_channels"] }+moonshine-save = { version = "=0.8.0", optional = true, default-features = false, features = [] }bevy_simple_tilemap = { version = "=0.21.0", optional = true, default-features = false, features = [] }bevy_sprite3d = { version = "=10.1.0", optional = true, default-features = false, features = [] }bevy_trauma_shake = { version = "=0.9.0", optional = true, default-features = false, features = ["events", "commands", "system_param"] }@@ -44,6 +45,7 @@ noise = ["dep:noise", "dep:fastnoise-lite"]noisy = ["dep:noisy_bevy"]northstar = ["dep:bevy_northstar"]quinnet = ["dep:bevy_quinnet"]+save = ["dep:moonshine-save"]simple_tilemap = ["dep:bevy_simple_tilemap"]sprite3d = ["dep:bevy_sprite3d"]trauma_shake = ["dep:bevy_trauma_shake"]diff --git a/engine/bevy-calls/src/lib.rs b/engine/bevy-calls/src/lib.rsindex 7fd3ba0a..a08ab5fe 100644--- a/engine/bevy-calls/src/lib.rs+++ b/engine/bevy-calls/src/lib.rs@@ -32,6 +32,8 @@ pub mod noisy;pub mod northstar;#[cfg(feature = "quinnet")]pub mod quinnet;+#[cfg(feature = "save")]+pub mod save;#[cfg(feature = "simple_tilemap")]pub mod simple_tilemap;#[cfg(feature = "sprite3d")]diff --git a/engine/bevy-calls/src/save.rs b/engine/bevy-calls/src/save.rsnew file mode 100644index 00000000..f4dcb9d6--- /dev/null+++ b/engine/bevy-calls/src/save.rs@@ -0,0 +1,78 @@+//! moonshine-save (the declaration's `"calls": "save"`): saving marked entities to a file and loading them back+//! (docs/plugins.feature PL16). Its markers (Save, Unload) aren't reflected and saving is an event a Rust system+//! triggers, so TypeScript marks and saves through methods. moonshine-save's own observers do the work; these record+//! what each save and load did.+//!+//! save/mark {entities: [entity, ...], unload?} -> null: marks them Save (saved, and replaced on load), or with+//! unload Unload (never saved, despawned on load: a saved entity's visuals)+//! save/save {path} -> {saved: [entity, ...]}: every Save entity's reflected, serializable components, as RON+//! save/load {path} -> {loaded: [entity, ...]}: despawns the Save and Unload entities, then spawns the file's and+//! marks them Save again (Save itself isn't saved, being unreflected)++use bevy::prelude::*;+use bevy_remote::BrpResult;+use moonshine_save::prelude::{Loaded, Save, SaveWorld, Saved, TriggerLoad, TriggerSave, Unload, LoadWorld, load_on_default_event, save_on_default_event};+use serde_json::{Value, json};++use crate::{add_method, entity, fail, params};++pub fn calls(app: &mut App) {+ app.add_observer(save_on_default_event).add_observer(load_on_default_event).add_observer(saved).add_observer(loaded);+ add_method(app, "save/mark", mark);+ add_method(app, "save/save", file(true));+ add_method(app, "save/load", file(false));+}++/// What the last save or load did: None until it finishes (moonshine-save logs why one failed)+#[derive(Resource, Default)]+struct Done(Option<Vec<Entity>>);++fn saved(s: On<Saved>, mut commands: Commands) {+ commands.insert_resource(Done(Some(s.entities().collect())));+}++fn loaded(l: On<Loaded>, mut commands: Commands) {+ let es: Vec<Entity> = l.entities().collect();+ for &e in &es {+ if let Ok(mut c) = commands.get_entity(e) {+ c.insert(Save);+ }+ }+ commands.insert_resource(Done(Some(es)));+}++#[derive(serde::Deserialize)]+struct MarkParams {+ entities: Vec<u64>,+ #[serde(default)]+ unload: bool,+}++fn mark(In(p): In<Option<Value>>, world: &mut World) -> BrpResult {+ let p: MarkParams = params(p)?;+ for bits in p.entities {+ let e = entity(bits)?;+ let mut at = world.get_entity_mut(e).map_err(|_| fail(format!("no entity {e}")))?;+ if p.unload { at.insert(Unload) } else { at.insert(Save) };+ }+ Ok(Value::Null)+}++#[derive(serde::Deserialize)]+struct PathParams {+ path: String,+}++/// save/save or save/load: one file through moonshine-save, and the entities it did, or why it didn't+fn file(save: bool) -> impl FnMut(In<Option<Value>>, &mut World) -> BrpResult {+ move |In(p), world| {+ let p: PathParams = params(p)?;+ world.insert_resource(Done(None));+ if save { world.trigger_save(SaveWorld::default_into_file(&p.path)) } else { world.trigger_load(LoadWorld::default_from_file(&p.path)) }+ world.flush();+ let (what, key) = if save { ("save to", "saved") } else { ("load from", "loaded") };+ let done = world.remove_resource::<Done>().and_then(|d| d.0).ok_or_else(|| fail(format!("{what} {} failed (the log says why)", p.path)))?;+ let bits: Vec<u64> = done.into_iter().map(Entity::to_bits).collect();+ Ok(Value::Object([(key.to_string(), json!(bits))].into_iter().collect()))+ }+}diff --git a/engine/bevy-plugins/Cargo.toml b/engine/bevy-plugins/Cargo.tomlindex f09404d9..50eceb9e 100644--- a/engine/bevy-plugins/Cargo.toml+++ b/engine/bevy-plugins/Cargo.toml@@ -7,6 +7,7 @@ publish = falsedescription = "Bevy plugins compiled into raea's engine, each behind a feature (sdk/raea/docs/bevy-plugins.md): declared in a project's package.json, resolved here by tools/bevy-plugins.sh, registered with raea-render's plugin hooks, driven from TSX by generic reflect rows and from TypeScript by bevy_remote's method table, stepped by the frame index"[dependencies]+raea-io-home = { path = "../../io/home" }raea-runtime-plugins = { path = "../../runtime/plugins" }# a declaration's Blitz widgets, registered for every page App (declared.rs)raea-sys-page = { path = "../../systems/page" }@@ -51,7 +52,6 @@ iyes_progress = { version = "=0.18.0", optional = true, default-features = falsebevy_quinnet = { version = "=0.22.0", optional = true, default-features = false, features = ["client", "server", "shared-client-id", "recv_channels"] }bevy_rand = { version = "=0.16.0", optional = true, default-features = false, features = ["std", "wyrand", "bevy_reflect", "thread_local_entropy"] }bevy_remote = { version = "=0.20.0", default-features = false }-moonshine-save = { version = "=0.8.0", optional = true, default-features = false, features = [] }bevy_simple_tilemap = { version = "=0.21.0", optional = true, default-features = false, features = [] }bevy_skein = { version = "=0.7.0-rc.1", optional = true, default-features = false, features = [] }bevy_smud = { version = "=0.15.0", optional = true, default-features = false, features = [] }@@ -108,7 +108,7 @@ rand = ["dep:bevy_rand"]rapier2d = ["raea-bevy-adapters/rapier2d"]rapier3d = ["raea-bevy-adapters/rapier3d"]remote = ["bevy_remote/http"]-save = ["dep:moonshine-save"]+save = ["raea-bevy-calls/save"]simple_tilemap = ["dep:bevy_simple_tilemap", "raea-bevy-calls/simple_tilemap"]skein = ["dep:bevy_skein"]smud = ["dep:bevy_smud"]diff --git a/engine/bevy-plugins/src/bevy.rs b/engine/bevy-plugins/src/bevy.rsindex d449eadd..643d2eb9 100644--- a/engine/bevy-plugins/src/bevy.rs+++ b/engine/bevy-plugins/src/bevy.rs@@ -3,7 +3,7 @@//! They need no plugin of raea's: turning a feature on puts its plugin in Bevy's DefaultPlugins, which raea-render's Engine//! builds. One exception is handled here: bevy_audio's AudioPlugin plays to the device, not into raea's mixer, so a//! render wouldn't hear it and a play would hear it twice. The Engine leaves it out; a TypeScript App that wants-//! Bevy's audio asks for it by name (`plugins: ["bevy_audio"]`).+//! Bevy's audio asks for it by name (`plugins: ["bevy_audio"]`). And under RAEA_OFFLINE the http asset source is left out.use bevy::app::PluginGroupBuilder;use bevy::prelude::*;@@ -21,5 +21,7 @@ pub fn register() {}fn group(b: PluginGroupBuilder) -> PluginGroupBuilder {- b.disable::<bevy::audio::AudioPlugin>()+ let b = b.disable::<bevy::audio::AudioPlugin>();+ // RAEA_OFFLINE: no http(s) asset source, so a model or texture named by URL is refused rather than fetched+ if raea_io_home::offline("Bevy's http asset source").is_err() { b.disable::<bevy::asset::io::web::WebAssetPlugin>() } else { b }}diff --git a/engine/bevy-plugins/src/declared.rs b/engine/bevy-plugins/src/declared.rsindex 9f6b2577..8b118e82 100644--- a/engine/bevy-plugins/src/declared.rs+++ b/engine/bevy-plugins/src/declared.rs@@ -82,7 +82,7 @@ pub fn install() {#[cfg(feature = "rapier3d")]raea_bevy_adapters::rapier3d::register();#[cfg(feature = "save")]- use moonshine_save as _;+ raea_runtime_plugins::register(raea_runtime_plugins::Registered { name: "save", install: |app| { raea_bevy_calls::save::calls(app); }, group: None, on_demand: false });#[cfg(feature = "simple_tilemap")]raea_runtime_plugins::register(raea_runtime_plugins::Registered { name: "simple_tilemap", install: |app| { crate::AddOnce::add_once(bevy_simple_tilemap::prelude::SimpleTileMapPlugin, app); raea_bevy_calls::simple_tilemap::calls(app); }, group: None, on_demand: false });#[cfg(feature = "skein")]@@ -164,7 +164,7 @@ pub fn declared() -> Vec<Declared> {#[cfg(feature = "rapier2d")] v.push(Declared { name: "rapier2d", krate: "bevy_rapier2d", source: "version = \"=0.37.0\"", prefixes: &["bevy_rapier2d::", "raea_bevy_adapters::rapier2d::"], headless: &[], on_demand: false });#[cfg(feature = "rapier3d")] v.push(Declared { name: "rapier3d", krate: "bevy_rapier3d", source: "version = \"=0.37.0\"", prefixes: &["bevy_rapier3d::", "raea_bevy_adapters::rapier3d::"], headless: &[], on_demand: false });v.push(Declared { name: "remote", krate: "bevy_remote", source: "version = \"=0.20.0\"", prefixes: &["bevy_remote::"], headless: &[], on_demand: false });- #[cfg(feature = "save")] v.push(Declared { name: "save", krate: "moonshine-save", source: "version = \"=0.8.0\"", prefixes: &["moonshine_save::"], headless: &[], on_demand: false });+ #[cfg(feature = "save")] v.push(Declared { name: "save", krate: "moonshine-save", source: "version = \"=0.8.0\"", prefixes: &["moonshine_save::"], headless: &["assets"], on_demand: false });#[cfg(feature = "simple_tilemap")] v.push(Declared { name: "simple_tilemap", krate: "bevy_simple_tilemap", source: "version = \"=0.21.0\"", prefixes: &["bevy_simple_tilemap::"], headless: &["shader", "image"], on_demand: false });#[cfg(feature = "skein")] v.push(Declared { name: "skein", krate: "bevy_skein", source: "version = \"=0.7.0-rc.1\"", prefixes: &["bevy_skein::"], headless: &[], on_demand: false });#[cfg(feature = "smud")] v.push(Declared { name: "smud", krate: "bevy_smud", source: "version = \"=0.15.0\"", prefixes: &["bevy_smud::"], headless: &["shader", "mesh"], on_demand: false });diff --git a/engine/cli/Cargo.toml b/engine/cli/Cargo.tomlindex 518351aa..d0b423a2 100644--- a/engine/cli/Cargo.toml+++ b/engine/cli/Cargo.toml@@ -22,6 +22,10 @@ required-features = ["bevy-plugins"][dependencies]raea-runtime-plugins = { path = "../../runtime/plugins" }raea-io-home = { path = "../../io/home" }+# the schemas of what an agent writes (brief.ts, script.ts, taste.ts, controllers): raea context reads specs against them+raea-core-brief = { path = "../../core/brief" }+# `raea workspace`, `raea project` and `raea controller` (docs/projects.feature PJ1-PJ4)+raea-app-workspace = { path = "../../apps/workspace" }raea-runtime-react = { path = "../../runtime/react", default-features = false, features = ["h264", "av1", "scripts", "modules", "network", "ml"] }# the sound of its renders and plays: <Seedling> samples and speech (raea-runtime-sound's features)raea-runtime-sound = { path = "../../runtime/sound", features = ["seedling", "ml"] }@@ -38,7 +42,10 @@ raea-io-media = { path = "../../io/media", default-features = false, features =raea-io-npm = { path = "../../io/npm" }# the agent's sandbox (WASI tools on Wasmtime/Pulley) as wsx.* native callswsx = { path = "../../engine/sandbox/wsx" }+serde = "1"serde_json = "1"+# `raea neural` (docs/raytracing.feature RT2)+raea-neural = { path = "../neural" }regex = "1"# the app crates' verbs: `raea check`, `raea ci`, and the local tools' (sao, tokensynth, setup-audio, sounds, splat)raea-app-check = { path = "../../apps/check" }diff --git a/engine/cli/conformance/surface.test.ts b/engine/cli/conformance/surface.test.tsindex ca6fe062..ef81ba27 100644--- a/engine/cli/conformance/surface.test.ts+++ b/engine/cli/conformance/surface.test.ts@@ -49,10 +49,11 @@ const listed = new Set([...help.matchAll(/raea ([a-z][\w-]*)/g), ...help.matchAlconst shellVerbs = JSON.parse(/const SHELL: &\[&str\] = &(\[[^\]]*\]);/.exec(readFileSync(join(raea, "engine/cli/src/verbs.rs"), "utf8"))![1]) as string[];const handled = new Set([...cli.matchAll(/case "(\w+)":/g)].map((m) => m[1]).filter((c) => c !== "--help" && c !== "help"));+/** the hand-written text under dir: a skill's reference/ is the help itself, written by tools/skills.sh gen */function files(dir: string, out: string[] = []): string[] {for (const f of readdirSync(dir)) {const p = join(dir, f);- if (lstatSync(p).isDirectory()) files(p, out);+ if (lstatSync(p).isDirectory()) f !== "reference" && files(p, out);else if (f.endsWith(".md")) out.push(p);}return out;@@ -134,6 +135,18 @@ describe("raea's surface", () => {} finally {rmSync(dir, { recursive: true, force: true });}+ // by feature (S5a): space.json, package.json, assets/, src/ with main.tsx, a feature, shots/; never components/+ const feat = mkdtempSync(join(tmpdir(), "raea-init-feature-"));+ const go = (...a: string[]) => spawnSync("bun", [join(here, "src/native.ts"), bin, ...a], { cwd: feat, encoding: "utf8" });+ try {+ expect(go("init", "--layout", "feature").stdout).toContain("made space.json, package.json, src/main.tsx");+ expect(["space.json", "package.json", "assets", "src/main.tsx", "src/title.tsx", "src/shots/opening.tsx", "src/screens", "src/ui", "AGENTS.md"].filter((f) => !existsSync(join(feat, f)))).toEqual([]);+ expect(existsSync(join(feat, "components"))).toBe(false);+ expect(go("init", "--layout", "feature").stdout).toContain("nothing to make");+ expect(go("init", "--layout", "other").status).toBe(2);+ } finally {+ rmSync(feat, { recursive: true, force: true });+ }});// a made clip (two colours: the take has a jump cut at 2 s) and a made-up transcript, never real footagediff --git a/engine/cli/src/cli.rs b/engine/cli/src/cli.rsindex b5acb40e..a92bf56b 100644--- a/engine/cli/src/cli.rs+++ b/engine/cli/src/cli.rs@@ -95,13 +95,26 @@ pub fn run_script(args: &[String]) -> R<i32> {pub fn run(args: &[String]) -> R<String> {// no arguments, or asking for help: the usage, plainly (the render line's refusal is for a render missing its file)+ // `help --json`: the same help, each verb's usage, flags and access tag (tools/skills.sh gen reads it)+ if args.len() == 2 && args[0] == "help" && args[1] == "--json" {+ return Ok(usage::help_json(&run(&["help".to_string()])?).to_string());+ }if args.is_empty() || matches!(args[0].as_str(), "help" | "--help" | "-h") {+ let neural_usage = neural::USAGE;let was = IN_HELP.replace(true);let usage = run(&["render".to_string()]).err().unwrap_or_default();IN_HELP.set(was);+ // `raea library` (engine/cli/src/library.ts), listed under render's usage+ let usage = format!("{usage}\n raea library [new NAME [--cloud] | add LIBRARY PATH | files LIBRARY | tag SHA TAGS | status | scan ...] | raea library search \"WORDS\" [--library LIBRARY] [--kind KIND] [--limit N] [--sound] (the person's libraries in the raea app: folders and drives indexed on this machine, searched by meaning; a folder an agent adds waits for the person's yes)");+ // a workspace's files and specs (docs/projects.feature), listed under render's usage like library+ let usage = format!("{usage}\n raea spec FILE.ts [--as brief|script|taste|plan|controller] (a spec's default export as JSON, checked against its schema: brief.ts, script.ts, taste.ts, plan.ts, controllers/ID.ts)\n raea workspace init [NAME] [--layout LAYOUT] | raea workspace adopt DIR [--name NAME] | raea workspace [--json] (a workspace: a git repo of projects and controllers under raea.root, ~/Studio 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 (Claude Code's PostToolUse hook: the quick check after a composition is saved)\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 {}\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", raea_app_check::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 --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 mezz [--check] PATH... (an intra-only ProRes copy of each long-GOP source over 1080p, for smooth scrubbing; --check says which would get one)\n raea traces [show [N|last|DIR]] (the sessions raea left, newest first: how each ended, its glitches; show tells one in full)"));+ return Ok(format!("raea: renders, plays and checks raea compositions (React and TypeScript) on the GPU.\n\nusage: {usage}\n raea init (a project's files where they're missing: edit.tsx, cuts.ts, components/, AGENTS.md)\n raea cut TAKE \"line\" ... | --at A-B ... [--append] (cuts.ts and words.json: a take under media/ cut in the pauses around each line it says, transcribed first if it has no TAKE.words.json; or at those seconds)\n raea frame TAKE [--at S] (how a take fits the edit: a talking take for <FaceFrame>, a screen for <ScreenFit>, from where its face is)\n raea 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 --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)+ if args.len() == 1 && matches!(args[0].as_str(), "--version" | "-V") {+ return Ok(skill::version());}// an argument the verb doesn't take is refused with its usage, never dropped (zsh's "--frame 20", one word, rendered// every frame): the verb's flags and how many arguments it takes are read from its lines in the help, the one list@@ -118,6 +131,55 @@ pub fn run(args: &[String]) -> R<String> {if args[0] == "context" {return context(args.get(1).map(String::as_str));}+ // `workspace …` and `project …`: the folder format, configured by committed git-config (docs/projects.feature PJ1)+ if args[0] == "workspace" {+ return raea_app_workspace::workspace(&args[1..]);+ }+ if args[0] == "project" {+ return raea_app_workspace::project(&args[1..]);+ }+ // `controller …`: the workspace's controllers/<id>.ts and a project's overrides (PJ2)+ if args[0] == "controller" {+ return raea_app_workspace::controller(&args[1..], spec::spec_json);+ }+ // `skill [NAME]` and `skills install --agent A`: the skills this raea ships, for its version (SK6)+ if args[0] == "skill" {+ return skill::skill(&args[1..]);+ }+ if args[0] == "skills" {+ return skill::install(&args[1..]);+ }+ // `next [DIR]` and `doctor [--fix] [DIR]`: the project's next steps, and its drift from this raea (SK10)+ if args[0] == "next" {+ return next(&args[1..]);+ }+ if args[0] == "doctor" {+ return skill::doctor(&args[1..]);+ }+ // `setup blender` and `blender run SCRIPT.py`: Blender found or downloaded, its MCP add-on, headless scripts (SK11)+ if args[0] == "setup" && args.get(1).map(String::as_str) == Some("blender") {+ return tools::blender::setup(&args[2..]);+ }+ if args[0] == "blender" {+ return tools::blender::blender(args);+ }+ // `spec FILE.ts`: a spec's data as JSON, for a program that reads specs without evaluating TypeScript (the feed's host)+ if args[0] == "spec" {+ return spec::spec_cli(&args[1..]);+ }+ // `check VIDEO --taste taste.ts|DIR`: the taste's .ts files evaluated here, then the check (main.rs takes the rest)+ if args[0] == "check" && args.iter().any(|a| a == "--quick") {+ let (report, bad) = raea_app_check::quick::quick(&args[1..], spec::tastes_ts(args)?)?;+ println!("{report}");+ std::process::exit(i32::from(bad));+ }+ // `hook claude`: Claude Code's PostToolUse hook, the quick check after a composition is saved (SK10)+ if args[0] == "hook" {+ return raea_app_check::quick::hook(&args[1..]);+ }+ if args[0] == "check" {+ std::process::exit(raea_app_check::cli_with(&args[1..], spec::tastes_ts(args)?));+ }if args.first().map(String::as_str) == Some("traces") {return traces(args);}@@ -136,6 +198,10 @@ pub fn run(args: &[String]) -> R<String> {}// `mezz [--check] PATH...`: optimized media (raea_io_media::mezz, lightspeed F4): each long-GOP source over 1080p under// PATH (a file, or a folder's videos) gets its intra-only ProRes copy, one at a time; --check only says which would+ // `neural mlxdlss DIR -o OUT`: DLSS 5 on a `render --aov` folder, through the founder's own MLX-DLSS (RT2)+ if args.first().map(String::as_str) == Some("neural") {+ return neural::neural(&args[1..]);+ }if args.first().map(String::as_str) == Some("mezz") {return mezz(&args[1..]);}@@ -157,6 +223,9 @@ pub fn run(args: &[String]) -> R<String> {Some("song") => return tools::song::song(args),// `track CLIP.mp4 [--subject X,Y,W,H] [--from S]`: the clip's camera solved for <Matchmove> (motion/track.rs)Some("track") => return motion::track::track(args),+ // `gen …`: generation flows on made.app, fal, Replicate, OpenRouter, Modal and ComfyUI, and ComfyUI workflows read+ // and written (raea-io-gen, through apps/tools generate.rs for the local models)+ Some("gen") => return raea_app_tools::generate::generate(args),// the agent shell's own verbs ported here (`init`, `cut`, `frame`): engine/cli's handler, run by its native.ts (shell())Some(v) if SHELL.contains(&v) => return shell(args),_ => {}@@ -255,7 +324,7 @@ pub fn run(args: &[String]) -> R<String> {}if args.first().map(String::as_str) != Some("render") || args.len() < 2 {return Err(format!(- "raea render EDIT.tsx -o OUT.mp4|OUT.png|DIR [--frame N | --at A,B] [--composition ID] [--w W] [--h H] [--fps FPS] [--frames N] [--words W.json] [--perception P.json] [--input I.json|inputs.rrl] [--manifest render.json] [--stage WxH] [--10bit] [--kbps N | --quality draft|high|master|0..1] (also: --lite --comps)\n raea render PAGE.html -o OUT.mp4|DIR [--at A,B] (an HTML composition, the HTML composition format format)\n raea render --bundle NAME.comp.js -o OUT.png|DIR [--dir DIR] [--frame N] (a bundle from raea bundle, as render_bundle draws it)+ "raea render EDIT.tsx -o OUT.mp4|OUT.png|DIR [--frame N | --at A,B] [--composition ID] [--w W] [--h H] [--fps FPS] [--frames N] [--words W.json] [--perception P.json] [--input I.json|inputs.rrl] [--manifest render.json] [--stage WxH] [--10bit] [--aov] [--alpha] [--kbps N | --quality draft|high|master|0..1] (also: --lite --comps)\n raea render PAGE.html -o OUT.mp4|DIR [--at A,B] (an HTML composition, the HTML composition format format)\n raea render --bundle NAME.comp.js -o OUT.png|DIR [--dir DIR] [--frame N] (a bundle from raea bundle, as render_bundle draws it)raea media probe|still|sheet|audio|loudness|motion|cuts|freezes|proxy|trim|concat FILE ... | ffmpeg ARGS | ffprobe ARGS (media work, native: media help)raea bundle EDIT.tsx --composition-bundle -o OUT.js [--portable DIR] (a composition for render_bundle, on the Mac or the iPhone)\n raea add PKG[@RANGE]... [--dev] | remove NAME... | install [--offline] [--in DIR] (npm packages for the project: raea.lock, node_modules)\n {} (foley, local)\n {} (an instrument's notes, local)\n raea setup-audio [--check] [sao|tokensynth] (install or check the local audio models)\n {} (the song's energy map: beats, sections, builds, drops, stops, hits, cuts per bar; also: --backend NAME)\n raea sounds [WORDS] | sounds get PACK/INSTRUMENT [--notes ..|--all] [-o DIR] (open sample libraries for a Sampler)\n {} (the clip's camera solved, for <Matchmove>)",tools::sound::SAO_USAGE, tools::sound::TOKENSYNTH_USAGE, tools::song::USAGE, motion::track::USAGEdiff --git a/engine/cli/src/guide.rs b/engine/cli/src/guide.rsindex 79d52f9b..68ea5668 100644--- a/engine/cli/src/guide.rs+++ b/engine/cli/src/guide.rs@@ -43,7 +43,7 @@ pub fn guide(name: Option<&str>) -> R<String> {Ok(if shell { format!("{GUIDE_NOTE}{text}") } else { text })}-/// The taste files a mode reads beside taste.brief, which is always read+/// The taste files a mode reads beside taste.ts, which is always readpub fn taste_kinds(mode: &str) -> &'static [&'static str] {match mode {"pitch" | "explain" | "story" => &["motion", "sound"],@@ -53,86 +53,65 @@ pub fn taste_kinds(mode: &str) -> &'static [&'static str] {}}-/// A brief's head facts (the `key: value` lines before its first `## `), "(assumed)" dropped-pub fn brief_fact(text: &str, key: &str) -> Option<String> {- text.lines()- .take_while(|l| !l.starts_with("## "))- .find_map(|l| {- let (k, v) = l.split_once(':')?;- (k.trim().eq_ignore_ascii_case(key)).then(|| v.trim().trim_end_matches("(assumed)").trim().to_string())- })- .filter(|v| !v.is_empty())-}--/// One `## Heading` section's text, without its heading-pub fn brief_section(text: &str, heading: &str) -> Option<String> {- let mut out = String::new();- let mut inside = false;- for l in text.lines() {- if let Some(h) = l.strip_prefix("## ") {- if inside {- break;- }- inside = h.trim().eq_ignore_ascii_case(heading);- continue;- }- if inside {- out.push_str(l);- out.push('\n');- }- }- let out = out.trim().to_string();- (!out.is_empty()).then_some(out)-}-/// `raea context PROJECT`: everything an agent reads before working on a project, in the order it should be read. That-/// is the person's taste (~/.raea/taste/taste.brief, then the files its modes need; RAEA_TASTE moves the folder), the-/// project's brief and any deliverable briefs it links, its look (the brief's ## Look and brand/brand.css), and the-/// craft floor and each mode's guide. PROJECT is a folder holding brief.brief, or a .brief file.+/// is the person's taste (~/.raea/taste/taste.ts, then the files its modes need; RAEA_TASTE moves the folder), the+/// project's brief and the briefs and script it names, its look (the brief's look and brand/brand.css), and the craft+/// floor and each mode's guide. PROJECT is a folder holding brief.ts, or the file.pub fn context(project: Option<&str>) -> R<String> {- let project = project.ok_or("usage: raea context PROJECT (a folder with brief.brief, or a .brief file)")?;- let path = Path::new(project);- let brief_path = if path.is_dir() { path.join("brief.brief") } else { path.to_path_buf() };- let brief = std::fs::read_to_string(&brief_path).map_err(|e| format!("no brief at {} ({e}): a project starts as brief.brief", brief_path.display()))?;+ let project = project.ok_or("usage: raea context PROJECT (a folder with brief.ts, or a brief.ts file)")?;+ 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 title = brief.lines().find_map(|l| l.strip_prefix("# ")).unwrap_or("Untitled").trim().to_string();- let modes_of = |text: &str| -> Vec<String> {- brief_fact(text, "mode").map(|m| m.split([',', '+', '&']).map(|s| s.trim().to_ascii_lowercase()).filter(|s| !s.is_empty()).collect()).unwrap_or_default()- };- // deliverable briefs: a Deliver line naming a .brief beside the project's- let mut subs: Vec<(PathBuf, String)> = Vec::new();- if let Some(deliver) = brief_section(&brief, "deliver") {- for tok in deliver.split(['·', '\n']).map(str::trim) {- let tok = tok.split(['→', ' ']).next().unwrap_or("").trim();- if tok.ends_with(".brief") {- let p = dir.join(tok);- match std::fs::read_to_string(&p) {- Ok(t) => subs.push((p, t)),- Err(e) => subs.push((p, format!("(missing: {e})"))),- }- }- }- }- let mut modes = modes_of(&brief);- for (_, t) in &subs {- for m in modes_of(t) {- if !modes.contains(&m) {- modes.push(m);- }- }- }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")));+ // a cheap doctor (file reads and git config): CONTEXT_STALE when this project or the agent's skill is from another raea+ let stale = raea_app_workspace::doctor::findings(&dir, &skill::agents(), &skill::version());+ let stale = match stale.first() {+ Some(f) => format!("CONTEXT_STALE raea doctor finds {} thing(s), first: {} (raea doctor --fix)\n\n", stale.len(), f.says),+ None => String::new(),+ };let mut out = format!(- "# raea context: {title}\n\nRead all of this before any work on the project, in this order. The person's taste beats every guide's default; the brief\nbeats your own taste. Modes: {}.\n",+ "{stale}# raea context: {title}\n\nRead all of this before any work on the project, in this order. The person's taste beats every guide's default; the brief\nbeats your own taste. Modes: {}.\n",if modes.is_empty() { "none yet (shape the brief first: who it's for, what they should believe, what kind of piece)".to_string() } else { modes.join(", ") });+ context_body(&mut out, &dir, taste_dir, &modes, &brief_path, brief, subs, look);+ Ok(out)+}++/// `raea next [DIR]`: the two or three useful next steps for the project (apps/workspace next.rs).+pub fn next(args: &[String]) -> R<String> {+ let brief_path = brief_at(args.first().map(String::as_str).unwrap_or("."))?;+ let l = spec::load_brief_ts(&brief_path)?;+ let dir = brief_path.parent().unwrap_or(Path::new(".")).to_path_buf();+ let stale = raea_app_workspace::doctor::findings(&dir, &skill::agents(), &skill::version()).len();+ Ok(raea_app_workspace::next::text(&dir, &raea_app_workspace::next::Brief { needs: l.missing, modes: l.modes }, stale))+}++/// The brief.ts for a folder anywhere inside a project, or the file named.+fn brief_at(project: &str) -> R<PathBuf> {+ let path = Path::new(project);+ let brief_path = if path.is_dir() {+ // from anywhere inside a project: the nearest folder up with a brief.ts or a .raea/project+ let dir = path.canonicalize().ok().and_then(|d| d.ancestors().find(|a| a.join("brief.ts").is_file() || a.join(".raea/project").is_file()).map(Path::to_path_buf));+ dir.unwrap_or_else(|| path.to_path_buf()).join("brief.ts")+ } else {+ path.to_path_buf()+ };+ if !brief_path.is_file() {+ return Err(format!("no brief at {}: a project starts as brief.ts (`export default brief({{ title: ... }})` from \"raea/brief\")", brief_path.display()));+ }+ Ok(brief_path)+}++/// The sections of `raea context` after its head, in reading order.+#[allow(clippy::too_many_arguments)]+fn context_body(out: &mut String, dir: &Path, taste_dir: Option<PathBuf>, modes: &[String], brief_path: &Path, brief: String, subs: Vec<(PathBuf, String)>, look: Option<String>) {let mut section = |name: String, body: String| out.push_str(&format!("\n\n===== {name} =====\n\n{}\n", body.trim_end()));- // the person's taste: always taste.brief, then each kind its modes need, once- match &taste_dir {- Some(t) if t.join("taste.brief").is_file() => {- section(format!("TASTE {}", t.join("taste.brief").display()), std::fs::read_to_string(t.join("taste.brief")).unwrap_or_default());+ // the person's taste: always taste.ts, then each kind its modes need, once+ match taste_dir.as_deref().and_then(|t| spec::taste_file(t, "taste").map(|f| (t, f))) {+ Some((t, (p, text))) => {+ section(format!("TASTE {}", p.display()), text);let mut kinds: Vec<&str> = Vec::new();- for m in &modes {+ for m in modes {for k in taste_kinds(m) {if !kinds.contains(k) {kinds.push(k);@@ -140,20 +119,27 @@ pub fn context(project: Option<&str>) -> R<String> {}}for k in kinds {- let p = t.join(format!("{k}.brief"));- if let Ok(text) = std::fs::read_to_string(&p) {+ if let Some((p, text)) = spec::taste_file(t, k) {section(format!("TASTE {}", p.display()), text);}}}- _ => section("TASTE".into(), "(no taste yet: ~/.raea/taste/taste.brief holds the person's standing corrections)".into()),+ None => section("TASTE".into(), "(no taste yet: ~/.raea/taste/taste.ts holds the person's standing corrections)".into()),+ }+ // the workspace's house rules, which every project in it follows (docs/projects.feature)+ if let Some((p, text)) = raea_app_workspace::up(&dir, ".raea/workspace").and_then(|ws| spec::taste_file(&ws, "taste")) {+ section(format!("WORKSPACE TASTE {}", p.display()), text);+ }+ // the workspace's controllers, with this project's overrides: its settings and workflows, which the work follows+ if let Some(text) = raea_app_workspace::summary(&dir, spec::spec_json) {+ section("CONTROLLERS (raea controller ls; a project's own values marked)".into(), text);}section(format!("BRIEF {}", brief_path.display()), brief.clone());for (p, t) in &subs {- section(format!("BRIEF {}", p.display()), t.clone());+ section(format!("{} {}", if p.to_string_lossy().contains("script") { "SCRIPT" } else { "BRIEF" }, p.display()), t.clone());}// the look: the brief's own section, and the brand's tokens when the project has them- let mut look = brief_section(&brief, "look").unwrap_or_else(|| "(the brief has no ## Look yet)".into());+ let mut look = look.unwrap_or_else(|| "(the brief has no look yet)".into());if let Ok(css) = std::fs::read_to_string(dir.join("brand/brand.css")) {look.push_str(&format!("\n\nbrand/brand.css:\n{css}"));}@@ -163,12 +149,11 @@ pub fn context(project: Option<&str>) -> R<String> {if let Ok(t) = std::fs::read_to_string(craft.join("floor.md")) {section(format!("GUIDE craft floor ({})", craft.join("floor.md").display()), t);}- for m in &modes {+ for m in modes {let p = craft.join("modes").join(format!("{m}.md"));match std::fs::read_to_string(&p) {Ok(t) => section(format!("GUIDE mode {m} ({})", p.display()), t),Err(_) => section(format!("GUIDE mode {m}"), format!("(raea has no guide for the mode {m:?} yet)")),}}- Ok(out)}diff --git a/engine/cli/src/index.ts b/engine/cli/src/index.tsindex dcd805fb..110e40ab 100644--- a/engine/cli/src/index.ts+++ b/engine/cli/src/index.ts@@ -4,6 +4,7 @@// (native.ts answers it), and every other verb is the engine's own command line (`engine`: the native `raea`), so there// is one `raea`, and its help is the native one. Every command prints what a person would read; files hold the rest.import { REGISTRY, TEMPLATE } from "./registry.gen";+import { FEATURE_DIRS, featureLayout } from "./layout";/** The host's answer to an op (src/native.ts answers shape, cut, frame and brand). Throws when there's no host. */export type Host = (op: string, args: Record<string, unknown>) => any;@@ -20,6 +21,8 @@ type Fs = {};type Ctx = { cwd: string; fs: Fs };const out = (stdout: string, exitCode = 0, stderr = "") => ({ stdout, stderr, exitCode });+// `raea library` (library.ts), kept apart from the imports above+import { libraryVerb } from "./library";function flag(args: string[], name: string): string | undefined {const i = args.indexOf(name);@@ -88,8 +91,8 @@ eyes 38% down as the speaker moves; an objectPosition or transform turns it off)<Img src>. Media files import as modules: import take from"./media/x.mov". Sound: music in Tone.js (import * as Tone from "raea/tone"): instruments in a Tone.Samplerplaying a Part or Sequence, the instrument's notes from Tone.tokensynth("a warm upright bass", ["C2", "C3", "C4"]) or a-sample library (\`raea sounds\`); sao("prompt", {seconds}) for an effect, as an <Audio src>; fish("words") for-narration. All local but fish. <Mix lufs ceiling> masters the sound.+sample library (\`raea sounds\`); sao("prompt", {seconds}) for an effect, as an <Audio src>; narration+is <Speech text start> from raea/speech (Pocket TTS). All of it local. <Mix lufs ceiling> masters the sound.Words: useWords() -> [{text, from, to}] (frames, the cuts' words), word("phrase") -> the frame it's said,findPhrase(words, "phrase", {occurrence, edge: "start" | "end"}).Placement: <Region name="top" | "bottom" | "center" | "auto" | "full"> keeps a part in a band clear of the face and@@ -138,6 +141,14 @@ export function raeaHandler(host?: Host, engine?: Engine) {made.push(name);};const shape = ask("shape", {}) as { width: number; height: number; fps: number };+ // by feature, as a Bevy project is (S5a): opt-in until it's the default+ if (args.includes("--layout") && args[args.indexOf("--layout") + 1] !== "feature") return out("", 2, "raea init [--layout feature]\n");+ if (args.includes("--layout")) {+ for (const d of FEATURE_DIRS) await c.fs.mkdir(p(d), { recursive: true });+ const name = c.cwd.replace(/\/$/, "").split("/").pop() || "project";+ for (const [f, body] of Object.entries(featureLayout(name, shape))) await put(f, body);+ return out(made.length ? `made ${made.join(", ")}; render it with raea render src/main.tsx\n` : "nothing to make: the project's files are here\n");+ }await c.fs.mkdir(p("components"), { recursive: true });await put("edit.tsx", TEMPLATE["edit.tsx"]);await put("cuts.ts", cutsModule([], shape));@@ -221,6 +232,8 @@ export function raeaHandler(host?: Host, engine?: Engine) {if (!q) return out("", 2, "raea brand DOMAIN|URL (stripe.com, or the site's URL: read on this machine)\n");return out(text(ask("brand", { brand: q })));}+ case "library":+ return out(libraryVerb(ask, args.slice(1), (globalThis as { process?: { env: Record<string, string | undefined> } }).process?.env ?? {}));default:return await native();}diff --git a/engine/cli/src/layout.ts b/engine/cli/src/layout.tsnew file mode 100644index 00000000..e2a9f2ea--- /dev/null+++ b/engine/cli/src/layout.ts@@ -0,0 +1,78 @@+// `raea init --layout feature`: an object's folder laid out as bevy_new_2d's template is, by feature (docs/sdk.feature+// S5a). A video is an App like a game: main.tsx registers its Composition, each feature (here its title) is one file+// with its components, shots are scenes in Sequences, and files sit in assets/, where staticFile reads them.++export interface Shape { width: number; height: number; fps: number }++/** The folders it makes, empty ones included: assets/ and src/'s screens/, shots/ and ui/. */+export const FEATURE_DIRS = ["assets", "src", "src/screens", "src/shots", "src/ui"];++/** Its files by path, for a project called `name`. */+export function featureLayout(name: string, shape: Shape): Record<string, string> {+ const { width, height, fps } = shape;+ return {+ "space.json": JSON.stringify({ name, kind: "video" }, null, 2) + "\n",+ "package.json": JSON.stringify({ name, private: true, raea: { plugins: [] } }, null, 2) + "\n",+ "src/main.tsx": `// The App: its plugins and its root. A video registers its Composition here; its shots play in Sequences.+import { AbsoluteFill, Composition, Sequence, registerRoot } from "raea";+import { Opening } from "./shots/opening";+import { Title } from "./title";++const FPS = ${fps};++function Main() {+ return (+ <AbsoluteFill style={{ background: "#101418" }}>+ <Sequence from={0} durationInFrames={FPS * 3}>+ <Opening />+ </Sequence>+ <Title text="${name}" from={FPS / 2} />+ </AbsoluteFill>+ );+}++registerRoot(() => <Composition id="main" component={Main} width={${width}} height={${height}} fps={FPS} durationInFrames={FPS * 3} />);+`,+ "src/title.tsx": `// A feature: its components together in one file. A feature with work in the App each frame (systems, resources)+// also exports its plugin, definePlugin({ name, build(app) }) from "raea/app"; this one draws only, so it has none.+import { interpolate, useCurrentFrame } from "raea";++export function Title({ text, from }: { text: string; from: number }) {+ const f = useCurrentFrame();+ const shown = interpolate(f, [from, from + 12], [0, 1], { extrapolateLeft: "clamp", extrapolateRight: "clamp" });+ return (+ <div style={{ position: "absolute", left: 0, right: 0, bottom: "12%", textAlign: "center", fontFamily: "Inter", fontWeight: 800, fontSize: ${Math.round(Math.min(width, height) / 12)}, color: "#ffffff", opacity: shown }}>+ {text}+ </div>+ );+}+`,+ "src/shots/opening.tsx": `// A shot: a scene component, one time range of the cut (main.tsx places it in a Sequence).+import { AbsoluteFill, interpolate, useCurrentFrame } from "raea";++export function Opening() {+ const f = useCurrentFrame();+ const x = interpolate(f, [0, 60], [-20, 20], { extrapolateRight: "clamp" });+ return (+ <AbsoluteFill style={{ alignItems: "center", justifyContent: "center" }}>+ <div style={{ width: "30%", aspectRatio: "1", borderRadius: "50%", background: "#ff7a1a", transform: \`translateX(\${x}%)\` }} />+ </AbsoluteFill>+ );+}+`,+ "AGENTS.md": `# This project++A video, laid out by feature as a Bevy project is (raea init --layout feature):++- space.json: its name and kind. package.json: raea.plugins, the Bevy, Blitz and raea plugins it uses.+- assets/: its files. \`staticFile("x.png")\` reads assets/x.png (a media/ folder beside it is read first).+- src/main.tsx: the App, rendered with \`raea render src/main.tsx\`. It registers the Composition.+- src/<feature>.tsx: one feature each (title, captions, music), its components together; one with work in the App+ each frame also exports its plugin (definePlugin from "raea/app").+- src/shots/: the shots, each a scene component placed in a Sequence. src/screens/: one file per top-level state.+ src/ui/: page parts shared between features.++Never a components/ folder: a feature file holds a feature's components by name.+`,+ };+}diff --git a/engine/cli/src/lib.rs b/engine/cli/src/lib.rsindex 27ce69ee..4c66f3d2 100644--- a/engine/cli/src/lib.rs+++ b/engine/cli/src/lib.rs@@ -8,10 +8,13 @@ use raea_runtime_react::scene::{self as motion, *};use raea_runtime_export::{self as export, *};use raea_app_tools as tools;use serde_json::json;+use raea_neural as neural;mod cli;mod guide;mod refused;+mod skill;+mod spec;mod tests;mod usage;mod verbs;diff --git a/engine/cli/src/library.ts b/engine/cli/src/library.tsnew file mode 100644index 00000000..1e164873--- /dev/null+++ b/engine/cli/src/library.ts@@ -0,0 +1,106 @@+// `raea library`: an agent's way into the person's libraries (raea docs/libraries.feature), through the raea app's+// host (apps/app host/library/service.ts, asked as host op "library"). An agent can list libraries, make one, ask to+// add a folder or drive (the person allows it in the app; a folder they already granted is added at once), search by+// meaning, list files and tag them. Every command prints what a person would read.++type Ask = (op: string, args: Record<string, unknown>) => any;+type Lib = { id: string; name: string; files: number; indexed: number; sources: { kind: string; label: string; here?: boolean; online: boolean }[] };++export const LIBRARY_USAGE = `raea library (the workspace's libraries, their sources, and folders waiting for the person)+raea library new NAME+raea library add LIBRARY PATH (a folder or a drive: the person allows it in the app unless it's already granted)+raea library search "WORDS" [--library LIBRARY] [--kind video|image|audio] [--limit N] [--sound] (--sound: a described sound, ranked by sound alone)+raea library files LIBRARY+raea library tag SHA256 TAG[,TAG...]+raea library status | raea library scan+LIBRARY is a library's name or id.+`;++const flagOf = (args: string[], name: string) => {+ const i = args.indexOf(name);+ return i >= 0 ? args[i + 1] : undefined;+};+const t = (s: number) => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, "0")}`;++export function libraryVerb(ask: Ask, args: string[], env: Record<string, string | undefined>): string {+ const workspace = env.RAEA_WORKSPACE ?? "w-default";+ const by = env.RAEA_LIBRARY_BY ?? `agent:${env.RAEA_AGENT ?? "cli"}`;+ const q = (op: string, a: Record<string, unknown> = {}) => ask("library", { op, ...a });+ const all = (): Lib[] => q("list", { workspace }).libraries;+ const find = (key?: string): Lib => {+ if (!key) throw new Error(`which library?\n${LIBRARY_USAGE}`);+ const ls = all();+ const l = ls.find((x) => x.id === key) ?? ls.find((x) => x.name.toLowerCase() === key.toLowerCase());+ if (!l) throw new Error(`no library "${key}"; there are: ${ls.map((x) => x.name).join(", ") || "none yet (raea library new NAME)"}`);+ return l;+ };+ const [sub, ...rest] = args;+ switch (sub) {+ case undefined:+ case "list": {+ const ls = all();+ const waiting: { library: string; path: string; by: string }[] = q("requests").requests;+ if (!ls.length) return "No libraries yet. raea library new NAME makes one.\n";+ return (+ ls+ .map((l) => {+ const src = l.sources.map((s) => ` ${s.kind} ${s.label}${s.here ? "" : s.online ? " (another machine)" : " (offline)"}`);+ const ask = waiting.filter((w) => w.library === l.id).map((w) => ` waiting for the person: ${w.path} (${w.by})`);+ return [`${l.name} [${l.id}] ${l.files} files, ${l.indexed} indexed`, ...src, ...ask].join("\n");+ })+ .join("\n") + "\n"+ );+ }+ case "new": {+ // on this Mac unless --cloud (Pro: searchable from the web and other devices)+ const name = rest.filter((w) => w !== "--cloud").join(" ").trim();+ if (!name) throw new Error("raea library new NAME [--cloud]");+ const l = q("create", { workspace, name, by, where: rest.includes("--cloud") ? "cloud" : "local" });+ return `made ${l.name} [${l.id}]${l.id.startsWith("loc_") ? " on this Mac" : " in raea cloud"}. raea library add "${l.name}" PATH asks to add a folder or drive.\n`;+ }+ case "add": {+ const [key, path] = rest;+ if (!path) throw new Error("raea library add LIBRARY PATH");+ const l = find(key);+ const r = q("add", { library: l.id, path, by });+ return r.state === "needs-approval"+ ? `asked: ${r.path} waits for the person to allow it in the raea app (Libraries > ${l.name}). Its files are indexed once they do.\n`+ : `added ${r.label} to ${l.name}; its files are being scanned and indexed on this machine.\n`;+ }+ case "search": {+ // --sound takes no value; the other flags take the word after them+ const valued = (a?: string) => !!a?.startsWith("--") && a !== "--sound";+ const words = rest.filter((a, i) => !a.startsWith("--") && !valued(rest[i - 1])).join(" ");+ if (!words) throw new Error('raea library search "WORDS"');+ const lib = flagOf(rest, "--library");+ const r = q("search", { workspace, words, libraries: lib ? [find(lib).id] : undefined, kind: flagOf(rest, "--kind"), limit: Number(flagOf(rest, "--limit")) || 10, sound: rest.includes("--sound") });+ if (!r.hits.length) return `nothing found for "${words}"\n`;+ const lines = r.hits.map((h: any) => {+ const span = h.t1 > 0 ? ` ${t(h.t0)}-${t(h.t1)}` : "";+ const where = h.local ?? (h.file?.locations?.[0] ? `${h.file.locations[0].label}/${h.file.locations[0].path} (not on this machine)` : h.sha256);+ return `${where}${span} (${h.matched.join(", ")})${h.text ? ` "${h.text.slice(0, 80)}"` : ""}`;+ });+ const note = r.by === "words" ? (r.rebuilding ? "(by words only: the cloud index is being rebuilt for a new model)\n" : "(by words only: the search model is still loading)\n") : r.by === "sound" ? "(by sound only)\n" : "";+ return `${note}${lines.join("\n")}\n`;+ }+ case "files": {+ const l = find(rest[0]);+ const r = q("files", { library: l.id });+ return r.files.map((f: any) => `${f.path} ${f.kind} ${f.sha256.slice(0, 12)}${f.labels.length ? ` labels: ${f.labels.join(", ")}` : ""}${f.tags.length ? ` tags: ${f.tags.join(", ")}` : ""}`).join("\n") + (r.next ? "\n(more: the app lists the rest)\n" : "\n");+ }+ case "tag": {+ const [sha, tags] = rest;+ if (!tags) throw new Error("raea library tag SHA256 TAG[,TAG...]");+ const r = q("tag", { sha256: sha, tags: tags.split(",").map((x) => x.trim()).filter(Boolean) });+ return `tagged ${sha.slice(0, 12)}: ${r.tags.join(", ")}\n`;+ }+ case "scan":+ return `${q("scan").queued} new files to index\n`;+ case "status": {+ const s = q("status");+ return `model ${s.model.phase}; ${s.indexing ? `indexing ${s.indexing.file} (${s.indexing.step}), ` : ""}${s.queue} waiting, ${s.done} done, ${s.failed} failed${s.errors[0] ? `\nlast error: ${s.errors[0].file}: ${s.errors[0].error}` : ""}\n`;+ }+ default:+ throw new Error(LIBRARY_USAGE);+ }+}diff --git a/engine/cli/src/main.rs b/engine/cli/src/main.rsindex 80252cf5..006703ce 100644--- a/engine/cli/src/main.rs+++ b/engine/cli/src/main.rs@@ -13,7 +13,8 @@ fn main() {let args: Vec<String> = std::env::args().skip(1).collect();let code = match args.first().map(String::as_str) {// `check VIDEO.mp4 …`: the floor's measurable lines on an export, ranked P0-P3- Some("check") => raea_app_check::cli(&args[1..]),+ // (with --taste or --quick, through the engine, which evaluates the taste.ts files or renders stills: raea_cli's `check`)+ Some("check") if !args.iter().any(|a| a == "--taste" || a == "--quick") => 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/native.ts b/engine/cli/src/native.tsindex 0fd425d3..c98b8def 100644--- a/engine/cli/src/native.ts+++ b/engine/cli/src/native.ts@@ -1,6 +1,6 @@// The agent shell's own verbs (init ...) on the native `raea`, which runs this file on its JavaScriptCore with Node's core// (runtime/react/src/scene.rs shell(), raea_native::js::run_node), so each verb has one source: this package's handler.-// The host's ops it needs are answered here, one more with each verb ported (docs/agent-context.md); the rest refuse.+// The host's ops it needs are answered here, one more with each verb ported (docs/agent-surfaces.md); the rest refuse.//// native.ts RAEA VERB ARGS... RAEA: the native raea's path, for the engine's own verbsimport { spawnSync } from "node:child_process";@@ -81,14 +81,24 @@ function words(take: string, hear = false): Word[] {.map((w) => ({ text: w.text.trim(), from: w.start_ms / 1000, to: w.end_ms / 1000 }));}+/** A tool a clean Mac lacks, found or installed once by raea's tools/ensure.sh (docs/app.feature AP6), which sits in+ * share/raea/tools beside a release's bin/raea, or in the tree a built raea is in; the bare name if there's none */+function ensure(name: string): string {+ const real = realpathSync(raea);+ const script = [`${dirname(real)}/../share/raea/tools/ensure.sh`, `${dirname(real)}/../../tools/ensure.sh`].find(existsSync);+ if (!script) return name;+ const r = spawnSync("bash", [script, name], { encoding: "utf8", stdio: ["ignore", "pipe", "inherit"] });+ return r.status === 0 && r.stdout.trim() ? r.stdout.trim() : name;+}+function hearTake(take: string, out: string) {const dir = mkdtempSync(`${tmpdir()}/raea-hear-`);try {const wav = `${dir}/take.wav`;const a = spawnSync(raea, ["media", "audio", at(take), "--rate", "16000", "--mono", "-o", wav], { encoding: "utf8" });if (a.status !== 0) throw new Error(`no sound to transcribe in ${take}: ${(a.stdout + a.stderr).trim()}`);- const p = spawnSync("parakeet-mlx", [wav, "--output-format", "json", "--output-dir", dir], { encoding: "utf8" });- if (p.status !== 0) throw new Error(`transcribing ${take} needs parakeet-mlx (pip install parakeet-mlx), or cut it by time: --at A-B`);+ const p = spawnSync(ensure("parakeet-mlx"), [wav, "--output-format", "json", "--output-dir", dir], { encoding: "utf8" });+ if (p.status !== 0) throw new Error(`transcribing ${take} needs parakeet-mlx (tools/ensure.sh installs it: ${(p.stderr ?? "").trim().split("\n").pop()}), or cut it by time: --at A-B`);const heard = JSON.parse(readFileSync(`${dir}/take.json`, "utf8")) as { sentences: { tokens: { text: string; start: number; end: number }[] }[] };const ws = heard.sentences.flatMap((s) => wordsOf(s.tokens)).map((w) => ({ text: w.text, start_ms: Math.round(w.start * 1000), end_ms: Math.round(w.end * 1000) }));writeFileSync(out, JSON.stringify(ws) + "\n");@@ -353,6 +363,20 @@ function brand(a: { brand: string }): string {return kit.said;}+/** An op of the feed host's libraries (apps/app host/library/service.ts): POST $RAEA_FEED_HOST/host/library. The feed+ * sets RAEA_FEED_HOST for the agents it starts; elsewhere it's given by hand. */+function library(a: Record<string, unknown>): unknown {+ const at = process.env.RAEA_FEED_HOST;+ if (!at) throw new Error("libraries live in the raea app: run this from an agent the app started, or set RAEA_FEED_HOST to the app's address");+ const r = spawnSync("curl", ["-sS", "--max-time", "120", "-w", "\n%{http_code}", "-H", "content-type: application/json", "--data-binary", "@-", `${at.replace(/\/$/, "")}/host/library`], { input: JSON.stringify(a), encoding: "utf8", maxBuffer: 64 << 20 });+ const text = r.stdout ?? "";+ const cut = text.lastIndexOf("\n");+ const [body, code] = [text.slice(0, cut), Number(text.slice(cut + 1))];+ if (r.status !== 0) throw new Error(`the raea app at ${at} didn't answer: ${(r.stderr ?? "").trim()}`);+ if (!(code >= 200 && code < 300)) throw new Error(body.trim() || `the raea app said ${code}`);+ return JSON.parse(body);+}+const host: Host = (op, a) => {switch (op) {case "shape":@@ -363,6 +387,8 @@ const host: Host = (op, a) => {return cut(a as Parameters<typeof cut>[0]);case "brand":return brand(a as Parameters<typeof brand>[0]);+ case "library":+ return library(a);default:throw new Error(`raea: this step (${op}) isn't in the native raea yet`);}diff --git a/engine/cli/src/skill.rs b/engine/cli/src/skill.rsnew file mode 100644index 00000000..203e0cf6--- /dev/null+++ b/engine/cli/src/skill.rs@@ -0,0 +1,179 @@+//! `raea skill` and `raea skills install` (docs/skills.feature SK6): the agent skills this raea ships, version-matched.+//! An agent can hold a skill from an older or newer install than its `raea`; the copy's front matter names the version it+//! came with (`version:`, stamped by tools/release.sh and by `skills install`), and when that differs from+//! `raea --version` the agent reads `raea skill` instead.+use super::*;++pub const USAGE: &str = "raea skill [NAME] [--reference cli|feed|files|sdk] | raea skills install --agent claude|codex|kimi|gemini [--pin MOVE]... [--no-mcp] [--no-hooks] (the agent skill this raea ships, for its version, which raea --version prints: an agent whose copy names another version reads this; install puts raea's skills where that agent reads skills, adds the blender MCP server unless --no-mcp, makes each --pin MOVE a /MOVE of its own, and for claude adds the quick-check hook unless --no-hooks)";++/// Where each agent reads a person's skills, one folder per skill holding SKILL.md. Checked by hand on 11-05:+/// claude: ~/.claude/skills (Claude Code's docs); codex: ~/.agents/skills (developers.openai.com/codex/skills, the user+/// scope; older builds read ~/.codex/skills); kimi: $KIMI_CODE_HOME/skills, else ~/.kimi-code/skills (kimi 2.3.3's own+/// binary; it also reads ~/.agents/skills and ~/.claude/skills); gemini: ~/.gemini/skills (geminicli.com/docs/cli/skills).+fn target(agent: &str) -> R<PathBuf> {+ let home = tools::agent_mcp::user_home()?;+ Ok(match agent {+ "claude" => home.join(".claude/skills"),+ "codex" => home.join(".agents/skills"),+ "kimi" => std::env::var_os("KIMI_CODE_HOME").filter(|v| !v.is_empty()).map(PathBuf::from).unwrap_or_else(|| home.join(".kimi-code")).join("skills"),+ "gemini" => home.join(".gemini/skills"),+ a => return Err(format!("no agent {a:?}: claude, codex, kimi or gemini")),+ })+}++/// Each agent and the folder it reads skills from, for `raea doctor` (an agent with no folder is skipped).+pub fn agents() -> Vec<(&'static str, PathBuf)> {+ ["claude", "codex", "kimi", "gemini"].into_iter().filter_map(|a| target(a).ok().map(|t| (a, t))).collect()+}++/// `raea doctor [--fix] [DIR]` (SK10): what doesn't match this raea, an agent's skill reinstalled by --fix.+pub fn doctor(args: &[String]) -> R<String> {+ let again = |agent: &str| install(&["install".into(), "--agent".into(), agent.into(), "--no-mcp".into()]);+ raea_app_workspace::doctor::doctor(args, &agents(), &version(), &again)+}++/// This raea's version: the release's (share/raea/VERSION), or the crate's for a build from a checkout.+pub fn version() -> String {+ std::fs::read_to_string(raea_io_home::home().join("VERSION"))+ .ok()+ .map(|v| v.trim().to_string())+ .filter(|v| !v.is_empty())+ .unwrap_or_else(|| format!("{}-checkout", env!("CARGO_PKG_VERSION")))+}++/// The skills raea ships: an install's share/raea/skills, or the checkout's sdk/skills.+fn shipped() -> R<PathBuf> {+ let home = raea_io_home::home();+ ["skills", "sdk/skills"].iter().map(|d| home.join(d)).find(|d| d.join("raea/SKILL.md").is_file()).ok_or_else(|| format!("no skills under {}: reinstall raea (curl -fsSL https://raea.io/install | sh)", home.display()))+}++/// SKILL.md with `version: V` in its front matter (replacing one that's there), so a copy says which raea it came with.+pub fn stamp(text: &str, v: &str) -> String {+ let Some(rest) = text.strip_prefix("---\n") else { return text.to_string() };+ let Some(end) = rest.find("\n---\n") else { return text.to_string() };+ let lines: Vec<&str> = rest[..end].lines().filter(|l| !l.starts_with("version:")).collect();+ format!("---\n{}\nversion: {v}\n---\n{}", lines.join("\n"), &rest[end + 5..])+}++/// `raea skill [NAME] [--reference cli|feed|files|sdk]`: the shipped skill's text, or one of its references.+pub fn skill(args: &[String]) -> R<String> {+ let name = args.first().filter(|a| !a.starts_with("--")).map(String::as_str).unwrap_or("raea");+ let reference = args.iter().position(|a| a == "--reference").map(|i| args.get(i + 1).cloned().ok_or("--reference takes cli, feed, files or sdk"));+ let ok = |s: &str| !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '-');+ if !ok(name) {+ return Err(format!("no skill {name:?}"));+ }+ let dir = shipped()?.join(name);+ if !dir.join("SKILL.md").is_file() {+ return Err(format!("no skill {name:?}: {}", installed_names()?.join(", ")));+ }+ match reference {+ Some(r) => {+ let r = r?;+ let path = dir.join("reference").join(format!("{r}.md"));+ if !ok(&r) || !path.is_file() {+ return Err(format!("no reference {r:?} in {name}: cli, feed, files or sdk"));+ }+ std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))+ }+ None => Ok(stamp(&std::fs::read_to_string(dir.join("SKILL.md")).map_err(|e| e.to_string())?, &version())),+ }+}++fn installed_names() -> R<Vec<String>> {+ let mut v = Vec::new();+ for e in std::fs::read_dir(shipped()?).map_err(|e| e.to_string())?.flatten() {+ // raea-work is internal (work.raea.io's pages): a checkout has it, a release doesn't ship it+ let name = e.file_name().to_string_lossy().into_owned();+ if name != "raea-work" && e.path().join("SKILL.md").is_file() {+ v.push(name);+ }+ }+ v.sort();+ Ok(v)+}++/// Copies a folder, following links (raea-bevy's topic files link to the craft guides in a checkout).+fn copy(from: &Path, to: &Path) -> R<()> {+ std::fs::create_dir_all(to).map_err(|e| format!("{}: {e}", to.display()))?;+ for e in std::fs::read_dir(from).map_err(|e| e.to_string())?.flatten() {+ let (src, dst) = (e.path(), to.join(e.file_name()));+ if src.is_dir() {+ copy(&src, &dst)?;+ } else if src.is_file() {+ std::fs::copy(&src, &dst).map_err(|e| format!("{}: {e}", src.display()))?;+ }+ }+ Ok(())+}++/// `raea skills install --agent claude|codex|kimi|gemini`: raea's skills, stamped with this version, where that agent+/// reads them; each replaces the copy that was there.+pub fn install(args: &[String]) -> R<String> {+ if args.first().map(String::as_str) != Some("install") {+ return Err(format!("usage: {USAGE}"));+ }+ let agent = args.iter().position(|a| a == "--agent").and_then(|i| args.get(i + 1)).ok_or("which agent: --agent claude|codex|kimi|gemini")?;+ let to = target(agent)?;+ let (from, v) = (shipped()?, version());+ let mut out = String::new();+ for name in installed_names()? {+ let dst = to.join(&name);+ if dst.exists() {+ std::fs::remove_dir_all(&dst).map_err(|e| format!("{}: {e}", dst.display()))?;+ }+ copy(&from.join(&name), &dst)?;+ let md = dst.join("SKILL.md");+ let text = std::fs::read_to_string(&md).map_err(|e| e.to_string())?;+ std::fs::write(&md, stamp(&text, &v)).map_err(|e| e.to_string())?;+ out += &format!("{}: {name} {v}\n", dst.display());+ }+ // pinned moves (SK10): a skill per move, so an agent's /quieter loads the one guide+ for (i, a) in args.iter().enumerate() {+ if a == "--pin" {+ let m = args.get(i + 1).ok_or("--pin takes a move: quieter, bolder, layout, adapt...")?;+ out += &tools::agent_mcp::pin(&to, m, &v)?;+ }+ }+ // Claude Code's hook: the quick check after a composition is saved (SK10); --no-hooks leaves its settings alone+ if agent == "claude" && !args.iter().any(|a| a == "--no-hooks") {+ let settings = target("claude")?.with_file_name("settings.json");+ out += &format!("{}: hook `raea hook claude` {}\n", settings.display(), if tools::agent_mcp::claude_hook(&settings)? { "added" } else { "already there" });+ }+ // the MCP servers raea offers (SK11): blender, for a running Blender; --no-mcp leaves the agent's servers alone+ if !args.iter().any(|a| a == "--no-mcp") {+ out += &tools::agent_mcp::offer(agent)?;+ out += "\n";+ }+ Ok(format!("{out}{agent} reads them in its next session"))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn stamp_puts_one_version_in_the_front_matter() {+ let md = "---\nname: raea\nversion: 0.0.1\ndescription: d\n---\n\n# raea\n";+ assert_eq!(stamp(md, "0.1.0-canary.3"), "---\nname: raea\ndescription: d\nversion: 0.1.0-canary.3\n---\n\n# raea\n");+ assert_eq!(stamp("# no front matter\n", "1"), "# no front matter\n");+ }++ #[test]+ fn the_skill_and_its_references_come_from_this_raea() {+ let core = skill(&[]).unwrap();+ assert!(core.starts_with("---\nname: raea\n") && core.contains(&format!("\nversion: {}\n---\n", version())), "{}", &core[..200.min(core.len())]);+ assert!(skill(&["--reference".into(), "cli".into()]).unwrap().contains("raea render"));+ assert!(skill(&["raea-bevy".into()]).is_ok());+ assert!(skill(&["../x".into()]).is_err());+ assert!(skill(&["--reference".into(), "../../x".into()]).is_err());+ }++ #[test]+ fn install_targets_each_agents_folder() {+ assert!(target("claude").unwrap().ends_with(".claude/skills"));+ assert!(target("codex").unwrap().ends_with(".agents/skills"));+ assert!(target("gemini").unwrap().ends_with(".gemini/skills"));+ assert!(target("cursor").is_err());+ }+}diff --git a/engine/cli/src/spec.rs b/engine/cli/src/spec.rsnew file mode 100644index 00000000..70931024--- /dev/null+++ b/engine/cli/src/spec.rs@@ -0,0 +1,128 @@+//! Specs written in TypeScript (docs/handoff/authoring.md, docs/projects.feature PJ0): brief.ts, script.ts, taste.ts+//! and a workspace's controllers. A spec is a module whose default export is data; the engine evaluates it headless+//! (bundle_module with PRINT_DEFAULT, run_bundle) and Rust reads the JSON against the schema in core/brief, so tsc's errors come first and+//! these come second, naming the field.+use super::*;+use raea_core_brief as schema;+use serde::de::DeserializeOwned;+use std::sync::atomic::Ordering;++/// The default export of a spec module, as the JSON it evaluates to.+pub fn spec_json(ts: &Path) -> R<String> {+ let ts = ts.canonicalize().map_err(|e| format!("{}: {e}", ts.display()))?;+ let out = std::env::temp_dir().join(format!("raea-spec-{}.js", std::process::id()));+ bundle_module(&ts, &out, PRINT_DEFAULT)?;+ // the JSON is ours to read, not the person's to see: the run prints nothing to the terminal+ let echo = raea_runtime_react::native::ECHO.swap(false, Ordering::Relaxed);+ let ran = run_bundle(&out, 60.0);+ raea_runtime_react::native::ECHO.store(echo, Ordering::Relaxed);+ let _ = std::fs::remove_file(&out);+ let (code, printed) = ran?;+ let last = printed.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("").to_string();+ if code != 0 {+ return Err(format!("{}: {}", ts.display(), last.strip_prefix("error: ").unwrap_or(&last)));+ }+ Ok(last)+}++/// A spec read against its schema; the error names the file and the field.+pub fn read_spec<T: DeserializeOwned>(ts: &Path) -> R<T> {+ let name = ts.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();+ schema::read(&name, &spec_json(ts)?)+}++/// What `raea context` reads from a project's brief.ts.+pub struct Loaded {+ pub path: PathBuf,+ /// what the agent reads: the file as written, with what's missing from it after+ pub text: String,+ pub title: String,+ pub modes: Vec<String>,+ /// deliverables' own briefs and the project's script, each (path, text)+ pub more: Vec<(PathBuf, String)>,+ pub look: Option<String>,+ /// what the brief still needs (schema::brief::doctor), empty when it's shaped+ pub missing: Vec<String>,+}++/// A project's brief.ts: checked against the Brief schema, its modes, its deliverables' briefs and its script.+pub fn load_brief_ts(path: &Path) -> R<Loaded> {+ let brief: schema::Brief = read_spec(path)?;+ let dir = path.parent().unwrap_or(Path::new(".")).to_path_buf();+ let mut text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;+ let missing = schema::brief::doctor(&brief);+ if !missing.is_empty() {+ text.push_str(&format!("\n\nWhat the brief still needs:\n{}", missing.iter().map(|m| format!("- {m}")).collect::<Vec<_>>().join("\n")));+ }+ let mut modes: Vec<String> = brief.mode.iter().map(|m| m.trim().to_ascii_lowercase()).filter(|m| !m.is_empty()).collect();+ let mut more = Vec::new();+ let mut files: Vec<String> = brief.deliver.iter().flat_map(|d| [d.brief.clone(), d.script.clone()]).flatten().collect();+ if dir.join("script.ts").is_file() && !files.iter().any(|f| f == "script.ts") {+ files.push("script.ts".into());+ }+ for f in files {+ let p = dir.join(&f);+ let checked = if f.contains("script") { read_spec::<schema::Script>(&p).map(|_| ()) } else { read_spec::<schema::Brief>(&p).map(|b| modes.extend(b.mode)) };+ let body = std::fs::read_to_string(&p).unwrap_or_else(|e| format!("(missing: {e})"));+ more.push((p, match checked {+ Ok(()) => body,+ Err(e) => format!("{body}\n\n(raea can't read it: {e})"),+ }));+ }+ modes.dedup();+ Ok(Loaded { path: path.to_path_buf(), text, title: brief.title.clone(), modes, more, look: brief.look, missing })+}++/// A taste file by name (taste, motion, games...): NAME.ts, checked as Taste.+pub fn taste_file(dir: &Path, name: &str) -> Option<(PathBuf, String)> {+ let ts = dir.join(format!("{name}.ts"));+ let body = std::fs::read_to_string(&ts).ok()?;+ Some(match read_spec::<schema::Taste>(&ts) {+ Ok(_) => (ts, body),+ Err(e) => (ts, format!("{body}\n\n(raea can't read it: {e})")),+ })+}++/// 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 spec FILE.ts [--as KIND]`: the default export as JSON, checked as KIND (by default from the file's name:+/// brief, script, taste or plan in it, controller under controllers/; anything else is checked as Taste, the files in+/// ~/.raea/taste being named for their kind).+pub fn spec_cli(args: &[String]) -> R<String> {+ const USAGE: &str = "usage: raea spec FILE.ts [--as brief|script|taste|plan|controller]";+ let file = args.iter().enumerate().find(|(i, a)| !a.starts_with("--") && (*i == 0 || args[i - 1] != "--as")).map(|(_, a)| PathBuf::from(a)).ok_or(USAGE)?;+ let named = file.to_string_lossy().to_lowercase();+ let kind = args.iter().position(|a| a == "--as").and_then(|i| args.get(i + 1)).cloned().unwrap_or_else(|| {+ let base = file.file_name().map(|n| n.to_string_lossy().to_lowercase()).unwrap_or_default();+ ["brief", "script", "plan"].iter().find(|k| base.contains(*k)).map(|k| k.to_string()).unwrap_or(if named.contains("controllers/") { "controller".into() } else { "taste".into() })+ });+ let json = spec_json(&file)?;+ let name = file.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();+ let value: serde_json::Value = match kind.as_str() {+ "brief" => serde_json::to_value(schema::read::<schema::Brief>(&name, &json)?),+ "script" => serde_json::to_value(schema::read::<schema::Script>(&name, &json)?),+ "taste" => serde_json::to_value(schema::read::<schema::Taste>(&name, &json)?),+ "plan" => serde_json::to_value(schema::read::<schema::Plan>(&name, &json)?),+ "controller" => {+ let raw: serde_json::Value = serde_json::from_str(&json).map_err(|e| format!("{name}: {e}"))?;+ serde_json::to_value(schema::controller::normalize(&raw).map_err(|e| format!("{name}: {e}"))?)+ }+ k => return Err(format!("raea spec can't check a {k:?}: brief, script, taste, plan or controller\n{USAGE}")),+ }+ .map_err(|e| e.to_string())?;+ Ok(value.to_string())+}diff --git a/engine/cli/src/tests.rs b/engine/cli/src/tests.rsindex 66c2656c..f25314fd 100644--- a/engine/cli/src/tests.rs+++ b/engine/cli/src/tests.rs@@ -37,6 +37,20 @@ fn help_lists_every_verb() {}}+#[test]+fn help_json_is_every_listed_verb() {+ // `raea help --json` (tools/skills.sh gen's source): the verbs the help lists, not its prose, each with its flags+ let help = run(&["help".to_string()]).unwrap();+ let j: serde_json::Value = serde_json::from_str(&run(&["help".to_string(), "--json".to_string()]).unwrap()).unwrap();+ let verbs: Vec<&str> = j["verbs"].as_array().unwrap().iter().map(|v| v["verb"].as_str().unwrap()).collect();+ assert_eq!(verbs, verb_list(&help).iter().map(String::as_str).collect::<Vec<_>>());+ assert!(!verbs.contains(&"compositions"), "the help's opening line isn't a verb: {verbs:?}");+ let controller = j["verbs"].as_array().unwrap().iter().find(|v| v["verb"] == "controller").unwrap();+ assert_eq!(controller["args"], 3);+ assert!(controller["flags"].as_array().unwrap().iter().any(|f| f["flag"] == "--by" && f["values"] == 1));+ assert!(j["verbs"].as_array().unwrap().iter().any(|v| v["verb"] == "gen" && v["own_parser"] == true));+}+#[test]fn a_verb_refuses_what_it_doesnt_take() {let help = run(&["help".to_string()]).unwrap();@@ -90,7 +104,7 @@ fn every_flag_a_verb_reads_is_in_the_help() {"--game", "--info", "--selftest", "--no-pointer", // an exported game's own player reads these (game.rs player_main)"--o", // track and splat take "--o" for -o, a slip they forgive"--nope", "--loud", // test fixtures- "--help",+ "--help", "--version", // raea's own, before any verb"--filter", "--bundle-only", "--define", "--alias", "--node-stub", // `raea test`, raea's own conformance runner, unlisted];let lit = regex::Regex::new(r#""(--[a-z0-9][a-z0-9-]*)[="]"#).unwrap();diff --git a/engine/cli/src/usage.rs b/engine/cli/src/usage.rsindex 11350df5..568e2f33 100644--- a/engine/cli/src/usage.rs+++ b/engine/cli/src/usage.rs@@ -139,8 +139,8 @@ pub fn usage_of(help: &str, verb: &str) -> Option<Usage> {/// the ones it takes. None when it is, or when the help doesn't give the verb's usage.pub fn stray(help: &str, args: &[String]) -> Option<String> {let verb = args.first()?;- // physics hands its subverb's arguments to the bake, the goo or the part, which check them- if verb == "physics" {+ // physics hands its subverb's arguments to the bake, the goo or the part, which check them; gen to raea-io-gen's own+ if verb == "physics" || verb == "gen" {return None;}let u = usage_of(help, verb)?;@@ -163,3 +163,53 @@ pub fn stray(help: &str, args: &[String]) -> Option<String> {}None}++/// Every verb the help lists, in its order (each `raea VERB` it names).+pub fn verb_list(help: &str) -> Vec<String> {+ let mut out: Vec<String> = Vec::new();+ for line in help.lines() {+ // a usage line, not the help's prose ("raea: renders … raea compositions")+ let line = line.trim().trim_start_matches("usage:").trim();+ if !line.starts_with("raea ") {+ continue;+ }+ let toks: Vec<&str> = line.split(" (").next().unwrap_or("").split_whitespace().collect();+ for w in toks.windows(2).filter(|w| w[0] == "raea") {+ let v = w[1].trim_end_matches(':');+ if v.chars().all(|c| c.is_ascii_lowercase() || c == '-') && !v.is_empty() && !out.iter().any(|o| o == v) {+ out.push(v.to_string());+ }+ }+ }+ out+}++/// Where a verb runs (docs/agent-surfaces.md section 4): HEADLESS unless it needs the feed's host.+fn access(verb: &str) -> &'static str {+ match verb {+ // the person's libraries live in the raea app's host; a folder an agent adds waits for the person's yes+ "library" => "HOST, then PERSON to add a folder",+ _ => "HEADLESS",+ }+}++/// `raea help --json`: each verb with its usage lines, its flags (with how many values follow each), how many+/// arguments it takes (null: any number), its access tag, and `own_parser` when its own parser checks them (its flags+/// are then its own help's, not these). tools/skills.sh gen writes the CLI reference from it.+pub fn help_json(help: &str) -> serde_json::Value {+ // a verb whose arguments its own parser checks: stray() lets even a flag no verb has through+ let own = |v: &str| stray(help, &[v.to_string(), "--no-such-flag".to_string()]).is_none();+ let rows: Vec<_> = verb_list(help)+ .into_iter()+ .map(|v| match usage_of(help, &v) {+ Some(u) => {+ let mut flags: Vec<_> = u.flags.into_iter().collect();+ flags.sort();+ json!({"verb": v, "usage": u.lines, "flags": flags.into_iter().map(|(f, n)| json!({"flag": f, "values": n})).collect::<Vec<_>>(), "args": u.slots, "access": access(&v), "own_parser": own(&v)})+ }+ // passes its arguments on (media's ffmpeg): its line, unparsed+ None => json!({"verb": v, "usage": help.lines().map(str::trim).filter(|l| l.contains(&format!("raea {v} "))).collect::<Vec<_>>(), "flags": [], "args": null, "access": access(&v), "own_parser": true}),+ })+ .collect();+ json!({"verbs": rows})+}diff --git a/engine/cli/src/verbs.rs b/engine/cli/src/verbs.rsindex cfb9f6a6..f7dd9b7a 100644--- a/engine/cli/src/verbs.rs+++ b/engine/cli/src/verbs.rs@@ -95,8 +95,8 @@ pub fn mezz(args: &[String]) -> R<String> {-/// The agent shell's own verbs (engine/cli/src/index.ts) this binary runs; the rest come one by one (docs/agent-context.md)-pub const SHELL: &[&str] = &["init", "cut", "frame", "part", "brand"];+/// The agent shell's own verbs (engine/cli/src/index.ts) this binary runs; the rest come one by one (docs/agent-surfaces.md)+pub const SHELL: &[&str] = &["init", "cut", "frame", "part", "brand", "library"];/// One of SHELL's verbs: @raea/cli's handler, run by engine/cli/src/native.ts on raea's JavaScriptCore with Node's core, so the/// verb's one source is its TypeScript. native.ts answers the host's ops it needs, and runs this binary for the engine's verbs.diff --git a/engine/neural/Cargo.toml b/engine/neural/Cargo.tomlnew file mode 100644index 00000000..ce899978--- /dev/null+++ b/engine/neural/Cargo.toml@@ -0,0 +1,12 @@+[package]+name = "raea-neural"+version = "0.1.0"+edition = "2024"+license = "FSL-1.1-ALv2"+publish = false+description = "raea neural: DLSS 5 neural rendering on a `render --aov` folder through the founder's own MLX-DLSS (docs/raytracing.feature RT2)"++[dependencies]+image = { version = "0.25", default-features = false, features = ["png"] }+# the CLI's flag reader and result type+raea-runtime-bundle = { path = "../../runtime/bundle" }diff --git a/engine/neural/src/lib.rs b/engine/neural/src/lib.rsnew file mode 100644index 00000000..bad830ba--- /dev/null+++ b/engine/neural/src/lib.rs@@ -0,0 +1,223 @@+//! `raea neural mlxdlss DIR -o OUT` (docs/raytracing.feature RT2): DLSS 5's neural rendering on a render, on the Mac,+//! through MLX-DLSS (github.com/iamwavecut/MLX-DLSS, Apache-2.0), fed raea's own motion vectors and depth (`render+//! --aov`). An optional integration: the mlxdlss binary and the weights are the founder's (the weights are NVIDIA's,+//! extracted from their own DLSS install, and never ship with raea).++use std::path::{Path, PathBuf};++use raea_runtime_bundle::{R, flag};++pub const USAGE: &str = "raea neural mlxdlss DIR -o OUT [--model M.dlssmodel] [--intensity X] [--profile P] [--skin-structure X] [--local-structure X] [--steady A]";++fn tool_and_model(args: &[String]) -> R<(PathBuf, PathBuf)> {+ let bin = std::env::var_os("RAEA_MLXDLSS").map(PathBuf::from).filter(|p| p.is_file()).ok_or(+ "raea neural mlxdlss needs your own MLX-DLSS build: set RAEA_MLXDLSS to its mlxdlss binary (github.com/iamwavecut/MLX-DLSS, `swift build -c release`)",+ )?;+ let model = flag(args, "--model").or_else(|| std::env::var("RAEA_DLSS_MODEL").ok()).map(PathBuf::from).filter(|p| p.exists()).ok_or(+ "raea neural mlxdlss needs weights you extracted yourself (MLX-DLSS's `mlxdlss-weights extract` from your NVIDIA DLSS install): --model or RAEA_DLSS_MODEL names the .dlssmodel; raea doesn't ship them",+ )?;+ Ok((bin, model))+}++/// The frames of a `render --aov` folder, in order: (picture, motion, depth).+fn frames(dir: &Path) -> R<Vec<(PathBuf, PathBuf, PathBuf)>> {+ let mut pngs: Vec<PathBuf> = std::fs::read_dir(dir).map_err(|e| format!("{}: {e}", dir.display()))?.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "png") && p.file_name().is_some_and(|n| n.to_string_lossy().starts_with("frame-"))).collect();+ pngs.sort();+ if pngs.is_empty() {+ return Err(format!("{}: no frame-NNNNN.png (make it with raea render EDIT.tsx -o {} --aov)", dir.display(), dir.display()));+ }+ pngs.into_iter()+ .map(|p| {+ let stem = p.file_stem().unwrap().to_string_lossy().into_owned();+ let (m, d) = (dir.join("motion").join(format!("{stem}.f32")), dir.join("depth").join(format!("{stem}.f32")));+ if !m.is_file() || !d.is_file() {+ return Err(format!("{}: no motion or depth beside it (render with --aov)", p.display()));+ }+ Ok((p, m, d))+ })+ .collect()+}++/// A 0..1 channel as an 8-bit one (rounded, clamped).+fn to_byte(x: f32) -> u8 {+ (x.clamp(0.0, 1.0) * 255.0).round() as u8+}++fn f32s(p: &Path) -> R<Vec<f32>> {+ let b = std::fs::read(p).map_err(|e| format!("{}: {e}", p.display()))?;+ Ok(b.chunks_exact(4).map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect())+}++fn write_f32s(p: &Path, v: impl Iterator<Item = f32>) -> R<()> {+ std::fs::write(p, v.flat_map(f32::to_le_bytes).collect::<Vec<u8>>()).map_err(|e| format!("{}: {e}", p.display()))+}++pub fn neural(args: &[String]) -> R<String> {+ if args.first().map(String::as_str) != Some("mlxdlss") || args.len() < 2 {+ return Err(format!("usage: {USAGE}"));+ }+ let dir = PathBuf::from(&args[1]);+ let out = PathBuf::from(flag(args, "-o").ok_or(format!("usage: {USAGE}"))?);+ let (bin, model) = tool_and_model(args)?;+ let list = frames(&dir)?;+ let (w, h) = image::image_dimensions(&list[0].0).map_err(|e| format!("{}: {e}", list[0].0.display()))?;+ // the inputs as run-sequence reads them: float32 NHWC, rows top to bottom. Colour is the frame's sRGB values in+ // 0..1 (as MLX-DLSS's own video path hands it frames); motion is negated, since run-sequence's normalized-uv adds+ // it to a pixel to find where it was, and Bevy's is where it is minus where it was; depth is Bevy's reverse Z+ let work = std::env::temp_dir().join(format!("raea-neural-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&work);+ std::fs::create_dir_all(&work).map_err(|e| e.to_string())?;+ // one run-sequence a shot: the network keeps a history, and carried over a cut it painted the last shot's face+ // onto the next one's+ let starts = cuts(&list, w as usize, h as usize)?;+ // each shot run, steadied and written before the next, and its float files deleted: a whole render's at once+ // (colour, motion and the network's output, 70 MB a 1080p frame) filled the disk+ std::fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?;+ let a: f32 = flag(args, "--steady").map(|v| v.parse::<f32>().ok().filter(|a| *a > 0.0 && *a <= 1.0).ok_or("--steady takes 0..1 (1: off)")).transpose()?.unwrap_or(0.25);+ let mut steady = Steady { w: w as usize, h: h as usize, a, hist: None };+ for (k, &s0) in starts.iter().enumerate() {+ let s1 = starts.get(k + 1).copied().unwrap_or(list.len());+ let mut cmd = std::process::Command::new(&bin);+ cmd.arg("run-sequence").arg(&model);+ for (i, (png, m, d)) in list.iter().enumerate().take(s1).skip(s0) {+ let rgb = image::open(png).map_err(|e| format!("{}: {e}", png.display()))?.to_rgb8();+ if rgb.dimensions() != (w, h) {+ return Err(format!("{}: {}x{}, the first frame is {w}x{h}", png.display(), rgb.width(), rgb.height()));+ }+ let (c, mo) = (work.join(format!("c{i:05}.f32")), work.join(format!("m{i:05}.f32")));+ write_f32s(&c, rgb.as_raw().iter().map(|&b| b as f32 / 255.0))?;+ // a shot's first frame has no last frame to have moved from+ let mv = if i == s0 { vec![0.0; (w * h * 2) as usize] } else { f32s(m)? };+ if mv.len() != (w * h * 2) as usize {+ return Err(format!("{}: {} floats, a {w}x{h} frame's motion is {}", m.display(), mv.len(), w * h * 2));+ }+ write_f32s(&mo, mv.into_iter().map(|v| -v))?;+ cmd.arg("--input").arg(&c).arg("--motion").arg(&mo).arg("--depth").arg(d);+ }+ let shot = work.join(format!("shot{k}"));+ cmd.args(["--input-format", "rgb-temporal-reference", "--motion-format", "normalized-uv", "--depth-inverted", "true"]);+ cmd.args(["--width", &w.to_string(), "--height", &h.to_string()]).arg("--output-dir").arg(&shot);+ for key in ["--intensity", "--profile", "--skin-structure", "--local-structure"] {+ if let Some(v) = flag(args, key) {+ cmd.args([key, &v]);+ }+ }+ let st = cmd.stdout(std::process::Stdio::null()).status().map_err(|e| format!("{}: {e}", bin.display()))?;+ if !st.success() {+ return Err(format!("mlxdlss run-sequence failed on frames {s0}..{s1} ({st})"));+ }+ for i in s0..s1 {+ let _ = std::fs::remove_file(work.join(format!("c{i:05}.f32")));+ let _ = std::fs::remove_file(work.join(format!("m{i:05}.f32")));+ }+ steady.hist = None;+ for (i, (png, m, d)) in list.iter().enumerate().take(s1).skip(s0) {+ let f = shot.join(format!("{:06}.f32", i - s0));+ let v = f32s(&f)?;+ if v.len() != (w * h * 3) as usize {+ return Err(format!("mlxdlss frame {i}: {} floats, not {w}x{h}x3", v.len()));+ }+ let raw: Vec<f32> = image::open(png).map_err(|e| format!("{}: {e}", png.display()))?.to_rgb8().as_raw().iter().map(|&b| b as f32 / 255.0).collect();+ let v = steady.frame(&raw, &v, &f32s(m)?, &f32s(d)?);+ let px: Vec<u8> = v.iter().copied().map(to_byte).collect();+ let dest = out.join(png.file_name().unwrap());+ image::save_buffer(&dest, &px, w, h, image::ColorType::Rgb8).map_err(|e| format!("{}: {e}", dest.display()))?;+ }+ let _ = std::fs::remove_dir_all(&shot);+ }+ eprintln!("raea: {} shot(s), cut before frames {:?}", starts.len(), &starts[1..]);+ let _ = std::fs::remove_dir_all(&work);+ Ok(format!("APPLIED {} frames through DLSS 5 neural rendering (MLX-DLSS, raea's motion and depth) to {}", list.len(), out.display()))+}++/// `--steady A`: the network re-invents fine detail a little differently each frame (skin grain, a silhouette's edge),+/// which reads as shimmer where raea's own frames are still. Its change to each frame (its output minus raea's) is+/// carried along raea's motion vectors and blended in at A a frame (an exponential history, as TAA's), then added back+/// onto raea's frame: the look stays, the shimmer goes. A cut (`cuts`) and a pixel that came+/// out from behind something (its depth where it was isn't its depth now) start again from this frame's change.+/// 1 turns it off. On the faces reel's still shot: shimmer 0.21 -> about a quarter of it (RT2).+struct Steady {+ w: usize,+ h: usize,+ a: f32,+ /// the last frame: its carried change (3 a pixel), raea's frame and depth (None at a shot's start)+ hist: Option<(Vec<f32>, Vec<f32>, Vec<f32>)>,+}++impl Steady {+ fn frame(&mut self, raw: &[f32], net: &[f32], motion: &[f32], depth: &[f32]) -> Vec<f32> {+ let (w, h, n) = (self.w, self.h, self.w * self.h);+ let change: Vec<f32> = net.iter().zip(raw).map(|(o, r)| o - r).collect();+ let carried = if self.hist.is_none() || self.a >= 1.0 {+ change+ } else {+ let (hc, _, hd) = self.hist.as_ref().unwrap();+ let mut c = vec![0f32; n * 3];+ for y in 0..h {+ for x in 0..w {+ let i = y * w + x;+ // where this pixel was: Bevy's motion is this frame's UV minus the last's+ let (px, py) = (x as f32 - motion[i * 2] * w as f32, y as f32 - motion[i * 2 + 1] * h as f32);+ let (fx, fy) = (px.floor(), py.floor());+ let inside = fx >= 0.0 && fy >= 0.0 && fx < (w - 1) as f32 && fy < (h - 1) as f32;+ let (x0, y0) = (fx as usize, fy as usize);+ let was = if inside { hd[y0 * w + x0].max(hd[y0 * w + x0 + 1]).max(hd[(y0 + 1) * w + x0]).max(hd[(y0 + 1) * w + x0 + 1]) } else { -1.0 };+ // reverse Z: close enough when within 2% (0 is the background, where any depth is the same)+ let same = inside && ((was - depth[i]).abs() <= 0.02 * depth[i].max(was) || (was == 0.0 && depth[i] == 0.0));+ for k in 0..3 {+ let now = change[i * 3 + k];+ c[i * 3 + k] = if same {+ let (tx, ty) = (px - fx, py - fy);+ let s = |xx: usize, yy: usize| hc[(yy * w + xx) * 3 + k];+ let old = (s(x0, y0) * (1.0 - tx) + s(x0 + 1, y0) * tx) * (1.0 - ty) + (s(x0, y0 + 1) * (1.0 - tx) + s(x0 + 1, y0 + 1) * tx) * ty;+ old + (now - old) * self.a+ } else {+ now+ };+ }+ }+ }+ c+ };+ let out = raw.iter().zip(&carried).map(|(r, c)| r + c).collect();+ self.hist = Some((carried, raw.to_vec(), depth.to_vec()));+ out+ }+}++/// Where the shots start (0 first): a frame is a cut when most of what it shows wasn't where its motion vectors say it+/// came from, by depth (reverse Z within 2%), or its foreground grew or shrank by half. raea's motion is the scene's,+/// so a cut between two people facing the same way (their silhouettes nearly the same) is still found.+fn cuts(list: &[(PathBuf, PathBuf, PathBuf)], w: usize, h: usize) -> R<Vec<usize>> {+ let mut starts = vec![0];+ let mut last = f32s(&list[0].2)?;+ for (i, (_, m, d)) in list.iter().enumerate().skip(1) {+ let (mv, depth) = (f32s(m)?, f32s(d)?);+ if mv.len() != w * h * 2 || depth.len() != w * h {+ return Err(format!("{}: not a {w}x{h} frame's motion and depth", m.display()));+ }+ let (mut fg, mut lost, mut was_fg) = (0usize, 0usize, 0usize);+ for y in (0..h).step_by(2) {+ for x in (0..w).step_by(2) {+ let k = y * w + x;+ was_fg += (last[k] > 0.0) as usize;+ if depth[k] <= 0.0 {+ continue;+ }+ fg += 1;+ let (px, py) = ((x as f32 - mv[k * 2] * w as f32).round(), (y as f32 - mv[k * 2 + 1] * h as f32).round());+ let ok = px >= 0.0 && py >= 0.0 && (px as usize) < w && (py as usize) < h && {+ let was = last[py as usize * w + px as usize];+ (was - depth[k]).abs() <= 0.02 * depth[k].max(was)+ };+ lost += (!ok) as usize;+ }+ }+ let grew = fg.max(was_fg) as f32 / fg.min(was_fg).max(1) as f32;+ if (fg > 0 && lost as f32 > 0.3 * fg as f32) || grew > 1.5 {+ starts.push(i);+ }+ last = depth;+ }+ Ok(starts)+}diff --git a/engine/page/Cargo.toml b/engine/page/Cargo.tomlindex ed726bce..de18e4ee 100644--- a/engine/page/Cargo.toml+++ b/engine/page/Cargo.toml@@ -12,6 +12,7 @@ raea-sys-page = { path = "../../systems/page" }raea-sys-fonts = { path = "../../systems/fonts" }raea-runtime-twins = { path = "../../runtime/twins" }raea-runtime-dom = { path = "../../runtime/dom" }+raea-runtime-edit = { path = "../../runtime/edit" }raea-runtime-input = { path = "../../runtime/input" }bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "bevy_render", "bevy_asset", "bevy_image", "bevy_log", "bevy_window", "ui_bevy_render", "bevy_picking", "ui_picking", "bevy_input_focus"] }# the document: stylo's styles, Taffy's and Blitz's layout (floats on, as Chrome lays them out)diff --git a/engine/page/host/Cargo.toml b/engine/page/host/Cargo.tomlindex 164a57a1..2896134f 100644--- a/engine/page/host/Cargo.toml+++ b/engine/page/host/Cargo.toml@@ -17,6 +17,8 @@ path = "src/main.rs"[features]# the page on QuickJS (raea-runtime-js's portable engine) in place of JavaScriptCoreportable = ["raea-runtime-js/portable"]+# raea's window on screen (--window: the desktop app, docs/app.feature AP5/AP6); the benches and tests stay headless+window = ["bevy/bevy_winit", "dep:raea-runtime-plugins", "raea-page-window/window"][dependencies]# the window as an image the UI camera draws, picking's pointer input, the remote protocol, and every image format the@@ -26,6 +28,8 @@ raea-runtime-js = { path = "../../../runtime/js" }# the page's accessibility recordsraea-sys-a11y = { path = "../../../systems/a11y" }raea-page = { path = ".." }+# the desktop window: --chrome and the native calls (clipboard, links, notifications, the dock badge, raea:// links)+raea-page-window = { path = "../window" }raea-sys-page = { path = "../../../systems/page" }raea-sys-fonts = { path = "../../../systems/fonts" }raea-runtime-dom = { path = "../../../runtime/dom" }@@ -38,22 +42,14 @@ blitz-dom = { version = "=0.3.0-beta.4", default-features = false }stylo = "=0.22.0"image = { version = "0.25", default-features = false, features = ["png"] }serde_json = "1"-# the live stage (src/stage.rs): raea-runtime-live, with raea-runtime-react's features turned on here (the legacy app's), on-# the shared device Bevy renders on here (raea-runtime-view's render_creation)-raea-runtime-react = { path = "../../../runtime/react", default-features = false, features = ["h264", "av1", "scripts", "modules", "network"] }-# and its sound's <Seedling> samples-raea-runtime-sound = { path = "../../../runtime/sound", features = ["seedling"] }-raea-runtime-live = { path = "../../../runtime/live" }-# its stage's bakes find the bundle's functions (raea-runtime-bake's modules, as raea-runtime-react's were)-raea-runtime-bake = { path = "../../../runtime/bake", features = ["modules"] }-raea-gpu-device = { path = "../../../gpu/device" }+# the live stage: <img data-raea-stage> (raea-page-stage)+raea-page-stage = { path = "../stage" }+# the window build turns bevy_winit on for every Bevy app in the process; the stage's engine is told to leave it out (main.rs)+raea-runtime-plugins = { path = "../../../runtime/plugins", optional = true }raea-runtime-view = { path = "../../../runtime/view" }-wgpu = "=30.0.1"-# a picked element's prop written into the game's next version-raea-sys-tweak = { path = "../../../systems/tweak" }tiny_http = "0.12"base64 = "0.22"# raea-io-media is here for its feature (the platform decoders raea-page and raea-runtime-js use), not called directly[package.metadata.cargo-shear]-ignored = ["raea-io-media", "raea-runtime-react", "raea-runtime-bake", "raea-runtime-sound"]+ignored = ["raea-io-media"]diff --git a/engine/page/host/src/lib.rs b/engine/page/host/src/lib.rsindex 54759555..50d0ef1a 100644--- a/engine/page/host/src/lib.rs+++ b/engine/page/host/src/lib.rs@@ -5,10 +5,13 @@//! adds [`HostPlugin`] and mounts its own (page::mount), its systems around the host's.pub mod brp;+/// the desktop window's chrome and native calls, in raea-page-window (kept under these names for main.rs and tests)+pub use raea_page_window::{chrome, native};+/// the live stage, in raea-page-stage+pub use raea_page_stage as stage;pub mod inject;pub mod mcp;pub mod page;-pub mod stage;pub mod tree;use std::time::Duration;@@ -87,3 +90,16 @@ pub fn camera(mut commands: Commands, mut images: ResMut<Assets<Image>>, size: Rcommands.insert_resource(inject::Target { image, norm, scale: 1.0, windowed: false });commands.insert_resource(UiCam(cam));}++/// On screen (raea's window, the `window` feature): the UI camera draws to the primary window at its own scale; the+/// window's pointer reaches picking through inject::window_pointer, its keys through bevy_winit as any app's.+pub fn camera_window(mut commands: Commands, mut images: ResMut<Assets<Image>>, primary: Query<Entity, With<bevy::window::PrimaryWindow>>) {+ let win = primary.single().expect("raea's window has a primary window");+ let target = RenderTarget::Window(bevy::window::WindowRef::Primary);+ let norm = target.normalize(Some(win)).expect("the primary window normalizes");+ let cam = commands.spawn((Camera2d, Camera { clear_color: ClearColorConfig::Custom(Color::BLACK), ..default() }, target)).id();+ // the image is unused on screen (inject::Target), a pixel to fill the field+ let image = images.add(Image::new_target_texture(1, 1, TextureFormat::Rgba8UnormSrgb, None));+ commands.insert_resource(inject::Target { image, norm, scale: 1.0, windowed: true });+ commands.insert_resource(UiCam(cam));+}diff --git a/engine/page/host/src/main.rs b/engine/page/host/src/main.rsindex f213ce09..61962cda 100644--- a/engine/page/host/src/main.rs+++ b/engine/page/host/src/main.rs@@ -1,12 +1,15 @@//! raea-page-host: a bundle on a Blitz page in a headless Bevy app, for the benches.//!-//! raea-page-host BUNDLE [--css FILE[:FILE...]] [--root DIR[:DIR...]] [--size WxH]+//! raea-page-host BUNDLE [--css FILE[:FILE...]] [--root DIR[:DIR...]] [--size WxH] [--window [--title T] [--chrome native|inset]]//!//! BUNDLE is built JS (an app's Blitz build). --css: the page's own CSS, laid out as Chrome lays out a page; without//! it, bevy_ui's kinds. --root: where the page's own-origin fetches are read from (RAEA_PAGE_ROOT). --size: the//! window, default 1440x900. RAEA_PAGE_BRP_PORT (default: a free one), RAEA_PAGE_MCP_PORT (default 7477; 0: none),//! RAEA_PAGE_PICK=0: the page's pointers and keys dispatched by the host (page::input) instead of through raea-page's-//! picking route, the default. The page's `<img data-raea-stage>` plays a composition live (src/stage.rs).+//! picking route, the default. The page's `<img data-raea-stage>` plays a composition live (raea-page-stage).+//! --chrome inset: the page under a transparent title bar, its title area moving the window (raea-page-window).+//! --window (built with the `window` feature): on screen, a window of its own that closes the app (raea's desktop app;+//! RAEA_PAGE_HOST sends the page's /host/* to the feed's host: raea-page-net).use std::time::Duration;@@ -14,18 +17,23 @@ use bevy::app::ScheduleRunnerPlugin;use bevy::log::{Level, LogPlugin};use bevy::prelude::*;use bevy::render::pipelined_rendering::PipelinedRenderingPlugin;-use bevy::window::{ExitCondition, WindowResolution};+use bevy::window::ExitCondition;+use raea_page_host::chrome::{self, Chrome};use raea_page_host::{HostPlugin, brp, camera, mcp, page, stage, tree};struct Args {bundle: String,css: Option<Vec<String>>,size: UVec2,+ window: bool,+ title: String,+ chrome: Chrome,}fn args() -> Result<Args, String> {let mut it = std::env::args().skip(1);- let (mut bundle, mut css, mut size) = (None, None, UVec2::new(1440, 900));+ let (mut bundle, mut css, mut size, mut window, mut title) = (None, None, UVec2::new(1440, 900), false, "raea".to_string());+ let mut chrome = Chrome::default();while let Some(a) = it.next() {let mut val = || it.next().ok_or(format!("{a} needs a value"));match a.as_str() {@@ -37,12 +45,16 @@ fn args() -> Result<Args, String> {let (w, h) = v.split_once('x').ok_or(format!("--size {v}: WxH"))?;size = UVec2::new(w.trim().parse().map_err(|_| format!("--size {v}"))?, h.trim().parse().map_err(|_| format!("--size {v}"))?);}+ "--window" if cfg!(feature = "window") => window = true,+ "--window" => return Err("--window: this build has no window (build with --features window)".into()),+ "--title" => title = val()?,+ "--chrome" => chrome = Chrome::parse(&val()?)?,s if s.starts_with("--") => return Err(format!("no option {s}")),s => bundle = Some(s.to_string()),}}let bundle = bundle.ok_or("usage: raea-page-host BUNDLE [--css FILE[:FILE]] [--root DIR[:DIR]] [--size WxH]")?;- Ok(Args { bundle, css, size })+ Ok(Args { bundle, css, size, window, title, chrome })}fn main() {@@ -54,6 +66,10 @@ fn main() {eprintln!("raea-page-host: {}: {e}", a.bundle);std::process::exit(1);});+ // with the window feature, bevy_winit is in every Bevy app this process makes: the stage's live engine (raea-render's+ // Engine, on its own thread) would make a second event loop and panic, so it leaves WinitPlugin out+ #[cfg(feature = "window")]+ raea_runtime_plugins::register(raea_runtime_plugins::Registered { name: "raea-page-host window", install: |_| {}, group: Some(|b| b.disable::<bevy::winit::WinitPlugin>()), on_demand: false });let picking = !std::env::var("RAEA_PAGE_PICK").is_ok_and(|v| v == "0");mcp::serve(mcp::port(), mcp::Server { name: "raea-page-host".into(), instructions: "A raea page. Drive it with input, read it with ui; brp reaches the whole ECS (Bevy Remote Protocol).".into(), prefix: "page".into() });@@ -61,37 +77,44 @@ fn main() {app.add_plugins(DefaultPlugins.set(WindowPlugin {- primary_window: Some(Window { title: "raea".into(), resolution: WindowResolution::new(a.size.x, a.size.y), ..default() }),- exit_condition: ExitCondition::DontExit,- close_when_requested: false,+ primary_window: Some(a.chrome.window(&a.title, a.size)),+ // on screen, closing the window ends the app; headless, nothing closes it but the process+ exit_condition: if a.window { ExitCondition::OnPrimaryClosed } else { ExitCondition::DontExit },+ close_when_requested: a.window,..default()}).set(LogPlugin { level: Level::WARN, ..default() })- // the shared device (raea_gpu_device), so a game on the stage (src/stage.rs), drawn there by the live engine, is a+ // the shared device (raea_gpu_device), so a game on the stage (raea-page-stage), drawn there by the live engine, is a// texture this renderer copies with no trip across devices (RAEA_SHARED_DEVICE=0: Bevy's own, no stage).set(bevy::render::RenderPlugin { render_creation: raea_runtime_view::render_creation(), ..default() })// each update draws its own frame: the frame `ui` reports is the one rendered.disable::<PipelinedRenderingPlugin>(),);- if !app.is_plugin_added::<ScheduleRunnerPlugin>() {+ // on screen, bevy_winit's event loop is the runner (a ScheduleRunner here replaced it: no window, 11-04)+ if !a.window && !app.is_plugin_added::<ScheduleRunnerPlugin>() {app.add_plugins(ScheduleRunnerPlugin::run_loop(Duration::from_secs_f64(1.0 / 60.0)));}app.add_plugins(HostPlugin { size: a.size, double_click: Duration::from_millis(500), picking }).add_plugins(brp::plugins(brp::port(), |r| r))- .add_plugins(stage::StagePlugin);+ .add_plugins(stage::StagePlugin)+ // the clipboard, links, notifications, the dock badge, raea:// links and the chrome (raea-page-window)+ .add_plugins(raea_page_window::DesktopPlugin { chrome: a.chrome, live: a.window });raea_page_host::page_plugins(&mut app, picking);let (css, size) = (a.css, a.size);- app.add_systems(- Startup,- (camera, move |world: &mut World| {- let m = page::Mount { code: code.clone(), preamble: vec![], css: css.clone(), styles: None, picking, size };- if let Err(e) = page::mount(world, m) {- eprintln!("raea-page-host: {e}");- std::process::exit(1);- }- })- .chain(),- );+ let preamble = vec![a.chrome.preamble()];+ let mount = move |world: &mut World| {+ chrome::install(world);+ let m = page::Mount { code: code.clone(), preamble: preamble.clone(), css: css.clone(), styles: None, picking, size };+ if let Err(e) = page::mount(world, m) {+ eprintln!("raea-page-host: {e}");+ std::process::exit(1);+ }+ };+ if a.window {+ app.add_systems(Startup, (raea_page_host::camera_window, mount).chain());+ } else {+ app.add_systems(Startup, (camera, mount).chain());+ }if picking {app.add_systems(PreUpdate, (page::read_input, page::frame_input, page::size).chain().before(bevy::picking::PickingSystems::ProcessInput)).add_systems(Update, (page::step_dropping_asks, page::show).chain());diff --git a/engine/page/host/src/page.rs b/engine/page/host/src/page.rsindex 62b7006e..1ea875ca 100644--- a/engine/page/host/src/page.rs+++ b/engine/page/host/src/page.rs@@ -68,6 +68,7 @@ pub fn mount(world: &mut World, m: Mount) -> Result<Entity, String> {}}world.insert_resource(HostPage(page));+ world.insert_resource(raea_page_stage::StagePage(page));let shows = world.spawn((Shows, Node { position_type: PositionType::Absolute, width: percent(100), height: percent(100), ..default() }, UiTargetCamera(cam))).id();if m.picking {// the node itself isn't a hit (bevy_ui's backend would report it above the page's twins, and nothing would@@ -253,6 +254,10 @@ pub fn tree(page: Res<HostPage>, roots: NonSend<Roots>, docs: NonSend<Docs>, winn["state"] = json!(state);if let Some(t) = s("data-text") {n["text"] = json!(t);+ } else if p.get("contentEditable").or(p.get("contenteditable")).is_some_and(|v| *v != json!(false) && *v != "false") {+ // a contenteditable's text, as Chrome's textContent has it (an editor's document isn't in its props)+ let node = roots.0.iter().find(|r| r.page == page.0).and_then(|r| r.nodes.by_id.get(&e.id)).and_then(|&n| docs.0.get(&page.0)?.get_node(n));+ n["text"] = json!(node.map(|d| d.text_content()).unwrap_or_default());}if let Some([top, max]) = e.scroll {n["scroll"] = json!({"top": r1(top), "max": r1(max)});diff --git a/engine/page/src/lib.rs b/engine/page/src/lib.rsindex 37bac679..6e298f38 100644--- a/engine/page/src/lib.rs+++ b/engine/page/src/lib.rs@@ -20,6 +20,7 @@ pub struct PagePlugin;impl Plugin for PagePlugin {fn build(&self, app: &mut App) {raea_runtime_dom::computed::register();+ raea_runtime_edit::register();app.add_plugins((raea_sys_page::PaintPlugin,raea_runtime_twins::bridge::BridgePlugin::<raea_runtime_dom::host::Roots>::default(),diff --git a/engine/page/stage/Cargo.toml b/engine/page/stage/Cargo.tomlnew file mode 100644index 00000000..553e7c70--- /dev/null+++ b/engine/page/stage/Cargo.toml@@ -0,0 +1,31 @@+[package]+name = "raea-page-stage"+version = "0.1.0"+edition = "2024"+license = "FSL-1.1-ALv2"+publish = false+description = "The live stage in a raea page: a game item's composition played live in the page's <img data-raea-stage> on raea-runtime-react's live engine, its frames copied on the GPU, driven by stage.* host calls"++[dependencies]+bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "default_font", "multi_threaded", "3d_bevy_render", "ui_bevy_render", "png", "tonemapping_luts", "ktx2", "zstd_rust", "bevy_picking", "ui_picking", "bevy_ui_widgets", "bevy_input_focus", "jpeg", "bevy_remote", "tga", "qoi", "tiff", "pnm", "ff", "dds", "exr", "hdr", "webp", "gif", "bmp", "ico"] }+raea-runtime-js = { path = "../../../runtime/js" }+raea-runtime-dom = { path = "../../../runtime/dom" }+raea-sys-page = { path = "../../../systems/page" }+blitz-dom = { version = "=0.3.0-beta.4", default-features = false }+serde_json = "1"+# the live engine, with raea-runtime-react's features turned on here (the legacy app's), on the shared device Bevy renders+# on (raea-runtime-view's render_creation, set by the app)+raea-runtime-live = { path = "../../../runtime/live" }+raea-runtime-react = { path = "../../../runtime/react", default-features = false, features = ["h264", "av1", "scripts", "modules", "network"] }+# and its sound's <Seedling> samples+raea-runtime-sound = { path = "../../../runtime/sound", features = ["seedling"] }+# its bakes find the bundle's functions (raea-runtime-bake's modules, as raea-runtime-react's were)+raea-runtime-bake = { path = "../../../runtime/bake", features = ["modules"] }+raea-gpu-device = { path = "../../../gpu/device" }+wgpu = "=30.0.1"+# a picked element's prop written into the game's next version+raea-sys-tweak = { path = "../../../systems/tweak" }++# here for their features (the live engine's), not called directly+[package.metadata.cargo-shear]+ignored = ["raea-runtime-react", "raea-runtime-bake", "raea-runtime-sound"]diff --git a/engine/page/host/src/stage.rs b/engine/page/stage/src/lib.rssimilarity index 98%rename from engine/page/host/src/stage.rsrename to engine/page/stage/src/lib.rsindex 2ce59262..36162267 100644--- a/engine/page/host/src/stage.rs+++ b/engine/page/stage/src/lib.rs@@ -35,7 +35,10 @@ use raea_runtime_dom::host::Roots;use raea_sys_page::view3d::ElementImages;use serde_json::{Value, json};-use crate::page::HostPage;+/// The page the stage is in: the app inserts it with the page it mounts (raea-page-host's page::mount).+#[derive(Resource)]+pub struct StagePage(pub Entity);+/// What the page asks of the stage's thread.enum Cmd {@@ -203,7 +206,7 @@ fn fit(stage: Res<Stage>, mut images: ResMut<Assets<Image>>) {/// The page's `<img data-raea-stage>` shows the stage's image while the stage has a picture (ElementImages: Vello draws/// it in the element's place).-fn bind(stage: Res<Stage>, page: Option<Res<HostPage>>, roots: Option<NonSend<Roots>>, docs: Option<NonSend<Docs>>, mut shows: ResMut<ElementImages>, mut held: Local<Option<(Entity, blitz_dom::NodeId)>>) {+fn bind(stage: Res<Stage>, page: Option<Res<StagePage>>, roots: Option<NonSend<Roots>>, docs: Option<NonSend<Docs>>, mut shows: ResMut<ElementImages>, mut held: Local<Option<(Entity, blitz_dom::NodeId)>>) {let (Some(page), Some(roots), Some(_docs)) = (page, roots, docs) else { return };let node = stage.size().and_then(|_| {let r = roots.0.iter().find(|r| r.page == page.0)?;diff --git a/engine/page/window/Cargo.toml b/engine/page/window/Cargo.tomlnew file mode 100644index 00000000..16339463--- /dev/null+++ b/engine/page/window/Cargo.toml@@ -0,0 +1,25 @@+[package]+name = "raea-page-window"+version = "0.1.0"+edition = "2024"+license = "FSL-1.1-ALv2"+publish = false+description = "raea's desktop window around a page: its chrome (--chrome inset: the page under a transparent title bar, window.drag and window.zoom) and what a Mac app does that a page can't (the clipboard, links, notifications, the dock badge, raea:// links)"++[features]+# on screen (raea-page-host's --window): AppKit's calls are made; without it they are recorded and answered+window = ["bevy/bevy_winit", "dep:objc2", "dep:objc2-app-kit", "dep:objc2-foundation", "dep:raw-window-handle", "dep:block2"]++[dependencies]+bevy = { version = "=0.20.0", default-features = false, features = ["std", "bevy_window"] }+raea-runtime-js = { path = "../../../runtime/js" }+serde_json = "1"++# --chrome inset's unified toolbar (the traffic lights centred in a 52 pt title area) and native.rs's AppKit calls+[target.'cfg(target_os = "macos")'.dependencies]+objc2 = { version = "0.6", optional = true }+objc2-app-kit = { version = "0.3", optional = true, default-features = false, features = ["std", "NSResponder", "NSView", "NSWindow", "NSToolbar"] }+objc2-foundation = { version = "0.3", optional = true, default-features = false, features = ["std", "NSString"] }+raw-window-handle = { version = "0.6", optional = true }+# completion handlers for notifications+block2 = { version = "0.6", optional = true }diff --git a/engine/page/window/src/chrome.rs b/engine/page/window/src/chrome.rsnew file mode 100644index 00000000..c070f8e4--- /dev/null+++ b/engine/page/window/src/chrome.rs@@ -0,0 +1,119 @@+//! The window's own chrome (--chrome inset, the desktop app): macOS's title bar made transparent with the page drawn+//! under it, its traffic lights kept, and what a title bar does left to the page. The page knows from+//! `globalThis.__raea_window` ({chrome, lights}: the lights' box in points, for the page to leave room for) and asks+//! through two host calls: `window.drag` (a press on the page's title area moves the window, as winit's drag_window+//! does from that press) and `window.zoom` (a double-click there zooms, as a native title bar's does).++use bevy::prelude::*;+use bevy::window::PrimaryWindow;+use raea_runtime_js::HostCalls;+use serde_json::json;++/// How the window's frame is drawn.+#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]+pub enum Chrome {+ /// the system's title bar above the page+ #[default]+ Native,+ /// the page fills the window, under a transparent title bar with only the traffic lights+ Inset,+}++impl Chrome {+ pub fn parse(s: &str) -> Result<Self, String> {+ match s {+ "native" => Ok(Self::Native),+ "inset" => Ok(Self::Inset),+ _ => Err(format!("--chrome {s}: native or inset")),+ }+ }++ /// The primary window, titled and sized, with this chrome's title bar.+ pub fn window(self, title: &str, size: UVec2) -> Window {+ let inset = self == Self::Inset;+ let resolution = bevy::window::WindowResolution::new(size.x, size.y);+ Window { title: title.into(), resolution, titlebar_transparent: inset, titlebar_show_title: !inset, fullsize_content_view: inset, ..default() }+ }++ /// JS run before the page's bundle: what the page reads to draw its own title area.+ pub fn preamble(self) -> String {+ // the traffic lights under the empty unified toolbar (toolbar, below): three 14 pt buttons from x 20, 6 pt+ // apart, centred in the 52 pt title area; elsewhere (no toolbar) AppKit's standard 28 pt bar's, from x 7+ let lights = if cfg!(all(target_os = "macos", feature = "window")) {+ json!({ "x": 20, "y": 19, "w": 54, "h": 14 })+ } else {+ json!({ "x": 7, "y": 6, "w": 54, "h": 14 })+ };+ let bar = if cfg!(all(target_os = "macos", feature = "window")) { 52 } else { 28 };+ let v = match self {+ Self::Native => json!({ "chrome": "native" }),+ Self::Inset => json!({ "chrome": "inset", "lights": lights, "bar": bar }),+ };+ format!("globalThis.__raea_window = {v};")+ }+}++/// The primary window, once winit has made it, given an empty unified toolbar (macOS): AppKit then draws a 52 pt title+/// area with the traffic lights centred in it, as in an app with a toolbar, under the page (inset chrome only).+#[cfg(all(target_os = "macos", feature = "window"))]+pub fn toolbar(_main: bevy::ecs::system::NonSendMarker, mut done: Local<bool>, chrome: Res<ChromeIs>) {+ use objc2::MainThreadMarker;+ use objc2_app_kit::{NSToolbar, NSView, NSWindowToolbarStyle};+ use raw_window_handle::{HasWindowHandle, RawWindowHandle};+ if *done || chrome.0 != Chrome::Inset {+ return;+ }+ let Some(mtm) = MainThreadMarker::new() else { return };+ bevy::winit::WINIT_WINDOWS.with_borrow(|ww| {+ let Some(w) = ww.windows.values().next() else { return };+ let Ok(handle) = w.window_handle() else { return };+ let RawWindowHandle::AppKit(h) = handle.as_raw() else { return };+ // SAFETY: winit's handle names its window's live content view, on this (the main) thread+ let view: &NSView = unsafe { h.ns_view.cast().as_ref() };+ let Some(win) = view.window() else { return };+ let tb = NSToolbar::new(mtm);+ win.setToolbar(Some(&tb));+ win.setToolbarStyle(NSWindowToolbarStyle::Unified);+ *done = true;+ });+}++/// The chrome the window was opened with.+#[derive(Resource, Clone, Copy)]+pub struct ChromeIs(pub Chrome);++/// `window.drag` and `window.zoom`, on the primary window.+pub fn install(world: &mut World) {+ world.init_resource::<HostCalls>();+ world+ .resource_mut::<HostCalls>()+ .on("window.drag", |w, _args, answer| {+ let mut q = w.query_filtered::<&mut Window, With<PrimaryWindow>>();+ match q.single_mut(w) {+ Ok(mut win) => {+ win.start_drag_move();+ answer.ok(json!(true))+ }+ Err(_) => answer.err("no window"),+ }+ })+ .on("window.zoom", |w, _args, answer| {+ let zoomed = {+ let mut z = w.get_resource_or_insert_with(|| Zoomed(false));+ z.0 = !z.0;+ z.0+ };+ let mut q = w.query_filtered::<&mut Window, With<PrimaryWindow>>();+ match q.single_mut(w) {+ Ok(mut win) => {+ win.set_maximized(zoomed);+ answer.ok(json!(zoomed))+ }+ Err(_) => answer.err("no window"),+ }+ });+}++/// Whether `window.zoom` last zoomed the window (AppKit's zoom toggles; Bevy keeps no maximized state to read).+#[derive(Resource)]+struct Zoomed(bool);diff --git a/engine/page/window/src/lib.rs b/engine/page/window/src/lib.rsnew file mode 100644index 00000000..5855a642--- /dev/null+++ b/engine/page/window/src/lib.rs@@ -0,0 +1,25 @@+//! raea's desktop window around a page (raea-page-host --window, the window raea.app runs): its chrome (chrome.rs) and+//! the native calls a page makes through host calls (native.rs).++pub mod chrome;+pub mod native;++use bevy::prelude::*;++/// The window's side of the app: the native calls (live only on screen, else recorded), the chrome it was opened with+/// and, on a Mac window with --chrome inset, its unified toolbar. `window.drag` and `window.zoom` are installed with+/// the page (chrome::install, at mount).+pub struct DesktopPlugin {+ pub chrome: chrome::Chrome,+ pub live: bool,+}++impl Plugin for DesktopPlugin {+ fn build(&self, app: &mut App) {+ app.add_plugins(native::NativePlugin { live: self.live }).insert_resource(chrome::ChromeIs(self.chrome));+ #[cfg(all(target_os = "macos", feature = "window"))]+ if self.live {+ app.add_systems(Update, chrome::toolbar);+ }+ }+}diff --git a/engine/page/window/src/native.rs b/engine/page/window/src/native.rsnew file mode 100644index 00000000..171afd75--- /dev/null+++ b/engine/page/window/src/native.rs@@ -0,0 +1,380 @@+//! What a Mac app does that a page can't (docs/onboarding.feature OB-N): the clipboard, links opened in the browser,+//! notifications, the dock badge, and raea:// links coming back to the app. The page asks through host calls:+//!+//! clipboard.write {text} clipboard.read -> text+//! app.open {url} an http(s) or mailto link, in the person's browser+//! notify {title, body} a macOS notification (asked for once, the first time: notify.permission)+//! notify.permission -> bool macOS's prompt, or its answer if already given+//! dock.badge {text} the dock icon's badge ("" clears it)+//! app.urls -> string[] raea:// links opened since the last ask, the app brought to the front for each+//! native.log -> {...} what was done, for tests+//!+//! Live only on screen (--window) and without RAEA_NO_OPEN=1: otherwise every call is recorded and answered as if done,+//! so headless runs never touch the person's clipboard, browser or notifications. Notifications and raea:// links need+//! the app's identity: the window running as raea.app's own process (tools/raea-app/launch.sh execs it from+//! Contents/MacOS); elsewhere notify answers an error that says so.+//! AppKit is called on the main thread: the calls queue here and `drain` (a NonSend system) runs them.++use std::sync::Mutex;++use bevy::ecs::system::NonSendMarker;+use bevy::prelude::*;+use raea_runtime_js::calls::{Answer, HostCalls};+use serde_json::{Value, json};++/// Whether calls reach macOS, or are only recorded.+#[derive(Resource, Clone, Copy)]+pub struct Live(pub bool);++/// What was done, live or recorded: read by native.log.+#[derive(Default)]+struct Log {+ clipboard: String,+ opened: Vec<String>,+ notified: Vec<Value>,+ badge: String,+ urls: Vec<String>,+}++static LOG: Mutex<Option<Log>> = Mutex::new(None);+/// raea:// links that arrived and the page hasn't read yet (filled by the Apple event handler, on the main thread).+static URLS: Mutex<Vec<String>> = Mutex::new(Vec::new());++fn log<T>(f: impl FnOnce(&mut Log) -> T) -> T {+ f(LOG.lock().unwrap().get_or_insert_with(Log::default))+}++/// A call waiting for the main thread.+struct Job(String, Value, Answer);++#[derive(Resource, Default)]+struct Queue(Mutex<Vec<Job>>);++/// The calls, live or recorded. Call once, after HostCalls exists.+pub struct NativePlugin {+ pub live: bool,+}++impl Plugin for NativePlugin {+ fn build(&self, app: &mut App) {+ let live = self.live && std::env::var("RAEA_NO_OPEN").as_deref() != Ok("1");+ app.insert_resource(Live(live)).init_resource::<Queue>().init_resource::<HostCalls>().add_systems(Startup, (calls, start)).add_systems(Update, drain);+ }+}++fn calls(mut calls: ResMut<HostCalls>) {+ for name in ["clipboard.write", "clipboard.read", "app.open", "notify", "notify.permission", "dock.badge", "app.urls", "native.log"] {+ calls.on(name, move |w, args, answer| w.resource::<Queue>().0.lock().unwrap().push(Job(name.to_string(), args, answer)));+ }+}++/// On screen: raea:// links are handed to the app from here on.+fn start(live: Res<Live>, _main: NonSendMarker) {+ if live.0 {+ mac::listen_for_urls();+ }+}++fn drain(world: &mut World) {+ let jobs = std::mem::take(&mut *world.resource::<Queue>().0.lock().unwrap());+ if jobs.is_empty() {+ return;+ }+ let live = world.resource::<Live>().0;+ for Job(name, args, answer) in jobs {+ run(live, &name, &args, answer);+ }+}++// NonSend: AppKit wants its main thread. An exclusive system with this marker would be enough; drain takes &mut World,+// which Bevy's executors already run on the main thread.++fn text(a: &Value, k: &str) -> String {+ a.get(k).and_then(Value::as_str).unwrap_or_default().to_string()+}++fn run(live: bool, name: &str, a: &Value, answer: Answer) {+ match name {+ "clipboard.write" => {+ let t = text(a, "text");+ if live {+ mac::clipboard_write(&t);+ }+ log(|l| l.clipboard = t);+ answer.ok(json!(true))+ }+ "clipboard.read" => answer.ok(json!(if live { mac::clipboard_read() } else { log(|l| l.clipboard.clone()) })),+ "app.open" => {+ let url = text(a, "url");+ if !(url.starts_with("https://") || url.starts_with("http://") || url.starts_with("mailto:")) {+ return answer.err(format!("app.open: {url:?} isn't an http(s) or mailto link"));+ }+ if live {+ mac::open(&url);+ }+ log(|l| l.opened.push(url));+ answer.ok(json!(true))+ }+ "notify" => {+ let (title, body) = (text(a, "title"), text(a, "body"));+ if live {+ if let Err(e) = mac::notify(&title, &body) {+ return answer.err(e);+ }+ }+ log(|l| l.notified.push(json!({"title": title, "body": body})));+ answer.ok(json!(true))+ }+ "notify.permission" => {+ if live {+ mac::ask_permission(answer)+ } else {+ answer.ok(json!(true))+ }+ }+ "dock.badge" => {+ let t = text(a, "text");+ if live {+ mac::badge(&t);+ }+ log(|l| l.badge = t);+ answer.ok(json!(true))+ }+ "app.urls" => {+ // a test hands the app a link with {push: url} when nothing is live (a raea:// link opened from outside)+ if !live && let Some(u) = a.get("push").and_then(Value::as_str) {+ URLS.lock().unwrap().push(u.to_string());+ }+ let urls = std::mem::take(&mut *URLS.lock().unwrap());+ log(|l| l.urls.extend(urls.iter().cloned()));+ answer.ok(json!(urls))+ }+ "native.log" => answer.ok(log(|l| json!({"live": live, "clipboard": l.clipboard, "opened": l.opened, "notified": l.notified, "badge": l.badge, "urls": l.urls}))),+ _ => answer.err(format!("no native call {name}")),+ }+}++#[cfg(all(target_os = "macos", feature = "window"))]+mod mac {+ use super::{Answer, URLS};+ use block2::RcBlock;+ use objc2::rc::Retained;+ use objc2::runtime::{AnyClass, AnyObject, Bool, NSObject};+ use objc2::{ClassType, define_class, msg_send};+ use objc2_foundation::NSString;+ use serde_json::json;+ use std::ffi::CString;+ use std::sync::Mutex;++ #[link(name = "UserNotifications", kind = "framework")]+ unsafe extern "C" {}+ #[link(name = "AppKit", kind = "framework")]+ unsafe extern "C" {}++ fn class(name: &str) -> Option<&'static AnyClass> {+ AnyClass::get(&CString::new(name).ok()?)+ }+++ fn rust(s: *mut AnyObject) -> String {+ if s.is_null() {+ return String::new();+ }+ let p: *const std::ffi::c_char = unsafe { msg_send![s, UTF8String] };+ if p.is_null() { String::new() } else { unsafe { std::ffi::CStr::from_ptr(p) }.to_string_lossy().into_owned() }+ }++ fn app() -> *mut AnyObject {+ unsafe { msg_send![class("NSApplication").unwrap(), sharedApplication] }+ }++ /// NSPasteboardTypeString's value+ const PLAIN: &str = "public.utf8-plain-text";++ /// The system clipboard, or (tests) a private pasteboard by name, which never touches the person's clipboard.+ fn pasteboard(name: Option<&str>) -> *mut AnyObject {+ let c = class("NSPasteboard").unwrap();+ match name {+ Some(n) => unsafe { msg_send![c, pasteboardWithName: &*NSString::from_str(n)] },+ None => unsafe { msg_send![c, generalPasteboard] },+ }+ }++ pub fn clipboard_write(t: &str) {+ write_to(None, t)+ }++ pub fn clipboard_read() -> String {+ read_from(None)+ }++ pub(super) fn write_to(name: Option<&str>, t: &str) {+ unsafe {+ let pb = pasteboard(name);+ let _: isize = msg_send![pb, clearContents];+ let _: Bool = msg_send![pb, setString: &*NSString::from_str(t), forType: &*NSString::from_str(PLAIN)];+ }+ }++ pub(super) fn read_from(name: Option<&str>) -> String {+ unsafe {+ let pb = pasteboard(name);+ rust(msg_send![pb, stringForType: &*NSString::from_str(PLAIN)])+ }+ }++ pub fn open(url: &str) {+ unsafe {+ let u: *mut AnyObject = msg_send![class("NSURL").unwrap(), URLWithString: &*NSString::from_str(url)];+ if u.is_null() {+ return;+ }+ let ws: *mut AnyObject = msg_send![class("NSWorkspace").unwrap(), sharedWorkspace];+ let _: Bool = msg_send![ws, openURL: u];+ }+ }++ pub fn badge(t: &str) {+ unsafe {+ let tile: *mut AnyObject = msg_send![app(), dockTile];+ let label: *const AnyObject = if t.is_empty() { std::ptr::null() } else { Retained::into_raw(NSString::from_str(t)).cast::<AnyObject>() };+ let _: () = msg_send![tile, setBadgeLabel: label];+ }+ }++ /// UNUserNotificationCenter refuses a process with no bundle identifier (it raises), so that is checked first.+ fn center() -> Result<*mut AnyObject, String> {+ unsafe {+ let bundle: *mut AnyObject = msg_send![class("NSBundle").unwrap(), mainBundle];+ let id: *mut AnyObject = msg_send![bundle, bundleIdentifier];+ if id.is_null() {+ return Err("notifications need raea.app (this window isn't running as the app)".into());+ }+ let c = class("UNUserNotificationCenter").ok_or("UserNotifications isn't loaded")?;+ Ok(msg_send![c, currentNotificationCenter])+ }+ }++ pub fn ask_permission(answer: Answer) {+ let center = match center() {+ Ok(c) => c,+ Err(e) => return answer.err(e),+ };+ let slot = Mutex::new(Some(answer));+ let done = RcBlock::new(move |granted: Bool, _err: *mut AnyObject| {+ if let Some(a) = slot.lock().unwrap().take() {+ a.ok(json!(granted.as_bool()))+ }+ });+ // alert | sound | badge+ let opts: usize = (1 << 2) | (1 << 1) | 1;+ unsafe {+ let _: () = msg_send![center, requestAuthorizationWithOptions: opts, completionHandler: &*done];+ }+ }++ pub fn notify(title: &str, body: &str) -> Result<(), String> {+ let center = center()?;+ unsafe {+ let content: Retained<AnyObject> = msg_send![class("UNMutableNotificationContent").ok_or("no UNMutableNotificationContent")?, new];+ let _: () = msg_send![&*content, setTitle: &*NSString::from_str(title)];+ let _: () = msg_send![&*content, setBody: &*NSString::from_str(body)];+ let id = NSString::from_str(&format!("raea-{}", std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_nanos()));+ let none: *const AnyObject = std::ptr::null();+ let req: *mut AnyObject = msg_send![class("UNNotificationRequest").unwrap(), requestWithIdentifier: &*id, content: &*content, trigger: none];+ let _: () = msg_send![center, addNotificationRequest: req, withCompletionHandler: none];+ }+ Ok(())+ }++ define_class!(+ // AppKit's Apple event handler for kAEGetURL: a raea:// link opened anywhere on the Mac+ #[unsafe(super(NSObject))]+ #[name = "RaeaUrlHandler"]+ struct UrlHandler;++ impl UrlHandler {+ #[unsafe(method(handle:reply:))]+ fn handle(&self, event: *mut AnyObject, _reply: *mut AnyObject) {+ // keyDirectObject '----'+ let desc: *mut AnyObject = unsafe { msg_send![event, paramDescriptorForKeyword: 0x2d2d2d2du32] };+ let url = if desc.is_null() { String::new() } else { rust(unsafe { msg_send![desc, stringValue] }) };+ if url.starts_with("raea://") {+ URLS.lock().unwrap().push(url);+ }+ let _: () = unsafe { msg_send![app(), activateIgnoringOtherApps: Bool::YES] };+ }+ }+ );++ /// A kAEGetURL event carrying `url`, handed to the handler as AppKit would (tests).+ #[cfg(test)]+ pub(super) fn deliver(url: &str) {+ unsafe {+ let cls = class("NSAppleEventDescriptor").unwrap();+ let none: *const AnyObject = std::ptr::null();+ let gurl: u32 = 0x4755_524c;+ let event: *mut AnyObject = msg_send![cls, appleEventWithEventClass: gurl, eventID: gurl, targetDescriptor: none, returnID: -1i16, transactionID: 0i32];+ let s: *mut AnyObject = msg_send![cls, descriptorWithString: &*NSString::from_str(url)];+ let _: () = msg_send![event, setParamDescriptor: s, forKeyword: 0x2d2d2d2du32];+ let h: Retained<UrlHandler> = msg_send![UrlHandler::class(), new];+ let _: () = msg_send![&*h, handle: event, reply: none];+ }+ }++ pub fn listen_for_urls() {+ unsafe {+ // kept for the app's life: the event manager doesn't retain its handler+ let handler: *mut AnyObject = Retained::<UrlHandler>::into_raw(msg_send![UrlHandler::class(), new]) as *mut AnyObject;+ let mgr: *mut AnyObject = msg_send![class("NSAppleEventManager").unwrap(), sharedAppleEventManager];+ // kInternetEventClass and kAEGetURL are both 'GURL'; the handler lives as long as the app+ let gurl: u32 = 0x4755_524c;+ let _: () = msg_send![mgr, setEventHandler: handler, andSelector: objc2::sel!(handle:reply:), forEventClass: gurl, andEventID: gurl];+ }+ }+}++/// Without a window (the benches, CI, other platforms): nothing reaches the system; Live is false, so these never run.+#[cfg(not(all(target_os = "macos", feature = "window")))]+mod mac {+ use super::Answer;+ pub fn clipboard_write(_: &str) {}+ pub fn clipboard_read() -> String {+ String::new()+ }+ pub fn open(_: &str) {}+ pub fn badge(_: &str) {}+ pub fn notify(_: &str, _: &str) -> Result<(), String> {+ Err("notifications need raea's window on a Mac".into())+ }+ pub fn ask_permission(a: Answer) {+ a.err("notifications need raea's window on a Mac")+ }+ pub fn listen_for_urls() {}+}++#[cfg(all(test, target_os = "macos", feature = "window"))]+mod tests {+ use super::{URLS, mac};++ #[test]+ fn pasteboard_round_trip_on_a_private_board() {+ let name = format!("io.raea.test.{}", std::process::id());+ mac::write_to(Some(&name), "RAEA-CODE-42 ✓");+ assert_eq!(mac::read_from(Some(&name)), "RAEA-CODE-42 ✓");+ }++ #[test]+ fn a_raea_link_reaches_the_queue_and_others_dont() {+ mac::deliver("raea://linked?code=ABC123");+ mac::deliver("https://example.com/not-ours");+ let urls = std::mem::take(&mut *URLS.lock().unwrap());+ assert_eq!(urls, vec!["raea://linked?code=ABC123".to_string()]);+ }++ #[test]+ fn notifications_outside_the_app_say_why() {+ let e = mac::notify("t", "b").unwrap_err();+ assert!(e.contains("raea.app"), "{e}");+ }+}diff --git a/engine/render/Cargo.toml b/engine/render/Cargo.tomlindex a75d09ab..9603ebdd 100644--- a/engine/render/Cargo.toml+++ b/engine/render/Cargo.toml@@ -55,6 +55,9 @@ bytemuck = "1"# the media plane: clips decode through a MediaBackend (soft everywhere, apple on Apple)raea-io-media = { path = "../../io/media", default-features = false, features = ["soft-audio", "apple"], optional = true }+# Bevy's Solari and MetalFX's denoiser on it (the raytracing feature)+raea-render-raytrace = { path = "raytrace", optional = true }+[features]# native: everything that only exists to render on the machine itself (clips' decoders, the GPU frame path and its# traces, the direct views); without it raea-render is the program format and the 3D engine, which is what a browser build needs (docs/web-export.md, milestone 1)@@ -64,6 +67,9 @@ web = ["bevy/webgpu"]# AV1 (dav1d decode, rav1e encode) as a media backend: on by default; an exported game's player goes without it# (lightspeed R7: about 1 MB of code no game uses)default = ["native", "h264", "av1", "scripts", "network"]+# Bevy's Solari, ray-traced lighting and its reference path tracer (docs/raytracing.feature RT3), and MetalFX's+# denoiser on it on the Mac (RT4)+raytracing = ["native", "dep:raea-render-raytrace"]# the soft backend's H.264 (openh264): mezzanines, raea-render export's GOPs, portable video decode; an exported game's# player goes without it and decodes video on the platform (lightspeed R7)h264 = ["native", "raea-io-media/h264"]diff --git a/engine/render/raytrace/Cargo.toml b/engine/render/raytrace/Cargo.tomlnew file mode 100644index 00000000..08d37478--- /dev/null+++ b/engine/render/raytrace/Cargo.toml@@ -0,0 +1,18 @@+[package]+name = "raea-render-raytrace"+version = "0.1.0"+edition = "2024"+license = "FSL-1.1-ALv2"+publish = false+description = "raea-render's ray tracing: Bevy's Solari for a scene whose camera asks for it (RT3), and MetalFX's temporal denoiser on it on the Mac (RT4)"++[dependencies]+bevy = { version = "=0.20.0", default-features = false, features = ["std", "3d_bevy_render", "bevy_solari"] }+# the same wgpu Bevy uses (the guide pass records on its device; MetalFX runs on its Metal objects)+wgpu = "=30.0.1"++# MetalFX's temporal denoiser (wgpu 30 is on objc2-metal 0.3)+[target.'cfg(target_os = "macos")'.dependencies]+objc2 = "0.6"+objc2-metal = { version = "0.3.2", default-features = false, features = ["std", "MTLTexture", "MTLCommandBuffer", "MTLCommandEncoder", "MTLBlitCommandEncoder", "MTLDevice", "MTLPixelFormat", "MTLResource"] }+objc2-metal-fx = "=0.3.2"diff --git a/engine/render/raytrace/src/lib.rs b/engine/render/raytrace/src/lib.rsnew file mode 100644index 00000000..b06d5ff1--- /dev/null+++ b/engine/render/raytrace/src/lib.rs@@ -0,0 +1,25 @@+//! raea-render's ray tracing (docs/raytracing.feature): Bevy's Solari for a scene whose camera asks for it (RT3,+//! solari.rs), and MetalFX's temporal denoiser on its lighting on the Mac (RT4, metalfx.rs). raea-render brings this+//! crate in under its `raytracing` feature and adds it to an engine only when the program asks.++use bevy::prelude::*;+use std::collections::HashMap;++mod solari;+#[cfg(target_os = "macos")]+mod metalfx;++pub use solari::add;++/// The program asks for Solari: a camera's SolariLighting or Pathtracer component (`prog` is raea-render's Program).+pub fn wanted(prog: &impl std::fmt::Debug) -> bool {+ format!("{prog:?}").contains("bevy_solari::")+}++/// After app.finish(): MetalFX's denoiser after Solari's lighting, on the Mac; nothing elsewhere.+pub fn add_denoiser(app: &mut App) {+ #[cfg(target_os = "macos")]+ metalfx::add(app);+ #[cfg(not(target_os = "macos"))]+ let _ = app;+}diff --git a/engine/render/raytrace/src/metalfx.rs b/engine/render/raytrace/src/metalfx.rsnew file mode 100644index 00000000..80d5720f--- /dev/null+++ b/engine/render/raytrace/src/metalfx.rs@@ -0,0 +1,290 @@+//! RT4 (docs/raytracing.feature): MetalFX's temporal denoiser on Solari's lighting, on the Mac. No denoiser of Bevy's+//! runs on Metal (Solari's is DLSS Ray Reconstruction, NVIDIA's), so Solari draws its few rays a pixel as noise there;+//! MTLFXTemporalDenoisedScaler (macOS 26) takes that noisy colour and the frame's guide data and gives it back clean.+//!+//! Each frame, after Solari has lit the view and before the opaque pass draws the forward meshes, a compute pass writes the guide textures MetalFX reads from Bevy's G-buffer (diffuse and specular albedo,+//! world normal, roughness); then a command buffer of its own, recorded through wgpu's Metal backend, runs the+//! denoiser on the view's colour, depth and motion and copies its output back over the colour, before the forward+//! meshes and the tonemapping. The two command buffers go to wgpu's queue in that order, after Solari's.+//!+//! Where there's no MetalFX denoiser (not macOS 26, not Metal, a device it doesn't support) the lighting draws as it+//! is and raea says so once. RAEA_SOLARI_DENOISE=0 turns it off, to see the noise.++use super::*;+use bevy::core_pipeline::core_3d::main_opaque_pass_3d;+use bevy::ecs::schedule::Schedules;+use bevy::core_pipeline::prepass::ViewPrepassTextures;+use bevy::core_pipeline::schedule::{Core3d, Core3dSystems};+use bevy::render::render_resource::TextureFormat;+use bevy::render::renderer::{RenderContext, RenderDevice, ViewQuery};+use bevy::render::view::{ExtractedView, ViewTarget};+use bevy::solari::prelude::SolariLighting;+use objc2::rc::Retained;+use objc2::runtime::ProtocolObject;+use objc2::Message;+use objc2_metal::{MTLBlitCommandEncoder, MTLCommandBuffer, MTLCommandEncoder, MTLPixelFormat, MTLTexture};+use objc2_metal_fx::{MTLFXTemporalDenoisedScaler, MTLFXTemporalDenoisedScalerBase, MTLFXTemporalDenoisedScalerDescriptor};+use wgpu::hal::api::Metal;++/// After app.finish(), when Solari's plugin has put its lighting system in Core3d: the denoiser right after that system+/// and before the opaque pass, as forward-drawn meshes (a <Character>'s skin, an extended material) come after it with+/// nothing in the G-buffer, and denoising them would smear them. Bevy doesn't export Solari's system, so it's found by+/// name and ordered against by its system type set.+pub(crate) fn add(app: &mut App) {+ if std::env::var("RAEA_SOLARI_DENOISE").is_ok_and(|v| v == "0") {+ return;+ }+ let Some(r) = app.get_sub_app_mut(bevy::render::RenderApp) else { return };+ let mut schedules = r.world_mut().resource_mut::<Schedules>();+ let Some(core) = schedules.get_mut(Core3d) else { return };+ let mut solari = None;+ for (_, s, _) in core.graph().systems.iter() {+ if format!("{}", s.name()).ends_with("solari_lighting") {+ solari = s.default_system_sets().into_iter().next();+ break;+ }+ }+ let Some(solari) = solari else {+ eprintln!("raea: <SolariLighting>: Solari's lighting isn't in the render schedule; no MetalFX denoiser");+ return;+ };+ core.add_systems(denoise.after(solari).before(main_opaque_pass_3d).in_set(Core3dSystems::MainPass));+}++// Bevy's G-buffer (bevy_pbr deferred/functions.wesl, types.wesl) to MetalFX's guides: r = base colour (sRGB-ish, pow+// 1/2.2) and perceptual roughness as unorm4x8; b = reflectance, metallic, occlusion, clearcoat as unorm4x8; a = a 24-bit+// octahedral normal (two 12-bit halves) and flags. Specular albedo is F0 (Bevy's 0.16 reflectance² for dielectrics,+// the base colour for metals)+const DECODE_WGSL: &str = r#"+@group(0) @binding(0) var gbuf: texture_2d<u32>;+@group(0) @binding(1) var diffuse: texture_storage_2d<rgba16float, write>;+@group(0) @binding(2) var specular: texture_storage_2d<rgba16float, write>;+@group(0) @binding(3) var normal: texture_storage_2d<rgba16float, write>;+@group(0) @binding(4) var rough: texture_storage_2d<r32float, write>;+fn unorm4x8(p: u32) -> vec4<f32> {+ return vec4<f32>(f32(p & 255u), f32((p >> 8u) & 255u), f32((p >> 16u) & 255u), f32(p >> 24u)) / 255.0;+}+fn octahedral(v: vec2<f32>) -> vec3<f32> {+ let f = v * 2.0 - 1.0;+ var n = vec3<f32>(f, 1.0 - abs(f.x) - abs(f.y));+ let t = saturate(-n.z);+ let w = select(vec2<f32>(t), vec2<f32>(-t), n.xy >= vec2<f32>(0.0));+ n = vec3<f32>(n.xy + w, n.z);+ return normalize(n);+}+@compute @workgroup_size(8, 8, 1)+fn main(@builtin(global_invocation_id) id: vec3<u32>) {+ let size = textureDimensions(diffuse);+ if (id.x >= size.x || id.y >= size.y) { return; }+ let p = vec2<i32>(id.xy);+ let g = textureLoad(gbuf, p, 0);+ let a = unorm4x8(g.r);+ let props = unorm4x8(g.b);+ let base = pow(a.rgb, vec3<f32>(2.2));+ let metallic = props.y;+ let f0 = mix(vec3<f32>(0.16 * props.x * props.x), base, metallic);+ let n = octahedral(vec2<f32>(f32(g.a & 0xFFFu), f32((g.a >> 12u) & 0xFFFu)) / 4095.0);+ textureStore(diffuse, p, vec4<f32>(base * (1.0 - metallic), 1.0));+ textureStore(specular, p, vec4<f32>(f0, 1.0));+ textureStore(normal, p, vec4<f32>(n, 0.0));+ textureStore(rough, p, vec4<f32>(a.w, 0.0, 0.0, 0.0));+}+"#;++/// A view's denoiser and its textures, made again when the view's size changes.+struct View {+ size: UVec2,+ scaler: Retained<ProtocolObject<dyn MTLFXTemporalDenoisedScaler>>,+ diffuse: wgpu::Texture,+ specular: wgpu::Texture,+ normal: wgpu::Texture,+ rough: wgpu::Texture,+ out: wgpu::Texture,+ fresh: bool,+}++#[derive(Default)]+struct Kit {+ pipeline: Option<wgpu::ComputePipeline>,+ views: HashMap<Entity, View>,+ off: bool,+}+// the Metal objects are only touched on the render thread, in this system+unsafe impl Send for Kit {}+unsafe impl Sync for Kit {}++fn texture(dev: &wgpu::Device, size: UVec2, format: wgpu::TextureFormat, usage: wgpu::TextureUsages, label: &str) -> wgpu::Texture {+ dev.create_texture(&wgpu::TextureDescriptor {+ label: Some(label),+ size: wgpu::Extent3d { width: size.x, height: size.y, depth_or_array_layers: 1 },+ mip_level_count: 1,+ sample_count: 1,+ dimension: wgpu::TextureDimension::D2,+ format,+ usage,+ view_formats: &[],+ })+}++/// A texture's MTLTexture, retained.+fn mtl(t: &wgpu::Texture) -> Option<Retained<ProtocolObject<dyn MTLTexture>>> {+ unsafe { t.as_hal::<Metal>() }.map(|t| t.raw_handle().retain())+}++impl View {+ fn new(dev: &wgpu::Device, size: UVec2) -> Result<View, String> {+ let hal = unsafe { dev.as_hal::<Metal>() }.ok_or("the GPU isn't on Metal")?;+ let device = hal.raw_device();+ unsafe {+ if !MTLFXTemporalDenoisedScalerDescriptor::supportsDevice(device) {+ return Err("MetalFX has no denoiser for this GPU (it needs macOS 26 and Apple silicon)".into());+ }+ let d = MTLFXTemporalDenoisedScalerDescriptor::new();+ d.setColorTextureFormat(MTLPixelFormat::RGBA16Float);+ d.setDepthTextureFormat(MTLPixelFormat::Depth32Float);+ d.setMotionTextureFormat(MTLPixelFormat::RG16Float);+ d.setDiffuseAlbedoTextureFormat(MTLPixelFormat::RGBA16Float);+ d.setSpecularAlbedoTextureFormat(MTLPixelFormat::RGBA16Float);+ d.setNormalTextureFormat(MTLPixelFormat::RGBA16Float);+ d.setRoughnessTextureFormat(MTLPixelFormat::R32Float);+ d.setOutputTextureFormat(MTLPixelFormat::RGBA16Float);+ d.setInputWidth(size.x as _);+ d.setInputHeight(size.y as _);+ d.setOutputWidth(size.x as _);+ d.setOutputHeight(size.y as _);+ d.setRequiresSynchronousInitialization(true);+ let scaler = d.newTemporalDenoisedScalerWithDevice(device).ok_or("MetalFX made no denoiser")?;+ drop(hal);+ use wgpu::TextureUsages as U;+ let guide = U::STORAGE_BINDING | U::TEXTURE_BINDING;+ Ok(View {+ size,+ scaler,+ diffuse: texture(dev, size, wgpu::TextureFormat::Rgba16Float, guide, "metalfx diffuse albedo"),+ specular: texture(dev, size, wgpu::TextureFormat::Rgba16Float, guide, "metalfx specular albedo"),+ normal: texture(dev, size, wgpu::TextureFormat::Rgba16Float, guide, "metalfx normal"),+ rough: texture(dev, size, wgpu::TextureFormat::R32Float, guide, "metalfx roughness"),+ out: texture(dev, size, wgpu::TextureFormat::Rgba16Float, guide | U::RENDER_ATTACHMENT | U::COPY_SRC, "metalfx output"),+ fresh: true,+ })+ }+ }++ /// The denoiser on `cb`, then its output copied over the colour.+ fn encode(&mut self, cb: &ProtocolObject<dyn MTLCommandBuffer>, color: &wgpu::Texture, depth: &wgpu::Texture, motion: &wgpu::Texture, view: &ExtractedView, reset: bool) -> Result<(), &'static str> {+ let get = |t: &wgpu::Texture| mtl(t).ok_or("a texture isn't a Metal one");+ let (color, depth, motion) = (get(color)?, get(depth)?, get(motion)?);+ let (diffuse, specular, normal, rough, out) = (get(&self.diffuse)?, get(&self.specular)?, get(&self.normal)?, get(&self.rough)?, get(&self.out)?);+ let s = &*self.scaler;+ unsafe {+ s.setColorTexture(Some(&color));+ s.setDepthTexture(Some(&depth));+ s.setMotionTexture(Some(&motion));+ s.setDiffuseAlbedoTexture(Some(&diffuse));+ s.setSpecularAlbedoTexture(Some(&specular));+ s.setNormalTexture(Some(&normal));+ s.setRoughnessTexture(Some(&rough));+ s.setOutputTexture(Some(&out));+ // Bevy's motion is this frame's UV minus the last's; MetalFX's points from this pixel to where it was, in+ // pixels+ s.setMotionVectorScaleX(-(self.size.x as f32));+ s.setMotionVectorScaleY(-(self.size.y as f32));+ s.setJitterOffsetX(0.0);+ s.setJitterOffsetY(0.0);+ s.setDepthReversed(true);+ s.setShouldResetHistory(reset || self.fresh);+ matrices(s, view.world_from_view.to_matrix().inverse(), view.clip_from_view);+ s.encodeToCommandBuffer(cb);+ let blit = cb.blitCommandEncoder().ok_or("no blit encoder")?;+ blit.copyFromTexture_toTexture(&out, &color);+ blit.endEncoding();+ }+ self.fresh = false;+ Ok(())+ }+}++/// worldToViewMatrix and viewToClipMatrix, simd_float4x4 properties objc2-metal-fx leaves out (no simd types in+/// objc2): sent by hand, as four float32x4 columns (an aggregate of four vectors, passed as simd_float4x4 is). Only on+/// Apple silicon, and only where the scaler has them; objc2 checks a message's types in a debug build and doesn't know+/// simd's, so a debug build leaves them out.+#[allow(unused_variables)]+fn matrices(s: &ProtocolObject<dyn MTLFXTemporalDenoisedScaler>, world_to_view: Mat4, view_to_clip: Mat4) {+ #[cfg(all(target_arch = "aarch64", not(debug_assertions)))]+ unsafe {+ use objc2::{msg_send, sel};+ use std::arch::aarch64::float32x4_t;+ #[repr(C)]+ #[derive(Clone, Copy)]+ struct Float4x4([float32x4_t; 4]);+ unsafe impl objc2::Encode for Float4x4 {+ const ENCODING: objc2::Encoding = objc2::Encoding::Struct("?", &[]);+ }+ let m = |m: Mat4| Float4x4(m.to_cols_array_2d().map(|c| std::mem::transmute::<[f32; 4], float32x4_t>(c)));+ let has: bool = msg_send![s, respondsToSelector: sel!(setWorldToViewMatrix:)];+ if has {+ let _: () = msg_send![s, setWorldToViewMatrix: m(world_to_view)];+ let _: () = msg_send![s, setViewToClipMatrix: m(view_to_clip)];+ }+ }+}++fn denoise(view: ViewQuery<(&ViewTarget, &ViewPrepassTextures, &ExtractedView, &SolariLighting)>, device: Res<RenderDevice>, mut kit: Local<Kit>, mut ctx: RenderContext) {+ if kit.off {+ return;+ }+ let entity = view.entity();+ let (target, pre, ext, solari) = view.into_inner();+ let (Some(depth), Some(motion), Some(gbuf)) = (pre.depth.as_ref(), pre.motion_vectors.as_ref(), pre.deferred.as_ref()) else { return };+ if target.main_texture_format() != TextureFormat::Rgba16Float {+ return;+ }+ let color: &wgpu::Texture = target.main_texture();+ let size = UVec2::new(color.width(), color.height());+ let dev = device.wgpu_device().clone();+ if kit.views.get(&entity).map(|v| v.size) != Some(size) {+ match View::new(&dev, size) {+ Ok(v) => {+ kit.views.insert(entity, v);+ }+ Err(e) => {+ kit.off = true;+ eprintln!("raea: <SolariLighting>: no MetalFX denoiser ({e}); the lighting draws un-denoised (docs/raytracing.feature RT4)");+ return;+ }+ }+ }+ let pipeline = kit+ .pipeline+ .get_or_insert_with(|| {+ let module = dev.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("metalfx guides"), source: wgpu::ShaderSource::Wgsl(DECODE_WGSL.into()) });+ dev.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some("metalfx guides"), layout: None, module: &module, entry_point: Some("main"), compilation_options: Default::default(), cache: None })+ })+ .clone();+ let v = kit.views.get_mut(&entity).unwrap();+ let views = [&v.diffuse, &v.specular, &v.normal, &v.rough].map(|t| t.create_view(&Default::default()));+ let mut entries = vec![wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&*gbuf.texture.default_view) }];+ for (i, tv) in views.iter().enumerate() {+ entries.push(wgpu::BindGroupEntry { binding: i as u32 + 1, resource: wgpu::BindingResource::TextureView(tv) });+ }+ let bind = dev.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("metalfx guides"), layout: &pipeline.get_bind_group_layout(0), entries: &entries });+ {+ let mut pass = ctx.command_encoder().begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("metalfx guides"), timestamp_writes: None });+ pass.set_pipeline(&pipeline);+ pass.set_bind_group(0, &bind, &[]);+ pass.dispatch_workgroups(size.x.div_ceil(8), size.y.div_ceil(8), 1);+ }+ // a command buffer of its own (wgpu won't mix its own commands and raw ones on one encoder), after the guides'+ let mut raw = dev.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("metalfx denoise") });+ let done = unsafe {+ raw.as_hal_mut::<Metal, _, _>(|e| match e.and_then(|e| e.raw_command_buffer()) {+ Some(cb) => v.encode(cb, color, &depth.texture.texture, &motion.texture.texture, ext, solari.reset),+ None => Err("wgpu gave no Metal command buffer"),+ })+ };+ ctx.add_command_buffer(raw.finish());+ if let Err(e) = done {+ kit.off = true;+ eprintln!("raea: <SolariLighting>: the MetalFX denoiser stopped ({e}); the lighting draws un-denoised");+ }+}diff --git a/engine/render/raytrace/src/solari.rs b/engine/render/raytrace/src/solari.rsnew file mode 100644index 00000000..e61d0cc8--- /dev/null+++ b/engine/render/raytrace/src/solari.rs@@ -0,0 +1,111 @@+//! RT3 (docs/raytracing.feature): Bevy's Solari, ray-traced lighting, for a scene whose camera asks for it+//! (<SolariLighting> or <Pathtracer> in raea/3d: SolariLighting or Pathtracer under <Camera3d>). Its plugins come in+//! only then: SolariLightingPlugin makes every opaque material deferred, which would change every other scene.+//! The shared GPU device asks for every feature its adapter has (raea-gpu-device), so ray queries are on where the GPU+//! has them; where it doesn't, Solari's plugins say so and the scene draws with raster lighting.+//!+//! Solari traces a mesh only in one layout (positions, normals, UV 0, tangents, nothing else, u32 indices), so each+//! mesh gets a copy in that layout for its RaytracingMesh3d, made once per mesh. Skinned and morphed meshes (a+//! <Character>) are left raster-lit, as Solari 0.20 can't trace them (RT5).++use super::*;+use bevy::camera::CameraMainTextureUsages;+use bevy::mesh::{Indices, PrimitiveTopology, VertexAttributeValues};+use bevy::solari::pathtracer::{Pathtracer, PathtracingPlugin};+use bevy::solari::prelude::{RaytracingMesh3d, SolariLighting, SolariPlugins};++pub fn add(app: &mut App) {+ app.add_plugins((SolariPlugins, PathtracingPlugin)).add_systems(PostUpdate, (cameras, meshes).before(bevy::camera::CameraUpdateSystems));+}++/// A camera or mesh already set up (or left out).+#[derive(Component)]+struct Done;++// Solari's camera needs: no MSAA and a main texture it can write to (SolariLighting's docs); Hdr, the prepasses and+// deferred come with its required components+fn cameras(mut cmd: Commands, q: Query<(Entity, Option<&CameraMainTextureUsages>), (Or<(With<SolariLighting>, With<Pathtracer>)>, Without<Done>)>) {+ for (e, u) in &q {+ let usages = u.map_or_else(|| CameraMainTextureUsages::default().0, |u| u.0) | bevy::render::render_resource::TextureUsages::STORAGE_BINDING;+ cmd.entity(e).insert((Msaa::Off, CameraMainTextureUsages(usages), Done));+ }+}++type Pending = (With<MeshMaterial3d<StandardMaterial>>, Without<RaytracingMesh3d>, Without<Done>);++fn meshes(+ mut cmd: Commands,+ on: Query<(), Or<(With<SolariLighting>, With<Pathtracer>)>>,+ q: Query<(Entity, &Mesh3d, Has<bevy::mesh::skinning::SkinnedMesh>, Has<bevy::mesh::morph::MeshMorphWeights>), Pending>,+ mut assets: ResMut<Assets<Mesh>>,+ mut copies: Local<HashMap<AssetId<Mesh>, Option<Handle<Mesh>>>>,+ mut said: Local<bool>,+) {+ if on.is_empty() {+ return;+ }+ for (e, m, skinned, morphed) in &q {+ if skinned || morphed {+ if !*said {+ *said = true;+ eprintln!("raea: <SolariLighting>: a skinned or morphed mesh (a <Character>) draws raster-lit; Bevy 0.20's Solari can't trace it (docs/raytracing.feature RT5)");+ }+ cmd.entity(e).insert(Done);+ continue;+ }+ // each mesh's traceable form, made once: itself when it's in Solari's layout, else a copy; None when it can't+ // be traced (not triangles, no normals, or its data only on the GPU)+ let h = match copies.get(&m.0.id()) {+ Some(h) => h.clone(),+ None => {+ let Some(t) = assets.get(&m.0).map(traceable) else { continue };+ let h = match t {+ Some(Traceable::Same) => Some(m.0.clone()),+ Some(Traceable::Copy(mesh)) => Some(assets.add(mesh)),+ None => None,+ };+ copies.insert(m.0.id(), h.clone());+ h+ }+ };+ match h {+ Some(h) => cmd.entity(e).insert((RaytracingMesh3d(h), Done)),+ None => cmd.entity(e).insert(Done),+ };+ }+}++enum Traceable {+ Same,+ Copy(Mesh),+}++fn traceable(src: &Mesh) -> Option<Traceable> {+ if src.primitive_topology() != PrimitiveTopology::TriangleList {+ return None;+ }+ let ids: Vec<_> = src.attributes().map(|(a, _)| a.id).collect();+ let layout = [Mesh::ATTRIBUTE_POSITION.id, Mesh::ATTRIBUTE_NORMAL.id, Mesh::ATTRIBUTE_UV_0.id, Mesh::ATTRIBUTE_TANGENT.id];+ if ids == layout && matches!(src.indices(), Some(Indices::U32(_))) {+ return Some(Traceable::Same);+ }+ let pos = src.attribute(Mesh::ATTRIBUTE_POSITION)?.clone();+ let n = pos.len();+ let normal = src.attribute(Mesh::ATTRIBUTE_NORMAL)?.clone();+ let uv = src.attribute(Mesh::ATTRIBUTE_UV_0).cloned().unwrap_or(VertexAttributeValues::Float32x2(vec![[0.0, 0.0]; n]));+ let mut out = Mesh::new(PrimitiveTopology::TriangleList, bevy::asset::RenderAssetUsages::default());+ out.insert_attribute(Mesh::ATTRIBUTE_POSITION, pos);+ out.insert_attribute(Mesh::ATTRIBUTE_NORMAL, normal);+ out.insert_attribute(Mesh::ATTRIBUTE_UV_0, uv);+ let idx: Vec<u32> = match src.indices() {+ Some(Indices::U32(v)) => v.clone(),+ Some(Indices::U16(v)) => v.iter().map(|&i| i as u32).collect(),+ None => (0..n as u32).collect(),+ };+ out.insert_indices(Indices::U32(idx));+ match src.attribute(Mesh::ATTRIBUTE_TANGENT) {+ Some(t) => out.insert_attribute(Mesh::ATTRIBUTE_TANGENT, t.clone()),+ None => out.generate_tangents().ok()?,+ }+ Some(Traceable::Copy(out))+}diff --git a/engine/render/src/engine.rs b/engine/render/src/engine.rsindex a565220b..b3e36b14 100644--- a/engine/render/src/engine.rs+++ b/engine/render/src/engine.rs@@ -40,6 +40,9 @@ pub(crate) use target::*;mod open;mod load;mod output;+// RT1: each frame's motion vectors and depth, for a neural or denoising pass after the render+mod aov;+pub use aov::Aov;// a frame's rows, the edit, the clock and the row helpers every pass reads (raea-sys-frame)use raea_sys_frame::*;@@ -215,6 +218,7 @@ impl Engine {self.pre_step();plugins::arm(self.app.world_mut());self.app.update();+ self.capture_aov(f);}/// With MotionBlur, the frame before the clock's drawn first (its readback ignored): Bevy takes each mesh's,diff --git a/engine/render/src/engine/aov.rs b/engine/render/src/engine/aov.rsnew file mode 100644index 00000000..e1b67151--- /dev/null+++ b/engine/render/src/engine/aov.rs@@ -0,0 +1,143 @@+//! RT1 (docs/raytracing.feature): each frame's motion vectors and depth, the guide data a neural or denoising pass+//! after the render needs (MLX-DLSS's run-sequence, MetalFX). Asked for with `want_aov`, before the first draw: the 3D+//! cameras then draw Bevy's depth and motion-vector prepasses (MSAA off: a multisampled prepass can't be read), and+//! each frame's first draw reads both back (`take_aov`). A redraw of the same frame keeps the first draw's: drawn+//! again, every mesh's last pose is its pose now, and its motion would read zero.++use super::*;+use bevy::core_pipeline::prepass::{DepthPrepass, MotionVectorPrepass, ViewPrepassTextures};++/// One frame's guide data at the prepass's size (the frame's, times RAEA_SS).+pub struct Aov {+ pub w: u32,+ pub h: u32,+ /// w x h x 2, Bevy's motion vectors: this frame's UV minus the last frame's (x right, y down)+ pub motion: Vec<f32>,+ /// w x h, reverse Z (1 at the near plane, 0 at infinity)+ pub depth: Vec<f32>,+}++/// The guide data is wanted; `frame` is the frame last read, `last` what it read.+#[derive(Resource, Default)]+pub(crate) struct AovWanted {+ frame: Option<i64>,+ last: Option<Aov>,+}++fn aov_prepasses(mut cmd: Commands, q: Query<Entity, (With<Camera3d>, Without<MotionVectorPrepass>)>) {+ for e in &q {+ cmd.entity(e).insert((DepthPrepass, MotionVectorPrepass, Msaa::Off));+ }+}++// the motion texture is made without COPY_SRC (bevy_core_pipeline's prepare_core_3d_depth_textures), so it's read in+// a shader, not copied: both textures into one buffer, three floats a pixel+const AOV_WGSL: &str = r#"+@group(0) @binding(0) var depth_t: texture_depth_2d;+@group(0) @binding(1) var motion_t: texture_2d<f32>;+@group(0) @binding(2) var<storage, read_write> out: array<f32>;+@group(0) @binding(3) var<uniform> dims: vec4<u32>;+@compute @workgroup_size(8, 8, 1)+fn main(@builtin(global_invocation_id) id: vec3<u32>) {+ if (id.x >= dims.x || id.y >= dims.y) { return; }+ let p = vec2<i32>(id.xy);+ let m = textureLoad(motion_t, p, 0).xy;+ let i = (id.y * dims.x + id.x) * 3u;+ out[i] = m.x;+ out[i + 1u] = m.y;+ out[i + 2u] = textureLoad(depth_t, p, 0);+}+"#;++impl Engine {+ /// Draw the guide data from now on (before the first draw: a camera's prepass is set up as it's extracted).+ pub fn want_aov(&mut self) {+ if self.app.world().contains_resource::<AovWanted>() {+ return;+ }+ self.app.init_resource::<AovWanted>();+ self.app.add_systems(Update, aov_prepasses);+ }++ /// Frame f's guide data, read after its first draw (Engine::draw calls this).+ pub(crate) fn capture_aov(&mut self, f: i64) {+ let Some(w) = self.app.world().get_resource::<AovWanted>() else { return };+ if w.frame == Some(f) {+ return;+ }+ let got = self.read_aov();+ let mut w = self.app.world_mut().resource_mut::<AovWanted>();+ w.frame = Some(f);+ match got {+ Ok(a) => w.last = Some(a),+ Err(e) => {+ w.last = None;+ eprintln!("raea: frame {f}: no motion vectors or depth: {e}");+ }+ }+ }++ /// The guide data the last frame drawn read, taken (None when it wasn't asked for or couldn't be read).+ pub fn take_aov(&mut self) -> Option<Aov> {+ self.app.world_mut().get_resource_mut::<AovWanted>()?.last.take()+ }++ fn read_aov(&mut self) -> Result<Aov, String> {+ let rw = self.app.get_sub_app_mut(bevy::render::RenderApp).ok_or("no render app")?.world_mut();+ // the biggest view with both (the frame's camera; a screen's or a mirror's is smaller)+ let mut q = rw.query::<&ViewPrepassTextures>();+ let pick = q+ .iter(rw)+ .filter(|t| t.depth.is_some() && t.motion_vectors.is_some())+ .max_by_key(|t| t.size.width * t.size.height)+ .ok_or("no 3D camera drew a depth and motion-vector prepass")?;+ // the target is a row taller than the frame (the frame tag's row, open.rs), at the frame's scale (RAEA_SS)+ let (w, h) = (pick.size.width, pick.size.height.min(self.h * (pick.size.width / self.w.max(1)).max(1)));+ let depth = pick.depth_only_view().ok_or("the prepass has no depth view")?.clone();+ let motion = pick.motion_vectors.as_ref().unwrap().texture.default_view.clone();+ let device = rw.resource::<bevy::render::renderer::RenderDevice>().wgpu_device().clone();+ let queue = rw.resource::<bevy::render::renderer::RenderQueue>().clone();+ let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("aov"), source: wgpu::ShaderSource::Wgsl(AOV_WGSL.into()) });+ let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some("aov"), layout: None, module: &module, entry_point: Some("main"), compilation_options: Default::default(), cache: None });+ let size = w as u64 * h as u64 * 12;+ let out = device.create_buffer(&wgpu::BufferDescriptor { label: Some("aov"), size, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false });+ let back = device.create_buffer(&wgpu::BufferDescriptor { label: Some("aov readback"), size, usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, mapped_at_creation: false });+ let dims = wgpu::util::DeviceExt::create_buffer_init(&device, &wgpu::util::BufferInitDescriptor { label: Some("aov dims"), contents: bytemuck::cast_slice(&[w, h, 0u32, 0u32]), usage: wgpu::BufferUsages::UNIFORM });+ let bind = device.create_bind_group(&wgpu::BindGroupDescriptor {+ label: Some("aov"),+ layout: &pipeline.get_bind_group_layout(0),+ entries: &[+ wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&*depth) },+ wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(&*motion) },+ wgpu::BindGroupEntry { binding: 2, resource: out.as_entire_binding() },+ wgpu::BindGroupEntry { binding: 3, resource: dims.as_entire_binding() },+ ],+ });+ let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("aov") });+ {+ let mut pass = enc.begin_compute_pass(&Default::default());+ pass.set_pipeline(&pipeline);+ pass.set_bind_group(0, &bind, &[]);+ pass.dispatch_workgroups(w.div_ceil(8), h.div_ceil(8), 1);+ }+ enc.copy_buffer_to_buffer(&out, 0, &back, 0, size);+ queue.submit([enc.finish()]);+ let (tx, rx) = std::sync::mpsc::channel();+ back.slice(..).map_async(wgpu::MapMode::Read, move |r| {+ let _ = tx.send(r);+ });+ device.poll(wgpu::PollType::Wait { submission_index: None, timeout: Some(std::time::Duration::from_secs(60)) }).map_err(|e| format!("the guide data's readback: {e}"))?;+ rx.recv().map_err(|e| e.to_string())?.map_err(|e| format!("the guide data's readback: {e}"))?;+ let data = back.slice(..).get_mapped_range().map_err(|e| format!("the guide data's readback: {e:?}"))?;+ let px: &[f32] = bytemuck::cast_slice(&data);+ let n = (w * h) as usize;+ let (mut motion, mut depth) = (Vec::with_capacity(n * 2), Vec::with_capacity(n));+ for p in px.chunks_exact(3) {+ motion.extend_from_slice(&p[..2]);+ depth.push(p[2]);+ }+ drop(data);+ back.unmap();+ Ok(Aov { w, h, motion, depth })+ }+}diff --git a/engine/render/src/engine/open.rs b/engine/render/src/engine/open.rsindex e8f28203..0b6fc0a8 100644--- a/engine/render/src/engine/open.rs+++ b/engine/render/src/engine/open.rs@@ -27,7 +27,12 @@ impl Engine {#[cfg(not(target_arch = "wasm32"))]let group = group.disable::<bevy::render::pipelined_rendering::PipelinedRenderingPlugin>();// a registered Bevy plugin may change the group (plugins.rs: one that brings bevy_winit turns WinitPlugin off)- app.add_plugins(plugins::group(group))+ app.add_plugins(plugins::group(group));+ #[cfg(feature = "raytracing")]+ if raea_render_raytrace::wanted(prog) {+ raea_render_raytrace::add(&mut app);+ }+ app.init_resource::<Clock>().init_resource::<Out>().init_resource::<Error>()@@ -152,6 +157,11 @@ impl Engine {mem_mark("engine: plugins built (DefaultPlugins, the render device)");app.finish();mem_mark("engine: plugins finished");+ // RT4: MetalFX's denoiser goes in after Solari's lighting, which Solari's plugin adds as it finishes+ #[cfg(feature = "raytracing")]+ if raea_render_raytrace::wanted(prog) {+ raea_render_raytrace::add_denoiser(&mut app);+ }// lights clustered on the CPU, not by Bevy 0.19's GPU clustering: on a fresh engine's first frames the GPU's// cluster lists left a spot light out (its fog shaft drawn, its light on no surface), for as many updates as its// readback took, so a render (a fresh engine a frame) missed it where play, warm, had it: volumetric-grid'sdiff --git a/engine/render/src/engine/spawn.rs b/engine/render/src/engine/spawn.rsindex 95c68ad5..1cdfd24d 100644--- a/engine/render/src/engine/spawn.rs+++ b/engine/render/src/engine/spawn.rs@@ -176,7 +176,11 @@ pub(crate) fn spawn_3d(world: &mut World, e: Entity, t: &Tup, inserted: &[Tup],match t.kind.as_str() {// directional (as before), point or spot: scene3d"light" => scene3d::light(world, e, vals),- "model" => scene3d::model(world, e, t, inserted, dir)?,+ // and its cloth, when it has one (meshseq/cloth.rs)+ "model" => {+ scene3d::model(world, e, t, inserted, dir)?;+ meshseq::cloth::spawn(world, e, t, inserted, dir)?+ }// a picture pressed onto a surface (<Decal>): decal.rs"decal" => decal::spawn(world, e, t, inserted, dir)?,// a box of air a <VolumetricFog> draws: scene3ddiff --git a/io/assets/Cargo.toml b/io/assets/Cargo.tomlindex 88511812..96e01281 100644--- a/io/assets/Cargo.toml+++ b/io/assets/Cargo.toml@@ -4,9 +4,7 @@ version = "0.1.0"edition = "2024"license = "FSL-1.1-ALv2"publish = false-description = "Made assets: a composition's make(model, prompt, seed, params) kept once under its content hash, from the local models (SAO, TokenSynth, splats, matchmove) or raea's API"--[features]+description = "Made assets: a composition's make(model, prompt, seed, params) kept once under its content hash, from the local models (SAO, TokenSynth, splats, matchmove)"[dependencies]raea-io-home = { path = "../home" }diff --git a/io/assets/src/api.rs b/io/assets/src/api.rsdeleted file mode 100644index 3124dda3..00000000--- a/io/assets/src/api.rs+++ /dev/null@@ -1,71 +0,0 @@-//! make()s through raea's API (fish narration, the `service` feature), with the paid-request cap and its ledger.--use super::*;---/// Where a run's paid requests are counted: the file the host names in $RAEA_GEN_LEDGER (void: one per eval scenario,-/// one per agent turn), whole; else the edit's own assets/paid.jsonl over the last 24 hours. Every render is its-/// own process, so the count has to outlive one.-pub(crate) fn ledger(dir: &Path) -> (PathBuf, Option<u64>) {- match std::env::var_os("RAEA_GEN_LEDGER").filter(|v| !v.is_empty()) {- Some(p) => (PathBuf::from(p), None),- None => (dir.join("paid.jsonl"), Some(24 * 3600)),- }-}--pub(crate) fn now_s() -> u64 {- std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)-}--/// Whether a paid request may go now. On by default and capped (the founder's decision, 2026-10-15): $RAEA_GEN_PAID=0-/// turns paid models off, and $RAEA_GEN_BUDGET=N sets the cap per run (default PAID_PER_RUN). A cached make() sends-/// nothing and counts nothing.-pub(crate) fn paid_allowed(model: &str, dir: &Path) -> Result<(), String> {- if std::env::var("RAEA_GEN_PAID").as_deref() == Ok("0") {- return Err(format!("{model} is paid generation, and the host turned it off (RAEA_GEN_PAID=0)"));- }- let n = std::env::var("RAEA_GEN_BUDGET").ok().and_then(|n| n.trim().parse::<usize>().ok()).unwrap_or(PAID_PER_RUN);- let (file, window) = ledger(dir);- let since = window.map(|w| now_s().saturating_sub(w)).unwrap_or(0);- let spent = std::fs::read_to_string(&file).unwrap_or_default().lines()- .filter_map(|l| serde_json::from_str::<J>(l).ok())- .filter(|l| l["t"].as_u64().unwrap_or(0) >= since)- .count();- if spent >= n {- return Err(format!("{model}: this run has used its {n} paid generations (RAEA_GEN_BUDGET); use tokensynth or sao (local), a cached take, or no sound"));- }- Ok(())-}--/// One paid request, counted when it's sent: a request that fails may still be billed.-pub(crate) fn count_paid(model: &str, dir: &Path) {- let (file, _) = ledger(dir);- if let Some(d) = file.parent() {- let _ = std::fs::create_dir_all(d);- }- if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&file) {- use std::io::Write;- let _ = writeln!(f, "{}", json!({"t": now_s(), "model": model}));- }-}--/// A setting: the process environment first, then raea's settings file ($RAEA_ENV_FILE, else ~/.raea/env).-pub(crate) fn setting(name: &str) -> Option<String> {- if let Some(v) = std::env::var(name).ok().filter(|v| !v.trim().is_empty()) {- return Some(v.trim().to_string());- }- let file = std::env::var_os("RAEA_ENV_FILE").map(PathBuf::from)- .unwrap_or_else(|| PathBuf::from(std::env::var_os("HOME").unwrap_or_default()).join(".raea/env"));- std::fs::read_to_string(file).ok()?.lines().find_map(|l| {- let (k, v) = l.trim().split_once('=')?;- (k.trim() == name && !l.trim_start().starts_with('#')).then(|| v.trim().trim_matches('"').to_string())- }).filter(|v| !v.is_empty())-}---/// A build without raea's API (the public engine) makes only with the local models.-#[cfg(not(feature = "service"))]-pub(crate) fn api(model: &str, _prompt: &str, _params: &J, _part: &Path) -> Result<(Vec<u8>, String), String> {- Err(format!("{model} isn't in this build of raea (the local models are tokensynth for music and sao for foley)"))-}-diff --git a/io/assets/src/lib.rs b/io/assets/src/lib.rsindex 3ced50e5..84d96b52 100644--- a/io/assets/src/lib.rs+++ b/io/assets/src/lib.rs@@ -4,15 +4,12 @@//!//! `make` is a registry keyed by model name: `stand-in` (a deterministic gradient and shapes drawn from the prompt and//! seed, what tests use), the two local audio models, `tokensynth` (an instrument's notes, for music) and `sao` (Stable-//! Audio Open on Core ML, foley), and raea's API: `fish` (narration). `lyria` (music) is retired:-//! a take made before plays from the index, and a new one is refused. The local models install themselves on first use (tools/sao/setup.sh,+//! Audio Open on Core ML, foley). Every model runs on this computer. `lyria` (music) and `fish` (narration, through+//! raea's API) are retired: a take made before plays from the index, and a new one is refused. Narration is Pocket TTS+//! (raea/speech), and Fish Audio is a `raea gen` backend like fal or Replicate (`fish:<model>`, the founder's own key). The local models install themselves on first use (tools/sao/setup.sh,//! tools/tokensynth/setup.sh). Each made asset gets a line in `assets/made.jsonl` under its cache key, a hash of//! (model, prompt, seed, params); `made` reads only that index, so a render or a check that resolves a make() never//! generates.-//!-//! raea's API (`fish`, signed in with a device token) is the `service` feature; the public engine builds without it, and-//! its paid-request bookkeeping below goes unused there.-#![cfg_attr(not(feature = "service"), allow(dead_code))]use std::path::{Path, PathBuf};@@ -27,18 +24,13 @@ pub use splat::{ensure_splat, splat_dir, splat_params};mod local;use local::*;-mod api;-use api::*;#[cfg(test)]mod tests;-/// The models `make` knows, by the name an edit writes: local ones first, then the paid API's. `matchmove` (a camera+/// The models `make` knows, by the name an edit writes: the local ones, then the retired ones whose takes still play. `matchmove` (a camera/// solve) is made from a clip, by `Store::matchmove`, and indexed the same way.pub const MODELS: [&str; 6] = ["stand-in", "tokensynth", "sao", "fish", "lyria", "matchmove"];-/// Paid requests a run may send when the host doesn't say ($RAEA_GEN_BUDGET): the founder's choice, on and capped small.-pub const PAID_PER_RUN: usize = 3;-/// TokenSynth's runtimes (tools/tokensynth/run.py --precision), and the one a note gets when its params don't say.pub const TOKENSYNTH_PRECISIONS: [&str; 5] = ["fp32", "fp16", "bf16", "int8", "coreml"];pub const TOKENSYNTH_PRECISION: &str = "fp16";@@ -109,7 +101,8 @@ impl Store {"tokensynth" => tokensynth(prompt, seed, params, &part).map(|wav| (wav, "wav".to_string())),"matchmove" => Err("matchmove is made from a clip: Store::matchmove(clip, params)".to_string()),"lyria" => Err("lyria is retired (raea's generation policy, 2026-10-20): make music with tokensynth; a lyria take made before still plays from assets/made.jsonl".to_string()),- _ => api(model, prompt, params, &part),+ "fish" => Err("fish is no longer part of raea (2026-11-05): narrate with <Speech> from raea/speech (Pocket TTS, on this computer), or make a line with a `raea gen` step on fish:<model> and your FISH_API_KEY; a fish take made before still plays from assets/made.jsonl".to_string()),+ _ => Err(format!("unknown model `{model}`")),};let _ = std::fs::remove_file(&part);let (bytes, ext) = made?;@@ -229,6 +222,7 @@ pub fn ensure_installed(model: &str) -> Result<PathBuf, String> {if std::env::var("RAEA_AUDIO_AUTOSETUP").as_deref() == Ok("0") {return Err(format!("{model} isn't installed: run {how}"));}+ raea_io_home::offline(&format!("installing {model} ({size} downloaded)"))?;if !script.exists() {return Err(format!("{model} isn't installed in {}, and its setup script isn't at {}", dir.display(), script.display()));}diff --git a/io/assets/src/tests.rs b/io/assets/src/tests.rsindex 91787f3c..1be89899 100644--- a/io/assets/src/tests.rs+++ b/io/assets/src/tests.rs@@ -1,5 +1,12 @@use super::*;+#[test]+fn a_new_fish_take_is_refused() {+ let s = Store { dir: std::env::temp_dir().join(format!("render-fish-{}", std::process::id())) };+ let e = s.make("fish", "Three drops.", 1, &json!({})).unwrap_err();+ assert!(e.contains("no longer part of raea") && e.contains("<Speech>"), "{e}");+ let _ = std::fs::remove_dir_all(&s.dir);+}#[test]fn a_new_lyria_take_is_refused() {@@ -8,7 +15,6 @@ fn a_new_lyria_take_is_refused() {let _ = std::fs::remove_dir_all(&s.dir);}-#[test]fn the_key_ignores_param_order_but_not_seed_or_params() {let k = make_key("sao", "rain", 3, &json!({"seconds": 6, "a": 1}));diff --git a/io/gen-comfy/Cargo.toml b/io/gen-comfy/Cargo.tomlnew file mode 100644index 00000000..d9d7ead0--- /dev/null+++ b/io/gen-comfy/Cargo.toml@@ -0,0 +1,11 @@+[package]+name = "raea-io-gen-comfy"+version = "0.1.0"+edition = "2024"+license = "FSL-1.1-ALv2"+publish = false+description = "ComfyUI both ways for generation flows: any workflow read and lifted to a flow, a flow written as a workflow, and a ComfyUI server as a place steps run"++[dependencies]+raea-io-gen-core = { path = "../gen-core" }+serde_json = "1"diff --git a/io/gen-comfy/src/api_nodes.rs b/io/gen-comfy/src/api_nodes.rsnew file mode 100644index 00000000..0845ec58--- /dev/null+++ b/io/gen-comfy/src/api_nodes.rs@@ -0,0 +1,178 @@+//! ComfyUI's partner API nodes (comfy.org bills them in its own credits) as made steps: the same vendor's model on+//! made.app, at the provider's price. A node's class names the vendor and what it does; its `model` setting, when it+//! has one, picks the version. 3D nodes (Tripo, Meshy, Rodin, Hunyuan) go to the same vendor on fal, since made makes+//! no meshes. The chat nodes+//! (Claude, OpenAI, Gemini) become text.generate on OpenRouter. Luma, Pixverse, Vidu and Runway stay ComfyUI.++use serde_json::{Map, Value as J, json};++use raea_io_gen_core::flow::Step;+++/// Class prefix, what it does (`image`: generate, or edit when it's given an image; `video`: likewise with a video;+/// `upscale`, `vupscale`, `speech`, `lipsync`, …), and its made model unless VERSIONS picks another.+const TABLE: &[(&str, &str, &str)] = &[+ ("GeminiImage", "image", "nano_banana_2"),+ ("GeminiNanoBanana2", "image", "nano_banana_2"),+ ("OpenAIGPTImage", "image", "gpt_image_2"),+ ("OpenAIDalle", "image", "gpt_image_2"),+ ("ByteDanceSeedream", "image", "seedream_5_pro"),+ ("ByteDanceImageEdit", "image", "seedream_5_pro_edit"),+ ("GrokImage", "image", "grok_imagine_image_2"),+ ("Flux2Image", "image", "flux_2_pro"),+ ("Flux3Image", "image", "flux_2_pro"),+ ("FluxKontextMax", "image", "flux_kontext_max"),+ ("FluxKontext", "image", "flux_kontext_pro"),+ ("FluxProUltra", "image", "flux_1_1_pro"),+ ("FluxPro", "image", "flux_1_1_pro"),+ ("RecraftV4TextToImage", "image", "recraft_4_1"),+ ("RecraftTextToImage", "image", "recraft_4_1"),+ ("Krea", "image", "krea_2"),+ ("MetaMuseImage", "image", "muse_image"),+ ("QwenImage", "image", "qwen_image_3"),+ ("IdeogramV4", "image", "ideogram_v4_5_edit"),+ ("ReveImage", "image", "reve_create"),+ ("BriaRemoveBackground", "rembg", "bria_background_removal"),+ ("WavespeedImageUpscale", "upscale", "topaz_upscale_image"),+ ("MagnificImageUpscaler", "upscale", "topaz_upscale_image"),+ ("TopazImage", "upscale", "topaz_upscale_image"),+ ("WavespeedFlashVSR", "vupscale", "seedvr_video_upscale"),+ ("TopazVideo", "vupscale", "seedvr_video_upscale"),+ ("KlingOmniProEditVideo", "video", "kling_o3_edit_pro"),+ ("KlingOmniPro", "video", "kling_o3_pro"),+ ("Kling4", "video", "kling_4"),+ ("KlingLipSync", "lipsync", "kling_lipsync"),+ ("KlingAvatar", "lipsync", "kling_avatar_v2_pro"),+ ("KlingMotionControl", "video", "kling_3_motion_control_pro"),+ ("Kling", "video", "kling_3_pro"),+ ("Veo3", "video", "veo_3_1"),+ ("Veo", "video", "veo_3_1"),+ ("ByteDance2Reference", "video", "seedance_2_5_reference"),+ ("ByteDance2", "video", "seedance_2"),+ ("ByteDanceImageToVideo", "video", "seedance_1_5_pro"),+ ("ByteDanceTextToVideo", "video", "seedance_1_5_pro"),+ ("ByteDanceFirstLastFrame", "video", "seedance_1_5_pro"),+ ("MinimaxHailuo03Reference", "video", "minimax_h3_max_reference"),+ ("MinimaxHailuo03", "video", "minimax_h3_max"),+ ("MinimaxHailuo", "video", "hailuo_02"),+ ("Minimax", "video", "hailuo_02"),+ ("Wan3Reference", "video", "wan_3_0_prime_reference"),+ ("Wan3", "video", "wan_3"),+ ("Wan2VideoEdit", "video", "wan_3_reference_edit"),+ ("Wan2", "video", "wan_2_7"),+ ("WanImageToVideoApi", "video", "wan_2_5_i2v"),+ ("WanTextToVideoApi", "video", "wan_2_7"),+ ("WanReferenceVideoApi", "video", "wan_3_0_prime_reference"),+ ("HappyHorse", "video", "happy_horse_1_1"),+ ("LtxApi", "video", "ltx_2_5_fast"),+ ("GrokVideoExtend", "video", "grok_imagine_video_extend"),+ ("GrokVideo", "video", "grok_imagine_video_1_5"),+ ("FluxVideoEdit", "video", "flux_3"),+ ("SyncLipSync", "lipsync", "sync_lipsync_v3"),+ ("SyncTalkingImage", "lipsync", "omnihuman_1_5"),+ ("VeedFabric", "lipsync", "veed_fabric"),+ ("ElevenLabsTextToSpeech", "speech", "elevenlabs_turbo_v2_5"),+ ("HeyGenTextToSpeech", "speech", "elevenlabs_turbo_v2_5"),+ ("HeyGenVoiceTextToSpeech", "speech", "elevenlabs_turbo_v2_5"),+ ("ElevenLabsSoundEffects", "sfx", "elevenlabs_sound_effects_v2"),+ ("ElevenLabsMusic", "music", "elevenlabs_music_v2_5"),+ // the chat nodes write prompts: OpenRouter has each vendor's models+ ("ClaudeNode", "text", "anthropic/claude-sonnet-4.5"),+ ("OpenAIChatNode", "text", "openai/gpt-5"),+ ("OpenRouterLLMNode", "text", "moonshotai/kimi-k3.1-pro"),+ ("GeminiNode", "text", "google/gemini-2.5-flash"),+ // 3D: no made model makes meshes, so these go to fal directly (an endpoint id has a slash)+ ("TripoTextToModel", "mesh", "tripo3d/h3.1/text-to-3d"),+ ("TripoImageToModel", "mesh", "tripo3d/h3.1/image-to-3d"),+ ("TripoMultiviewToModel", "mesh", "tripo3d/h3.1/multiview-to-3d"),+ ("TripoP1ImageToModel", "mesh", "tripo3d/p1/image-to-3d"),+ ("TripoPSeriesImageToModel", "mesh", "tripo3d/p2/image-to-3d"),+ ("MeshyTextToModel", "mesh", "meshy/v7.1/text-to-3d"),+ ("MeshyImageToModel", "mesh", "meshy/v7.1/image-to-3d"),+ ("MeshyMultiImageToModel", "mesh", "meshy/v7.1/multi-image-to-3d"),+ ("Rodin3D", "mesh", "fal-ai/hyper3d/rodin/v2.5"),+ ("TencentImageToModel", "mesh", "fal-ai/hunyuan-3d/v3.1/pro/image-to-3d"),+ ("TencentTextToModel", "mesh", "fal-ai/hunyuan-3d/v3.1/pro/text-to-3d"),+];++/// A TABLE row's other models: the first whose text is in the node's `model` setting (lowercased) wins.+const VERSIONS: &[(&str, &str, &str)] = &[+ ("GeminiImage", "3-pro", "nano_banana_pro"), ("GeminiImage", "pro-image", "nano_banana_pro"), ("GeminiImage", "2.5", "nano_banana"),+ ("OpenAIGPTImage", "2.5", "gpt_image_2_5_flare"),+ ("ByteDanceSeedream", "4.5", "seedream_5_pro"), ("ByteDanceSeedream", "4", "seedream_4"),+ ("GrokImage", "quality", "grok_imagine_image_quality"),+ ("Kling", "2-6", "kling_2_6"), ("Kling", "2.6", "kling_2_6"), ("Kling", "2-5", "kling_2_5_turbo_pro"), ("Kling", "2.5", "kling_2_5_turbo_pro"),+ ("Veo3", "fast", "veo_3_fast"), ("Veo", "fast", "veo_3_fast"),+];++/// ComfyUI input names and the flow input each becomes.+const NAMES: &[(&str, &str)] = &[+ ("prompt", "prompt"), ("text", "prompt"), ("negative_prompt", "negative"), ("seed", "seed"), ("aspect_ratio", "aspect_ratio"),+ ("duration", "seconds"), ("resolution", "resolution"), ("generate_audio", "audio"),+ ("first_frame", "start_image"), ("start_frame", "start_image"), ("start_image", "start_image"),+ ("end_frame", "end_image"), ("last_frame", "end_image"), ("end_image", "end_image"),+ ("image", "image"), ("images", "image"), ("input_image", "image"), ("reference_images", "refs"), ("reference_image", "refs"),+ ("video", "video"), ("audio", "x_audio"),+];++/// A partner node as a step (its links still `[id, slot]`, for the lifter to point at steps), or None.+pub fn api_step(class: &str, inputs: &Map<String, J>) -> Option<Step> {+ let (row, does, model) = TABLE.iter().find(|(prefix, _, _)| class.starts_with(prefix))?;+ let setting = inputs.get("model").and_then(|m| m.as_str()).unwrap_or("").to_ascii_lowercase();+ let made = VERSIONS.iter().find(|(r, text, _)| r == row && setting.contains(text)).map_or(*model, |v| v.2);+ let mut i = Map::new();+ for (k, v) in inputs {+ // a dynamic combo's settings (`model.resolution`) are the chosen version's own+ let base = k.rsplit('.').next().unwrap_or(k);+ if let Some((_, to)) = NAMES.iter().find(|(from, _)| *from == base) {+ i.entry(to.to_string()).or_insert(v.clone());+ }+ }+ let (has_image, has_video) = (i.contains_key("image") || i.contains_key("refs"), i.contains_key("video"));+ let op = match *does {+ "image" if has_image => "image.edit",+ "image" => "image.generate",+ "video" if has_video => "video.edit",+ "video" => {+ if let Some(img) = i.remove("image") {+ i.entry("start_image".to_string()).or_insert(img);+ }+ "video.generate"+ }+ "upscale" => "image.upscale",+ "rembg" => "image.remove_background",+ "vupscale" => "video.upscale",+ "speech" => {+ if let Some(p) = i.remove("prompt") {+ i.insert("text".into(), p);+ }+ "audio.speech"+ }+ "sfx" => "audio.sfx",+ "music" => "audio.music",+ "mesh" => "mesh.generate",+ "text" => "text.generate",+ // lip sync: a video (or a still) and the audio it's synced to+ _ => {+ let media = i.remove("video").or_else(|| i.remove("image")).or_else(|| i.remove("start_image"));+ i.insert("video".into(), media.unwrap_or(J::Null));+ i.entry("prompt".to_string()).or_insert(json!(""));+ "video.edit"+ }+ };+ if op == "image.edit" && !i.contains_key("image") {+ if let Some(r) = i.remove("refs") {+ i.insert("image".into(), r);+ }+ }+ if op == "image.edit" || op == "video.edit" || op == "video.generate" {+ i.entry("prompt".to_string()).or_insert(json!(""));+ }+ // inputs an op doesn't take are carried as the model's own (x_…)+ let known = raea_io_gen_core::flow::op(op).map(|o| [o.2, o.3].concat()).unwrap_or_default();+ let i: Map<String, J> = i.into_iter().map(|(k, v)| if known.contains(&k.as_str()) || k.starts_with("x_") { (k, v) } else { (format!("x_{k}"), v) }).collect();+ let mut s = Step::new(op, J::Object(i));+ s.model = Some(match (*does, made.contains('/')) { ("text", _) => format!("openrouter:{made}"), (_, true) => format!("fal:{made}"), _ => format!("made:{made}") });+ s.from = Some(format!("comfy {class} ({})", if setting.is_empty() { "-" } else { &setting }));+ Some(s)+}diff --git a/io/gen-comfy/src/lib.rs b/io/gen-comfy/src/lib.rsnew file mode 100644index 00000000..f4107343--- /dev/null+++ b/io/gen-comfy/src/lib.rs@@ -0,0 +1,29 @@+//! ComfyUI both ways: a workflow (UI or API format) read into named nodes and lifted to a flow; a flow written back as+//! an API-format workflow; and a ComfyUI server (local, or hosted on Modal or any machine) as a place a step runs.++pub mod api_nodes;+pub mod lift;+pub mod needs;+pub mod read;+pub mod schema;+pub mod server;+pub mod view;+pub mod write;++use serde_json::Value as J;++use raea_io_gen_core::flow::Flow;++pub(crate) use raea_io_gen_core::flow::index as flow_index;++/// A workflow's JSON as a flow, with the schema this machine has.+pub fn import(v: &J) -> Result<lift::Lifted, String> {+ let schema = schema::load();+ let g = read::read(v, &schema)?;+ Ok(lift::lift(&g, &schema))+}++/// A flow as API-format JSON for ComfyUI's /prompt.+pub fn export(f: &Flow) -> Result<J, String> {+ write::write(f)+}diff --git a/io/gen-comfy/src/lift.rs b/io/gen-comfy/src/lift.rsnew file mode 100644index 00000000..ce3a984d--- /dev/null+++ b/io/gen-comfy/src/lift.rs@@ -0,0 +1,370 @@+//! A ComfyUI graph lifted to a flow: each output's chain named by what it makes. A sampler chain (KSampler or+//! SamplerCustomAdvanced, its loaders, prompts and latent) becomes image.generate, image.edit or video.generate with+//! its weights, LoRAs and settings kept as inputs; a partner API node (Gemini, Kling, Veo, Seedance, …) becomes the+//! same op on the made model that runs that vendor's model; loaders become media.load. What has no name stays ComfyUI+//! nodes in a `comfy` step, with the steps it reads bound in, so it runs exactly on a ComfyUI server.++use std::collections::BTreeMap;++use serde_json::{Map, Value as J, json};++use crate::api_nodes::api_step;+use crate::read::{Graph, link, upstream};+use raea_io_gen_core::flow::{Flow, Step};++const SAMPLERS: [&str; 4] = ["KSampler", "KSamplerAdvanced", "SamplerCustomAdvanced", "SamplerCustom"];+const LOADS: [(&str, &str); 5] = [("LoadImage", "image"), ("LoadImageMask", "image"), ("LoadVideo", "file"), ("VHS_LoadVideo", "video"), ("LoadAudio", "audio")];+/// latent or conditioning nodes that make a sampler's output a video, and the image inputs they carry+const VIDEO_LATENTS: [&str; 12] = ["EmptyHunyuanLatentVideo", "EmptyLTXVLatentVideo", "EmptyMochiLatentVideo", "EmptyCosmosLatentVideo", "WanImageToVideo", "WanFirstLastFrameToVideo", "Wan22ImageToVideoLatent", "LTXVImgToVideo", "HunyuanImageToVideo", "CosmosImageToVideoLatent", "WanVaceToVideo", "EmptyWanLatentVideo"];++/// What a lift found: the flow, and each sink's step (by sink node id) for a reader.+pub struct Lifted {+ pub flow: Flow,+ pub sinks: BTreeMap<String, String>,+}++fn is_sink(class: &str, schema_out: bool) -> bool {+ schema_out || class.starts_with("Save") || class.starts_with("Preview") || class == "VHS_VideoCombine"+}++struct Cx<'a> {+ g: &'a Graph,+ flow: Flow,+ /// comfy node id → step id, once lifted+ done: BTreeMap<String, String>,+}++impl Cx<'_> {+ fn input(&self, id: &str, name: &str) -> Option<&J> {+ self.g.get(id)?.inputs.get(name)+ }++ /// An input followed to a literal: through primitive and string nodes (a node's own value, text or string), a+ /// switch's chosen branch (the other when that one leads nowhere: an LLM enhancer), string edits to their source.+ fn lit(&self, id: &str, name: &str) -> Option<J> {+ self.lit_at(self.input(id, name)?, 0)+ }++ fn lit_at(&self, v: &J, depth: usize) -> Option<J> {+ let Some((src, _)) = link(v) else { return Some(v.clone()) };+ if depth > 12 {+ return None;+ }+ let n = self.g.get(src)?;+ let follow = |k: &str| n.inputs.get(k).and_then(|x| self.lit_at(x, depth + 1));+ if n.class.contains("Switch") {+ let on = follow("switch").and_then(|b| b.as_bool()).unwrap_or(false);+ let (a, b) = if on { ("on_true", "on_false") } else { ("on_false", "on_true") };+ return follow(a).filter(|x| x.as_str().is_none_or(|s| !s.trim().is_empty())).or_else(|| follow(b));+ }+ ["value", "text", "string", "prompt", "string_a", "text_a"].iter().find_map(|k| follow(k))+ }++ /// The first node upstream of `id` (itself not counted) whose class passes `f`.+ fn find(&self, id: &str, f: impl Fn(&str) -> bool) -> Option<String> {+ upstream(self.g, id).into_iter().skip(1).find(|n| self.g.get(n).is_some_and(|x| f(&x.class)))+ }++ /// The text a conditioning input leads to: the nearest text-encode node's words.+ fn text(&self, id: &str, input: &str) -> Option<String> {+ let (src, _) = link(self.input(id, input)?)?;+ let enc = std::iter::once(src.to_string()).chain(upstream(self.g, src)).find(|n| self.g.get(n).is_some_and(|x| x.class.contains("TextEncode")))?;+ ["text", "prompt", "t5xxl", "clip_l"].iter().find_map(|k| self.lit(&enc, k)).and_then(|v| v.as_str().map(str::to_string))+ }++ fn step(&mut self, comfy_id: &str, mut step: Step) -> String {+ let id = format!("n{}", comfy_id.replace(':', "_"));+ if step.from.is_none() {+ step.from = Some(format!("comfy {} {comfy_id}", self.g[comfy_id].class));+ }+ self.flow.steps.insert(id.clone(), step);+ self.done.insert(comfy_id.to_string(), id.clone());+ id+ }++ /// The step that makes what `id`'s output is: lifted when it can be named, else kept as ComfyUI nodes.+ fn lift(&mut self, id: &str) -> String {+ if let Some(s) = self.done.get(id) {+ return s.clone();+ }+ let class = self.g[id].class.clone();+ if let Some((_, key)) = LOADS.iter().find(|(c, _)| *c == class) {+ let path = self.lit(id, key).unwrap_or(J::Null);+ return self.step(id, Step::new("media.load", json!({"path": path})));+ }+ if class == "VAEDecode" || class == "VAEDecodeTiled" {+ let why = match self.find(id, |c| SAMPLERS.contains(&c)) {+ Some(s) => match self.sampler(&s) {+ Ok(step) => return self.step(id, step),+ Err(why) => why,+ },+ None => "no sampler upstream".to_string(),+ };+ let kept = self.keep(id);+ self.flow.steps.get_mut(&kept).unwrap().from = Some(format!("comfy VAEDecode {id}, kept: {why}"));+ return kept;+ }+ if class == "ImageUpscaleWithModel" {+ if let Some((img, _)) = self.input(id, "image").and_then(link).map(|(a, b)| (a.to_string(), b)) {+ let model = self.input(id, "upscale_model").and_then(link).and_then(|(m, _)| self.lit(m, "model_name"));+ let factor = model.as_ref().and_then(|m| m.as_str()).and_then(|m| m.chars().next().and_then(|c| c.to_digit(10))).unwrap_or(4);+ let image = self.lift(&img);+ return self.step(id, Step::new("image.upscale", json!({"image": format!("@{image}"), "factor": factor, "weights": model})));+ }+ }+ if let Some(step) = self.utility(id, &class) {+ return self.step(id, step);+ }+ let named: Map<String, J> = self.g[id].inputs.clone();+ if let Some(mut step) = api_step(&class, &named) {+ // its media inputs are other nodes' outputs: lift them and point at their steps+ for v in step.inputs.values_mut() {+ self.point(v);+ }+ return self.step(id, step);+ }+ self.keep(id)+ }++ /// Links inside a lifted step's inputs (`[id, slot]`, or arrays of them) replaced by `@step`.+ fn point(&mut self, v: &mut J) {+ if let Some((src, _)) = link(v).map(|(a, b)| (a.to_string(), b)) {+ *v = json!(format!("@{}", self.lift(&src)));+ } else if let Some(a) = v.as_array_mut() {+ for x in a {+ self.point(x);+ }+ }+ }++ /// A node with no name kept as ComfyUI: it and what it reads, up to media that other steps make (a load, a+ /// lifted generation), which are bound in as `bind: {"<node>.<input>": "@step"}`.+ fn keep(&mut self, id: &str) -> String {+ let mut nodes = Map::new();+ let mut bind = Map::new();+ let mut queue = vec![id.to_string()];+ while let Some(n) = queue.pop() {+ if nodes.contains_key(&n) {+ continue;+ }+ let node = self.g[&n].clone();+ for (name, v) in &node.inputs {+ let Some((src, _)) = link(v) else { continue };+ let sc = &self.g[src].class;+ let media = LOADS.iter().any(|(c, _)| c == sc) || ((sc == "VAEDecode" || sc == "VAEDecodeTiled") && src != id);+ if media && src != id {+ let step = self.lift(src);+ bind.insert(format!("{n}.{name}"), json!(format!("@{step}")));+ } else {+ queue.push(src.to_string());+ }+ }+ nodes.insert(n.clone(), json!({"class_type": node.class, "inputs": node.inputs}));+ }+ let mut inputs = json!({"nodes": nodes, "output": id});+ if !bind.is_empty() {+ inputs["bind"] = J::Object(bind);+ }+ self.step(id, Step::new("comfy", inputs))+ }++ /// A sampler's chain as one step.+ fn sampler(&mut self, s: &str) -> Result<Step, String> {+ let class = self.g[s].class.clone();+ let mut i = Map::new();+ // the guider holds the prompts on SamplerCustomAdvanced; the sampler itself does elsewhere+ let cond = if class == "SamplerCustomAdvanced" { self.input(s, "guider").and_then(link).map(|(g, _)| g.to_string()).ok_or("its guider isn't linked")? } else { s.to_string() };+ let prompt = ["positive", "conditioning", "cond1"].iter().find_map(|k| self.text(&cond, k)).ok_or_else(|| format!("no prompt found up {}'s conditioning", self.g[&cond].class))?;+ i.insert("prompt".into(), json!(prompt));+ if let Some(neg) = self.text(&cond, "negative").or_else(|| self.text(&cond, "cond2")).filter(|t| !t.trim().is_empty()) {+ i.insert("negative".into(), json!(neg));+ }+ let pick = |cx: &Cx, from: Option<String>, keys: &[(&str, &str)], i: &mut Map<String, J>| {+ if let Some(n) = from {+ for (k, to) in keys {+ if let Some(v) = cx.lit(&n, k).filter(|v| !v.is_null()) {+ i.insert(to.to_string(), v);+ }+ }+ }+ };+ pick(self, Some(s.into()), &[("seed", "seed"), ("noise_seed", "seed"), ("steps", "steps"), ("cfg", "cfg"), ("sampler_name", "sampler"), ("scheduler", "scheduler")], &mut i);+ if class == "SamplerCustomAdvanced" {+ let up = |name: &str| self.input(s, name).and_then(link).map(|(n, _)| n.to_string());+ pick(self, up("noise"), &[("noise_seed", "seed")], &mut i);+ pick(self, up("sigmas"), &[("steps", "steps"), ("scheduler", "scheduler"), ("denoise", "x_denoise")], &mut i);+ pick(self, up("sampler"), &[("sampler_name", "sampler")], &mut i);+ pick(self, Some(cond.clone()), &[("cfg", "cfg")], &mut i);+ }+ if let Some(g) = self.find(&cond, |c| c == "FluxGuidance") {+ pick(self, Some(g), &[("guidance", "cfg")], &mut i);+ }+ // weights and LoRAs: every loader up the model input+ let model_root = self.input(s, "model").or_else(|| self.input(&cond, "model")).and_then(link).map(|(m, _)| m.to_string());+ if let Some(m) = model_root {+ let chain = upstream(self.g, &m);+ let mut weights = Vec::new();+ let mut loras = Vec::new();+ for n in &chain {+ for k in ["ckpt_name", "unet_name"] {+ if let Some(w) = self.lit(n, k) {+ weights.push(w);+ }+ }+ if let Some(l) = self.lit(n, "lora_name") {+ loras.push(json!({"name": l, "strength": self.lit(n, "strength_model").unwrap_or(json!(1.0))}));+ }+ }+ if !weights.is_empty() {+ i.insert("weights".into(), if weights.len() == 1 { weights.remove(0) } else { J::Array(weights) });+ }+ if !loras.is_empty() {+ i.insert("loras".into(), J::Array(loras));+ }+ }+ // the latent says what kind of step this is+ let latent = self.input(s, "latent_image").and_then(link).map(|(l, _)| l.to_string());+ let video = self.find(s, |c| VIDEO_LATENTS.contains(&c) || c.ends_with("ToVideo") || c.contains("ToVideoLatent"));+ if let Some(v) = video {+ for (k, to) in [("width", "width"), ("height", "height"), ("length", "x_frames")] {+ if let Some(x) = self.lit(&v, k) {+ i.insert(to.into(), x);+ }+ }+ for (k, to) in [("start_image", "start_image"), ("image", "start_image"), ("end_image", "end_image")] {+ if let Some((src, _)) = self.input(&v, k).and_then(link).map(|(a, b)| (a.to_string(), b)) {+ let st = self.lift(&src);+ i.insert(to.into(), json!(format!("@{st}")));+ }+ }+ return Ok(Step::new("video.generate", J::Object(i)));+ }+ let mut latent = latent.ok_or("its latent isn't linked")?;+ // a second pass (a refiner, a high- then low-noise sampler) or an upscaled latent: back to the first latent+ for _ in 0..8 {+ let n = &self.g[&latent];+ let next = if SAMPLERS.contains(&n.class.as_str()) { n.inputs.get("latent_image") } else if n.class.starts_with("LatentUpscale") { n.inputs.get("samples") } else { None };+ match next.and_then(link) {+ Some((l, _)) => latent = l.to_string(),+ None => break,+ }+ }+ let lclass = self.g[&latent].class.clone();+ if lclass.starts_with("Empty") {+ pick(self, Some(latent), &[("width", "width"), ("height", "height")], &mut i);+ return Ok(Step::new("image.generate", J::Object(i)));+ }+ // an encoded image: img2img (or inpainting, with a mask on the way)+ let enc = std::iter::once(latent.clone()).chain(upstream(self.g, &latent)).find(|n| self.g.get(n).is_some_and(|x| x.class.starts_with("VAEEncode") || x.class == "InpaintModelConditioning")).ok_or_else(|| format!("its latent comes from {}, neither empty nor an encoded image", lclass))?;+ let (px, _) = self.input(&enc, "pixels").and_then(link).map(|(a, b)| (a.to_string(), b)).ok_or("the encoded image isn't linked")?;+ let image = self.lift(&px);+ i.insert("image".into(), json!(format!("@{image}")));+ if let Some((m, _)) = self.input(&enc, "mask").or_else(|| self.input(&latent, "mask")).and_then(link).map(|(a, b)| (a.to_string(), b)) {+ let mask = self.lift(&m);+ i.insert("mask".into(), json!(format!("@{mask}")));+ }+ if let Some(d) = self.lit(s, "denoise") {+ i.insert("strength".into(), d);+ }+ Ok(Step::new("image.edit", J::Object(i)))+ }+}++impl Cx<'_> {+ /// The image utilities raea runs itself (image.crop, image.scale, image.stitch), from ComfyUI's core nodes; None+ /// for any other node, or one whose image or numbers aren't plain.+ fn utility(&mut self, id: &str, class: &str) -> Option<Step> {+ let num = |cx: &Self, k: &str| cx.lit(id, k).filter(|v| v.is_number());+ let image = |cx: &mut Self, k: &str| -> Option<J> {+ let (src, _) = cx.input(id, k).and_then(link).map(|(a, b)| (a.to_string(), b))?;+ Some(json!(format!("@{}", cx.lift(&src))))+ };+ let mut i = Map::new();+ match class {+ "ImageCrop" => {+ for k in ["width", "height", "x", "y"] {+ i.insert(k.into(), num(self, k)?);+ }+ i.insert("image".into(), image(self, "image")?);+ Some(Step::new("image.crop", J::Object(i)))+ }+ "ImageScale" | "ImageScaleBy" | "ImageScaleToTotalPixels" => {+ match class {+ // 0 keeps the picture's proportions on that side+ "ImageScale" => {+ for k in ["width", "height"] {+ if let Some(v) = num(self, k).filter(|v| v.as_f64() != Some(0.0)) {+ i.insert(k.into(), v);+ }+ }+ let cover = self.lit(id, "crop").is_some_and(|c| c == "center");+ i.insert("fit".into(), json!(if cover { "cover" } else { "stretch" }));+ }+ "ImageScaleBy" => { i.insert("factor".into(), num(self, "scale_by")?); }+ _ => { i.insert("megapixels".into(), num(self, "megapixels")?); }+ }+ i.insert("image".into(), image(self, "image")?);+ Some(Step::new("image.scale", J::Object(i)))+ }+ "ImageStitch" => {+ let mut images = vec![image(self, "image1")?];+ images.extend(image(self, "image2"));+ i.insert("images".into(), J::Array(images));+ if let Some(d) = self.lit(id, "direction") {+ i.insert("direction".into(), d);+ }+ Some(Step::new("image.stitch", J::Object(i)))+ }+ _ => None,+ }+ }+}++/// Every output of a graph lifted. A video sink (CreateVideo, VHS_VideoCombine) gives its step seconds from frames+/// and fps.+pub fn lift(g: &Graph, schema: &crate::schema::Schema) -> Lifted {+ let mut cx = Cx { g, flow: Flow::default(), done: BTreeMap::new() };+ let mut sinks = BTreeMap::new();+ for (id, n) in g {+ if !is_sink(&n.class, schema.get(&n.class).is_some_and(|c| c.output_node)) || n.class == "PreviewAny" {+ continue;+ }+ // what the sink saves: its first linked input, through CreateVideo-style wrappers that only add fps+ let Some((mut src, slot)) = n.inputs.values().find_map(link).map(|(a, b)| (a.to_string(), b)) else { continue };+ let mut fps = n.inputs.get("frame_rate").or(n.inputs.get("fps")).cloned();+ if g[&src].class == "CreateVideo" {+ fps = cx.lit(&src, "fps").or(fps);+ if let Some((img, _)) = g[&src].inputs.get("images").and_then(link) {+ src = img.to_string();+ }+ }+ let step = cx.lift(&src);+ if let (Some(fps), Some(s)) = (fps.and_then(|f| f.as_f64()), cx.flow.steps.get_mut(&step)) {+ if s.op == "video.generate" || s.inputs.contains_key("x_frames") {+ s.op = "video.generate".into();+ if let Some(frames) = s.inputs.remove("x_frames").and_then(|f| f.as_f64()) {+ s.inputs.insert("seconds".into(), json!(((frames / fps) * 100.0).round() / 100.0));+ }+ s.inputs.insert("fps".into(), json!(fps));+ }+ }+ // a kept node saved from several of its outputs (a stem separator's four): the step gives each slot, in order+ if let Some(st) = cx.flow.steps.get_mut(&step).filter(|st| st.op == "comfy" && st.inputs.get("output").and_then(|o| o.as_str()) == Some(src.as_str())) {+ let slots = st.inputs.entry("slots").or_insert(json!([]));+ if let Some(a) = slots.as_array_mut().filter(|a| !a.contains(&json!(slot))) {+ a.push(json!(slot));+ }+ }+ if !cx.flow.out.contains(&step) {+ cx.flow.out.push(step.clone());+ }+ sinks.insert(id.clone(), step);+ }+ // one slot, the first: the plain case, no list+ for st in cx.flow.steps.values_mut() {+ if st.inputs.get("slots") == Some(&json!([0])) {+ st.inputs.remove("slots");+ }+ }+ Lifted { flow: cx.flow, sinks }+}diff --git a/io/gen-comfy/src/needs.rs b/io/gen-comfy/src/needs.rsnew file mode 100644index 00000000..b8b7dbf0--- /dev/null+++ b/io/gen-comfy/src/needs.rs@@ -0,0 +1,101 @@+//! What a workflow needs from a ComfyUI server beyond what it has: the node packs its classes come from and the model+//! files its loaders read. A UI-format workflow says both itself (each node's `properties.cnr_id`, the ComfyUI+//! registry's id for its pack, or `aux_id`, a GitHub repo; `properties.models`, each file with its download URL and+//! models/ folder). Classes it doesn't attribute, and API-format graphs, are looked up in ComfyUI-Manager's+//! extension-node-map (which repo provides which class), kept in ~/.cache/raea-gen, then the registry's node search. tools/comfy/setup.sh nodes|models+//! installs them on this machine's server, tools/comfy/modal_comfy.py on the hosted one.++use std::collections::{BTreeMap, BTreeSet};++use serde_json::{Value as J, json};++use crate::schema::Schema;++/// Classes neither the map nor the registry search knows, found by hand (10-29): (class, repo).+const KNOWN: &[(&str, &str)] = &[+ ("ImageConstant", "https://github.com/spacepxl/ComfyUI-Image-Filters"),+ // utility-audioseparation's own note names this pack; its __init__.py registers the class+ ("AudioStemSeparate", "https://github.com/lum3on/ComfyUI_AudioTools"),+];++/// The ComfyUI registry's pack for a class, by its node search (api.comfy.org); None when it finds none or several.+fn registry_pack(class: &str) -> Option<String> {+ let q: String = class.bytes().map(|b| if b.is_ascii_alphanumeric() { (b as char).to_string() } else { format!("%{b:02X}") }).collect();+ let r = raea_io_gen_core::http::call("GET", &format!("https://api.comfy.org/nodes/search?comfy_node_search={q}&limit=2"), &[], raea_io_gen_core::http::Body::None, None, 30).ok()?;+ let v = r.json().ok()?;+ match v["nodes"].as_array()?.as_slice() {+ [one] => one["id"].as_str().map(str::to_string),+ _ => None,+ }+}++const NODE_MAP: &str = "https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main/extension-node-map.json";++/// ComfyUI-Manager's class → repo map (the first repo listing a class; several packs reuse some names).+fn node_map() -> BTreeMap<String, String> {+ let f = raea_io_gen_core::made::cached("comfy-extension-node-map.json");+ if !f.is_file() {+ let _ = std::fs::create_dir_all(f.parent().unwrap_or(&f));+ let _ = raea_io_gen_core::http::call("GET", NODE_MAP, &[], raea_io_gen_core::http::Body::None, Some(&f), 120);+ }+ let v: J = std::fs::read(&f).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or(J::Null);+ let mut m = BTreeMap::new();+ for (repo, entry) in v.as_object().into_iter().flatten() {+ for class in entry[0].as_array().into_iter().flatten().filter_map(|c| c.as_str()) {+ m.entry(class.to_string()).or_insert_with(|| repo.clone());+ }+ }+ m+}++/// Every node of a UI-format workflow, its subgraphs' too.+fn ui_nodes(v: &J) -> Vec<&J> {+ let mut out: Vec<&J> = v["nodes"].as_array().into_iter().flatten().collect();+ for s in v["definitions"]["subgraphs"].as_array().into_iter().flatten() {+ out.extend(s["nodes"].as_array().into_iter().flatten());+ }+ out+}++/// What `workflow` needs that a server with `schema` lacks: {"packs": registry ids, "repos": git URLs, "models":+/// [{name, url, directory}], "unknown": classes nobody is known to provide}.+pub fn needs(workflow: &J, schema: &Schema) -> J {+ let (mut packs, mut repos, mut unknown) = (BTreeSet::new(), BTreeSet::new(), BTreeSet::new());+ let mut models: BTreeMap<String, J> = BTreeMap::new();+ let mut loose = BTreeSet::new();+ let ui = workflow["nodes"].is_array();+ let classes: Vec<(String, Option<&J>)> = if ui {+ ui_nodes(workflow).into_iter().map(|n| (n["type"].as_str().unwrap_or("").to_string(), Some(&n["properties"]))).collect()+ } else {+ workflow.as_object().into_iter().flatten().map(|(_, n)| (n["class_type"].as_str().unwrap_or("").to_string(), None)).collect()+ };+ for (class, props) in classes {+ for m in props.and_then(|p| p["models"].as_array()).into_iter().flatten() {+ if let Some(name) = m["name"].as_str() {+ models.insert(name.to_string(), json!({"name": name, "url": m["url"], "directory": m["directory"]}));+ }+ }+ // a subgraph's own node (its type is the subgraph's id), a note, or a class the server has+ if class.is_empty() || schema.contains_key(&class) || class.len() == 36 && class.matches('-').count() == 4 || matches!(class.as_str(), "Note" | "MarkdownNote" | "Reroute" | "PrimitiveNode") {+ continue;+ }+ match props.map(|p| (p["cnr_id"].as_str(), p["aux_id"].as_str())) {+ Some((Some(id), _)) if id != "comfy-core" => { packs.insert(id.to_string()); }+ Some((_, Some(aux))) => { repos.insert(format!("https://github.com/{aux}")); }+ _ => { loose.insert(class); }+ }+ }+ if !loose.is_empty() {+ let map = node_map();+ for class in loose {+ if let Some(repo) = map.get(&class).cloned().or_else(|| KNOWN.iter().find(|k| k.0 == class).map(|k| k.1.to_string())) {+ repos.insert(repo);+ } else if let Some(id) = registry_pack(&class) {+ packs.insert(id);+ } else {+ unknown.insert(class);+ }+ }+ }+ json!({"packs": packs, "repos": repos, "models": models.into_values().collect::<Vec<_>>(), "unknown": unknown})+}diff --git a/io/gen-comfy/src/read.rs b/io/gen-comfy/src/read.rsnew file mode 100644index 00000000..7c6b8026--- /dev/null+++ b/io/gen-comfy/src/read.rs@@ -0,0 +1,229 @@+//! A ComfyUI workflow as nodes with named inputs: API format (what /prompt takes: `{id: {class_type, inputs}}`,+//! links as `[id, slot]`) as it is, and UI format (what the editor saves: positional widgets, a link table, subgraphs,+//! reroutes, primitives, muted and bypassed nodes) brought to the same shape. Subgraphs are inlined with their ids+//! prefixed by the instance's (`105:23`); notes and muted nodes go; a bypassed node passes its input of the same type.++use std::collections::BTreeMap;++use serde_json::{Map, Value as J, json};++use crate::schema::{Schema, name_widgets};++#[derive(Clone, Debug, PartialEq)]+pub struct Node {+ pub class: String,+ /// a setting's value, or `[node id, output slot]` for a link+ pub inputs: Map<String, J>,+ pub title: Option<String>,+}++pub type Graph = BTreeMap<String, Node>;++/// `[id, slot]`: the node and output an input is linked to.+pub fn link(v: &J) -> Option<(&str, usize)> {+ let a = v.as_array().filter(|a| a.len() == 2)?;+ Some((a[0].as_str()?, a[1].as_u64()? as usize))+}++/// Either format, told apart by its shape. A PNG's or a wrapper's `{"prompt": {...}}` is opened too.+pub fn read(v: &J, schema: &Schema) -> Result<Graph, String> {+ if v["nodes"].is_array() {+ return from_ui(v, schema);+ }+ let api = if v["prompt"].is_object() { &v["prompt"] } else { v };+ let o = api.as_object().ok_or("not a ComfyUI workflow: neither UI format (nodes, links) nor API format ({id: {class_type, inputs}})")?;+ let mut g = Graph::new();+ for (id, n) in o {+ let Some(class) = n["class_type"].as_str() else { continue };+ let mut inputs = n["inputs"].as_object().cloned().unwrap_or_default();+ // API format writes link ids as strings or numbers depending on who saved it+ for v in inputs.values_mut() {+ if let Some(a) = v.as_array_mut().filter(|a| a.len() == 2 && a[1].is_u64()) {+ if let Some(n) = a[0].as_u64() {+ a[0] = json!(n.to_string());+ }+ }+ }+ g.insert(id.clone(), Node { class: class.into(), inputs, title: n["_meta"]["title"].as_str().map(str::to_string) });+ }+ if g.is_empty() {+ return Err("no nodes with a class_type".into());+ }+ Ok(g)+}++/// Where an input's value comes from while a UI workflow is being flattened.+#[derive(Clone, Debug)]+enum Src {+ Link(String, usize),+ Lit(J),+}++struct Flat {+ nodes: Vec<(String, String, i64, J, Vec<(String, Option<Src>, String)>, Option<String>)>,+ /// (node, slot) that stand for something else: a subgraph's outputs, reroutes, primitives, bypassed nodes+ alias: BTreeMap<(String, usize), Option<Src>>,+}++pub(crate) fn ui_links(v: &J) -> BTreeMap<i64, (i64, usize)> {+ v.as_array().into_iter().flatten().filter_map(|l| match l {+ J::Array(a) => Some((a[0].as_i64()?, (a[1].as_i64()?, a[2].as_u64()? as usize))),+ J::Object(_) => Some((l["id"].as_i64()?, (l["origin_id"].as_i64()?, l["origin_slot"].as_u64()? as usize))),+ _ => None,+ }).collect()+}++fn flatten(nodes: &J, links: &J, prefix: &str, defs: &BTreeMap<String, J>, parent: &[Option<Src>], flat: &mut Flat, depth: usize) -> Result<Vec<Option<Src>>, String> {+ if depth > 16 {+ return Err("subgraphs nested more than 16 deep (a subgraph that contains itself?)".into());+ }+ let table = ui_links(links);+ let src_of = |link: &J| -> Option<Src> {+ let (origin, slot) = *table.get(&link.as_i64()?)?;+ if origin == -10 { parent.get(slot).cloned().flatten() } else { Some(Src::Link(format!("{prefix}{origin}"), slot)) }+ };+ for n in nodes.as_array().into_iter().flatten() {+ let id = format!("{prefix}{}", id_of(n));+ let class = n["type"].as_str().unwrap_or_default().to_string();+ let mode = n["mode"].as_i64().unwrap_or(0);+ let ins: Vec<(String, Option<Src>, String)> = n["inputs"].as_array().into_iter().flatten().map(|i| {+ (i["name"].as_str().unwrap_or_default().to_string(), src_of(&i["link"]), i["type"].as_str().unwrap_or("*").to_string())+ }).collect();+ if let Some(sub) = defs.get(&class) {+ // the instance's own widget values fill the subgraph's inputs that aren't linked, in widget order+ let wv = n["widgets_values"].as_array().cloned().unwrap_or_default();+ let mut wi = 0;+ let by_name: BTreeMap<String, Option<Src>> = n["inputs"].as_array().into_iter().flatten().map(|i| {+ let name = i["name"].as_str().unwrap_or_default().to_string();+ let mut s = src_of(&i["link"]);+ if i["widget"].is_object() {+ if s.is_none() {+ s = wv.get(wi).cloned().map(Src::Lit);+ }+ wi += 1;+ }+ (name, s)+ }).collect();+ let feed: Vec<Option<Src>> = sub["inputs"].as_array().into_iter().flatten().map(|si| by_name.get(si["name"].as_str().unwrap_or_default()).cloned().flatten()).collect();+ let outs = if mode == 2 { vec![] } else { flatten(&sub["nodes"], &sub["links"], &format!("{id}:"), defs, &feed, flat, depth + 1)? };+ for (k, o) in outs.into_iter().enumerate() {+ flat.alias.insert((id.clone(), k), o);+ }+ continue;+ }+ let first = || ins.first().and_then(|(_, v, _)| v.clone());+ match class.as_str() {+ "Note" | "MarkdownNote" | "Label (rgthree)" => continue,+ "Reroute" => { flat.alias.insert((id, 0), first()); continue; }+ "PrimitiveNode" => { flat.alias.insert((id, 0), n["widgets_values"].get(0).cloned().map(Src::Lit)); continue; }+ _ => {}+ }+ if mode == 2 {+ for k in 0..8 { flat.alias.insert((id.clone(), k), None); }+ continue;+ }+ if mode == 4 {+ // bypassed: each output passes the first linked input of its type+ for (k, o) in n["outputs"].as_array().into_iter().flatten().enumerate() {+ let ty = o["type"].as_str().unwrap_or("*");+ let pass = ins.iter().find(|i| i.1.is_some() && (i.2 == ty || ty == "*")).and_then(|i| i.1.clone());+ flat.alias.insert((id.clone(), k), pass);+ }+ continue;+ }+ flat.nodes.push((id, class, mode, n["widgets_values"].clone(), ins, n["title"].as_str().map(str::to_string)));+ }+ // what this level hands out: links into its output node (-20)+ let mut outs: Vec<Option<Src>> = Vec::new();+ for l in links.as_array().into_iter().flatten() {+ let (target, tslot, link_id) = match l {+ J::Array(a) => (a[3].as_i64(), a[4].as_u64(), a[0].clone()),+ _ => (l["target_id"].as_i64(), l["target_slot"].as_u64(), l["id"].clone()),+ };+ if target == Some(-20) {+ let k = tslot.unwrap_or(0) as usize;+ if outs.len() <= k {+ outs.resize(k + 1, None);+ }+ outs[k] = src_of(&link_id);+ }+ }+ Ok(outs)+}++fn from_ui(v: &J, schema: &Schema) -> Result<Graph, String> {+ let defs: BTreeMap<String, J> = v["definitions"]["subgraphs"].as_array().into_iter().flatten().filter_map(|s| Some((s["id"].as_str()?.to_string(), s.clone()))).collect();+ let mut flat = Flat { nodes: Vec::new(), alias: BTreeMap::new() };+ flatten(&v["nodes"], &v["links"], "", &defs, &[], &mut flat, 0)?;+ // follow aliases to a real node's output (or a literal)+ let resolve = |s: &Src| -> Option<Src> {+ let mut s = s.clone();+ for _ in 0..64 {+ match &s {+ Src::Link(id, slot) => match flat.alias.get(&(id.clone(), *slot)) {+ Some(next) => s = next.clone()?,+ None => return Some(s),+ },+ Src::Lit(_) => return Some(s),+ }+ }+ None+ };+ let mut g = Graph::new();+ for (id, class, _, wv, ins, title) in &flat.nodes {+ let c = schema.get(class);+ let mut inputs: Map<String, J> = name_widgets(c, wv).into_iter().filter(|(k, _)| c.is_none() || !k.starts_with("widget_")).collect();+ for (name, src, _) in ins {+ match src.as_ref().and_then(resolve) {+ Some(Src::Link(n, slot)) => { inputs.insert(name.clone(), json!([n, slot])); }+ Some(Src::Lit(l)) => { inputs.insert(name.clone(), l); }+ None => {}+ }+ }+ g.insert(id.clone(), Node { class: class.clone(), inputs, title: title.clone() });+ }+ // a link to a node that went (muted, a note) is dropped rather than left dangling+ let ids: std::collections::BTreeSet<String> = g.keys().cloned().collect();+ for n in g.values_mut() {+ n.inputs.retain(|_, v| link(v).is_none_or(|(id, _)| ids.contains(id)));+ }+ if g.is_empty() {+ return Err("the workflow has no nodes that run".into());+ }+ Ok(g)+}++/// API format, as /prompt takes it.+pub fn to_api(g: &Graph) -> J {+ J::Object(g.iter().map(|(id, n)| {+ let mut o = json!({"class_type": n.class, "inputs": n.inputs});+ if let Some(t) = &n.title {+ o["_meta"] = json!({"title": t});+ }+ (id.clone(), o)+ }).collect())+}++/// The nodes `id` reads from, nearest first, itself included.+pub fn upstream(g: &Graph, id: &str) -> Vec<String> {+ let (mut seen, mut queue) = (Vec::new(), vec![id.to_string()]);+ while let Some(n) = queue.pop() {+ if seen.contains(&n) {+ continue;+ }+ if let Some(node) = g.get(&n) {+ queue.extend(node.inputs.values().filter_map(link).map(|(s, _)| s.to_string()));+ }+ seen.push(n);+ }+ seen+}++/// A UI node's id as text (a number in most workflows, a string in some).+pub(crate) fn id_of(n: &J) -> String {+ match &n["id"] {+ J::Number(i) => i.to_string(),+ J::String(s) => s.clone(),+ _ => String::new(),+ }+}diff --git a/io/gen-comfy/src/schema.rs b/io/gen-comfy/src/schema.rsnew file mode 100644index 00000000..54abe747--- /dev/null+++ b/io/gen-comfy/src/schema.rs@@ -0,0 +1,190 @@+//! What each ComfyUI node class takes, in order: a UI workflow keeps a node's settings as `widgets_values`, a list by+//! position, and only the class's schema names them. The schema comes from a ComfyUI server's /object_info, kept as+//! ~/.cache/raea-gen/comfy-object-info.json by `raea gen comfy schema [URL]`; without it, CORE names the settings of+//! the classes most workflows are built from.++use std::collections::BTreeMap;++use serde_json::Value as J;++/// One setting a node shows as a widget: its name, its type, whether a seed-style "control after generate" value+/// follows it in widgets_values, and (a dynamic combo) the settings each choice adds after it.+#[derive(Clone, Debug)]+pub struct Widget {+ pub name: String,+ pub ty: String,+ pub control: bool,+ pub choices: BTreeMap<String, Vec<Widget>>,+}++#[derive(Clone, Debug, Default)]+pub struct Class {+ pub widgets: Vec<Widget>,+ /// link-only inputs (MODEL, IMAGE, …) by name+ pub links: Vec<(String, String)>,+ pub outputs: Vec<String>,+ /// a partner API node (comfy.org's paid nodes: Kling, Veo, Gemini, …)+ pub api: bool,+ pub output_node: bool,+}++pub type Schema = BTreeMap<String, Class>;++/// The settings, in widget order, of the classes most workflows use. `+` marks a seed followed by its control value.+const CORE: &[(&str, &str)] = &[+ ("CheckpointLoaderSimple", "ckpt_name"),+ ("CLIPTextEncode", "text"),+ ("KSampler", "seed+ steps cfg sampler_name scheduler denoise"),+ ("KSamplerAdvanced", "add_noise noise_seed+ steps cfg sampler_name scheduler start_at_step end_at_step return_with_leftover_noise"),+ ("EmptyLatentImage", "width height batch_size"),+ ("EmptySD3LatentImage", "width height batch_size"),+ ("SaveImage", "filename_prefix"),+ ("LoadImage", "image upload"),+ ("LoraLoader", "lora_name strength_model strength_clip"),+ ("LoraLoaderModelOnly", "lora_name strength_model"),+ ("UNETLoader", "unet_name weight_dtype"),+ ("CLIPLoader", "clip_name type device"),+ ("DualCLIPLoader", "clip_name1 clip_name2 type device"),+ ("VAELoader", "vae_name"),+ ("KSamplerSelect", "sampler_name"),+ ("BasicScheduler", "scheduler steps denoise"),+ ("RandomNoise", "noise_seed+"),+ ("FluxGuidance", "guidance"),+ ("CFGGuider", "cfg"),+ ("ModelSamplingSD3", "shift"),+ ("ModelSamplingAuraFlow", "shift"),+ ("SaveVideo", "filename_prefix format codec"),+ ("CreateVideo", "fps"),+ ("LoadVideo", "file upload"),+ ("ImageScaleBy", "upscale_method scale_by"),+ ("UpscaleModelLoader", "model_name"),+ ("SaveAudio", "filename_prefix"),+ ("PrimitiveStringMultiline", "value"),+ ("PrimitiveString", "value"),+ ("PrimitiveInt", "value+"),+ ("PrimitiveFloat", "value"),+ ("PrimitiveBoolean", "value"),+ ("WanImageToVideo", "width height length batch_size"),+ ("EmptyHunyuanLatentVideo", "width height length batch_size"),+];++fn core() -> Schema {+ CORE.iter().map(|(class, ws)| {+ let widgets = ws.split_whitespace().map(|w| Widget { name: w.trim_end_matches('+').into(), ty: String::new(), control: w.ends_with('+'), choices: BTreeMap::new() }).collect();+ (class.to_string(), Class { widgets, ..Default::default() })+ }).collect()+}++const WIDGET_TYPES: [&str; 6] = ["INT", "FLOAT", "STRING", "BOOLEAN", "COMBO", "COMFY_DYNAMICCOMBO_V3"];++fn widget(name: &str, spec: &J) -> Option<Widget> {+ let ty = match &spec[0] {+ J::Array(_) => "COMBO".to_string(),+ J::String(s) => s.clone(),+ _ => return None,+ };+ let opts = &spec[1];+ if !WIDGET_TYPES.contains(&ty.as_str()) || opts["forceInput"] == true {+ return None;+ }+ let control = !matches!(opts.get("control_after_generate"), None | Some(J::Bool(false)));+ let mut choices = BTreeMap::new();+ if ty == "COMFY_DYNAMICCOMBO_V3" {+ for o in opts["options"].as_array().into_iter().flatten() {+ let key = o["key"].as_str().unwrap_or_default().to_string();+ choices.insert(key, ordered(&o["inputs"], None).0);+ }+ }+ Some(Widget { name: name.into(), ty, control, choices })+}++/// Widgets and links of an `input` block, in the order the class declares (input_order, else the block's own).+fn ordered(input: &J, order: Option<&J>) -> (Vec<Widget>, Vec<(String, String)>) {+ let (mut ws, mut ls) = (Vec::new(), Vec::new());+ for part in ["required", "optional"] {+ let block = &input[part];+ let names: Vec<String> = match order.and_then(|o| o[part].as_array()) {+ Some(a) => a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect(),+ None => block.as_object().map(|o| o.keys().cloned().collect()).unwrap_or_default(),+ };+ for n in names {+ let spec = &block[&n];+ match widget(&n, spec) {+ Some(w) => ws.push(w),+ None => ls.push((n, spec[0].as_str().unwrap_or("*").to_string())),+ }+ }+ }+ (ws, ls)+}++/// A schema from /object_info's JSON.+pub fn from_object_info(v: &J) -> Schema {+ v.as_object().map(|o| o.iter().map(|(class, c)| {+ let (widgets, links) = ordered(&c["input"], c.get("input_order"));+ let outputs = c["output"].as_array().map(|a| a.iter().map(|t| String::from(t.as_str().unwrap_or("*"))).collect()).unwrap_or_default();+ (class.clone(), Class { widgets, links, outputs, api: c["api_node"] == true, output_node: c["output_node"] == true })+ }).collect()).unwrap_or_default()+}++/// The server's node classes, kept in raea gen's cache under this name (made::cached).+pub const CACHE_NAME: &str = "comfy-object-info.json";++/// The schema this machine has: the cached /object_info over CORE.+pub fn load() -> Schema {+ let mut s = core();+ if let Some(v) = std::fs::read(raea_io_gen_core::made::cached(CACHE_NAME)).ok().and_then(|b| serde_json::from_slice::<J>(&b).ok()) {+ s.extend(from_object_info(&v));+ }+ s+}++/// The value kept at a widget slot: an index into widgets_values, or a dynamic combo's setting by name.+pub fn slot_value(values: &J, at: &J) -> J {+ match at {+ J::String(k) => values[k.as_str()].clone(),+ _ => values[at.as_u64().unwrap_or(0) as usize].clone(),+ }+}++/// A UI node's widgets_values named: (name, value) for each, the control values after seeds skipped, a dynamic+/// combo's added settings as `combo.setting`. Values beyond what the schema names keep their place as `widget_N`.+pub fn name_widgets(class: Option<&Class>, values: &J) -> Vec<(String, J)> {+ widget_slots(class, values).into_iter().map(|(name, at)| {+ let v = slot_value(values, &at);+ (name, v)+ }).collect()+}++/// Where each named setting is in a UI node's widgets_values: its index, or its key when a node pack saves its+/// widgets by name (an edit writes back there; apps/app's whiteboards change a flow's settings this way).+pub fn widget_slots(class: Option<&Class>, values: &J) -> Vec<(String, J)> {+ // some node packs (VideoHelperSuite) save their widgets by name already+ if let Some(o) = values.as_object() {+ return o.keys().filter(|k| k.as_str() != "videopreview").map(|k| (k.clone(), J::String(k.clone()))).collect();+ }+ let vals = values.as_array().cloned().unwrap_or_default();+ let mut out = Vec::new();+ let mut i = 0;+ fn walk(ws: &[Widget], prefix: &str, vals: &[J], i: &mut usize, out: &mut Vec<(String, J)>) {+ for w in ws {+ let Some(v) = vals.get(*i) else { return };+ out.push((format!("{prefix}{}", w.name), J::from(*i)));+ *i += 1;+ // a control value ("randomize", "fixed", …) rides after a seed; an older save may leave it out+ if w.control && vals.get(*i).and_then(|c| c.as_str()).is_some_and(|c| ["fixed", "increment", "decrement", "randomize"].contains(&c)) {+ *i += 1;+ }+ if let Some(sub) = v.as_str().and_then(|k| w.choices.get(k)) {+ walk(sub, &format!("{}.", w.name), vals, i, out);+ }+ }+ }+ if let Some(c) = class {+ walk(&c.widgets, "", &vals, &mut i, &mut out);+ }+ for k in i..vals.len() {+ out.push((format!("widget_{k}"), J::from(k)));+ }+ out+}diff --git a/io/gen-comfy/src/server.rs b/io/gen-comfy/src/server.rsnew file mode 100644index 00000000..847aff6c--- /dev/null+++ b/io/gen-comfy/src/server.rs@@ -0,0 +1,142 @@+//! A ComfyUI server as a place steps run: this machine's (`raea gen comfy setup` installs one) or one hosted+//! anywhere that speaks ComfyUI's own HTTP API (a Modal app, a rented GPU). RAEA_COMFY_URL says where (default+//! http://127.0.0.1:8188); RAEA_COMFY_TOKEN, when set, goes as a bearer token (a hosted server behind auth).++use std::path::{Path, PathBuf};+use std::time::{Duration, Instant};++use serde_json::{Value as J, json};++use raea_io_gen_core::http::{Body, call};+use raea_io_gen_core::setting;++pub struct Comfy {+ pub url: String,+ token: Option<String>,+}++impl Comfy {+ pub fn from_settings() -> Comfy {+ Comfy { url: setting("RAEA_COMFY_URL").unwrap_or_else(|| "http://127.0.0.1:8188".into()).trim_end_matches('/').to_string(), token: setting("RAEA_COMFY_TOKEN") }+ }++ fn headers(&self) -> Vec<String> {+ self.token.iter().map(|t| format!("Authorization: Bearer {t}")).collect()+ }++ fn get(&self, path: &str, secs: u32) -> Result<J, String> {+ let r = call("GET", &format!("{}{path}", self.url), &self.headers(), Body::None, None, secs)?;+ if !r.ok() {+ return Err(format!("ComfyUI {path} answered {}: {}", r.code, r.text(300)));+ }+ r.json()+ }++ /// Whether a server answers at all.+ pub fn up(&self) -> bool {+ self.get("/system_stats", 5).is_ok()+ }++ /// Whether it answers, giving a hosted one (a Modal app scaled to zero) up to `limit` to start; this machine's+ /// is asked once.+ pub fn wake(&self, limit: Duration) -> bool {+ if self.url.contains("127.0.0.1") || self.url.contains("localhost") {+ return self.up();+ }+ let t = Instant::now();+ while t.elapsed() < limit {+ if self.get("/system_stats", 60).is_ok() {+ return true;+ }+ std::thread::sleep(Duration::from_secs(3));+ }+ false+ }++ /// The server's node schema, kept for the importer (schema::CACHE_NAME, in made::cached).+ pub fn save_schema(&self) -> Result<usize, String> {+ let v = self.get("/object_info", 120)?;+ let n = v.as_object().map(|o| o.len()).unwrap_or(0);+ let f = raea_io_gen_core::made::cached(crate::schema::CACHE_NAME);+ let _ = std::fs::create_dir_all(f.parent().unwrap_or(Path::new(".")));+ std::fs::write(&f, v.to_string()).map_err(|e| format!("{}: {e}", f.display()))?;+ Ok(n)+ }++ /// A file into the server's input folder; the name a Load node uses for it.+ pub fn upload(&self, file: &Path) -> Result<String, String> {+ let fields = vec![("image".to_string(), format!("@{}", file.display())), ("overwrite".to_string(), "true".to_string())];+ let r = call("POST", &format!("{}/upload/image", self.url), &self.headers(), Body::Form(&fields), None, 600)?;+ if !r.ok() {+ return Err(format!("ComfyUI upload of {} answered {}: {}", file.display(), r.code, r.text(300)));+ }+ let v = r.json()?;+ let name = v["name"].as_str().ok_or("ComfyUI upload: no name")?;+ Ok(match v["subfolder"].as_str().filter(|s| !s.is_empty()) { Some(sub) => format!("{sub}/{name}"), None => name.to_string() })+ }++ /// An API-format graph queued; its prompt id. A graph the server refuses says which nodes and why.+ pub fn queue(&self, graph: &J) -> Result<String, String> {+ let body = json!({"prompt": graph, "client_id": "raea-gen"});+ let r = call("POST", &format!("{}/prompt", self.url), &self.headers(), Body::Json(&body), None, 120)?;+ let v = r.json().unwrap_or(J::Null);+ if !r.ok() {+ let mut why = v["error"]["message"].as_str().unwrap_or("refused").to_string();+ for (node, e) in v["node_errors"].as_object().into_iter().flatten() {+ let errs: Vec<String> = e["errors"].as_array().into_iter().flatten().map(|x| format!("{} ({})", x["message"].as_str().unwrap_or(""), x["details"].as_str().unwrap_or(""))).collect();+ why += &format!("; node {node} {}: {}", e["class_type"].as_str().unwrap_or(""), errs.join(", "));+ }+ return Err(format!("ComfyUI refused the graph: {why}"));+ }+ v["prompt_id"].as_str().map(str::to_string).ok_or_else(|| format!("ComfyUI /prompt: no prompt_id in {v}"))+ }++ /// The prompt's history once it ends; an error when it failed. Given up after `limit` with no result.+ pub fn wait(&self, id: &str, limit: Duration) -> Result<J, String> {+ let t = Instant::now();+ let mut nap = 1;+ loop {+ let h = self.get(&format!("/history/{id}"), 30)?;+ if let Some(entry) = h.get(id) {+ if entry["status"]["status_str"] == "error" {+ let msg = entry["status"]["messages"].as_array().into_iter().flatten().filter(|m| m[0] == "execution_error").map(|m| format!("{} {}: {}", m[1]["node_type"].as_str().unwrap_or(""), m[1]["node_id"].as_str().unwrap_or(""), m[1]["exception_message"].as_str().unwrap_or("").trim())).collect::<Vec<_>>().join("; ");+ return Err(format!("ComfyUI run failed: {msg}"));+ }+ if entry["status"]["completed"] == true || entry["outputs"].as_object().is_some_and(|o| !o.is_empty()) {+ return Ok(entry.clone());+ }+ }+ if t.elapsed() > limit {+ return Err(format!("ComfyUI prompt {id} gave nothing back in {}s", limit.as_secs()));+ }+ std::thread::sleep(Duration::from_secs(nap));+ nap = (nap + 1).min(5);+ }+ }++ /// One node's files from a finished run, downloaded into `dir`.+ pub fn fetch(&self, entry: &J, node: &str, dir: &Path) -> Result<Vec<PathBuf>, String> {+ let out = &entry["outputs"][node];+ let mut files = Vec::new();+ for key in ["images", "gifs", "videos", "video", "audio", "3d"] {+ for f in out[key].as_array().into_iter().flatten() {+ let (name, sub, ty) = (f["filename"].as_str().unwrap_or(""), f["subfolder"].as_str().unwrap_or(""), f["type"].as_str().unwrap_or("output"));+ if name.is_empty() {+ continue;+ }+ let dest = dir.join(name.rsplit('/').next().unwrap_or(name));+ let q = |s: &str| s.bytes().map(|b| if b.is_ascii_alphanumeric() || b"-_.~".contains(&b) { (b as char).to_string() } else { format!("%{b:02X}") }).collect::<String>();+ let url = format!("{}/view?filename={}&subfolder={}&type={}", self.url, q(name), q(sub), q(ty));+ let r = call("GET", &url, &self.headers(), Body::None, Some(&dest), 600)?;+ if !r.ok() {+ return Err(format!("ComfyUI /view {name} answered {}", r.code));+ }+ files.push(dest);+ }+ }+ if files.is_empty() {+ return Err(format!("ComfyUI node {node} saved no files (outputs: {})", out));+ }+ Ok(files)+ }+}diff --git a/io/gen-comfy/src/view.rs b/io/gen-comfy/src/view.rsnew file mode 100644index 00000000..d7613f95--- /dev/null+++ b/io/gen-comfy/src/view.rs@@ -0,0 +1,225 @@+//! A workflow as a whiteboard shows it (docs/whiteboards.feature CF1, apps/app src/whiteboard/flow.ts): each node+//! with its class, title, mode, place and settings by name; the links between them; its groups. And a board's edits+//! written back (CF2): settings, bypass and notes. The workflow stays the source of truth; the board is a view of it.++use serde_json::{Map, Value as J, json};++use crate::read::{id_of, link, ui_links};+use crate::schema::{Schema, slot_value, widget_slots};++const NOTES: [&str; 2] = ["Note", "MarkdownNote"];++fn mode_name(m: i64) -> &'static str {+ match m {+ 2 => "mute",+ 4 => "bypass",+ _ => "on",+ }+}++/// A node's settings by name, with where each is kept (`at`: an index into widgets_values, or an input's name).+fn ui_widgets(n: &J, schema: &Schema) -> Vec<J> {+ let class = n["type"].as_str().unwrap_or_default();+ let wv = &n["widgets_values"];+ if NOTES.contains(&class) {+ return vec![json!({"name": "text", "value": wv[0].clone(), "at": 0})];+ }+ widget_slots(schema.get(class), wv).into_iter().map(|(name, at)| {+ let value = slot_value(wv, &at);+ json!({"name": name, "value": value, "at": at})+ }).collect()+}++/// The workflow (UI or API format) as nodes, links and groups. A UI workflow's own layout comes along (pos, size);+/// an API one has none, and the board lays it out by its links. Subgraphs show as the node that holds them.+pub fn view(v: &J, schema: &Schema) -> Result<J, String> {+ if v["nodes"].is_array() {+ let table = ui_links(&v["links"]);+ let mut nodes = Vec::new();+ let mut links = Vec::new();+ for n in v["nodes"].as_array().into_iter().flatten() {+ let id = id_of(n);+ let mut inputs = Vec::new();+ for i in n["inputs"].as_array().into_iter().flatten() {+ let name = i["name"].as_str().unwrap_or_default();+ if let Some((from, slot)) = i["link"].as_i64().and_then(|l| table.get(&l)) {+ links.push(json!({"from": from.to_string(), "slot": slot, "to": id, "input": name, "type": i["type"]}));+ }+ inputs.push(json!({"name": name, "type": i["type"], "linked": i["link"].is_i64()}));+ }+ let outputs: Vec<J> = n["outputs"].as_array().into_iter().flatten().map(|o| json!({"name": o["name"], "type": o["type"]})).collect();+ nodes.push(json!({+ "id": id, "class": n["type"], "title": n["title"], "mode": mode_name(n["mode"].as_i64().unwrap_or(0)),+ "pos": n["pos"], "size": n["size"], "widgets": ui_widgets(n, schema), "inputs": inputs, "outputs": outputs,+ "note": NOTES.contains(&n["type"].as_str().unwrap_or_default()),+ }));+ }+ let groups: Vec<J> = v["groups"].as_array().into_iter().flatten().map(|g| json!({"title": g["title"], "box": g["bounding"], "color": g["color"]})).collect();+ return Ok(json!({"format": "ui", "nodes": nodes, "links": links, "groups": groups}));+ }+ let api = if v["prompt"].is_object() { &v["prompt"] } else { v };+ let o = api.as_object().ok_or("not a ComfyUI workflow: neither UI format (nodes, links) nor API format ({id: {class_type, inputs}})")?;+ let mut ids: Vec<&String> = o.keys().filter(|k| o[k.as_str()]["class_type"].is_string()).collect();+ ids.sort_by_key(|k| (k.parse::<i64>().unwrap_or(i64::MAX), k.to_string()));+ let mut nodes = Vec::new();+ let mut links = Vec::new();+ for id in ids {+ let n = &o[id.as_str()];+ let mut widgets = Vec::new();+ let mut inputs = Vec::new();+ for (name, val) in n["inputs"].as_object().into_iter().flatten() {+ match link(val) {+ Some((from, slot)) => {+ links.push(json!({"from": from, "slot": slot, "to": id, "input": name}));+ inputs.push(json!({"name": name, "linked": true}));+ }+ None => widgets.push(json!({"name": name, "value": val, "at": name})),+ }+ }+ nodes.push(json!({"id": id, "class": n["class_type"], "title": n["_meta"]["title"], "mode": "on", "widgets": widgets, "inputs": inputs, "outputs": [], "note": false}));+ }+ if nodes.is_empty() {+ return Err("no nodes with a class_type".into());+ }+ Ok(json!({"format": "api", "nodes": nodes, "links": links, "groups": []}))+}++/// A board's value for a setting in the setting's own type: "30" for a number is 30, "true" for a flag is true.+fn coerce(old: &J, new: &J) -> Result<J, String> {+ let Some(s) = new.as_str() else { return Ok(new.clone()) };+ Ok(match old {+ J::Number(n) if n.is_i64() || n.is_u64() => J::from(s.trim().parse::<i64>().map_err(|_| format!("{s:?} isn't a whole number"))?),+ J::Number(_) => json!(s.trim().parse::<f64>().map_err(|_| format!("{s:?} isn't a number"))?),+ J::Bool(_) => J::Bool(match s.trim() { "true" | "on" | "yes" => true, "false" | "off" | "no" => false, _ => return Err(format!("{s:?} isn't true or false")) }),+ _ => new.clone(),+ })+}++/// A board's edits written into the workflow: `{widgets: [{node, name, value}], modes: [{node, mode: on|bypass|mute}],+/// notes: [{node?, text}]}` (a note with no node is a new Note node). Returns how many changes it made.+pub fn set(v: &mut J, changes: &J, schema: &Schema) -> Result<usize, String> {+ let mut n_changed = 0;+ if v["nodes"].is_array() {+ let find = |v: &mut J, id: &str| -> Result<usize, String> {+ v["nodes"].as_array().unwrap().iter().position(|n| id_of(n) == id).ok_or(format!("the workflow has no node {id}"))+ };+ for c in changes["widgets"].as_array().into_iter().flatten() {+ let (id, name) = (c["node"].as_str().unwrap_or_default(), c["name"].as_str().unwrap_or_default());+ let k = find(v, id)?;+ let n = &mut v["nodes"][k];+ let at = ui_widgets(n, schema).into_iter().find(|w| w["name"] == name).map(|w| w["at"].clone()).ok_or(format!("node {id} has no setting {name}"))?;+ let slot = match &at { J::String(key) => &mut n["widgets_values"][key.as_str()], _ => &mut n["widgets_values"][at.as_u64().unwrap_or(0) as usize] };+ let new = coerce(slot, &c["value"])?;+ if *slot != new {+ *slot = new;+ n_changed += 1;+ }+ }+ for c in changes["modes"].as_array().into_iter().flatten() {+ let id = c["node"].as_str().unwrap_or_default();+ let m = match c["mode"].as_str() { Some("on") => 0, Some("mute") => 2, Some("bypass") => 4, other => return Err(format!("mode {other:?}: on, bypass or mute")) };+ let k = find(v, id)?;+ if v["nodes"][k]["mode"].as_i64().unwrap_or(0) != m {+ v["nodes"][k]["mode"] = J::from(m);+ n_changed += 1;+ }+ }+ for c in changes["notes"].as_array().into_iter().flatten() {+ let text = c["text"].as_str().ok_or("a note needs its text")?;+ if let Some(id) = c["node"].as_str() {+ let k = find(v, id)?;+ if v["nodes"][k]["widgets_values"][0] != text {+ v["nodes"][k]["widgets_values"] = json!([text]);+ n_changed += 1;+ }+ continue;+ }+ // a new note goes right of everything, so it covers nothing+ let nodes = v["nodes"].as_array().unwrap();+ let right = nodes.iter().map(|n| n["pos"][0].as_f64().unwrap_or(0.0) + n["size"][0].as_f64().unwrap_or(0.0)).fold(0.0, f64::max);+ let top = nodes.iter().filter_map(|n| n["pos"][1].as_f64()).fold(f64::MAX, f64::min);+ let id = v["last_node_id"].as_i64().unwrap_or(0).max(nodes.iter().filter_map(|n| n["id"].as_i64()).max().unwrap_or(0)) + 1;+ let mut note = Map::new();+ for (k, val) in [("id", json!(id)), ("type", json!("Note")), ("pos", json!([right + 60.0, if top == f64::MAX { 0.0 } else { top }])), ("size", json!([320, 120])), ("flags", json!({})), ("order", json!(nodes.len())), ("mode", json!(0)), ("inputs", json!([])), ("outputs", json!([])), ("properties", json!({})), ("widgets_values", json!([text]))] {+ note.insert(k.into(), val);+ }+ v["nodes"].as_array_mut().unwrap().push(J::Object(note));+ v["last_node_id"] = json!(id);+ n_changed += 1;+ }+ return Ok(n_changed);+ }+ if changes["modes"].as_array().is_some_and(|a| !a.is_empty()) || changes["notes"].as_array().is_some_and(|a| !a.is_empty()) {+ return Err("an API-format workflow keeps no bypass or notes: save the workflow from ComfyUI's editor (UI format) to have them".into());+ }+ let api = if v["prompt"].is_object() { &mut v["prompt"] } else { v };+ for c in changes["widgets"].as_array().into_iter().flatten() {+ let (id, name) = (c["node"].as_str().unwrap_or_default(), c["name"].as_str().unwrap_or_default());+ let slot = api.get_mut(id).and_then(|n| n["inputs"].get_mut(name)).ok_or(format!("node {id} has no setting {name}"))?;+ if link(slot).is_some() {+ return Err(format!("node {id}'s {name} is a link, not a setting"));+ }+ let new = coerce(slot, &c["value"])?;+ if *slot != new {+ *slot = new;+ n_changed += 1;+ }+ }+ Ok(n_changed)+}++#[cfg(test)]+mod tests {+ use super::*;++ fn ui() -> J {+ json!({+ "last_node_id": 3,+ "nodes": [+ {"id": 1, "type": "KSampler", "mode": 0, "pos": [0, 0], "size": [300, 260], "inputs": [{"name": "model", "type": "MODEL", "link": 7}], "outputs": [{"name": "LATENT", "type": "LATENT"}], "widgets_values": [42, "randomize", 20, 7.5, "euler", "normal", 1.0]},+ {"id": 2, "type": "CheckpointLoaderSimple", "mode": 4, "pos": [-400, 0], "size": [300, 100], "outputs": [{"name": "MODEL", "type": "MODEL"}], "widgets_values": ["sd.safetensors"]},+ {"id": 3, "type": "Note", "mode": 0, "pos": [0, 300], "size": [300, 100], "widgets_values": ["try 30 steps"]}+ ],+ "links": [[7, 2, 0, 1, 0, "MODEL"]],+ "groups": [{"title": "Sample", "bounding": [-20, -40, 360, 320]}]+ })+ }++ #[test]+ fn a_ui_workflow_viewed_names_settings_past_the_seed_control() {+ let s = crate::schema::load();+ let g = view(&ui(), &s).unwrap();+ let k = &g["nodes"][0];+ assert_eq!(k["widgets"][1], json!({"name": "steps", "value": 20, "at": 2}));+ assert_eq!(g["nodes"][1]["mode"], "bypass");+ assert_eq!(g["links"][0], json!({"from": "2", "slot": 0, "to": "1", "input": "model", "type": "MODEL"}));+ assert_eq!(g["groups"][0]["title"], "Sample");+ assert_eq!(g["nodes"][2]["note"], true);+ }++ #[test]+ fn edits_go_back_into_the_workflow_in_their_own_types() {+ let s = crate::schema::load();+ let mut w = ui();+ let n = set(&mut w, &json!({"widgets": [{"node": "1", "name": "steps", "value": "30"}, {"node": "1", "name": "cfg", "value": "6.5"}], "modes": [{"node": "2", "mode": "on"}], "notes": [{"node": "3", "text": "30 is better"}, {"text": "new idea"}]}), &s).unwrap();+ assert_eq!(n, 5);+ assert_eq!(w["nodes"][0]["widgets_values"], json!([42, "randomize", 30, 6.5, "euler", "normal", 1.0]));+ assert_eq!(w["nodes"][1]["mode"], 0);+ assert_eq!(w["nodes"][2]["widgets_values"], json!(["30 is better"]));+ assert_eq!(w["nodes"][3]["type"], "Note");+ assert_eq!(w["last_node_id"], 4);+ assert!(set(&mut w, &json!({"widgets": [{"node": "1", "name": "steps", "value": "lots"}]}), &s).is_err());+ }++ #[test]+ fn an_api_workflow_takes_settings_but_not_bypass() {+ let s = crate::schema::load();+ let mut w = json!({"1": {"class_type": "ImageScale", "inputs": {"image": ["2", 0], "width": 48}}, "2": {"class_type": "LoadImage", "inputs": {"image": "in.png"}}});+ let g = view(&w, &s).unwrap();+ assert_eq!(g["links"][0], json!({"from": "2", "slot": 0, "to": "1", "input": "image"}));+ assert_eq!(set(&mut w, &json!({"widgets": [{"node": "1", "name": "width", "value": "64"}]}), &s).unwrap(), 1);+ assert_eq!(w["1"]["inputs"]["width"], 64);+ assert!(set(&mut w, &json!({"widgets": [{"node": "1", "name": "image", "value": "x"}]}), &s).is_err());+ assert!(set(&mut w, &json!({"modes": [{"node": "1", "mode": "bypass"}]}), &s).is_err());+ }+}diff --git a/io/gen-comfy/src/write.rs b/io/gen-comfy/src/write.rsnew file mode 100644index 00000000..4b28097c--- /dev/null+++ b/io/gen-comfy/src/write.rs@@ -0,0 +1,258 @@+//! A flow written as a ComfyUI workflow (API format). A step with ComfyUI weights and no made model becomes the+//! classic chain (checkpoint, LoRAs, prompts, latent, KSampler, decode); a `comfy` step goes back as its own nodes;+//! a load becomes LoadImage, LoadVideo or LoadAudio; every other step becomes a RaeaMade node, which tools/comfy/raea_made+//! (a custom node pack) runs on made.app from inside ComfyUI (text.generate on OpenRouter, its words on a STRING output). Each output gets a Save node of its kind.++use std::collections::BTreeMap;++use serde_json::{Map, Value as J, json};++use raea_io_gen_core::flow::{Flow, Kind, Step, op, reference};++/// A step's output in the written graph: the node, the slot, what kind of thing it is.+type Out = (String, usize, Kind);++struct W {+ nodes: Map<String, J>,+ outs: BTreeMap<String, Out>,+ /// a comfy step's outputs when it gives several slots (`slots`), in its order: `@step.N` is the Nth+ slots: BTreeMap<String, Vec<Out>>,+}++impl W {+ fn add(&mut self, id: String, class: &str, inputs: J) -> String {+ self.nodes.insert(id.clone(), json!({"class_type": class, "inputs": inputs}));+ id+ }++ fn link(&self, v: &J) -> Option<J> {+ let r = reference(v)?;+ let (n, s, _) = match crate::flow_index(v).and_then(|i| self.slots.get(r)?.get(i)) {+ Some(o) => o,+ None => self.outs.get(r)?,+ };+ Some(json!([n, s]))+ }+}++fn kind_of(step: &Step, w: &W) -> Kind {+ match op(&step.op).map(|o| o.1) {+ Some(Kind::Any) | None => {+ if step.op == "media.load" {+ let p = step.inputs.get("path").or(step.inputs.get("url")).and_then(|p| p.as_str()).unwrap_or("").to_ascii_lowercase();+ return if [".mp4", ".mov", ".webm", ".mkv"].iter().any(|e| p.ends_with(e)) { Kind::Video } else if [".wav", ".mp3", ".flac", ".m4a", ".ogg"].iter().any(|e| p.ends_with(e)) { Kind::Audio } else { Kind::Image };+ }+ let _ = w;+ Kind::Image+ }+ Some(k) => k,+ }+}++fn get<'a>(s: &'a Step, k: &str) -> Option<&'a J> {+ s.inputs.get(k)+}++/// Whether a step is written as the classic sampler chain: it names ComfyUI weights and isn't sent to made.+fn local_chain(s: &Step) -> bool {+ matches!(s.op.as_str(), "image.generate" | "image.edit") && get(s, "weights").is_some_and(|w| w.is_string()) && !s.model.as_deref().is_some_and(|m| m.starts_with("made:"))+}++pub fn write(flow: &Flow) -> Result<J, String> {+ let mut w = W { nodes: Map::new(), outs: BTreeMap::new(), slots: BTreeMap::new() };+ for id in flow.order()? {+ let s = &flow.steps[&id];+ let kind = kind_of(s, &w);+ let out: Out = if s.op == "media.load" {+ let p = get(s, "path").or(get(s, "url")).and_then(|p| p.as_str()).unwrap_or("input.png");+ let name = std::path::Path::new(p).file_name().and_then(|n| n.to_str()).unwrap_or(p).to_string();+ let (class, key) = match kind { Kind::Video => ("LoadVideo", "file"), Kind::Audio => ("LoadAudio", "audio"), _ => ("LoadImage", "image") };+ (w.add(id.clone(), class, json!({key: name})), 0, kind)+ } else if s.op == "comfy" {+ comfy(&mut w, &id, s)?+ } else if let Some(o) = native(&mut w, &id, s) {+ o+ } else if local_chain(s) {+ chain(&mut w, &id, s)+ } else {+ made(&mut w, &id, s, kind)+ };+ w.outs.insert(id, out);+ }+ for (k, o) in flow.out.iter().enumerate() {+ // one Save per output; a step giving several slots gets one per slot: save<k>, save<k>.1, save<k>.2, …+ let outs = w.slots.get(o).cloned().unwrap_or_else(|| vec![w.outs[o].clone()]);+ for (j, (n, slot, kind)) in outs.into_iter().enumerate() {+ let (class, key) = match kind { Kind::Video => ("SaveVideo", "video"), Kind::Audio => ("SaveAudio", "audio"), Kind::Text => ("PreviewAny", "source"), _ => ("SaveImage", "images") };+ let mut inputs = json!({key: [n, slot], "filename_prefix": format!("raea/{o}")});+ if class == "PreviewAny" {+ inputs = json!({key: [n, slot]});+ }+ if class == "SaveVideo" {+ inputs["format"] = json!("auto");+ inputs["codec"] = json!("auto");+ }+ w.add(if j == 0 { format!("save{k}") } else { format!("save{k}.{j}") }, class, inputs);+ }+ }+ Ok(J::Object(w.nodes))+}++/// A `comfy` step's nodes, ids prefixed by the step's, links rewritten, bound inputs pointed at the steps they name.+fn comfy(w: &mut W, id: &str, s: &Step) -> Result<Out, String> {+ let nodes = get(s, "nodes").and_then(|n| n.as_object()).ok_or(format!("step `{id}`: comfy nodes aren't an object"))?;+ let bind = get(s, "bind").and_then(|b| b.as_object()).cloned().unwrap_or_default();+ let pre = |n: &str| format!("{id}.{n}");+ for (nid, n) in nodes {+ let mut inputs = n["inputs"].as_object().cloned().unwrap_or_default();+ for (name, v) in inputs.iter_mut() {+ if let Some(target) = bind.get(&format!("{nid}.{name}")) {+ *v = w.link(target).ok_or(format!("step `{id}` binds {nid}.{name} to {target}, which isn't written yet"))?;+ } else if let Some(a) = v.as_array_mut().filter(|a| a.len() == 2 && a[1].is_u64() && a[0].is_string()) {+ a[0] = json!(pre(a[0].as_str().unwrap_or_default()));+ }+ }+ w.add(pre(nid), n["class_type"].as_str().unwrap_or_default(), J::Object(inputs));+ }+ let output = get(s, "output").and_then(|o| o.as_str()).ok_or(format!("step `{id}`: no output node"))?;+ let class = nodes.get(output).and_then(|n| n["class_type"].as_str()).unwrap_or("");+ let schema = crate::schema::load();+ let slots: Vec<usize> = get(s, "slots").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|x| x.as_u64()).map(|x| x as usize).collect()).filter(|v: &Vec<usize>| !v.is_empty()).unwrap_or(vec![0]);+ let mut outs = Vec::new();+ for slot in slots {+ // what the node puts out there, from the server's schema where it's known, else read from its name+ let ty = schema.get(class).and_then(|c| c.outputs.get(slot)).cloned().unwrap_or_default();+ outs.push(if ty == "MASK" {+ // a mask is saved as the picture of it+ let m = w.add(pre(&format!("{output}.picture{slot}")), "MaskToImage", json!({"mask": [pre(output), slot]}));+ (m, 0, Kind::Image)+ } else {+ let kind = match ty.as_str() {+ "VIDEO" => Kind::Video,+ "AUDIO" => Kind::Audio,+ "IMAGE" => Kind::Image,+ _ if class.contains("Video") => Kind::Video,+ _ if class.contains("Audio") => Kind::Audio,+ _ => Kind::Image,+ };+ (pre(output), slot, kind)+ });+ }+ let first = outs[0].clone();+ if outs.len() > 1 {+ w.slots.insert(id.to_string(), outs);+ }+ Ok(first)+}++/// raea's own image utilities as ComfyUI's core nodes: ImageCrop, ImageScale (or ScaleBy, ScaleToTotalPixels), and+/// ImageStitch chained for more than two pictures.+/// A step's setting `k`, else `d`.+fn num(s: &Step, k: &str, d: J) -> J {+ get(s, k).cloned().unwrap_or(d)+}++fn native(w: &mut W, id: &str, s: &Step) -> Option<Out> {+ let img = |w: &W, k: &str| get(s, k).and_then(|v| w.link(v));+ let node = match s.op.as_str() {+ "image.crop" => w.add(id.into(), "ImageCrop", json!({"image": img(w, "image")?, "width": num(s, "width", json!(512)), "height": num(s, "height", json!(512)), "x": num(s, "x", json!(0)), "y": num(s, "y", json!(0))})),+ "image.scale" => {+ let image = img(w, "image")?;+ if let Some(f) = get(s, "factor") {+ w.add(id.into(), "ImageScaleBy", json!({"image": image, "upscale_method": "lanczos", "scale_by": f}))+ } else if let Some(mp) = get(s, "megapixels") {+ w.add(id.into(), "ImageScaleToTotalPixels", json!({"image": image, "upscale_method": "lanczos", "megapixels": mp, "resolution_steps": 1}))+ } else {+ // contain has no core node: it scales as stretch would, to the box+ let crop = if get(s, "fit").is_some_and(|f| f == "cover") { "center" } else { "disabled" };+ w.add(id.into(), "ImageScale", json!({"image": image, "upscale_method": "lanczos", "width": num(s, "width", json!(0)), "height": num(s, "height", json!(0)), "crop": crop}))+ }+ }+ "image.stitch" => {+ let links: Vec<J> = get(s, "images")?.as_array()?.iter().filter_map(|v| w.link(v)).collect();+ let dir = num(s, "direction", json!("right"));+ let mut acc = links.first()?.clone();+ let mut last = String::new();+ for (k, next) in links.iter().enumerate().skip(1) {+ let nid = if k + 1 == links.len() { id.to_string() } else { format!("{id}.{k}") };+ last = w.add(nid, "ImageStitch", json!({"image1": acc, "image2": next, "direction": dir, "match_image_size": true, "spacing_width": 0, "spacing_color": "white"}));+ acc = json!([last, 0]);+ }+ if last.is_empty() {+ // one picture: nothing to stitch+ return Some((acc[0].as_str()?.to_string(), acc[1].as_u64()? as usize, Kind::Image));+ }+ last+ }+ _ => return None,+ };+ Some((node, 0, Kind::Image))+}++/// The classic chain for a step with weights: checkpoint, each LoRA, the prompts, a latent (empty, or the image+/// encoded), KSampler, decode.+fn chain(w: &mut W, id: &str, s: &Step) -> Out {+ let n = |k: &str| format!("{id}.{k}");+ w.add(n("ckpt"), "CheckpointLoaderSimple", json!({"ckpt_name": get(s, "weights")}));+ let (mut model, mut clip) = (json!([n("ckpt"), 0]), json!([n("ckpt"), 1]));+ for (k, l) in get(s, "loras").and_then(|l| l.as_array()).cloned().unwrap_or_default().iter().enumerate() {+ let lid = w.add(n(&format!("lora{k}")), "LoraLoader", json!({"model": model, "clip": clip, "lora_name": l["name"], "strength_model": l["strength"].as_f64().unwrap_or(1.0), "strength_clip": l["strength"].as_f64().unwrap_or(1.0)}));+ (model, clip) = (json!([lid, 0]), json!([lid, 1]));+ }+ w.add(n("pos"), "CLIPTextEncode", json!({"clip": clip, "text": num(s, "prompt", json!(""))}));+ w.add(n("neg"), "CLIPTextEncode", json!({"clip": clip, "text": num(s, "negative", json!(""))}));+ let (latent, denoise) = match get(s, "image").and_then(|v| w.link(v)) {+ Some(img) => {+ w.add(n("enc"), "VAEEncode", json!({"pixels": img, "vae": [n("ckpt"), 2]}));+ (json!([n("enc"), 0]), num(s, "strength", json!(0.75)))+ }+ None => {+ w.add(n("latent"), "EmptyLatentImage", json!({"width": num(s, "width", json!(1024)), "height": num(s, "height", json!(1024)), "batch_size": 1}));+ (json!([n("latent"), 0]), json!(1.0))+ }+ };+ w.add(n("sample"), "KSampler", json!({+ "model": model, "positive": [n("pos"), 0], "negative": [n("neg"), 0], "latent_image": latent,+ "seed": num(s, "seed", json!(0)), "steps": num(s, "steps", json!(25)), "cfg": num(s, "cfg", json!(7.0)),+ "sampler_name": num(s, "sampler", json!("euler")), "scheduler": num(s, "scheduler", json!("normal")), "denoise": denoise,+ }));+ w.add(n("decode"), "VAEDecode", json!({"samples": [n("sample"), 0], "vae": [n("ckpt"), 2]}));+ (n("decode"), 0, Kind::Image)+}++/// A RaeaMade node: the op, the made model, the text inputs as settings, the rest as JSON; media as links.+fn made(w: &mut W, id: &str, s: &Step, kind: Kind) -> Out {+ let mut inputs = Map::new();+ let mut params = Map::new();+ let mut refs = 0;+ for (k, v) in &s.inputs {+ let links: Vec<J> = match v {+ J::Array(a) => a.iter().filter_map(|x| w.link(x)).collect(),+ _ => w.link(v).into_iter().collect(),+ };+ if !links.is_empty() {+ for l in links {+ // ComfyUI inputs are one link each: a list of references becomes ref_1, ref_2, …+ let name = if matches!(v, J::Array(_)) || k == "refs" { refs += 1; format!("ref_{refs}") } else { k.clone() };+ inputs.insert(name, l);+ }+ } else if k == "prompt" || k == "text" {+ inputs.insert("prompt".into(), v.clone());+ } else {+ params.insert(k.clone(), v.clone());+ }+ }+ inputs.insert("op".into(), json!(s.op));+ inputs.insert("model".into(), json!(s.model.as_deref().and_then(|m| m.strip_prefix("made:")).unwrap_or("auto")));+ inputs.insert("params".into(), json!(J::Object(params).to_string()));+ inputs.entry("prompt").or_insert(json!(""));+ // RaeaMade's outputs: IMAGE, VIDEO, AUDIO, MASK, STRING+ let slot = match kind { Kind::Video => 1, Kind::Audio => 2, Kind::Text => 4, _ => 0 };+ let node = w.add(id.to_string(), "RaeaMade", J::Object(inputs));+ if s.op == "image.remove_background" {+ // the cut-out's transparency rides as the mask: joined back so it's saved+ let join = w.add(format!("{id}.alpha"), "JoinImageWithAlpha", json!({"image": [node, 0], "alpha": [node, 3]}));+ return (join, 0, kind);+ }+ (node, slot, kind)+}diff --git a/io/gen-core/Cargo.toml b/io/gen-core/Cargo.tomlnew file mode 100644index 00000000..fd409793--- /dev/null+++ b/io/gen-core/Cargo.toml@@ -0,0 +1,12 @@+[package]+name = "raea-io-gen-core"+version = "0.1.0"+edition = "2024"+license = "FSL-1.1-ALv2"+publish = false+description = "Generation flows' ground: the flow format and its op table, settings, and the hosted backends a step runs on (made.app at provider cost, fal, Replicate, OpenRouter, Modal)"++[dependencies]+raea-io-home = { path = "../home" }+serde_json = "1"+sha2 = "0.10"diff --git a/io/gen-core/src/direct.rs b/io/gen-core/src/direct.rsnew file mode 100644index 00000000..9be1c346--- /dev/null+++ b/io/gen-core/src/direct.rs@@ -0,0 +1,90 @@+//! A made request sent to fal itself, at fal's price. made says `markupPercent: 0`, but since 2026-10-29 it rounds each+//! job up to a whole credit (10¢): a 1¢ FLUX Klein image is billed 10¢ (its /v1/cost answers providerCostCents 1,+//! customerCostCents 10). For a model made runs on fal, its catalog row says exactly how made calls fal: the endpoint+//! (`workflowId`, or `editWorkflowId` when given media), each media role's fal field (`mediaRoles`), and how settings+//! are renamed, scaled, stringified or dropped (`inputMap`, `providerParams`). So when made would charge more than the+//! provider does, the same request goes to fal directly (FAL_KEY), unless RAEA_GEN_VIA=made. A model made runs+//! elsewhere goes the same way when fal serves the same model (TWINS).++use serde_json::{Map, Value as J, json};++/// made models it runs elsewhere that fal also serves, the same model at the same setting: (made id, fal endpoint,+/// fal endpoint given pictures, fal settings that make it that model). gpt_image_2_5_fast is made_batch's+/// gpt-image-2.5-flare-low: fal's page prices low quality at 0.4-0.6¢ an image (10-29), made bills 10¢.+const TWINS: &[(&str, &str, &str, &str)] = &[+ ("gpt_image_2_5_fast", "openai/gpt-image-2.5/flare/text-to-image", "openai/gpt-image-2.5/flare/edit", r#"{"quality":"low"}"#),+];++fn twin(model: &J) -> Option<&'static (&'static str, &'static str, &'static str, &'static str)> {+ TWINS.iter().find(|t| model["id"] == t.0)+}++/// Whether this model can go straight to fal: made runs it there (or fal serves its twin), and none of its settings+/// need made's own handling.+pub fn possible(model: &J) -> bool {+ twin(model).is_some() || model["provider"] == "fal" && model["workflowId"].is_string() && !model["inputMap"].as_object().is_some_and(|m| m.values().any(|v| v["dimensions"] == true))+}++/// A made body for a twin: the prompt, pictures as image_urls, the aspect as fal's image_size, the twin's settings.+fn twin_body(t: &(&str, &str, &str, &str), made: &J) -> (String, J) {+ let medias = made["medias"].as_array().cloned().unwrap_or_default();+ let mut out: Map<String, J> = serde_json::from_str(t.3).unwrap_or_default();+ out.insert("prompt".into(), made["prompt"].clone());+ if let Some(size) = made["aspect_ratio"].as_str().and_then(|a| match a {+ "1:1" => Some("square_hd"), "4:3" => Some("landscape_4_3"), "3:4" => Some("portrait_4_3"),+ "16:9" => Some("landscape_16_9"), "9:16" => Some("portrait_16_9"), _ => None,+ }) {+ out.insert("image_size".into(), json!(size));+ }+ if medias.is_empty() {+ return (t.1.to_string(), J::Object(out));+ }+ out.insert("image_urls".into(), J::Array(medias.iter().map(|m| m["value"].clone()).collect()));+ (t.2.to_string(), J::Object(out))+}++/// A made body (model, prompt, medias with values as URLs, settings) as (fal endpoint, fal input).+pub fn body(model: &J, made: &J) -> Result<(String, J), String> {+ if let Some(t) = twin(model) {+ return Ok(twin_body(t, made));+ }+ let medias = made["medias"].as_array().cloned().unwrap_or_default();+ let endpoint = match (medias.is_empty(), model["editWorkflowId"].as_str()) {+ (false, Some(e)) => e,+ _ => model["workflowId"].as_str().ok_or("no workflowId")?,+ }.to_string();+ let map = model["inputMap"].as_object().cloned().unwrap_or_default();+ let mut out = Map::new();+ for (k, v) in made.as_object().into_iter().flatten() {+ if matches!(k.as_str(), "model" | "medias" | "request_id" | "max_cost_cents" | "count") {+ continue;+ }+ let rule = map.get(k).cloned().unwrap_or(J::Null);+ if rule["drop"] == true {+ continue;+ }+ let mut v = v.clone();+ if let Some(scale) = rule["scale"].as_f64() {+ v = json!(v.as_f64().unwrap_or(0.0) * scale);+ }+ if let Some(to) = rule["values"].get(v.to_string().trim_matches('"')).or_else(|| rule["values"].get(v.as_str().unwrap_or(""))) {+ v = to.clone();+ } else if rule["stringify"] == true {+ v = json!(v.to_string().trim_matches('"'));+ }+ out.insert(rule["field"].as_str().unwrap_or(k).to_string(), v);+ }+ let roles = model["mediaRoles"].as_object().cloned().unwrap_or_default();+ for m in &medias {+ let role = m["role"].as_str().unwrap_or("");+ let field = roles.get(role).and_then(|f| f.as_str()).ok_or(format!("{} has no fal field for role {role}", model["id"]))?;+ match field.strip_suffix("[]") {+ Some(list) => out.entry(list).or_insert(json!([])).as_array_mut().ok_or("media field clash")?.push(m["value"].clone()),+ None => { out.insert(field.to_string(), m["value"].clone()); }+ }+ }+ for (k, v) in model["providerParams"].as_object().into_iter().flatten() {+ out.entry(k.clone()).or_insert(v.clone());+ }+ Ok((endpoint, J::Object(out)))+}diff --git a/io/gen-core/src/fal.rs b/io/gen-core/src/fal.rsnew file mode 100644index 00000000..61b7088c--- /dev/null+++ b/io/gen-core/src/fal.rs@@ -0,0 +1,151 @@+//! fal directly, for what made doesn't carry (3D: Tripo, Meshy, Rodin, Hunyuan 3D; any niche endpoint): a step+//! whose model is `fal:<endpoint id>`. A request goes on fal's queue (queue.fal.run), is polled at the status URL it+//! hands back and read from the response URL; the files are every `url` in the response. Media go inline as data+//! URIs. The key is FAL_KEY; prices come from fal's pricing API (a unit price per image, second or request).++use std::path::Path;+use std::time::{Duration, Instant};++use serde_json::{Value as J, json};++use crate::http::{Body, call, key_header};++pub struct Fal {+ headers: Vec<String>,+}++impl Fal {+ pub fn from_settings() -> Result<Fal, String> {+ Ok(Fal { headers: vec![key_header("FAL_KEY", "Key", "fal needs FAL_KEY in ~/.raea/env (fal.ai/dashboard/keys)")?] })+ }++ fn json(&self, method: &str, url: &str, body: Option<&J>) -> Result<J, String> {+ let r = call(method, url, &self.headers, body.map(Body::Json).unwrap_or(Body::None), None, 120)?;+ let v = r.json().map_err(|e| format!("fal {}: {e}", crate::http::redact(url)))?;+ if !r.ok() {+ return Err(format!("fal {} answered {}: {}", crate::http::redact(url), r.code, crate::http::clip(&v["detail"].as_str().map(str::to_string).unwrap_or(v.to_string()))));+ }+ Ok(v)+ }++ /// The endpoint's unit price in cents and what the unit is (`image`, `second`, `request`…), when fal publishes one.+ pub fn price(&self, endpoint: &str) -> Result<(f64, String), String> {+ let v = self.json("GET", &format!("https://api.fal.ai/v1/models/pricing?endpoint_id={endpoint}"), None)?;+ let p = v["prices"].as_array().and_then(|a| a.first()).ok_or(format!("fal has no price for {endpoint}"))?;+ Ok((p["unit_price"].as_f64().unwrap_or(0.0) * 100.0, p["unit"].as_str().unwrap_or("request").to_string()))+ }++ /// The endpoint's input fields (from its OpenAPI page), kept in ~/.cache/raea-gen/fal/: (name, is a list).+ pub fn inputs(&self, endpoint: &str) -> Vec<(String, bool)> {+ let cache = crate::made::cache_dir().join("fal").join(format!("{}.json", endpoint.replace('/', "__")));+ let spec = std::fs::read(&cache).ok().and_then(|b| serde_json::from_slice::<J>(&b).ok()).or_else(|| {+ let r = call("GET", &format!("https://fal.ai/api/openapi/queue/openapi.json?endpoint_id={endpoint}"), &[], Body::None, None, 30).ok()?;+ let v = r.json().ok().filter(|_| r.ok())?;+ let _ = std::fs::create_dir_all(cache.parent()?);+ let _ = std::fs::write(&cache, v.to_string());+ Some(v)+ });+ let Some(spec) = spec else { return vec![] };+ spec["components"]["schemas"].as_object().into_iter().flatten().filter(|(k, _)| k.ends_with("Input")).flat_map(|(_, v)| {+ v["properties"].as_object().into_iter().flatten().map(|(n, p)| (n.clone(), p["type"] == "array")).collect::<Vec<_>>()+ }).collect()+ }++ /// A request run to the end: fal's response JSON.+ /// A local file into fal's storage; its https URL, so a request carries a link rather than megabytes of data URI.+ pub fn upload(&self, file: &std::path::Path) -> Result<String, String> {+ let mime = crate::made::mime_of(file);+ let name = file.file_name().and_then(|n| n.to_str()).unwrap_or("file");+ let v = self.json("POST", "https://rest.alpha.fal.ai/storage/upload/initiate?storage_type=fal-cdn-v3", Some(&json!({"content_type": mime, "file_name": name})))?;+ let (put, url) = (v["upload_url"].as_str().ok_or("fal storage: no upload_url")?, v["file_url"].as_str().ok_or("fal storage: no file_url")?);+ let r = call("PUT", put, &[format!("Content-Type: {mime}")], Body::File(file), None, 600)?;+ if !r.ok() {+ return Err(format!("fal storage upload of {} answered {}", file.display(), r.code));+ }+ Ok(url.to_string())+ }++ pub fn run(&self, endpoint: &str, input: &J, stall: Duration) -> Result<J, String> {+ let q = self.json("POST", &format!("https://queue.fal.run/{endpoint}"), Some(input))?;+ let status = q["status_url"].as_str().ok_or_else(|| format!("fal queue: no status_url in {q}"))?.to_string();+ let response = q["response_url"].as_str().ok_or("fal queue: no response_url")?.to_string();+ let (mut seen, mut since, mut nap) = (String::new(), Instant::now(), 1);+ loop {+ let s = self.json("GET", &status, None)?;+ let now = format!("{}:{}", s["status"], s["queue_position"]);+ match s["status"].as_str() {+ Some("COMPLETED") => break,+ Some("FAILED" | "ERROR") => return Err(format!("fal {endpoint} failed: {s}")),+ _ => {}+ }+ if now != seen {+ (seen, since) = (now, Instant::now());+ } else if since.elapsed() > stall {+ let _ = self.json("PUT", &format!("{}/cancel", status.trim_end_matches("/status")), None);+ return Err(format!("fal {endpoint} sat at {seen} for {}s, canceled", stall.as_secs()));+ }+ std::thread::sleep(Duration::from_secs(nap));+ nap = (nap + 1).min(6);+ }+ self.json("GET", &response, None)+ }+}++/// Every file URL in a response, in the order they appear (images[0].url, video.url, model_mesh.url, …).+pub fn urls(v: &J, out: &mut Vec<String>) {+ match v {+ J::Object(o) => {+ if let Some(u) = o.get("url").and_then(|u| u.as_str()).filter(|u| u.starts_with("http")) {+ out.push(u.to_string());+ }+ o.iter().filter(|(k, _)| k.as_str() != "url").for_each(|(_, x)| urls(x, out));+ }+ J::Array(a) => a.iter().for_each(|x| urls(x, out)),+ _ => {}+ }+}++/// A local file as a data URI, which fal's endpoints take wherever they take a URL.+pub fn data_uri(file: &Path) -> Result<String, String> {+ let bytes = std::fs::read(file).map_err(|e| format!("{}: {e}", file.display()))?;+ Ok(format!("data:{};base64,{}", crate::made::mime_of(file), base64(&bytes)))+}++fn base64(b: &[u8]) -> String {+ const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";+ let mut s = String::with_capacity(b.len().div_ceil(3) * 4);+ for c in b.chunks(3) {+ let n = (c[0] as u32) << 16 | (*c.get(1).unwrap_or(&0) as u32) << 8 | *c.get(2).unwrap_or(&0) as u32;+ for i in 0..4 {+ s.push(if i <= c.len() { T[(n >> (18 - 6 * i) & 63) as usize] as char } else { '=' });+ }+ }+ s+}++/// A step's inputs as the endpoint's fields: prompt, seed, negative_prompt; x_<name> as <name>; media into the+/// endpoint's image field (from its schema: `image_url`, `input_image_url`, `image_urls`, …).+pub fn body(inputs: &serde_json::Map<String, J>, media: &[(String, String)], fields: &[(String, bool)]) -> J {+ let mut b = json!({});+ for (k, v) in inputs {+ match k.as_str() {+ "prompt" | "seed" | "negative" => { b[if k == "negative" { "negative_prompt" } else { k.as_str() }] = v.clone(); }+ k if k.starts_with("x_") => { b[&k[2..]] = v.clone(); }+ _ => {}+ }+ }+ let images: Vec<&String> = media.iter().map(|(_, u)| u).collect();+ if images.is_empty() {+ return b;+ }+ let field = |list: bool| fields.iter().find(|(n, l)| *l == list && n.contains("image_url")).map(|(n, _)| n.clone());+ match (images.len(), field(false), field(true)) {+ (1, Some(one), _) => b[one.as_str()] = json!(images[0]),+ (_, _, Some(many)) => b[many.as_str()] = json!(images),+ (_, Some(one), None) => b[one.as_str()] = json!(images[0]),+ // no schema to read: fal's most common names+ (1, None, None) => b["image_url"] = json!(images[0]),+ _ => b["image_urls"] = json!(images),+ }+ b+}diff --git a/io/gen-core/src/fish.rs b/io/gen-core/src/fish.rsnew file mode 100644index 00000000..4ace4a87--- /dev/null+++ b/io/gen-core/src/fish.rs@@ -0,0 +1,87 @@+//! Fish Audio: an audio.speech step on Fish's text-to-speech (`fish:<model>`, else `fish:s2.1-pro`), with the founder's own+//! key in FISH_API_KEY. raea sends the step's words (`text`), its `voice` as Fish's reference_id (a voice model's id+//! from fish.audio) and its `speed` as Fish's prosody speed, and keeps the MP3 that comes back. Fish bills UTF-8 bytes+//! of text ($15 a million on its price list, 11-05), so a plan quotes the words before anything is sent.+//! RAEA_FISH_API points the requests somewhere else (a test's stand-in).++use std::path::{Path, PathBuf};++use serde_json::{Map, Value as J, json};++use crate::http::{Body, call};+use crate::setting;++/// The model a bare `fish:` names.+pub const DEFAULT_MODEL: &str = "s2.1-pro";++/// Fish's price for a million UTF-8 bytes of text, in cents.+const CENTS_PER_MILLION_BYTES: f64 = 1500.0;++fn model(name: &str) -> &str {+ if name.is_empty() { DEFAULT_MODEL } else { name }+}++/// What a step's words would cost, in cents (whole cents, rounded up; a short line is 1¢).+pub fn quote(text: &str) -> u64 {+ ((text.len() as f64) * CENTS_PER_MILLION_BYTES / 1_000_000.0).ceil().max(1.0) as u64+}++/// The JSON body Fish's /v1/tts reads, from an audio.speech step's inputs.+pub fn body(inputs: &Map<String, J>) -> Result<J, String> {+ let text = inputs.get("text").and_then(J::as_str).filter(|t| !t.trim().is_empty()).ok_or("an audio.speech step on fish needs text")?;+ let mut b = json!({"text": text, "format": "mp3"});+ if let Some(v) = inputs.get("voice").and_then(J::as_str).filter(|v| !v.is_empty()) {+ b["reference_id"] = json!(v);+ }+ if let Some(s) = inputs.get("speed").and_then(J::as_f64) {+ if !(0.5..=2.0).contains(&s) {+ return Err(format!("fish: speed is 0.5 to 2, got {s}"));+ }+ b["prosody"] = json!({"speed": s});+ }+ Ok(b)+}++/// One audio.speech step on Fish: the MP3 written beside `stem`, and what the words cost.+pub fn run(name: &str, op: &str, inputs: &Map<String, J>, stem: &Path) -> Result<(PathBuf, u64), String> {+ if op != "audio.speech" {+ return Err(format!("fish:{name} makes speech (audio.speech), not {op}"));+ }+ let key = setting("FISH_API_KEY").ok_or("fish needs your Fish Audio API key: put FISH_API_KEY=… in ~/.raea/env (fish.audio, API keys)")?;+ let body = body(inputs)?;+ let api = setting("RAEA_FISH_API").unwrap_or_else(|| "https://api.fish.audio".into());+ let out = stem.with_extension("mp3");+ let h = [format!("Authorization: Bearer {key}"), format!("model: {}", model(name))];+ let r = call("POST", &format!("{}/v1/tts", api.trim_end_matches('/')), &h, Body::Json(&body), Some(&out), 600)?;+ if !r.ok() {+ let said = std::fs::read_to_string(&out).unwrap_or_default().chars().take(300).collect::<String>();+ let _ = std::fs::remove_file(&out);+ return Err(format!("fish:{} answered {}: {said}", model(name), r.code));+ }+ if !r.mime.starts_with("audio/") {+ let _ = std::fs::remove_file(&out);+ return Err(format!("fish:{} answered {} rather than audio", model(name), r.mime));+ }+ Ok((out, quote(body["text"].as_str().unwrap_or(""))))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_step_becomes_fishs_body() {+ let i = json!({"text": "Three drops.", "voice": "abc", "speed": 0.85});+ assert_eq!(body(i.as_object().unwrap()).unwrap(), json!({"text": "Three drops.", "format": "mp3", "reference_id": "abc", "prosody": {"speed": 0.85}}));+ assert!(body(json!({"text": " "}).as_object().unwrap()).is_err());+ assert!(body(json!({"text": "a", "speed": 3}).as_object().unwrap()).is_err());+ }++ #[test]+ fn words_are_quoted_by_their_bytes() {+ assert_eq!(quote("short"), 1);+ assert_eq!(quote(&"a".repeat(10_000)), 15);+ // a non-ASCII character is several bytes+ assert_eq!(quote(&"語".repeat(10_000)), 45);+ }+}diff --git a/io/gen-core/src/flow.rs b/io/gen-core/src/flow.rsnew file mode 100644index 00000000..4b78a780--- /dev/null+++ b/io/gen-core/src/flow.rs@@ -0,0 +1,225 @@+//! A flow: generation steps by what they make, not by who runs them. Each step is an op from OPS (image.generate,+//! video.generate, audio.sfx, …) with its inputs, literal or `@step` (another step's output); a step may name a model+//! (`made:kling_3_pro_i2v`, `fal:<endpoint>`, `replicate:owner/name`, `openrouter:<model>`, `modal:<endpoint>`, `comfy`,+//! `local:sao`) or leave it to the router. A step the importer couldn't name keeps its+//! ComfyUI nodes whole (`comfy`), so nothing is lost and it runs where ComfyUI runs.+//!+//! On disk it's JSON (`{"flow": 1, "steps": {...}, "out": [...]}`); agents write it in TypeScript with raea/gen's+//! flow(), which prints the same JSON.++use std::collections::BTreeMap;++use serde_json::{Map, Value as J, json};+use sha2::{Digest, Sha256};++/// What a step makes.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Kind {+ Image,+ Video,+ Audio,+ /// a 3D model (glb)+ Mesh,+ /// words (a prompt an LLM wrote): a step reading one gets its text in place of the reference+ Text,+ Any,+}++/// The ops a step may be: its name, what it makes, the inputs it reads (the first ones it can't go without).+pub const OPS: &[(&str, Kind, &[&str], &[&str])] = &[+ ("image.generate", Kind::Image, &["prompt"], &["negative", "width", "height", "aspect_ratio", "seed", "steps", "cfg", "sampler", "scheduler", "weights", "loras", "refs", "resolution"]),+ ("image.edit", Kind::Image, &["image", "prompt"], &["mask", "strength", "negative", "seed", "steps", "cfg", "sampler", "scheduler", "weights", "loras", "refs", "aspect_ratio", "resolution"]),+ ("image.upscale", Kind::Image, &["image"], &["factor", "weights"]),+ ("image.remove_background", Kind::Image, &["image"], &[]),+ ("image.expand", Kind::Image, &["image", "aspect_ratio"], &["prompt"]),+ // run by raea itself (io/gen native.rs), no model: ComfyUI's ImageCrop, ImageScale* and ImageStitch+ ("image.crop", Kind::Image, &["image", "width", "height"], &["x", "y"]),+ ("image.scale", Kind::Image, &["image"], &["width", "height", "factor", "megapixels", "fit"]),+ ("image.stitch", Kind::Image, &["images"], &["direction"]),+ ("video.generate", Kind::Video, &[], &["prompt", "negative", "sampler", "scheduler", "seconds", "fps", "width", "height", "aspect_ratio", "start_image", "end_image", "refs", "audio", "seed", "steps", "cfg", "weights", "loras", "resolution"]),+ ("video.edit", Kind::Video, &["video", "prompt"], &["refs", "seconds", "aspect_ratio", "resolution"]),+ ("video.reframe", Kind::Video, &["video", "aspect_ratio"], &[]),+ ("video.upscale", Kind::Video, &["video"], &["factor"]),+ ("audio.music", Kind::Audio, &["prompt"], &["seconds", "seed", "weights"]),+ ("audio.sfx", Kind::Audio, &["prompt"], &["seconds", "video", "seed", "weights"]),+ ("audio.speech", Kind::Audio, &["text"], &["voice", "speed"]),+ ("mesh.generate", Kind::Mesh, &[], &["prompt", "image", "refs", "seed", "texture"]),+ ("text.generate", Kind::Text, &["prompt"], &["system", "image", "refs"]),+ ("media.load", Kind::Any, &[], &["path", "url"]),+ ("comfy", Kind::Any, &["nodes", "output"], &["bind", "slots"]),+];++pub fn op(name: &str) -> Option<&'static (&'static str, Kind, &'static [&'static str], &'static [&'static str])> {+ OPS.iter().find(|o| o.0 == name)+}++#[derive(Clone, Debug, PartialEq)]+pub struct Step {+ pub op: String,+ pub inputs: Map<String, J>,+ /// `made:<id>`, `comfy`, `replicate`, `local:<name>`, or None for the router's choice+ pub model: Option<String>,+ /// how the step came to be (`comfy: KSampler 3 ← CheckpointLoaderSimple 4, …`), for a reader+ pub from: Option<String>,+}++#[derive(Clone, Debug, Default, PartialEq)]+pub struct Flow {+ pub steps: BTreeMap<String, Step>,+ pub out: Vec<String>,+}++/// `@id` (or `@id.N`, an output by index): the step it points at.+pub fn reference(v: &J) -> Option<&str> {+ v.as_str()?.strip_prefix('@').map(|r| r.split_once('.').map_or(r, |(step, _)| step))+}++/// Which of a step's files a reference names: `@step.N` the Nth (a batch's pictures); None for `@step`.+pub fn index(v: &J) -> Option<usize> {+ v.as_str()?.strip_prefix('@')?.split_once('.')?.1.parse().ok()+}++/// Every step a value points at, nested in arrays and objects too (`refs: ["@a", "@b"]`).+pub fn references(v: &J, out: &mut Vec<String>) {+ match v {+ J::String(_) => out.extend(reference(v).map(str::to_string)),+ J::Array(a) => a.iter().for_each(|x| references(x, out)),+ J::Object(o) => o.values().for_each(|x| references(x, out)),+ _ => {}+ }+}++impl Step {+ pub fn new(op: &str, inputs: J) -> Step {+ Step { op: op.into(), inputs: inputs.as_object().cloned().unwrap_or_default(), model: None, from: None }+ }++ pub fn needs(&self) -> Vec<String> {+ let mut out = Vec::new();+ // a comfy step's own nodes link by [id, slot], never by @; only its bindings point at other steps+ let inputs: Vec<&J> = if self.op == "comfy" { self.inputs.get("bind").into_iter().collect() } else { self.inputs.values().collect() };+ inputs.into_iter().for_each(|v| references(v, &mut out));+ out.sort();+ out.dedup();+ out+ }+}++impl Flow {+ pub fn parse(v: &J) -> Result<Flow, String> {+ if v["flow"].as_u64() != Some(1) {+ return Err("not a flow: it says {\"flow\": 1, \"steps\": {...}} at the top".into());+ }+ let mut f = Flow::default();+ for (id, s) in v["steps"].as_object().ok_or("a flow's steps are an object by id")? {+ let op = s["op"].as_str().ok_or(format!("step `{id}` has no op"))?;+ let mut step = Step::new(op, s["in"].clone());+ step.model = s["model"].as_str().map(str::to_string);+ step.from = s["from"].as_str().map(str::to_string);+ f.steps.insert(id.clone(), step);+ }+ f.out = v["out"].as_array().map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()).unwrap_or_default();+ f.check()?;+ Ok(f)+ }++ pub fn to_json(&self) -> J {+ let steps: Map<String, J> = self.steps.iter().map(|(id, s)| {+ let mut o = json!({"op": s.op, "in": s.inputs});+ if let Some(m) = &s.model {+ o["model"] = json!(m);+ }+ if let Some(f) = &s.from {+ o["from"] = json!(f);+ }+ (id.clone(), o)+ }).collect();+ json!({"flow": 1, "steps": steps, "out": self.out})+ }++ /// Ops known, required inputs given, references to steps that exist, no cycles, outputs that exist.+ pub fn check(&self) -> Result<(), String> {+ for (id, s) in &self.steps {+ let (_, _, required, optional) = op(&s.op).ok_or_else(|| format!("step `{id}`: unknown op `{}` (ops: {})", s.op, OPS.iter().map(|o| o.0).collect::<Vec<_>>().join(", ")))?;+ for r in required.iter() {+ if !s.inputs.contains_key(*r) {+ return Err(format!("step `{id}` ({}) needs `{r}`", s.op));+ }+ }+ if s.op != "comfy" {+ if let Some(k) = s.inputs.keys().find(|k| !required.contains(&k.as_str()) && !optional.contains(&k.as_str()) && !k.starts_with("x_")) {+ return Err(format!("step `{id}` ({}) doesn't take `{k}` (it takes {}; a model's own setting goes in as x_<name>)", s.op, required.iter().chain(optional.iter()).copied().collect::<Vec<_>>().join(", ")));+ }+ }+ for n in s.needs() {+ if !self.steps.contains_key(&n) {+ return Err(format!("step `{id}` points at `@{n}`, which isn't a step"));+ }+ }+ }+ for o in &self.out {+ if !self.steps.contains_key(o) {+ return Err(format!("out names `{o}`, which isn't a step"));+ }+ }+ self.order().map(|_| ())+ }++ /// Steps in an order that runs each after what it reads.+ pub fn order(&self) -> Result<Vec<String>, String> {+ let (mut done, mut out) = (std::collections::BTreeSet::new(), Vec::new());+ while out.len() < self.steps.len() {+ let ready: Vec<String> = self.steps.iter().filter(|(id, s)| !done.contains(*id) && s.needs().iter().all(|n| done.contains(n))).map(|(id, _)| id.clone()).collect();+ if ready.is_empty() {+ let left: Vec<&String> = self.steps.keys().filter(|k| !done.contains(*k)).collect();+ return Err(format!("these steps read each other in a circle: {left:?}"));+ }+ for r in ready {+ done.insert(r.clone());+ out.push(r);+ }+ }+ Ok(out)+ }++ /// Each step's key: a hash of its op, model and inputs, with each reference replaced by that step's key, so a+ /// step's key changes when anything it's made from does. Cached outputs are found by it.+ pub fn keys(&self) -> Result<BTreeMap<String, String>, String> {+ let mut keys = BTreeMap::new();+ for id in self.order()? {+ let s = &self.steps[&id];+ let inputs = J::Object(s.inputs.clone());+ let resolved = substitute(&inputs, &|r| keys.get(r).map(|k: &String| format!("key:{k}")));+ let text = format!("{}\u{0}{}\u{0}{}", s.op, s.model.as_deref().unwrap_or(""), canonical(&resolved));+ keys.insert(id, format!("{:x}", Sha256::digest(text.as_bytes()))[..24].to_string());+ }+ Ok(keys)+ }+}++/// A value with every `@ref` string replaced by what `f` gives for it (or kept).+pub fn substitute(v: &J, f: &dyn Fn(&str) -> Option<String>) -> J {+ match v {+ J::String(_) => reference(v).and_then(f).map(J::String).unwrap_or_else(|| v.clone()),+ J::Array(a) => J::Array(a.iter().map(|x| substitute(x, f)).collect()),+ J::Object(o) => J::Object(o.iter().map(|(k, x)| (k.clone(), substitute(x, f))).collect()),+ _ => v.clone(),+ }+}++/// JSON with object keys sorted and whole floats written as integers, so the same inputs always hash the same.+pub fn canonical(v: &J) -> String {+ match v {+ J::Object(o) => {+ let mut ks: Vec<&String> = o.keys().collect();+ ks.sort();+ format!("{{{}}}", ks.iter().map(|k| format!("{}:{}", J::String((*k).clone()), canonical(&o[*k]))).collect::<Vec<_>>().join(","))+ }+ J::Array(a) => format!("[{}]", a.iter().map(canonical).collect::<Vec<_>>().join(",")),+ J::Number(n) => match n.as_f64() {+ Some(f) if f.fract() == 0.0 && f.abs() < 1e15 => format!("{}", f as i64),+ _ => n.to_string(),+ },+ _ => v.to_string(),+ }+}diff --git a/io/gen-core/src/http.rs b/io/gen-core/src/http.rsnew file mode 100644index 00000000..e0f9855d--- /dev/null+++ b/io/gen-core/src/http.rs@@ -0,0 +1,122 @@+//! HTTP through curl (raea's io crates link no HTTP client). The URL, headers and body go to curl's stdin as its+//! config, so a key never shows in the process list.++use std::io::Write;+use std::path::Path;++use serde_json::Value as J;++/// What came back: the status, the content type and the body (empty when it went to a file).+pub struct Reply {+ pub code: u16,+ pub mime: String,+ pub body: Vec<u8>,+}++impl Reply {+ pub fn ok(&self) -> bool {+ (200..300).contains(&self.code)+ }++ pub fn json(&self) -> Result<J, String> {+ serde_json::from_slice(&self.body).map_err(|e| format!("not JSON ({e}): {}", self.text(200)))+ }++ pub fn text(&self, n: usize) -> String {+ String::from_utf8_lossy(&self.body).chars().take(n).collect()+ }+}++/// What to send: a JSON body, a file's bytes (PUT uploads), or nothing.+pub enum Body<'a> {+ None,+ Json(&'a J),+ File(&'a Path),+ /// form fields and files, as curl's -F takes them (ComfyUI's /upload/image)+ Form(&'a [(String, String)]),+}++fn q(s: &str) -> String {+ format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\""))+}++/// One request. `out` takes the body when given (downloads); otherwise it comes back in the reply.+pub fn call(method: &str, url: &str, headers: &[String], body: Body, out: Option<&Path>, secs: u32) -> Result<Reply, String> {+ raea_io_home::offline(&format!("raea gen's request to {}", redact(url)))?;+ let mut config = format!("url = {}\nrequest = {}\nheader = \"User-Agent: raea-gen\"\nmax-time = {secs}\nlocation\n", q(url), q(method));+ for h in headers {+ config += &format!("header = {}\n", q(h));+ }+ match body {+ Body::None => {}+ Body::Json(j) => config += &format!("header = \"Content-Type: application/json\"\ndata-binary = {}\n", q(&j.to_string())),+ Body::File(p) => config += &format!("upload-file = {}\n", q(&p.display().to_string())),+ Body::Form(fields) => {+ for (k, v) in fields {+ config += &format!("form = {}\n", q(&format!("{k}={v}")));+ }+ }+ }+ let tmp;+ let dest = match out {+ Some(p) => p,+ None => {+ // one name per call: two requests at once in one process never share a file+ static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);+ let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed);+ tmp = std::env::temp_dir().join(format!("raea-gen-{}-{n}", std::process::id()));+ &tmp+ }+ };+ let mut child = std::process::Command::new("curl")+ .args(["-sS", "-K", "-", "-o"])+ .arg(dest)+ .args(["-w", "%{http_code} %{content_type}"])+ .stdin(std::process::Stdio::piped())+ .stdout(std::process::Stdio::piped())+ .stderr(std::process::Stdio::piped())+ .spawn()+ .map_err(|e| format!("curl: {e}"))?;+ child.stdin.take().ok_or("curl: no stdin")?.write_all(config.as_bytes()).map_err(|e| format!("curl: {e}"))?;+ let o = child.wait_with_output().map_err(|e| format!("curl: {e}"))?;+ if !o.status.success() {+ let _ = out.is_none().then(|| std::fs::remove_file(dest));+ return Err(format!("{method} {}: {}", redact(url), String::from_utf8_lossy(&o.stderr).trim()));+ }+ let w = String::from_utf8_lossy(&o.stdout).to_string();+ let (code, mime) = w.split_once(' ').unwrap_or((&w, ""));+ let body = if out.is_none() {+ let b = std::fs::read(dest).unwrap_or_default();+ let _ = std::fs::remove_file(dest);+ b+ } else {+ Vec::new()+ };+ Ok(Reply { code: code.parse().unwrap_or(0), mime: mime.to_string(), body })+}++/// A URL as an error may show it: no query (signed links carry their signature there).+/// The Authorization header for a hosted service's key, read with crate::setting: `Authorization: SCHEME KEY`,+/// or `missing` (where to get one) when it isn't set.+pub fn key_header(name: &str, scheme: &str, missing: &str) -> Result<String, String> {+ Ok(format!("Authorization: {scheme} {}", crate::setting(name).ok_or(missing)?))+}++pub fn redact(url: &str) -> &str {+ url.split('?').next().unwrap_or(url)+}++/// Text for an error: data URIs cut to their head, the whole kept under 600 characters.+pub fn clip(s: &str) -> String {+ let mut out = String::new();+ let mut rest = s;+ while let Some(i) = rest.find("data:") {+ out += &rest[..i];+ let tail = &rest[i..];+ let end = tail.find(|c: char| c == '"' || c == ' ' || c == '\'').unwrap_or(tail.len());+ out += &format!("{}…", &tail[..end.min(40)]);+ rest = &tail[end..];+ }+ out += rest;+ out.chars().take(600).collect()+}diff --git a/io/gen-core/src/lib.rs b/io/gen-core/src/lib.rsnew file mode 100644index 00000000..97963965--- /dev/null+++ b/io/gen-core/src/lib.rs@@ -0,0 +1,19 @@+//! Generation flows' ground. A flow (flow.rs) names generation steps by what they make (image.generate,+//! video.generate, audio.sfx, mesh.generate, …), its ops in one table (types.rs writes it as raea/gen's TypeScript);+//! the hosted backends a step runs on are here too: made.app (one key for 118 image, video and audio models at the+//! provider's price), fal, Replicate, OpenRouter, Modal endpoints and Fish Audio's speech. ComfyUI is raea-io-gen-comfy; routing and running+//! are raea-io-gen.++pub mod direct;+pub mod fal;+pub mod fish;+pub mod flow;+pub mod http;+pub mod made;+pub mod modal;+pub mod openrouter;+pub mod replicate;+pub mod types;++/// A setting: the environment, then raea's settings file (raea_io_home::setting).+pub use raea_io_home::setting;diff --git a/io/gen-core/src/made.rs b/io/gen-core/src/made.rsnew file mode 100644index 00000000..cdfc9200--- /dev/null+++ b/io/gen-core/src/made.rs@@ -0,0 +1,199 @@+//! made.app (www.made.app/api): one key for 118 image, video and audio models (fal's, ElevenLabs', Kling's, Veo's and+//! made's own), priced at the provider's cost: every job and quote says `markupPercent: 0`. A request is quoted first+//! (POST /v1/cost, free), sent (POST /v1/generations, 202 with a job, debited on acceptance) and polled until it+//! succeeds; a failed or canceled job is refunded. Reference media go up through /v1/media (reserve, PUT, confirm) or+//! are an https URL or an earlier `job_…` id, which made reads as that job's output.+//!+//! The key is MADE_API_KEY (the environment, then ~/.raea/env).++use std::path::{Path, PathBuf};+use std::time::{Duration, Instant};++use serde_json::{Value as J, json};++use crate::http::{Body, call, key_header, redact};+use crate::setting;++pub const BASE: &str = "https://www.made.app/api";++/// Fields every generation takes; a model's catalog row adds its own (`allowedParams`, `inputMap`).+const COMMON: [&str; 13] = ["model", "prompt", "aspect_ratio", "duration", "resolution", "audio", "medias", "count", "request_id", "max_cost_cents", "quality", "image_size", "characters"];++pub struct Made {+ headers: Vec<String>,+ base: String,+}++impl Made {+ pub fn from_settings() -> Result<Made, String> {+ let key = key_header("MADE_API_KEY", "Bearer", "made.app needs a key: put MADE_API_KEY=made_sk_… in ~/.raea/env (www.made.app/account/api-keys)")?;+ Ok(Made { headers: vec![key], base: setting("MADE_API").unwrap_or_else(|| BASE.into()) })+ }++ fn get(&self, path: &str) -> Result<J, String> {+ let r = call("GET", &format!("{}{path}", self.base), &self.headers, Body::None, None, 60)?;+ answer(path, &r)+ }++ fn post(&self, path: &str, body: &J) -> Result<J, String> {+ let r = call("POST", &format!("{}{path}", self.base), &self.headers, Body::Json(body), None, 120)?;+ answer(path, &r)+ }++ /// The catalog, each model with its prices, roles and parameters; kept a day in ~/.cache/raea-gen/made-models.json.+ pub fn models(&self) -> Result<Vec<J>, String> {+ let cache = cache_dir().join("made-models.json");+ let fresh = std::fs::metadata(&cache).and_then(|m| m.modified()).ok().and_then(|t| t.elapsed().ok()).is_some_and(|age| age < Duration::from_secs(24 * 3600));+ if fresh {+ if let Some(m) = std::fs::read(&cache).ok().and_then(|b| serde_json::from_slice::<J>(&b).ok()) {+ return Ok(m["models"].as_array().cloned().unwrap_or_default());+ }+ }+ let v = self.get("/v1/models")?;+ let _ = std::fs::create_dir_all(cache_dir());+ let _ = std::fs::write(&cache, v.to_string());+ Ok(v["models"].as_array().cloned().unwrap_or_default())+ }++ pub fn model(&self, id: &str) -> Result<J, String> {+ self.models()?.into_iter().find(|m| m["id"] == id).ok_or_else(|| format!("made.app has no model `{id}` (raea gen models lists them)"))+ }++ /// What a request would cost, in cents, without running it: (what made charges, what the provider charges).+ /// made rounds a job up to a whole credit (10¢), so the two differ on small jobs (direct.rs).+ pub fn cost(&self, body: &J) -> Result<(u64, u64), String> {+ let v = self.post("/v1/cost", body)?;+ let c = v["cost"]["customerCostCents"].as_u64().ok_or_else(|| format!("/v1/cost: no customerCostCents in {v}"))?;+ Ok((c, v["cost"]["providerCostCents"].as_u64().unwrap_or(c)))+ }++ pub fn balance_cents(&self) -> Result<u64, String> {+ let v = self.get("/v1/balance")?;+ Ok((v["credits"].as_f64().unwrap_or(0.0) * 10.0).round() as u64)+ }++ /// A job, created: 202 and the job (its id, status, costCents).+ pub fn create(&self, body: &J) -> Result<J, String> {+ self.post("/v1/generations", body)+ }++ pub fn job(&self, id: &str) -> Result<J, String> {+ self.get(&format!("/v1/generations/{id}"))+ }++ pub fn cancel(&self, id: &str) -> Result<J, String> {+ self.post(&format!("/v1/generations/{id}/cancel"), &json!({}))+ }++ /// The job once it's done: succeeded, or an error saying how it ended. A job whose status and progress stay the same+ /// for `stall` is given up on (and canceled, which refunds it).+ pub fn wait(&self, id: &str, stall: Duration) -> Result<J, String> {+ let (mut seen, mut since, mut nap) = (String::new(), Instant::now(), 1u64);+ loop {+ let j = self.job(id)?;+ match j["status"].as_str().unwrap_or("") {+ "succeeded" => return Ok(j),+ s @ ("failed" | "canceled" | "cancelled") => return Err(format!("made.app job {id} {s}: {}", j["error"].as_str().unwrap_or("no reason given"))),+ _ => {}+ }+ let now = format!("{}:{}", j["status"], j["progress"]);+ if now != seen {+ (seen, since) = (now, Instant::now());+ } else if since.elapsed() > stall {+ let _ = self.cancel(id);+ return Err(format!("made.app job {id} sat at {seen} for {}s, canceled (refunded)", stall.as_secs()));+ }+ std::thread::sleep(Duration::from_secs(nap));+ nap = (nap + 1).min(8);+ }+ }++ /// A local file as made media (`media_…`): reserved, PUT to the signed URL with the headers it names, confirmed.+ pub fn upload(&self, file: &Path) -> Result<String, String> {+ let mime = mime_of(file);+ let v = self.post("/v1/media", &json!({"content_type": mime}))?;+ let id = v["media"]["id"].as_str().ok_or_else(|| format!("/v1/media: no id in {v}"))?.to_string();+ let url = v["upload"]["url"].as_str().ok_or("/v1/media: no upload url")?;+ let headers: Vec<String> = v["upload"]["headers"].as_object().map(|h| h.iter().map(|(k, v)| format!("{k}: {}", v.as_str().unwrap_or(""))).collect()).unwrap_or_default();+ let r = call("PUT", url, &headers, Body::File(file), None, 600)?;+ if !r.ok() {+ return Err(format!("upload of {} answered {}: {}", file.display(), r.code, r.text(200)));+ }+ self.post(&format!("/v1/media/{id}/confirm"), &json!({}))?;+ Ok(id)+ }+}++fn answer(path: &str, r: &crate::http::Reply) -> Result<J, String> {+ let v = r.json().map_err(|e| format!("made.app {path} answered {}: {e}", r.code))?;+ if !r.ok() {+ let why = match r.code {+ 401 => "the key was refused (MADE_API_KEY)",+ 402 => "not enough credits (www.made.app/pricing)",+ 429 => "too many refunded failures in a row; wait before sending more",+ _ => "",+ };+ return Err(format!("made.app {path} answered {}{}: {}", r.code, if why.is_empty() { String::new() } else { format!(", {why}") }, v["error"].as_str().map(str::to_string).unwrap_or(v.to_string())));+ }+ Ok(v)+}++/// A request body with only the fields this model takes: the common ones, its `allowedParams` and its `inputMap`'s.+/// made refuses an undeclared field rather than ignoring it, so a step's extra settings are dropped here, by name.+pub fn fit(model: &J, body: J) -> (J, Vec<String>) {+ let allowed: Vec<&str> = model["allowedParams"].as_array().map(|a| a.iter().filter_map(|v| v.as_str()).collect()).unwrap_or_default();+ let mapped: Vec<&str> = model["inputMap"].as_object().map(|m| m.keys().map(String::as_str).collect()).unwrap_or_default();+ let mut out = serde_json::Map::new();+ let mut dropped = Vec::new();+ for (k, v) in body.as_object().cloned().unwrap_or_default() {+ if COMMON.contains(&k.as_str()) || allowed.contains(&k.as_str()) || mapped.contains(&k.as_str()) {+ out.insert(k, v);+ } else {+ dropped.push(k);+ }+ }+ (J::Object(out), dropped)+}++/// A finished job's outputs: each asset's URL and type (image, video, audio).+pub fn outputs(job: &J) -> Vec<(String, String)> {+ job["result"]["assets"].as_array().map(|a| a.iter().filter_map(|x| Some((x["url"].as_str()?.to_string(), x["type"].as_str().unwrap_or("").to_string()))).collect()).unwrap_or_default()+}++/// A signed asset URL downloaded to `out`; the file's extension from the URL's path.+pub fn download(url: &str, out_stem: &Path) -> Result<PathBuf, String> {+ let ext = Path::new(redact(url)).extension().and_then(|e| e.to_str()).unwrap_or("bin").to_ascii_lowercase();+ let out = out_stem.with_extension(&ext);+ let r = call("GET", url, &[], Body::None, Some(&out), 900)?;+ if !r.ok() {+ let _ = std::fs::remove_file(&out);+ return Err(format!("download of {} answered {}", redact(url), r.code));+ }+ Ok(out)+}++pub fn mime_of(file: &Path) -> &'static str {+ match file.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).as_deref() {+ Some("png") => "image/png",+ Some("jpg" | "jpeg") => "image/jpeg",+ Some("webp") => "image/webp",+ Some("gif") => "image/gif",+ Some("mp4" | "m4v") => "video/mp4",+ Some("mov") => "video/quicktime",+ Some("webm") => "video/webm",+ Some("wav") => "audio/wav",+ Some("mp3") => "audio/mpeg",+ Some("m4a") => "audio/mp4",+ _ => "application/octet-stream",+ }+}++/// A file of raea gen's cache (cache_dir) by its name.+pub fn cached(name: &str) -> PathBuf {+ cache_dir().join(name)+}++/// Where raea gen keeps fetched catalogs and generated files: $RAEA_GEN_CACHE, else ~/.cache/raea-gen.+pub fn cache_dir() -> PathBuf {+ raea_io_home::env_path("RAEA_GEN_CACHE", ".cache/raea-gen")+}diff --git a/io/gen-core/src/modal.rs b/io/gen-core/src/modal.rsnew file mode 100644index 00000000..fe03e601--- /dev/null+++ b/io/gen-core/src/modal.rs@@ -0,0 +1,55 @@+//! Modal: GPU code of your own, two ways. A ComfyUI server deployed on Modal (tools/comfy/modal.py: `modal deploy`+//! prints its URL) is a ComfyUI server like any other: RAEA_COMFY_URL points at it and comfy steps run there. And any+//! web endpoint you deploy that speaks raea's step contract is a backend by `modal:<url>` (or `modal:<name>`, with+//! RAEA_MODAL_<NAME> holding the URL): it's POSTed {op, inputs} (media inline as data URIs) and answers+//! {files: [{url} | {data, ext}], cents?}. Modal's proxy auth, when the endpoint asks for it, is MODAL_KEY and+//! MODAL_SECRET (sent as Modal-Key and Modal-Secret).++use std::path::{Path, PathBuf};++use serde_json::{Value as J, json};++use crate::http::{Body, call};+use crate::setting;++/// The endpoint a step names: a URL, or a name whose URL is RAEA_MODAL_<NAME>.+pub fn endpoint(name: &str) -> Result<String, String> {+ if name.starts_with("https://") {+ return Ok(name.to_string());+ }+ let var = format!("RAEA_MODAL_{}", name.to_ascii_uppercase().replace(['-', '.'], "_"));+ setting(&var).ok_or(format!("modal:{name} has no URL: deploy it and put {var}=https://… in ~/.raea/env"))+}++/// One step on a Modal endpoint: its files written beside `stem`, and what it says it cost.+pub fn run(name: &str, op: &str, inputs: &J, stem: &Path) -> Result<(Vec<PathBuf>, u64), String> {+ let url = endpoint(name)?;+ let mut h = Vec::new();+ if let (Some(k), Some(s)) = (setting("MODAL_KEY"), setting("MODAL_SECRET")) {+ h.push(format!("Modal-Key: {k}"));+ h.push(format!("Modal-Secret: {s}"));+ }+ // a cold container may take minutes to start: the request waits for it+ let r = call("POST", &url, &h, Body::Json(&json!({"op": op, "inputs": inputs})), None, 1800)?;+ let v = r.json().map_err(|e| format!("modal:{name} answered {}: {e}", r.code))?;+ if !r.ok() {+ return Err(format!("modal:{name} answered {}: {}", r.code, v["error"].as_str().map(str::to_string).unwrap_or(v.to_string())));+ }+ let mut files = Vec::new();+ for (k, f) in v["files"].as_array().into_iter().flatten().enumerate() {+ let s = if k == 0 { stem.to_path_buf() } else { PathBuf::from(format!("{}-{k}", stem.display())) };+ if let Some(u) = f["url"].as_str() {+ files.push(crate::made::download(u, &s)?);+ } else if let Some(d) = f["data"].as_str() {+ let ext = f["ext"].as_str().unwrap_or("bin");+ files.push(crate::openrouter::save(&format!("data:application/octet-stream;base64,{d}"), &s).and_then(|p| {+ let to = p.with_extension(ext);+ std::fs::rename(&p, &to).map(|_| to).map_err(|e| e.to_string())+ })?);+ }+ }+ if files.is_empty() {+ return Err(format!("modal:{name} answered with no files: {}", v.to_string().chars().take(300).collect::<String>()));+ }+ Ok((files, v["cents"].as_u64().unwrap_or(0)))+}diff --git a/io/gen-core/src/openrouter.rs b/io/gen-core/src/openrouter.rsnew file mode 100644index 00000000..2615706d--- /dev/null+++ b/io/gen-core/src/openrouter.rs@@ -0,0 +1,81 @@+//! OpenRouter (openrouter.ai/api/v1): its image-output models (`openrouter:google/gemini-3.1-flash-image`,+//! `openrouter:black-forest-labs/flux-3-image`, …) for image.generate and image.edit, and any of its text models for+//! text.generate (the prompt-writing LLM nodes ComfyUI workflows use). One chat completion: the prompt and any images+//! as the founder's message, `modalities` asking for images back, which arrive as data URIs. The key is+//! OPENROUTER_API_KEY.++use std::path::{Path, PathBuf};++use serde_json::{Value as J, json};++use crate::http::{Body, call, key_header};++pub struct OpenRouter {+ headers: Vec<String>,+}++impl OpenRouter {+ pub fn from_settings() -> Result<OpenRouter, String> {+ let key = key_header("OPENROUTER_API_KEY", "Bearer", "OpenRouter needs OPENROUTER_API_KEY in ~/.raea/env (openrouter.ai/keys)")?;+ Ok(OpenRouter { headers: vec![key, "X-Title: raea".to_string()] })+ }++ fn post(&self, body: &J) -> Result<J, String> {+ let r = call("POST", "https://openrouter.ai/api/v1/chat/completions", &self.headers, Body::Json(body), None, 600)?;+ let v = r.json().map_err(|e| format!("OpenRouter: {e}"))?;+ if !r.ok() || v.get("error").is_some() {+ return Err(format!("OpenRouter answered {}: {}", r.code, v["error"]["message"].as_str().map(str::to_string).unwrap_or(v.to_string())));+ }+ Ok(v)+ }++ /// One completion: the text it wrote and the images it made (data URIs), with what OpenRouter billed in cents.+ pub fn complete(&self, model: &str, prompt: &str, system: Option<&str>, images: &[String], want_images: bool, extra: &serde_json::Map<String, J>) -> Result<(String, Vec<String>, f64), String> {+ let mut content = vec![json!({"type": "text", "text": prompt})];+ content.extend(images.iter().map(|u| json!({"type": "image_url", "image_url": {"url": u}})));+ let mut messages = Vec::new();+ if let Some(s) = system {+ messages.push(json!({"role": "system", "content": s}));+ }+ messages.push(json!({"role": "user", "content": content}));+ let mut body = json!({"model": model, "messages": messages, "usage": {"include": true}});+ if want_images {+ body["modalities"] = json!(["image", "text"]);+ }+ for (k, v) in extra {+ body[k.as_str()] = v.clone();+ }+ let v = self.post(&body)?;+ let msg = &v["choices"][0]["message"];+ let text = msg["content"].as_str().unwrap_or("").to_string();+ let imgs: Vec<String> = msg["images"].as_array().into_iter().flatten().filter_map(|i| i["image_url"]["url"].as_str().map(str::to_string)).collect();+ Ok((text, imgs, v["usage"]["cost"].as_f64().unwrap_or(0.0) * 100.0))+ }+}++/// A data URI (or an https URL) written to `stem` with the extension its type says.+pub fn save(uri: &str, stem: &Path) -> Result<PathBuf, String> {+ if uri.starts_with("http") {+ return crate::made::download(uri, stem);+ }+ let (head, data) = uri.strip_prefix("data:").and_then(|r| r.split_once(',')).ok_or("not a data URI")?;+ let ext = match head.split(';').next().unwrap_or("") { "image/jpeg" => "jpg", "image/webp" => "webp", "image/svg+xml" => "svg", _ => "png" };+ let out = stem.with_extension(ext);+ std::fs::write(&out, unbase64(data)?).map_err(|e| format!("{}: {e}", out.display()))?;+ Ok(out)+}++fn unbase64(s: &str) -> Result<Vec<u8>, String> {+ let val = |c: u8| -> Option<u32> {+ Some(match c { b'A'..=b'Z' => c - b'A', b'a'..=b'z' => c - b'a' + 26, b'0'..=b'9' => c - b'0' + 52, b'+' | b'-' => 62, b'/' | b'_' => 63, _ => return None } as u32)+ };+ let bytes: Vec<u32> = s.bytes().filter(|c| !c.is_ascii_whitespace() && *c != b'=').map(|c| val(c).ok_or("bad base64")).collect::<Result<_, _>>()?;+ let mut out = Vec::with_capacity(bytes.len() * 3 / 4);+ for ch in bytes.chunks(4) {+ let n = ch.iter().enumerate().fold(0u32, |n, (i, v)| n | v << (18 - 6 * i));+ out.push((n >> 16) as u8);+ if ch.len() > 2 { out.push((n >> 8) as u8); }+ if ch.len() > 3 { out.push(n as u8); }+ }+ Ok(out)+}diff --git a/io/gen-core/src/replicate.rs b/io/gen-core/src/replicate.rsnew file mode 100644index 00000000..5ec04967--- /dev/null+++ b/io/gen-core/src/replicate.rs@@ -0,0 +1,75 @@+//! Replicate (api.replicate.com/v1): any model by `replicate:owner/name` (its latest version) or+//! `replicate:owner/name:version`. A prediction is created and its `urls.get` polled until it succeeds; its output+//! is a URL or a list of them. Media go as data URIs. ComfyUI on Replicate is the same call on+//! fofr/any-comfyui-workflow with the API-format graph as `workflow_json`. The key is REPLICATE_API_TOKEN;+//! RAEA_REPLICATE_API moves the base (a test's stand-in, a proxy).++use std::time::{Duration, Instant};++use serde_json::{Value as J, json};++use crate::http::{Body, call};+use crate::setting;++pub const COMFY: &str = "fofr/any-comfyui-workflow";++pub struct Replicate {+ token: String,+ base: String,+}++impl Replicate {+ pub fn from_settings() -> Result<Replicate, String> {+ let token = setting("REPLICATE_API_TOKEN").ok_or("Replicate needs REPLICATE_API_TOKEN in ~/.raea/env (replicate.com/account/api-tokens)")?;+ let base = setting("RAEA_REPLICATE_API").unwrap_or_else(|| "https://api.replicate.com/v1".into()).trim_end_matches('/').to_string();+ Ok(Replicate { token, base })+ }++ fn json(&self, method: &str, url: &str, body: Option<&J>) -> Result<J, String> {+ let h = vec![format!("Authorization: Bearer {}", self.token)];+ let r = call(method, url, &h, body.map(Body::Json).unwrap_or(Body::None), None, 120)?;+ let v = r.json().map_err(|e| format!("Replicate: {e}"))?;+ if !r.ok() {+ return Err(format!("Replicate {} answered {}: {}", crate::http::redact(url), r.code, v["detail"].as_str().map(str::to_string).unwrap_or(v.to_string())));+ }+ Ok(v)+ }++ /// A prediction run to the end: its output.+ pub fn run(&self, model: &str, input: &J, stall: Duration) -> Result<J, String> {+ let (url, body) = match model.split_once(':') {+ Some((_, version)) => (format!("{}/predictions", self.base), json!({"version": version, "input": input})),+ None => (format!("{}/models/{model}/predictions", self.base), json!({"input": input})),+ };+ let mut p = self.json("POST", &url, Some(&body))?;+ let get = p["urls"]["get"].as_str().ok_or_else(|| format!("Replicate: no urls.get in {p}"))?.to_string();+ let (mut seen, mut since, mut nap) = (String::new(), Instant::now(), 1);+ loop {+ match p["status"].as_str() {+ Some("succeeded") => return Ok(p["output"].clone()),+ Some(s @ ("failed" | "canceled")) => return Err(format!("Replicate {model} {s}: {}", p["error"].as_str().unwrap_or(""))),+ _ => {}+ }+ let now = format!("{}:{}", p["status"], p["logs"].as_str().map(|l| l.len()).unwrap_or(0));+ if now != seen {+ (seen, since) = (now, Instant::now());+ } else if since.elapsed() > stall {+ let _ = self.json("POST", &format!("{get}/cancel"), None);+ return Err(format!("Replicate {model} sat at {} for {}s, canceled", p["status"], stall.as_secs()));+ }+ std::thread::sleep(Duration::from_secs(nap));+ nap = (nap + 1).min(6);+ p = self.json("GET", &get, None)?;+ }+ }+}++/// A prediction's output as file URLs: a string, a list, or an object of them.+pub fn urls(out: &J) -> Vec<String> {+ match out {+ J::String(s) if s.starts_with("http") || s.starts_with("data:") => vec![s.clone()],+ J::Array(a) => a.iter().flat_map(urls).collect(),+ J::Object(o) => o.values().flat_map(urls).collect(),+ _ => vec![],+ }+}diff --git a/io/gen-core/src/types.rs b/io/gen-core/src/types.rsnew file mode 100644index 00000000..915dbfcc--- /dev/null+++ b/io/gen-core/src/types.rs@@ -0,0 +1,50 @@+//! The flow ops as TypeScript (`raea gen types`): sdk/gen/src/ops.gen.ts is written from OPS, so what raea/gen lets an+//! agent write is what the runner checks.++use crate::flow::OPS;++/// An input's TypeScript type, by its name.+fn ty(name: &str) -> &'static str {+ match name {+ "prompt" | "negative" | "text" | "system" | "aspect_ratio" | "resolution" | "sampler" | "scheduler" | "voice" | "path" | "url" | "output" => "string",+ "fit" => "\"stretch\" | \"cover\" | \"contain\"",+ "direction" => "\"right\" | \"down\" | \"left\" | \"up\"",+ "x" | "y" | "megapixels" => "number",+ "width" | "height" | "seed" | "steps" | "cfg" | "seconds" | "fps" | "factor" | "strength" | "speed" => "number",+ "audio" | "texture" => "boolean",+ "image" | "start_image" | "end_image" | "video" | "mask" => "Ref",+ "refs" | "images" => "Ref[]",+ "weights" => "string | string[]",+ "loras" => "{ name: string; strength?: number }[]",+ "nodes" => "Record<string, { class_type: string; inputs: Record<string, unknown> }>",+ "bind" => "Record<string, Ref>",+ "slots" => "number[]",+ _ => "unknown",+ }+}++/// A name as a TypeScript type name: image.generate → ImageGenerate.+fn pascal(op: &str) -> String {+ op.split(['.', '_']).map(|w| w[..1].to_uppercase() + &w[1..]).collect()+}++pub fn typescript() -> String {+ let mut out = String::from("// Written by `raea gen types` from io/gen/src/flow.rs OPS; don't edit by hand.\n\n/** Another step's output: `@step` (or `@step.N`). */\nexport type Ref = `@${string}`;\n/** A model's own setting, passed through as it is. */\nexport type Extra = { [setting: `x_${string}`]: unknown };\n\n");+ let mut ops = Vec::new();+ for (name, _, required, optional) in OPS {+ let t = pascal(name);+ out += &format!("export interface {t} extends Extra {{\n");+ for r in required.iter() {+ out += &format!(" {r}: {};\n", ty(r));+ }+ for o in optional.iter() {+ out += &format!(" {o}?: {};\n", ty(o));+ }+ out += "}\n\n";+ ops.push(format!(" \"{name}\": {t};"));+ }+ out += &format!("/** Every op and its inputs. */\nexport interface Ops {{\n{}\n}}\n\n", ops.join("\n"));+ let names: Vec<String> = OPS.iter().map(|o| format!("\"{}\"", o.0)).collect();+ out += &format!("/** The ops, for the builders. */\nexport const OP_NAMES = [{}] as const;\n", names.join(", "));+ out+}diff --git a/io/gen/Cargo.toml b/io/gen/Cargo.tomlnew file mode 100644index 00000000..3cf77498--- /dev/null+++ b/io/gen/Cargo.toml@@ -0,0 +1,15 @@+[package]+name = "raea-io-gen"+version = "0.1.0"+edition = "2024"+license = "FSL-1.1-ALv2"+publish = false+description = "Generation flows: made.app's models at provider cost, ComfyUI workflows read and written, and the runner that routes each step to made, fal, Replicate, OpenRouter, Modal, a ComfyUI server or a local model"++[dependencies]+raea-io-gen-comfy = { path = "../gen-comfy" }+raea-io-gen-core = { path = "../gen-core" }+raea-io-home = { path = "../home" }+serde_json = "1"+# image.crop, image.scale, image.stitch, run here (native.rs)+image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp"] }diff --git a/io/gen/src/bin/raea-gen.rs b/io/gen/src/bin/raea-gen.rsnew file mode 100644index 00000000..a6bc7e33--- /dev/null+++ b/io/gen/src/bin/raea-gen.rs@@ -0,0 +1,11 @@+//! `raea-gen`: `raea gen` on its own (the same verbs, without raea's local models).+fn main() {+ let args: Vec<String> = std::env::args().skip(1).collect();+ match raea_io_gen::cli::command(&args, None) {+ Ok(out) => println!("{out}"),+ Err(e) => {+ println!("REFUSED {e}");+ std::process::exit(1);+ }+ }+}diff --git a/io/gen/src/cli.rs b/io/gen/src/cli.rsnew file mode 100644index 00000000..9027280e--- /dev/null+++ b/io/gen/src/cli.rs@@ -0,0 +1,291 @@+//! `raea gen …`: the verbs over flows, made's catalog and ComfyUI workflows. Each returns what it prints.++use std::path::{Path, PathBuf};++use serde_json::{Value as J, json};++use crate::comfy;+use crate::flow::{Flow, Step};+use crate::made::Made;+use crate::run::{Local, Run};++pub const USAGE: &str = "raea gen models [--kind image|video|audio] [--query WORDS] | balance | types [-o FILE] | flow FLOW.ts [-o FLOW.json]+ raea gen image|video|music|sfx|speech|mesh|text \"PROMPT\" [--model M] [--image FILE]... [--seconds S] [--aspect W:H] [-o DIR] [--max-cents N] [--plan]+ raea gen plan FLOW.json|FLOW.ts [--exact] | raea gen run FLOW.json|FLOW.ts [-o DIR] [--max-cents N] [--exact] [--comfy-on-replicate] [--no-local]+ raea gen comfy import WORKFLOW.json [-o FLOW.json] | comfy export FLOW.json|FLOW.ts [-o WORKFLOW.json] | comfy needs WORKFLOW.json [-o NEEDS.json]+ raea gen comfy run WORKFLOW.json [-o DIR] (any workflow as it is, on the ComfyUI server: its input files uploaded, every output fetched)+ raea gen comfy view WORKFLOW.json [-o FILE] | comfy set WORKFLOW.json CHANGES.json (nodes, settings by name, links, groups; edits written back)+ raea gen comfy schema [URL] | comfy coverage DIR | comfy up";++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)+}++/// A JSON file's value, or an error naming the file.+fn read_json(p: impl AsRef<Path>) -> Result<J, String> {+ let p = p.as_ref();+ let b = std::fs::read(p).map_err(|e| format!("{}: {e}", p.display()))?;+ serde_json::from_slice(&b).map_err(|e| format!("{}: not JSON ({e})", p.display()))+}++/// A flow file: JSON as it is, or TypeScript (raea/gen's `flow()` as the default export) run with bun under the SDK's+/// import names.+fn read_flow(p: &str) -> Result<Flow, String> {+ if ![".ts", ".mts", ".tsx"].iter().any(|e| p.ends_with(e)) {+ return Flow::parse(&read_json(p)?);+ }+ let file = std::path::absolute(p).map_err(|e| format!("{p}: {e}"))?;+ let sdk = raea_io_home::home().join("sdk");+ let entry = std::env::temp_dir().join(format!("raea-gen-flow-{}.ts", std::process::id()));+ let js = "const m = await import(process.argv[2]);\nconst f = typeof m.default === \"function\" ? await m.default() : await m.default;\nconsole.log(JSON.stringify(f));\n";+ std::fs::write(&entry, js).map_err(|e| format!("{}: {e}", entry.display()))?;+ let out = std::process::Command::new("bun")+ .arg("--tsconfig-override")+ .arg(sdk.join(raea_io_home::sdk::LIST))+ .arg(&entry)+ .arg(&file)+ .output();+ let _ = std::fs::remove_file(&entry);+ let out = out.map_err(|e| format!("{p}: a TypeScript flow runs with bun, which didn't start ({e})"))?;+ // bun reports an override that isn't the file's own folder as an internal error; it isn't one+ let err: String = String::from_utf8_lossy(&out.stderr).lines().filter(|l| !l.contains("directory mismatch")).collect::<Vec<_>>().join("\n");+ if !out.status.success() {+ return Err(format!("{p}: {}", err.trim()));+ }+ let v: J = serde_json::from_slice(&out.stdout).map_err(|e| format!("{p}: its default export isn't a flow ({e})"))?;+ Flow::parse(&v)+}++fn write_or_print(v: &J, out: Option<&str>) -> Result<String, String> {+ let text = serde_json::to_string_pretty(v).unwrap_or_default();+ match out {+ Some(o) => std::fs::write(o, &text).map(|_| format!("wrote {o}")).map_err(|e| format!("{o}: {e}")),+ None => Ok(text),+ }+}++fn runner<'a>(args: &[String], base: &Path, local: Option<&'a dyn Local>) -> Run<'a> {+ let dir = flag(args, "-o").map(PathBuf::from).unwrap_or_else(|| base.join("gen"));+ let mut r = Run::new(dir, base.to_path_buf());+ if let Some(c) = flag(args, "--max-cents").and_then(|c| c.parse().ok()) {+ r.max_cents = c;+ }+ r.policy.exact = args.iter().any(|a| a == "--exact");+ r.policy.comfy_on_replicate = args.iter().any(|a| a == "--comfy-on-replicate") || crate::setting("RAEA_COMFY_ON") .as_deref() == Some("replicate");+ if let Some(l) = local.filter(|_| !args.iter().any(|a| a == "--no-local")) {+ r.policy.local = l.names();+ r.local = Some(l);+ }+ r+}++pub fn command(args: &[String], local: Option<&dyn Local>) -> Result<String, String> {+ let verb = args.first().map(String::as_str).unwrap_or("");+ match verb {+ "models" => {+ let kind = flag(args, "--kind");+ let q = flag(args, "--query").map(str::to_ascii_lowercase);+ let mut out = String::new();+ for m in Made::from_settings()?.models()? {+ if kind.is_some_and(|k| m["kind"] != k) || q.as_ref().is_some_and(|q| !m.to_string().to_ascii_lowercase().contains(q)) {+ continue;+ }+ out += &format!("{:<34} {:<6} {}\n", m["id"].as_str().unwrap_or(""), m["kind"].as_str().unwrap_or(""), m["pricing"]["display"].as_str().unwrap_or(""));+ }+ Ok(out.trim_end().to_string())+ }+ "balance" => Ok(format!("{:.1} credits (${:.2}) on made.app", Made::from_settings()?.balance_cents()? as f64 / 10.0, Made::from_settings()?.balance_cents()? as f64 / 100.0)),+ "plan" | "run" => {+ let path = args.get(1).ok_or(USAGE)?;+ let flow = read_flow(path)?;+ let base = Path::new(path).parent().map(Path::to_path_buf).unwrap_or_default();+ let r = runner(args, &base, local);+ write_or_print(&if verb == "plan" { r.plan(&flow)? } else { r.run(&flow)? }, None)+ }+ "image" | "video" | "music" | "sfx" | "speech" | "mesh" | "text" => {+ let prompt = args.get(1).filter(|p| !p.starts_with("--")).ok_or(USAGE)?;+ let images: Vec<&str> = args.windows(2).filter(|w| w[0] == "--image").map(|w| w[1].as_str()).collect();+ let mut flow = Flow::default();+ for (k, f) in images.iter().enumerate() {+ let abs = std::fs::canonicalize(f).map_err(|e| format!("{f}: {e}"))?;+ flow.steps.insert(format!("in{k}"), Step::new("media.load", json!({"path": abs})));+ }+ let refs: Vec<J> = (0..images.len()).map(|k| json!(format!("@in{k}"))).collect();+ let (op, mut inputs) = match verb {+ "image" if refs.is_empty() => ("image.generate", json!({"prompt": prompt})),+ "image" => ("image.edit", json!({"prompt": prompt, "image": if refs.len() == 1 { refs[0].clone() } else { J::Array(refs.clone()) }})),+ "video" => ("video.generate", match refs.len() { 0 => json!({"prompt": prompt}), 1 => json!({"prompt": prompt, "start_image": refs[0]}), _ => json!({"prompt": prompt, "start_image": refs[0], "end_image": refs[1]}) }),+ "music" => ("audio.music", json!({"prompt": prompt})),+ "sfx" => ("audio.sfx", json!({"prompt": prompt})),+ "speech" => ("audio.speech", json!({"text": prompt})),+ "mesh" => ("mesh.generate", if refs.is_empty() { json!({"prompt": prompt}) } else { json!({"prompt": prompt, "image": refs[0]}) }),+ _ => ("text.generate", if refs.is_empty() { json!({"prompt": prompt}) } else { json!({"prompt": prompt, "image": refs[0]}) }),+ };+ if let Some(s) = flag(args, "--seconds").and_then(|s| s.parse::<f64>().ok()) {+ inputs["seconds"] = json!(s);+ }+ if let Some(a) = flag(args, "--aspect") {+ inputs["aspect_ratio"] = json!(a);+ }+ let mut step = Step::new(op, inputs);+ step.model = flag(args, "--model").map(|m| if m.contains(':') { m.to_string() } else { format!("made:{m}") });+ flow.steps.insert("out".into(), step);+ flow.out = vec!["out".into()];+ flow.check()?;+ let cwd = std::env::current_dir().map_err(|e| e.to_string())?;+ let r = runner(args, &cwd, local);+ write_or_print(&if args.iter().any(|a| a == "--plan") { r.plan(&flow)? } else { r.run(&flow)? }, None)+ }+ "comfy" => comfy_verb(&args[1..]),+ "flow" => write_or_print(&read_flow(args.get(1).ok_or(USAGE)?)?.to_json(), flag(args, "-o")),+ "types" => {+ let ts = crate::types::typescript();+ match flag(args, "-o") {+ Some(o) => std::fs::write(o, &ts).map(|_| format!("wrote {o}")).map_err(|e| format!("{o}: {e}")),+ None => Ok(ts),+ }+ }+ _ => Err(USAGE.to_string()),+ }+}++fn comfy_verb(args: &[String]) -> Result<String, String> {+ match args.first().map(String::as_str).unwrap_or("") {+ "import" => {+ let l = comfy::import(&read_json(args.get(1).ok_or(USAGE)?)?)?;+ l.flow.check()?;+ let kept = l.flow.steps.values().filter(|s| s.op == "comfy").count();+ eprintln!("raea gen: {} steps ({} named, {} kept as ComfyUI nodes), {} outputs", l.flow.steps.len(), l.flow.steps.len() - kept, kept, l.flow.out.len());+ write_or_print(&l.flow.to_json(), flag(args, "-o"))+ }+ "needs" => {+ let path = args.get(1).ok_or(USAGE)?;+ write_or_print(&comfy::needs::needs(&read_json(path)?, &comfy::schema::load()), flag(args, "-o"))+ }+ "export" => {+ let flow = read_flow(args.get(1).ok_or(USAGE)?)?;+ write_or_print(&comfy::export(&flow)?, flag(args, "-o"))+ }+ "schema" => {+ let mut c = comfy::server::Comfy::from_settings();+ if let Some(u) = args.get(1) {+ c.url = u.trim_end_matches('/').to_string();+ }+ Ok(format!("{} node classes from {} kept in {}", c.save_schema()?, c.url, crate::made::cached(comfy::schema::CACHE_NAME).display()))+ }+ "up" => {+ let c = comfy::server::Comfy::from_settings();+ Ok(format!("ComfyUI at {}: {}", c.url, if c.up() { "answering" } else { "not answering (raea gen comfy setup installs one; RAEA_COMFY_URL names a hosted one)" }))+ }+ "coverage" => coverage(Path::new(args.get(1).ok_or(USAGE)?)),+ "run" => run_workflow(args),+ // a workflow as a whiteboard shows it, and a board's edits written back into it (apps/app whiteboards, CF1-2)+ "view" => write_or_print(&comfy::view::view(&read_json(args.get(1).ok_or(USAGE)?)?, &comfy::schema::load())?, flag(args, "-o")),+ "set" => {+ let path = args.get(1).ok_or(USAGE)?;+ let mut w = read_json(path)?;+ let n = comfy::view::set(&mut w, &read_json(args.get(2).ok_or(USAGE)?)?, &comfy::schema::load())?;+ // written whole, then moved over the old one: a reader never sees half a workflow+ let tmp = format!("{path}.{}.tmp", std::process::id());+ std::fs::write(&tmp, serde_json::to_string_pretty(&w).map_err(|e| e.to_string())? + "\n").map_err(|e| format!("{tmp}: {e}"))?;+ std::fs::rename(&tmp, path).map_err(|e| format!("{path}: {e}"))?;+ Ok(format!("{n} changes written to {path}"))+ }+ _ => Err(USAGE.to_string()),+ }+}++/// Every workflow under a folder imported: how many read, how many steps came out named or kept as ComfyUI, which+/// node classes were kept most, and each failure's reason.+fn coverage(dir: &Path) -> Result<String, String> {+ let schema = comfy::schema::load();+ let mut files: Vec<PathBuf> = std::fs::read_dir(dir).map_err(|e| format!("{}: {e}", dir.display()))?.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|e| e == "json")).collect();+ files.sort();+ let (mut read, mut failed, mut named, mut kept, mut whole) = (0, Vec::new(), 0, 0, 0);+ let mut ops: std::collections::BTreeMap<String, usize> = Default::default();+ let mut kept_classes: std::collections::BTreeMap<String, usize> = Default::default();+ let mut unknown: std::collections::BTreeMap<String, usize> = Default::default();+ let mut why: std::collections::BTreeMap<String, usize> = Default::default();+ for f in &files {+ let Ok(v) = read_json(f) else { continue };+ if !(v["nodes"].is_array() || v.as_object().is_some_and(|o| o.values().any(|n| matches!(n["class_type"], J::String(_))))) {+ continue;+ }+ let g = match comfy::read::read(&v, &schema) {+ Ok(g) => g,+ Err(e) => { failed.push(format!("{}: {e}", f.display())); continue; }+ };+ for n in g.values().filter(|n| !schema.contains_key(&n.class)) {+ *unknown.entry(n.class.clone()).or_default() += 1;+ }+ let l = comfy::lift::lift(&g, &schema);+ if let Err(e) = l.flow.check() {+ failed.push(format!("{}: {e}", f.file_name().unwrap_or_default().to_string_lossy()));+ continue;+ }+ read += 1;+ if l.flow.steps.values().all(|s| s.op != "comfy" || s.op == "media.load") && !l.flow.out.is_empty() {+ whole += 1;+ }+ for s in l.flow.steps.values() {+ *ops.entry(s.op.clone()).or_default() += 1;+ if s.op == "comfy" {+ kept += 1;+ if let Some(w) = s.from.as_deref().and_then(|f| f.split_once("kept: ")).map(|(_, w)| w) {+ let w: String = w.split_whitespace().map(|t| if t.chars().any(|c| c.is_ascii_digit()) { "_" } else { t }).collect::<Vec<_>>().join(" ");+ *why.entry(w).or_default() += 1;+ }+ let out = s.inputs["output"].as_str().unwrap_or("");+ *kept_classes.entry(s.inputs["nodes"][out]["class_type"].as_str().unwrap_or("?").to_string()).or_default() += 1;+ } else if s.op != "media.load" {+ named += 1;+ }+ }+ }+ let top = |m: &std::collections::BTreeMap<String, usize>, n: usize| {+ let mut v: Vec<(&String, &usize)> = m.iter().collect();+ v.sort_by(|a, b| b.1.cmp(a.1));+ v.into_iter().take(n).map(|(k, c)| format!("{k} {c}")).collect::<Vec<_>>().join(", ")+ };+ Ok(serde_json::to_string_pretty(&json!({+ "workflows": files.len(), "read": read, "failed": failed.len(), "every_step_named": whole,+ "steps_named": named, "steps_kept_comfy": kept, "ops": ops,+ "kept_most": top(&kept_classes, 25), "classes_without_schema": top(&unknown, 15), "samplers_kept_because": top(&why, 20),+ "failures": failed.iter().take(15).collect::<Vec<_>>(),+ })).unwrap_or_default())+}++/// A workflow run as it is on the ComfyUI server: each Load node's file (beside the workflow, or a path) uploaded+/// first, every output node's files fetched into DIR.+fn run_workflow(args: &[String]) -> Result<String, String> {+ let path = args.get(1).ok_or(USAGE)?;+ let base = Path::new(path).parent().map(Path::to_path_buf).unwrap_or_default();+ let schema = comfy::schema::load();+ let mut g = comfy::read::read(&read_json(path)?, &schema)?;+ let server = comfy::server::Comfy::from_settings();+ if !server.wake(std::time::Duration::from_secs(600)) {+ return Err(format!("nothing answers at {} (tools/comfy/setup.sh serve; or RAEA_COMFY_URL)", server.url));+ }+ for n in g.values_mut() {+ for key in ["image", "file", "video", "audio"] {+ let Some(name) = n.inputs.get(key).and_then(|v| v.as_str()).map(str::to_string) else { continue };+ let f = if Path::new(&name).is_absolute() { PathBuf::from(&name) } else { base.join(&name) };+ if n.class.starts_with("Load") && f.is_file() {+ n.inputs.insert(key.into(), json!(server.upload(&f)?));+ }+ }+ }+ let pid = server.queue(&comfy::read::to_api(&g))?;+ let entry = server.wait(&pid, std::time::Duration::from_secs(3600))?;+ let dir = PathBuf::from(flag(args, "-o").unwrap_or("comfy-out"));+ std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;+ let mut files = Vec::new();+ // which node made each file too, so a whiteboard puts it beside its Save node (apps/app CF2)+ let mut outputs = serde_json::Map::new();+ for node in entry["outputs"].as_object().map(|o| o.keys().cloned().collect::<Vec<_>>()).unwrap_or_default() {+ let made = server.fetch(&entry, &node, &dir).unwrap_or_default();+ outputs.insert(node.clone(), json!(made));+ files.extend(made);+ }+ write_or_print(&json!({"prompt_id": pid, "files": files, "outputs": outputs}), None)+}diff --git a/io/gen/src/hosted.rs b/io/gen/src/hosted.rsnew file mode 100644index 00000000..4b22d93f--- /dev/null+++ b/io/gen/src/hosted.rs@@ -0,0 +1,139 @@+//! The hosted backends that take media inline (fal, Replicate, OpenRouter, a Modal endpoint): each step's references+//! become an https URL when the step that made them has one, else a data URI of its file.++use std::collections::BTreeMap;++use serde_json::{Map, Value as J, json};++use crate::flow::{Step, reference};+use crate::run::{Made1, Run};++/// Puts a local file where a hosted API can fetch it; its URL (fal's storage). Without one, files go as data URIs.+type Upload<'a> = Option<&'a dyn Fn(&std::path::Path) -> Result<String, String>>;++/// A made step's output as a value a hosted API reads.+fn media(done: &BTreeMap<String, Made1>, v: &J, up: Upload) -> Result<Option<String>, String> {+ let file = |f: &std::path::Path| match up { Some(u) => u(f), None => crate::fal::data_uri(f) };+ let Some(r) = reference(v) else { return Ok(None) };+ let up = done.get(r).ok_or(format!("@{r} isn't made yet"))?;+ if crate::flow::index(v).is_some() {+ return crate::run::file_of(done, v).ok_or(format!("{v} names no file of @{r}")).and_then(|f| file(f)).map(Some);+ }+ match (&up.url, up.files.first()) {+ (Some(u), _) => Ok(Some(u.clone())),+ (None, Some(f)) => file(f).map(Some),+ _ => Err(format!("@{r} made nothing")),+ }+}++/// The step's literal inputs, and its media as (input, value) in input order (arrays of references spread out).+fn split(s: &Step, done: &BTreeMap<String, Made1>, up: Upload) -> Result<(Map<String, J>, Vec<(String, String)>), String> {+ let (mut lit, mut med) = (Map::new(), Vec::new());+ for (k, v) in &s.inputs {+ let vals: Vec<&J> = match v { J::Array(a) if a.iter().any(|x| reference(x).is_some()) => a.iter().collect(), _ => vec![v] };+ let mut any = false;+ for x in vals {+ if let Some(m) = media(done, x, up)? {+ any = true;+ // a model's own media input (x_<name>) keeps its name+ if k.starts_with("x_") { lit.insert(k.clone(), json!(m)); } else { med.push((k.clone(), m)); }+ }+ }+ if !any {+ lit.insert(k.clone(), v.clone());+ }+ }+ Ok((lit, med))+}++fn stems(run: &Run, key: &str, k: usize) -> std::path::PathBuf {+ run.dir.join(if k == 0 { key.to_string() } else { format!("{key}-{k}") })+}++impl Run<'_> {+ pub(crate) fn fal(&self, endpoint: &str, s: &Step, key: &str, done: &BTreeMap<String, Made1>) -> Result<Made1, String> {+ let fal = crate::fal::Fal::from_settings()?;+ let upload = |f: &std::path::Path| fal.upload(f);+ let (lit, med) = split(s, done, Some(&upload))?;+ let resp = fal.run(endpoint, &crate::fal::body(&lit, &med, &fal.inputs(endpoint)), self.stall)?;+ let mut urls = Vec::new();+ crate::fal::urls(&resp, &mut urls);+ let files = if urls.is_empty() { vec![] } else { crate::run::save_all(&urls, &self.dir, key)? };+ if files.is_empty() {+ return Err(format!("fal {endpoint} answered with no files: {}", resp.to_string().chars().take(300).collect::<String>()));+ }+ Ok(Made1 { files, ..Default::default() })+ }++ /// Replicate: the inputs by their own names (x_<name> as <name>; prompt, image, seed as they are), media inline.+ /// A comfy step on Replicate sends its graph as any-comfyui-workflow's workflow_json.+ pub(crate) fn replicate(&self, model: &str, s: &Step, key: &str, done: &BTreeMap<String, Made1>) -> Result<Made1, String> {+ let rep = crate::replicate::Replicate::from_settings()?;+ let input = if s.op == "comfy" {+ if !s.needs().is_empty() {+ return Err("a comfy step on Replicate can't read other steps' files yet (any-comfyui-workflow takes one input_file); run it on a ComfyUI server".into());+ }+ let mut mini = crate::flow::Flow::default();+ mini.steps.insert("g".into(), Step { model: None, ..s.clone() });+ mini.out = vec!["g".into()];+ json!({"workflow_json": crate::comfy::export(&mini)?.to_string(), "output_format": "png"})+ } else {+ let (lit, med) = split(s, done, None)?;+ let mut b = json!({});+ for (k, v) in lit {+ let name = k.strip_prefix("x_").map(str::to_string).unwrap_or(if k == "negative" { "negative_prompt".into() } else { k });+ b[name.as_str()] = v;+ }+ for (k, v) in med {+ let name = match k.as_str() { "start_image" => "start_image", "end_image" => "end_image", "video" => "video", "mask" => "mask", _ => "image" };+ b[name] = json!(v);+ }+ b+ };+ let out = rep.run(model, &input, self.stall)?;+ let urls = crate::replicate::urls(&out);+ let files = if urls.is_empty() { vec![] } else { crate::run::save_all(&urls, &self.dir, key)? };+ if files.is_empty() {+ return Err(format!("Replicate {model} gave no files: {out}"));+ }+ Ok(Made1 { files, ..Default::default() })+ }++ /// OpenRouter: text.generate writes words (kept as .txt); image ops ask an image model for pictures.+ pub(crate) fn openrouter(&self, model: &str, s: &Step, key: &str, done: &BTreeMap<String, Made1>) -> Result<(Made1, u64), String> {+ let or = crate::openrouter::OpenRouter::from_settings()?;+ let (lit, med) = split(s, done, None)?;+ let prompt = lit.get("prompt").or(lit.get("text")).and_then(|p| p.as_str()).unwrap_or("").to_string();+ let system = lit.get("system").and_then(|p| p.as_str());+ let extra: Map<String, J> = lit.iter().filter_map(|(k, v)| k.strip_prefix("x_").map(|n| (n.to_string(), v.clone()))).collect();+ let images: Vec<String> = med.into_iter().map(|(_, v)| v).collect();+ let text = s.op == "text.generate";+ let (words, pics, cents) = or.complete(model, &prompt, system, &images, !text, &extra)?;+ let files = if text {+ let f = stems(self, key, 0).with_extension("txt");+ std::fs::write(&f, words.trim()).map_err(|e| format!("{}: {e}", f.display()))?;+ vec![f]+ } else {+ pics.iter().enumerate().map(|(k, u)| crate::openrouter::save(u, &stems(self, key, k))).collect::<Result<Vec<_>, _>>()?+ };+ if files.is_empty() {+ return Err(format!("OpenRouter {model} made no image (it said: {})", words.chars().take(200).collect::<String>()));+ }+ Ok((Made1 { files, ..Default::default() }, cents.ceil() as u64))+ }++ pub(crate) fn modal(&self, name: &str, s: &Step, key: &str, done: &BTreeMap<String, Made1>) -> Result<(Made1, u64), String> {+ let (mut lit, med) = split(s, done, None)?;+ for (k, v) in med {+ lit.insert(k, json!(v));+ }+ let (files, cents) = crate::modal::run(name, &s.op, &J::Object(lit), &stems(self, key, 0))?;+ Ok((Made1 { files, ..Default::default() }, cents))+ }++ /// A speech step on Fish Audio: its words (a text step's already put in by run), voice and speed.+ pub(crate) fn fish(&self, model: &str, s: &Step, key: &str) -> Result<(Made1, u64), String> {+ let (file, cents) = crate::fish::run(model, &s.op, &s.inputs, &stems(self, key, 0))?;+ Ok((Made1 { files: vec![file], ..Default::default() }, cents))+ }+}diff --git a/io/gen/src/lib.rs b/io/gen/src/lib.rsnew file mode 100644index 00000000..9b489d6c--- /dev/null+++ b/io/gen/src/lib.rs@@ -0,0 +1,15 @@+//! Generation flows run: route.rs sends each step of a flow to a backend (made.app, fal, Replicate, OpenRouter, a Modal+//! endpoint, Fish Audio, a ComfyUI server, or a model the host runs locally) and run.rs makes them, cached by content; cli.rs is+//! `raea gen`. The flow format and hosted backends are raea-io-gen-core, ComfyUI import and export raea-io-gen-comfy,+//! both re-exported here under their old paths.++pub mod cli;+mod hosted;+pub mod native;+pub mod route;+pub mod run;+#[cfg(test)]+mod tests;++pub use raea_io_gen_comfy as comfy;+pub use raea_io_gen_core::{direct, fal, fish, flow, http, made, modal, openrouter, replicate, setting, types};diff --git a/io/gen/src/native.rs b/io/gen/src/native.rsnew file mode 100644index 00000000..87123a61--- /dev/null+++ b/io/gen/src/native.rs@@ -0,0 +1,94 @@+//! The ops raea runs itself, with no model and no server: image.crop, image.scale and image.stitch (what ComfyUI's+//! ImageCrop, ImageScale* and ImageStitch do), each writing a PNG.++use std::path::{Path, PathBuf};++use image::{DynamicImage, GenericImage, GenericImageView, imageops::FilterType};+use serde_json::Value as J;++use crate::flow::Step;++pub const OPS: [&str; 3] = ["image.crop", "image.scale", "image.stitch"];++fn open(f: &Path) -> Result<DynamicImage, String> {+ image::open(f).map_err(|e| format!("{}: {e}", f.display()))+}++/// `s` made from its pictures (`file` gives a reference's file), written to `<dir>/<key>.png`.+pub fn run(s: &Step, file: &dyn Fn(&J) -> Result<PathBuf, String>, dir: &Path, key: &str) -> Result<PathBuf, String> {+ let n = |k: &str| s.inputs.get(k).and_then(|v| v.as_f64());+ let pic = |k: &str| s.inputs.get(k).ok_or(format!("{} needs {k}", s.op)).and_then(file).and_then(|f| open(&f));+ let out = match s.op.as_str() {+ "image.crop" => {+ let img = pic("image")?;+ let (x, y) = (n("x").unwrap_or(0.0).max(0.0) as u32, n("y").unwrap_or(0.0).max(0.0) as u32);+ // ComfyUI clamps the box to the picture+ let (x, y) = (x.min(img.width().saturating_sub(1)), y.min(img.height().saturating_sub(1)));+ let w = (n("width").unwrap_or(img.width() as f64) as u32).clamp(1, img.width() - x);+ let h = (n("height").unwrap_or(img.height() as f64) as u32).clamp(1, img.height() - y);+ img.crop_imm(x, y, w, h)+ }+ "image.scale" => {+ let img = pic("image")?;+ let (iw, ih) = (img.width() as f64, img.height() as f64);+ let (w, h) = if let Some(f) = n("factor") {+ (iw * f, ih * f)+ } else if let Some(mp) = n("megapixels") {+ let f = (mp * 1_048_576.0 / (iw * ih)).sqrt();+ (iw * f, ih * f)+ } else {+ // a missing side keeps the proportions+ match (n("width"), n("height")) {+ (Some(w), Some(h)) => (w, h),+ (Some(w), None) => (w, ih * w / iw),+ (None, Some(h)) => (iw * h / ih, h),+ (None, None) => (iw, ih),+ }+ };+ let (w, h) = ((w.round() as u32).max(1), (h.round() as u32).max(1));+ match s.inputs.get("fit").and_then(|f| f.as_str()).unwrap_or("stretch") {+ "cover" => img.resize_to_fill(w, h, FilterType::Lanczos3),+ "contain" => img.resize(w, h, FilterType::Lanczos3),+ _ => img.resize_exact(w, h, FilterType::Lanczos3),+ }+ }+ "image.stitch" => {+ let list = s.inputs.get("images").and_then(|v| v.as_array()).ok_or("image.stitch needs images, a list")?;+ let pics: Vec<DynamicImage> = list.iter().map(|v| file(v).and_then(|f| open(&f))).collect::<Result<_, _>>()?;+ let dir_ = s.inputs.get("direction").and_then(|d| d.as_str()).unwrap_or("right");+ stitch(pics, dir_)?+ }+ op => return Err(format!("{op} isn't one raea runs itself ({})", OPS.join(", "))),+ };+ let f = dir.join(format!("{key}.png"));+ out.save(&f).map_err(|e| format!("{}: {e}", f.display()))?;+ Ok(f)+}++/// Pictures side by side (right, left) or stacked (down, up), each scaled to the first's height or width, as+/// ImageStitch does with match_image_size.+fn stitch(mut pics: Vec<DynamicImage>, direction: &str) -> Result<DynamicImage, String> {+ if pics.is_empty() {+ return Err("image.stitch: no images".into());+ }+ if matches!(direction, "left" | "up") {+ pics.reverse();+ }+ let across = matches!(direction, "right" | "left");+ let (w0, h0) = pics[0].dimensions();+ let pics: Vec<DynamicImage> = pics.into_iter().map(|p| {+ let (w, h) = p.dimensions();+ if across && h != h0 { p.resize_exact((w as f64 * h0 as f64 / h as f64).round() as u32, h0, FilterType::Lanczos3) }+ else if !across && w != w0 { p.resize_exact(w0, (h as f64 * w0 as f64 / w as f64).round() as u32, FilterType::Lanczos3) }+ else { p }+ }).collect();+ let (w, h) = if across { (pics.iter().map(|p| p.width()).sum(), h0) } else { (w0, pics.iter().map(|p| p.height()).sum()) };+ let mut out = DynamicImage::new_rgba8(w, h);+ let mut at = 0;+ for p in &pics {+ let (x, y) = if across { (at, 0) } else { (0, at) };+ out.copy_from(&p.to_rgba8(), x, y).map_err(|e| e.to_string())?;+ at += if across { p.width() } else { p.height() };+ }+ Ok(out)+}diff --git a/io/gen/src/route.rs b/io/gen/src/route.rsnew file mode 100644index 00000000..6594b892--- /dev/null+++ b/io/gen/src/route.rs@@ -0,0 +1,219 @@+//! Where each step runs. A step that names its model goes there (`made:<id>`, `fal:<endpoint>`,+//! `replicate:<owner/name>`, `openrouter:<model>`, `modal:<endpoint>`, `fish:<model>`, `comfy`, `local:<name>`). text.generate goes to+//! OpenRouter (RAEA_GEN_TEXT_MODEL, else Kimi). Otherwise: a `comfy` step on the ComfyUI server; a step with ComfyUI weights on the server too when+//! the flow asks for the exact weights (`--exact`), else made's model for that op, which is noted as standing in for+//! them; a local model when the host has one for the op (sao for effects); made for the rest.++use serde_json::{Map, Value as J, json};++use crate::flow::{Step, reference};++#[derive(Clone, Debug, PartialEq)]+pub enum Backend {+ Made(String),+ Fal(String),+ Replicate(String),+ OpenRouter(String),+ Modal(String),+ /// Fish Audio's text-to-speech, with the founder's FISH_API_KEY (raea-io-gen-core's fish.rs)+ Fish(String),+ Comfy,+ Local(String),+ Load,+ /// raea itself: native.rs+ Native,+}++impl std::fmt::Display for Backend {+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {+ match self {+ Backend::Made(m) => write!(f, "made:{m}"),+ Backend::Fal(m) => write!(f, "fal:{m}"),+ Backend::Replicate(m) => write!(f, "replicate:{m}"),+ Backend::OpenRouter(m) => write!(f, "openrouter:{m}"),+ Backend::Modal(m) => write!(f, "modal:{m}"),+ Backend::Fish(m) => write!(f, "fish:{}", if m.is_empty() { crate::fish::DEFAULT_MODEL } else { m }),+ Backend::Comfy => write!(f, "comfy"),+ Backend::Local(m) => write!(f, "local:{m}"),+ Backend::Load => write!(f, "load"),+ Backend::Native => write!(f, "raea"),+ }+ }+}++/// made's model for an op when the step doesn't name one: a good default at a fair price, by what the step is given.+pub fn made_default(s: &Step) -> Option<&'static str> {+ let has = |k: &str| s.inputs.contains_key(k);+ Some(match s.op.as_str() {+ "image.generate" => "nano_banana_2",+ "image.edit" => "nano_banana_2",+ "image.upscale" => "topaz_upscale_image",+ "image.remove_background" => "bria_background_removal",+ "image.expand" => "flux_2_pro_outpaint",+ "video.generate" if has("start_image") || has("end_image") => "kling_3_pro_i2v",+ "video.generate" if has("refs") => "seedance_2_5_reference",+ "video.generate" => "kling_3_pro",+ "video.edit" => "kling_o3_edit_pro",+ "video.upscale" => "seedvr_video_upscale",+ "audio.music" => "elevenlabs_music_v2_5",+ "audio.sfx" if has("video") => "mirelo_sfx_1_5",+ "audio.sfx" => "elevenlabs_sound_effects_v2",+ "audio.speech" => "elevenlabs_turbo_v2_5",+ _ => return None,+ })+}++/// The local model an op prefers when the host has it (raea's generation policy: SAO for effects).+pub fn local_default(s: &Step) -> Option<&'static str> {+ match s.op.as_str() {+ "audio.sfx" if !s.inputs.contains_key("video") => Some("sao"),+ _ => None,+ }+}++/// Settings for routing a whole flow.+#[derive(Clone, Debug, Default)]+pub struct Policy {+ /// steps with ComfyUI weights run those weights (on ComfyUI) rather than made's nearest model+ pub exact: bool,+ /// the local models the host can run+ pub local: Vec<String>,+ /// comfy steps go to Replicate's any-comfyui-workflow rather than a ComfyUI server (RAEA_COMFY_URL)+ pub comfy_on_replicate: bool,+}++/// Where a step runs, and a note when it stands in for something it was asked for.+pub fn route(s: &Step, p: &Policy) -> Result<(Backend, Option<String>), String> {+ if let Some(m) = &s.model {+ let (kind, name) = m.split_once(':').unwrap_or((m.as_str(), ""));+ return Ok((match kind {+ "made" => Backend::Made(name.into()),+ "fal" => Backend::Fal(name.into()),+ "replicate" => Backend::Replicate(name.into()),+ "openrouter" => Backend::OpenRouter(name.into()),+ "modal" => Backend::Modal(name.into()),+ "fish" => Backend::Fish(name.into()),+ "comfy" => Backend::Comfy,+ "local" => Backend::Local(name.into()),+ _ => return Err(format!("model `{m}`: say made:<id>, fal:<endpoint>, replicate:<owner/name>, openrouter:<model>, modal:<endpoint>, fish:<model>, comfy or local:<name>")),+ }, None));+ }+ match s.op.as_str() {+ "media.load" => return Ok((Backend::Load, None)),+ op if crate::native::OPS.contains(&op) => return Ok((Backend::Native, None)),+ "comfy" if p.comfy_on_replicate => return Ok((Backend::Replicate(crate::replicate::COMFY.into()), None)),+ "comfy" => return Ok((Backend::Comfy, None)),+ "text.generate" => return Ok((Backend::OpenRouter(crate::setting("RAEA_GEN_TEXT_MODEL").unwrap_or_else(|| "moonshotai/kimi-k3.1-pro".into())), None)),+ "mesh.generate" => {+ let e = if s.inputs.contains_key("image") { "fal-ai/hunyuan-3d/v3.1/rapid/image-to-3d" } else { "fal-ai/hunyuan-3d/v3.1/rapid/text-to-3d" };+ return Ok((Backend::Fal(e.into()), None));+ }+ _ => {}+ }+ if let Some(w) = s.inputs.get("weights").filter(|w| !w.is_null()) {+ if p.exact {+ return Ok((Backend::Comfy, None));+ }+ let m = made_default(s).ok_or(format!("{} has no made model", s.op))?;+ return Ok((Backend::Made(m.into()), Some(format!("made's {m} stands in for {w}{} (--exact runs them on ComfyUI)", if s.inputs.contains_key("loras") { " and its LoRAs" } else { "" }))));+ }+ if let Some(l) = local_default(s).filter(|l| p.local.iter().any(|x| x.as_str() == *l)) {+ return Ok((Backend::Local(l.into()), None));+ }+ let m = made_default(s).ok_or(format!("nothing runs {} yet: give it a model (made:<id>, fal:<endpoint>, comfy)", s.op))?;+ Ok((Backend::Made(m.into()), None))+}++/// Which made media role an input takes, from the roles the model declares.+fn role(input: &str, roles: &Map<String, J>) -> Option<String> {+ let wants: &[&str] = match input {+ "image" | "refs" => &["image", "reference_image", "reference_images", "image_urls", "start_image", "character_image"],+ "start_image" => &["start_image", "image", "first_frame"],+ "end_image" => &["end_image", "last_frame"],+ "video" => &["video", "source_video", "reference_video", "input_video"],+ "mask" => &["mask", "mask_image"],+ "x_audio" => &["audio", "audio_url"],+ _ => &[],+ };+ wants.iter().find(|w| roles.contains_key(**w)).map(|w| w.to_string()).or_else(|| (input == "image" || input == "refs").then(|| roles.keys().next().cloned()).flatten())+}++/// The nearest of a model's offered values (durations, aspect ratios) to what a step asks for.+fn nearest(want: f64, offered: &[f64]) -> Option<f64> {+ offered.iter().map(|&o| (o, (o - want).abs())).min_by(|a, b| a.1.total_cmp(&b.1)).map(|(o, _)| o)+}++/// The aspect ratio offered nearest to width:height.+fn ratio(w: f64, h: f64, offered: &[J]) -> Option<String> {+ let parse = |s: &str| s.split_once(':').and_then(|(a, b)| Some(a.parse::<f64>().ok()? / b.parse::<f64>().ok()?));+ offered.iter().filter_map(|o| o.as_str()).filter_map(|o| Some((o, parse(o)?))).min_by(|a, b| ((a.1 / (w / h)).ln().abs()).total_cmp(&(b.1 / (w / h)).ln().abs())).map(|(o, _)| o.to_string())+}++/// A step as a made request: its text, timing and shape fitted to what the model offers, and `media(input)` for+/// each media input (a `job_…`, `media_…` or https URL). Returns the body and what was changed or dropped to fit.+pub fn made_body(s: &Step, model: &J, media: &dyn Fn(&J) -> Result<String, String>) -> Result<(J, Vec<String>), String> {+ let mut b = json!({"model": model["id"]});+ let mut notes = Vec::new();+ let roles = model["mediaRoles"].as_object().cloned().unwrap_or_default();+ let mut medias = Vec::new();+ for (k, v) in &s.inputs {+ let vals: Vec<&J> = match v { J::Array(a) if a.iter().any(|x| reference(x).is_some()) => a.iter().collect(), _ => vec![v] };+ if vals.iter().any(|x| reference(x).is_some()) {+ let r = role(k, &roles).ok_or_else(|| format!("{} takes no {k} (its media roles: {})", model["id"], roles.keys().cloned().collect::<Vec<_>>().join(", ")))?;+ for x in vals {+ medias.push(json!({"value": media(x)?, "role": r}));+ }+ continue;+ }+ match k.as_str() {+ "prompt" | "text" => b["prompt"] = v.clone(),+ "negative" => b["negative_prompt"] = v.clone(),+ "seconds" => {+ let want = v.as_f64().unwrap_or(5.0);+ let offered: Vec<f64> = model["durations"].as_array().map(|a| a.iter().filter_map(|d| d.as_f64()).collect()).unwrap_or_default();+ let d = nearest(want, &offered).unwrap_or(want.round());+ if (d - want).abs() > 0.01 {+ notes.push(format!("{want}s asked, {} offers {d}s", model["id"]));+ }+ b["duration"] = json!(d as u64);+ }+ "aspect_ratio" | "resolution" | "audio" | "seed" => b[k.as_str()] = v.clone(),+ k if k.starts_with("x_") => b[&k[2..]] = v.clone(),+ "width" | "height" | "steps" | "cfg" | "sampler" | "scheduler" | "weights" | "loras" | "strength" | "fps" | "factor" => {}+ _ => b[k.as_str()] = v.clone(),+ }+ }+ // an aspect the model doesn't offer: ComfyUI's "auto" is made's match_input_image (or the model's default), a+ // ratio the nearest one offered+ if let (Some(a), Some(offered)) = (b.get("aspect_ratio").and_then(|a| a.as_str()).map(str::to_string), model["aspectRatios"].as_array()) {+ if !offered.iter().any(|o| o == a.as_str()) {+ let has = |x: &str| offered.iter().any(|o| o == x);+ let pick = match a.split_once(':').and_then(|(w, h)| Some((w.parse::<f64>().ok()?, h.parse::<f64>().ok()?))) {+ Some((w, h)) => ratio(w, h, offered),+ None if has("match_input_image") && !medias.is_empty() => Some("match_input_image".into()),+ None => None,+ };+ notes.push(format!("aspect {a} isn't one {} offers: {}", model["id"], pick.as_deref().unwrap_or("its default")));+ match pick {+ Some(p) => b["aspect_ratio"] = json!(p),+ None => { b.as_object_mut().map(|o| o.remove("aspect_ratio")); }+ }+ }+ }+ if b.get("aspect_ratio").is_none() {+ if let (Some(w), Some(h), Some(offered)) = (s.inputs.get("width").and_then(|v| v.as_f64()), s.inputs.get("height").and_then(|v| v.as_f64()), model["aspectRatios"].as_array()) {+ if let Some(r) = ratio(w, h, offered) {+ b["aspect_ratio"] = json!(r);+ }+ }+ }+ if !medias.is_empty() {+ b["medias"] = J::Array(medias);+ }+ if b.get("prompt").is_none() || b["prompt"].as_str().is_some_and(|p| p.trim().is_empty()) {+ b.as_object_mut().map(|o| o.remove("prompt"));+ }+ let (fitted, dropped) = crate::made::fit(model, b);+ notes.extend(dropped.into_iter().map(|d| format!("{} doesn't take `{d}`; left out", model["id"])));+ Ok((fitted, notes))+}diff --git a/io/gen/src/run.rs b/io/gen/src/run.rsnew file mode 100644index 00000000..a2cafcea--- /dev/null+++ b/io/gen/src/run.rs@@ -0,0 +1,408 @@+//! A flow run step by step where route() sends each one. Every step's output is kept under its key in the run's+//! folder (`<key>.<ext>`, indexed in gen.jsonl), so a step whose inputs haven't changed is never made twice. A made+//! step is quoted first and refused when it would pass the run's cap (--max-cents, else RAEA_GEN_MAX_CENTS, else+//! 100); its output stays a `job_…` for the next made step to read without a download and upload. `plan` routes and+//! quotes without sending anything.++use std::collections::BTreeMap;+use std::path::{Path, PathBuf};+use std::time::Duration;++use serde_json::{Value as J, json};++use crate::comfy::server::Comfy;+use crate::fal::Fal;+use crate::flow::{Flow, Step, index, reference, substitute};+use crate::made::{Made, outputs};+use crate::route::{Backend, Policy, made_body, route};++/// A model the host runs on this machine (raea's sao): the step, its inputs' files, where to write.+pub trait Local {+ fn names(&self) -> Vec<String>;+ fn make(&self, name: &str, step: &Step, dir: &Path, key: &str) -> Result<PathBuf, String>;+}++#[derive(Clone, Debug, Default)]+pub struct Made1 {+ pub files: Vec<PathBuf>,+ pub job: Option<String>,+ pub url: Option<String>,+}++pub struct Run<'a> {+ pub dir: PathBuf,+ pub base: PathBuf,+ pub policy: Policy,+ pub max_cents: u64,+ pub local: Option<&'a dyn Local>,+ pub stall: Duration,+}++impl<'a> Run<'a> {+ pub fn new(dir: PathBuf, base: PathBuf) -> Run<'a> {+ let max_cents = crate::setting("RAEA_GEN_MAX_CENTS").and_then(|c| c.parse().ok()).unwrap_or(100);+ Run { dir, base, policy: Policy::default(), max_cents, local: None, stall: Duration::from_secs(600) }+ }++ fn index(&self) -> BTreeMap<String, Made1> {+ std::fs::read_to_string(self.dir.join("gen.jsonl")).unwrap_or_default().lines().filter_map(|l| serde_json::from_str::<J>(l).ok()).filter_map(|l| {+ let files: Vec<PathBuf> = l["files"].as_array()?.iter().filter_map(|f| f.as_str()).map(|f| self.dir.join(f)).collect();+ (!files.is_empty() && files.iter().all(|f| f.exists())).then(|| (l["key"].as_str().unwrap_or_default().to_string(), Made1 { files, job: l["job"].as_str().map(str::to_string), url: None }))+ }).collect()+ }++ fn keep(&self, key: &str, id: &str, s: &Step, b: &Backend, m: &Made1, cents: u64) {+ // a load is its file, read again each run+ if *b == Backend::Load {+ return;+ }+ let names: Vec<String> = m.files.iter().filter_map(|f| f.strip_prefix(&self.dir).ok().map(|p| p.display().to_string())).collect();+ let line = json!({"key": key, "step": id, "op": s.op, "backend": b.to_string(), "files": names, "job": m.job, "cents": cents, "t": std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs())});+ if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(self.dir.join("gen.jsonl")) {+ let _ = std::io::Write::write_all(&mut f, format!("{line}\n").as_bytes());+ }+ if cents > 0 {+ let spend = crate::made::cached("spend.jsonl");+ if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(spend) {+ let _ = std::io::Write::write_all(&mut f, format!("{line}\n").as_bytes());+ }+ }+ }++ /// What each step would do and cost, sending nothing that runs or bills (made's /v1/cost is free).+ pub fn plan(&self, flow: &Flow) -> Result<J, String> {+ let made = Made::from_settings().ok();+ let cached = self.index();+ let keys = flow.keys()?;+ let (mut rows, mut total) = (Vec::new(), 0u64);+ // a text step's words aren't written yet: a stand-in prices the prompts that take them+ let words = |r: &str| flow.steps.get(r).filter(|t| t.op == "text.generate").map(|_| format!("(the words of step {r})"));+ for id in flow.order()? {+ let s = &Step { inputs: substitute(&J::Object(flow.steps[&id].inputs.clone()), &words).as_object().cloned().unwrap_or_default(), ..flow.steps[&id].clone() };+ let (b, note) = route(s, &self.policy)?;+ let mut row = json!({"step": id, "op": s.op, "runs_on": b.to_string(), "from": s.from});+ if let Some(n) = note {+ row["note"] = json!(n);+ }+ if cached.contains_key(&keys[&id]) {+ row["cached"] = json!(true);+ } else if let (Backend::Made(m), Some(made)) = (&b, &made) {+ let model = made.model(m)?;+ // a quote reads the media's count, not its bytes: a stand-in URL prices it+ let (body, fit) = made_body(s, &model, &|_| Ok("https://www.made.app/favicon.ico".into()))?;+ match made.cost(&body) {+ Ok((c, p)) if p < c && crate::direct::possible(&model) && crate::setting("FAL_KEY").is_some() && crate::setting("RAEA_GEN_VIA").as_deref() != Some("made") => {+ total += p;+ row["cents"] = json!(p);+ row["note"] = json!(format!("made would charge {c}¢ (a whole credit); fal's own {p}¢, so it goes to fal directly"));+ }+ Ok((c, p)) => {+ total += c;+ row["cents"] = json!(c);+ // made bills whole credits: what that adds over the provider's own price, shown, not hidden+ if c > p {+ row["provider_cents"] = json!(p);+ row["rounding_cents"] = json!(c - p);+ }+ }+ Err(e) => row["quote"] = json!(e),+ }+ if !fit.is_empty() {+ row["fitted"] = json!(fit);+ }+ } else if let Backend::Fish(_) = &b {+ // Fish bills the words' bytes: known before anything is sent+ let c = crate::fish::quote(s.inputs.get("text").and_then(|t| t.as_str()).unwrap_or(""));+ total += c;+ row["cents"] = json!(c);+ } else if let Backend::Fal(e) = &b {+ if let Ok((c, unit)) = Fal::from_settings().and_then(|f| f.price(e)) {+ row["cents_per"] = json!(format!("{c:.1} per {unit}"));+ total += c.ceil() as u64;+ }+ }+ rows.push(row);+ }+ Ok(json!({"steps": rows, "cents": total, "cap_cents": self.max_cents}))+ }++ /// The flow made: each output step's files.+ pub fn run(&self, flow: &Flow) -> Result<J, String> {+ std::fs::create_dir_all(&self.dir).map_err(|e| format!("{}: {e}", self.dir.display()))?;+ let keys = flow.keys()?;+ let cached = self.index();+ let mut done: BTreeMap<String, Made1> = BTreeMap::new();+ let (mut spent, mut rows) = (0u64, Vec::new());+ let mut made: Option<Made> = None;+ for id in flow.order()? {+ let s = &flow.steps[&id];+ let key = &keys[&id];+ let (b, note) = route(s, &self.policy)?;+ if let Some(m) = cached.get(key) {+ rows.push(json!({"step": id, "runs_on": b.to_string(), "cached": true, "files": m.files}));+ done.insert(id, m.clone());+ continue;+ }+ // a reference to words another step wrote (text.generate) reads as those words+ let s = &inline_text(s, &done);+ // a batch (several pictures from one step) goes to a model as each of its pictures+ let spread;+ let s = if matches!(b, Backend::Made(_) | Backend::Fal(_) | Backend::Replicate(_) | Backend::OpenRouter(_) | Backend::Modal(_)) { spread = spread_batches(s, &done); &spread } else { s };+ eprintln!("raea gen: {id} ({}) on {b}{}", s.op, note.as_deref().map(|n| format!(" — {n}")).unwrap_or_default());+ let (out, cents) = match &b {+ Backend::Load => (self.load(s)?, 0),+ Backend::Native => {+ let file = |v: &J| -> Result<PathBuf, String> {+ let r = reference(v).ok_or(format!("step `{id}`: {v} isn't a step's output"))?;+ let m = done.get(r).ok_or(format!("step `{id}`: {r} hasn't run"))?;+ match (m.files.first(), &m.url) {+ (Some(f), _) => Ok(f.clone()),+ (None, Some(u)) => save_all(std::slice::from_ref(u), &self.dir, &format!("{key}-in")).map(|f| f[0].clone()),+ _ => Err(format!("step `{id}`: {r} made no file")),+ }+ };+ (Made1 { files: vec![crate::native::run(s, &file, &self.dir, key)?], ..Default::default() }, 0)+ }+ Backend::Made(m) => {+ if made.is_none() {+ made = Some(Made::from_settings()?);+ }+ self.made(made.as_ref().unwrap(), m, s, key, &done, &mut spent)?+ }+ Backend::Fal(e) => (self.fal(e, &s, key, &done)?, 0),+ Backend::Replicate(m) => (self.replicate(m, &s, key, &done)?, 0),+ Backend::OpenRouter(m) => self.openrouter(m, &s, key, &done)?,+ Backend::Modal(m) => self.modal(m, &s, key, &done)?,+ Backend::Fish(m) => {+ // the words' price is known before sending: held to the run's cap like a made step+ let charge = crate::fish::quote(s.inputs.get("text").and_then(|t| t.as_str()).unwrap_or(""));+ if spent + charge > self.max_cents {+ return Err(format!("{b} would cost {charge}¢, past this run's cap of {}¢ ({spent}¢ spent): raise --max-cents or RAEA_GEN_MAX_CENTS", self.max_cents));+ }+ let (m1, c) = self.fish(m, &s, key)?;+ spent += c;+ (m1, c)+ }+ Backend::Comfy => (self.comfy(&id, s, key, &done)?, 0),+ Backend::Local(n) => {+ let l = self.local.filter(|l| l.names().contains(n)).ok_or(format!("step `{id}` wants local:{n}, which this host doesn't run"))?;+ let resolved = Step { inputs: substitute(&J::Object(s.inputs.clone()), &|r| done.get(r).and_then(|m| m.files.first()).map(|f| f.display().to_string())).as_object().cloned().unwrap_or_default(), ..s.clone() };+ (Made1 { files: vec![l.make(n, &resolved, &self.dir, key)?], ..Default::default() }, 0)+ }+ };+ self.keep(key, &id, s, &b, &out, cents);+ // a made model sent to fal directly (GN3) says where it really ran+ let (runs_on, note) = match out.job.as_deref().filter(|j| j.starts_with("fal:")) {+ Some(j) => (j.to_string(), Some(format!("{b} sent to fal directly: made rounds up to a whole credit"))),+ None => (b.to_string(), note),+ };+ rows.push(json!({"step": id, "runs_on": runs_on, "cents": cents, "files": out.files, "note": note}));+ done.insert(id, out);+ }+ // each output under its own name too (<dir>/clip.mp4), so a composition can name it: staticFile("gen/clip.mp4")+ let mut outs = serde_json::Map::new();+ for o in &flow.out {+ let files = done.get(o).map(|m| m.files.clone()).unwrap_or_default();+ outs.insert(o.clone(), json!(name_output(&self.dir, o, &files)?));+ }+ Ok(json!({"out": outs, "steps": rows, "cents": spent}))+ }++ fn load(&self, s: &Step) -> Result<Made1, String> {+ if let Some(u) = s.inputs.get("url").and_then(|u| u.as_str()) {+ return Ok(Made1 { url: Some(u.into()), ..Default::default() });+ }+ let p = s.inputs.get("path").and_then(|p| p.as_str()).ok_or("media.load needs a path or url")?;+ let f = if Path::new(p).is_absolute() { PathBuf::from(p) } else { self.base.join(p) };+ if !f.is_file() {+ return Err(format!("media.load: no file {}", f.display()));+ }+ Ok(Made1 { files: vec![f], ..Default::default() })+ }++ fn made(&self, made: &Made, m: &str, s: &Step, key: &str, done: &BTreeMap<String, Made1>, spent: &mut u64) -> Result<(Made1, u64), String> {+ let model = made.model(m)?;+ // priced first with a stand-in for each media (a quote reads their count, not their bytes)+ let (probe, notes) = made_body(s, &model, &|_| Ok("https://www.made.app/favicon.ico".into()))?;+ for n in notes {+ eprintln!("raea gen: {n}");+ }+ let (cents, provider) = made.cost(&probe)?;+ let direct = provider < cents && crate::direct::possible(&model) && crate::setting("RAEA_GEN_VIA").as_deref() != Some("made") && crate::setting("FAL_KEY").is_some();+ let charge = if direct { provider } else { cents };+ if *spent + charge > self.max_cents {+ return Err(format!("{m} would cost {charge}¢, past this run's cap of {}¢ ({}¢ spent): raise --max-cents or RAEA_GEN_MAX_CENTS", self.max_cents, *spent));+ }+ if direct {+ eprintln!("raea gen: made charges {cents}¢ for this (a whole credit), fal {provider}¢: sent to fal directly");+ let fal = crate::fal::Fal::from_settings()?;+ let url = |v: &J| -> Result<String, String> {+ let up = done.get(reference(v).ok_or("not a reference")?).ok_or("not made yet")?;+ if index(v).is_some() {+ return fal.upload(file_of(&done, v).ok_or("no such picture in the batch")?);+ }+ match (&up.url, up.files.first()) {+ (Some(u), _) => Ok(u.clone()),+ (None, Some(f)) => fal.upload(f),+ _ => Err("made nothing".into()),+ }+ };+ let (body, _) = made_body(s, &model, &url)?;+ let (endpoint, input) = crate::direct::body(&model, &body)?;+ let resp = fal.run(&endpoint, &input, self.stall)?;+ let mut urls = Vec::new();+ crate::fal::urls(&resp, &mut urls);+ let files = if urls.is_empty() { vec![] } else { save_all(&urls, &self.dir, key)? };+ if files.is_empty() {+ return Err(format!("fal {endpoint} answered with no files"));+ }+ *spent += provider;+ return Ok((Made1 { files, job: Some(format!("fal:{endpoint}")), url: urls.first().cloned() }, provider));+ }+ let media = |v: &J| -> Result<String, String> {+ let r = reference(v).ok_or("not a reference")?;+ let up = done.get(r).ok_or(format!("@{r} isn't made yet"))?;+ // a job or URL stands for the whole output; one picture of a batch goes up as its file+ if let Some(j) = up.job.as_ref().or(up.url.as_ref()).filter(|_| index(v).is_none()) {+ return Ok(j.clone());+ }+ made.upload(file_of(done, v).ok_or(format!("{v} names no file of @{r}"))?)+ };+ let (mut body, _) = made_body(s, &model, &media)?;+ body["request_id"] = json!(format!("raea-{key}"));+ body["max_cost_cents"] = json!(cents);+ let job = made.create(&body)?;+ let jid = job["id"].as_str().ok_or_else(|| format!("made.app: no job id in {job}"))?.to_string();+ *spent += cents;+ let fin = made.wait(&jid, self.stall)?;+ let outs = outputs(&fin);+ let files = if outs.is_empty() { vec![] } else { save_all(&outs.iter().map(|o| o.0.clone()).collect::<Vec<_>>(), &self.dir, key)? };+ if files.is_empty() {+ return Err(format!("made.app job {jid} succeeded with no assets"));+ }+ Ok((Made1 { files, job: Some(jid), url: outs.first().map(|o| o.0.clone()) }, fin["costCents"].as_u64().unwrap_or(cents)))+ }++ /// The step alone as a ComfyUI graph: what it reads uploaded and loaded, the step written as nodes, its output saved.+ fn comfy(&self, id: &str, s: &Step, key: &str, done: &BTreeMap<String, Made1>) -> Result<Made1, String> {+ let server = Comfy::from_settings();+ if !server.wake(std::time::Duration::from_secs(600)) {+ return Err(format!("step `{id}` runs on ComfyUI, and nothing answers at {} (raea gen comfy setup; or RAEA_COMFY_URL for a hosted one)", server.url));+ }+ let mut mini = Flow::default();+ for need in s.needs() {+ let up = done.get(&need).ok_or(format!("@{need} isn't made yet"))?;+ let f = up.files.first().ok_or(format!("@{need} has no file for ComfyUI"))?;+ let name = server.upload(f)?;+ mini.steps.insert(need, Step::new("media.load", json!({"path": name})));+ }+ let mut me = s.clone();+ me.model = None;+ mini.steps.insert(id.to_string(), me);+ mini.out = vec![id.to_string()];+ let graph = crate::comfy::export(&mini)?;+ let pid = server.queue(&graph)?;+ let entry = server.wait(&pid, self.stall)?;+ let tmp = self.dir.join(format!(".{key}"));+ let _ = std::fs::create_dir_all(&tmp);+ // a step giving several slots saved each as save0, save0.1, …: its files in that order (@step.N)+ let n = s.inputs.get("slots").and_then(|v| v.as_array()).map(|a| a.len()).unwrap_or(1).max(1);+ let mut got = server.fetch(&entry, "save0", &tmp)?;+ for j in 1..n {+ got.extend(server.fetch(&entry, &format!("save0.{j}"), &tmp)?);+ }+ let mut files = Vec::new();+ for (k, f) in got.into_iter().enumerate() {+ let ext = f.extension().and_then(|e| e.to_str()).unwrap_or("bin").to_string();+ let dest = self.dir.join(format!("{}.{ext}", if k == 0 { key.to_string() } else { format!("{key}-{k}") }));+ std::fs::rename(&f, &dest).map_err(|e| format!("{}: {e}", dest.display()))?;+ files.push(dest);+ }+ let _ = std::fs::remove_dir_all(&tmp);+ Ok(Made1 { files, ..Default::default() })+ }+}++/// The file a reference names: `@step` the step's main file, `@step.N` its Nth.+pub(crate) fn file_of<'a>(done: &'a BTreeMap<String, Made1>, v: &J) -> Option<&'a PathBuf> {+ done.get(reference(v)?)?.files.get(index(v).unwrap_or(0))+}++/// A step with each plain reference to a batch (a step whose files are all pictures, more than one) spread into one+/// reference per picture; a mesh with its textures isn't a batch.+pub(crate) fn spread_batches(s: &Step, done: &BTreeMap<String, Made1>) -> Step {+ let pictures = |r: &str| done.get(r).map(|m| m.files.len()).filter(|&n| n > 1 && done[r].files.iter().all(|f| matches!(f.extension().and_then(|e| e.to_str()), Some("png" | "jpg" | "jpeg" | "webp")))).unwrap_or(0);+ let spread = |v: &J| -> Vec<J> {+ match (reference(v), index(v)) {+ (Some(r), None) if pictures(r) > 1 => (0..pictures(r)).map(|i| json!(format!("@{r}.{i}"))).collect(),+ _ => vec![v.clone()],+ }+ };+ let inputs = s.inputs.iter().map(|(k, v)| {+ let v = match v {+ J::Array(a) => J::Array(a.iter().flat_map(spread).collect()),+ v => match spread(v) { one if one.len() == 1 => one[0].clone(), many => J::Array(many) },+ };+ (k.clone(), v)+ }).collect();+ Step { inputs, ..s.clone() }+}++/// A step with each reference to a .txt output replaced by its text.+fn inline_text(s: &Step, done: &BTreeMap<String, Made1>) -> Step {+ let text = |r: &str| done.get(r).and_then(|m| m.files.first()).filter(|f| f.extension().is_some_and(|e| e == "txt")).and_then(|f| std::fs::read_to_string(f).ok());+ Step { inputs: substitute(&J::Object(s.inputs.clone()), &text).as_object().cloned().unwrap_or_default(), ..s.clone() }+}++/// An output's files under the output's name: one file as `<name>.<ext>`, several (a mesh and its textures) as+/// `<name>/` holding them, and a GLB among them also as `<name>.glb`. Replaced on every run, so the name always holds the latest result.+fn name_output(dir: &Path, name: &str, files: &[PathBuf]) -> Result<Vec<PathBuf>, String> {+ let copy = |from: &Path, to: &Path| std::fs::copy(from, to).map(|_| to.to_path_buf()).map_err(|e| format!("{}: {e}", to.display()));+ match files {+ [] => Ok(vec![]),+ [one] if one.parent() == Some(dir) => {+ let to = dir.join(format!("{name}.{}", one.extension().and_then(|e| e.to_str()).unwrap_or("bin")));+ Ok(vec![copy(one, &to)?])+ }+ many => {+ let sub = dir.join(name);+ let _ = std::fs::remove_dir_all(&sub);+ std::fs::create_dir_all(&sub).map_err(|e| format!("{}: {e}", sub.display()))?;+ let mut out: Vec<PathBuf> = many.iter().map(|f| copy(f, &sub.join(f.file_name().unwrap_or_default()))).collect::<Result<_, _>>()?;+ // a GLB holds its own textures: it also goes as <name>.glb, the file a scene names (gen/kite.glb)+ if let Some(glb) = many.first().filter(|f| f.extension().is_some_and(|e| e == "glb")) {+ out.insert(0, copy(glb, &dir.join(format!("{name}.glb")))?);+ }+ Ok(out)+ }+ }+}++/// A step's files from their URLs: one file is `<key>.<ext>`; several stay together in `<key>/` under their own names+/// (an OBJ's material and textures find each other by name), the main one first (a GLB, else an OBJ, else the first).+pub(crate) fn save_all(urls: &[String], dir: &Path, key: &str) -> Result<Vec<PathBuf>, String> {+ let mut seen = std::collections::BTreeSet::new();+ let urls: Vec<&String> = urls.iter().filter(|u| seen.insert(crate::http::redact(u).to_string())).collect();+ if urls.len() == 1 {+ return Ok(vec![crate::openrouter::save(urls[0], &dir.join(key))?]);+ }+ let sub = dir.join(key);+ std::fs::create_dir_all(&sub).map_err(|e| format!("{}: {e}", sub.display()))?;+ let mut files = Vec::new();+ for (k, u) in urls.iter().enumerate() {+ let name = Path::new(crate::http::redact(u)).file_name().and_then(|n| n.to_str()).map(|n| n.to_string()).unwrap_or(format!("file{k}"));+ let stem = sub.join(Path::new(&name).file_stem().and_then(|s| s.to_str()).unwrap_or("file"));+ let f = crate::openrouter::save(u, &stem)?;+ // made and fal name some outputs by their content type only; keep the URL's own extension+ let want = sub.join(&name);+ if f != want && Path::new(&name).extension().is_some() {+ let _ = std::fs::rename(&f, &want);+ files.push(want);+ } else {+ files.push(f);+ }+ }+ let rank = |p: &PathBuf| match p.extension().and_then(|e| e.to_str()) { Some("glb") => 0, Some("gltf") => 1, Some("obj") => 2, Some("mp4" | "mov" | "webm") => 3, _ => 4 };+ files.sort_by_key(rank);+ Ok(files)+}diff --git a/io/gen/src/tests.rs b/io/gen/src/tests.rsnew file mode 100644index 00000000..6d5efaec--- /dev/null+++ b/io/gen/src/tests.rs@@ -0,0 +1,468 @@+use serde_json::json;++use crate::comfy::{lift::lift, read::read, schema, write::write};+use crate::flow::{Flow, Step};+use crate::route::{Backend, Policy, route};+use crate::run::Local;++/// The classic text-to-image graph in API format, as ComfyUI's own example saves it.+fn sd_api() -> serde_json::Value {+ json!({+ "4": {"class_type": "CheckpointLoaderSimple", "inputs": {"ckpt_name": "sd_xl_base_1.0.safetensors"}},+ "10": {"class_type": "LoraLoader", "inputs": {"model": ["4", 0], "clip": ["4", 1], "lora_name": "ink.safetensors", "strength_model": 0.8, "strength_clip": 0.8}},+ "6": {"class_type": "CLIPTextEncode", "inputs": {"clip": ["10", 1], "text": "a lighthouse in fog"}},+ "7": {"class_type": "CLIPTextEncode", "inputs": {"clip": ["10", 1], "text": "blurry"}},+ "5": {"class_type": "EmptyLatentImage", "inputs": {"width": 1216, "height": 832, "batch_size": 1}},+ "3": {"class_type": "KSampler", "inputs": {"model": ["10", 0], "positive": ["6", 0], "negative": ["7", 0], "latent_image": ["5", 0], "seed": 7, "steps": 30, "cfg": 6.5, "sampler_name": "euler", "scheduler": "normal", "denoise": 1.0}},+ "8": {"class_type": "VAEDecode", "inputs": {"samples": ["3", 0], "vae": ["4", 2]}},+ "9": {"class_type": "SaveImage", "inputs": {"images": ["8", 0], "filename_prefix": "x"}},+ })+}++#[test]+fn a_sampler_chain_lifts_to_one_generate_step() {+ let s = schema::load();+ let l = lift(&read(&sd_api(), &s).unwrap(), &s);+ assert_eq!(l.flow.out, vec!["n8"]);+ let st = &l.flow.steps["n8"];+ assert_eq!(st.op, "image.generate");+ assert_eq!(st.inputs["prompt"], "a lighthouse in fog");+ assert_eq!(st.inputs["negative"], "blurry");+ assert_eq!(st.inputs["weights"], "sd_xl_base_1.0.safetensors");+ assert_eq!(st.inputs["loras"][0]["name"], "ink.safetensors");+ assert_eq!((st.inputs["width"].as_u64(), st.inputs["seed"].as_u64()), (Some(1216), Some(7)));+ l.flow.check().unwrap();+}++#[test]+fn weights_route_to_made_unless_exact() {+ let s = schema::load();+ let l = lift(&read(&sd_api(), &s).unwrap(), &s);+ let st = &l.flow.steps["n8"];+ let (b, note) = route(st, &Policy::default()).unwrap();+ assert_eq!(b, Backend::Made("nano_banana_2".into()));+ assert!(note.unwrap().contains("sd_xl_base"));+ assert_eq!(route(st, &Policy { exact: true, ..Default::default() }).unwrap().0, Backend::Comfy);+}++#[test]+fn a_lifted_chain_writes_back_and_lifts_the_same() {+ let s = schema::load();+ let once = lift(&read(&sd_api(), &s).unwrap(), &s).flow;+ let api = write(&once).unwrap();+ let twice = lift(&read(&api, &s).unwrap(), &s).flow;+ assert_eq!(once.steps.values().map(|s| &s.inputs).collect::<Vec<_>>(), twice.steps.values().map(|s| &s.inputs).collect::<Vec<_>>());+}++#[test]+fn unknown_nodes_stay_comfy_with_their_media_bound() {+ let g = json!({+ "1": {"class_type": "LoadImage", "inputs": {"image": "cat.png"}},+ "2": {"class_type": "SomePackFilter", "inputs": {"image": ["1", 0], "amount": 3}},+ "3": {"class_type": "SaveImage", "inputs": {"images": ["2", 0]}},+ });+ let s = schema::load();+ let f = lift(&read(&g, &s).unwrap(), &s).flow;+ let st = &f.steps["n2"];+ assert_eq!(st.op, "comfy");+ assert_eq!(st.inputs["bind"]["2.image"], "@n1");+ assert_eq!(f.steps["n1"].op, "media.load");+ // written back, the bound input is a link to the load again+ let api = write(&f).unwrap();+ assert_eq!(api["n2.2"]["inputs"]["image"], json!(["n1", 0]));+}++#[test]+fn partner_nodes_become_made_steps() {+ let g = json!({+ "1": {"class_type": "LoadImage", "inputs": {"image": "a.png"}},+ "2": {"class_type": "KlingFirstLastFrameNode", "inputs": {"prompt": "a slow push in", "duration": 5, "first_frame": ["1", 0], "end_frame": ["1", 0], "generate_audio": false, "model": "kling-v3", "model.resolution": "1080p", "seed": 1}},+ "3": {"class_type": "SaveVideo", "inputs": {"video": ["2", 0]}},+ });+ let s = schema::load();+ let f = lift(&read(&g, &s).unwrap(), &s).flow;+ let st = &f.steps["n2"];+ assert_eq!((st.op.as_str(), st.model.as_deref()), ("video.generate", Some("made:kling_3_pro")));+ assert_eq!((st.inputs["start_image"].as_str(), st.inputs["end_image"].as_str(), st.inputs["seconds"].as_u64()), (Some("@n1"), Some("@n1"), Some(5)));+ f.check().unwrap();+}++#[test]+fn ui_widgets_are_named_and_subgraphs_inlined() {+ // a UI-format save: a subgraph holding the prompt encode, a reroute, a muted note+ let ui = json!({+ "nodes": [+ {"id": 4, "type": "CheckpointLoaderSimple", "mode": 0, "inputs": [], "outputs": [{"type": "MODEL"}, {"type": "CLIP"}, {"type": "VAE"}], "widgets_values": ["flux1-dev.safetensors"]},+ {"id": 20, "type": "sub-1", "mode": 0, "inputs": [{"name": "clip", "type": "CLIP", "link": 1}], "outputs": [{"type": "CONDITIONING"}], "widgets_values": []},+ {"id": 5, "type": "EmptyLatentImage", "mode": 0, "inputs": [], "widgets_values": [512, 768, 1]},+ {"id": 3, "type": "KSampler", "mode": 0, "inputs": [{"name": "model", "link": 2}, {"name": "positive", "link": 3}, {"name": "negative", "link": 3}, {"name": "latent_image", "link": 4}], "widgets_values": [42, "randomize", 20, 3.5, "euler", "simple", 1.0]},+ {"id": 8, "type": "VAEDecode", "mode": 0, "inputs": [{"name": "samples", "link": 5}, {"name": "vae", "link": 6}], "widgets_values": []},+ {"id": 30, "type": "Reroute", "mode": 0, "inputs": [{"name": "", "link": 7}], "widgets_values": []},+ {"id": 9, "type": "SaveImage", "mode": 0, "inputs": [{"name": "images", "link": 8}], "widgets_values": ["out"]},+ {"id": 11, "type": "Note", "mode": 0, "inputs": [], "widgets_values": ["hello"]}+ ],+ "links": [[1, 4, 1, 20, 0, "CLIP"], [2, 4, 0, 3, 0, "MODEL"], [3, 20, 0, 3, 1, "CONDITIONING"], [4, 5, 0, 3, 3, "LATENT"], [5, 3, 0, 8, 0, "LATENT"], [6, 4, 2, 8, 1, "VAE"], [7, 8, 0, 30, 0, "IMAGE"], [8, 30, 0, 9, 0, "IMAGE"]],+ "definitions": {"subgraphs": [{+ "id": "sub-1", "inputs": [{"name": "clip", "type": "CLIP"}], "outputs": [{"name": "CONDITIONING"}],+ "nodes": [{"id": 1, "type": "CLIPTextEncode", "mode": 0, "inputs": [{"name": "clip", "link": 10}], "widgets_values": ["a red kite"]}],+ "links": [{"id": 10, "origin_id": -10, "origin_slot": 0, "target_id": 1, "target_slot": 0}, {"id": 11, "origin_id": 1, "origin_slot": 0, "target_id": -20, "target_slot": 0}]+ }]}+ });+ let s = schema::load();+ let g = read(&ui, &s).unwrap();+ assert_eq!(g["3"].inputs["steps"], 20);+ assert_eq!(g["20:1"].inputs["clip"], json!(["4", 1]));+ assert_eq!(g["3"].inputs["positive"], json!(["20:1", 0]));+ assert_eq!(g["9"].inputs["images"], json!(["8", 0]));+ assert!(!g.contains_key("11"));+ let f = lift(&g, &s).flow;+ assert_eq!(f.steps["n8"].inputs["prompt"], "a red kite");+ assert_eq!(f.steps["n8"].inputs["cfg"], 3.5);+}++#[test]+fn keys_change_with_what_a_step_reads() {+ let mut f = Flow::default();+ f.steps.insert("a".into(), Step::new("image.generate", json!({"prompt": "one"})));+ f.steps.insert("b".into(), Step::new("image.upscale", json!({"image": "@a"})));+ f.out = vec!["b".into()];+ let k1 = f.keys().unwrap();+ f.steps.get_mut("a").unwrap().inputs.insert("prompt".into(), json!("two"));+ let k2 = f.keys().unwrap();+ assert_ne!(k1["a"], k2["a"]);+ assert_ne!(k1["b"], k2["b"]);+ assert_eq!(Flow::parse(&f.to_json()).unwrap(), f);+}++#[test]+fn made_bodies_fit_the_model() {+ let model = json!({"id": "kling_3_pro_i2v", "durations": [3, 4, 5, 10], "mediaRoles": {"start_image": "x", "end_image": "y"}, "allowedParams": ["negative_prompt"], "inputMap": {"audio": {}}});+ let s = Step::new("video.generate", json!({"prompt": "push in", "seconds": 6.2, "start_image": "@a", "seed": 3, "negative": "blur"}));+ let (b, notes) = crate::route::made_body(&s, &model, &|_| Ok("job_1".into())).unwrap();+ assert_eq!(b["duration"], 5);+ assert_eq!(b["medias"], json!([{"value": "job_1", "role": "start_image"}]));+ assert_eq!(b["negative_prompt"], "blur");+ assert!(b.get("seed").is_none() && notes.iter().any(|n| n.contains("seed")));+}++struct FakeLocal;++impl crate::run::Local for FakeLocal {+ fn names(&self) -> Vec<String> {+ vec!["sao".into()]+ }+ fn make(&self, name: &str, step: &Step, dir: &std::path::Path, key: &str) -> Result<std::path::PathBuf, String> {+ let f = dir.join(format!("{key}.wav"));+ std::fs::write(&f, format!("{name}:{}", step.inputs["prompt"].as_str().unwrap_or(""))).map_err(|e| e.to_string())?;+ Ok(f)+ }+}++#[test]+fn local_models_run_and_cache() {+ let dir = std::env::temp_dir().join(format!("raea-gen-test-{}", std::process::id()));+ let mut f = Flow::default();+ f.steps.insert("rain".into(), Step::new("audio.sfx", json!({"prompt": "rain on a tin roof", "seconds": 3})));+ f.out = vec!["rain".into()];+ let local = FakeLocal;+ let mut r = crate::run::Run::new(dir.clone(), dir.clone());+ r.policy.local = local.names();+ r.local = Some(&local);+ let out = r.run(&f).unwrap();+ assert_eq!(out["steps"][0]["runs_on"], "local:sao");+ let file = out["out"]["rain"][0].as_str().unwrap().to_string();+ assert_eq!(std::fs::read_to_string(&file).unwrap(), "sao:rain on a tin roof");+ // the second run finds it by key+ assert_eq!(r.run(&f).unwrap()["steps"][0]["cached"], true);+ // without the host's sao, effects go to made+ assert_eq!(route(&f.steps["rain"], &Policy::default()).unwrap().0, Backend::Made("elevenlabs_sound_effects_v2".into()));+ let _ = std::fs::remove_dir_all(dir);+}++#[test]+fn made_requests_map_to_fal_fields() {+ let model = json!({"id": "kling_3_pro_i2v", "provider": "fal", "workflowId": "fal-ai/kling-video/v3/pro/image-to-video",+ "mediaRoles": {"start_image": "start_image_url", "end_image": "end_image_url"},+ "inputMap": {"audio": {"field": "generate_audio"}, "duration": {"stringify": true}, "aspect_ratio": {"drop": true}},+ "providerParams": {"cfg_scale": 0.5}});+ let made = json!({"model": "kling_3_pro_i2v", "prompt": "push in", "duration": 5, "audio": false, "aspect_ratio": "16:9",+ "medias": [{"value": "https://x/a.png", "role": "start_image"}], "request_id": "r", "max_cost_cents": 9});+ let (endpoint, body) = crate::direct::body(&model, &made).unwrap();+ assert_eq!(endpoint, "fal-ai/kling-video/v3/pro/image-to-video");+ assert_eq!(body, json!({"prompt": "push in", "duration": "5", "generate_audio": false, "start_image_url": "https://x/a.png", "cfg_scale": 0.5}));+ // list fields collect every media of their role; an edit endpoint is used when there's media+ let nb = json!({"id": "nano_banana_2", "provider": "fal", "workflowId": "fal-ai/nano-banana-2", "editWorkflowId": "fal-ai/nano-banana-2/edit", "mediaRoles": {"image": "image_urls[]"}});+ let (e, b) = crate::direct::body(&nb, &json!({"model": "nano_banana_2", "prompt": "p", "medias": [{"value": "u1", "role": "image"}, {"value": "u2", "role": "image"}]})).unwrap();+ assert_eq!((e.as_str(), &b["image_urls"]), ("fal-ai/nano-banana-2/edit", &json!(["u1", "u2"])));+ assert!(!crate::direct::possible(&json!({"provider": "reapi", "workflowId": "x"})));+}++#[test]+fn partner_3d_and_chat_nodes_route_to_fal_and_openrouter() {+ let g = json!({+ "1": {"class_type": "LoadImage", "inputs": {"image": "toy.png"}},+ "2": {"class_type": "TripoImageToModelNode", "inputs": {"image": ["1", 0], "seed": 3}},+ "3": {"class_type": "SaveGLB", "inputs": {"mesh": ["2", 0]}},+ "4": {"class_type": "ClaudeNode", "inputs": {"prompt": "describe a toy"}},+ "5": {"class_type": "PreviewAny", "inputs": {"source": ["4", 0]}},+ "6": {"class_type": "SaveText", "inputs": {"text": ["4", 0]}},+ });+ let s = schema::load();+ let f = lift(&read(&g, &s).unwrap(), &s).flow;+ assert_eq!((f.steps["n2"].op.as_str(), f.steps["n2"].model.as_deref()), ("mesh.generate", Some("fal:tripo3d/h3.1/image-to-3d")));+ assert_eq!(f.steps["n2"].inputs["image"], "@n1");+ assert_eq!(f.steps["n4"].op, "text.generate");+ assert!(f.steps["n4"].model.as_deref().unwrap().starts_with("openrouter:"));+ f.check().unwrap();+}++#[test]+fn text_steps_feed_prompts_by_reference() {+ let mut f = Flow::default();+ f.steps.insert("idea".into(), Step::new("text.generate", json!({"prompt": "write a prompt"})));+ f.steps.insert("pic".into(), Step::new("image.generate", json!({"prompt": "@idea"})));+ f.out = vec!["pic".into()];+ f.check().unwrap();+ assert_eq!(f.order().unwrap(), vec!["idea", "pic"]);+ assert!(matches!(route(&f.steps["idea"], &Policy::default()).unwrap().0, Backend::OpenRouter(_)));+}++#[test]+fn exported_text_steps_link_their_words() {+ let mut f = Flow::default();+ f.steps.insert("idea".into(), Step::new("text.generate", json!({"prompt": "write a prompt"})));+ f.steps.insert("pic".into(), Step::new("image.generate", json!({"prompt": "@idea"})));+ f.out = vec!["pic".into(), "idea".into()];+ let g = crate::comfy::export(&f).unwrap();+ // RaeaMade's STRING output is slot 4; a text output is shown, not saved as a picture+ assert_eq!(g["pic"]["inputs"]["prompt"], json!(["idea", 4]));+ assert_eq!(g["save1"]["class_type"], "PreviewAny");+}++#[test]+fn image_utilities_lift_run_here_and_export_as_core_nodes() {+ let dir = std::env::temp_dir().join(format!("raea-gen-native-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ image::RgbImage::from_pixel(64, 32, image::Rgb([200, 30, 30])).save(dir.join("red.png")).unwrap();+ image::RgbImage::from_pixel(16, 16, image::Rgb([30, 30, 200])).save(dir.join("blue.png")).unwrap();+ let g = json!({+ "1": {"class_type": "LoadImage", "inputs": {"image": "red.png"}},+ "2": {"class_type": "LoadImage", "inputs": {"image": "blue.png"}},+ "3": {"class_type": "ImageCrop", "inputs": {"image": ["1", 0], "width": 32, "height": 32, "x": 16, "y": 0}},+ "4": {"class_type": "ImageScale", "inputs": {"image": ["2", 0], "upscale_method": "lanczos", "width": 0, "height": 32, "crop": "disabled"}},+ "5": {"class_type": "ImageStitch", "inputs": {"image1": ["3", 0], "image2": ["4", 0], "direction": "right", "match_image_size": true, "spacing_width": 0, "spacing_color": "white"}},+ "6": {"class_type": "SaveImage", "inputs": {"images": ["5", 0], "filename_prefix": "x"}},+ });+ let s = schema::load();+ let f = lift(&read(&g, &s).unwrap(), &s).flow;+ let ops: Vec<&str> = f.order().unwrap().iter().map(|id| f.steps[id].op.as_str()).collect();+ assert!(ops.contains(&"image.crop") && ops.contains(&"image.scale") && ops.contains(&"image.stitch"), "{ops:?}");+ assert!(f.steps.values().all(|s| s.op != "comfy"));+ // no model, no server: raea runs them+ let r = crate::run::Run::new(dir.clone(), dir.clone());+ let out = r.run(&f).unwrap();+ let file = out["out"][&f.out[0]][0].as_str().unwrap().to_string();+ let pic = image::open(&file).unwrap().to_rgb8();+ assert_eq!(pic.dimensions(), (64, 32));+ assert_eq!(pic.get_pixel(5, 5).0, [200, 30, 30]);+ assert_eq!(pic.get_pixel(50, 5).0, [30, 30, 200]);+ // and back out as ComfyUI's own nodes+ let w = write(&f).unwrap();+ let classes: Vec<&str> = w.as_object().unwrap().values().filter_map(|n| n["class_type"].as_str()).collect();+ for c in ["ImageCrop", "ImageScale", "ImageStitch"] {+ assert!(classes.contains(&c), "{classes:?}");+ }+ let _ = std::fs::remove_dir_all(dir);+}++/// A stand-in for Replicate's predictions API on 127.0.0.1: a model's POST starts a prediction, its urls.get answers+/// "processing" once and then "succeeded" with an output URL, which serves a PNG. Every request is kept for asserts.+fn fake_replicate() -> (String, std::sync::Arc<std::sync::Mutex<Vec<String>>>) {+ use std::io::{BufRead, BufReader, Read, Write};+ let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ let base = format!("http://{}", l.local_addr().unwrap());+ let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));+ let (b, s) = (base.clone(), seen.clone());+ let mut png = Vec::new();+ image::RgbImage::from_pixel(8, 8, image::Rgb([10, 200, 10])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();+ std::thread::spawn(move || {+ let mut polls = 0;+ for c in l.incoming().flatten() {+ let mut r = BufReader::new(c.try_clone().unwrap());+ let (mut head, mut line, mut len) = (String::new(), String::new(), 0);+ while r.read_line(&mut line).unwrap_or(0) > 2 {+ if let Some(n) = line.to_ascii_lowercase().strip_prefix("content-length:") { len = n.trim().parse().unwrap_or(0); }+ head += &line;+ line.clear();+ }+ let mut body = vec![0; len];+ r.read_exact(&mut body).unwrap();+ let first = head.lines().next().unwrap_or("").to_string();+ s.lock().unwrap().push(format!("{first} {} {}", head.contains("Bearer r8_test"), String::from_utf8_lossy(&body)));+ let (mime, out): (&str, Vec<u8>) = if first.starts_with("POST /v1/models/") {+ ("application/json", json!({"id": "p1", "status": "starting", "urls": {"get": format!("{b}/v1/predictions/p1")}}).to_string().into_bytes())+ } else if first.starts_with("GET /v1/predictions/p1") {+ polls += 1;+ let st = if polls < 2 { json!({"status": "processing", "logs": "50%", "urls": {"get": format!("{b}/v1/predictions/p1")}}) } else { json!({"status": "succeeded", "output": [format!("{b}/out.png")], "urls": {"get": format!("{b}/v1/predictions/p1")}}) };+ ("application/json", st.to_string().into_bytes())+ } else {+ ("image/png", png.clone())+ };+ let mut c = c;+ let _ = write!(c, "HTTP/1.1 200 OK\r\nContent-Type: {mime}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", out.len());+ let _ = c.write_all(&out);+ }+ });+ (base, seen)+}++#[test]+fn replicate_steps_run_through_the_predictions_api() {+ let (base, seen) = fake_replicate();+ // SAFETY: only this test reads these two settings+ unsafe {+ std::env::set_var("REPLICATE_API_TOKEN", "r8_test");+ std::env::set_var("RAEA_REPLICATE_API", format!("{base}/v1"));+ }+ let dir = std::env::temp_dir().join(format!("raea-gen-replicate-{}", std::process::id()));+ let mut f = Flow::default();+ let mut s = Step::new("image.generate", json!({"prompt": "a green square", "x_num_outputs": 1}));+ s.model = Some("replicate:black-forest-labs/flux-schnell".into());+ f.steps.insert("sq".into(), s);+ f.out = vec!["sq".into()];+ let out = crate::run::Run::new(dir.clone(), dir.clone()).run(&f).unwrap();+ assert_eq!(out["steps"][0]["runs_on"], "replicate:black-forest-labs/flux-schnell");+ let pic = image::open(out["out"]["sq"][0].as_str().unwrap()).unwrap().to_rgb8();+ assert_eq!(pic.get_pixel(0, 0).0, [10, 200, 10]);+ let seen = seen.lock().unwrap();+ // created on the model's own route with the token, its input as the step said; polled until it succeeded+ assert!(seen[0].starts_with("POST /v1/models/black-forest-labs/flux-schnell/predictions HTTP/1.1 true"), "{seen:?}");+ assert!(seen[0].contains(r#""prompt":"a green square""#) && seen[0].contains(r#""num_outputs":1"#), "{seen:?}");+ assert_eq!(seen.iter().filter(|r| r.starts_with("GET /v1/predictions/p1")).count(), 2);+ let _ = std::fs::remove_dir_all(dir);+}++#[test]+fn a_batch_reaches_a_model_as_each_of_its_pictures() {+ use std::collections::BTreeMap;+ let mut done = BTreeMap::new();+ done.insert("batch".to_string(), crate::run::Made1 { files: vec!["a.png".into(), "b.png".into()], ..Default::default() });+ done.insert("mesh".to_string(), crate::run::Made1 { files: vec!["m.glb".into(), "t.png".into()], ..Default::default() });+ let s = Step::new("image.edit", json!({"image": "@batch", "refs": ["@mesh", "@batch.1"], "prompt": "x"}));+ let out = crate::run::spread_batches(&s, &done);+ assert_eq!(out.inputs["image"], json!(["@batch.0", "@batch.1"]));+ // a mesh with its textures stays whole; an indexed reference stays as it is+ assert_eq!(out.inputs["refs"], json!(["@mesh", "@batch.1"]));+ assert_eq!(crate::run::file_of(&done, &json!("@batch.1")).unwrap().to_str(), Some("b.png"));+}++#[test]+fn comfy_auto_aspect_fits_what_made_offers() {+ let model = json!({"id": "nano_banana_pro", "aspectRatios": ["match_input_image", "1:1", "16:9", "9:16"], "mediaRoles": {"image": "image_urls[]"}});+ let s = Step::new("image.edit", json!({"image": "@a", "prompt": "x", "aspect_ratio": "auto"}));+ let (b, notes) = crate::route::made_body(&s, &model, &|_| Ok("https://x/a.png".into())).unwrap();+ assert_eq!(b["aspect_ratio"], "match_input_image");+ assert!(notes.iter().any(|n| n.contains("auto")));+ let s = Step::new("image.generate", json!({"prompt": "x", "aspect_ratio": "17:9"}));+ assert_eq!(crate::route::made_body(&s, &model, &|_| Ok(String::new())).unwrap().0["aspect_ratio"], "16:9");+}++#[test]+fn a_workflow_says_the_packs_and_weights_it_needs() {+ // UI format: each node's pack is its properties' registry id (cnr_id) or repo (aux_id); models carry their URLs+ let wf = json!({"nodes": [+ {"id": 1, "type": "LoadImage", "properties": {"cnr_id": "comfy-core"}},+ {"id": 2, "type": "ImageResizeKJv2", "properties": {"cnr_id": "comfyui-kjnodes"}},+ {"id": 3, "type": "FL_PixelSort", "properties": {"aux_id": "filliptm/ComfyUI_Fill-Nodes"}},+ {"id": 4, "type": "LoadBackgroundRemovalModel", "properties": {"models": [{"name": "birefnet.safetensors", "url": "https://huggingface.co/x/birefnet.safetensors", "directory": "background_removal"}]}},+ ], "links": []});+ let mut s = crate::comfy::schema::Schema::new();+ s.insert("LoadImage".into(), Default::default());+ s.insert("LoadBackgroundRemovalModel".into(), Default::default());+ let n = crate::comfy::needs::needs(&wf, &s);+ assert_eq!(n["packs"], json!(["comfyui-kjnodes"]));+ assert_eq!(n["repos"], json!(["https://github.com/filliptm/ComfyUI_Fill-Nodes"]));+ assert_eq!(n["models"][0]["directory"], "background_removal");+ assert_eq!(n["unknown"], json!([]));+}++#[test]+fn a_made_model_fal_also_serves_goes_to_its_twin() {+ let model = json!({"id": "gpt_image_2_5_fast", "provider": "made_batch", "workflowId": "gpt-image-2.5-flare-low"});+ assert!(crate::direct::possible(&model));+ let (e, b) = crate::direct::body(&model, &json!({"model": "gpt_image_2_5_fast", "prompt": "a kite", "aspect_ratio": "16:9"})).unwrap();+ assert_eq!(e, "openai/gpt-image-2.5/flare/text-to-image");+ assert_eq!((b["quality"].as_str(), b["image_size"].as_str()), (Some("low"), Some("landscape_16_9")));+ let (e, b) = crate::direct::body(&model, &json!({"prompt": "edit", "medias": [{"value": "https://x/a.png", "role": "image"}]})).unwrap();+ assert_eq!((e.as_str(), &b["image_urls"]), ("openai/gpt-image-2.5/flare/edit", &json!(["https://x/a.png"])));+}++#[test]+fn a_kept_node_saved_from_several_outputs_gives_each() {+ let g = json!({+ "1": {"class_type": "LoadImage", "inputs": {"image": "a.png"}},+ "2": {"class_type": "SplitterOfSomePack", "inputs": {"image": ["1", 0]}},+ "3": {"class_type": "SaveImage", "inputs": {"images": ["2", 0], "filename_prefix": "a"}},+ "4": {"class_type": "SaveImage", "inputs": {"images": ["2", 2], "filename_prefix": "b"}},+ });+ let s = schema::load();+ let f = lift(&read(&g, &s).unwrap(), &s).flow;+ let st = f.steps.values().find(|s| s.op == "comfy").unwrap();+ assert_eq!(st.inputs["slots"], json!([0, 2]));+ assert_eq!(f.out.len(), 1);+ let w = write(&f).unwrap();+ // one Save per slot, in order, which the runner fetches as the step's files (@step.0, @step.1)+ let src = |save: &str| w[save]["inputs"]["images"].clone();+ assert_eq!(src("save0")[1], json!(0));+ assert_eq!(src("save0.1")[1], json!(2));+}++/// fish:<model> against a stand-in for Fish's /v1/tts: the key, the model header and the step's words, voice and speed+/// as Fish reads them, an MP3 kept, its bytes' price quoted in the plan and charged in the run.+#[test]+fn fish_speech_steps_send_the_users_key_and_words() {+ use std::io::{BufRead, BufReader, Read, Write};+ let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ let base = format!("http://{}", l.local_addr().unwrap());+ let seen = std::sync::Arc::new(std::sync::Mutex::new(String::new()));+ let s2 = seen.clone();+ std::thread::spawn(move || {+ for c in l.incoming().flatten() {+ let mut r = BufReader::new(c.try_clone().unwrap());+ let (mut head, mut line, mut len) = (String::new(), String::new(), 0);+ while r.read_line(&mut line).unwrap_or(0) > 2 {+ if let Some(n) = line.to_ascii_lowercase().strip_prefix("content-length:") { len = n.trim().parse().unwrap_or(0); }+ head += &line;+ line.clear();+ }+ let mut body = vec![0; len];+ r.read_exact(&mut body).unwrap();+ *s2.lock().unwrap() = format!("{head}{}", String::from_utf8_lossy(&body));+ let mp3 = b"ID3fake-mp3";+ let mut c = c;+ let _ = write!(c, "HTTP/1.1 200 OK\r\nContent-Type: audio/mpeg\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", mp3.len());+ let _ = c.write_all(mp3);+ }+ });+ // SAFETY: only this test reads these two settings+ unsafe {+ std::env::set_var("FISH_API_KEY", "fish_test");+ std::env::set_var("RAEA_FISH_API", &base);+ }+ let dir = std::env::temp_dir().join(format!("raea-gen-fish-{}", std::process::id()));+ let mut f = Flow::default();+ let mut s = Step::new("audio.speech", json!({"text": "Three drops, every morning.", "voice": "abc", "speed": 0.9}));+ s.model = Some("fish:".into());+ f.steps.insert("vo".into(), s);+ f.out = vec!["vo".into()];+ let run = crate::run::Run::new(dir.clone(), dir.clone());+ let plan = run.plan(&f).unwrap();+ assert_eq!((plan["steps"][0]["runs_on"].as_str(), plan["steps"][0]["cents"].as_u64()), (Some("fish:s2.1-pro"), Some(1)), "{plan}");+ let out = run.run(&f).unwrap();+ assert_eq!(std::fs::read(out["out"]["vo"][0].as_str().unwrap()).unwrap(), b"ID3fake-mp3");+ assert_eq!(out["cents"], 1);+ let seen = seen.lock().unwrap().to_ascii_lowercase();+ assert!(seen.starts_with("post /v1/tts ") && seen.contains("authorization: bearer fish_test") && seen.contains("model: s2.1-pro"), "{seen}");+ assert!(seen.contains(r#""text":"three drops, every morning.""#) && seen.contains(r#""reference_id":"abc""#) && seen.contains(r#""prosody":{"speed":0.9}"#), "{seen}");+ let _ = std::fs::remove_dir_all(dir);+}diff --git a/io/home/src/lib.rs b/io/home/src/lib.rsindex 180e46e0..c5851281 100644--- a/io/home/src/lib.rs+++ b/io/home/src/lib.rs@@ -54,6 +54,27 @@ fn user_dir(apple: &str, xdg: &str, xdg_default: &str, windows: &str) -> Option<Some(base.join("raea"))}+/// A path an environment variable names, else `under_home` in the founder's home folder: RAEA_GEN_CACHE's+/// ~/.cache/raea-gen, RAEA_ENV_FILE's ~/.raea/env. An empty variable counts as unset.+pub fn env_path(var: &str, under_home: &str) -> std::path::PathBuf {+ match std::env::var_os(var).filter(|v| !v.is_empty()) {+ Some(p) => p.into(),+ None => std::path::PathBuf::from(std::env::var_os("HOME").unwrap_or_default()).join(under_home),+ }+}++/// A setting: the process environment first, then raea's settings file ($RAEA_ENV_FILE, else ~/.raea/env), where a+/// line is NAME=value (quotes around the value dropped) and a line starting with # is a comment. Empty is unset.+pub fn setting(name: &str) -> Option<String> {+ if let Some(v) = std::env::var(name).ok().filter(|v| !v.trim().is_empty()) {+ return Some(v.trim().to_string());+ }+ std::fs::read_to_string(env_path("RAEA_ENV_FILE", ".raea/env")).ok()?.lines().find_map(|l| {+ let (k, v) = l.trim().split_once('=')?;+ (k.trim() == name && !l.trim_start().starts_with('#')).then(|| v.trim().trim_matches('"').to_string())+ }).filter(|v| !v.is_empty())+}+/// A local file as a page's `src` (an <img>, a page's snapshot): its path on Unix; on Windows a file URL, since the/// page reads `C:\...` as a URL whose scheme is `c` and loads nothing (PT20). A verbatim `\\?\C:\` path loses its/// prefix first.@@ -96,3 +117,48 @@ mod tests {}}}++/// RAEA_OFFLINE (in the environment, or set in raea's settings file, $RAEA_ENV_FILE else ~/.raea/env): raea sends+/// nothing over the network. Every outbound call asks this first, so set, a fetch, a model download, a sample library, a+/// composition's own fetch() or WebSocket, a generation step or a signing request is refused instead, saying what wanted+/// out; what's already on disk (raea's caches, installed models) still works. "0" or empty is off.+pub fn offline(what: &str) -> Result<(), String> {+ let on = |v: &str| !v.trim().is_empty() && v.trim() != "0";+ let set = match std::env::var("RAEA_OFFLINE") {+ Ok(v) => on(&v),+ Err(_) => {+ let file = std::env::var_os("RAEA_ENV_FILE").map(std::path::PathBuf::from).or_else(|| std::env::var_os("HOME").map(|h| std::path::PathBuf::from(h).join(".raea/env")));+ file.and_then(|f| std::fs::read_to_string(f).ok()).is_some_and(|s| {+ s.lines().filter(|l| !l.trim_start().starts_with('#')).filter_map(|l| l.split_once('=')).any(|(k, v)| k.trim() == "RAEA_OFFLINE" && on(v.trim().trim_matches('"')))+ })+ }+ };+ if set { Err(format!("{what}: not sent, because RAEA_OFFLINE is set (raea makes no network requests)")) } else { Ok(()) }+}++#[cfg(test)]+mod offline_tests {+ // the only test that touches RAEA_OFFLINE and RAEA_ENV_FILE in this crate+ #[test]+ fn offline_is_read_from_the_environment_then_the_settings_file() {+ let file = std::env::temp_dir().join(format!("raea-offline-{}.env", std::process::id()));+ // SAFETY: no other test in this crate reads these+ unsafe {+ std::env::remove_var("RAEA_OFFLINE");+ std::env::set_var("RAEA_ENV_FILE", &file);+ }+ assert!(super::offline("x").is_ok(), "no file, no variable: online");+ std::fs::write(&file, "# RAEA_OFFLINE=1\nRAEA_OFFLINE=1\n").unwrap();+ let e = super::offline("the sao model").unwrap_err();+ assert!(e.starts_with("the sao model: not sent") && e.contains("RAEA_OFFLINE"), "{e}");+ unsafe { std::env::set_var("RAEA_OFFLINE", "0") };+ assert!(super::offline("x").is_ok(), "the environment's 0 wins over the file");+ unsafe { std::env::set_var("RAEA_OFFLINE", "1") };+ assert!(super::offline("x").is_err());+ unsafe {+ std::env::remove_var("RAEA_OFFLINE");+ std::env::remove_var("RAEA_ENV_FILE");+ }+ let _ = std::fs::remove_file(&file);+ }+}diff --git a/io/net/src/cache.rs b/io/net/src/cache.rsindex 0f123d62..a3508de6 100644--- a/io/net/src/cache.rs+++ b/io/net/src/cache.rs@@ -36,9 +36,7 @@ pub fn fetch(url: &str) -> Result<PathBuf, String> {if path.metadata().is_ok_and(|m| m.is_file() && m.len() > 0) {return Ok(named(path));}- if std::env::var_os("RAEA_OFFLINE").is_some() {- return Err(format!("{url}: not cached, and RAEA_OFFLINE is set"));- }+ raea_io_home::offline(&format!("{url} (not in raea's cache)"))?;let agent = ureq::AgentBuilder::new().redirects(10).timeout(Duration::from_secs(300)).build();let r = agent.get(url).set("User-Agent", if google { CHROME_UA } else { PLAIN_UA }).call().map_err(|e| format!("{url}: {e}"))?;let mut bytes = Vec::new();diff --git a/io/net/src/http.rs b/io/net/src/http.rsindex adf2c6a8..736e130d 100644--- a/io/net/src/http.rs+++ b/io/net/src/http.rs@@ -30,6 +30,7 @@ pub fn headers(resp: &ureq::Response) -> Vec<(String, String)> {/// The page's net.fetch, made on the calling thread.pub fn fetch(args: &Value) -> Result<Value, String> {let url = args["url"].as_str().ok_or("no url")?;+ raea_io_home::offline(&format!("fetch {url}"))?;let method = args["method"].as_str().unwrap_or("GET");let follow = args["redirect"].as_str().unwrap_or("follow") == "follow";let agent = ureq::AgentBuilder::new().redirects(if follow { 20 } else { 0 }).timeout(Duration::from_secs(300)).build();diff --git a/io/net/src/ws.rs b/io/net/src/ws.rsindex 789e4c6b..2c9deef5 100644--- a/io/net/src/ws.rs+++ b/io/net/src/ws.rs@@ -21,6 +21,10 @@ pub enum Cmd {/// The socket `args` {url, protocols} opens, run until it closes or `rx` hangs up.pub fn run(args: &Value, rx: Receiver<Cmd>, tell: &dyn Fn(Value)) {let fail = || tell(json!({"ev": "close", "code": 1006, "reason": "", "clean": false, "error": true}));+ if let Err(e) = raea_io_home::offline(&format!("WebSocket {}", args["url"].as_str().unwrap_or(""))) {+ eprintln!("{e}");+ return fail();+ }let Some(mut req) = args["url"].as_str().and_then(|u| u.into_client_request().ok()) else { return fail() };let protos: Vec<String> = args["protocols"].as_array().into_iter().flatten().filter_map(|p| p.as_str().map(String::from)).collect();if !protos.is_empty()diff --git a/io/npm/Cargo.toml b/io/npm/Cargo.tomlindex d045e670..e848bab4 100644--- a/io/npm/Cargo.toml+++ b/io/npm/Cargo.toml@@ -6,6 +6,7 @@ description = "A project's npm dependencies installed without Node: resolved bylicense = "FSL-1.1-ALv2"[dependencies]+raea-io-home = { path = "../../io/home" }# Deno's npm resolver and semver, on their own: no deno_core, no V8 (raea's V8 runs what's installed)deno_npm = "0.72"deno_semver = "0.10"diff --git a/io/npm/src/lib.rs b/io/npm/src/lib.rsindex 47a8a0f8..4e00f4fe 100644--- a/io/npm/src/lib.rs+++ b/io/npm/src/lib.rs@@ -143,6 +143,8 @@ pub fn remove(root: &Path, names: &[String]) -> R<Report> {/// Makes the project's node_modules what its package.json says: resolved against raea.lock (the registry asked only for/// what the lock doesn't have), fetched into the store, laid out, and the lock written.pub fn install(root: &Path, offline: bool) -> R<Report> {+ // RAEA_OFFLINE: the packages raea already has, as --offline+ let offline = offline || raea_io_home::offline("npm").is_err();let pj = PackageJson::read(root)?;let mut warnings = Vec::new();let mut deps: Vec<(String, PackageReq)> = Vec::new();diff --git a/io/shell/Cargo.toml b/io/shell/Cargo.tomlindex 12eba035..22639520 100644--- a/io/shell/Cargo.toml+++ b/io/shell/Cargo.toml@@ -12,6 +12,7 @@ default = ["net"]net = ["dep:raea-io-net", "dep:url"][dependencies]+raea-io-home = { path = "../../io/home" }raea-core-calls = { path = "../../core/calls" }serde_json = "1"sha2 = "0.10"diff --git a/io/shell/src/net.rs b/io/shell/src/net.rsindex aae9f596..fa751e84 100644--- a/io/shell/src/net.rs+++ b/io/shell/src/net.rs@@ -125,6 +125,7 @@ fn fetch(v: &Value) -> R<Value> {None => None,};let given: Vec<(String, String)> = v.get("headers").and_then(Value::as_object).map(|h| h.iter().filter_map(|(k, v)| v.as_str().map(|v| (k.to_ascii_lowercase(), v.to_string()))).collect()).unwrap_or_default();+ raea_io_home::offline("the shell's network request")?;let agent = raea_io_net::ureq::AgentBuilder::new().redirects(0).timeout(std::time::Duration::from_millis(timeout)).build();let mut chain = Vec::new();loop {diff --git a/runtime/bundle/src/fresh.rs b/runtime/bundle/src/fresh.rsindex ad12893d..6ba4dab0 100644--- a/runtime/bundle/src/fresh.rs+++ b/runtime/bundle/src/fresh.rs@@ -4,10 +4,17 @@ use super::*;/// resolution on top (raea-bundle's script.rs: the SDK from its source, the test API, raea-runtime-react's node_modules as the/// fallback); its default export, if a function, is called and awaited, then the run ends.pub fn bundle_script(ts: &Path, out: &Path) -> R<()> {- let entry = format!(- "import * as M from {:?};\nconst call = (globalThis as any).__raea_call;\nPromise.resolve().then(() => (typeof (M as any).default === \"function\" ? (M as any).default() : undefined)).then(() => call(\"done\", JSON.stringify({{ code: 0 }})), (e: any) => {{ call(\"print\", JSON.stringify({{ text: \"error: \" + (e && e.stack ? e.stack : String(e)) }})); call(\"done\", JSON.stringify({{ code: 1 }})); }});\n",- spec(ts)- );+ bundle_module(ts, out, "Promise.resolve().then(() => (typeof (M as any).default === \"function\" ? (M as any).default() : undefined)).then(() => call(\"done\", JSON.stringify({ code: 0 })), (e: any) => { call(\"print\", JSON.stringify({ text: \"error: \" + (e && e.stack ? e.stack : String(e)) })); call(\"done\", JSON.stringify({ code: 1 })); });")+}++/// What a spec's run does (brief.ts, script.ts, taste.ts, a controller: docs/projects.feature PJ0), for bundle_module:+/// it prints the module's default export as one line of JSON and ends, or prints the error and exits 1. The reader is+/// engine/cli spec.rs.+pub const PRINT_DEFAULT: &str = "try { const v = (M as any).default; if (v === undefined) throw new Error(\"it has no default export\"); call(\"print\", JSON.stringify({ text: JSON.stringify(v) })); call(\"done\", JSON.stringify({ code: 0 })); } catch (e: any) { call(\"print\", JSON.stringify({ text: \"error: \" + (e && e.message ? e.message : String(e)) })); call(\"done\", JSON.stringify({ code: 1 })); }";++/// An entry that imports the module as M, with the engine's `call`, then runs `body` (PRINT_DEFAULT for a spec).+pub fn bundle_module(ts: &Path, out: &Path, body: &str) -> R<()> {+ let entry = format!("import * as M from {:?};\nconst call = (globalThis as any).__raea_call;\n{body}\n", spec(ts));bundle_entry(&entry, out, &[])}@@ -226,9 +233,12 @@ pub fn bundle_fresh(tsx: &Path, out_js: &Path, o: &CompOpts, portable: Option<&P}let to_motion = format!("{}motion", "../".repeat(rel.components().count()));let from_dir = dir.join(rel.parent().unwrap_or(Path::new("")));- let text = point_outside(&std::fs::read_to_string(&p).map_err(|e| e.to_string())?, &from_dir, &Path::new("src").join(rel.parent().unwrap_or(Path::new(""))), &dir, &outs);+ // compared with the file as it was: one whose only change is an outside import pointed at its copy (a helper+ // importing ../floors/generate and nothing of the SDK) is written too+ let was = std::fs::read_to_string(&p).map_err(|e| e.to_string())?;+ let text = point_outside(&was, &from_dir, &Path::new("src").join(rel.parent().unwrap_or(Path::new(""))), &dir, &outs);let rewritten = rewrite_into(&text, &from_dir, &motion_src, &to_motion, portable).map_err(|e| format!("{}: {e}", rel.display()))?;- if rewritten != text {+ if rewritten != was {std::fs::write(&p, rewritten).map_err(|e| e.to_string())?;}}diff --git a/runtime/bundle/src/rewrite.rs b/runtime/bundle/src/rewrite.rsindex 46318b2f..798920fd 100644--- a/runtime/bundle/src/rewrite.rs+++ b/runtime/bundle/src/rewrite.rs@@ -28,7 +28,7 @@ pub const MEDIA_EXTS: [&str; 10] = ["mp4", "mov", "m4v", "mp3", "wav", "m4a", "p/// statements, so an import over several lines is rewritten too. With `portable` a folder, imported media is copied/// into its media/ and named `media/<file>`, so the bundle and that folder travel together (to the iPhone).pub fn rewrite_into(src: &str, from_dir: &Path, motion_src: &Path, to_motion: &str, portable: Option<&Path>) -> R<String> {- // `export ... from` too: a package re-exporting the umbrella (tone.tsx's sao, lyria and fish) was left external+ // `export ... from` too: a package re-exporting the umbrella (tone.tsx's sao and lyria) was left externallet re = regex::Regex::new(r#"(?s)\b(?:(import)\s+([^;'"]*?)|(export)\s+((?:\*|\{|type\s*\{)[^;'"]*?))\s+from\s+(["'])([^"']+)["']"#).unwrap();let mut out = String::new();let mut last = 0;@@ -43,7 +43,8 @@ pub fn rewrite_into(src: &str, from_dir: &Path, motion_src: &Path, to_motion: &slet ext = Path::new(spec).extension().and_then(|x| x.to_str()).unwrap_or("").to_lowercase();let local = spec.starts_with('.') || spec.starts_with('/');if kw == "import" && MEDIA_EXTS.contains(&ext.as_str()) && local {- let path = from_dir.join(spec);+ // "/media/x" is the project's (its media/, then assets/: S5a), anything else beside the edit+ let path = if spec.starts_with("/media/") { raea_core_scene::media_path(from_dir, spec) } else { from_dir.join(spec) };if !path.exists() {return Err(format!("line {line}: {spec} doesn't exist (imported media resolves beside the edit)"));}diff --git a/runtime/bundle/src/tests.rs b/runtime/bundle/src/tests.rsindex fa18bcfe..f0abf842 100644--- a/runtime/bundle/src/tests.rs+++ b/runtime/bundle/src/tests.rs@@ -5,13 +5,13 @@ use super::*;fn rewrite_into_points_imports_and_re_exports_at_the_copies() {// the SDK's names resolve through the tree's sdk/tsconfig.base.jsonlet m = &raea_io_home::home().join("sdk/raea/src");- let src = "import { a } from \"raea\";\nimport { useCurrentFrame } from \"raea/clock\";\nimport { Clock } from \"@raea/app/clock\";\nexport { sao, fish } from \"raea/asset\";\nexport * from \"raea/video\";\nexport type { T } from \"raea/native-calls\";\nexport default 1\nimport b from \"raea\";\nexport function f() { return \"from\"; }\n";+ let src = "import { a } from \"raea\";\nimport { useCurrentFrame } from \"raea/clock\";\nimport { Clock } from \"@raea/app/clock\";\nexport { sao, lyria } from \"raea/asset\";\nexport * from \"raea/video\";\nexport type { T } from \"raea/native-calls\";\nexport default 1\nimport b from \"raea\";\nexport function f() { return \"from\"; }\n";let out = rewrite_into(src, Path::new("/nowhere/app"), m, "../motion", None).unwrap();assert!(out.contains("import { a } from \"../motion/prelude\""));// a module whose code moved into a package is that package's copy, beside motion/assert!(out.contains("import { useCurrentFrame } from \"../app/clock\""));assert!(out.contains("import { Clock } from \"../app/clock\""));- assert!(out.contains("export { sao, fish } from \"../motion/asset\""));+ assert!(out.contains("export { sao, lyria } from \"../motion/asset\""));assert!(out.contains("export * from \"../motion/video\""));assert!(out.contains("export type { T } from \"../motion/native-calls\""));// an `export default` with no semicolon isn't swallowed into the import after itdiff --git a/runtime/calls/Cargo.toml b/runtime/calls/Cargo.tomlindex 765c1fc5..285635e3 100644--- a/runtime/calls/Cargo.toml+++ b/runtime/calls/Cargo.toml@@ -14,6 +14,7 @@ ml = ["dep:raea-sys-ml", "dep:raea-sys-speech"]raea-runtime-plugins = { path = "../plugins" }raea-native = { path = "../../engine/native", default-features = false }raea-core-shape = { path = "../../core/shape" }+raea-core-scene = { path = "../../core/scene" }raea-io-media = { path = "../../io/media", default-features = false, features = ["soft-audio", "apple"] }raea-io-net = { path = "../../io/net" }raea-sys-mix = { path = "../../systems/mix" }diff --git a/runtime/calls/src/ml.rs b/runtime/calls/src/ml.rsindex 5b267169..c8920f46 100644--- a/runtime/calls/src/ml.rs+++ b/runtime/calls/src/ml.rs@@ -50,7 +50,8 @@ fn resolve(src: &str) -> R<PathBuf> {if let Some(rest) = src.strip_prefix("/media/") {let dir = dir.ok_or("no composition is open, so /media/ has no folder")?;let rest = rest.split('/').map(|s| raea_io_net::percent_decode_str(s)).collect::<Vec<_>>().join("/");- return Ok(dir.join("media").join(rest));+ // the project's media/, then its assets/ (S5a)+ return Ok(raea_core_scene::media_path(&dir, &format!("/media/{rest}")));}let p = PathBuf::from(src);if p.is_absolute() {diff --git a/runtime/dom/src/computed.rs b/runtime/dom/src/computed.rsindex cb20b53e..76a68fca 100644--- a/runtime/dom/src/computed.rs+++ b/runtime/dom/src/computed.rs@@ -3,7 +3,7 @@//! document restyled and laid out, as a browser flushes style and layout for getComputedStyle, then each property's//! resolved value is read off the element (blitz-dom's resolved_style_value: used values for sizes, margins, insets//! and transforms). sdk/ui asks it for every wired element of an HTML page; its own cascade answers only where the host-//! has none (an unwired element, a call outside a step).+//! has none (an unwired element, a call outside a step). `layout.now` is the same flush for a box script reads.use bevy::prelude::*;use serde_json::{Map, Value};@@ -11,9 +11,27 @@ use serde_json::{Map, Value};use crate::host::PageSync;use raea_sys_page::ops;-/// Registers `style.computed`: `{id, names}` (a wire id, kebab-case names) to `{name: value}`.+/// Registers `style.computed`: `{id, names}` (a wire id, kebab-case names) to `{name: value}`; and `layout.now`.pub fn register() {raea_runtime_js::calls::on_sync_ctx("style.computed", computed);+ raea_runtime_js::calls::on_sync_ctx("layout.now", layout_now);+}++/// `layout.now`: the page laid out as its JS wrote it so far, and its snapshot (what the next `__ui_layout` would+/// give), as a browser lays out when script reads a box it changed. sdk/ui asks when an element it placed has no box+/// yet: Excalidraw sizes its opacity slider's label from the input's offsetWidth in the effect after it mounts.+fn layout_now(ctx: &mut dyn std::any::Any, _args: &Value) -> Result<Value, String> {+ let p = ctx.downcast_mut::<PageSync>().ok_or("layout.now: not a page's call")?;+ let at = {+ let w = p.world();+ w.resource::<raea_sys_page::PageClock>().0.unwrap_or_else(|| w.resource::<Time>().elapsed_secs_f64())+ };+ p.commit();+ let nodes = p.nodes() as *const raea_sys_page::ops::Nodes;+ let doc = p.doc().ok_or("layout.now: the page has no document")?;+ doc.resolve(at);+ // (the ids and the document are separate borrows of what the JS call lent)+ Ok(Value::String(crate::host::snapshot(doc, unsafe { &*nodes })))}fn computed(ctx: &mut dyn std::any::Any, args: &Value) -> Result<Value, String> {diff --git a/runtime/dom/src/host/bridge.rs b/runtime/dom/src/host/bridge.rsindex 92d14060..d1409fef 100644--- a/runtime/dom/src/host/bridge.rs+++ b/runtime/dom/src/host/bridge.rs@@ -197,7 +197,14 @@ impl EventHandler for Bridge<'_> {(DomEventData::PointerDown(p) | DomEventData::PointerUp(p) | DomEventData::PointerMove(p), Some((id, n))) => {// a press's count on its release too: sdk/ui gives click and dblclick their detail from itlet detail = if matches!(ev, Ev::PointerDown | Ev::PointerUp) { self.clicks } else { 0 };- wire::event(id, ev, pointer_json(p, d.get_client_bounding_rect(n), detail))+ let mut payload = pointer_json(p, d.get_client_bounding_rect(n), detail);+ // the deepest element sdk/ui knows on Blitz's hit path: Stylo's pointer-events and z-order decided it, as+ // Chrome's would (sdk/ui's own walk sees only inline styles and Tailwind classes, so a stylesheet's+ // `pointer-events: none` layer over the page, Excalidraw's SVGLayer, took every release and no click came)+ if let Some(target) = path.iter().find_map(|n| self.nodes.id_of(*n)) {+ payload["target"] = json!(target);+ }+ wire::event(id, ev, payload)}(DomEventData::PointerEnter(_) | DomEventData::PointerLeave(_), Some((id, _))) => wire::event(id, ev, Value::Null),(DomEventData::Wheel(w), Some((id, n))) => {diff --git a/runtime/dom/src/host/elements.rs b/runtime/dom/src/host/elements.rsindex dff1ba2d..7d0b1200 100644--- a/runtime/dom/src/host/elements.rs+++ b/runtime/dom/src/host/elements.rs@@ -180,6 +180,38 @@ impl Plugin for HostPlugin {/// Numbers per element in the layout snapshot (raea_runtime_js::dom::STRIDE: sdk/ui's dom.ts reads the same).pub(crate) const STRIDE: usize = 18;+/// The page's layout as its JS reads it (`__ui_layout`'s argument, and `layout.now`'s answer: computed.rs): per wired+/// element, in page px, id, x, y, w, h, scroll offsets and sizes, padding, border and z (STRIDE numbers).+pub fn snapshot(doc: &BaseDocument, nodes: &Nodes) -> String {+ let vp = doc.viewport().window_size;+ let mut n = String::new();+ let mut num = |v: f32| {+ let x = (v * 100.0).round() / 100.0;+ if x == x.trunc() {+ n.push_str(&format!("{},", x as i64));+ } else {+ n.push_str(&format!("{x},"));+ }+ };+ for (id, node) in &nodes.by_id {+ // (text nodes have no layout data of their own to ask)+ let Some(el) = doc.get_node(*node).filter(|n| n.is_element()) else { continue };+ let Some(b) = doc.get_client_bounding_rect(*node) else { continue };+ let l = el.final_layout();+ let s = el.scroll_offset();+ num(*id as f32);+ for v in [b.x as f32, b.y as f32, b.width as f32, b.height as f32, s.x as f32, s.y as f32, el.scroll_width(), el.scroll_height()] {+ num(v);+ }+ for v in [l.padding.left, l.padding.top, l.padding.right, l.padding.bottom, l.border.left, l.border.top, l.border.right, l.border.bottom, 0.0] {+ num(v);+ }+ }+ debug_assert_eq!(STRIDE, 18);+ n.pop();+ format!("{{\"vw\":{},\"vh\":{},\"dpr\":1,\"n\":[{n}]}}", vp.0, vp.1)+}+/// After the page's layout: each root's snapshot to its JS's `__ui_layout`, as raea-runtime-js's dom.rs sends bevy_ui's (the/// DOM layer's geometry: getBoundingClientRect, client and scroll sizes, hit tests, the observers, rAF). Per element,/// in page px: id, x, y, w, h, scrollLeft, scrollTop, scrollWidth, scrollHeight, padding l t r b, border l t r b, z.@@ -188,36 +220,23 @@ pub(crate) const STRIDE: usize = 18;pub fn layout_out(world: &mut World, mut last: Local<HashMap<Entity, String>>) {let Some(mut roots) = world.remove_non_send::<Roots>() else { return };for r in &mut roots.0 {+ // a frame's root reads its own document, swapped out of its iframe as for its step (step.rs): in Docs its+ // page holds the iframe's placeholder, where none of its nodes are, so its JS saw no geometry at all+ if let Some(f) = &r.frame+ && !super::frames::swap_frame(world, r.page, f)+ {+ continue;+ }let json = {let docs = world.non_send::<Docs>();- let Some(doc) = docs.0.get(&r.page) else { continue };- let vp = doc.viewport().window_size;- let mut n = String::new();- let mut num = |v: f32| {- let x = (v * 100.0).round() / 100.0;- if x == x.trunc() {- n.push_str(&format!("{},", x as i64));- } else {- n.push_str(&format!("{x},"));+ let Some(doc) = docs.0.get(&r.page) else {+ drop(docs);+ if let Some(f) = &r.frame {+ super::frames::swap_frame(world, r.page, f);}+ continue;};- for (id, node) in &r.nodes.by_id {- // (text nodes have no layout data of their own to ask)- let Some(el) = doc.get_node(*node).filter(|n| n.is_element()) else { continue };- let Some(b) = doc.get_client_bounding_rect(*node) else { continue };- let l = el.final_layout();- let s = el.scroll_offset();- num(*id as f32);- for v in [b.x as f32, b.y as f32, b.width as f32, b.height as f32, s.x as f32, s.y as f32, el.scroll_width(), el.scroll_height()] {- num(v);- }- for v in [l.padding.left, l.padding.top, l.padding.right, l.padding.bottom, l.border.left, l.border.top, l.border.right, l.border.bottom, 0.0] {- num(v);- }- }- debug_assert_eq!(STRIDE, 18);- n.pop();- format!("{{\"vw\":{},\"vh\":{},\"dpr\":1,\"n\":[{n}]}}", vp.0, vp.1)+ snapshot(doc, &r.nodes)};let arg = if last.get(&r.page) == Some(&json) { String::new() } else { json.clone() };match r.js(world, |js| js.call("__ui_layout", &[Arg::Str(&arg)])) {@@ -228,6 +247,9 @@ pub fn layout_out(world: &mut World, mut last: Local<HashMap<Entity, String>>) {None => {}}drain(world, r);+ if let Some(f) = &r.frame {+ super::frames::swap_frame(world, r.page, f);+ }}world.insert_non_send(roots);}diff --git a/runtime/dom/src/host/frames.rs b/runtime/dom/src/host/frames.rsindex 914d4e67..810554fb 100644--- a/runtime/dom/src/host/frames.rs+++ b/runtime/dom/src/host/frames.rs@@ -69,16 +69,18 @@ pub fn mount(world: &mut World, w: u32, h: u32, code: &str, preamble: &[String],world.init_resource::<HostCalls>();world.init_resource::<SpaceActions>();world.init_resource::<PageAsks>();- // a page's fetch of its own origin is a file under its roots (net.rs page_fetch); the rest goes out as raea-runtime-js's+ // a page's fetch of its own origin is a file under its roots (net.rs page_fetch), or its host's (RAEA_PAGE_HOST: host.rs); the rest goes out as raea-runtime-js'sif !world.contains_resource::<PageFetch>() {world.insert_resource(PageFetch);world.resource_mut::<HostCalls>().on("net.fetch", |_w, args, answer| {- std::thread::spawn(move || match raea_sys_page::net::page_fetch(&args).map(Ok).unwrap_or_else(|| raea_io_net::http::fetch(&args)) {+ std::thread::spawn(move || match raea_sys_page::net::fetch(&args).map(Ok).unwrap_or_else(|| raea_io_net::http::fetch(&args)) {Ok(v) => answer.ok(v),Err(e) => answer.err(e),});});raea_runtime_js::calls::on_sync("canvas.read", raea_sys_canvas::read);+ raea_runtime_js::calls::on_sync("canvas.advances", raea_sys_canvas::advances);+ raea_sys_canvas::fonts(blitz_dom::util::svg_fonts);raea_sys_canvas::videos(|src| Some(raea_sys_page::net::page_path(src.strip_prefix("http://localhost").unwrap_or(src)).into()));}if world.get_non_send::<Roots>().is_none() {diff --git a/runtime/edit/Cargo.toml b/runtime/edit/Cargo.tomlnew file mode 100644index 00000000..1669237a--- /dev/null+++ b/runtime/edit/Cargo.toml@@ -0,0 +1,17 @@+[package]+name = "raea-runtime-edit"+version = "0.1.0"+edition = "2024"+license = "FSL-1.1-ALv2"+publish = false+description = "Text geometry and the selection's paint on a Blitz page, for sdk/ui's Range, Selection and contenteditable: text.rects, caret.at, selection.set"++[dependencies]+raea-runtime-dom = { path = "../dom" }+raea-runtime-js = { path = "../js" }+raea-sys-page = { path = "../../systems/page" }+bevy = { version = "=0.20.0", default-features = false, features = ["std"] }+blitz-dom = { version = "=0.3.0-beta.4", default-features = false }+# the inline layout's cursors and selections, for Range rects and the caret+parley = { version = "0.12", default-features = false, features = ["std"] }+serde_json = "1"diff --git a/runtime/edit/src/lib.rs b/runtime/edit/src/lib.rsnew file mode 100644index 00000000..68d211b0--- /dev/null+++ b/runtime/edit/src/lib.rs@@ -0,0 +1,318 @@+//! raea-runtime-edit: text geometry and the selection's paint for sdk/ui's Range, Selection and contenteditable (docs/ts-native.feature+//! P14e), as synchronous host calls answered from Blitz's inline layout as the JS wrote it:+//! - `text.rects {spans: [[id, from, to], ...]}`: each text's client rects for its UTF-16 range [from, to) (a+//! collapsed one: the caret's zero-width rect), as Range.getClientRects;+//! - `caret.at {x, y}`: the text position at a point, `{id, offset}` (a text's wire id and UTF-16 offset, or an+//! element's with a child index), as caretPositionFromPoint;+//! - `selection.set {anchor, focus, caret} | null`: Blitz's selection set to it (painted as Blitz paints a drag's), and+//! the caret drawn where it's collapsed in a focused editable.+//!+//! Blitz keeps text positions as (inline root, byte offset in its layout's text); each text node's bytes there are+//! recorded as its layout is built (TextLayout::text_nodes), so a DOM offset maps to the layout's and back by walking+//! the node's own characters against the layout's (collapsed white space taken out).++use bevy::prelude::*;+use blitz_dom::node::NodeData;+use blitz_dom::{BaseDocument, NodeId};+use serde_json::{Value, json};++use raea_runtime_dom::host::PageSync;+use raea_sys_page::ops::{self, Nodes};++/// Registers `text.rects`, `caret.at` and `selection.set`.+pub fn register() {+ raea_runtime_js::calls::on_sync_ctx("text.rects", rects);+ raea_runtime_js::calls::on_sync_ctx("caret.at", caret_at);+ raea_runtime_js::calls::on_sync_ctx("selection.set", selection_set);+}++type R<T> = Result<T, String>;++/// The page's document committed and laid out as the JS wrote it (as style.computed does).+fn ready(p: &mut PageSync) -> R<()> {+ let at = {+ let w = p.world();+ w.resource::<raea_sys_page::PageClock>().0.unwrap_or_else(|| w.resource::<Time>().elapsed_secs_f64())+ };+ p.commit();+ p.doc().ok_or("the page has no document")?.resolve(at);+ Ok(())+}++/// The inline root a node's text is laid out in: up from it to the first that is one.+fn inline_root(doc: &BaseDocument, mut n: NodeId) -> Option<NodeId> {+ loop {+ let node = doc.get_node(n)?;+ if node.flags.is_inline_root() {+ return Some(n);+ }+ n = node.parent?;+ }+}++/// A text node's content.+fn content(doc: &BaseDocument, t: NodeId) -> Option<&str> {+ match &doc.get_node(t)?.data {+ NodeData::Text(d) => Some(&d.content),+ _ => None,+ }+}++/// Where a text node's bytes are in its inline root's layout text: (root, start, end).+fn span_of(doc: &BaseDocument, t: NodeId) -> Option<(NodeId, usize, usize)> {+ let root = inline_root(doc, doc.get_node(t)?.parent?)?;+ let lay = doc.get_node(root)?.element_data()?.inline_layout_data.as_ref()?;+ lay.text_nodes.iter().find(|e| e.0 == t).map(|&(_, a, b)| (root, a, b))+}++/// A UTF-16 offset in a text node's content to a byte offset in the layout's text: the node's characters walked+/// against the layout's from its start, a collapsed white-space character taking no layout byte.+fn to_layout(content: &str, lay: &str, start: usize, end: usize, off16: usize) -> usize {+ let mut b = start;+ let mut u = 0;+ let mut lay_chars = lay.get(start..end).unwrap_or("").chars();+ let mut next = lay_chars.next();+ for c in content.chars() {+ if u >= off16 {+ break;+ }+ u += c.len_utf16();+ match next {+ Some(l) if l == c || (l.is_whitespace() && c.is_whitespace()) => {+ b += l.len_utf8();+ next = lay_chars.next();+ }+ // collapsed away+ _ if c.is_whitespace() => {}+ // a transformed character (text-transform): one for one+ Some(l) => {+ b += l.len_utf8();+ next = lay_chars.next();+ }+ None => {}+ }+ }+ b.min(end)+}++/// The other way: a byte offset in the layout's text (within the node's bytes) to a UTF-16 offset in its content.+fn to_dom(content: &str, lay: &str, start: usize, end: usize, byte: usize) -> usize {+ let mut b = start;+ let mut u = 0;+ let mut lay_chars = lay.get(start..end).unwrap_or("").chars();+ let mut next = lay_chars.next();+ for c in content.chars() {+ if b >= byte {+ break;+ }+ match next {+ Some(l) if l == c || (l.is_whitespace() && c.is_whitespace()) || !c.is_whitespace() => {+ b += l.len_utf8();+ next = lay_chars.next();+ }+ _ => {}+ }+ u += c.len_utf16();+ }+ u+}++/// A text node's UTF-16 offset as (inline root, byte).+fn text_point(doc: &BaseDocument, t: NodeId, off16: usize) -> Option<(NodeId, usize)> {+ let (root, a, b) = span_of(doc, t)?;+ let lay = &doc.get_node(root)?.element_data()?.inline_layout_data.as_ref()?.text;+ Some((root, to_layout(content(doc, t)?, lay, a, b, off16)))+}++/// The first (or last) text node in `n`'s subtree that has a place in a layout.+fn edge_text(doc: &BaseDocument, n: NodeId, last: bool) -> Option<NodeId> {+ let node = doc.get_node(n)?;+ if matches!(node.data, NodeData::Text(_)) {+ return span_of(doc, n).map(|_| n);+ }+ let kids: Vec<NodeId> = if last { node.children.iter().rev().copied().collect() } else { node.children.iter().copied().collect() };+ kids.into_iter().find_map(|k| edge_text(doc, k, last))+}++/// The first inline root at or under `n` (an empty block's: its line, with no text in it).+fn root_under(doc: &BaseDocument, n: NodeId) -> Option<NodeId> {+ let node = doc.get_node(n)?;+ if node.flags.is_inline_root() {+ return Some(n);+ }+ node.children.iter().find_map(|&k| root_under(doc, k))+}++/// A boundary point from sdk/ui (`{id, offset}` for a text or an element's own string, `{id, before}` for a point+/// among an element's children) as (inline root, byte).+fn point(doc: &BaseDocument, nodes: &Nodes, v: &Value) -> Option<(NodeId, usize)> {+ let el = ops::node(nodes, v["id"].as_u64()?)?;+ let node = doc.get_node(el)?;+ if let Some(off) = v["offset"].as_u64() {+ let off = off as usize;+ // a text, or the element's own string (its one text child)+ let t = if matches!(node.data, NodeData::Text(_)) { el } else { *node.children.iter().find(|&&k| matches!(doc.get_node(k).map(|n| &n.data), Some(NodeData::Text(_))))? };+ return text_point(doc, t, off);+ }+ // before a child: the first text from it on (else the end of the last before it); at the end: the last text+ let before = v["before"].as_u64().and_then(|b| ops::node(nodes, b));+ let kids = &node.children;+ let at = before.and_then(|b| kids.iter().position(|&k| k == b)).unwrap_or(kids.len());+ if let Some(t) = kids[at..].iter().find_map(|&k| edge_text(doc, k, false)) {+ // only within the same inline root as the point's element (a later paragraph's text is a different line)+ let (root, a, _) = span_of(doc, t)?;+ if inline_root(doc, el) == Some(root) || before.is_some_and(|b| doc.get_node(b).is_some_and(|n| !n.flags.is_inline_root())) {+ return Some((root, a));+ }+ }+ if let Some(t) = kids[..at].iter().rev().find_map(|&k| edge_text(doc, k, true)) {+ let (root, _, b) = span_of(doc, t)?;+ return Some((root, b));+ }+ let r = before.and_then(|b| root_under(doc, b)).or_else(|| inline_root(doc, el)).or_else(|| root_under(doc, el))?;+ Some((r, 0))+}++/// A rect in an inline root's layout (its units, from the content box's start, past its block offset) in client px.+fn client_rect(doc: &BaseDocument, root: NodeId, r: &parley::BoundingBox) -> Option<[f64; 4]> {+ let node = doc.get_node(root)?;+ let lay = node.element_data()?.inline_layout_data.as_ref()?;+ let b = doc.get_client_bounding_rect(root)?;+ let l = node.final_layout();+ let s = lay.layout.scale() as f64;+ let x = b.x + (l.padding.left + l.border.left) as f64 + r.x0 / s;+ let y = b.y + (l.padding.top + l.border.top + lay.block_offset) as f64 + r.y0 / s;+ Some([x, y, (r.x1 - r.x0) / s, (r.y1 - r.y0) / s])+}++/// One text's rects for [from, to) (UTF-16): the selection's boxes, or the caret's zero-width one when collapsed.+fn text_rects(doc: &BaseDocument, t: NodeId, from: usize, to: usize) -> Option<Vec<[f64; 4]>> {+ let (root, a) = text_point(doc, t, from)?;+ let (_, b) = text_point(doc, t, to)?;+ let layout = &doc.get_node(root)?.element_data()?.inline_layout_data.as_ref()?.layout;+ use parley::{Affinity, Cursor, Selection};+ if a == b {+ let c = Cursor::from_byte_index(layout, a, Affinity::Downstream).geometry(layout, 0.0);+ return Some(vec![client_rect(doc, root, &c)?]);+ }+ let sel = Selection::new(Cursor::from_byte_index(layout, a, Affinity::Downstream), Cursor::from_byte_index(layout, b, Affinity::Upstream));+ Some(sel.geometry(layout).iter().filter_map(|(r, _)| client_rect(doc, root, r)).collect())+}++fn rects(ctx: &mut dyn std::any::Any, args: &Value) -> R<Value> {+ let p = ctx.downcast_mut::<PageSync>().ok_or("text.rects: not a page's call")?;+ ready(p)?;+ let spans: Vec<(u64, usize, usize)> = args["spans"].as_array().map(|a| a.iter().filter_map(|s| Some((s[0].as_u64()?, s[1].as_u64()? as usize, s[2].as_u64()? as usize))).collect()).unwrap_or_default();+ let ids: Vec<Option<NodeId>> = spans.iter().map(|s| ops::node(p.nodes(), s.0)).collect();+ let doc = p.doc().ok_or("text.rects: the page has no document")?;+ let out: Vec<Value> = spans.iter().zip(ids).map(|(&(_, a, b), t)| t.and_then(|t| text_rects(doc, t, a, b)).map_or(Value::Null, |rs| json!(rs))).collect();+ Ok(Value::Array(out))+}++/// The text node and UTF-16 offset at a layout position (at a seam, the text it ends: Chrome's upstream caret).+fn text_at(doc: &BaseDocument, root: NodeId, byte: usize) -> Option<(NodeId, usize)> {+ let lay = doc.get_node(root)?.element_data()?.inline_layout_data.as_ref()?;+ // the text it's inside, else the one it ends+ let holds = lay.text_nodes.iter().filter(|e| e.1 <= byte && byte <= e.2);+ let e = holds.min_by_key(|e| e.2 == byte)?;+ Some((e.0, to_dom(content(doc, e.0)?, &lay.text, e.1, e.2, byte)))+}++/// The inline roots in a subtree (a block's paragraphs).+fn roots_in(doc: &BaseDocument, n: NodeId, out: &mut Vec<NodeId>) {+ let Some(node) = doc.get_node(n) else { return };+ if node.flags.is_inline_root() {+ out.push(n);+ return;+ }+ for &k in node.children.iter() {+ roots_in(doc, k, out);+ }+}++/// A point that's off every line moved onto the nearest one under what it hit: into that inline root's content box.+fn nearest_line(doc: &BaseDocument, x: f32, y: f32) -> Option<(f32, f32)> {+ let hit = doc.hit(x, y)?;+ let mut roots = Vec::new();+ roots_in(doc, hit.node_id, &mut roots);+ let (x, y) = (x as f64, y as f64);+ let boxes = roots.into_iter().filter_map(|r| {+ let b = doc.get_client_bounding_rect(r)?;+ let l = doc.get_node(r)?.final_layout();+ let (l0, t0) = (b.x + (l.padding.left + l.border.left) as f64, b.y + (l.padding.top + l.border.top) as f64);+ let (r0, b0) = (b.x + b.width - (l.padding.right + l.border.right) as f64, b.y + b.height - (l.padding.bottom + l.border.bottom) as f64);+ (r0 > l0 && b0 > t0).then_some((l0, t0, r0, b0))+ });+ let dist = |&(l, t, r, b): &(f64, f64, f64, f64)| (x - x.clamp(l, r)).powi(2) + (y - y.clamp(t, b)).powi(2);+ let (l, t, r, b) = boxes.min_by(|a, b| dist(a).total_cmp(&dist(b)))?;+ Some((x.clamp(l + 0.5, r - 0.5) as f32, y.clamp(t + 0.5, b - 0.5) as f32))+}++fn caret_at(ctx: &mut dyn std::any::Any, args: &Value) -> R<Value> {+ let p = ctx.downcast_mut::<PageSync>().ok_or("caret.at: not a page's call")?;+ ready(p)?;+ let (x, y) = (args["x"].as_f64().unwrap_or(0.0) as f32, args["y"].as_f64().unwrap_or(0.0) as f32);+ let found = {+ let doc = p.doc().ok_or("caret.at: the page has no document")?;+ // a point off any line (a block's padding, past a paragraph's end): clamped into the nearest line, as Chrome's+ // caretPositionFromPoint clamps it+ let pos = doc.find_text_position(x, y).or_else(|| {+ let (cx, cy) = nearest_line(doc, x, y)?;+ doc.find_text_position(cx, cy)+ });+ match pos {+ Some((root, byte)) => text_at(doc, root, byte),+ None => doc.hit(x, y).map(|h| (h.node_id, 0)),+ }+ };+ let Some((node, off)) = found else { return Ok(Value::Null) };+ let doc = p.doc().ok_or("caret.at: the page has no document")?;+ let is_text = matches!(doc.get_node(node).map(|n| &n.data), Some(NodeData::Text(_)));+ let parent = doc.get_node(node).and_then(|n| n.parent);+ let nodes = p.nodes();+ // a text the ops made, else its element (React's own string: the offset is in it), else the nearest element up+ if let Some(id) = nodes.id_of(node) {+ return Ok(json!({ "id": id, "offset": off }));+ }+ let mut up = if is_text { parent } else { Some(node) };+ let doc = p.doc().ok_or("caret.at: the page has no document")?;+ let mut chain = Vec::new();+ while let Some(n) = up {+ chain.push(n);+ up = doc.get_node(n).and_then(|x| x.parent);+ }+ let nodes = p.nodes();+ for n in chain {+ if let Some(id) = nodes.id_of(n) {+ return Ok(json!({ "id": id, "offset": if is_text { off } else { 0 } }));+ }+ }+ Ok(Value::Null)+}++fn selection_set(ctx: &mut dyn std::any::Any, args: &Value) -> R<Value> {+ let p = ctx.downcast_mut::<PageSync>().ok_or("selection.set: not a page's call")?;+ ready(p)?;+ let ends = if args.is_null() {+ None+ } else {+ let nodes: *const Nodes = p.nodes();+ let doc = p.doc().ok_or("selection.set: the page has no document")?;+ // (nodes and the document are apart: the ids' map is the root's, the document the page's)+ let nodes = unsafe { &*nodes };+ point(doc, nodes, &args["anchor"]).zip(point(doc, nodes, &args["focus"]))+ };+ let caret = args["caret"].as_bool().unwrap_or(false);+ let doc = p.doc().ok_or("selection.set: the page has no document")?;+ match ends {+ Some((a, f)) => {+ doc.set_text_selection(a.0, a.1, f.0, f.1);+ doc.caret = (caret && a == f).then_some(f);+ }+ None => {+ doc.clear_text_selection();+ doc.caret = None;+ }+ }+ Ok(Value::Null)+}diff --git a/runtime/encode/src/render.rs b/runtime/encode/src/render.rsindex ab86f6e6..e05c451a 100644--- a/runtime/encode/src/render.rs+++ b/runtime/encode/src/render.rs@@ -337,7 +337,23 @@ pub fn render_with(prog: &Program, rows: &[Tup], dir: &Path, out: &Path, ro: &Re} else {std::fs::create_dir_all(&out).map_err(|e| e.to_string())?;let nv12 = e.nv12;- let rgba_of = |px: Vec<u8>| if nv12 { raea_io_media::yuv::nv12_to_rgba(&px, w as usize, h as usize) } else { px };+ // the composite is premultiplied; a PNG holds straight colour. Only a transparent clear (render --alpha) leaves+ // alpha under 255, so an opaque frame is written as it comes+ let rgba_of = |px: Vec<u8>| {+ if nv12 {+ return raea_io_media::yuv::nv12_to_rgba(&px, w as usize, h as usize);+ }+ let mut px = px;+ for p in px.chunks_exact_mut(4) {+ let a = p[3] as u32;+ if a > 0 && a < 255 {+ for c in &mut p[..3] {+ *c = ((*c as u32 * 255 + a / 2) / a).min(255) as u8;+ }+ }+ }+ px+ };e.frames(&list, |f, px| save_png(&out.join(format!("frame-{f:05}.png")), &rgba_of(px), w, h))?;}eprintln!("{} ({} frames) in {:.2}s", out.display(), list.len(), t0.elapsed().as_secs_f64());diff --git a/runtime/export/Cargo.toml b/runtime/export/Cargo.tomlindex 702b2171..0594a26f 100644--- a/runtime/export/Cargo.toml+++ b/runtime/export/Cargo.toml@@ -13,7 +13,7 @@ raea-runtime-react = { path = "../../runtime/react", default-features = false }raea-runtime-page = { path = "../page" }raea-runtime-sound = { path = "../sound", default-features = false }raea-runtime-bake = { path = "../bake" }-raea-render = { path = "../../engine/render", default-features = false, features = ["native"] }+raea-render = { path = "../../engine/render", default-features = false, features = ["native", "raytracing"] }# renders to files: RenderOpts, render, render_fedraea-runtime-encode = { path = "../encode" }raea-page = { path = "../../engine/page" }diff --git a/runtime/export/src/fed.rs b/runtime/export/src/fed.rsindex 536bdac0..34289607 100644--- a/runtime/export/src/fed.rs+++ b/runtime/export/src/fed.rs@@ -20,6 +20,27 @@ pub(crate) struct FrameLog {pub(crate) rows: Vec<(i64, f64, [f64; 5])>,}+/// Whether any of `frames` shows 3D: each rendered on its own in one runtime (frames are pure, so a frame stepped+/// alone is the frame a whole pass would have stepped), stopping at the first that does.+pub(crate) fn frames_hold_3d(js: &Path, dir: &Path, frames: &[i64]) -> R<bool> {+ edit_dir(dir);+ let mut app = App::new();+ app.add_plugins(MinimalPlugins).add_plugins(ReactPlugin::new(js.to_path_buf()));+ app.insert_resource(raea_runtime_react::OneBatch::default());+ settle(&mut app, Some(-1), 20.0)?.ok_or("the composition's settings didn't arrive")?;+ let mut held = false;+ for &f in frames {+ raea_runtime_bake::step_frames(&mut app, f, f + 1, |app, _| {+ held |= !scene_of(app.world_mut()).is_empty();+ Ok(())+ })?;+ if held {+ break;+ }+ }+ Ok(held)+}+/// The frames `scene_program_to` reads its rows from, with the composition's size and rate.////// Stepped as a bake steps (bake.rs, lightspeed T3): React renders a range of frames back to back (raea-frames) anddiff --git a/runtime/export/src/lib.rs b/runtime/export/src/lib.rsindex 2bea5bfb..f3445414 100644--- a/runtime/export/src/lib.rs+++ b/runtime/export/src/lib.rs@@ -74,6 +74,14 @@ static STAGE: std::sync::Mutex<Option<(u32, u32)>> = std::sync::Mutex::new(None)/// render exactly (8-bit limited-range H.264 errs up to 2/255 by its own round trip; lightspeed Q3.colour).static TEN_BIT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);+/// `render --aov` (docs/raytracing.feature RT1): each frame's motion vectors and depth beside its picture, in DIR/motion+/// and DIR/depth, for a neural or denoising pass after the render (`raea neural`).+static AOV: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);++/// `render --alpha`: PNGs (a frame or a folder) kept transparent where the composition draws nothing, the pages+/// composited over a clear background instead of black: overlays for another editor's timeline.+static ALPHA: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);+/// `render --kbps N`: the video's average bitrate (raea_io_media::default_kbps when 0, from the size and frame rate).static KBPS: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);@@ -142,7 +150,7 @@ pub(crate) struct Ctx<'a> {fn generated(props: &mut Map<String, Value>, cx: &mut Ctx) -> bool {let (Some(model), Some(prompt)) = (props.get("data-generate").and_then(|v| v.as_str()).map(str::to_string), props.get("data-prompt").and_then(|v| v.as_str()).map(str::to_string)) else { return true };let seconds = num(props, "data-seconds").unwrap_or(4.0);- // the generator's own settings (a TokenSynth note's pitch and seed, a Fish voice's speed) make another sound+ // the generator's own settings (a TokenSynth note's pitch and seed) make another soundlet options = props.get("data-options").and_then(|v| v.as_str()).map(str::to_string);let key = format!("{model}|{prompt}|{seconds}|{}", options.as_deref().unwrap_or(""));if !cx.made.contains_key(&key) {diff --git a/runtime/export/src/program.rs b/runtime/export/src/program.rsindex 6abce85a..716aad1e 100644--- a/runtime/export/src/program.rs+++ b/runtime/export/src/program.rs@@ -13,8 +13,12 @@ pub(crate) fn program(frames: &[(i64, Frame)], w: u32, h: u32, fps: f64) -> raear.insert("id".into(), V::S(id.into()));r};- let clear = frames.first().and_then(|(_, f)| f.clear.clone()).and_then(|c| hex_of(&c)).unwrap_or("#000000".into());+ // --alpha: nothing under the pages, so what the composition leaves empty stays transparent+ let clear = if ALPHA.load(std::sync::atomic::Ordering::Relaxed) { "#00000000".into() } else { frames.first().and_then(|(_, f)| f.clear.clone()).and_then(|c| hex_of(&c)).unwrap_or("#000000".into()) };let has3d = frames.iter().any(|(_, f)| !f.scene.is_empty());+ if has3d && ALPHA.load(std::sync::atomic::Ordering::Relaxed) {+ eprintln!("raea: --alpha keeps 2D pages and <Video> clips transparent; the frames with 3D are drawn over the 3D and come out opaque");+ }let mut cam = row("cam", vec![("bg", V::S(clear))]);if has3d {// where it is and looks, frame by frame; its lens, ambient light and post-processing (scene3d)diff --git a/runtime/export/src/render.rs b/runtime/export/src/render.rsindex d2c7ce93..86b49657 100644--- a/runtime/export/src/render.rs+++ b/runtime/export/src/render.rs@@ -49,6 +49,15 @@ pub fn render(args: &[String]) -> R<String> {};*MANIFEST.lock().unwrap() = flag(args, "--manifest").map(PathBuf::from);TEN_BIT.store(args.iter().any(|a| a == "--10bit"), std::sync::atomic::Ordering::Relaxed);+ AOV.store(args.iter().any(|a| a == "--aov"), std::sync::atomic::Ordering::Relaxed);+ if AOV.load(std::sync::atomic::Ordering::Relaxed) && !out_ext(&out).is_empty() {+ return Err("--aov writes frames: -o names a folder (DIR/frame-NNNNN.png, DIR/motion, DIR/depth)".into());+ }+ let alpha = args.iter().any(|a| a == "--alpha");+ if alpha && !matches!(out_ext(&out).as_str(), "png" | "") {+ return Err("--alpha writes PNGs (OUT.png or a folder): video here is H.264 or HEVC, which hold no alpha. Encode the folder with alpha after (ffmpeg -i DIR/frame-%05d.png -c:v prores_ks -profile:v 4444 -pix_fmt yuva444p10le overlay.mov)".into());+ }+ ALPHA.store(alpha, std::sync::atomic::Ordering::Relaxed);let kbps = flag(args, "--kbps").map(|k| k.parse::<u32>().ok().filter(|k| *k > 0).ok_or("--kbps takes a bitrate in kbit/s")).transpose()?;KBPS.store(kbps.unwrap_or(0), std::sync::atomic::Ordering::Relaxed);let quality = flag(args, "--quality").map(|q| raea_io_media::parse_quality(&q)).transpose()?;@@ -184,7 +193,7 @@ pub(crate) fn render_bundle_with(js: &Path, dir: &Path, out: &Path, wanted: Optilet mut cx = Ctx { dir, work: &work, sounds: Vec::new(), scene: Vec::new(), clear: None, marker: None, mix: None, audible: HashMap::new(), brand: page_css(dir, w, js), manifest: MANIFEST.lock().unwrap().as_ref().map(|_| Vec::new()), now: 0, said: Default::default(), made: HashMap::new(), scene3d: None, live3d: None };if fed {if let Some(p) = scene {- cx.scene3d = Some(raea_render::engine::Engine::new_live(&p, &raea_render::inserted_of(&p), dir)?);+ cx.scene3d = Some(aov_on(raea_render::engine::Engine::new_live(&p, &raea_render::inserted_of(&p), dir)?));raea_runtime_react::startup_mark("the 3D's engine open");}if live3d {@@ -197,7 +206,7 @@ pub(crate) fn render_bundle_with(js: &Path, dir: &Path, out: &Path, wanted: Optilet programmed = scene.is_some();match scene {Some(p) => {- cx.scene3d = Some(raea_render::engine::Engine::new_live(&p, &raea_render::inserted_of(&p), dir)?);+ cx.scene3d = Some(aov_on(raea_render::engine::Engine::new_live(&p, &raea_render::inserted_of(&p), dir)?));raea_runtime_react::startup_mark("the 3D's engine open");}None => cx.live3d = Some(LiveScene::default()),@@ -218,7 +227,7 @@ pub(crate) fn render_bundle_with(js: &Path, dir: &Path, out: &Path, wanted: Optiif i == 0 && programmed && raea_runtime_page::VIEW_BOX.lock().unwrap().is_some() {let upto = wanted.iter().max().map_or(0, |m| m + 1);if let Some(p) = scene_program_checked(js, dir, upto, Some(&wanted))? {- cx.scene3d = Some(raea_render::engine::Engine::new_live(&p, &raea_render::inserted_of(&p), dir)?);+ cx.scene3d = Some(aov_on(raea_render::engine::Engine::new_live(&p, &raea_render::inserted_of(&p), dir)?));px = bevy_over_3d(app.world_mut(), pg, &mut cx, fps)?;}}@@ -228,6 +237,9 @@ pub(crate) fn render_bundle_with(js: &Path, dir: &Path, out: &Path, wanted: Opti}let dest = if folder { out.join(format!("frame-{i:05}.png")) } else { out.to_path_buf() };image::save_buffer(&dest, &px, w, h, image::ColorType::Rgba8).map_err(|e| format!("{}: {e}", dest.display()))?;+ if folder {+ write_aov(out, i, cx.scene3d.as_mut())?;+ }}if let Some(t) = FED_CLIPPING.lock().unwrap().take() {let _ = t.join();@@ -320,3 +332,27 @@ pub(crate) fn render_bundle_with(js: &Path, dir: &Path, out: &Path, wanted: Optidrop(page);Ok(format!("APPLIED {} frames rendered to {} ({react_ms:.0} ms a frame in React and bevy_ui)", frames.len(), out.display()))}++/// An engine for the scene path, drawing the guide data when `--aov` asked for it.+fn aov_on(mut e: raea_render::engine::Engine) -> raea_render::engine::Engine {+ if AOV.load(std::sync::atomic::Ordering::Relaxed) {+ e.want_aov();+ }+ e+}++/// Frame i's guide data (RT1) as mlxdlss run-sequence reads it: DIR/motion/frame-NNNNN.f32 (H x W x 2 float32) and+/// DIR/depth/frame-NNNNN.f32 (H x W float32), little-endian, rows top to bottom.+fn write_aov(out: &Path, i: usize, e: Option<&mut raea_render::engine::Engine>) -> R<()> {+ if !AOV.load(std::sync::atomic::Ordering::Relaxed) {+ return Ok(());+ }+ let a = e.and_then(|e| e.take_aov()).ok_or_else(|| format!("frame {i}: --aov, but the frame drew no motion vectors or depth (a 3D camera draws them)"))?;+ for (sub, v) in [("motion", &a.motion), ("depth", &a.depth)] {+ let d = out.join(sub);+ std::fs::create_dir_all(&d).map_err(|e| format!("{}: {e}", d.display()))?;+ let f = d.join(format!("frame-{i:05}.f32"));+ std::fs::write(&f, v.iter().flat_map(|x| x.to_le_bytes()).collect::<Vec<u8>>()).map_err(|e| format!("{}: {e}", f.display()))?;+ }+ Ok(())+}diff --git a/runtime/export/src/run.rs b/runtime/export/src/run.rsindex 7a9daf1e..afffe72f 100644--- a/runtime/export/src/run.rs+++ b/runtime/export/src/run.rs@@ -60,6 +60,16 @@ pub(crate) fn scene_program_to(js: &Path, dir: &Path, upto: i64) -> R<Option<rae/// A render's 3D rows as `scene_program_to` makes them, and the 3D parts that pass through each other on screen in/// `wanted` (one frame, a still; else all): said on stderr, and kept for the render's manifest (FED_CLIPPING).pub(crate) fn scene_program_checked(js: &Path, dir: &Path, upto: i64, wanted: Option<&[i64]>) -> R<Option<raea_core_program::ir::Program>> {+ // stills: the frames asked for looked at first, each on its own (frames are pure). When none of them shows 3D,+ // their render needs no rows, and a 2D piece's still skips stepping its whole timeline (an 80 s film's still took+ // 16 s here, all of it the rows' pass finding no 3D)+ if let Some(w) = wanted.filter(|w| !w.is_empty()) {+ raea_runtime_react::startup_mark("the 3D's rows: the wanted frames looked at");+ if !frames_hold_3d(js, dir, w)? {+ raea_runtime_react::startup_mark("the 3D's rows: none in the wanted frames");+ return Ok(None);+ }+ }raea_runtime_react::startup_mark("the 3D's rows: stepping React through the frames");let Some((frames, w, h, fps)) = scene_frames_to(js, dir, upto)? else { return Ok(None) };raea_runtime_react::startup_mark("the 3D's rows: frames stepped");diff --git a/runtime/js/Cargo.toml b/runtime/js/Cargo.tomlindex 53620447..f358e713 100644--- a/runtime/js/Cargo.toml+++ b/runtime/js/Cargo.toml@@ -32,4 +32,8 @@ raea-runtime-jsengine = { path = "../jsengine" }raea-io-media = { path = "../../io/media", default-features = false, optional = true }# webaudio's samples across the wirebase64 = "0.22"+# the HTML runtime bundled in process (html_page.rs): raea's files where an install or this checkout has them, and+# raea-bundle's library loaded beside the binary+raea-io-home = { path = "../../io/home" }+raea-runtime-bundle = { path = "../bundle" }diff --git a/runtime/js/js/build.ts b/runtime/js/js/build.tsdeleted file mode 100644index 585f84b1..00000000--- a/runtime/js/js/build.ts+++ /dev/null@@ -1,40 +0,0 @@-// A TSX entry bundled for raea-runtime-js: `bun build.ts ENTRY OUT.js UI_SRC FALLBACK_MODULES` makes one IIFE of the entry,-// @raea/ui (resolved to UI_SRC, sdk/ui/src) and React. Bare imports resolve from the entry's own node_modules first,-// then FALLBACK_MODULES (raea's sdk/react/js/node_modules), so an entry folder needs no install of its own.-import { dirname, join } from "node:path";--const [entry, out, ui, fallback] = process.argv.slice(2);-if (!entry || !out || !ui) {- console.error("usage: bun build.ts ENTRY OUT.js UI_SRC [FALLBACK_MODULES]");- process.exit(2);-}-const b = await Bun.build({- entrypoints: [entry],- target: "browser",- format: "iife",- minify: { syntax: true },- define: { "process.env.NODE_ENV": '"production"' },- plugins: [- {- name: "raea-runtime-js-modules",- setup(b) {- // @raea/ui's subpaths (./react, ./wire, ./platform ...) from UI_SRC- b.onResolve({ filter: /^@raea\/ui(\/.*)?$/ }, (a) => ({ path: join(ui, (a.path.slice("@raea/ui/".length) || "index") + ".ts") }));- // React and friends: the entry's own, else the fallback's- b.onResolve({ filter: /^(react|react-dom|react-reconciler|scheduler)(\/.*)?$/ }, (a) => {- try {- return { path: Bun.resolveSync(a.path, dirname(a.importer || entry)) };- } catch {- if (!fallback) throw new Error(`${a.path}: not installed beside ${entry}`);- return { path: Bun.resolveSync(a.path, fallback + "/") };- }- });- },- },- ],-});-if (!b.success) {- console.error(b.logs.map((l) => String(l)).join("\n"));- process.exit(1);-}-await Bun.write(out, await b.outputs[0].text());diff --git a/runtime/js/src/bundle.rs b/runtime/js/src/bundle.rsdeleted file mode 100644index e3f36127..00000000--- a/runtime/js/src/bundle.rs+++ /dev/null@@ -1,36 +0,0 @@-//! A TSX entry bundled with bun (js/build.ts): one IIFE of the entry, @raea/ui and React, ready for any engine.-//! `BEVY_TSX_UI` names @raea/ui's source folder and `BEVY_TSX_MODULES` the node_modules to fall back to; both default-//! to raea's (sdk/ui/src, sdk/react/js/node_modules beside this crate).--use std::path::{Path, PathBuf};-use std::time::Instant;--fn here() -> PathBuf {- PathBuf::from(env!("CARGO_MANIFEST_DIR"))-}--/// The bundle of `entry`, as JS.-pub fn build(entry: &Path) -> Result<String, String> {- let ui = std::env::var("BEVY_TSX_UI").map(PathBuf::from).unwrap_or_else(|_| here().join("../../sdk/ui/src"));- let modules = std::env::var("BEVY_TSX_MODULES").map(PathBuf::from).unwrap_or_else(|_| here().join("../../sdk/react/js/node_modules"));- let entry = entry.canonicalize().map_err(|e| format!("{}: {e}", entry.display()))?;- let out = std::env::temp_dir().join(format!("raea-runtime-js-{}-{}.js", std::process::id(), entry.file_stem().and_then(|s| s.to_str()).unwrap_or("entry")));- let t = Instant::now();- let r = std::process::Command::new("bun")- .arg(here().join("js/build.ts"))- .arg(&entry)- .arg(&out)- .arg(&ui)- .arg(&modules)- .output()- .map_err(|e| format!("bun (is it installed?): {e}"))?;- if !r.status.success() {- return Err(format!("bun build {}: {}", entry.display(), String::from_utf8_lossy(&r.stderr)));- }- let code = std::fs::read_to_string(&out).map_err(|e| e.to_string())?;- let _ = std::fs::remove_file(&out);- if crate::trace().is_some() {- eprintln!("raea-runtime-js: bundled {} in {} ms ({} KB)", entry.display(), t.elapsed().as_millis(), code.len() / 1024);- }- Ok(code)-}diff --git a/runtime/js/src/html_page.rs b/runtime/js/src/html_page.rsindex 01ee7df3..09ff59b2 100644--- a/runtime/js/src/html_page.rs+++ b/runtime/js/src/html_page.rs@@ -50,12 +50,19 @@ pub fn read_answer(dir: &Path, args: &Value) -> R<Value> {Ok(out)}-/// The runtime's bundle (sdk/ui/src/html.ts), bundled once a process.+/// The runtime's bundle (sdk/ui/src/html.ts), bundled once a process by raea's own bundler (Rolldown, in process),+/// from raea's files where `raea_io_home` finds them: an install's share/raea, else this checkout. `BEVY_TSX_UI` names+/// another sdk/ui/src. (It was bun and this crate's js/build.ts, beside the tree it was built from: a release has+/// neither, so `raea render PAGE.html` failed installed.)pub fn bundle() -> R<String> {static CODE: OnceLock<R<String>> = OnceLock::new();CODE.get_or_init(|| {- let entry = std::env::var("BEVY_TSX_UI").map(PathBuf::from).unwrap_or_else(|_| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../sdk/ui/src")).join("html.ts");- crate::bundle::build(&entry)+ let ui = std::env::var_os("BEVY_TSX_UI").map(PathBuf::from).unwrap_or_else(|| raea_io_home::home().join("sdk/ui/src"));+ let entry = ui.join("html.ts");+ if !entry.is_file() {+ return Err(format!("{}: the HTML runtime isn't there (BEVY_TSX_UI names another sdk/ui/src)", entry.display()));+ }+ raea_runtime_bundle::inproc::bundle(&entry, json!({})).map(|(js, _css)| js).map_err(|e| format!("the HTML runtime ({}): {e}", entry.display()))}).clone()}@@ -88,7 +95,15 @@ fn listing(dir: &Path) -> Vec<String> {/// The root composition's size as its markup gives it (data-width / data-height of the first composition), before/// the page runs.fn size_of(src: &str) -> (u32, u32) {- let at = src.find("data-composition-id").unwrap_or(0);+ // the first element carrying data-composition-id: an attribute (whitespace before, `=` after), not the name in a+ // stylesheet's selector (`[data-composition-id="main"] > div`), which comes first in a page's <head> and sized a+ // 1080 x 1920 page at the 1920 x 1080 default+ let key = "data-composition-id";+ let at = src+ .match_indices(key)+ .map(|(i, _)| i)+ .find(|&i| i > 0 && src.as_bytes()[i - 1].is_ascii_whitespace() && src[i + key.len()..].trim_start().starts_with('='))+ .unwrap_or(0);let tag_start = src[..at].rfind('<').unwrap_or(0);let tag_end = src[at..].find('>').map(|i| at + i).unwrap_or(src.len());let tag = &src[tag_start..tag_end];@@ -175,3 +190,13 @@ pub fn videos_of(done: &Value) -> Vec<VideoAt> {.unwrap_or_default()}+#[cfg(test)]+mod tests {+ #[test]+ fn size_comes_from_the_root_element_not_a_selector() {+ let page = r#"<html><head><style>[data-composition-id="main"] > div { position: absolute; }</style></head>+<body><div id="root" data-composition-id="main" data-start="0" data-width="1080" data-height="1920"></div></body></html>"#;+ assert_eq!(super::size_of(page), (1080, 1920));+ assert_eq!(super::size_of("<div data-composition-id='m'></div>"), (1920, 1080));+ }+}diff --git a/runtime/js/src/lib.rs b/runtime/js/src/lib.rsindex b52da672..10194c3a 100644--- a/runtime/js/src/lib.rs+++ b/runtime/js/src/lib.rs@@ -8,7 +8,6 @@//! Its bevy_ui host (elements as bevy_ui nodes, with their controls, svg, layout snapshot and painter) went in the//! overhaul (docs/overhaul.md, 10-27): no app mounted it after docs/blitz-bevy.feature B5d, since every page is Blitz's.-pub mod bundle;pub mod calls;pub mod html_page;pub mod js;diff --git a/runtime/look/src/lib.rs b/runtime/look/src/lib.rsindex 29599a09..e93d6ba1 100644--- a/runtime/look/src/lib.rs+++ b/runtime/look/src/lib.rs@@ -85,6 +85,13 @@ pub fn surface_spec(p: &Map<String, Value>) -> Value {o.insert(col.into(), Value::String(src_path(src)));}}+ // how its alpha draws: a glTF's MASK hair made "coverage" (soft over MSAA), or a part made "blend"+ if let Some(Value::String(a)) = p.get("alphaMode") {+ o.insert("alpha".into(), Value::String(a.clone()));+ }+ if let Some(v) = num(p, "alphaCutoff") {+ o.insert("alpha_cutoff".into(), Value::from(v));+ }// StandardMaterial's other fields (docs/shaders.feature SH7)if let Some(f) = fields_of(p) {o.insert("fields".into(), Value::String(f));diff --git a/runtime/scene/src/fast.rs b/runtime/scene/src/fast.rsindex 513c01da..1b25094b 100644--- a/runtime/scene/src/fast.rs+++ b/runtime/scene/src/fast.rs@@ -2,6 +2,9 @@use super::*;+/// the most values a part keys in a frame: placement (9), animation (1, 8 mixed, 32 graph), morphs (64) and a few more+const WANT: usize = 128;+impl LiveScene {/// `diff(current(f))` for a frame whose parts are all known, without the rows: each known part's changing values worked out into a fixed array and held/// against what was sent in place, as diff holds a row (the same rules: recoloured meshes keyed, the emissive strength@@ -111,7 +114,7 @@ impl LiveScene {// pass 2: each part's values, then held against what was sentfor (i, id) in parts {let it = &its[i];- let mut want: [(&str, Option<f64>); 24] = [("", None); 24];+ let mut want: [(&str, Option<f64>); WANT] = [("", None); WANT];let mut nw = 0usize;let mut put = |k: &'static str, v: f64| {want[nw] = (k, Some(r6(v)));@@ -185,7 +188,7 @@ impl LiveScene {}}if let Some(Value::Array(a)) = it.props.get("morphs") {- for (i, c) in a.iter().enumerate().take(8) {+ for (i, c) in a.iter().enumerate().take(MORPH_COLS.len()) {put(MORPH_COLS[i], c.get("weight").and_then(Value::as_f64).unwrap_or(0.0));}}@@ -195,6 +198,9 @@ impl LiveScene {if it.props.contains_key("screenPower") {put("screen_power", n(&it.props, "screenPower", 1.0));}+ if let Some(f) = it.props.get("cloth").and_then(|c| c.get("frame")).and_then(Value::as_f64) {+ put("cloth_frame", f);+ }place(&mut put);"model"}@@ -223,7 +229,7 @@ impl LiveScene {let r = self.rows.get_mut(id).expect("checked in pass 1");r.seen = true;r.missing = 0;- let set = |want: &mut [(&str, Option<f64>); 24], nw: &mut usize, k: &'static str, v: Option<f64>, only_if_absent: bool| {+ let set = |want: &mut [(&str, Option<f64>); WANT], nw: &mut usize, k: &'static str, v: Option<f64>, only_if_absent: bool| {match want[..*nw].iter_mut().find(|w| w.0 == k) {Some(w) => {if !only_if_absent {diff --git a/runtime/scene/src/live.rs b/runtime/scene/src/live.rsindex 6aae35d3..6c9f67ce 100644--- a/runtime/scene/src/live.rs+++ b/runtime/scene/src/live.rs@@ -49,14 +49,15 @@ pub(crate) const LIVE_GROUPS: [&str; 5] = ["light", "mesh", "model", "panel", "d/// A <Model animations>'s keyed columns (its clips' times and weights) and a <Model morphs>'s (its targets' weights).pub(crate) const MIX_COLS: [(&str, &str); 4] = [("mix0_t", "mix0_w"), ("mix1_t", "mix1_w"), ("mix2_t", "mix2_w"), ("mix3_t", "mix3_w")];pub(crate) const GRAPH_COLS: [[&str; 2]; 16] = [["g0_w", "g0_t"], ["g1_w", "g1_t"], ["g2_w", "g2_t"], ["g3_w", "g3_t"], ["g4_w", "g4_t"], ["g5_w", "g5_t"], ["g6_w", "g6_t"], ["g7_w", "g7_t"], ["g8_w", "g8_t"], ["g9_w", "g9_t"], ["g10_w", "g10_t"], ["g11_w", "g11_t"], ["g12_w", "g12_t"], ["g13_w", "g13_t"], ["g14_w", "g14_t"], ["g15_w", "g15_t"]];-pub(crate) const MORPH_COLS: [&str; 8] = ["morph0", "morph1", "morph2", "morph3", "morph4", "morph5", "morph6", "morph7"];+/// Up to 64 morph weights a model (Bevy takes 256; a MakeHuman face has 34 expression units).+pub(crate) const MORPH_COLS: [&str; 64] = ["morph0", "morph1", "morph2", "morph3", "morph4", "morph5", "morph6", "morph7", "morph8", "morph9", "morph10", "morph11", "morph12", "morph13", "morph14", "morph15", "morph16", "morph17", "morph18", "morph19", "morph20", "morph21", "morph22", "morph23", "morph24", "morph25", "morph26", "morph27", "morph28", "morph29", "morph30", "morph31", "morph32", "morph33", "morph34", "morph35", "morph36", "morph37", "morph38", "morph39", "morph40", "morph41", "morph42", "morph43", "morph44", "morph45", "morph46", "morph47", "morph48", "morph49", "morph50", "morph51", "morph52", "morph53", "morph54", "morph55", "morph56", "morph57", "morph58", "morph59", "morph60", "morph61", "morph62", "morph63"];/// The columns a frame may change, per kind (what `rows_into` and `camera` key); everything else is the first frame's.pub(crate) fn live_dynamic(kind: &str) -> &'static [&'static str] {match kind {"light" => &["lux", "lumens", "x", "y", "z", "dir_x", "dir_y", "dir_z"],"mesh" => &["x", "y", "z", "rot_x", "rot_y", "rot_z", "scale_x", "scale_y", "scale_z", "visible", "col_r", "col_g", "col_b", "rough", "metal", "emissive_k", "opacity", "sh_r", "sh_g", "sh_b", "rim_k", "spec_k", "outline_w", "pass"],- "model" => &["x", "y", "z", "rot_x", "rot_y", "rot_z", "scale_x", "scale_y", "scale_z", "visible", "anim_t", "mix0_t", "mix0_w", "mix1_t", "mix1_w", "mix2_t", "mix2_w", "mix3_t", "mix3_w", "morph0", "morph1", "morph2", "morph3", "morph4", "morph5", "morph6", "morph7", "g0_w", "g0_t", "g1_w", "g1_t", "g2_w", "g2_t", "g3_w", "g3_t", "g4_w", "g4_t", "g5_w", "g5_t", "g6_w", "g6_t", "g7_w", "g7_t", "g8_w", "g8_t", "g9_w", "g9_t", "g10_w", "g10_t", "g11_w", "g11_t", "g12_w", "g12_t", "g13_w", "g13_t", "g14_w", "g14_t", "g15_w", "g15_t", "look", "glitch_explode", "glitch_scramble", "glitch_jitter", "glitch_snap", "glitch_smear_x", "glitch_smear_y", "glitch_smear_z", "glitch_seed", "screen_power", "pass"],+ "model" => &["x", "y", "z", "rot_x", "rot_y", "rot_z", "scale_x", "scale_y", "scale_z", "visible", "anim_t", "mix0_t", "mix0_w", "mix1_t", "mix1_w", "mix2_t", "mix2_w", "mix3_t", "mix3_w", "morph0", "morph1", "morph2", "morph3", "morph4", "morph5", "morph6", "morph7", "morph8", "morph9", "morph10", "morph11", "morph12", "morph13", "morph14", "morph15", "morph16", "morph17", "morph18", "morph19", "morph20", "morph21", "morph22", "morph23", "morph24", "morph25", "morph26", "morph27", "morph28", "morph29", "morph30", "morph31", "morph32", "morph33", "morph34", "morph35", "morph36", "morph37", "morph38", "morph39", "morph40", "morph41", "morph42", "morph43", "morph44", "morph45", "morph46", "morph47", "morph48", "morph49", "morph50", "morph51", "morph52", "morph53", "morph54", "morph55", "morph56", "morph57", "morph58", "morph59", "morph60", "morph61", "morph62", "morph63", "g0_w", "g0_t", "g1_w", "g1_t", "g2_w", "g2_t", "g3_w", "g3_t", "g4_w", "g4_t", "g5_w", "g5_t", "g6_w", "g6_t", "g7_w", "g7_t", "g8_w", "g8_t", "g9_w", "g9_t", "g10_w", "g10_t", "g11_w", "g11_t", "g12_w", "g12_t", "g13_w", "g13_t", "g14_w", "g14_t", "g15_w", "g15_t", "look", "glitch_explode", "glitch_scramble", "glitch_jitter", "glitch_snap", "glitch_smear_x", "glitch_smear_y", "glitch_smear_z", "glitch_seed", "cloth_frame", "screen_power", "pass"],"panel" => &["x", "y", "z", "rot_x", "rot_y", "rot_z", "scale_x", "scale_y", "scale_z", "visible", "screen_power", "screen_bright", "pass"],"decal" => &["x", "y", "z", "rot_x", "rot_y", "rot_z", "scale_x", "scale_y", "scale_z", "visible", "col_r", "col_g", "col_b", "opacity", "rough", "metal"],_ => &[],diff --git a/runtime/scene/src/meshseq.rs b/runtime/scene/src/meshseq.rsindex 1ec7c5e8..cfa69358 100644--- a/runtime/scene/src/meshseq.rs+++ b/runtime/scene/src/meshseq.rs@@ -20,6 +20,16 @@ pub(super) fn glitch_columns(p: &mut Program, row: &mut BTreeMap<String, V>, id:}}+/// A Character part's cloth (`<Model cloth={{src, frame}}>`, docs/cloth.md K2): the baked `.rseq` of the part's own+/// vertices in its bind pose (raea/body tools/cloth.ts `--bind`), as `cloth`, and its frame keyed per frame as+/// `cloth_frame`. The engine puts that frame's positions and normals on the part's mesh and the skin poses them.+pub(super) fn cloth_columns(p: &mut Program, row: &mut BTreeMap<String, V>, id: &str, its: &[Item]) {+ let Some(src) = its.iter().find_map(|i| i.props.get("cloth").and_then(|c| c.get("src")).and_then(Value::as_str)) else { return };+ row.insert("cloth".into(), V::S(src_path(src)));+ let f = |i: &Item| i.props.get("cloth").and_then(|c| c.get("frame")).and_then(Value::as_f64).unwrap_or(0.0);+ column(p, row, id, "cloth_frame", &its.iter().map(f).collect::<Vec<_>>());+}+/// Numeric props of a sequence and the columns they key (the default when a frame leaves one out).const KEYED: &[(&str, &str, f64)] = &[("frame", "frame", 0.0), ("roughness", "rough", 0.3), ("metalness", "metal", 0.0)];diff --git a/runtime/scene/src/models.rs b/runtime/scene/src/models.rsindex ca819f99..346789ab 100644--- a/runtime/scene/src/models.rs+++ b/runtime/scene/src/models.rs@@ -53,7 +53,7 @@ pub(crate) fn models_rows(tr: &Tracks, names: &[String], p: &mut Program) {}if let Some(Value::Array(a)) = first.get("morphs") {row.insert("morph_names".into(), V::S(Value::Array(a.iter().map(|c| c.get("target").cloned().unwrap_or(Value::Null)).collect()).to_string()));- for i in 0..a.len() {+ for i in 0..a.len().min(64) {let vals: Vec<f64> = its.iter().map(|it| it.props.get("morphs").and_then(|x| x.get(i)).and_then(|c| c.get("weight")).and_then(Value::as_f64).unwrap_or(0.0)).collect();column(p, &mut row, &id, &format!("morph{i}"), &vals);}@@ -127,6 +127,7 @@ pub(crate) fn models_rows(tr: &Tracks, names: &[String], p: &mut Program) {}}meshseq::glitch_columns(p, &mut row, &id, &its);+ meshseq::cloth_columns(p, &mut row, &id, &its);placement(p, &mut row, &id, &its);visible(p, &mut row, &id, &track);pass_column(p, &mut row, &id, &its, &names);diff --git a/runtime/sound/src/lib.rs b/runtime/sound/src/lib.rsindex f733af89..ad1025d5 100644--- a/runtime/sound/src/lib.rs+++ b/runtime/sound/src/lib.rs@@ -298,8 +298,8 @@ static MAKING: std::sync::Mutex<Option<HashMap<String, Option<PathBuf>>>> = std:/// A generated sound for live play: the file a worker made, once it has; the worker started the first time it's asked/// for. Only local models: a paid one (lyria, speech) is made by a render, which counts it against the run's cap./// A generated <Audio>'s params as the asset store takes them, and its seed (as a Sampler's spec gives them, above):-/// its seconds and the generator's own settings (data-options: a TokenSynth note's midi, velocity, seed and precision; a-/// Fish voice and speed), the seed from them (1 without one). Every one of them is in the made sound's key.+/// its seconds and the generator's own settings (data-options: a TokenSynth note's midi, velocity, seed and+/// precision), the seed from them (1 without one). Every one of them is in the made sound's key.pub fn generated_params(seconds: f64, options: Option<&str>) -> (Value, u64) {let mut params = serde_json::Map::new();if let Some(Value::Object(o)) = options.and_then(|s| serde_json::from_str::<Value>(s).ok()) {diff --git a/sdk/asset/src/assets.ts b/sdk/asset/src/assets.tsindex b8098600..c05b4245 100644--- a/sdk/asset/src/assets.ts+++ b/sdk/asset/src/assets.ts@@ -1,7 +1,7 @@// Generated assets as values (spec: "Generated assets as values"). lyria() and sao() only describe what to make;// the renderer generates each one once, under the run's paid-generation cap, and caches it by id.-export type AssetKind = "lyria" | "sao" | "fish" | "tokensynth";+export type AssetKind = "lyria" | "sao" | "tokensynth";export interface GeneratedAsset {kind: AssetKind;@@ -11,7 +11,7 @@ export interface GeneratedAsset {id: string;/** "asset:<kind>/<id>" */src: string;- /** the generator's own settings (a TokenSynth note's midi, velocity, seed and device; a Fish voice) */+ /** the generator's own settings (a TokenSynth note's midi, velocity, seed and device) */options?: Record<string, unknown>;}@@ -45,17 +45,11 @@ export function sao(prompt: string, options: { seconds?: number } = {}): Generatreturn describe("sao", prompt, options.seconds ?? 2);}-/** Non-diegetic speech to generate (Fish: a narrator, a UI voice): the words are the prompt. `speed` is Fish's- * prosody speed (1 is its own pace; a documentary narrator reads nearer 0.85). */-export function fish(text: string, options: { seconds?: number; voice?: string; speed?: number } = {}): GeneratedAsset {- const a = describe("fish", text, options.seconds ?? 4);- const o: Record<string, unknown> = {};- if (options.voice) o.reference_id = options.voice;- if (options.speed !== undefined) {- if (!(options.speed >= 0.5 && options.speed <= 2)) throw new RangeError(`fish("${text.slice(0, 24)}..."): speed is 0.5 to 2, got ${options.speed}`);- o.prosody = { speed: options.speed };- }- return Object.keys(o).length ? { ...a, options: o } : a;+/** Retired on 2026-11-05: Fish narration is no longer part of raea. Narrate with `<Speech text start>` from+ * raea/speech (Pocket TTS, on this computer), or make a line with a `raea gen` step on `fish:<model>` and your own+ * FISH_API_KEY. Kept as a name only, so an older edit says what to use instead of failing to bundle. */+export function fish(text: string, _options: Record<string, unknown> = {}): never {+ throw new Error(`fish("${String(text).slice(0, 24)}"): fish left raea on 2026-11-05. Narrate with <Speech text start> from "raea/speech", or a raea gen step on fish:<model> with your FISH_API_KEY`);}/** One note of an instrument described in words, rendered by TokenSynth (local, CPU): a Sampler's root note. */@@ -73,7 +67,7 @@ export function isGeneratedAsset(v: unknown): v is GeneratedAsset {return (typeof v === "object" &&v !== null &&- ["lyria", "sao", "fish", "tokensynth"].includes((v as GeneratedAsset).kind) &&+ ["lyria", "sao", "tokensynth"].includes((v as GeneratedAsset).kind) &&typeof (v as GeneratedAsset).src === "string");}diff --git a/sdk/character/src/character.tsx b/sdk/character/src/character.tsxindex 0021b0bf..559177e9 100644--- a/sdk/character/src/character.tsx+++ b/sdk/character/src/character.tsx@@ -6,14 +6,14 @@//// import kid from "./media/characters/kid/skeleton.json" with { type: "json" };// registerBody(kid); // its glbs in media/characters/kid-// const pose = held(kid, { "RightArm": [-0.2, -0.6, 0.75] }); // or clipPose(clip, t), or the matcher+// const pose = held(kid, { upperarm_r: [-0.2, -0.6, 0.75] }); // or clipPose(clip, t), or the matcher// <Character body="kid" pose={pose} position={[0, 0, 1]} yaw={Math.PI}// goals={{ hands: { R: { at: MOUSE, point: [0, 0, -1] } }, look: SCREEN }} />//// Every joint's rest frame is the world's (the T-pose the skin is bound in, no bone roll), so a joint's turn is the same// kind of thing a BVH file gives: a rotation from rest, relative to its parent's. Frame-pure: a pose is a function of// its inputs, so a render and a live play agree.-export { skinJoints, add, sub, scale3, dot, cross, len, norm, qmul, qinv, qnorm, qrot, qaxis, qfromTo, slerp, qbasis, eulerXYZ, qyaw, joint, bodyScale, captured, rest, pose, withFingers, setWorld, held, aim, twoBone, softElbows, flatHand, cupHand, ballInHand, palmAt, handAlong, palmFacing, FINGERS, fingerJoints, HAND_LIMITS, handPose, SKIN_GIVE, closeOn, fingerSegments, surface, handSurface, reach, plant, lookAt, sit, blend, leanToward, solve, toBody, toScene, goalsToBody, registerBody, Character } from "./character/all";-export type { Quat, Joint, Skeleton, SkinJoint, Pose, Posed, Side, Finger, HandShape, Closing, FingerSegment, SurfacePoint, HandGoal, FootGoal, SeatGoal, Goals, Placement, CharacterProps, CharacterGhost } from "./character/all";+export { I, handRest, B, SIDES, BODY_JOINTS, FINGER_JOINTS, sideOf, mirrorName, roleOf, isFinger, skinJoints, add, sub, scale3, dot, cross, len, norm, qmul, qinv, qnorm, qrot, qaxis, qfromTo, slerp, qbasis, eulerXYZ, qyaw, joint, bodyScale, captured, rest, pose, withFingers, setWorld, held, aim, twoBone, softElbows, flatHand, cupHand, ballInHand, palmAt, handAlong, palmFacing, FINGERS, fingerJoints, HAND_LIMITS, RELAXED_HAND, RELAXED_CAPTURE, relaxHands, handPose, capturedHand, HAND_POSES, capturedLocal, alongPath, pathHand, pinchPoint, SKIN_GIVE, closeOn, fingerSegments, surface, handSurface, reach, plant, lookAt, sit, blend, leanToward, solve, toBody, toScene, goalsToBody, registerBody, Character, FACE_UNITS, FACE_PRESETS, faceWeights, HAIR_LOOK, HAIR_WESL, SKIN_LOOK, SKIN_SURFACE, SKIN_WESL } from "./character/all";+export type { Quat, Joint, Skeleton, Pose, Posed, Side, Finger, HandShape, Closing, FingerSegment, SurfacePoint, HandGoal, FootGoal, SeatGoal, Goals, Placement, CharacterProps, CharacterGhost, FaceUnit, FacePreset, Face, HairLook } from "./character/all";diff --git a/sdk/character/src/character/all.ts b/sdk/character/src/character/all.tsindex d6da317d..7b79152f 100644--- a/sdk/character/src/character/all.ts+++ b/sdk/character/src/character/all.ts@@ -1,9 +1,14 @@// Every part of character.tsx, in the order they load: each after what it uses while it loads. The parts import// each other only from here, so this order holds whichever is reached first.+export * from "./bones";export * from "./vectors";export * from "./skeleton";export * from "./goals";export * from "./fingers";+export * from "./captured";export * from "./solve";+export * from "./face";+export * from "./hair";+export * from "./skin";export * from "./drawing";export * from "./core";diff --git a/sdk/character/src/character/bones.ts b/sdk/character/src/character/bones.tsnew file mode 100644index 00000000..2bef97d3--- /dev/null+++ b/sdk/character/src/character/bones.ts@@ -0,0 +1,65 @@+// The joints' names: MakeHuman's game_engine rig (Unreal's mannequin names), raea's one character skeleton+// (docs/skeleton.feature SK0a). Every part of the SDK names joints through these, never with string literals.++export type Side = "L" | "R";++export const SIDES: readonly Side[] = ["L", "R"];++/** the suffix a side's joints carry */+const sx = (s: Side) => (s === "L" ? "l" : "r");++export const FINGERS = ["thumb", "index", "middle", "ring", "pinky"] as const;++export type Finger = (typeof FINGERS)[number];++/** Joint names, by role. A body's joints are the trunk, then each arm and leg; the fingers come after all of them. */+export const B = {+ pelvis: "pelvis",+ /** the spine from the pelvis up: spine_01 (the waist), spine_02, spine_03 (the chest, which the clavicles and neck hang from) */+ spine: ["spine_01", "spine_02", "spine_03"] as const,+ chest: "spine_03",+ neck: "neck_01",+ head: "head",+ clavicle: (s: Side) => `clavicle_${sx(s)}`,+ upperarm: (s: Side) => `upperarm_${sx(s)}`,+ lowerarm: (s: Side) => `lowerarm_${sx(s)}`,+ hand: (s: Side) => `hand_${sx(s)}`,+ thigh: (s: Side) => `thigh_${sx(s)}`,+ calf: (s: Side) => `calf_${sx(s)}`,+ foot: (s: Side) => `foot_${sx(s)}`,+ /** the ball of the foot, where the toes bend */+ ball: (s: Side) => `ball_${sx(s)}`,+ /** a finger's phalanx k (1 at the knuckle, 3 at the tip; the thumb's 1 is its metacarpal) */+ finger: (f: Finger, k: 1 | 2 | 3, s: Side) => `${f}_0${k}_${sx(s)}`,+ arm: (s: Side) => [B.upperarm(s), B.lowerarm(s), B.hand(s)],+ leg: (s: Side) => [B.thigh(s), B.calf(s), B.foot(s)],+ /** both feet's ankles then both balls: L foot, R foot, L ball, R ball */+ feet: () => [B.foot("L"), B.foot("R"), B.ball("L"), B.ball("R")],+};++/** The body's joints in skeleton order (parents first): what a clip turns. */+export const BODY_JOINTS: readonly string[] = [+ B.pelvis, ...B.spine, B.neck, B.head,+ ...SIDES.flatMap((s) => [B.clavicle(s), B.upperarm(s), B.lowerarm(s), B.hand(s)]),+ ...SIDES.flatMap((s) => [B.thigh(s), B.calf(s), B.foot(s), B.ball(s)]),+];++/** The fingers' joints in skeleton order, after the body's: each side's thumb, index, middle, ring, pinky, 1 to 3. */+export const FINGER_JOINTS: readonly string[] = SIDES.flatMap((s) => FINGERS.flatMap((f) => ([1, 2, 3] as const).map((k) => B.finger(f, k, s))));++/** a joint's side from its name ("" on the midline) */+export function sideOf(name: string): Side | "" {+ return name.endsWith("_l") ? "L" : name.endsWith("_r") ? "R" : "";+}++/** a joint's name on the other side (itself on the midline) */+export function mirrorName(name: string): string {+ return name.endsWith("_l") ? name.slice(0, -1) + "r" : name.endsWith("_r") ? name.slice(0, -1) + "l" : name;+}++/** a joint's role, its name without the side: "thigh", "index_02", "spine_01" */+export function roleOf(name: string): string {+ return name.replace(/_[lr]$/, "");+}++export const isFinger = (name: string): boolean => FINGERS.some((f) => name.startsWith(f + "_"));diff --git a/sdk/character/src/character/captured.ts b/sdk/character/src/character/captured.tsnew file mode 100644index 00000000..e250d32f--- /dev/null+++ b/sdk/character/src/character/captured.ts@@ -0,0 +1,124 @@+// Hands from captured poses (Shane, 11-01: "the fingers are definitely fucked up ... can we find some assets that+// exist for grips"): 35 hand poses made on a MakeHuman hand by DigitalN8m4r3 for Godot XR Tools (CC0), the grips,+// pinches and cups among them, read out of its Blender file by projects/psx/handposes.py into hands.json. Each+// finger bone is [its direction, its own x axis] in the hand's frame [along, palm, across] (across toward the thumb,+// palm out of the palm), so a right hand's pose is a left hand's too.+//+// A body's finger takes the capture's turn from the capture's rest as the body's arm takes a clip's (retarget.ts):+// laid first along the capture's bone at rest (F), then turned as the capture's bone turned from its rest (D), with+// the hand wherever it is.+import { type Vec3 } from "@raea/render/3d";+import { B, FINGERS, Finger, I, Pose, Quat, Side, Skeleton, add, cross, dot, fingerJoints, handRest, joint, norm, palmAt, pose, qbasis, qfromTo, qinv, qmul, qrot, rest, scale3, slerp, sub, withFingers } from "./all";+import data from "./hands.json" with { type: "json" };++/** a captured hand: each finger's three bones, [direction, x axis] in the hand's frame */+export type CapturedHand = Record<Finger, [Vec3, Vec3][]>;++const REST = data.rest as unknown as CapturedHand;+/** the captured poses by name: "Grip", "Grip Shaft", "Cup", "Pinch Tight", "Pinch Large", "Hold", "Rounded", ... */+export const HAND_POSES = data.poses as unknown as Record<string, CapturedHand>;++/** a hand-frame vector in the world, the frame given by its three axes */+const inFrame = (c: Vec3, f: { along: Vec3; palm: Vec3; across: Vec3 }): Vec3 => [+ c[0] * f.along[0] + c[1] * f.palm[0] + c[2] * f.across[0],+ c[0] * f.along[1] + c[1] * f.palm[1] + c[2] * f.across[1],+ c[0] * f.along[2] + c[1] * f.palm[2] + c[2] * f.across[2],+];+/** a bone's frame from its direction and x axis (squared), as a turn */+const boneFrame = (d: Vec3, x: Vec3): Quat => {+ const a = norm(d), z = norm(cross(a, x));+ return qbasis(a, cross(z, a), z);+};++const restTurns = new WeakMap<Skeleton, Partial<Record<Side, Map<string, Quat[][]>>>>();++/** each finger bone's world turn from rest, for a hand at rest, to take the captured pose `c` */+function turnsAtRest(skel: Skeleton, s: Side, c: CapturedHand): Quat[][] {+ const r = handRest(skel, s), F = fingerJoints(skel, s), J = skel.joints;+ return FINGERS.map((f, k) => F[k].map((i, ph) => {+ const [rd, rx] = REST[f][ph], [pd, px] = c[f][ph];+ const was = boneFrame(inFrame(rd, r), inFrame(rx, r)), now = boneFrame(inFrame(pd, r), inFrame(px, r));+ // F: the body's bone along the capture's at rest; D: the capture's bone's turn from its rest+ const fix = qfromTo(sub(J[i].tail, J[i].head), inFrame(rd, r));+ return qmul(qmul(now, qinv(was)), fix);+ }));+}++function cached(skel: Skeleton, s: Side, name: string, c: CapturedHand): Quat[][] {+ let m = restTurns.get(skel);+ if (!m) restTurns.set(skel, (m = {}));+ const bySide = (m[s] ??= new Map());+ let t = bySide.get(name);+ if (!t) bySide.set(name, (t = turnsAtRest(skel, s, c)));+ return t;+}++/** A hand in a captured pose (a name in HAND_POSES, or one given), `t` of the way from the pose's own fingers+ * (1: all of it). The fingers follow the hand wherever the pose has it. For a skeleton without fingers, the pose as+ * it was. */+export function capturedHand(skel: Skeleton, p: Pose, s: Side, which: string | CapturedHand, t = 1): Pose {+ const F = fingerJoints(skel, s);+ if (!F.length) return p;+ const c = typeof which === "string" ? HAND_POSES[which] : which;+ if (!c) throw new Error(`capturedHand: no hand pose ${which} (there are ${Object.keys(HAND_POSES).join(", ")})`);+ const G = typeof which === "string" ? cached(skel, s, which, c) : turnsAtRest(skel, s, c);+ const turns = p.turns.slice();+ while (turns.length < skel.joints.length) turns.push(I);+ const hand = pose(skel, p).rot[joint(skel, B.hand(s))];+ F.forEach((chain, k) => {+ let parent = hand;+ chain.forEach((i, ph) => {+ const world = qmul(hand, G[k][ph]);+ const local = qmul(qinv(parent), world);+ turns[i] = t >= 1 ? local : slerp(turns[i] ?? I, local, t);+ parent = qmul(parent, turns[i]);+ });+ });+ return { ...p, turns };+}++const locals = new WeakMap<Skeleton, Partial<Record<Side, Map<string, Quat[][]>>>>();++/** each finger joint's own turn (against the bone it hangs from) in the captured pose `name`: the same wherever the+ * hand is, so a path between poses is turns to slerp */+export function capturedLocal(skel: Skeleton, s: Side, name: string): Quat[][] {+ let m = locals.get(skel);+ if (!m) locals.set(skel, (m = {}));+ const bySide = (m[s] ??= new Map());+ let L = bySide.get(name);+ if (!L) {+ const c = HAND_POSES[name];+ if (!c) throw new Error(`capturedLocal: no hand pose ${name}`);+ const G = cached(skel, s, name, c);+ bySide.set(name, (L = G.map((g) => g.map((q, ph) => (ph === 0 ? q : qmul(qinv(g[ph - 1]), q))))));+ }+ return L;+}++/** finger `k`'s joint `ph` at `u` along `path` (captured poses, open to closed: 0 the first, 1 the second, ...) */+export function alongPath(skel: Skeleton, s: Side, path: readonly string[], k: number, ph: number, u: number): Quat {+ const v = Math.max(0, Math.min(path.length - 1, u)), i = Math.min(path.length - 2, Math.floor(v));+ if (path.length === 1) return capturedLocal(skel, s, path[0])[k][ph];+ return slerp(capturedLocal(skel, s, path[i])[k][ph], capturedLocal(skel, s, path[i + 1])[k][ph], v - i);+}++/** A hand along a captured path: each finger's joints where `at` puts them along it (a finger left out at the path's+ * start), from finger `from` on (1: the thumb left as it is). The fingers' joint turns only; the hand as the pose has+ * it. */+export function pathHand(skel: Skeleton, p: Pose, s: Side, path: readonly string[], at: Partial<Record<Finger, [number, number, number]>>, from = 0): Pose {+ const F = fingerJoints(skel, s);+ if (!F.length) return p;+ const turns = p.turns.slice();+ while (turns.length < skel.joints.length) turns.push(I);+ F.forEach((chain, k) => k >= from && chain.forEach((i, ph) => { turns[i] = alongPath(skel, s, path, k, ph, at[FINGERS[k]]?.[ph] ?? 0); }));+ return { ...p, turns };+}++/** where a captured pinch's pads meet (between the thumb's tip and the index's), from the palm's middle (palmAt), in+ * the hand's frame [along, palm, across]: where a pinched thing sits in the hand */+export function pinchPoint(skel: Skeleton, s: Side, name = "Pinch Tight"): Vec3 {+ const p = capturedHand(skel, rest(skel), s, name), w = withFingers(skel, pose(skel, p)), r = handRest(skel, s), J = skel.joints;+ const tip = (n: string) => { const i = joint(skel, n); return add(w.pos[i], qrot(w.rot[i], sub(J[i].tail, J[i].head))); };+ const mid = scale3(add(tip(B.finger("thumb", 3, s)), tip(B.finger("index", 3, s))), 0.5), d = sub(mid, palmAt(skel, w, s));+ return [dot(d, r.along), dot(d, r.palm), dot(d, r.across)];+}diff --git a/sdk/character/src/character/core.ts b/sdk/character/src/character/core.tsindex d4ce06da..f0c86a31 100644--- a/sdk/character/src/character/core.ts+++ b/sdk/character/src/character/core.ts@@ -1,24 +1,21 @@// The skeleton's types: joints, skeletons, poses.import { type Vec3 } from "@raea/render/3d";-import { Side, add, qmul, qrot, slerp, sub, withFingers } from "./all";+import { Side, withFingers } from "./all";export type Quat = [number, number, number, number];export interface Joint {name: string;- /** the parent's index, -1 for the root (Hips) */+ /** the parent's index, -1 for the root (the pelvis) */parent: number;/** where the joint is at rest, and where its bone ends (the next joint's head, mostly): metres, the body's frame */head: Vec3;tail: Vec3;- /** a finger's joint (after the capture's 31): the capture's joint its skin rode before it had its own (a phalanx 1- * the finger base, 2 and 3 the finger, the thumb's the thumb). Its turn is on top of that chain's (see `pose`) */- follow?: number;/** a finger's joint: its thickness (the median of its skin's distance from the bone), metres */radius?: number;}-/** A body's skeleton, as character.py writes it (skeleton.json). The body's frame: y up, facing +z, x its left, feet on+/** A body's skeleton, as projects/psx/export.py writes it (skeleton.json): MakeHuman's game_engine joints (bones.ts). The body's frame: y up, facing +z, x its left, feet on* y = 0. */export interface Skeleton {name: string;@@ -27,40 +24,19 @@ export interface Skeleton {joints: Joint[];/** between the eyes; how far the hip joints sit over a seat (the back of the thigh under them) */landmarks: { eyes: Vec3; sitDrop?: number };- /** where each joint stands with the body at rest (Anny's own A-pose) and its turn from there to the T-pose */- bind?: { turns: Quat[]; heads: Vec3[] };- /** the skin's own joints (character.py binds the skin with Anny's default rig's weights): each at its head at rest,- * carried by the joint `drive`, turned as `from` slerped `u` of the way to `to` */- skin?: SkinJoint[];- /** samples of the skin's surface (`surface`): each a rest vertex of body.glb, its offset `o` from skin joint j[0]'s- * head, its normal `n` at rest, and its skin joints `j` and weights `w` as the glb has them */+ /** samples of the skin's surface: each a rest vertex of body.glb, its offset `o` from joint j[0]'s head, its normal+ * `n` at rest, and its joints `j` and weights `w` as the glb skins it */surface?: { part: string; side: Side | ""; j: number[]; w: number[]; o: Vec3; n: Vec3 }[];}-export interface SkinJoint {- name: string;- head: Vec3;- drive: number;- from: number;- to: number;- u: number;-}--/** The skin's joints at a pose (the skeleton's own when it has no skin of its own): each's place and world turn. */+/** The joints at a pose as the skin follows them (each body.glb bone is the joint of its name): each's place and+ * world turn, the fingers' too. */export function skinJoints(skel: Skeleton, w: Posed): { name: string; pos: Vec3; rot: Quat }[] {w = withFingers(skel, w);- if (!skel.skin || !skel.bind) return skel.joints.map((j, i) => ({ name: j.name, pos: w.pos[i], rot: w.rot[i] }));- const { turns, heads } = skel.bind;- // each joint's turn from the body at rest: from rest to the T-pose, then the pose's from there- const fromRest = w.rot.map((r, i) => qmul(r, turns[i]));- return skel.skin.map((s) => ({- name: s.name,- pos: add(w.pos[s.drive], qrot(fromRest[s.drive], sub(s.head, heads[s.drive]))),- rot: s.from === s.to ? fromRest[s.from] : slerp(fromRest[s.from], fromRest[s.to], s.u),- }));+ return skel.joints.map((j, i) => ({ name: j.name, pos: w.pos[i], rot: w.rot[i] }));}-/** A pose: where the root (Hips) is in the body's frame, and each joint's turn from rest relative to its parent (by+/** A pose: where the root (the pelvis) is in the body's frame, and each joint's turn from rest relative to its parent (by* joint index; a missing one is no turn). */export interface Pose {root: Vec3;diff --git a/sdk/character/src/character/drawing.tsx b/sdk/character/src/character/drawing.tsxindex 072aea64..49b40014 100644--- a/sdk/character/src/character/drawing.tsx+++ b/sdk/character/src/character/drawing.tsx@@ -1,10 +1,12 @@// Placement in the scene, and drawing a body: <Character>.import type { ReactNode } from "react";-import { Model, type Vec3 } from "@raea/render/3d";+import { MeshPhysicalMaterial, MeshStandardMaterial, Model, type Vec3 } from "@raea/render/3d";+import { HAIR_LOOK, HAIR_WESL, type HairLook } from "./hair";+import { SKIN_LOOK, SKIN_SURFACE, SKIN_WESL, type SkinLook, type SkinSurface } from "./skin";import { LinearRgba, Srgba, StandardMaterial } from "@raea/render/bevy3d";import type { Glitch } from "@raea/physics/physics";import { staticFile } from "@raea/video/media";-import { Goals, Pose, Side, Skeleton, add, eulerXYZ, pose, qmul, qrot, qyaw, rest, scale3, skinJoints, solve, sub } from "./all";+import { Goals, Pose, Side, Skeleton, add, eulerXYZ, faceWeights, pose, qmul, qrot, qyaw, rest, scale3, skinJoints, solve, sub, type Face } from "./all";// ---------------------------------------------------------------- placement@@ -65,7 +67,7 @@ export interface CharacterProps extends Placement {pose?: Pose;/** goals met on top of the pose, in the scene's coordinates */goals?: Goals;- /** its ink outline (the inverted hull; true by default, false for a ghost): looks with their own outlines leave it out */+ /** its ink outline (the inverted hull): off unless asked for (true), as a look that wants an ink line does */outline?: boolean;/** the skin's own triangles broken up by the frame's values (physics.tsx's Glitch: explode, scramble, jitter, snap,* smear, seed) while it keeps following the pose; the hull, if drawn, glitched the same */@@ -75,11 +77,45 @@ export interface CharacterProps extends Placement {ghost?: CharacterGhost;/** the composition pass its skin (and hull) draws in (Mesh's `pass`; "scene" by default) */pass?: string;+ /** the face (a psx body's morph targets): any of MakeHuman's 34 expression units by name (FACE_UNITS:+ * "mouth-open", "eyebrows-left-up" ...) and presets mixed from them (FACE_PRESETS: blink, smile, frown, surprise,+ * sad, and the lips' open, pucker and wide), 0 to 1; they add */+ face?: Face;+ /** the hair drawn as hair (character/hair.ts: strand highlights on the body's "hair" material, after lighting): on by+ * default, false for the plain surface, or settings over HAIR_LOOK; `coverage: true` softens the cards' cut edges+ * (alphaMode "coverage", for a scene with <AntiAliasing mode="msaa">: without MSAA the cards draw solid); `color`+ * tints the hair's texture (a hex colour: a creator's hair colour) */+ hair?: boolean | (Partial<HairLook> & { coverage?: boolean; color?: string });+ /** the skin drawn as skin (character/skin.ts, on the body's "skin" material): the fine relief of real skin (fading out with distance), the photo's own surface detail,+ * a second, tighter shine (clearcoat) and light scattered under the skin (a soft, reddened falloff at shadow edges).+ * Off by default; true, or settings over SKIN_LOOK and SKIN_SURFACE. `mask` is the fine relief's strength by region (the+ * body's skin_mask.png, which projects/psx bodies have; false for even relief everywhere); `detailMap` the photo's surface+ * detail (the body's skin_detail.png, psx bodies since 11-05; false for none); `microMap` the fine relief tile (the+ * body's skin_micro.png, from a photograph of real skin; false for none) */+ skin?: boolean | (Partial<SkinLook> & Partial<SkinSurface> & { mask?: string | false; detailMap?: string | false; microMap?: string | false });+ /** more of the body's morph targets by name, beside the face's: a character kit's face-*, weight-*, age-* and tuck-*+ * (corpo's people/kit.py). Name the same set every frame: the engine fixes a model's morph names when it makes it */+ morphs?: Record<string, number>;+ /** more skinned models on the same joints, drawn with the body: a kit's garments and hair (parts/*.glb), each with+ * its own morph weights and materials. A part named "hair" in its src is shaded as hair, as the body's own is */+ parts?: CharacterPart[];/** the skin's materials, as a <Model>'s: <MeshStandardMaterial> re-covering its glTF materials (all, or the one* `material` names), with or without a `shader` over them (docs/shaders.feature SH3); the joints and hull keep theirs */children?: ReactNode;}+/** A model worn on the body's joints (a garment, hair): its glTF's joints named as the body's. */+export interface CharacterPart {+ /** its .glb */+ src: string;+ /** its morph targets' weights by name (a kit part carries the body's weight-*, age-* and, for hair, face-*) */+ morphs?: Record<string, number>;+ /** its cloth: a baked simulation of its vertices in its bind pose and the frame drawn (<Model cloth>, docs/cloth.md) */+ cloth?: { src: string; frame: number };+ /** <MeshStandardMaterial> re-covering its materials, as the body's children do */+ children?: ReactNode;+}+/** A ghost's material: one colour over the whole skin (its own picture taken off). */export interface CharacterGhost {/** hex colour ("#33e6ff") */@@ -97,6 +133,32 @@ export interface CharacterGhost {/** An Anny body posed. Each joint is a hidden model where the pose puts it, and the skin follows them (Model's* `bones`). Groups are flattened before the engine sees them while a skin's joints are placed in the skin's own frame,* so a Character is placed by its own position, yaw and scale, never inside a <Group>. */+/** the body's "hair" material shaded as hair (character/hair.ts) */+function hairMaterial(h: CharacterProps["hair"]) {+ const { coverage, color, ...look } = typeof h === "object" ? h : ({} as { coverage?: boolean; color?: string });+ return <MeshStandardMaterial material="hair" roughness={1} reflectance={0.04} {...(color ? { color } : {})} {...(coverage ? { alphaMode: "coverage" as const } : {})} shader={{ wesl: HAIR_WESL, uniforms: { ...HAIR_LOOK, ...look } as Record<string, number | number[]> }} />;+}++/** the body's "skin" material shaded as skin (character/skin.ts) */+function skinMaterial(sk: CharacterProps["skin"], src: string) {+ const { mask, detailMap, microMap, clearcoat, clearcoatRoughness, reflectance, ...look } = typeof sk === "object" ? sk : ({} as Exclude<CharacterProps["skin"], boolean | undefined>);+ const dir = src.replace(/^\//, ""); // (an asset path: no leading slash)+ const m = mask === false ? undefined : (mask ?? `${dir}/skin_mask.png`);+ const dm = detailMap === false ? undefined : (detailMap ?? `${dir}/skin_detail.png`);+ const mm = microMap === false ? undefined : (microMap ?? `${dir}/skin_micro.png`);+ const textures = { ...(m ? { mask: m } : {}), ...(dm ? { detail: dm } : {}), ...(mm ? { micro: mm } : {}) };+ const defs = { ...(m ? { SKIN_MASK: true } : {}), ...(dm ? { SKIN_DETAIL: true } : {}), ...(mm ? { SKIN_MICRO: true } : {}) };+ const surface = { ...SKIN_SURFACE, ...(clearcoat !== undefined ? { clearcoat } : {}), ...(clearcoatRoughness !== undefined ? { clearcoatRoughness } : {}), ...(reflectance !== undefined ? { reflectance } : {}) };+ return (+ <MeshPhysicalMaterial+ material="skin"+ {...surface}+ diffuseTransmission={0}+ shader={{ wesl: SKIN_WESL, uniforms: { ...SKIN_LOOK, ...look } as Record<string, number | number[]>, ...(m || dm || mm ? { textures, defs } : {}) }}+ />+ );+}+export function Character(props: CharacterProps) {const reg = typeof props.body === "string" ? bodies.get(props.body) : undefined;if (typeof props.body === "string" && !reg) throw new Error(`Character: no body ${props.body} (registerBody its skeleton.json first; registered: ${[...bodies.keys()].join(", ") || "none"})`);@@ -115,17 +177,31 @@ export function Character(props: CharacterProps) {const bones = Object.fromEntries(sj.map((j) => [j.name, `${name}-${j.name}`]));const g = props.glitch, ghost = props.ghost;const pass = props.pass !== undefined ? { pass: props.pass } : {};+ // (all 34 units always named, so the model's morph names never change: the engine fixes them when it makes the model)+ const named = { ...(props.face ? faceWeights(props.face) : {}), ...(props.morphs ?? {}) };+ const morphs = Object.keys(named).length ? { morphs: named } : {};const glitch = g ? { explode: g.explode ?? 0, scramble: g.scramble ?? 0, jitter: g.jitter ?? 0, snap: g.snap ?? 0, smear: g.smear ?? [0, 0, 0], seed: g.seed ?? 0 } : undefined;return (<>{sj.map((j) => (<Model key={j.name} name={`${name}-${j.name}`} src={`${src}/joint.glb`} position={scale3(toScene(at, j.pos), 1 / k)} rotation={eulerXYZ(qmul(turn, j.rot))} scale={0.001} />))}- <Model name={`${name}-body`} src={`${src}/body.glb`} bones={bones} scale={k} allowOverlap={ghost ? true : undefined} flat={ghost ? ghost.unlit !== false : undefined} {...(glitch ? { glitch } : {})} {...pass}>+ <Model name={`${name}-body`} src={`${src}/body.glb`} bones={bones} scale={k} allowOverlap={ghost ? true : undefined} flat={ghost ? ghost.unlit !== false : undefined} {...(glitch ? { glitch } : {})} {...pass} {...morphs}>{props.children}+ {!ghost && props.hair !== false && hairMaterial(props.hair)}+ {!ghost && props.skin && skinMaterial(props.skin, src)}{ghost && <StandardMaterial base_color_texture={null} base_color={ghost.opacity !== undefined ? Srgba.hex(ghost.color).with_alpha(ghost.opacity) : ghost.color} {...(ghost.opacity !== undefined && ghost.opacity < 1 ? { alpha_mode: "Blend" as const } : {})} {...(ghost.emissive ? { emissive: LinearRgba.from(Srgba.hex(ghost.emissive)).mul(ghost.emissiveIntensity ?? 1) } : {})} />}</Model>- {(props.outline ?? !ghost) && <Model name={`${name}-hull`} src={`${src}/body.hull.glb`} bones={bones} scale={k} flat {...(glitch ? { glitch } : {})} {...pass} />}+ {(props.parts ?? []).map((part) => {+ const id = part.src.split("/").pop()!.replace(/\.glb$/, "");+ return (+ <Model key={id} name={`${name}-${id}`} src={part.src} bones={bones} scale={k} {...(glitch ? { glitch } : {})} {...pass} {...(part.morphs && Object.keys(part.morphs).length ? { morphs: part.morphs } : {})} {...(part.cloth ? { cloth: part.cloth } : {})}>+ {part.children}+ {id.includes("hair") && props.hair !== false && hairMaterial(props.hair)}+ </Model>+ );+ })}+ {props.outline === true && !ghost && <Model name={`${name}-hull`} src={`${src}/body.hull.glb`} bones={bones} scale={k} flat {...(glitch ? { glitch } : {})} {...pass} />}</>);}diff --git a/sdk/character/src/character/face.ts b/sdk/character/src/character/face.tsnew file mode 100644index 00000000..6011901d--- /dev/null+++ b/sdk/character/src/character/face.ts@@ -0,0 +1,49 @@+// A psx body's face: MakeHuman's 34 expression units (MPFB2's CC0 targets/expression/units, the FACS-like pieces+// MakeHuman mixes its own expressions from), baked into body.glb as morph targets by projects/psx (faces.py), each+// mixed for the person's ancestry. <Character face> sets any of them by name, or a preset (smile, frown ...) that is+// a mix of them; presets and units add, and each unit's weight is held to 0..1.++/** The 34 units, in the body's morph targets' order. */+export const FACE_UNITS = [+ "eye-left-closure", "eye-left-opened-up", "eye-left-slit", "eye-right-closure", "eye-right-opened-up", "eye-right-slit",+ "eyebrows-left-down", "eyebrows-left-extern-up", "eyebrows-left-inner-up", "eyebrows-left-up",+ "eyebrows-right-down", "eyebrows-right-extern-up", "eyebrows-right-inner-up", "eyebrows-right-up",+ "mouth-compression", "mouth-corner-puller", "mouth-depression", "mouth-depression-retraction", "mouth-elevation",+ "mouth-eversion", "mouth-open", "mouth-parling", "mouth-part-later", "mouth-protusion", "mouth-pursing",+ "mouth-retraction", "mouth-upward-retraction", "neck-platysma", "nose-compression", "nose-depression",+ "nose-left-dilatation", "nose-left-elevation", "nose-right-dilatation", "nose-right-elevation",+] as const;+export type FaceUnit = (typeof FACE_UNITS)[number];++const both = (unit: string, w: number) => ({ [unit.replace("SIDE", "left")]: w, [unit.replace("SIDE", "right")]: w }) as Partial<Record<FaceUnit, number>>;++/** Expressions as mixes of the units. Lips: open (a jaw drop), pucker (oo, w), wide (ee); feelings: smile, frown,+ * surprise, sad; and blink. */+export const FACE_PRESETS = {+ blink: both("eye-SIDE-closure", 1),+ // the full corner pull read as a grin at 1; this is a warm smile+ smile: { "mouth-corner-puller": 0.55, "mouth-upward-retraction": 0.15, ...both("eye-SIDE-slit", 0.25) },+ frown: { ...both("eyebrows-SIDE-down", 1), "mouth-depression": 0.7, ...both("nose-SIDE-elevation", 0.35) },+ surprise: { ...both("eyebrows-SIDE-up", 1), ...both("eye-SIDE-opened-up", 0.7) },+ open: { "mouth-open": 1 },+ pucker: { "mouth-pursing": 1, "mouth-protusion": 0.5 },+ wide: { "mouth-retraction": 1 },+ sad: { ...both("eyebrows-SIDE-inner-up", 1), "mouth-depression": 0.5 },+} satisfies Record<string, Partial<Record<FaceUnit, number>>>;+export type FacePreset = keyof typeof FACE_PRESETS;+export type Face = Partial<Record<FaceUnit | FacePreset, number>>;++/** every unit's weight for a face (all 34 named, so a model's morph names never change from frame to frame) */+export function faceWeights(face: Face): Record<FaceUnit, number> {+ const w = Object.fromEntries(FACE_UNITS.map((u) => [u, 0])) as Record<FaceUnit, number>;+ for (const [k, v] of Object.entries(face)) {+ if (v === undefined) continue;+ if (!Number.isFinite(v)) throw new RangeError(`Character: face.${k} is a weight, got ${v}`);+ const mix = (FACE_PRESETS as Record<string, Partial<Record<FaceUnit, number>>>)[k];+ if (mix) for (const [u, m] of Object.entries(mix)) w[u as FaceUnit] += m! * v;+ else if (k in w) w[k as FaceUnit] += v;+ else throw new RangeError(`Character: face.${k} is not a face unit or preset (${Object.keys(FACE_PRESETS).join(", ")}, or one of FACE_UNITS)`);+ }+ for (const u of FACE_UNITS) w[u] = Math.min(1, Math.max(0, w[u]));+ return w;+}diff --git a/sdk/character/src/character/fingers.ts b/sdk/character/src/character/fingers.tsindex 1b07734c..9857d8cd 100644--- a/sdk/character/src/character/fingers.ts+++ b/sdk/character/src/character/fingers.ts@@ -1,24 +1,38 @@// Fingers: hand shapes and closing on a thing.import { type Vec3 } from "@raea/render/3d";-import { FingerSegment, I, Pose, Posed, Quat, Side, Skeleton, add, cross, dot, fingerSegments, handRest, joint, norm, place, pose, qaxis, qmul, qrot, scale3, slerp, sub, surface, withFingers } from "./all";+import { B, FINGERS, Finger, FingerSegment, alongPath, captured, capturedHand, I, pathHand, Pose, Posed, Quat, Side, Skeleton, add, cross, dot, fingerSegments, handRest, joint, norm, place, pose, qaxis, qmul, qrot, scale3, slerp, sub, surface, withFingers } from "./all";// ---------------------------------------------------------------- fingers-export const FINGERS = ["thumb", "index", "middle", "ring", "pinky"] as const;--export type Finger = (typeof FINGERS)[number];-/** Each finger's own joints on a side (thumb first), phalanx 1 to 3; empty for a skeleton without them. */export function fingerJoints(skel: Skeleton, s: Side): number[][] {- const S = s === "L" ? "Left" : "Right", has = skel.joints.some((j) => j.name === `${S}HandIndex1`);- if (!has) return [];- return FINGERS.map((f) => [1, 2, 3].map((k) => joint(skel, `${S}Hand${f[0].toUpperCase()}${f.slice(1)}${k}`)));+ if (!skel.joints.some((j) => j.name === B.finger("index", 1, s))) return [];+ return FINGERS.map((f) => ([1, 2, 3] as const).map((k) => joint(skel, B.finger(f, k, s))));}/** A hand's shape: each finger's curl at its three joints (radians; + bends toward the palm, about each bone's own* hinge, so a fist is about [1.4, 1.6, 1.1] on the fingers), how far the fingers fan apart (radians at the index and* pinky, + spreads), and the thumb's opposition (radians about the hand's length, + swings it under the palm toward* the fingers, as a pinch or a grip round a glass's stem wants). A finger left out is straight. */+/** A hand at ease, as a hanging hand rests: the fingers a little curled, more toward the pinky, the thumb in a little+ * (for clips without fingers: 100STYLE's and most of CMU's) */+export const RELAXED_HAND: HandShape = {+ index: [0.2, 0.3, 0.15], middle: [0.28, 0.38, 0.2], ring: [0.34, 0.44, 0.24], pinky: [0.4, 0.5, 0.28],+ thumb: [0.1, 0.2, 0.1], spread: 0.04, thumbOpp: 0.25,+};++/** the captured hand a hanging hand rests in (Godot XR Tools' "Rounded": the fingers curled at all three joints, more+ * toward the pinky; RELAXED_HAND's curls left the middle and end joints near straight, a flat hand) */+export const RELAXED_CAPTURE = "Rounded";++/** a pose with both hands at ease (RELAXED_CAPTURE on a body with fingers, else RELAXED_HAND) where it has no finger+ * turns of its own */+export function relaxHands(skel: Skeleton, p: Pose): Pose {+ if (p.turns.length > captured(skel)) return p;+ if (fingerJoints(skel, "L").length) return capturedHand(skel, capturedHand(skel, p, "L", RELAXED_CAPTURE), "R", RELAXED_CAPTURE);+ return handPose(skel, handPose(skel, p, "L", RELAXED_HAND), "R", RELAXED_HAND);+}+export interface HandShape {thumb?: [number, number, number];index?: [number, number, number];@@ -66,12 +80,11 @@ const clampTo = (x: number, [lo, hi]: [number, number]) => Math.max(lo, Math.min/** A hand shaped: each finger's and the thumb's joints curled as `h` says (held inside HAND_LIMITS), in place of the* capture's own fingers (the finger base, finger and thumb it turns are set straight, so the shape is the hand's* whatever the clip had them doing). For a skeleton without fingers of its own, the pose as it was. */-export function handPose(skel: Skeleton, p: Pose, s: Side, h: HandShape): Pose {+export function handPose(skel: Skeleton, p: Pose, s: Side, h: HandShape, only?: readonly Finger[]): Pose {const F = fingerJoints(skel, s);if (!F.length) return p;const ax = axesOf(skel, s), turns = p.turns.slice();while (turns.length < skel.joints.length) turns.push(I);- for (const n of s === "L" ? ["LeftFingerBase", "LeftHandFinger1", "LThumb"] : ["RightFingerBase", "RightHandFinger1", "RThumb"]) turns[joint(skel, n)] = I;// (the fan: the index out the most, the middle barely, the ring and pinky the other way)const fan = [0, 1, 0.15, -0.55, -1];// the thumb `t` of the way to its shape (its curl and its swing under the palm; a thumb curled back or swung out@@ -83,7 +96,7 @@ export function handPose(skel: Skeleton, p: Pose, s: Side, h: HandShape): Pose {turns[i] = q;});FINGERS.forEach((f, k) => {- if (k === 0) return;+ if (k === 0 || (only && !only.includes(f))) return;const c = h[f] ?? [0, 0, 0];F[k].forEach((i, ph) => {let q = qaxis(ax.hinge[k][ph], clampTo(c[ph], HAND_LIMITS.finger[ph]));@@ -91,6 +104,7 @@ export function handPose(skel: Skeleton, p: Pose, s: Side, h: HandShape): Pose {turns[i] = q;});});+ if (only && !only.includes("thumb")) return { ...p, turns };thumbAt(1);// the thumb rests on the fingers, never in them: closed as far as its skin clears the fingers' (a full wrap swung it// under the palm through the index's knuckle, its tip out the back of the hand; Shane, 10-22: "column 2 of the grips@@ -118,10 +132,22 @@ function thumbInFingers(skel: Skeleton, p: Pose, s: Side): boolean {/** How a hand closes on a thing (closeOn; items.ts's grips): the fingers that close on it (`on`), the shape the* others hold (`rest`), how far one may curl at a joint (`max`, radians), the fan and the thumb's opposition. */-export interface Closing { on: readonly Finger[]; rest?: Partial<Record<Finger, [number, number, number]>>; max: number; spread: number; opp: number }+export interface Closing {+ on: readonly Finger[]; rest?: Partial<Record<Finger, [number, number, number]>>; max: number; spread: number; opp: number;+ /** captured hand poses, open to closed (HAND_POSES' names): the fingers close along them, each joint's number its+ * place on the path (0 the first pose, 1 the next, ...) rather than a curl, `rest` and `max` too, and the fan and+ * the thumb's swing are the poses' own (Shane, 11-01: the made-up curls looked wrong; captured hands don't) */+ path?: readonly string[];+ /** with a path, the thumb closing as a curl and a swing under the palm instead (radians: how far it curls, and its+ * opposition): a power grip's thumb goes round the far side of a can, where the captured grips lay it along the+ * fingers and nothing held the can against them */+ thumb?: { max: number; opp: number };+}// how a finger curls as one while it closes: the middle joint the most, the tip the least (the thumb's knuckle most)const CURL: [number, number, number] = [1, 1.1, 0.75], THUMB_CURL: [number, number, number] = [0.45, 0.8, 0.6];+// (along a captured path the poses already move the joints together)+const EVEN: [number, number, number] = [1, 1, 1];/** how far a finger's skin may press into a thing it rests on (soft skin gives a few millimetres: ContactOpt's* 2-3 mm), metres */@@ -163,22 +189,26 @@ function fingerSkinOf(skel: Skeleton, s: Side) {* eases rather than flicks, and where that is in the thing, opens from there as little as clears it.*/export function closeOn(skel: Skeleton, p: Pose, s: Side, field: (q: Vec3) => number, g: Closing, close = 1, prev?: HandShape): HandShape {- const shape: HandShape = { spread: g.spread * close, thumbOpp: g.opp * close };+ // (along the path or not, finger by finger: a power grip's thumb curls as ever)+ const onPath = (k: number) => !!g.path && !(k === 0 && g.thumb);+ const shape: HandShape = { spread: g.spread * close, thumbOpp: (g.thumb?.opp ?? g.opp) * close };for (const [f, c] of Object.entries(g.rest ?? {}) as [Finger, [number, number, number]][]) shape[f] = c.map((v) => v * close) as [number, number, number];for (const f of g.on) shape[f] = [0, 0, 0];const F = fingerJoints(skel, s);- if (!F.length || !skel.surface || !skel.skin || !skel.bind) return shape;- const P = handPose(skel, p, s, shape), turns = P.turns;+ if (!F.length || !skel.surface) return shape;+ const P = g.path ? pathHand(skel, p, s, g.path, shape, g.thumb ? 1 : 0) : handPose(skel, p, s, shape), turns = P.turns;const w = withFingers(skel, pose(skel, P)), wp: Posed = { pos: w.pos.slice(), rot: w.rot.slice() };- const ax = axesOf(skel, s), skin = fingerSkinOf(skel, s), sk = skel.skin, { turns: bt, heads } = skel.bind;+ const ax = axesOf(skel, s), skin = fingerSkinOf(skel, s), sk = skel.joints;const fan = [0, 1, 0.15, -0.55, -1];const order = [1, 2, 3, 4, 0];- const lim = (k: number) => (k === 0 ? HAND_LIMITS.thumb : HAND_LIMITS.finger);+ const end = g.path ? g.path.length - 1 : 0, along: [number, number][] = [[0, end], [0, end], [0, end]];+ const lim = (k: number) => (onPath(k) ? along : k === 0 ? HAND_LIMITS.thumb : HAND_LIMITS.finger);// finger k's skin at curl c (and the thumb's opposition o): each phalanx's nearest to the surface (metres, < 0 in// it), and for the thumb whether it is in the fingerslet segs: FingerSegment[] = [];const at = (k: number, c: [number, number, number], o: number) => {F[k].forEach((i, ph) => {+ if (onPath(k)) { turns[i] = alongPath(skel, s, g.path!, k, ph, c[ph]); place(skel, turns, wp, i, i + 1, P.root); return; }let q = qaxis(ax.hinge[k][ph], clampTo(c[ph], lim(k)[ph]));if (ph === 0 && k === 0 && o) q = qmul(qaxis(ax.opp, clampTo(o, HAND_LIMITS.thumbOpp)), q);if (ph === 0 && k > 0 && shape.spread) q = qmul(qaxis(ax.spread, fan[k] * clampTo(shape.spread, HAND_LIMITS.spread)), q);@@ -187,8 +217,7 @@ export function closeOn(skel: Skeleton, p: Pose, s: Side, field: (q: Vec3) => nu});const sj: { pos: Vec3; rot: Quat }[] = [];for (const j of skin[k].sj) {- const x = sk[j], fr = qmul(wp.rot[x.drive], bt[x.drive]);- sj[j] = { pos: add(wp.pos[x.drive], qrot(fr, sub(x.head, heads[x.drive]))), rot: x.from === x.to ? qmul(wp.rot[x.from], bt[x.from]) : slerp(qmul(wp.rot[x.from], bt[x.from]), qmul(wp.rot[x.to], bt[x.to]), x.u) };+ sj[j] = { pos: wp.pos[j], rot: wp.rot[j] };}const near: [number, number, number] = [Infinity, Infinity, Infinity];let inFingers = false;@@ -245,13 +274,13 @@ export function closeOn(skel: Skeleton, p: Pose, s: Side, field: (q: Vec3) => nureturn best ?? outOf(k, x, open);};for (const k of order) {- const f = FINGERS[k], on = g.on.includes(f), R = k === 0 ? THUMB_CURL : CURL, L = lim(k);+ const f = FINGERS[k], on = g.on.includes(f), R = onPath(k) ? EVEN : k === 0 ? THUMB_CURL : CURL, L = lim(k);if (k === 0) segs = fingerSegments(skel, wp, s).slice(1).flatMap((x) => x.segments);- const o0 = k === 0 ? shape.thumbOpp ?? 0 : 0, cap = (m: number) => Math.min(g.max * close, L[m][1]);+ const o0 = k === 0 ? shape.thumbOpp ?? 0 : 0, mx = k === 0 && g.thumb ? g.thumb.max : g.max, cap = (m: number) => Math.min(mx * close, L[m][1]);// where it closes to (a finger the grip holds as it is: that shape) and where it opens to: past straight as far// as the hand lets it, the thumb swung out from under the palmconst want: Fit = [on ? [cap(0), cap(1), cap(2)] : shape[f] ?? [0, 0, 0], o0];- const open: Fit = [[L[0][0], L[1][0], L[2][0]], k === 0 ? HAND_LIMITS.thumbOpp[0] : 0];+ const open: Fit = [[L[0][0], L[1][0], L[2][0]], k === 0 && !onPath(0) ? HAND_LIMITS.thumbOpp[0] : 0];let x: Fit;if (!on) {// (a finger the grip holds as it is: opened until it only just touches)diff --git a/sdk/character/src/character/goals.ts b/sdk/character/src/character/goals.tsindex fc73f7b9..d36ee5cc 100644--- a/sdk/character/src/character/goals.ts+++ b/sdk/character/src/character/goals.ts@@ -1,15 +1,10 @@// Goals (inverse kinematics): two-bone reaches, elbows, hands.import { type Vec3 } from "@raea/render/3d";-import { I, Pose, Posed, Quat, Skeleton, add, cross, dot, fingerJoints, joint, len, norm, pose, qaxis, qbasis, qfromTo, qinv, qmul, qrot, scale3, setWorld, slerp, sub } from "./all";+import { B, FINGERS, I, Pose, Posed, Quat, Side, Skeleton, add, cross, dot, fingerJoints, joint, len, norm, pose, qaxis, qbasis, qfromTo, qinv, qmul, qrot, scale3, setWorld, slerp, sub } from "./all";// ---------------------------------------------------------------- goals (inverse kinematics)-export type Side = "L" | "R";--export const LIMB = {- arm: (s: Side) => (s === "L" ? ["LeftArm", "LeftForeArm", "LeftHand"] : ["RightArm", "RightForeArm", "RightHand"]),- leg: (s: Side) => (s === "L" ? ["LeftUpLeg", "LeftLeg", "LeftFoot"] : ["RightUpLeg", "RightLeg", "RightFoot"]),-};+export const LIMB = { arm: B.arm, leg: B.leg };/** Two bones (a hip, knee, ankle or a shoulder, elbow, wrist) bent so the end comes to `target`. The bend stays in the* plane it is in (so a clip's knees keep bending its way), unless `pole` says which way the middle joint points (a@@ -52,8 +47,8 @@ export function twoBone(skel: Skeleton, p: Pose, names: string[], target: Vec3,return setWorld(skel, p, w, c, endRot);}-/** A pose with its elbows never quite straight: a bend under twice `least` degrees eases up toward `least` (a straight- * arm gets `least`, one bent twice that or more is left alone), about the way the elbow bends, so arms a clip swings+/** A pose with its elbows never quite straight: a bend under twice `least` degrees becomes `least` plus half of it (a+ * straight arm gets `least`, one bent twice that or more is left alone), about the way the elbow bends, so arms a clip swings* locked straight (100STYLE's Neutral walks at 6° on average) hang relaxed. */export function softElbows(skel: Skeleton, p: Pose, least = 12): Pose {for (const s of ["L", "R"] as const) {@@ -67,7 +62,9 @@ export function softElbows(skel: Skeleton, p: Pose, least = 12): Pose {const fp = sub(fore, scale3(hinge, dot(fore, hinge)));const bent = (Math.atan2(dot(cross(un, fp), hinge), dot(un, fp)) * 180) / Math.PI;if (bent >= 2 * least) continue;- const want = bent <= 0 ? least : least + (bent * bent) / (4 * least);+ // (half the clip's own bend on top of `least`, so its swing stays: easing toward `least` flattened 100STYLE's+ // 0-20 deg elbow swing to 12-18 and the arms read stiff)+ const want = Math.max(least / 2, least + bent / 2);p = setWorld(skel, p, w, b, qmul(qaxis(hinge, ((want - bent) * Math.PI) / 180), w.rot[b]));}return p;@@ -76,9 +73,10 @@ export function softElbows(skel: Skeleton, p: Pose, least = 12): Pose {/** The hand's own frame at rest: its length (wrist to knuckles), its across (thumb side out) and its palm's normal. */export function handRest(skel: Skeleton, s: Side) {const J = skel.joints;- const h = J[joint(skel, s === "L" ? "LeftHand" : "RightHand")];- const knuckles = J[joint(skel, s === "L" ? "LeftFingerBase" : "RightFingerBase")].tail;- const thumb = J[joint(skel, s === "L" ? "LThumb" : "RThumb")].head;+ const h = J[joint(skel, B.hand(s))];+ // (the knuckles: the middle finger's first joint; the thumb from its base)+ const knuckles = J[joint(skel, B.finger("middle", 1, s))].head;+ const thumb = J[joint(skel, B.finger("thumb", 2, s))].head;const along = norm(sub(knuckles, h.head));const across = norm(sub(sub(thumb, h.head), scale3(along, dot(sub(thumb, h.head), along))));// the palm faces away from the back of the hand: for the left hand, across x along is the palm side (checked on a@@ -90,7 +88,7 @@ export function handRest(skel: Skeleton, s: Side) {/** A hand laid flat: fingers along `point` (in the body's frame, levelled), the palm facing `facing` (down by* default). */export function flatHand(skel: Skeleton, p: Pose, s: Side, point: Vec3, facing: Vec3 = [0, -1, 0]): Pose {- const i = joint(skel, s === "L" ? "LeftHand" : "RightHand");+ const i = joint(skel, B.hand(s));const r = handRest(skel, s);const n = norm(facing);const f = norm(sub(point, scale3(n, dot(point, n))));@@ -101,7 +99,6 @@ export function flatHand(skel: Skeleton, p: Pose, s: Side, point: Vec3, facing:p = setWorld(skel, p, w, i, qmul(R1, qinv(R0)));// the fingers and thumb straight along the hand (as they are at rest), whatever the clip had them doingconst turns = p.turns.slice();- for (const n of s === "L" ? ["LeftFingerBase", "LeftHandFinger1", "LThumb"] : ["RightFingerBase", "RightHandFinger1", "RThumb"]) turns[joint(skel, n)] = I;for (const i of fingerJoints(skel, s).flat()) if (i < turns.length) turns[i] = I;return { ...p, turns };}@@ -110,41 +107,44 @@ export function flatHand(skel: Skeleton, p: Pose, s: Side, point: Vec3, facing:* palm at their base and again along them, the thumb turned in across the palm. CMU's hands are captured flat, and a* ball laid on a flat palm read as floating off it in an overhand throw (Shane, 10-22). */export function cupHand(skel: Skeleton, p: Pose, s: Side, r: number, w = 1): Pose {- const { along, across } = handRest(skel, s), len = 2 * Math.hypot(...sub(handRest(skel, s).centre, skel.joints[joint(skel, s === "L" ? "LeftHand" : "RightHand")].head));+ const { along, across } = handRest(skel, s), len = 2 * Math.hypot(...sub(handRest(skel, s).centre, skel.joints[joint(skel, B.hand(s))].head));// (a smaller ball against the same hand closes it further: about 60° at the knuckles for a ball a hand long across)const k = Math.min(1.3, Math.max(0.6, len / (2 * r)));const sg = s === "L" ? -1 : 1, turns = p.turns.slice();// (in place of the capture's own finger turns, by w: CMU's fingers are a marker or two, and a throw's flick bent them// back past straight with the ball in them)const at = (n: string, q: Quat) => { const i = joint(skel, n); turns[i] = slerp(turns[i], q, Math.min(1, w)); };- const L = s === "L" ? "Left" : "Right";- at(`${L}FingerBase`, qaxis(across, sg * 0.9 * k));- at(`${L}HandFinger1`, qaxis(across, sg * 0.7 * k));- at(s === "L" ? "LThumb" : "RThumb", qaxis(along, -sg * 0.6 * k));+ while (turns.length < skel.joints.length) turns.push(I);+ for (const f of FINGERS) {+ if (f === "thumb") { at(B.finger(f, 1, s), qaxis(along, -sg * 0.6 * k)); continue; }+ at(B.finger(f, 1, s), qaxis(across, sg * 0.9 * k));+ at(B.finger(f, 2, s), qaxis(across, sg * 0.4 * k));+ at(B.finger(f, 3, s), qaxis(across, sg * 0.3 * k));+ }return { ...p, turns };}/** Where a ball of radius `r` sits in a cupped hand (cupHand): off the palm by its radius and toward the fingers that* close on it. */export function ballInHand(skel: Skeleton, w: Posed, s: Side, r: number): Vec3 {- const i = joint(skel, s === "L" ? "LeftHand" : "RightHand"), hr = handRest(skel, s);+ const i = joint(skel, B.hand(s)), hr = handRest(skel, s);const len = 2 * Math.hypot(...sub(hr.centre, skel.joints[i].head));return add(palmAt(skel, w, s), add(scale3(palmFacing(skel, w, s), r + 0.004), scale3(qrot(w.rot[i], hr.along), 0.2 * len)));}/** where the middle of a hand's palm is, posed */export function palmAt(skel: Skeleton, w: Posed, s: Side): Vec3 {- const i = joint(skel, s === "L" ? "LeftHand" : "RightHand");+ const i = joint(skel, B.hand(s));const r = handRest(skel, s);return add(w.pos[i], qrot(w.rot[i], sub(r.centre, skel.joints[i].head)));}/** the way a hand's fingers point (from the wrist to the knuckles), posed */export function handAlong(skel: Skeleton, w: Posed, s: Side): Vec3 {- return qrot(w.rot[joint(skel, s === "L" ? "LeftHand" : "RightHand")], handRest(skel, s).along);+ return qrot(w.rot[joint(skel, B.hand(s))], handRest(skel, s).along);}/** the way a hand's palm faces, posed */export function palmFacing(skel: Skeleton, w: Posed, s: Side): Vec3 {- return qrot(w.rot[joint(skel, s === "L" ? "LeftHand" : "RightHand")], handRest(skel, s).palm);+ return qrot(w.rot[joint(skel, B.hand(s))], handRest(skel, s).palm);}diff --git a/sdk/character/src/character/hair.ts b/sdk/character/src/character/hair.tsnew file mode 100644index 00000000..d5e2923e--- /dev/null+++ b/sdk/character/src/character/hair.ts@@ -0,0 +1,55 @@+// Hair on cards, shaded as hair (<Character> puts it on a body's "hair" material, the name projects/psx gives it): the standard surface lit as usual (diffuse, shadows), then the strand highlights added+// after lighting the way games shade hair cards (Scheuermann, "Hair Rendering and Shading", GDC 2004; the lobes as+// Karis's "Physically Based Hair Shading in Unreal", 2016, separates them):+// R a white highlight off the strands' surface, a band across them (Kajiya-Kay on the tangent shifted to the root)+// TRT a wider band in the hair's own colour, shifted to the tip (light that went in and back out), broken up per strand+// TT light through the hair from behind, in its colour (the rim round a backlit head)+// The tangent is the strand's direction (baked into the hair's TANGENT by projects/psx hairlook.py), and the depth shade+// (COLOR_0) dims the highlights inside the hair as it dims its colour.+export const HAIR_WESL = /* wgsl */ `+fn hair_hash(x: f32) -> f32 { return fract(sin(x * 12.9898) * 43758.5453); }+// smooth 1D value noise: strands as stripes across the hair (each a value, eased into the next)+fn hair_strands(x: f32) -> f32 { let i = floor(x); let f = fract(x); let u = f * f * (3.0 - 2.0 * f); return mix(hair_hash(i), hair_hash(i + 1.0), u); }++// Kajiya-Kay: the highlight of a thin cylinder along T, faded where the half vector is behind the strand+fn hair_kk(T: vec3<f32>, H: vec3<f32>, e: f32) -> f32 {+ let th = dot(T, H);+ let s = sqrt(max(0.0, 1.0 - th * th));+ return smoothstep(-1.0, 0.0, th) * pow(s, e);+}++fn lit(in: VertexOutput, pbr: PbrInput, color: vec4<f32>) -> vec4<f32> {+ if (bevy_pbr::render::mesh_view_bindings::lights.n_directional_lights == 0u) { return color; }+ let N = normalize(pbr.N);+ let V = normalize(pbr.V);+ let T = normalize(in.world_tangent.xyz);+ let L = normalize(bevy_pbr::render::mesh_view_bindings::lights.directional_lights[0].direction_to_light);+ let Lc = bevy_pbr::render::mesh_view_bindings::lights.directional_lights[0].color.rgb * view.exposure;+ let H = normalize(L + V);+ // (a strand's value from where it lies across the strands, in the world: stretched along it, varying across it, and+ // the same however a card's UVs run; a 2D hash of the UV sparkled like sand)+ let across = dot(in.world_position.xyz, normalize(cross(N, T)));+ let id = 0.6 * hair_strands(across * u_grain().x) + 0.4 * hair_strands(across * u_grain().y + 17.0);+ let shift = (id - 0.5) * u_jitter();+ let T1 = normalize(T + N * (u_shift_r() + shift));+ let T2 = normalize(T + N * (u_shift_trt() + shift));+ let base = pbr.material.base_color.rgb;+ let occ = in.color.r;+ let wrap = clamp(dot(N, L) * 0.5 + 0.5, 0.0, 1.0);+ // (the white highlight broken up by the texture's own strands: lit evenly it read as a wet patch)+ let lum = dot(base, vec3<f32>(0.3, 0.59, 0.11)) / max(1e-3, max(base.r, max(base.g, base.b)));+ let r = hair_kk(T1, H, u_exp_r()) * u_r() * clamp(lum * lum * 2.0, 0.2, 1.5) * mix(0.5, 1.5, id);+ let trt = hair_kk(T2, H, u_exp_trt()) * u_trt() * mix(0.4, 1.4, id);+ let tt = pow(clamp(dot(-L, V), 0.0, 1.0), 6.0) * u_tt();+ // the first reflection is nearly white in real hair, but across a whole card it read as grey on brown hair: half+ // tinted by the hair's own hue+ let hue = base / max(1e-3, max(base.r, max(base.g, base.b)));+ let add = (r * mix(vec3<f32>(1.0), hue, 0.5) + base * (trt + tt)) * Lc * wrap * occ;+ return vec4<f32>(color.rgb + add, color.a);+}+`;++/** the hair look's settings: each lobe's strength (r, trt, tt), the bands' sharpness (exp_r, exp_trt) and shifts along+ * the strand (shift_r, shift_trt), how much strands differ (jitter) and how fine they are across (grain, per metre) */+export interface HairLook { r: number; trt: number; tt: number; exp_r: number; exp_trt: number; shift_r: number; shift_trt: number; jitter: number; grain: [number, number] }+export const HAIR_LOOK: HairLook = { r: 0.03, trt: 0.07, tt: 0.3, exp_r: 80, exp_trt: 12, shift_r: -0.1, shift_trt: 0.12, jitter: 0.15, grain: [900, 260] };diff --git a/sdk/character/src/character/hands.json b/sdk/character/src/character/hands.jsonnew file mode 100644index 00000000..4712f107--- /dev/null+++ b/sdk/character/src/character/hands.json@@ -0,0 +1,6918 @@+{+"source": "Godot XR Tools hand poses (CC0, DigitalN8m4r3), animations_hand_r.blend",+"frame": "[along, palm, across] of a right hand",+"rest": {+"thumb": [+[+[+0.7569,+0.25347,+0.60237+],+[+0.21628,+-0.96694,+0.13512+]+],+[+[+0.76609,+0.39931,+0.50364+],+[+0.36266,+-0.9155,+0.17421+]+],+[+[+0.71166,+0.36669,+0.59924+],+[+0.33005,+-0.92749,+0.17559+]+]+],+"index": [+[+[+0.9638,+-0.09254,+0.25005+],+[+-0.11624,+-0.98986,+0.08171+]+],+[+[+0.91369,+0.36892,+0.17048+],+[+0.34939,+-0.92732,+0.13417+]+],+[+[+0.7807,+0.60429,+0.15918+],+[+0.58467,+-0.79626,+0.15533+]+]+],+"middle": [+[+[+0.99336,+0.0779,+-0.08466+],+[+0.08786,+-0.98873,+0.12118+]+],+[+[+0.93422,+0.35462,+-0.0384+],+[+0.35666,+-0.92726,+0.11392+]+],+[+[+0.76233,+0.63922,+-0.10128+],+[+0.6469,+-0.75728,+0.08973+]+]+],+"ring": [+[+[+0.97419,+0.01699,+-0.22509+],+[+0.04764,+-0.99018,+0.13146+]+],+[+[+0.91428,+0.3349,+-0.22788+],+[+0.36302,+-0.92702,+0.09411+]+],+[+[+0.78268,+0.56105,+-0.26952+],+[+0.59368,+-0.80299,+0.05246+]+]+],+"pinky": [+[+[+0.93512,+0.07409,+-0.34651+],+[+0.12443,+-0.98428,+0.12534+]+],+[+[+0.84696,+0.44124,+-0.2966+],+[+0.47934,+-0.87507,+0.06698+]+],+[+[+0.71633,+0.60912,+-0.34037+],+[+0.65321,+-0.7569,+0.02018+]+]+]+},+"poses": {+"Cup": {+"thumb": [+[+[+0.58945,+0.80265,+0.0911+],+[+0.58225,+-0.50033,+0.64082+]+],+[+[+0.48227,+0.8231,+-0.29987+],+[+0.65692,+-0.11334,+0.74539+]+],+[+[+0.63646,+0.63743,+-0.4343+],+[+0.61713,+-0.08307,+0.78247+]+]+],+"index": [+[+[+0.89204,+0.45196,+0.00226+],+[+0.45188,+-0.89196,+0.01481+]+],+[+[+0.27653,+0.96091,+-0.0134+],+[+0.96012,+-0.27685,+-0.03913+]+],+[+[+-0.41473,+0.90912,+0.03863+],+[+0.90821,+0.41619,+-0.04411+]+]+],+"middle": [+[+[+0.80082,+0.59865,+-0.01768+],+[+0.59726,+-0.79608,+0.09769+]+],+[+[+0.21237,+0.97719,+-0.00043+],+[+0.97377,+-0.21159,+0.08373+]+],+[+[+-0.53219,+0.84402,+-0.06637+],+[+0.84498,+0.5344,+0.02053+]+]+],+"ring": [+[+[+0.83857,+0.54285,+-0.04597+],+[+0.54401,+-0.82981,+0.12439+]+],+[+[+0.40362,+0.91372,+-0.04705+],+[+0.91199,+-0.39767,+0.10071+]+],+[+[+-0.27824,+0.95759,+-0.07485+],+[+0.95698,+0.28305,+0.06377+]+]+],+"pinky": [+[+[+0.97704,+0.19829,+-0.0779+],+[+0.20522,+-0.97416,+0.09437+]+],+[+[+0.61199,+0.79086,+0.00312+],+[+0.78736,+-0.60965,+0.09165+]+],+[+[+0.03661,+0.99921,+0.01552+],+[+0.99739,+-0.03751,+0.06173+]+]+]+},+"Default pose": {+"thumb": [+[+[+0.7569,+0.25347,+0.60237+],+[+0.21628,+-0.96694,+0.13512+]+],+[+[+0.76609,+0.39931,+0.50364+],+[+0.36266,+-0.9155,+0.17421+]+],+[+[+0.71166,+0.36669,+0.59924+],+[+0.33005,+-0.92749,+0.17559+]+]+],+"index": [+[+[+0.9638,+-0.09254,+0.25005+],+[+-0.11624,+-0.98985,+0.08171+]+],+[+[+0.91369,+0.36892,+0.17048+],+[+0.34939,+-0.92732,+0.13417+]+],+[+[+0.7807,+0.60429,+0.15918+],+[+0.58467,+-0.79626,+0.15533+]+]+],+"middle": [+[+[+0.99336,+0.0779,+-0.08466+],+[+0.08786,+-0.98873,+0.12118+]+],+[+[+0.93422,+0.35462,+-0.0384+],+[+0.35666,+-0.92726,+0.11392+]+],+[+[+0.76233,+0.63922,+-0.10128+],+[+0.6469,+-0.75728,+0.08973+]+]+],+"ring": [+[+[+0.97419,+0.01699,+-0.22509+],+[+0.04764,+-0.99018,+0.13146+]+],+[+[+0.91428,+0.3349,+-0.22788+],+[+0.36302,+-0.92702,+0.09411+]+],+[+[+0.78268,+0.56105,+-0.26952+],+[+0.59368,+-0.80299,+0.05246+]+]+],+"pinky": [+[+[+0.93512,+0.07409,+-0.34651+],+[+0.12443,+-0.98428,+0.12534+]+],+[+[+0.84696,+0.44124,+-0.2966+],+[+0.47934,+-0.87507,+0.06698+]+],+[+[+0.71633,+0.60912,+-0.34037+],+[+0.65321,+-0.7569,+0.02018+]+]+]+},+"Grip": {+"thumb": [+[+[+0.67702,+0.56526,+0.4713+],+[+0.17653,+-0.74641,+0.64164+]+],+[+[+0.83434,+0.48184,+-0.26778+],+[+0.485,+-0.41074,+0.77205+]+],+[+[+0.36307,+-0.05202,+-0.93031+],+[+0.78984,+-0.51249,+0.33691+]+]+],+"index": [+[+[+0.013,+0.99978,+0.01621+],+[+0.99968,+-0.01264,+-0.02213+]+],+[+[+-0.98795,+0.14753,+0.04686+],+[+0.14672,+0.98897,+-0.02027+]+],+[+[+0.11437,+-0.98912,+-0.09248+],+[+-0.99245,+-0.11791,+0.03375+]+]+],+"middle": [+[+[+-0.03291,+0.99908,+-0.02755+],+[+0.99942,+0.03267,+-0.00925+]+],+[+[+-0.9893,+0.12691,+0.07201+],+[+0.12586,+0.99187,+-0.01907+]+],+[+[+0.2116,+-0.97691,+0.02946+],+[+-0.97731,+-0.21118,+0.01662+]+]+],+"ring": [+[+[+0.10688,+0.99413,+-0.01703+],+[+0.99423,+-0.10703,+-0.00775+]+],+[+[+-0.93483,+0.32176,+0.15018+],+[+0.32235,+0.94638,+-0.02108+]+],+[+[+0.10692,+-0.99084,+0.08254+],+[+-0.96335,+-0.0827,+0.25518+]+]+],+"pinky": [+[+[+0.14442,+0.98944,+0.01234+],+[+0.98836,+-0.14363,+-0.05014+]+],+[+[+-0.93061,+0.253,+0.2645+],+[+0.27719,+0.95907,+0.0579+]+],+[+[+0.06488,+-0.99316,+0.09711+],+[+-0.92869,+-0.02449,+0.37005+]+]+]+},+"Grip 1": {+"thumb": [+[+[+0.70987,+0.4418,+0.54854+],+[+0.33162,+-0.89673,+0.29309+]+],+[+[+0.53593,+0.84355,+-0.03478+],+[+0.7897,+-0.4863,+0.37401+]+],+[+[+0.64774,+0.56051,+-0.51601+],+[+0.76123,+-0.50367,+0.40846+]+]+],+"index": [+[+[+0.68543,+0.71691,+0.12737+],+[+0.71516,+-0.69571,+0.06733+]+],+[+[+-0.27168,+0.96238,+0.0034+],+[+0.95722,+0.26985,+0.10444+]+],+[+[+-0.97224,+0.2207,+-0.07777+],+[+0.21683,+0.97464,+0.05526+]+]+],+"middle": [+[+[+0.60562,+0.79218,+-0.07539+],+[+0.79548,+-0.60518,+0.03115+]+],+[+[+-0.19074,+0.98164,+0.00255+],+[+0.98149,+0.19075,+-0.01707+]+],+[+[+-0.97165,+0.23368,+0.03575+],+[+0.23118,+0.97087,+-0.06297+]+]+],+"ring": [+[+[+0.66599,+0.72742,+-0.16527+],+[+0.73873,+-0.67391,+0.01069+]+],+[+[+-0.13275,+0.99103,+-0.01528+],+[+0.984,+0.12992,+-0.12189+]+],+[+[+-0.91196,+0.37554,+0.16522+],+[+0.37355,+0.92656,+-0.04417+]+]+],+"pinky": [+[+[+0.63467,+0.73678,+-0.23311+],+[+0.75007,+-0.65992,+-0.04361+]+],+[+[+-0.2346,+0.97176,+0.02556+],+[+0.95601,+0.22588,+0.18715+]+],+[+[+-0.90495,+0.39708,+0.15297+],+[+0.40391,+0.91467,+0.01521+]+]+]+},+"Grip 2": {+"thumb": [+[+[+0.76702,+0.19607,+0.61093+],+[+0.15278,+-0.98059,+0.12289+]+],+[+[+0.71885,+0.67049,+0.18358+],+[+0.61994,+-0.73779,+0.26711+]+],+[+[+0.79858,+0.5428,+-0.26006+],+[+0.60188,+-0.7209,+0.34358+]+]+],+"index": [+[+[+0.78792,+0.60093,+0.13443+],+[+0.59735,+-0.79891,+0.07009+]+],+[+[+-0.07182,+0.9973,+0.01517+],+[+0.99217,+0.06987,+0.10353+]+],+[+[+-0.84285,+0.53508,+-0.05744+],+[+0.53094,+0.84422,+0.07352+]+]+],+"middle": [+[+[+0.71045,+0.69902,+-0.08148+],+[+0.7032,+-0.70969,+0.04291+]+],+[+[+-0.00497,+0.99989,+-0.014+],+[+0.99998,+0.0049,+-0.005+]+],+[+[+-0.8464,+0.53252,+0.00499+],+[+0.53107,+0.84472,+-0.0665+]+]+],+"ring": [+[+[+0.75704,+0.6311,+-0.16914+],+[+0.64405,+-0.76437,+0.03065+]+],+[+[+0.04089,+0.99759,+-0.05613+],+[+0.99459,+-0.04601,+-0.09315+]+],+[+[+-0.76036,+0.64296,+0.0919+],+[+0.63817,+0.7659,+-0.07832+]+]+],+"pinky": [+[+[+0.70815,+0.66387,+-0.24042+],+[+0.68257,+-0.73078,+-0.00743+]+],+[+[+-0.03981,+0.9992,+-0.00372+],+[+0.9922,+0.03909,+-0.11841+]+],+[+[+-0.73593,+0.64514,+0.20542+],+[+0.64047,+0.76174,+-0.09775+]+]+]+},+"Grip 3": {+"thumb": [+[+[+0.76702,+0.19607,+0.61093+],+[+0.15278,+-0.98059,+0.12289+]+],+[+[+0.66525,+0.71767,+0.20589+],+[+0.6673,+-0.69521,+0.26718+]+],+[+[+0.75885,+0.62785,+-0.17304+],+[+0.64462,+-0.68628,+0.33688+]+]+],+"index": [+[+[+0.83681,+0.5271,+0.14806+],+[+0.52248,+-0.84963,+0.07172+]+],+[+[+0.07835,+0.99649,+0.02958+],+[+0.99025,+-0.08122,+0.11318+]+],+[+[+-0.69795,+0.71461,+-0.04674+],+[+0.70908,+0.69874,+0.09465+]+]+],+"middle": [+[+[+0.76491,+0.6386,+-0.08423+],+[+0.64332,+-0.76396,+0.05008+]+],+[+[+0.13696,+0.99033,+-0.02202+],+[+0.99058,+-0.13691,+0.00367+]+],+[+[+-0.70797,+0.7061,+-0.0138+],+[+0.70538,+0.70602,+-0.06309+]+]+],+"ring": [+[+[+0.80263,+0.56893,+-0.17919+],+[+0.58386,+-0.81083,+0.04084+]+],+[+[+0.17508,+0.98101,+-0.08352+],+[+0.97987,+-0.18188,+-0.08233+]+],+[+[+-0.60855,+0.79204,+0.04836+],+[+0.78634,+0.6101,+-0.09716+]+]+],+"pinky": [+[+[+0.75406,+0.60385,+-0.25837+],+[+0.62652,+-0.77937,+0.007+]+],+[+[+0.08957,+0.99491,+-0.0462+],+[+0.98909,+-0.0943,+-0.1132+]+],+[+[+-0.59487,+0.79062,+0.14506+],+[+0.78064,+0.61126,+-0.13027+]+]+]+},+"Grip 4": {+"thumb": [+[+[+0.76702,+0.19607,+0.61093+],+[+0.15278,+-0.98059,+0.12289+]+],+[+[+0.71505,+0.6367,+0.28864+],+[+0.58344,+-0.77098,+0.25531+]+],+[+[+0.80484,+0.59239,+0.03624+],+[+0.5545,+-0.77232,+0.30991+]+]+],+"index": [+[+[+0.90918,+0.37846,+0.17365+],+[+0.37166,+-0.92562,+0.07141+]+],+[+[+0.35159,+0.93406,+0.06254+],+[+0.92573,+-0.35684,+0.12525+]+],+[+[+-0.33453,+0.94233,+-0.01018+],+[+0.93392,+0.33295,+0.13014+]+]+],+"middle": [+[+[+0.85313,+0.51427,+-0.08779+],+[+0.52002,+-0.85175,+0.06401+]+],+[+[+0.394,+0.91849,+-0.0339+],+[+0.91907,+-0.39337,+0.02367+]+],+[+[+-0.35992,+0.93173,+-0.0484+],+[+0.93265,+0.35793,+-0.0452+]+]+],+"ring": [+[+[+0.87476,+0.44326,+-0.19576+],+[+0.46213,+-0.88465,+0.06193+]+],+[+[+0.41604,+0.89968,+-0.13222+],+[+0.90345,+-0.42548,+-0.05232+]+],+[+[+-0.25354,+0.96636,+-0.04327+],+[+0.96278,+0.24777,+-0.10799+]+]+],+"pinky": [+[+[+0.82743,+0.48169,+-0.28867+],+[+0.51252,+-0.85785,+0.03761+]+],+[+[+0.32595,+0.93709,+-0.12497+],+[+0.93708,+-0.33774,+-0.08837+]+],+[+[+-0.26474,+0.96423,+0.01306+],+[+0.95155,+0.2634,+-0.15867+]+]+]+},+"Grip 5": {+"thumb": [+[+[+0.76702,+0.19607,+0.61093+],+[+0.15278,+-0.98059,+0.12289+]+],+[+[+0.76304,+0.50918,+0.39813+],+[+0.45782,+-0.86058,+0.22318+]+],+[+[+0.81218,+0.48854,+0.31889+],+[+0.42352,+-0.86966,+0.25363+]+]+],+"index": [+[+[+0.96449,+0.16393,+0.20707+],+[+0.15381,+-0.98601,+0.06418+]+],+[+[+0.67039,+0.73295,+0.11559+],+[+0.72212,+-0.68029,+0.12548+]+],+[+[+0.23723,+0.96901,+0.06881+],+[+0.9572,+-0.24525,+0.15368+]+]+],+"middle": [+[+[+0.94052,+0.32784,+-0.08914+],+[+0.33504,+-0.93851,+0.08337+]+],+[+[+0.69529,+0.71754,+-0.04134+],+[+0.71863,+-0.69308,+0.05674+]+],+[+[+0.19847,+0.97649,+-0.08408+],+[+0.97999,+-0.19903,+0.00175+]+]+],+"ring": [+[+[+0.94227,+0.25847,+-0.21287+],+[+0.28303,+-0.9545,+0.09389+]+],+[+[+0.69569,+0.69338,+-0.18771+],+[+0.70689,+-0.70728,+0.00726+]+],+[+[+0.27999,+0.94521,+-0.16789+],+[+0.95348,+-0.29415,+-0.06593+]+]+],+"pinky": [+[+[+0.89792,+0.30041,+-0.3217+],+[+0.34349,+-0.93526,+0.08539+]+],+[+[+0.60966,+0.76094,+-0.222+],+[+0.77674,+-0.62936,+-0.02413+]+],+[+[+0.23546,+0.95554,+-0.17747+],+[+0.95888,+-0.25818,+-0.1179+]+]+]+},+"Grip Shaft": {+"thumb": [+[+[+0.82497,+0.32372,+0.46328+],+[+0.18202,+-0.92822,+0.32448+]+],+[+[+0.84207,+0.53493,+0.06911+],+[+0.46679,+-0.78694,+0.40354+]+],+[+[+0.8402,+0.47508,+-0.26146+],+[+0.54212,+-0.74754,+0.38379+]+]+],+"index": [+[+[+0.85142,+0.50695,+0.1345+],+[+0.49812,+-0.86186,+0.09529+]+],+[+[+0.05936,+0.99823,+-0.00404+],+[+0.99138,+-0.05848,+0.1172+]+],+[+[+-0.37684,+0.92626,+-0.00647+],+[+0.92279,+0.37602,+0.08405+]+]+],+"middle": [+[+[+0.78849,+0.6099,+-0.07941+],+[+0.61444,+-0.78685,+0.05774+]+],+[+[+0.12611,+0.99174,+-0.02331+],+[+0.992,+-0.12595,+0.0081+]+],+[+[+-0.81164,+0.58412,+-0.00634+],+[+0.58288,+0.8091,+-0.07489+]+]+],+"ring": [+[+[+0.82648,+0.53919,+-0.16188+],+[+0.551,+-0.83372,+0.03621+]+],+[+[+0.16848,+0.97534,+-0.14257+],+[+0.98201,+-0.1786,+-0.06133+]+],+[+[+-0.6611,+0.75024,+0.00939+],+[+0.74332,+0.65661,+-0.12784+]+]+],+"pinky": [+[+[+0.94143,+0.27054,+-0.20129+],+[+0.29973,+-0.94487,+0.13186+]+],+[+[+0.40613,+0.90965,+-0.0871+],+[+0.91327,+-0.40732,+0.00446+]+],+[+[+-0.52148,+0.85107,+0.06115+],+[+0.84245,+0.52492,+-0.12143+]+]+]+},+"Hold": {+"thumb": [+[+[+0.61901,+0.67657,+0.39883+],+[+0.4432,+-0.72016,+0.5338+]+],+[+[+0.58619,+0.73236,+0.34647+],+[+0.03296,+-0.44885,+0.893+]+],+[+[+0.85959,+0.37355,+-0.34867+],+[+0.50142,+-0.48517,+0.71637+]+]+],+"index": [+[+[+0.70109,+0.68878,+0.18455+],+[+0.69955,+-0.71452,+0.00922+]+],+[+[+-0.0344,+0.98984,+0.13793+],+[+0.99891,+0.02972,+0.03589+]+],+[+[+-0.87904,+0.45603,+0.13904+],+[+0.46525,+0.88422,+0.04129+]+]+],+"middle": [+[+[+-0.03291,+0.99908,+-0.02755+],+[+0.99942,+0.03267,+-0.00925+]+],+[+[+-0.9893,+0.12691,+0.07201+],+[+0.12586,+0.99187,+-0.01907+]+],+[+[+0.2116,+-0.97691,+0.02946+],+[+-0.97731,+-0.21118,+0.01662+]+]+],+"ring": [+[+[+0.10688,+0.99413,+-0.01703+],+[+0.99423,+-0.10703,+-0.00775+]+],+[+[+-0.93483,+0.32176,+0.15018+],+[+0.32235,+0.94638,+-0.02108+]+],+[+[+0.10692,+-0.99084,+0.08254+],+[+-0.96335,+-0.0827,+0.25518+]+]+],+"pinky": [+[+[+0.14442,+0.98944,+0.01234+],+[+0.98836,+-0.14363,+-0.05014+]+],+[+[+-0.93061,+0.253,+0.2645+],+[+0.27719,+0.95907,+0.0579+]+],+[+[+0.06488,+-0.99316,+0.09711+],+[+-0.92869,+-0.02449,+0.37005+]+]+]+},+"Horns": {+"thumb": [+[+[+0.65958,+0.60697,+0.44333+],+[+0.1925,+-0.70656,+0.68097+]+],+[+[+0.76891,+0.46765,+-0.43598+],+[+0.61472,+-0.35325,+0.70522+]+],+[+[+0.20313,+-0.11378,+-0.97252+],+[+0.84421,+-0.48281,+0.23281+]+]+],+"index": [+[+[+0.96047,+0.1692,+0.22106+],+[+0.16406,+-0.98557,+0.04158+]+],+[+[+0.78229,+0.60124,+0.16292+],+[+0.59602,+-0.79848,+0.08479+]+],+[+[+0.58927,+0.79085,+0.16526+],+[+0.7867,+-0.60824,+0.10559+]+]+],+"middle": [+[+[+0.07707,+0.99669,+-0.02574+],+[+0.99703,+-0.07705,+0.00182+]+],+[+[+-0.99183,+-0.08829,+0.0921+],+[+-0.09069,+0.99563,+-0.02221+]+],+[+[+-0.34587,+-0.93827,+-0.00462+],+[+-0.93812,+0.34589,+-0.01712+]+]+],+"ring": [+[+[+0.18,+0.98358,+-0.01331+],+[+0.98367,+-0.17999,+0.00214+]+],+[+[+-0.97831,+0.0829,+0.18985+],+[+0.07722,+0.99632,+-0.03714+]+],+[+[+-0.41211,+-0.90931,+0.05768+],+[+-0.88581,+0.41468,+0.20829+]+]+],+"pinky": [+[+[+0.8698,+0.31455,+-0.38015+],+[+0.39098,+-0.90936,+0.14214+]+],+[+[+0.68646,+0.64534,+-0.33514+],+[+0.70103,+-0.70976,+0.06921+]+],+[+[+0.51392,+0.77008,+-0.37797+],+[+0.83484,+-0.55032,+0.01389+]+]+]+},+"Metal": {+"thumb": [+[+[+0.76702,+0.19607,+0.61093+],+[+0.15278,+-0.98059,+0.12289+]+],+[+[+0.61738,+0.3369,+0.71087+],+[+0.28897,+-0.9376,+0.19338+]+],+[+[+0.53956,+0.3,+0.78669+],+[+0.2569,+-0.94847,+0.18549+]+]+],+"index": [+[+[+0.96047,+0.1692,+0.22106+],+[+0.16406,+-0.98557,+0.04158+]+],+[+[+0.78229,+0.60124,+0.16292+],+[+0.59602,+-0.79848,+0.08479+]+],+[+[+0.58927,+0.79085,+0.16526+],+[+0.7867,+-0.60824,+0.10559+]+]+],+"middle": [+[+[+0.07707,+0.99669,+-0.02574+],+[+0.99703,+-0.07705,+0.00182+]+],+[+[+-0.99183,+-0.08829,+0.0921+],+[+-0.09069,+0.99563,+-0.02221+]+],+[+[+-0.34587,+-0.93827,+-0.00462+],+[+-0.93812,+0.34589,+-0.01712+]+]+],+"ring": [+[+[+0.18,+0.98358,+-0.01331+],+[+0.98367,+-0.17999,+0.00214+]+],+[+[+-0.97831,+0.0829,+0.18985+],+[+0.07722,+0.99632,+-0.03714+]+],+[+[+-0.41211,+-0.90931,+0.05768+],+[+-0.88581,+0.41468,+0.20829+]+]+],+"pinky": [+[+[+0.8698,+0.31455,+-0.38015+],+[+0.39098,+-0.90936,+0.14214+]+],+[+[+0.68646,+0.64534,+-0.33514+],+[+0.70103,+-0.70976,+0.06921+]+],+[+[+0.51392,+0.77008,+-0.37797+],+[+0.83484,+-0.55032,+0.01389+]+]+]+},+"Middle": {+"thumb": [+[+[+0.65958,+0.60697,+0.44333+],+[+0.1925,+-0.70656,+0.68097+]+],+[+[+0.76891,+0.46765,+-0.43598+],+[+0.61472,+-0.35325,+0.70522+]+],+[+[+0.20313,+-0.11378,+-0.97252+],+[+0.84421,+-0.48281,+0.23281+]+]+],+"index": [+[+[+0.013,+0.99978,+0.01621+],+[+0.99968,+-0.01264,+-0.02213+]+],+[+[+-0.99702,+0.06077,+0.04752+],+[+0.06002,+0.99805,+-0.01695+]+],+[+[+0.20004,+-0.97509,+-0.09585+],+[+-0.97839,+-0.20401,+0.03351+]+]+],+"middle": [+[+[+0.80557,+0.58851,+-0.06861+],+[+0.59249,+-0.80079,+0.08766+]+],+[+[+0.61085,+0.79163,+-0.01348+],+[+0.78947,+-0.60772,+0.08614+]+],+[+[+0.31513,+0.94656,+-0.06865+],+[+0.9479,+-0.31037,+0.0718+]+]+],+"ring": [+[+[+0.10688,+0.99413,+-0.01703+],+[+0.99423,+-0.10703,+-0.00775+]+],+[+[+-0.93483,+0.32176,+0.15018+],+[+0.32235,+0.94638,+-0.02108+]+],+[+[+0.10692,+-0.99084,+0.08254+],+[+-0.96335,+-0.0827,+0.25518+]+]+],+"pinky": [+[+[+0.14442,+0.98944,+0.01234+],+[+0.98836,+-0.14363,+-0.05014+]+],+[+[+-0.93061,+0.253,+0.2645+],+[+0.27719,+0.95907,+0.0579+]+],+[+[+0.06488,+-0.99316,+0.09711+],+[+-0.92869,+-0.02449,+0.37005+]+]+]+},+"OK": {+"thumb": [+[+[+0.75154,+0.54278,+0.37495+],+[+0.36813,+-0.8167,+0.44439+]+],+[+[+0.75193,+0.64081,+0.15483+],+[+0.53945,+-0.73308,+0.41424+]+],+[+[+0.56147,+0.47708,+-0.67612+],+[+0.80269,+-0.51255,+0.30492+]+]+],+"index": [+[+[+0.7603,+0.64725,+0.05487+],+[+0.63768,+-0.7598,+0.12676+]+],+[+[+-0.03663,+0.99853,+-0.04003+],+[+0.99869,+0.03801,+0.03416+]+],+[+[+-0.91811,+0.39285,+0.05233+],+[+0.38525,+0.91564,+-0.11483+]+]+],+"middle": [+[+[+0.89391,+0.43169,+-0.12066+],+[+0.44359,+-0.89065,+0.09984+]+],+[+[+0.74092,+0.66822,+-0.06719+],+[+0.67156,+-0.73622,+0.08355+]+],+[+[+0.47548,+0.87173,+-0.11837+],+[+0.87966,+-0.47281,+0.05152+]+]+],+"ring": [+[+[+0.97385,+0.03741,+-0.22411+],+[+0.06866,+-0.98869,+0.13333+]+],+[+[+0.90716,+0.35396,+-0.22755+],+[+0.38266,+-0.91887,+0.09619+]+],+[+[+0.77079,+0.57717,+-0.26973+],+[+0.61065,+-0.79002,+0.05455+]+]+],+"pinky": [+[+[+0.83227,+-0.32138,+-0.45172+],+[+-0.29017,+-0.94683,+0.13901+]+],+[+[+0.918,+-0.1098,+-0.38107+],+[+-0.10498,+-0.99391,+0.03349+]+],+[+[+0.90399,+0.10431,+-0.41463+],+[+0.10048,+-0.99445,+-0.03109+]+]+]+},+"Peace": {+"thumb": [+[+[+0.68781,+0.66119,+0.29957+],+[+0.4405,+-0.70821,+0.55173+]+],+[+[+0.47618,+0.60804,+-0.63525+],+[+0.87494,+-0.25536,+0.41143+]+],+[+[+0.28855,+-0.54798,+-0.78515+],+[+0.9063,+-0.10816,+0.40857+]+]+],+"index": [+[+[+0.94335,+-0.08028,+0.32193+],+[+-0.09318,+-0.99534,+0.02483+]+],+[+[+0.9574,+0.04516,+0.2852+],+[+0.0299,+-0.99789,+0.05767+]+],+[+[+0.90537,+0.31066,+0.28946+],+[+0.29009,+-0.95035,+0.11262+]+]+],+"middle": [+[+[+0.99112,+0.10155,+-0.08586+],+[+0.11036,+-0.98833,+0.10498+]+],+[+[+0.99926,+0.0385,+0.00028+],+[+0.03829,+-0.99436,+0.09886+]+],+[+[+0.92944,+0.36408,+-0.05988+],+[+0.36824,+-0.92552,+0.08838+]+]+],+"ring": [+[+[+0.10688,+0.99413,+-0.01703+],+[+0.99423,+-0.10703,+-0.00775+]+],+[+[+-0.93483,+0.32176,+0.15018+],+[+0.32235,+0.94638,+-0.02108+]+],+[+[+0.10692,+-0.99084,+0.08254+],+[+-0.96335,+-0.0827,+0.25518+]+]+],+"pinky": [+[+[+0.14442,+0.98944,+0.01234+],+[+0.98836,+-0.14363,+-0.05014+]+],+[+[+-0.93061,+0.253,+0.2645+],+[+0.27719,+0.95907,+0.0579+]+],+[+[+0.06488,+-0.99316,+0.09711+],+[+-0.92869,+-0.02449,+0.37005+]+]+]+},+"Pinch Flat": {+"thumb": [+[+[+0.70932,+0.55891,+0.42952+],+[+0.33068,+-0.80198,+0.49748+]+],+[+[+0.57328,+0.81934,+-0.00502+],+[+0.75332,+-0.52466,+0.39654+]+],+[+[+0.6196,+0.75793,+-0.20407+],+[+0.77643,+-0.5537,+0.30095+]+]+],+"index": [+[+[+0.7256,+0.68652,+0.04681+],+[+0.68797,+-0.72518,+-0.02852+]+],+[+[+0.16187,+0.98603,+0.03938+],+[+0.98608,+-0.16008,+-0.04494+]+],+[+[+-0.71985,+0.69229,+0.05057+],+[+0.69345,+0.72046,+0.00806+]+]+],+"middle": [+[+[+0.86359,+0.50112,+0.05561+],+[+0.49889,+-0.86524,+0.04963+]+],+[+[+0.63039,+0.7759,+0.02415+],+[+0.77246,+-0.63007,+0.07948+]+],+[+[+0.08582,+0.99487,+-0.05347+],+[+0.99338,+-0.08134,+0.08107+]+]+],+"ring": [+[+[+0.94952,+0.30564,+0.07074+],+[+0.30565,+-0.95208,+0.0109+]+],+[+[+0.752,+0.65915,+0.00293+],+[+0.65793,+-0.75087,+0.05764+]+],+[+[+0.32076,+0.94572,+-0.05216+],+[+0.94552,+-0.31648,+0.07631+]+]+],+"pinky": [+[+[+0.98894,+0.12539,+0.07917+],+[+0.12532,+-0.9921,+0.00588+]+],+[+[+0.96891,+0.23601,+0.07422+],+[+0.23149,+-0.97068,+0.06469+]+],+[+[+0.8113,+0.58449,+0.01256+],+[+0.58098,+-0.80845,+0.09417+]+]+]+},+"Pinch Large": {+"thumb": [+[+[+0.74353,+0.54807,+0.38313+],+[+0.27772,+-0.77428,+0.56865+]+],+[+[+0.6133,+0.75984,+-0.21566+],+[+0.77521,+-0.52673,+0.34871+]+],+[+[+0.62224,+0.66804,+-0.40809+],+[+0.78039,+-0.57045,+0.25609+]+]+],+"index": [+[+[+0.99585,+0.08569,+0.03067+],+[+0.0834,+-0.99409,+0.06952+]+],+[+[+-0.03359,+0.99511,+-0.0929+],+[+0.99943,+0.03366,+-0.00083+]+],+[+[+-0.21428,+0.97515,+-0.05618+],+[+0.97634,+0.21212,+-0.04201+]+]+],+"middle": [+[+[+-0.03291,+0.99908,+-0.02755+],+[+0.99942,+0.03267,+-0.00925+]+],+[+[+-0.9893,+0.12691,+0.07201+],+[+0.12586,+0.99187,+-0.01907+]+],+[+[+0.2116,+-0.97691,+0.02946+],+[+-0.97731,+-0.21118,+0.01662+]+]+],+"ring": [+[+[+0.10688,+0.99413,+-0.01703+],+[+0.99423,+-0.10703,+-0.00775+]+],+[+[+-0.93483,+0.32176,+0.15018+],+[+0.32235,+0.94638,+-0.02108+]+],+[+[+0.10692,+-0.99084,+0.08254+],+[+-0.96335,+-0.0827,+0.25518+]+]+],+"pinky": [+[+[+0.14442,+0.98944,+0.01234+],+[+0.98836,+-0.14363,+-0.05014+]+],+[+[+-0.93061,+0.253,+0.2645+],+[+0.27719,+0.95907,+0.0579+]+],+[+[+0.06488,+-0.99316,+0.09711+],+[+-0.92869,+-0.02449,+0.37005+]+]+]+},+"Pinch Middle": {+"thumb": [+[+[+0.69378,+0.71089,+0.11537+],+[+0.3591,+-0.48032,+0.80021+]+],+[+[+0.54685,+0.74231,+-0.3872+],+[+0.77207,+-0.26823,+0.57616+]+],+[+[+0.59388,+0.5985,+-0.53768+],+[+0.79551,+-0.33687,+0.50367+]+]+],+"index": [+[+[+0.91502,+0.2991,+0.2707+],+[+0.28813,+-0.95421,+0.08037+]+],+[+[+0.737,+0.65751,+0.15654+],+[+0.62992,+-0.75215,+0.19357+]+],+[+[+0.38808,+0.92034,+0.04862+],+[+0.8886,+-0.38765,+0.2452+]+]+],+"middle": [+[+[+0.71824,+0.68957,+-0.09286+],+[+0.69504,+-0.71727,+0.04951+]+],+[+[+0.02,+0.9986,+-0.04899+],+[+0.9998,+-0.01996,+0.00139+]+],+[+[+-0.83889,+0.54345,+-0.03023+],+[+0.54387,+0.83476,+-0.08587+]+]+],+"ring": [+[+[+0.8883,+0.35985,+-0.28536+],+[+0.38998,+-0.91919,+0.05486+]+],+[+[+0.76181,+0.58968,+-0.26819+],+[+0.59928,+-0.79873,+-0.05391+]+],+[+[+0.44341,+0.88018,+-0.1693+],+[+0.87047,+-0.46791,+-0.1528+]+]+],+"pinky": [+[+[+0.80384,+0.38091,+-0.45689+],+[+0.43228,+-0.9017,+0.00879+]+],+[+[+0.61469,+0.69181,+-0.37888+],+[+0.68355,+-0.70691,+-0.18177+]+],+[+[+0.35927,+0.91342,+-0.1913+],+[+0.8541,+-0.40443,+-0.32703+]+]+]+},+"Pinch Ring": {+"thumb": [+[+[+0.80298,+0.58826,+0.09571+],+[+0.26801,+-0.49984,+0.8236+]+],+[+[+0.34946,+0.78232,+-0.51561+],+[+0.87029,+-0.06717,+0.48794+]+],+[+[+0.2687,+0.40131,+-0.87564+],+[+0.9576,+-0.01325,+0.28778+]+]+],+"index": [+[+[+0.91502,+0.2991,+0.2707+],+[+0.28813,+-0.95421,+0.08037+]+],+[+[+0.737,+0.65751,+0.15654+],+[+0.62992,+-0.75215,+0.19357+]+],+[+[+0.38808,+0.92034,+0.04862+],+[+0.8886,+-0.38765,+0.2452+]+]+],+"middle": [+[+[+0.87375,+0.48137,+-0.06957+],+[+0.4854,+-0.87208,+0.06219+]+],+[+[+0.70758,+0.70659,+-0.0073+],+[+0.70559,+-0.70595,+0.06141+]+],+[+[+0.43361,+0.89944,+-0.05466+],+[+0.90084,+-0.43121,+0.05053+]+]+],+"ring": [+[+[+0.66367,+0.7388,+-0.11712+],+[+0.74229,+-0.66981,+-0.01891+]+],+[+[+-0.10094,+0.99195,+-0.07645+],+[+0.99464,+0.10235,+0.01473+]+],+[+[+-0.33417,+0.93731,+-0.09889+],+[+0.93432,+0.34324,+0.09607+]+]+],+"pinky": [+[+[+0.80384,+0.38091,+-0.45689+],+[+0.43228,+-0.9017,+0.00879+]+],+[+[+0.61469,+0.69181,+-0.37888+],+[+0.68355,+-0.70691,+-0.18177+]+],+[+[+0.35927,+0.91342,+-0.1913+],+[+0.8541,+-0.40443,+-0.32703+]+]+]+},+"Pinch Tight": {+"thumb": [+[+[+0.74353,+0.54807,+0.38313+],+[+0.27772,+-0.77428,+0.56865+]+],+[+[+0.62501,+0.77714,+-0.07363+],+[+0.71749,+-0.53473,+0.4464+]+],+[+[+0.66745,+0.69547,+-0.26616+],+[+0.73877,+-0.57356,+0.35391+]+]+],+"index": [+[+[+0.76838,+0.63993,+-0.00925+],+[+0.63972,+-0.76755,+0.04032+]+],+[+[+0.22517,+0.97319,+-0.04689+],+[+0.97373,+-0.22645,+-0.02403+]+],+[+[+-0.67368,+0.73886,+-0.01565+],+[+0.73852,+0.67229,+-0.05106+]+]+],+"middle": [+[+[+-0.03291,+0.99908,+-0.02755+],+[+0.99942,+0.03267,+-0.00925+]+],+[+[+-0.9893,+0.12691,+0.07201+],+[+0.12586,+0.99187,+-0.01907+]+],+[+[+0.2116,+-0.97691,+0.02946+],+[+-0.97731,+-0.21118,+0.01662+]+]+],+"ring": [+[+[+0.10688,+0.99413,+-0.01703+],+[+0.99423,+-0.10703,+-0.00775+]+],+[+[+-0.93483,+0.32176,+0.15018+],+[+0.32235,+0.94638,+-0.02108+]+],+[+[+0.10692,+-0.99084,+0.08254+],+[+-0.96335,+-0.0827,+0.25518+]+]+],+"pinky": [+[+[+0.14442,+0.98944,+0.01234+],+[+0.98836,+-0.14363,+-0.05014+]+],+[+[+-0.93061,+0.253,+0.2645+],+[+0.27719,+0.95907,+0.0579+]+],+[+[+0.06488,+-0.99316,+0.09711+],+[+-0.92869,+-0.02449,+0.37005+]+]+]+},+"Pinch Up": {+"thumb": [+[+[+0.74353,+0.54807,+0.38313+],+[+0.27772,+-0.77428,+0.56865+]+],+[+[+0.62501,+0.77714,+-0.07363+],+[+0.71749,+-0.53473,+0.4464+]+],+[+[+0.66745,+0.69547,+-0.26616+],+[+0.73877,+-0.57356,+0.35391+]+]+],+"index": [+[+[+0.76838,+0.63993,+-0.00925+],+[+0.63972,+-0.76755,+0.04032+]+],+[+[+0.22517,+0.97319,+-0.04689+],+[+0.97373,+-0.22645,+-0.02403+]+],+[+[+-0.67368,+0.73886,+-0.01565+],+[+0.73852,+0.67229,+-0.05106+]+]+],+"middle": [+[+[+0.83939,+0.54039,+-0.05828+],+[+0.54347,+-0.83597,+0.07609+]+],+[+[+0.7225,+0.68757,+-0.07236+],+[+0.69136,+-0.71902,+0.07094+]+],+[+[+0.40569,+0.9076,+-0.10808+],+[+0.91328,+-0.40725,+0.00824+]+]+],+"ring": [+[+[+0.93836,+0.34562,+-0.00499+],+[+0.34432,+-0.93337,+0.10135+]+],+[+[+0.78959,+0.60825,+-0.08115+],+[+0.61335,+-0.77824,+0.13468+]+],+[+[+0.62523,+0.77348,+-0.10402+],+[+0.77972,+-0.61336,+0.12581+]+]+],+"pinky": [+[+[+0.99526,+0.09669,+-0.01032+],+[+0.09721,+-0.98695,+0.12835+]+],+[+[+0.94457,+0.32575,+-0.04082+],+[+0.32763,+-0.92743,+0.18039+]+],+[+[+0.76986,+0.6284,+-0.11152+],+[+0.63794,+-0.75253,+0.16351+]+]+]+},+"PingPong": {+"thumb": [+[+[+0.74353,+0.54807,+0.38313+],+[+0.27772,+-0.77428,+0.56865+]+],+[+[+0.62501,+0.77714,+-0.07363+],+[+0.71749,+-0.53473,+0.4464+]+],+[+[+0.66745,+0.69547,+-0.26616+],+[+0.73877,+-0.57356,+0.35391+]+]+],+"index": [+[+[+0.76838,+0.63993,+-0.00925+],+[+0.63972,+-0.76755,+0.04032+]+],+[+[+0.22517,+0.97319,+-0.04689+],+[+0.97373,+-0.22645,+-0.02403+]+],+[+[+-0.67368,+0.73886,+-0.01565+],+[+0.73852,+0.67229,+-0.05106+]+]+],+"middle": [+[+[+0.30163,+0.9504,+-0.07587+],+[+0.95342,+-0.30086,+0.02159+]+],+[+[+-0.7078,+0.70331,+-0.0662+],+[+0.70602,+0.70742,+-0.03303+]+],+[+[+-0.71808,+-0.69438,+0.0469+],+[+-0.69404,+0.70947,+-0.1223+]+]+],+"ring": [+[+[+0.34087,+0.93553,+-0.09274+],+[+0.94011,+-0.33923,+0.03334+]+],+[+[+-0.65679,+0.74766,+-0.09814+],+[+0.75236,+0.65849,+-0.01842+]+],+[+[+-0.73185,+-0.66876,+0.131+],+[+-0.67703,+0.73542,+-0.02794+]+]+],+"pinky": [+[+[+0.45911,+0.88642,+-0.05899+],+[+0.88836,+-0.45848,+0.02466+]+],+[+[+-0.63951,+0.76658,+-0.05817+],+[+0.7625,+0.64212,+0.07926+]+],+[+[+-0.81578,+-0.56663,+0.11591+],+[+-0.56818,+0.8226,+0.02245+]+]+]+},+"Pinky": {+"thumb": [+[+[+0.67702,+0.56526,+0.4713+],+[+0.17653,+-0.74641,+0.64164+]+],+[+[+0.83434,+0.48184,+-0.26778+],+[+0.485,+-0.41074,+0.77205+]+],+[+[+0.36307,+-0.05202,+-0.93031+],+[+0.78984,+-0.51249,+0.33691+]+]+],+"index": [+[+[+0.013,+0.99978,+0.01621+],+[+0.99968,+-0.01264,+-0.02213+]+],+[+[+-0.98795,+0.14753,+0.04686+],+[+0.14672,+0.98897,+-0.02027+]+],+[+[+0.11437,+-0.98912,+-0.09248+],+[+-0.99245,+-0.11791,+0.03375+]+]+],+"middle": [+[+[+-0.03291,+0.99908,+-0.02755+],+[+0.99942,+0.03267,+-0.00925+]+],+[+[+-0.9893,+0.12691,+0.07201+],+[+0.12586,+0.99187,+-0.01907+]+],+[+[+0.2116,+-0.97691,+0.02946+],+[+-0.97731,+-0.21118,+0.01662+]+]+],+"ring": [+[+[+0.10688,+0.99413,+-0.01703+],+[+0.99423,+-0.10703,+-0.00775+]+],+[+[+-0.93483,+0.32176,+0.15018+],+[+0.32235,+0.94638,+-0.02108+]+],+[+[+0.10692,+-0.99084,+0.08254+],+[+-0.96335,+-0.0827,+0.25518+]+]+],+"pinky": [+[+[+0.78767,+0.61105,+-0.07866+],+[+0.61603,+-0.77937,+0.11438+]+],+[+[+0.50437,+0.86258,+-0.03955+],+[+0.85553,+-0.49299,+0.15818+]+],+[+[+0.31519,+0.94262,+-0.11006+],+[+0.94105,+-0.29543,+0.16473+]+]+]+},+"Pistol": {+"thumb": [+[+[+0.82749,+0.32552,+0.45749+],+[+0.38391,+-0.92259,+-0.03794+]+],+[+[+0.66691,+0.74513,+-0.00394+],+[+0.74481,+-0.66644,+0.03345+]+],+[+[+0.55091,+0.5344,+-0.64103+],+[+0.763,+-0.63371,+0.12744+]+]+],+"index": [+[+[+0.993,+-0.09369,+0.07195+],+[+-0.09927,+-0.99197,+0.07837+]+],+[+[+0.46068,+0.88664,+-0.04062+],+[+0.88712,+-0.45851,+0.05273+]+],+[+[+-0.65427,+0.75421,+-0.05558+],+[+0.75582,+0.65463,+-0.01396+]+]+],+"middle": [+[+[+0.50712,+0.85911,+-0.06895+],+[+0.86173,+-0.5069,+0.02191+]+],+[+[+-0.44272,+0.89651,+0.0162+],+[+0.89626,+0.44299,+-0.02194+]+],+[+[+-0.98741,+-0.14835,+0.05483+],+[+-0.15126,+0.98704,+-0.0535+]+]+],+"ring": [+[+[+0.58219,+0.80223,+-0.1322+],+[+0.80963,+-0.58693,+0.00382+]+],+[+[+-0.38039,+0.92429,+0.03144+],+[+0.91853,+0.38154,+-0.10362+]+],+[+[+-0.98247,+0.0071,+0.1863+],+[+0.01195,+0.99962,+0.02491+]+]+],+"pinky": [+[+[+0.53387,+0.82699,+-0.17624+],+[+0.83508,+-0.54839,+-0.04363+]+],+[+[+-0.43695,+0.89085,+0.12434+],+[+0.88782,+0.44934,+-0.09936+]+],+[+[+-0.94471,+0.02856,+0.32665+],+[+0.05054,+0.99698,+0.059+]+]+]+},+"Ring": {+"thumb": [+[+[+0.67702,+0.56526,+0.4713+],+[+0.17653,+-0.74641,+0.64164+]+],+[+[+0.83434,+0.48184,+-0.26778+],+[+0.485,+-0.41074,+0.77205+]+],+[+[+0.36307,+-0.05202,+-0.93031+],+[+0.78984,+-0.51249,+0.33691+]+]+],+"index": [+[+[+0.013,+0.99978,+0.01621+],+[+0.99968,+-0.01264,+-0.02213+]+],+[+[+-0.98795,+0.14753,+0.04686+],+[+0.14672,+0.98897,+-0.02027+]+],+[+[+0.11437,+-0.98912,+-0.09248+],+[+-0.99245,+-0.11791,+0.03375+]+]+],+"middle": [+[+[+-0.03291,+0.99908,+-0.02755+],+[+0.99942,+0.03267,+-0.00925+]+],+[+[+-0.9893,+0.12691,+0.07201+],+[+0.12586,+0.99187,+-0.01907+]+],+[+[+0.2116,+-0.97691,+0.02946+],+[+-0.97731,+-0.21118,+0.01662+]+]+],+"ring": [+[+[+0.88254,+0.46875,+-0.03739+],+[+0.46399,+-0.85512,+0.23125+]+],+[+[+0.68664,+0.72241,+-0.08155+],+[+0.71595,+-0.65247,+0.2484+]+],+[+[+0.4787,+0.86165,+-0.16854+],+[+0.86784,+-0.43528,+0.23956+]+]+],+"pinky": [+[+[+0.14442,+0.98944,+0.01234+],+[+0.98836,+-0.14363,+-0.05014+]+],+[+[+-0.93061,+0.253,+0.2645+],+[+0.27719,+0.95907,+0.0579+]+],+[+[+0.06488,+-0.99316,+0.09711+],+[+-0.92869,+-0.02449,+0.37005+]+]+]+},+"Rounded": {+"thumb": [+[+[+0.7569,+0.25347,+0.60237+],+[+0.21628,+-0.96694,+0.13512+]+],+[+[+0.75298,+0.50667,+0.41989+],+[+0.44613,+-0.86212,+0.24026+]+],+[+[+0.84439,+0.4786,+0.24073+],+[+0.41063,+-0.86679,+0.28295+]+]+],+"index": [+[+[+0.9191,+0.29078,+0.26589+],+[+0.26904,+-0.95616,+0.11567+]+],+[+[+0.48575,+0.86737,+0.10826+],+[+0.84001,+-0.49747,+0.2166+]+],+[+[+-0.10345,+0.99453,+-0.01426+],+[+0.96737,+0.10394,+0.23108+]+]+],+"middle": [+[+[+0.90162,+0.42232,+-0.09338+],+[+0.42994,+-0.89864,+0.08709+]+],+[+[+0.53854,+0.8411,+-0.05035+],+[+0.84251,+-0.53665,+0.04662+]+],+[+[+-0.12471,+0.9889,+-0.08079+],+[+0.99201,+0.12271,+-0.02935+]+]+],+"ring": [+[+[+0.8955,+0.3413,+-0.28566+],+[+0.3703,+-0.92741,+0.05277+]+],+[+[+0.54305,+0.81232,+-0.2127+],+[+0.81571,+-0.57045,+-0.096+]+],+[+[+-0.02298,+0.99441,+-0.10302+],+[+0.98268,+0.00351,+-0.1853+]+]+],+"pinky": [+[+[+0.80898,+0.37779,+-0.45037+],+[+0.41815,+-0.90832,+-0.01084+]+],+[+[+0.4403,+0.86261,+-0.24907+],+[+0.8442,+-0.4922,+-0.2123+]+],+[+[+-0.04382,+0.99717,+-0.0611+],+[+0.94672,+0.02191,+-0.32131+]+]+]+},+"Sign 1": {+"thumb": [+[+[+0.67702,+0.56526,+0.4713+],+[+0.17653,+-0.74641,+0.64164+]+],+[+[+0.83434,+0.48184,+-0.26778+],+[+0.485,+-0.41074,+0.77205+]+],+[+[+0.36307,+-0.05202,+-0.93031+],+[+0.78984,+-0.51249,+0.33691+]+]+],+"index": [+[+[+0.99303,+-0.09083,+0.07505+],+[+-0.09767,+-0.99086,+0.09308+]+],+[+[+0.99882,+0.03205,+0.03639+],+[+0.03028,+-0.99839,+0.048+]+],+[+[+0.95301,+0.29816,+0.05364+],+[+0.29655,+-0.95434,+0.03607+]+]+],+"middle": [+[+[+-0.03291,+0.99908,+-0.02755+],+[+0.99942,+0.03267,+-0.00925+]+],+[+[+-0.9893,+0.12691,+0.07201+],+[+0.12586,+0.99187,+-0.01907+]+],+[+[+0.2116,+-0.97691,+0.02946+],+[+-0.97731,+-0.21118,+0.01662+]+]+],+"ring": [+[+[+0.10688,+0.99413,+-0.01703+],+[+0.99423,+-0.10703,+-0.00775+]+],+[+[+-0.93483,+0.32176,+0.15018+],+[+0.32235,+0.94638,+-0.02108+]+],+[+[+0.10692,+-0.99084,+0.08254+],+[+-0.96335,+-0.0827,+0.25518+]+]+],+"pinky": [+[+[+0.14442,+0.98944,+0.01234+],+[+0.98836,+-0.14363,+-0.05014+]+],+[+[+-0.93061,+0.253,+0.2645+],+[+0.27719,+0.95907,+0.0579+]+],+[+[+0.06488,+-0.99316,+0.09711+],+[+-0.92869,+-0.02449,+0.37005+]+]+]+},+"Sign 2": {+"thumb": [+[+[+0.68781,+0.66119,+0.29957+],+[+0.4405,+-0.70821,+0.55173+]+],+[+[+0.47618,+0.60804,+-0.63525+],+[+0.87494,+-0.25536,+0.41143+]+],+[+[+0.28855,+-0.54798,+-0.78515+],+[+0.9063,+-0.10816,+0.40857+]+]+],+"index": [+[+[+0.9837,+-0.09011,+0.15558+],+[+-0.09978,+-0.99346,+0.05552+]+],+[+[+0.99275,+0.03464,+0.1151+],+[+0.02707,+-0.99741,+0.06668+]+],+[+[+0.94552,+0.30091,+0.12427+],+[+0.29342,+-0.95302,+0.07522+]+]+],+"middle": [+[+[+0.99112,+0.10155,+-0.08586+],+[+0.11036,+-0.98833,+0.10498+]+],+[+[+0.99926,+0.0385,+0.00028+],+[+0.03829,+-0.99436,+0.09886+]+],+[+[+0.92944,+0.36408,+-0.05988+],+[+0.36824,+-0.92552,+0.08838+]+]+],+"ring": [+[+[+0.10688,+0.99413,+-0.01703+],+[+0.99423,+-0.10703,+-0.00775+]+],+[+[+-0.93483,+0.32176,+0.15018+],+[+0.32235,+0.94638,+-0.02108+]+],+[+[+0.10692,+-0.99084,+0.08254+],+[+-0.96335,+-0.0827,+0.25518+]+]+],+"pinky": [+[+[+0.14442,+0.98944,+0.01234+],+[+0.98836,+-0.14363,+-0.05014+]+],+[+[+-0.93061,+0.253,+0.2645+],+[+0.27719,+0.95907,+0.0579+]+],+[+[+0.06488,+-0.99316,+0.09711+],+[+-0.92869,+-0.02449,+0.37005+]+]+]+},+"Sign 3": {+"thumb": [+[+[+0.89339,+0.44927,+0.00418+],+[+0.30371,+-0.61074,+0.73127+]+],+[+[+0.33591,+0.72063,+-0.60651+],+[+0.94097,+-0.28529,+0.18218+]+],+[+[+0.01385,+0.07554,+-0.99705+],+[+0.98856,+-0.1508,+0.00231+]+]+],+"index": [+[+[+0.94335,+-0.08028,+0.32193+],+[+-0.09318,+-0.99534,+0.02483+]+],+[+[+0.9574,+0.04516,+0.2852+],+[+0.0299,+-0.99789,+0.05767+]+],+[+[+0.90537,+0.31066,+0.28946+],+[+0.29009,+-0.95035,+0.11262+]+]+],+"middle": [+[+[+0.99112,+0.10155,+-0.08586+],+[+0.11036,+-0.98833,+0.10498+]+],+[+[+0.99926,+0.0385,+0.00028+],+[+0.03829,+-0.99436,+0.09886+]+],+[+[+0.92944,+0.36408,+-0.05988+],+[+0.36824,+-0.92552,+0.08838+]+]+],+"ring": [+[+[+0.95154,+0.0231,+-0.30666+],+[+0.07001,+-0.98726,+0.14286+]+],+[+[+0.96421,+0.00601,+-0.26507+],+[+0.04424,+-0.98938,+0.13849+]+],+[+[+0.91206,+0.2606,+-0.31661+],+[+0.30097,+-0.94982,+0.08521+]+]+],+"pinky": [+[+[+0.14442,+0.98944,+0.01234+],+[+0.98836,+-0.14363,+-0.05014+]+],+[+[+-0.68116,+0.57934,+0.44764+],+[+0.49692,+0.81486,+-0.29845+]+],+[+[+-0.81832,+0.23316,+0.52534+],+[+0.2294,+0.97056,+-0.07341+]+]+]+},+"Sign 4": {+"thumb": [+[+[+0.70915,+0.60753,+0.35779+],+[+0.40229,+-0.7654,+0.50231+]+],+[+[+0.75917,+0.18621,+-0.62368+],+[+0.46291,+-0.82808,+0.31623+]+],+[+[+-0.1728,+-0.50362,+-0.84647+],+[+0.58684,+-0.74285,+0.32217+]+]+],+"index": [+[+[+0.94335,+-0.08028,+0.32193+],+[+-0.09318,+-0.99534,+0.02483+]+],+[+[+0.9574,+0.04516,+0.2852+],+[+0.0299,+-0.99789,+0.05767+]+],+[+[+0.90537,+0.31066,+0.28946+],+[+0.29009,+-0.95035,+0.11262+]+]+],+"middle": [+[+[+0.99112,+0.10155,+-0.08586+],+[+0.11036,+-0.98833,+0.10498+]+],+[+[+0.99926,+0.0385,+0.00028+],+[+0.03829,+-0.99436,+0.09886+]+],+[+[+0.92944,+0.36408,+-0.05988+],+[+0.36824,+-0.92552,+0.08838+]+]+],+"ring": [+[+[+0.95154,+0.0231,+-0.30666+],+[+0.07001,+-0.98726,+0.14286+]+],+[+[+0.96421,+0.00601,+-0.26507+],+[+0.04424,+-0.98938,+0.13849+]+],+[+[+0.91206,+0.2606,+-0.31661+],+[+0.30097,+-0.94982,+0.08521+]+]+],+"pinky": [+[+[+0.8707,+-0.10211,+-0.48109+],+[+-0.03268,+-0.98806,+0.15057+]+],+[+[+0.91661,+-0.06228,+-0.39491+],+[+-0.01322,+-0.99197,+0.12577+]+],+[+[+0.88248,+0.14572,+-0.44721+],+[+0.19014,+-0.98017,+0.05583+]+]+]+},+"Sign 5": {+"thumb": [+[+[+0.74998,+-0.03028,+0.66076+],+[+0.03562,+-0.99565,+-0.08606+]+],+[+[+0.79064,+0.12959,+0.59841+],+[+0.18595,+-0.982,+-0.03303+]+],+[+[+0.69274,+-0.16501,+0.70206+],+[+0.22797,+-0.87346,+-0.43024+]+]+],+"index": [+[+[+0.94335,+-0.08028,+0.32193+],+[+-0.09318,+-0.99534,+0.02483+]+],+[+[+0.9574,+0.04516,+0.2852+],+[+0.0299,+-0.99789,+0.05767+]+],+[+[+0.90537,+0.31066,+0.28946+],+[+0.29009,+-0.95035,+0.11262+]+]+],+"middle": [+[+[+0.99112,+0.10155,+-0.08586+],+[+0.11036,+-0.98833,+0.10498+]+],+[+[+0.99926,+0.0385,+0.00028+],+[+0.03829,+-0.99436,+0.09886+]+],+[+[+0.92944,+0.36408,+-0.05988+],+[+0.36824,+-0.92552,+0.08838+]+]+],+"ring": [+[+[+0.95154,+0.0231,+-0.30666+],+[+0.07001,+-0.98726,+0.14286+]+],+[+[+0.96421,+0.00601,+-0.26507+],+[+0.04424,+-0.98938,+0.13849+]+],+[+[+0.91206,+0.2606,+-0.31661+],+[+0.30097,+-0.94982,+0.08521+]+]+],+"pinky": [+[+[+0.8707,+-0.10211,+-0.4811+],+[+-0.03268,+-0.98806,+0.15057+]+],+[+[+0.91661,+-0.06228,+-0.39491+],+[+-0.01322,+-0.99197,+0.12576+]+],+[+[+0.88248,+0.14572,+-0.44721+],+[+0.19014,+-0.98017,+0.05583+]+]+]+},+"Sign_Point": {+"thumb": [+[+[+0.70915,+0.60753,+0.35779+],+[+0.40229,+-0.7654,+0.50231+]+],+[+[+0.68744,+0.69615,+0.20687+],+[+0.53695,+-0.67901,+0.50063+]+],+[+[+0.64283,+0.69935,+0.31254+],+[+0.50732,+-0.69439,+0.51034+]+]+],+"index": [+[+[+0.99303,+-0.09083,+0.07505+],+[+-0.09767,+-0.99086,+0.09308+]+],+[+[+0.99882,+0.03205,+0.03639+],+[+0.03028,+-0.99839,+0.048+]+],+[+[+0.95301,+0.29816,+0.05364+],+[+0.29655,+-0.95434,+0.03607+]+]+],+"middle": [+[+[+-0.03291,+0.99908,+-0.02755+],+[+0.99942,+0.03267,+-0.00925+]+],+[+[+-0.9893,+0.12691,+0.07201+],+[+0.12586,+0.99187,+-0.01907+]+],+[+[+0.2116,+-0.97691,+0.02946+],+[+-0.97731,+-0.21118,+0.01662+]+]+],+"ring": [+[+[+0.10688,+0.99413,+-0.01703+],+[+0.99423,+-0.10703,+-0.00775+]+],+[+[+-0.93483,+0.32176,+0.15018+],+[+0.32235,+0.94638,+-0.02108+]+],+[+[+0.10692,+-0.99084,+0.08254+],+[+-0.96335,+-0.0827,+0.25518+]+]+],+"pinky": [+[+[+0.14442,+0.98944,+0.01234+],+[+0.98836,+-0.14363,+-0.05014+]+],+[+[+-0.93061,+0.253,+0.2645+],+[+0.27719,+0.95907,+0.0579+]+],+[+[+0.06488,+-0.99316,+0.09711+],+[+-0.92869,+-0.02449,+0.37005+]+]+]+},+"Straight": {+"thumb": [+[+[+0.76702,+0.19607,+0.61093+],+[+0.15278,+-0.98059,+0.12289+]+],+[+[+0.98772,+-0.01968,+0.15496+],+[+-0.03248,+-0.99622,+0.08052+]+],+[+[+0.99454,+-0.08131,+-0.06541+],+[+-0.08127,+-0.99669,+0.00329+]+]+],+"index": [+[+[+0.99449,+-0.099,+-0.03444+],+[+-0.0941,+-0.98799,+0.12259+]+],+[+[+0.9905,+0.11005,+-0.08248+],+[+0.11452,+-0.99208,+0.05156+]+],+[+[+0.92614,+0.37207,+-0.06192+],+[+0.37322,+-0.92771,+0.00782+]+]+],+"middle": [+[+[+0.99375,+0.10805,+-0.02803+],+[+0.11035,+-0.98879,+0.10063+]+],+[+[+0.99184,+0.12198,+-0.03717+],+[+0.12518,+-0.98696,+0.10121+]+],+[+[+0.89278,+0.44015,+-0.09594+],+[+0.44758,+-0.89082,+0.07815+]+]+],+"ring": [+[+[+0.9968,+0.07329,+0.03182+],+[+0.06962,+-0.9921,+0.10441+]+],+[+[+0.9915,+0.12717,+-0.02753+],+[+0.12986,+-0.98052,+0.14736+]+],+[+[+0.92255,+0.37509,+-0.09061+],+[+0.38515,+-0.90944,+0.15674+]+]+],+"pinky": [+[+[+0.99581,+-0.02243,+0.08862+],+[+-0.03352,+-0.9915,+0.12568+]+],+[+[+0.9936,+0.08855,+0.07019+],+[+0.07433,+-0.98007,+0.1842+]+],+[+[+0.95764,+0.28787,+-0.00819+],+[+0.28292,+-0.93509,+0.21344+]+]+]+},+"Surfer": {+"thumb": [+[+[+0.76702,+0.19607,+0.61093+],+[+0.15278,+-0.98059,+0.12289+]+],+[+[+0.65037,+0.20996,+0.73002+],+[+0.18135,+-0.97617,+0.11918+]+],+[+[+0.19192,+0.04254,+0.98049+],+[+-0.1913,+-0.97827,+0.07989+]+]+],+"index": [+[+[+0.013,+0.99978,+0.01621+],+[+0.99968,+-0.01264,+-0.02213+]+],+[+[+-0.98795,+0.14752,+0.04686+],+[+0.14672,+0.98897,+-0.02027+]+],+[+[+0.11437,+-0.98912,+-0.09248+],+[+-0.99245,+-0.11791,+0.03375+]+]+],+"middle": [+[+[+-0.03291,+0.99908,+-0.02755+],+[+0.99942,+0.03267,+-0.00925+]+],+[+[+-0.9893,+0.12691,+0.07201+],+[+0.12586,+0.99187,+-0.01907+]+],+[+[+0.2116,+-0.97691,+0.02946+],+[+-0.97731,+-0.21118,+0.01662+]+]+],+"ring": [+[+[+0.10688,+0.99413,+-0.01703+],+[+0.99423,+-0.10703,+-0.00775+]+],+[+[+-0.93483,+0.32176,+0.15018+],+[+0.32235,+0.94638,+-0.02108+]+],+[+[+0.10692,+-0.99084,+0.08254+],+[+-0.96335,+-0.0827,+0.25518+]+]+],+"pinky": [+[+[+0.87052,+-0.02778,+-0.49136+],+[+0.05452,+-0.98682,+0.15239+]+],+[+[+0.8734,+0.0113,+-0.48687+],+[+0.06836,+-0.99268,+0.09961+]+],+[+[+0.81979,+0.21732,+-0.52983+],+[+0.26218,+-0.96497,+0.00987+]+]+]+},+"Thumb": {+"thumb": [+[+[+0.76702,+0.19607,+0.61093+],+[+0.15278,+-0.98059,+0.12289+]+],+[+[+0.65037,+0.20996,+0.73002+],+[+0.18135,+-0.97617,+0.11918+]+],+[+[+0.19192,+0.04254,+0.98049+],+[+-0.1913,+-0.97827,+0.07989+]+]+],+"index": [+[+[+0.013,+0.99978,+0.01621+],+[+0.99968,+-0.01264,+-0.02213+]+],+[+[+-0.98795,+0.14753,+0.04686+],+[+0.14672,+0.98897,+-0.02027+]+],+[+[+0.11437,+-0.98912,+-0.09248+],+[+-0.99245,+-0.11791,+0.03375+]+]+],+"middle": [+[+[+-0.03291,+0.99908,+-0.02755+],+[+0.99942,+0.03267,+-0.00925+]+],+[+[+-0.9893,+0.12691,+0.07201+],+[+0.12586,+0.99187,+-0.01907+]+],+[+[+0.2116,+-0.97691,+0.02946+],+[+-0.97731,+-0.21118,+0.01662+]+]+],+"ring": [+[+[+0.10688,+0.99413,+-0.01703+],+[+0.99423,+-0.10703,+-0.00775+]+],+[+[+-0.93483,+0.32176,+0.15018+],+[+0.32235,+0.94638,+-0.02108+]+],+[+[+0.10692,+-0.99084,+0.08254+],+[+-0.96335,+-0.0827,+0.25518+]+]+],+"pinky": [+[+[+0.14442,+0.98944,+0.01234+],+[+0.98836,+-0.14363,+-0.05014+]+],+[+[+-0.93061,+0.253,+0.2645+],+[+0.27719,+0.95907,+0.0579+]+],+[+[+0.06488,+-0.99316,+0.09711+],+[+-0.92869,+-0.02449,+0.37005+]+]+]+}+}+}\ No newline at end of filediff --git a/sdk/character/src/character/skeleton.ts b/sdk/character/src/character/skeleton.tsindex 0914f654..23ef676f 100644--- a/sdk/character/src/character/skeleton.ts+++ b/sdk/character/src/character/skeleton.ts@@ -1,6 +1,6 @@// The skeleton: joints, rest, posing.import { type Vec3 } from "@raea/render/3d";-import { I, Pose, Posed, Quat, Skeleton, add, qfromTo, qinv, qmul, qnorm, qrot, sub } from "./all";+import { B, I, Pose, Posed, Quat, Skeleton, add, isFinger, qfromTo, qinv, qmul, qnorm, qrot, sub } from "./all";// ---------------------------------------------------------------- the skeleton@@ -21,17 +21,17 @@ export function joint(skel: Skeleton, name: string): number {* faster. */export function bodyScale(skel: Skeleton): number {const J = (n: string) => skel.joints[joint(skel, n)].head, d = (a: number[], b: number[]) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);- return (d(J("LeftUpLeg"), J("LeftLeg")) + d(J("LeftLeg"), J("LeftFoot"))) / 0.5944;+ return (d(J(B.thigh("L")), J(B.calf("L"))) + d(J(B.calf("L")), J(B.foot("L")))) / 0.5944;}-/** How many of the skeleton's joints a capture turns (CMU's 31): the fingers' own joints come after them, and a clip's- * frames have a turn for each of these only. */+/** How many of the skeleton's joints a capture turns: the body's (bones.ts BODY_JOINTS), the fingers' coming after+ * them, and a clip's frames have a turn for each of these only. */const capturedOf = new WeakMap<Skeleton, number>();export function captured(skel: Skeleton): number {let k = capturedOf.get(skel);if (k === undefined) {- k = skel.joints.findIndex((j) => j.follow !== undefined);+ k = skel.joints.findIndex((j) => isFinger(j.name));capturedOf.set(skel, (k = k < 0 ? skel.joints.length : k));}return k;@@ -43,12 +43,9 @@ export function rest(skel: Skeleton): Pose {return { root: [...skel.joints[0].head] as Vec3, turns: skel.joints.slice(0, captured(skel)).map(() => I) };}-/** Each joint's place and turn (forward kinematics). Parents come before their children in the skeleton. A finger's- * own joint (`follow`) turns on top of the chain its skin rode before: unturned (every clip), it is carried exactly- * as the joint it follows carries it, so a finger rides the capture's finger base and finger as it always did; turned,- * it bends from there down its own chain. A pose that turns none of them (a clip's: as many turns as the capture's- * joints) is drawn without them, the capture's joints placing them (`withFingers`; the skin, fingerSegments and- * surface add them): they cost three times a joint, and the solvers pose a body thousands of times a run. */+/** Each joint's place and turn (forward kinematics). Parents come before their children in the skeleton. A pose that+ * turns only the body's joints (a clip's) is drawn without the fingers (`withFingers` adds them, unturned): they cost+ * more than the body, and the solvers pose a body thousands of times a run. */export function pose(skel: Skeleton, p: Pose): Posed {const nc = captured(skel), n = p.turns.length > nc ? skel.joints.length : nc;return place(skel, p.turns, { pos: new Array(n), rot: new Array(n) }, 0, n, p.root);@@ -62,22 +59,14 @@ export function withFingers(skel: Skeleton, w: Posed): Posed {export function place(skel: Skeleton, turns: Quat[], w: Posed, from: number, to: number, root: Vec3): Posed {const J = skel.joints, { pos, rot } = w;- // where the old chain puts a finger's joint: rigid on the joint it follows- const rig = (i: number) => { const f = J[i].follow; return f === undefined ? pos[i] : add(pos[f], qrot(rot[f], sub(J[i].head, J[f].head))); };for (let i = from; i < to; i++) {- const t = turns[i] ?? I, par = J[i].parent, f = J[i].follow;+ const t = turns[i] ?? I, par = J[i].parent;if (par < 0) {rot[i] = t;pos[i] = root;- } else if (f === undefined) {+ } else {rot[i] = qmul(rot[par], t);pos[i] = add(pos[par], qrot(rot[par], sub(J[i].head, J[par].head)));- } else {- // its turn and step from the parent's place on the old chain, both carried by the parent as it is: unturned,- // parents and all, that is the old chain exactly- const pf = J[par].follow ?? par, back = qinv(rot[pf]);- rot[i] = qmul(qmul(rot[par], qmul(back, rot[f])), t);- pos[i] = add(pos[par], qrot(rot[par], qrot(back, sub(rig(i), rig(par)))));}}return w;@@ -85,12 +74,10 @@ export function place(skel: Skeleton, turns: Quat[], w: Posed, from: number, to:/** A copy of a pose with joint i's turn in the body's frame made `world` (its children ride with it). */export function setWorld(skel: Skeleton, p: Pose, w: Posed, i: number, world: Quat): Pose {- const J = skel.joints, par = J[i].parent, f = J[i].follow;- if (f !== undefined) w = withFingers(skel, w);+ const par = skel.joints[i].parent;+ if (par >= w.rot.length || i >= w.rot.length) w = withFingers(skel, w);const turns = p.turns.slice();- // (a finger's joint turns on top of the old chain's turn: see `pose`)- const from = par < 0 ? I : f === undefined ? w.rot[par] : qmul(w.rot[par], qmul(qinv(w.rot[J[par].follow ?? par]), w.rot[f]));- turns[i] = qnorm(qmul(qinv(from), world));+ turns[i] = qnorm(qmul(qinv(par < 0 ? I : w.rot[par]), world));return { ...p, turns };}diff --git a/sdk/character/src/character/skin.ts b/sdk/character/src/character/skin.tsnew file mode 100644index 00000000..49307b72--- /dev/null+++ b/sdk/character/src/character/skin.ts@@ -0,0 +1,126 @@+// Skin, shaded as skin (<Character skin> puts it on a body's "skin" material, the name projects/psx gives it). Real-time+// skin as games do it, in the material's two hooks (docs/shaders.feature SH1), with no pass of its own:+// surface the photo's own surface detail (psx fit.py's skin_detail.png, from Marigold's normals of the photo: its+// folds and the nose's and lips' shape finer than the mesh), against a frame made from the screen's+// derivatives; then the skin's fine relief and pores from a photograph of real skin (psx skintile.py's+// skin_micro.png, from a CC0 macro photo; 11-05, replacing pores drawn here as noise), tiled about 25 mm+// across. It fades out as it shrinks below a pixel, so a wide shot shows smooth skin rather than shimmering+// grain, and the skin goes a little rougher as it does (the shine it broke up spreads: Activision's+// "Next-Gen Character Rendering", GDC 2013). How strongly it shows by region comes from the body's+// skin_mask.png (psx fit.py: none on the lips).+// lit light scattered under the skin: each directional light's diffuse redone with a softer falloff, wider for+// red than green, wider than blue, and with red shaded from the mesh's smooth normal rather than the fine relief's+// (pre-integrated skin, Penner and Borshukov, GPU Pro 2, 2011, without its lookup table: a wrap per channel,+// widened where the surface curves fast, at the nose, lips and ears), and red reaching further into a+// shadow's soft edge. It adds the difference to Bevy's own diffuse, light by light, under the same shadow.+// The second, tighter shine of oily skin is the material's clearcoat (Bevy's own layer), set by <Character skin>.+export const SKIN_WESL = /* wgsl */ `+// a data texture's stored value: raea's shader textures load as sRGB colour images (no way yet to load one linear),+// so the GPU decoded the map's bytes as colour; encoded again here (unencoded, a flat 0.5 read as 0.21 and tilted+// every pixel along its triangle's own frame: faint facets over the face)+fn skin_stored(c: vec3<f32>) -> vec3<f32> {+ return select(1.055 * pow(c, vec3<f32>(1.0 / 2.4)) - 0.055, c * 12.92, c <= vec3<f32>(0.0031308));+}++fn surface(in: VertexOutput, pbr: ptr<function, PbrInput>) {+ let p = in.uv * u_micro().x; // the tile's coordinates (unwrapped)+ // (derivatives first, in uniform control flow)+ let dp1 = dpdx(in.world_position.xyz);+ let dp2 = dpdy(in.world_position.xyz);+ let duv1 = dpdx(in.uv);+ let duv2 = dpdy(in.uv);+ let dq1 = dpdx(p);+ let dq2 = dpdy(p);+ let across = length(fwidth(p)) * u_micro().z; // the tile's features per pixel+ let fade = 1.0 - smoothstep(u_fade().x, u_fade().y, across);+@if(SKIN_MASK)+ let strength = skin_stored(textureSample(tex_mask, samp_mask, in.uv).rgb).r;+@else+ let strength = 1.0;+@if(SKIN_DETAIL)+ let dtex = skin_stored(textureSample(tex_detail, samp_detail, in.uv).rgb) * 2.0 - 1.0;+ // (the shader's textures share one sampler, which clamps: the tile wraps by fract, its mip level kept from the+ // unwrapped coordinates' derivatives, so no seam line where it wraps)+@if(SKIN_MICRO)+ let mtex = skin_stored(textureSampleGrad(tex_micro, samp_micro, fract(p), dq1, dq2).rgb) * 2.0 - 1.0;+ var N = normalize((*pbr).N);+ // the directions in which u and v grow on the surface (Schuler, "Normal Mapping Without Precomputed Tangents"),+ // signed by the screen's handedness: his frame is GLSL's, whose y runs up the screen; WGSL's dpdy runs down, which+ // turned the old procedural pores inside out (dimples drawn as bumps) until the sign was taken from the derivatives+ let dp2perp = cross(dp2, N);+ let dp1perp = cross(N, dp1);+ let hand = select(-1.0, 1.0, dot(cross(dp1, dp2), N) >= 0.0);+ let T = (dp2perp * duv1.x + dp1perp * duv2.x) * hand;+ let B = (dp2perp * duv1.y + dp1perp * duv2.y) * hand;+ let Tu = T * inverseSqrt(max(dot(T, T), 1e-20));+ let Bu = B * inverseSqrt(max(dot(B, B), 1e-20));+@if(SKIN_DETAIL)+ {+ // the photo's surface detail (psx fit.py's skin_detail.png): a normal against this same frame+ N = normalize(u_detail() * (dtex.x * Tu + dtex.y * Bu) + dtex.z * N);+ }+@if(SKIN_MICRO)+ {+ // the skin's fine relief, from a photograph of real skin (psx skintile.py's skin_micro.png), tiled, by region,+ // and gone as it shrinks below a pixel; the skin a little rougher as it goes (the shine it broke up spreads)+ let k = u_micro().y * strength * fade;+ N = normalize(N + k * (mtex.x * Tu + mtex.y * Bu));+ (*pbr).material.perceptual_roughness = clamp((*pbr).material.perceptual_roughness + u_fade().z * (1.0 - fade) * strength, 0.0, 1.0);+ }+ (*pbr).N = N;+}++fn lit(in: VertexOutput, pbr: PbrInput, color: vec4<f32>) -> vec4<f32> {+ let Nd = normalize(pbr.N); // the fine relief's normal: blue's, and Bevy's own diffuse+ let Ns = normalize(pbr.world_normal); // the mesh's smooth one: red's mostly+ // how fast the surface curves, per metre (a centimetre's radius is 100), scaled: the nose, lips and ears scatter more+ let curve = clamp(length(fwidth(Ns)) / max(length(fwidth(pbr.world_position.xyz)), 1e-6) * u_curve(), 0.0, 1.0);+ let lights = &bevy_pbr::render::mesh_view_bindings::lights;+ let n = (*lights).n_directional_lights;+ if (n == 0u) { return color; }+ let base = pbr.material.base_color.rgb * (1.0 - pbr.material.metallic) * (1.0 - pbr.material.diffuse_transmission);+ let w = u_scatter() * mix(0.6, 1.6, curve);+ let Nr = normalize(mix(Nd, Ns, u_soft().x));+ let Ng = normalize(mix(Nd, Ns, u_soft().y));+ let Nb = normalize(mix(Nd, Ns, u_soft().z));+ let view_z = dot(vec4<f32>(view.view_from_world[0].z, view.view_from_world[1].z, view.view_from_world[2].z, view.view_from_world[3].z), pbr.world_position);+ var add = vec3<f32>(0.0);+ for (var i = 0u; i < n; i++) {+ let light = &(*lights).directional_lights[i];+ let L = (*light).direction_to_light.xyz;+ var shadow = 1.0;+ if (((*light).flags & bevy_pbr::render::mesh_view_types::DIRECTIONAL_LIGHT_FLAGS_SHADOWS_ENABLED_BIT) != 0u) {+ shadow = bevy_pbr::render::shadows::fetch_directional_shadow(i, pbr.world_position, Ns, view_z, pbr.frag_coord.xy);+ }+ let nl = vec3<f32>(dot(Nr, L), dot(Ng, L), dot(Nb, L));+ // the plain falloff plus a band of scattered light round the light's edge, w wide for each colour: smooth on both+ // sides (a wrap that ended where the shadow map took over drew a hard red line down the cheek), shorter into the+ // dark side than the lit, and no brighter where the face is fully lit+ let t = clamp(abs(nl) / max(w, vec3<f32>(1e-3)), vec3<f32>(0.0), vec3<f32>(1.0));+ let side = select(vec3<f32>(1.0), vec3<f32>(0.6), nl < vec3<f32>(0.0));+ let band = w * u_band() * (1.0 - t) * (1.0 - t) * side;+ let skin = max(nl, vec3<f32>(0.0)) + band;+ // a soft shadow's edge reaches further for red: the light that went in on the lit side comes out in the shade+ let sh = pow(vec3<f32>(shadow), u_shadow());+ let bevy = max(dot(Nd, L), 0.0) * shadow;+ add += base * (skin * sh - vec3<f32>(bevy)) * (*light).color.rgb;+ }+ // (Bevy's Burley diffuse is about 1/pi of the light; exposure as Bevy applies it)+ return vec4<f32>(color.rgb + max(add * (0.31830988 * view.exposure), vec3<f32>(-color.rgb)), color.a);+}+`;++/** the skin look's settings. micro: the fine relief tile (skin_micro.png) [repeats per UV unit (psx bodies: about 1.2 m+ * of face to a unit, so 46 is the tile's 25 mm), how far it tilts the normal, its features across the tile (for the+ * fade)]; detail: how strongly the photo's surface detail (skin_detail.png) tilts the normal (1 as baked); fade: [the+ * relief's features per pixel where it starts to fade, where it's gone, the roughness added as it goes]; scatter: how+ * far each of red, green and blue wraps past the light's edge; soft: how much of the mesh's smooth normal each of red,+ * green and blue is shaded from (1 all, 0 the fine relief's); shadow: each colour's falloff into a soft shadow's edge+ * (below 1 reaches further); curve: how much the surface's curvature (per metre) widens the scatter */+export interface SkinLook { micro: [number, number, number]; detail: number; fade: [number, number, number]; scatter: [number, number, number]; band: number; soft: [number, number, number]; shadow: [number, number, number]; curve: number }+export const SKIN_LOOK: SkinLook = { micro: [46, 0.5, 40], detail: 1, fade: [0.2, 0.55, 0.06], scatter: [0.35, 0.14, 0.07], band: 0.3, soft: [0.85, 0.45, 0.1], shadow: [0.8, 0.95, 1.0], curve: 0.008 };++/** the skin's material settings beside the shader: the second shine (clearcoat, smooth, over the fine relief's base layer),+ * the base layer's reflectance (skin's F0 about 0.028) */+export interface SkinSurface { clearcoat: number; clearcoatRoughness: number; reflectance: number }+export const SKIN_SURFACE: SkinSurface = { clearcoat: 0.15, clearcoatRoughness: 0.32, reflectance: 0.4 };diff --git a/sdk/character/src/character/solve.ts b/sdk/character/src/character/solve.tsindex 243450a2..299c15b6 100644--- a/sdk/character/src/character/solve.ts+++ b/sdk/character/src/character/solve.ts@@ -1,6 +1,6 @@// The body's surface, reaching, planting, looking, sitting, and solving goals.import { type Vec3 } from "@raea/render/3d";-import { FINGERS, Finger, I, LIMB, Pose, Posed, Side, Skeleton, add, cross, fingerJoints, flatHand, held, joint, len, norm, palmAt, pose, qaxis, qfromTo, qmul, qrot, qyaw, scale3, setWorld, skinJoints, slerp, sub, twoBone, withFingers } from "./all";+import { B, FINGERS, Finger, I, LIMB, Pose, Posed, Side, Skeleton, add, cross, fingerJoints, flatHand, held, joint, len, norm, palmAt, pose, qaxis, qfromTo, qmul, qrot, qyaw, scale3, setWorld, skinJoints, slerp, sub, twoBone, withFingers } from "./all";export interface FingerSegment { joint: number; head: Vec3; tail: Vec3; radius: number }@@ -20,13 +20,13 @@ export function fingerSegments(skel: Skeleton, w: Posed, s: Side): { finger: Finexport interface SurfacePoint { part: string; side: Side | ""; joint: string; at: Vec3; normal: Vec3 }-/** The skin's surface samples posed (character.py's `surface`): each a vertex of the skinned mesh, where the skin puts it- * (the glb's own linear blend of its skin joints) and its normal. `parts` picks them by part ("palm", "thumb1",- * "index2", "chest", "waist", "foreArm"...) or by skin joint's name (a RegExp tests both); `side` by side. For hugging a+/** The skin's surface samples posed (skeleton.json's `surface`): each a vertex of the skinned mesh, where the skin puts+ * it (the glb's own linear blend of its joints) and its normal. `parts` picks them by part ("palm", "thumb1",+ * "index2", "chest", "waist", "foreArm"...) or by joint's name (a RegExp tests both); `side` by side. For hugging a* thing to the chest without it going in, keeping fingertips on a thing's surface. */export function surface(skel: Skeleton, w: Posed, parts?: RegExp | string[], side?: Side): SurfacePoint[] {- if (!skel.surface || !skel.skin) return [];- const sk = skel.skin, sj = skinJoints(skel, w);+ if (!skel.surface) return [];+ const sk = skel.joints, sj = skinJoints(skel, w);const want = (part: string, name: string) => !parts || (parts instanceof RegExp ? parts.test(part) || parts.test(name) : parts.includes(part) || parts.includes(name));const out: SurfacePoint[] = [];for (const x of skel.surface) {@@ -62,7 +62,7 @@ export function reach(skel: Skeleton, p: Pose, s: Side, g: HandGoal): Pose {if (g.point) p = flatHand(skel, p, s, g.point, g.facing);// a flat hand's middle half its thickness off the surface it rests on (about 1% of the body's height)if (g.point) g = { ...g, at: sub(g.at, scale3(norm(g.facing ?? [0, -1, 0]), 0.009 * skel.height)) };- const hi = joint(skel, s === "L" ? "LeftHand" : "RightHand");+ const hi = joint(skel, B.hand(s));// the wrist where the palm lands at the at, with the hand's turn as it will be (twoBone keeps it)let w = pose(skel, p);const off = sub(palmAt(skel, w, s), w.pos[hi]);@@ -87,8 +87,8 @@ export interface FootGoal {/** A foot planted: the leg bent so the ankle stands over `at` at its height at rest, the sole flat. */export function plant(skel: Skeleton, p: Pose, s: Side, g: FootGoal): Pose {- const fi = joint(skel, s === "L" ? "LeftFoot" : "RightFoot");- const ti = joint(skel, s === "L" ? "LeftToeBase" : "RightToeBase");+ const fi = joint(skel, B.foot(s));+ const ti = joint(skel, B.ball(s));const J = skel.joints;const ankle = J[fi].head[1];if (g.flat !== false) {@@ -104,10 +104,10 @@ export function plant(skel: Skeleton, p: Pose, s: Side, g: FootGoal): Pose {}/** The head (with the neck taking a share) turned so the eyes look at `target`. */-export function lookAt(skel: Skeleton, p: Pose, target: Vec3, share: [number, number, number] = [0.25, 0.25, 0.5]): Pose {- const chain = ["Neck", "Neck1", "Head"].map((n) => joint(skel, n));+export function lookAt(skel: Skeleton, p: Pose, target: Vec3, share: [number, number] = [0.5, 0.5]): Pose {+ const chain = [B.neck, B.head].map((n) => joint(skel, n));const eyesRest = skel.landmarks.eyes;- const head = chain[2];+ const head = chain[1];for (let k = 0; k < 4; k++) {const w0 = pose(skel, p);const eyes = add(w0.pos[head], qrot(w0.rot[head], sub(eyesRest, skel.joints[head].head)));@@ -116,7 +116,7 @@ export function lookAt(skel: Skeleton, p: Pose, target: Vec3, share: [number, nu// the turn taking the face's forward to the target, split up the neck (yaw about the body's up, then pitch)const turn = qfromTo(fwd, want);// each joint's share of the turn, about the same axis in the body's frame, so the shares add up to the whole- for (let c = 0; c < 3; c++) {+ for (let c = 0; c < chain.length; c++) {const w = pose(skel, p);p = setWorld(skel, p, w, chain[c], qmul(slerp(I, turn, share[c]), w.rot[chain[c]]));}@@ -142,17 +142,17 @@ export function sit(skel: Skeleton, p: Pose, g: SeatGoal): Pose {const hips = J[0].head;// the hip joints sit a little above the seat (the buttocks under them): their height over the lowest of the body at// the hips, from the rest's leg (about a fifth of the thigh)- const over = skel.landmarks.sitDrop ?? 0.3 * len(sub(J[joint(skel, "LeftLeg")].head, J[joint(skel, "LeftUpLeg")].head));- p = { ...p, root: [g.at[0], g.at[1] + over + (hips[1] - J[joint(skel, "LeftUpLeg")].head[1]), g.at[2]] };+ const over = skel.landmarks.sitDrop ?? 0.3 * len(sub(J[joint(skel, B.calf("L"))].head, J[joint(skel, B.thigh("L"))].head));+ p = { ...p, root: [g.at[0], g.at[1] + over + (hips[1] - J[joint(skel, B.thigh("L"))].head[1]), g.at[2]] };const lean = g.lean ?? 0.15;p = held(skel, {- LeftUpLeg: [0.08, -0.05, 1], RightUpLeg: [-0.08, -0.05, 1],- LowerBack: [0, 1, Math.tan(lean)], Spine: [0, 1, Math.tan(lean)], Spine1: [0, 1, Math.tan(lean)],+ [B.thigh("L")]: [0.08, -0.05, 1], [B.thigh("R")]: [-0.08, -0.05, 1],+ [B.spine[0]]: [0, 1, Math.tan(lean)], [B.spine[1]]: [0, 1, Math.tan(lean)], [B.spine[2]]: [0, 1, Math.tan(lean)],}, p);const floor = g.floor ?? 0;for (const s of ["L", "R"] as Side[]) {const w = pose(skel, p);- const knee = w.pos[joint(skel, s === "L" ? "LeftLeg" : "RightLeg")];+ const knee = w.pos[joint(skel, B.calf(s))];const at = g.feet?.[s] ?? [knee[0], floor, knee[2] + 0.05];p = plant(skel, p, s, { at, toes: [0, 0, 1] });}@@ -187,7 +187,7 @@ export function blend(a: Pose, b: Pose, w: number): Pose {export function leanToward(skel: Skeleton, p: Pose, hands: Partial<Record<Side, HandGoal>>, o: { reach?: number; most?: number } = {}): Pose {const goals = (Object.entries(hands) as [Side, HandGoal | undefined][]).filter((e): e is [Side, HandGoal] => !!e[1]);if (!goals.length) return p;- const chain = ["LowerBack", "Spine", "Spine1"].map((n) => joint(skel, n)), share = [0.25, 0.35, 0.4];+ const chain = [B.spine[0], B.spine[1], B.chest].map((n) => joint(skel, n)), share = [0.25, 0.35, 0.4];const J = skel.joints;const arm = (s: Side) => {const [a, b, c] = LIMB.arm(s).map((n) => joint(skel, n));diff --git a/sdk/character/src/clip.ts b/sdk/character/src/clip.tsindex eb1650c3..81c7d783 100644--- a/sdk/character/src/clip.ts+++ b/sdk/character/src/clip.ts@@ -1,10 +1,7 @@-// Motion clips for raea/character: BVH read, retargeted onto a character's skeleton, stored compactly and-// played back at any time (slerped between frames). CMU's motion capture (mocap.cs.cmu.edu, free for any use; cgspeed's-// BVH conversion) is on the same 31 joints as a character, and a character's skin is bound in CMU's T-pose, so a clip's-// turns play nearly as they are: each bone takes a small correction for what's left between the two rests (CMU's legs-// splayed, its spine straighter), and the hips' travel is scaled by the legs' length.+// Motion clips for raea/character: BVH read, retargeted onto a character's skeleton (retarget.ts), stored compactly+// and played back at any time (slerped between frames).import { fromBase64, toBase64 } from "@raea/video/codecs";-import { captured, joint, pose, qaxis, qfromTo, qinv, qmul, qnorm, slerp, sub, type Pose, type Quat, type Skeleton } from "raea/character";+import { captured, qnorm, slerp, type Pose, type Quat, type Skeleton } from "raea/character";import type { Vec3 } from "raea/3d";export interface Bvh {@@ -67,160 +64,12 @@ export interface Clip {/** the neck's and head's mean turns the retarget took out (its actor's carriage), for retargeting the actor's other* clips about the same */carriage?: Record<string, Quat>;+ /** the body's hip height over the capture's actor's (the retarget scaled the travel by it): what the cadence is+ * scaled by in play, as Froude's dynamic similarity has it (matching/perform.ts) */+ scale?: number;}-/** A BVH frame's turns (from its rest, relative to the parent) and its root's place, in BVH units. */-function bvhFrame(b: Bvh, values: number[]): { root: Vec3; turns: Quat[] } {- const DEG = Math.PI / 180;- let c = 0;- let root: Vec3 = [0, 0, 0];- const turns = b.joints.map((j) => {- let q: Quat = [0, 0, 0, 1];- for (const ch of j.channels) {- const v = values[c++];- if (ch === "Xposition") root = [v, root[1], root[2]];- else if (ch === "Yposition") root = [root[0], v, root[2]];- else if (ch === "Zposition") root = [root[0], root[1], v];- // the channels in their order, each about the frame the ones before left (R = R1·R2·R3)- else q = qmul(q, qaxis(ch[0] === "X" ? [1, 0, 0] : ch[0] === "Y" ? [0, 1, 0] : [0, 0, 1], v * DEG));- }- return q;- });- return { root, turns };-}--/** the child whose head a joint's bone points at (a joint with several follows its main line) */-const MAIN: Record<string, string> = { Hips: "LowerBack", Spine1: "Neck", LeftHand: "LeftFingerBase", RightHand: "RightFingerBase" };-/** the bones that branch off a parent's pivot to a joint beside the chain: the hip joints and the shoulders */-const BRANCH = /^([LR]HipJoint|(Left|Right)Shoulder)$/;-/** the body's axis: the back, neck and head */-const AXIS = /^(LowerBack|Spine1?|Neck1?|Head)$/;-/** the neck and head, held about the clip's mean */-const CARRIAGE = /^(Neck1?|Head)$/;--/** A BVH retargeted onto a skeleton, resampled to `fps`, from `from` to `to` seconds. Its joints are found by the- * skeleton's names, or by `map` (the skeleton's name to the BVH's; a joint left out of a map, or missing from the BVH,- * holds still against its parent: fingers a BVH hasn't). `carriage`: the neck and head move about this (a clip's- * `carriage` from the same actor) rather than the clip's own average. The BVH's up is y and its subject faces +z at rest (cgspeed's- * CMU files and 100STYLE's do); its units are scaled by the legs. */-export function retarget(skel: Skeleton, b: Bvh, o: { name: string; fps?: number; from?: number; to?: number; map?: Record<string, string>; carriage?: Record<string, Quat> }): Clip {- const fps = o.fps ?? 30;- // (the capture's joints: the fingers' own come after them and no BVH turns them)- const J = skel.joints.slice(0, captured(skel));- // cgspeed's files call the fingers' joint HandIndex1- const alias = (n: string) => n.replace("HandFinger1", "HandIndex1");- const src = J.map((j) => {- if (o.map) return o.map[j.name] ? b.joints.findIndex((x) => x.name === o.map![j.name]) : -1;- const i = b.joints.findIndex((x) => x.name === j.name || x.name === alias(j.name));- if (i < 0) throw new Error(`retarget ${o.name}: the BVH has no joint ${j.name}`);- return i;- });- if (src[0] < 0) throw new Error(`retarget ${o.name}: the BVH has no joint for the root ${J[0].name}`);- if (o.map) for (const [t, n] of Object.entries(o.map)) if (!b.joints.some((x) => x.name === n)) throw new Error(`retarget ${o.name}: the map sends ${t} to ${n}, which the BVH hasn't`);- // the BVH's joints at rest, in the world (its rest frames are the world's)- const restAt: Vec3[] = [];- b.joints.forEach((j, i) => { restAt[i] = j.parent < 0 ? [0, 0, 0] : [restAt[j.parent][0] + j.offset[0], restAt[j.parent][1] + j.offset[1], restAt[j.parent][2] + j.offset[2]]; });- // each bone at rest in both: towards its main child's head, looking past children at the same place (cgspeed's- // hand, its finger base and its thumb are all at the wrist), or its end site- const bone = (i: number) => {- const child = (j: number) => (MAIN[J[j].name] ? joint(skel, MAIN[J[j].name]) : J.findIndex((x) => x.parent === j));- let c = child(i), s: Vec3 | undefined;- for (let j = i; ; ) {- const cj = child(j);- if (cj < 0) { s = b.joints[src[i]].end; break; }- if (src[cj] >= 0) {- const d = sub(restAt[src[cj]], restAt[src[i]]);- if (Math.hypot(...d) > 1e-6) { s = d; break; }- }- j = cj;- }- const t = c >= 0 ? sub(J[c].head, J[i].head) : sub(J[i].tail, J[i].head);- if (Math.hypot(...t) < 1e-6) c = -1;- return { s, t: c >= 0 ? t : sub(J[i].tail, J[i].head) };- };- // the correction a joint's turn takes so the target's bone lies along the source's: both stand in a T-pose at rest,- // but CMU's legs are splayed. Small, so a shortest turn keeps each bone's roll (bound in Anny's A-pose the arms took- // 48-degree corrections that twisted them and broke the shoulders). Not for the root, nor the back, neck and head:- // CMU's are a straight stick leaning back, and laid along it Anny's spine lost its curve and her neck, 20 degrees- // forward at rest, walked 9 back, the head pushed back over it and the chin into the throat. They keep Anny's build- // and take the capture's turns from rest as they are. Nor the bones that branch off a parent's pivot to a joint- // beside it (the hip joints off the pelvis, the shoulders off the chest): those differ in build, and turning them- // moves the joint they lead to (corrected, Anny's hip joints went 6 cm down and forward and the whole body rode- // up). Those take their parent's correction, so they turn with it as the body is built- const fix: Quat[] = [];- J.forEach((j, i) => {- if (i === 0 || AXIS.test(j.name)) fix[i] = [0, 0, 0, 1];- else if (BRANCH.test(j.name) || src[i] < 0) fix[i] = fix[j.parent];- else {- const { s, t } = bone(i);- fix[i] = s && Math.hypot(...s) > 1e-6 && Math.hypot(...t) > 1e-6 ? qfromTo(t, s) : [0, 0, 0, 1];- }- });- // the legs' length in both, for the hips' travel- const legOf = (pts: (n: string) => Vec3) => Math.hypot(...sub(pts("LeftUpLeg"), pts("LeftLeg"))) + Math.hypot(...sub(pts("LeftLeg"), pts("LeftFoot")));- const k = legOf((n) => J[joint(skel, n)].head) / legOf((n) => restAt[src[joint(skel, n)]]);- const dur = (b.frames.length - 1) * b.frameTime;- // (cgspeed's files open on a T-pose frame: left out)- const t0 = Math.max(b.frameTime, o.from ?? 0), t1 = Math.min(dur, o.to ?? dur);- const n = Math.max(1, Math.floor((t1 - t0) * fps) + 1);- const root = new Float32Array(n * 3), turns = new Float32Array(n * J.length * 4);- for (let f = 0; f < n; f++) {- const at = (t0 + f / fps) / b.frameTime;- const a = Math.min(b.frames.length - 1, Math.floor(at)), c = Math.min(b.frames.length - 1, a + 1), u = at - a;- const A = bvhFrame(b, b.frames[a]), B = bvhFrame(b, b.frames[c]);- // the source's world turns, then the target's: G_t = G_s · fix, and its turn relative to the parent's G_t- const gs: Quat[] = [], gt: Quat[] = [];- b.joints.forEach((j, i) => {- const q = slerp(A.turns[i], B.turns[i], u);- gs[i] = j.parent < 0 ? q : qmul(gs[j.parent], q);- });- for (let i = 0; i < J.length; i++) {- const p = J[i].parent;- // a joint the BVH hasn't holds still against its parent- gt[i] = src[i] >= 0 ? qnorm(qmul(gs[src[i]], fix[i])) : p < 0 ? [0, 0, 0, 1] : gt[p];- const l = p < 0 ? gt[i] : qmul(qinv(gt[p]), gt[i]);- turns.set(l, (f * J.length + i) * 4);- }- const r: Vec3 = [(A.root[0] + (B.root[0] - A.root[0]) * u) * k, (A.root[1] + (B.root[1] - A.root[1]) * u) * k, (A.root[2] + (B.root[2] - A.root[2]) * u) * k];- root.set(r, f * 3);- }- // the neck and head carry themselves as Anny does, moving about it as the capture moves about its average: CMU's- // subjects hold the neck 10 degrees back and the head 16 down on a clip's mean, a chin pulled into the throat. The- // average is the clip's own, or `carriage` (another clip's, its actor at their most neutral) so a style's own- // carriage (an old man's hanging head) stays- const carriage: Record<string, Quat> = {};- for (let i = 0; i < J.length; i++) {- if (!CARRIAGE.test(J[i].name)) continue;- let mq = o.carriage?.[J[i].name];- if (!mq) {- const m = [0, 0, 0, 0];- for (let f = 0; f < n; f++) {- const o4 = (f * J.length + i) * 4, sgn = turns[o4 + 3] < 0 ? -1 : 1;- for (let a = 0; a < 4; a++) m[a] += sgn * turns[o4 + a];- }- mq = qnorm(m as Quat);- }- carriage[J[i].name] = mq;- const off = qinv(mq);- for (let f = 0; f < n; f++) {- const o4 = (f * J.length + i) * 4;- turns.set(qmul(off, Array.from(turns.subarray(o4, o4 + 4)) as Quat), o4);- }- }- // feet on the floor: the clip lifted so its lowest toe, over the clip, is at the toes' height at rest- const clip: Clip = { name: o.name, fps, frames: n, root, turns, carriage };- const toes = ["LeftToeBase", "RightToeBase"].map((x) => joint(skel, x));- let low = Infinity;- for (let f = 0; f < n; f++) {- const w = pose(skel, clipFrame(clip, f, J.length));- for (const t of toes) low = Math.min(low, w.pos[t][1]);- }- const lift = J[toes[0]].head[1] - low;- for (let f = 0; f < n; f++) root[f * 3 + 1] += lift;- return clip;-}--function clipFrame(c: Clip, f: number, nj: number): Pose {+export function clipFrame(c: Clip, f: number, nj: number): Pose {const turns: Quat[] = [];for (let i = 0; i < nj; i++) {const o = (f * nj + i) * 4;@@ -252,7 +101,7 @@ export function framePose(c: Clip, f: number): Pose {export interface ClipFile {skeleton: string;joints: string[];- clips: { name: string; fps: number; frames: number; root: string; turns: string }[];+ clips: { name: string; fps: number; frames: number; root: string; turns: string; scale?: number }[];}export function writeClips(skel: Skeleton, clips: Clip[]): ClipFile {@@ -262,7 +111,7 @@ export function writeClips(skel: Skeleton, clips: Clip[]): ClipFile {clips: clips.map((c) => {const q = new Int16Array(c.turns.length);for (let i = 0; i < q.length; i++) q[i] = Math.round(Math.max(-1, Math.min(1, c.turns[i])) * 32767);- return { name: c.name, fps: c.fps, frames: c.frames, root: toBase64(new Uint8Array(c.root.buffer.slice(0))), turns: toBase64(new Uint8Array(q.buffer)) };+ return { name: c.name, fps: c.fps, frames: c.frames, root: toBase64(new Uint8Array(c.root.buffer.slice(0))), turns: toBase64(new Uint8Array(q.buffer)), ...(c.scale ? { scale: Math.round(c.scale * 1e4) / 1e4 } : {}) };}),};}@@ -282,10 +131,10 @@ export function readClips(file: ClipFile): Map<string, Clip> {const v = qnorm([q[i] / 32767, q[i + 1] / 32767, q[i + 2] / 32767, q[i + 3] / 32767]);turns.set(v, i);}- m.set(c.name, { name: c.name, fps: c.fps, frames: c.frames, root, turns });+ m.set(c.name, { name: c.name, fps: c.fps, frames: c.frames, root, turns, ...(c.scale ? { scale: c.scale } : {}) });}decoded.set(file, m);return m;}-+export { retarget, retargetIK, SHRUG, type RetargetOptions } from "./retarget";diff --git a/sdk/character/src/clips/build.ts b/sdk/character/src/clips/build.tsindex 615e438d..29b3f81a 100644--- a/sdk/character/src/clips/build.ts+++ b/sdk/character/src/clips/build.ts@@ -1,6 +1,6 @@// Building a database from clips.import { framePose, type Clip } from "../clip";-import { bodyScale, joint, pose, qrot, qyaw, type Skeleton } from "raea/character";+import { B, SIDES, bodyScale, joint, pose, qrot, qyaw, type Skeleton } from "raea/character";import { FEATURE_COUNT as NF, STATE_COUNT as NS, libraryRows, levelClip, swingClear } from "../matching";import { DbClip, FLAG, FS, HLEVELS, HSTEP, HW, MF_SIGN, MF_SRC, MS_SIGN, MS_SRC, QF, SS, TAGS, TAG_INDEX, Tag, hdcEncode, q16, tagsOf, writeDb } from "./all";@@ -13,7 +13,7 @@ export function buildDb(skel: Skeleton, clips: Iterable<BuildClip>, log: (s: strconst C = NF + 5 + NS, metas: DbClip[] = [], rowParts: Float32Array[] = [], hipParts: Uint16Array[] = [], spdParts: Uint16Array[] = [], movParts: Uint8Array[] = [], crParts: Uint8Array[] = [], rootParts: Float32Array[] = [];let n0 = 0, fps = 0;const t0 = performance.now();- const handJ = ["LeftHand", "RightHand"].map((x) => joint(skel, x)), handParts: Int16Array[] = [], clearParts: Int16Array[] = [];+ const handJ = SIDES.map(B.hand).map((x) => joint(skel, x)), handParts: Int16Array[] = [], clearParts: Int16Array[] = [];for (const b of clips) {const c = levelClip(skel, b.clip);if (!fps) fps = c.fps;@@ -83,7 +83,7 @@ export function buildDb(skel: Skeleton, clips: Iterable<BuildClip>, log: (s: strfor (let i = 0; i < NS; i++) S[k * SS + i] = q16((raw[k * C + NF + 5 + i] - stateMean[i]) / stateSd[i]);G[k * 3] = raw[k * C + NF]; G[k * 3 + 1] = raw[k * C + NF + 1]; G[k * 3 + 2] = raw[k * C + NF + 2];}- const ankleRest = skel.joints.find((j) => j.name === "LeftFoot")!.head[1], restHips = skel.joints[0].head[1], hz = bodyScale(skel);+ const ankleRest = skel.joints.find((j) => j.name === B.foot("L"))!.head[1], restHips = skel.joints[0].head[1], hz = bodyScale(skel);const hipY = new Float32Array(n0);{ let a = 0; for (const b of rootParts) { hipY.set(b, a); a += b.length; } }const clipBits = metas.map((mt) => { const b: [number, number] = [0, 0]; for (const t of mt.tags) { const i = TAG_INDEX.get(t)!; b[i >> 5] |= 1 << (i & 31); } return b; });diff --git a/sdk/character/src/course.ts b/sdk/character/src/course.tsindex 18941f7f..73d23535 100644--- a/sdk/character/src/course.ts+++ b/sdk/character/src/course.ts@@ -34,7 +34,7 @@// (not the capture's own moves, nor a pick-up's squat or a throw)// unfinished the course not run to its endimport type { Vec3 } from "raea/3d";-import { add, bodyScale, joint, palmAt, pose, qrot, type Pose, type Skeleton } from "raea/character";+import { B, add, bodyScale, joint, palmAt, pose, qrot, type Pose, type Skeleton } from "raea/character";import { interact, planItems, type Interaction, type Item, type ItemClip, type ItemPlan, type ItemTask, type PickManner, type ThrowStyle } from "./items";import { motionLint } from "./lint";import type { ActionFit, MotionLibrary, Performance } from "./matching";@@ -206,11 +206,11 @@ export interface CourseCheck {/** the body as capsules: bones (joint to joint) with a radius, as a share of the body's height (a child's build) */const CAPSULES: [string, string, number][] = [- ["Hips", "Spine1", 0.075], ["Spine1", "Neck", 0.07], ["Neck", "Head", 0.035],- ["LeftUpLeg", "LeftLeg", 0.045], ["LeftLeg", "LeftFoot", 0.034], ["LeftFoot", "LeftToeBase", 0.014],- ["RightUpLeg", "RightLeg", 0.045], ["RightLeg", "RightFoot", 0.034], ["RightFoot", "RightToeBase", 0.014],- ["LeftArm", "LeftForeArm", 0.028], ["LeftForeArm", "LeftHand", 0.024],- ["RightArm", "RightForeArm", 0.028], ["RightForeArm", "RightHand", 0.024],+ [B.pelvis, B.chest, 0.075], [B.chest, B.neck, 0.07], [B.neck, B.head, 0.035],+ [B.thigh("L"), B.calf("L"), 0.045], [B.calf("L"), B.foot("L"), 0.034], [B.foot("L"), B.ball("L"), 0.014],+ [B.thigh("R"), B.calf("R"), 0.045], [B.calf("R"), B.foot("R"), 0.034], [B.foot("R"), B.ball("R"), 0.014],+ [B.upperarm("L"), B.lowerarm("L"), 0.028], [B.lowerarm("L"), B.hand("L"), 0.024],+ [B.upperarm("R"), B.lowerarm("R"), 0.028], [B.lowerarm("R"), B.hand("R"), 0.024],];/** the head as a ball over the Head joint (its middle a share of the height above, its radius) */const HEAD = { up: 0.06, r: 0.07 };@@ -234,9 +234,9 @@ export function checkCourse(skel: Skeleton, course: Course, perf: Performance, lconst poseAt = (f: number): Pose => (live ? live.pose(f) : perf.pose(f));const J = (s: string) => joint(skel, s);const caps = CAPSULES.map(([a, b, r]) => ({ a: J(a), b: J(b), r: r * h, name: `${a}-${b}` }));- const head = J("Head");+ const head = J(B.head);const feet = (["L", "R"] as const).map((s) => {- const a = J(s === "L" ? "LeftFoot" : "RightFoot"), t = J(s === "L" ? "LeftToeBase" : "RightToeBase");+ const a = J(B.foot(s)), t = J(B.ball(s));// (the toes' tip, past the ball the skeleton ends at: a foot pushing off stands on it, its ball a few cm up)const jt = skel.joints[t], d = [0, 1, 2].map((k) => jt.tail[k] - jt.head[k]), dl = Math.hypot(...d) || 1;const tip = d.map((v) => (v / dl) * TOE * h) as Vec3;diff --git a/sdk/character/src/effects.ts b/sdk/character/src/effects.tsindex 202a8fb7..2f453a62 100644--- a/sdk/character/src/effects.ts+++ b/sdk/character/src/effects.ts@@ -17,7 +17,7 @@// log: postures add (weighted), gains and rates multiply (as powers), so half of one and half of another is a body// between them, and a weight of 0 is the motion as it was.import type { Vec3 } from "raea/3d";-import { captured, joint, pose, qinv, qmul, qnorm, qrot, qyaw, type Pose, type Quat, type Skeleton } from "raea/character";+import { B, mirrorName, captured, joint, pose, qinv, qmul, qnorm, qrot, qyaw, type Pose, type Quat, type Skeleton } from "raea/character";import { framePose, type Clip } from "./clip";import { styleMean } from "./style";@@ -49,7 +49,7 @@ export function qexp(v: Vec3): Quat {const feetOf = new WeakMap<Skeleton, number[]>();const FEET = (skel: Skeleton) => {let f = feetOf.get(skel);- if (!f) feetOf.set(skel, (f = ["LeftFoot", "RightFoot", "LeftToeBase", "RightToeBase"].map((n) => joint(skel, n))));+ if (!f) feetOf.set(skel, (f = B.feet().map((n) => joint(skel, n))));return f;};@@ -125,9 +125,9 @@ export function learnEffect(skel: Skeleton, neutral: Clip, styled: Clip, o: { n?// each arm's swing, calibrated: the joints' gains don't come out as the hand's swing (a posture that rolls the trunk// or turns the arm changes how much of a joint's swing is the hand's, fore and aft), so neutral with the effect is// measured and each arm's gains scaled until its hand swings as the style's does (a limp's arms swing unevenly)- const arms = [["LeftShoulder", "LeftArm", "LeftForeArm", "LeftHand"], ["RightShoulder", "RightArm", "RightForeArm", "RightHand"]].map((s) => s.map((n) => joint(skel, n)));+ const arms = [[B.clavicle("L"), B.upperarm("L"), B.lowerarm("L"), B.hand("L")], [B.clavicle("R"), B.upperarm("R"), B.lowerarm("R"), B.hand("R")]].map((s) => s.map((n) => joint(skel, n)));// and likewise the hips' and thighs' gains for the feet's sway under the hips (which their gains overshoot)- const legs = ["Hips", "LeftUpLeg", "RightUpLeg"].map((n) => joint(skel, n)).filter((i) => i >= 0);+ const legs = [B.pelvis, B.thigh("L"), B.thigh("R")].map((n) => joint(skel, n)).filter((i) => i >= 0);const want = [vs.armSwingL, vs.armSwingR], m1 = Math.min(n1, n0 + 30 * neutral.fps);for (let it = 0; it < 3; it++) {const got = styleMean(skel, mapped(skel, neutral, n0, m1, (p) => applyEffect(skel, p, e, { base: mn })));@@ -186,7 +186,7 @@ export function applyEffect(skel: Skeleton, p: Pose, e: RigEffect, o: { base: Clreturn { root: [p.root[0], p.root[1] + low(p) - low(out), p.root[2]], turns };}-const SWAP = (n: string) => n.startsWith("Left") ? "Right" + n.slice(4) : n.startsWith("Right") ? "Left" + n.slice(5) : /^L[A-Z]/.test(n) ? "R" + n.slice(1) : /^R[A-Z]/.test(n) ? "L" + n.slice(1) : n;+const SWAP = mirrorName;/** An effect seen in a mirror: left and right swapped (a limp on the left one on the right), for mirrored motion. */export function mirrorEffect(skel: Skeleton, e: RigEffect): RigEffect {diff --git a/sdk/character/src/feet.ts b/sdk/character/src/feet.tsindex cdb191b0..7cbbe2a0 100644--- a/sdk/character/src/feet.ts+++ b/sdk/character/src/feet.ts@@ -10,12 +10,12 @@// footDrift measures any performance: how far each standing foot's pivot slides (cm per contact, and its speed) and how// fast the knees bend while the feet stand (a buckle), so planting can be judged by numbers rather than by eye.import type { Vec3 } from "raea/3d";-import { bodyScale, joint, pose, qaxis, qinv, qmul, qnorm, qrot, twoBone, type Pose, type Quat, type Skeleton } from "raea/character";+import { B, bodyScale, joint, pose, qaxis, qinv, qmul, qnorm, qrot, twoBone, type Pose, type Quat, type Skeleton } from "raea/character";import { qlog } from "./effects";-const SIDES = [["LeftUpLeg", "LeftLeg", "LeftFoot", "LeftToeBase"], ["RightUpLeg", "RightLeg", "RightFoot", "RightToeBase"]] as const;+export const LEGS = [[B.thigh("L"), B.calf("L"), B.foot("L"), B.ball("L")], [B.thigh("R"), B.calf("R"), B.foot("R"), B.ball("R")]] as const;-interface FootFrame {+export interface FootFrame {hip: Vec3;ankle: Vec3;ball: Vec3;@@ -23,9 +23,9 @@ interface FootFrame {}/** each frame's feet, posed */-function feetOf(skel: Skeleton, p: Pose): FootFrame[] {+export function feetOf(skel: Skeleton, p: Pose): FootFrame[] {const w = pose(skel, p);- return SIDES.map((names) => {+ return LEGS.map((names) => {const [h, , a, b] = names.map((n) => joint(skel, n));return { hip: w.pos[h], ankle: w.pos[a], ball: w.pos[b], rot: w.rot[a] };});@@ -33,13 +33,13 @@ function feetOf(skel: Skeleton, p: Pose): FootFrame[] {/** the floor heights of a standing ankle and ball (the skeleton's at rest, standing on the floor), and the body's size* (`z`, bodyScale: the centimetres and speeds here were set on a child) */-function rests(skel: Skeleton): { ankle: number; ball: number; leg: number[]; z: number } {+export function rests(skel: Skeleton): { ankle: number; ball: number; leg: number[]; z: number } {const J = skel.joints;- const leg = SIDES.map((names) => {+ const leg = LEGS.map((names) => {const [h, k, a] = names.map((n) => J[joint(skel, n)].head);return Math.hypot(k[0] - h[0], k[1] - h[1], k[2] - h[2]) + Math.hypot(a[0] - k[0], a[1] - k[1], a[2] - k[2]);});- return { ankle: J[joint(skel, "LeftFoot")].head[1], ball: J[joint(skel, "LeftToeBase")].head[1], leg, z: bodyScale(skel) };+ return { ankle: J[joint(skel, B.foot("L"))].head[1], ball: J[joint(skel, B.ball("L"))].head[1], leg, z: bodyScale(skel) };}/** Which frames each foot stands: low (ankle within 3 cm of its standing height, or the ball within 1.2 cm: a child's swing@@ -112,7 +112,7 @@ export function plantFeet(skel: Skeleton, raw: Pose[], hint?: [number, number][]let feet = raw.map((p) => feetOf(skel, p));const stand = standing(skel, feet, hint, fps, raw.map((p) => p.root));// the knee's bend (degrees) a leg needs to span `d` from hip to ankle- const bones = SIDES.map((nm) => { const [h, k, a] = nm.map((x) => skel.joints[joint(skel, x)].head); return [Math.hypot(k[0] - h[0], k[1] - h[1], k[2] - h[2]), Math.hypot(a[0] - k[0], a[1] - k[1], a[2] - k[2])]; });+ const bones = LEGS.map((nm) => { const [h, k, a] = nm.map((x) => skel.joints[joint(skel, x)].head); return [Math.hypot(k[0] - h[0], k[1] - h[1], k[2] - h[2]), Math.hypot(a[0] - k[0], a[1] - k[1], a[2] - k[2])]; });const bendFor = (s: number, d: number) => { const [la, lb] = bones[s], c = (la * la + lb * lb - d * d) / (2 * la * lb); return 180 - (Math.acos(Math.max(-1, Math.min(1, c))) * 180) / Math.PI; };// each foot's ankle target where it is held (null where it swings free), and the offset it carries into a swingconst target: (Vec3 | null)[][] = [[], []], stepping: boolean[][] = [[], []];@@ -257,7 +257,7 @@ export function plantFeet(skel: Skeleton, raw: Pose[], hint?: [number, number][]// lifts, the ball stays put), as a trailing leg does at the end of a long step: the heel's turn (about the ball's// across axis, level and square to the foot) that brings the ankle into reach, 0.8 at mostconst rollFor = (s: number, q: Pose, tg: Vec3): { th: number; ax: Vec3; lifted: (th: number) => Vec3; out: boolean } => {- const [hi, , ai, bi] = SIDES[s].map((nm) => joint(skel, nm));+ const [hi, , ai, bi] = LEGS[s].map((nm) => joint(skel, nm));const w = pose(skel, q), hip = w.pos[hi], own = Math.hypot(...[0, 1, 2].map((i) => w.pos[ai][i] - hip[i]) as [number, number, number]);const L = Math.min(0.9995 * r.leg[s], Math.max(0.995 * r.leg[s], own));const reachOf = (a: Vec3) => Math.hypot(a[0] - hip[0], a[1] - hip[1], a[2] - hip[2]);@@ -277,8 +277,11 @@ export function plantFeet(skel: Skeleton, raw: Pose[], hint?: [number, number][]for (let s = 0; s < 2; s++) {let tg = target[s][t];if (!tg) continue;- const legs = [SIDES[s][0], SIDES[s][1], SIDES[s][2]];- const [hi, , ai, bi] = SIDES[s].map((nm) => joint(skel, nm));+ const legs = [LEGS[s][0], LEGS[s][1], LEGS[s][2]];+ const [hi, , ai, bi] = LEGS[s].map((nm) => joint(skel, nm));+ // the knee's way (psx trials, docs/skeleton.feature SK4): the clip's own knee off the hip-ankle line, a little+ // toward the toes and never behind them, so a leg near straight never flips its knee or bends it backwards+ const pole = kneePole(skel, p, s);const roll = (ax: Vec3, th: number) => {const w2 = pose(skel, q), shin = skel.joints[ai].parent;const turns = q.turns.slice();@@ -294,7 +297,7 @@ export function plantFeet(skel: Skeleton, raw: Pose[], hint?: [number, number][]if (log) log.lift[s][t] = Math.abs(th);const was = tg;tg = lifted(th);- q = twoBone(skel, q, legs, tg, undefined, { keep: true });+ q = twoBone(skel, q, legs, tg, pole, { keep: true });roll(ax, th);// the ankle's move with it too, so letting go doesn't drop the heel back in a framelastRoll[s] = { ax, th, d: [tg[0] - was[0], tg[1] - was[1], tg[2] - was[2]] };@@ -310,7 +313,7 @@ export function plantFeet(skel: Skeleton, raw: Pose[], hint?: [number, number][]const k = !stand[s][t] && g ? (() => { const u = Math.min(1, (t - g.at) / g.len); return 1 - u * u * (3 - 2 * u); })() : 0;if (g && k > 1e-3) tg = [tg[0] + g.d[0] * k, tg[1] + g.d[1] * k, tg[2] + g.d[2] * k];const base = q, own = pose(skel, p).pos[ai], clipBend = kneeOf(skel, p, s);- q = twoBone(skel, base, legs, tg, undefined, { keep: true });+ q = twoBone(skel, base, legs, tg, pole, { keep: true });// never a buckle: a knee bent more than 12° past the clip's own lets the foot give toward the clip's, just enough// (never down: the clip's foot can be through the floor)// (not in a quick step: a foot lifted to step folds the knee, as it should)@@ -318,10 +321,10 @@ export function plantFeet(skel: Skeleton, raw: Pose[], hint?: [number, number][]let lo = 0, hi3 = 1;for (let it = 0; it < 8; it++) {const m = (lo + hi3) / 2, t2: Vec3 = [tg[0] + (own[0] - tg[0]) * m, tg[1] + Math.max(0, own[1] - tg[1]) * m, tg[2] + (own[2] - tg[2]) * m];- if (kneeOf(skel, twoBone(skel, base, legs, t2, undefined, { keep: true }), s) - clipBend > 12) lo = m; else hi3 = m;+ if (kneeOf(skel, twoBone(skel, base, legs, t2, pole, { keep: true }), s) - clipBend > 12) lo = m; else hi3 = m;}tg = [tg[0] + (own[0] - tg[0]) * hi3, tg[1] + Math.max(0, own[1] - tg[1]) * hi3, tg[2] + (own[2] - tg[2]) * hi3];- q = twoBone(skel, base, legs, tg, undefined, { keep: true });+ q = twoBone(skel, base, legs, tg, pole, { keep: true });}if (g && k > 1e-3) roll(g.ax, g.th * k);else if (g && !stand[s][t]) rollGo[s] = null;@@ -331,7 +334,7 @@ export function plantFeet(skel: Skeleton, raw: Pose[], hint?: [number, number][]// a leg's turns smoothed where planting made them change speed more suddenly than the clip's, by 2°/f² (twice, a// quarter, a half, a quarter): a lock, a roll or the knee guard giving way turned a knee or hip in a framefor (let s = 0; s < 2; s++) {- const js = [SIDES[s][0], SIDES[s][1], SIDES[s][2]].map((nm) => joint(skel, nm)), ai = js[2], bi = joint(skel, SIDES[s][3]);+ const js = [LEGS[s][0], LEGS[s][1], LEGS[s][2]].map((nm) => joint(skel, nm)), ai = js[2], bi = joint(skel, LEGS[s][3]);const jerk = (P: Pose[], t: number, j: number) => {const v1 = qlog(qmul(qinv(P[t - 1].turns[j]), P[t].turns[j])), v2 = qlog(qmul(qinv(P[t].turns[j]), P[t + 1].turns[j]));return (Math.hypot(v2[0] - v1[0], v2[1] - v1[1], v2[2] - v1[2]) * 180) / Math.PI;@@ -378,7 +381,7 @@ export function footDrift(skel: Skeleton, poseAt: (f: number) => Pose, frames: nfor (let f = 0; f < frames; f++) {const p = poseAt(f), w = pose(skel, p);feet.push(feetOf(skel, p));- knees.push(SIDES.map((names) => {+ knees.push(LEGS.map((names) => {const [h, k, a] = names.map((x) => w.pos[joint(skel, x)]);const u = [h[0] - k[0], h[1] - k[1], h[2] - k[2]], v = [a[0] - k[0], a[1] - k[1], a[2] - k[2]];return (Math.acos(Math.max(-1, Math.min(1, (u[0] * v[0] + u[1] * v[1] + u[2] * v[2]) / Math.hypot(...u) / Math.hypot(...v)))) * 180) / Math.PI;@@ -424,5 +427,20 @@ export function footDrift(skel: Skeleton, poseAt: (f: number) => Pose, frames: nconst norm3 = (v: Vec3): Vec3 => { const l = Math.hypot(v[0], v[1], v[2]) || 1; return [v[0] / l, v[1] / l, v[2] / l]; };const rotAbout = (axis: Vec3, th: number, v: Vec3): Vec3 => qrot(qaxis(axis, th), v);+/** Which way a leg's knee points for two-bone IK: the clip's knee off its hip-ankle line, plus 0.05 of the toes' way+ * (level), with any part pointing behind the toes taken out (psx's knees: 0 flips, 0 bent backwards). */+export function kneePole(skel: Skeleton, p: Pose, s: number): Vec3 {+ const [hi, ki, ai, bi] = LEGS[s].map((nm) => joint(skel, nm)), w = pose(skel, p);+ const hip = w.pos[hi], knee = w.pos[ki], ankle = w.pos[ai];+ const d = [ankle[0] - hip[0], ankle[1] - hip[1], ankle[2] - hip[2]], dl = Math.hypot(d[0], d[1], d[2]) || 1, n = d.map((x) => x / dl);+ const kv = [knee[0] - hip[0], knee[1] - hip[1], knee[2] - hip[2]], kd = kv[0] * n[0] + kv[1] * n[1] + kv[2] * n[2];+ let off: Vec3 = [kv[0] - n[0] * kd, kv[1] - n[1] * kd, kv[2] - n[2] * kd];+ const J = skel.joints, rd = [J[bi].head[0] - J[ai].head[0], 0, J[bi].head[2] - J[ai].head[2]] as Vec3;+ const tw = qrot(w.rot[ai], rd), tl = Math.hypot(tw[0], tw[2]) || 1, toes: Vec3 = [tw[0] / tl, 0, tw[2] / tl];+ const back = off[0] * toes[0] + off[2] * toes[2];+ if (back < 0) off = [off[0] - toes[0] * back, off[1], off[2] - toes[2] * back];+ return [off[0] + 0.05 * toes[0], off[1], off[2] + 0.05 * toes[2]];+}+/** a knee's bend, degrees: the shin's turn at the knee (at rest the leg is straight) */-const kneeOf = (skel: Skeleton, p: Pose, s: number) => { const q = p.turns[joint(skel, SIDES[s][1])], w = Math.min(1, Math.abs(q[3])); return (2 * Math.acos(w) * 180) / Math.PI; };+const kneeOf = (skel: Skeleton, p: Pose, s: number) => { const q = p.turns[joint(skel, LEGS[s][1])], w = Math.min(1, Math.abs(q[3])); return (2 * Math.acos(w) * 180) / Math.PI; };diff --git a/sdk/character/src/items/all.ts b/sdk/character/src/items/all.tsindex 73fe504b..b143c78d 100644--- a/sdk/character/src/items/all.ts+++ b/sdk/character/src/items/all.ts@@ -4,7 +4,10 @@ export * from "./plan";export * from "./clips";export * from "./beats";export * from "./interact";+export * from "./hold";export * from "./passes";+export * from "./flight";+export * from "./lock";export * from "./body";export * from "./grasp";export * from "./core";diff --git a/sdk/character/src/items/beats.ts b/sdk/character/src/items/beats.tsindex 15200ce3..0d711141 100644--- a/sdk/character/src/items/beats.ts+++ b/sdk/character/src/items/beats.ts@@ -1,6 +1,6 @@// What interact asks of the body and the plan, beat by beat.import type { Vec3 } from "raea/3d";-import { add, qinv, joint, len, norm, pose, qmul, qrot, qyaw, rest, scale3, sub, type Side, type Skeleton } from "raea/character";+import { B, add, cross, qinv, joint, len, norm, pinchPoint, pose, qmul, qrot, qyaw, rest, scale3, sub, type Side, type Skeleton } from "raea/character";import { type Performance } from "../matching";import { handOn, pickGuide } from "../grasp";import { shapeOf, surfacesOf, toLocal } from "../things";@@ -12,10 +12,10 @@ import { Beat, D, FRONT, GUIDED, ItemPlan, SEGMENTS, T, lerp, thingSdf, trunkTurexport function beatGeometry(skel: Skeleton, perf: Performance, plan: ItemPlan) {const h = skel.height, dt = 1 / plan.fps;const J = skel.joints;- const chestY = J[joint(skel, "Spine1")].head[1], shoulderY = J[joint(skel, "LeftArm")].head[1], hipsY = J[0].head[1];+ const chestY = J[joint(skel, B.chest)].head[1], shoulderY = J[joint(skel, B.upperarm("L"))].head[1], hipsY = J[0].head[1];// the shoulders at rest, in the body's frame (its middle over the floor), and an arm's length- const shoulder: Record<Side, Vec3> = { L: J[joint(skel, "LeftArm")].head, R: J[joint(skel, "RightArm")].head };- const armLength = len(sub(J[joint(skel, "LeftForeArm")].head, J[joint(skel, "LeftArm")].head)) + len(sub(J[joint(skel, "LeftHand")].head, J[joint(skel, "LeftForeArm")].head));+ const shoulder: Record<Side, Vec3> = { L: J[joint(skel, B.upperarm("L"))].head, R: J[joint(skel, B.upperarm("R"))].head };+ const armLength = len(sub(J[joint(skel, B.lowerarm("L"))].head, J[joint(skel, B.upperarm("L"))].head)) + len(sub(J[joint(skel, B.hand("L"))].head, J[joint(skel, B.lowerarm("L"))].head));const beatAt = new Map(plan.beats.map((b) => [b.step, b]));// the body's ground frame at a frame: the hips over the floor, its heading the hips' (over half a second, so the// hold doesn't sway with each step)@@ -52,7 +52,16 @@ export function beatGeometry(skel: Skeleton, perf: Performance, plan: ItemPlan)// the lower edges of its sides: the palm low on the side, turned up a little to the edge, the fingers down// past it to curl under the bottomcase "wrap": out[s] = { at: [sd * (ex + 0.008), 0, -0.35 * ez], facing: [-sd, 0, 0.3], point: [0, 0.1, 1] }; break;- case "pinch": out[s] = { at: [sd * 0.25 * ex, ey + 0.004, -0.3 * ez], facing: [0, -1, 0], point: [-sd * 0.3, -0.3, 1] }; break;+ // from above, the fingers across its length (along it, it went between the index and middle fingers), the+ // thing where the captured pinch's pads meet (pinchPoint) rather than under the palm+ case "pinch": {+ const n: Vec3 = [0, -1, 0], f = norm(ez >= ex ? [-sd, -0.3, 0.3] : [-sd * 0.3, -0.3, 1]);+ const c = s === "R" ? cross(f, n) : cross(n, f), [pa, pp, pc] = pinchPoint(skel, s);+ const target: Vec3 = ez >= ex ? [0, 0, -0.25 * ez] : [sd * 0.25 * ex, 0, 0];+ const mid = sub(target, add(add(scale3(f, pa), scale3(n, pp)), scale3(c, pc)));+ out[s] = { at: add(mid, scale3(n, 0.009 * h)), facing: n, point: f };+ break;+ }// near its back end, from above and the side as it is written with, the fingers along it toward the pointcase "tripod": out[s] = { at: [sd * (ex + 0.006), 0.6 * ey, -0.25 * ez], facing: [-sd * 0.7, -0.7, 0], point: [0, -0.35, 1] }; break;// round the stem from its side, the fingers closing round it, the bowl over the hand@@ -179,7 +188,7 @@ export function beatGeometry(skel: Skeleton, perf: Performance, plan: ItemPlan)const sd = b.hands[0] === "L" ? 1 : -1;// (a wine glass carried before the body, upright, the upper arm hanging and the forearm out: hanging at the// side it spills)- at = sub(b.how.grip === "stem" ? [sd * 0.12 * h, shoulderY - 0.17 * h, 0.14 * h] : [sd * 0.12 * h, shoulderY - 0.78 * armLength, 0.1 * h], on[b.hands[0]]!.at);+ at = sub(b.how.grip === "stem" || plan.items[b.item].upright ? [sd * 0.12 * h, shoulderY - 0.17 * h, 0.14 * h] : [sd * 0.12 * h, shoulderY - 0.78 * armLength, 0.1 * h], on[b.hands[0]]!.at);} else if (b.how.grip === "pole") at = [0, hipsY + 0.04 * h, 0.15 * h];else at = [0, chestY - 0.16 * h - ey - 0.05 * h * heavy, Math.max(0.2 * h - 0.04 * h * heavy, FRONT * h + ez + 0.02)];// raised and drawn in until the hands are in easy reach of the shoulders (a big thing is held high against the@@ -202,7 +211,7 @@ export function beatGeometry(skel: Skeleton, perf: Performance, plan: ItemPlan)// (the lean back up to 0.2 rad, the hips up to a twentieth of the height, the bend up to 0.25), solved on the body// at rest, so a ball or a mug moves nothing. `moved`: the load's middle moved with the trunk (the body's frame).type Statics = { pitch: number; back: number; roll: number; abduct: number; moved: Vec3 };- const restPose = rest(skel), restW = pose(skel, restPose), spineJ = joint(skel, "Spine");+ const restPose = rest(skel), restW = pose(skel, restPose), spineJ = joint(skel, B.spine[1]);const comOf = (w: ReturnType<typeof pose>): Vec3 => {let c: Vec3 = [0, 0, 0], sum = 0;for (const [a, b2, k] of SEGMENTS) { const A = w.pos[joint(skel, a)], B = w.pos[joint(skel, b2)]; c = add(c, scale3(add(A, B), 0.5 * k)); sum += k; }@@ -214,7 +223,7 @@ export function beatGeometry(skel: Skeleton, perf: Performance, plan: ItemPlan)const staticsOf = (b: Beat): Statics => {if (staticsMemo.has(b)) return staticsMemo.get(b)!;const r = b.how.load, L0 = holdOf(b), one = b.hands.length === 1 && b.how.grip !== "stem", sd = b.hands[0] === "L" ? 1 : -1;- const shJ = joint(skel, b.hands[0] === "L" ? "LeftArm" : "RightArm");+ const shJ = joint(skel, B.upperarm(b.hands[0]));const at = (t: number) => {const pitch = -0.2 * t * (one ? 0 : 1), back = 0.05 * h * t * (one ? 0 : 1), roll = one ? sd * 0.25 * t : 0;const w = pose(skel, trunkTurn(skel, restPose, 0, 0, pitch, roll));@@ -265,8 +274,10 @@ export function beatGeometry(skel: Skeleton, perf: Performance, plan: ItemPlan)const freeOf = (b: Beat) => {// (a wine glass carried steady before the waist, never swung)if (b.hands.length !== 1 || b.how.grip === "stem") return 0;+ // (one carried upright swings a third as freely: steady, but not a steadicam's)+ const up = plan.items[b.item].upright ? 0.35 : 1;const small = 1 - Math.min(1, Math.max(0, (Math.max(...plan.items[b.item].size) - 0.1 * h) / (0.1 * h)));- return 0.85 * small * (1 - Math.min(1, Math.max(0, (b.how.load - 0.003) / 0.027)));+ return up * 0.85 * small * (1 - Math.min(1, Math.max(0, (b.how.load - 0.003) / 0.027)));};const holdW = (b: Beat) => 1 - freeOf(b);const grip = (b: Beat) => ({ pinch: 0.55, tripod: 0.6, top: 1, wrap: 1, handle: 1, stem: 1.1, palm: 0.35, sides: 0.45, edges: 0.9, cradle: 0.3, hug: 0.5, pole: 1 })[b.how.grip];diff --git a/sdk/character/src/items/body.ts b/sdk/character/src/items/body.tsindex 1c44af77..661d0543 100644--- a/sdk/character/src/items/body.ts+++ b/sdk/character/src/items/body.ts@@ -1,6 +1,6 @@// The body's trunk turned, crouched and stooped, and its fingers.import type { Vec3 } from "raea/3d";-import { add, joint, len, twoBone, palmAt, pose, qaxis, qmul, qrot, qyaw, reach, scale3, setWorld, slerp, sub, type HandGoal, type Pose, type Side, type Skeleton } from "raea/character";+import { B, FINGERS, I, handRest, add, joint, len, twoBone, palmAt, pose, qaxis, qmul, qrot, qyaw, reach, scale3, setWorld, slerp, sub, type HandGoal, type Pose, type Side, type Skeleton } from "raea/character";import { lerp } from "./all";/** The trunk turned: twisted about up (`twist`, + to the body's left), pitched about the body's left (`pitch`, +@@ -8,7 +8,7 @@ import { lerp } from "./all";* so the shoulders and arms ride with it. */export function trunkTurn(skel: Skeleton, p: Pose, yaw: number, twist: number, pitch: number, roll = 0): Pose {if (!twist && !pitch && !roll) return p;- const chain = ["LowerBack", "Spine", "Spine1"].map((n) => joint(skel, n)), share = [0.25, 0.35, 0.4];+ const chain = [B.spine[0], B.spine[1], B.chest].map((n) => joint(skel, n)), share = [0.25, 0.35, 0.4];const left = qrot(qyaw(yaw), [1, 0, 0]), ahead = qrot(qyaw(yaw), [0, 0, 1]);for (let c = 0; c < 3; c++) {const w = pose(skel, p);@@ -30,7 +30,9 @@ export function crouched(skel: Skeleton, p: Pose, hands: Partial<Record<Side, Haexport function crouchedAt(skel: Skeleton, p: Pose, hands: Partial<Record<Side, HandGoal>>, drop: number, lean: number, stoopAt?: number, back = 0): { pose: Pose; stoop: number } {// (on the floor as far as it squats: a carry at a run keeps its stride's feet, in the air over a hurdle too)const down = Math.min(1, Math.max(0, drop / 0.06));- const w0 = pose(skel, p), feet = (["L", "R"] as Side[]).map((s) => { const i = joint(skel, s === "L" ? "LeftFoot" : "RightFoot"), a = w0.pos[i]; return [a[0], (a[1] - skel.joints[i].head[1]) * (1 - down), a[2]] as Vec3; });+ // (a foot mid-step, over 2.5 cm up, stays where the step has it: put on the floor, it was dragged along the floor+ // the whole step, errands' turn at the desk sliding 11 cm)+ const w0 = pose(skel, p), feet = (["L", "R"] as Side[]).map((s) => { const i = joint(skel, B.foot(s)), a = w0.pos[i], up = a[1] - skel.joints[i].head[1]; return [a[0], up > 0.025 ? up : up * (1 - down), a[2]] as Vec3; });// the hips go back as they go down (a squat sits back over the heels, balancing the knees ahead)let q: Pose = { ...p, root: add(p.root, add([0, -drop, 0], scale3(backOf(p), 0.25 * drop + back))) };let th = 0, axis: Vec3 = [1, 0, 0];@@ -46,7 +48,7 @@ export function crouchedAt(skel: Skeleton, p: Pose, hands: Partial<Record<Side,// the hips no higher than lets both feet stand flat on the floor (sat back and bent over, the legs would stretch// and leave the body on its toes)const legs = (["L", "R"] as Side[]).map((s, i) => {- const [u, k, f] = (s === "L" ? ["LeftUpLeg", "LeftLeg", "LeftFoot"] : ["RightUpLeg", "RightLeg", "RightFoot"]).map((n) => joint(skel, n));+ const [u, k, f] = B.leg(s).map((n) => joint(skel, n));const J = skel.joints, L = 0.985 * (len(sub(J[k].head, J[u].head)) + len(sub(J[f].head, J[k].head)));const hip = pose(skel, q).pos[u], ankle: Vec3 = [feet[i][0], J[f].head[1] + feet[i][1], feet[i][2]];const dh = Math.hypot(hip[0] - ankle[0], hip[2] - ankle[2]), dv = hip[1] - ankle[1];@@ -55,12 +57,12 @@ export function crouchedAt(skel: Skeleton, p: Pose, hands: Partial<Record<Side,const sink = Math.max(...legs);if (sink > 0) q = { ...q, root: [q.root[0], q.root[1] - sink, q.root[2]] };(["L", "R"] as Side[]).forEach((s, i) => {- const fi = joint(skel, s === "L" ? "LeftFoot" : "RightFoot"), knee = qrot(qyaw(yaw), [s === "L" ? 0.25 : -0.25, 0, 1]);+ const fi = joint(skel, B.foot(s)), knee = qrot(qyaw(yaw), [s === "L" ? 0.25 : -0.25, 0, 1]);// (the ankle at its standing height over the floor: the foot flat)- q = twoBone(skel, q, s === "L" ? ["LeftUpLeg", "LeftLeg", "LeftFoot"] : ["RightUpLeg", "RightLeg", "RightFoot"], [feet[i][0], skel.joints[fi].head[1] + feet[i][1], feet[i][2]], knee);+ q = twoBone(skel, q, B.leg(s), [feet[i][0], skel.joints[fi].head[1] + feet[i][1], feet[i][2]], knee);// the foot flat on the floor, turned the way its toes point (not tipped onto its toes with the shin, nor up on// them as the walk had it mid-step)- const ti = joint(skel, s === "L" ? "LeftToeBase" : "RightToeBase"), restDir = sub(skel.joints[ti].head, skel.joints[fi].head), now = qrot(w0.rot[fi], restDir);+ const ti = joint(skel, B.ball(s)), restDir = sub(skel.joints[ti].head, skel.joints[fi].head), now = qrot(w0.rot[fi], restDir);const wq = pose(skel, q);q = setWorld(skel, q, wq, fi, slerp(w0.rot[fi], qyaw(Math.atan2(now[0], now[2]) - Math.atan2(restDir[0], restDir[2])), down));});@@ -70,7 +72,7 @@ export function crouchedAt(skel: Skeleton, p: Pose, hands: Partial<Record<Side,// of the stoopif (th > 0) for (const s of ["L", "R"] as Side[]) {if (hands[s]) continue;- const i = joint(skel, s === "L" ? "LeftArm" : "RightArm"), w = pose(skel, q);+ const i = joint(skel, B.upperarm(s)), w = pose(skel, q);q = setWorld(skel, q, w, i, qmul(qaxis(axis, -0.85 * th), w.rot[i]));}return { pose: q, stoop: th };@@ -87,9 +89,9 @@ function backOf(p: Pose): Vec3 {* up the back. (leanToward bends the back alone, which for a reach to the floor brings the shoulders down too little.) */export function stoop(skel: Skeleton, p: Pose, hands: Partial<Record<Side, HandGoal>>, most: number, fixed?: number): { pose: Pose; th: number; axis: Vec3 } {const goals = Object.entries(hands) as [Side, HandGoal][];- const J = skel.joints, chain = ["LowerBack", "Spine", "Spine1"].map((n) => joint(skel, n)), share = [0.2, 0.2, 0.15], hipShare = 0.45;- const arm = (s: Side) => joint(skel, s === "L" ? "LeftArm" : "RightArm");- const armLen = (s: Side) => { const [a, b, c] = (s === "L" ? ["LeftArm", "LeftForeArm", "LeftHand"] : ["RightArm", "RightForeArm", "RightHand"]).map((n) => J[joint(skel, n)].head); return len(sub(b, a)) + len(sub(c, b)); };+ const J = skel.joints, chain = [B.spine[0], B.spine[1], B.chest].map((n) => joint(skel, n)), share = [0.2, 0.2, 0.15], hipShare = 0.45;+ const arm = (s: Side) => joint(skel, B.upperarm(s));+ const armLen = (s: Side) => { const [a, b, c] = B.arm(s).map((n) => J[joint(skel, n)].head); return len(sub(b, a)) + len(sub(c, b)); };const w0 = pose(skel, p);const mid = scale3(add(w0.pos[arm("L")], w0.pos[arm("R")]), 0.5);const toward = goals.reduce<Vec3>((acc, [, g]) => add(acc, sub(g.at, mid)), [0, 0, 0]);@@ -155,13 +157,13 @@ export function fingers(skel: Skeleton, p: Pose, amounts: Partial<Record<Side, nconst turns = p.turns.slice();for (const [s, amount] of Object.entries(amounts) as [Side, number][]) {if (!(amount > 0)) continue;- // the fingers curl about the hand's across axis: at rest the arms are out along x, the palms down, so the fingers- // (along x) curl about z- const ax: Vec3 = [0, 0, 1], sign = s === "L" ? -1 : 1;- for (const [n, a] of [["FingerBase", 0.5], ["HandFinger1", 1.1], ["Thumb", 0.4]] as [string, number][]) {- const name = n === "Thumb" ? `${s}Thumb` : `${s === "L" ? "Left" : "Right"}${n}`;- const i = skel.joints.findIndex((j) => j.name === name);- if (i >= 0) turns[i] = qmul(turns[i], qaxis(ax, sign * a * amount));+ // the fingers curl about the hand's across axis at rest (the knuckles a little, the two joints past them more),+ // the thumb in about the hand's length+ const { along, across } = handRest(skel, s), sign = s === "L" ? -1 : 1;+ while (turns.length < skel.joints.length) turns.push(I);+ for (const f of FINGERS) for (const k of [1, 2, 3] as const) {+ const i = joint(skel, B.finger(f, k, s));+ turns[i] = qmul(turns[i], f === "thumb" ? qaxis(along, -sign * 0.4 * amount) : qaxis(across, sign * (k === 1 ? 0.5 : 0.55) * amount));}}return { ...p, turns };diff --git a/sdk/character/src/items/core.ts b/sdk/character/src/items/core.tsindex 10ebf4d6..fae85e79 100644--- a/sdk/character/src/items/core.ts+++ b/sdk/character/src/items/core.ts@@ -1,6 +1,6 @@// Items' tasks and plans, and the moments and measures of a reach, a carry and a throw.import type { Vec3 } from "raea/3d";-import { joint, palmAt, pose, rest, type HandGoal, type Side, type Skeleton } from "raea/character";+import { B, SIDES, joint, palmAt, pose, rest, type HandGoal, type Side, type Skeleton } from "raea/character";import { type PerformanceSpec, type Step } from "../matching";import { type Handling, type Thing } from "../things";import { crouchDrop, crouchedAt, stoop } from "./all";@@ -91,8 +91,8 @@ export const FRONT = 0.092;// the body's segments' masses, a share of the whole each, at the middle of its two joints (de Leva 1996): the trunk,// the head, and each side's upper arm, forearm, hand, thigh, shin and foot-export const SEGMENTS: [string, string, number][] = [["Hips", "Spine1", 0.497], ["Neck", "Head", 0.081],- ...["Left", "Right"].flatMap((s) => [[s + "Arm", s + "ForeArm", 0.028], [s + "ForeArm", s + "Hand", 0.016], [s + "Hand", s + "Hand", 0.006], [s + "UpLeg", s + "Leg", 0.1], [s + "Leg", s + "Foot", 0.0465], [s + "Foot", s + "ToeBase", 0.0145]] as [string, string, number][])];+export const SEGMENTS: [string, string, number][] = [[B.pelvis, B.chest, 0.497], [B.neck, B.head, 0.081],+ ...SIDES.flatMap((s) => [[B.upperarm(s), B.lowerarm(s), 0.028], [B.lowerarm(s), B.hand(s), 0.016], [B.hand(s), B.hand(s), 0.006], [B.thigh(s), B.calf(s), 0.1], [B.calf(s), B.foot(s), 0.0465], [B.foot(s), B.ball(s), 0.0145]] as [string, string, number][])];// a patient pick, after it: raised before the chest and turned over in the hand, looked at, then lowered to the hold// (seconds)@@ -145,7 +145,7 @@ export const leanFor = (bend: number) => lerp(1.4, 0.7, bend);* body standing at rest with the crouch interact uses, so the plan never asks a squat to reach past its arms (it would* fold flat over its knees to get there). */export function reachAhead(skel: Skeleton, y: number, bend: number): number {- const p0 = rest(skel), x = skel.joints[joint(skel, "RightArm")].head[0], h = skel.height;+ const p0 = rest(skel), x = skel.joints[joint(skel, B.upperarm("R"))].head[0], h = skel.height;const ok = (d: number) => {const goal: HandGoal = { at: [x, y, d] }, { drop, stoop } = crouchDrop(skel, p0, { R: goal }, leanFor(bend), bend);const pa = palmAt(skel, pose(skel, crouchedAt(skel, p0, { R: goal }, drop, leanFor(bend), stoop).pose), "R");diff --git a/sdk/character/src/items/flight.ts b/sdk/character/src/items/flight.tsnew file mode 100644index 00000000..cbf8bfc5--- /dev/null+++ b/sdk/character/src/items/flight.ts@@ -0,0 +1,54 @@+// interact's things in the air: let go, falling and flying until they land, then a light ball bounces and rolls.+import type { Vec3 } from "raea/3d";+import { qaxis, qmul, scale3, slerp, type Quat } from "raea/character";+import { handling, shapeOf, toLocal } from "../things";+import { Beat, Flight, G, ItemPlan, Track, uprightNear } from "./all";++/** each thing in the air moved on one frame (`dt`), `now` and `placed` set where it is */+export function fly(flying: Map<string, Flight>, holding: Map<string, Beat>, now: Map<string, Track>, placed: Map<string, { at: Vec3; rot: Quat }>, plan: ItemPlan, h: number, dt: number,+ landing: (p: Vec3, below: number) => { y: number; inside: boolean }, supportAt: (p: Vec3, below: number) => number) {+ // the things let go: falling and flying until they land, then a light ball bounces and rolls to a stop+ for (const [id, fl] of flying) {+ if (holding.has(id) || now.get(id)?.held) { flying.delete(id); continue; }+ const it = plan.items[id], ball = shapeOf(it) === "ball", r = it.size[0] / 2;+ if (!fl.landed) {+ const next: Vec3 = [fl.at[0] + fl.vel[0] * dt, fl.at[1] + fl.vel[1] * dt - 0.5 * G * dt * dt, fl.at[2] + fl.vel[2] * dt];+ const { y: floor, inside } = landing(next, fl.at[1]);+ fl.vel = [fl.vel[0], fl.vel[1] - G * dt, fl.vel[2]];+ const w = Math.hypot(...fl.spin);+ if (w > 0) fl.rot = qmul(qaxis(scale3(fl.spin, 1 / w), w * dt), fl.rot);+ if (next[1] <= floor) {+ next[1] = floor;+ const light = handling(it, h).weight === "light";+ if (ball && light && !inside && fl.vel[1] < -1.2 && fl.bounces < 4) {+ fl.vel = [fl.vel[0] * 0.7, -fl.vel[1] * 0.45, fl.vel[2] * 0.7];+ fl.bounces++;+ } else {+ fl.landed = true;+ fl.vel = ball && !inside ? [fl.vel[0] * 0.7, 0, fl.vel[2] * 0.7] : [0, 0, 0];+ }+ }+ fl.at = next;+ } else {+ // a ball rolls (slowing), turning by the way it goes; anything else settles flat over a few frames+ const sp = Math.hypot(fl.vel[0], fl.vel[2]);+ if (ball && sp > 0.02) {+ const k = Math.max(0, sp - 1.5 * dt) / sp;+ fl.vel = [fl.vel[0] * k, 0, fl.vel[2] * k];+ const next: Vec3 = [fl.at[0] + fl.vel[0] * dt, fl.at[1], fl.at[2] + fl.vel[2] * dt];+ // it stops against anything standing in its way+ if (plan.things.some((t) => t.at[1] < 0.02 && toLocal(t, next)[1] < t.size[1] && Math.abs(toLocal(t, next)[0]) < t.size[0] / 2 + r && Math.abs(toLocal(t, next)[2]) < t.size[2] / 2 + r)) fl.vel = [0, 0, 0];+ else {+ const axis: Vec3 = [fl.vel[2] / sp, 0, -fl.vel[0] / sp];+ fl.rot = qmul(qaxis(axis, (sp * k * dt) / Math.max(0.01, r)), fl.rot);+ fl.at = [next[0], supportAt(next, fl.at[1] + 0.01), next[2]];+ }+ } else if (!ball && fl.settle < 1) {+ fl.settle = Math.min(1, fl.settle + 0.2);+ fl.rot = slerp(fl.rot, uprightNear(fl.rot), fl.settle);+ }+ }+ now.set(id, { at: fl.at, rot: fl.rot, held: false });+ placed.set(id, { at: fl.at, rot: fl.rot });+ }+}diff --git a/sdk/character/src/items/grasp.ts b/sdk/character/src/items/grasp.tsindex f5ede77c..575d6396 100644--- a/sdk/character/src/items/grasp.ts+++ b/sdk/character/src/items/grasp.ts@@ -1,6 +1,6 @@// A thing's distance field, the hands kept out of it, and a grip's fingers closed on it.import type { Vec3 } from "raea/3d";-import { add, closeOn, surface, handPose, handSurface, norm, pose, qrot, scale3, slerp, sub, type Finger, type HandShape, type Pose, type Side, type Skeleton } from "raea/character";+import { add, closeOn, pathHand, surface, handPose, type Closing, handSurface, norm, pose, qrot, scale3, slerp, sub, type Finger, type HandShape, type Pose, type Side, type Skeleton } from "raea/character";import { type Guide } from "../grasp";import { shapeOf, type Handling, type Thing } from "../things";import { fingers } from "./all";@@ -98,26 +98,40 @@ export function turnGuide(g: Guide, pt: (v: Vec3) => Vec3, dir: (v: Vec3) => Vec}}-// each grip's fingers: which close on the thing (the rest held as `rest` says), how far they may close (a fist's-// curl is about 1.5 at the knuckle), the fan and the thumb's opposition. A ball in the palm is held by all five,-// spread round it; a pencil by the thumb, index and middle, the ring and pinky tucked; a wine glass's stem between-// the thumb and the first two fingers, the others curled under the foot; a box's edge by the four fingers curled-// under it, the thumb along its side; a big thing by spread fingers lying on it-export const GRASP: Record<Handling["grip"], { on: Finger[]; rest?: Partial<Record<Finger, [number, number, number]>>; max: number; spread: number; opp: number }> = {- palm: { on: ["thumb", "index", "middle", "ring", "pinky"], max: 1.4, spread: 0.35, opp: 0.7 },- top: { on: ["thumb", "index", "middle", "ring", "pinky"], max: 1.6, spread: 0.3, opp: 0.5 },- wrap: { on: ["thumb", "index", "middle", "ring", "pinky"], max: 1.6, spread: 0, opp: 0.8 },- handle: { on: ["thumb", "index", "middle", "ring", "pinky"], max: 1.6, spread: 0, opp: 0.6 },- pole: { on: ["thumb", "index", "middle", "ring", "pinky"], max: 1.6, spread: 0, opp: 0.8 },- pinch: { on: ["thumb", "index"], rest: { middle: [0.6, 0.7, 0.4], ring: [0.8, 0.9, 0.5], pinky: [0.9, 1, 0.6] }, max: 1.3, spread: 0.1, opp: 0.9 },- tripod: { on: ["thumb", "index", "middle"], rest: { ring: [1.3, 1.4, 0.9], pinky: [1.4, 1.5, 1] }, max: 1.3, spread: 0.15, opp: 0.9 },- stem: { on: ["thumb", "index", "middle"], rest: { ring: [1.2, 1.3, 0.9], pinky: [1.3, 1.4, 1] }, max: 1.5, spread: -0.05, opp: 0.8 },- edges: { on: ["index", "middle", "ring", "pinky"], rest: { thumb: [0.15, 0.1, 0.05] }, max: 1.5, spread: 0, opp: 0 },- sides: { on: ["thumb", "index", "middle", "ring", "pinky"], max: 0.6, spread: 0.1, opp: 0.2 },- cradle: { on: ["thumb", "index", "middle", "ring", "pinky"], max: 0.7, spread: 0.3, opp: 0.15 },- hug: { on: ["thumb", "index", "middle", "ring", "pinky"], max: 0.9, spread: 0.2, opp: 0.15 },+// each grip's fingers, along captured hands (character/captured.ts: Godot XR Tools' poses, CC0): which close on the+// thing, along which poses (open to closed), the rest held where (`rest`, places on that path) and how far along it+// they may go (`max`). A power grip (a can, a mug's handle, a pole, a box's edge) closes through the capture's own+// steps from open round a shaft (Grip Shaft: its thumb opposed, not folded over the fingers as in a fist) to a fist; a pinch through Pinch Large to Pinch Tight, the other three tucked as+// it tucks them; a pencil's tripod and a wine glass's stem the same with the middle finger closing under it; a ball+// in the palm through Cup; a big thing's spread fingers no further than Rounded or Cup, lying on it+const POWER = ["Default pose", "Grip 5", "Grip Shaft", "Grip 1", "Grip"] as const;+const PINCH = ["Default pose", "Pinch Large", "Pinch Tight"] as const;+const ROUND = ["Default pose", "Rounded", "Cup"] as const;+const ALL: Finger[] = ["thumb", "index", "middle", "ring", "pinky"];+const tucked = { middle: [2, 2, 2], ring: [2, 2, 2], pinky: [2, 2, 2] } as Partial<Record<Finger, [number, number, number]>>;+export const GRASP: Record<Handling["grip"], Closing> = {+ palm: { on: ALL, path: ["Default pose", "Cup", "Grip"], max: 2, spread: 0, opp: 0, thumb: { max: 1.4, opp: 0.7 } },+ top: { on: ALL, path: POWER, max: 4, spread: 0, opp: 0, thumb: { max: 1.6, opp: 0.5 } },+ wrap: { on: ALL, path: POWER, max: 4, spread: 0, opp: 0, thumb: { max: 1.6, opp: 0.8 } },+ handle: { on: ALL, path: POWER, max: 4, spread: 0, opp: 0, thumb: { max: 1.6, opp: 0.6 } },+ pole: { on: ALL, path: POWER, max: 4, spread: 0, opp: 0, thumb: { max: 1.6, opp: 0.8 } },+ pinch: { on: ["thumb", "index"], path: PINCH, rest: tucked, max: 2, spread: 0, opp: 0 },+ tripod: { on: ["thumb", "index", "middle"], path: PINCH, rest: { ring: [2, 2, 2], pinky: [2, 2, 2] }, max: 2, spread: 0, opp: 0 },+ stem: { on: ["thumb", "index", "middle"], path: PINCH, rest: { ring: [2, 2, 2], pinky: [2, 2, 2] }, max: 2, spread: 0, opp: 0, thumb: { max: 1.5, opp: 0.8 } },+ edges: { on: ["index", "middle", "ring", "pinky"], path: POWER, max: 4, spread: 0, opp: 0 },+ sides: { on: ALL, path: ROUND, max: 1, spread: 0, opp: 0, thumb: { max: 0.6, opp: 0.2 } },+ cradle: { on: ALL, path: ROUND, max: 1.5, spread: 0, opp: 0, thumb: { max: 0.7, opp: 0.15 } },+ hug: { on: ALL, path: ROUND, max: 1.5, spread: 0, opp: 0, thumb: { max: 0.9, opp: 0.15 } },};+/** a hand in a grip's shape `shape` (closeOn's: curls, or places along the grip's captured path) */+export function shapedHand(skel: Skeleton, p: Pose, s: Side, grip: Handling["grip"], shape: HandShape): Pose {+ const g = GRASP[grip];+ if (!g.path) return handPose(skel, p, s, shape);+ const on = pathHand(skel, p, s, g.path, shape, g.thumb ? 1 : 0);+ return g.thumb ? handPose(skel, on, s, shape, ["thumb"]) : on;+}+/*** A hand's fingers closed on a thing (its distance field in the scene, `field`): closeOn curls each the grip closes* until its skin rests on the thing, the thumb on the fingers too, no further than the grip closes them by `close`;@@ -127,7 +141,7 @@ export const GRASP: Record<Handling["grip"], { on: Finger[]; rest?: Partial<Recoexport function graspThing(skel: Skeleton, p: Pose, s: Side, field: (q: Vec3) => number, grip: Handling["grip"], close: number, w: number, hand?: { shape?: HandShape }): Pose {const shape = closeOn(skel, p, s, field, GRASP[grip], close, hand?.shape);if (hand) hand.shape = shape;- const done = handPose(skel, p, s, shape);+ const done = shapedHand(skel, p, s, grip, shape);if (w >= 1) return done;return { ...done, turns: done.turns.map((q, i) => (i < p.turns.length ? slerp(p.turns[i], q, w) : slerp([0, 0, 0, 1], q, w))) };}diff --git a/sdk/character/src/items/hold.ts b/sdk/character/src/items/hold.tsnew file mode 100644index 00000000..175d2373--- /dev/null+++ b/sdk/character/src/items/hold.ts@@ -0,0 +1,186 @@+// hold: the things fitted to the hands that have them, the last pass of interact. Each frame, a thing in hand is+// moved with the hand (rigidly on a guide, by the palms' miss otherwise), sat in the palm (a ball) or pushed out of the+// body and the hands, its grip locked once the fingers have closed on it, and the free hand moved out of its way;+// the dodges eased over the frames after. It returns how far the hands missed their goals, frame by frame.+import type { Vec3 } from "raea/3d";+import { B, add, ballInHand, cross, dot, handAlong, qbasis, qinv, handSurface, joint, len, norm, palmAt, palmFacing, pose, qaxis, qmul, qnorm, qrot, reach, scale3, setWorld, slerp, sub, type HandGoal, type HandShape, type Pose, type Side, type Skeleton } from "raea/character";+import { handling, shapeOf, type Handling } from "../things";+import { type Attach, type Goals, GRASP, ItemPlan, PINCHED, Track, depthIn, easeDodges, easeOff, fieldNormal, graspThing, leadOf, lockOn, mix, outOfBody, outOfHands, pinchLock, reachLocked, riddenSliding, settled, shapedHand, thingSdf, type Lock } from "./all";++/** a frame of interact's work: the walk's pose, the goals laid over it, the hips' drop and stoop it needs, the things+ * riding the hands, whether a beat is on, and a thing sat in a palm */+export interface Work { p: Pose; goals: Goals; drop: number; stoop: number; attach: Attach[]; beat: boolean; palmed?: { id: string; hand: Side; w: number } }++export function holdThings(skel: Skeleton, plan: ItemPlan, h: number, poses: Pose[], work: Work[], tracks: Map<string, Track[]>): number[] {+ const misses: number[] = [];+ // how far each hand not on a thing moves out of one in hand, frame by frame (dodged after, smoothed)+ const dodge: Record<Side, (Vec3 | undefined)[]> = { L: [], R: [] };+ // (and the thing a dodging hand carries, which goes with it)+ const carried: (string | undefined)[] = [];+ // (each frame's grasps of a thing in hand, to close again on it where the dodge moves the hand)+ const grasped: { id: string; hands: Side[]; grip: Handling["grip"]; close: number }[][] = [];+ // (and each hand's fingers' shape on it, frame by frame: a hand's fingers move on from the last frame's)+ const shapes: Record<Side, (HandShape | undefined)[]> = { L: [], R: [] };+ // (each thing's grip once the hands have closed on it, fixed while it is held: lock.ts)+ const locks = new Map<string, Lock>(), ready = new Map<string, number>();+ // (whether a thing's grip at a frame is one a guide placed the hand for)+ const guidedGrip = (id: string, f: number) => work[f].goals.grasps.some((g) => g.id === id && g.guide);+ for (let f = 0; f < work.length; f++) {+ const p = poses[f], { goals } = work[f];+ let miss = 0;+ if (goals.weight >= 1) {+ const w = pose(skel, p);+ for (const [s, g] of Object.entries(goals.hands) as [Side, HandGoal][]) {+ const at = g.point ? sub(g.at, scale3(norm(g.facing ?? [0, -1, 0]), 0.009 * h)) : g.at;+ miss = Math.max(miss, len(sub(palmAt(skel, w, s), at)));+ }+ }+ misses.push(miss);+ // (where each thing was sent, before it is fitted to the hands: a locked one goes from there)+ const sent = new Map([...tracks].map(([id, t]) => [id, t[f]]));+ if (work[f].attach.length) {+ const w = pose(skel, p);+ for (const a of work[f].attach) {+ if (locks.has(a.id)) continue;+ // (a flat hand's palm rests half its thickness off the goal, as reach puts it)+ const goalOf = (g: HandGoal) => (g.point ? sub(g.at, scale3(norm(g.facing ?? [0, -1, 0]), 0.009 * h)) : g.at);+ const tr = tracks.get(a.id)!, g1 = goals.hands[a.hands[0]]!;+ if (a.hands.length === 1 && g1.point && guidedGrip(a.id, f)) {+ // a thing on a guide in one hand rides it rigidly, turned with the hand as well as moved with it: the hand's+ // frame where it is against where it was sent (a can carried by a hand swinging with the walk tips with it,+ // and stays on the palm, not just as far from it)+ const s = a.hands[0], n = norm(g1.facing ?? [0, -1, 0]), fp = norm(sub(g1.point, scale3(n, dot(g1.point, n))));+ const na = palmFacing(skel, w, s), al = handAlong(skel, w, s), fa = norm(sub(al, scale3(na, dot(al, na))));+ const turn = slerp([0, 0, 0, 1], qmul(qbasis(fa, na, cross(fa, na)), qinv(qbasis(fp, n, cross(fp, n)))), a.w);+ const from = goalOf(g1), to = add(from, scale3(sub(palmAt(skel, w, s), from), a.w));+ tr[f] = { ...tr[f], at: add(to, qrot(turn, sub(tr[f].at, from))), rot: qnorm(qmul(turn, tr[f].rot)) };+ } else {+ const off = a.hands.reduce<Vec3>((acc, s) => add(acc, scale3(sub(palmAt(skel, w, s), goalOf(goals.hands[s]!)), 1 / a.hands.length)), [0, 0, 0]);+ tr[f] = { ...tr[f], at: add(tr[f].at, scale3(off, a.w)) };+ }+ }+ }+ // (a ball sat in the palm as it swings; anything else stays in its grip, a cup wrapped)+ const pm = work[f].palmed && shapeOf(plan.items[work[f].palmed!.id]) === "ball" ? work[f].palmed : undefined;+ if (pm && !locks.has(pm.id)) {+ const it = plan.items[pm.id], tr = tracks.get(pm.id)!, r = Math.max(...it.size) / 2;+ // (sat in the palm as far as it is in it: graspThing closes the fingers on it)+ const w = pose(skel, poses[f]), mid = ballInHand(skel, w, pm.hand, r);+ tr[f] = { ...tr[f], at: mix(tr[f].at, sub(mid, qrot(tr[f].rot, [0, it.size[1] / 2, 0])), pm.w) };+ }+ // each hand on a thing: the thing out of the hand's skin (a thing in hand moves; one still where it lies is+ // reached to its surface), then each finger closed until it touches it, as far as the grip closes them+ const grasps = goals.grasps.length ? goals.grasps : pm ? [{ id: pm.id, hands: [pm.hand], grip: "palm" as const, w: pm.w, close: 1 }] : [];+ for (const gr of grasps) {+ const tr = tracks.get(gr.id)!, planned = sent.get(gr.id)!.at, held = tr[f].held || work[f].attach.some((a) => a.id === gr.id) || pm?.id === gr.id;+ const sdf = thingSdf(plan.items[gr.id]);+ const field = (q: Vec3) => sdf(qrot(qinv(tr[f].rot), sub(q, tr[f].at)));+ if (!held) { locks.delete(gr.id); ready.delete(gr.id); }+ const lk = held ? locks.get(gr.id) : undefined, ride = work[f].attach.find((a) => a.id === gr.id)?.w ?? (pm?.id === gr.id ? 1 : 0);+ if (lk) {+ // locked: a light thing in one hand where the hand has it; anything else where it goes, the hands on it+ if (lk.lead === "hand") {+ // (a thing carried upright kept so by the wrist, RAEA_CARRY_UPRIGHT=0 not: a cup riding a hand that swings with+ // the walk tipped with it, 60 to 96 degrees off upright all the way to the desk; the hand turned about the wrist by the+ // shortest turn that stands it up, no more than a wrist bends (RAEA_UPRIGHT_MAX, 70 degrees), as far as it rides)+ if (process.env.RAEA_CARRY_UPRIGHT !== "0" && plan.items[gr.id].upright && ride > 0) {+ const s = gr.hands[0], w0 = pose(skel, poses[f]), hi = joint(skel, B.hand(s));+ const up = qrot(riddenSliding(skel, w0, s, { ...lk, slide: undefined }).rot, [0, 1, 0]);+ const ax = cross(up, [0, 1, 0]), sn = len(ax), a = Math.atan2(sn, up[1]);+ const most = (Number(process.env.RAEA_UPRIGHT_MAX ?? 70) * Math.PI) / 180;+ if (sn > 1e-6 && a > 1e-3) poses[f] = setWorld(skel, poses[f], w0, hi, qnorm(qmul(qaxis(scale3(ax, 1 / sn), Math.min(a, most) * ride), w0.rot[hi])));+ }+ // (let go of by the hand as it is put down: where it goes, the hand brought to its locked place on it)+ const r = riddenSliding(skel, pose(skel, poses[f]), gr.hands[0], lk);+ lk.off = easeOff(lk.off, [0, 0, 0]);+ tr[f] = { ...tr[f], at: mix(add(tr[f].at, lk.off), r.at, ride), rot: qnorm(slerp(tr[f].rot, r.rot, ride)) };+ if (ride < 0.999) poses[f] = reachLocked(skel, poses[f], lk, tr[f].at, tr[f].rot, { L: goals.hands.L?.elbow, R: goals.hands.R?.elbow }).p;+ const v = outOfBody(skel, poses[f], field, false);+ if (len(v) > 0.002) { dodge[gr.hands[0]][f] = add(v, scale3(norm(v), 0.006)); carried[f] = gr.id; }+ } else {+ lk.off = easeOff(lk.off, gr.hands.length === 2 ? outOfBody(skel, poses[f], field) : [0, 0, 0]);+ const at0 = add(tr[f].at, lk.off), r = reachLocked(skel, poses[f], lk, at0, tr[f].rot, { L: goals.hands.L?.elbow, R: goals.hands.R?.elbow });+ poses[f] = r.p;+ tr[f] = { ...tr[f], at: add(at0, scale3(r.miss, ride)) };+ }+ // (the fingers go on closing on it from where they were: the hand fixed on it, they meet it the same way+ // each frame, and settle)+ const fieldL = (q: Vec3) => sdf(qrot(qinv(tr[f].rot), sub(q, tr[f].at)));+ for (const s of gr.hands) {+ const hand = { shape: shapes[s][f - 1] };+ poses[f] = graspThing(skel, poses[f], s, fieldL, gr.grip, gr.close, 1, hand);+ shapes[s][f] = hand.shape;+ }+ (grasped[f] ??= []).push(gr);+ } else {+ if (held) {+ // (a thing against the body out of its trunk, head and thighs, the hands brought with it; a small thing in one+ // hand swings past the thigh as the arm does)+ const off = gr.hands.length === 2 ? outOfBody(skel, poses[f], field) : [0, 0, 0] as Vec3;+ // (one in one hand swung into the thigh or the waist: the hand and it dodged out, smoothed after)+ // (a ball swung with the stride isn't: dodging it frame by frame jerked the arm)+ if (gr.hands.length === 1 && !(pm && pm.id === gr.id)) {+ const v = outOfBody(skel, poses[f], field, false);+ if (len(v) > 0.002) { dodge[gr.hands[0]][f] = add(v, scale3(norm(v), 0.006)); carried[f] = gr.id; }+ }+ if (len(off) > 5e-4) {+ tr[f] = { ...tr[f], at: add(tr[f].at, off) };+ for (const s of gr.hands) { const g = goals.hands[s]; if (g) poses[f] = reach(skel, poses[f], s, { ...g, at: add(g.at, off) }); }+ }+ const f1 = (q: Vec3) => sdf(qrot(qinv(tr[f].rot), sub(q, tr[f].at)));+ if (gr.hands.length === 2) {+ // (a thing between two palms can't be pushed out of both: each hand drawn back out of it instead)+ // (a few times over: a reach lands within a centimetre, and the man's palms stayed that far into a shoe box)+ for (const s of gr.hands) {+ const g = goals.hands[s];+ let goal = g?.at;+ for (let k = 0; k < 3 && g && goal; k++) {+ let deep = 0, at: Vec3 | undefined;+ for (const x of handSurface(skel, pose(skel, poses[f]), s)) if (x.part === "palm" || x.part === "thumb1") { const d = -f1(x.at); if (d > deep) { deep = d; at = x.at; } }+ if (!at || deep <= 5e-4) break;+ goal = add(goal, scale3(fieldNormal(f1, at), deep + 0.001));+ poses[f] = reach(skel, poses[f], s, { ...g, at: goal });+ }+ }+ } else if (gr.guide && shapes[gr.hands[0]][f - 1]) {+ // (a hand on a guide: out of the hand as it last closed on it, its fingers round it; laid straight, the+ // knuckles' pads stand off the palm and pushed a can a centimetre and a half off it, out of the palm's reach)+ const hs = gr.hands[0], shaped = shapedHand(skel, poses[f], hs, gr.grip, shapes[hs][f - 1]!);+ tr[f] = { ...tr[f], at: add(tr[f].at, outOfHands(skel, shaped, gr.hands, f1, false)) };+ } else tr[f] = { ...tr[f], at: add(tr[f].at, outOfHands(skel, poses[f], gr.hands, f1, GRASP[gr.grip].on.length === 5)) };+ }+ const field2 = (q: Vec3) => sdf(qrot(qinv(tr[f].rot), sub(q, tr[f].at)));+ // (a thing in hand gripped fully, however freely the arm swings with it)+ for (const s of gr.hands) {+ const hand = { shape: shapes[s][f - 1] };+ poses[f] = graspThing(skel, poses[f], s, field2, gr.grip, gr.close, held ? 1 : gr.w, hand);+ shapes[s][f] = hand.shape;+ }+ if (held) (grasped[f] ??= []).push(gr);+ // (the hand's place on it locked as the thing is first held: the fingers closed and still (or six frames on), the+ // hand clear of it (not one taken from above to be looked at: turned palm up under it, locked, its fingers let a+ // ball go)+ const pinched = PINCHED.has(gr.grip) && gr.hands.length === 1;+ if (held && !locks.has(gr.id) && pinched) locks.set(gr.id, pinchLock(skel, pose(skel, poses[f]), tr[f].at, tr[f].rot, plan.items[gr.id].size, gr.hands[0]));+ else if (held && !pinched && gr.close >= 0.999 && (ready.set(gr.id, (ready.get(gr.id) ?? 0) + 1), depthIn(skel, poses[f], gr.hands, field2) <= 0.002)+ && gr.grip !== "top" && (gr.hands.every((s) => settled(shapes[s][f], shapes[s][f - 1])) || ready.get(gr.id)! >= 6)) {+ // (with the thing's push off where it was sent as it locked, let go over the frames after: dropped at once, a+ // shoe box jumped 16 cm in the hands)+ const l = lockOn(skel, pose(skel, poses[f]), tr[f].at, tr[f].rot, gr.hands, { L: shapes.L[f], R: shapes.R[f] }, leadOf(gr.hands, handling(plan.items[gr.id], h)));+ l.off = sub(tr[f].at, planned);+ locks.set(gr.id, l);+ }+ }+ const fieldNow = (q: Vec3) => sdf(qrot(qinv(tr[f].rot), sub(q, tr[f].at)));+ // the other hand out of its way (hanging where a wine glass is brought down to the table)+ for (const s of (["L", "R"] as Side[]).filter((x) => !gr.hands.includes(x))) {+ const w = pose(skel, poses[f]);+ let deep = 0, at: Vec3 | undefined;+ for (const x of handSurface(skel, w, s)) { const d = -fieldNow(x.at); if (d > deep) { deep = d; at = x.at; } }+ if (at && deep > 0.002) dodge[s][f] = scale3(fieldNormal(fieldNow, at), deep + 0.008);+ }+ }+ }+ easeDodges(skel, plan, poses, dodge, carried, tracks, grasped, shapes);+ return misses;+}diff --git a/sdk/character/src/items/interact.ts b/sdk/character/src/items/interact.tsindex 0a64bbeb..c5250d66 100644--- a/sdk/character/src/items/interact.ts+++ b/sdk/character/src/items/interact.ts@@ -1,9 +1,10 @@-// interact: the hands, the lean, the squat, the trunk, the gaze and the grip laid over a performance.+// interact: the hands, the lean, the squat, the trunk, the gaze and the grip laid over a performance (the things then+// fitted to the hands that have them: hold.ts).import type { Vec3 } from "raea/3d";-import { add, ballInHand, cross, dot, flatHand, handAlong, qbasis, blend as blendPose, qinv, handPose, handSurface, joint, len, norm, palmAt, palmFacing, pose, qaxis, qmul, qnorm, qrot, qyaw, reach, scale3, setWorld, slerp, solve, sub, type HandGoal, type HandShape, type Pose, type Quat, type Side, type Skeleton } from "raea/character";+import { B, add, ballInHand, flatHand, blend as blendPose, joint, norm, palmAt, pose, qaxis, qmul, qrot, qyaw, scale3, setWorld, slerp, solve, sub, type Pose, type Quat, type Side, type Skeleton } from "raea/character";import { type Performance } from "../matching";-import { handling, shapeOf, toLocal, type Handling, type Thing } from "../things";-import { type Attach, type Goals, type Grasp, HAND, halfOf, Beat, D, E, Flight, G, GRASP, Interaction, ItemPlan, P, QUICK_TWIST, S, T, THROW_HAND, THROW_LEN, Track, W, beatGeometry, clearWay, crouchDrop, crouched, easeDodges, eased, fieldNormal, fingers, flightTime, graspThing, launch, leanFor, mix, outOfBody, outOfHands, smooth, smoothCarries, span, stoop, thingSdf, throwAt, throwKeys, trunkTurn, uprightNear } from "./all";+import { shapeOf } from "../things";+import { type Attach, type Goals, HAND, halfOf, Beat, D, E, Flight, Interaction, ItemPlan, P, QUICK_TWIST, S, T, THROW_HAND, THROW_LEN, Track, W, beatGeometry, clearWay, crouchDrop, crouched, eased, fingers, flightTime, fly, holdThings, launch, leanFor, smooth, smoothCarries, span, throwAt, throwKeys, trunkTurn, type Work } from "./all";export function interact(skel: Skeleton, perf: Performance, plan: ItemPlan): Interaction {const { beatAt, chestY, dt, freeOf, grip, ground, guided, h, halves, handsOn, hipsY, holdOf, holdW, landing, lookPast, shoulderY, staticsOf, supportAt, toScene } = beatGeometry(skel, perf, plan);@@ -17,7 +18,7 @@ export function interact(skel: Skeleton, perf: Performance, plan: ItemPlan): Intconst startPalm = new Map<number, Record<Side, Vec3>>();// the frame each thing looked past was first carried fromconst heldFrom = new Map<Beat, number>();- const work: { p: Pose; goals: Goals; drop: number; stoop: number; attach: Attach[]; beat: boolean; palmed?: { id: string; hand: Side; w: number } }[] = [];+ const work: Work[] = [];for (let f = 0; f < perf.frames; f++) {const p = perf.pose(f), st = perf.step(f), b = st ? beatAt.get(st.index) : undefined, g = ground(f);@@ -69,7 +70,7 @@ export function interact(skel: Skeleton, perf: Performance, plan: ItemPlan): Int// a thing carried keeps the trunk upright: the walk's own stoop (a turn's, a stop's) stood back up, or the head// goes into a big thing and a wine glass is tipped at the face (a ball swung in one hand goes as the walk has it)if (hb.how.grip === "hug" || hb.how.grip === "cradle" || hb.how.grip === "edges" || hb.how.grip === "stem") {- const up = qrot(pose(skel, p).rot[joint(skel, "Spine1")], [0, 1, 0]), fw = qrot(qyaw(g.yaw), [0, 0, 1]);+ const up = qrot(pose(skel, p).rot[joint(skel, B.chest)], [0, 1, 0]), fw = qrot(qyaw(g.yaw), [0, 0, 1]);const stoop = Math.atan2(up[0] * fw[0] + up[2] * fw[2], up[1]);goals.pitch = Math.min(goals.pitch, (st.pitch - Math.max(0, stoop - 0.05)) * u);}@@ -156,7 +157,9 @@ export function interact(skel: Skeleton, perf: Performance, plan: ItemPlan): Intgoals.twist = toward * smooth(s / 0.4);// reaching: each hand from where it is to its place on the thing, round the furniture (over the edge of// a shelf, not through it), taken up at once (its goal starts where the hand is)- handsTo(b, mid0, rot0, smooth(s / 0.2), smooth((s - T.grip + 0.2) / 0.2));+ // (the goal's weight over the reach's own span (RAEA_REACH_FAST=1 for the old fifth of a second): taken up at+ // once, the hand's turn onto the thing went whole in 0.2 s, the wrist turning 20 degrees a frame on the cup)+ handsTo(b, mid0, rot0, process.env.RAEA_REACH_FAST === "1" ? smooth(s / 0.2) : span(s, [0, T.reach[1]]), smooth((s - T.grip + 0.2) / 0.2));for (const hs of b.hands) { const gh = goals.hands[hs]!; gh.at = clearWay(startPalm.get(b.step)![hs], gh.at, plan.things, HAND)(span(s, T.reach)); }track(b, mid0, rot0, false);} else {@@ -198,7 +201,10 @@ export function interact(skel: Skeleton, perf: Performance, plan: ItemPlan): Int// let go: the hands open, come up off it and back out over the edge to where the walk has them, and only// then are let go of (a hand let go of straight away swings down through the furniture)placed.set(b.item, { at: to.at, rot: qyaw(to.yaw) });- handsTo(b, mid1, rot1, 1 - span(s, [P.back[0] + 0.7 * (P.back[1] - P.back[0]), P.back[1]]), 1 - smooth((s - P.release) / 0.15));+ // (let go over the whole way back (RAEA_RELEASE_LATE=1 for over its last 30%): the hand's turn on the thing,+ // held to the end and dropped in a fifth of a second, swung the wrist 24 degrees a frame back to the walk's)+ const back0 = process.env.RAEA_RELEASE_LATE === "1" ? P.back[0] + 0.7 * (P.back[1] - P.back[0]) : P.back[0];+ handsTo(b, mid1, rot1, 1 - span(s, [back0, P.back[1]]), 1 - smooth((s - P.release) / 0.15));const home = natural();for (const hs of b.hands) { const gh = goals.hands[hs]!; gh.at = clearWay(add(gh.at, [0, 0.01, 0]), home[hs], plan.things, HAND)(span(s, P.back)); }now.set(b.item, { at: to.at, rot: qyaw(to.yaw), held: false });@@ -290,50 +296,7 @@ export function interact(skel: Skeleton, perf: Performance, plan: ItemPlan): Int}}}- // the things let go: falling and flying until they land, then a light ball bounces and rolls to a stop- for (const [id, fl] of flying) {- if (holding.has(id) || now.get(id)?.held) { flying.delete(id); continue; }- const it = plan.items[id], ball = shapeOf(it) === "ball", r = it.size[0] / 2;- if (!fl.landed) {- const next: Vec3 = [fl.at[0] + fl.vel[0] * dt, fl.at[1] + fl.vel[1] * dt - 0.5 * G * dt * dt, fl.at[2] + fl.vel[2] * dt];- const { y: floor, inside } = landing(next, fl.at[1]);- fl.vel = [fl.vel[0], fl.vel[1] - G * dt, fl.vel[2]];- const w = Math.hypot(...fl.spin);- if (w > 0) fl.rot = qmul(qaxis(scale3(fl.spin, 1 / w), w * dt), fl.rot);- if (next[1] <= floor) {- next[1] = floor;- const light = handling(it, h).weight === "light";- if (ball && light && !inside && fl.vel[1] < -1.2 && fl.bounces < 4) {- fl.vel = [fl.vel[0] * 0.7, -fl.vel[1] * 0.45, fl.vel[2] * 0.7];- fl.bounces++;- } else {- fl.landed = true;- fl.vel = ball && !inside ? [fl.vel[0] * 0.7, 0, fl.vel[2] * 0.7] : [0, 0, 0];- }- }- fl.at = next;- } else {- // a ball rolls (slowing), turning by the way it goes; anything else settles flat over a few frames- const sp = Math.hypot(fl.vel[0], fl.vel[2]);- if (ball && sp > 0.02) {- const k = Math.max(0, sp - 1.5 * dt) / sp;- fl.vel = [fl.vel[0] * k, 0, fl.vel[2] * k];- const next: Vec3 = [fl.at[0] + fl.vel[0] * dt, fl.at[1], fl.at[2] + fl.vel[2] * dt];- // it stops against anything standing in its way- if (plan.things.some((t) => t.at[1] < 0.02 && toLocal(t, next)[1] < t.size[1] && Math.abs(toLocal(t, next)[0]) < t.size[0] / 2 + r && Math.abs(toLocal(t, next)[2]) < t.size[2] / 2 + r)) fl.vel = [0, 0, 0];- else {- const axis: Vec3 = [fl.vel[2] / sp, 0, -fl.vel[0] / sp];- fl.rot = qmul(qaxis(axis, (sp * k * dt) / Math.max(0.01, r)), fl.rot);- fl.at = [next[0], supportAt(next, fl.at[1] + 0.01), next[2]];- }- } else if (!ball && fl.settle < 1) {- fl.settle = Math.min(1, fl.settle + 0.2);- fl.rot = slerp(fl.rot, uprightNear(fl.rot), fl.settle);- }- }- now.set(id, { at: fl.at, rot: fl.rot, held: false });- placed.set(id, { at: fl.at, rot: fl.rot });- }+ fly(flying, holding, now, placed, plan, h, dt, landing, supportAt);const hasHands = Object.keys(goals.hands).length > 0;// (a throw's knees are its style's: it doesn't squat to reach its wind-up)const need = hasHands && goals.weight > 0 && goals.squat ? crouchDrop(skel, p, goals.hands, goals.lean, goals.bend) : { drop: 0, stoop: 0 };@@ -343,7 +306,7 @@ export function interact(skel: Skeleton, perf: Performance, plan: ItemPlan): Int// the hips' drop and the stoop over the frames, eased (eased, below)// the stoop too, the same way (its least is as jumpy as the drop's, and tips the pelvis the legs hang from)const drops = eased(work.map((x) => x.drop)), stoops = eased(work.map((x) => x.stoop));- const poses: Pose[] = [], misses: number[] = [];+ const poses: Pose[] = [];for (let f = 0; f < work.length; f++) {let { p } = work[f];const { goals } = work[f];@@ -364,7 +327,7 @@ export function interact(skel: Skeleton, perf: Performance, plan: ItemPlan): Int// the free arm lifted out from the side, away from a load in the other handfor (const [s, a] of Object.entries(goals.abduct) as [Side, number][]) {if (!a || goals.hands[s]) continue;- const i = joint(skel, s === "L" ? "LeftArm" : "RightArm"), w = pose(skel, p);+ const i = joint(skel, B.upperarm(s)), w = pose(skel, p);p = setWorld(skel, p, w, i, qmul(qaxis(qrot(qyaw(g.yaw), [0, 0, 1]), s === "L" ? a : -a), w.rot[i]));}if (goals.look && goals.lookWeight > 0) p = solve(skel, p, { look: goals.look, lookWeight: goals.lookWeight });@@ -373,117 +336,7 @@ export function interact(skel: Skeleton, perf: Performance, plan: ItemPlan): Intposes.push(p);}smoothCarries(skel, poses, work);- // how far each hand not on a thing moves out of one in hand, frame by frame (dodged after, smoothed)- const dodge: Record<Side, (Vec3 | undefined)[]> = { L: [], R: [] };- // (and the thing a dodging hand carries, which goes with it)- const carried: (string | undefined)[] = [];- // (each frame's grasps of a thing in hand, to close again on it where the dodge moves the hand)- const grasped: { id: string; hands: Side[]; grip: Handling["grip"]; close: number }[][] = [];- // (and each hand's fingers' shape on it, frame by frame: a hand's fingers move on from the last frame's)- const shapes: Record<Side, (HandShape | undefined)[]> = { L: [], R: [] };- // (whether a thing's grip at a frame is one a guide placed the hand for)- const guidedGrip = (id: string, f: number) => work[f].goals.grasps.some((g) => g.id === id && g.guide);- for (let f = 0; f < work.length; f++) {- const p = poses[f], { goals } = work[f];- let miss = 0;- if (goals.weight >= 1) {- const w = pose(skel, p);- for (const [s, g] of Object.entries(goals.hands) as [Side, HandGoal][]) {- const at = g.point ? sub(g.at, scale3(norm(g.facing ?? [0, -1, 0]), 0.009 * h)) : g.at;- miss = Math.max(miss, len(sub(palmAt(skel, w, s), at)));- }- }- misses.push(miss);- if (work[f].attach.length) {- const w = pose(skel, p);- for (const a of work[f].attach) {- // (a flat hand's palm rests half its thickness off the goal, as reach puts it)- const goalOf = (g: HandGoal) => (g.point ? sub(g.at, scale3(norm(g.facing ?? [0, -1, 0]), 0.009 * h)) : g.at);- const tr = tracks.get(a.id)!, g1 = goals.hands[a.hands[0]]!;- if (a.hands.length === 1 && g1.point && guidedGrip(a.id, f)) {- // a thing on a guide in one hand rides it rigidly, turned with the hand as well as moved with it: the hand's- // frame where it is against where it was sent (a can carried by a hand swinging with the walk tips with it,- // and stays on the palm, not just as far from it)- const s = a.hands[0], n = norm(g1.facing ?? [0, -1, 0]), fp = norm(sub(g1.point, scale3(n, dot(g1.point, n))));- const na = palmFacing(skel, w, s), al = handAlong(skel, w, s), fa = norm(sub(al, scale3(na, dot(al, na))));- const turn = slerp([0, 0, 0, 1], qmul(qbasis(fa, na, cross(fa, na)), qinv(qbasis(fp, n, cross(fp, n)))), a.w);- const from = goalOf(g1), to = add(from, scale3(sub(palmAt(skel, w, s), from), a.w));- tr[f] = { ...tr[f], at: add(to, qrot(turn, sub(tr[f].at, from))), rot: qnorm(qmul(turn, tr[f].rot)) };- } else {- const off = a.hands.reduce<Vec3>((acc, s) => add(acc, scale3(sub(palmAt(skel, w, s), goalOf(goals.hands[s]!)), 1 / a.hands.length)), [0, 0, 0]);- tr[f] = { ...tr[f], at: add(tr[f].at, scale3(off, a.w)) };- }- }- }- // (a ball sat in the palm as it swings; anything else stays in its grip, a cup wrapped)- const pm = work[f].palmed && shapeOf(plan.items[work[f].palmed!.id]) === "ball" ? work[f].palmed : undefined;- if (pm) {- const it = plan.items[pm.id], tr = tracks.get(pm.id)!, r = Math.max(...it.size) / 2;- // (sat in the palm as far as it is in it: graspThing closes the fingers on it)- const w = pose(skel, poses[f]), mid = ballInHand(skel, w, pm.hand, r);- tr[f] = { ...tr[f], at: mix(tr[f].at, sub(mid, qrot(tr[f].rot, [0, it.size[1] / 2, 0])), pm.w) };- }- // each hand on a thing: the thing out of the hand's skin (a thing in hand moves; one still where it lies is- // reached to its surface), then each finger closed until it touches it, as far as the grip closes them- const grasps = goals.grasps.length ? goals.grasps : pm ? [{ id: pm.id, hands: [pm.hand], grip: "palm" as const, w: pm.w, close: 1 }] : [];- for (const gr of grasps) {- const tr = tracks.get(gr.id)!, held = tr[f].held || work[f].attach.some((a) => a.id === gr.id) || pm?.id === gr.id;- const sdf = thingSdf(plan.items[gr.id]);- const field = (q: Vec3) => sdf(qrot(qinv(tr[f].rot), sub(q, tr[f].at)));- if (held) {- // (a thing against the body out of its trunk, head and thighs, the hands brought with it; a small thing in one- // hand swings past the thigh as the arm does)- const off = gr.hands.length === 2 ? outOfBody(skel, poses[f], field) : [0, 0, 0] as Vec3;- // (one in one hand swung into the thigh or the waist: the hand and it dodged out, smoothed after)- // (a ball swung with the stride isn't: dodging it frame by frame jerked the arm)- if (gr.hands.length === 1 && !(pm && pm.id === gr.id)) {- const v = outOfBody(skel, poses[f], field, false);- if (len(v) > 0.002) { dodge[gr.hands[0]][f] = add(v, scale3(norm(v), 0.006)); carried[f] = gr.id; }- }- if (len(off) > 5e-4) {- tr[f] = { ...tr[f], at: add(tr[f].at, off) };- for (const s of gr.hands) { const g = goals.hands[s]; if (g) poses[f] = reach(skel, poses[f], s, { ...g, at: add(g.at, off) }); }- }- const f1 = (q: Vec3) => sdf(qrot(qinv(tr[f].rot), sub(q, tr[f].at)));- if (gr.hands.length === 2) {- // (a thing between two palms can't be pushed out of both: each hand drawn back out of it instead)- // (a few times over: a reach lands within a centimetre, and the man's palms stayed that far into a shoe box)- for (const s of gr.hands) {- const g = goals.hands[s];- let goal = g?.at;- for (let k = 0; k < 3 && g && goal; k++) {- let deep = 0, at: Vec3 | undefined;- for (const x of handSurface(skel, pose(skel, poses[f]), s)) if (x.part === "palm" || x.part === "thumb1") { const d = -f1(x.at); if (d > deep) { deep = d; at = x.at; } }- if (!at || deep <= 5e-4) break;- goal = add(goal, scale3(fieldNormal(f1, at), deep + 0.001));- poses[f] = reach(skel, poses[f], s, { ...g, at: goal });- }- }- } else if (gr.guide && shapes[gr.hands[0]][f - 1]) {- // (a hand on a guide: out of the hand as it last closed on it, its fingers round it; laid straight, the- // knuckles' pads stand off the palm and pushed a can a centimetre and a half off it, out of the palm's reach)- const hs = gr.hands[0], shaped = handPose(skel, poses[f], hs, shapes[hs][f - 1]!);- tr[f] = { ...tr[f], at: add(tr[f].at, outOfHands(skel, shaped, gr.hands, f1, false)) };- } else tr[f] = { ...tr[f], at: add(tr[f].at, outOfHands(skel, poses[f], gr.hands, f1, GRASP[gr.grip].on.length === 5)) };- }- const field2 = (q: Vec3) => sdf(qrot(qinv(tr[f].rot), sub(q, tr[f].at)));- // (a thing in hand gripped fully, however freely the arm swings with it)- for (const s of gr.hands) {- const hand = { shape: shapes[s][f - 1] };- poses[f] = graspThing(skel, poses[f], s, field2, gr.grip, gr.close, held ? 1 : gr.w, hand);- shapes[s][f] = hand.shape;- }- if (held) (grasped[f] ??= []).push(gr);- // the other hand out of its way (hanging where a wine glass is brought down to the table)- for (const s of (["L", "R"] as Side[]).filter((x) => !gr.hands.includes(x))) {- const w = pose(skel, poses[f]);- let deep = 0, at: Vec3 | undefined;- for (const x of handSurface(skel, w, s)) { const d = -field2(x.at); if (d > deep) { deep = d; at = x.at; } }- if (at && deep > 0.002) dodge[s][f] = scale3(fieldNormal(field2, at), deep + 0.008);- }- }- }- easeDodges(skel, plan, poses, dodge, carried, tracks, grasped, shapes);+ const misses = holdThings(skel, plan, h, poses, work, tracks);const at = <X,>(a: X[], f: number) => a[Math.max(0, Math.min(a.length - 1, Math.round(f)))];return {frames: perf.frames,diff --git a/sdk/character/src/items/lock.ts b/sdk/character/src/items/lock.tsnew file mode 100644index 00000000..4f4ae1dc--- /dev/null+++ b/sdk/character/src/items/lock.ts@@ -0,0 +1,126 @@+// A grip's lock: once a hand has closed on a thing, where it holds it and how its fingers lie are fixed for as long+// as it is held, so nothing is fitted again frame by frame (Shane, 11-01: "a lot of the hand placement on an object+// does tend to recompute constantly and makes it look like the hands are glitching, especially with bigger objects").+//+// Which leads is the thing's weight and size (handling): a light thing in one hand rides the hand, turned and moved+// with it however the arm swings; a thing in two hands, or one heavy for the body, leads, and the arms reach to their+// locked places on it (the thing joins the arms' IK as their goal).+import type { Vec3 } from "raea/3d";+import { add, cross, dot, handAlong, handPose, handSurface, norm, palmAt, palmFacing, pinchPoint, pose, qbasis, qinv, qmul, qnorm, qrot, reach, scale3, sub, type HandGoal, type HandShape, type Pose, type Quat, type Side, type Skeleton } from "raea/character";+import type { Handling } from "../things";++type Posed = ReturnType<typeof pose>;++/** one hand's hold in the thing's frame: the palm's middle, the way it faces and the fingers point, and their shape */+export interface HandLock { at: Vec3; facing: Vec3; along: Vec3; shape: HandShape }++export interface Lock {+ /** "hand": the thing rides the hand; "thing": the hands reach to it */+ lead: "hand" | "thing";+ hands: Partial<Record<Side, HandLock>>;+ /** the thing's push out of the body, eased over the frames (it jumped frame to frame when taken raw) */+ off: Vec3;+ /** how far the thing still has to slide into the hand (a pinch's pads), let go over the frames */+ slide?: Vec3;+}++/** the grips taken between the thumb's pad and the fingers' (pinchPoint): a pinched thing sits there */+export const PINCHED = new Set(["pinch", "tripod"]);++/**+ * A pinch's lock, as soon as the thing is taken: the thing (its middle `size[1] / 2` up from `at`) placed where the+ * captured pinch's pads meet in hand `s`, sliding there from where it is over the frames after (`slide`). A reach+ * lands within a few centimetres, and the pads closed on air beside a pencil and carried it under the fist (11-01).+ */+export function pinchLock(skel: Skeleton, w: Posed, at: Vec3, rot: Quat, size: Vec3, s: Side): Lock {+ const facing = norm(palmFacing(skel, w, s)), along = norm(handAlong(skel, w, s));+ const across = s === "R" ? cross(along, facing) : cross(facing, along), [pa, pp, pc] = pinchPoint(skel, s);+ const pads = add(palmAt(skel, w, s), add(add(scale3(along, pa), scale3(facing, pp)), scale3(across, pc)));+ const to = sub(pads, qrot(rot, [0, size[1] / 2, 0]));+ const l = lockOn(skel, w, to, rot, [s], {}, "hand");+ l.slide = sub(at, to);+ return l;+}++/** a thing ridden by its hand (`ridden`), still sliding into it by what's left of `l.slide`, eased a frame */+export function riddenSliding(skel: Skeleton, w: Posed, s: Side, l: Lock): { at: Vec3; rot: Quat } {+ const r = ridden(skel, w, s, l.hands[s]!);+ if (!l.slide) return r;+ l.slide = Math.hypot(...l.slide) < 1e-4 ? undefined : easeOff(l.slide, [0, 0, 0]);+ return l.slide ? { ...r, at: add(r.at, l.slide) } : r;+}++/** the lead for a grip: one light hand's thing goes with the hand, anything else leads the arms */+export const leadOf = (hands: Side[], how: Handling): Lock["lead"] => (hands.length === 1 && how.weight === "light" ? "hand" : "thing");++/** the hand's frame (fingers along, palm facing, and across), squared */+function handFrame(facing: Vec3, along: Vec3): Quat {+ const n = norm(facing), a = norm(sub(along, scale3(n, dot(along, n))));+ return qbasis(a, n, cross(a, n));+}++/** the lock of the hands on a thing at `at`, turned `rot`, as the pose `w` has them and their fingers `shapes` */+export function lockOn(skel: Skeleton, w: Posed, at: Vec3, rot: Quat, hands: Side[], shapes: Partial<Record<Side, HandShape>>, lead: Lock["lead"]): Lock {+ const inv = qinv(rot), out: Lock = { lead, hands: {}, off: [0, 0, 0] };+ for (const s of hands) {+ out.hands[s] = {+ at: qrot(inv, sub(palmAt(skel, w, s), at)),+ facing: qrot(inv, palmFacing(skel, w, s)),+ along: qrot(inv, handAlong(skel, w, s)),+ shape: shapes[s] ?? {},+ };+ }+ return out;+}++/** a hand's goal on the thing where it is now: its locked place, moved and turned with it */+export function lockedGoal(skel: Skeleton, l: HandLock, at: Vec3, rot: Quat, elbow?: Vec3): HandGoal {+ const facing = qrot(rot, l.facing);+ // (reach rests a flat hand's palm half its thickness short of the goal along the way it faces)+ return { at: add(add(at, qrot(rot, l.at)), scale3(norm(facing), 0.009 * skel.height)), facing, point: qrot(rot, l.along), elbow };+}++/** where a thing ridden by hand `s` is, the hand as the pose `w` has it: its locked frame in the hand carried over */+export function ridden(skel: Skeleton, w: Posed, s: Side, l: HandLock): { at: Vec3; rot: Quat } {+ const now = handFrame(palmFacing(skel, w, s), handAlong(skel, w, s)), was = handFrame(l.facing, l.along);+ const rot = qnorm(qmul(now, qinv(was)));+ return { at: sub(palmAt(skel, w, s), qrot(rot, l.at)), rot };+}++/** the arms reached to their locked places on a thing that leads, and how far the palms still miss them (the+ * thing is moved that far after, so it stays in the hands: a reach lands within a centimetre) */+export function reachLocked(skel: Skeleton, p: Pose, lock: Lock, at: Vec3, rot: Quat, elbows: Partial<Record<Side, Vec3 | undefined>>): { p: Pose; miss: Vec3 } {+ const sides = Object.keys(lock.hands) as Side[];+ for (const s of sides) p = reach(skel, p, s, lockedGoal(skel, lock.hands[s]!, at, rot, elbows[s]));+ const w = pose(skel, p);+ let miss: Vec3 = [0, 0, 0];+ for (const s of sides) miss = add(miss, scale3(sub(palmAt(skel, w, s), add(at, qrot(rot, lock.hands[s]!.at))), 1 / sides.length));+ return { p, miss };+}++/** the push out of the body eased: taken at once when it grows, let back over a few frames when it shrinks */+export function easeOff(prev: Vec3, raw: Vec3): Vec3 {+ const lp = Math.hypot(...prev), lr = Math.hypot(...raw);+ return lr >= lp ? raw : [prev[0] + (raw[0] - prev[0]) * 0.2, prev[1] + (raw[1] - prev[1]) * 0.2, prev[2] + (raw[2] - prev[2]) * 0.2];+}++/** whether a hand's fingers have stopped closing: no joint's curl moved more than `tol` (radians) since the frame+ * before (locked while still closing, a pinch froze open on a pencil and never held it) */+export function settled(now?: HandShape, was?: HandShape, tol = 0.01): boolean {+ if (!now || !was) return false;+ for (const k of ["thumb", "index", "middle", "ring", "pinky"] as const) {+ const a = now[k] ?? [0, 0, 0], b = was[k] ?? [0, 0, 0];+ if (a.some((x, i) => Math.abs(x - b[i]) > tol)) return false;+ }+ return Math.abs((now.spread ?? 0) - (was.spread ?? 0)) <= tol && Math.abs((now.thumbOpp ?? 0) - (was.thumbOpp ?? 0)) <= tol;+}++/** how far the hands' skin is into a thing (its distance field `field`): a grip locks only clear of it */+export function depthIn(skel: Skeleton, p: Pose, hands: Side[], field: (q: Vec3) => number): number {+ const w = pose(skel, p);+ let deep = 0;+ for (const s of hands) for (const x of handSurface(skel, w, s)) deep = Math.max(deep, -field(x.at));+ return deep;+}++diff --git a/sdk/character/src/items/passes.ts b/sdk/character/src/items/passes.tsindex 3fefce7b..1d1ac048 100644--- a/sdk/character/src/items/passes.ts+++ b/sdk/character/src/items/passes.ts@@ -1,6 +1,6 @@// interact's passes over the frames, a way clear of things, and a throw's keys and flight.import type { Vec3 } from "raea/3d";-import { add, qinv, joint, len, palmAt, pose, qnorm, qrot, qyaw, reach, rest, scale3, sub, type HandShape, type Pose, type Quat, type Side, type Skeleton } from "raea/character";+import { B, add, qinv, joint, len, palmAt, pose, qnorm, qrot, qyaw, reach, rest, scale3, sub, type HandShape, type Pose, type Quat, type Side, type Skeleton } from "raea/character";import { surfacesOf, toLocal, type Handling, type Thing } from "../things";import { Beat, G, ItemPlan, LAUNCH, ThrowStyle, Track, W, graspThing, mix, smooth, thingSdf } from "./all";@@ -22,7 +22,7 @@ export function eased(v: number[], R = 10) {export function smoothCarries(skel: Skeleton, poses: Pose[], work: { attach: { w: number; hands: Side[] }[]; goals: { hands: Partial<Record<Side, { at: Vec3 }>> } }[]) {const carries = (f: number, s: Side) => work[f].attach.some((a) => a.w >= 1 && a.hands.includes(s));for (const s of ["L", "R"] as Side[]) {- const js = ["Arm", "ForeArm", "Hand"].map((x) => joint(skel, (s === "L" ? "Left" : "Right") + x));+ const js = B.arm(s).map((x) => joint(skel, x));for (let pass = 0; pass < 2; pass++) {const was = poses.map((q) => js.map((j) => q.turns[j]));for (let f = 1; f + 1 < poses.length; f++) {diff --git a/sdk/character/src/items/plan.ts b/sdk/character/src/items/plan.tsindex 036f921f..073c37d5 100644--- a/sdk/character/src/items/plan.ts+++ b/sdk/character/src/items/plan.ts@@ -1,6 +1,6 @@// planItems: the walks, reaches and waits that do the tasks.import type { Vec3 } from "raea/3d";-import { bodyScale, joint, len, qrot, qyaw, sub, type Side } from "raea/character";+import { B, bodyScale, joint, len, qrot, qyaw, sub, type Side } from "raea/character";import { route, type MotionLibrary, type Obstacle, type Step } from "../matching";import { handling, obstacleDistance, placeOn, shapeOf, standAt, surfacesOf, thingObstacles, toLocal, toWorld, under, type Handling, type Thing } from "../things";import { Beat, D, E, Item, ItemPlan, ItemTask, P, S, T, THROW_LEN, autoStyle, clipMove, gripTurn, reachAhead, wrap } from "./all";@@ -11,7 +11,15 @@ export function planItems(lib: MotionLibrary, start: { at: Vec3; facing: numberconst h = lib.skel.height, steps: Step[] = [], beats: Beat[] = [];const looks: number[] = [];const named = o.things && !Array.isArray(o.things) ? o.things : {};- const furniture = Array.isArray(o.things) ? o.things : Object.values(named);+ const furniture = [...(Array.isArray(o.things) ? o.things : Object.values(named))];+ // every seat the plan sits on is in the way of its walks (RAEA_SEAT_OBSTACLE=0 not): unknown to the routes, errands'+ // walk to the chair's front from behind it went straight through it, the feet 15 cm into its base+ if (process.env.RAEA_SEAT_OBSTACLE !== "0") for (const t of tasks) {+ const sit = "step" in t ? (t.step as { sit?: { at: Vec3; facing: number | Vec3 } }).sit : undefined;+ if (!sit) continue;+ const fy = typeof sit.facing === "number" ? sit.facing : Math.atan2(sit.facing[0] - sit.at[0], sit.facing[2] - sit.at[2]);+ furniture.push({ at: [sit.at[0], 0, sit.at[2]], size: [0.48, sit.at[1], 0.48], yaw: fy });+ }let x = start.at[0], z = start.at[2], yaw = start.facing;const holding = new Map<string, Beat>();const carried = () => [...holding.values()].reduce((a, b) => a + b.how.load, 0);@@ -19,8 +27,8 @@ export function planItems(lib: MotionLibrary, start: { at: Vec3; facing: number// walk from walks, and a heavy thing takes the whole body from carries; a library without tags plays the step whole)// (a thing in one hand: that hand low at its side, as interact's hold has it, so a suitcase's carry is played rather// than a box's, the hands before the chest)- const SJ = lib.skel.joints, shY = SJ[joint(lib.skel, "LeftArm")].head[1];- const armL = len(sub(SJ[joint(lib.skel, "LeftForeArm")].head, SJ[joint(lib.skel, "LeftArm")].head)) + len(sub(SJ[joint(lib.skel, "LeftHand")].head, SJ[joint(lib.skel, "LeftForeArm")].head));+ const SJ = lib.skel.joints, shY = SJ[joint(lib.skel, B.upperarm("L"))].head[1];+ const armL = len(sub(SJ[joint(lib.skel, B.lowerarm("L"))].head, SJ[joint(lib.skel, B.upperarm("L"))].head)) + len(sub(SJ[joint(lib.skel, B.hand("L"))].head, SJ[joint(lib.skel, B.lowerarm("L"))].head));const held = (): Pick<Extract<Step, { walk: unknown }>, "tags" | "limbs"> => {if (!holding.size) return {};const hands: Partial<Record<Side, Vec3>> = {}, clear: Partial<Record<Side, number>> = {};@@ -230,7 +238,14 @@ export function planItems(lib: MotionLibrary, start: { at: Vec3; facing: numberx = e[0]; z = e[1];} else if ("step" in t) {steps.push(t.step);- x = t.at[0]; z = t.at[1]; yaw = t.face;+ const sit = (t.step as { sit?: { at: Vec3; facing: number | Vec3 } }).sit;+ if (sit && process.env.RAEA_SEAT_OBSTACLE !== "0") {+ // stood up, a step forward clear of it before turning anywhere (turned on the spot at its front, the turn's+ // steps went back into it)+ const out: [number, number] = [t.at[0] + Math.sin(t.face) * 0.45, t.at[1] + Math.cos(t.face) * 0.45];+ steps.push({ walk: [[t.at[0], t.at[1]], out], speed: 0.8, ...held() });+ x = out[0]; z = out[1]; yaw = t.face;+ } else { x = t.at[0]; z = t.at[1]; yaw = t.face; }} else if (t.face !== undefined) {steps.push({ wait: t.wait, face: t.face, slack, ...held() });yaw = t.face;diff --git a/sdk/character/src/lint.ts b/sdk/character/src/lint.tsindex f6b31b60..8164601a 100644--- a/sdk/character/src/lint.ts+++ b/sdk/character/src/lint.ts@@ -12,7 +12,7 @@// finding is measured again at every stage of the performance (the clip's frame as chosen, blended in, the feet// planted, the elbows relaxed, the gaze), and the first stage where it shows is the one that made it.import type { Quat } from "raea/character";-import { captured, joint, qinv, qmul, qrot, qyaw, type Pose, type Skeleton } from "raea/character";+import { B, isFinger, sideOf as sideOfJoint, captured, joint, qinv, qmul, qrot, qyaw, type Pose, type Skeleton } from "raea/character";import { framePose } from "./clip";import { qlog } from "./effects";import type { MotionLibrary, Performance } from "./matching";@@ -51,7 +51,7 @@ function localTurn(p: Pose, i: number): Quat {/** a joint's turn from one frame to the next, as a rotation vector (radians) */const step = (a: Pose, b: Pose, i: number) => qlog(qmul(qinv(localTurn(a, i)), localTurn(b, i)));const DEG = 180 / Math.PI;-const watched = (name: string) => !/Finger|Thumb/.test(name);+const watched = (name: string) => !isFinger(name);const refs = new WeakMap<MotionLibrary, { speed: number[]; jerk: number[] }>();/** each joint's 99.5th percentile turn speed and change of speed over the library's frames (degrees a frame) */@@ -80,7 +80,7 @@ function libraryLimits(lib: MotionLibrary): { speed: number[]; jerk: number[] }/** a knee's bend, degrees: the shin's turn at the knee (at rest the leg is straight) */function kneeBend(skel: Skeleton, p: Pose, side: 0 | 1): number {- return Math.hypot(...qlog(localTurn(p, joint(skel, side ? "RightLeg" : "LeftLeg")))) * DEG;+ return Math.hypot(...qlog(localTurn(p, joint(skel, side ? B.calf("R") : B.calf("L"))))) * DEG;}/** Lint a performance made with `trace: true` (see the head of the file). */@@ -89,7 +89,7 @@ export function motionLint(lib: MotionLibrary, perf: Performance, o: { margin?:if (!tr) throw new Error("motionLint: perform with { trace: true }");const skel = lib.skel, lim = libraryLimits(lib), m = o.margin ?? 1.25, n = perf.frames;const names = skel.joints.slice(0, captured(skel)).map((j) => j.name);- const sideOf = (name: string): 0 | 1 | -1 => (/^(Left|L[A-Z])/.test(name) ? 0 : /^(Right|R[A-Z])/.test(name) ? 1 : -1);+ const sideOf = (name: string): 0 | 1 | -1 => (sideOfJoint(name) === "L" ? 0 : sideOfJoint(name) === "R" ? 1 : -1);const metric = (st: Stage, t: number, i: number, kind: "speed" | "jerk") => {const P = tr.stages[st];if (t < 2 || t >= P.length) return 0;@@ -103,7 +103,7 @@ export function motionLint(lib: MotionLibrary, perf: Performance, o: { margin?:return kind === "speed" ? Math.max(2, lim.speed[i] * r * m) : Math.max(1.5, lim.jerk[i] * r * r * m * 1.2);};const causes = (t: number, name: string): string[] => {- const out: string[] = [], side = sideOf(name), leg = /UpLeg|Leg$|Foot|Toe|Hips/.test(name);+ const out: string[] = [], side = sideOf(name), leg = /^(thigh|calf|foot|ball)_|^pelvis$/.test(name);for (const s of tr.switches) if (Math.abs(s - t) <= 3) out.push(`clip switch @${s}`);if (tr.plant) {for (const e of tr.plant.events) if (Math.abs(e.t - t) <= 3 && leg && (side < 0 || side === e.foot)) out.push(`${e.foot ? "R" : "L"} ${e.what} @${e.t}`);@@ -132,7 +132,7 @@ export function motionLint(lib: MotionLibrary, perf: Performance, o: { margin?:}// buckles: a standing knee folded well past the clip's ownif (tr.plant) for (const s of [0, 1] as const) {- const ki = joint(skel, s ? "RightLeg" : "LeftLeg");+ const ki = joint(skel, s ? B.calf("R") : B.calf("L"));for (let t = 0; t < n; t++) {if (tr.plant.state[s][t] === "swing") continue;const over = kneeBend(skel, tr.stages.gaze[t], s) - kneeBend(skel, tr.stages.blend[t], s);diff --git a/sdk/character/src/lock.ts b/sdk/character/src/lock.tsnew file mode 100644index 00000000..43766ec5--- /dev/null+++ b/sdk/character/src/lock.ts@@ -0,0 +1,261 @@+// Contact-locked feet (the standard game method: Holden's "contact locking" in his motion-matching notes, after+// Bollo's inertialization talk): each foot is held where it touched down for as long as the library says it stands,+// and let go into its swing through a critically damped spring, so the offset the lock built up fades without a jump in+// place or speed. The leg reaches its foot by analytic two-bone IK (soft near full stretch); the foot keeps the clip's+// own turn, so the heel lifts and the ball pivots as the capture's did.+//+// The lock is an offset on the clip's ankle, never a place of its own: at touchdown the offset is whatever the last+// release left (so landing never jumps), while standing it grows by exactly what the clip's pivot slides (so the pivot+// stays put), and when the pivot moves from the heel to the ball the new lock is taken where the ball already is.+import type { Vec3 } from "raea/3d";+import { joint, pose, qinv, qmul, qnorm, qrot, qyaw, setWorld, twoBone, type Pose, type Quat, type Skeleton } from "raea/character";+import { LEGS, feetOf, kneePole, rests, standing } from "./feet";+import { qlog } from "./effects";++/** What lockFeet did per frame and foot, for checks and the debug overlay: whether it stood, on which pivot, the+ * locked spot (null in a swing), the ankle's target and where the solved ankle reached. */+export interface LockLog {+ stand: boolean[][];+ pivot: ("heel" | "ball" | null)[][];+ lock: ([number, number] | null)[][];+ target: Vec3[][];+ reached: Vec3[][];+ clip: Vec3[][];+}++export interface LockOptions {+ /** the release spring's half-life, as a share of the swing it fades over (and never over `maxHalf` seconds) */+ half?: number;+ maxHalf?: number;+ /** a heel sole more than this far over the ball's (m, on a 1.75 m body) has lifted: the ball is the pivot */+ heelUp?: number;+ log?: LockLog;+ /** a sole on the floor slower than this (m/s) stands, whatever the clip says */+ slow?: number;+ /** frames over which a landing foot slows onto its spot (3) */+ land?: number;+ /** passes of the legs' jerk easing (3) */+ ease?: number;+ /** how far behind the ankle the heel's point is, as a share of the ankle-to-ball run (0.36) */+ heelBack?: number;+ /** how far (body-height share, 0.03) a lock may get from where the clip has its foot before it lets go */+ radius?: number;+ /** the most of its length a standing leg is let reach before the hips come down (0.97; 1 never lowers them) */+ fold?: number;+}++/** a critically damped spring's offset and speed `t` seconds after release from x0 moving at v0 (half-life h) */+function decay(x0: number, v0: number, h: number, t: number): number {+ const y = (2 * Math.LN2) / Math.max(1e-4, h), j = v0 + x0 * y;+ return Math.exp(-y * t) * (x0 + j * t);+}++/** Each foot locked through its contacts and released on a spring; the legs solved to reach. `hint` is the clip's own+ * contacts per frame (see plantFeet). */+export function lockFeet(skel: Skeleton, raw: Pose[], hint?: [number, number][], fps = 30, o: LockOptions = {}): Pose[] {+ const n = raw.length;+ if (!n) return raw;+ const r = rests(skel), z = r.z, dt = 1 / fps;+ const half = o.half ?? 0.25, maxHalf = o.maxHalf ?? 0.12, heelUp = (o.heelUp ?? 0.01) * z;+ const radius = (o.radius ?? Number(process.env.RAEA_LOCK_RADIUS ?? 0.03)) * z;+ const feet = raw.map((p) => feetOf(skel, p));+ // the soles: the floor points under the heel (the ankle) and the ball, turned with the foot, and their heights+ const J = skel.joints, ai = LEGS.map((l) => joint(skel, l[2])), bi = LEGS.map((l) => joint(skel, l[3]));+ // (the heel's point is its back, where a foot strikes and rolls: 0.36 of the ankle-to-ball run behind the ankle, as+ // the body's foot surface has it; under the ankle, the locked point swung 3 cm forward as the foot rolled flat, and+ // the knee kinked 5 degrees at every landing)+ const back = [0, 1].map((s) => { const a = J[ai[s]].head, b = J[bi[s]].head, k = (o.heelBack ?? Number(process.env.RAEA_HEEL_BACK ?? 0.36)); return [-(b[0] - a[0]) * k, -a[1], -(b[2] - a[2]) * k] as Vec3; });+ const soles = raw.map((p) => { const w = pose(skel, p); return [0, 1].map((s) => [ai[s], bi[s]].map((i, k) => { const v = qrot(w.rot[i], k ? [0, -J[i].head[1], 0] : back[s]); return [w.pos[i][0] + v[0], w.pos[i][1] + v[1], w.pos[i][2] + v[2]] as Vec3; })); });+ const low = (t: number, s: number) => Math.min(soles[t][s][0][1], soles[t][s][1][1]);+ const speed = (t: number, s: number, k: number) => { const a = soles[Math.max(0, t - 1)][s][k], b = soles[Math.min(n - 1, t + 1)][s][k]; return (Math.hypot(b[0] - a[0], b[2] - a[2]) * fps) / (t > 0 && t < n - 1 ? 2 : 1); };+ // standing: where the clip says so, and wherever a sole is on the floor (under 2 cm) and slow (0.6 m/s): a capture's+ // foot lands before its contact says and skims after it; gaps of two frames filled, stands under three frames dropped+ const stand = standing(skel, feet, hint, fps, raw.map((p) => p.root)).map((c, s) => c.map((v, t) => v || (low(t, s) < 0.02 * z && Math.min(speed(t, s, 0), speed(t, s, 1)) < (o.slow ?? Number(process.env.RAEA_LOCK_SLOW ?? 0.6)) * z)));+ for (const c of stand) {+ for (let t = 1; t < n - 1; t++) if (!c[t] && c[t - 1]) { let e = t; while (e < n && !c[e]) e++; if (e < n && e - t <= 2) for (let k = t; k < e; k++) c[k] = true; t = e; }+ for (let t = 0; t < n; t++) if (c[t]) { let e = t; while (e < n && c[e]) e++; if (e - t < 3) for (let k = t; k < e; k++) c[k] = false; t = e; }+ }+ // each standing foot's turn (yaw) locked too, from touchdown until it is up on its ball (a foot flat on the floor+ // turned with the body swept its ball 3 cm round its heel), then held while it turns on the ball, and let go on the+ // spring; the soles turned with it about the ankle+ const yawOf = (t: number, s: number) => { const [h, b] = soles[t][s]; return Math.atan2(b[0] - h[0], b[2] - h[2]); };+ const wrapA = (a: number) => Math.atan2(Math.sin(a), Math.cos(a));+ const yo: number[][] = [[], []], onBallAt: boolean[][] = [[], []];+ for (let s = 0; s < 2; s++) {+ let lockYaw: number | null = null, onBall = false, rel: { at: number; x0: number; v0: number; h: number } | null = null;+ for (let t = 0; t < n; t++) {+ const [heel, ballP] = soles[t][s], prev = t ? yo[s][t - 1] : 0;+ if (stand[s][t]) {+ rel = null;+ onBall = (lockYaw !== null && onBall) || heel[1] > ballP[1] + heelUp;+ if (lockYaw === null) lockYaw = (t ? yawOf(t - 1, s) : yawOf(t, s)) + prev;+ if (onBall) lockYaw = yawOf(t, s) + prev; // (held: the clip turns it on its ball)+ yo[s].push(onBall ? prev : wrapA(lockYaw - yawOf(t, s)));+ onBallAt[s].push(onBall);+ continue;+ }+ onBallAt[s].push(false);+ if (lockYaw !== null) {+ const a = yo[s][t - 1], b = yo[s][Math.max(0, t - 2)];+ let e = t; while (e < n && !stand[s][e]) e++;+ rel = { at: t - 1, x0: a, v0: (a - b) / dt, h: Math.min(maxHalf, (e - t) * dt * half) };+ lockYaw = null; onBall = false;+ }+ yo[s].push(rel ? decay(rel.x0, rel.v0, rel.h, (t - rel.at) * dt) : 0);+ }+ for (let t = 0; t < n; t++) if (Math.abs(yo[s][t]) > 1e-6) {+ const an = feet[t][s].ankle, Q = qyaw(yo[s][t]);+ soles[t][s] = soles[t][s].map((p) => { const v = qrot(Q, [p[0] - an[0], p[1] - an[1], p[2] - an[2]]); return [an[0] + v[0], an[1] + v[1], an[2] + v[2]] as Vec3; });+ }+ }+ const off: Vec3[][] = [[], []];+ for (let s = 0; s < 2; s++) {+ let lock: [number, number] | null = null, onBall = false;+ let rel: { at: number; x0: Vec3; v0: Vec3; h: number } | null = null;+ for (let t = 0; t < n; t++) {+ const [heel, ballP] = soles[t][s], prev = t ? off[s][t - 1] : ([0, 0, 0] as Vec3);+ if (stand[s][t]) {+ rel = null;+ // the pivot: the heel until it is `heelUp` over the ball (the foot rolling forward), then the ball to the end+ const ball = onBallAt[s][t];+ const pivot = ball ? ballP : heel;+ if (!lock || ball !== onBall) {+ // touchdown, or the heel lifting: the lock taken where the (offset) pivot is now, so nothing moves this frame+ const was = t ? soles[t - 1][s][ball ? 1 : 0] : pivot;+ lock = t ? [was[0] + prev[0], was[2] + prev[2]] : [pivot[0], pivot[2]];+ onBall = ball;+ }+ if (o.log) { o.log.pivot[s][t] = ball ? "ball" : "heel"; o.log.lock[s][t] = [lock[0], lock[1]]; }+ // (the pivot on the floor; on the ball, the heel kept 1.6 cm up: a foot turning on its ball swept its heel round+ // across the floor)+ const o3: Vec3 = [lock[0] - pivot[0], ball ? Math.max(-pivot[1], 0.016 * z - heel[1]) : -pivot[1], lock[1] - pivot[2]];+ // let go once the lock is `radius` from where the clip has the foot (Holden's unlock radius): the body carried on+ // while a ball stayed locked, the leg stretched 5 to 14 cm short of it, and then snapped into the swing+ if (Math.hypot(o3[0], o3[2]) > radius && t > 0) {+ // (for a few frames, RAEA_LOCK_RELOCK (4; 0 for the rest of the stand), then it may lock again where it is once the clip's sole is slow (0.15 m/s): let+ // go for the whole stand, a pick-up's standing foot followed the clip's 3 cm wobble held up off the floor)+ const re = Number(process.env.RAEA_LOCK_RELOCK ?? 4);+ for (let e = t; e < n && stand[s][e]; e++) {+ let left = 0; while (e + left < n && stand[s][e + left]) left++;+ if (re > 0 && e >= t + re && left >= 5 && Math.min(speed(e, s, 0), speed(e, s, 1)) < 0.15 * z) break;+ stand[s][e] = false;+ }+ } else {+ off[s].push(o3);+ continue;+ }+ }+ if (o.log) { o.log.pivot[s][t] = null; o.log.lock[s][t] = null; }+ if (lock) {+ // let go: the spring starts from the offset and the speed it had over the stand's last frames+ const a = off[s][t - 1], b = off[s][Math.max(0, t - 2)];+ let e = t; while (e < n && !stand[s][e]) e++;+ rel = { at: t - 1, x0: a, v0: [0, 1, 2].map((k) => (a[k] - b[k]) / dt) as Vec3, h: Math.min(maxHalf, ((e - t) * dt * half)) };+ lock = null; onBall = false;+ }+ const u = rel ? (t - rel.at) * dt : 0;+ const d = rel ? ([0, 1, 2].map((k) => decay(rel!.x0[k], rel!.v0[k], rel!.h, u)) as Vec3) : ([0, 0, 0] as Vec3);+ // a swinging sole kept off the floor (1.6 cm): skimming it at swing speed is a skate+ d[1] = Math.max(d[1], 0.016 * z - low(t, s));+ off[s].push(d);+ }+ // the heights eased (a quarter, a half, a quarter, three times): a stand puts its pivot on the floor, a swing lifts+ // its sole clear, and the step between them is a jump+ for (let pass = 0; pass < Number(process.env.RAEA_LOCK_YPASS ?? 3); pass++) {+ const y = off[s].map((v) => v[1]);+ for (let t = 1; t < n - 1; t++) off[s][t][1] = 0.25 * y[t - 1] + 0.5 * y[t] + 0.25 * y[t + 1];+ }+ // each landing eased in: over the frames before touchdown the foot closes on the spot it locks at, arriving with no+ // speed (stopped dead in a frame, the knee kinked 4-6 degrees at every landing)+ const K = o.land ?? Number(process.env.RAEA_LOCK_LAND ?? 0);+ for (let t0 = 1; t0 < n; t0++) if (stand[s][t0] && !stand[s][t0 - 1]) {+ const A = feet[t0][s].ankle, d0 = off[s][t0];+ for (let k = 1; k <= K && t0 - k >= 0 && !stand[s][t0 - k]; k++) {+ const t = t0 - k, a = feet[t][s].ankle, d = off[s][t], u = 1 - k / (K + 1), w = u * u * (3 - 2 * u);+ for (const c of [0, 2]) d[c] -= w * (a[c] + d[c] - A[c] - d0[c]);+ }+ }+ // and after easing, a swinging sole still clear of the floor (easing pulled toe-offs back down to 1.2 cm, sliding)+ // (lifted smoothly: what each swinging frame needs, spread over the frames round it (the most of its neighbours',+ // faded over 3 frames, then averaged twice) and added; then the floor held. Held frame by frame with a bare max,+ // the lift came and went in a frame, the knee kinking with it: 9% of a short body's run frames)+ if (process.env.RAEA_LOCK_CLEAR !== "0") {+ const need = off[s].map((d, t) => (stand[s][t] ? 0 : Math.max(0, 0.016 * z - low(t, s) - d[1])));+ if (process.env.RAEA_LOCK_CLEAR_SMOOTH !== "0") {+ const Wd = 3, held = need.map((_, t) => { let m = 0; for (let k = -Wd; k <= Wd; k++) { const tt = t + k; if (tt < 0 || tt >= n || stand[s][tt] !== stand[s][t]) continue; m = Math.max(m, need[tt] * (1 - Math.abs(k) / (Wd + 1))); } return m; });+ for (let pass = 0; pass < 2; pass++) { const c = held.slice(); for (let t = 1; t < n - 1; t++) if (!stand[s][t]) held[t] = 0.25 * c[t - 1] + 0.5 * c[t] + 0.25 * c[t + 1]; }+ for (let t = 0; t < n; t++) if (!stand[s][t]) off[s][t][1] += Math.max(held[t], need[t]);+ } else for (let t = 0; t < n; t++) off[s][t][1] += need[t];+ }+ }+ // each leg solved to its ankle target (the clip's ankle plus the offset; never below the floor), knee toward the+ // clip's own+ if (o.log) o.log.stand = stand;+ // the hips lowered, smoothly, by what the legs need to reach their targets bent at least `bend` of their length+ // (a leg near straight turns its knee several degrees for a centimetre: every jog and run landing kinked the knee)+ const fold = o.fold ?? Number(process.env.RAEA_LOCK_FOLD ?? 0.97);+ const drop = new Array(n).fill(0);+ if (fold < 1) {+ for (let t = 0; t < n; t++) for (let s = 0; s < 2; s++) {+ const d = off[s][t], f = feet[t][s], tg = [f.ankle[0] + d[0], f.ankle[1] + d[1], f.ankle[2] + d[2]], h = f.hip;+ const dx = tg[0] - h[0], dz = tg[2] - h[2], L = fold * r.leg[s], dy = h[1] - tg[1];+ const need = L * L - dx * dx - dz * dz;+ drop[t] = Math.max(drop[t], need > 0 ? dy - Math.sqrt(need) : 0);+ }+ // eased over a third of a second either side (each frame the most of its neighbours', faded, then averaged)+ const W = Math.round(fps / 3), held = drop.map((_, t) => { let m = 0; for (let k = -W; k <= W; k++) { const v = drop[Math.max(0, Math.min(n - 1, t + k))]; m = Math.max(m, v * (1 - Math.abs(k) / (W + 1))); } return m; });+ for (let pass = 0; pass < 3; pass++) { const c = held.slice(); for (let t = 1; t < n - 1; t++) held[t] = 0.25 * c[t - 1] + 0.5 * c[t] + 0.25 * c[t + 1]; }+ for (let t = 0; t < n; t++) drop[t] = Math.min(held[t], 0.06 * z);+ }+ const out = raw.map((p0, t) => {+ const p = drop[t] > 1e-5 ? { ...p0, root: [p0.root[0], p0.root[1] - drop[t], p0.root[2]] as Vec3 } : p0;+ let q = p;+ for (let s = 0; s < 2; s++) {+ const d = off[s][t], f = feet[t][s];+ const tg: Vec3 = [f.ankle[0] + d[0], f.ankle[1] + d[1], f.ankle[2] + d[2]];+ if (o.log) { o.log.target[s][t] = tg; o.log.clip[s][t] = f.ankle; }+ if (Math.hypot(d[0], d[1], d[2]) < 1e-5 && Math.abs(yo[s][t]) < 1e-6) continue;+ if (Math.abs(yo[s][t]) > 1e-6) { const w = pose(skel, q); q = setWorld(skel, q, w, ai[s], qmul(qyaw(yo[s][t]), w.rot[ai[s]])); }+ const legs = [LEGS[s][0], LEGS[s][1], LEGS[s][2]];+ q = twoBone(skel, q, legs, tg, kneePole(skel, p, s), { keep: true });+ }+ return q;+ });+ // the legs' turns eased where the solve made them speed up or slow more suddenly than the clip's own (by 2 degrees a+ // frame, twice): a foot stopped at touchdown with the knee nearly straight swings the knee 5 degrees in a frame. Each+ // ease kept only where the standing sole stays within 2 mm.+ const passes = o.ease ?? Number(process.env.RAEA_LOCK_EASE ?? 3);+ for (let s = 0; s < 2; s++) {+ const js = [0, 1, 2].map((k) => joint(skel, LEGS[s][k]));+ const jerk = (P: Pose[], t: number, j: number) => {+ const v1 = qlog(qmul(qinv(P[t - 1].turns[j]), P[t].turns[j])), v2 = qlog(qmul(qinv(P[t].turns[j]), P[t + 1].turns[j]));+ return (Math.hypot(v2[0] - v1[0], v2[1] - v1[1], v2[2] - v1[2]) * 180) / Math.PI;+ };+ for (let pass = 0; pass < passes; pass++) {+ const was = out.map((q) => js.map((j) => q.turns[j]));+ for (let t = 1; t + 1 < n; t++) {+ if (!js.some((j) => jerk(out, t, j) > jerk(raw, t, j) + 2)) continue;+ const turns = out[t].turns.slice();+ js.forEach((j, i) => {+ const a = was[t - 1][i], b = was[t][i], c = was[t + 1][i], sg = (q: Quat) => (q[0] * b[0] + q[1] * b[1] + q[2] * b[2] + q[3] * b[3] < 0 ? -1 : 1);+ const sa = sg(a), sc = sg(c);+ turns[j] = qnorm([0, 1, 2, 3].map((k) => 0.25 * sa * a[k] + 0.5 * b[k] + 0.25 * sc * c[k]) as Quat);+ });+ const next = { ...out[t], turns };+ {+ // (standing, or a sole within 2.5 cm of the floor: eased swings at toe-off slid the foot along it)+ const A = pose(skel, out[t]), Bp = pose(skel, next);+ const sole = (w: typeof A, k: number) => { const v = qrot(w.rot[k], [0, -J[k].head[1], 0]); return [w.pos[k][0] + v[0], w.pos[k][1] + v[1], w.pos[k][2] + v[2]]; };+ const near = stand[s][t] || [ai[s], bi[s]].some((k) => Math.min(sole(A, k)[1], sole(Bp, k)[1]) < 0.025 * z);+ const moved = [ai[s], bi[s]].some((k) => { const a = sole(A, k), b = sole(Bp, k); return Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]) > 0.002 * z; });+ if (near && moved) continue;+ }+ out[t] = next;+ }+ }+ }+ if (o.log) out.forEach((q, t) => { const w = pose(skel, q); for (let s = 0; s < 2; s++) o.log!.reached[s][t] = w.pos[ai[s]]; });+ return out;+}++export const lockLog = (): LockLog => ({ stand: [[], []], pivot: [[], []], lock: [[], []], target: [[], []], reached: [[], []], clip: [[], []] });diff --git a/sdk/character/src/matching.ts b/sdk/character/src/matching.tsindex ffe172c0..56cefc09 100644--- a/sdk/character/src/matching.ts+++ b/sdk/character/src/matching.ts@@ -19,3 +19,4 @@ export { FEATURE_COUNT, STATE, STATE_COUNT, mirror, libraryPose, libraryRows, moexport type { MotionLibrary, SearchQuery, SearchBackend, TagCond, TagSpec, LibraryOptions, LibraryTable, MotionState, PhaseGoal, ObstacleKind, ActionFit, Obstacle, Mark, Step, Limbs, Seat, PerformanceSpec, PerformOptions, Performance } from "./matching/all";+export { MotionDebug, type MotionDebugProps } from "./matching/debug";diff --git a/sdk/character/src/matching/actions.ts b/sdk/character/src/matching/actions.tsindex 2917f3df..dffd94fe 100644--- a/sdk/character/src/matching/actions.ts+++ b/sdk/character/src/matching/actions.ts@@ -1,6 +1,6 @@// Actions: a clip's floor, levelled, and fitted onto an obstacle.import type { Vec3 } from "raea/3d";-import { bodyScale, captured, joint, pose, type Posed, type Skeleton } from "raea/character";+import { B, bodyScale, captured, joint, pose, qaxis, qmul, qrot, setWorld, type Posed, type Skeleton } from "raea/character";import { framePose, type Clip } from "../clip";// ---------------------------------------------------------------- actions@@ -35,7 +35,7 @@ export interface ActionFit {export function clipFloor(skel: Skeleton, c: Clip): { floor: number; contact: [number, number][] } {const hit = floors.get(c);if (hit && hit.skel === skel) return hit.g;- const F = ["LeftFoot", "RightFoot", "LeftToeBase", "RightToeBase"].map((n) => joint(skel, n));+ const F = B.feet().map((n) => joint(skel, n));// (centimetres and speeds by the body's size, bodyScale: a capture on a bigger body travels further in the same time)const rest = F.map((i) => skel.joints[i].head[1]), z = bodyScale(skel);const soles = Array.from({ length: c.frames }, (_, f) => { const w = pose(skel, framePose(c, f)); return F.map((i, q) => [w.pos[i][0], w.pos[i][1] - rest[q], w.pos[i][2]] as Vec3); });@@ -67,17 +67,17 @@ const floors = new WeakMap<Clip, { skel: Skeleton; g: { floor: number; contact:* a line along the way the hips go, through the soles of the feet standing still (those well over the line, on a box,* dropped, twice over), and taken off the root's height: the clip's floor at 0 all along. Unchanged with too few stances* to fit, and only the mean taken off when it barely moves. */-export function levelClip(skel: Skeleton, c: Clip): Clip {- const F = ["LeftFoot", "RightFoot", "LeftToeBase", "RightToeBase"].map((n) => joint(skel, n)), rest = F.map((i) => skel.joints[i].head[1]), z = bodyScale(skel);+export function levelClip(skel: Skeleton, c: Clip, residual = process.env.RAEA_LEVEL_RESIDUAL !== "0"): Clip {+ const F = B.feet().map((n) => joint(skel, n)), rest = F.map((i) => skel.joints[i].head[1]), z = bodyScale(skel);const W = Array.from({ length: c.frames }, (_, f) => pose(skel, framePose(c, f)));const a = W[0].pos[0], b = W[c.frames - 1].pos[0], L = Math.hypot(b[0] - a[0], b[2] - a[2]);const along = (f: number) => (L > 0.5 ? ((W[f].pos[0][0] - a[0]) * (b[0] - a[0]) + (W[f].pos[0][2] - a[2]) * (b[2] - a[2])) / L : 0);- const pts: [number, number][] = [];+ const pts: [number, number, number][] = [];for (let f = 0; f < c.frames; f++) for (const s of [0, 1]) {const lowAt = (g: number) => { const p = W[g].pos[F[s]][1] - rest[s] < W[g].pos[F[s + 2]][1] - rest[s + 2] ? F[s] : F[s + 2]; return W[g].pos[p]; };const p0 = lowAt(Math.max(0, f - 1)), p1 = lowAt(Math.min(c.frames - 1, f + 1));if ((Math.hypot(p1[0] - p0[0], p1[2] - p0[2]) * c.fps) / 2 > 0.4 * z) continue;- pts.push([along(f), Math.min(W[f].pos[F[s]][1] - rest[s], W[f].pos[F[s + 2]][1] - rest[s + 2])]);+ pts.push([along(f), Math.min(W[f].pos[F[s]][1] - rest[s], W[f].pos[F[s + 2]][1] - rest[s + 2]), f]);}if (pts.length < 8) return c;let k0 = 0, k1 = 0, use = pts;@@ -95,9 +95,44 @@ export function levelClip(skel: Skeleton, c: Clip): Clip {if (Math.abs(k1) * L > 0.08 * z) k1 = 0;const res = use.map((p) => p[1] - k1 * p[0]).sort((x, y) => x - y);k0 = res[Math.floor(res.length * 0.2)];+ // what the line leaves, over time: a take whose floor rises and falls as it turns (the volume calibrated off level in+ // two directions; a turn walks back over it) stood 4 to 5 cm over the floor through WalkTurnChange's middle, so its+ // feet never read as standing and were never locked. The stances' height above the line, Gaussian-weighted over 0.4 s+ // either side, taken off frame by frame (at most 6 cm; a stance on a box, over 4 cm, still dropped)+ const sg = 0.4 * c.fps, near = use.filter((p) => Math.abs(p[1] - (k0 + k1 * p[0])) < 0.04 * z);+ const off = new Float32Array(c.frames);+ for (let f = 0; f < c.frames; f++) {+ let w = 0, v = 0;+ for (const p of near) { const d = (p[2] - f) / sg; if (Math.abs(d) > 3) continue; const e = Math.exp(-0.5 * d * d); w += e; v += e * (p[1] - (k0 + k1 * p[0])); }+ off[f] = w > 0.5 ? Math.max(-0.06 * z, Math.min(0.06 * z, v / w)) : NaN;+ }+ // (frames far from any stance, a run's flights, take the nearest stance's)+ for (let f = 0; f < c.frames; f++) if (Number.isNaN(off[f])) { let a = f, b = f; while (a >= 0 && Number.isNaN(off[a])) a--; while (b < c.frames && Number.isNaN(off[b])) b++; off[f] = a >= 0 && b < c.frames ? (off[a] + off[b]) / 2 : a >= 0 ? off[a] : b < c.frames ? off[b] : 0; }const root = new Float32Array(c.root);- for (let f = 0; f < c.frames; f++) root[f * 3 + 1] -= k0 + k1 * along(f);- return { ...c, root };+ for (let f = 0; f < c.frames; f++) root[f * 3 + 1] -= k0 + k1 * along(f) + (residual ? off[f] : 0);+ const out = { ...c, root };+ return process.env.RAEA_UPRIGHT_HEAD !== "0" ? uprightHead(skel, out) : out;+}++/** The clip's head carried level: its mean sideways tilt (the head's left-right axis over the hips' heading) taken off+ * at the neck, about the way the hips face, every frame. ACCAD's Male2 holds his head 3.5 degrees to his right through+ * every take, and the library plays each clip mirrored too: a switch between the two swung the head 9 degrees, and a+ * walk's head rolled 8 a second where the capture's rolls 2 (docs/locomotion.md, U4). The tilt's motion stays. */+export function uprightHead(skel: Skeleton, c: Clip): Clip {+ const head = joint(skel, B.head), neck = joint(skel, B.neck), nj = c.turns.length / (c.frames * 4);+ if (neck >= nj || head >= nj) return c;+ const W = Array.from({ length: c.frames }, (_, f) => pose(skel, framePose(c, f)));+ const fwdOf = (w: Posed) => { const v = qrot(w.rot[0], [0, 0, 1]), l = Math.hypot(v[0], v[2]) || 1; return [v[0] / l, 0, v[2] / l] as Vec3; };+ let m = 0;+ for (const w of W) m += Math.asin(Math.max(-1, Math.min(1, qrot(w.rot[head], [1, 0, 0])[1])));+ m /= c.frames;+ if (Math.abs(m) < 0.003) return c;+ const turns = new Float32Array(c.turns);+ for (let f = 0; f < c.frames; f++) {+ const p = framePose(c, f), q = setWorld(skel, p, W[f], neck, qmul(qaxis(fwdOf(W[f]), -m), W[f].rot[neck]));+ turns.set(q.turns[neck], (f * nj + neck) * 4);+ }+ return { ...c, turns };}/** How an action clip clears an obstacle of a kind (its longest flight, its stretch up on a box, its lowest head, its@@ -106,7 +141,7 @@ export function fitAction(skel: Skeleton, c: Clip, kind: ObstacleKind): ActionFiconst n = c.frames, W: Posed[] = Array.from({ length: n }, (_, f) => pose(skel, framePose(c, f)));// (lengths and speeds by the body's size, bodyScale: set on the child, a man's head ducked into the bar)const J = (s: string) => joint(skel, s), z = bodyScale(skel);- const feet = ["LeftFoot", "RightFoot", "LeftToeBase", "RightToeBase"].map(J), head = J("Head");+ const feet = B.feet().map(J), head = J(B.head);const hip = (f: number) => W[f].pos[0];const a = hip(0), b = hip(n - 1), L = Math.hypot(b[0] - a[0], b[2] - a[2]), dir = [(b[0] - a[0]) / L, (b[2] - a[2]) / L];const along = (p: number[]) => (p[0] - a[0]) * dir[0] + (p[2] - a[2]) * dir[1];diff --git a/sdk/character/src/matching/all.ts b/sdk/character/src/matching/all.tsindex 931b5a7b..0f431e40 100644--- a/sdk/character/src/matching/all.ts+++ b/sdk/character/src/matching/all.ts@@ -6,6 +6,10 @@ export * from "./search";export * from "./actions";export * from "./routes";export * from "./guide";+export * from "./steer";+export * from "./settle";export * from "./perform";export * from "./finish";export * from "./core";+export * from "./head";+export * from "./arms";diff --git a/sdk/character/src/matching/arms.ts b/sdk/character/src/matching/arms.tsnew file mode 100644index 00000000..c4fa3ad2--- /dev/null+++ b/sdk/character/src/matching/arms.ts@@ -0,0 +1,49 @@+// Arms kept out of the trunk in play (docs/locomotion.md, U1). The retarget clears each clip's arms of the body's own+// trunk (retarget-ik.ts clearOfTrunk), but play moves them back in: blends between clips, Froude-quickened cadence, a+// body built wider than the capture's actor (mai's forearms crossed into her trunk on 3% of a run's frames). Each+// frame's arm is cleared again, and the turn that took, at the shoulder about the world, spread over the frames round+// it (the strongest of the neighbours', faded over `spread` frames, then averaged twice), so an arm swings wide of the+// body smoothly instead of hopping off it in a frame.+import type { Vec3 } from "raea/3d";+import { B, SIDES, joint, pose, qinv, qmul, qnorm, setWorld, type Pose, type Skeleton } from "raea/character";+import { qexp, qlog } from "../effects";+import { clearOfTrunk } from "../retarget-ik";++export function clearArms(skel: Skeleton, poses: Pose[], spread = 3): Pose[] {+ const n = poses.length;+ if (!n) return poses;+ const W = poses.map((p) => pose(skel, p));+ const sides = SIDES.map((s) => joint(skel, B.upperarm(s)));+ // each frame's correction per side: the world turn clearOfTrunk put on the upper arm+ const corr: Vec3[][] = sides.map(() => []);+ for (let f = 0; f < n; f++) {+ const nj = poses[f].turns.length, G = clearOfTrunk(skel, W[f].rot.slice(0, nj), nj);+ sides.forEach((u, k) => corr[k].push(qlog(qnorm(qmul(G[u], qinv(W[f].rot[u]))))));+ }+ const mag = (v: Vec3) => Math.hypot(v[0], v[1], v[2]);+ const smoothed = corr.map((c) => {+ if (!c.some((v) => mag(v) > 1e-5)) return null;+ const held = c.map((_, t) => {+ let best: Vec3 = [0, 0, 0], bm = 0;+ for (let k = -spread; k <= spread; k++) {+ const v = c[t + k];+ if (!v) continue;+ const w = 1 - Math.abs(k) / (spread + 1), m = mag(v) * w;+ if (m > bm) { bm = m; best = [v[0] * w, v[1] * w, v[2] * w]; }+ }+ return best;+ });+ for (let pass = 0; pass < 2; pass++) { const h = held.map((v) => [...v] as Vec3); for (let t = 1; t < n - 1; t++) for (let a = 0; a < 3; a++) held[t][a] = 0.25 * h[t - 1][a] + 0.5 * h[t][a] + 0.25 * h[t + 1][a]; }+ // (never less than the frame's own: averaged, a peak came out short of clear)+ return held.map((v, t) => (mag(v) >= mag(c[t]) ? v : c[t]));+ });+ return poses.map((p, f) => {+ let q = p;+ sides.forEach((u, k) => {+ const s = smoothed[k];+ if (!s || mag(s[f]) < 1e-5) return;+ q = setWorld(skel, q, pose(skel, q), u, qmul(qexp(s[f]), pose(skel, q).rot[u]));+ });+ return q;+ });+}diff --git a/sdk/character/src/matching/costs.ts b/sdk/character/src/matching/costs.tsindex 5f207878..3181720d 100644--- a/sdk/character/src/matching/costs.ts+++ b/sdk/character/src/matching/costs.ts@@ -1,6 +1,6 @@// What a frame costs: states, phases, a crouch, an arm's swing past held things, tags.import type { Vec3 } from "raea/3d";-import { bodyScale, joint, palmAt, palmFacing, pose, surface, type Posed, type Quat, type Skeleton } from "raea/character";+import { B, bodyScale, joint, palmAt, palmFacing, pose, surface, type Posed, type Quat, type Skeleton } from "raea/character";import { STYLE_KEYS, type StyleVector } from "../style";import { STATES } from "../effects";import { MotionLibrary, NF, NS, STATE, Step, TagCond, TagSpec, add3, libraryPose, movingAt } from "./all";@@ -147,8 +147,8 @@ function swingCapsules(skel: Skeleton) {const d = surface(skel, rest, re, side as "L" | "R" | undefined).map((x) => segDist(x.at, rest.pos[a], rest.pos[b])).sort((x, y) => x - y);return d.length ? d[Math.floor(0.9 * (d.length - 1))] : guess * bodyScale(skel);};- const thigh = (["L", "R"] as const).map((s) => { const a = J(s === "L" ? "LeftUpLeg" : "RightUpLeg"), b = J(s === "L" ? "LeftLeg" : "RightLeg"); return [a, b, fit(a, b, /^thigh$/, s, 0.075)] as [number, number, number]; });- const wa = J("Hips"), wb = J("Spine");+ const thigh = (["L", "R"] as const).map((s) => { const a = J(B.thigh(s)), b = J(B.calf(s)); return [a, b, fit(a, b, /^thigh$/, s, 0.075)] as [number, number, number]; });+ const wa = J(B.pelvis), wb = J(B.spine[1]);c = { thigh, waist: [wa, wb, fit(wa, wb, /^(waist|hips)$/, undefined, 0.12)] };capsulesOf.set(skel, c);return c;diff --git a/sdk/character/src/matching/debug.tsx b/sdk/character/src/matching/debug.tsxnew file mode 100644index 00000000..97ba1ae0--- /dev/null+++ b/sdk/character/src/matching/debug.tsx@@ -0,0 +1,81 @@+// What motion matching and foot locking did, drawn over the scene (Bevy gizmos), so slips, misses and the route can be+// seen where they happen rather than read off a table:+// white the guide's route on the floor; yellow, the hips' own trail over the last three seconds+// soles each foot's heel and ball over the last second and a half: green held by its lock, blue in the air, red on+// the floor and moving without a lock (a skate), orange held but still moving more than 2 mm a frame (a slip)+// lock a green cross where each standing foot is locked (on its pivot: heel, then ball)+// ik a cyan cross at each ankle's target, joined to where the leg reached it in red when it missed by over 1 cm+// The performance has to be made with { trace: true, feet: "lock" } for the lock and the IK; without it the route and+// the trails still draw.+//+// const perf = perform(lib, spec, { trace: true, feet: "lock" });+// <MotionDebug skeleton={turbo} perf={perf} frame={f} />+import { Gizmo, type Vec3 } from "@raea/render/3d";+import { B, SIDES, joint, pose, qrot, type Skeleton } from "../character/all";+import type { Performance } from "./all";++const GREEN = "#36d67a", BLUE = "#5b8cff", RED = "#ff3b3b", ORANGE = "#ffa62b", CYAN = "#3be8ff", WHITE = "#f4f4f4", YELLOW = "#ffd84a";+const LIFT = 0.004;++interface Soles { at: Vec3[][][]; root: Vec3[] }+const cache = new WeakMap<Performance, Soles>();++/** every frame's sole points (each side's heel and ball, on the floor under the joint as the joint turns) and hips */+function solesOf(skel: Skeleton, perf: Performance): Soles {+ let c = cache.get(perf);+ if (c) return c;+ const J = skel.joints, ids = SIDES.map((s) => [joint(skel, B.foot(s)), joint(skel, B.ball(s))]);+ const at: Vec3[][][] = [], root: Vec3[] = [];+ for (let f = 0; f < perf.frames; f++) {+ const p = perf.pose(f), w = pose(skel, p);+ root.push([p.root[0], LIFT, p.root[2]]);+ at.push(ids.map((pair) => pair.map((i) => { const v = qrot(w.rot[i], [0, -J[i].head[1], 0]); return [w.pos[i][0] + v[0], w.pos[i][1] + v[1], w.pos[i][2] + v[2]] as Vec3; })));+ }+ c = { at, root };+ cache.set(perf, c);+ return c;+}++const cross = (p: Vec3, r: number): [Vec3, Vec3][] => [[[p[0] - r, p[1], p[2]], [p[0] + r, p[1], p[2]]], [[p[0], p[1], p[2] - r], [p[0], p[1], p[2] + r]], [[p[0], p[1] - r, p[2]], [p[0], p[1] + r, p[2]]]];++export interface MotionDebugProps {+ skeleton: Skeleton;+ perf: Performance;+ frame: number;+ /** how many frames of the sole trails to draw (45) and of the hips' trail (90) */+ trail?: number;+ hips?: number;+ /** draw over the body and floor (true) or depth-tested */+ front?: boolean;+}++export function MotionDebug({ skeleton, perf, frame, trail = 45, hips = 90, front = true }: MotionDebugProps) {+ const f = Math.max(0, Math.min(perf.frames - 1, Math.round(frame)));+ const S = solesOf(skeleton, perf), L = perf.trace?.lock, bias = front ? -1 : 0;+ const route = perf.guide.map((g) => [g.x, LIFT, g.z] as Vec3);+ const lines: [Vec3, Vec3][] = [], colors: string[] = [];+ const seg = (a: Vec3, b: Vec3, c: string) => { lines.push([a, b]); colors.push(c, c); };+ // the soles' trails, coloured by what each frame was+ for (let s = 0; s < 2; s++) for (let k = 0; k < 2; k++) for (let t = Math.max(1, f - trail); t <= f; t++) {+ const a = S.at[t - 1][s][k], b = S.at[t][s][k], held = L?.stand[s][t] ?? false, down = b[1] < 0.015;+ const move = Math.hypot(b[0] - a[0], b[2] - a[2]);+ const c = held ? (move > 0.002 && down ? ORANGE : GREEN) : down && move > 0.002 ? RED : BLUE;+ seg([a[0], Math.max(LIFT, a[1]), a[2]], [b[0], Math.max(LIFT, b[1]), b[2]], c);+ }+ if (L) for (let s = 0; s < 2; s++) {+ const lk = L.lock[s][f];+ if (lk) for (const [a, b] of cross([lk[0], LIFT, lk[1]], 0.05)) seg(a, b, GREEN);+ const tg = L.target[s][f], re = L.reached[s][f];+ if (tg && re) {+ for (const [a, b] of cross(tg, 0.025)) seg(a, b, CYAN);+ if (Math.hypot(tg[0] - re[0], tg[1] - re[1], tg[2] - re[2]) > 0.01) seg(tg, re, RED);+ }+ }+ return (+ <>+ <Gizmo name="debug-route" strip={route} color={WHITE} width={1.5} depthBias={bias} />+ <Gizmo name="debug-hips" strip={S.root.slice(Math.max(0, f - hips), f + 1)} color={YELLOW} width={2} depthBias={bias} />+ {lines.length > 0 && <Gizmo name="debug-feet" lines={lines} color={colors} width={3} depthBias={bias} />}+ </>+ );+}diff --git a/sdk/character/src/matching/finish.ts b/sdk/character/src/matching/finish.tsindex 035926e0..244a432e 100644--- a/sdk/character/src/matching/finish.ts+++ b/sdk/character/src/matching/finish.ts@@ -1,6 +1,6 @@// perform's lookups and passes: each frame's asks, a switch's speed, still clips smoothed, an action's feet, the gaze.import type { Vec3 } from "raea/3d";-import { bodyScale, joint, lookAt, pose, qnorm, qrot, qyaw, type Pose, type Quat, type Skeleton } from "raea/character";+import { B, bodyScale, joint, lookAt, pose, qmul, qnorm, qrot, qyaw, setWorld, type Pose, type Quat, type Skeleton } from "raea/character";import { type RigEffect } from "../effects";import { MotionLibrary, Performance, PerformanceSpec, Step, TagCond, crouched, guide, labelCost, stateMix, stateQuery, stepTags, swingCost, wrap } from "./all";@@ -111,7 +111,7 @@ export function smoothStill(raw: Pose[], G: Guide) {// still going, 15 cm), the whole body is moved back by the slide, the leg as the clip has it (held by the leg it// folded 20° past the clip's), and the offset eased out once no foot slides (the slower foot's, both down)export function holdActionFeet(skel: Skeleton, raw: Pose[], G: Guide, contacts: [number, number][]) {- const lows = ["LeftFoot", "RightFoot", "LeftToeBase", "RightToeBase"].map((nm) => joint(skel, nm));+ const lows = B.feet().map((nm) => joint(skel, nm));const lowOf = (t: number, s: number) => { const w = pose(skel, raw[t]); const a = w.pos[lows[s]], b = w.pos[lows[s + 2]]; return a[1] - skel.joints[lows[s]].head[1] < b[1] - skel.joints[lows[s + 2]].head[1] ? a : b; };let off: [number, number] = [0, 0], from: [number, number] = [0, 0], since = -1;const EASE = 10;@@ -143,7 +143,8 @@ export function holdActionFeet(skel: Skeleton, raw: Pose[], G: Guide, contacts:export function stages(G: Guide, spec: PerformanceSpec, fps: number): Pick<Performance, "phase" | "step"> {const phase: Performance["phase"] = (frame) => {const a = G[Math.min(G.length - 1, Math.max(0, Math.round(frame)))]?.act;- if (!a || Math.round(frame) >= G.length) return null;+ // (a sit's only: an action clip's play, a pick-up or a throw, is an act with no seat)+ if (!a || !a.seat || Math.round(frame) >= G.length) return null;const [d, s] = a.len, j = a.j;const stage = j < d ? "down" : j < d + s ? "sat" : "up";const at = stage === "down" ? j : stage === "sat" ? j - d : j - d - s, n = a.len[stage === "down" ? 0 : stage === "sat" ? 1 : 2];@@ -173,7 +174,7 @@ export const smooth = (u: number) => {* second before the body gets there. The face turns by most of the way the guide will have turned by then (up to* about 45°), about up only, so the clip's own nods stay. */export function leadGaze(skel: Skeleton, poses: Pose[], G: Performance["guide"]): Pose[] {- const head = joint(skel, "Head"), eyes = skel.landmarks.eyes, lead = 20;+ const head = joint(skel, B.head), neck = joint(skel, B.neck), eyes = skel.landmarks.eyes, lead = 20;// the lead each frame, then smoothed over a third of a second either side: read raw it jumped where one step ends// and the next begins, and the head jerked (the motion lint's finding at the end of every walk)const want = poses.map((_, f) => {@@ -187,6 +188,14 @@ export function leadGaze(skel: Skeleton, poses: Pose[], G: Performance["guide"])return poses.map((p, f) => {const g = G[Math.min(G.length - 1, f)], turn = turns[f];if (g?.act || Math.abs(turn) < 0.002) return p;+ // the turn about the world's up, half at the neck and half at the head (RAEA_GAZE_ARC=1: the old look-at, whose+ // shortest arc from a face pitched down to the same pitch turned aside tilts the head: turn 90's head rolled 10.7+ // degrees over a second where the clips roll 5)+ if (process.env.RAEA_GAZE_ARC !== "1") {+ let q = p;+ for (const j of [neck, head]) q = setWorld(skel, q, pose(skel, q), j, qmul(qyaw(turn / 2), pose(skel, q).rot[j]));+ return q;+ }const w = pose(skel, p);const at = add3(w.pos[head], qrot(w.rot[head], [eyes[0] - skel.joints[head].head[0], eyes[1] - skel.joints[head].head[1], eyes[2] - skel.joints[head].head[2]]));const fwd = qrot(qyaw(turn), qrot(w.rot[head], [0, 0, 1]));@@ -206,7 +215,7 @@ export function strideEffect(skel: Skeleton, k: number): RigEffect {if (hit) return hit;const e: RigEffect = {posture: skel.joints.map(() => [0, 0, 0] as Vec3),- amplitude: skel.joints.map((j) => (/UpLeg$/.test(j.name) ? [kk, 1, 1] : /^(Left|Right)Leg$/.test(j.name) ? [Math.sqrt(kk), 1, 1] : [1, 1, 1]) as Vec3),+ amplitude: skel.joints.map((j) => (/^thigh_/.test(j.name) ? [kk, 1, 1] : /^calf_/.test(j.name) ? [Math.sqrt(kk), 1, 1] : [1, 1, 1]) as Vec3),rate: 1,};strides.set(key, e);@@ -215,3 +224,25 @@ export function strideEffect(skel: Skeleton, k: number): RigEffect {/** whether RAEA_LINT is set (every performance lints itself) */export const lintEnv = () => { const g = globalThis as { process?: { env?: Record<string, string | undefined> } }; return !!g.process?.env?.RAEA_LINT; };++/** The matched motion's joints smoothed over time (the binomial mean of the five frames round each, twice): a switch's+ * blend and the library's frame steps left the toes and feet snapping 10 to 25 degrees in a frame, which the planting+ * that follows does not undo. The root's place and turn are the guide's and stay. */+export function smoothTurns(raw: Pose[], passes = 2) {+ const TAPS: [number, number][] = [[-2, 1], [-1, 4], [0, 6], [1, 4], [2, 1]];+ for (let pass = 0; pass < passes; pass++) {+ const was = raw.slice(), n = raw.length;+ for (let t = 0; t < n; t++) {+ const turns = was[t].turns.map((c, i) => {+ if (i === 0) return c;+ const m = [0, 0, 0, 0];+ for (const [d, w] of TAPS) {+ const q = was[Math.min(n - 1, Math.max(0, t + d))].turns[i], sg = q[0] * c[0] + q[1] * c[1] + q[2] * c[2] + q[3] * c[3] < 0 ? -w : w;+ for (let a = 0; a < 4; a++) m[a] += sg * q[a];+ }+ return qnorm(m as Quat);+ });+ raw[t] = { ...was[t], turns };+ }+ }+}diff --git a/sdk/character/src/matching/guide.ts b/sdk/character/src/matching/guide.tsindex 89ce6bb4..40a492a2 100644--- a/sdk/character/src/matching/guide.ts+++ b/sdk/character/src/matching/guide.ts@@ -3,6 +3,7 @@ import type { Vec3 } from "raea/3d";import { bodyScale, qinv, qmul, qnorm, qrot, qyaw, type Pose } from "raea/character";import { framePose, type Clip } from "../clip";import { type PlantLog } from "../feet";+import { type LockLog } from "../lock";import { qexp, qlog, type RigEffect } from "../effects";import { MotionLibrary, MotionState, TagSpec, labelOf, rounded } from "./all";@@ -78,6 +79,14 @@ export interface PerformanceSpec {}export interface PerformOptions {+ /** how the guide pulls the body: true (Holden's velocity-limited adjustment and clamp, docs/locomotion.md; the+ * default) or the flat pull (false; RAEA_ADJUST=0) */+ adjust?: boolean | "1";+ /** passes of the five-frame smoothing over the matched joints (2 by default; 0 leaves them as matched) */+ smooth?: number;+ /** how the feet are held while they stand: "lock" (lockFeet, the default: contacts baked from the soles, heel then+ * ball locked, released on a spring) or "plant" (plantFeet, the older pinning; RAEA_FEET=plant) */+ feet?: "plant" | "lock";/** how often it searches the library, frames */every?: number;/** a switch's blend, seconds */@@ -157,7 +166,7 @@ export interface Performance {step(frame: number): { index: number; kind: "walk" | "wait" | "sit" | "act"; since: number; left: number } | null;/** with `trace`: the pose at each stage (the clip's frame as chosen, blended in, the feet planted, the elbows relaxed,* the gaze), the frames a switch began, the rate (library frames a frame) and what planting did, for motionLint */- trace?: { stages: Record<"clip" | "blend" | "plant" | "elbows" | "gaze", Pose[]>; switches: number[]; rate: number[]; plant?: PlantLog };+ trace?: { stages: Record<"clip" | "blend" | "plant" | "elbows" | "gaze", Pose[]>; switches: number[]; rate: number[]; plant?: PlantLog; lock?: LockLog };}export const wrap = (a: number) => Math.atan2(Math.sin(a), Math.cos(a));@@ -219,7 +228,10 @@ export function guide(spec: PerformanceSpec, fps: number, lib: MotionLibrary): Pcontinue;}// a walk's own corners (a route's are rounded already) rounded a little: no one walks to a corner and pivots- const pts = rounded(st.walk, [], 0);+ // (from where the body is: a walk whose first point is elsewhere goes there first; taken as its start, the guide+ // jumped 3 m and the body was pulled across at 11 m/s with its feet down)+ const w0 = st.walk[0], far = !w0 || Math.hypot(w0[0] - x, w0[1] - z) > 0.05;+ const pts = rounded(far ? [[x, z] as [number, number], ...st.walk] : st.walk, [], 0);const segs: { a: [number, number]; b: [number, number]; l: number }[] = [];for (let k = 1; k < pts.length; k++) segs.push({ a: pts[k - 1], b: pts[k], l: Math.hypot(pts[k][0] - pts[k - 1][0], pts[k][1] - pts[k - 1][1]) });const total = segs.reduce((a, s) => a + s.l, 0);diff --git a/sdk/character/src/matching/head.ts b/sdk/character/src/matching/head.tsnew file mode 100644index 00000000..d743362b--- /dev/null+++ b/sdk/character/src/matching/head.ts@@ -0,0 +1,30 @@+// The head held steady (docs/locomotion.md, U4): a walker's head stays nearly level in the world whatever the trunk+// does under it, the vestibulo-collic reflex, pitch held within a few degrees in walking (Pozzo et al. 1990). Each frame+// the head's tilt in the world (its roll about the way the hips face, its pitch about their side) follows a critically+// damped second-order spring at `hz`; the head keeps `keep` of what the tilt does faster than that, and the spring's+// slow part all of it, so a lean into a turn or a look down stays and the sway on top goes.+import type { Vec3 } from "raea/3d";+import { B, joint, pose, qaxis, qmul, qrot, setWorld, type Pose, type Skeleton } from "raea/character";++export interface SteadyHead { hz?: number; keep?: number; keepPitch?: number }++export function steadyHead(skel: Skeleton, poses: Pose[], fps = 30, o: SteadyHead = {}): Pose[] {+ const head = joint(skel, B.head), n = poses.length;+ if (n < 3) return poses;+ const hz = o.hz ?? Number(process.env.RAEA_STEADY_HZ ?? 1.5), keep = o.keep ?? Number(process.env.RAEA_STEADY_KEEP ?? 0.35);+ const keepP = o.keepPitch ?? Number(process.env.RAEA_STEADY_KEEP_PITCH ?? 0.6);+ const W = poses.map((p) => pose(skel, p));+ const frame = (f: number) => { const v = qrot(W[f].rot[0], [0, 0, 1]), l = Math.hypot(v[0], v[2]) || 1; const fw: Vec3 = [v[0] / l, 0, v[2] / l]; return { fw, side: [fw[2], 0, -fw[0]] as Vec3 }; };+ const tilt = (f: number) => { const q = W[f].rot[head]; return [Math.asin(Math.max(-1, Math.min(1, qrot(q, [1, 0, 0])[1]))), Math.asin(Math.max(-1, Math.min(1, qrot(q, [0, 0, 1])[1])))]; };+ // (t3ssel8r's second-order system with z = 1, r = 0: k1 = 1/(pi f), k2 = 1/(2 pi f)^2, stepped twice a frame)+ const k1 = 1 / (Math.PI * hz), k2 = 1 / (2 * Math.PI * hz) ** 2, dt = 1 / fps / 2;+ const T = poses.map((_, f) => tilt(f)), y = [...T[0]], v = [0, 0], out = poses.slice();+ for (let f = 0; f < n; f++) {+ for (let s = 0; s < 2; s++) for (let c = 0; c < 2; c++) { v[c] += (dt * (T[f][c] - y[c] - k1 * v[c])) / k2; y[c] += dt * v[c]; }+ const dr = (keep - 1) * (T[f][0] - y[0]), dp = (keepP - 1) * (T[f][1] - y[1]), { fw, side } = frame(f);+ if (Math.abs(dr) + Math.abs(dp) < 1e-4) continue;+ // (pitch measured up as the face's forward rises: a turn about the side axis (+x for a body facing +z) lowers it)+ out[f] = setWorld(skel, poses[f], W[f], head, qmul(qmul(qaxis(fw, dr), qaxis(side, -dp)), W[f].rot[head]));+ }+ return out;+}diff --git a/sdk/character/src/matching/library.ts b/sdk/character/src/matching/library.tsindex 454f52f5..d12407cd 100644--- a/sdk/character/src/matching/library.ts+++ b/sdk/character/src/matching/library.ts@@ -1,6 +1,6 @@// The library: its frames' features, mirrored, as a table.import type { Vec3 } from "raea/3d";-import { captured, joint, pose, qrot, qyaw, type Pose, type Quat, type Skeleton } from "raea/character";+import { B, mirrorName, captured, joint, pose, qrot, qyaw, type Pose, type Quat, type Skeleton } from "raea/character";import { framePose, type Clip } from "../clip";import { fromBase64, toBase64 } from "@raea/video/codecs";import { styleOf, type StyleVector } from "../style";@@ -14,7 +14,7 @@ function facing(rot: Quat): number {return Math.atan2(f[0], f[2]);}-const SWAP = (n: string) => n.startsWith("Left") ? "Right" + n.slice(4) : n.startsWith("Right") ? "Left" + n.slice(5) : n[0] === "L" && /^L[A-Z]/.test(n) ? "R" + n.slice(1) : n[0] === "R" && /^R[A-Z]/.test(n) ? "L" + n.slice(1) : n;+const SWAP = mirrorName;/** A pose seen in a mirror across the body's x = 0: left and right swapped. */export function mirror(skel: Skeleton, p: Pose): Pose {@@ -77,7 +77,7 @@ function rawRows(skel: Skeleton, list: { name: string; c: Clip; acting: booleanconst C = NF + 5 + NS;const total = list.reduce((a, x) => a + x.c.frames, 0);const rows = new Float32Array(total * C).fill(NaN);- const L = ["LeftFoot", "RightFoot", "LeftToeBase", "RightToeBase"].map((x) => joint(skel, x));+ const L = B.feet().map((x) => joint(skel, x));const ankleRest = skel.joints[L[0]].head[1], toeRest = skel.joints[L[2]].head[1];let base = 0;for (const { c } of list) {diff --git a/sdk/character/src/matching/perform.ts b/sdk/character/src/matching/perform.tsindex e779a2dd..6124e718 100644--- a/sdk/character/src/matching/perform.ts+++ b/sdk/character/src/matching/perform.ts@@ -1,11 +1,9 @@-// perform: the performance simulated once from frame 0.+// perform: the performance simulated once from frame 0 (how it steers: steer.ts; its passes after play: settle.ts).import type { Vec3 } from "raea/3d";-import { softElbows, qinv, qmul, qnorm, qrot, qyaw, type Pose, type Quat } from "raea/character";+import { qinv, qmul, qnorm, qrot, qyaw, type Pose, type Quat } from "raea/character";import { framePose } from "../clip";-import { plantFeet, type PlantLog } from "../feet";-import { lintReport, motionLint } from "../lint";import { applyEffect, clipMeans, mirrorEffect, mixEffects, qexp, qlog, type RigEffect } from "../effects";-import { Act, FUTURE, MotionLibrary, NF, PerformOptions, Performance, PerformanceSpec, PhaseGoal, S, before, between, carrySpeed, clipFloor, guide, handCost, holdActionFeet, idOf, labelOf, leadGaze, libraryPose, lintEnv, mirror, nearest, nearestHands, paceOf, performances, phaseCost, seatYaw, smooth, smoothStill, stages, stateCost, stateMix, stepLookups, strideEffect, tagCost, wrap } from "./all";+import { Act, FUTURE, MotionLibrary, NF, PerformOptions, Performance, PerformanceSpec, PhaseGoal, between, clipFloor, fadeParts, guide, handCost, idOf, labelOf, libraryPose, lintEnv, mirror, nearest, nearestHands, offAt, paceOf, pacedSpec, performances, phaseCost, pullToGuide, seatYaw, settle, smooth, startFrame, stateCost, stepLookups, strideEffect, tagCost, wrap } from "./all";/** A performance simulated once for its library and spec: the guide along the steps, each moment's best library frame,* blended switches, the body pulled onto the guide, and the feet pinned while they stand. */@@ -17,19 +15,16 @@ export function perform(lib: MotionLibrary, spec: PerformanceSpec, o: PerformOptif (hit) return hit;const skel = lib.skel, fps = lib.fps;// a walk in a state goes at the state's pace (an old man's is a third of neutral's) unless the step says its own- const paced = effects ? { ...spec, steps: spec.steps.map((st) => {- const s = ("state" in st && st.state) || spec.state, mix = s ? stateMix(s) : null;- if (!("walk" in st) || st.speed !== undefined || !mix) return st;- // the heaviest style the library has frames of sets the pace (its walks' own); the others scale it by their- // effects' (a library with none of them: its Neutral's pace, or the default walk's, scaled)- const own = Object.entries(mix).filter(([l]) => paceOf(lib, l) > 0).sort((x, y) => y[1] - x[1])[0];- let k = own ? paceOf(lib, own[0]) : paceOf(lib, "Neutral") || 1;- for (const [l, w] of Object.entries(mix)) if (!own || l !== own[0]) k *= (effects[l]?.speed ?? 1) ** w;- return { ...st, speed: Math.max(0.2, k) };- }) } : spec;+ const paced = pacedSpec(lib, spec, effects);const G = guide(paced, fps, lib);const N = spec.frames ?? G.length;- const every = o.every ?? 6, bf = Math.max(1, Math.round((o.blend ?? 0.2) * fps)), bo = Math.max(bf, Math.round((o.blendOut ?? 0.45) * fps)), pull = o.pull ?? 0.12;+ const every = o.every ?? 6, bf = Math.max(1, Math.round((o.blend ?? 0.2) * fps)), bo = Math.max(bf, Math.round((o.blendOut ?? 0.45) * fps)), pull = o.pull ?? Number(process.env.RAEA_PULL ?? 0.12);+ // (RAEA_ADJUST=0 for the old flat pull) the guide pulls the body as Holden's controller does (velocity-limited, halflives 0.1 s and 0.2 s,+ // half the clip's own motion at most, clamped to 15 cm), in place of a flat pull+ const adjust = o.adjust !== undefined ? o.adjust === true || o.adjust === "1" : process.env.RAEA_ADJUST !== "0";+ const damp = (hl: number) => 1 - Math.exp((-Math.LN2 / fps) / hl);+ const aPos = damp(Number(process.env.RAEA_ADJUST_HL ?? 0.1)), aRot = damp(Number(process.env.RAEA_ADJUST_HLR ?? 0.2));+ const adjRatio = Number(process.env.RAEA_ADJUST_RATIO ?? 0.5), clampDist = Number(process.env.RAEA_ADJUST_CLAMP ?? 0.15);// the body's ground frame in the scene, and the library frame it playslet x = spec.at[0], z = spec.at[2], yaw = spec.facing;const gAt = (k: number) => G[Math.min(G.length - 1, Math.max(0, k))];@@ -108,48 +103,31 @@ export function perform(lib: MotionLibrary, spec: PerformanceSpec, o: PerformOptreturn q;};// where it starts: the frame nearest standing still facing ahead- const start = (() => {- const s = new Float32Array(NF);- for (let d = 0; d < 15; d++) s[d] = lib.mean[d];- for (let d = 6; d < 15; d++) s[d] = 0;- let c = 15;- for (const _ of FUTURE) { s[c++] = 0; s[c++] = 0; }- for (const _ of FUTURE) { s[c++] = 0; s[c++] = 1; }- const k0 = nearest(lib, s, undefined, wantAt(0), ws, penAt(0), undefined, undefined, condAt(0)).k;- // (a walk entered at speed starts mid-stride: the frame whose way on is the guide's, its pose any)- const first = spec.steps[0];- if (!(first && "walk" in first && (first.enter ?? 0) > 0.5)) return k0;- const g = query(k0, 0), F = lib.features;- let best = k0, bd = Infinity;- for (let k2 = 0; k2 < lib.size; k2++) {- if (lib.jump[k2] !== 1) continue;- let dd = 0;- for (let d = 15; d < NF; d++) dd += (F[k2 * NF + d] - (g[d] - lib.mean[d]) * lib.scale[d]) ** 2;- if (dd < bd) { bd = dd; best = k2; }- }- return best;- })();+ const start = startFrame(lib, spec, (s) => nearest(lib, s, undefined, wantAt(0), ws, penAt(0), undefined, undefined, condAt(0)).k, query);let k = start;// the blend out of a switch (inertialized): each joint's offset and how fast it was changing, and the hips' height's,// fading to nothing over the blend on a Hermite curve, so a switch keeps the body's speed as well as its place- let off: { x: Vec3[]; v: Vec3[]; y: number; vy: number } | null = null, since = 0;+ let off: { x: Vec3[]; v: Vec3[]; y: number; vy: number; n: number[] } | null = null, since = 0;// (longer at an action's edges: its run-in and run-out lean into the obstacle, a capture's runs stand up, and the// lean taken off in a fifth of a second read as a hitch. The hips' tilt too, the lean is mostly theirs, but the legs// turned back by its difference from the short blend: legs blended as long slid the feet and floated the strides)let bl = bf;- // (the legs: from the hips' children that lead down to a thigh, LHipJoint and on)- const legOf = (i: number): boolean => i > 0 && (/UpLeg/.test(skel.joints[i].name) || skel.joints.some((j, c) => j.parent === i && legOf(c)));- const thighs = skel.joints.flatMap((j, i) => (j.parent === 0 && legOf(i) ? [i] : []));- const upper = skel.joints.map((_, i) => { for (let a = i; a > 0; a = skel.joints[a].parent) if (thighs.includes(a)) return false; return true; });+ // the most an upper-body joint's fade turns it in a frame (radians), and the longest fade that allows+ const fadeRate = (Number(process.env.RAEA_FADE_RATE ?? 4) * Math.PI) / 180, maxFade = Math.round(0.6 * fps);+ const legRate = (Number(process.env.RAEA_LEG_FADE_RATE ?? 12) * Math.PI) / 180, legMax = Math.round(0.4 * fps);+ // (the legs: the pelvis's children that lead down to a thigh)+ const { thighs, upper, trunk } = fadeParts(skel);const hermite = (s: number, n = bf): [number, number] => { if (s >= n) return [0, 0]; const a = s / n; return [2 * a ** 3 - 3 * a ** 2 + 1, (a ** 3 - 2 * a ** 2 + a) * n]; };- const offAt = (O: NonNullable<typeof off>, i: number, [a, b]: [number, number]) => qexp([O.x[i][0] * a + O.v[i][0] * b, O.x[i][1] * a + O.v[i][1] * b, O.x[i][2] * a + O.v[i][2] * b]);/** each joint's blend offset `s` frames into it; `fr`, the frame it goes onto (its turns and ground heading), to keep* the legs: the thighs turned back by the hips' difference, through their hip joints (which hold still in every* capture: turned themselves, they jerked past the library's) */const blendAt = (s: number, fr?: { turns: Quat[]; g: number }): Quat[] | null => {- if (!off || s >= Math.max(bf, bl)) return null;- const lo = hermite(s), hi = hermite(s, bl), O = off;- const out = O.x.map((_, i) => offAt(O, i, upper[i] ? hi : lo));+ if (!off || s >= Math.max(bf, bl, ...off.n)) return null;+ const lo = hermite(s), O = off;+ // (an upper joint's offset fades over its own length, its velocity over the short blend: carried over a long fade the+ // velocity overshot, a hand swinging the old clip's way 26 degrees a frame where both clips turned it 16 to 19)+ const vb = lo[1];+ const out = O.x.map((_, i) => offAt(O, i, upper[i] || O.n[i] > bf ? [hermite(s, O.n[i])[0], vb] : lo));if (fr && bl > bf) {const local = qmul(qyaw(-fr.g), fr.turns[0]), d = qmul(qinv(local), qmul(qmul(qinv(out[0]), offAt(O, 0, lo)), local));for (const i of thighs) {@@ -235,10 +213,23 @@ export function perform(lib: MotionLibrary, spec: PerformanceSpec, o: PerformOpt};const xA = offOf(fromA, k, nextA, to, since), xB = offOf(fromB, k1, nextB, t1, since + 1);const yA = yAt(since) + fromA.root[1] - nextA.root[1], yB = yAt(since + 1) + fromB.root[1] - nextB.root[1];- off = { x: xA, v: xA.map((x, i) => [xB[i][0] - x[0], xB[i][1] - x[1], xB[i][2] - x[2]] as Vec3), y: yA, vy: yB - yA };// (a switch inside a long blend keeps what is left of it){ const t = raw.length, out = [1, 2, 3].some((d) => G[t - d]?.act?.play) && !G[t]?.act;bl = Math.max(bf, bl - since, out ? bo : 0); }+ // each upper-body joint's fade long enough that no frame of it turns the joint more than `rate` (a Hermite fade's+ // steepest frame turns 1.5 x offset / length): one fade length for all had a big offset, the head's or a hand's+ // across a turn, cross in 6 frames at 10 to 19 degrees a frame+ // (the legs' fades rate-limited too, at RAEA_LEG_FADE_RATE degrees (12; 0 for one length), up to 0.4 s: a run turn+ // handing to a walk turn crossed the calf 14 degrees a frame in a 6-frame fade, where the clips turn it 8)+ const n = xA.map((x, i) => (upper[i] ? Math.min(maxFade, Math.max(bl, Math.ceil((1.5 * Math.hypot(...x) * 2) / fadeRate))) : legRate > 0 ? Math.min(legMax, Math.max(bf, Math.ceil((1.5 * Math.hypot(...x) * 2) / legRate))) : bf));+ // (the trunk's joints (RAEA_FADE_SHARED=0 for each its own) all fade over the longest of their lengths: each over its own, a hip+ // faded in 6 frames under a neck fading over 18 left the head tilted 13 degrees past either clip, run turn 90)+ if (process.env.RAEA_FADE_SHARED !== "0") { const L = Math.max(...n.filter((_, i) => trunk[i])); n.forEach((_, i) => { if (trunk[i]) n[i] = L; }); }+ // (and each leg joint no quicker than the joint it hangs from (RAEA_LEG_CHAIN=0 not): a stand-up's thighs, flexed+ // 31 degrees off the walk's, faded back in a third of the time of its pitched pelvis, and the straightened legs+ // hung back off the leaning hips, the feet 28 cm behind them and into the chair)+ if (process.env.RAEA_LEG_CHAIN !== "0" && Math.hypot(...xA[0]) > Number(process.env.RAEA_LEG_CHAIN_MIN ?? 0.4)) skel.joints.forEach((j, i) => { if (!upper[i] && j.parent >= 0) n[i] = Math.max(n[i], n[j.parent]); });+ off = { x: xA, v: xA.map((x, i) => [xB[i][0] - x[0], xB[i][1] - x[1], xB[i][2] - x[2]] as Vec3), y: yA, vy: yB - yA, n };// the way come since frame k carried into the body's place, as the new frame starts from none of itconst w = onward();x += w.dx; z += w.dz; yaw += w.dyaw;@@ -248,13 +239,21 @@ export function perform(lib: MotionLibrary, spec: PerformanceSpec, o: PerformOpt};// an action's alignment: the clip's seat onto the scene's, and the error at its start, eased out over sitting downlet align: { rot: number; e: [number, number]; ey: number } | null = null;+ let satU = 0;const actFrame = (a: Act): number => {const S = lib.sit!;+ satU = 0;if (a.j < a.len[0]) return S.down[0] + a.j;if (a.j < a.len[0] + a.len[1]) {- // the sat stretch to and fro as long as it is sat- const m = Math.max(1, S.sat[1] - S.sat[0]), u = (a.j - a.len[0]) % (2 * m);- return S.sat[0] + (u < m ? u : 2 * m - u);+ const m = Math.max(1, S.sat[1] - S.sat[0]), s = a.j - a.len[0];+ if (process.env.RAEA_SIT_PINGPONG === "1") { const u = s % (2 * m); return S.sat[0] + (u < m ? u : 2 * m - u); }+ // the sat stretch played forward, slowed to fill the sit (to and fro, RAEA_SIT_PINGPONG=1, played every move+ // backwards at each turn: 0.29 turns a second of errands' sit); a sit longer than twice the stretch loops it at+ // half speed, timed from its end so the last pass runs into the stand-up's first frame (the stretch's last)+ const r = Math.max(0.5, Math.min(1, m / Math.max(1, a.len[1])));+ const pos = r > 0.5 ? s * r : m - (((a.len[1] - s) * r) % m || m);+ satU = pos - Math.floor(pos);+ return S.sat[0] + Math.floor(pos);}return S.up[0] + (a.j - a.len[0] - a.len[1]);};@@ -263,13 +262,17 @@ export function perform(lib: MotionLibrary, spec: PerformanceSpec, o: PerformOpt// the pace asked of the walk against the library's, eased over a third of a second// (a library with no walking style's pace: against the playing clip's own, a little either way, so a run matched// into a slower capture cycles its legs quicker rather than the hips being pulled on over standing feet)+ // (Froude: a body of another build than the capture's walks at the same Froude number, v^2/gL, so its cadence goes+ // as 1/sqrt of its legs' scale and its stride as the scale: the retarget scaled only the stride, which played a+ // short body's legs at a tall actor's cadence. RAEA_FROUDE=0 for the capture's cadence)+ const froude = process.env.RAEA_FROUDE === "0" ? 1 : (lib.clips[lib.frameClip[k]].clip.scale ?? 1) ** -0.5;const own = libPace > 0 || act ? 0 : ownPace(k);- const want = g0.moving && g0.speed && libPace > 0 && !effects ? Math.max(0.5, Math.min(2.5, g0.speed / libPace))- : g0.moving && g0.speed && own > 0.2 && !effects ? Math.max(0.7, Math.min(1.6, g0.speed / own)) : 1;+ const want = g0.moving && g0.speed && libPace > 0 && !effects ? Math.max(0.5, Math.min(2.5, g0.speed / (libPace * froude)))+ : g0.moving && g0.speed && own > 0.2 && !effects ? Math.max(0.7, Math.min(1.6, g0.speed / (own * froude))) : 1;paceK += (want - paceK) * 0.1;// (against the clip's own pace, all of it in the cadence: a longer stride than the capture's drags the hips on past// the standing foot's reach, the foot pulled up off the floor)- rate = effRate * paceK ** (ownPaced ? 1 : 0.6);+ rate = effRate * froude * paceK ** (ownPaced ? 1 : 0.6);stride = effStride * paceK ** (ownPaced ? 0 : 0.4);if (act?.play) {// an action clip plays straight through; its first frame blends in from what shows@@ -321,14 +324,15 @@ export function perform(lib: MotionLibrary, spec: PerformanceSpec, o: PerformOptif (a2?.play && a2.j === 0) { phase = { to: a2.play.from, m: Math.round(d * rate), w: 1.5 }; late = d <= 6; break; }if (a2) break;}+ const sw = swingAt(t);if (valid(k)) {const z0 = lib.features.subarray(k * NF, (k + 1) * NF);const pen = penAt(t);const tc = condAt(t);- stay = stateCost(lib, k, want, ws) + (pen ? pen[lib.frameClip[k]] : 0) + (phase ? phaseCost(lib, k, phase) : 0) + (maskAt(t)?.[k] ? Infinity : 0) + (swingAt(t)?.[k] ?? 0) + (tc ? tagCost(lib, k, tc) : 0);+ stay = stateCost(lib, k, want, ws) + (pen ? pen[lib.frameClip[k]] : 0) + (phase ? phaseCost(lib, k, phase) : 0) + (maskAt(t)?.[k] ? Infinity : 0) + (sw?.[k] ?? 0) + (tc ? tagCost(lib, k, tc) : 0);for (let d = 0; d < NF; d++) stay += (z0[d] - (cur[d] - lib.mean[d]) * lib.scale[d]) ** 2;}- const best = late && valid(k) ? { k: -1, d: Infinity } : nearest(lib, cur, near, want, ws, penAt(t), phase, maskAt(t), condAt(t), swingAt(t));+ const best = late && valid(k) ? { k: -1, d: Infinity } : nearest(lib, cur, near, want, ws, penAt(t), phase, maskAt(t), condAt(t), sw);if (best.k >= 0 && best.d < stay * 0.9) switchTo(best.k);}}@@ -364,7 +368,7 @@ export function perform(lib: MotionLibrary, spec: PerformanceSpec, o: PerformOptconst onU = !!cu && kU >= 0, leaveU = wasU && !onU;// (an action takes the whole body: what the upper body had is let go)if (act) { offU = null; kU = -1; }- const fr = { clip: lib.frameClip[k], f: lib.frameF[k], ...shownAt(k, act ? 0 : u) };+ const fr = { clip: lib.frameClip[k], f: lib.frameF[k], ...shownAt(k, act ? (act.play ? 0 : satU) : u) };played.push({ clip: lib.clips[fr.clip].name + (lib.clips[fr.clip].mirrored ? "~" : ""), f: fr.f });if (o.trace) { clipStage.push({ root: fr.root, turns: fr.turns }); rates.push(rate); }const f = blendAt(since, { turns: fr.turns, g: lib.ground[k * 3 + 2] });@@ -450,6 +454,7 @@ export function perform(lib: MotionLibrary, spec: PerformanceSpec, o: PerformOpt}// advance: the library's own steps (as many as the effects' rate makes this frame), turned into the body's// heading, then pulled toward the guide+ const px0 = x, pz0 = z, pyaw0 = yaw;for (u += rate; u >= 1; u--) {const nk = k + 1 < lib.clips[lib.frameClip[k]].end ? k + 1 : k;if (nk === k) { u = 0; break; }@@ -462,34 +467,7 @@ export function perform(lib: MotionLibrary, spec: PerformanceSpec, o: PerformOptk = nk;}const g = gAt(t + 1);- if (!g.act) {- // against where the body shows, u of the way on to the next library frame (at a rate other than 1 the ground- // frame moves in whole library frames, and pulling that against the guide shakes the body)- const w = onward();- // (a wait with slack pulled only for how far it is past it: a stop at a thing taken in passing overran its spot- // 8 cm, was pulled back over standing feet, and at the start after them the feet were 10 cm from the clip's)- let ex = g.x - x - w.dx, ez = g.z - z - w.dz;- if (g.slack) { const e = Math.hypot(ex, ez), k2 = e > g.slack ? 1 - g.slack / e : 0; ex *= k2; ez *= k2; }- x += ex * pull;- z += ez * pull;- yaw += wrap(g.yaw - yaw) * pull;- }+ if (!g.act) ({ x, z, yaw } = pullToGuide({ x, z, yaw }, { x: px0, z: pz0, yaw: pyaw0 }, g, onward(), { adjust, aPos, aRot, adjRatio, clampDist, pull }));}- carrySpeed(raw, switches, fps);- smoothStill(raw, G);- holdActionFeet(skel, raw, G, contacts);- // relaxed elbows: the library's arms can swing locked straight- const log: PlantLog | undefined = o.trace ? { state: [[], []], events: [], drop: [], lift: [[], []] } : undefined;- const planted = o.pin === false ? raw : plantFeet(skel, raw, contacts, fps, log);- const relaxed = planted.map((p) => softElbows(skel, p));- const poses = o.gaze === false ? relaxed : leadGaze(skel, relaxed, G);- const { phase, step } = stages(G, spec, fps);- const perf: Performance = { frames: N, pose: (frame) => poses[Math.min(N - 1, Math.max(0, Math.round(frame)))], guide: G, played, phase, step };- if (playedU.some(Boolean)) perf.upper = playedU;- if (o.trace) perf.trace = { stages: { clip: clipStage, blend: raw, plant: planted, elbows: relaxed, gaze: poses }, switches, rate: rates, plant: log };- // RAEA_LINT=1: every performance lints itself and says what it found (its trace kept for that)- if (o.trace && lintEnv() && !o.quiet) console.warn(`[motion lint] ${spec.steps.length} steps, ${N} frames\n` + lintReport(motionLint(lib, perf)));- performances.set(key, perf);- if (performances.size > 64) performances.delete(performances.keys().next().value!);- return perf;+ return settle(lib, spec, o, G, N, key, { raw, contacts, switches, played, playedU, clipStage, rates });}diff --git a/sdk/character/src/matching/settle.ts b/sdk/character/src/matching/settle.tsnew file mode 100644index 00000000..2a5d20a4--- /dev/null+++ b/sdk/character/src/matching/settle.ts@@ -0,0 +1,45 @@+// settle: a performance's passes after it is played (perform.ts): the speed carried through switches, still stretches+// and turns smoothed, an action's feet held, the feet planted or locked, the elbows and hands relaxed, the arms cleared+// of the trunk, the gaze led and the head steadied; then its trace, its lint, and the cache.+import { relaxHands, softElbows, type Pose } from "raea/character";+import { plantFeet, type PlantLog } from "../feet";+import { lockFeet, lockLog } from "../lock";+import { lintReport, motionLint } from "../lint";+import { MotionLibrary, PerformOptions, Performance, PerformanceSpec, carrySpeed, clearArms, holdActionFeet, leadGaze, lintEnv, performances, smoothStill, smoothTurns, stages, steadyHead } from "./all";++/** what playing a performance gives: the poses as played, each frame's foot contacts, the switches, the clips played+ * (the body's and the upper body's own), and for a trace the clips' own frames and the rates */+export interface Played {+ raw: Pose[]; contacts: [number, number][]; switches: number[];+ played: Performance["played"]; playedU: ({ clip: string; f: number } | null)[];+ clipStage: Pose[]; rates: number[];+}++/** the performance from what was played, settled; cached under `key` */+export function settle(lib: MotionLibrary, spec: PerformanceSpec, o: PerformOptions, G: Performance["guide"], N: number, key: string, s: Played): Performance {+ const skel = lib.skel, fps = lib.fps, { raw, contacts, switches, played, playedU, clipStage, rates } = s;+ carrySpeed(raw, switches, fps);+ smoothStill(raw, G);+ if (o.smooth !== 0) smoothTurns(raw, o.smooth ?? 2);+ holdActionFeet(skel, raw, G, contacts);+ // relaxed elbows: the library's arms can swing locked straight+ const log: PlantLog | undefined = o.trace ? { state: [[], []], events: [], drop: [], lift: [[], []] } : undefined;+ const lockL = o.trace ? lockLog() : undefined;+ const feetBy = o.feet ?? (process.env.RAEA_FEET === "plant" ? "plant" : "lock");+ const planted = o.pin === false ? raw : feetBy === "lock" ? lockFeet(skel, raw, contacts, fps, { log: lockL }) : plantFeet(skel, raw, contacts, fps, log);+ const elbowed = planted.map((p) => relaxHands(skel, softElbows(skel, p)));+ // (arms cleared of the trunk again after play, matching/arms.ts; RAEA_CLEAR_ARMS=0 not)+ const relaxed = process.env.RAEA_CLEAR_ARMS !== "0" ? clearArms(skel, elbowed) : elbowed;+ const gazed = o.gaze === false ? relaxed : leadGaze(skel, relaxed, G);+ // (the head held steady (RAEA_STEADY_HEAD=0 not) in the world, matching/head.ts)+ const poses = process.env.RAEA_STEADY_HEAD !== "0" ? steadyHead(skel, gazed, fps) : gazed;+ const { phase, step } = stages(G, spec, fps);+ const perf: Performance = { frames: N, pose: (frame) => poses[Math.min(N - 1, Math.max(0, Math.round(frame)))], guide: G, played, phase, step };+ if (playedU.some(Boolean)) perf.upper = playedU;+ if (o.trace) perf.trace = { stages: { clip: clipStage, blend: raw, plant: planted, elbows: relaxed, gaze: poses }, switches, rate: rates, plant: log, lock: lockL };+ // RAEA_LINT=1: every performance lints itself and says what it found (its trace kept for that)+ if (o.trace && lintEnv() && !o.quiet) console.warn(`[motion lint] ${spec.steps.length} steps, ${N} frames\n` + lintReport(motionLint(lib, perf)));+ performances.set(key, perf);+ if (performances.size > 64) performances.delete(performances.keys().next().value!);+ return perf;+}diff --git a/sdk/character/src/matching/steer.ts b/sdk/character/src/matching/steer.tsnew file mode 100644index 00000000..2d5e5533--- /dev/null+++ b/sdk/character/src/matching/steer.ts@@ -0,0 +1,97 @@+// steer: how perform steers the body. The pace a walk in a state goes at, the library frame a performance starts from,+// the pull that keeps the body on the guide; and the parts of the body a switch's fade treats apart, and each joint's offset in it.+import { qexp, type RigEffect } from "../effects";+import type { Vec3 } from "raea/3d";+import type { Quat, Skeleton } from "raea/character";+import { FUTURE, MotionLibrary, NF, Performance, PerformanceSpec, paceOf, stateMix, wrap } from "./all";++/** the spec with each walk in a state at the state's pace (an old man's is a third of neutral's), unless the step says+ * its own */+export function pacedSpec(lib: MotionLibrary, spec: PerformanceSpec, effects?: Record<string, RigEffect>): PerformanceSpec {+ return effects ? { ...spec, steps: spec.steps.map((st) => {+ const s = ("state" in st && st.state) || spec.state, mix = s ? stateMix(s) : null;+ if (!("walk" in st) || st.speed !== undefined || !mix) return st;+ // the heaviest style the library has frames of sets the pace (its walks' own); the others scale it by their+ // effects' (a library with none of them: its Neutral's pace, or the default walk's, scaled)+ const own = Object.entries(mix).filter(([l]) => paceOf(lib, l) > 0).sort((x, y) => y[1] - x[1])[0];+ let k = own ? paceOf(lib, own[0]) : paceOf(lib, "Neutral") || 1;+ for (const [l, w] of Object.entries(mix)) if (!own || l !== own[0]) k *= (effects[l]?.speed ?? 1) ** w;+ return { ...st, speed: Math.max(0.2, k) };+ }) } : spec;+}++/** where a performance starts: the frame nearest standing still facing ahead (`nearest0` finds it from the features),+ * or a walk entered at speed mid-stride, the frame whose way on is the guide's (`query` asks it) */+export function startFrame(lib: MotionLibrary, spec: PerformanceSpec, nearest0: (s: Float32Array) => number, query: (k: number, t: number) => Float32Array): number {+ const s = new Float32Array(NF);+ for (let d = 0; d < 15; d++) s[d] = lib.mean[d];+ for (let d = 6; d < 15; d++) s[d] = 0;+ let c = 15;+ for (const _ of FUTURE) { s[c++] = 0; s[c++] = 0; }+ for (const _ of FUTURE) { s[c++] = 0; s[c++] = 1; }+ const k0 = nearest0(s);+ // (a walk entered at speed starts mid-stride: the frame whose way on is the guide's, its pose any)+ const first = spec.steps[0];+ if (!(first && "walk" in first && (first.enter ?? 0) > 0.5)) return k0;+ const g = query(k0, 0), F = lib.features;+ let best = k0, bd = Infinity;+ for (let k2 = 0; k2 < lib.size; k2++) {+ if (lib.jump[k2] !== 1) continue;+ let dd = 0;+ for (let d = 15; d < NF; d++) dd += (F[k2 * NF + d] - (g[d] - lib.mean[d]) * lib.scale[d]) ** 2;+ if (dd < bd) { bd = dd; best = k2; }+ }+ return best;+}++/** how the guide pulls the body, and how hard */+export interface Pull { adjust: boolean; aPos: number; aRot: number; adjRatio: number; clampDist: number; pull: number }++/** the body's place (x, z, heading) pulled toward the guide's frame `g`, against where it shows (`w`: u of the way on+ * to the next library frame; at a rate other than 1 the ground frame moves in whole library frames, and pulling that+ * against the guide shakes the body); `from` its place before this frame's library steps */+export function pullToGuide(at: { x: number; z: number; yaw: number }, from: { x: number; z: number; yaw: number }, g: Performance["guide"][number], w: { dx: number; dz: number }, P: Pull) {+ let { x, z, yaw } = at;+ const { adjust, aPos, aRot, adjRatio, clampDist, pull } = P, px0 = from.x, pz0 = from.z, pyaw0 = from.yaw;+ // (a wait with slack pulled only for how far it is past it: a stop at a thing taken in passing overran its spot+ // 8 cm, was pulled back over standing feet, and at the start after them the feet were 10 cm from the clip's)+ let ex = g.x - x - w.dx, ez = g.z - z - w.dz;+ if (g.slack) { const e = Math.hypot(ex, ez), k2 = e > g.slack ? 1 - g.slack / e : 0; ex *= k2; ez *= k2; }+ if (adjust) {+ // Holden's velocity-limited adjustment (docs/locomotion.md 1): a damper toward the guide, but never more in a+ // frame than a share of what the clip itself moves the body (still, nothing pulls; a plant-turn turns only as+ // the clip turns), then clamped to a most distance from it+ const moved = Math.hypot(x - px0, z - pz0), turned = Math.abs(wrap(yaw - pyaw0));+ let ax = ex * aPos, az = ez * aPos;+ const al = Math.hypot(ax, az), cap = adjRatio * moved;+ if (al > cap) { ax *= cap / al; az *= cap / al; }+ x += ax; z += az;+ let ay = wrap(g.yaw - yaw) * aRot;+ const capY = adjRatio * turned;+ if (Math.abs(ay) > capY) ay = Math.sign(ay) * capY;+ yaw += ay;+ const rx = g.x - x - w.dx, rz = g.z - z - w.dz, rl = Math.hypot(rx, rz), lim = Math.max(clampDist, g.slack ?? 0);+ if (rl > lim) { x += rx * (1 - lim / rl); z += rz * (1 - lim / rl); }+ } else {+ x += ex * pull;+ z += ez * pull;+ yaw += wrap(g.yaw - yaw) * pull;+ }+ return { x, z, yaw };+}++/** the skeleton's parts as a switch fades them: the thighs, whether each joint is above the legs, and the trunk (the hips,+ * the spine, the neck and the head, the arms' clavicles not) */+export function fadeParts(skel: Skeleton) {+ // (the legs: the pelvis's children that lead down to a thigh)+ const legOf = (i: number): boolean => i > 0 && (/^thigh_/.test(skel.joints[i].name) || skel.joints.some((j, c) => j.parent === i && legOf(c)));+ const thighs = skel.joints.flatMap((j, i) => (j.parent === 0 && legOf(i) ? [i] : []));+ const upper = skel.joints.map((_, i) => { for (let a = i; a > 0; a = skel.joints[a].parent) if (thighs.includes(a)) return false; return true; });+ // (the trunk: the hips, the spine, the neck and the head, the arms' clavicles not)+ const trunk = skel.joints.map((j, i) => i === 0 || /^(spine|neck|head)/.test(j.name));+ return { thighs, upper, trunk };+}++/** joint i's blend offset at a Hermite fade's weights (the offset's, its velocity's) */+export const offAt = (O: { x: Vec3[]; v: Vec3[] }, i: number, [a, b]: [number, number]): Quat =>+ qexp([O.x[i][0] * a + O.v[i][0] * b, O.x[i][1] * a + O.v[i][1] * b, O.x[i][2] * a + O.v[i][2] * b]);diff --git a/sdk/character/src/ragdoll/body.ts b/sdk/character/src/ragdoll/body.tsindex a874feae..bd18f700 100644--- a/sdk/character/src/ragdoll/body.ts+++ b/sdk/character/src/ragdoll/body.ts@@ -1,15 +1,16 @@// The body: its parts from the skeleton, the sim, and ragdoll().import { add, blend, captured, cross, dot, joint, len, norm, pose as forward, qbasis, qfromTo, qinv, qmul, qnorm, qrot, scale3, sub, surface, type Pose, type Skeleton } from "../character";import { Air, Body, Box, ID, Joint, Q, RagdollOptions, Skin, Sphere, V3, World, angles, clamp, frameFrom, irot, qlog, relative, skinAt, step, swingPose } from "./all";+import { B } from "../character/bones";// ---------------------------------------------------------------- the body/** the parts: name, lead joint, share of the body's mass (de Leva's segments; the hand with the forearm) */const PARTS: [string, string, number][] = [- ["pelvis", "Hips", 0.112], ["abdomen", "LowerBack", 0.163], ["chest", "Spine1", 0.16], ["head", "Neck", 0.069],- ["upperarm.L", "LeftArm", 0.027], ["lowerarm.L", "LeftForeArm", 0.022], ["upperarm.R", "RightArm", 0.027], ["lowerarm.R", "RightForeArm", 0.022],- ["thigh.L", "LeftUpLeg", 0.142], ["shin.L", "LeftLeg", 0.043], ["foot.L", "LeftFoot", 0.014],- ["thigh.R", "RightUpLeg", 0.142], ["shin.R", "RightLeg", 0.043], ["foot.R", "RightFoot", 0.014],+ ["pelvis", B.pelvis, 0.112], ["abdomen", B.spine[0], 0.163], ["chest", B.chest, 0.16], ["head", B.neck, 0.069],+ ["upperarm.L", B.upperarm("L"), 0.027], ["lowerarm.L", B.lowerarm("L"), 0.022], ["upperarm.R", B.upperarm("R"), 0.027], ["lowerarm.R", B.lowerarm("R"), 0.022],+ ["thigh.L", B.thigh("L"), 0.142], ["shin.L", B.calf("L"), 0.043], ["foot.L", B.foot("L"), 0.014],+ ["thigh.R", B.thigh("R"), 0.142], ["shin.R", B.calf("R"), 0.043], ["foot.R", B.foot("R"), 0.014],];/** each joint's limits (radians), heros-journey's: swing about x (flexion), about z (abduction, + outwards on the left),@@ -101,20 +102,19 @@ function buildParts(skel: Skeleton, p: Pose) {const samples: { p: V3; n: V3 }[][] = PARTS.map(() => []);// the contact samples: where (world, at the pose), their normal, and their parts' weightsconst touch: { p: V3; n: V3; parts: [number, number][] }[] = [];- if (skel.surface && skel.skin) {- // each sample to the part whose bones it is nearest (by its skin joint, the pelvis had four: the hips' skin rides- // the thighs and the lower back)+ if (skel.surface) {+ // each sample to the part whose bones it is nearest (by its joint)const bones: { pi: number; a: V3; b: V3 }[] = [];for (let i = 0; i < nc; i++) if (partOf[i] >= 0) bones.push({ pi: partOf[i], a: w.pos[i], b: add(w.pos[i], qrot(w.rot[i], sub(J[i].tail, J[i].head))) });const toSeg = (x: V3, a: V3, b: V3) => { const ab = sub(b, a), l2 = dot(ab, ab), t = l2 > 1e-12 ? clamp(dot(sub(x, a), ab) / l2, 0, 1) : 0; return len(sub(x, add(a, scale3(ab, t)))); };- const S = skel.surface, sk = skel.skin;+ const S = skel.surface;surface(skel, w).forEach((s, i) => {let best = -1, bd = Infinity;for (const bn of bones) { const d = toSeg(s.at, bn.a, bn.b); if (d < bd) { bd = d; best = bn.pi; } }samples[best].push({ p: local(best, s.at), n: irot(w.rot[lead[best]], s.normal) });- // its weights by part (the skin joints' drives'), the least dropped, the main part first+ // its weights by part (its joints'), the least dropped, the main part firstconst by = new Map<number, number>();- S[i].j.forEach((j, k) => { const pi = partOf[sk[j].drive]; if (pi >= 0) by.set(pi, (by.get(pi) ?? 0) + S[i].w[k]); });+ S[i].j.forEach((j, k) => { const pi = partOf[j]; if (pi >= 0) by.set(pi, (by.get(pi) ?? 0) + S[i].w[k]); });const tot = [...by.values()].reduce((a, b) => a + b, 0);const parts = [...by].filter(([, x]) => x > 0.05 * tot).sort((a, b) => b[1] - a[1]);const kept = parts.reduce((a, [, x]) => a + x, 0);@@ -193,7 +193,7 @@ function makeSim(skel: Skeleton, motion: (f: number) => Pose, from: number, o: Rconst ref = parts.map((pt) => {const kind = pt.name.split(".")[0];if (kind !== "upperarm" && kind !== "lowerarm") return ID;- const side = pt.name.endsWith(".L") ? "L" : "R", j = J[joint(skel, side === "L" ? "LeftArm" : "RightArm")];+ const side = pt.name.endsWith(".L") ? "L" : "R", j = J[joint(skel, B.upperarm(side))];return qfromTo(sub(j.tail, j.head), [(side === "L" ? 1 : -1) * Math.sin(HANG), -Math.cos(HANG), 0]);});// an elbow's hinge, in the arm's own frame at rest: the way the motion bends it (the capture's elbow is a hinge, butdiff --git a/sdk/character/src/retarget-ik.ts b/sdk/character/src/retarget-ik.tsnew file mode 100644index 00000000..6ec4028d--- /dev/null+++ b/sdk/character/src/retarget-ik.ts@@ -0,0 +1,210 @@+// The body solved onto a capture frame by frame (retarget's `ik`; Shane, 11-01: "the whole human rig breaks with+// these ... lets do the ik based one"). The rotation transfer (retarget.ts: each joint turned as its source joint+// turned from rest) is only right where the two skeletons stand alike at rest and twist their bones alike, and every+// source broke it its own way (a T-pose, an A-pose, ACCAD's trunk lying along x). Here the capture is taken by where+// its joints are, which no rest pose changes, and the body is solved to it within what a person can do:+//+// the trunk, neck and head point as the source's segments point (pelvis to the chest, the chest to the neck, the+// neck to the head, the head to its crown), each turned no more than it needs (its twist the transfer's);+// an elbow and a knee are hinges: the forearm and the shin bend about the joint's own axis, never back past+// straight, and that bend's plane is what turns the upper arm and the thigh about their length (the transfer's+// twist only while the limb is near straight and the plane says nothing);+// the forearm's turn about its length (the hand's pronation), the wrist, the ankle and the head keep the+// transfer's, held inside a person's range;+// the limbs' bones point where the source's do, at the body's own lengths (a hand goes where the source's goes,+// scaled to the body).+//+// Inputs are world turns from rest (the body's rest frames are the world's) and the source's joint places this frame,+// already faced and in the body's frame (A applied); out come the world turns solved.+import type { Vec3 } from "raea/3d";+import { B, SIDES, cross, dot, joint, len, norm, pose, qaxis, qfromTo, qinv, qmul, qrot, slerp, sub, surface, type Quat, type Side, type Skeleton } from "raea/character";++const DEG = Math.PI / 180;+/** a person's range, degrees: the forearm's turn about its length from rest, the wrist's bend and its turn, the ankle's+ * bend and turn, the head's and neck's turn, the upper arm's and thigh's turn about their length, the shin's */+export const IK_LIMITS = { pronate: 95, wrist: 75, wristTwist: 35, ankle: 50, ankleTwist: 25, neckTwist: 60, armTwist: 95, legTwist: 55, shinTwist: 12 };++/** the twist of turn `q` about unit `axis` (radians), and the turn with it taken out (its swing) */+function swingTwist(q: Quat, axis: Vec3): { swing: Quat; twist: number } {+ const p = dot([q[0], q[1], q[2]], axis);+ let tw: Quat = [axis[0] * p, axis[1] * p, axis[2] * p, q[3]];+ const l = Math.hypot(...tw);+ tw = l < 1e-9 ? [0, 0, 0, 1] : [tw[0] / l, tw[1] / l, tw[2] / l, tw[3] / l];+ const twist = 2 * Math.atan2(dot([tw[0], tw[1], tw[2]], axis), tw[3]);+ return { swing: qmul(q, qinv(tw)), twist: ((twist + 3 * Math.PI) % (2 * Math.PI)) - Math.PI };+}+const clamp = (x: number, lim: number) => Math.max(-lim * DEG, Math.min(lim * DEG, x));+/** `q` with its twist about `axis` held to `lim` degrees and its swing to `swingLim` (if given) */+function held(q: Quat, axis: Vec3, lim: number, swingLim?: number): Quat {+ const { swing, twist } = swingTwist(q, axis);+ let s = swing;+ if (swingLim !== undefined) {+ const a = 2 * Math.acos(Math.min(1, Math.abs(s[3])));+ if (a > swingLim * DEG) s = slerp([0, 0, 0, 1], s, (swingLim * DEG) / a);+ }+ return qmul(s, qaxis(axis, clamp(twist, lim)));+}+/** G turned the least that points its rest bone `rest` along `to` */+const aimed = (G: Quat, rest: Vec3, to: Vec3): Quat => (len(to) < 1e-9 ? G : qmul(qfromTo(qrot(G, rest), to), G));+const smooth = (a: number, b: number, x: number) => { const t = Math.max(0, Math.min(1, (x - a) / (b - a))); return t * t * (3 - 2 * t); };++export interface IkRig {+ /** body joint index -> the source joint it follows (-1 none) */+ src: number[];+ /** a joint's rest bone (to the next joint down its chain, or its own tail) */+ restDir: (i: number) => Vec3;+ /** the source's crown: the head joint's end site, in its own frame (or none) */+ crown?: Vec3;+}++/**+ * The world turns `G` (from rest, the transfer's) solved onto the source's joint places `P` (faced, in the body's+ * frame) and world turns `R` (raw, for the crown's end site), as the header says.+ */+export function solveFrame(skel: Skeleton, rig: IkRig, G: Quat[], P: Vec3[], R: Quat[], A: Quat): Quat[] {+ const out = G.slice(), J = skel.joints, j = (n: string) => joint(skel, n), s = (n: string) => rig.src[j(n)];+ const dirOf = (a: string, b: string): Vec3 | undefined => (s(a) >= 0 && s(b) >= 0 ? sub(P[s(b)], P[s(a)]) : undefined);+ // the pelvis tipped onto the source's hips (up along the hips to the spine), its heading the transfer's+ // (up to the first spine joint that sits clear of the hips: CMU's lower back starts at its hips)+ const pv = j(B.pelvis);+ const above = [...B.spine, B.neck].find((n) => { const d = dirOf(B.pelvis, n); return d && len(d) > 0.03; }), up = above && dirOf(B.pelvis, above);+ // (only a tip: a pelvis the transfer has far off, rolling or flipping, keeps the transfer's)+ if (above && up) {+ const r0 = sub(J[j(above)].head, J[pv].head), off = Math.acos(Math.max(-1, Math.min(1, dot(norm(qrot(out[pv], r0)), norm(up)))));+ const w = 1 - smooth(TIP - 10 * DEG, TIP, off);+ if (w > 0) out[pv] = slerp(out[pv], aimed(out[pv], r0, up), w);+ }+ // the trunk, neck and head along the source's segments+ const trunk: [string, string][] = [[B.spine[0], B.spine[1]], [B.spine[1], B.spine[2]], [B.spine[2], B.neck], [B.neck, B.head]];+ for (const [a, b] of trunk) { const d = dirOf(a, b); if (d && len(d) > 0.01) out[j(a)] = aimed(out[j(a)], sub(J[j(b)].head, J[j(a)].head), d); }+ const h = j(B.head);+ if (rig.crown && s(B.head) >= 0) {+ const crown = qrot(A, qrot(R[s(B.head)], rig.crown));+ // (the head's own bone runs up to its crown)+ out[h] = aimed(out[h], sub(J[h].tail, J[h].head), crown);+ }+ // the head and neck turned about their length no further than a person turns them, against the chest and neck+ for (const [n, p] of [[B.neck, B.chest], [B.head, B.neck]] as const) {+ const i = j(n), local = qmul(qinv(out[j(p)]), out[i]);+ out[i] = qmul(out[j(p)], held(local, norm(rig.restDir(i)), IK_LIMITS.neckTwist));+ }+ for (const side of SIDES) {+ limb(skel, rig, out, P, side, B.upperarm(side), B.lowerarm(side), B.hand(side), [0, 0, 1], { twist: IK_LIMITS.armTwist, mid: IK_LIMITS.pronate, end: IK_LIMITS.wristTwist, endSwing: IK_LIMITS.wrist });+ limb(skel, rig, out, P, side, B.thigh(side), B.calf(side), B.foot(side), [0, 0, -1], { twist: IK_LIMITS.legTwist, mid: IK_LIMITS.shinTwist, end: IK_LIMITS.ankleTwist, endSwing: IK_LIMITS.ankle });+ // the foot along the source's foot (the ankle to the ball)+ const f = j(B.foot(side)), d = dirOf(B.foot(side), B.ball(side));+ if (d) out[f] = aimed(out[f], rig.restDir(f), d);+ }+ return out;+}++/**+ * One limb solved: the upper bone `up` along the source's, its twist from the hinge's plane; the lower bone `mid` bent+ * about the hinge only (toward `bend` at rest: forward for an elbow, back for a knee), never past straight, turned+ * about its length as the transfer had it within `lim.mid`; the end (`end`: the hand, the foot) kept as it was against+ * the lower bone, within its range.+ */+function limb(skel: Skeleton, rig: IkRig, G: Quat[], P: Vec3[], _side: Side, up: string, mid: string, end: string, bend: Vec3, lim: { twist: number; mid: number; end: number; endSwing: number }) {+ const u = joint(skel, up), m = joint(skel, mid), e = joint(skel, end), su = rig.src[u], sm = rig.src[m], se = rig.src[e];+ if (su < 0 || sm < 0 || se < 0) return;+ const ru = norm(rig.restDir(u)), rm = norm(rig.restDir(m)), re = norm(rig.restDir(e));+ // the hinge at rest: the axis that bends the lower bone toward `bend` (forward for an elbow, back for a knee)+ const hinge0 = norm(cross(ru, bend));+ const du = norm(sub(P[sm], P[su])), dm = norm(sub(P[se], P[sm]));+ const theta = Math.acos(Math.max(-1, Math.min(1, dot(du, dm))));+ // the end against the lower bone as the transfer had it (kept through the lower bone's new turn)+ const endLocal = qmul(qinv(G[m]), G[e]);+ // the upper bone along the source's, its twist the transfer's+ let Gu = aimed(G[u], ru, du);+ // the hinge's plane: the twist about the upper bone that lays the hinge across the bend (a bent limb says it)+ const want = norm(cross(du, dm)), have = qrot(Gu, hinge0);+ const w = smooth(8 * DEG, 25 * DEG, theta);+ if (w > 0 && len(cross(du, dm)) > 1e-6) {+ const a = Math.atan2(dot(cross(have, want), du), dot(have, want));+ // (a bend the hinge can't make without the bone turned past a person's range is a limb hyperextended: held straight)+ const tw = swingTwist(qmul(qinv(G[joint(skel, J0(skel, up))]), qmul(qaxis(du, a), Gu)), ru).twist;+ if (Math.abs(tw) <= lim.twist * DEG + 0.35) Gu = qmul(qaxis(du, a * w), Gu);+ }+ // the upper bone's twist against its parent held to a person's range+ const pu = joint(skel, J0(skel, up)), lu = qmul(qinv(G[pu]), Gu);+ Gu = qmul(G[pu], held(lu, ru, lim.twist));+ // the lower bone: the upper's frame bent about the hinge as far as the source bends (none if it bends the wrong way)+ const hingeNow = qrot(Gu, hinge0);+ const signed = Math.atan2(dot(cross(du, dm), hingeNow), dot(du, dm));+ const bentBy = Math.max(0, signed);+ // (the body's rest frames are the world's, and its rest elbow is bent (turbo's by 44°): straight on the upper bone+ // is the upper's turn with the rest bend taken out)+ let Gm = qmul(qaxis(hingeNow, bentBy), qmul(Gu, qfromTo(rm, ru)));+ // its turn about its own length as the transfer had it, within range+ const tw = swingTwist(qmul(qinv(Gm), G[m]), rm).twist;+ Gm = qmul(Gm, qaxis(rm, clamp(tw, lim.mid)));+ // (and laid exactly along the source's lower bone where the hinge alone falls short: a bend off the hinge plane, or a+ // nearly straight limb whose plane is noise, up to a few degrees past straight as real elbows and knees go)+ if (signed > -BACK || theta < LOOSE) Gm = aimed(Gm, rm, dm);+ G[u] = Gu; G[m] = Gm;+ G[e] = qmul(Gm, held(endLocal, re, lim.end, lim.endSwing));+}++/** a joint's parent's name */+function J0(skel: Skeleton, name: string): string {+ const j = skel.joints[joint(skel, name)];+ return skel.joints[j.parent].name;+}++const TRUNK = /^(hips|waist|torso|chest)$/, ARM = /^(palm|foreArm)$/;++/**+ * The arms out of the trunk: a body built wider than the source's (turbo's hips and waist against a slim actor's) has+ * a hanging hand or a forearm across the belly in it. Each arm in it is turned about its shoulder, the way the trunk's+ * skin faces where it goes in deepest, by as little as clears it (a few steps, 30° at most). World turns in and out.+ */+/** the trunk's surface points binned in CELL cubes: a point's neighbours are the 27 cells round it, so an arm point+ * more than CELL from the trunk (well clear, or deeper than any arm goes) skips the search */+const CELL = 0.08;+/** how far past straight an elbow or knee may follow its source */+const BACK = 6 * DEG;+/** the most the pelvis is tipped onto the source's */+const TIP = 35 * DEG;+/** how far an arm may sink into the trunk before it is pushed out (cloth and flesh give that much) */+const SKIN = 0.004;+/** the deepest an arm is taken to be in the trunk (deeper readings are points outside, beside the trunk's edge) */+const REACH = 0.05;+/** a bend this small follows the source whatever its plane: a near-straight limb's plane is noise */+const LOOSE = 20 * DEG;+function cells(pts: { at: Vec3; normal: Vec3 }[]) {+ const bins = new Map<string, { at: Vec3; normal: Vec3 }[]>(), key = (a: number, b: number, c: number) => `${a},${b},${c}`;+ for (const p of pts) { const k = key(...(p.at.map((x) => Math.floor(x / CELL)) as Vec3)); (bins.get(k) ?? bins.set(k, []).get(k)!).push(p); }+ return (at: Vec3) => {+ const [i, j, k] = at.map((x) => Math.floor(x / CELL)), out: { at: Vec3; normal: Vec3 }[] = [];+ for (let a = -1; a <= 1; a++) for (let b = -1; b <= 1; b++) for (let c = -1; c <= 1; c++) out.push(...(bins.get(key(i + a, j + b, k + c)) ?? []));+ return out;+ };+}++export function clearOfTrunk(skel: Skeleton, G: Quat[], nj: number): Quat[] {+ const J = skel.joints, out = G.slice();+ const posed = () => pose(skel, { root: [0, 0, 0], turns: out.map((q, i) => (J[i].parent < 0 ? q : qmul(qinv(out[J[i].parent]), q))).slice(0, nj) });+ for (const s of SIDES) {+ const chain = [B.upperarm(s), B.lowerarm(s), B.hand(s)].map((n) => joint(skel, n));+ let turned = 0;+ for (let k = 0; k < 8; k++) {+ const w = posed(), near = cells(surface(skel, w, TRUNK)), arm = surface(skel, w, ARM, s);+ let deep = 0, at: Vec3 | undefined, n: Vec3 | undefined;+ for (const a of arm) {+ let best = Infinity, d = 0, nn: Vec3 = [0, 0, 0];+ for (const x of near(a.at)) { const v = sub(a.at, x.at), dd = dot(v, v); if (dd < best) { best = dd; d = -dot(v, x.normal); nn = x.normal; } }+ // (a point truly in is no further from the skin than it is deep: a far nearest point is the trunk's other side)+ if (d > deep && best < REACH * REACH) { deep = d; at = a.at; n = nn; }+ }+ if (deep < (turned ? 0.004 : SKIN) || !at || !n) break;+ const sh = w.pos[chain[0]], arm0 = sub(at, sh), axis = cross(arm0, n);+ if (len(axis) < 1e-6) break;+ const step = Math.min(30 * DEG - turned, (deep + 0.004) / Math.max(0.1, len(arm0)));+ if (step <= 0) break;+ const q = qaxis(norm(axis), step);+ for (const i of chain) out[i] = qmul(q, out[i]);+ turned += step;+ }+ }+ return out;+}diff --git a/sdk/character/src/retarget.ts b/sdk/character/src/retarget.tsnew file mode 100644index 00000000..3c6b5b0e--- /dev/null+++ b/sdk/character/src/retarget.ts@@ -0,0 +1,295 @@+// A BVH retargeted onto a character (docs/skeleton.feature SK3, SK5, SK6): the psx trials' method (projects/psx,+// trials/T4-body/retarget.py), measured there on CMU 02_01 and 100STYLE's Neutral and Old walks.+//+// The character's skeleton is MakeHuman's game_engine rig in its own A-pose, every joint's rest frame the world's; a+// BVH's rest is its actor's T-pose, its frames the world's too. A source map (sdk/raea/tools/maps/<source>.json) names+// the source joint each body joint follows. Each frame, a joint's turn in the body's frame is+//+// G = A · S · A⁻¹ · F+//+// S the source joint's world turn from its rest, A the facing (a turn about up only: a lean in it tipped the clip+// and sank a walker 17 cm), and F the rest fix: each limb bone laid along its source bone at rest (the T-pose's arms+// onto the A-pose's), the hand along the forearm (no source hand has a length), the forearm and hand twisted so the+// thumb goes where the source's does (palms down for a source without a thumb). The trunk, neck and head keep their+// own build and take the capture's turns from rest. The pelvis travels as the source's hips do, scaled by the hips'+// height over the feet.+import { B, SIDES, captured, joint, pose, qaxis, qfromTo, qinv, qmul, qnorm, qrot, slerp, sub, type Quat, type Skeleton } from "raea/character";+import type { Vec3 } from "raea/3d";+import { clipFrame, type Bvh, type Clip } from "./clip";+import { clearOfTrunk, solveFrame, type IkRig } from "./retarget-ik";++/** retarget solved onto the capture's joint places (retarget-ik.ts) */+export const retargetIK = (skel: Skeleton, b: Bvh, o: RetargetOptions): Clip => retarget(skel, b, { ...o, ik: true });++/** The clavicle's share of the arm's elevation off rest. 0: the capture's own clavicles, turned from the body's rest,+ * already carry the shoulder's rhythm (0.3 was set while clavicles took their source's slope, and sank them 6° more) */+export const SHRUG = 0;+/** how far it turns, degrees: down, up */+const SHRUG_LIMIT: [number, number] = [-20, 25];+/** both arms raised past this off hanging (degrees) is a T-pose: such frames at a clip's ends are left out */+const T_POSE = 70;++const DEG = Math.PI / 180;+const len = (v: Vec3) => Math.hypot(v[0], v[1], v[2]);+const nrm = (v: Vec3): Vec3 => { const l = len(v) || 1; return [v[0] / l, v[1] / l, v[2] / l]; };+const dotv = (a: Vec3, b: Vec3) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];+const crossv = (a: Vec3, b: Vec3): Vec3 => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];+const angle = (a: Vec3, b: Vec3) => Math.acos(Math.max(-1, Math.min(1, dotv(nrm(a), nrm(b)))));+/** v with its part along `axis` (a unit vector) taken out */+const across = (v: Vec3, axis: Vec3): Vec3 => nrm(sub(v, [axis[0] * dotv(v, axis), axis[1] * dotv(v, axis), axis[2] * dotv(v, axis)]));++/** A BVH frame's turns (from its rest, relative to the parent) and its root's place, in BVH units. */+function bvhFrame(b: Bvh, values: number[]): { root: Vec3; turns: Quat[] } {+ let c = 0;+ let root: Vec3 = [0, 0, 0];+ const turns = b.joints.map((j) => {+ let q: Quat = [0, 0, 0, 1];+ for (const ch of j.channels) {+ const v = values[c++];+ if (ch === "Xposition") root = [v, root[1], root[2]];+ else if (ch === "Yposition") root = [root[0], v, root[2]];+ else if (ch === "Zposition") root = [root[0], root[1], v];+ // the channels in their order, each about the frame the ones before left (R = R1·R2·R3)+ else q = qmul(q, qaxis(ch[0] === "X" ? [1, 0, 0] : ch[0] === "Y" ? [0, 1, 0] : [0, 0, 1], v * DEG));+ }+ return q;+ });+ return { root, turns };+}++/** a BVH frame's world turns and places (forward kinematics from its offsets) */+function bvhWorld(b: Bvh, f: { root: Vec3; turns: Quat[] }): { rot: Quat[]; pos: Vec3[] } {+ const rot: Quat[] = [], pos: Vec3[] = [];+ b.joints.forEach((j, i) => {+ if (j.parent < 0) { rot[i] = f.turns[i]; pos[i] = f.root; return; }+ const p = j.parent, o = qrot(rot[p], j.offset);+ rot[i] = qmul(rot[p], f.turns[i]);+ pos[i] = [pos[p][0] + o[0], pos[p][1] + o[1], pos[p][2] + o[2]];+ });+ return { rot, pos };+}++/** The body joint each limb bone aims at (its next joint down the limb), and the bone the hand carries on from. */+const AIM: Record<string, string> = Object.fromEntries(SIDES.flatMap((s) => [+ [B.clavicle(s), B.upperarm(s)], [B.upperarm(s), B.lowerarm(s)], [B.lowerarm(s), B.hand(s)],+ [B.thigh(s), B.calf(s)], [B.calf(s), B.foot(s)], [B.foot(s), B.ball(s)],+]));++export interface RetargetOptions {+ name: string;+ fps?: number;+ /** metres a BVH unit (ACCAD's cm 0.01, cgspeed's CMU 0.056444): with it the clip records its `scale`, the body's+ * hip height over the actor's, for Froude-scaled play; without, no scale */+ unit?: number;+ /** seconds of the BVH to take */+ from?: number;+ to?: number;+ /** body joint -> the BVH's joint (a source map); by the skeleton's own names when left out. A body joint left out+ * holds still against its parent. `thumb_01_l`/`_r` name the source's thumb, if it has one (its end site is where+ * the thumb points). */+ map?: Record<string, string>;+ /** the clavicles' share of the arm's elevation (SHRUG by default; 0 leaves the capture's clavicles) */+ shrug?: number;+ /** keep T-pose frames at the ends (left out by default) */+ keepTPose?: boolean;+ /** passes of the five-frame smoothing over each joint's turn (1 by default; 0 keeps the capture's every flicker) */+ smooth?: number;+ /** the neck's and head's mean turns to take out (a clip's `carriage`: one actor's neutral walk), so they move about+ * the body's own carriage as the capture moves about its; the clip's own mean when left out, none with false */+ carriage?: Record<string, Quat> | false;+ /** a frame of channel values the BVH's turns are measured from instead of its zero pose: for a source whose zero+ * pose isn't its actor standing (ACCAD's MotionBuilder exports lie the trunk along x at zero; their actors stand+ * in each one's A1_Stand), so its rest is that frame, turned to face +z */+ rest?: number[];+ /** solve the body onto the capture's joint places within a person's range (retarget-ik.ts) rather than transfer+ * each joint's turn; the neck and head then follow the capture's, not a carriage */+ ik?: boolean;+}++/** A BVH retargeted onto a skeleton, resampled to `fps`, from `from` to `to` seconds. The BVH's up is y and its actor+ * faces +z at rest (cgspeed's CMU files and 100STYLE's do); its travel is scaled by the hips' height. */+export function retarget(skel: Skeleton, b: Bvh, o: RetargetOptions): Clip {+ const fps = o.fps ?? 30, shrug = o.shrug ?? SHRUG;+ const J = skel.joints.slice(0, captured(skel)), nj = J.length;+ const srcOf = (name: string) => {+ const want = o.map ? o.map[name] : name;+ if (!want) return -1;+ const i = b.joints.findIndex((x) => x.name === want);+ if (i < 0 && o.map) throw new Error(`retarget ${o.name}: the map sends ${name} to ${want}, which the BVH hasn't`);+ return i;+ };+ const src = J.map((j) => srcOf(j.name));+ if (src[0] < 0) throw new Error(`retarget ${o.name}: the BVH has no joint for the root ${J[0].name}`);+ const need = [B.thigh("L"), B.thigh("R"), B.foot("L"), B.foot("R")];+ for (const n of need) if (src[joint(skel, n)] < 0) throw new Error(`retarget ${o.name}: the BVH has no joint for ${n}`);+ const S = (n: string) => src[joint(skel, n)];+ const T = (n: string) => J[joint(skel, n)].head;+ // the source at rest (its rest frames are the world's), or at its `rest` frame, every joint's turn there taken as+ // its rest (Rf: what each world turn is measured from)+ const zero = bvhWorld(b, { root: [0, 0, 0], turns: b.joints.map(() => [0, 0, 0, 1] as Quat) });+ let R0 = zero.pos, Rf: Quat[] | undefined;+ if (o.rest) {+ const w = bvhWorld(b, { ...bvhFrame(b, o.rest), root: [0, 0, 0] });+ const lt = sub(w.pos[S(B.thigh("L"))], w.pos[S(B.thigh("R"))]);+ // its left onto +x, so it faces +z+ const Y = qfromTo(nrm([lt[0], 0, lt[2]]), [1, 0, 0]);+ R0 = w.pos.map((p) => qrot(Y, p));+ Rf = w.rot.map((q) => qinv(qmul(Y, q)));+ }+ // the facing: a turn about up taking the source's left (its left thigh from its right) onto the body's+ const flatX = (v: Vec3) => nrm([v[0], 0, v[2]]);+ const A = qfromTo(flatX(sub(R0[S(B.thigh("L"))], R0[S(B.thigh("R"))])), flatX(sub(T(B.thigh("L")), T(B.thigh("R")))));+ const Ai = qinv(A);+ // the source scaled to the body by the hips' height over the feet at rest+ const feetS = [B.foot("L"), B.foot("R"), B.ball("L"), B.ball("R")].map(S).filter((i) => i >= 0);+ const hs = R0[src[0]][1] - Math.min(...feetS.map((i) => R0[i][1]));+ const ht = J[0].head[1] - Math.min(...B.feet().map((n) => T(n)[1]));+ const k = ht / hs;+ // the rest fix F per joint+ const fix: Quat[] = J.map(() => [0, 0, 0, 1] as Quat);+ const restDir = (i: number): Vec3 => {+ const c = J.findIndex((x) => x.parent === i && AIM[J[i].name] === x.name);+ return c >= 0 ? sub(J[c].head, J[i].head) : sub(J[i].tail, J[i].head);+ };+ J.forEach((j, i) => {+ const aim = AIM[j.name];+ // (not the clavicles: a capture's shoulder joints sit where its markers put them, ACCAD's sloped 34 degrees and CMU's+ // nearly level, so a clavicle laid along its source's took that marker set's slope; it moves from the body's own rest)+ if (aim !== undefined && src[i] >= 0 && !SIDES.some((s) => j.name === B.clavicle(s))) {+ const si = src[joint(skel, aim)];+ const sd = si >= 0 ? sub(R0[si], R0[src[i]]) : undefined;+ if (sd && len(sd) > 1e-6) fix[i] = qfromTo(restDir(i), qrot(A, sd));+ }+ });+ for (const s of SIDES) {+ const h = joint(skel, B.hand(s)), fa = joint(skel, B.lowerarm(s));+ // the hand along the forearm: its rest bone turned as the forearm's was, then onto the source forearm's line+ if (src[h] >= 0 && src[fa] >= 0) {+ const sd = qrot(A, sub(R0[src[h]], R0[src[fa]]));+ fix[h] = qfromTo(sub(J[h].tail, J[h].head), sd);+ }+ // the forearm and hand twisted about their own length so the thumb goes the source's way (forward if it has none)+ const thumbName = o.map?.[B.finger("thumb", 1, s)];+ const ti = thumbName ? b.joints.findIndex((x) => x.name === thumbName) : -1;+ const want: Vec3 = ti >= 0 && b.joints[ti].end ? qrot(A, sub(add3(R0[ti], b.joints[ti].end!), R0[src[h]])) : [0, 0, 1];+ const thumb0 = sub(skel.joints[joint(skel, B.finger("thumb", 1, s))].head, J[h].head);+ for (const i of [fa, h]) {+ if (src[i] < 0) continue;+ const axis = nrm(qrot(fix[i], restDir(i)));+ const have = across(qrot(fix[i], thumb0), axis), to = across(want, axis);+ const a = angle(have, to) * (dotv(crossv(have, to), axis) > 0 ? 1 : -1);+ fix[i] = qmul(qaxis(axis, a), fix[i]);+ }+ }+ // the shoulders' rest: each upper arm's elevation off hanging along the chest, in the body at rest+ const chest = joint(skel, B.chest);+ const chestUp = nrm(restDir(chest));+ const elevation = (arm: Vec3, up: Vec3) => angle(arm, [-up[0], -up[1], -up[2]]) / DEG;+ const restElev = Object.fromEntries(SIDES.map((s) => [s, elevation(restDir(joint(skel, B.upperarm(s))), chestUp)]));+ // T-pose frames at the ends (the source's own arms raised past T_POSE on both sides)+ const dur = (b.frames.length - 1) * b.frameTime;+ let t0 = Math.max(0, o.from ?? 0), t1 = Math.min(dur, o.to ?? dur);+ if (!o.keepTPose) {+ const raised = (t: number) => {+ const w = bvhWorld(b, bvhFrame(b, b.frames[Math.min(b.frames.length - 1, Math.round(t / b.frameTime))]));+ const up = sub(w.pos[S(B.head)] ?? w.pos[src[0]], w.pos[src[0]]);+ return SIDES.every((s) => {+ const a = S(B.upperarm(s)), f = S(B.lowerarm(s));+ return a >= 0 && f >= 0 && elevation(sub(w.pos[f], w.pos[a]), up) > T_POSE;+ });+ };+ // (a clip held in a T-pose throughout is a pose, not a calibration: kept)+ let a = t0, z = t1;+ while (a < z && raised(a)) a += 1 / fps;+ while (z > a && raised(z)) z -= 1 / fps;+ if (a < z) { t0 = a; t1 = z; }+ }+ const n = Math.max(1, Math.floor((t1 - t0) * fps) + 1);+ const root = new Float32Array(n * 3), turns = new Float32Array(n * nj * 4);+ const clav = SIDES.map((s) => [joint(skel, B.clavicle(s)), joint(skel, B.upperarm(s))]);+ const headS = S(B.head), rig: IkRig | undefined = o.ik ? { src, restDir, crown: headS >= 0 ? b.joints[headS].end : undefined } : undefined;+ for (let f = 0; f < n; f++) {+ const at = (t0 + f / fps) / b.frameTime;+ const a = Math.min(b.frames.length - 1, Math.floor(at)), c = Math.min(b.frames.length - 1, a + 1), u = at - a;+ const FA = bvhFrame(b, b.frames[a]), FB = bvhFrame(b, b.frames[c]);+ const fr = { root: lerp3(FA.root, FB.root, u), turns: FA.turns.map((q, i) => slerp(q, FB.turns[i], u)) };+ const ws = bvhWorld(b, fr), raw = ws.rot;+ if (Rf) ws.rot = ws.rot.map((q, i) => qmul(q, Rf![i]));+ const G: Quat[] = [];+ for (let i = 0; i < nj; i++) {+ const p = J[i].parent;+ G[i] = src[i] >= 0 ? qnorm(qmul(qmul(qmul(A, ws.rot[src[i]]), Ai), fix[i])) : p < 0 ? [0, 0, 0, 1] : G[p];+ }+ // the shoulder rhythm: each clavicle turned by `shrug` of its arm's elevation off rest (the upper arm keeps its+ // captured world turn, so the arm still points where the capture's does)+ if (shrug) SIDES.forEach((s, si) => {+ const [ci, ui] = clav[si];+ if (src[ci] < 0 || src[ui] < 0) return;+ const up = nrm(qrot(G[chest], restDir(chest)));+ const e = elevation(qrot(G[ui], restDir(ui)), up);+ const lift = Math.max(SHRUG_LIMIT[0], Math.min(SHRUG_LIMIT[1], shrug * (e - restElev[s])));+ const d = nrm(qrot(G[ci], restDir(ci)));+ G[ci] = qnorm(qmul(qaxis(nrm(crossv(up, d)), -lift * DEG), G[ci]));+ });+ if (rig) { const solved = solveFrame(skel, rig, G, ws.pos.map((x) => qrot(A, x)), raw, A); G.splice(0, G.length, ...(clearOfTrunk(skel, solved, nj))); }+ for (let i = 0; i < nj; i++) {+ const p = J[i].parent;+ turns.set(p < 0 ? G[i] : qmul(qinv(G[p]), G[i]), (f * nj + i) * 4);+ }+ const r = qrot(A, fr.root);+ root.set([r[0] * k, r[1] * k, r[2] * k], f * 3);+ }+ // the neck and head carried as the body carries them, moving about it as the capture moves about its mean (the+ // capture's own carriage onto a body of another build put the head 18 degrees off and read wrong). The mean is the+ // clip's own or `carriage` (one actor's neutral walk), so a style's own carriage (an old man's hanging head) stays+ const carriage: Record<string, Quat> = {};+ if (o.carriage !== false && !o.ik) for (const name of [B.neck, B.head]) {+ const i = joint(skel, name);+ let mq = o.carriage?.[name];+ if (!mq) {+ const m = [0, 0, 0, 0];+ for (let f = 0; f < n; f++) {+ const o4 = (f * nj + i) * 4, sg = turns[o4 + 3] < 0 ? -1 : 1;+ for (let a = 0; a < 4; a++) m[a] += sg * turns[o4 + a];+ }+ mq = qnorm(m as Quat);+ }+ carriage[name] = mq;+ const off = qinv(mq);+ for (let f = 0; f < n; f++) {+ const o4 = (f * nj + i) * 4;+ turns.set(qmul(off, Array.from(turns.subarray(o4, o4 + 4)) as Quat), o4);+ }+ }+ // a capture's frame-to-frame noise (toe markers flick, a solved hand jumps a frame) taken out: each joint's turn the+ // binomial mean of the five frames round it, `smooth` times over (1, a 30 fps clip's default: under a frame of lag)+ for (let pass = 0; pass < (o.smooth ?? 1); pass++) {+ const was = turns.slice();+ for (let f = 0; f < n; f++) for (let i = 0; i < nj; i++) {+ const c = (f * nj + i) * 4, m = [0, 0, 0, 0];+ for (const [d, w] of TAPS) {+ const o4 = (Math.min(n - 1, Math.max(0, f + d)) * nj + i) * 4;+ const sg = was[o4] * was[c] + was[o4 + 1] * was[c + 1] + was[o4 + 2] * was[c + 2] + was[o4 + 3] * was[c + 3] < 0 ? -w : w;+ for (let a = 0; a < 4; a++) m[a] += sg * was[o4 + a];+ }+ turns.set(qnorm(m as Quat), c);+ }+ }+ // feet on the floor: the clip lifted so its lowest ball, over the clip, is at the balls' height at rest (feet.ts+ // plants them frame by frame)+ const clip: Clip = { name: o.name, fps, frames: n, root, turns, carriage, ...(o.unit ? { scale: k / o.unit } : {}) };+ const balls = SIDES.map(B.ball).map((x) => joint(skel, x));+ let low = Infinity;+ for (let f = 0; f < n; f++) {+ const w = pose(skel, clipFrame(clip, f, nj));+ for (const t of balls) low = Math.min(low, w.pos[t][1]);+ }+ const lift = J[balls[0]].head[1] - low;+ for (let f = 0; f < n; f++) root[f * 3 + 1] += lift;+ return clip;+}++/** the binomial five taps (frame offset, weight) */+const TAPS: [number, number][] = [[-2, 1 / 16], [-1, 4 / 16], [0, 6 / 16], [1, 4 / 16], [2, 1 / 16]];+const add3 = (a: Vec3, b: Vec3): Vec3 => [a[0] + b[0], a[1] + b[1], a[2] + b[2]];+const lerp3 = (a: Vec3, b: Vec3, u: number): Vec3 => [a[0] + (b[0] - a[0]) * u, a[1] + (b[1] - a[1]) * u, a[2] + (b[2] - a[2]) * u];diff --git a/sdk/character/src/style.ts b/sdk/character/src/style.tsindex e7ea2f65..e559e8f6 100644--- a/sdk/character/src/style.ts+++ b/sdk/character/src/style.ts@@ -10,7 +10,7 @@// Every measurement is in the body's own ground frame (x its left, z ahead), in metres, degrees, seconds or ratios,// and is the same for a clip and its mirror image except the signed ones (trunkRoll, asym*), which flip.import type { Vec3 } from "raea/3d";-import { captured, joint, pose, qrot, sub, type Posed, type Skeleton } from "raea/character";+import { B, SIDES, captured, joint, pose, qrot, sub, type Posed, type Skeleton } from "raea/character";import { framePose, type Clip } from "./clip";/** the measurements, in order, with what each one is */@@ -54,8 +54,8 @@ const angleAt = (a: Vec3, b: Vec3, c: Vec3) => {/** The style of a clip's frames f0 to f1 (exclusive). */export function styleOf(skel: Skeleton, c: Clip, f0: number, f1: number): StyleVector {const J = (n: string) => joint(skel, n);- const [hips, neck, head, arm, fore, hand, up, leg, foot, toe] = [J("Hips"), J("Neck"), J("Head"), ["LeftArm", "RightArm"].map(J), ["LeftForeArm", "RightForeArm"].map(J),- ["LeftHand", "RightHand"].map(J), ["LeftUpLeg", "RightUpLeg"].map(J), ["LeftLeg", "RightLeg"].map(J), ["LeftFoot", "RightFoot"].map(J), ["LeftToeBase", "RightToeBase"].map(J)];+ const [hips, neck, head, arm, fore, hand, up, leg, foot, toe] = [J(B.pelvis), J(B.neck), J(B.head), SIDES.map(B.upperarm).map(J), SIDES.map(B.lowerarm).map(J),+ SIDES.map(B.hand).map(J), SIDES.map(B.thigh).map(J), SIDES.map(B.calf).map(J), SIDES.map(B.foot).map(J), SIDES.map(B.ball).map(J)];const R = skel.joints.map((j) => j.head);const restHips = R[hips][1], restKnee = R[leg[0]][1], restShoulder = (R[arm[0]][1] + R[arm[1]][1]) / 2 - R[neck][1];const ankleRest = R[foot[0]][1], toeRest = R[toe[0]][1];diff --git a/sdk/character/src/things.ts b/sdk/character/src/things.tsindex f2d26e83..0db9d9d1 100644--- a/sdk/character/src/things.ts+++ b/sdk/character/src/things.ts@@ -50,6 +50,10 @@ export interface Thing {/** solid down to the floor (a plinth, a chest, a counter's kickboard flush with its front): no room under its edge,* so a body bending its knees to reach onto it stands further back */solid?: boolean;+ /** carried upright (a cup of coffee, a glass of water: open, with something in it): in one hand before the body,+ * the forearm out, swung little, the wrist keeping it stood up; by default a thing in one hand hangs at the side+ * and swings with the walk, as the hand has it (a wrapped cup on a hanging arm lies on its side) */+ upright?: boolean;/** handles (by default it is held by its sides, round its middle or from under it) */grips?: Grip[];/** how hands take it (grasp.ts, docs/grasp-guides.feature): cylinders, pinches, spheres and slabs in its frame,@@ -241,8 +245,9 @@ export function handling(t: Thing, height: number): Handling {const weight = load < 0.03 ? "light" : load < 0.12 ? "medium" : load < 0.35 ? "heavy" : "immovable";const s = shapeOf(t), hand = 0.1 * height; // a hand spans about a tenth of the heightconst wide = Math.max(t.size[0], s === "box" ? t.size[2] : 0);- // (a pencil, a brush, a spoon: thin, light and no longer than two hands, held as it is written with)- if (s === "pole" && weight === "light" && t.size[0] < 0.15 * hand && t.size[2] < 2.5 * hand) return { grip: "tripod", hands: 1, load, weight };+ // (a pencil, a brush, a spoon: thin, light and no longer than two hands, picked up between the thumb and index;+ // the tripod is how it is written with, not how it is taken off a table: Shane, 11-01)+ if (s === "pole" && weight === "light" && t.size[0] < 0.15 * hand && t.size[2] < 2.5 * hand) return { grip: "pinch", hands: 1, load, weight };if (s === "pole") return { grip: "pole", hands: weight === "light" && t.size[2] < 0.5 * height ? 1 : 2, load, weight };if (t.grips?.length && weight !== "heavy") return { grip: t.grips[0].kind === "stem" ? "stem" : "handle", hands: 1, load, weight };// (a ball too big or heavy for a palm is held from under, whatever it weighs: hugged, its curve rolls off the arms)diff --git a/sdk/guides/craft/NOTICE b/sdk/guides/craft/NOTICEindex 05d525af..7b5bb518 100644--- a/sdk/guides/craft/NOTICE+++ b/sdk/guides/craft/NOTICE@@ -15,11 +15,12 @@ interfaces:What raea took: the order of work (context, shaping questions, a direction someone approved, a floor read beforeevery edit, then evidence), modes that say what success looks like, directions dealt from a larger set, short-playbooks for refinement verbs, and critiques ranked P0-P3 that a polish pass works through. raea's guides are+guides for refinement moves, and critiques ranked P0-P3 that a polish pass works through. raea's guides arewritten for video, motion, 3D and games. This NOTICE is the only place in the guides that names the source.Written new by raea (2026-10-24), following the method without copying its text:ROUTER.md, floor.md, rubric.md, modes/*.md (pitch, explain, story, play, tool), verbs/*.md (critique, polish,- quieter, bolder, distill, clarify, retime, recut, regrade, remix, harden)+ quieter, bolder, distill, clarify, retime, recut, regrade, remix, harden; on 2026-11-05 layout, typeset, animate,+ delight, adapt, optimize, extract, generate)raea's own, adapting nothing: motion.md and motion/, bevy.md and bevy/ (see bevy/NOTICE).diff --git a/sdk/guides/craft/ROUTER.md b/sdk/guides/craft/ROUTER.mdindex 36329dc1..69fd1e5e 100644--- a/sdk/guides/craft/ROUTER.md+++ b/sdk/guides/craft/ROUTER.md@@ -16,18 +16,18 @@ Two rules come before everything else:Run `raea context PROJECT` before anything else and read all of it. It prints, in order:-1. **Taste** (`~/.raea/taste/`): the person's standing corrections, across every project. A line there beats any- guide.-2. **The brief** (`brief.brief`): who it's for (`audience`), the one thing they should think afterwards (`believe`),+1. **Taste** (`~/.raea/taste/taste.ts`, then the workspace's `taste.ts`): the person's standing corrections, across+ every project. A line there beats any guide.+2. **The brief** (`brief.ts`): who it's for (`audience`), the one thing they should think afterwards (`believe`),what kind of piece it is (`mode`), the narrator and tone (`voice`), what it delivers, the tasks and the agents.- Deliverables can have their own briefs, with a storyboard (`.board`) and a `## Direction`.-3. **The look** (`## Look`, and `brand/brand.css` when there is one): the project's committed world.+ Deliverables can have their own briefs, with a storyboard (`NAME.script.ts`) and a direction.+3. **The look** (the brief's `look`, and `brand/brand.css` when there is one): the project's committed world.4. **The floor**: what breaks a piece, read again right before every edit.5. **One guide per mode**: what that kind of piece has to do.If it says the brief isn't shaped (no `believe`, no `mode`), shape it before making anything. Ask two or three-questions, each with your best guess, or write your guess with `(assumed)` after it and go on. The person confirms-assumed facts later.+questions, each with your best guess, or write your guess and add its field to the brief's `assumed` list, and go on. The person+confirms assumed facts later.## Modes@@ -52,7 +52,7 @@ leads. raea will add modes as its work grows; `raea context` says when a brief n3. **Plan:** for a pitch, an explain or a story, a storyboard file (scene · on screen · narration · payoff) and acamera map, approved by the person before anything renders.4. **Direction:** when the look or the structure is open, offer real options made with raea, and write the chosen- one into the deliverable's brief as `## Direction`.+ one into the deliverable's brief as a section headed "Direction".5. **The floor:** read it right before you edit.6. **Make it.**7. **Evidence:** run `raea check`, look at the frames, critique against the mode's guide, fix, and look again.@@ -74,12 +74,24 @@ moment it names:- **regrade:** colour and light;- **remix:** the sound;- **harden:** a game's edge cases;+- **layout:** where things sit and how much room each gets;+- **typeset:** the type on screen;+- **animate:** motion added to what holds still;+- **delight:** one small detail that rewards attention;+- **adapt:** another size, length or platform;+- **optimize:** smaller files, faster renders, smooth play;+- **extract:** a brand kit read from finished work;+- **generate:** variants of one element to pick from;- **polish:** close out the latest critique;- **critique:** judge the piece honestly before you call it done.-Each move has a short playbook: `raea guide quieter` (and the rest). Read the one a note calls for before you act on+Each move has a short guide: `raea guide quieter` (and the rest). Read the one a note calls for before you act onit. Never show these words to the person. Answer the note in their terms.+raea has no colorize, onboard, overdrive or audit move. Colour is **regrade**; more of everything is **bolder** on+the one beat that earns it, never on all of them; an audit is `raea check` and then **critique**; a game's first+seconds are part of its mode (`raea guide play`), not a note.+A note reaches you with the move already named when the feed can tell (`{verb, part or moment, words}`). The person'swords still come first: if they say more than the verb, do what they say.diff --git a/sdk/guides/craft/bevy.md b/sdk/guides/craft/bevy.mdindex dc381750..a328acb6 100644--- a/sdk/guides/craft/bevy.md+++ b/sdk/guides/craft/bevy.md@@ -25,6 +25,7 @@ pieces; then write the file. Each file's example is a complete composition you c| moving things: spins, springs, reveals, things arriving later, model clips | `bevy/animation` || a 3D game: state, input, many entities, collisions, state machines | `bevy/games` || glTF models, pictures in space, where files go | `bevy/assets` |+| an asset to fix in Blender first (scale, pivot, heavy mesh, FBX/OBJ, rig, bake); never a whole scene | `bevy/blender` || a real scene or object from footage as gaussian splats, and animating them (assemble, disperse, morph...) | `bevy/splats` || liquids and goo: coffee dumped from a mug, a tap's stream, honey, things melting | `bevy/liquids` || bloom, fog, tone mapping, exposure, fisheye and lens distortion, motion blur | `bevy/post` |diff --git a/sdk/guides/craft/bevy/blender.md b/sdk/guides/craft/bevy/blender.mdnew file mode 100644index 00000000..0094d356--- /dev/null+++ b/sdk/guides/craft/bevy/blender.md@@ -0,0 +1,84 @@+# Blender: fixing an asset before it goes in a scene++## When Blender, when raea++- **raea** makes anything that renders or plays: the scene, its camera, lights, motion, materials, people and games.+ Build those in TSX (the other `bevy/` topics), never in Blender.+- **Blender** fixes an asset on its way in: a model at the wrong scale or with its origin off to one side, a mesh too+ heavy to draw, a format raea can't load (FBX, OBJ, .blend), a rig to retarget, a texture or light to bake into a+ mesh. One asset at a time, out to a `.glb` under the project's `media/`, then into a scene with `<Model>`+ (`bevy/assets`).+- Never build a whole scene in Blender and export it; the scene belongs in TSX, where it's frame-pure and checked+ (`raea scene lint`).++## Setting it up — HEADLESS++- `raea setup blender` finds a Blender (`git config --global raea.blender PATH`, `/Applications/Blender.app`, then+ `blender` on PATH) or downloads the current LTS from blender.org into `~/.raea/tools/blender`, checked against+ blender.org's sha256 list. raea never bundles Blender: it's GPL, so it runs as its own program.+- The same command installs the MCP for Blender add-on into that Blender (it needs uv's `uvx`).+ `raea setup blender --check` only reports.++## Headless: `raea blender run` — HEADLESS++`raea blender run SCRIPT.py [ARGS...]` runs the script in a windowless Blender (`--background --factory-startup`);+the script reads its own arguments after `--` in `sys.argv`, and an uncaught Python error makes the command fail.+Use it for every fix an agent can describe in code: convert, clean, decimate, set scale and pivot, re-rig, bake.++## Live: the `blender` MCP server — BLENDER++`raea skills install --agent claude|codex|kimi|gemini` registers a `blender` MCP server for the agent+(`uvx mcp-for-blender`). Its tools (look, scene info, run Python, search and import Poly Haven, Sketchfab and+Poly Pizza assets, generate a model) need a Blender running with its window open: tag such a step **BLENDER**, and+give the headless `raea blender run` way beside it. `generate_3d` can cost the person a credit; ask first.+In the raea app, a workspace gives it to the feed's agents with a controller's servers field holding+`uvx mcp-for-blender` (`raea controller set PATH VALUE`).++## Licences++Only permissive assets (CC0, CC BY with its credit, MIT). Write the source, licence and credit beside the `.glb`+(`chair.glb.json`: `{"source": URL, "license": "CC0", "credit": ""}`), and keep them through every fix.++## Common mistakes++- Building the scene in Blender: export one asset, build the scene in TSX.+- Judging scale by eye: read the model's bounds in the script and scale to a size in metres (a chair seat is+ 0.45 m high), with the origin at the bottom centre so it stands on the floor at `position={[x, 0, z]}`.+- Hardcoding shader node names: they're localized; find nodes by `type` (`BSDF_PRINCIPLED`).+- Exporting `.gltf` with loose files: export `.glb`, one file.+- Moving a rigged model's mesh: the example is for a static model. A rigged one moves with its armature, so scale+ and place the armature (the mesh's parent) and apply its transform, or the skin pulls the mesh back.++## Example: scale and pivot fixed, out as one .glb++`raea blender run fix.py media/chair.fbx media/chair.glb 0.9` imports the file, makes it 0.9 m tall, puts its origin+at the bottom centre and exports a `.glb`:++```python+import bpy, sys+src, out, height = sys.argv[sys.argv.index("--") + 1:][:3]+bpy.ops.wm.read_factory_settings(use_empty=True)+ext = src.lower().rsplit(".", 1)[-1]+load = {"fbx": bpy.ops.import_scene.fbx, "obj": bpy.ops.wm.obj_import, "glb": bpy.ops.import_scene.gltf,+ "gltf": bpy.ops.import_scene.gltf}.get(ext)+load(filepath=src)+objs = [o for o in bpy.context.scene.objects if o.type == "MESH"]+bpy.ops.object.select_all(action="DESELECT")+for o in objs:+ o.select_set(True)+bpy.context.view_layer.objects.active = objs[0]+bpy.ops.object.join()+o = bpy.context.active_object+bpy.ops.object.transform_apply(location=True, rotation=True, scale=True)+s = float(height) / o.dimensions.z+o.scale = (s, s, s)+bpy.ops.object.transform_apply(scale=True)+xs, ys, zs = zip(*[o.matrix_world @ v.co for v in o.data.vertices])+bpy.context.scene.cursor.location = ((min(xs) + max(xs)) / 2, (min(ys) + max(ys)) / 2, min(zs))+bpy.ops.object.origin_set(type="ORIGIN_CURSOR")+o.location = (0, 0, 0)+bpy.ops.export_scene.gltf(filepath=out, use_selection=True, export_format="GLB")+print("wrote", out, [round(d, 3) for d in o.dimensions])+```++Blender's Z is up and glTF's Y is up; the exporter converts, so the model stands upright in raea.diff --git a/sdk/guides/craft/floor.md b/sdk/guides/craft/floor.mdindex 2905f3f3..e092c889 100644--- a/sdk/guides/craft/floor.md+++ b/sdk/guides/craft/floor.md@@ -31,6 +31,10 @@ Before you say a piece is done, every line here is true of the last render, nottranscript heard them.- **You looked.** You have seen the frames at the moments that matter, at the size it ships, and opened the wholeexport, not just a shot.+- **A note got its move.** Before any edit for a note, you picked the move it asks for (`raea guide router` lists+ them) and read that move's guide (`raea guide layout`, `raea guide quieter`, ...).+- **The last version is still there.** Each version renders to a new file beside the old (`card-v2.mp4` next to+ `card.mp4`), never over it, and in the app it's posted naming the item it `replaces`.## Refuse@@ -63,7 +67,7 @@ No reason makes these right:- **Invented facts.** No number, result, price, quote, customer or comparison that the brief, the person or thefootage didn't give you. If the piece needs proof you don't have, make it without the proof and say what would help.- **Generated images or video.** Pictures come from real footage, stock in the project's media, or are built:- components, drawn shapes, 3D. Generated sound is allowed: TokenSynth instruments and SAO foley (both local), Fish for- narration.+ components, drawn shapes, 3D. Generated sound is allowed: TokenSynth instruments, SAO foley and Pocket TTS+ narration (all local).- **Redrawn logos.** Use the real files.- **Calling it done without looking.** A render nobody looked at isn't finished.diff --git a/sdk/guides/craft/motion/apps.md b/sdk/guides/craft/motion/apps.mdnew file mode 100644index 00000000..b0ced301--- /dev/null+++ b/sdk/guides/craft/motion/apps.md@@ -0,0 +1,34 @@+# npm packages and React apps in a composition+<!-- sources: io/npm/src -->++What works today. The "not yet" list is the gaps: when one is built, delete its line here.++- Packages: `raea add @assistant-ui/react` writes `package.json` and `raea.lock` and lays out `node_modules`. raea's own package+ manager does it; no Node, npm or bun is needed, and install scripts never run.+- A React library that needs a real DOM (assistant-ui, Radix, shadcn) runs as an app: a module whose default export is+ a component taking `{ width, height }`, running on real react-dom in a document of its own. Place it:+ - on a screen in 3D: `<Screen name="chat" app="chat.tsx" resolution={[480, 640]} crt={false} />` (beside the 3D, or+ as a Model's `screens` entry). The path is relative to the composition's folder;+ - as an app panel or tool: `export const surface = "dom"` in the panel's file.+- Input in live play: the pointer reaches an app screen through the 3D (where it lands on the picture). Pressing on the+ screen gives it the keys, and the game gets none until a press elsewhere or Escape.+- Renders: an app runs on the frame clock (timers, `Date`, `performance.now`, `requestAnimationFrame` follow the frame),+ so a render repeats frame for frame.+- Exported games: `export-game` bundles each app with its packages. The player must be built with them:+ `cargo build --profile game -p raea-app-game --bin raea-game --features player,surfaces` (+6.7 MB); export refuses+ an app screen with a player built without.++Not yet:+- An app as a flat 2D layer of a composition. It can be a 3D `<Screen>` or an app panel only; for a flat look, put a+ `crt={false}` screen square to the camera.+- A composition itself importing a DOM library. Only an app (above) can; the composition's own React is raea's lite+ runtime.+- Input to an app in a render: `render --input` replays the page's input, but an app screen gets none. Script what it+ should show inside the app, on its own timers.+- Anything in front of a screen blocking its clicks: the ray hits the nearest screen, through other objects. It also+ assumes the 3D fills the stage.+- Network calls in an app during a render: nothing records and replays them, so a render that calls a model doesn't+ repeat. Keep renders offline.+- Packages that need Node (`fs`, `child_process`, native addons, postinstall steps), and `git:`, `file:` and `link:`+ dependencies. Browser-only packages work.+- A package's own `.css` imports and Tailwind inside an app are untested; style with style objects until they are.diff --git a/sdk/guides/craft/motion/assets.md b/sdk/guides/craft/motion/assets.mdindex ab84d31e..8a063fa0 100644--- a/sdk/guides/craft/motion/assets.md+++ b/sdk/guides/craft/motion/assets.md@@ -28,8 +28,8 @@ error and so is a URL (`https://...`). `staticFile` checks both. A module importfails loudly with the line that has it instead of rendering a black clip.Generated imagery is banned outright (floor): no AI-generated images or video, ever. Generated sound is allowed by-policy, and made on this computer but for narration: TokenSynth for an instrument's notes (music), SAO for foley, Fish-for narration over the picture. The sample libraries are recordings under open licences (CC0, CC-BY, public domain);+policy, and made on this computer: TokenSynth for an instrument's notes (music), SAO for foley, Pocket TTS+(`<Speech>`) for narration over the picture. The sample libraries are recordings under open licences (CC0, CC-BY, public domain);a CC-BY one is credited where the piece is shown.## Common mistakesdiff --git a/sdk/guides/craft/motion/games.md b/sdk/guides/craft/motion/games.mdindex 164fbfbb..4d32b55b 100644--- a/sdk/guides/craft/motion/games.md+++ b/sdk/guides/craft/motion/games.md@@ -36,7 +36,7 @@that the step falls back to when the Clock has none, so `raea render` plays it the same way every time.- Theme the field and the Arena's parts from the brand (`--brand-text`, `--brand-accent`, `--brand-background`) like anyother piece, each with a fallback colour (`var(--brand-accent, #ff5a36)`): a project with no brand defines none, and- a bare `var()` draws nothing (a GLM table-tennis game's paddles and net were invisible).+ a bare `var()` draws nothing (an agent's table-tennis game's paddles and net were invisible).- When an entity has modes (idle, run, jump, hurt; patrol, chase; playing, won, game over), write each as a statemachine: `machine<Ctx, Env>()({ id, initial, states })` from `raea`, guards polled every frame, delays inframes, the snapshot kept in the entity at `sm` and stepped inside the step (`stepAll` for one per enemy). The rulesdiff --git a/sdk/guides/craft/motion/gen.md b/sdk/guides/craft/motion/gen.mdnew file mode 100644index 00000000..ec86cf59--- /dev/null+++ b/sdk/guides/craft/motion/gen.md@@ -0,0 +1,60 @@+# Generated media: raea gen, flows, made.app, fal, OpenRouter, Replicate, Modal, ComfyUI++## What to do++- Generate a picture, a clip, music, an effect, a voice, a 3D model or words with `raea gen` when the piece needs+ something that isn't in the footage, the stock or the scene. `-o` is the folder; each command prints the files it wrote; use it like any+ other media (`<Img src>`, `<Video src>`, `<Audio src>`, `<Model src>`).+- Quote first. `raea gen plan FLOW` and `--plan` on a one-shot cost nothing and say where each step runs and what it+ costs in cents. A run past its cap is refused before anything is spent: `--max-cents N`, else+ `RAEA_GEN_MAX_CENTS`, else 100.+- One thing at a time: a one-shot verb.++ ```sh+ raea gen image "a paper kite over dunes at dawn, 35mm" --aspect 16:9 -o media/gen+ raea gen video "the kite climbs into the light" --image media/gen/<the still>.png --seconds 5 -o media/gen+ raea gen sfx "paper flutter in wind, close, no music" --seconds 3 -o media/gen+ raea gen speech "Find your wind." -o media/gen+ raea gen mesh "a paper kite" --image media/gen/<the still>.png -o media/gen # the GLB and its textures together+ raea gen text "five hooks for a kite shop ad" -o media/gen+ raea gen models --kind video --query kling # made's catalog, with prices+ ```++- Several steps that feed each other: a flow in TypeScript. Each maker returns its step's output, which the next step+ takes. A text step's words go straight into a prompt.++ ```ts+ import { flow } from "raea/gen";+ export default flow(({ image, video, text }) => {+ const line = text.generate({ prompt: "one vivid 15-word image prompt for a kite shop ad; the prompt only" });+ const still = image.generate({ prompt: line, aspect_ratio: "9:16" });+ return { clip: video.generate({ start_image: still, prompt: "slow push in, ribbons in the wind", seconds: 5 }) };+ });+ ```++ Then `raea gen plan kite.ts`, then `raea gen run kite.ts -o media/gen`. Each output is copied to its own name+ (`media/gen/clip.mp4`; a mesh and its textures as `media/gen/<name>/`), so the composition says+ `<Video src={staticFile("gen/clip.mp4")} />`. The steps' files sit beside them under their keys, with a+ `gen.jsonl` index. A step that is already there isn't run again, and a changed prompt reruns only what comes after+ it, so edit and rerun freely.+- Pick a model only when the piece needs one. Without one, each op goes to its default: made.app for pictures, video+ and audio, OpenRouter (Kimi) for words, fal for meshes, this Mac's sao for effects, and made.app for speech. To name a+ model, use `{ model: "made:kling_3_pro" }`, `"fal:<endpoint>"`, `"replicate:owner/name"`, `"openrouter:<model>"`,+ `"modal:<name>"`, `"fish:<model>"` (Fish Audio, with your FISH_API_KEY), `"comfy"` or `"local:sao"`. `raea gen models` lists made's ids. A made model's own setting goes in+ as `x_<name>`.+- Crops, resizes and side-by-sides between steps are free and run here: `image.crop`, `image.scale` (width, height,+ factor or megapixels; fit stretch, cover or contain) and `image.stitch` (a list of images, right or down).+- ComfyUI: `raea gen comfy import workflow.json -o flow.json` turns a workflow into a flow. Sampler chains and+ partner nodes become steps, and anything else stays as ComfyUI nodes that run on the ComfyUI server+ (`RAEA_COMFY_URL`). `raea gen comfy export kite.ts -o kite.workflow.json` writes any flow as a workflow; the steps+ ComfyUI can't run itself become RaeaMade nodes (tools/comfy/raea_made).+- A workflow that needs node packs or model weights: `raea gen comfy needs workflow.json -o needs.json`, then+ `tools/comfy/setup.sh needs needs.json` (this Mac) or the Modal lines in tools/comfy/modal_comfy.py (hosted).++## Never++- Never run a paid step without its plan's number in front of you. Never raise the cap to get past a refusal without+ saying what it costs.+- Never generate what the footage, the brand kit or a built 3D scene already has. A generated face, product or logo+ stands in for the real one only when the brief says so.+- Never rely on a generated clip for words on screen. Set type in the composition.diff --git a/sdk/guides/craft/motion/music.md b/sdk/guides/craft/motion/music.mdindex edaa9ccd..7cf6ff9b 100644--- a/sdk/guides/craft/motion/music.md+++ b/sdk/guides/craft/motion/music.md@@ -22,7 +22,7 @@pads, kicks, risers and anything synthetic.- Make sound effects and foley with SAO: `Tone.sao("a bright arcade coin chime, short", { seconds: 1 })` in aSampler or Player, or `sao(...)` in an `<Audio>` (`motion/sound`). Narration over the picture is- `Tone.fish("...")` / `fish("...")` (raea's generation API, paid and capped).+ `<Speech>` from `raea/speech` (Pocket TTS, local; `motion/sound`).- Build the graph at the top level of the file: every instrument, effect and channel, and how they connect. The graphis the one the composition has when its first frame renders. Schedule notes with the Transport (or with explicittimes). Never trigger notes from inside a component's render: a game's one-shots go through `<Tone.Sfx>`.@@ -100,7 +100,7 @@ SAO run on this computer and install themselves the first time they're used (a fnotes on instruments can be edited note by note, cut on the bar and ducked per part; a generated track can't.Policy: music is Tone.js instruments (TokenSynth, the sample libraries, synths), foley and effects are SAO, narration-is Fish. No other generation: no generated images, video or remote sound effects. (`lyria()`, a remote music model, is+is Pocket TTS (`<Speech>`), all local. No other generation: no generated images, video or remote sound effects. (`lyria()`, a remote music model, isretired: an older edit keeps the take it made, and a new one is refused.)## Common mistakesdiff --git a/sdk/guides/craft/motion/rendering.md b/sdk/guides/craft/motion/rendering.mdindex 0d0422ed..e79e3d60 100644--- a/sdk/guides/craft/motion/rendering.md+++ b/sdk/guides/craft/motion/rendering.md@@ -39,3 +39,19 @@ looking again, finds more than a still per change and costs less.- Calling it done without listening. The voice must stay intelligible over the bed, and every sound should land onits beat.- Answering while `raea check` still names a fault.++## Bitrate, quality and dark material++A video's bitrate follows its size and frame rate (about 20 Mbit/s at 1080p30, 80 at 4K30; VideoToolbox spends less on+flat pictures), and `--kbps N` sets it. `--quality draft|high|master` (or 0..1: 0.6, 0.85, 0.95) asks for constant+quality instead, each frame getting the bits it needs: `master` keeps thin type and hard vector edges clean at 4K+(about 31 Mbit/s on flat motion graphics). Blotching in dark areas is the encoder, not the composition: export dark+material as PNG frames (`RAEA_READBACK=rgba raea render piece.tsx -o frames/`) and encode them with more bits for the+darks.++## A person's hand edits++A person's hand edit in the raea app comes back as props, so keep them when you revise: `<Composition ... edit={{+segments: [[0, 412], [430, 3285]] }}>` plays those frame ranges one after another (a trim, a split, a cut word), and+`<Nudge x={0} y={-156}>` around an element moves it by those px. Edit the composition under them; change the segments+only when the cut itself should change.diff --git a/sdk/guides/craft/motion/sound.md b/sdk/guides/craft/motion/sound.mdindex ab93e4bd..479c9a3f 100644--- a/sdk/guides/craft/motion/sound.md+++ b/sdk/guides/craft/motion/sound.md@@ -1,4 +1,4 @@-# Sound: Audio, sao and fish, the music bus, gains, fades, Mix+# Sound: Audio, sao and Speech, the music bus, gains, fades, Mix## What to do@@ -20,8 +20,9 @@`Tone.buses.music.duck(Tone.buses.voice, { amount: -12 })`, give the voice `<Audio bus="voice">`, and set the bed'slevel on the bus: `Tone.buses.music.volume.value = -21`, then `Tone.buses.music.volume.rampTo(-12, 0.3, t)` to liftit at `t` seconds for the end card.-- Narration over the picture, when the footage has no voice for it, is `fish("the words")` in an `<Audio- bus="voice">` (raea's generation API: paid, capped per run).+- Narration over the picture, when the footage has no voice for it, is+ `<Speech text="the words" start={frame} />` from `raea/speech` (Pocket TTS, on this computer; `voice` picks a+ Pocket voice or a WAV of one).- Master the sum with one `<Mix lufs={-14} ceiling={-1.5} />` per composition. It brings the whole mix to -14 LUFSintegrated and limits true peaks under the ceiling, which is what the floor's loudness defect asks for.- Put the sounds in the tree in time order. The engine keys a sound's stretch by its place in the tree, so adding a@@ -43,14 +44,15 @@A sound placed without a Sequence starts at frame 0 with everything else. A Sequence with the default layout adds afull-frame box that paints over the parts beneath it.-`sao()` and `fish()` return an asset `{kind, prompt, seconds, id, src}` whose id is a stable hash of the kind, the+`sao()` returns an asset `{kind, prompt, seconds, id, src}` whose id is a stable hash of the kind, theprompt and the length. The renderer makes each asset once and caches it in the object's `assets/`. SAO runs on thiscomputer (Stable Audio Open, a few seconds a sound; it installs itself the first time). The same call always reusesthe same sound, and changing one word of the prompt makes a new one. So settle the prompt before you iterate ongains.-Policy: music is Tone.js instruments (TokenSynth, the sample libraries, synths), SAO makes foley, and Fish makes-narration over the picture. No other generation. (`lyria()`, a remote music model, is retired: a+Policy: music is Tone.js instruments (TokenSynth, the sample libraries, synths), SAO makes foley, and Pocket TTS+(`<Speech>`) says narration over the picture, all on this computer. Any other generation is a `raea gen` step+(`motion/gen`). (`lyria()`, a remote music model, is retired: anew take is refused, and a bed of instruments can be cut on the bar and edited note by note anyway.)Sound sells the cut, but one move everywhere is a lint: a whoosh on every entrance flattens all of them. Give@@ -68,7 +70,8 @@ everyone else. Two checks, both cheap:loops only between `startFrom` and `endAt`, and that loop is a hard jump. Tile it instead: copies of the take end toend, each in its own Sequence, crossfading over 1.5 s (`fadeIn`/`fadeOut`), or make the take as long as the span.- **Check the finished file.** `raea check FILM.mp4 --words words.json` (the voice's words on the film's clock)- reports, by timecode, dead stops (a steady sound that ends in one 10 ms step), stretches with no voice louder than+ reports, by timecode, dead stops (a steady sound that ends in one 10 ms step: fade a bed out over 100 ms or more;+ a voice ending its word isn't one), stretches with no voice louder thanthe voice, a bed closer than 12 dB to the voice over it, and a true peak over -1 dBTP. Fix every line it prints, orsay why it stands.@@ -87,7 +90,7 @@ ends up shouting over the narrator while another is inaudible.render warns). With `endAt` it repeats with a hard jump at each loop; tile copies with crossfades instead.- Two `<Mix>` in one composition: it throws.- No `<Mix>`: the sum plays as it is, at whatever loudness it adds up to.-- Rewording a `sao()` prompt on every pass. Each new prompt makes a new sound (and `fish()` pays again).+- Rewording a `sao()` prompt on every pass. Each new prompt makes a new sound .- `style` on an `<Audio>`: Audio has no picture and takes no style.- Hand-placing dozens of game sounds from a log. Cue them from `useGameEvents` (`motion/games`).- Writing music note by note in `<Audio>` files, or a game's sounds by hand. Write them in Tone.js (`motion/music`):diff --git a/sdk/guides/craft/verbs/adapt.md b/sdk/guides/craft/verbs/adapt.mdnew file mode 100644index 00000000..24106293--- /dev/null+++ b/sdk/guides/craft/verbs/adapt.md@@ -0,0 +1,21 @@+# adapt++Notes like these: "we need it in 16:9", "a square one for the feed", "4:5 for Instagram", "a 6 second cut", "for+YouTube". The same piece made right for another size, length or platform; never a crop of the old one.++## Assess+- The controllers' delivery specs name the sizes, lengths and platforms; work to those.+- For each size, find what no longer fits: type that wraps, a face cut off, a part in a platform's button zone, a+ hold that's too long for a shorter cut.++## Change+- Register one `<Composition>` per size in the same root, sharing the parts; each lays out for its own frame+ (`raea guide motion/compositions`). Never scale or crop one size into another.+- Re-place type and faces for each frame and its safe zones (`raea guide motion/placement`). Wider frames get room,+ not bigger type.+- A shorter cut keeps the hook and the ending and drops whole beats from the middle, cut on words.+- Name each file for its size: `spring-launch-16x9.mp4`.++## Verify+- `raea render --composition ID --at 0,45,89` stills for every size; `raea check` on each export.+- Every size says the same thing; nothing is cut off or crowded in any of them.diff --git a/sdk/guides/craft/verbs/animate.md b/sdk/guides/craft/verbs/animate.mdnew file mode 100644index 00000000..fffbc761--- /dev/null+++ b/sdk/guides/craft/verbs/animate.md@@ -0,0 +1,21 @@+# animate++Notes like these: "it's static", "bring it to life", "make it move", "it feels like a slideshow". Motion added to+something that holds still, so each move says something.++## Assess+- Find what the motion should say at each moment: arrival, emphasis, cause and effect, a change of state. A part+ with nothing to say stays still.+- Find the beats it lands on: the voice's words, the music's hits (`raea song FILE --plot`), the cuts.++## Change+- Animate entrances, the one emphasis per beat and exits; leave everything else still.+- One easing family for the whole piece; springs for things with weight, short eases for type (`raea guide+ motion/animating`).+- Stagger related parts by a few frames instead of moving them at once.+- Everything reads the frame (`useCurrentFrame()`), every `interpolate` clamped.++## Verify+- Play it at full speed, then step the frames around each beat: each move starts on its cue and settles before+ the next.+- Nothing moves without a reason you could say in a few words.diff --git a/sdk/guides/craft/verbs/delight.md b/sdk/guides/craft/verbs/delight.mdnew file mode 100644index 00000000..b1e7a3ef--- /dev/null+++ b/sdk/guides/craft/verbs/delight.md@@ -0,0 +1,18 @@+# delight++Notes like these: "it's fine but forgettable", "add something fun", "a little surprise", "make me smile". One small+detail that rewards attention, in the piece's own voice.++## Assess+- Is the piece right first? Delight on a piece that doesn't land is noise: fix the note's real problem before this.+- Find a moment with room: a hold, a transition, the end card, a game's idle or its win.++## Change+- One detail, maybe two: a character's blink, a sound on a hit, the logo doing one thing it only does here, a line+ of copy that's a little warmer than it has to be.+- From the brand and the subject, never generic (no confetti unless confetti is the point).+- Small and quick: it shouldn't take the eye from what the moment is about.++## Verify+- Watch it as someone seeing it for the first time: the detail is noticed second, not first.+- Take it out and watch again: if nothing is lost, it wasn't worth keeping.diff --git a/sdk/guides/craft/verbs/extract.md b/sdk/guides/craft/verbs/extract.mdnew file mode 100644index 00000000..94c893d9--- /dev/null+++ b/sdk/guides/craft/verbs/extract.md@@ -0,0 +1,20 @@+# extract++Notes like these: "use the same look as last time", "make a brand kit from this", "we don't have guidelines, use+the video". A brand kit read from finished work rather than a website.++## Assess+- Gather the finished pieces the person names: renders in `out/`, earlier projects, their files in+ `raea library search`.+- From stills across them, find what repeats: the two or three colours, the faces and weights of type, the logo and+ how it's shown, how things move and cut.++## Change+- With a site, start from `raea brand DOMAIN`, then add what the work shows that the site doesn't.+- Write what you found into the kit: `brand/brand.css` (`--brand-*` colours and fonts), `brand/brand.json`, and+ BRAND.md (what each colour means, the motion and cutting habits) (`raea guide motion/brand`).+- Take logos from the source files the person gives, never from a frame grab.+- Mark guesses as guesses in BRAND.md, and ask the person to confirm them.++## Verify+- A test card in the new kit sits beside a still of the old work and reads as the same brand.diff --git a/sdk/guides/craft/verbs/generate.md b/sdk/guides/craft/verbs/generate.mdnew file mode 100644index 00000000..156a7ae2--- /dev/null+++ b/sdk/guides/craft/verbs/generate.md@@ -0,0 +1,20 @@+# generate++Notes like these: "show me a few options", "try some versions", "I'm not sure what I want", "give me variants of+the end card". Variants of one element to pick from, not of the whole piece.++## Assess+- Name the one element (a title card, a colour, the hook's first line, a sound) and what the variants should differ+ in. Everything else stays the same.+- Three to five variants; more is a choice nobody wants to make.++## Change+- Variants in code: one component with a prop for what changes, one `<Composition>` per variant, rendered as stills+ or short clips side by side.+- Generated media (an image, a sound, a voice): `raea gen` (`raea gen` alone lists its flags); each variant keeps its prompt+ and seed so the chosen one can be made again.+- Make them really different on the one axis, not five shades of the same idea.++## Verify+- Show them together, labelled plainly (A, B, C), with one line each on what it does differently. The person+ picks; then remove the rest from the composition.diff --git a/sdk/guides/craft/verbs/layout.md b/sdk/guides/craft/verbs/layout.mdnew file mode 100644index 00000000..23cab61c--- /dev/null+++ b/sdk/guides/craft/verbs/layout.md@@ -0,0 +1,20 @@+# layout++Notes like these: "it's cramped", "where do I look", "everything's the same size", "it's crooked", "too much empty+space", "the logo's lost". Where things sit in the frame and how much room each gets.++## Assess+- Name the one thing each moment is about. Is it the biggest, the brightest or the most central thing in the frame?+- Find what fights it: two things the same size, a part over a face or under a platform's buttons (the safe zones in+ `raea guide motion/placement`), edges that almost line up but don't.+- Look at the frame at the size it ships (a phone for 9:16), not at full resolution.++## Change+- One focal point per moment. Make it bigger or give it more room; make the rest smaller rather than moving it away.+- Put parts on a grid: shared left edges, shared baselines, the same margin on every side (`raea guide motion/layout`).+- Use the room on purpose: space around the focal point, not spread evenly across the frame.+- Keep text and faces inside the safe zones of every platform the controllers name.++## Verify+- Stills at the same frames, before and after (`raea render --at`), at ship size. The eye goes to the right place first.+- `raea check` reports no overlap or out-of-safe-zone parts.diff --git a/sdk/guides/craft/verbs/optimize.md b/sdk/guides/craft/verbs/optimize.mdnew file mode 100644index 00000000..28b4d7c7--- /dev/null+++ b/sdk/guides/craft/verbs/optimize.md@@ -0,0 +1,19 @@+# optimize++Notes like these: "it's slow", "the file's too big", "it stutters", "the game lags", "it took forever to render".+The same piece, lighter: smaller files, faster renders, smooth play.++## Assess+- Measure first: the export's size and bitrate (`raea media probe`), the render's time, a game's frame rate live.+- Find the cost: footage at a far higher resolution than the frame, 3D lights and shadows nobody sees, a model with+ more triangles than pixels, per-frame work that could be computed once.++## Change+- Delivery: `--quality` per use (`raea guide rendering`); a share copy for sending (the skill's ffmpeg line).+- Footage: `raea mezz` for long-GOP sources; trim to the parts used.+- 3D: fewer shadow-casting lights, smaller shadow maps, decimated models (`raea guide bevy/blender`), the limits in+ `raea guide bevy/limits`.+- Code: compute what doesn't change outside the frame function, keyed by index, still frame-pure.++## Verify+- The same measurements, before and after. The look is unchanged in stills at the same frames.diff --git a/sdk/guides/craft/verbs/typeset.md b/sdk/guides/craft/verbs/typeset.mdnew file mode 100644index 00000000..bad12129--- /dev/null+++ b/sdk/guides/craft/verbs/typeset.md@@ -0,0 +1,20 @@+# typeset++Notes like these: "I can't read it", "the font", "too small on my phone", "the captions", "the title looks cheap",+"too many fonts". The type on screen: its face, size, spacing and how long it stays.++## Assess+- Read every line at the size it ships, for as long as it's on screen. Can it be read twice in that time?+- Count the faces and weights. Name what each one is for (the brand's, from `brand/brand.css`; a caption's).+- Check the measure: lines too long to take in at a glance, single words left alone on a line.++## Change+- One face, two at most, from the brand kit. Contrast comes from size and weight, not from more fonts.+- Size for the phone: a 9:16 caption at least 48 px tall on a 1080 wide frame; titles far bigger.+- Break lines by sense, not by width: one idea per line, no orphan.+- Tighten tracking on big type, loosen it on small caps. Lines close together in a block, blocks well apart.+- Hold each line long enough to read twice (`raea guide motion/words`), and let words land on the voice's cue.++## Verify+- Stills of each line on a phone-size preview; read them aloud at speaking pace.+- The faces in the render are only the ones the brand names.diff --git a/sdk/plugins/src/plugins.lock.json b/sdk/plugins/src/plugins.lock.jsonindex 7a705e33..e597cbca 100644--- a/sdk/plugins/src/plugins.lock.json+++ b/sdk/plugins/src/plugins.lock.json@@ -103,7 +103,7 @@},"save": {"crate": "moonshine-save",- "version": "v0.8.0",+ "version": "","schema": "29d3be85d09e76b5"},"vox": {diff --git a/sdk/raea/bench/bevy-plugins/avian.tsx b/sdk/raea/bench/bevy-plugins/avian.tsxindex 73f384c6..736edef4 100644--- a/sdk/raea/bench/bevy-plugins/avian.tsx+++ b/sdk/raea/bench/bevy-plugins/avian.tsx@@ -4,7 +4,7 @@// from avian's TypeRegistry; no raea-render system is per component. Render and play// must agree: sdk/raea/bench/bevy/check.sh with RAEA_BIN=bevy-plugins/motion.sh.import { AbsoluteFill, Composition, registerRoot } from "raea";-import { Canvas3D, Sphere } from "raea/3d";+import { Sphere } from "raea/3d";import { AngularVelocity, ColliderConstructor, Friction, GravityResource, LinearVelocity, Restitution, RigidBody } from "raea/plugins/avian";import { StandardMaterial } from "raea/pbr";import { Cuboid, Mesh3d } from "raea/mesh";@@ -29,7 +29,7 @@ const crates = [function Drop() {return (<AbsoluteFill style={{ background: "#0f1720" }}>- <Canvas3D>+ <><Camera3d transform={Transform.fromXyz(0, 2.5, 9).lookingAt([0, 1, 0])} projection={{ Perspective: { fov: 0.785398163397448 } }} /><AmbientLight brightness={200} /><DirectionalLight transform={Transform.fromXyz(3, 6, 4).lookingAt([0, 0, 0])} illuminance={10400} shadow_maps_enabled />@@ -60,7 +60,7 @@ function Drop() {{c.kick ? <LinearVelocity value={[-4, 3, 0]} from={60} /> : null}</Mesh3d>))}- </Canvas3D>+ </></AbsoluteFill>);}diff --git a/sdk/raea/bench/bevy-plugins/catalog/games.ts b/sdk/raea/bench/bevy-plugins/catalog/games.tsindex b9b5d85b..d77946b9 100644--- a/sdk/raea/bench/bevy-plugins/catalog/games.ts+++ b/sdk/raea/bench/bevy-plugins/catalog/games.ts@@ -1,6 +1,7 @@-// The game plugins' drives (docs/plugins.feature PL0a), spread into proof.ts's: easings, navigator, northstar+// The game plugins' drives (docs/plugins.feature PL0a) and save's (PL16), spread into proof.ts'simport { at, with as w } from "raea/bevy";import { easings } from "raea/plugins/easings";+import { native } from "raea/native";import { Drive, Transform, check, part } from "./drive";// within a frame (1/60 s) of the curve@@ -54,4 +55,24 @@ export const games: Record<string, Drive> = {check(app.call<Path>("northstar/path", { grid, from: [0, 0], to: [9, 0], mode: "astar" }) === null, "a walled-in goal has no way");return { cost: way!.cost, steps: way!.points.length };},+ save(app) {+ // two of three entities marked Save, saved, one of them moved, then loaded: the file's two come back as new+ // entities where they were saved (the old ones despawned, the move with them) and the unmarked one stays put; the+ // loaded ones are marked again, so a second save takes them+ const xs = [1, 2, 3].map((x) => app.spawn(at(x, 0, 0)));+ app.call("save/mark", { entities: xs.slice(0, 2) });+ const path = `${native("host.env", { name: "TMPDIR" }) ?? "/tmp"}/raea-proof-save.ron`;+ const saved = app.call<{ saved: number[] }>("save/save", { path }).saved;+ check(JSON.stringify([...saved].sort()) === JSON.stringify(xs.slice(0, 2).sort()), `saved ${saved}, not ${xs.slice(0, 2)}`);+ app.insert(xs[0], w(Transform, part({ translation: [10, 0, 0] })));+ const loaded = app.call<{ loaded: number[] }>("save/load", { path }).loaded;+ const x = (e: number) => app.get(e, Transform)?.translation?.[0];+ const back = loaded.map(x).sort();+ check(JSON.stringify(back) === "[1,2]", `loaded at ${back}, not 1 and 2`);+ check(!loaded.includes(xs[0]) && app.query({ data: [Transform] }).every((q) => x(q.entity) !== 10), "the moved entity should be gone");+ check(x(xs[2]) === 3, `the unmarked entity moved to ${x(xs[2])}`);+ const again = app.call<{ saved: number[] }>("save/save", { path }).saved;+ check(JSON.stringify([...again].sort()) === JSON.stringify([...loaded].sort()), `the second save took ${again}, not ${loaded}`);+ return { saved, loaded, back };+ },};diff --git a/sdk/raea/bench/bevy-plugins/hanabi.tsx b/sdk/raea/bench/bevy-plugins/hanabi.tsxindex 2dd8910a..cb4175f6 100644--- a/sdk/raea/bench/bevy-plugins/hanabi.tsx+++ b/sdk/raea/bench/bevy-plugins/hanabi.tsx@@ -3,7 +3,7 @@// hanabi.rs builds the effect asset from it); its TSX wrapper is generated like any other (raea/plugins/hanabi,// from tools/bevy-plugins.sh gen). Render and play are compared by sdk/raea/bench/bevy/check.sh with RAEA_BIN=bevy-plugins/motion.sh.import { AbsoluteFill, Composition, registerRoot } from "raea";-import { Canvas3D } from "raea/3d";+import { Particles } from "raea/plugins/hanabi";import { StandardMaterial } from "raea/pbr";import { ConicalFrustum, Mesh3d } from "raea/mesh";@@ -17,7 +17,7 @@ const FRAMES = 120;function Fountains() {return (<AbsoluteFill style={{ background: "#0b1020" }}>- <Canvas3D>+ <><Camera3d transform={Transform.fromXyz(0, 1.5, 7).lookingAt([0, 1.2, 0])} projection={{ Perspective: { fov: 0.785398163397448 } }} /><AmbientLight brightness={200} /><DirectionalLight transform={Transform.fromXyz(2, 5, 4).lookingAt([0, 0, 0])} illuminance={9600} shadow_maps_enabled />@@ -31,7 +31,7 @@ function Fountains() {<StandardMaterial base_color="#475569" /><Particles value={{ rate: 300, lifetime: 1.6, speed: 4, spread: 0.3, size: 0.08, color: [0.3, 0.7, 1, 0.5], gravity: 5, seed: 7, opaque: false }} /></Mesh3d>- </Canvas3D>+ </></AbsoluteFill>);}diff --git a/sdk/raea/bench/bevy-plugins/package.json b/sdk/raea/bench/bevy-plugins/package.jsonindex 17df0370..faccfd67 100644--- a/sdk/raea/bench/bevy-plugins/package.json+++ b/sdk/raea/bench/bevy-plugins/package.json@@ -672,7 +672,9 @@"0.19": "=0.7.0","0.20": "=0.8.0"},- "library": true+ "library": true,+ "calls": "save",+ "headless": ["assets"]},"svg": {"crate": "bevy_svg",diff --git a/sdk/raea/bench/bevy-ts/cases/camera-seek.tsx b/sdk/raea/bench/bevy-ts/cases/camera-seek.tsxindex b36c2ced..10a0af45 100644--- a/sdk/raea/bench/bevy-ts/cases/camera-seek.tsx+++ b/sdk/raea/bench/bevy-ts/cases/camera-seek.tsx@@ -7,7 +7,7 @@// probe: 32 32 r>150 g<80 b<80// probe: 4 32 r<30 g<30 b<30import { AbsoluteFill, Composition, registerRoot, useCurrentFrame } from "raea";-import { Canvas3D, ToneMapping } from "raea/3d";+import { ToneMapping } from "raea/3d";import { Camera3d } from "raea/camera";import { Transform } from "raea/transform";import { StandardMaterial } from "raea/pbr";@@ -17,14 +17,14 @@ function Shot() {const x = useCurrentFrame() * 0.1;return (<AbsoluteFill style={{ background: "#000" }}>- <Canvas3D>+ <><Camera3d transform={Transform.fromXyz(x, 0, 0).lookingAt([x, 0, -1])} projection={{ Perspective: { fov: 0.785398 } }} /><ToneMapping mode="none" /><Mesh3d name="red" transform={Transform.fromXyz(3, 0, -5)}><Cuboid half_size={[0.5, 0.5, 0.5]} /><StandardMaterial base_color="#ff0000" unlit /></Mesh3d>- </Canvas3D>+ </></AbsoluteFill>);}diff --git a/sdk/raea/bench/bevy-ts/cases/compute.tsx b/sdk/raea/bench/bevy-ts/cases/compute.tsxindex c05cf801..b800cdda 100644--- a/sdk/raea/bench/bevy-ts/cases/compute.tsx+++ b/sdk/raea/bench/bevy-ts/cases/compute.tsx@@ -9,7 +9,7 @@// probe: 47 32 r<40 g>200 b>200// probe: 32 4 r<40 g<40 b<40import { AbsoluteFill, Composition, registerRoot } from "raea";-import { Canvas3D, Compute, ShaderMesh, ToneMapping } from "raea/3d";+import { Compute, ShaderMesh, ToneMapping } from "raea/3d";import { Transform } from "raea/transform";import { Camera3d } from "raea/camera";@@ -33,13 +33,13 @@ const pic = { src: "render:cgrid:4x4", sampler: { filter: "nearest" } };function Shot() {return (<AbsoluteFill style={{ background: "#000" }}>- <Canvas3D>+ <><Camera3d transform={Transform.fromXyz(0, 0, 6).lookingAt([0, 0, 0])} projection={{ Perspective: { fov: 0.872664625997165 } }} /><ToneMapping mode="none" /><Compute wesl={fill} workgroups={[1]} uniforms={{ red: 1 }} buffers={{ cells: [0, 1], count: { size: 1 } }} images={{ out: "render:cgrid:4x4" }} /><ShaderMesh shape="box(1, 1, 1)" position={[-1.4, 0, 0]} wesl={read(0.125)} textures={{ pic }} /><ShaderMesh shape="box(1, 1, 1)" position={[1.4, 0, 0]} wesl={read(0.875)} textures={{ pic }} />- </Canvas3D>+ </></AbsoluteFill>);}diff --git a/sdk/raea/bench/bevy-ts/cases/frame-pass.tsx b/sdk/raea/bench/bevy-ts/cases/frame-pass.tsxindex 02630bb8..8b1943a4 100644--- a/sdk/raea/bench/bevy-ts/cases/frame-pass.tsx+++ b/sdk/raea/bench/bevy-ts/cases/frame-pass.tsx@@ -5,7 +5,7 @@// probe: 32 32 b>200 g>200 r<40// probe: 4 4 r>200 g<40 b<40import { AbsoluteFill, Composition, registerRoot } from "raea";-import { ToneMapping, Canvas3D, FramePass } from "raea/3d";+import { ToneMapping, FramePass } from "raea/3d";import { StandardMaterial } from "raea/pbr";import { Cuboid, Mesh3d } from "raea/mesh";import { AmbientLight } from "raea/light";@@ -26,14 +26,14 @@ fn shade(in: FullscreenVertexOutput) -> vec4<f32> {function Shot() {return (<AbsoluteFill style={{ background: "#000" }}>- <Canvas3D>+ <><Camera3d transform={Transform.fromXyz(0, 0, 5).lookingAt([0, 0, 0])} projection={{ Perspective: { fov: 0.872664625997165 } }} /><ToneMapping mode="none" /><AmbientLight brightness={400} /><Mesh3d><Cuboid half_size={[0.5, 0.5, 0.5]} /><StandardMaterial base_color="#ffffff" /></Mesh3d><FramePass wesl={probe} at="before-tonemap" prepass={{ depth: true, normal: true }} uniforms={{ far: 10 }} /><FramePass wesl={swap} />- </Canvas3D>+ </></AbsoluteFill>);}diff --git a/sdk/raea/bench/bevy-ts/cases/material-fields.tsx b/sdk/raea/bench/bevy-ts/cases/material-fields.tsxindex b2855428..27efdee3 100644--- a/sdk/raea/bench/bevy-ts/cases/material-fields.tsx+++ b/sdk/raea/bench/bevy-ts/cases/material-fields.tsx@@ -13,7 +13,7 @@// probe: 43 43 r<40 g<40// rows: specularTint.*anisotropyimport { AbsoluteFill, Composition, registerRoot } from "raea";-import { Canvas3D, Fog, ToneMapping } from "raea/3d";+import { Fog, ToneMapping } from "raea/3d";import { StandardMaterial } from "raea/pbr";import { Affine2 } from "raea/math";import { Cuboid, Mesh3d, Plane3d } from "raea/mesh";@@ -25,7 +25,7 @@ const glow = { base_color: "#000000", perceptual_roughness: 1 } as const;function Shot() {return (<AbsoluteFill style={{ background: "#000" }}>- <Canvas3D>+ <><Camera3d transform={Transform.fromXyz(0, 0, 6).lookingAt([0, 0, 0])} projection={{ Perspective: { fov: 0.872664625997165 } }} /><ToneMapping mode="none" /><Fog color="#ffffff" near={1} far={2} />@@ -42,7 +42,7 @@ function Shot() {<Plane3d normal={[0, 0, 1]} half_size={[0.8, 0.6]} /><StandardMaterial {...glow} emissive="#ffffff" emissive_texture={{ path: "checker2.png", sampler: { filter: "nearest", wrap: "repeat" } }} fog_enabled={false} uv_transform={Affine2.fromTranslation([0.5, 0])} /></Mesh3d>- </Canvas3D>+ </></AbsoluteFill>);}diff --git a/sdk/raea/bench/bevy-ts/cases/plugin-aseprite.tsx b/sdk/raea/bench/bevy-ts/cases/plugin-aseprite.tsxindex 2d34e590..1cb0db69 100644--- a/sdk/raea/bench/bevy-ts/cases/plugin-aseprite.tsx+++ b/sdk/raea/bench/bevy-ts/cases/plugin-aseprite.tsx@@ -8,7 +8,7 @@// probe: 32 32 g>150 r<80 b<80// probe: 2 2 r<20 g<20 b<20import { AbsoluteFill, Composition, registerRoot } from "raea";-import { BevyComponent, Canvas3D, Entity } from "raea/3d";+import { BevyComponent, Entity } from "raea/3d";import { Camera3d } from "raea/camera";import { Transform } from "raea/transform";import { AseAnimation } from "raea/plugins/aseprite";@@ -18,14 +18,14 @@ const play = { tag: null, speed: 1, playing: true, repeat: "Loop", direction: nufunction Shot() {return (<AbsoluteFill style={{ background: "#000" }}>- <Canvas3D>+ <><Camera3d transform={Transform.fromXyz(0, 0, 5).lookingAt([0, 0, 0])} projection={{ Perspective: { fov: 0.785398 } }} /><Entity position={[32, -32, 0]}><BevyComponent type="raea_sys_sprite::Draws2d" value={{}} /><BevyComponent type="bevy_sprite::sprite::Sprite" value={{ custom_size: [32, 32] }} /><AseAnimation value={{ aseprite: "plugin-aseprite.aseprite", animation: { ...play, queue: [] } }} /></Entity>- </Canvas3D>+ </></AbsoluteFill>);}diff --git a/sdk/raea/bench/bevy-ts/cases/plugin-enoki.tsx b/sdk/raea/bench/bevy-ts/cases/plugin-enoki.tsxindex 7fdb9827..ad11bb8d 100644--- a/sdk/raea/bench/bevy-ts/cases/plugin-enoki.tsx+++ b/sdk/raea/bench/bevy-ts/cases/plugin-enoki.tsx@@ -9,7 +9,7 @@// probe: 4 30 r<20 g<20 b<20// probe: 60 30 r<20 g<20 b<20import { AbsoluteFill, Composition, registerRoot } from "raea";-import { Canvas3D, Entity } from "raea/3d";+import { Entity } from "raea/3d";import { Camera3d } from "raea/camera";import { Transform } from "raea/transform";import { Sparks } from "raea/plugins/enoki";@@ -17,12 +17,12 @@ import { Sparks } from "raea/plugins/enoki";function Shot() {return (<AbsoluteFill style={{ background: "#000" }}>- <Canvas3D>+ <><Camera3d transform={Transform.fromXyz(0, 0, 5).lookingAt([0, 0, 0])} projection={{ Perspective: { fov: 0.785398 } }} /><Entity position={[32, -48, 0]}><Sparks value={{ every: 0.02, amount: 1, lifetime: 1, speed: 60, direction: [0, 1], spread: 0, size: 6, color: [1, 0.6, 0.2, 1], gravity: 0 }} /></Entity>- </Canvas3D>+ </></AbsoluteFill>);}diff --git a/sdk/raea/bench/bevy-ts/cases/plugin-flair.tsx b/sdk/raea/bench/bevy-ts/cases/plugin-flair.tsxindex befbe7bd..4c9e17e5 100644--- a/sdk/raea/bench/bevy-ts/cases/plugin-flair.tsx+++ b/sdk/raea/bench/bevy-ts/cases/plugin-flair.tsx@@ -8,7 +8,7 @@// probe: 32 32 g>200 r<60 b<60// probe: 4 4 r<30 g<30 b<30import { AbsoluteFill, Composition, registerRoot } from "raea";-import { BevyComponent, Canvas3D, Entity, ToneMapping } from "raea/3d";+import { BevyComponent, Entity, ToneMapping } from "raea/3d";import { Camera3d } from "raea/camera";import { Transform } from "raea/transform";import { ClassList, Styled } from "raea/plugins/flair";@@ -18,7 +18,7 @@ const black = { Srgba: { red: 0, green: 0, blue: 0, alpha: 0 } };function Shot() {return (<AbsoluteFill style={{ background: "#000" }}>- <Canvas3D>+ <><Camera3d transform={Transform.fromXyz(0, 0, 3).lookingAt([0, 0, 0])} projection={{ Perspective: { fov: 0.785398 } }}><BevyComponent type="bevy_ui::ui_node::IsDefaultUiCamera" value={{}} /></Camera3d>@@ -29,7 +29,7 @@ function Shot() {<Styled value={{ StyleSheet: "plugin-flair.css" }} /><ClassList value={["box"]} /></Entity>- </Canvas3D>+ </></AbsoluteFill>);}diff --git a/sdk/raea/bench/bevy-ts/cases/plugin-hanabi.tsx b/sdk/raea/bench/bevy-ts/cases/plugin-hanabi.tsxindex 3bb08833..c6c4d8a4 100644--- a/sdk/raea/bench/bevy-ts/cases/plugin-hanabi.tsx+++ b/sdk/raea/bench/bevy-ts/cases/plugin-hanabi.tsx@@ -8,7 +8,7 @@// probe: 2 2 r<20 g<20 b<20// probe: 61 2 r<20 g<20 b<20import { AbsoluteFill, Composition, registerRoot } from "raea";-import { Canvas3D, ToneMapping } from "raea/3d";+import { ToneMapping } from "raea/3d";import { Particles } from "raea/plugins/hanabi";import { StandardMaterial } from "raea/pbr";import { ConicalFrustum, Mesh3d } from "raea/mesh";@@ -19,7 +19,7 @@ import { Camera3d } from "raea/camera";function Shot() {return (<AbsoluteFill style={{ background: "#000" }}>- <Canvas3D>+ <><Camera3d transform={Transform.fromXyz(0, 1.5, 5).lookingAt([0, 1.5, 0])} projection={{ Perspective: { fov: 0.785398163397448 } }} /><ToneMapping mode="none" /><AmbientLight brightness={0} />@@ -28,7 +28,7 @@ function Shot() {<StandardMaterial base_color="#000000" /><Particles value={{ rate: 2000, lifetime: 1.6, speed: 4, spread: 0.15, size: 0.12, color: [1, 0.55, 0.1, 1], gravity: 5, seed: 7, opaque: true }} /></Mesh3d>- </Canvas3D>+ </></AbsoluteFill>);}diff --git a/sdk/raea/bench/bevy-ts/cases/plugin-hui.tsx b/sdk/raea/bench/bevy-ts/cases/plugin-hui.tsxindex b21a70ad..ffecf212 100644--- a/sdk/raea/bench/bevy-ts/cases/plugin-hui.tsx+++ b/sdk/raea/bench/bevy-ts/cases/plugin-hui.tsx@@ -8,7 +8,7 @@// probe: 32 32 g>200 r<60 b<60// probe: 4 4 b>200 r<60 g<60import { AbsoluteFill, Composition, registerRoot } from "raea";-import { BevyComponent, Canvas3D, Entity, ToneMapping } from "raea/3d";+import { BevyComponent, Entity, ToneMapping } from "raea/3d";import { Camera3d } from "raea/camera";import { Transform } from "raea/transform";import { HtmlNode } from "raea/plugins/hui";@@ -16,7 +16,7 @@ import { HtmlNode } from "raea/plugins/hui";function Shot() {return (<AbsoluteFill style={{ background: "#000" }}>- <Canvas3D>+ <><Camera3d transform={Transform.fromXyz(0, 0, 3).lookingAt([0, 0, 0])} projection={{ Perspective: { fov: 0.785398 } }}><BevyComponent type="bevy_ui::ui_node::IsDefaultUiCamera" value={{}} /></Camera3d>@@ -24,7 +24,7 @@ function Shot() {<Entity name="ui"><HtmlNode value="plugin-hui.html" /></Entity>- </Canvas3D>+ </></AbsoluteFill>);}diff --git a/sdk/raea/bench/bevy-ts/cases/plugin-ldtk.tsx b/sdk/raea/bench/bevy-ts/cases/plugin-ldtk.tsxindex eabeaf15..02f960f3 100644--- a/sdk/raea/bench/bevy-ts/cases/plugin-ldtk.tsx+++ b/sdk/raea/bench/bevy-ts/cases/plugin-ldtk.tsx@@ -10,7 +10,7 @@// probe: 16 48 g>200 r<60 b<60// probe: 48 48 r>200 g<60 b<60import { AbsoluteFill, Composition, registerRoot } from "raea";-import { Canvas3D, Entity } from "raea/3d";+import { Entity } from "raea/3d";import { Camera3d } from "raea/camera";import { Transform } from "raea/transform";import { CurrentLevel, LdtkProjectHandle } from "raea/plugins/ldtk";@@ -18,13 +18,13 @@ import { CurrentLevel, LdtkProjectHandle } from "raea/plugins/ldtk";function Shot() {return (<AbsoluteFill style={{ background: "#000" }}>- <Canvas3D>+ <><Camera3d transform={Transform.fromXyz(0, 0, 5).lookingAt([0, 0, 0])} projection={{ Perspective: { fov: 0.785398 } }} /><Entity position={[0, -64, 0]}><LdtkProjectHandle value={{ handle: "plugin-ldtk.ldtk" }} /><CurrentLevel value={{ index: 0 }} /></Entity>- </Canvas3D>+ </></AbsoluteFill>);}diff --git a/sdk/raea/bench/bevy-ts/cases/plugin-light-2d.tsx b/sdk/raea/bench/bevy-ts/cases/plugin-light-2d.tsxindex 09db1bf8..a0903961 100644--- a/sdk/raea/bench/bevy-ts/cases/plugin-light-2d.tsx+++ b/sdk/raea/bench/bevy-ts/cases/plugin-light-2d.tsx@@ -7,7 +7,7 @@// probe: 14 32 r>120 g<60 b<60// probe: 56 32 r<20 g<20 b<20import { AbsoluteFill, Composition, registerRoot } from "raea";-import { BevyComponent, Canvas3D, Entity } from "raea/3d";+import { BevyComponent, Entity } from "raea/3d";import { Camera3d } from "raea/camera";import { Transform } from "raea/transform";import { Lighting2d, PointLight2d } from "raea/plugins/light_2d";@@ -15,7 +15,7 @@ import { Lighting2d, PointLight2d } from "raea/plugins/light_2d";function Shot() {return (<AbsoluteFill style={{ background: "#000" }}>- <Canvas3D>+ <><Camera3d transform={Transform.fromXyz(0, 0, 5).lookingAt([0, 0, 0])} projection={{ Perspective: { fov: 0.785398 } }} /><Entity position={[32, -32, 0]}><BevyComponent type="raea_sys_sprite::Draws2d" value={{}} />@@ -27,7 +27,7 @@ function Shot() {<Entity><Lighting2d value={{ color: [1, 1, 1], brightness: 0 }} /></Entity>- </Canvas3D>+ </></AbsoluteFill>);}diff --git a/sdk/raea/bench/bevy-ts/cases/plugin-panorbit.tsx b/sdk/raea/bench/bevy-ts/cases/plugin-panorbit.tsxindex de2b3203..237eb6cd 100644--- a/sdk/raea/bench/bevy-ts/cases/plugin-panorbit.tsx+++ b/sdk/raea/bench/bevy-ts/cases/plugin-panorbit.tsx@@ -9,7 +9,7 @@// probe: 54 32 g>150 r<80 b<80// probe: 8 32 r<30 g<30 b<30import { AbsoluteFill, Composition, registerRoot } from "raea";-import { Canvas3D, ToneMapping } from "raea/3d";+import { ToneMapping } from "raea/3d";import { Camera3d } from "raea/camera";import { Transform } from "raea/transform";import { StandardMaterial } from "raea/pbr";@@ -19,7 +19,7 @@ import { PanOrbitCamera } from "raea/plugins/panorbit";function Shot() {return (<AbsoluteFill style={{ background: "#000" }}>- <Canvas3D>+ <><Camera3d transform={Transform.fromXyz(0, 0, -5).lookingAt([0, 0, -10])} projection={{ Perspective: { fov: 0.785398 } }}><PanOrbitCamera value={{ focus: [0, 0, 0], yaw: Math.PI / 2, pitch: 0, radius: 5 } as PanOrbitCamera} /></Camera3d>@@ -32,7 +32,7 @@ function Shot() {<Cuboid half_size={[0.4, 0.4, 0.4]} /><StandardMaterial base_color="#00ff00" unlit /></Mesh3d>- </Canvas3D>+ </></AbsoluteFill>);}diff --git a/sdk/raea/bench/bevy-ts/cases/plugin-smud.tsx b/sdk/raea/bench/bevy-ts/cases/plugin-smud.tsxindex 53efa6d9..e3272a21 100644--- a/sdk/raea/bench/bevy-ts/cases/plugin-smud.tsx+++ b/sdk/raea/bench/bevy-ts/cases/plugin-smud.tsx@@ -8,7 +8,7 @@// probe: 2 2 r<20 g<20 b<20// probe: 61 61 r<20 g<20 b<20import { AbsoluteFill, Composition, registerRoot } from "raea";-import { BevyComponent, Canvas3D, Entity } from "raea/3d";+import { BevyComponent, Entity } from "raea/3d";import { Camera3d } from "raea/camera";import { Transform } from "raea/transform";import { SmudShape } from "raea/plugins/smud";@@ -16,7 +16,7 @@ import { SmudShape } from "raea/plugins/smud";function Shot() {return (<AbsoluteFill style={{ background: "#000" }}>- <Canvas3D>+ <><Camera3d transform={Transform.fromXyz(0, 0, 5).lookingAt([0, 0, 0])} projection={{ Perspective: { fov: 0.785398 } }} /><Entity position={[32, -32, 0]}><BevyComponent type="raea_sys_sprite::Draws2d" value={{}} />@@ -32,7 +32,7 @@ function Shot() {}}/></Entity>- </Canvas3D>+ </></AbsoluteFill>);}diff --git a/sdk/raea/bench/bevy-ts/cases/plugin-sprite3d.tsx b/sdk/raea/bench/bevy-ts/cases/plugin-sprite3d.tsxindex c91439c8..d89e70bd 100644--- a/sdk/raea/bench/bevy-ts/cases/plugin-sprite3d.tsx+++ b/sdk/raea/bench/bevy-ts/cases/plugin-sprite3d.tsx@@ -9,7 +9,7 @@// probe: 45 45 r>200 g>200 b>200// probe: 45 19 r<40 g<40 b<40import { AbsoluteFill, Composition, registerRoot } from "raea";-import { Canvas3D, Entity, ToneMapping } from "raea/3d";+import { Entity, ToneMapping } from "raea/3d";import { Camera3d } from "raea/camera";import { Transform } from "raea/transform";import { SpriteQuad } from "raea/plugins/sprite3d";@@ -17,13 +17,13 @@ import { SpriteQuad } from "raea/plugins/sprite3d";function Shot() {return (<AbsoluteFill style={{ background: "#000" }}>- <Canvas3D>+ <><Camera3d transform={Transform.fromXyz(0, 0, 3).lookingAt([0, 0, 0])} projection={{ Perspective: { fov: 0.785398 } }} /><ToneMapping mode="none" /><Entity position={[0, 0, 0]}><SpriteQuad value={{ image: { width: 2, height: 2, pixels: ["#ffffff", "#000000", "#000000", "#ffffff"], nearest: true }, pixels_per_metre: 1, unlit: true }} /></Entity>- </Canvas3D>+ </></AbsoluteFill>);}diff --git a/sdk/raea/bench/bevy-ts/cases/plugin-spritesheet.tsx b/sdk/raea/bench/bevy-ts/cases/plugin-spritesheet.tsxindex a30c18fe..1d731577 100644--- a/sdk/raea/bench/bevy-ts/cases/plugin-spritesheet.tsx+++ b/sdk/raea/bench/bevy-ts/cases/plugin-spritesheet.tsx@@ -8,7 +8,7 @@// probe: 32 32 g>150 r<80 b<80// probe: 2 2 r<20 g<20 b<20import { AbsoluteFill, Composition, registerRoot } from "raea";-import { Canvas3D, Entity } from "raea/3d";+import { Entity } from "raea/3d";import { Camera3d } from "raea/camera";import { Transform } from "raea/transform";import { SheetAnimation } from "raea/plugins/spritesheet";@@ -16,12 +16,12 @@ import { SheetAnimation } from "raea/plugins/spritesheet";function Shot() {return (<AbsoluteFill style={{ background: "#000" }}>- <Canvas3D>+ <><Camera3d transform={Transform.fromXyz(0, 0, 5).lookingAt([0, 0, 0])} projection={{ Perspective: { fov: 0.785398 } }} /><Entity position={[32, -32, 0]}><SheetAnimation value={{ image: { width: 2, height: 1, pixels: ["#ff0000", "#00ff00"], nearest: true }, image_size: [2, 1], columns: 2, rows: 1, frames: [0, 1], frame_ms: 500, size: [32, 32] }} /></Entity>- </Canvas3D>+ </></AbsoluteFill>);}diff --git a/sdk/raea/bench/bevy-ts/cases/plugin-text3d.tsx b/sdk/raea/bench/bevy-ts/cases/plugin-text3d.tsxindex 30eac6c1..c937d7d4 100644--- a/sdk/raea/bench/bevy-ts/cases/plugin-text3d.tsx+++ b/sdk/raea/bench/bevy-ts/cases/plugin-text3d.tsx@@ -12,7 +12,7 @@// probe: 32 22 r<20 g<20 b<20// probe: 2 2 r<20 g<20 b<20import { AbsoluteFill, Composition, registerRoot } from "raea";-import { Canvas3D, Entity, ToneMapping } from "raea/3d";+import { Entity, ToneMapping } from "raea/3d";import { Camera3d } from "raea/camera";import { Transform } from "raea/transform";import { Label3d } from "raea/plugins/text3d";@@ -20,13 +20,13 @@ import { Label3d } from "raea/plugins/text3d";function Shot() {return (<AbsoluteFill style={{ background: "#000" }}>- <Canvas3D>+ <><Camera3d transform={Transform.fromXyz(0, 0, 3).lookingAt([0, 0, 0])} projection={{ Perspective: { fov: 0.785398 } }} /><ToneMapping mode="none" /><Entity position={[0, 0, 0]}><Label3d value={{ text: "H", size: 128, world_scale: 1.5, color: [1, 1, 1, 1], font: "Fira Mono" }} /></Entity>- </Canvas3D>+ </></AbsoluteFill>);}diff --git a/sdk/raea/bench/bevy-ts/cases/plugin-tiled.tsx b/sdk/raea/bench/bevy-ts/cases/plugin-tiled.tsxindex 8dfe2834..6de0aa1f 100644--- a/sdk/raea/bench/bevy-ts/cases/plugin-tiled.tsx+++ b/sdk/raea/bench/bevy-ts/cases/plugin-tiled.tsx@@ -10,7 +10,7 @@// probe: 16 48 g>200 r<60 b<60// probe: 48 48 r>200 g<60 b<60import { AbsoluteFill, Composition, registerRoot } from "raea";-import { BevyComponent, Canvas3D, Entity } from "raea/3d";+import { BevyComponent, Entity } from "raea/3d";import { Camera3d } from "raea/camera";import { Transform } from "raea/transform";import { TiledMap } from "raea/plugins/tiled";@@ -19,14 +19,14 @@ import { TilemapAnchor } from "raea/plugins/tilemap";function Shot() {return (<AbsoluteFill style={{ background: "#000" }}>- <Canvas3D>+ <><Camera3d transform={Transform.fromXyz(0, 0, 5).lookingAt([0, 0, 0])} projection={{ Perspective: { fov: 0.785398 } }} /><Entity position={[0, 0, 0]}><BevyComponent type="raea_sys_sprite::Draws2d" value={{}} /><TiledMap value="plugin-tiled.tmx" /><TilemapAnchor value="TopLeft" /></Entity>- </Canvas3D>+ </></AbsoluteFill>);}diff --git a/sdk/raea/bench/bevy-ts/cases/plugin-tilemap.tsx b/sdk/raea/bench/bevy-ts/cases/plugin-tilemap.tsxindex a2708c80..4108aae2 100644--- a/sdk/raea/bench/bevy-ts/cases/plugin-tilemap.tsx+++ b/sdk/raea/bench/bevy-ts/cases/plugin-tilemap.tsx@@ -10,7 +10,7 @@// probe: 16 48 g>200 r<60 b<60// probe: 48 48 r>200 g<60 b<60import { AbsoluteFill, Composition, registerRoot } from "raea";-import { BevyComponent, Canvas3D, Entity } from "raea/3d";+import { BevyComponent, Entity } from "raea/3d";import { Camera3d } from "raea/camera";import { Transform } from "raea/transform";import { TilemapAnchor, TilemapGridSize, TilemapId, TilemapSize, TilemapTexture, TilemapTileSize, TilePos, TileTextureIndex } from "raea/plugins/tilemap";@@ -20,7 +20,7 @@ const tiles: [number, number, number][] = [[0, 1, 0], [1, 1, 1], [0, 0, 1], [1,function Shot() {return (<AbsoluteFill style={{ background: "#000" }}>- <Canvas3D>+ <><Camera3d transform={Transform.fromXyz(0, 0, 5).lookingAt([0, 0, 0])} projection={{ Perspective: { fov: 0.785398 } }} /><Entity name="map" position={[0, 0, 0]}><BevyComponent type="raea_sys_sprite::Draws2d" value={{}} />@@ -37,7 +37,7 @@ function Shot() {<TileTextureIndex value={i} /></Entity>))}- </Canvas3D>+ </></AbsoluteFill>);}diff --git a/sdk/raea/bench/bevy-ts/cases/plugin-trenchbroom.tsx b/sdk/raea/bench/bevy-ts/cases/plugin-trenchbroom.tsxindex a304d62b..637f5fe5 100644--- a/sdk/raea/bench/bevy-ts/cases/plugin-trenchbroom.tsx+++ b/sdk/raea/bench/bevy-ts/cases/plugin-trenchbroom.tsx@@ -10,7 +10,7 @@// probe: 2 2 r<20 g<20 b<20// probe: 61 61 r<20 g<20 b<20import { AbsoluteFill, Composition, registerRoot } from "raea";-import { BevyComponent, Canvas3D, Entity } from "raea/3d";+import { BevyComponent, Entity } from "raea/3d";import { Camera3d } from "raea/camera";import { DirectionalLight } from "raea/light";import { Transform } from "raea/transform";@@ -18,13 +18,13 @@ import { Transform } from "raea/transform";function Shot() {return (<AbsoluteFill style={{ background: "#000" }}>- <Canvas3D>+ <><Camera3d transform={Transform.fromXyz(0, 0, 6).lookingAt([0, 0, 0])} projection={{ Perspective: { fov: 0.785398 } }} /><DirectionalLight transform={Transform.fromXyz(0.2, 0.3, 1).lookingAt([0, 0, 0])} illuminance={10000} /><Entity><BevyComponent type="bevy_world_serialization::components::WorldAssetRoot" value="plugin-trenchbroom.map#Scene" /></Entity>- </Canvas3D>+ </></AbsoluteFill>);}diff --git a/sdk/raea/bench/bevy-ts/cases/plugin-vector-shapes.tsx b/sdk/raea/bench/bevy-ts/cases/plugin-vector-shapes.tsxindex 95064bf7..549af781 100644--- a/sdk/raea/bench/bevy-ts/cases/plugin-vector-shapes.tsx+++ b/sdk/raea/bench/bevy-ts/cases/plugin-vector-shapes.tsx@@ -9,7 +9,7 @@// probe: 48 32 g>150 b>150 r<80// probe: 32 4 r<20 g<20 b<20import { AbsoluteFill, Composition, registerRoot } from "raea";-import { Canvas3D, Entity } from "raea/3d";+import { Entity } from "raea/3d";import { Camera3d } from "raea/camera";import { Transform } from "raea/transform";import { DiscComponent, RectangleComponent, Shape3d, ShapeFill, ShapeMaterial } from "raea/plugins/vector_shapes";@@ -20,7 +20,7 @@ const srgb = (red: number, green: number, blue: number) => ({ Srgba: { red, greefunction Shot() {return (<AbsoluteFill style={{ background: "#000" }}>- <Canvas3D>+ <><Camera3d transform={Transform.fromXyz(0, 0, 5).lookingAt([0, 0, 0])} projection={{ Perspective: { fov: 0.785398 } }} /><Entity position={[-1, 0, 0]}><ShapeMaterial value={material} />@@ -34,7 +34,7 @@ function Shot() {<RectangleComponent value={{ alignment: "Flat", size: [1.2, 1.2], corner_radii: [0, 0, 0, 0] }} /><Shape3d value={{}} /></Entity>- </Canvas3D>+ </></AbsoluteFill>);}diff --git a/sdk/raea/bench/bevy-ts/cases/sampler-linear.tsx b/sdk/raea/bench/bevy-ts/cases/sampler-linear.tsxindex 62ca9c8b..8532ec5d 100644--- a/sdk/raea/bench/bevy-ts/cases/sampler-linear.tsx+++ b/sdk/raea/bench/bevy-ts/cases/sampler-linear.tsx@@ -4,7 +4,7 @@// probe: 32 20 r>60 r<200// probe: 32 44 r>60 r<200import { AbsoluteFill, Composition, registerRoot } from "raea";-import { Canvas3D } from "raea/3d";+import { Mesh3d, Plane3d } from "raea/mesh";import { Transform } from "raea/transform";import { Camera3d } from "raea/camera";@@ -13,13 +13,13 @@ import { StandardMaterial } from "raea/pbr";function Shot() {return (<AbsoluteFill style={{ background: "#000" }}>- <Canvas3D>+ <><Camera3d transform={Transform.fromXyz(0, 0, 3).lookingAt([0, 0, 0])} projection={{ Perspective: { fov: 0.698131700797732 } }} /><Mesh3d><Plane3d normal={[0, 0, 1]} half_size={[1, 1]} /><StandardMaterial base_color="#cccccc" base_color_texture={{ path: "checker2.png", sampler: { filter: "linear" } }} unlit /></Mesh3d>- </Canvas3D>+ </></AbsoluteFill>);}diff --git a/sdk/raea/bench/bevy-ts/cases/sampler-nearest.tsx b/sdk/raea/bench/bevy-ts/cases/sampler-nearest.tsxindex f83f22c8..6ccd2827 100644--- a/sdk/raea/bench/bevy-ts/cases/sampler-nearest.tsx+++ b/sdk/raea/bench/bevy-ts/cases/sampler-nearest.tsx@@ -5,7 +5,7 @@// probe: 35 20 r<40 g<40// probe: 35 44 r>150import { AbsoluteFill, Composition, registerRoot } from "raea";-import { Canvas3D } from "raea/3d";+import { Mesh3d, Plane3d } from "raea/mesh";import { Transform } from "raea/transform";import { Camera3d } from "raea/camera";@@ -14,13 +14,13 @@ import { StandardMaterial } from "raea/pbr";function Shot() {return (<AbsoluteFill style={{ background: "#000" }}>- <Canvas3D>+ <><Camera3d transform={Transform.fromXyz(0, 0, 3).lookingAt([0, 0, 0])} projection={{ Perspective: { fov: 0.698131700797732 } }} /><Mesh3d><Plane3d normal={[0, 0, 1]} half_size={[1, 1]} /><StandardMaterial base_color="#cccccc" base_color_texture={{ path: "checker2.png", sampler: { filter: "nearest" } }} unlit /></Mesh3d>- </Canvas3D>+ </></AbsoluteFill>);}diff --git a/sdk/raea/bench/bevy-ts/cases/shader-character.tsx b/sdk/raea/bench/bevy-ts/cases/shader-character.tsxindex 0b584c7c..1cfc0b14 100644--- a/sdk/raea/bench/bevy-ts/cases/shader-character.tsx+++ b/sdk/raea/bench/bevy-ts/cases/shader-character.tsx@@ -5,14 +5,14 @@// probe: 32 32 g>100 r<40 b<40// probe: 4 32 g<20import { AbsoluteFill, Composition, registerRoot } from "raea";-import { ToneMapping, Canvas3D } from "raea/3d";+import { ToneMapping } from "raea/3d";import { Character, type Skeleton } from "raea/character";import { AmbientLight, DirectionalLight } from "raea/light";import { Transform } from "raea/transform";import { Camera3d } from "raea/camera";import { ExtendedMaterial, ShaderExtension, StandardMaterial } from "raea/pbr";// card-body/skeleton.json, inline-const skeleton: Skeleton = { name: "card", height: 2, joints: [{ name: "Hips", parent: -1, head: [0, 1, 0], tail: [0, 2, 0] }], landmarks: { eyes: [0, 1.7, 0] } };+const skeleton: Skeleton = { name: "card", height: 2, joints: [{ name: "pelvis", parent: -1, head: [0, 1, 0], tail: [0, 2, 0] }], landmarks: { eyes: [0, 1.7, 0] } };const wesl = `fn lit(in: VertexOutput, pbr: PbrInput, color: vec4<f32>) -> vec4<f32> {@@ -22,7 +22,7 @@ fn lit(in: VertexOutput, pbr: PbrInput, color: vec4<f32>) -> vec4<f32> {function Shot() {return (<AbsoluteFill style={{ background: "#000" }}>- <Canvas3D>+ <><Camera3d transform={Transform.fromXyz(0, 1, 4).lookingAt([0, 1, 0])} projection={{ Perspective: { fov: 0.698131700797732 } }} /><ToneMapping mode="none" /><AmbientLight brightness={120} />@@ -30,7 +30,7 @@ function Shot() {<Character skeleton={skeleton} src="card-body" outline={false}><ExtendedMaterial base={<StandardMaterial base_color="#cccccc" />} extension={<ShaderExtension {...({ wesl })} />} /></Character>- </Canvas3D>+ </></AbsoluteFill>);}diff --git a/sdk/raea/bench/bevy-ts/cases/shader-defs.tsx b/sdk/raea/bench/bevy-ts/cases/shader-defs.tsxindex 56c2d3bb..78431642 100644--- a/sdk/raea/bench/bevy-ts/cases/shader-defs.tsx+++ b/sdk/raea/bench/bevy-ts/cases/shader-defs.tsx@@ -10,7 +10,7 @@// probe: 32 1 r>200 g>200 b>200// probe: 32 32 r<40 g<40 b<40import { AbsoluteFill, Composition, registerRoot } from "raea";-import { Canvas3D, FramePass, ShaderMesh, ToneMapping } from "raea/3d";+import { FramePass, ShaderMesh, ToneMapping } from "raea/3d";import { Cuboid, Mesh3d } from "raea/mesh";import { Transform } from "raea/transform";import { Camera3d } from "raea/camera";@@ -38,7 +38,7 @@ fn shade(in: FullscreenVertexOutput) -> vec4<f32> {function Shot() {return (<AbsoluteFill style={{ background: "#000" }}>- <Canvas3D>+ <><Camera3d transform={Transform.fromXyz(0, 0, 6).lookingAt([0, 0, 0])} projection={{ Perspective: { fov: 0.872664625997165 } }} /><ToneMapping mode="none" /><ShaderMesh shape="box(1, 1, 1)" position={[-1.4, 1.2, 0]} wesl={pick} defs={{ RED: true }} />@@ -46,7 +46,7 @@ function Shot() {<Mesh3d transform={Transform.fromXyz(-1.4, -1.2, 0)}><Cuboid half_size={[0.5, 0.5, 0.5]} /><ExtendedMaterial base={<StandardMaterial base_color="#ffffff" />} extension={<ShaderExtension wesl={level} defs={{ G: 255 }} />} /></Mesh3d><Mesh3d transform={Transform.fromXyz(1.4, -1.2, 0)}><Cuboid half_size={[0.5, 0.5, 0.5]} /><ExtendedMaterial base={<StandardMaterial base_color="#ffffff" />} extension={<ShaderExtension wesl={level} defs={{ G: 0 }} />} /></Mesh3d><FramePass wesl={band} defs={{ BAND: true }} />- </Canvas3D>+ </></AbsoluteFill>);}diff --git a/sdk/raea/bench/bevy-ts/cases/shader-extension.tsx b/sdk/raea/bench/bevy-ts/cases/shader-extension.tsxindex 762467ff..c25a6376 100644--- a/sdk/raea/bench/bevy-ts/cases/shader-extension.tsx+++ b/sdk/raea/bench/bevy-ts/cases/shader-extension.tsx@@ -5,7 +5,7 @@// probe: 22 32 r>110 g<60 b>150// probe: 43 32 r<70 g<60 b>150import { AbsoluteFill, Composition, registerRoot } from "raea";-import { ToneMapping, Canvas3D, Sphere } from "raea/3d";+import { ToneMapping, Sphere } from "raea/3d";import { Mesh3d } from "raea/mesh";import { AmbientLight, DirectionalLight } from "raea/light";import { Transform } from "raea/transform";@@ -23,7 +23,7 @@ fn lit(in: VertexOutput, pbr: PbrInput, color: vec4<f32>) -> vec4<f32> {function Shot() {return (<AbsoluteFill style={{ background: "#000" }}>- <Canvas3D>+ <><Camera3d transform={Transform.fromXyz(0, 0, 4).lookingAt([0, 0, 0])} projection={{ Perspective: { fov: 1.0471975511966 } }} /><ToneMapping mode="none" /><AmbientLight brightness={0} />@@ -32,7 +32,7 @@ function Shot() {<Sphere radius={1.2} /><ExtendedMaterial base={<StandardMaterial base_color="#ffffff" perceptual_roughness={0.9} />} extension={<ShaderExtension {...({ wesl, uniforms: { blue: 1 } })} />} /></Mesh3d>- </Canvas3D>+ </></AbsoluteFill>);}diff --git a/sdk/raea/bench/bevy-ts/cases/shader-model.tsx b/sdk/raea/bench/bevy-ts/cases/shader-model.tsxindex 43e74999..cd014666 100644--- a/sdk/raea/bench/bevy-ts/cases/shader-model.tsx+++ b/sdk/raea/bench/bevy-ts/cases/shader-model.tsx@@ -5,7 +5,7 @@// probe: 32 32 g>100 r<40 b<40// probe: 4 4 g<20import { AbsoluteFill, Composition, registerRoot } from "raea";-import { ToneMapping, Canvas3D, Model } from "raea/3d";+import { ToneMapping, Model } from "raea/3d";import { AmbientLight, DirectionalLight } from "raea/light";import { Transform } from "raea/transform";import { Camera3d } from "raea/camera";@@ -19,7 +19,7 @@ fn lit(in: VertexOutput, pbr: PbrInput, color: vec4<f32>) -> vec4<f32> {function Shot() {return (<AbsoluteFill style={{ background: "#000" }}>- <Canvas3D>+ <><Camera3d transform={Transform.fromXyz(0, 0, 4).lookingAt([0, 0, 0])} projection={{ Perspective: { fov: 0.698131700797732 } }} /><ToneMapping mode="none" /><AmbientLight brightness={120} />@@ -27,7 +27,7 @@ function Shot() {<Model src="lit-card.gltf"><ExtendedMaterial base={<StandardMaterial material="card" />} extension={<ShaderExtension {...({ wesl })} />} /></Model>- </Canvas3D>+ </></AbsoluteFill>);}diff --git a/sdk/raea/bench/bevy-ts/cases/shader-scene.tsx b/sdk/raea/bench/bevy-ts/cases/shader-scene.tsxindex bff0e51c..9f260281 100644--- a/sdk/raea/bench/bevy-ts/cases/shader-scene.tsx+++ b/sdk/raea/bench/bevy-ts/cases/shader-scene.tsx@@ -7,7 +7,7 @@// probe: 32 46 g>100 r<40 b<40// probe: 32 12 r>180 g>180 b>180import { AbsoluteFill, Composition, registerRoot } from "raea";-import { ToneMapping, Canvas3D, Model, SurfaceShader } from "raea/3d";+import { ToneMapping, Model, SurfaceShader } from "raea/3d";import { StandardMaterial } from "raea/pbr";import { Cuboid, Mesh3d } from "raea/mesh";import { AmbientLight, DirectionalLight } from "raea/light";@@ -22,7 +22,7 @@ fn lit(in: VertexOutput, pbr: PbrInput, color: vec4<f32>) -> vec4<f32> {function Shot() {return (<AbsoluteFill style={{ background: "#000" }}>- <Canvas3D>+ <><Camera3d transform={Transform.fromXyz(0, 0, 6).lookingAt([0, 0, 0])} projection={{ Perspective: { fov: 0.872664625997165 } }} /><ToneMapping mode="none" /><AmbientLight brightness={120} />@@ -32,7 +32,7 @@ function Shot() {<Mesh3d transform={Transform.fromXyz(1.6, 0.9, 0)}><Cuboid half_size={[0.5, 0.5, 0.5]} /><StandardMaterial base_color="#ffffff" /></Mesh3d><Mesh3d transform={Transform.fromXyz(0, 1.6, 0)}><Cuboid half_size={[0.3, 0.3, 0.3]} /><StandardMaterial base_color="#ffffff" unlit /></Mesh3d><Model src="lit-card.gltf" position={[0, -1.2, 0]} scale={0.6} />- </Canvas3D>+ </></AbsoluteFill>);}diff --git a/sdk/raea/bench/bevy-ts/cases/texture-array.tsx b/sdk/raea/bench/bevy-ts/cases/texture-array.tsxindex f0301185..31f352f9 100644--- a/sdk/raea/bench/bevy-ts/cases/texture-array.tsx+++ b/sdk/raea/bench/bevy-ts/cases/texture-array.tsx@@ -12,7 +12,7 @@// probe: 32 1 r>200 g>200 b>200// probe: 32 32 r<40 g<40 b<40import { AbsoluteFill, Composition, registerRoot } from "raea";-import { Canvas3D, FramePass, ShaderMesh, ToneMapping } from "raea/3d";+import { FramePass, ShaderMesh, ToneMapping } from "raea/3d";import { Cuboid, Mesh3d } from "raea/mesh";import { Transform } from "raea/transform";import { Camera3d } from "raea/camera";@@ -42,7 +42,7 @@ fn shade(in: FullscreenVertexOutput) -> vec4<f32> {function Shot() {return (<AbsoluteFill style={{ background: "#000" }}>- <Canvas3D>+ <><Camera3d transform={Transform.fromXyz(0, 0, 6).lookingAt([0, 0, 0])} projection={{ Perspective: { fov: 0.872664625997165 } }} /><ToneMapping mode="none" /><ShaderMesh shape="box(1, 1, 1)" position={[-1.4, 1.2, 0]} wesl={pick} uniforms={{ layer: 0 }} textures={{ frames }} />@@ -50,7 +50,7 @@ function Shot() {<Mesh3d transform={Transform.fromXyz(-1.4, -1.2, 0)}><Cuboid half_size={[0.5, 0.5, 0.5]} /><ExtendedMaterial base={<StandardMaterial base_color="#ffffff" />} extension={<ShaderExtension wesl={strip(0)} textures={{ strip: checker }} />} /></Mesh3d><Mesh3d transform={Transform.fromXyz(1.4, -1.2, 0)}><Cuboid half_size={[0.5, 0.5, 0.5]} /><ExtendedMaterial base={<StandardMaterial base_color="#ffffff" />} extension={<ShaderExtension wesl={strip(1)} textures={{ strip: checker }} />} /></Mesh3d><FramePass wesl={band} textures={{ ramp: { layers: [one("#000000"), one("#ffffff")] } }} />- </Canvas3D>+ </></AbsoluteFill>);}diff --git a/sdk/raea/bench/bevy/lights/edit.tsx b/sdk/raea/bench/bevy/lights/edit.tsxindex 7b496f96..9c2ea1ea 100644--- a/sdk/raea/bench/bevy/lights/edit.tsx+++ b/sdk/raea/bench/bevy/lights/edit.tsx@@ -2,10 +2,10 @@// (position and lookAt animated); a Group turns its children together; a pillar grows (non-uniform scale); a sphere// appears at frame 30 from a Sequence.import { AbsoluteFill, Composition, interpolate, registerRoot, Sequence, useCurrentFrame } from "raea";-import { Cylinder, Sphere, SpotLight, Torus, Entity } from "raea/3d";+import { Cylinder, Sphere, Torus, Entity } from "raea/3d";import { StandardMaterial } from "raea/pbr";import { Cuboid, Mesh3d } from "raea/mesh";-import { AmbientLight, DirectionalLight, PointLight } from "raea/light";+import { AmbientLight, DirectionalLight, PointLight, SpotLight } from "raea/light";import { Quat, Transform } from "raea/transform";import { Camera3d } from "raea/camera";@@ -24,7 +24,7 @@ function Shot() {<AmbientLight brightness={60} /><DirectionalLight transform={Transform.fromXyz(-4, 6, 2).lookingAt([0, 0, 0])} illuminance={2000} /><PointLight color="#ffd29a" transform={Transform.fromXyz(Math.cos(a) * 2.5, 1.8, Math.sin(a) * 2.5)} intensity={1080000} range={12} shadow_maps_enabled />- <SpotLight position={[0, 6, 0]} target={[0, 0, 0]} angle={0.5} penumbra={0.4} intensity={2.5} color="#9ad0ff" castShadow />+ <SpotLight color="#9ad0ff" transform={Transform.fromXyz(0, 6, 0).lookingAt([0, 0, 0], [0, 0, -1])} intensity={2250000} outer_angle={0.5} inner_angle={0.3} shadow_maps_enabled /><Mesh3d transform={Transform.fromXyz(0, -0.05, 0)}><Cuboid half_size={[6, 0.05, 6]} /><StandardMaterial base_color="#9aa0a6" perceptual_roughness={0.8} />diff --git a/sdk/raea/bench/bevy/shadows/edit.tsx b/sdk/raea/bench/bevy/shadows/edit.tsxindex dc4877cb..8cf6bb01 100644--- a/sdk/raea/bench/bevy/shadows/edit.tsx+++ b/sdk/raea/bench/bevy/shadows/edit.tsx@@ -3,9 +3,9 @@// a 4096 map and a little more bias than Bevy's. The camera dollies along the columns, so their shadows cross from one// cascade to the next.import { AbsoluteFill, Composition, interpolate, registerRoot, useCurrentFrame } from "raea";-import { Cylinder, Shadows } from "raea/3d";+import { Shadows } from "raea/3d";import { StandardMaterial } from "raea/pbr";-import { Cuboid, Mesh3d, Plane3d } from "raea/mesh";+import { Cuboid, Mesh3d, Plane3d, ConicalFrustum } from "raea/mesh";import { AmbientLight, DirectionalLight, SpotLight } from "raea/light";import { Quat, Transform } from "raea/transform";import { Camera3d } from "raea/camera";@@ -32,7 +32,7 @@ function Shot() {</Mesh3d>{columns.map((cz) => (<Mesh3d key={cz} transform={Transform.fromXyz(1.5, 2, cz)}>- <Cylinder args={[0.35, 0.4, 4, 24]} />+ <ConicalFrustum radius_top={0.35} radius_bottom={0.4} height={4} /><StandardMaterial base_color="#e6dccb" perceptual_roughness={0.7} /></Mesh3d>))}diff --git a/sdk/raea/bench/bevy/volume-light/edit.tsx b/sdk/raea/bench/bevy/volume-light/edit.tsxindex 21dbacbf..2933d92e 100644--- a/sdk/raea/bench/bevy/volume-light/edit.tsx+++ b/sdk/raea/bench/bevy/volume-light/edit.tsx@@ -5,10 +5,10 @@// over the right of the field, unseen: only its shadow and the gap it cuts in the shafts show. Every value is the// frame's, so render equals play (check.sh).import { AbsoluteFill, Composition, interpolate, registerRoot, useCurrentFrame } from "raea";-import { Cylinder, FogVolume, Shadows, Sphere, ToneMapping, VolumetricFog } from "raea/3d";+import { FogVolume, Shadows, Sphere, ToneMapping, VolumetricFog } from "raea/3d";import { Cloud } from "../../../../../examples/volumes/cloud";import { StandardMaterial } from "raea/pbr";-import { Cuboid, Mesh3d } from "raea/mesh";+import { Cuboid, Mesh3d, ConicalFrustum } from "raea/mesh";import { AmbientLight, DirectionalLight } from "raea/light";import { Quat, Transform } from "raea/transform";import { Camera3d } from "raea/camera";@@ -50,7 +50,7 @@ function Shot() {<StandardMaterial base_color="#7c8a5c" perceptual_roughness={0.95} /></Mesh3d><Mesh3d transform={Transform.fromXyz(-6, 4, 2)} name="column">- <Cylinder args={[1, 1.2, 8]} />+ <ConicalFrustum radius_top={1} radius_bottom={1.2} height={8} /><StandardMaterial base_color="#d8d2c6" perceptual_roughness={0.7} /></Mesh3d><Mesh3d transform={Transform.fromXyz(4, 1.5, 6)} name="ball">diff --git a/sdk/raea/bench/black-frame/scene.tsx b/sdk/raea/bench/black-frame/scene.tsxindex 4bcfffe9..63d7e1b2 100644--- a/sdk/raea/bench/black-frame/scene.tsx+++ b/sdk/raea/bench/black-frame/scene.tsx@@ -1,7 +1,7 @@// The black-frame redraw's 3D case: a box under a page of text (the 3D path, bevy_over_3d), so a redraw draws both// again. check.sh renders it as is and with a GPU fault injected (RAEA_BLACK_FAULT).import { AbsoluteFill, Composition, registerRoot } from "raea";-import { Canvas3D } from "raea/3d";+import { Transform } from "raea/transform";import { Camera3d } from "raea/camera";import { Cuboid, Mesh3d } from "raea/mesh";@@ -10,10 +10,10 @@ import { StandardMaterial } from "raea/pbr";function Shot() {return (<AbsoluteFill style={{ background: "#efe0b4" }}>- <Canvas3D>+ <><Camera3d transform={Transform.fromXyz(0, 0, 5).lookingAt([0, 0, 0])} /><Mesh3d transform={Transform.fromXyz(0, 0, 0)}><Cuboid half_size={[1, 1, 1]} /><StandardMaterial base_color="#3a7d44" unlit /></Mesh3d>- </Canvas3D>+ </><AbsoluteFill style={{ padding: 16, display: "flex", flexWrap: "wrap", gap: 6, alignContent: "flex-start", fontFamily: "sans-serif" }}>{Array.from({ length: 30 }, (_, i) => (<div key={i} style={{ padding: "4px 8px", borderRadius: 6, background: "#2d4a6b", color: "#fff", fontSize: 14 }}>label {i}</div>diff --git a/sdk/raea/bench/character/clips.ts b/sdk/raea/bench/character/clips.tsindex 200df9ed..5241bd66 100644--- a/sdk/raea/bench/character/clips.ts+++ b/sdk/raea/bench/character/clips.ts@@ -71,7 +71,7 @@ function quality(sc: Scene, perf: ReturnType<typeof perform>, L: { contact: Uintconst nr = rangeOf(L as any), frames = perf.played.map((p) => nr.get(p.clip)!.start + p.f), tagged = !!L.db;const rest = skel.joints[0].head[1];let midMin = Infinity;- const feet = ["LeftFoot", "RightFoot"].map((n) => joint(skel, n));+ const feet = ["foot_l", "foot_r"].map((n) => joint(skel, n));let maxWalkY = -Infinity, walkN = 0, fast = 0, crouchedN = 0, carryN = 0, carryWalkN = 0, standY: number[] = [], minWalkY = Infinity, skateSum = 0, skateMax = 0;let prev: Vec3[] | null = null, prevK = -1;for (let f = 0; f < perf.frames; f++) {diff --git a/sdk/raea/bench/feature-layout/AGENTS.md b/sdk/raea/bench/feature-layout/AGENTS.mdnew file mode 100644index 00000000..00850fd3--- /dev/null+++ b/sdk/raea/bench/feature-layout/AGENTS.md@@ -0,0 +1,13 @@+# This project++A video, laid out by feature as a Bevy project is (raea init --layout feature):++- space.json: its name and kind. package.json: raea.plugins, the Bevy, Blitz and raea plugins it uses.+- assets/: its files. `staticFile("x.png")` reads assets/x.png (a media/ folder beside it is read first).+- src/main.tsx: the App, rendered with `raea render src/main.tsx`. It registers the Composition.+- src/<feature>.tsx: one feature each (title, captions, music), its components together; one with work in the App+ each frame also exports its plugin (definePlugin from "raea/app").+- src/shots/: the shots, each a scene component placed in a Sequence. src/screens/: one file per top-level state.+ src/ui/: page parts shared between features.++Never a components/ folder: a feature file holds a feature's components by name.diff --git a/sdk/raea/bench/feature-layout/assets/mark.svg b/sdk/raea/bench/feature-layout/assets/mark.svgnew file mode 100644index 00000000..dc3e80d3--- /dev/null+++ b/sdk/raea/bench/feature-layout/assets/mark.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64"><rect width="64" height="64" rx="12" fill="#22b573"/><path d="M16 34 l10 10 l22 -24" stroke="#ffffff" stroke-width="7" fill="none" stroke-linecap="round"/></svg>diff --git a/sdk/raea/bench/feature-layout/package.json b/sdk/raea/bench/feature-layout/package.jsonnew file mode 100644index 00000000..9ed757a3--- /dev/null+++ b/sdk/raea/bench/feature-layout/package.json@@ -0,0 +1,7 @@+{+ "name": "feature-layout",+ "private": true,+ "raea": {+ "plugins": []+ }+}diff --git a/sdk/raea/bench/feature-layout/space.json b/sdk/raea/bench/feature-layout/space.jsonnew file mode 100644index 00000000..7bf71560--- /dev/null+++ b/sdk/raea/bench/feature-layout/space.json@@ -0,0 +1,4 @@+{+ "name": "feature-layout",+ "kind": "video"+}diff --git a/sdk/raea/bench/feature-layout/src/main.tsx b/sdk/raea/bench/feature-layout/src/main.tsxnew file mode 100644index 00000000..5dddc7fa--- /dev/null+++ b/sdk/raea/bench/feature-layout/src/main.tsx@@ -0,0 +1,19 @@+// The App: its plugins and its root. A video registers its Composition here; its shots play in Sequences.+import { AbsoluteFill, Composition, Sequence, registerRoot } from "raea";+import { Opening } from "./shots/opening";+import { Title } from "./title";++const FPS = 30;++function Main() {+ return (+ <AbsoluteFill style={{ background: "#101418" }}>+ <Sequence from={0} durationInFrames={FPS * 3}>+ <Opening />+ </Sequence>+ <Title text="feature-layout" from={FPS / 2} />+ </AbsoluteFill>+ );+}++registerRoot(() => <Composition id="main" component={Main} width={1080} height={1920} fps={FPS} durationInFrames={FPS * 3} />);diff --git a/sdk/raea/bench/feature-layout/src/shots/opening.tsx b/sdk/raea/bench/feature-layout/src/shots/opening.tsxnew file mode 100644index 00000000..3c9728a2--- /dev/null+++ b/sdk/raea/bench/feature-layout/src/shots/opening.tsx@@ -0,0 +1,14 @@+// A shot: a scene component, one time range of the cut (main.tsx places it in a Sequence).+import { AbsoluteFill, Img, interpolate, staticFile, useCurrentFrame } from "raea";++export function Opening() {+ const f = useCurrentFrame();+ const x = interpolate(f, [0, 60], [-20, 20], { extrapolateRight: "clamp" });+ return (+ <AbsoluteFill style={{ alignItems: "center", justifyContent: "center" }}>+ <div style={{ width: "30%", aspectRatio: "1", borderRadius: "50%", background: "#ff7a1a", transform: `translateX(${x}%)` }} />+ {/* the fixture's own: a file in assets/, read by staticFile through the project's folder (S5a) */}+ <Img src={staticFile("mark.svg")} style={{ position: "absolute", left: "8%", top: "8%", width: "12%" }} />+ </AbsoluteFill>+ );+}diff --git a/sdk/raea/bench/feature-layout/src/title.tsx b/sdk/raea/bench/feature-layout/src/title.tsxnew file mode 100644index 00000000..5d8173ff--- /dev/null+++ b/sdk/raea/bench/feature-layout/src/title.tsx@@ -0,0 +1,13 @@+// A feature: its components together in one file. A feature with work in the App each frame (systems, resources)+// also exports its plugin, definePlugin({ name, build(app) }) from "raea/app"; this one draws only, so it has none.+import { interpolate, useCurrentFrame } from "raea";++export function Title({ text, from }: { text: string; from: number }) {+ const f = useCurrentFrame();+ const shown = interpolate(f, [from, from + 12], [0, 1], { extrapolateLeft: "clamp", extrapolateRight: "clamp" });+ return (+ <div style={{ position: "absolute", left: 0, right: 0, bottom: "12%", textAlign: "center", fontFamily: "Inter", fontWeight: 800, fontSize: 90, color: "#ffffff", opacity: shown }}>+ {text}+ </div>+ );+}diff --git a/sdk/raea/conformance/character.test.ts b/sdk/raea/conformance/character.test.tsindex 40182db9..0cfce7b3 100644--- a/sdk/raea/conformance/character.test.ts+++ b/sdk/raea/conformance/character.test.ts@@ -1,9 +1,9 @@// raea/character, clip and matching under plain bun: the skeleton's forward kinematics, the goals landing// where they are sent, clips surviving their file format, routes keeping clear, and a performance being a pure-// function of its inputs. The skeleton is a small stand-in with CMU's joints' names (no Anny export needed).+// function of its inputs. The skeleton is a small stand-in on raea's game_engine joints (stick.ts).import { afterAll, beforeAll, describe, expect, test } from "bun:test";import { BevyApp } from "raea/bevy";-import { flatHand, len, lookAt, palmAt, plant, pose, qaxis, qrot, reach, rest, softElbows, sub, twoBone, type Skeleton } from "raea/character";+import { captured, flatHand, withFingers, len, lookAt, palmAt, plant, pose, qaxis, qrot, reach, rest, softElbows, sub, twoBone, type Skeleton } from "raea/character";import { readBvh, readClips, retarget, writeClips } from "raea/clip";import { before, libraryPose, libraryTable, mirror, motionLibrary, perform, planFloor, route, stateMix, through, walkPlan } from "raea/matching";import { applyEffect, clipMeans, learnEffect, mirrorEffect, mixEffects } from "raea/effects";@@ -21,28 +21,28 @@ const near = (a: Vec3, b: Vec3, tol: number) => expect(len(sub(a, b))).toBeLessTdescribe("the skeleton", () => {test("at rest every joint is at its head", () => {- const w = pose(skel, rest(skel));+ const w = withFingers(skel, pose(skel, rest(skel)));skel.joints.forEach((j, i) => near(w.pos[i], j.head, 1e-9));});test("a turn at the shoulder carries the arm round it", () => {const p = rest(skel);- p.turns[at("LeftArm")] = qaxis([0, 0, 1], -Math.PI / 2); // the left arm down+ p.turns[at("upperarm_l")] = qaxis([0, 0, 1], -Math.PI / 2); // the left arm downconst w = pose(skel, p);- near(w.pos[at("LeftHand")], [0.12, 0.98 - 0.42, 0], 1e-9);+ near(w.pos[at("hand_l")], [0.12, 0.98 - 0.42, 0], 1e-9);});test("a mirrored pose mirrors the joints", () => {const p = rest(skel);- p.turns[at("LeftArm")] = qaxis([0, 0, 1], -1);+ p.turns[at("upperarm_l")] = qaxis([0, 0, 1], -1);const w = pose(skel, p), m = pose(skel, mirror(skel, p));- near(m.pos[at("RightHand")], mirrorX(w.pos[at("LeftHand")]), 1e-9);+ near(m.pos[at("hand_r")], mirrorX(w.pos[at("hand_l")]), 1e-9);});});describe("goals", () => {test("twoBone brings the wrist to a point in reach", () => {const target: Vec3 = [0.3, 0.75, 0.25];- const w = pose(skel, twoBone(skel, rest(skel), ["LeftArm", "LeftForeArm", "LeftHand"], target, [0, -1, 0]));- near(w.pos[at("LeftHand")], target, 1e-3);+ const w = pose(skel, twoBone(skel, rest(skel), ["upperarm_l", "lowerarm_l", "hand_l"], target, [0, -1, 0]));+ near(w.pos[at("hand_l")], target, 1e-3);});test("a limb never locks straight: out of reach it stops short, and a straight limb bends its own way", () => {const bend = (p: ReturnType<typeof rest>, a: string, b: string, c: string) => {@@ -50,40 +50,40 @@ describe("goals", () => {return (Math.acos((u[0] * v[0] + u[1] * v[1] + u[2] * v[2]) / len(u) / len(v)) * 180) / Math.PI;};// a wrist sent a metre out: the elbow still about 11° bent- const far = twoBone(skel, rest(skel), ["LeftArm", "LeftForeArm", "LeftHand"], [1.2, 0.98, 0]);- expect(bend(far, "LeftArm", "LeftForeArm", "LeftHand")).toBeGreaterThan(9);+ const far = twoBone(skel, rest(skel), ["upperarm_l", "lowerarm_l", "hand_l"], [1.2, 0.98, 0]);+ expect(bend(far, "upperarm_l", "lowerarm_l", "hand_l")).toBeGreaterThan(9);// an ankle pulled a little up from a straight leg: the knee goes ahead, not out or back- const w = pose(skel, twoBone(skel, rest(skel), ["LeftUpLeg", "LeftLeg", "LeftFoot"], [0.1, 0.12, 0]));- const knee = w.pos[at("LeftLeg")];+ const w = pose(skel, twoBone(skel, rest(skel), ["thigh_l", "calf_l", "foot_l"], [0.1, 0.12, 0]));+ const knee = w.pos[at("calf_l")];expect(knee[2]).toBeGreaterThan(0.05);// a straight arm relaxed to 12°, one bent 30° left alone- expect(bend(softElbows(skel, rest(skel)), "LeftArm", "LeftForeArm", "LeftHand")).toBeCloseTo(12, 0);+ expect(bend(softElbows(skel, rest(skel)), "upperarm_l", "lowerarm_l", "hand_l")).toBeCloseTo(12, 0);const bent = rest(skel);- bent.turns[at("LeftForeArm")] = qaxis([0, 1, 0], -(30 * Math.PI) / 180);- expect(bend(softElbows(skel, bent), "LeftArm", "LeftForeArm", "LeftHand")).toBeCloseTo(30, 1);+ bent.turns[at("lowerarm_l")] = qaxis([0, 1, 0], -(30 * Math.PI) / 180);+ expect(bend(softElbows(skel, bent), "upperarm_l", "lowerarm_l", "hand_l")).toBeCloseTo(30, 1);// relaxing bends the forearm ahead of the body- expect(pose(skel, softElbows(skel, rest(skel))).pos[at("LeftHand")][2]).toBeGreaterThan(0.02);+ expect(pose(skel, softElbows(skel, rest(skel))).pos[at("hand_l")][2]).toBeGreaterThan(0.02);});test("reach lays the hand flat and puts the palm on the point", () => {const target: Vec3 = [0.25, 0.7, 0.3];const p = reach(skel, rest(skel), "L", { at: target, point: [0, 0, 1] });- const w = pose(skel, p);+ const w = withFingers(skel, pose(skel, p));// the palm resting on the point: its middle half a hand's thickness over itnear(palmAt(skel, w, "L"), [target[0], target[1] + 0.009 * skel.height, target[2]], 2e-3);// the fingers ahead and level- const f = sub(w.pos[at("LeftFingerBase")], w.pos[at("LeftHand")]);+ const f = sub(w.pos[at("middle_01_l")], w.pos[at("hand_l")]);expect(f[2] / len(f)).toBeGreaterThan(0.99);void flatHand;});test("a planted foot's ankle stands over its spot at its height", () => {// on a step 10 cm up, a little aheadconst w = pose(skel, plant(skel, rest(skel), "L", { at: [0.1, 0.1, 0.1] }));- near(w.pos[at("LeftFoot")], [0.1, 0.16, 0.1], 1e-3);+ near(w.pos[at("foot_l")], [0.1, 0.16, 0.1], 1e-3);});test("lookAt turns the face to the target", () => {const target: Vec3 = [1, 1.14, 1];const w = pose(skel, lookAt(skel, rest(skel), target));- const h = at("Head");+ const h = at("head");const fwd = qrot(w.rot[h], [0, 0, 1]);const eyes = sub(w.pos[h], qrot(w.rot[h], sub(skel.joints[h].head, skel.landmarks.eyes)));const want = sub(target, eyes);@@ -99,7 +99,8 @@ describe("clips", () => {expect(b.frames.length).toBe(361);});test("retargeting onto the same skeleton keeps the walk's pace", () => {- expect(clip.frames).toBe(90);+ // (3 s at 30 fps, both ends: a BVH's T-pose frames are trimmed by pose, not by a skipped first frame)+ expect(clip.frames).toBe(91);const d = clip.root[(clip.frames - 1) * 3 + 2] - clip.root[2];expect(d / ((clip.frames - 1) / 30)).toBeCloseTo(1.1, 2);});@@ -188,7 +189,7 @@ describe("the library's table, styles and effects", () => {});test("an effect learned from a clip against itself changes nothing, and at weight 0 nothing either", () => {const e = learnEffect(skel, walk, walk), base = clipMeans(skel, walk), p = readClips(writeClips(skel, [walk])).get("walk")!;- const q = { root: [p.root[30], p.root[31], p.root[32]] as Vec3, turns: Array.from({ length: skel.joints.length }, (_, i) => Array.from(p.turns.subarray((30 * skel.joints.length + i) * 4, (30 * skel.joints.length + i) * 4 + 4)) as [number, number, number, number]) };+ const q = { root: [p.root[30], p.root[31], p.root[32]] as Vec3, turns: Array.from({ length: captured(skel) }, (_, i) => Array.from(p.turns.subarray((30 * captured(skel) + i) * 4, (30 * captured(skel) + i) * 4 + 4)) as [number, number, number, number]) };const out = applyEffect(skel, q, e, { base });for (let i = 0; i < q.turns.length; i++) for (let a = 0; a < 4; a++) expect(Math.abs(Math.abs(out.turns[i][a]) - Math.abs(q.turns[i][a]))).toBeLessThan(1e-3);expect(applyEffect(skel, q, mixEffects([[e, 1]]), { base, weight: 0 })).toBe(q);diff --git a/sdk/raea/conformance/extensions.test.tsx b/sdk/raea/conformance/extensions.test.tsxindex cd13377c..e5a933ae 100644--- a/sdk/raea/conformance/extensions.test.tsx+++ b/sdk/raea/conformance/extensions.test.tsx@@ -96,7 +96,8 @@ describe("3D", () => {const html = renderFrame(<Canvas3D><Mesh position={[1, 2, 3]}><Box args={[1, 2, 3]} /><MeshStandardMaterial color="#ff0000" /></Mesh></Canvas3D>,{ ...base, frame: 0 });- expect(html).toContain('data-3d="Canvas3D"');+ // a plain Canvas3D is its children (M6): no root of its own+ expect(html).not.toContain('data-3d="Canvas3D"');expect(html).toContain('data-3d="Mesh"');expect(html).toContain('data-shape="box(1, 2, 3)"');expect(html).toContain(""position":[1,2,3]");diff --git a/sdk/raea/conformance/golden/04-mesh-sign/edit.tsx b/sdk/raea/conformance/golden/04-mesh-sign/edit.tsxindex 98a133fa..2410bd92 100644--- a/sdk/raea/conformance/golden/04-mesh-sign/edit.tsx+++ b/sdk/raea/conformance/golden/04-mesh-sign/edit.tsx@@ -1,20 +1,20 @@// golden case 04: a Manifold shape in Bevy (a sign with SALE cut through it), turning, under a camera and two lightsimport { AbsoluteFill, interpolate, useCurrentFrame } from "../../../src";-import { AmbientLight, Canvas3D, DirectionalLight, Mesh, MeshStandardMaterial, PerspectiveCamera } from "../../../src/3d";+import { AmbientLight, DirectionalLight, Mesh, MeshStandardMaterial, PerspectiveCamera } from "../../../src/3d";export default function Sign() {const frame = useCurrentFrame();const turn = interpolate(frame, [0, 59], [-0.5, 0.5]);return (<AbsoluteFill style={{ background: "#101418" }}>- <Canvas3D>+ <><PerspectiveCamera position={[0, 0, 6]} fov={50} /><AmbientLight intensity={1} /><DirectionalLight position={[2, 3, 4]} intensity={1} /><Mesh shape={'minus(rounded_box(2.4, 1.1, 0.25, 0.08), text3d("SALE", 0.62, 0.6))'} rotation={[0, turn, 0]}><MeshStandardMaterial color="#e11d48" roughness={0.4} metalness={0} /></Mesh>- </Canvas3D>+ </></AbsoluteFill>);}diff --git a/sdk/raea/conformance/golden/05-world-solid/edit.tsx b/sdk/raea/conformance/golden/05-world-solid/edit.tsxindex 639e5e14..a549082c 100644--- a/sdk/raea/conformance/golden/05-world-solid/edit.tsx+++ b/sdk/raea/conformance/golden/05-world-solid/edit.tsx@@ -1,7 +1,7 @@// golden case 05: case 04's sign, made as a native solid (manifold.roundedBox(...).minus(manifold.text3d(...))) and// drawn from an ECS world whose system turns it each frame; the same frames as the rrl editimport { AbsoluteFill } from "../../../src";-import { Canvas3D, Scene, manifold } from "../../../src/3d";+import { Scene, manifold } from "../../../src/3d";import { createWorld } from "raea/ecs";const sign = manifold.roundedBox(2.4, 1.1, 0.25, 0.08).minus(manifold.text3d("SALE", 0.62, 0.6));@@ -16,9 +16,9 @@ world.system((w, f) => w.set(m, { rot_y: -0.5 + (f + 1) / 59 }));export default function WorldSign() {return (<AbsoluteFill style={{ background: "#101418" }}>- <Canvas3D>+ <><Scene world={world} />- </Canvas3D>+ </></AbsoluteFill>);}diff --git a/sdk/raea/conformance/golden/06-world-entities/edit.tsx b/sdk/raea/conformance/golden/06-world-entities/edit.tsxindex d4bd69b4..c92227b9 100644--- a/sdk/raea/conformance/golden/06-world-entities/edit.tsx+++ b/sdk/raea/conformance/golden/06-world-entities/edit.tsx@@ -2,7 +2,7 @@// (cylinder) as its child, turned by a system each frame; the gun's Transform is in the ship's space. The reference// (edit.rrl) is lowered from reference.tsx, which places the same meshes by hand with <Mesh>.import { AbsoluteFill, useCurrentFrame } from "../../../src";-import { AmbientLight, Canvas3D, DirectionalLight, Entities, PerspectiveCamera } from "../../../src/3d";+import { AmbientLight, DirectionalLight, Entities, PerspectiveCamera } from "../../../src/3d";import { createWorld } from "raea/ecs";const game = createWorld();@@ -14,12 +14,12 @@ export default function Ships() {const frame = useCurrentFrame();return (<AbsoluteFill style={{ background: "#0b1020" }}>- <Canvas3D>+ <><PerspectiveCamera position={[0, 1.5, 6]} fov={50} /><AmbientLight intensity={1} /><DirectionalLight position={[2, 3, 4]} intensity={1} /><Entities world={game.at(frame)} />- </Canvas3D>+ </></AbsoluteFill>);}diff --git a/sdk/raea/conformance/golden/06-world-entities/reference.tsx b/sdk/raea/conformance/golden/06-world-entities/reference.tsxindex b2b24c6e..4dfc1026 100644--- a/sdk/raea/conformance/golden/06-world-entities/reference.tsx+++ b/sdk/raea/conformance/golden/06-world-entities/reference.tsx@@ -1,13 +1,13 @@// the same picture as edit.tsx, placed by hand: the ship turned by 0.05 rad a frame, the gun 0.6 above its centre (a// point on the turning axis, so it stays put while it turns with the ship)import { AbsoluteFill, useCurrentFrame } from "../../../src";-import { AmbientLight, Canvas3D, DirectionalLight, Mesh, MeshStandardMaterial, PerspectiveCamera } from "../../../src/3d";+import { AmbientLight, DirectionalLight, Mesh, MeshStandardMaterial, PerspectiveCamera } from "../../../src/3d";export default function Ships() {const f = useCurrentFrame();return (<AbsoluteFill style={{ background: "#0b1020" }}>- <Canvas3D>+ <><PerspectiveCamera position={[0, 1.5, 6]} fov={50} /><AmbientLight intensity={1} /><DirectionalLight position={[2, 3, 4]} intensity={1} />@@ -17,7 +17,7 @@ export default function Ships() {<Mesh shape="cylinder(0.15, 1.2)" position={[0, 0.6, 0]} rotation={[0, f * 0.05, 0]}><MeshStandardMaterial color="#f59e0b" roughness={0.4} metalness={0} /></Mesh>- </Canvas3D>+ </></AbsoluteFill>);}diff --git a/sdk/raea/conformance/ragdoll.test.ts b/sdk/raea/conformance/ragdoll.test.tsindex f11a07c0..8c4627d1 100644--- a/sdk/raea/conformance/ragdoll.test.ts+++ b/sdk/raea/conformance/ragdoll.test.ts@@ -1,32 +1,12 @@// raea/ragdoll under plain bun: a body going limp mid-run falls onto the ground or a box, keeps its joints in// their limits, never sinks through, comes to rest and stays there, and is the same whichever frame is asked first.-// The skeleton is a stand-in with CMU's joints' names and no skin samples (the ragdoll rings its bones instead).+// The skeleton is the stick stand-in (stick.ts, game_engine joints) with no skin samples (the ragdoll rings its bones instead).import { describe, expect, test } from "bun:test";-import { rest, type Pose, type Skeleton } from "raea/character";+import { rest, type Pose } from "raea/character";import { ragdoll } from "raea/ragdoll";import type { Vec3 } from "../src/3d";+import { skel } from "./stick";-const J: [string, string | null, Vec3][] = [- ["Hips", null, [0, 0.65, 0]], ["LHipJoint", "Hips", [0, 0.65, 0]], ["LeftUpLeg", "LHipJoint", [0.08, 0.64, 0]], ["LeftLeg", "LeftUpLeg", [0.09, 0.35, 0.01]],- ["LeftFoot", "LeftLeg", [0.1, 0.06, 0]], ["LeftToeBase", "LeftFoot", [0.1, 0.02, 0.1]], ["LowerBack", "Hips", [0, 0.7, 0]], ["Spine", "LowerBack", [0, 0.8, 0]],- ["Spine1", "Spine", [0, 0.92, 0]], ["LeftShoulder", "Spine1", [0.02, 0.99, 0]], ["LeftArm", "LeftShoulder", [0.12, 0.98, 0]], ["LeftForeArm", "LeftArm", [0.34, 0.98, 0]],- ["LeftHand", "LeftForeArm", [0.54, 0.98, 0]], ["LThumb", "LeftHand", [0.55, 0.98, 0.03]], ["LeftFingerBase", "LeftHand", [0.56, 0.98, 0]], ["LeftHandFinger1", "LeftFingerBase", [0.62, 0.98, 0]],- ["Neck", "Spine1", [0, 1.04, 0]], ["Neck1", "Neck", [0, 1.08, 0]], ["Head", "Neck1", [0, 1.1, 0]],-];-const named = [...J];-for (const [n, p, h] of J) {- const m = n.replace(/^Left/, "Right").replace(/^LHip/, "RHip").replace(/^LThumb/, "RThumb");- if (m !== n) named.push([m, p && p.replace(/^Left/, "Right").replace(/^LHip/, "RHip"), [-h[0], h[1], h[2]]]);-}-const names = named.map((j) => j[0]);-const tails: Record<string, Vec3> = { LeftToeBase: [0.1, 0.02, 0.14], RightToeBase: [-0.1, 0.02, 0.14], Head: [0, 1.2, 0], LeftHandFinger1: [0.66, 0.98, 0], RightHandFinger1: [-0.66, 0.98, 0], LThumb: [0.57, 0.98, 0.06], RThumb: [-0.57, 0.98, 0.06] };-const skel: Skeleton = {- name: "stick", height: 1.2, landmarks: { eyes: [0, 1.14, 0.08] },- joints: named.map(([n, p, h]) => {- const kids = named.filter((x) => x[1] === n);- return { name: n, parent: p ? names.indexOf(p) : -1, head: h, tail: tails[n] ?? (kids.length ? kids[0][2] : [h[0], h[1] + 0.05, h[2]]) };- }),-};// running along +x at 2.5 m/s, stood straight (the stand-in's feet just off the floor)const still = rest(skel);const run = (f: number): Pose => ({ ...still, root: [2.5 * (f / 30), 0.72, 0] });diff --git a/sdk/raea/conformance/stick.ts b/sdk/raea/conformance/stick.tsindex 288d9bcd..b93d8aff 100644--- a/sdk/raea/conformance/stick.ts+++ b/sdk/raea/conformance/stick.ts@@ -1,29 +1,44 @@-// The conformance tests' stick body, and a BVH of it walking: a small stand-in with CMU's joints' names (no Anny-// export needed), shared by character.test.ts and the CharacterPlugin program (bench/bevy-ts/programs/character.ts).-import { sub, type Skeleton } from "raea/character";+// The conformance tests' stick body, and a BVH of it walking: a small stand-in on raea's game_engine joints+// (docs/skeleton.feature SK0a) in a T-pose, shared by character.test.ts, ragdoll.test.ts and the CharacterPlugin+// program (bench/bevy-ts/programs/character.ts).+import { BODY_JOINTS, FINGER_JOINTS, FINGERS, sub, type Skeleton } from "raea/character";import type { Vec3 } from "../src/3d";-// a T-posed stick body: 1.2 m, facing +z, x its left-const J: [string, string | null, Vec3][] = [- ["Hips", null, [0, 0.65, 0]], ["LHipJoint", "Hips", [0, 0.65, 0]], ["LeftUpLeg", "LHipJoint", [0.08, 0.64, 0]], ["LeftLeg", "LeftUpLeg", [0.09, 0.35, 0.01]],- ["LeftFoot", "LeftLeg", [0.1, 0.06, 0]], ["LeftToeBase", "LeftFoot", [0.1, 0.02, 0.1]], ["LowerBack", "Hips", [0, 0.7, 0]], ["Spine", "LowerBack", [0, 0.8, 0]],- ["Spine1", "Spine", [0, 0.92, 0]], ["LeftShoulder", "Spine1", [0.02, 0.99, 0]], ["LeftArm", "LeftShoulder", [0.12, 0.98, 0]], ["LeftForeArm", "LeftArm", [0.34, 0.98, 0]],- ["LeftHand", "LeftForeArm", [0.54, 0.98, 0]], ["LThumb", "LeftHand", [0.55, 0.98, 0.03]], ["LeftFingerBase", "LeftHand", [0.56, 0.98, 0]], ["LeftHandFinger1", "LeftFingerBase", [0.62, 0.98, 0]],- ["Neck", "Spine1", [0, 1.04, 0]], ["Neck1", "Neck", [0, 1.08, 0]], ["Head", "Neck1", [0, 1.1, 0]],-];export const mirrorX = (v: Vec3): Vec3 => [-v[0], v[1], v[2]];-const named = [...J];-for (const [n, p, h] of J) {- const m = n.replace(/^Left/, "Right").replace(/^LHip/, "RHip").replace(/^LThumb/, "RThumb");- if (m !== n) named.push([m, p && p.replace(/^Left/, "Right").replace(/^LHip/, "RHip"), mirrorX(h)]);++// the left side and the midline: [name, parent, head, tail?]; the right side is the left's mirror image+const LEFT: [string, string | null, Vec3, Vec3?][] = [+ ["pelvis", null, [0, 0.65, 0]], ["spine_01", "pelvis", [0, 0.7, 0]], ["spine_02", "spine_01", [0, 0.8, 0]],+ ["spine_03", "spine_02", [0, 0.92, 0]], ["neck_01", "spine_03", [0, 1.04, 0]], ["head", "neck_01", [0, 1.1, 0], [0, 1.2, 0]],+ ["clavicle_l", "spine_03", [0.02, 0.99, 0]], ["upperarm_l", "clavicle_l", [0.12, 0.98, 0]], ["lowerarm_l", "upperarm_l", [0.34, 0.98, 0]],+ ["hand_l", "lowerarm_l", [0.54, 0.98, 0], [0.6, 0.98, 0]],+ ["thigh_l", "pelvis", [0.08, 0.64, 0]], ["calf_l", "thigh_l", [0.09, 0.35, 0.01]], ["foot_l", "calf_l", [0.1, 0.06, 0]],+ ["ball_l", "foot_l", [0.1, 0.02, 0.1], [0.1, 0.02, 0.14]],+];+// each finger's knuckle (z across the hand: the thumb ahead, the pinky behind) and its phalanges' length+const KNUCKLE: Record<string, [Vec3, number]> = {+ thumb: [[0.55, 0.98, 0.03], 0.022], index: [[0.62, 0.98, 0.02], 0.03], middle: [[0.62, 0.98, 0], 0.032],+ ring: [[0.615, 0.98, -0.018], 0.03], pinky: [[0.605, 0.98, -0.034], 0.024],+};+for (const f of FINGERS) {+ const [k, l] = KNUCKLE[f], dir: Vec3 = f === "thumb" ? [0.6, 0, 0.8] : [1, 0, 0];+ for (const ph of [1, 2, 3]) {+ const at = (m: number): Vec3 => [k[0] + dir[0] * l * m, k[1], k[2] + dir[2] * l * m];+ LEFT.push([`${f}_0${ph}_l`, ph === 1 ? "hand_l" : `${f}_0${ph - 1}_l`, at(ph - 1), at(ph)]);+ }+}+const all = new Map<string, [string | null, Vec3, Vec3?]>();+for (const [n, p, h, t] of LEFT) {+ all.set(n, [p, h, t]);+ if (n.endsWith("_l")) all.set(n.slice(0, -1) + "r", [p && (p.endsWith("_l") ? p.slice(0, -1) + "r" : p), mirrorX(h), t && mirrorX(t)]);}-export const names = named.map((j) => j[0]);-const tails: Record<string, Vec3> = { LeftToeBase: [0.1, 0.02, 0.14], RightToeBase: [-0.1, 0.02, 0.14], Head: [0, 1.2, 0], LeftHandFinger1: [0.66, 0.98, 0], RightHandFinger1: [-0.66, 0.98, 0], LThumb: [0.57, 0.98, 0.06], RThumb: [-0.57, 0.98, 0.06] };+export const names = [...BODY_JOINTS, ...FINGER_JOINTS];export const skel: Skeleton = {name: "stick", height: 1.2, landmarks: { eyes: [0, 1.14, 0.08], sitDrop: 0.07 },- joints: named.map(([n, p, h]) => {- const kids = named.filter((x) => x[1] === n);- return { name: n, parent: p ? names.indexOf(p) : -1, head: h, tail: tails[n] ?? (kids.length ? kids[0][2] : [h[0], h[1] + 0.05, h[2]]) };+ joints: names.map((n) => {+ const [p, h, t] = all.get(n)!;+ const kid = names.find((c) => all.get(c)![0] === n && !/^(thumb|index|ring|pinky)_01|^thigh|^clavicle/.test(c));+ return { name: n, parent: p ? names.indexOf(p) : -1, head: h, tail: t ?? (kid ? all.get(kid)![1] : [h[0], h[1] + 0.05, h[2]]) };}),};@@ -33,7 +48,7 @@ export function stickBvh(frames: number, fps = 120, still = false): string {const write = (i: number, depth: number) => {const j = skel.joints[i], pad = " ".repeat(depth);const off = j.parent < 0 ? [0, 0, 0] : sub(j.head, skel.joints[j.parent].head);- lines.push(`${pad}${j.parent < 0 ? "ROOT" : "JOINT"} ${j.name.replace("HandFinger1", "HandIndex1")}`, `${pad}{`, `${pad} OFFSET ${off.join(" ")}`);+ lines.push(`${pad}${j.parent < 0 ? "ROOT" : "JOINT"} ${j.name}`, `${pad}{`, `${pad} OFFSET ${off.join(" ")}`);lines.push(`${pad} CHANNELS ${j.parent < 0 ? "6 Xposition Yposition Zposition " : "3 "}Zrotation Yrotation Xrotation`);const kids = skel.joints.map((k, ki) => [k, ki] as const).filter(([k]) => k.parent === i);if (!kids.length) lines.push(`${pad} End Site`, `${pad} {`, `${pad} OFFSET ${sub(j.tail, j.head).join(" ")}`, `${pad} }`);@@ -41,15 +56,20 @@ export function stickBvh(frames: number, fps = 120, still = false): string {lines.push(`${pad}}`);};write(0, 0);+ // (the joints in the BVH's own order, as it was written: depth first)+ const order: number[] = [];+ const walk = (i: number) => { order.push(i); skel.joints.forEach((k, ki) => k.parent === i && walk(ki)); };+ walk(0);lines.push("MOTION", `Frames: ${frames}`, `Frame Time: ${1 / fps}`);for (let f = 0; f < frames; f++) {const t = still ? 0 : f / fps, swing = 25 * Math.sin(t * 2 * Math.PI);const row: number[] = [];- skel.joints.forEach((j) => {+ for (const i of order) {+ const j = skel.joints[i];if (j.parent < 0) row.push(0, 0.65, t * 1.1);- const x = j.name === "LeftUpLeg" ? swing : j.name === "RightUpLeg" ? -swing : 0;+ const x = j.name === "thigh_l" ? swing : j.name === "thigh_r" ? -swing : 0;row.push(0, 0, x);- });+ }lines.push(row.join(" "));}return lines.join("\n");diff --git a/sdk/raea/docs/bevy-plugins.md b/sdk/raea/docs/bevy-plugins.mdindex 10a8ef4e..9923b54a 100644--- a/sdk/raea/docs/bevy-plugins.md+++ b/sdk/raea/docs/bevy-plugins.md@@ -288,6 +288,9 @@ Most are a plain `plugin` expression. Rust was written only where the API isn't- **navigator** (`src/navigator.rs`): `navigator/mesh {edges, obstacles?, mesh?}` builds (or, given `mesh`, rebuilds)a NavMesh in the plugin's assets from its outline and obstacles; `navigator/path {mesh, from, to}` gives `{length,points}` or null.+- **save** (`src/save.rs`, PL16): `save/mark {entities, unload?}` marks entities Save (or Unload); `save/save {path}`+ writes every Save entity's reflected components as RON and gives `{saved}`; `save/load {path}` despawns the Save+ and Unload entities, spawns the file's, marks them Save again and gives `{loaded}`.- **northstar** (`src/northstar.rs`): `northstar/grid {size, walls?, chunk?, grid?}` spawns (or rebuilds) an entitywith an OrdinalGrid3d; `northstar/path {grid, from, to, mode?}` gives `{cost, points}` or null.diff --git a/sdk/raea/spec/motion.feature b/sdk/raea/spec/motion.featureindex 18d922f9..aa7f65b0 100644--- a/sdk/raea/spec/motion.feature+++ b/sdk/raea/spec/motion.feature@@ -207,15 +207,16 @@ Feature: raea, the behaviour of its API("<name> covers <p>% of the face at x .. y .. w .. h"); the renderer measures each part after layout andrefuses a frame with faultsScenario: Generated assets as values- Then `sao(prompt, {seconds = 2})`, `fish(text, {seconds = 4, voice?})` and `lyria(prompt, {seconds = 30})` return+ Then `sao(prompt, {seconds = 2})` and `lyria(prompt, {seconds = 30})` returnan asset {kind, prompt, seconds, id, src}: id is a stable hash of kind, prompt and seconds (the same call alwaysgives the same id) and src is "asset:<kind>/<id>"; `Tone.tokensynth(timbre, notes = ["C2", "C3", "C4"],{seconds = 2, velocity = 100, seed = 1234, precision = "fp16"})` returns one such asset per note, a Sampler's urlsAnd an Audio given an asset as src carries data-generate="<kind>", data-prompt and data-seconds, so the renderermakes it once and caches it in the edit's assets/ by everything that decides its bytes: sao and tokensynth on- this computer (installed on first use), fish through raea's API under the run's paid-generation cap+ this computer (installed on first use)And music is written as Tone.js instruments (TokenSynth notes or an open sample library's in a Sampler); sao is- foley; fish is narration; lyria is retired: a take an older edit made still plays, a new one is refused+ foley; narration is <Speech> (raea/speech, Pocket TTS on this computer); lyria is retired: a take an older edit+ made still plays, a new one is refused; fish left raea on 11-05 (Fish Audio is a `raea gen` backend, fish:<model>)Scenario: 3D in the same treeThen `raea/3d` (src/3d.tsx) has Canvas3D, Mesh {position = [0,0,0], rotation = [0,0,0] (radians),scale = 1 (or [x,y,z]), shape?}, the geometries Box {args: [w, h, d]}, Sphere {args: [r]}, Plane {args: [w,diff --git a/core/brief/brief.d.ts b/sdk/raea/src/brief.gen.tssimilarity index 75%rename from core/brief/brief.d.tsrename to sdk/raea/src/brief.gen.tsindex dc35ae62..c54db366 100644--- a/core/brief/brief.d.ts+++ b/sdk/raea/src/brief.gen.ts@@ -189,3 +189,13 @@ material?: string, style?: string,* what a near crop of it must show*/near?: string, };++export type Controller = { id: string, title: string, help?: string, groups: Array<Group>, };++export type Group = { id: string, title: string, help?: string, fields: Array<Field>, };++export type Field = { id: string, label: string, help?: string, } & ({ "type": "toggle", value: boolean, } | { "type": "choice", options: Array<string>, value: string, } | { "type": "number", value: number, unit?: string, min?: number, max?: number, step?: number, } | { "type": "text", value: string, placeholder?: string, multiline?: boolean, } | { "type": "list", value: Array<string>, placeholder?: string, } | { "type": "agents", value: Array<string>, } | { "type": "channels", value: Array<string>, } | { "type": "workflow", value: Array<Step>, channels?: Array<string>, } | { "type": "servers", value: Array<string>, } | { "type": "skills", value: Array<string>, });++export type Kind = { "type": "toggle", value: boolean, } | { "type": "choice", options: Array<string>, value: string, } | { "type": "number", value: number, unit?: string, min?: number, max?: number, step?: number, } | { "type": "text", value: string, placeholder?: string, multiline?: boolean, } | { "type": "list", value: Array<string>, placeholder?: string, } | { "type": "agents", value: Array<string>, } | { "type": "channels", value: Array<string>, } | { "type": "workflow", value: Array<Step>, channels?: Array<string>, } | { "type": "servers", value: Array<string>, } | { "type": "skills", value: Array<string>, };++export type Step = { name: string, by?: string, back?: string, };diff --git a/sdk/raea/src/brief.ts b/sdk/raea/src/brief.tsnew file mode 100644index 00000000..2175ef61--- /dev/null+++ b/sdk/raea/src/brief.ts@@ -0,0 +1,31 @@+// raea/brief: what an agent writes for raea as data (docs/handoff/authoring.md, docs/projects.feature PJ0). A spec is a+// module whose default export is one of these values; it renders nothing and imports nothing that renders.+//+// // brief.ts+// import { brief } from "raea/brief";+// export default brief({ title: "Spring drop", believe: "...", mode: ["pitch"] });+//+// The types are generated from the Rust schemas (core/brief, raea-core-brief) into brief.gen.ts, so what tsc checks is+// what raea reads: `raea context` evaluates the module and Rust validates its default export again.+import type { Brief, Controller, Field, Group, Plan, Script, Taste } from "./brief.gen";++export type * from "./brief.gen";++/** A field as written: its id is filled in from its label when left out. */+export type FieldInput = Field extends infer F ? (F extends Field ? Omit<F, "id"> & { id?: string } : never) : never;+/** A controller as written: ids are filled in from titles and labels when left out. */+export type ControllerInput = Omit<Controller, "id" | "groups"> & {+ id?: string;+ groups: (Omit<Group, "id" | "fields"> & { id?: string; fields: FieldInput[] })[];+};++/** A project's brief (brief.ts): what to make, for whom, the one thing to believe, its deliverables and staged tasks. */+export const brief = (b: Brief): Brief => b;+/** A storyboard or a screenplay (script.ts): scenes, beats, lines, camera and cut. */+export const script = (s: Script): Script => s;+/** Taste (taste.ts): standing rules, some with a check `raea check --taste` holds every export to. */+export const taste = (t: Taste): Taste => t;+/** An object's plan (plan.ts): its parts by name, levels, counts, materials. */+export const plan = (p: Plan): Plan => p;+/** A workspace's controller (controllers/<id>.ts): settings in groups of typed fields that every agent works to. */+export const controller = (c: ControllerInput): ControllerInput => c;diff --git a/sdk/raea/src/light.ts b/sdk/raea/src/light.tsindex 72c16551..18b7b22e 100644--- a/sdk/raea/src/light.ts+++ b/sdk/raea/src/light.ts@@ -5,3 +5,5 @@export { AmbientLight, GlobalAmbientLight, DirectionalLight, PointLight, SpotLight, RectLight, type AmbientLightProps, type DirectionalLightProps, type PointLightProps, type SpotLightProps, type RectLightProps } from "@raea/render/bevy3d";export { Atmosphere, Environment, Shadows, type AtmosphereProps, type EnvironmentProps, type ShadowsProps } from "./3d";export * from "@raea/render/daylight";+// ray-traced lighting (Bevy's Solari, docs/raytracing.feature RT3)+export { SolariLighting, Pathtracer, type SolariLightingProps, type PathtracerProps } from "@raea/render/bevy3d";diff --git a/sdk/raea/tools/library.ts b/sdk/raea/tools/library.tsindex 40868510..2c5efc3c 100644--- a/sdk/raea/tools/library.ts+++ b/sdk/raea/tools/library.ts@@ -3,8 +3,9 @@// ranges into 100STYLE's 1.5 GB zip, CMU's per-clip zips), so nothing but the retargeted clips lands on disk. Clips// already written are skipped, so a run picks up where the last one stopped.//-// bun sdk/raea/tools/library.ts 100style SKELETON.json OUT [--moves FW,ID] [--styles Neutral,Old,...]+// bun sdk/raea/tools/library.ts 100style SKELETON.json OUT [--moves FW,ID,...] [--styles Neutral,Old,...]// bun sdk/raea/tools/library.ts cmu SKELETON.json OUT [--match REGEX] [--not REGEX] [--ids 127_03,64_27,...] [--max N]+// bun sdk/raea/tools/library.ts accad SKELETON.json OUT [--match REGEX] ACCAD's BVHs (unzipped in ACCAD_DIR)// bun sdk/raea/tools/library.ts index OUT// bun sdk/raea/tools/library.ts tables SKELETON.json OUT each clip file's per-frame table (FILE.table.json)// bun sdk/raea/tools/library.ts effects SKELETON.json OUT each 100STYLE style's rig effect against Neutral, from@@ -18,10 +19,13 @@//// 100STYLE (CC BY 4.0): 100 styles of one actor, each walked forward (FW), back (BW), sideways (SW), run (FR, BR,// SR), stood (ID) and turned (TR1-3), cut by its Frame_Cuts.csv. CMU (free for any use; cgspeed's BVH conversion):-// 2,505 clips, chosen by their descriptions in ~/.cache/raea-mocap/cmu/index/all.tsv.+// 2,505 clips, chosen by their descriptions in ~/.cache/raea-mocap/cmu/index/all.tsv. ACCAD's Open Motion Project+// (CC BY 3.0, the Ohio State University's ACCAD): three actors' takes (Male1, Male2, Female1), among them picking up,+// lifting, carrying and putting down a box from a stand, a walk and a run; each actor's turns measured from its own+// A1_Stand (retarget's `rest`), since its files' zero pose isn't a person standing.import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";import { inflateRawSync } from "node:zlib";-import { readBvh, readClips, retarget, writeClips, type ClipFile } from "raea/clip";+import { readBvh, readClips, retarget, retargetIK, writeClips, type ClipFile } from "raea/clip";import { libraryTable } from "raea/matching";import { buildDb, type BuildClip } from "@raea/character/clips";import { learnEffect, type RigEffect } from "raea/effects";@@ -30,6 +34,11 @@ import type { Skeleton } from "raea/character";const STYLE_ZIP = "https://zenodo.org/api/records/8127870/files/100STYLE.zip/content";const STYLE_MAP = JSON.parse(readFileSync(new URL("./maps/100style.json", import.meta.url), "utf8")) as Record<string, string>;+const CMU_MAP = JSON.parse(readFileSync(new URL("./maps/cmu.json", import.meta.url), "utf8")) as Record<string, string>;+/** 100STYLE unpacked on disk (read from there when it is; from Zenodo's zip by HTTP ranges when not) */+const STYLE_DIR = process.env.STYLE_DIR ?? `${process.env.HOME}/.cache/raea-mocap/100style-full`;+const ACCAD_MAP = JSON.parse(readFileSync(new URL("./maps/accad.json", import.meta.url), "utf8")) as Record<string, string>;+const ACCAD_DIR = process.env.ACCAD_DIR ?? `${process.env.HOME}/.cache/raea-mocap/accad`;const CMU_INDEX = `${process.env.HOME}/.cache/raea-mocap/cmu/index/all.tsv`;const MOVES = ["BR", "BW", "FR", "FW", "ID", "SR", "SW", "TR1", "TR2", "TR3"];@@ -103,10 +112,13 @@ function flag(args: string[], name: string): string | undefined {async function style(skel: Skeleton, out: string, args: string[]) {const dir = `${out}/100style`;mkdirSync(dir, { recursive: true });- const zip = await remoteZip(STYLE_ZIP);+ const zip = existsSync(`${STYLE_DIR}/100STYLE/Frame_Cuts.csv`)+ ? { read: async (name: string) => readFileSync(`${STYLE_DIR}/${name}`, "utf8") }+ : await remoteZip(STYLE_ZIP);const cuts = (await zip.read("100STYLE/Frame_Cuts.csv")).trim().split("\n").map((l) => l.split(","));const head = cuts.shift()!;- const moves = (flag(args, "--moves") ?? "FW,ID").split(",");+ // (every move: 100STYLE is the locomotion, docs/skeleton.feature SK7)+ const moves = (flag(args, "--moves") ?? MOVES.join(",")).split(",");const only = flag(args, "--styles")?.split(",");// the actor's carriage, from their Neutral walk: every style's neck and head move about it, so a style's own// carriage (Old's hanging head) stays@@ -124,7 +136,7 @@ async function style(skel: Skeleton, out: string, args: string[]) {const a = row[head.indexOf(`${mv}_START`)], b = row[head.indexOf(`${mv}_STOP`)];if (!a || a === "N/A" || clips.some((c) => c.name === `${name}_${mv}`)) continue;const bvh = readBvh(await zip.read(`100STYLE/${name}/${name}_${mv}.bvh`));- clips.push(retarget(skel, bvh, { name: `${name}_${mv}`, from: +a / 60, to: +b / 60, map: STYLE_MAP, carriage }));+ clips.push(retargetIK(skel, bvh, { name: `${name}_${mv}`, from: +a / 60, to: +b / 60, map: STYLE_MAP, carriage }));added++;}if (added) {@@ -150,12 +162,38 @@ async function cmu(skel: Skeleton, out: string, args: string[]) {const zip = await wholeZip(id[2].replace("github.com/", "raw.githubusercontent.com/").replace("/raw/", "/"));const bvhName = zip.names.find((x) => x.endsWith(".bvh"));if (!bvhName) { console.log(`${id[1]}: no BVH in its zip`); continue; }- const c = retarget(skel, readBvh(await zip.read(bvhName)), { name: `c${id[1]}` });+ const c = retargetIK(skel, readBvh(await zip.read(bvhName)), { name: `c${id[1]}`, map: CMU_MAP, unit: 0.056444 });writeFileSync(file, JSON.stringify(writeClips(skel, [c])));console.log(`c${id[1]}: ${c.frames} frames, ${f[3].trim()}`);}}+/** ACCAD's takes: OUT/accad/<take>.json, clip `a<take>` (Male1_A5_PickUpBox: aMale1_A5_PickUpBox) */+async function accad(skel: Skeleton, out: string, args: string[]) {+ const dir = `${out}/accad`;+ mkdirSync(dir, { recursive: true });+ const match = new RegExp(flag(args, "--match") ?? ".", "i");+ for (const actor of ["Male1", "Male2", "Female1"]) {+ const src = `${ACCAD_DIR}/${actor}_bvh`;+ if (!existsSync(src)) { console.log(`${src}: not there (unzip ${actor}_bvh.zip from accad.osu.edu)`); continue; }+ const files = readdirSync(src).filter((x) => x.endsWith(".bvh")).sort();+ const stand = files.find((x) => /_A0?1_Stand\.bvh$/.test(x));+ if (!stand) throw new Error(`accad: ${actor} has no A1_Stand to measure from`);+ const standB = readBvh(readFileSync(`${src}/${stand}`, "utf8")), rest = standB.frames[0];+ const shape = (b: { joints: { name: string }[] }) => b.joints.map((j) => j.name).join(" ");+ for (const f of files.filter((x) => match.test(x))) {+ const take = f.replace(/\.bvh$/, ""), file = `${dir}/${take}.json`;+ if (existsSync(file)) continue;+ const b = readBvh(readFileSync(`${src}/${f}`, "utf8"));+ // (three of Male2's takes are another skeleton, with no stand of their own to measure from)+ if (shape(b) !== shape(standB)) { console.log(`a${take}: skipped, not ${stand}'s skeleton`); continue; }+ const c = retargetIK(skel, b, { name: `a${take}`, map: ACCAD_MAP, rest, unit: 0.01 });+ writeFileSync(file, JSON.stringify(writeClips(skel, [c])));+ console.log(`a${take}: ${c.frames} frames`);+ }+ }+}+/** what each clip is: its source, file, move, label and length */function index(out: string) {const desc = new Map<string, string>();@@ -164,12 +202,14 @@ function index(out: string) {if (id) desc.set(`c${id[1]}`, f[3].trim());}const rows: { name: string; source: string; file: string; label: string; move?: string; frames: number; fps: number }[] = [];- for (const src of ["100style", "cmu"]) {+ for (const src of ["100style", "cmu", "accad"]) {if (!existsSync(`${out}/${src}`)) continue;for (const f of readdirSync(`${out}/${src}`).filter((x: string) => x.endsWith(".json") && !x.endsWith(".table.json")).sort()) {const file = JSON.parse(readFileSync(`${out}/${src}/${f}`, "utf8")) as ClipFile;for (const c of file.clips) {- const [label, move] = src === "100style" ? c.name.split("_") : [desc.get(c.name) ?? "", undefined];+ const [label, move] = src === "100style" ? c.name.split("_")+ : src === "accad" ? [c.name.slice(1).split("_").slice(2).join(" ").replace(/([a-z])([A-Z])/g, "$1 $2").toLowerCase(), undefined]+ : [desc.get(c.name) ?? "", undefined];rows.push({ name: c.name, source: src, file: `${src}/${f}`, label, move, frames: c.frames, fps: c.fps });}}@@ -180,7 +220,7 @@ function index(out: string) {}function clipFiles(out: string): string[] {- return ["100style", "cmu"].filter((s) => existsSync(`${out}/${s}`)).flatMap((s) =>+ return ["100style", "cmu", "accad"].filter((s) => existsSync(`${out}/${s}`)).flatMap((s) =>readdirSync(`${out}/${s}`).filter((x) => x.endsWith(".json") && !x.endsWith(".table.json")).sort().map((x) => `${out}/${s}/${x}`));}@@ -259,12 +299,12 @@ else if (cmd === "tables" || cmd === "styles" || cmd === "effects") {const skel = JSON.parse(readFileSync(rest[0], "utf8")) as Skeleton;({ tables, styles, effects })[cmd](skel, rest[1]);}-else if (cmd === "100style" || cmd === "cmu") {+else if (cmd === "100style" || cmd === "cmu" || cmd === "accad") {const [skelPath, out] = rest;const skel = JSON.parse(readFileSync(skelPath, "utf8")) as Skeleton;- await (cmd === "100style" ? style : cmu)(skel, out, rest.slice(2));+ await ({ "100style": style, cmu, accad })[cmd](skel, out, rest.slice(2));index(out);} else {- console.error("usage: library.ts 100style|cmu|tables|styles|effects SKELETON.json OUT [...] | library.ts index OUT");+ console.error("usage: library.ts 100style|cmu|accad|tables|styles|effects SKELETON.json OUT [...] | library.ts index OUT");process.exit(2);}diff --git a/sdk/raea/tools/maps/100style.json b/sdk/raea/tools/maps/100style.jsonindex cabc8376..8b1f3a23 100644--- a/sdk/raea/tools/maps/100style.json+++ b/sdk/raea/tools/maps/100style.json@@ -1,24 +1,24 @@{- "Hips": "Hips",- "LowerBack": "Chest",- "Spine": "Chest2",- "Spine1": "Chest4",- "Neck": "Neck",- "Head": "Head",- "LeftShoulder": "LeftCollar",- "LeftArm": "LeftShoulder",- "LeftForeArm": "LeftElbow",- "LeftHand": "LeftWrist",- "LeftUpLeg": "LeftHip",- "LeftLeg": "LeftKnee",- "LeftFoot": "LeftAnkle",- "LeftToeBase": "LeftToe",- "RightShoulder": "RightCollar",- "RightArm": "RightShoulder",- "RightForeArm": "RightElbow",- "RightHand": "RightWrist",- "RightUpLeg": "RightHip",- "RightLeg": "RightKnee",- "RightFoot": "RightAnkle",- "RightToeBase": "RightToe"+ "pelvis": "Hips",+ "spine_01": "Chest",+ "spine_02": "Chest2",+ "spine_03": "Chest4",+ "neck_01": "Neck",+ "head": "Head",+ "clavicle_l": "LeftCollar",+ "clavicle_r": "RightCollar",+ "upperarm_l": "LeftShoulder",+ "upperarm_r": "RightShoulder",+ "lowerarm_l": "LeftElbow",+ "lowerarm_r": "RightElbow",+ "hand_l": "LeftWrist",+ "hand_r": "RightWrist",+ "thigh_l": "LeftHip",+ "thigh_r": "RightHip",+ "calf_l": "LeftKnee",+ "calf_r": "RightKnee",+ "foot_l": "LeftAnkle",+ "foot_r": "RightAnkle",+ "ball_l": "LeftToe",+ "ball_r": "RightToe"}\ No newline at end of filediff --git a/sdk/raea/tools/maps/accad.json b/sdk/raea/tools/maps/accad.jsonnew file mode 100644index 00000000..f1e18489--- /dev/null+++ b/sdk/raea/tools/maps/accad.json@@ -0,0 +1,24 @@+{+ "pelvis": "Hips",+ "spine_01": "ToSpine",+ "spine_02": "Spine",+ "spine_03": "Spine1",+ "neck_01": "Neck",+ "head": "Head",+ "clavicle_l": "LeftShoulder",+ "clavicle_r": "RightShoulder",+ "upperarm_l": "LeftArm",+ "upperarm_r": "RightArm",+ "lowerarm_l": "LeftForeArm",+ "lowerarm_r": "RightForeArm",+ "hand_l": "LeftHand",+ "hand_r": "RightHand",+ "thigh_l": "LeftUpLeg",+ "thigh_r": "RightUpLeg",+ "calf_l": "LeftLeg",+ "calf_r": "RightLeg",+ "foot_l": "LeftFoot",+ "foot_r": "RightFoot",+ "ball_l": "LeftToeBase",+ "ball_r": "RightToeBase"+}diff --git a/sdk/raea/tools/maps/cmu.json b/sdk/raea/tools/maps/cmu.jsonnew file mode 100644index 00000000..a359cb0a--- /dev/null+++ b/sdk/raea/tools/maps/cmu.json@@ -0,0 +1,26 @@+{+ "pelvis": "Hips",+ "spine_01": "LowerBack",+ "spine_02": "Spine",+ "spine_03": "Spine1",+ "neck_01": "Neck1",+ "head": "Head",+ "clavicle_l": "LeftShoulder",+ "clavicle_r": "RightShoulder",+ "upperarm_l": "LeftArm",+ "upperarm_r": "RightArm",+ "lowerarm_l": "LeftForeArm",+ "lowerarm_r": "RightForeArm",+ "hand_l": "LeftHand",+ "hand_r": "RightHand",+ "thigh_l": "LeftUpLeg",+ "thigh_r": "RightUpLeg",+ "calf_l": "LeftLeg",+ "calf_r": "RightLeg",+ "foot_l": "LeftFoot",+ "foot_r": "RightFoot",+ "ball_l": "LeftToeBase",+ "ball_r": "RightToeBase",+ "thumb_01_l": "LThumb",+ "thumb_01_r": "RThumb"+}\ No newline at end of filediff --git a/sdk/raea/tools/motion-check.ts b/sdk/raea/tools/motion-check.tsnew file mode 100644index 00000000..1d11b64d--- /dev/null+++ b/sdk/raea/tools/motion-check.ts@@ -0,0 +1,204 @@+// Motion check: a body's performances on the fixed suite (tools/motion-suite.ts) measured against the motion goal's bars.+//+// bun sdk/raea/tools/motion-check.ts SKELETON.json [--only NAME,NAME] [--out FILE]+//+// Every measure reads the delivered poses and the library's own clips, never the pipeline's internals, so a new+// pipeline is judged the same way as the old:+// slide a foot's contact point (the sole under the ankle, the heel, and under the ball, each turned with its joint;+// down = within 1.5 cm of the floor) moving over the floor during one contact: the most over any contact, cm (bar < 1)+// pops frames where a down foot moves more than 2 cm in a frame (bar 0)+// switch at each switch (the played clip changes, or skips more than 2 frames) and 3 frames round it, the most any+// joint turns in a frame beyond what the source turns it: the faster of the clip showing (at the rate it+// plays) and the clip before the switch carried on at its rate (bar < 10 degrees)+// inside frames with a hand or forearm more than 1.5 cm into the trunk, % (bar under 1%)+// kinks frames where a joint turns more than 4 degrees further than the mean of the frames either side, % (bar < 2)+// grip a held thing's place in its hand's frame drifting from where it was taken, cm and degrees (bar < 0.5 cm)+import { readFileSync, writeFileSync } from "node:fs";+import { B, SIDES, joint, mirrorName, palmAt, pose, qinv, qmul, qrot, surface, type Pose, type Quat, type Skeleton } from "raea/character";+import { clipFrame } from "raea/clip";+import { perform, type MotionLibrary } from "raea/matching";+import { interact } from "raea/items";+import { locoClips, suiteCases, suiteLibrary } from "./motion-suite";+import { faults, reference } from "./motion-faults";+import { sceneFaults } from "./scene-faults";+import { buildDb, perform as performBody } from "raea/body";++const BARS = { slide: 1, pops: 0, switch: 10, inside: 1, kinks: 2, grip: 0.5 };+const DEG = 180 / Math.PI;+const ang = (q: Quat) => 2 * Math.acos(Math.min(1, Math.abs(q[3]))) * DEG;+const sub = (a: number[], b: number[]) => a.map((x, i) => x - b[i]), dot = (a: number[], b: number[]) => a.reduce((s, x, i) => s + x * b[i], 0);+const TRUNK = /^(hips|waist|torso|chest)$/, ARM = /^(palm|foreArm)$/;++type World = ReturnType<typeof pose>;++/** each joint's turn from the frame before, degrees */+const speeds = (W: World[]) => W.map((w, f) => (f ? w.rot.map((q, i) => ang(qmul(q, qinv(W[f - 1].rot[i])))) : w.rot.map(() => 0)));++function feet(skel: Skeleton, W: World[]) {+ const J = skel.joints, z = (n: string) => J[joint(skel, n)].head[1];+ let slide = 0, pops = 0, where = "";+ for (const s of SIDES) {+ for (const n of [B.foot(s), B.ball(s)]) {+ // (the sole under the joint: the heel under the ankle, the tread under the ball, turned as the joint turns)+ const i = joint(skel, n), drop = [0, -z(n), 0] as any, sole = (w: World) => sub(w.pos[i], [0, 0, 0]).map((x, k) => x + (qrot(w.rot[i], drop) as number[])[k]);+ let start: number[] | null = null, far = 0;+ for (let f = 0; f < W.length; f++) {+ const p = sole(W[f]), down = p[1] < 0.015;+ if (!down) { start = null; continue; }+ if (!start) { start = p; continue; }+ const d = Math.hypot(p[0] - start[0], p[2] - start[2]);+ if (d > far) { far = d; if (far > slide) where = `${n}@${f}`; }+ const q = sole(W[f - 1]);+ if (Math.hypot(p[0] - q[0], p[2] - q[2]) > 0.02) pops++;+ }+ slide = Math.max(slide, far);+ }+ }+ return { slide: slide * 100, pops, slideAt: where };+}++function switches(skel: Skeleton, lib: MotionLibrary, played: { clip: string; f: number }[], W: World[], sp: number[][]) {+ // what the source does through a switch is both clips at the rate they play: the clip played before it, carried on at+ // its rate (what the blend fades out of), and the one after; a joint's turn in a frame beyond the faster of the two+ // is what the switch added (measured against one-frame steps of the new clip alone, a body slowing out of a clip+ // played at 1.5x read as a jump)+ const byName = new Map(lib.clips.map((c) => [c.name + (c.mirrored ? "~" : ""), c]));+ const swap = skel.joints.map((j) => joint(skel, mirrorName(j.name)));+ const worlds = new Map<string, World[]>();+ const worldOf = (name: string) => {+ const c = byName.get(name);+ if (!c) return null;+ let w = worlds.get(name);+ if (!w) {+ const nj = c.clip.turns.length / (c.clip.frames * 4);+ w = Array.from({ length: c.clip.frames }, (_, k) => pose(skel, clipFrame(c.clip, k, nj)));+ worlds.set(name, w);+ }+ return w;+ };+ /** each joint's turn in the named clip from frame a to frame b (clamped), degrees */+ const step = (name: string, a: number, b: number) => {+ const w = worldOf(name), c = byName.get(name);+ if (!w || !c) return null;+ const A = w[Math.max(0, Math.min(w.length - 1, Math.round(a)))], Bf = w[Math.max(0, Math.min(w.length - 1, Math.round(b)))];+ const row = A.rot.map((q, i) => ang(qmul(Bf.rot[i], qinv(q))));+ return c.mirrored ? row.map((_, i) => row[swap[i]]) : row;+ };+ const at: number[] = [];+ for (let f = 1; f < played.length; f++) if (played[f].clip !== played[f - 1].clip || Math.abs(played[f].f - played[f - 1].f) > 2) at.push(f);+ let worst = 0, where = "", detail = "";+ for (const s of at) {+ const o = played[s - 1], r = s >= 2 && played[s - 2].clip === o.clip ? o.f - played[s - 2].f : 1;+ for (let f = Math.max(1, s - 3); f <= Math.min(W.length - 1, s + 3); f++) {+ const p = played[f], q = played[f - 1];+ // the clip showing now, at the rate it plays (one frame at its switch, which has no frame before in it)+ // (a clip played below 1x shows a frame twice: it is between frames, not still, so the step is the frame before's)+ const now = step(p.clip, q.clip === p.clip && f !== s && q.f !== p.f ? q.f : p.f - 1, p.f);+ // the clip before the switch carried on at its rate+ const was = f >= s ? step(o.clip, o.f + r * (f - s), o.f + r * (f - s + 1)) : null;+ if (!now) continue;+ sp[f].forEach((v, i) => { const d = v - Math.max(now[i], was ? was[i] : 0); if (d > worst) { worst = d; where = `${skel.joints[i].name}@${f}`; detail = `${v.toFixed(0)} vs ${now[i].toFixed(0)}/${was ? was[i].toFixed(0) : "-"}`; } });+ }+ }+ return { switch: worst, switchAt: where, switchDetail: detail, switches: at.length };+}++function inside(skel: Skeleton, W: World[]) {+ let bad = 0, n = 0;+ for (let f = 0; f < W.length; f += 2) {+ n++;+ const trunk = surface(skel, W[f], TRUNK), arms = surface(skel, W[f], ARM);+ for (const a of arms) {+ let best = Infinity, depth = 0;+ for (const x of trunk) { const d = sub(a.at, x.at), dd = dot(d, d); if (dd < best) { best = dd; depth = -dot(d, x.normal); } }+ if (depth > 0.015 && best < 0.05 * 0.05) { bad++; break; }+ }+ }+ return (100 * bad) / Math.max(1, n);+}++function kinks(sp: number[][]) {+ let k = 0;+ for (let f = 1; f + 1 < sp.length; f++) if (sp[f].some((v, i) => v - (sp[f - 1][i] + sp[f + 1][i]) / 2 > 4)) k++;+ return (100 * k) / Math.max(1, sp.length);+}++/** each held stretch: the thing's place and turn in the nearer palm's frame (the hand joint's turn), its most drift+ * from six frames after it is taken (the hand settled) to its release */+function grips(skel: Skeleton, W: World[], live: ReturnType<typeof interact>, ids: string[]) {+ let cm = 0, deg = 0;+ for (const id of ids) {+ let ref: { s: (typeof SIDES)[number]; p: number[]; q: Quat } | null = null, since = 0;+ for (let f = 0; f < W.length; f++) {+ if (!live.held(id, f)) { ref = null; since = 0; continue; }+ if (++since < 6) continue;+ const it = live.item(id, f);+ const local = (s: (typeof SIDES)[number]) => {+ const h = W[f].rot[joint(skel, B.hand(s))], inv = qinv(h);+ return { p: qrot(inv, sub(it.at, palmAt(skel, W[f], s)) as any) as number[], q: qmul(inv, it.rot) };+ };+ if (!ref) {+ const s = SIDES.reduce((a, b) => (Math.hypot(...sub(it.at, palmAt(skel, W[f], a))) <= Math.hypot(...sub(it.at, palmAt(skel, W[f], b))) ? a : b));+ ref = { s, ...local(s) };+ continue;+ }+ const now = local(ref.s);+ cm = Math.max(cm, Math.hypot(...sub(now.p, ref.p)) * 100);+ deg = Math.max(deg, ang(qmul(now.q, qinv(ref.q))));+ }+ }+ return { grip: cm, gripDeg: deg };+}++const args = process.argv.slice(2), flag = (k: string) => { const i = args.indexOf(k); return i >= 0 ? args[i + 1] : undefined; };+const skel = JSON.parse(readFileSync(args[0], "utf8")) as Skeleton;+const only = flag("--only")?.split(",");+const lib = suiteLibrary(skel);+const rows: Record<string, any>[] = [];+console.log("case frames slide cm pops switch° (where) inside% kinks% grip cm/° pass");+// --body: the new layer (sdk/body's locomotion, docs/character.md C3) on the body library; errands wait for C5/C6+const body = args.includes("--body") ? buildDb(skel as any, process.env.RAEA_MOTION_LIB ?? `${process.env.HOME}/.cache/raea-mocap/lib/turbo`) : null;+const performNew = (spec: any) => {+ const p = performBody(body!, spec, JSON.parse(process.env.RAEA_BODY_OPTS ?? "{}"));+ return { ...p, guide: p.guide.map((g) => ({ ...g, moving: g.want > 0.05 || g.speed > 0.05 })) } as any;+};+for (const c of suiteCases(lib, skel)) {+ if (only && !only.includes(c.name)) continue;+ if (body && c.plan) continue;+ const perf = body ? performNew(c.spec) : c.plan ? perform(lib, c.plan.spec) : perform(lib, c.spec);+ const live = c.plan ? interact(skel, perf, c.plan) : null;+ const poses: Pose[] = Array.from({ length: perf.frames }, (_, f) => (live ? live.pose(f) : perf.pose(f)));+ const W = poses.map((p) => pose(skel, p)), sp = speeds(W);+ const r: Record<string, any> = { name: c.name, frames: perf.frames, ...feet(skel, W), ...switches(skel, lib, perf.played, W, sp), inside: inside(skel, W), kinks: kinks(sp) };+ if (live && c.plan) Object.assign(r, grips(skel, W, live, Object.keys((c.plan as any).items ?? { ball: 0, cup: 0 })));+ if (live && c.plan) { const P = c.plan as any; r.scene = sceneFaults(skel, perf, live, P.things ?? {}, P.items ?? {}, c.seat); }+ const fails = Object.entries(BARS).filter(([k, bar]) => r[k] !== undefined && (k === "pops" ? r[k] > bar : r[k] >= bar)).map(([k]) => k);+ r.pass = fails.length === 0; r.fails = fails;+ r.faults = faults(skel, lib, perf, W);+ rows.push(r);+ const g = r.grip !== undefined ? `${r.grip.toFixed(1)}/${r.gripDeg.toFixed(0)}` : "-";+ console.log(`${c.name.padEnd(16)} [slide ${r.slideAt}] ${String(r.frames).padStart(6)} ${r.slide.toFixed(1).padStart(9)} ${String(r.pops).padStart(5)} ${r.switch.toFixed(0).padStart(8)} ${r.switchAt.padEnd(16)} ${r.inside.toFixed(1).padStart(7)} ${r.kinks.toFixed(1).padStart(7)} ${g.padStart(10)} ${r.pass ? "yes" : "no: " + fails.join(", ")}`);+}+// --stages: the same measures at each of the pipeline's stages (perform's trace), to find which stage brings a fault in+if (args.includes("--stages")) for (const c of suiteCases(lib, skel)) {+ if (c.plan || (only && !only.includes(c.name))) continue;+ const perf = perform(lib, c.spec, { trace: true });+ for (const [stage, poses] of Object.entries(perf.trace!.stages)) {+ const W = poses.map((p) => pose(skel, p)), sp = speeds(W), ft = feet(skel, W), sw = switches(skel, lib, perf.played, W, sp);+ console.log(` ${c.name.padEnd(16)} ${stage.padEnd(7)} slide ${ft.slide.toFixed(1).padStart(5)} [${ft.slideAt}] pops ${String(ft.pops).padStart(3)} switch ${sw.switch.toFixed(0).padStart(3)} [${sw.switchAt}] kinks ${kinks(sp).toFixed(1)}`);+ }+}+// the taxonomy's faults (tools/motion-faults.ts, docs/locomotion.md), the library's own clips first as the reference+{+ const ref = reference(skel, lib, [...locoClips().keys()]);+ const cols = ["skate", "float", "sink", "reach", "drift", "driftMax", "crab", "spin", "overrun", "switchesPerS", "returns", "flips", "stall", "armPhase", "armBack", "headPitch", "headRoll", "trunk", "jitter", "froude", "cadence"];+ console.log("\nfaults " + cols.map((c) => c.slice(0, 7).padStart(8)).join(""));+ console.log("library " + cols.map((c) => (c in ref ? (ref as any)[c].toFixed(2) : "").padStart(8)).join(""));+ for (const r of rows) console.log(r.name.padEnd(17) + cols.map((c) => (r.faults[c] ?? 0).toFixed(c === "returns" || c === "flips" ? 0 : 2).padStart(8)).join(""));+ // the scene's faults (plan cases): tools/scene-faults.ts+ for (const r of rows) if (r.scene) { const x = r.scene; console.log(`scene ${r.name}: clip ${x.clip.toFixed(1)}% (deepest ${x.clipDeep.toFixed(1)} cm, ${x.clipAt}) inThing ${x.inThing.toFixed(1)}% (deepest ${x.inDeep.toFixed(1)} cm, ${x.inAt}) gripGap ${x.gripGap.toFixed(1)}% sitLoop ${x.sitLoop.toFixed(2)}/s\n hands in things by item: ${JSON.stringify(x.inBy)} grip gaps: ${JSON.stringify(x.gapBy)} widest ${JSON.stringify(x.gapMax)}\n clip frames by thing/stage: ${JSON.stringify(x.clipBy)}\n deepest by thing: ${JSON.stringify(x.deepBy)}`); }+}+const passed = rows.filter((r) => r.pass).length;+console.log(`${passed}/${rows.length} cases pass`);+const out = flag("--out");+if (out) writeFileSync(out, JSON.stringify({ bars: BARS, rows }, null, 1));diff --git a/sdk/raea/tools/motion-faults.ts b/sdk/raea/tools/motion-faults.tsnew file mode 100644index 00000000..66a46f6a--- /dev/null+++ b/sdk/raea/tools/motion-faults.ts@@ -0,0 +1,189 @@+// Locomotion faults (docs/locomotion.md's taxonomy), measured on delivered poses only, so any pipeline is judged alike.+// Each measure that has no fixed bar is also taken on the library's own locomotion clips (`reference`): a case is+// read against what real capture does, not a guessed number.+//+// skate C3 foot horizontal speed x (2 - 2^(h/H)) under H = 2.5 cm (Holden et al.'s skating), cm a frame, mean+// float C4 frames whose slower foot (the standing one) is over 3 cm up, %+// sink C5 frames with a sole over 1 cm under the floor, %+// reach B1 frames with a hip-to-ankle span over 99.5% of the leg's length (a leg pulled straight), %+// drift R1 the hips from the guide's point, cm: mean and most+// crab R2 frames moving over 1 m/s with the hips facing over 25 degrees off the way they go, %+// spin R3 frames turning the hips over 90 degrees a second on two standing feet, %+// overrun R4 at a stop, how far the hips came back along the way they were going, cm+// thrash T2 switches a second, and returns to a clip left under half a second before+// flip T3 switches where a standing foot of the clip before is a swinging foot of the clip after+// stall T5 frames in runs of 6 or more where the body moves over 0.5 m/s and no limb joint turns 0.2 degrees, %+// armPhase U2 the larger of the two sides' correlation of the upper arm's swing with its own thigh's (natural < 0)+// armBack U3 how far behind the trunk the upper arms swing, degrees (99th percentile, while moving)+// head U4 the head's pitch and roll range over a second, degrees (median over the moving seconds)+// trunk U5 the chest's pitch range over a second, degrees (median)+// jitter K2 the body joints' mean change of turn speed, degrees a frame squared+import { B, SIDES, joint, pose, qrot, type Pose, type Skeleton } from "raea/character";+import { clipFrame } from "raea/clip";+import type { MotionLibrary, Performance } from "raea/matching";++type World = ReturnType<typeof pose>;+type V = number[];+const DEG = 180 / Math.PI;+const sub = (a: V, b: V) => a.map((x, i) => x - b[i]);+const len = (a: V) => Math.hypot(...a);+const dot = (a: V, b: V) => a.reduce((s, x, i) => s + x * b[i], 0);+const pct = (xs: number[], p: number) => { if (!xs.length) return 0; const s = [...xs].sort((a, b) => a - b); return s[Math.min(s.length - 1, Math.floor(p * s.length))]; };+const median = (xs: number[]) => pct(xs, 0.5);+const mean = (xs: number[]) => (xs.length ? xs.reduce((a, b) => a + b, 0) / xs.length : 0);+function corr(a: number[], b: number[]) {+ const ma = mean(a), mb = mean(b);+ let s = 0, sa = 0, sb = 0;+ for (let i = 0; i < a.length; i++) { s += (a[i] - ma) * (b[i] - mb); sa += (a[i] - ma) ** 2; sb += (b[i] - mb) ** 2; }+ return sa > 0 && sb > 0 ? s / Math.sqrt(sa * sb) : 0;+}++/** the bits of a skeleton the measures use */+function rig(skel: Skeleton) {+ const J = skel.joints, j = (n: string) => joint(skel, n), y = (n: string) => J[j(n)].head[1];+ const soles = SIDES.flatMap((s) => [B.foot(s), B.ball(s)].map((n) => ({ s, i: j(n), drop: [0, -y(n), 0] })));+ const legLen = (s: (typeof SIDES)[number]) => len(sub(J[j(B.thigh(s))].head, J[j(B.calf(s))].head)) + len(sub(J[j(B.calf(s))].head, J[j(B.foot(s))].head));+ const limbs = SIDES.flatMap((s) => [B.thigh(s), B.calf(s), B.upperarm(s), B.lowerarm(s)].map(j));+ const body = J.map((x, i) => i).filter((i) => !/_0[123]_/.test(J[i].name));+ return { j, soles, legLen, limbs, body };+}++/** a sole point (the floor under a foot joint, turned as it turns) */+const solePos = (w: World, s: { i: number; drop: number[] }) => sub(w.pos[s.i], [0, 0, 0]).map((x, k) => x + (qrot(w.rot[s.i], s.drop as any) as V)[k]);+/** a joint's axis in the world */+const axis = (w: World, i: number, a: V) => qrot(w.rot[i], a as any) as V;+/** the hips' heading (radians) */+const heading = (w: World, hip: number) => { const f = axis(w, hip, [0, 0, 1]); return Math.atan2(f[0], f[2]); };+const wrap = (a: number) => Math.atan2(Math.sin(a), Math.cos(a));++/** per-frame turn speed of every joint, degrees a frame */+function turnSpeeds(W: World[]): number[][] {+ return W.map((w, f) => w.rot.map((q, i) => {+ if (!f) return 0;+ const p = W[f - 1].rot[i], d = Math.abs(q[0] * p[0] + q[1] * p[1] + q[2] * p[2] + q[3] * p[3]);+ return 2 * Math.acos(Math.min(1, d)) * DEG;+ }));+}++/** the measures any stretch of poses has (also taken on the library's clips) */+export function bodyMeasures(skel: Skeleton, W: World[], fps: number) {+ const R = rig(skel), hip = R.j(B.pelvis), chest = R.j(B.chest), head = R.j(B.head);+ const sp = turnSpeeds(W);+ const hipV = W.map((w, f) => { const a = W[Math.max(0, f - 2)], b = W[Math.min(W.length - 1, f + 2)], n = Math.min(W.length - 1, f + 2) - Math.max(0, f - 2); return n > 0 ? (Math.hypot(b.pos[hip][0] - a.pos[hip][0], b.pos[hip][2] - a.pos[hip][2]) * fps) / n : 0; });+ const moving = hipV.map((v) => v > 0.5);+ // U2, U3: each side's upper arm and thigh swing, as angles fore (+) and aft in the hips' sagittal plane+ const child = (n: string) => skel.joints.findIndex((x) => x.parent === R.j(n));+ const swingOf = (w: World, n: string) => { const i = R.j(n), c = child(n); const d = sub(w.pos[c], w.pos[i]), f = axis(w, hip, [0, 0, 1]); return Math.atan2(dot(d, f), -d[1]) * DEG; };+ let armPhase = -1, armBack: number[] = [];+ for (const s of SIDES) {+ const a: number[] = [], t: number[] = [];+ W.forEach((w, f) => { if (!moving[f]) return; a.push(swingOf(w, B.upperarm(s))); t.push(swingOf(w, B.thigh(s))); });+ if (a.length > 30) { armPhase = Math.max(armPhase, corr(a, t)); armBack.push(...a.map((x) => -x)); }+ }+ // U4, U5: head pitch and roll, chest pitch, as ranges over one-second windows while moving+ const pitch = (w: World, i: number) => Math.asin(Math.max(-1, Math.min(1, axis(w, i, [0, 0, 1])[1]))) * DEG;+ const roll = (w: World, i: number) => Math.asin(Math.max(-1, Math.min(1, axis(w, i, [1, 0, 0])[1]))) * DEG;+ const win = Math.round(fps), hp: number[] = [], hr: number[] = [], cp: number[] = [];+ for (let f = 0; f + win <= W.length; f += Math.max(1, win >> 1)) {+ if (moving.slice(f, f + win).filter(Boolean).length < win * 0.9) continue;+ const range = (g: (w: World) => number) => { const v = W.slice(f, f + win).map(g); return Math.max(...v) - Math.min(...v); };+ hp.push(range((w) => pitch(w, head))); hr.push(range((w) => roll(w, head))); cp.push(range((w) => pitch(w, chest)));+ }+ // B1: the gait's Froude number v^2/(g L) (L the hips' height at rest; people walk near 0.25, change to a run near+ // 0.5) and its cadence (steps a second, from the thighs' swing crossing each other), over the moving frames: a body+ // of another build than the capture's should keep the Froude number at its own speed, its cadence as 1/sqrt(L)+ const L = skel.joints[hip].head[1];+ const fwdOf = (w: World) => axis(w, hip, [0, 0, 1]);+ const gap = W.map((w) => { const f = fwdOf(w), a = w.pos[child(B.thigh("L"))], b = w.pos[child(B.thigh("R"))]; return dot(sub(a, b), f); });+ let steps = 0, movingN = 0, v2 = 0;+ for (let f = 1; f < W.length; f++) if (moving[f]) { movingN++; v2 += hipV[f] ** 2; if (Math.sign(gap[f]) !== Math.sign(gap[f - 1])) steps++; }+ const froude = movingN ? v2 / movingN / (9.81 * L) : 0, cadence = movingN ? (steps * fps) / movingN : 0;+ // K2: change of turn speed over the body's joints+ const jit: number[] = [];+ for (let f = 2; f < sp.length; f++) jit.push(mean(R.body.map((i) => Math.abs(sp[f][i] - sp[f - 1][i]))));+ return {+ armPhase, armBack: pct(armBack, 0.99), headPitch: median(hp), headRoll: median(hr), trunk: median(cp), jitter: mean(jit), froude, cadence,+ _sp: sp, _moving: moving, _hipV: hipV,+ };+}++/** the faults of one delivered performance */+export function faults(skel: Skeleton, lib: MotionLibrary, perf: Performance, W: World[]) {+ const fps = lib.fps, R = rig(skel), hip = R.j(B.pelvis), N = W.length;+ const m = bodyMeasures(skel, W, fps), sp = m._sp;+ // C3 to C5 and R3: the soles+ const H = 0.025;+ let skate = 0, skN = 0, float = 0, sink = 0, spin = 0;+ const down = (w: World, p: World | undefined, s: (typeof R.soles)[number]) => { const a = solePos(w, s), b = p ? solePos(p, s) : a; return { h: a[1], v: Math.hypot(a[0] - b[0], a[2] - b[2]) }; };+ for (let f = 1; f < N; f++) {+ const st = R.soles.map((s) => down(W[f], W[f - 1], s));+ for (const x of st) { if (x.h < H) skate += x.v * (2 - 2 ** (Math.max(0, x.h) / H)); skN++; }+ if (st.some((x) => x.h < -0.01)) sink++;+ // the standing foot: each side's lower sole, and the slower side's+ const side = SIDES.map((_, k) => ({ h: Math.min(st[k * 2].h, st[k * 2 + 1].h), v: Math.min(st[k * 2].v, st[k * 2 + 1].v) }));+ const stand = side[0].v <= side[1].v ? side[0] : side[1];+ if (stand.v < 0.005 && stand.h > 0.03 && !perf.guide[f]?.act) float++;+ if (side.every((x) => x.h < 0.015 && x.v < 0.005) && Math.abs(wrap(heading(W[f], hip) - heading(W[f - 1], hip))) * fps * DEG > 90) spin++;+ }+ // B1: a leg's span against its length+ let reach = 0;+ for (const w of W) if (SIDES.some((s) => len(sub(w.pos[R.j(B.foot(s))], w.pos[R.j(B.thigh(s))])) > 0.995 * R.legLen(s))) reach++;+ // R1, R2: the hips against the guide, and against the way they go+ const G = perf.guide, dr: number[] = [];+ let crab = 0;+ for (let f = 0; f < N; f++) {+ const g = G[Math.min(G.length - 1, f)];+ if (!g.act) dr.push(Math.hypot(W[f].pos[hip][0] - g.x, W[f].pos[hip][2] - g.z));+ if (m._hipV[f] > 1 && f >= 2 && f + 2 < N) {+ const a = W[f - 2].pos[hip], b = W[f + 2].pos[hip], go = Math.atan2(b[0] - a[0], b[2] - a[2]);+ if (Math.abs(wrap(heading(W[f], hip) - go)) * DEG > 25) crab++;+ }+ }+ // R4: at each stop (the guide moving, then not), the hips' most travel back along the way they came, over 1.5 s+ let overrun = 0;+ for (let f = 1; f < Math.min(N, G.length); f++) {+ if (!(G[f - 1].moving && !G[f].moving) || G[f].act) continue;+ const a = W[Math.max(0, f - 6)].pos[hip], b = W[f].pos[hip], d = [b[0] - a[0], b[2] - a[2]], n = Math.hypot(d[0], d[1]) || 1;+ let far = -Infinity, end = 0;+ for (let k = f; k < Math.min(N, f + Math.round(1.5 * fps)); k++) { const p = W[k].pos[hip], s = ((p[0] - b[0]) * d[0] + (p[2] - b[2]) * d[1]) / n; far = Math.max(far, s); end = s; }+ overrun = Math.max(overrun, far - end);+ }+ // T2, T3: switches+ const P = perf.played, at: number[] = [];+ for (let f = 1; f < P.length; f++) if (P[f].clip !== P[f - 1].clip || Math.abs(P[f].f - P[f - 1].f) > 2) at.push(f);+ const left = new Map<string, number>();+ let returns = 0, flips = 0;+ const byName = new Map(lib.clips.map((c) => [c.name + (c.mirrored ? "~" : ""), c]));+ const contactOf = (p: { clip: string; f: number }) => { const c = byName.get(p.clip); if (!c) return null; const k = c.start + p.f; return k < c.end ? [lib.contact[k * 2], lib.contact[k * 2 + 1]] : null; };+ for (const s of at) {+ const was = P[s - 1], now = P[s];+ if (was.clip !== now.clip) { const l = left.get(now.clip); if (l !== undefined && s - l < fps / 2) returns++; left.set(was.clip, s); }+ const a = contactOf(was), b = contactOf(now);+ if (a && b && ((a[0] === 1 && b[0] === 0) || (a[1] === 1 && b[1] === 0))) flips++;+ }+ // T5: limbs frozen while the body moves+ let stall = 0, run = 0;+ for (let f = 1; f < N; f++) {+ const frozen = m._hipV[f] > 0.5 && R.limbs.every((i) => sp[f][i] < 0.2);+ run = frozen ? run + 1 : 0;+ if (run === 6) stall += 6; else if (run > 6) stall++;+ }+ const P100 = (n: number) => (100 * n) / Math.max(1, N);+ return {+ skate: (100 * skate) / Math.max(1, skN), float: P100(float), sink: P100(sink), reach: P100(reach),+ drift: mean(dr) * 100, driftMax: Math.max(0, ...dr) * 100, crab: P100(crab), spin: P100(spin), overrun: overrun * 100,+ switchesPerS: (at.length * fps) / Math.max(1, N), returns, flips, stall: P100(stall),+ armPhase: m.armPhase, armBack: m.armBack, headPitch: m.headPitch, headRoll: m.headRoll, trunk: m.trunk, jitter: m.jitter, froude: m.froude, cadence: m.cadence,+ };+}++/** the same body measures over the library's own locomotion clips (unmirrored): what real capture does */+export function reference(skel: Skeleton, lib: MotionLibrary, names: string[]) {+ const rows = lib.clips.filter((c) => !c.mirrored && names.includes(c.name)).map((c) => {+ const nj = c.clip.turns.length / (c.clip.frames * 4);+ const W = Array.from({ length: c.clip.frames }, (_, k) => pose(skel, clipFrame(c.clip, k, nj) as Pose));+ return bodyMeasures(skel, W, lib.fps);+ });+ const keys = ["armPhase", "armBack", "headPitch", "headRoll", "trunk", "jitter", "froude", "cadence"] as const;+ return Object.fromEntries(keys.map((k) => [k, median(rows.map((r) => r[k]).filter((x) => Number.isFinite(x) && x !== -1))])) as Record<(typeof keys)[number], number>;+}diff --git a/sdk/raea/tools/motion-suite.ts b/sdk/raea/tools/motion-suite.tsnew file mode 100644index 00000000..a51efe3a--- /dev/null+++ b/sdk/raea/tools/motion-suite.ts@@ -0,0 +1,81 @@+// The motion check's fixed suite: turbo's library (ACCAD Male2's locomotion, CMU's pick-up, throw and sit) and the+// performances it is judged on: walk, jog and run on a curve, a 90 and a 180 degree turn, a start and a stop, a run+// turning, and errands (a pick, a throw, a sit, a cup carried and put down).+import { readFileSync, readdirSync } from "node:fs";+import type { Skeleton } from "raea/character";+import { readClips, type Clip, type ClipFile } from "raea/clip";+import { levelClip, motionLibrary, seatApproach, type MotionLibrary, type Seat } from "raea/matching";+import { planItems } from "raea/items";+import type { Vec3 } from "raea/3d";++const LIB = process.env.RAEA_MOTION_LIB ?? `${process.env.HOME}/.cache/raea-mocap/lib/turbo`;+const json = (p: string) => JSON.parse(readFileSync(p, "utf8")) as ClipFile;++/** ACCAD Male2's forward locomotion: walks, turns, starts and stops, runs and a stand */+export function locoClips(): Map<string, Clip> {+ const dir = `${LIB}/accad`;+ const files = readdirSync(dir).filter((f) => /^Male2_([BC]\d+|A1)_/.test(f) && !/back|box|hop|leap|crouch|skip|bow|ready|jump/i.test(f));+ return new Map(files.flatMap((f) => [...readClips(json(`${dir}/${f}`))]));+}++export const PICK = { name: "c64_27", from: 39, to: 105 }, THROW = { name: "c111_33", from: 176, to: 218 };++export function suiteLibrary(skel: Skeleton): MotionLibrary {+ // (each clip on a level floor, as the product's database stands them: clips/library.ts levels every clip it loads)+ const lv = (m: [string, Clip][]) => m.map(([n, c]) => [n, levelClip(skel, c)] as [string, Clip]);+ const loco = new Map(lv([...locoClips()]));+ const acts = lv(["64_27", "111_33", "113_15"].flatMap((id) => [...readClips(json(`${LIB}/cmu/cmu/${id}.json`))]));+ return motionLibrary(skel, new Map([...loco, ...acts]), {+ locomotion: [...loco.keys()], actions: [PICK.name, THROW.name],+ sit: { clip: "c113_15", down: [42, 80], sat: [80, 140], up: [140, 178] },+ });+}++export interface Case { name: string; spec?: any; plan?: ReturnType<typeof planItems>; seat?: Seat }++/** turbo's hip height (its thigh joints over the floor), what the suite's speeds were set for */+const TURBO_HIP = 0.975;++/** The cases. With `skel`, the locomotion cases' speeds are asked at the same Froude number as turbo's, v scaled by+ * sqrt of the body's hip height over turbo's (RAEA_SUITE_ABS=1 for the same metres a second for every body): 3.6 m/s+ * is turbo's run and mai's sprint (Froude 1.07, where capture runs at 0.87). Errands keep their speeds. */+export function suiteCases(lib: MotionLibrary, skel?: Skeleton): Case[] {+ const at: Vec3 = [0, 0, 0], curve: [number, number][] = [[0, 3], [2, 7], [6, 9]];+ const th = skel?.joints.find((j) => j.name === "thigh_l"), fk = th && process.env.RAEA_SUITE_ABS !== "1" ? Math.sqrt(th.head[1] / TURBO_HIP) : 1;+ const walk = (name: string, steps: any[]): Case => ({ name, spec: { at, facing: 0, steps: steps.map((st) => (st.speed ? { ...st, speed: st.speed * fk } : st)) } });+ const cases: Case[] = [+ walk("walk curve", [{ walk: curve, speed: 1.3 }, { wait: 0.5 }]),+ walk("jog curve", [{ walk: curve, speed: 2.6 }, { wait: 0.5 }]),+ walk("run curve", [{ walk: curve, speed: 3.6 }, { wait: 0.5 }]),+ walk("turn 90", [{ walk: [[0, 3], [3, 3]], speed: 1.3 }, { wait: 0.5 }]),+ walk("turn 180", [{ walk: [[0, 3], [0, 0.5]], speed: 1.3 }, { wait: 0.5 }]),+ walk("run turn 90", [{ walk: [[0, 4], [4, 4]], speed: 3.6 }, { wait: 0.5 }]),+ walk("start and stop", [{ wait: 1 }, { walk: [[0, 3]], speed: 1.3 }, { wait: 1.5 }]),+ ];+ // errands, as ~/Studio/internal/projects/psx/raea/errands.tsx runs them+ const things = {+ bin: { at: [8.6, 0, 5.4] as Vec3, size: [0.45, 0.4, 0.45] as Vec3, surfaces: [{ y: 0.03, min: [-0.2, -0.2] as [number, number], max: [0.2, 0.2] as [number, number] }] },+ side: { at: [7.6, 0, 0.6] as Vec3, size: [0.5, 0.74, 0.5] as Vec3 },+ desk: { at: [0.2, 0, -3.4] as Vec3, size: [1.2, 0.74, 0.6] as Vec3 },+ };+ const items = {+ ball: { at: [2.4, 0, 5.2] as Vec3, size: [0.11, 0.11, 0.11] as Vec3, shape: "ball" as const, mass: 0.15 },+ cup: { at: [7.6, 0.74, 0.6] as Vec3, size: [0.08, 0.1, 0.08] as Vec3, mass: 0.3, upright: true },+ };+ const SEAT: Seat = { at: [5.0, 0.46, 2.2], facing: Math.PI }, seat = seatApproach(lib, SEAT);+ const plan = planItems(lib, { at: [0, 0, 0], facing: 0 }, items, [+ { walk: [[0, 2.5], [1.2, 4]], speed: 0.8 },+ { pick: "ball", clip: PICK },+ { walk: [[3.8, 7], [6.2, 7.2]], speed: 2.6 },+ { throw: "ball", to: "bin", clip: THROW },+ { walk: [[6.2, 5.2], [seat.at[0], seat.at[1]]], speed: 1.3 },+ { step: { sit: SEAT, for: 3.5 }, at: seat.at, face: seat.face },+ { pick: "cup" },+ { walk: [[8.2, -1.2], [5.5, -2.8], [2.2, -2.6]], speed: 1.9 },+ { place: "cup", on: "desk", spot: [0.3, 0] },+ { walk: [[-1.6, -1.5], [-1.8, 2.5], [0.5, 4.5]], speed: 3.6 },+ { wait: 1.5 },+ ] as any, { things } as any);+ cases.push({ name: "errands", plan, seat: SEAT });+ return cases;+}diff --git a/sdk/raea/tools/retarget-check.ts b/sdk/raea/tools/retarget-check.tsnew file mode 100644index 00000000..c82cb188--- /dev/null+++ b/sdk/raea/tools/retarget-check.ts@@ -0,0 +1,188 @@+// How well clips retarget onto a body: each source BVH (100STYLE, CMU, ACCAD, on disk) retargeted and measured frame by+// frame against itself and against what a person can do (docs/skeleton.feature; Shane, 11-01: "the whole human rig+// breaks with these ... its all the bad retargeting"). Nothing here depends on a source's rest pose: the source is+// measured by where its joints are and how its bones turn frame to frame.+//+// bun sdk/raea/tools/retarget-check.ts SKELETON.json [--method old|ik] [--sources 100style,cmu,accad] [--max N]+// [--match REGEX] [--every K] [--out FILE.json] [--worst N]+//+// Per clip, the share of frames (every K-th) with each fault:+// twist a bone turned about its own length past a person's range (forearm 100°, wrist 60°, upper arm 100°, thigh+// 60°, shin 30°, foot 40°, neck 60°, head 60°), from the body's rest+// bend a knee or an elbow bent the wrong way, more than 10°+// inside a hand or forearm more than 1.5 cm into the trunk (hips, waist, torso, chest)+// trunk the trunk (pelvis to neck) more than 15° off the source's, or the neck (neck to head) more than 25° off,+// each in its own body's heading+// limbs an upper arm, forearm, thigh or shin more than 15° off the source's bone+// pop a joint turning more than 15° further in one frame than its source joint does+import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";+import { clipFrame, readBvh, retarget, type Bvh, type Clip } from "raea/clip";+import { B, SIDES, joint, pose, qinv, qmul, qrot, surface, type Quat, type Side, type Skeleton } from "raea/character";+import type { Vec3 } from "raea/3d";++const HOME = process.env.HOME!, M = (n: string) => JSON.parse(readFileSync(new URL(`./maps/${n}.json`, import.meta.url), "utf8")) as Record<string, string>;+const flag = (n: string) => { const i = process.argv.indexOf(n); return i > 0 ? process.argv[i + 1] : undefined; };+const skel = JSON.parse(readFileSync(process.argv[2], "utf8")) as Skeleton;+const method = flag("--method") ?? "old", every = +(flag("--every") ?? 3), max = +(flag("--max") ?? Infinity);+const match = new RegExp(flag("--match") ?? ".", "i"), sources = (flag("--sources") ?? "100style,cmu,accad").split(",");+const DEG = 180 / Math.PI;++// ---- the sources on disk: [name, bvh path, map, rest frame]+type Src = { name: string; path: string; map: Record<string, string>; rest?: number[] };+function list(): Src[] {+ const out: Src[] = [];+ if (sources.includes("100style")) {+ const d = `${HOME}/.cache/raea-mocap/100style-full/100STYLE`, map = M("100style");+ for (const st of readdirSync(d).sort()) for (const mv of ["FW", "FR", "ID", "TR1", "SW"]) {+ const p = `${d}/${st}/${st}_${mv}.bvh`;+ if (existsSync(p)) out.push({ name: `${st}_${mv}`, path: p, map });+ }+ }+ if (sources.includes("cmu")) {+ const d = `${HOME}/.cache/raea-mocap/cmu/bvh`, map = M("cmu");+ for (const f of readdirSync(d).filter((x) => x.endsWith(".bvh")).sort()) out.push({ name: `c${f.slice(0, -4)}`, path: `${d}/${f}`, map });+ }+ if (sources.includes("accad")) {+ const map = M("accad");+ for (const actor of ["Male1", "Male2", "Female1"]) {+ const d = `${HOME}/.cache/raea-mocap/accad/${actor}_bvh`, files = readdirSync(d).filter((x) => x.endsWith(".bvh")).sort();+ const stand = readBvh(readFileSync(`${d}/${files.find((x) => /_A0?1_Stand\.bvh$/.test(x))!}`, "utf8"));+ const shape = (b: Bvh) => b.joints.map((j) => j.name).join(" ");+ for (const f of files) {+ const b = readBvh(readFileSync(`${d}/${f}`, "utf8"));+ if (shape(b) === shape(stand)) out.push({ name: `a${f.slice(0, -4)}`, path: `${d}/${f}`, map, rest: stand.frames[0] });+ }+ }+ }+ return out.filter((s) => match.test(s.name)).slice(0, max);+}++// ---- small vector and turn helpers+const sub = (a: Vec3, b: Vec3): Vec3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];+const dot = (a: Vec3, b: Vec3) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];+const nrm = (a: Vec3): Vec3 => { const l = Math.hypot(...a) || 1; return [a[0] / l, a[1] / l, a[2] / l]; };+const ang = (a: Vec3, b: Vec3) => Math.acos(Math.max(-1, Math.min(1, dot(nrm(a), nrm(b))))) * DEG;+const qang = (q: Quat) => 2 * Math.acos(Math.min(1, Math.abs(q[3]))) * DEG;+/** a turn's twist about `axis` (degrees, signed) */+const twist = (q: Quat, axis: Vec3) => { const a = nrm(axis), p = dot([q[0], q[1], q[2]], a); return 2 * Math.atan2(p, q[3]) * DEG; };+const wrap = (d: number) => ((d + 540) % 360) - 180;+/** v turned about up so `across` lies along +x: a vector in its body's own heading */+const unheaded = (v: Vec3, across: Vec3) => { const h = Math.atan2(-across[2], across[0]), c = Math.cos(h), s = Math.sin(h); return [c * v[0] - s * v[2], v[1], s * v[0] + c * v[2]] as Vec3; };++// ---- the source's forward kinematics (its own frames; nothing about its rest is used)+function sourceWorld(b: Bvh, vals: number[]) {+ let c = 0;+ const rot: Quat[] = [], pos: Vec3[] = [];+ b.joints.forEach((j, i) => {+ let q: Quat = [0, 0, 0, 1], t: Vec3 = [...j.offset] as Vec3;+ for (const ch of j.channels) {+ const v = vals[c++];+ if (ch.endsWith("position")) { t = [...t] as Vec3; t["XYZ".indexOf(ch[0])] = v; continue; }+ const h = (v * Math.PI) / 360, ax: Quat = ch[0] === "X" ? [Math.sin(h), 0, 0, Math.cos(h)] : ch[0] === "Y" ? [0, Math.sin(h), 0, Math.cos(h)] : [0, 0, Math.sin(h), Math.cos(h)];+ q = qmul(q, ax);+ }+ if (j.parent < 0) { rot[i] = q; pos[i] = t; return; }+ rot[i] = qmul(rot[j.parent], q);+ const o = qrot(rot[j.parent], j.offset);+ pos[i] = [pos[j.parent][0] + o[0], pos[j.parent][1] + o[1], pos[j.parent][2] + o[2]];+ });+ return { rot, pos };+}++// ---- the body's measures+const J = skel.joints, ji = (n: string) => joint(skel, n), restAxis = (i: number) => sub(J[i].tail, J[i].head);+const TWIST: [string, number][] = [+ ...SIDES.flatMap((s) => [[B.lowerarm(s), 100], [B.hand(s), 60], [B.upperarm(s), 100], [B.thigh(s), 60], [B.calf(s), 30], [B.foot(s), 40]] as [string, number][]),+ [B.neck, 60], [B.head, 60],+];+const LIMBS = SIDES.flatMap((s) => [[B.upperarm(s), B.lowerarm(s)], [B.lowerarm(s), B.hand(s)], [B.thigh(s), B.calf(s)], [B.calf(s), B.foot(s)]]);+const TRUNK = /^(hips|waist|torso|chest)$/, ARM = /^(palm|foreArm)$/;++type Faults = { twist: number; bend: number; inside: number; trunk: number; limbs: number; pop: number };+const KINDS: (keyof Faults)[] = ["twist", "bend", "inside", "trunk", "limbs", "pop"];++function check(src: Src, clip: Clip, b: Bvh) {+ const nj = clip.turns.length / (clip.frames * 4), S = (n: string) => b.joints.findIndex((x) => x.name === src.map[n]);+ const n = { ...Object.fromEntries(KINDS.map((k) => [k, 0])) } as Faults, worst: Record<string, [number, string]> = {};+ const note = (k: keyof Faults, v: number, what: string) => { if (v > (worst[k]?.[0] ?? 0)) worst[k] = [v, what]; };+ let frames = 0, prevT: Quat[] | undefined, prevS: Quat[] | undefined;+ for (let f = 0; f < clip.frames; f += every) {+ const t = f / clip.fps, bf = Math.min(b.frames.length - 1, Math.round(t / b.frameTime));+ const p = clipFrame(clip, f, nj), w = pose(skel, p), sw = sourceWorld(b, b.frames[bf]);+ const hit: Partial<Record<keyof Faults, boolean>> = {};+ // twist past a person's range, from rest (each joint's own turn against its parent's)+ for (const [name, lim] of TWIST) {+ const i = ji(name), d = Math.abs(wrap(twist(p.turns[i], restAxis(i))));+ if (d > lim) { hit.twist = true; note("twist", d - lim, `${name} ${d.toFixed(0)}°@${f}`); }+ }+ // a knee bent forward or an elbow bent back (the lower bone against the upper's rest frame)+ for (const s of SIDES) for (const [up, lo, sign] of [[B.thigh(s), B.calf(s), -1], [B.upperarm(s), B.lowerarm(s), 1]] as [string, string, number][]) {+ const u = ji(up), l = ji(lo), dl = qrot(qinv(w.rot[u]), qrot(w.rot[l], restAxis(l))), du = restAxis(u);+ const fwd = dot(nrm(dl), [0, 0, 1]) * sign, along = dot(nrm(dl), nrm(du));+ const back = Math.atan2(-fwd, along) * DEG;+ if (back > 10) { hit.bend = true; note("bend", back, `${lo} ${back.toFixed(0)}°@${f}`); }+ }+ // a hand or forearm in the trunk+ if (f % (every * 2) === 0) {+ const trunk = surface(skel, w, TRUNK), arms = surface(skel, w, ARM);+ for (const a of arms) {+ let best = Infinity, depth = 0;+ for (const x of trunk) { const d = sub(a.at, x.at), dd = dot(d, d); if (dd < best) { best = dd; depth = -dot(d, x.normal); } }+ // (no deeper than its distance to the nearest skin: a far nearest point means the arm is beside the trunk, not in it)+ if (depth > 0.015 && best < 0.05 * 0.05) { hit.inside = true; note("inside", depth * 100, `${a.side}${a.part} ${(depth * 100).toFixed(1)}cm@${f}`); break; }+ }+ }+ // the trunk, neck and limbs against the source's, each in its own heading+ const tAcross = sub(w.pos[ji(B.thigh("L"))], w.pos[ji(B.thigh("R"))]), sAcross = sub(sw.pos[S(B.thigh("L"))], sw.pos[S(B.thigh("R"))]);+ const tv = (a: string, c: string) => unheaded(sub(w.pos[ji(c)], w.pos[ji(a)]), tAcross);+ const sv = (a: string, c: string) => unheaded(sub(sw.pos[S(c)], sw.pos[S(a)]), sAcross);+ const tr = ang(tv(B.pelvis, B.neck), sv(B.pelvis, B.neck)), nk = ang(tv(B.neck, B.head), sv(B.neck, B.head));+ if (tr > 15 || nk > 25) { hit.trunk = true; note("trunk", Math.max(tr - 15, nk - 25), `trunk ${tr.toFixed(0)}° neck ${nk.toFixed(0)}°@${f}`); }+ for (const [a, c] of LIMBS) {+ if (S(a) < 0 || S(c) < 0) continue;+ const d = ang(tv(a, c), sv(a, c));+ if (d > 15) { hit.limbs = true; note("limbs", d, `${a} ${d.toFixed(0)}°@${f}`); }+ }+ // a joint turning faster than its source joint did+ const mapped = J.slice(0, nj).map((j, i) => [i, S(j.name)] as const).filter(([, s]) => s >= 0);+ const tRot = mapped.map(([i]) => w.rot[i]), sRot = mapped.map(([, s]) => sw.rot[s]);+ if (prevT && prevS) mapped.forEach(([i], k) => {+ const dt = qang(qmul(tRot[k], qinv(prevT![k]))), ds = qang(qmul(sRot[k], qinv(prevS![k])));+ if (dt - ds > 15) { hit.pop = true; note("pop", dt - ds, `${J[i].name} +${(dt - ds).toFixed(0)}°@${f}`); }+ });+ prevT = tRot; prevS = sRot;+ for (const k of KINDS) if (hit[k]) n[k]++;+ frames++;+ }+ const share = Object.fromEntries(KINDS.map((k) => [k, n[k] / Math.max(1, frames)])) as Faults;+ return { name: src.name, frames, share, worst: Object.fromEntries(Object.entries(worst).map(([k, v]) => [k, v[1]])) };+}++const all = list(), rows: ReturnType<typeof check>[] = [];+const ik = method === "ik" ? await import("raea/clip").then((m) => (m as unknown as { retargetIK?: typeof retarget }).retargetIK) : undefined;+if (method === "ik" && !ik) throw new Error("retarget-check: raea/clip has no retargetIK yet");+for (const src of all) {+ const b = readBvh(readFileSync(src.path, "utf8"));+ try {+ const clip = (ik ?? retarget)(skel, b, { name: src.name, map: src.map, rest: src.rest, keepTPose: true });+ rows.push(check(src, clip, b));+ if (rows.length % 25 === 0) console.error(`${rows.length}/${all.length} clips`);+ } catch (e) { console.log(`${src.name}: ${(e as Error).message}`); }+}+// the summary: per source and over all, the mean share of frames with each fault and the clips with any fault on a+// tenth of their frames or more+const bySrc = (r: { name: string }) => (r.name.startsWith("a") && /^a(Male|Female)/.test(r.name) ? "accad" : /^c\d/.test(r.name) ? "cmu" : "100style");+const pct = (x: number) => `${(x * 100).toFixed(1)}%`.padStart(6);+console.log(`method ${method}: ${rows.length} clips, frames every ${every}`);+console.log(`${"".padEnd(9)} ${KINDS.map((k) => k.padStart(6)).join(" ")} bad clips`);+for (const g of [...new Set(rows.map(bySrc)), "all"]) {+ const rs = rows.filter((r) => g === "all" || bySrc(r) === g);+ const mean = (k: keyof Faults) => rs.reduce((a, r) => a + r.share[k], 0) / Math.max(1, rs.length);+ const bad = rs.filter((r) => KINDS.some((k) => r.share[k] >= 0.1)).length;+ console.log(`${g.padEnd(9)} ${KINDS.map((k) => pct(mean(k))).join(" ")} ${bad}/${rs.length}`);+}+const worstN = +(flag("--worst") ?? 12), score = (r: (typeof rows)[number]) => KINDS.reduce((a, k) => a + r.share[k], 0);+console.log(`\nworst ${worstN}:`);+for (const r of [...rows].sort((a, b) => score(b) - score(a)).slice(0, worstN))+ console.log(` ${r.name.padEnd(34)} ${KINDS.filter((k) => r.share[k] > 0).map((k) => `${k} ${pct(r.share[k]).trim()} (${r.worst[k]})`).join("; ")}`);+if (flag("--out")) writeFileSync(flag("--out")!, JSON.stringify({ method, every, rows }, null, 1));diff --git a/sdk/raea/tools/retarget.ts b/sdk/raea/tools/retarget.tsindex 0c38f305..bfc5e7d3 100644--- a/sdk/raea/tools/retarget.ts+++ b/sdk/raea/tools/retarget.ts@@ -1,22 +1,17 @@// Motion capture retargeted onto a character (raea/clip): each BVH (a whole file, or a stretch of it) onto the-// skeleton character.py wrote, all into one clip file the composition imports.+// skeleton projects/psx/export.py wrote (game_engine joints), all into one clip file the composition imports.//// bun sdk/raea/tools/retarget.ts SKELETON.json OUT.json [--map MAP.json] NAME=FILE.bvh[@FROM-TO] ...//-// --map: a BVH whose joints aren't named as the skeleton's (100STYLE's), as { skeleton's joint: BVH's joint }; see-// tools/maps/.-// --carriage NAME: every clip's neck and head move about NAME's average (one actor's neutral walk) rather than their-// own, so a style's own carriage stays.+// --map: the capture's source map, { game_engine joint: BVH joint } (tools/maps/100style.json, cmu.json).import { readFileSync, writeFileSync } from "node:fs";-import { readBvh, retarget, writeClips, type Clip } from "raea/clip";+import { readBvh, retarget, writeClips } from "raea/clip";import type { Skeleton } from "raea/character";const args = process.argv.slice(2);const mi = args.indexOf("--map");const map = mi >= 0 ? (JSON.parse(readFileSync(args[mi + 1], "utf8")) as Record<string, string>) : undefined;if (mi >= 0) args.splice(mi, 2);-const ci = args.indexOf("--carriage");-const carriageFrom = ci >= 0 ? args[ci + 1] : undefined;if (ci >= 0) args.splice(ci, 2);const [skelPath, out, ...specs] = args;if (!skelPath || !out || specs.length === 0) {@@ -24,18 +19,15 @@ if (!skelPath || !out || specs.length === 0) {process.exit(2);}const skel = JSON.parse(readFileSync(skelPath, "utf8")) as Skeleton;-const one = (s: string, carriage?: Clip["carriage"]) => {+const one = (s: string) => {const m = /^([^=]+)=([^@]+)(?:@([\d.]+)-([\d.]+))?$/.exec(s);if (!m) throw new Error(`retarget: ${s} isn't NAME=FILE.bvh[@FROM-TO]`);const b = readBvh(readFileSync(m[2], "utf8"));- const c = retarget(skel, b, { name: m[1], from: m[3] ? +m[3] : undefined, to: m[4] ? +m[4] : undefined, map, carriage });+ const c = retarget(skel, b, { name: m[1], from: m[3] ? +m[3] : undefined, to: m[4] ? +m[4] : undefined, map });console.log(`${c.name}: ${c.frames} frames at ${c.fps} fps from ${m[2]}`);return c;};-const ref = carriageFrom ? specs.find((s) => s.startsWith(`${carriageFrom}=`)) : undefined;-if (carriageFrom && !ref) throw new Error(`retarget: --carriage ${carriageFrom} isn't one of the clips`);-const carriage = ref ? one(ref).carriage : undefined;-const clips = specs.map((s) => one(s, carriage));+const clips = specs.map((s) => one(s));const file = writeClips(skel, clips);writeFileSync(out, JSON.stringify(file));console.log(`${out}: ${clips.length} clips, ${(JSON.stringify(file).length / 1024).toFixed(0)} KB`);diff --git a/sdk/raea/tools/scene-faults.ts b/sdk/raea/tools/scene-faults.tsnew file mode 100644index 00000000..2d15f664--- /dev/null+++ b/sdk/raea/tools/scene-faults.ts@@ -0,0 +1,85 @@+// Faults of a body among things (docs/locomotion.md, I-class): what clips into furniture, what the hands do to the+// thing they take, and how a sit plays. For a plan case (errands): its things are boxes, a seat is errands.tsx's chair+// (a seat top at 0.46 m, a leg block under it, a back behind the sitter).+//+// clip I1 frames with a body surface point more than 1.5 cm inside furniture or the chair (%), the deepest (cm)+// and where; the hips, waist and thighs on the seat's top while sitting are not in it+// inThing I2 frames with a palm or finger point more than 0.5 cm inside the thing being taken or held (%), deepest+// gripGap I2 held frames on which no palm or finger point is within 1 cm of the thing's surface (%): a float+// sitLoop I4 turns back of the seat clip's frame while sat, a second: a sit's held part played to and fro+import type { Vec3 } from "raea/3d";+import { pose, qinv, qrot, surface, type Pose, type Quat, type Skeleton } from "raea/character";+import type { Performance } from "raea/matching";+import { thingSdf, type Interaction } from "raea/items";+import type { Seat } from "raea/matching";++const seatYaw = (s: Seat) => (typeof s.facing === "number" ? s.facing : Math.atan2(s.facing[0] - s.at[0], s.facing[2] - s.at[2]));++interface Box { name: string; c: Vec3; h: Vec3; rot: Quat }+const I: Quat = [0, 0, 0, 1];+const yawQ = (a: number): Quat => [0, Math.sin(a / 2), 0, Math.cos(a / 2)];++/** how far inside a box a point is (metres; negative outside, the distance to the nearest face either way) */+function depth(b: Box, p: Vec3): number {+ const l = qrot(qinv(b.rot), [p[0] - b.c[0], p[1] - b.c[1], p[2] - b.c[2]]);+ const d = [0, 1, 2].map((k) => b.h[k] - Math.abs(l[k]));+ if (d.every((x) => x > 0)) return Math.min(...d);+ const o = [0, 1, 2].map((k) => Math.max(0, -d[k]));+ return -Math.hypot(...o);+}++export function sceneFaults(skel: Skeleton, perf: Performance, live: Interaction, things: Record<string, any>, items: Record<string, any>, seat?: Seat) {+ // (the plan's own box for a seat sat on is left out: the chair below is drawn as errands.tsx draws it)+ const boxes: Box[] = Object.entries(things).filter(([, t]) => !seat || Math.hypot(t.at[0] - seat.at[0], t.at[2] - seat.at[2]) > 0.01).map(([name, t]) => ({ name, c: [t.at[0], t.size[1] / 2, t.at[2]], h: [t.size[0] / 2, t.size[1] / 2, t.size[2] / 2], rot: yawQ(t.yaw ?? 0) }));+ if (seat) {+ const r = yawQ(seatYaw(seat) + Math.PI), at = (x: number, y: number, z: number): Vec3 => { const v = qrot(r, [x, 0, z]); return [seat.at[0] + v[0], y, seat.at[2] + v[2]]; };+ const top = seat.at[1];+ boxes.push({ name: "seat", c: at(0, top - 0.02, 0), h: [0.24, 0.02, 0.24], rot: r }, { name: "chair legs", c: at(0, (top - 0.04) / 2, 0), h: [0.2, (top - 0.04) / 2, 0.2], rot: r }, { name: "chair back", c: at(0, top + 0.29, 0.25), h: [0.24, 0.3, 0.02], rot: r });+ }+ const n = perf.frames, sitting = (f: number) => !!perf.phase(f)?.stage;+ const by: Record<string, number> = {}, deepBy: Record<string, { d: number; at: string }> = {};+ const inBy: Record<string, number> = {}, gapBy: Record<string, number> = {}, gapMax: Record<string, number> = {}, sdfs: Record<string, (p: Vec3) => number> = {};+ let clipN = 0, clipDeep = 0, clipAt = "", inN = 0, inDeep = 0, inAt = "", heldN = 0, gapN = 0;+ for (let f = 0; f < n; f++) {+ const w = pose(skel, live.pose(f) as Pose), pts = surface(skel, w);+ // I1: the body in furniture+ let worst = 0, wAt = "";+ for (const p of pts) for (const b of boxes) {+ if (b.name === "seat" && sitting(f) && /^(hips|waist|thigh)$/.test(p.part)) continue;+ const d = depth(b, p.at);+ if (d > worst) { worst = d; wAt = `${p.part}${p.side}@${f} in ${b.name}`; }+ }+ if (worst > 0.015) { clipN++; const k = `${wAt.split(" in ")[1]}/${perf.phase(f)?.stage ?? (live.held("cup", f) || live.held("ball", f) ? "carry" : "walk")}`; by[k] = (by[k] ?? 0) + 1; }+ if (worst > clipDeep) { clipDeep = worst; clipAt = wAt; }+ if (worst > 0.015) { const bn = wAt.split(" in ")[1]; if (!(bn in deepBy) || worst > deepBy[bn].d) deepBy[bn] = { d: worst, at: wAt.split(" in ")[0] }; }+ // I2: the hands and the things+ const hand = pts.filter((p) => /^(palm|thumb|index|middle|ring|pinky)\d?$/.test(p.part));+ for (const [id, it] of Object.entries(items)) {+ const s = live.item(id, f), held = live.held(id, f);+ // (in the thing's own frame, its own distance field: a cup's box had corners out past the cup)+ const sdf = (sdfs[id] ??= thingSdf(it));+ const dOf = (p: Vec3) => -sdf(qrot(qinv(s.rot), [p[0] - s.at[0], p[1] - s.at[1], p[2] - s.at[2]]));+ let deep = 0, dAt = "", near = Infinity;+ for (const p of hand) { const d = dOf(p.at); if (d > deep) { deep = d; dAt = `${p.part}${p.side}@${f} in ${id}`; } near = Math.min(near, Math.abs(d)); }+ const key = `${id}/${held ? "held" : "free"}`;+ if (deep > 0.005) { inN++; inBy[key] = (inBy[key] ?? 0) + 1; }+ if (deep > inDeep) { inDeep = deep; inAt = dAt; }+ if (held) { heldN++; if (near > 0.01) { gapN++; gapBy[id] = (gapBy[id] ?? 0) + 1; gapMax[id] = Math.max(gapMax[id] ?? 0, near); } }+ }+ }+ // I4: the seat clip's frame turning back while sat+ let backs = 0, satN = 0, dir = 0;+ for (let f = 1; f < n; f++) {+ if (perf.phase(f)?.stage !== "sat" || perf.phase(f - 1)?.stage !== "sat") continue;+ satN++;+ const d = Math.sign(perf.played[f].f - perf.played[f - 1].f);+ if (d && dir && d !== dir) backs++;+ if (d) dir = d;+ }+ return {+ clip: (100 * clipN) / n, clipDeep: clipDeep * 100, clipAt, clipBy: by, deepBy: Object.fromEntries(Object.entries(deepBy).map(([k, v]) => [k, `${(v.d * 100).toFixed(1)} cm ${v.at}`])),+ inThing: (100 * inN) / n, inDeep: inDeep * 100, inAt, inBy,+ gripGap: heldN ? (100 * gapN) / heldN : 0, gapBy, gapMax: Object.fromEntries(Object.entries(gapMax).map(([k, v]) => [k, `${(v * 100).toFixed(1)} cm`])),+ sitLoop: satN ? (backs * 30) / satN : 0,+ };+}diff --git a/sdk/react/docs/audio-stack.md b/sdk/react/docs/audio-stack.mdindex 57c74928..fdc7a387 100644--- a/sdk/react/docs/audio-stack.md+++ b/sdk/react/docs/audio-stack.md@@ -247,7 +247,7 @@ Missing means it isn't there.- `Channel.duck(key, {amount, threshold, attack, release})`: sidechain ducking.- `<Sfx when play>`: frame-exact one-shots.- `vary(instrument, {pitch, volume})`: seeded variation per event.-- Generated sources: `sao`, `lyria`, `fish` and `tokensynth(timbre, notes)`.+- Generated sources: `sao`, `lyria` and `tokensynth(timbre, notes)`; narration is `<Speech>` (raea/speech).- `Time(...).toFrames(fps)`: cuts on bars and beats.- `raea/music` (Part and Sequence on named instruments, MIDI in and out) is a shorthand. It plays throughthis layer: each instrument name is a Tone preset.@@ -258,13 +258,12 @@ A Sampler's `urls` and a Player's `url` take a media path, or a generated asset:- `Tone.tokensynth(timbre, notes, {seconds, velocity, seed, precision})`: one asset per root note, by TokenSynth,local CPU. The Sampler pitches between the roots. This is how raea makes music.- `Tone.sao(prompt, {seconds})`: foley, by Stable Audio Open Small on Core ML, local.-- `Tone.fish(text, {voice})`: narration over the picture, by Fish, paid.- `Tone.lyria(prompt)`: a music bed, by Lyria, paid. Still wired; the guides no longer use it.- A file from an open sample library in the media folder: `raea sounds get PACK/INSTRUMENT` (below).How a source is made and played:- **Policy** (2026-10-19). Music is Tone.js instruments: TokenSynth notes, an open sample library's notes, or- synths, in a Sampler playing a Part or Sequence. SAO for foley, Fish for non-diegetic voice. No other generation+ synths, in a Sampler playing a Part or Sequence. SAO for foley, Pocket TTS (`<Speech>`) for non-diegetic voice. No other generation(no images, video or remote sound effects); Lyria stays in the code for older edits. Nothing in this work spent money: the fixtures' sounds come from SAO and TokenSynth (local) and thevoice from macOS `say` at test time.- **Resolution.** The graph's sources are resolved by react (audio.rs `tone_of`): media paths through the mediadiff --git a/sdk/render/src/3d/compute.tsx b/sdk/render/src/3d/compute.tsxindex fd70d1a2..26ab205a 100644--- a/sdk/render/src/3d/compute.tsx+++ b/sdk/render/src/3d/compute.tsx@@ -23,7 +23,7 @@ export interface ComputeProps {const IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;-/** A compute over the frame, inside a <Canvas3D>; several run in the order written, before the cameras draw.+/** A compute over the frame, in the 3D beside the camera; several run in the order written, before the cameras draw.* @bevy raea_sys_compute::Computes */export function Compute(props: ComputeProps) {const { wesl, wgsl, workgroups, uniforms = {}, buffers = {}, images = {}, defs } = props;diff --git a/sdk/render/src/3d/materials.tsx b/sdk/render/src/3d/materials.tsxindex 5db30f94..c4f1be25 100644--- a/sdk/render/src/3d/materials.tsx+++ b/sdk/render/src/3d/materials.tsx@@ -9,8 +9,9 @@ import { Animate3d, apply3d, node3d } from "./all";export interface SurfaceDrawProps {/** "opaque" (the default), "blend" (what `transparent` gives), "mask" (cut out where the alpha is under* `alphaCutoff`: leaves, chain-link, a sprite's edge; no sorting), "add" (glows add up: sparks, light beams),- * "multiply" (darkens what's behind: stained glass, a shadow decal), "premultiplied" */- alphaMode?: "opaque" | "blend" | "mask" | "add" | "multiply" | "premultiplied";+ * "multiply" (darkens what's behind: stained glass, a shadow decal), "premultiplied", "coverage" (soft cut-out edges+ * from the alpha over MSAA's samples: hair cards, foliage; needs <AntiAliasing mode="msaa">, without it draws solid) */+ alphaMode?: "opaque" | "blend" | "mask" | "add" | "multiply" | "premultiplied" | "coverage";/** with alphaMode="mask": the alpha under which it's cut away, 0..1 (0.5) */alphaCutoff?: number;/** which faces draw: "front" (the default), "back" (the inside only: a sky dome, a room seen from outside),@@ -194,7 +195,7 @@ export function checkTextures(owner: string, textures: Record<string, string | R/** One shader over every lit standard surface in the scene that has none of its own (meshes, Models' materials,* Characters), so the whole scene shares one look (docs/shaders.feature SH4). Unlit, toon, paint, flat and looked- * surfaces and ShaderMesh keep theirs. Inside a <Canvas3D>; one per scene.+ * surfaces and ShaderMesh keep theirs. In the 3D beside the camera; one per scene.* @bevy bevy_pbr::mesh_material::MeshMaterial3d<bevy_pbr::extended_material::ExtendedMaterial<bevy_pbr::pbr_material::StandardMaterial, raea_sys_shader::ShaderExt>> */export function SurfaceShader(props: SurfaceShaderSpec) {return node3d("SurfaceShader", { shader: surfaceShader("SurfaceShader", props) });@@ -223,7 +224,7 @@ export interface FramePassProps {const PASS_HOOK = /(^|[^A-Za-z0-9_])fn\s+shade\s*\(|@fragment/;-/** A full-screen pass over the scene camera's frame, inside a <Canvas3D>; several run in the order written. With a+/** A full-screen pass over the scene camera's frame, beside the camera; several run in the order written. With a* frame <Look> they run on its cells, before the look's composite.* @bevy raea_sys_framepass::FramePasses */export function FramePass(props: FramePassProps) {@@ -277,7 +278,7 @@ export function checkMaterial(owner: string, props: Record<string, unknown>): voif (v !== undefined && !(typeof v === "number" && v >= 0 && v <= 1)) throw new RangeError(`${owner}: ${k} must be in [0, 1], got ${v}`);}const am = props.alphaMode;- if (am !== undefined && !["opaque", "blend", "mask", "add", "multiply", "premultiplied"].includes(am as string)) throw new TypeError(`${owner}: alphaMode is opaque, blend, mask, add, multiply or premultiplied, got ${JSON.stringify(am)}`);+ if (am !== undefined && !["opaque", "blend", "mask", "add", "multiply", "premultiplied", "coverage"].includes(am as string)) throw new TypeError(`${owner}: alphaMode is opaque, blend, mask, add, multiply, premultiplied or coverage, got ${JSON.stringify(am)}`);if (props.side !== undefined && !["front", "back", "double"].includes(props.side as string)) throw new TypeError(`${owner}: side is front, back or double, got ${JSON.stringify(props.side)}`);if (props.ior !== undefined && !(typeof props.ior === "number" && props.ior >= 1)) throw new RangeError(`${owner}: ior must be 1 or more, got ${props.ior}`);if (props.thickness !== undefined && !(typeof props.thickness === "number" && props.thickness >= 0)) throw new RangeError(`${owner}: thickness must be 0 or more metres, got ${props.thickness}`);diff --git a/sdk/render/src/3d/model.tsx b/sdk/render/src/3d/model.tsxindex c0d004f3..aa603318 100644--- a/sdk/render/src/3d/model.tsx+++ b/sdk/render/src/3d/model.tsx@@ -143,6 +143,10 @@ export interface ModelProps {* <Outline skip>, <Bloom skip>, <Grade skip>) leaves its pixels as drawn, and <Look passes> gives one its own paint;* a piece names at most three passes besides "scene"; keyed per frame */pass?: string;+ /** a skinned model's own vertices replaced each frame by a baked cloth simulation (docs/cloth.md K2): `src` a .rseq+ * of the model's vertices in its bind pose, in the glTF's order (raea/body tools/cloth.ts --bind), `frame` the one+ * drawn (keyed per frame). The skin poses them, so its materials, alpha, morphs and bones are kept. */+ cloth?: { src: string; frame: number };/** fixed to another model's bone (`to`: that model's name; `bone`: the node's name in its glTF, "Head"): it follows* the bone's animated pose, and its position, rotation and scale are in the bone's space (a glTF's armature is* often scaled, so a hat may need scale 0.01) */@@ -184,7 +188,8 @@ export interface ModelProps {* bones in its `mask` alone (a wave on the arm over a walk: { add: [{ clip: "walk" }, { clip: "wave", mask: ["leg_l",* "leg_r"] }] }). Weights and clip times may change every frame. Up to 16 nodes; not with animation or animations */graph?: AnimGraphNode;- /** morph target (blend shape) weights, 0 to 1: by target name ({ smile: 0.8 }) or index ([0.8, 0]); up to 8 */+ /** morph target (blend shape) weights, 0 to 1: by target name ({ smile: 0.8 }) or index ([0.8, 0]); up to 64. The+ * names are fixed when the model is made: pass the same set every frame (0 for a target at rest) */morphs?: Record<string, number> | number[];/** seconds into the clip (by default the Sequence's time: frame / fps); the clip loops unless loop={false} */time?: number;@@ -284,6 +289,7 @@ export function Model(props: ModelProps) {if (!Number.isFinite(time)) throw new RangeError(`Model: time must be a finite number of seconds, got ${time}`);if (props.look !== undefined && !["solid", "pixel", "site"].includes(props.look)) throw new TypeError(`Model: look must be "solid", "pixel" or "site", got ${JSON.stringify(props.look)}`);checkPass("Model", props.pass);+ if (props.cloth !== undefined && !(typeof props.cloth?.src === "string" && /\.rseq$/.test(props.cloth.src) && Number.isFinite(props.cloth.frame))) throw new TypeError(`Model: cloth is { src: a .rseq file, frame: a number }, got ${JSON.stringify(props.cloth)}`);if (props.sampler !== undefined) samplerSpec("Model", props.sampler);if (props.pixelSize !== undefined && !(props.pixelSize >= 1)) throw new RangeError(`Model: pixelSize must be at least 1, got ${props.pixelSize}`);if (props.bones !== undefined && (typeof props.bones !== "object" || Object.values(props.bones).some((v) => typeof v !== "string"))) throw new TypeError(`Model: bones maps each joint's name to a model's name, got ${JSON.stringify(props.bones)}`);@@ -308,7 +314,7 @@ export function Model(props: ModelProps) {if (props.morphs !== undefined) {const m = props.morphs;const entries: [string | number, number][] = Array.isArray(m) ? m.map((w, i) => [i, w]) : typeof m === "object" && m !== null ? Object.entries(m) : [];- if (entries.length < 1 || entries.length > 8) throw new RangeError(`Model: morphs names 1 to 8 targets (by name or index), got ${JSON.stringify(m)}`);+ if (entries.length < 1 || entries.length > 64) throw new RangeError(`Model: morphs names 1 to 64 targets (by name or index), got ${JSON.stringify(m)}`);for (const [k, w] of entries) if (!Number.isFinite(w)) throw new RangeError(`Model: morphs.${k} is a weight, got ${w}`);p.morphs = entries.map(([k, w]) => ({ target: k, weight: w }));}diff --git a/sdk/render/src/3d/shapes.tsx b/sdk/render/src/3d/shapes.tsxindex 024ed48a..ae93fec0 100644--- a/sdk/render/src/3d/shapes.tsx+++ b/sdk/render/src/3d/shapes.tsx@@ -7,15 +7,16 @@ import { Canvas3DProps, Vec3, checkArgs, checkPass, checkVec, node3d, serialisabconst FILL = { position: "absolute", left: 0, top: 0, width: "100%", height: "100%" } as const;-/** The 3D scene's root; everything 3D goes inside it. `layered`: the 3D is drawn in the page's order, at the box of- * the nearest positioned element around it (the whole frame when there's none; B3 H7), at that box's size and aspect:+/** Only for `layered`: the 3D is drawn in the page's order, at the box of the nearest positioned element around it+ * (the whole frame when there's none; B3 H7), at that box's size and aspect:** <div style={{ position: "absolute", left: 100, top: 50, width: 200, height: 150 }}>* <Canvas3D layered><Camera3d transform={...} /><Mesh3d>...</Mesh3d></Canvas3D>* </div>- * @deprecated not needed (S2a): a <Camera3d> makes a view */+ * Without `layered` it is its children, as written straight in the page (M6).+ * @deprecated without `layered`: not needed, a <Camera3d> makes a view */export function Canvas3D(props: Canvas3DProps) {- if (!props.layered) return node3d("Canvas3D", props, props.children);+ if (!props.layered) return <>{props.children}</>;// layered: a full-frame box in the page's flow, and the slot the 3D's frame is painted into (an <img> the renderer// points at the 3D's texture), first so the 3D parts after it stay out of the page's paintreturn (diff --git a/sdk/render/src/bevy3d.tsx b/sdk/render/src/bevy3d.tsxindex 4c8691b7..6aab686f 100644--- a/sdk/render/src/bevy3d.tsx+++ b/sdk/render/src/bevy3d.tsx@@ -12,6 +12,8 @@ export { Quat, Affine2, Transform, Mesh3d, Camera3d, Srgba, LinearRgba, Standardexport type { EulerRot, TransformValue, TransformBuilt, Mesh3dProps, Projection, Camera3dProps, AlphaMode, StandardMaterialProps, StandardMaterialAnimate, ToonExtensionAnimate, SampledImage, MetallicRoughnessMaps, GridExtensionProps, PaintExtensionProps, WearExtensionProps, ToonExtensionProps, ShaderExtensionProps, ExtendedMaterialProps, ToonMaterialProps, Mesh2dProps, CircleProps, RectangleProps, EllipseProps, RegularPolygonProps, ColorMaterialProps, PointLightProps, SpotLightProps, DirectionalLightProps, AmbientLightProps, RectLightProps } from "./bevy3d/all";export { eulerOf };+// ray-traced lighting: Bevy's Solari (docs/raytracing.feature RT3)+export { SolariLighting, Pathtracer, type SolariLightingProps, type PathtracerProps } from "./bevy3d/raytracing";export { ConicalFrustum, type ConicalFrustumProps } from "./3d/shapes";// a Bevy texture (a camera's target) drawn in an element (B3 H7)export { TextureView } from "./layers";diff --git a/sdk/render/src/bevy3d/raytracing.tsx b/sdk/render/src/bevy3d/raytracing.tsxnew file mode 100644index 00000000..02da58c8--- /dev/null+++ b/sdk/render/src/bevy3d/raytracing.tsx@@ -0,0 +1,37 @@+// Ray-traced lighting: Bevy's Solari (docs/raytracing.feature RT3), on the camera it's inside.+import { BevyComponent } from "../3d";++export interface SolariLightingProps {+ /** ReSTIR: reuse light samples between pixels and frames (finer shadows, steadier in hard light; slower). Off by+ * default, as Bevy has it */+ restir?: boolean;+ /** how many times light bounces (Bevy's default when left out) */+ bounces?: number;+ /** start the lighting's history again (a cut) */+ reset?: boolean;+}++/** Ray-traced direct and indirect light for the <Camera3d> it's inside (Bevy's SolariLighting): shadows, bounce+ * light and reflections traced against the scene, in place of shadow maps. Needs a GPU with ray queries (Apple+ * silicon on Metal, RTX on Vulkan); elsewhere the scene draws raster-lit and raea says so. On the Mac MetalFX's+ * temporal denoiser cleans it up (RT4; RAEA_SOLARI_DENOISE=0 shows the raw noise). A <Character> (skinned, morphed) stays raster-lit: Bevy 0.20's+ * Solari can't trace it (RT5). */+export function SolariLighting(p: SolariLightingProps = {}) {+ if (p.bounces !== undefined && !(Number.isInteger(p.bounces) && p.bounces >= 0)) throw new RangeError(`SolariLighting: bounces is a whole number, got ${p.bounces}`);+ const value: Record<string, unknown> = {};+ if (p.restir !== undefined) value.restir = p.restir;+ if (p.bounces !== undefined) value.max_bounces = p.bounces;+ if (p.reset !== undefined) value.reset = p.reset;+ return <BevyComponent type="bevy_solari::realtime::SolariLighting" value={value} />;+}++export interface PathtracerProps {+ /** start the accumulation again */+ reset?: boolean;+}++/** Bevy's reference path tracer for the <Camera3d> it's inside: slow and exact, accumulating over frames while the+ * view holds still. For stills to check a look against, not for motion. Same GPU needs as <SolariLighting>. */+export function Pathtracer(p: PathtracerProps = {}) {+ return <BevyComponent type="bevy_solari::pathtracer::Pathtracer" value={{ reset: p.reset ?? false }} />;+}diff --git a/sdk/render/src/matchmove.tsx b/sdk/render/src/matchmove.tsxindex 277017ac..da77365f 100644--- a/sdk/render/src/matchmove.tsx+++ b/sdk/render/src/matchmove.tsx@@ -7,7 +7,7 @@// 0 looking down -Z. `<Text3D position={[0, 0, -4]}>` stands on the ground.import { createContext, useContext, type ReactNode } from "react";import { useCurrentFrame, useVideoConfig } from "@raea/app/clock";-import { Canvas3D, PerspectiveCamera, Plate, ToneMapping, type Vec3 } from "./3d";+import { PerspectiveCamera, Plate, ToneMapping, type Vec3 } from "./3d";import { hasNative, native } from "@raea/app/native";export interface MatchmoveCamera {@@ -162,7 +162,7 @@ export function matchmoveIndex(solve: MatchmoveSolve, time: number): number {/*** Footage with real 3D standing in it: the clip behind, its camera solved and followed, the subject in front. Fills- * the frame (it is its own Canvas3D); its children are the 3D in the shot's world, lights included.+ * the frame (its camera's view is the frame's); its children are the 3D in the shot's world, lights included.*/export function Matchmove(props: MatchmoveProps) {checkMatchmove(props);@@ -193,12 +193,10 @@ export function Matchmove(props: MatchmoveProps) {return (<MatchmoveContext.Provider value={state}><div style={{ position: "absolute", left: 0, top: 0, width, height, overflow: "hidden", background: "#000000" }}>- <Canvas3D><PerspectiveCamera position={p} lookAt={lookAt} up={up} fov={solve.fov} near={0.05} far={2000} {...(plain ? {} : { view })} /><ToneMapping mode={props.toneMapping ?? "none"} /><Plate src={props.src} time={time} k1={solve.k1} />{props.children}- </Canvas3D>{cut ? <img fetchPriority="low" src={cut} style={{ position: "absolute", left: -view.x, top: -view.y, width: view.width, height: view.height }} /> : null}</div></MatchmoveContext.Provider>diff --git a/sdk/skills/raea-bevy/SKILL.md b/sdk/skills/raea-bevy/SKILL.mdindex d615014a..412af650 100644--- a/sdk/skills/raea-bevy/SKILL.md+++ b/sdk/skills/raea-bevy/SKILL.md@@ -26,6 +26,7 @@ the topic files here link to those, except `rows.md` and `plugins.md`, which onl| a 3D game: state, input, entities, collisions, state machines | `games.md` || a game's sound: one-shots on transitions (`<Tone.Sfx>`), buses, a bed ducked under a voice (Tone.js on raea) | `games.md` (Sound), then `raea guide motion/music` || glTF models, pictures in space, media files | `assets.md` |+| an asset to fix before it goes in: scale and pivot, a heavy mesh, FBX/OBJ/.blend to .glb, a rig, a bake (Blender, `raea blender run`; never a whole scene) | `blender.md` || gaussian splats: a real scene or object trained from footage (`raea splat train`), `<Splat>` and its reveal, assemble, disperse, explode, wave, twist, morph, pulse | `splats.md` || liquids and goo: coffee dumped from a mug, a tap's stream, honey, things melting (`<Goo>`, sph or mpm, baked) | `liquids.md` || bloom, fog, tone mapping, exposure, fisheye and lens distortion, motion blur, fire (`<Fire>`), frame looks (pixel, ink, painted illustration `<Look mode="paint">`, cartoon `<Look mode="cartoon">`) | `post.md` |diff --git a/sdk/skills/raea/SKILL.md b/sdk/skills/raea/SKILL.mdindex ef1d135c..fa016b37 100644--- a/sdk/skills/raea/SKILL.md+++ b/sdk/skills/raea/SKILL.md@@ -5,217 +5,150 @@ description: Make video, motion graphics, games and 3D scenes with raea, the Ren# raea-raea renders compositions written in TypeScript and React (`raea`) with a GPU engine built on Bevy. A-composition is a function of the frame: give it frame N and it draws frame N. The same file renders to video, plays-live as a game, or renders single frames for checking.--## Set up (once)--1. macOS on Apple Silicon. Install (or update) raea: `curl -fsSL https://raea.io/install | sh`. It puts `raea`- in `~/.raea/bin`, links it from `~/.local/bin` (make sure that's on `PATH`, ahead of any older `raea`), and adds this- skill and raea-bevy to `~/.claude/skills`. Check it with `raea help` (it prints its usage).-2. From a checkout of the repository instead: `cargo build --release -p raea-cli` at its root (Rust stable); the- binary is `target/release/raea`.-3. Optional settings live in `~/.raea/env` (see `docs/settings.md`). Rendering needs none of them.--## Before working on a project--Run `raea context PROJECT` (a project folder with `brief.brief`, or a `.brief` file) and read all of it first. It-prints the person's taste (`~/.raea/taste/`; a line there beats any guide's default), the brief, the look, the craft-floor and the guide for each of the brief's modes. If it says the brief isn't shaped (no `believe`, no `mode`), shape-it before making anything: ask who it's for and the one thing they should believe, or write your best guess with-`(assumed)` after it and go on.--For a pitch, an explain or a story, plan before you make: write the deliverable's storyboard as `name.board` beside-the brief (a table: scene · on screen · narration · payoff), name it on the deliverable's line, and add a-`- [ ] … storyboard approved #gate` task. Render nothing until the person approves it.--When the person leaves a note, read it as one move (quieter, bolder, distill, clarify, retime, recut, regrade, remix,-harden, polish, critique) on the part or moment it names, and read that move's playbook first: `raea guide quieter`.-Answer in their words; never name the move to them.--Right before any edit to a composition, even a one-line change, read the floor again: `raea guide craft`. For the-order of work (shape, storyboard, direction, floor, evidence) and how to read the person's notes, read-`raea guide router` once.--## Write a composition--One `.tsx` file whose root registers compositions (for a footage edit, `raea init` in its folder writes the files it-starts from: edit.tsx over cuts.ts, components/, styles.gen.ts and AGENTS.md):+raea renders compositions written in TypeScript and React with a GPU engine built on Bevy. A composition is a function+of the frame: give it frame N and it draws frame N. The same file renders to video, plays live as a game, or renders+single frames to check.++Each step below says where it runs. **HEADLESS**: the `raea` CLI alone, in any shell. **HOST**: needs the raea app+running on this machine (its host answers). **PAGE**: needs the person's feed open in the app. **PERSON**: only the+person can do it. Every PAGE step says what a headless agent does instead.++## 1. Install (once) — HEADLESS+<!-- sources: tools/release.sh apps/site/public/install engine/cli/src/skill.rs -->++- macOS (Apple Silicon) or Linux (x86_64): `curl -fsSL https://raea.io/install | sh`. Windows 10 or 11, in+ PowerShell: `irm https://raea.io/install.ps1 | iex`. Either puts `raea` under `~/.raea`, puts it on your PATH, and+ adds this skill and raea-bevy to `~/.claude/skills`. Run it again to update. `raea help` lists every verb.+- Another agent: `raea skills install --agent claude|codex|kimi|gemini` puts the skills where that agent reads them.+ `--pin quieter` (any move) adds a `/quieter` that loads one move. For Claude it also adds a hook that runs+ `raea check --quick` after a composition is saved and hands you what it finds.+- This file's front matter names the raea it shipped with (`version:`). If `raea --version` prints another, read+ `raea skill` instead: it is this skill as your raea ships it.+- From a checkout of the repository: `cargo build --release -p raea-cli`; the binary is `target/release/raea`.+- Optional settings live in `~/.raea/env` (`docs/settings.md`). Rendering needs none of them.++## Reference++Generated from the code by `tools/skills.sh gen`, so they're current. Read the one you need instead of guessing a flag:+- [reference/cli.md](reference/cli.md): every `raea` verb, its flags and where it runs (`raea help` prints the same).+- [reference/feed.md](reference/feed.md): the raea app's tools for an agent it launches, and which need its page.+- [reference/files.md](reference/files.md): a workspace's and a project's files, what lives in `~/.raea`, and each+ spec's fields (brief.ts, NAME.script.ts, taste.ts, plan.ts, controllers/ID.ts).+- [reference/sdk.md](reference/sdk.md): what each `raea` import gives a composition.+- [reference/app.md](reference/app.md): driving the raea app's window over MCP, as a person would (HOST).++## 2. The workspace and its projects — HEADLESS+<!-- sources: apps/workspace/src -->++Work lives in a workspace: a git repo under raea.root (`~/Studio` unless `git config --global raea.root` says+otherwise), one per studio or client, holding projects and controllers. In the raea app a project shows as a channel.+- `raea workspace init NAME` makes one; `raea workspace adopt DIR` makes an existing folder one. `raea workspace`+ shows it (`--json` for the projects and their paths).+- `raea project new NAME` adds a project: its folder with `brief.ts`, `media/`, `out/` and `brand/`. A project can+ live inline or as its own repo (`raea project split NAME`, `raea project join NAME`); both keep its history.+- Work in the project's folder. Footage and other media go in `media/`, renders in `out/`.++## 3. Read before you make — HEADLESS+<!-- sources: engine/cli/src/guide.rs apps/workspace/src core/brief/src -->++- `raea context .` in the project prints everything to read first, in order: the person's taste+ (`~/.raea/taste/taste.ts`; a line there beats any guide's default), the workspace's taste, the brief, the look, the+ workspace's controllers, the craft floor and each of the brief's modes' guides. Read all of it.+- Run it once a session. If it refuses, say so in one line ("raea context failed: its message; reading the brief and+ controllers directly") and read `brief.ts`, any `*.script.ts`, `~/.raea/taste/taste.ts` and `raea controller ls`+ yourself. A `CONTEXT_STALE` line means `raea doctor` finds files from another version: run `raea doctor --fix`.+- With no request in hand, `raea next` lists the two or three useful next steps from the brief, the compositions,+ the renders and their checks. Offer them; never run one unasked.+- The controllers (`raea controller ls`, `raea controller get PATH`) are the workspace's settings and workflows:+ delivery specs, who reviews what, the tools every agent gets. Work to them. Change one only when the person asks:+ `raea controller set PATH VALUE` (each change is a commit).+- If the brief isn't shaped (no `believe`, no `mode`), shape it before making anything: ask who it's for and the one+ thing they should believe, or write your best guess and add its field to the brief's `assumed` list.+- For a pitch, an explain or a story, plan first: write the deliverable's storyboard as `NAME.script.ts` beside the+ brief (`export default script({...})` from "raea/brief": scenes of beats, what's on screen and what each scene must+ land; its fields are in reference/files.md), name it on the deliverable, and add a task "storyboard approved" tagged `gate`. `raea spec NAME.script.ts`+ checks it. Render nothing until the person approves it (PERSON).+- The person's footage and files: `raea library search "WORDS"` finds them by meaning across the libraries they've+ indexed (HEADLESS once indexed; adding a folder waits for the person's yes, PERSON).+- Right before any edit to a composition, even a one-line change, read the floor: `raea guide craft`. Read+ `raea guide router` once for the order of work.++## 4. Make an item — HEADLESS+<!-- sources: sdk/raea/src/index.tsx sdk/raea/src/3d.tsx -->++One `.tsx` file whose root registers compositions (`raea init` in a footage project writes the files to start from):```tsximport { AbsoluteFill, Composition, Sequence, interpolate, registerRoot, useCurrentFrame } from "raea";function Card({ text }: { text: string }) {const f = useCurrentFrame();- return (- <AbsoluteFill style={{ background: "#000", color: "#fff", justifyContent: "center", alignItems: "center", fontSize: 96 }}>- <span style={{ opacity: interpolate(f, [0, 12], [0, 1], { extrapolateLeft: "clamp", extrapolateRight: "clamp" }) }}>{text}</span>- </AbsoluteFill>- );-}--function Piece() {- return (- <>- <Sequence from={0} durationInFrames={45}><Card text="One" /></Sequence>- <Sequence from={45} durationInFrames={45}><Card text="Two" /></Sequence>- </>- );+ const opacity = interpolate(f, [0, 12], [0, 1], { extrapolateLeft: "clamp", extrapolateRight: "clamp" });+ return <AbsoluteFill style={{ background: "#000", color: "#fff", justifyContent: "center", alignItems: "center", fontSize: 96 }}><span style={{ opacity }}>{text}</span></AbsoluteFill>;}-registerRoot(() => <Composition id="piece" component={Piece} width={1080} height={1920} fps={30} durationInFrames={90} />);+registerRoot(() => (+ <Composition id="piece" width={1080} height={1920} fps={30} durationInFrames={90} component={() => (+ <><Sequence from={0} durationInFrames={45}><Card text="One" /></Sequence><Sequence from={45} durationInFrames={45}><Card text="Two" /></Sequence></>+ )} />+));```-Rules that keep renders right (`raea guide motion` has all ten, under "The core rules"; these are the ones every-file needs):+Rules that keep renders right (`raea guide motion` has all ten, under "The core rules"; every file needs these):- **Frame-pure.** Everything that moves reads `useCurrentFrame()`; `useState`, `useEffect` and timers don't animate a- render. `Math.random()` is seeded for each frame (new numbers every frame, the same on every render), so seed what- should hold still from an index; `Date` is the frame's time.-- **Clamp every interpolate.** Pass `{extrapolateLeft: "clamp", extrapolateRight: "clamp"}` unless you mean the line- to run on past its ends.-- **Cue on words, not on guessed frames.** `word("phrase")` returns the frame where the phrase is said (`raea render`- passes the cut's words.json), so cues follow the words if the cut moves.-- Footage: `<Video src=...>` and `<Audio src=...>`.-- Games: keep state in `useGameState(initial, step)`, where `step(state, input, frame)` is pure; read keys with- `useInput()`. The game plays live and renders from a logged play to the same pixels.-- Brand and Tailwind: put the kit's `--brand-*` variables in `brand/brand.css`, `import { css } from "./styles.gen"`- and render `<style>{css}</style>` once. `raea render` (and `play`, `bundle`) writes `styles.gen.ts` beside- the composition from brand.css and the Tailwind classes your files use (`bg-brand-bg`, `text-brand-accent`,- `font-brand`, plus all of Tailwind's own).-- Fonts: a face this Mac doesn't have goes in `media/fonts/`, declared with `@font-face { font-family: "Sohne";- font-weight: 600; src: url("/media/fonts/Sohne-600.woff2"); }` (in brand.css or a `<style>`; `staticFile("fonts/...")`- gives the same path). woff2, woff, ttf and otf load; a `data:` URL works too. Google Fonts families load by name.-- Counters: `<Animate enter={tick({ to: 9130, separator: true, prefix: "$", suffix: "\u00a0pts" })} at={30} />` is- hidden until its `at`. In JSX, `\u` escapes work only inside braces: `unit={"\u00a0pts"}`, never `unit="\u00a0pts"`.-- 3D: Bevy's names (Camera3d, Mesh3d, StandardMaterial, the lights) from `raea/camera`, `raea/mesh`, `raea/pbr`, `raea/light`, or `raea/prelude`. Read the raea-bevy skill (`sdk/skills/raea-bevy/SKILL.md`) first;- its "modules, in the order a frame is made" maps every Bevy-named module (sources, evaluate, compose, render, output).-- 3D in footage (matchmove): `raea track clip.mp4 --subject X,Y,W,H` solves the clip's camera once (COLMAP,- kept in the asset store; check the APPLIED line's registered frames and error, and its notes for a rotation-only- fallback). Then `<Matchmove src={staticFile("clip.mp4")} subject={[x, y, w, h]} crop={0.4}>` with 3D children draws- the footage, follows its camera and keeps the subject in front. Its world is metres, ground at y = 0, frame 0 looking- down -Z; `crop` places a 9:16 window on 16:9 footage.-- Sound: music in Tone.js (`import * as Tone from "raea/tone"`): instruments in a `Tone.Sampler` playing a- `Part` or `Sequence`, their notes from `Tone.tokensynth("a warm upright bass", ["C2", "C3", "C4"])` (TokenSynth, on- this Mac) or from an open sample library (`raea sounds`); foley with `sao("prompt", { seconds })` in an- `<Audio>` (Stable Audio Open, on this Mac); narration with `fish("words")`. One `<Mix lufs={-14} />` masters it.- Both local models install themselves on first use. No generated images or video.-- Music-led pieces: before cutting anything to a song, run `raea song FILE --plot FILE.song.png` and look at- the plot. Time every cut, slam and move from the map's beats, downbeats and events (`useSong`, `song(map).cutsAt()`),- never from a constant BPM: a tempo times bar count drifts off the real beats within a minute, and it can't see a- build, a stop or a drop.-- Music SOP: a library instrument first; a TokenSynth instrument is curated, not trusted (several seeds a root, roots- 3-4 semitones apart, `tools/tokensynth/curate.py` picks the clean takes); under a voice, write a sparse drone score,- not genre pastiche. Read `raea guide music` ("Instruments from TokenSynth", "Writing music for picture")- before scoring anything. A drum kit from `raea sounds kick` / `hihat` / `rimshot` goes on `Tone.buses.music`- (what `sounds get` prints for drums); `Tone.buses.sfx` is for hits on the picture.--## npm packages and React libraries--What works today. The "not yet" list is the gaps: when one is built, delete its line here.--- Packages: `raea add @assistant-ui/react` (also `add PKG@RANGE`, `--dev`, `remove NAME`, `install`,- `install --offline`, `--in DIR`) writes `package.json` and `raea.lock` and lays out `node_modules`. raea's own package- manager does it; no Node, npm or bun is needed, and install scripts never run.-- A React library that needs a real DOM (assistant-ui, Radix, shadcn) runs as an app: a module whose default export is- a component taking `{ width, height }`, running on real react-dom in a document of its own. Place it:- - on a screen in 3D: `<Screen name="chat" app="chat.tsx" resolution={[480, 640]} crt={false} />` (beside the 3D, or- as a Model's `screens` entry). The path is relative to the composition's folder;- - as an app panel or tool: `export const surface = "dom"` in the panel's file.-- Input in live play: the pointer reaches an app screen through the 3D (where it lands on the picture). Pressing on the- screen gives it the keys, and the game gets none until a press elsewhere or Escape.-- Renders: an app runs on the frame clock (timers, `Date`, `performance.now`, `requestAnimationFrame` follow the frame),- so a render repeats frame for frame.-- Exported games: `export-game` bundles each app with its packages. The player must be built with them:- `cargo build --profile game -p raea-app-game --bin raea-game --features player,surfaces` (+6.7 MB); export refuses- an app screen with a player built without.--Not yet:-- An app as a flat 2D layer of a composition. It can be a 3D `<Screen>` or an app panel only; for a flat look, put a- `crt={false}` screen square to the camera.-- A composition itself importing a DOM library. Only an app (above) can; the composition's own React is raea's lite- runtime.-- Input to an app in a render: `render --input` replays the page's input, but an app screen gets none. Script what it- should show inside the app, on its own timers.-- Anything in front of a screen blocking its clicks: the ray hits the nearest screen, through other objects. It also- assumes the 3D fills the stage.-- Network calls in an app during a render: nothing records and replays them, so a render that calls a model doesn't- repeat. Keep renders offline.-- Packages that need Node (`fs`, `child_process`, native addons, postinstall steps), and `git:`, `file:` and `link:`- dependencies. Browser-only packages work.-- A package's own `.css` imports and Tailwind inside an app are untested; style with style objects until they are.--## Render and check--```sh-raea render piece.tsx -o piece.mp4 # the whole composition-raea render piece.tsx --frame 60 -o frame60.png # one frame, to look at-raea render piece.tsx --at 0,45,89 -o frames/ # a few frames-raea render piece.tsx --quality master -o piece.mp4 # a final export: constant quality-raea play game.tsx --input # play a game live-```--A video's bitrate follows its size and frame rate (about 20 Mbit/s at 1080p30, 80 at 4K30; VideoToolbox spends less on-flat pictures), and `--kbps N` sets it. `--quality draft|high|master` (or 0..1: 0.6, 0.85, 0.95) asks for constant-quality instead, each frame getting the bits it needs: `master` keeps thin type and hard vector edges clean at 4K-(about 31 Mbit/s on flat motion graphics), so a final motion-graphics export needs no PNG folder through x264.--Sound from the command line, through the same cache the composition's render uses (run them in the composition's-folder, or pass `--dir`):+ render. `Math.random()` is seeded per frame, so seed what should hold still from an index.+- **Clamp every interpolate.** Do it unless you mean the line to run on past its ends.+- **Cue on words, not on guessed frames.** `word("phrase")` is the frame where it's said, so cues follow the cut.+- Footage: `<Video>` and `<Audio>`. Games: `useGameState(initial, step)` with a pure `step`, keys from `useInput()`.+- Brand: the kit's `--brand-*` variables in `brand/brand.css` (`raea brand DOMAIN` reads them from a site), then+ `import { css } from "./styles.gen"` and Tailwind classes like `bg-brand-bg`.+- 3D: read the raea-bevy skill first; an asset to fix first (scale, pivot, FBX to .glb) goes through Blender+ (`raea setup blender`, then `raea guide bevy/blender`).+- Sound: `raea guide sound` and `raea guide music`; to cut to a song, run `raea song FILE --plot FILE.song.png` and+ time cuts from its map, never a constant BPM. npm packages and React apps: `raea guide apps`.+- Generated media: `raea guide gen` before the first `raea gen`.++`raea check --quick piece.tsx` checks three stills' text (clipped, cramped, safe areas) in about a second: run it+after each save when no hook does. Then render, and look before you call it done:```sh-raea sao "deep punchy impact hit, tight" --seconds 1.2 -o hit.wav # foley (Stable Audio Open)-raea tokensynth "a soft wooden marimba" --notes C3,C4,C5 -o marimba/ # an instrument's notes (TokenSynth)-raea sounds piano # open sample libraries-raea sounds get salamander/piano --notes C3,C4,C5 # into media/sounds/, with its Sampler-raea setup-audio # install both local models now-raea song song.wav --plot song.song.png # the song's energy map (song.song.json)+raea render piece.tsx --at 0,45,89 -o frames/ # stills to look at: text fits, nothing overlaps+raea render piece.tsx --alpha -o frames/ # transparent PNGs, for an overlay in another editor+raea render piece.tsx -o out/piece.mp4 --manifest out/render.json+raea check out/piece.mp4 --manifest out/render.json --taste ~/.raea/taste/taste.ts -o out/piece.check.json # P0-P3; exits 1 on a P0 or P1```-`song` runs `raea-perceive` (installed beside raea in `~/.raea/bin`; from a checkout, `cargo build --release--p raea-perceive`, or set `RAEA_PERCEIVE`) and its beat model, which the install ships.+`raea guide rendering` covers stills, the check, bitrate and quality; `raea guide rubric` covers judging the rest.-To cut to a song, map it first: `raea song` finds beats, bars, sections (the file's `[Section]` lyrics markers-when it has them), builds, drops, stops (the beat dropping out, with its hits), hits and dips, and a cut rate per-section. Look at the plot, then pace with it: `import map from "./song.song.json"`, `useSong(map)` for the frame's-beat, energy, section, `inBuild`/`buildProgress` and `untilDrop`, and `song(map, { fps }).cutsAt()` for the frames to-cut on. Hold through low sections, cut faster through a build, smash-cut on the drop, cut on a stop's hits.+## 5. Show it and read the notes — PAGE, PERSON+<!-- sources: sdk/skills/raea/reference/feed.md -->-Look at the frames you rendered before you call the work done: check text fits, nothing overlaps, and cues land-where the transcript says. Then measure the export against the floor:+- In the raea app, post the render to the project's feed with `feed_post` (a watch, look, listen or play item); the+ person watches, plays and leaves notes on it there (PERSON). `feed_items` reads the items and their notes.+- Headless instead: leave the file in the project's `out/`, give the person its path, and take their notes as text.+- Every note, from the feed or as text, gets a move before any edit: pick the one it asks for (quieter, bolder,+ distill, clarify, retime, recut, regrade, remix, harden, layout, typeset, animate, delight, adapt, optimize, extract,+ generate, polish, critique) on the part or moment it names, and run `raea guide MOVE` before you touch the+ composition. Answer in their words, and never name the move to them.-```sh-raea render piece.tsx -o piece.mp4 --manifest render.json-raea check piece.mp4 --manifest render.json --words words.json [--platform tiktok|reels|shorts] [--taste ~/.raea/taste] [-o check.json]-```+## 6. The next version — HEADLESS, then PAGE+<!-- sources: sdk/skills/raea/reference/feed.md -->-It ranks what it finds P0 to P3 (clipped text, text under a platform's buttons, captions too brief to read, caption-contrast, frozen stretches, cues off their words, loudness, blotching in the darks) and exits 1 while a P0 or P1-stands. `--taste` adds the person's own mechanical rules, the `## Checks` lines of their taste briefs (`- text-above-54%: Text sits well clear of the bottom of the frame.`), each a P1 when broken. Fix those before anyone sees it. To judge the rest (the open, the point, the pacing, the sound), read-`raea guide rubric`: it lists the questions a critique asks for each mode and how answers become ranks. Blotching in-dark areas is the encoder, not the composition: export dark material as PNG frames (`RAEA_READBACK=rgba raea render-piece.tsx -o frames/`) and encode them with more bits for the darks.+- Change the composition under the person's hand edits (the `edit` segments and `<Nudge>` props the app writes; see+ `raea guide rendering`), render again and check again.+- Render each version to a new file beside the old (`piece-v2.mp4`), never over it: the earlier version stays+ watchable. In the app, post it with `feed_post` naming the item it `replaces`, so the feed keeps both as versions.-A person's hand edit in the raea app comes back as props, so keep them when you revise: `<Composition ... edit={{ segments:-[[0, 412], [430, 3285]] }}>` plays those frame ranges of the composition one after another (a trim, a split, a cut-word), and `<Nudge x={0} y={-156}>` around an element moves it by those px. Edit the composition under them; change-the segments only when the cut itself should change.+## 7. Deliver — HEADLESS+<!-- sources: runtime/export/src -->-## Deliver--- Name exported files with lowercase letters, digits and hyphens only (`tag-adnanna.mp4`): no `@`, `#`, spaces or- other sigils. Messages, mail and some uploaders refuse or mangle names with them.-- A render is already a standard file (H.264 High, yuv420p, AAC). It is large, though (its bitrate: see Render and- check), so hand over a share copy as well, small enough to text:- `ffmpeg -i film.mp4 -c:v libx264 -preset slow -crf 23 -maxrate 2600k -bufsize 5200k -pix_fmt yuv420p -c:a aac -b:a 128k -movflags +faststart film-share.mp4`- (about 1 MB for every 4 seconds).+- Final exports: `--quality master` for motion graphics and type; name files with lowercase letters, digits and+ hyphens only (`spring-launch-9x16.mp4`).+- A render is a standard file (H.264 High, yuv420p, AAC) but large; hand over a share copy too:+ `ffmpeg -i film.mp4 -c:v libx264 -preset slow -crf 23 -maxrate 2600k -bufsize 5200k -pix_fmt yuv420p -c:a aac -b:a 128k -movflags +faststart film-share.mp4`.+- Deliver to the controllers' specs (sizes, platforms, loudness) when the workspace sets them.## Go further-Paths here are relative to the root of the raea repository.--- Writing guides (pacing, captions, layout, sound, games, 3D): `raea guide` lists them and- `raea guide NAME` prints one (`motion` first, then `animating`, `layout`, `brand`, `music`, `sound` and the- rest; `bevy` and `bevy/NAME` for 3D). They ship with the install; in the repository they're under `sdk/guides/craft`.-- The SDK's behaviour: `sdk/raea/spec/motion.feature`; what 3D reaches: `sdk/raea/docs/bevy-coverage.md`.+- The guides: `raea guide` lists them; `raea guide NAME` prints one (`motion` first; `bevy` and `bevy/NAME` for 3D).+- The SDK's behaviour: `sdk/raea/spec/motion.feature`; what 3D reaches: `raea guide coverage`.diff --git a/sdk/skills/raea/reference/app.md b/sdk/skills/raea/reference/app.mdnew file mode 100644index 00000000..3b8b5d3b--- /dev/null+++ b/sdk/skills/raea/reference/app.md@@ -0,0 +1,44 @@+<!-- generated by tools/skills.sh gen; do not edit -->++# The app's window over MCP++The raea app's window (raea-page-host, `raea-window` inside raea.app) can serve an MCP server on+`http://127.0.0.1:PORT/mcp`: Streamable HTTP, JSON answers. It is how an agent drives the app as a person would and sees+what they see: real input events, the interface's elements with their `data-testid`s, the window as a PNG, and any Bevy+Remote Protocol method. Access: HOST. The packaged app serves it only when started with RAEA_PAGE_MCP_PORT set+(tools/raea-app/launch.sh; RAEA_APP_HEADLESS=1 runs it with no window, as its own checks do); a page host started by+hand serves 7477 unless RAEA_PAGE_MCP_PORT says otherwise (0: none). The conformance suite (sdk/ui/conformance) drives+the app through `input` and `ui`.++## input++One input event in window points, posted as the window gets it (the messages winit writes, picking and focus see them as real): move {x,y}; down/up {x,y,button,clicks}; leave; wheel {x,y,dy,dx?,unit: pixel|line,phase?}; key {key, mods, state?: down|up} (no state: down then up); text {text}; ime {marked?, commit?}; resize {w,h}. Returns {frame}: the frame it landed before (the first frame that saw it).++## ui++The interface as presented in the latest frame: {frame, window: {w,h}, nodes: [{id, role, name, rect: {x,y,w,h} (window points), visible, hovered, focused, pressed, selected, value, scroll?: {top, max}, text?}]}, one per element with a data-testid.++## frame_png++The composited window as a PNG (the render target read back from the GPU).++## state++The app's state: frame, window, scale, and what the app adds.++## actions++The page's actions, as it names them (its emit("actions", ...)): [{name, about, args}].++## action++Runs one of the page's actions as a click there would: {name, args?}. Returns what it returned.++## brp++Any Bevy Remote Protocol method on the running app, by name: Bevy's own (world.query, world.get_components, world.insert_components, world.mutate_components, world.get_resources, world.write_message, world.trigger_event, registry.schema, schedule.list, schedule.graph, ...), the host's (page.*) and any plugin's. A +watch method answers with its first result. See brp_methods.++## brp_methods++The Bevy Remote Protocol methods this app answers (rpc.discover): [name].+diff --git a/sdk/skills/raea/reference/cli.md b/sdk/skills/raea/reference/cli.mdnew file mode 100644index 00000000..ee7b5513--- /dev/null+++ b/sdk/skills/raea/reference/cli.md@@ -0,0 +1,392 @@+<!-- generated by tools/skills.sh gen; do not edit -->++# raea CLI++Every verb `raea help` lists, with its forms, its flags (and how many values follow each) and where it runs:+HEADLESS needs nothing running; HOST needs the raea app's host; PERSON waits on a click. A verb refuses a flag+or an argument its usage doesn't name, so these lists are what it takes.++## raea render++Access: HEADLESS. Arguments besides flags: 1.++```+raea render EDIT.tsx -o OUT.mp4|OUT.png|DIR [--frame N | --at A,B] [--composition ID] [--w W] [--h H] [--fps FPS] [--frames N] [--words W.json] [--perception P.json] [--input I.json|inputs.rrl] [--manifest render.json] [--stage WxH] [--10bit] [--aov] [--alpha] [--kbps N | --quality draft|high|master|0..1] (also: --lite --comps)+raea render PAGE.html -o OUT.mp4|DIR [--at A,B] (an HTML composition, the HTML composition format format)+raea render --bundle NAME.comp.js -o OUT.png|DIR [--dir DIR] [--frame N] (a bundle from raea bundle, as render_bundle draws it)+```++Flags: `--10bit`, `--alpha`, `--aov`, `--at` (1), `--bundle` (1), `--composition` (1), `--comps`, `--dir` (1), `--fps` (1), `--frame` (1), `--frames` (1), `--h` (1), `--input` (1), `--kbps` (1), `--lite`, `--manifest` (1), `--perception` (1), `--quality` (1), `--stage` (1), `--w` (1), `--words` (1), `-o` (1).++## raea media++Access: HEADLESS. Its arguments go to a parser of its own: `raea media` alone lists them.++```+raea media probe|still|sheet|audio|loudness|motion|cuts|freezes|proxy|trim|concat FILE ... | ffmpeg ARGS | ffprobe ARGS (media work, native: media help)+```++## raea bundle++Access: HEADLESS. Arguments besides flags: 1.++```+raea bundle EDIT.tsx --composition-bundle -o OUT.js [--portable DIR] (a composition for render_bundle, on the Mac or the iPhone)+```++Flags: `--composition-bundle`, `--portable` (1), `-o` (1).++## raea add++Access: HEADLESS. Arguments besides flags: any number.++```+raea add PKG[@RANGE]... [--dev] | remove NAME... | install [--offline] [--in DIR] (npm packages for the project: raea.lock, node_modules)+```++Flags: `--dev`, `--in` (1), `--offline`.++## raea sao++Access: HEADLESS. Arguments besides flags: 1.++```+raea sao "PROMPT" [--seconds 2] [--seed 1] [--dir EDIT_DIR] [-o OUT.wav] (foley, local)+```++Flags: `--dir` (1), `--seconds` (1), `--seed` (1), `-o` (1).++## raea tokensynth++Access: HEADLESS. Arguments besides flags: 1.++```+raea tokensynth "TIMBRE" [--notes C2,C3,C4] [--seconds 2] [--velocity 100] [--seed 1234] [--precision fp16] [--dir EDIT_DIR] [-o OUT_DIR] (an instrument's notes, local)+```++Flags: `--dir` (1), `--notes` (1), `--precision` (1), `--seconds` (1), `--seed` (1), `--velocity` (1), `-o` (1).++## raea setup-audio++Access: HEADLESS. Arguments besides flags: 1.++```+raea setup-audio [--check] [sao|tokensynth] (install or check the local audio models)+```++Flags: `--check`.++## raea song++Access: HEADLESS. Arguments besides flags: 1.++```+raea song FILE [-o OUT.song.json] [--srt S.srt|none] [--plot OUT.png] [--size 2400x1350] (the song's energy map: beats, sections, builds, drops, stops, hits, cuts per bar; also: --backend NAME)+```++Flags: `--backend` (1), `--plot` (1), `--size` (1), `--srt` (1), `-o` (1).++## raea sounds++Access: HEADLESS. Arguments besides flags: 2.++```+raea sounds [WORDS] | sounds get PACK/INSTRUMENT [--notes ..|--all] [-o DIR] (open sample libraries for a Sampler)+```++Flags: `--all`, `--notes` (1), `-o` (1).++## raea track++Access: HEADLESS. Arguments besides flags: 1.++```+raea track CLIP.mp4 [--subject X,Y,W,H] [--from S] [--seconds N] [--height M] [--fov DEG] [--smooth F] [--dir EDIT_DIR] [-o OUT.json] (the clip's camera solved, for <Matchmove>)+```++Flags: `--dir` (1), `--fov` (1), `--from` (1), `--height` (1), `--seconds` (1), `--smooth` (1), `--subject` (1), `-o` (1).++## raea library++Access: HOST, then PERSON to add a folder. Arguments besides flags: any number.++```+raea library [new NAME [--cloud] | add LIBRARY PATH | files LIBRARY | tag SHA TAGS | status | scan ...] | raea library search "WORDS" [--library LIBRARY] [--kind KIND] [--limit N] [--sound] (the person's libraries in the raea app: folders and drives indexed on this machine, searched by meaning; a folder an agent adds waits for the person's yes)+```++Flags: `--cloud`, `--kind` (1), `--library` (1), `--limit` (1), `--sound`.++## raea spec++Access: HEADLESS. Arguments besides flags: 1.++```+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)+```++Flags: `--as` (1).++## raea workspace++Access: HEADLESS. Arguments besides flags: 2.++```+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, ~/Studio unless git config says)+```++Flags: `--json`, `--layout` (1), `--name` (1).++## raea project++Access: HEADLESS. Arguments besides flags: 2.++```+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)+```++Flags: `--json`, `--remote` (1), `--storage` (1).++## raea controller++Access: HEADLESS. Arguments besides flags: 3.++```+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)+```++Flags: `--by` (1), `--json`, `--project`.++## raea check++Access: HEADLESS. Arguments besides flags: 1.++```+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)+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, cues, loudness, blotching, a placeholder brand kit; P0-P3)+```++Flags: `--manifest` (1), `--perception` (1), `--platform` (1), `--quick`, `--shape` (1), `--taste` (1), `--words` (1), `-o` (1).++## raea hook++Access: HEADLESS. Arguments besides flags: 1.++```+raea hook claude (Claude Code's PostToolUse hook: the quick check after a composition is saved)+```++## raea next++Access: HEADLESS. Arguments besides flags: 1.++```+raea next [DIR] (the two or three useful next steps for the project, from its brief, compositions, renders and checks)+```++## raea doctor++Access: HEADLESS. Arguments besides flags: 1.++```+raea doctor [--fix] [DIR] (what doesn't match this raea: old brief files, an older workspace format, an agent's skill from another version)+```++Flags: `--fix`.++## raea skill++Access: HEADLESS. Arguments besides flags: 1.++```+raea skill [NAME] [--reference cli|feed|files|sdk] | raea skills install --agent claude|codex|kimi|gemini [--pin MOVE]... [--no-mcp] [--no-hooks] (the agent skill this raea ships, for its version, which raea --version prints: an agent whose copy names another version reads this; install puts raea's skills where that agent reads skills, adds the blender MCP server unless --no-mcp, makes each --pin MOVE a /MOVE of its own, and for claude adds the quick-check hook unless --no-hooks)+```++Flags: `--agent` (1), `--no-hooks`, `--no-mcp`, `--pin` (1), `--reference` (1).++## raea skills++Access: HEADLESS. Arguments besides flags: 1.++```+raea skill [NAME] [--reference cli|feed|files|sdk] | raea skills install --agent claude|codex|kimi|gemini [--pin MOVE]... [--no-mcp] [--no-hooks] (the agent skill this raea ships, for its version, which raea --version prints: an agent whose copy names another version reads this; install puts raea's skills where that agent reads skills, adds the blender MCP server unless --no-mcp, makes each --pin MOVE a /MOVE of its own, and for claude adds the quick-check hook unless --no-hooks)+```++Flags: `--agent` (1), `--no-hooks`, `--no-mcp`, `--pin` (1), `--reference` (1).++## raea setup++Access: HEADLESS. Arguments besides flags: 1.++```+raea setup blender [--check] [--download] (find Blender or download the LTS into ~/.raea/tools/blender, and install its MCP add-on)+```++Flags: `--check`, `--download`.++## raea blender++Access: HEADLESS. Its arguments go to a parser of its own: `raea blender` alone lists them.++```+raea blender run SCRIPT.py [ARGS...] (blender --background --python SCRIPT.py -- ARGS, headless)+```++## raea init++Access: HEADLESS. Arguments besides flags: 0.++```+raea init (a project's files where they're missing: edit.tsx, cuts.ts, components/, AGENTS.md)+```++## raea cut++Access: HEADLESS. Arguments besides flags: any number.++```+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)+```++Flags: `--append`, `--at` (1).++## raea frame++Access: HEADLESS. Arguments besides flags: 1.++```+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)+```++Flags: `--at` (1).++## raea part++Access: HEADLESS. Arguments besides flags: any number.++```+raea part list | raea part add NAME ... [--force] (a ready part copied into components/, yours to change)+```++Flags: `--force`.++## raea brand++Access: HEADLESS. Arguments besides flags: 1.++```+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)+```++## raea guide++Access: HEADLESS. Arguments besides flags: 1.++```+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)+```++## raea context++Access: HEADLESS. Arguments besides flags: 1.++```+raea context PROJECT (what to read before working on a project: taste, brief, look, the floor and its modes' guides)+```++## raea play++Access: HEADLESS. Arguments besides flags: 1.++```+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 --scrub N --baked --autoplay --no-vsync --master --3d)+```++Flags: `--3d`, `--autoplay`, `--baked`, `--input`, `--input-log` (1), `--input-script` (1), `--json` (1), `--master`, `--no-vsync`, `--offscreen`, `--scrub` (1), `--seconds` (1), `--seek` (2), `--size` (1), `--snapshot` (2).++## raea export-game++Access: HEADLESS. Arguments besides flags: 1.++```+raea export-game EDIT.tsx -o OUT [--target mac-app|mac-cli] [--name NAME] [--icon PNG] [--keys SETS] [--player BIN] [--no-strip] (a game as a program of its own: a Mac app or a command)+```++Flags: `--icon` (1), `--keys` (1), `--name` (1), `--no-strip`, `--player` (1), `--target` (1), `-o` (1).++## raea scene++Access: HEADLESS. Arguments besides flags: 2.++```+raea scene lint|explain|light EDIT.tsx [--composition ID] [--frame N] [--part NAME] [--json] (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)+```++Flags: `--composition` (1), `--frame` (1), `--json`, `--part` (1).++## raea physics++Access: HEADLESS. Its arguments go to a parser of its own: `raea physics` alone lists them.++```+raea physics bake REQUEST.json [-o OUT.json] | physics goo SPEC.json | physics part SRC.glb NODE... (the bakes <Physics> and <Goo> make)+```++Flags: `-o` (1).++## raea splat++Access: HEADLESS. Arguments besides flags: 2.++```+raea splat train VIDEO|IMAGE_DIR -o OUT.ply [--frames 150] [--steps 20000] [--max-res 1600] [--from S] [--seconds N] [--max-splats 2000000] [--matte none|black] [--match sequential|exhaustive] [--credit TEXT] [--license TEXT] [--dir EDIT_DIR]+raea splat setup (footage trained into a Gaussian splat for <Splat>; setup installs its tools)+```++Flags: `--credit` (1), `--dir` (1), `--frames` (1), `--from` (1), `--license` (1), `--match` (1), `--matte` (1), `--max-res` (1), `--max-splats` (1), `--seconds` (1), `--steps` (1), `-o` (1).++## raea run++Access: HEADLESS. Arguments besides flags: 1.++```+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)+```++Flags: `--timeout` (1).++## raea gen++Access: HEADLESS. Its arguments go to a parser of its own: `raea gen` alone lists them.++```+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)+```++## raea neural++Access: HEADLESS. Arguments besides flags: 2.++```+raea neural mlxdlss DIR -o OUT [--model M.dlssmodel] [--intensity X] [--profile P] [--skin-structure X] [--local-structure X] [--steady A] (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)+```++Flags: `--intensity` (1), `--local-structure` (1), `--model` (1), `--profile` (1), `--skin-structure` (1), `--steady` (1), `-o` (1).++## raea mezz++Access: HEADLESS. Arguments besides flags: any number.++```+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)+```++Flags: `--check`.++## raea traces++Access: HEADLESS. Arguments besides flags: 2.++```+raea traces [show [N|last|DIR]] (the sessions raea left, newest first: how each ended, its glitches; show tells one in full)+```+diff --git a/sdk/skills/raea/reference/feed.md b/sdk/skills/raea/reference/feed.mdnew file mode 100644index 00000000..d864203f--- /dev/null+++ b/sdk/skills/raea/reference/feed.md@@ -0,0 +1,163 @@+<!-- generated by tools/skills.sh gen; do not edit -->++# The feed's tools++The tools the raea app offers every agent it launches, as the MCP server `feed` (apps/app host/acp/feed-mcp.ts).+PAGE: the feed's page answers it, so the app must be open (or a windowless page); PERSON: a click finishes it.+With no page, use the CLI instead: `raea controller` for the controllers, `raea context .` for the brief.++## feed_post++Access: PAGE.++Post an item to the project's feed: a render to watch (.mp4), a still to look at (.png/.jpg), audio to listen to (.wav/.mp3/.m4a) or a game to play (its .tsx). The person sees it in the feed and leaves notes on it; a new version of an item names the one it replaces.++| input | | |+|---|---|---|+| `type` | required | watch, look, listen or play |+| `title` | required | what the person sees on the card |+| `file` | required | absolute path of the file to post |+| `replaces` | optional | the id of the item this is a new version of |+| `controls` | optional | play: the game's controls |++## feed_propose++Access: PAGE, then PERSON (accept).++Propose a planned item for the person to accept: what you would make next, before making it.++| input | | |+|---|---|---|+| `type` | required | string |+| `title` | required | the item you would make |+| `why` | optional | one line on why |++## feed_brief++Access: PAGE.++Read the project's brief as it stands now, as brief.ts (`export default brief({...})` from "raea/brief"): what to make, for whom, the one thing to believe, its deliverables and staged tasks.++No input.++## workspace_read++Access: PAGE (Chat only).++Read the workspace: its channels (id, name, logline), its agents, and its repo as raea keeps it (repo: its folder, layout, and each project's path, storage and id, from .raea/workspace). Workspace sessions (Chat) only.++No input.++## controllers_read++Access: PAGE.++Read the workspace's controllers: each controller's groups and fields with their paths (controller.group.field), types and values, as text and as JSON.++No input.++## controller_write++Access: PAGE.++Add a controller to the workspace, or replace the one with its id. A controller is { id?, title, help?, groups: [{ id?, title, help?, fields: [{ id?, label, help?, type, value, ... }] }] }; field types: toggle, choice (options), number (unit, min, max, step), text (placeholder, multiline), list, agents, channels, workflow (value: [{ name, by, back }], channels), servers, skills. The person sees it at once, and every agent works to it.++| input | | |+|---|---|---|+| `controller` | required | the controller, whole |++## controller_set++Access: PAGE.++Set one field's value by its path (controller.group.field), checked against its type.++| input | | |+|---|---|---|+| `path` | required | controller.group.field |+| `value` | required | the new value, of the field's type |++## controller_remove++Access: PAGE.++Remove a controller from the workspace.++| input | | |+|---|---|---|+| `id` | required | the controller's id |++## channel_create++Access: PAGE.++Make a channel (a client, a game, a show) from one sentence on what it is. Returns its id.++| input | | |+|---|---|---|+| `about` | required | one sentence on what the channel is |++## feed_items++Access: PAGE.++List the project's items, newest first: id, type, title, status, what each replaces, and the notes people left on it.++No input.++## whiteboard_read++Access: PAGE.++Read a whiteboard item: its plan (what you or another agent wrote) and every element on the board by id, with its text, the frame it's in, what an arrow joins, and by: plan or person (what people drew by hand).++| input | | |+|---|---|---|+| `board` | required | the whiteboard item's id |++## whiteboard_write++Access: PAGE.++Make a whiteboard (a plan, with no board) or change one (board plus a plan to replace its plan, or a patch). Say what is on it and how it's grouped; the feed lays it out, so never give positions. Sections become frames side by side: notes stacks cards, flow stacks them with arrows between, refs shows feed items' posters. People's own drawing on the board is kept.++| input | | |+|---|---|---|+| `board` | optional | the whiteboard to change; leave out to make a new one |+| `plan` | optional | the whole board |+| `patch` | optional | changes by id to the board's plan |++## flow_board++Access: PAGE.++Put a ComfyUI workflow (UI or API format JSON, for example one a raea gen flow ran) on a whiteboard in the feed: each node a card with its settings, links as arrows, groups as frames, input and output images beside their nodes. The workflow is copied into the project and stays the source of truth.++| input | | |+|---|---|---|+| `workflow` | required | absolute path of the workflow's .json on this machine |+| `title` | required | the board's title |++## flow_write++Access: PAGE.++Change a flow board's workflow (whiteboard_read shows its nodes and settings by name): settings' values, a node's mode (on, bypass, mute), and notes. The board is laid out again from it.++| input | | |+|---|---|---|+| `board` | required | the flow board's item id |+| `widgets` | optional | settings to change |+| `modes` | optional | array |+| `notes` | optional | a Note node's new text, or a new note (no node) |++## flow_run++Access: PAGE.++Run a flow board's workflow as it stands through raea gen (ComfyUI). Its outputs go on the board and into the feed as look items, each a new version of the last run's.++| input | | |+|---|---|---|+| `board` | required | the flow board's item id |+diff --git a/sdk/skills/raea/reference/files.md b/sdk/skills/raea/reference/files.mdnew file mode 100644index 00000000..ee1b7e5d--- /dev/null+++ b/sdk/skills/raea/reference/files.md@@ -0,0 +1,248 @@+<!-- generated by tools/skills.sh gen; do not edit -->++# Files++## A workspace and its project++What `raea workspace init Example` and then `raea project new Launch` make, under raea.root (`git config+--global raea.root`, else ~/Studio). The workspace is one git repo; media/ and out/ go to LFS.++```+example+ .gitattributes+ .raea+ workspace+ controllers+ .gitkeep+ projects+ .gitkeep+ launch+ .raea+ project+ AGENTS.md+ brand+ .gitkeep+ brief.ts+ media+ .gitkeep+ out+ .gitkeep+ taste.ts+```++## ~/.raea++The files and folders under ~/.raea that raea's CLI, its engine and the raea app keep, the environment variable+that moves each (when there is one) and the files that name them.++| path | moved by | named in |+|---|---|---|+| `~/.raea/Library/Caches` | | apps/app/host/acp/fence.ts |+| `~/.raea/account.json` | `RAEA_ACCOUNT` | apps/app/host/auth.ts |+| `~/.raea/actions.jsonl` | | io/shell/src/fs/mod.rs |+| `~/.raea/bin` | | io/assets/src/lib.rs, runtime/bundle/src/fresh.rs, runtime/page/src/faces.rs |+| `~/.raea/cache` | | apps/app/host/take.ts |+| `~/.raea/env` | `RAEA_ENV_FILE` | apps/app/host/director.ts, io/gen-core/src/fal.rs, io/gen-core/src/fish.rs, io/gen-core/src/made.rs, io/gen-core/src/modal.rs, io/gen-core/src/openrouter.rs, io/gen-core/src/replicate.rs, io/home/src/lib.rs |+| `~/.raea/evals/skills` | | apps/app/host/evals/skills.ts |+| `~/.raea/feed/media` | | apps/app/host/paths.ts |+| `~/.raea/library` | `RAEA_LIBRARY_HOME` | apps/app/host/library/local.ts |+| `~/.raea/library/granted.json` | `RAEA_LIBRARY_GRANTS` | apps/app/host/library/service.ts |+| `~/.raea/library/hashes.json` | `RAEA_LIBRARY_STATE` | apps/app/host/library/scan.ts |+| `~/.raea/library/requests.json` | `RAEA_LIBRARY_REQUESTS` | apps/app/host/library/service.ts |+| `~/.raea/models` | `RAEA_MODELS` | apps/app/host/library/embed.ts, apps/app/host/library/words.ts, io/provenance/src/mark.rs |+| `~/.raea/models/trustmark` | | io/provenance/src/mark.rs |+| `~/.raea/node.json` | `RAEA_NODE_FILE` | apps/app/host/link.ts, apps/app/host/reach.ts |+| `~/.raea/npm` | `RAEA_NPM_HOME` | io/npm/src/store.rs |+| `~/.raea/npm/store` | | io/npm/src/lib.rs, io/npm/src/store.rs |+| `~/.raea/objects` | | io/shell/src/fs/mod.rs |+| `~/.raea/onboarding.json` | `RAEA_ONBOARDING_FILE` | apps/app/host/onboard-account.ts, apps/app/host/onboard.ts |+| `~/.raea/publish/drive.json` | `RAEA_DRIVE_PICKS` | apps/app/host/publish-source.ts |+| `~/.raea/publish/ready.json` | `RAEA_PUBLISH_READY` | apps/app/host/publish-ready.ts |+| `~/.raea/sign-token` | | io/provenance/src/lib.rs, io/provenance/src/main.rs |+| `~/.raea/taste` | `RAEA_TASTE` | apps/app/host/taste.ts, engine/cli/src/guide.rs, engine/cli/src/spec.rs |+| `~/.raea/taste/corrections.jsonl` | | apps/app/host/taste.ts |+| `~/.raea/taste/taste.ts` | | engine/cli/src/guide.rs |+| `~/.raea/update` | `RAEA_UPDATE_DIR` | apps/app/host/onboard.ts, apps/app/host/update.ts |++## The spec files++Each spec's fields, as raea/brief's types (sdk/raea/src/brief.gen.ts, generated from the schemas in core/brief that+`raea spec` checks against): brief.ts is a Brief, NAME.script.ts a Script, taste.ts a Taste, plan.ts a Plan and+controllers/ID.ts a Controller. A field marked ? may be left out.++```ts+export type Brief = { title: string, logline?: string,+/**+ * who the work is for (a person or a client)+ */+for?: string,+/**+ * YYYY-MM-DD+ */+due?: string,+/**+ * who watches or plays it, and where+ */+audience?: string,+/**+ * the one thing they should think afterwards+ */+believe?: string,+/**+ * pitch, explain, story, play, tool: an open set, one guide each; a piece can mix two+ */+mode?: Array<string>,+/**+ * the narrator and the tone+ */+voice?: string, sound?: string,+/**+ * the project's committed world: palette by role, type, camera language, light, references+ */+look?: string,+/**+ * the anti-goals+ */+notDoing?: Array<string>,+/**+ * facts an agent wrote and the person hasn't confirmed, by key ("voice", "audience")+ */+assumed?: Array<string>,+/**+ * prose sections beyond the fields above (Goal, Background), in order+ */+sections?: Array<Section>, deliver?: Array<Deliverable>, references?: Array<Reference>,+/**+ * the tasks, in stages ("Act one", "The cut")+ */+stages?: Array<Stage>, agents?: Array<Agent>, };+export type Section = { heading: string, text: string, };+export type Deliverable = { name: string,+/**+ * "90 s", "16:9", "with sound"+ */+specs?: Array<string>,+/**+ * the feed item it lands as+ */+item?: string,+/**+ * its own brief module, when it differs from the project in mode, look or audience+ */+brief?: string,+/**+ * its script module (storyboard or screenplay)+ */+script?: string, };+export type Reference = { target: string, note?: string, };+export type Stage = { name: string, tasks: Array<Task>, };+export type Mark = "todo" | "done" | "dropped";+export type Task = { text: string,+/**+ * a task linked to an item takes the item's state (the work is the truth); this is for unlinked ones+ */+mark?: Mark, agents?: Array<string>, item?: string, tags?: Array<string>, due?: string,+/**+ * the craft verb it was written as ("quieter"): agents read it, the page shows the text+ */+verb?: string, };+export type Agent = { name: string, role?: string, };+export type Script = { title: string, logline?: string, scenes: Array<Scene>, };+export type Scene = {+/**+ * where and when ("INT. SENATE - NIGHT", or "The brief page")+ */+heading?: string, beats: Array<Beat>,+/**+ * what the scene must land+ */+payoff?: string, };+export type Beat = {+/**+ * what's seen (a screenplay's action)+ */+onScreen: string,+/**+ * the move ("push in on the knife", "orbit left, keeps moving through the cut")+ */+camera?: string,+/**+ * how this beat is cut into ("match on motion", "hard cut")+ */+cut?: string, lines?: Array<Line>,+/**+ * sound and music cues ("strings drop out", "the theme's second hit")+ */+cues?: Array<string>, seconds?: number,+/**+ * the word the beat cuts on, so a new take keeps the cut in sync with the transcript+ */+onWord?: string, };+export type Line = {+/**+ * a character, or "narrator"+ */+who: string, says: string,+/**+ * a screenplay's parenthetical ("quietly")+ */+how?: string, };+export type Taste = { title: string,+/**+ * when this file is read ("Read for pitch, explain and story")+ */+note?: string, for?: string,+/**+ * the kinds of work with their own taste file (motion, games, sound, ui)+ */+kinds?: Array<string>, sections: Array<TasteSection>, };+export type TasteSection = {+/**+ * "Always", "Never", "Camera"+ */+heading: string, rules: Array<Rule>, };+export type Rule = { text: string, check?: Check, };+export type Check = { "form": "text-hold", "value": number } | { "form": "text-above", "value": number } | { "form": "text-below", "value": number } | { "form": "text-margin", "value": number } | { "form": "loudness", "value": number } | { "form": "still-max", "value": number };+export type Plan = { concept: Concept,+/**+ * by name; the build's parts are typed from these keys, so a planned part the build skips is a tsc error+ */+parts: { [key in string]: Part }, };+export type Concept = {+/**+ * what it is ("flight feather", "toy rocking horse")+ */+what: string, style: string,+/**+ * its largest extent, in metres+ */+size: number,+/**+ * how close it's seen, in metres: sets how much detail up close must hold+ */+seenFrom: number, material?: string, use?: string, };+export type Level = "primary" | "secondary" | "tertiary";+export type Count = number | { min: number, max: number, };+export type Part = {+/**+ * the label it carries into the world ("seat", "leaf", "gem")+ */+role: string, level: Level,+/**+ * the part it sits on or in; none for the root+ */+parent?: string, count?: Count,+/**+ * its own, else its parent's, else the concept's+ */+material?: string, style?: string,+/**+ * what a near crop of it must show+ */+near?: string, };+export type Controller = { id: string, title: string, help?: string, groups: Array<Group>, };+export type Group = { id: string, title: string, help?: string, fields: Array<Field>, };+export type Field = { id: string, label: string, help?: string, } & ({ "type": "toggle", value: boolean, } | { "type": "choice", options: Array<string>, value: string, } | { "type": "number", value: number, unit?: string, min?: number, max?: number, step?: number, } | { "type": "text", value: string, placeholder?: string, multiline?: boolean, } | { "type": "list", value: Array<string>, placeholder?: string, } | { "type": "agents", value: Array<string>, } | { "type": "channels", value: Array<string>, } | { "type": "workflow", value: Array<Step>, channels?: Array<string>, } | { "type": "servers", value: Array<string>, } | { "type": "skills", value: Array<string>, });+export type Kind = { "type": "toggle", value: boolean, } | { "type": "choice", options: Array<string>, value: string, } | { "type": "number", value: number, unit?: string, min?: number, max?: number, step?: number, } | { "type": "text", value: string, placeholder?: string, multiline?: boolean, } | { "type": "list", value: Array<string>, placeholder?: string, } | { "type": "agents", value: Array<string>, } | { "type": "channels", value: Array<string>, } | { "type": "workflow", value: Array<Step>, channels?: Array<string>, } | { "type": "servers", value: Array<string>, } | { "type": "skills", value: Array<string>, };+export type Step = { name: string, by?: string, back?: string, };+```diff --git a/sdk/skills/raea/reference/sdk.md b/sdk/skills/raea/reference/sdk.mdnew file mode 100644index 00000000..e7c3529c--- /dev/null+++ b/sdk/skills/raea/reference/sdk.md@@ -0,0 +1,107 @@+<!-- generated by tools/skills.sh gen; do not edit -->++# The raea SDK++What each import gives a composition, a game or a spec (values only; their types come along). Components start+with a capital, hooks with `use`. A component's props are in its file.++## `raea` (sdk/raea/src/index.tsx)++`ACTION_KEY`, `AbsoluteFill`, `Animate`, `Audio`, `Clock`, `Composition`, `Easing`, `FEED_KEY`, `Freeze`, `Img`, `InputRegion`, `Loop`, `MEDIA_ROOT`, `Mix`, `Nudge`, `Overlay`, `Region`, `SPACE_KEY`, `Sequence`, `Series`, `SongPlot`, `Stagger`, `Video`, `actionsIn`, `applyActions`, `curve`, `curveFn`, `delay`, `fade`, `feedIn`, `fill`, `findPhrase`, `firstDecider`, `fish`, `getCompositions`, `gridDelay`, `inState`, `interpolate`, `isGeneratedAsset`, `keyEdges`, `lyria`, `machine`, `measureSpring`, `move`, `moves`, `overlays`, `parallel`, `pop`, `proofBoxes`, `propsFingerprint`, `pushIn`, `regionBand`, `registerRoot`, `replayDecider`, `reverse`, `rise`, `sampleAnimation`, `sao`, `sequence`, `sequenceGap`, `slam`, `slide`, `song`, `songAt`, `spring`, `stagger`, `stateOf`, `staticFile`, `stepAll`, `strike`, `tick`, `timeline`, `toMove`, `track`, `transitionOf`, `useCurrentFrame`, `useGameEvents`, `useGameState`, `useInput`, `useRegion`, `useSong`, `useVideoConfig`, `useWords`, `wipe`, `word`++## `raea/3d` (sdk/raea/src/3d.tsx)++`Body`, `Echoes`, `Goo`, `MeshSequence`, `Part`, `Physics`, `ZFight`, `about`, `bodyPose`, `gooSpec`, `hash01`, `lastBeat`, `part`, `physicsRequest`, `quatAxis`, `quatMul`, `snapPose`, `teleport`, `useBake`, `useGoo`, `usePhysics`++## `raea/animation` (sdk/raea/src/animation.ts)++`clipEvents`++## `raea/app` (sdk/raea/src/app.ts)++`App`, `BevyApp`, `First`, `FixedFirst`, `FixedLast`, `FixedPostUpdate`, `FixedPreUpdate`, `FixedUpdate`, `Last`, `PluginGroup`, `PostStartup`, `PostUpdate`, `PreStartup`, `PreUpdate`, `RunFixedMainLoop`, `SpawnScene`, `Startup`, `StateTransition`, `Update`, `conditions`, `definePlugin`++## `raea/asset` (sdk/raea/src/asset.ts)++`MEDIA_ROOT`, `staticFile`++## `raea/audio` (sdk/raea/src/audio.ts)++`Audio`, `Tone`, `music`++## `raea/brief` (sdk/raea/src/brief.ts)++`brief`, `controller`, `plan`, `script`, `taste`++## `raea/camera` (sdk/raea/src/camera.ts)++`Camera3d`, `Canvas3D`, `Matchmove`, `OrthographicCamera`, `PerspectiveCamera`, `TextureView`, `checkMatchmove`, `matchmoveIndex`, `matchmoveView`, `useMatchmove`++## `raea/color` (sdk/raea/src/color.ts)++`LinearRgba`, `Srgba`, `kelvin`, `toHex`++## `raea/gizmos` (sdk/raea/src/gizmos.ts)++`Gizmo`++## `raea/image` (sdk/raea/src/image.ts)++`ImagePlane`, `Img`, `Plate`++## `raea/input` (sdk/raea/src/input.ts)++`keyEdges`, `useInput`, `wireKeys`++## `raea/light` (sdk/raea/src/light.ts)++`AmbientLight`, `Atmosphere`, `DirectionalLight`, `Environment`, `GlobalAmbientLight`, `Pathtracer`, `PointLight`, `RectLight`, `Shadows`, `SolariLighting`, `SpotLight`++## `raea/math` (sdk/raea/src/math.ts)++`Affine2`, `curve`, `curveFn`, `hash01`, `quatAxis`, `quatMul`++## `raea/mesh` (sdk/raea/src/mesh.ts)++`BufferMesh`, `Capsule`, `Capsule3d`, `Cone`, `ConicalFrustum`, `Cuboid`, `Cylinder`, `Mesh`, `Mesh2d`, `Mesh3d`, `MeshSequence`, `Plane3d`, `Sphere`, `Torus`++## `raea/pbr` (sdk/raea/src/pbr.ts)++`AmbientOcclusion`, `Decal`, `ExtendedMaterial`, `Fire`, `Fog`, `FogVolume`, `GridExtension`, `MeshBasicMaterial`, `MeshPhysicalMaterial`, `MeshStandardMaterial`, `MeshToonMaterial`, `PaintExtension`, `Refinish`, `ShaderExtension`, `ShaderMesh`, `StandardMaterial`, `SurfaceShader`, `ToonExtension`, `ToonMaterial`, `VolumetricFog`, `WearExtension`++## `raea/post_process` (sdk/raea/src/post_process.ts)++`AntiAliasing`, `Bloom`, `Compute`, `DepthOfField`, `Fisheye`, `FramePass`, `Grade`, `LensDistortion`, `Look`, `MotionBlur`, `Outline`, `ToneMapping`++## `raea/remote` (sdk/raea/src/remote.ts)++`BevyApp`++## `raea/sprite` (sdk/raea/src/sprite.ts)++`Circle`, `ColorMaterial`, `Ellipse`, `Mesh2d`, `Rectangle`, `RegularPolygon`, `Shape2D`, `Sprite`++## `raea/state` (sdk/raea/src/state.ts)++`stepAll`, `useGameEvents`, `useGameState`++## `raea/text` (sdk/raea/src/text.ts)++`RichText`, `Span`, `Text3D`++## `raea/time` (sdk/raea/src/time.ts)++`Clock`, `useCurrentFrame`, `useLocalTime`, `useVideoConfig`++## `raea/transform` (sdk/raea/src/transform.ts)++`Group`, `Quat`, `Transform`, `eulerOf`, `surfaceTurn`++## `raea/ui` (sdk/raea/src/ui.ts)++`AbsoluteFill`++## `raea/video` (sdk/raea/src/video.ts)++`Freeze`, `Loop`, `Sequence`, `Series`, `Video`+diff --git a/sdk/tsconfig.base.json b/sdk/tsconfig.base.jsonindex f8d52381..fe4b07f0 100644--- a/sdk/tsconfig.base.json+++ b/sdk/tsconfig.base.json@@ -16,6 +16,7 @@"raea/bevy": ["./app/src/bevy.ts"],"raea/bevy-own": ["./render/src/bevy-own.gen.tsx"],"raea/bevy3d": ["./render/src/bevy3d.tsx"],+ "raea/body": ["./body/src/index.ts"],"raea/character": ["./character/src/character.tsx"],"raea/clip": ["./character/src/clip.ts"],"raea/clock": ["./app/src/clock.tsx"],@@ -28,6 +29,7 @@"raea/feet": ["./character/src/feet.ts"],"raea/glb": ["./asset/src/glb.ts"],"raea/games": ["./app/src/games.ts"],+ "raea/gen": ["./gen/src/index.ts"],"raea/grasp": ["./character/src/grasp.ts"],"raea/interpolate": ["./math/src/interpolate.ts"],"raea/items": ["./character/src/items.ts"],@@ -45,6 +47,7 @@"raea/paint": ["./render/src/paint.tsx"],"raea/panel": ["./video/src/panel.ts"],"raea/physics": ["./physics/src/physics.tsx"],+ "raea/playable": ["./playable/src/index.ts"],"raea/pick": ["./render/src/pick.ts"],"raea/playtest": ["./app/src/playtest.ts"],"raea/ragdoll": ["./character/src/ragdoll.ts"],@@ -77,9 +80,12 @@"@raea/audio/*": ["./audio/src/*"],"@raea/video": ["./video/src/index.ts"],"@raea/video/*": ["./video/src/*"],+ "@raea/body": ["./body/src/index.ts"],+ "@raea/body/*": ["./body/src/*"],"@raea/character": ["./character/src/index.ts"],"@raea/character/*": ["./character/src/*"],"@raea/asset": ["./asset/src/index.ts"],+ "@raea/gen": ["./gen/src/index.ts"],"@raea/asset/*": ["./asset/src/*"],"@raea/dev_tools": ["./dev_tools/src/index.ts"],"@raea/dev_tools/*": ["./dev_tools/src/*"],@@ -92,6 +98,8 @@"@raea/ui/plugin": ["./ui/src/plugin.ts"],"@raea/physics": ["./physics/src/index.ts"],"@raea/physics/*": ["./physics/src/*"],+ "@raea/playable": ["./playable/src/index.ts"],+ "@raea/playable/*": ["./playable/src/*"],"@raea/room": ["./room/src/index.ts"],"@raea/room/*": ["./room/src/*"],"@raea/plugins": ["./plugins/src/index.ts"],diff --git a/sdk/ui/conformance/fixture/make.sh b/sdk/ui/conformance/fixture/make.shindex 8f371e9e..b8d5e366 100755--- a/sdk/ui/conformance/fixture/make.sh+++ b/sdk/ui/conformance/fixture/make.sh@@ -11,8 +11,9 @@# .spare/live.mp4 not in the feed (hidden): the live cases copy it into a renders/ folder# library/still-01.png .. still-40.png forty small stills, not in the feed (no renders/): the left panel's Assets# list overflows at every size, so the left-list scroll cases have a range-# .home/films/raea-play/pong/ the world's home (the runner moves .home there): the play item's game,-# ~/films/raea-play/pong/pong.tsx, as links to the repo's own bench Pong+# .home/Studio/internal/projects/raea-play/pong/ the world's home (the runner moves .home there): the play+# item's game, pong.tsx, as links to the repo's own bench Pong (and+# .home/films/raea-play, a link to it, for older raea-feed)# The runner copies OUT into each case's world and dates the files by times.txt. conformance runs this itself (once# per version of this folder, cached under $TMPDIR/conformance/fixture-<hash>).set -euo pipefail@@ -35,8 +36,11 @@ cp "$here/board.md" "$out/storyboard/board.md"ff -f lavfi -i "testsrc2=s=160x90:r=1:d=1" -frames:v 1 "$out/library/still-01.png"for i in $(seq -w 2 40); do cp "$out/library/still-01.png" "$out/library/still-$i.png"; donerepo=$(cd "$here/../../../.." && pwd)-pong=$out/.home/films/raea-play/pong-mkdir -p "$pong"+# the play item's source is ~/Studio/internal/projects/raea-play/pong (raea-feed from 40a27b4) or, in older+# raea-feed, ~/films/raea-play/pong: the fixture's home has both+pong=$out/.home/Studio/internal/projects/raea-play/pong+mkdir -p "$pong" "$out/.home/films"for f in "$repo"/sdk/react/bench/games/pong/*; do ln -s "$f" "$pong/$(basename "$f")"; doneln -s "$repo/sdk/react/bench/games/pong/edit.tsx" "$pong/pong.tsx"+ln -s ../Studio/internal/projects/raea-play "$out/.home/films/raea-play"du -sh "$out" | awk '{print "fixture: " $1 " in " $2}'diff --git a/sdk/ui/parity/bun.lock b/sdk/ui/parity/bun.lockindex 0cf40fa0..4df611d7 100644--- a/sdk/ui/parity/bun.lock+++ b/sdk/ui/parity/bun.lock@@ -7,6 +7,10 @@"dependencies": {"@tailwindcss/cli": "4.3.3","@tanstack/react-virtual": "3.14.22",+ "@tiptap/core": "3.32.0",+ "@tiptap/pm": "3.32.0",+ "@tiptap/react": "3.32.0",+ "@tiptap/starter-kit": "3.32.0","basecoat-css": "1.1.0","radix-ui": "1.8.1","react": "19.2.0",@@ -230,6 +234,68 @@"@tanstack/virtual-core": ["@tanstack/[email protected]", "", {}, "sha512-gxy5SvH0mFRJ0YujtrflB/1HAu9Wn1KGvL0bjZfQkYVVMsIpQiwcf1mR06/ViN4NjllUb4HNCjqE9FGwgTvMCQ=="],+ "@tiptap/core": ["@tiptap/[email protected]", "", { "peerDependencies": { "@tiptap/pm": "3.32.0" } }, "sha512-Ghh2h02GKSqzytQGcLV4espYOG4EHxjj0MsrUB2Vnr47xmlZYRf6r7k2J09H+JpBdaGrWwrTkyBEi5i3c3yy2Q=="],++ "@tiptap/extension-blockquote": ["@tiptap/[email protected]", "", { "peerDependencies": { "@tiptap/core": "3.32.0", "@tiptap/pm": "3.32.0" } }, "sha512-wmuthEdlYVArNoUbqFPH35giutBABFu7fqEB0lTD1k0UXJUs4dFvcbRyGWWgnHFZgP3TT4u8e+xiayYw0eQ0NQ=="],++ "@tiptap/extension-bold": ["@tiptap/[email protected]", "", { "peerDependencies": { "@tiptap/core": "3.32.0" } }, "sha512-SQYewnYDoIBN+8oH53IDcD8p+Pz+Jnyq3hrxjy/FAo5ctc+96d3ZLdqc9gzLVSqFFo/SUINv2FVGoq9PvU7yqw=="],++ "@tiptap/extension-bubble-menu": ["@tiptap/[email protected]", "", { "dependencies": { "@floating-ui/dom": "^1.0.0" }, "peerDependencies": { "@tiptap/core": "3.32.0", "@tiptap/pm": "3.32.0" } }, "sha512-X3ll8i9Z8QNvt7+tcqlwopJG+68ugO13Av0Ox4Ico+jXcTnFdDuKQJBSI9sLuMR5vTQOeTHhKYXhjF88aahMSA=="],++ "@tiptap/extension-bullet-list": ["@tiptap/[email protected]", "", { "peerDependencies": { "@tiptap/extension-list": "3.32.0" } }, "sha512-Y5P/l06pVCUG46vXpBl3z0fW2b6JpSMX4Cvr+5sfQh8zB3TxwSiLQaaPwI3R5MFD1KfRk3AjiPRieEyXdWcNHw=="],++ "@tiptap/extension-code": ["@tiptap/[email protected]", "", { "peerDependencies": { "@tiptap/core": "3.32.0" } }, "sha512-I+aEVl0dTmkfnU6HzBGEefb9U7ja2MkucwBBwrmoMwU+uIKpC4xw8NcHC9X6sjAcom3Pxs2HX+8WEo4Vp13R/Q=="],++ "@tiptap/extension-code-block": ["@tiptap/[email protected]", "", { "peerDependencies": { "@tiptap/core": "3.32.0", "@tiptap/pm": "3.32.0" } }, "sha512-9NZW/yXP9j9XKr+hRS5m58xiyZI+tQo1PJ7eLHXjGNFWaF601NG/h6741mbKh5uCY51XsbyqG+7que+RavngPA=="],++ "@tiptap/extension-document": ["@tiptap/[email protected]", "", { "peerDependencies": { "@tiptap/core": "3.32.0" } }, "sha512-GugeKE6AnZDluRXJUNBuX43TPcaJxy5wck6vT2J4a0/EnKStJ43suSZZf1IPfb1ij9EL9bYvAwg9DOcrvdEzTQ=="],++ "@tiptap/extension-dropcursor": ["@tiptap/[email protected]", "", { "peerDependencies": { "@tiptap/extensions": "3.32.0" } }, "sha512-t4Ug8hFLt30dwwYvrh63BVUt6N1Yg5PVI3tMllhCmN3Q68oD47v4MB/i5nGfzIsQqMyXUOetwHJWcZ4MoLTx4Q=="],++ "@tiptap/extension-floating-menu": ["@tiptap/[email protected]", "", { "peerDependencies": { "@floating-ui/dom": "^1.0.0", "@tiptap/core": "3.32.0", "@tiptap/pm": "3.32.0" } }, "sha512-AzKCWceL+4Q1pTc8Whw1kPqN/aYGPQ70/jXPsblWl501t/pXi6Kz0Pi/NggKkuu73VGjykh68YYf/dcOJ/mPZQ=="],++ "@tiptap/extension-gapcursor": ["@tiptap/[email protected]", "", { "peerDependencies": { "@tiptap/extensions": "3.32.0" } }, "sha512-HUpKKWJLtthnpQY5LIjHlJJOmh562RusmOMIe/4iP/H7y+WUR9ZFiZjEs1NBkRjig9fwj8F3BfsrVPYBnM4nLA=="],++ "@tiptap/extension-hard-break": ["@tiptap/[email protected]", "", { "peerDependencies": { "@tiptap/core": "3.32.0" } }, "sha512-IKUYvK+bO2hGrDWhhTVg0CSh9C2belWg9GyLzvpyd3SZyQ9EgdccLfoytNjOBKbAE/TQ4Oo3kSP+XF6RsUIKPA=="],++ "@tiptap/extension-heading": ["@tiptap/[email protected]", "", { "peerDependencies": { "@tiptap/core": "3.32.0" } }, "sha512-XRiZxZuhfjvbgwCvoBHj04gOsPANEXxxRwrFCQVuFi5yeTHYIzMEioc81j6iAH9pV7aQeJCwLxuh6VHNz3dXEQ=="],++ "@tiptap/extension-horizontal-rule": ["@tiptap/[email protected]", "", { "peerDependencies": { "@tiptap/core": "3.32.0", "@tiptap/pm": "3.32.0" } }, "sha512-Iry7ynsG4xgcxnH1cm+uXJnEtUzoop4sGA10NUN9I+08TOjhj/GrDiRKMQHKAiVI/R7t2MVav1MJlxFf2FdzGw=="],++ "@tiptap/extension-italic": ["@tiptap/[email protected]", "", { "peerDependencies": { "@tiptap/core": "3.32.0" } }, "sha512-KB/i1xoHilbBGcQ+UotDWhi60KpdCde3RzRIpl2na0Yol4z4Fe2IRWg8ljIrlsssDRwel/fsHJbG7a13EP8oKA=="],++ "@tiptap/extension-link": ["@tiptap/[email protected]", "", { "dependencies": { "linkifyjs": "^4.3.3" }, "peerDependencies": { "@tiptap/core": "3.32.0", "@tiptap/pm": "3.32.0" } }, "sha512-DRdQSgWPSEjrDg5EDBB5yxRygHtUVLhceVGzAsTz8RziiFyvcwAvzBHCO9hd9jutjCXQ2DLIuZB8P+aHhFWnpg=="],++ "@tiptap/extension-list": ["@tiptap/[email protected]", "", { "peerDependencies": { "@tiptap/core": "3.32.0", "@tiptap/pm": "3.32.0" } }, "sha512-QdzS5nFz9agAQhBgIuQluobWib39W2cMKx1XB6tYSue7bHMJdgPFP0EnGfFajaeVX42CG6RXtQWrNfyQGKhBvg=="],++ "@tiptap/extension-list-item": ["@tiptap/[email protected]", "", { "peerDependencies": { "@tiptap/extension-list": "3.32.0" } }, "sha512-FdJTCAeALixzyyGSSEmroXmkIEclbo/4t2Pl03aRERqpPOSPJcC3evDtIhLazTuP6v+FjCmJ+pXNql6ov7qitA=="],++ "@tiptap/extension-list-keymap": ["@tiptap/[email protected]", "", { "peerDependencies": { "@tiptap/extension-list": "3.32.0" } }, "sha512-vXFre18Dk2m5N/gjo408C02GSrolZ8ZIf0wz6/U8lNC4FcYOISgZFj3BND6uabVntGh2GCSPrVFuNpVPhFnn/A=="],++ "@tiptap/extension-ordered-list": ["@tiptap/[email protected]", "", { "peerDependencies": { "@tiptap/extension-list": "3.32.0" } }, "sha512-htZ5hoMLBkGiDP6M5mGemjOoaBmkrj911wiGoTmMMKzO7qJq9QxUBkLY7ILPaKlUWL8U3ccLdDV2TB/nysp4Jg=="],++ "@tiptap/extension-paragraph": ["@tiptap/[email protected]", "", { "peerDependencies": { "@tiptap/core": "3.32.0" } }, "sha512-afKLMc7fWMkkar9H5FilizStSbhFzUoCzdwwdZf6DDsn3LUt8tJlFHACK78cAyx/TzMJBo0N8/8T1u9bL+N67Q=="],++ "@tiptap/extension-strike": ["@tiptap/[email protected]", "", { "peerDependencies": { "@tiptap/core": "3.32.0" } }, "sha512-J9Vw6wmh/wV6SxSsN9RhurvAGcXSY5J3p4EQrROD5PARBl0VOnDFi7/UVoz1RkSdqOKPgAiqDZpaLRgtdBO9Rg=="],++ "@tiptap/extension-text": ["@tiptap/[email protected]", "", { "peerDependencies": { "@tiptap/core": "3.32.0" } }, "sha512-sF0jIK67IHdZMnzv2mz5vPTyK7R0ui6/YZgFg+/bLnFCNmweVAoYcHZLlC7ISRnwu0mqJr+epNtzJepY1ZDCjg=="],++ "@tiptap/extension-underline": ["@tiptap/[email protected]", "", { "peerDependencies": { "@tiptap/core": "3.32.0" } }, "sha512-rMLdd4vg6sed/JnaXnaupLbCtYiWikTnQ8qir9ItKOXwf1Ui9P1Y4G0bYU4+gcnMsFzaSGtrOhMqG4/c66AogQ=="],++ "@tiptap/extensions": ["@tiptap/[email protected]", "", { "peerDependencies": { "@tiptap/core": "3.32.0", "@tiptap/pm": "3.32.0" } }, "sha512-qO+ndNvlOjzU2MWCtQHoRg1tIortCXLvqPjDx58F1pUYFNCOVZegXi+jqLGDODUA31er+TVz66umzRbbN1bO1Q=="],++ "@tiptap/pm": ["@tiptap/[email protected]", "", { "dependencies": { "prosemirror-changeset": "^2.4.4", "prosemirror-commands": "^1.7.2", "prosemirror-dropcursor": "^1.8.4", "prosemirror-gapcursor": "^1.4.1", "prosemirror-history": "^1.5.1", "prosemirror-inputrules": "^1.5.1", "prosemirror-keymap": "^1.2.3", "prosemirror-model": "^1.25.12", "prosemirror-schema-list": "^1.5.1", "prosemirror-state": "^1.4.4", "prosemirror-tables": "^1.8.5", "prosemirror-transform": "^1.12.2", "prosemirror-view": "^1.42.6" } }, "sha512-H9eN+xHFboJybE7KPGVsu24S8aBlCIgYz38vCHRSnNv17nwmqm06owq/IQ5scza0n3Y7IfUfpgPOtm9SgeHmNQ=="],++ "@tiptap/react": ["@tiptap/[email protected]", "", { "dependencies": { "@types/use-sync-external-store": "^0.0.6", "fast-equals": "^5.3.3", "use-sync-external-store": "^1.4.0" }, "optionalDependencies": { "@tiptap/extension-bubble-menu": "3.32.0", "@tiptap/extension-floating-menu": "3.32.0" }, "peerDependencies": { "@tiptap/core": "3.32.0", "@tiptap/pm": "3.32.0", "@types/react": "^17.0.0 || ^18.0.0 || ^19.0.0", "@types/react-dom": "^17.0.0 || ^18.0.0 || ^19.0.0", "react": "^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-+iS9RKj6Ve8SXqJ49xptDiifF7PQXmUOh4cjMu+BCXXqKphQkiUccvbWYAeOJCTceM01wWgFhrpfy8qG+CHJYw=="],++ "@tiptap/starter-kit": ["@tiptap/[email protected]", "", { "dependencies": { "@tiptap/core": "3.32.0", "@tiptap/extension-blockquote": "3.32.0", "@tiptap/extension-bold": "3.32.0", "@tiptap/extension-bullet-list": "3.32.0", "@tiptap/extension-code": "3.32.0", "@tiptap/extension-code-block": "3.32.0", "@tiptap/extension-document": "3.32.0", "@tiptap/extension-dropcursor": "3.32.0", "@tiptap/extension-gapcursor": "3.32.0", "@tiptap/extension-hard-break": "3.32.0", "@tiptap/extension-heading": "3.32.0", "@tiptap/extension-horizontal-rule": "3.32.0", "@tiptap/extension-italic": "3.32.0", "@tiptap/extension-link": "3.32.0", "@tiptap/extension-list": "3.32.0", "@tiptap/extension-list-item": "3.32.0", "@tiptap/extension-list-keymap": "3.32.0", "@tiptap/extension-ordered-list": "3.32.0", "@tiptap/extension-paragraph": "3.32.0", "@tiptap/extension-strike": "3.32.0", "@tiptap/extension-text": "3.32.0", "@tiptap/extension-underline": "3.32.0", "@tiptap/extensions": "3.32.0", "@tiptap/pm": "3.32.0" } }, "sha512-aPYxaevci4PgMrTLsg+baiqI7M1ICd4V9H+zTTdrqs8OUZIbAvj/pNDuHU8uWZyKMu3Dh72t2D6ZdqRu/6aSWw=="],++ "@types/react": ["@types/[email protected]", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg=="],++ "@types/react-dom": ["@types/[email protected]", "", { "peerDependencies": { "@types/react": "^19.3.0" } }, "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q=="],++ "@types/use-sync-external-store": ["@types/[email protected]", "", {}, "sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg=="],+"aria-hidden": ["[email protected]", "", { "dependencies": { "tslib": "^2.0.0" } }, "sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA=="],"basecoat-css": ["[email protected]", "", {}, "sha512-qQ25lbkdXiBQd8uBd4juOX1y2ut+Ww4Aaa7EwO9Is/jd143Ze/eRULQdJmiwAwzKKqkxtvg9YTJg79xXz2nLeg=="],@@ -238,12 +304,16 @@"clsx": ["[email protected]", "", {}, "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA=="],+ "csstype": ["[email protected]", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="],+"detect-libc": ["[email protected]", "", { "bin": { "detect-libc": "./bin/detect-libc.js" } }, "sha512-pGjwhsmsp4kL2RTz08wcOlGN83otlqHeD/Z5T8GXZB+/YcpQ/dgo+lbU8ZsGxV0HIvqqxo9l7mqYwyYMD9bKDg=="],"detect-node-es": ["[email protected]", "", {}, "sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ=="],"enhanced-resolve": ["[email protected]", "", { "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.3.3" } }, "sha512-9vhedylFonb2YGogzUKX6+Ja72gOJbN1QHAqdrvqLwhdl/QWbKopzoUC9EbQNVsAns/bx/4uyqalrQAoy1IByw=="],+ "fast-equals": ["[email protected]", "", {}, "sha512-yKEpcFuRPu/pTQL2VB8YKE2yFldrLlIsoWtJeBnAdqEhvu21OgkFT0C8njf/xYc2LSZGEr3K9JGjthHJxnVLvQ=="],+"fill-range": ["[email protected]", "", { "dependencies": { "to-regex-range": "^5.0.1" } }, "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg=="],"get-nonce": ["[email protected]", "", {}, "sha512-FJhYRoDaiatfEkUK8HKlicmu/3SGFD51q3itKDGoSTysQJBnfOcxU5GxnhE1E6soB76MbT0MBtnKJuXyAx+96Q=="],@@ -282,6 +352,8 @@"lightningcss-win32-x64-msvc": ["[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q=="],+ "linkifyjs": ["[email protected]", "", {}, "sha512-InTexvtbai+2c+dEVGcc6O6P2DMVIiwD9a/i4zFroazOIYLOS6FSVmAJ7kFeumnCMx6/gQqNAkbUvgMubV4+MA=="],+"magic-string": ["[email protected]", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="],"micromatch": ["[email protected]", "", { "dependencies": { "braces": "^3.0.3", "picomatch": "^2.3.1" } }, "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA=="],@@ -290,10 +362,38 @@"node-addon-api": ["[email protected]", "", {}, "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ=="],+ "orderedmap": ["[email protected]", "", {}, "sha512-TvAWxi0nDe1j/rtMcWcIj94+Ffe6n7zhow33h40SKxmsmozs6dz/e+EajymfoFcHd7sxNn8yHM8839uixMOV6g=="],+"picocolors": ["[email protected]", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="],"picomatch": ["[email protected]", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="],+ "prosemirror-changeset": ["[email protected]", "", { "dependencies": { "prosemirror-transform": "^1.0.0" } }, "sha512-P0cY3DSLm4M2boUOCmHDyaID5o6HgWmb21Bvs9p8lLqfJjKBBEHG5Ma5qW5SCmwOYamtWOLf2k+yvt6077zlTg=="],++ "prosemirror-commands": ["[email protected]", "", { "dependencies": { "prosemirror-model": "^1.0.0", "prosemirror-state": "^1.0.0", "prosemirror-transform": "^1.10.2" } }, "sha512-q6Q6szxqdu9Xd6EcdKsqXghu5nQdZTpB4Q9yd04WRc7/jt763e/rT60Owh0L1GYY+T46o5rD+9lEN36dZS43tw=="],++ "prosemirror-dropcursor": ["[email protected]", "", { "dependencies": { "prosemirror-state": "^1.0.0", "prosemirror-transform": "^1.1.0", "prosemirror-view": "^1.1.0" } }, "sha512-VmKxhcA6a+h5oPSYmfF1ZNeQqPbyYaIxqZsKqeYCyTlPtrjUgNaHL3P8vVaO19oqAV0zuaM/axkowZHrB1P3Tg=="],++ "prosemirror-gapcursor": ["[email protected]", "", { "dependencies": { "prosemirror-keymap": "^1.0.0", "prosemirror-model": "^1.0.0", "prosemirror-state": "^1.0.0", "prosemirror-view": "^1.0.0" } }, "sha512-pMdYaEnjNMSwl11yjEGtgTmLkR08m/Vl+Jj443167p9eB3HVQKhYCc4gmHVDsLPODfZfjr/MmirsdyZziXbQKw=="],++ "prosemirror-history": ["[email protected]", "", { "dependencies": { "prosemirror-state": "^1.2.2", "prosemirror-transform": "^1.0.0", "prosemirror-view": "^1.31.0", "rope-sequence": "^1.3.0" } }, "sha512-onlwnqKvgtFg6srZOmDOAhlAy1FIHQpOExORybX0S+DvJepE5tPALrB9iGet/2sqqqrelSnB10OoiOJqAvu2DA=="],++ "prosemirror-inputrules": ["[email protected]", "", { "dependencies": { "prosemirror-state": "^1.0.0", "prosemirror-transform": "^1.0.0" } }, "sha512-7wj4uMjKaXWAQ1CDgxNzNtR9AlsuwzHfdFH1ygEHA2KHF2DOEaXl1CJfNPAKCg9qNEh4rum975QLaCiQPyY6Fw=="],++ "prosemirror-keymap": ["[email protected]", "", { "dependencies": { "prosemirror-state": "^1.0.0", "w3c-keyname": "^2.2.0" } }, "sha512-4HucRlpiLd1IPQQXNqeo81BGtkY8Ai5smHhKW9jjPKRc2wQIxksg7Hl1tTI2IfT2B/LgX6bfYvXxEpJl7aKYKw=="],++ "prosemirror-model": ["[email protected]", "", { "dependencies": { "orderedmap": "^2.0.0" } }, "sha512-Ue2gTmXMa7EhpLNhC7J+h4+ykD8ha12K6rrZFFKKJHBForfIStw5gJ6Zrf1mqqAa9NmpmEB4wp9bKmA4eUVjWg=="],++ "prosemirror-schema-list": ["[email protected]", "", { "dependencies": { "prosemirror-model": "^1.0.0", "prosemirror-state": "^1.0.0", "prosemirror-transform": "^1.7.3" } }, "sha512-G1srDtan+VqWn+qpmWFj/6j0YsZ5zMU+ZIlGVIW41a5JF2jAI3jzfMRWmSABmEH2Qoq1PmAG/o2mucMMdLOsLg=="],++ "prosemirror-state": ["[email protected]", "", { "dependencies": { "prosemirror-model": "^1.0.0", "prosemirror-transform": "^1.0.0", "prosemirror-view": "^1.27.0" } }, "sha512-6jiYHH2CIGbCfnxdHbXZ12gySFY/fz/ulZE333G6bPqIZ4F+TXo9ifiR86nAHpWnfoNjOb3o5ESi7J8Uz1jXHw=="],++ "prosemirror-tables": ["[email protected]", "", { "dependencies": { "prosemirror-keymap": "^1.2.3", "prosemirror-model": "^1.25.4", "prosemirror-state": "^1.4.4", "prosemirror-transform": "^1.10.5", "prosemirror-view": "^1.41.4" } }, "sha512-V/0cDCsHKHe/tfWkeCmthNUcEp1IVO3p6vwN8XtwE9PZQLAZJigbw3QoraAdfJPir4NKJtNvOB8oYGKRl+t0Dw=="],++ "prosemirror-transform": ["[email protected]", "", { "dependencies": { "prosemirror-model": "^1.21.0" } }, "sha512-3EBXZBM4h3MKuWvs9sQ7IA0/v6jCqCZ4wC08PIvzY1VSQWDL90KEyfg5C0Ex52UJesf/QVogxvuBsZdKmLc3NQ=="],++ "prosemirror-view": ["[email protected]", "", { "dependencies": { "prosemirror-model": "^1.25.12", "prosemirror-state": "^1.0.0", "prosemirror-transform": "^1.1.0" } }, "sha512-bKbfzeKZOu2H2JQU2TaJmYu6EBcor3VnGIR4jR31cbEt1ztUnfUB6bKGV1+fJzOJdrVWR+tRU0208zM3oQx4wA=="],+"radix-ui": ["[email protected]", "", { "dependencies": { "@radix-ui/primitive": "1.2.0", "@radix-ui/react-accessible-icon": "1.2.0", "@radix-ui/react-accordion": "1.3.1", "@radix-ui/react-alert-dialog": "1.2.1", "@radix-ui/react-arrow": "1.1.17", "@radix-ui/react-aspect-ratio": "1.2.0", "@radix-ui/react-avatar": "1.3.1", "@radix-ui/react-checkbox": "1.4.1", "@radix-ui/react-collapsible": "1.2.1", "@radix-ui/react-collection": "1.2.0", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.3.0", "@radix-ui/react-context-menu": "2.4.1", "@radix-ui/react-dialog": "1.3.1", "@radix-ui/react-direction": "1.2.0", "@radix-ui/react-dismissable-layer": "1.2.1", "@radix-ui/react-dropdown-menu": "2.2.1", "@radix-ui/react-focus-guards": "1.2.0", "@radix-ui/react-focus-scope": "1.3.1", "@radix-ui/react-form": "0.3.0", "@radix-ui/react-hover-card": "1.2.1", "@radix-ui/react-label": "2.1.17", "@radix-ui/react-menu": "2.2.1", "@radix-ui/react-menubar": "1.2.1", "@radix-ui/react-navigation-menu": "1.4.1", "@radix-ui/react-one-time-password-field": "0.2.1", "@radix-ui/react-password-toggle-field": "0.2.1", "@radix-ui/react-popover": "1.3.1", "@radix-ui/react-popper": "1.4.0", "@radix-ui/react-portal": "1.2.0", "@radix-ui/react-presence": "1.1.11", "@radix-ui/react-primitive": "2.2.0", "@radix-ui/react-progress": "1.2.1", "@radix-ui/react-radio-group": "1.5.1", "@radix-ui/react-roving-focus": "1.2.1", "@radix-ui/react-scroll-area": "1.4.0", "@radix-ui/react-select": "2.4.1", "@radix-ui/react-separator": "1.2.0", "@radix-ui/react-slider": "1.6.1", "@radix-ui/react-slot": "1.5.0", "@radix-ui/react-switch": "1.4.1", "@radix-ui/react-tabs": "1.2.1", "@radix-ui/react-toast": "1.3.1", "@radix-ui/react-toggle": "1.2.1", "@radix-ui/react-toggle-group": "1.2.1", "@radix-ui/react-toolbar": "1.2.1", "@radix-ui/react-tooltip": "1.4.1", "@radix-ui/react-use-callback-ref": "1.1.5", "@radix-ui/react-use-controllable-state": "1.3.0", "@radix-ui/react-use-effect-event": "0.0.5", "@radix-ui/react-use-escape-keydown": "1.1.6", "@radix-ui/react-use-is-hydrated": "0.1.3", "@radix-ui/react-use-layout-effect": "1.1.4", "@radix-ui/react-use-size": "1.1.5", "@radix-ui/react-visually-hidden": "1.2.13" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-HPfpVGizO9xANlsFSauruLhRe/3+iOt3vPX0MXYle/UQi3gorQrSYtBcdiv0BZYewcl2rvL59qrIuLFMGAmUrw=="],"react": ["[email protected]", "", {}, "sha512-tmbWg6W31tQLeB5cdIBOicJDJRR2KzXsV7uSK9iNfLWQ5bIZfxuPEHp7M8wiHyHnn0DD1i7w3Zmin0FtkrwoCQ=="],@@ -314,6 +414,8 @@"react-style-singleton": ["[email protected]", "", { "dependencies": { "get-nonce": "^1.0.0", "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-b6jSvxvVnyptAiLjbkWLE/lOnR4lfTtDAl+eUC7RZy+QQWc6wRzIV2CE6xBuMmDxc2qIihtDCZD5NPOFl7fRBQ=="],+ "rope-sequence": ["[email protected]", "", {}, "sha512-UT5EDe2cu2E/6O4igUr5PSFs23nvvukicWHx6GnOPlHAiiYbzNuCRQCuiUdHJQcqKalLKlrYJnjY0ySGsXNQXQ=="],+"scheduler": ["[email protected]", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="],"source-map-js": ["[email protected]", "", {}, "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw=="],@@ -332,6 +434,8 @@"use-sync-external-store": ["[email protected]", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-6L+EeigHMQhdaIPNIFUKwfWJSwWFQ8gJbJ2DLOs5sDIegTwR9fRxvnM3uciHKjIZhFz+KAv2emhWMRvDmMcY8A=="],+ "w3c-keyname": ["[email protected]", "", {}, "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ=="],+"@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/[email protected]", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.3", "tslib": "^2.4.0" }, "bundled": true }, "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg=="],"@tailwindcss/oxide-wasm32-wasi/@emnapi/runtime": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="],diff --git a/sdk/ui/parity/cases/p12-css/list-markers.tsx b/sdk/ui/parity/cases/p12-css/list-markers.tsxnew file mode 100644index 00000000..171dc19b--- /dev/null+++ b/sdk/ui/parity/cases/p12-css/list-markers.tsx@@ -0,0 +1,27 @@+// Outside list markers: an ol's numbers and a ul's discs sit a gap before their item's text (Chrome's "1. " keeps its+// space) in their ::marker colour, for plain items and for items holding a p as ProseMirror makes them. The items'+// text is drawn transparent and the lists are narrow, so the markers are most of what each list shows.+// proves: css.properties.list-style-position.outside, css.properties.list-style-type, css.selectors.marker, tw.utility.list-*+export const steps = [];+const li = "[&_li::marker]:text-rose-600 [&_li]:text-transparent";+export default function Case() {+ return (+ <div data-testid="root" className="h-full w-full bg-white p-4 text-2xl text-slate-900">+ <ol data-testid="ol" className={`w-20 list-decimal pl-10 ${li}`}>+ <li>I</li>+ <li>+ <p className="my-1">I</p>+ </li>+ </ol>+ <ol data-testid="ol-shown" className="mt-3 w-28 list-decimal pl-10">+ <li>Cut</li>+ </ol>+ <ul data-testid="ul" className={`mt-3 w-20 list-disc pl-10 ${li}`}>+ <li>I</li>+ <li>+ <p className="my-1">I</p>+ </li>+ </ul>+ </div>+ );+}diff --git a/sdk/ui/parity/cases/p12-css/selection-colors.tsx b/sdk/ui/parity/cases/p12-css/selection-colors.tsxnew file mode 100644index 00000000..eb768934--- /dev/null+++ b/sdk/ui/parity/cases/p12-css/selection-colors.tsx@@ -0,0 +1,18 @@+// ::selection colours: a word double clicked in light text on a dark box takes the box's ::selection background and+// colour (Tailwind's selection: variant, as apps/app's index.css sets it), on the word in a bold span too.+// proves: css.selectors.selection, tw.variant.selection+export const steps = [{ click: "ed", at: [0.12, 0.5], clicks: 2 }];+export default function Case() {+ return (+ <div data-testid="root" className="h-full w-full bg-zinc-900 p-4 text-zinc-100">+ <div+ data-testid="ed"+ contentEditable+ suppressContentEditableWarning+ className="w-80 p-2 text-lg outline-none selection:bg-indigo-400/40 selection:text-amber-200"+ >+ Fieldwork <b>Creative</b> handbook+ </div>+ </div>+ );+}diff --git a/sdk/ui/parity/cases/p14-forms/contenteditable.tsx b/sdk/ui/parity/cases/p14-forms/contenteditable.tsxnew file mode 100644index 00000000..e9c26ccb--- /dev/null+++ b/sdk/ui/parity/cases/p14-forms/contenteditable.tsx@@ -0,0 +1,34 @@+// A plain contenteditable (docs/ts-native.feature P14e): click into it, type, Backspace, arrows, Shift+arrows to select+// and type over the selection, End, and across an inline mark; the DOM Chrome's editing makes is what's compared.+// proves: html.global_attributes.contenteditable, api.HTMLElement.isContentEditable, api.Element.beforeinput_event, api.Selection+import { useRef, useState } from "react";+export const steps = [+ { click: "ed", at: [0.04, 0.5] },+ { text: "Say " },+ { key: "End" },+ { text: "!!" },+ { key: "Backspace" },+ { key: "ArrowLeft" },+ { key: "ArrowLeft" },+ { key: "ArrowLeft", mods: ["shift"] },+ { key: "ArrowLeft", mods: ["shift"] },+ { text: "X" },+ { click: "dump" },+];+export default function Case() {+ const ed = useRef<HTMLDivElement>(null);+ const [html, setHtml] = useState("");+ return (+ <div data-testid="root" className="h-full w-full bg-white p-4 text-slate-900">+ <div ref={ed} data-testid="ed" contentEditable suppressContentEditableWarning className="w-80 border border-slate-400 p-2 text-sm outline-none">+ hello <b>bold</b> end+ </div>+ <button data-testid="dump" className="mt-2 border px-2 text-sm" onClick={() => setHtml(ed.current?.innerHTML ?? "")}>+ dump+ </button>+ <pre data-testid="out" className="mt-2 text-xs">+ {html}+ </pre>+ </div>+ );+}diff --git a/sdk/ui/parity/cases/p14-forms/tiptap.tsx b/sdk/ui/parity/cases/p14-forms/tiptap.tsxnew file mode 100644index 00000000..01fbcfe1--- /dev/null+++ b/sdk/ui/parity/cases/p14-forms/tiptap.tsx@@ -0,0 +1,50 @@+// Tiptap (ProseMirror) on contenteditable (docs/ts-native.feature P14e; the feed's editors are): type a+// paragraph, Enter, Mod-B and type bold, double click a word and delete it, arrows back into the bold mark and type,+// then undo. The document Tiptap holds is shown after each step, so a difference in what the editing did shows as text.+// proves: html.global_attributes.contenteditable, api.Range, api.Document.caretPositionFromPoint, api.Document.selectionchange_event+import { EditorContent, useEditor } from "@tiptap/react";+import StarterKit from "@tiptap/starter-kit";+import { useState } from "react";+export const steps = [+ { click: "pm", at: [0.5, 0.15] },+ { text: "Hello world" },+ { key: "Enter" },+ { key: "b", mods: ["meta"] },+ { text: "bold" },+ { key: "b", mods: ["meta"] },+ { text: " plain" },+ // "world" on the first line: two clicks pick it, Backspace deletes it+ { click: "pm", at: [0.2, 0.15], clicks: 2 },+ { key: "Backspace" },+ // to the end of the second paragraph, then back across " plain" into "bold"+ { key: "ArrowDown" },+ { key: "End" },+ { key: "ArrowLeft" },+ { key: "ArrowLeft" },+ { key: "ArrowLeft" },+ { key: "ArrowLeft" },+ { key: "ArrowLeft" },+ { key: "ArrowLeft" },+ { key: "ArrowLeft" },+ { key: "ArrowLeft" },+ { text: "X" },+ { key: "z", mods: ["meta"] },+];+export default function Case() {+ const [html, setHtml] = useState("");+ const editor = useEditor({+ extensions: [StarterKit],+ content: "",+ immediatelyRender: true,+ editorProps: { attributes: { "data-testid": "pm", class: "h-32 w-80 border border-slate-400 p-2 text-sm outline-none [&_p]:my-1" } },+ onUpdate: ({ editor }) => setHtml(editor.getHTML()),+ });+ return (+ <div data-testid="root" className="h-full w-full bg-white p-4 text-slate-900">+ <EditorContent editor={editor} />+ <pre data-testid="doc" className="mt-2 w-96 whitespace-pre-wrap text-xs">+ {html}+ </pre>+ </div>+ );+}diff --git a/sdk/ui/parity/package.json b/sdk/ui/parity/package.jsonindex 3711327f..b4e6211b 100644--- a/sdk/ui/parity/package.json+++ b/sdk/ui/parity/package.json@@ -8,6 +8,10 @@"dependencies": {"@tailwindcss/cli": "4.3.3","@tanstack/react-virtual": "3.14.22",+ "@tiptap/core": "3.32.0",+ "@tiptap/pm": "3.32.0",+ "@tiptap/react": "3.32.0",+ "@tiptap/starter-kit": "3.32.0","basecoat-css": "1.1.0","radix-ui": "1.8.1","react": "19.2.0",diff --git a/sdk/ui/parity/src/main.rs b/sdk/ui/parity/src/main.rsindex afa4459e..92bc1ec7 100644--- a/sdk/ui/parity/src/main.rs+++ b/sdk/ui/parity/src/main.rs@@ -134,7 +134,7 @@ fn parse() -> Result<Opts, String> {}fn usage() -> &'static str {- "usage: ui-parity run|calibrate|list [--only TEXT]... [--tier quick|full] [--jobs N] [--out DIR] [--self] [--bevy BIN] [--chrome BIN] [--engine jsc|quickjs]\n ui-parity wpt [--area NAME]... [--only TEXT]... [--tier quick|full] [--jobs N] [--out DIR] [--chrome BIN] [--motion BIN] [--page blitz] [--wpt DIR] (src/wpt.rs)\n ui-parity app [--only TEXT]... [--out DIR] [--bevy BIN] [--chrome BIN] [--engine jsc|quickjs] (src/app.rs: apps/app's screens)"+ "usage: ui-parity run|calibrate|list [--only TEXT]... [--tier quick|full] [--jobs N] [--out DIR] [--self] [--bevy BIN] [--chrome BIN] [--engine jsc|quickjs]\n ui-parity wpt [--area NAME]... [--only TEXT]... [--tier quick|full] [--jobs N] [--out DIR] [--chrome BIN] [--motion BIN] [--page blitz] [--wpt DIR] (src/wpt.rs)\n ui-parity app [--only TEXT]... [--out DIR] [--bevy BIN] [--chrome BIN] [--engine jsc|quickjs] (src/app.rs: apps/app's screens; RAEA_PARITY_APP=DIR for a copy of it)"}#[derive(Clone, Debug)]@@ -446,7 +446,7 @@ fn main() {};let code = match o.cmd.as_str() {"run" | "list" => run(o),- "app" => chrome_bin(&o).and_then(|chrome| app::run(app::Opts { out: o.out.clone(), chrome, bevy: o.bevy.clone(), engine: o.engine.clone(), only: o.only.clone(), app: repo().join("apps/app") })),+ "app" => chrome_bin(&o).and_then(|chrome| app::run(app::Opts { out: o.out.clone(), chrome, bevy: o.bevy.clone(), engine: o.engine.clone(), only: o.only.clone(), app: std::env::var_os("RAEA_PARITY_APP").map(PathBuf::from).unwrap_or_else(|| repo().join("apps/app")) })),"wpt" => chrome_bin(&o).and_then(|chrome| wpt::run(wpt::Opts { tier: o.tier, jobs: o.jobs, out: o.out, chrome, motion: o.motion, wpt: o.wpt, only: o.only, areas: o.areas, page: o.page })),"calibrate" => {// every case Chrome against Chrome (identical by construction: each must pass, the calibration cases asdiff --git a/sdk/ui/src/canvas/all.ts b/sdk/ui/src/canvas/all.tsindex 7a4af7de..34b9b055 100644--- a/sdk/ui/src/canvas/all.ts+++ b/sdk/ui/src/canvas/all.ts@@ -3,5 +3,6 @@export * from "./core";export * from "./filter";export * from "./paths";+export * from "./measure";export * from "./context";export * from "./images";diff --git a/sdk/ui/src/canvas/context.ts b/sdk/ui/src/canvas/context.tsindex 1f6d01b6..adbbb156 100644--- a/sdk/ui/src/canvas/context.ts+++ b/sdk/ui/src/canvas/context.ts@@ -1,6 +1,7 @@// CanvasRenderingContext2D.import * as wire from "../wire";-import { COMPOSITES, CanvasHost, Gradient, ID, ImageData_, Paint, Path, Path2D_, S, State, fresh, metrics, mul, paintOf, parseColor, parseFilter, parseFont, unb64 } from "./all";+import { base64, encodePng } from "./png";+import { COMPOSITES, CanvasHost, Gradient, ID, ImageData_, Paint, Path, Path2D_, S, State, fresh, measure, mul, paintOf, parseColor, parseFilter, parseFont, unb64 } from "./all";export class CanvasRenderingContext2D_ {private s: State = fresh();@@ -29,7 +30,7 @@ export class CanvasRenderingContext2D_ {}private push(op: unknown[]) {const [w, h] = [this.canvas.width, this.canvas.height];- if (w !== this.size[0] || h !== this.size[1]) {+ if (w !== this.size[0] || h !== this.size[1] || this.coversAll(op, w, h)) {this.list = [];this.gen++;this.size = [w, h];@@ -37,6 +38,26 @@ export class CanvasRenderingContext2D_ {this.list.push(op);this.send();}+ /** A clear, or an opaque source-over fill, over the whole bitmap: nothing drawn before it shows, so the list can+ * start again with it. Libraries that clear under a transform (Excalidraw's zoom and pixel ratio) never hit+ * clearRect's own case, and their lists grew by a whole scene every frame. */+ private coversAll(op: unknown[], w: number, h: number) {+ const kind = op[0];+ if (kind !== "clear" && kind !== "fill") return false;+ const d = op[1];+ const st = op[op.length - 1] as { alpha: number; comp: string; clip: unknown[]; shadow: unknown; filter: unknown };+ if (!Array.isArray(d) || !st || st.clip.length || st.shadow || st.filter) return false;+ if (kind === "fill") {+ const paint = op[3];+ if (st.alpha !== 1 || st.comp !== "source-over" || !Array.isArray(paint) || paint[3] !== 1) return false;+ }+ // a rectangle: move, three lines, close (each command then its point), axis-aligned, covering 0,0..w,h+ if (d.length !== 13 || d[0] !== 0 || d[3] !== 1 || d[6] !== 1 || d[9] !== 1 || d[12] !== 4) return false;+ const xs = [d[1], d[4], d[7], d[10]] as number[];+ const ys = [d[2], d[5], d[8], d[11]] as number[];+ const axis = (xs[0] === xs[1] || ys[0] === ys[1]) && (xs[1] === xs[2] || ys[1] === ys[2]);+ return axis && Math.min(...xs) <= 0 && Math.min(...ys) <= 0 && Math.max(...xs) >= w && Math.max(...ys) >= h;+ }private send() {if (this.pending) return;this.pending = true;@@ -47,6 +68,28 @@ export class CanvasRenderingContext2D_ {wire.set(id, "__canvas2d", { gen: this.gen, w: this.size[0], h: this.size[1], ops: this.list });});}+ private static uids = 0;+ private uid = ++CanvasRenderingContext2D_.uids;+ /** The list as it is now, for this canvas drawn onto another (systems/canvas's "canvas" op replays it there), with+ * a key the host keeps its bitmap by: the list only grows within a generation, so the key names its contents. */+ _snapshot(): { key: string; w: number; h: number; ops: unknown[] } | null {+ const [w, h] = [this.canvas.width, this.canvas.height];+ if (!w || !h) return null;+ const same = w === this.size[0] && h === this.size[1];+ return { key: `${this.uid}:${this.gen}:${same ? this.list.length : 0}:${w}x${h}`, w, h, ops: same ? this.list.slice() : [] };+ }+ private snap?: { gen: number; n: number; w: number; h: number; url: string };+ /** The bitmap as a PNG data URL, read back from the host (toDataURL; this canvas drawn onto another, where an+ * image op can only name a src). Kept until something more is drawn. */+ _dataUrl(): string {+ const [w, h] = [this.canvas.width, this.canvas.height];+ if (!w || !h) return "data:,";+ const k = this.snap;+ if (k && k.gen === this.gen && k.n === this.list.length && k.w === w && k.h === h) return k.url;+ const url = `data:image/png;base64,${base64(encodePng(w, h, this.getImageData(0, 0, w, h).data))}`;+ this.snap = { gen: this.gen, n: this.list.length, w, h, url };+ return url;+ }private state() {const s = this.s;return {@@ -377,22 +420,22 @@ export class CanvasRenderingContext2D_ {this.text("stroke", t, x, y, maxWidth);}measureText(text: string) {- const f = parseFont(this.s.font)!;- const fam = f.family.replace(/["']/g, "").split(",")[0].trim().toLowerCase();- const m = metrics.get(fam) ?? metrics.get(S.defaultFamily.toLowerCase());- // without the host's advances: the default face's (Fira Mono, monospace: 600 units of 1000 a character)- let w = 0;- for (const ch of String(text)) w += m ? (m.adv[ch] ?? m.dflt) / m.em : 0.6;- w *= f.size;- return { width: w, actualBoundingBoxLeft: 0, actualBoundingBoxRight: w, fontBoundingBoxAscent: f.size * 0.8, fontBoundingBoxDescent: f.size * 0.2, actualBoundingBoxAscent: f.size * 0.7, actualBoundingBoxDescent: 0 };+ return measure(this.s.font, String(text));}drawImage(img: { src?: string; currentSrc?: string; _canvas2d?: CanvasRenderingContext2D_; width?: number; height?: number; naturalWidth?: number; naturalHeight?: number }, ...a: number[]) {- const src = img.currentSrc || img.src;- if (!src) return;let s: (number | null)[];if (a.length === 2) s = [null, null, null, null, a[0], a[1], null, null];else if (a.length === 4) s = [null, null, null, null, a[0], a[1], a[2], a[3]];else s = a.slice(0, 8);+ // a canvas as the source: its list as it is now, drawn on the host (no pixels come back to JS)+ const ctx = (img as { _ctx?: CanvasRenderingContext2D_ })._ctx;+ if (ctx && !img.currentSrc && !img.src) {+ const snap = ctx._snapshot();+ if (snap) this.push(["canvas", snap, ...s, this.state()]);+ return;+ }+ const src = img.currentSrc || img.src || "";+ if (!src || src === "data:,") return;// a video: the frame it shows now, decoded where the list is drawn (its time rides at the end)const v = img as { tagName?: string; currentTime?: number };if (String(v.tagName).toUpperCase() === "VIDEO") this.push(["video", src, ...s, this.state(), Number(v.currentTime) || 0]);diff --git a/sdk/ui/src/canvas/images.ts b/sdk/ui/src/canvas/images.tsindex 061d2070..9785c54a 100644--- a/sdk/ui/src/canvas/images.ts+++ b/sdk/ui/src/canvas/images.ts@@ -57,7 +57,7 @@ export function canvasClass<T extends new (...a: any[]) => CanvasHost & { setAttreturn (this._ctx ??= new CanvasRenderingContext2D_(this as unknown as CanvasHost & { width: number; height: number }));}toDataURL() {- return "data:,";+ return (this.getContext("2d") as CanvasRenderingContext2D_)._dataUrl();}};}diff --git a/sdk/ui/src/canvas/measure.ts b/sdk/ui/src/canvas/measure.tsnew file mode 100644index 00000000..b26061d2--- /dev/null+++ b/sdk/ui/src/canvas/measure.ts@@ -0,0 +1,39 @@+// measureText: each character's advance from the host's faces (canvas.advances), else the bundled metrics.+import * as wire from "../wire";+import { S, metrics, parseFont } from "./all";++/** measureText's answer for `text` in a CSS `font`. */+export function measure(font: string, text: string) {+ const f = parseFont(font)!;+ const fam = f.family.replace(/["']/g, "").split(",")[0].trim().toLowerCase();+ const m = metrics.get(fam) ?? metrics.get(S.defaultFamily.toLowerCase());+ const host = hostAdvances(f, text);+ // without the host's advances: the default face's (Fira Mono, monospace: 600 units of 1000 a character)+ let w = 0;+ for (const ch of text) w += host?.get(ch) ?? (m ? (m.adv[ch] ?? m.dflt) / m.em : 0.6);+ w *= f.size;+ return { width: w, actualBoundingBoxLeft: 0, actualBoundingBoxRight: w, fontBoundingBoxAscent: f.size * 0.8, fontBoundingBoxDescent: f.size * 0.2, actualBoundingBoxAscent: f.size * 0.7, actualBoundingBoxDescent: 0 };+}++/** Each character's advance (a fraction of the size) in a font, as the host draws it (canvas.advances, systems/canvas+ * measure.rs): asked once per character the font's own family has; one another family stood in for is asked again, so a+ * face loaded later takes over. Undefined where there's no host to ask. */+const ADVANCES = new Map<string, Map<string, number>>();+function hostAdvances(f: { family: string; weight: string; style: string }, text: string) {+ const key = `${f.family}|${f.weight}|${f.style}`;+ let known = ADVANCES.get(key);+ if (!known) ADVANCES.set(key, (known = new Map()));+ const ask = [...new Set(text)].filter((c) => !known!.has(c));+ if (!ask.length) return known;+ const r = wire.callSync<{ adv: (number | null)[]; own: boolean[] }>("canvas.advances", { font: f, chars: ask.join("") });+ if (!r) return known.size ? known : undefined;+ const now = new Map(known);+ ask.forEach((c, i) => {+ const a = r.adv[i];+ if (a == null) return;+ now.set(c, a);+ if (r.own[i]) known!.set(c, a);+ });+ return now;+}+diff --git a/sdk/ui/src/canvas/png.ts b/sdk/ui/src/canvas/png.tsnew file mode 100644index 00000000..da23b940--- /dev/null+++ b/sdk/ui/src/canvas/png.ts@@ -0,0 +1,92 @@+// A canvas's pixels as a PNG data URL (toDataURL, and drawImage with a canvas as its source): RGBA rows in stored+// (uncompressed) deflate blocks. Big, but exact and quick to write; the host decodes it like any PNG.++const CRC = (() => {+ const t = new Uint32Array(256);+ for (let n = 0; n < 256; n++) {+ let c = n;+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;+ t[n] = c >>> 0;+ }+ return t;+})();++function crc32(b: Uint8Array, from: number, to: number) {+ let c = 0xffffffff;+ for (let i = from; i < to; i++) c = CRC[(c ^ b[i]) & 0xff] ^ (c >>> 8);+ return (c ^ 0xffffffff) >>> 0;+}++const B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";++/** base64 without btoa (the host's engines may not have it). */+export function base64(b: Uint8Array): string {+ const out: string[] = [];+ let line = "";+ for (let i = 0; i < b.length; i += 3) {+ const n = (b[i] << 16) | ((b[i + 1] ?? 0) << 8) | (b[i + 2] ?? 0);+ line += B64[(n >> 18) & 63] + B64[(n >> 12) & 63] + (i + 1 < b.length ? B64[(n >> 6) & 63] : "=") + (i + 2 < b.length ? B64[n & 63] : "=");+ if (line.length >= 8192) {+ out.push(line);+ line = "";+ }+ }+ out.push(line);+ return out.join("");+}++/** w×h RGBA (straight alpha, as ImageData holds it) as PNG bytes. */+export function encodePng(w: number, h: number, rgba: Uint8ClampedArray | Uint8Array): Uint8Array {+ const row = w * 4 + 1;+ const raw = row * h;+ // zlib: header, stored blocks of at most 65535 bytes, adler32+ const blocks = Math.max(1, Math.ceil(raw / 65535));+ const zlen = 2 + raw + blocks * 5 + 4;+ const out = new Uint8Array(8 + 25 + 12 + zlen + 12);+ const dv = new DataView(out.buffer);+ out.set([137, 80, 78, 71, 13, 10, 26, 10], 0);+ let p = 8;+ const chunk = (type: string, len: number, body: (at: number) => void) => {+ dv.setUint32(p, len);+ for (let i = 0; i < 4; i++) out[p + 4 + i] = type.charCodeAt(i);+ body(p + 8);+ dv.setUint32(p + 8 + len, crc32(out, p + 4, p + 8 + len));+ p += 12 + len;+ };+ chunk("IHDR", 13, (at) => {+ dv.setUint32(at, w);+ dv.setUint32(at + 4, h);+ out.set([8, 6, 0, 0, 0], at + 8);+ });+ chunk("IDAT", zlen, (at) => {+ out[at] = 0x78;+ out[at + 1] = 0x01;+ let q = at + 2;+ let a = 1;+ let b = 0;+ let left = raw;+ let i = 0; // index into the filtered stream (a 0 filter byte, then the row)+ while (left > 0 || q === at + 2) {+ const n = Math.min(65535, left);+ out[q] = left - n === 0 ? 1 : 0;+ out[q + 1] = n & 0xff;+ out[q + 2] = n >> 8;+ out[q + 3] = ~n & 0xff;+ out[q + 4] = (~n >> 8) & 0xff;+ q += 5;+ for (let k = 0; k < n; k++, i++) {+ const y = Math.floor(i / row);+ const x = i - y * row;+ const v = x === 0 ? 0 : rgba[y * w * 4 + x - 1];+ out[q++] = v;+ a = (a + v) % 65521;+ b = (b + a) % 65521;+ }+ left -= n;+ if (n === 0) break;+ }+ dv.setUint32(q, ((b << 16) | a) >>> 0);+ });+ chunk("IEND", 0, () => {});+ return out;+}diff --git a/sdk/ui/src/dom.ts b/sdk/ui/src/dom.tsindex 3cdc075d..ca941414 100644--- a/sdk/ui/src/dom.ts+++ b/sdk/ui/src/dom.ts@@ -18,9 +18,9 @@// - ResizeObserver and IntersectionObserver report from the snapshot, MutationObserver from the mirror's mutations,// requestAnimationFrame runs once a frame after the snapshot.//-// Left out on purpose: innerHTML parsing, Range and Selection (a stub), shadow DOM (ShadowRoot exists for instanceof+// Left out on purpose: the HTML5 tree builder (innerHTML and DOMParser use the composition parser), shadow DOM (ShadowRoot exists for instanceof// checks only), CSSOM stylesheets (a <style> element is kept in head, never applied), layout of elements that aren't// connected, navigation (links and form submission do nothing past their events), iframes and windows.-export { setRunner, apiMisses, EventTarget_, Event_, CustomEvent_, UIEvent_, FocusEvent_, MouseEvent_, PointerEvent_, WheelEvent_, KeyboardEvent_, InputEvent_, SubmitEvent_, AnimationEvent_, TransitionEvent_, TouchEvent_, CompositionEvent_, ClipboardEvent_, DragEvent_, Node_, Text_, Comment_, DocumentFragment_, ShadowRoot_, Element_, HTMLElement_, focusable, HTMLInputElement_, HTMLTextAreaElement_, HTMLButtonElement_, HTMLSelectElement_, HTMLOptionElement_, HTMLFormElement_, HTMLAnchorElement_, HTMLLabelElement_, HTMLDivElement_, HTMLSpanElement_, HTMLUListElement_, HTMLLIElement_, setPageUrl, HTMLImageElement_, HTMLMediaElement_, HTMLStyleElement_, HTMLBodyElement_, HTMLHtmlElement_, HTMLHeadElement_, HTMLIFrameElement_, HTMLDialogElement_, HTMLCanvasElement_, SVGElement_, SVGSVGElement_, hostElement, hostText, hostUpdate, mirrorPlace, mirrorRemove, mirrorText, mirrorClear, listenFor, reactContainer, getComputedStyle, DOMRectReadOnly_, DOMRect_, NodeFilter_, TreeWalker_, Document_, MutationObserver_, ResizeObserver_, IntersectionObserver_, matchMedia, requestAnimationFrame, cancelAnimationFrame, effStyle, adoptDocument, setSheet, container, resetMount, layout, install } from "./dom/all";+export { setRunner, apiMisses, EventTarget_, Event_, CustomEvent_, UIEvent_, FocusEvent_, MouseEvent_, PointerEvent_, WheelEvent_, KeyboardEvent_, InputEvent_, SubmitEvent_, AnimationEvent_, TransitionEvent_, TouchEvent_, CompositionEvent_, ClipboardEvent_, DragEvent_, Node_, Text_, Comment_, DocumentFragment_, ShadowRoot_, Element_, HTMLElement_, focusable, HTMLInputElement_, HTMLTextAreaElement_, HTMLButtonElement_, HTMLSelectElement_, HTMLOptionElement_, HTMLFormElement_, HTMLAnchorElement_, HTMLLabelElement_, HTMLDivElement_, HTMLSpanElement_, HTMLUListElement_, HTMLLIElement_, setPageUrl, HTMLImageElement_, HTMLMediaElement_, HTMLStyleElement_, HTMLBodyElement_, HTMLHtmlElement_, HTMLHeadElement_, HTMLIFrameElement_, HTMLDialogElement_, HTMLCanvasElement_, SVGElement_, SVGSVGElement_, hostElement, hostText, hostUpdate, innerHtmlProp, mirrorPlace, mirrorRemove, mirrorText, mirrorClear, listenFor, reactContainer, getComputedStyle, DOMRectReadOnly_, DOMRect_, NodeFilter_, TreeWalker_, Document_, MutationObserver_, ResizeObserver_, IntersectionObserver_, matchMedia, requestAnimationFrame, cancelAnimationFrame, effStyle, adoptDocument, setSheet, container, resetMount, layout, install } from "./dom/all";diff --git a/sdk/ui/src/dom/all.ts b/sdk/ui/src/dom/all.tsindex aa10f1ee..e49e085a 100644--- a/sdk/ui/src/dom/all.ts+++ b/sdk/ui/src/dom/all.ts@@ -11,5 +11,10 @@ export * from "./keys";export * from "./computed";export * from "./selectors";export * from "./document";+export * from "./selection";+export * from "./caret";+export * from "./moves";+export * from "./editing";+export * from "./parser";export * from "./core";export * from "./frame";diff --git a/sdk/ui/src/dom/caret.ts b/sdk/ui/src/dom/caret.tsnew file mode 100644index 00000000..56996b3e--- /dev/null+++ b/sdk/ui/src/dom/caret.ts@@ -0,0 +1,108 @@+// Text geometry the host lays out (docs/ts-native.feature P14a): a range's client rects, and the caret position at a+// point (caretPositionFromPoint, caretRangeFromPoint). The host answers from the page as the JS wrote it (raea-page's+// `text.rects` and `caret.at`, synchronous calls); without one (tests) the text is taken as one line in its parent's+// box at a fixed advance, enough to keep a caller's arithmetic going.+import * as wire from "../wire";+import { DOMRect_, Element_, Node_, Range_, Text_, body, computedOf, doc, hit } from "./all";++/** a character's advance where there's no host to ask: of the parent's font size */+function advance(t: Text_): number {+ const p = t.parentNode;+ const fs = p instanceof Element_ ? parseFloat(String(computedOf(p).fontSize ?? "16")) || 16 : 16;+ return fs * 0.55;+}++/** rects for one text's part [a, b): the host's, else the estimate */+function estimate(t: Text_, a: number, b: number): DOMRect_[] {+ const p = t.parentNode;+ if (!(p instanceof Element_)) return [];+ const box = p.getBoundingClientRect();+ const w = advance(t);+ // the text's start: after the texts before it in the same parent+ let before = 0;+ for (const k of p._kids) {+ if (k === t) break;+ before += (k.textContent ?? "").length;+ }+ const h = Math.max(box.height, w / 0.55) || w / 0.55;+ return [new DOMRect_(box.left + (before + a) * w, box.top, (b - a) * w, Math.min(h, (w / 0.55) * 1.25))];+}++/** A range's client rects, as Chrome's Range.getClientRects: one per line box of each text it covers (a collapsed+ * range in a text: the caret's zero-width rect). */+export function rangeRects(r: Range_): DOMRect_[] {+ const texts = r._texts().filter(([t, a, b]) => t.isConnected && (a < b || r.collapsed));+ if (!texts.length) return [];+ const wired = texts.filter(([t]) => t._wired && t.__wid !== undefined);+ let host: number[][][] | undefined;+ if (wired.length === texts.length) {+ try {+ host = wire.callSync<number[][][]>("text.rects", { spans: wired.map(([t, a, b]) => [t.__wid, a, b]) });+ } catch {+ host = undefined;+ }+ }+ const out: DOMRect_[] = [];+ texts.forEach(([t, a, b], i) => {+ const rs = host?.[i];+ if (rs) for (const [x, y, w, h] of rs) out.push(new DOMRect_(x, y, w, h));+ else out.push(...estimate(t, a, b));+ });+ return out;+}++/** The node on the host as wire id `id`: an element or a text. */+export function nodeByWid(id: number, from: Node_ = doc): Node_ | null {+ if (from.__wid === id && from._wired) return from;+ for (const k of from._kids) {+ const n = nodeByWid(id, k);+ if (n) return n;+ }+ return null;+}++export class CaretPosition_ {+ constructor(+ public offsetNode: Node_,+ public offset: number,+ ) {}+ getClientRect(): DOMRect_ | null {+ const r = new Range_();+ r.setStart(this.offsetNode, this.offset);+ return r.getBoundingClientRect();+ }+}++/** The caret position at (x, y): the host's (its text hit testing), else the nearest of the element there's texts. */+export function caretAt(x: number, y: number): CaretPosition_ | null {+ let ans: { id: number; offset: number } | null | undefined;+ try {+ ans = wire.callSync<{ id: number; offset: number } | null>("caret.at", { x, y });+ } catch {+ ans = undefined;+ }+ if (ans) {+ const n = nodeByWid(ans.id);+ if (n instanceof Text_) return new CaretPosition_(n, Math.min(ans.offset, n.data.length));+ if (n instanceof Element_) {+ // the element's own string, or a point between its children+ if (n._inline !== undefined) return new CaretPosition_(n, 0);+ return new CaretPosition_(n, Math.min(ans.offset, n._kids.length));+ }+ }+ const el = hit(body, x, y);+ if (!el) return null;+ const t = el._kids.find((k): k is Text_ => k instanceof Text_);+ if (!t) return new CaretPosition_(el, 0);+ const [r] = estimate(t, 0, 0);+ const o = r ? Math.round((x - r.left) / advance(t)) : 0;+ return new CaretPosition_(t, Math.max(0, Math.min(t.data.length, o)));+}++export function caretRangeAt(x: number, y: number): Range_ | null {+ const p = caretAt(x, y);+ if (!p) return null;+ const r = new Range_();+ r.setStart(p.offsetNode, p.offset);+ return r;+}diff --git a/sdk/ui/src/dom/core.ts b/sdk/ui/src/dom/core.tsindex 6cade545..7245dbff 100644--- a/sdk/ui/src/dom/core.ts+++ b/sdk/ui/src/dom/core.ts@@ -1,7 +1,7 @@// The layout snapshot, the runner, the API scan, install (window and document) and an HTML page: what the parts share.import * as wire from "../wire";import { canvasGlobals } from "../canvas";-import { AnimationEvent_, ClipboardEvent_, Comment_, CompositionEvent_, CustomEvent_, DOMRectReadOnly_, DOMRect_, DocumentFragment_, Document_, DragEvent_, Element_, EventTarget_, Event_, FocusEvent_, HTMLAnchorElement_, HTMLBodyElement_, HTMLButtonElement_, HTMLCanvasElement_, HTMLDialogElement_, HTMLDivElement_, HTMLElement_, HTMLFormElement_, HTMLHeadElement_, HTMLHtmlElement_, HTMLIFrameElement_, HTMLImageElement_, HTMLInputElement_, HTMLLIElement_, HTMLLabelElement_, HTMLMediaElement_, HTMLOptionElement_, HTMLSelectElement_, HTMLSpanElement_, HTMLStyleElement_, HTMLTextAreaElement_, HTMLUListElement_, InputEvent_, IntersectionObserver_, KeyboardEvent_, MediaNews, MouseEvent_, MutationObserver_, NodeFilter_, Node_, PointerEvent_, ResizeObserver_, SVGElement_, SVGSVGElement_, ShadowRoot_, SubmitEvent_, Text_, TouchEvent_, TransitionEvent_, TreeWalker_, UIEvent_, WheelEvent_, addListener, cancelAnimationFrame, cssEscape, dispatch, fontWaits, getComputedStyle, heard, key, keyUp, makeElement, matchMedia, materialize, mediaNews, mirrorPlace, mirrorRemove, onLayout, query, reactContainer, removeListener, requestAnimationFrame, syncRoot, wireOf } from "./all";+import { AnimationEvent_, ClipboardEvent_, FontFace_, Comment_, CompositionEvent_, CustomEvent_, DOMRectReadOnly_, DOMRect_, DocumentFragment_, Document_, DragEvent_, Element_, EventTarget_, Event_, FocusEvent_, HTMLAnchorElement_, HTMLBodyElement_, HTMLButtonElement_, HTMLCanvasElement_, HTMLDialogElement_, HTMLDivElement_, HTMLElement_, HTMLFormElement_, HTMLHeadElement_, HTMLHtmlElement_, HTMLIFrameElement_, HTMLImageElement_, HTMLInputElement_, HTMLLIElement_, HTMLLabelElement_, HTMLMediaElement_, HTMLOptionElement_, HTMLSelectElement_, HTMLSpanElement_, HTMLStyleElement_, HTMLTextAreaElement_, HTMLUListElement_, InputEvent_, IntersectionObserver_, KeyboardEvent_, MediaNews, MouseEvent_, MutationObserver_, NodeFilter_, Node_, DOMParser_, Range_, Selection_, CaretPosition_, markEditing, resetSelection, selection, PointerEvent_, ResizeObserver_, SVGElement_, SVGSVGElement_, ShadowRoot_, SubmitEvent_, Text_, TouchEvent_, TransitionEvent_, TreeWalker_, UIEvent_, WheelEvent_, addListener, cancelAnimationFrame, cssEscape, dispatch, fontWaits, getComputedStyle, heard, key, keyUp, makeElement, matchMedia, materialize, mediaNews, mirrorPlace, mirrorRemove, onLayout, plainClasses, query, reactContainer, removeListener, requestAnimationFrame, syncRoot, wireOf } from "./all";export const g = globalThis as any;@@ -267,6 +267,7 @@ export function resetMount() {S.wantFocus = undefined;S.spaceDown = null;S.downTarget = S.pointerCapture = null;+ resetSelection();geo.clear();heard.delete(rootContainer);syncRoot();@@ -321,8 +322,11 @@ export function install() {HTMLSelectElement: HTMLSelectElement_, HTMLOptionElement: HTMLOptionElement_, HTMLFormElement: HTMLFormElement_, HTMLAnchorElement: HTMLAnchorElement_, HTMLLabelElement: HTMLLabelElement_,HTMLDivElement: HTMLDivElement_, HTMLSpanElement: HTMLSpanElement_, HTMLUListElement: HTMLUListElement_, HTMLLIElement: HTMLLIElement_, HTMLImageElement: HTMLImageElement_, HTMLMediaElement: HTMLMediaElement_, HTMLVideoElement: HTMLMediaElement_, HTMLAudioElement: HTMLMediaElement_, HTMLStyleElement: HTMLStyleElement_,HTMLBodyElement: HTMLBodyElement_, HTMLHtmlElement: HTMLHtmlElement_, HTMLHeadElement: HTMLHeadElement_, HTMLIFrameElement: HTMLIFrameElement_, HTMLDialogElement: HTMLDialogElement_, HTMLCanvasElement: HTMLCanvasElement_, ...canvasGlobals(),+ DOMParser: DOMParser_, Range: Range_, Selection: Selection_, CaretPosition: CaretPosition_,DOMRect: DOMRect_, DOMRectReadOnly: DOMRectReadOnly_, NodeFilter: NodeFilter_, TreeWalker: TreeWalker_,MutationObserver: MutationObserver_, ResizeObserver: ResizeObserver_, IntersectionObserver: IntersectionObserver_,+ FontFace: FontFace_,+ ...plainClasses,};for (const [k, v] of Object.entries(classes)) {put(k, v);@@ -347,7 +351,7 @@ export function install() {put("cancelAnimationFrame", cancelAnimationFrame);g.requestIdleCallback ??= (fn: (d: unknown) => void) => setTimeout(() => fn({ didTimeout: false, timeRemaining: () => 0 }), 1);g.cancelIdleCallback ??= (id: number) => clearTimeout(id);- put("getSelection", () => ({ rangeCount: 0, isCollapsed: true, type: "None", anchorNode: null, focusNode: null, removeAllRanges() {}, addRange() {}, getRangeAt() {}, collapse() {}, toString: () => "" }));+ put("getSelection", () => selection);put("scrollTo", () => {});put("scrollBy", () => {});put("scroll", () => {});@@ -396,6 +400,8 @@ export function install() {}});g.__ui_layout = onLayout;+ // contenteditable edits as Chrome's (editing.ts, P14e): a rich-text editor (Tiptap) can rely on this+ markEditing();if (scanning) {Object.setPrototypeOf(EventTarget_.prototype, scanProxy("EventTarget"));Object.setPrototypeOf(Event_.prototype, scanProxy("Event"));diff --git a/sdk/ui/src/dom/document.ts b/sdk/ui/src/dom/document.tsindex 4a2a7ccf..6719e81d 100644--- a/sdk/ui/src/dom/document.ts+++ b/sdk/ui/src/dom/document.ts@@ -1,6 +1,6 @@// TreeWalker and NodeFilter, and the Document.import * as wire from "../wire";-import { Comment_, CustomEvent_, DOMRect_, DocumentFragment_, Element_, Event_, HTML_NS, KeyboardEvent_, MouseEvent_, Node_, S, Text_, body, g, head, hit, html, makeElement, nodeList, query } from "./all";+import { Comment_, CustomEvent_, DocumentFragment_, Range_, caretAt, caretRangeAt, implementation, selection, Element_, Event_, HTML_NS, KeyboardEvent_, MouseEvent_, Node_, S, Text_, body, g, head, hit, html, makeElement, nodeList, query } from "./all";// ---------------------------------------------------------------- TreeWalker@@ -149,26 +149,159 @@ const fontsLoaded = () =>if (fontWaits.length === 1) wire.emit("fonts.wait", true);});+// FontFace (the CSS Font Loading API): a face made in script becomes an @font-face rule in one sheet of the page's+// own (<style data-raea-fonts> in body), which the host loads as it loads any sheet's faces; load() and `loaded`+// settle as document.fonts does, once nothing is still loading. Excalidraw makes its fonts this way.+const faces = new Set<FontFace_>();+let faceSheet: Element_ | null = null;++const cssString = (s: string) => `"${s.replace(/["\\]/g, "\\$&")}"`;++function writeFaces() {+ const css = [...faces]+ .map((f) => `@font-face{font-family:${cssString(f.family)};src:${f._src};font-style:${f.style};font-weight:${f.weight};font-stretch:${f.stretch};unicode-range:${f.unicodeRange};font-display:${f.display}}`)+ .join("\n");+ if (!faceSheet) {+ faceSheet = makeElement("style");+ faceSheet.setAttribute("data-raea-fonts", "");+ body.appendChild(faceSheet);+ }+ if (faceSheet.textContent !== css) faceSheet.textContent = css;+}++/** A font's bytes as a data URL, for a face made from an ArrayBuffer or a typed array. */+function bytesUrl(src: ArrayBuffer | ArrayBufferView): string {+ const b = src instanceof ArrayBuffer ? new Uint8Array(src) : new Uint8Array(src.buffer, src.byteOffset, src.byteLength);+ let s = "";+ for (let i = 0; i < b.length; i += 0x8000) s += String.fromCharCode(...b.subarray(i, i + 0x8000));+ return `url(data:font/ttf;base64,${btoa(s)})`;+}++type FaceDescriptors = { style?: string; weight?: string; stretch?: string; unicodeRange?: string; display?: string; featureSettings?: string };++export class FontFace_ {+ family: string;+ style = "normal";+ weight = "normal";+ stretch = "normal";+ unicodeRange = "U+0-10FFFF";+ display = "auto";+ featureSettings = "normal";+ variant = "normal";+ status: "unloaded" | "loading" | "loaded" | "error" = "unloaded";+ /** the rule's src: the url()/local() list as given, or the bytes as a data URL */+ _src: string;+ loaded: Promise<FontFace_>;+ private _done!: (f: FontFace_) => void;+ constructor(family: string, source: string | ArrayBuffer | ArrayBufferView, descriptors: FaceDescriptors = {}) {+ this.family = String(family).replace(/^["']|["']$/g, "");+ for (const k of Object.keys(descriptors) as (keyof FaceDescriptors)[]) if (descriptors[k] !== undefined) (this as any)[k] = String(descriptors[k]);+ this._src = typeof source === "string" ? source : bytesUrl(source);+ this.loaded = new Promise((done) => (this._done = done));+ // a face from bytes is loaded once made, as in Chrome (its data is already here)+ if (typeof source !== "string") this.load();+ }+ load(): Promise<FontFace_> {+ if (this.status === "unloaded") {+ this.status = "loading";+ // a face loads by being in the page's sheet, so one loaded by hand joins it as add() would+ faces.add(this);+ writeFaces();+ void fontsLoaded().then(() => {+ this.status = "loaded";+ this._done(this);+ fontSet._loaded(this);+ });+ }+ return this.loaded;+ }+}++/** The families a CSS font shorthand names ("bold 20px Excalifont, sans-serif" -> Excalifont, sans-serif). */+function familiesOf(font: string): string[] {+ const m = font.match(/(?:^|\s)[\d.]+(?:px|pt|em|rem|%|vh|vw)(?:\/\S+)?\s+(.+)$/);+ return (m ? m[1] : font).split(",").map((f) => f.trim().replace(/^["']|["']$/g, "")).filter(Boolean);+}++type FontsListener = ((e: { type: string; fontfaces: FontFace_[] }) => void) | { handleEvent(e: unknown): void };+class FontFaceSet_ {- status = "loaded";+ onloading: unknown = null;+ onloadingdone: unknown = null;+ onloadingerror: unknown = null;+ private listeners = new Map<string, Set<FontsListener>>();+ private done: FontFace_[] = [];+ get status() {+ return [...faces].some((f) => f.status === "loading") ? "loading" : "loaded";+ }get ready() {return fontsLoaded().then(() => this);}- load(_font: string, _text?: string) {- return fontsLoaded().then(() => []);+ /** As in Chrome: the faces of the font's families start loading, and the promise has those loaded. */+ load(font: string, _text?: string) {+ const names = new Set(familiesOf(font));+ const mine = [...faces].filter((f) => names.has(f.family));+ return Promise.all(mine.map((f) => f.load())).then(() => mine.filter((f) => f.status === "loaded"));+ }+ /** False while a face of one of the font's families is in the set but not loaded, as in Chrome; Excalidraw waits on+ * this, and measured text in the fallback when it always said true. */+ check(font: string, _text?: string) {+ const names = new Set(familiesOf(font));+ const mine = [...faces].filter((f) => names.has(f.family));+ return !mine.length || mine.some((f) => f.status === "loaded");+ }+ /** A face finished loading: one loadingdone for the faces done in this turn, which is how Excalidraw learns to+ * redraw text it drew in the fallback. */+ _loaded(f: FontFace_) {+ this.done.push(f);+ if (this.done.length > 1) return;+ queueMicrotask(() => {+ const fontfaces = this.done;+ this.done = [];+ const e = { type: "loadingdone", fontfaces };+ if (typeof this.onloadingdone === "function") (this.onloadingdone as (e: unknown) => void)(e);+ for (const l of [...(this.listeners.get("loadingdone") ?? [])]) typeof l === "function" ? l(e) : l.handleEvent(e);+ });+ }+ add(f: FontFace_) {+ if (!faces.has(f)) {+ faces.add(f);+ writeFaces();+ }+ return this;+ }+ delete(f: FontFace_) {+ const had = faces.delete(f);+ if (had) writeFaces();+ return had;}- check(_font: string, _text?: string) {- return true;+ clear() {+ faces.clear();+ writeFaces();}get size() {- return 0;+ return faces.size;}- forEach() {}- has() {- return false;+ forEach(fn: (f: FontFace_, k: FontFace_, set: FontFaceSet_) => void) {+ for (const f of faces) fn(f, f, this);+ }+ has(f: FontFace_) {+ return faces.has(f);+ }+ values() {+ return faces.values();+ }+ [Symbol.iterator]() {+ return faces.values();+ }+ addEventListener(type: string, l: FontsListener | null) {+ if (!l) return;+ if (!this.listeners.has(type)) this.listeners.set(type, new Set());+ this.listeners.get(type)!.add(l);+ }+ removeEventListener(type: string, l: FontsListener | null) {+ if (l) this.listeners.get(type)?.delete(l);}- addEventListener() {}- removeEventListener() {}}const fontSet = new FontFaceSet_();@@ -272,11 +405,22 @@ export class Document_ extends Node_ {hasFocus() {return true;}+ get implementation() {+ return implementation;+ }getSelection() {- return g.getSelection();+ return selection;}createRange() {- return { setStart() {}, setEnd() {}, selectNodeContents() {}, collapse() {}, getBoundingClientRect: () => new DOMRect_(), getClientRects: () => [], cloneContents: () => new DocumentFragment_(), commonAncestorContainer: body };+ const r = new Range_();+ r.setStart(this, 0);+ return r;+ }+ caretPositionFromPoint(x: number, y: number) {+ return caretAt(x, y);+ }+ caretRangeFromPoint(x: number, y: number) {+ return caretRangeAt(x, y);}execCommand() {return false;diff --git a/sdk/ui/src/dom/editing.ts b/sdk/ui/src/dom/editing.tsnew file mode 100644index 00000000..673044c1--- /dev/null+++ b/sdk/ui/src/dom/editing.ts@@ -0,0 +1,353 @@+// contenteditable as Chrome edits it (docs/ts-native.feature P14a): the editing host and isContentEditable, and a+// key's or the pointer's default action in one: keypress, beforeinput (cancellable), the DOM changed in place (real+// mutation records: characterData with its old value, childList), then input. ProseMirror reads those back, so typing,+// Backspace, Delete, arrows and the pointer work as in Chrome, and what it handles itself (Enter, Mod-B) it prevents.+import * as wire from "../wire";+import { ClipboardEvent_, Element_, InputEvent_, KeyboardEvent_, Node_, S, Text_, blockAt, blockOf, charStep, clearGoal, dispatch, doc, g, lineEdge, lineStep, modify, moveTo, nodeLength, selection, syncListens, textsIn, wordAt, wordStep } from "./all";++type Pos = [Node_, number];++// ---------------------------------------------------------------- the editing host++const EDITABLE = new Set(["", "true", "plaintext-only"]);++/** an element's own contenteditable: true, false, or inherited (null) */+function own(el: Element_): boolean | null {+ const a = el.getAttribute("contenteditable");+ if (a === null) {+ const p = el._props.contentEditable;+ if (p === true || p === "true" || p === "") return true;+ if (p === false || p === "false") return false;+ return null;+ }+ return EDITABLE.has(a.toLowerCase()) ? true : a.toLowerCase() === "false" ? false : null;+}++export function isEditable(el: Element_): boolean {+ for (let n: Node_ | null = el; n instanceof Element_; n = n.parentNode) {+ const o = own(n);+ if (o !== null) return o;+ }+ return false;+}++/** the editing host `n` is in: the outermost editable element up from it */+export function editingHost(n: Node_ | null): Element_ | null {+ let host: Element_ | null = null;+ for (let x: Node_ | null = n; x instanceof Element_ || x instanceof Text_; x = x.parentNode) {+ if (!(x instanceof Element_)) continue;+ const o = own(x);+ if (o === true) host = x;+ else if (o === false) break;+ }+ return host;+}++/** an editing host itself (focusable, as Chrome makes one) */+export const isEditingHost = (el: Element_) => own(el) === true && !(el.parentNode instanceof Element_ && isEditable(el.parentNode));++/** contenteditable set or removed: the host's tabIndex and its keys follow */+export function editableChanged(el: Element_) {+ if (!el._wired || el.__wid === undefined) return;+ if (isEditingHost(el) && !el.hasAttribute("tabindex")) wire.set(el.__wid, "tabIndex", 0);+ syncListens(el);+}++/** the editing host the selection's focus is in, when it has the focus */+function activeHost(): Element_ | null {+ const f = selection.focusNode;+ const h = editingHost(f);+ return h && S.active && (S.active === h || S.active.contains(h)) ? h : null;+}++(globalThis as { __raea_modify?: unknown }).__raea_modify = (s: typeof selection, a: string, d: string, gr: string) => modify(s, a, d, gr, editingHost(s.focusNode));++/** A focused editing host with no selection in it: the caret at its start (Chrome's focus()) */+export function focusedHost(el: Element_) {+ if (!isEditingHost(el)) return;+ if (selection.focusNode && el.contains(selection.focusNode)) return selection._changed(true);+ const t = textsIn(el)[0];+ selection.collapse(t ?? el, 0);+}++// ---------------------------------------------------------------- the edits++/** beforeinput (cancellable), the edit, then input: Chrome's order. Returns whether the edit ran. */+function edit(host: Element_, inputType: string, data: string | null, run: () => void): boolean {+ const init = { bubbles: true, cancelable: true, composed: true, inputType, data, isComposing: false, view: g };+ if (!dispatch(host, new InputEvent_("beforeinput", init), true)) return false;+ run();+ dispatch(host, new InputEvent_("input", { ...init, cancelable: false }), true);+ return true;+}++/** the selection's contents gone, the caret where they were */+function deleteSelection() {+ const r = selection.rangeCount ? selection.getRangeAt(0) : null;+ if (!r || r.collapsed) return;+ r.deleteContents();+ selection.collapse(r.startContainer, r.startOffset);+}++/** an element's own string (React's text content) as a real text child, so an edit has a node to change */+function ownText(el: Element_) {+ if (el._inline === undefined) return;+ const s = el._inline;+ el.textContent = "";+ el._inline = undefined;+ if (el._wired && el.__wid !== undefined) wire.text(el.__wid, "");+ el.appendChild(doc.createTextNode(s));+}++/** text put in at the caret: into the text it's in or beside, else a new text (an empty block's `<br>` replaced) */+export function insertText(s: string) {+ deleteSelection();+ let n = selection.focusNode;+ let o = selection.focusOffset;+ if (!n) return;+ if (n instanceof Element_ && n._inline !== undefined) {+ const at = o ? n._inline.length : 0;+ ownText(n);+ [n, o] = [n.firstChild!, at];+ }+ if (n instanceof Text_) {+ n.insertData(o, s);+ selection.collapse(n, o + s.length);+ return;+ }+ const before = n._kids[o - 1];+ const after = n._kids[o];+ if (before instanceof Text_) {+ before.appendData(s);+ selection.collapse(before, before.data.length);+ } else if (after instanceof Text_) {+ after.insertData(0, s);+ selection.collapse(after, s.length);+ } else {+ const t = doc.createTextNode(s);+ // an empty block's placeholder break goes as text comes in+ if (after instanceof Element_ && after.localName === "br" && !after.nextSibling) n.replaceChild(t, after);+ else n.insertBefore(t, after ?? null);+ selection.collapse(t, s.length);+ }+}++/** a character back or on deleted (or the selection): within a text, or two blocks joined at their edge */+function deleteChar(dir: -1 | 1, host: Element_) {+ if (!selection.isCollapsed) return deleteSelection();+ const f: Pos = [selection.focusNode!, selection.focusOffset];+ const to = charStep(f, dir, host);+ if (to[0] === f[0] && to[1] === f[1]) return;+ const [a, b] = dir < 0 ? [to, f] : [f, to];+ const ba = blockOf(a[0], host);+ const bb = blockOf(b[0], host);+ if (ba !== bb && bb !== host && ba.contains(bb) === false && bb.contains(ba) === false) {+ // the later block's contents into the earlier one, and it gone+ const keep = a;+ for (const k of bb._kids.slice()) ba.appendChild(k);+ bb.remove();+ for (const br of ba._kids.filter((k) => k instanceof Element_ && k.localName === "br" && k !== ba.lastChild)) br.remove();+ selection.collapse(keep[0], Math.min(keep[1], nodeLength(keep[0])));+ return;+ }+ selection.setBaseAndExtent(a[0], a[1], b[0], b[1]);+ deleteSelection();+}++/** Enter: the block split at the caret (a new one of the same kind after it), as Chrome's insertParagraph */+function splitBlock(host: Element_) {+ deleteSelection();+ const n = selection.focusNode!;+ const o = selection.focusOffset;+ const b = blockOf(n, host);+ if (b === host) {+ // a host with no blocks: what's after the caret into a div+ const div = doc.createElement("div");+ moveAfter(host, n, o, div);+ host.appendChild(div);+ if (!div.firstChild) div.appendChild(doc.createElement("br"));+ selection.collapse(textsIn(div)[0] ?? div, 0);+ return;+ }+ const nb = b.cloneNode(false) as Element_;+ moveAfter(b, n, o, nb);+ b.parentNode!.insertBefore(nb, b.nextSibling);+ if (!textsIn(b).some((t) => t.data)) b.appendChild(doc.createElement("br"));+ if (!nb.firstChild) nb.appendChild(doc.createElement("br"));+ selection.collapse(textsIn(nb)[0] ?? nb, 0);+}++/** what's after (n, o) in `from` moved into `to` (a text split at the point) */+function moveAfter(from: Element_, n: Node_, o: number, to: Element_) {+ let start: Node_;+ if (n instanceof Text_) start = o < n.data.length ? (o ? n.splitText(o) : n) : n.nextSibling!;+ else start = n._kids[o];+ if (!start) return;+ // up to the child of `from` the point is in+ while (start && start.parentNode !== from) start = start.parentNode!.nextSibling ?? start.parentNode!;+ for (let k: Node_ | null = start; k; ) {+ const next: Node_ | null = k.nextSibling;+ to.appendChild(k);+ k = next;+ }+}++// ---------------------------------------------------------------- clipboard (the page's own, as the window has none)++let clipboard = "";++function clipboardEvent(type: string, data: string) {+ const store = new Map<string, string>([["text/plain", data]]);+ const ev = new ClipboardEvent_(type, { bubbles: true, cancelable: true, composed: true }) as ClipboardEvent_ & { clipboardData: unknown };+ ev.clipboardData = {+ types: ["text/plain"],+ getData: (t: string) => store.get(t === "text" ? "text/plain" : t) ?? "",+ setData: (t: string, v: string) => void store.set(t === "text" ? "text/plain" : t, String(v)),+ clearData: () => store.clear(),+ items: [],+ files: [],+ };+ return { ev, store };+}++// ---------------------------------------------------------------- keys and the pointer++const mac = () => /Mac/.test(String(g.navigator?.platform ?? ""));++/** A key's default action in a focused editing host, after its keydown went unprevented. Returns whether it acted+ * (the host's own default, a scroll, is then prevented). */+export function editKey(t: Element_, init: { key: string; shiftKey: boolean; ctrlKey: boolean; altKey: boolean; metaKey: boolean; keyCode: number }): boolean {+ const host = activeHost() ?? (isEditable(t) ? editingHost(t) : null);+ if (!host || !selection.focusNode) return false;+ const k = init.key;+ const mod = mac() ? init.metaKey : init.ctrlKey;+ const ext = init.shiftKey;+ const f: Pos = [selection.focusNode, selection.focusOffset];+ const collapseTo = (dir: -1 | 1): Pos => {+ const r = selection.getRangeAt(0);+ return dir < 0 ? [r.startContainer, r.startOffset] : [r.endContainer, r.endOffset];+ };+ const word = mac() ? init.altKey : init.ctrlKey;+ if (k !== "ArrowUp" && k !== "ArrowDown") clearGoal();+ switch (k) {+ case "ArrowLeft":+ case "ArrowRight": {+ const dir = k === "ArrowLeft" ? -1 : 1;+ if (!ext && !selection.isCollapsed && !word && !(mac() && init.metaKey)) moveTo(selection, collapseTo(dir), false);+ else moveTo(selection, mac() && init.metaKey ? lineEdge(f, dir, host) : word ? wordStep(f, dir, host) : charStep(f, dir, host), ext);+ return true;+ }+ case "ArrowUp":+ case "ArrowDown":+ moveTo(selection, lineStep(f, k === "ArrowUp" ? -1 : 1, host), ext);+ return true;+ case "Home":+ case "End":+ moveTo(selection, lineEdge(f, k === "Home" ? -1 : 1, host), ext);+ return true;+ case "Backspace":+ case "Delete": {+ const dir = k === "Backspace" ? -1 : 1;+ const type = word ? (dir < 0 ? "deleteWordBackward" : "deleteWordForward") : dir < 0 ? "deleteContentBackward" : "deleteContentForward";+ edit(host, type, null, () => {+ if (word && selection.isCollapsed) moveTo(selection, wordStep(f, dir, host), true);+ deleteChar(dir, host);+ });+ return true;+ }+ case "Enter":+ if (ext) edit(host, "insertLineBreak", null, () => insertBreak());+ else edit(host, "insertParagraph", null, () => splitBlock(host));+ return true;+ case "Tab":+ return false;+ default:+ break;+ }+ if (mod && !init.altKey) {+ const c = k.toLowerCase();+ if (c === "a") {+ const texts = textsIn(host);+ const last = texts[texts.length - 1];+ selection.setBaseAndExtent(texts[0] ?? host, 0, last ?? host, last ? last.data.length : host._kids.length);+ return true;+ }+ if (c === "c" || c === "x") {+ const { ev, store } = clipboardEvent(c === "c" ? "copy" : "cut", selection.toString());+ const ok = dispatch(host, ev, true);+ if (!ok || selection.toString()) clipboard = store.get("text/plain") ?? "";+ if (ok && c === "x" && !selection.isCollapsed) edit(host, "deleteByCut", null, () => deleteSelection());+ return true;+ }+ if (c === "v") {+ const { ev } = clipboardEvent("paste", clipboard);+ if (dispatch(host, ev, true) && clipboard) edit(host, "insertFromPaste", clipboard, () => insertText(clipboard));+ return true;+ }+ return false;+ }+ // a character typed: keypress, then the insert+ if (k.length && [...k].length === 1 && !init.ctrlKey && !init.metaKey) {+ const kp = new KeyboardEvent_("keypress", { ...init, bubbles: true, cancelable: true, composed: true, view: g, charCode: k.codePointAt(0), keyCode: k.codePointAt(0), which: k.codePointAt(0) });+ if (!dispatch(selection.focusNode instanceof Element_ ? selection.focusNode : (selection.focusNode.parentNode ?? host), kp, true)) return true;+ edit(host, "insertText", k, () => insertText(k));+ return true;+ }+ return false;+}++/** Shift+Enter: a `<br>` at the caret (and one more at a block's end, so the new line shows) */+function insertBreak() {+ deleteSelection();+ let n = selection.focusNode!;+ let o = selection.focusOffset;+ const br = doc.createElement("br");+ if (n instanceof Text_) {+ const rest = o < n.data.length ? n.splitText(o) : null;+ n.parentNode!.insertBefore(br, rest ?? n.nextSibling);+ [n, o] = [br.parentNode!, br.parentNode!._kids.indexOf(br) + 1];+ } else {+ n.insertBefore(br, n._kids[o] ?? null);+ o++;+ }+ if (!br.nextSibling) br.parentNode!.appendChild(doc.createElement("br"));+ selection.collapse(n, o);+}++let dragging = false;++/** The pointer in an editable (its mousedown unprevented): a press places the caret (Shift extends; two clicks pick+ * a word, three its paragraph), a drag with the button down extends, the release ends it. */+export function editPointer(kind: "down" | "move" | "up", t: Element_, x: number, y: number, p: { shiftKey?: boolean; detail?: number }) {+ if (kind === "up") {+ dragging = false;+ return;+ }+ if (kind === "move") {+ if (!dragging) return;+ const at = doc.caretPositionFromPoint(x, y);+ const host = editingHost(selection.anchorNode);+ if (at && host && host.contains(at.offsetNode)) moveTo(selection, [at.offsetNode, at.offset], true);+ return;+ }+ const host = editingHost(t);+ if (!host) return;+ clearGoal();+ const at = doc.caretPositionFromPoint(x, y);+ const pos: Pos = at && host.contains(at.offsetNode) ? [at.offsetNode, at.offset] : [textsIn(host)[0] ?? host, 0];+ const clicks = p.detail ?? 1;+ if (clicks === 2 || clicks >= 3) {+ const [a, b] = clicks === 2 ? wordAt(pos, host) : blockAt(pos, host);+ selection.setBaseAndExtent(a[0], a[1], b[0], b[1]);+ return;+ }+ moveTo(selection, pos, !!p.shiftKey && !!selection.anchorNode && host.contains(selection.anchorNode));+ dragging = true;+}++/** The page can edit rich text: a rich-text editor (Tiptap) checks `__raea_editing` before it starts+ * (set as the DOM installs) */+export function markEditing() {+ g.__raea_editing = true;+}+diff --git a/sdk/ui/src/dom/element.ts b/sdk/ui/src/dom/element.tsindex 42d14fdd..85147e37 100644--- a/sdk/ui/src/dom/element.ts+++ b/sdk/ui/src/dom/element.ts@@ -1,6 +1,6 @@// Element: attributes, classes, geometry from the layout snapshot, focus and pointer capture.import * as wire from "../wire";-import { ATTR_PROP, Comment_, DOMRect_, HTML_NS, Node_, S, body, computedOf, cssText, doc, geo, html, htmlDoc, installed, kebab, makeStyle, matchesSelector, mutated, nodeList, parseCss, parseSelector, pointerEventsOf, query, tellCapture, wireStyle } from "./all";+import { ATTR_PROP, Comment_, DOMRect_, HTML_NS, editableChanged, forceLayout, setInnerHtml, Node_, S, body, computedOf, cssText, doc, geo, html, htmlDoc, installed, kebab, makeStyle, matchesSelector, mutated, nodeList, parseCss, parseSelector, pointerEventsOf, query, tellCapture, wireStyle } from "./all";// ---------------------------------------------------------------- elements@@ -123,6 +123,7 @@ export class Element_ extends Node_ {}this._attrs.set(name, value);this._toWire(name, value);+ if (name === "contenteditable") editableChanged(this);mutated(this, { type: "attributes", attributeName: name, oldValue: old });}setAttributeNS(_ns: string | null, n: string, v: unknown) {@@ -138,6 +139,7 @@ export class Element_ extends Node_ {}this._attrs.delete(name);this._toWire(name, null);+ if (name === "contenteditable") editableChanged(this);mutated(this, { type: "attributes", attributeName: name, oldValue: old });}removeAttributeNS(_ns: string | null, n: string) {@@ -245,8 +247,7 @@ export class Element_ extends Node_ {return this._kids.map((k) => (k instanceof Element_ ? k.outerHTML : escapeHtml(k.textContent ?? ""))).join("");}set innerHTML(v: string) {- // no HTML parser: a string with no markup is its text; markup is out of scope (P18: innerHTML)- this.textContent = String(v).replace(/<[^>]*>/g, "");+ setInnerHtml(this, String(v ?? ""));}get outerHTML(): string {const attrs = [...this._attrs].map(([k, v]) => ` ${k}="${escapeHtml(v)}"`).join("");@@ -307,7 +308,9 @@ export class Element_ extends Node_ {// ---- geometry_box(): number[] | undefined {if (this === body || this === html) return undefined;- return this._wired && this.__wid !== undefined && this.isConnected ? geo.get(this.__wid) : undefined;+ if (!(this._wired && this.__wid !== undefined && this.isConnected)) return undefined;+ // placed since the page was last laid out: laid out now, as Chrome does for the read (forceLayout)+ return geo.get(this.__wid) ?? (forceLayout() ? geo.get(this.__wid) : undefined);}getBoundingClientRect(): DOMRect_ {if (this === html || this === body) return new DOMRect_(0, 0, S.vw, this === html ? S.vh : S.vh);diff --git a/sdk/ui/src/dom/frame.ts b/sdk/ui/src/dom/frame.tsindex 55f1406f..d971e80e 100644--- a/sdk/ui/src/dom/frame.ts+++ b/sdk/ui/src/dom/frame.ts@@ -1,4 +1,5 @@// The observers, matchMedia, and the frame: snapshot, observers, requestAnimationFrame.+import * as wire from "../wire";import { DOMRectReadOnly_, Document_, Element_, EventTarget_, Event_, Node_, S, STRIDE, UIEvent_, body, computedOf, dispatch, dispatchDirect, doc, g, geo, html, nodeList, reportMisses, run, scanning } from "./all";// ---------------------------------------------------------------- observers@@ -303,9 +304,36 @@ if (frameClock && g.performance) {Object.defineProperty(g.performance, "now", { value: now, configurable: true, writable: true });}+/** The ops written when the page was last laid out (a frame's snapshot, or forceLayout). */+let laidAt = -1;++/** A box script reads that the last layout doesn't have yet, laid out now, as Chrome lays out on the read: the host's+ * layout.now (runtime/dom computed.rs) commits what's written, lays the page out and gives its snapshot, whose boxes+ * replace the frame's; the viewport and the observers wait for the frame. Once per change: a box that still isn't+ * there (display: none) isn't asked for again until something else is written. Off where there's no such call. */+let noLayoutNow = false;+export function forceLayout(): boolean {+ if (noLayoutNow || laidAt === wire.writes()) return false;+ let json: string | undefined;+ try {+ json = wire.callSync<string>("layout.now");+ } catch (e) {+ // a host without it (bevy_ui's) never will have it; one outside a step may next time+ if (/no synchronous host call/.test(String(e))) noLayoutNow = true;+ json = undefined;+ }+ laidAt = wire.writes();+ if (!json) return false;+ const s = JSON.parse(json) as { n: number[] };+ geo.clear();+ for (let i = 0; i + STRIDE <= s.n.length; i += STRIDE) geo.set(s.n[i], s.n.slice(i + 1, i + STRIDE));+ return true;+}+/** The host's call after each frame's layout (runtime/js/src/dom.rs): the snapshot when it changed ("" when* it didn't), then resize, matchMedia changes, the observers and the frame's animation callbacks. */export function onLayout(json: string) {+ laidAt = wire.writes();S.frameNo++;S.wantFocus = undefined;let resized = false;diff --git a/sdk/ui/src/dom/host.ts b/sdk/ui/src/dom/host.tsindex 0fb79b3c..51a22d43 100644--- a/sdk/ui/src/dom/host.ts+++ b/sdk/ui/src/dom/host.ts@@ -1,7 +1,7 @@// An element on the wire, React's host instances in DOM mode, and which events the host sends each element.import * as wire from "../wire";import type { Ev } from "../wire";-import { Control_, Element_, FOCUSABLE_TAGS, HTMLOptionElement_, HTMLSelectElement_, HTML_HIDDEN, Node_, S, SKIP_PROPS, SVG_NS, TEXT_INPUTS, Text_, attrName, attrValue, body, cssText, doc, g, hostEvent, html, htmlDoc, htmlValue, installed, makeElement, mutated, nativelyFocusable, query, rootContainer, scrollable, tellCapture, typesOn, unwire } from "./all";+import { Control_, Element_, FOCUSABLE_TAGS, HTMLOptionElement_, HTMLSelectElement_, HTML_HIDDEN, Node_, S, SKIP_PROPS, SVG_NS, TEXT_INPUTS, Text_, attrName, attrValue, body, cssText, doc, g, hostEvent, html, htmlDoc, htmlValue, installed, isEditable, makeElement, mutated, nativelyFocusable, query, rootContainer, scrollable, tellCapture, typesOn, unwire } from "./all";// ---------------------------------------------------------------- what an element is on the wire@@ -64,6 +64,9 @@ export function wireOf(tag: string, props: Record<string, unknown>, el?: Element}const focusableTag = tag === "button" || tag === "select" || (tag === "a" && props.href !== undefined) || (tag === "input" && type !== "hidden");if (out.tabIndex === undefined && focusableTag && !props.disabled) out.tabIndex = 0;+ // an editing host takes the focus and its keys, as Chrome's (editing.ts)+ const ce = props.contentEditable;+ if (out.tabIndex === undefined && (ce === true || ce === "" || ce === "true" || ce === "plaintext-only") && !(el?.parentNode instanceof Element_ && isEditable(el.parentNode))) out.tabIndex = 0;if (props.disabled && FOCUSABLE_TAGS.has(tag) && props.tabIndex === undefined) delete out.tabIndex;return { kind, props: out };}@@ -153,8 +156,19 @@ function applyProps(el: Element_, old: Record<string, unknown>, next: Record<str/** React's update of an element's props: the mirror, and the host's props (each changed one whole, the style as* merged). Returns nothing; it emits the wire ops itself. */+/** React's dangerouslySetInnerHTML: its markup as the element's children when it's new or changed (React DOM sets+ * `innerHTML`; with no `__html` the children are left to React). */+export function innerHtmlProp(el: Element_, old: Record<string, unknown> | undefined, next: Record<string, unknown>) {+ const html = (p?: Record<string, unknown>) => (p?.dangerouslySetInnerHTML as { __html?: unknown } | undefined)?.__html;+ const now = html(next);+ if (now == null) return old && html(old) != null ? void (el.innerHTML = "") : undefined;+ if (old && html(old) === now) return;+ el.innerHTML = String(now);+}+export function hostUpdate(el: Element_, type: string, old: Record<string, unknown>, next: Record<string, unknown>, fiber: unknown) {if (fiber) el._fiber = fiber;+ innerHtmlProp(el, old, next);const styleWas = el._style;applyProps(el, old, next, false);const id = el.__wid!;diff --git a/sdk/ui/src/dom/html.ts b/sdk/ui/src/dom/html.tsindex 0fced47d..05339f95 100644--- a/sdk/ui/src/dom/html.ts+++ b/sdk/ui/src/dom/html.ts@@ -1,6 +1,6 @@// HTMLElement and the form controls: focusability, values, selection, forms, anchors and labels.import * as wire from "../wire";-import { Element_, Event_, FOCUSABLE_TAGS, PointerEvent_, S, activate, body, computedOf, dispatch, doc, focusTo, g, isField, nodeList, query, submitForm, transition } from "./all";+import { Element_, Event_, FOCUSABLE_TAGS, PointerEvent_, S, activate, body, computedOf, dispatch, doc, focusTo, focusedHost, g, isEditable, isEditingHost, isField, nodeList, query, submitForm, transition } from "./all";export class HTMLElement_ extends Element_ {get hidden() {@@ -42,10 +42,19 @@ export class HTMLElement_ extends Element_ {return this.getAttribute("draggable") === "true";}get contentEditable() {- return this.getAttribute("contenteditable") ?? "inherit";+ const a = this.getAttribute("contenteditable");+ if (a === null) return "inherit";+ const l = a.toLowerCase();+ return l === "" || l === "true" ? "true" : l === "false" || l === "plaintext-only" ? l : "inherit";+ }+ set contentEditable(v: string) {+ const l = String(v).toLowerCase();+ if (l === "inherit") this.removeAttribute("contenteditable");+ else if (l === "true" || l === "false" || l === "plaintext-only") this.setAttribute("contenteditable", l);+ else throw new Error(`SyntaxError: contentEditable can't be ${v}`);}get isContentEditable() {- return false;+ return this.isConnected && isEditable(this);}get accessKey() {return this.getAttribute("accesskey") ?? "";@@ -73,6 +82,7 @@ export class HTMLElement_ extends Element_ {focus(opts?: { preventScroll?: boolean; focusVisible?: boolean }) {void opts?.preventScroll;focusTo(this, true);+ if (S.active === this) focusedHost(this);}blur() {if (S.active === this) transition(null, true);@@ -104,6 +114,7 @@ export function nativelyFocusable(el: Element_): boolean {if (t === "a" || t === "area") return el.hasAttribute("href");if (FOCUSABLE_TAGS.has(t)) return !(t === "input" && el.getAttribute("type") === "hidden");if (t === "summary" || t === "iframe") return true;+ if (isEditingHost(el)) return true;return false;}@@ -163,10 +174,11 @@ export class Control_ extends HTMLElement_ {set value(v: string) {const s = v === null || v === undefined ? "" : String(v);this._value = s;- if (isField(this) && this._wired && this.__wid !== undefined) {- this._extra.value = s;- wire.set(this.__wid, "value", s);- }+ if (!isField(this)) return;+ // kept for the host node too when it's made later: a field JS made and filled before placing it (Excalidraw's text+ // editor) is created with its value (materialize), else it showed empty+ this._extra.value = s;+ if (this._wired && this.__wid !== undefined) wire.set(this.__wid, "value", s);}get defaultValue() {return this.getAttribute("value") ?? "";diff --git a/sdk/ui/src/dom/input.ts b/sdk/ui/src/dom/input.tsindex 6167ede9..459d9682 100644--- a/sdk/ui/src/dom/input.ts+++ b/sdk/ui/src/dom/input.ts@@ -1,7 +1,7 @@// React's event system as React DOM runs it, and the host's input turned into DOM events.import * as wire from "../wire";import type { Ev } from "../wire";-import { Control_, DIRECT, Element_, Event_, FocusEvent_, InputEvent_, MouseEvent_, Node_, PointerEvent_, REACT_BY_NATIVE, S, WheelEvent_, activate, addListener, body, byWid, computedOf, container, dispatch, focusTarget, focusable, g, inputKind, isField, key, keyUp, report, rootContainer, run, scrolling, tellCapture } from "./all";+import { Control_, DIRECT, Element_, Event_, FocusEvent_, InputEvent_, MouseEvent_, Node_, PointerEvent_, REACT_BY_NATIVE, S, WheelEvent_, activate, addListener, body, byWid, computedOf, container, dispatch, editPointer, focusTarget, focusable, g, inputKind, isField, key, keyUp, report, rootContainer, run, scrolling, selection, tellCapture } from "./all";// ---------------------------------------------------------------- React's event system, as React DOM runs it@@ -146,6 +146,8 @@ export function transition(to: Element_ | null, tellHost: boolean) {dispatchDirect(to, new FocusEvent_("focus", { relatedTarget: from, view: g, composed: true }));dispatch(to, new FocusEvent_("focusin", { bubbles: true, relatedTarget: from, view: g, composed: true }), true);}+ // the caret shows only in a focused editable (selection.ts's paint)+ selection._changed(false);if (tellHost) {S.wantFocus = S.active;if (S.active?._wired && S.active.__wid !== undefined) wire.emit("focus", S.active.__wid);@@ -199,6 +201,17 @@ export function hit(from: Node_, x: number, y: number): Element_ | null {return best;}+/** The element a press or move is for. sdk/ui's own walk (hit) reads pointer-events only from inline styles and plain+ * pointer-events-* classes; the host sends the deepest element it knows on Blitz's hit path, which Stylo's cascade+ * decided as Chrome's would (a `[&>*]:pointer-events-auto` child under a pointer-events-none dock, a stylesheet's+ * layer). The walk's answer stands when it lies inside the host's; when they disagree, the host's wins. */+function pointed(from: Node_, x: number, y: number, p: { target?: unknown }): Element_ | null {+ const h = hit(from, x, y);+ const t = typeof p.target === "number" ? byWid(p.target) : null;+ if (!t || !t.isConnected || (h && t.contains(h))) return h;+ return from === body || from.contains(t) ? t : h;+}+function commonAncestor(a: Node_, b: Node_): Element_ | null {const sa = new Set<Node_>();for (let n: Node_ | null = a; n; n = n.parentNode) sa.add(n);@@ -206,7 +219,7 @@ function commonAncestor(a: Node_, b: Node_): Element_ | null {return null;}-type Ptr = { clientX?: number; clientY?: number; button?: number; detail?: number; shiftKey?: boolean; ctrlKey?: boolean; altKey?: boolean; metaKey?: boolean; deltaX?: number; deltaY?: number };+type Ptr = { target?: number; clientX?: number; clientY?: number; button?: number; detail?: number; shiftKey?: boolean; ctrlKey?: boolean; altKey?: boolean; metaKey?: boolean; deltaX?: number; deltaY?: number };function mouseInit(p: Ptr, target: Element_, extra: Record<string, unknown> = {}) {const x = p.clientX ?? lastPointer[0];@@ -244,7 +257,7 @@ export function hostEvent(el: Node_, ev: Ev, payload: any) {case "pointerdown": {const p = (payload ?? {}) as Ptr;lastPointer = [p.clientX ?? 0, p.clientY ?? 0];- const t = hit(from, lastPointer[0], lastPointer[1]) ?? (from instanceof Element_ && from !== body ? from : body);+ const t = pointed(from, lastPointer[0], lastPointer[1], p) ?? (from instanceof Element_ && from !== body ? from : body);// a secondary press comes as pointerdown (button 2) before its contextmenu, as Chrome sends thembuttons = p.button === 2 ? 2 : 1;S.downTarget = t;@@ -260,21 +273,25 @@ export function hostEvent(el: Node_, ev: Ev, payload: any) {const f = focusTarget(t);if (f) focusTo(f, false);else if (S.active) transition(null, false);+ // in an editable: the caret placed, a word or paragraph picked, a drag started (editing.ts)+ editPointer("down", t, lastPointer[0], lastPointer[1], p);}break;}case "pointermove": {const p = (payload ?? {}) as Ptr;lastPointer = [p.clientX ?? 0, p.clientY ?? 0];- const t = S.pointerCapture ?? hit(body, lastPointer[0], lastPointer[1]) ?? body;+ const t = S.pointerCapture ?? pointed(body, lastPointer[0], lastPointer[1], p) ?? body;if (dispatch(t, new PointerEvent_("pointermove", mouseInit(p, t, { cancelable: true })), true) && !downPrevented) dispatch(t, new MouseEvent_("mousemove", mouseInit(p, t)), true);+ if (buttons && !downPrevented) editPointer("move", t, lastPointer[0], lastPointer[1], p);break;}case "pointerup": {const p = (payload ?? {}) as Ptr;lastPointer = [p.clientX ?? lastPointer[0], p.clientY ?? lastPointer[1]];- const t = S.pointerCapture ?? hit(body, lastPointer[0], lastPointer[1]) ?? body;+ const t = S.pointerCapture ?? pointed(body, lastPointer[0], lastPointer[1], p) ?? body;buttons = 0;+ editPointer("up", t, lastPointer[0], lastPointer[1], p);dispatch(t, new PointerEvent_("pointerup", mouseInit(p, t)), true);if (!downPrevented) dispatch(t, new MouseEvent_("mouseup", mouseInit(p, t)), true);if (S.pointerCapture) {diff --git a/sdk/ui/src/dom/keys.ts b/sdk/ui/src/dom/keys.tsindex f4bfdae7..666c0edc 100644--- a/sdk/ui/src/dom/keys.ts+++ b/sdk/ui/src/dom/keys.ts@@ -1,6 +1,6 @@// Keys and activation: focus targets, Space and Enter clicks, and form submission.import * as wire from "../wire";-import { Control_, Element_, Event_, HTMLButtonElement_, HTMLFormElement_, HTMLInputElement_, HTMLLabelElement_, HTMLOptionElement_, HTMLSelectElement_, InputEvent_, KeyboardEvent_, MODS, Node_, PointerEvent_, S, SubmitEvent_, disabledEl, dispatch, doc, focusTo, focusable, g, installed, isField, keyInit, query } from "./all";+import { Control_, Element_, Event_, HTMLButtonElement_, HTMLFormElement_, HTMLInputElement_, HTMLLabelElement_, HTMLOptionElement_, HTMLSelectElement_, InputEvent_, KeyboardEvent_, MODS, Node_, PointerEvent_, S, SubmitEvent_, disabledEl, dispatch, doc, editKey, focusTo, focusable, g, installed, isField, keyInit, query } from "./all";/** An edit's inputType and data, from a field's value before and after it: what was put in (insertText, the text),* else what was taken out (deleteContentBackward, or Forward when the caret's side stayed). */@@ -37,8 +37,8 @@ export function key(t: Element_, payload: any) {if (payload && t instanceof Control_ && typeof payload.value === "string") t._value = payload.value;const init = keyInit(payload ?? {});const ok = dispatch(t, new KeyboardEvent_("keydown", init), true);- // the host's default actions (Tab's focus move) wait on this- if (!ok) wire.emit("prevented");+ // the host's default actions (Tab's focus move) wait on this; an editable's key is its edit (editing.ts)+ if (!ok || (!isField(t) && editKey(t, init))) wire.emit("prevented");S.spaceDown = init.key === " " ? { t, ok } : null;const tag = t.localName;// a closed select's type-ahead: a letter picks the next option whose text starts with it (input, then change)diff --git a/sdk/ui/src/dom/media.ts b/sdk/ui/src/dom/media.tsindex 852cd0cd..1d3b083c 100644--- a/sdk/ui/src/dom/media.ts+++ b/sdk/ui/src/dom/media.ts@@ -163,6 +163,23 @@ const TAG_CLASS: Record<string, typeof HTMLElement_> = {dialog: HTMLDialogElement_,};+/** Chrome's per-tag classes that have no behaviour of their own here. Pages test them: Excalidraw's isWritableElement+ * asks `instanceof HTMLBRElement` on every keydown, and with no such global every shortcut threw. Each is a window+ * global and what its tags make. */+const PLAIN: Record<string, string[]> = {+ HTMLBRElement: ["br"], HTMLParagraphElement: ["p"], HTMLHRElement: ["hr"], HTMLPreElement: ["pre", "listing", "xmp"],+ HTMLHeadingElement: ["h1", "h2", "h3", "h4", "h5", "h6"], HTMLQuoteElement: ["blockquote", "q"], HTMLDListElement: ["dl"],+ HTMLTableElement: ["table"], HTMLTableRowElement: ["tr"], HTMLTableCellElement: ["td", "th"], HTMLTableSectionElement: ["thead", "tbody", "tfoot"],+ HTMLFieldSetElement: ["fieldset"], HTMLLegendElement: ["legend"], HTMLPictureElement: ["picture"], HTMLSourceElement: ["source"],+ HTMLLinkElement: ["link"], HTMLMetaElement: ["meta"], HTMLTimeElement: ["time"],+};+export const plainClasses: Record<string, typeof HTMLElement_> = {};+for (const [name, tags] of Object.entries(PLAIN)) {+ const C = class extends HTMLElement_ {};+ plainClasses[name] = C;+ for (const t of tags) TAG_CLASS[t] ??= C;+}+export function makeElement(tag: string, ns?: string): Element_ {const svg = ns === SVG_NS || (ns === undefined && SVG_TAGS.has(tag) && tag !== "text" && tag !== "image" && tag !== "title");if (svg) return tag === "svg" ? new SVGSVGElement_(tag, SVG_NS) : new SVGElement_(tag, SVG_NS);diff --git a/sdk/ui/src/dom/moves.ts b/sdk/ui/src/dom/moves.tsnew file mode 100644index 00000000..ab6fb563--- /dev/null+++ b/sdk/ui/src/dom/moves.ts@@ -0,0 +1,187 @@+// Caret moves in an editable, as Chrome makes them (docs/ts-native.feature P14a): by character across text nodes and+// blocks, by word, to a line's ends and up or down a line from the caret's rect, and the pointer's placing, dragging+// and word and paragraph picks. Positions are (text, offset) where there's text, else (element, child index).+import { Element_, Node_, Range_, Selection_, Text_, caretAt, computedOf, rangeRects } from "./all";++type Pos = [Node_, number];++const BLOCK = new Set(["block", "flex", "grid", "list-item", "table", "flow-root"]);++export function isBlock(n: Node_): boolean {+ return n instanceof Element_ && BLOCK.has(String(computedOf(n).display ?? (["div", "p", "li", "h1", "h2", "h3", "h4", "h5", "h6", "ul", "ol", "blockquote", "pre"].includes(n.localName) ? "block" : "inline")));+}++/** the nearest block at or above `n`, up to the editing host */+export function blockOf(n: Node_, host: Element_): Element_ {+ for (let x: Node_ | null = n; x && x !== host; x = x.parentNode) if (x instanceof Element_ && isBlock(x)) return x;+ return host;+}++/** the host's texts in tree order */+export function textsIn(host: Node_): Text_[] {+ const out: Text_[] = [];+ const walk = (n: Node_) => {+ for (const k of n._kids) {+ if (k instanceof Text_) out.push(k);+ else if (k instanceof Element_ && k.getAttribute("contenteditable") !== "false") walk(k);+ }+ };+ walk(host);+ return out;+}++/** a point as a text position: in a text, or the text at or next to an element's offset (none in an empty block) */+export function toText(p: Pos, host: Element_): Pos {+ const [n, o] = p;+ if (n instanceof Text_) return p;+ const texts = textsIn(host);+ if (!texts.length) return p;+ // the first text after the point, else the last before it+ const r = new Range_();+ r.setStart(n, o);+ for (const t of texts) if (r.comparePoint(t, t.data.length) >= 0 && r.comparePoint(t, 0) >= 0) return blockOf(t, host) === blockOf(n, host) || n === host ? [t, 0] : p;+ const last = texts[texts.length - 1];+ return blockOf(last, host) === blockOf(n, host) ? [last, last.data.length] : p;+}++const surrogateHi = (c: number) => c >= 0xd800 && c <= 0xdbff;++/** one character on from `p` (dir -1 back, 1 on): within a text, else into the next text (a block's edge is a step) */+export function charStep(p: Pos, dir: -1 | 1, host: Element_): Pos {+ const [n, o] = toText(p, host);+ if (n instanceof Text_) {+ if (dir < 0 && o > 0) return [n, o - (o > 1 && surrogateHi(n.data.charCodeAt(o - 2)) ? 2 : 1)];+ if (dir > 0 && o < n.data.length) return [n, o + (surrogateHi(n.data.charCodeAt(o)) ? 2 : 1)];+ const texts = textsIn(host);+ const i = texts.indexOf(n);+ const next = texts[i + dir];+ if (!next) return [n, o];+ const sameBlock = blockOf(next, host) === blockOf(n, host);+ if (dir < 0) return [next, sameBlock ? Math.max(0, next.data.length - 1) : next.data.length];+ return [next, sameBlock ? Math.min(next.data.length, 1) : 0];+ }+ return p;+}++const wordChar = (c: string) => /[\p{L}\p{N}_]/u.test(c);++/** to the start of this or the last word (back), or the end of this or the next word (on), as Chrome on a Mac's Alt */+export function wordStep(p: Pos, dir: -1 | 1, host: Element_): Pos {+ let [n, o] = toText(p, host);+ if (!(n instanceof Text_)) return p;+ let t = n as Text_;+ const at = (i: number) => t.data[i] ?? "";+ // past what isn't a word, then through the word+ for (let seen = false; ; ) {+ const c = dir < 0 ? at(o - 1) : at(o);+ if (!c) {+ const step = charStep([t, o], dir, host);+ if (step[0] === t && step[1] === o) return [t, o];+ if (seen) return [t, o];+ [n, o] = step;+ t = n as Text_;+ continue;+ }+ if (wordChar(c)) seen = true;+ else if (seen) return [t, o];+ o += dir;+ }+}++/** the caret's rect at a position (a collapsed range's, or its text's next character's left edge) */+export function caretRect(p: Pos): { x: number; top: number; bottom: number } | null {+ const r = new Range_();+ r.setStart(p[0], p[1]);+ const rs = rangeRects(r);+ if (rs[0]) return { x: rs[0].left, top: rs[0].top, bottom: rs[0].bottom };+ const el = p[0] instanceof Element_ ? p[0] : p[0].parentElement;+ if (!el) return null;+ const b = el.getBoundingClientRect();+ return { x: b.left, top: b.top, bottom: b.bottom };+}++/** the column a run of Up and Down keeps (Chrome's goal x), cleared by any other move */+let goalX: number | null = null;++export const clearGoal = () => (goalX = null);++/** a line up or down from `p`: the position at the caret's x on the line above or below */+export function lineStep(p: Pos, dir: -1 | 1, host: Element_): Pos {+ const c = caretRect(p);+ if (!c) return p;+ const x = goalX ?? c.x;+ goalX = x;+ const h = Math.max(1, c.bottom - c.top);+ const y = dir < 0 ? c.top - h / 2 : c.bottom + h / 2;+ const hb = host.getBoundingClientRect();+ if (y < hb.top || y > hb.bottom) {+ // past the host's first or last line: to its start or end+ const texts = textsIn(host);+ if (!texts.length) return p;+ return dir < 0 ? [texts[0], 0] : [texts[texts.length - 1], texts[texts.length - 1].data.length];+ }+ const at = caretAt(x, y);+ return at && host.contains(at.offsetNode) ? [at.offsetNode, at.offset] : p;+}++/** the start or end of the caret's line (Home, End; Cmd+Left and Right on a Mac) */+export function lineEdge(p: Pos, dir: -1 | 1, host: Element_): Pos {+ const c = caretRect(p);+ if (!c) return p;+ // within the caret's own block (the host's padding has no line in it)+ const hb = blockOf(p[0], host).getBoundingClientRect();+ const at = caretAt(dir < 0 ? hb.left + 1 : hb.right - 1, (c.top + c.bottom) / 2);+ return at && host.contains(at.offsetNode) ? [at.offsetNode, at.offset] : p;+}++/** the word around a position (a double click): its start and end */+export function wordAt(p: Pos, host: Element_): [Pos, Pos] {+ const [n, o] = toText(p, host);+ if (!(n instanceof Text_)) return [p, p];+ const d = n.data;+ const inWord = wordChar(d[o] ?? "") || wordChar(d[o - 1] ?? "");+ const same = (c: string) => (inWord ? wordChar(c) : !wordChar(c) && /\S/.test(c));+ let a = o;+ let b = o;+ while (a > 0 && same(d[a - 1])) a--;+ while (b < d.length && same(d[b])) b++;+ if (a === b && b < d.length) b++;+ return [+ [n, a],+ [n, b],+ ];+}++/** the paragraph around a position (a triple click): its block's contents */+export function blockAt(p: Pos, host: Element_): [Pos, Pos] {+ const b = blockOf(p[0], host);+ const texts = textsIn(b);+ if (!texts.length) return [[b, 0], [b, b._kids.length]];+ const last = texts[texts.length - 1];+ return [+ [texts[0], 0],+ [last, last.data.length],+ ];+}++/** the selection moved (`extend`: its focus only) to a position */+export function moveTo(s: Selection_, p: Pos, extend: boolean) {+ if (extend && s.anchorNode) s.setBaseAndExtent(s.anchorNode, s.anchorOffset, p[0], p[1]);+ else s.collapse(p[0], p[1]);+}++/** Selection.modify: `alter` move or extend, `direction` forward/backward/left/right, by character, word, line or+ * lineboundary, within the editing host the focus is in */+export function modify(s: Selection_, alter: string, direction: string, granularity: string, host: Element_ | null) {+ if (!s.focusNode || !host) return;+ const dir: -1 | 1 = direction === "backward" || direction === "left" ? -1 : 1;+ const f: Pos = [s.focusNode, s.focusOffset];+ let p: Pos = f;+ if (granularity === "character") p = charStep(f, dir, host);+ else if (granularity === "word") p = wordStep(f, dir, host);+ else if (granularity === "line") p = lineStep(f, dir, host);+ else if (granularity === "lineboundary") p = lineEdge(f, dir, host);+ if (granularity !== "line") clearGoal();+ moveTo(s, p, alter === "extend");+}+diff --git a/sdk/ui/src/dom/nodes.ts b/sdk/ui/src/dom/nodes.tsindex bb191bd7..683c201a 100644--- a/sdk/ui/src/dom/nodes.ts+++ b/sdk/ui/src/dom/nodes.ts@@ -1,6 +1,6 @@// Nodes: Node, the tree's mutations, attributes and props, and the style object.import * as wire from "../wire";-import { Document_, Element_, EventTarget_, MutationRecord_, body, cloneOf, connectedTree, disconnected, doc, htmlDoc, observers, query, queueRecord, rootContainer, svgNs, syncListens, wireOf } from "./all";+import { Document_, Element_, EventTarget_, MutationRecord_, body, cloneOf, connectedTree, disconnected, doc, htmlDoc, liveRanges, observers, query, queueRecord, rangesChildList, rangesSplit, rangesText, rootContainer, svgNs, syncListens, wireOf } from "./all";// ---------------------------------------------------------------- nodes@@ -11,6 +11,12 @@ export const SVG_NS = "http://www.w3.org/2000/svg";export const SVG_TAGS = new Set(["svg", "path", "circle", "rect", "line", "polyline", "polygon", "ellipse", "g", "defs", "linearGradient", "radialGradient", "stop", "clipPath", "mask", "use", "symbol", "text", "tspan", "pattern", "filter", "foreignObject", "image", "marker", "title", "desc"]);export function mutated(target: Node_, rec: Partial<MutationRecord_>) {+ // the selection's range moved as the tree changed (selection.ts): a child list's index from its siblings now+ if (liveRanges() && rec.type === "childList") {+ const prev = rec.previousSibling;+ const at = prev ? target._kids.indexOf(prev) + 1 : 0;+ rangesChildList(target, at, rec.addedNodes?.length ?? 0, rec.removedNodes?.[0] ?? null);+ }if (observers.size) queueRecord(target, rec);}@@ -225,10 +231,16 @@ export function materialize(n: Node_) {export class Text_ extends Node_ {nodeType = 3;- data: string;+ _d: string;constructor(data = "") {super();- this.data = String(data);+ this._d = String(data);+ }+ get data() {+ return this._d;+ }+ set data(v: string) {+ this.setData(v ?? "");}get nodeName() {return "#text";@@ -251,12 +263,46 @@ export class Text_ extends Node_ {get length() {return this.data.length;}- setData(v: string, fromReact = false) {- const old = this.data;- this.data = String(v);+ /** The data replaced (DOM's replace data): `count` characters from `at` by `v`, the live ranges moved with it.+ * A whole replace (nodeValue, data, textContent) is from 0 over all of it. */+ setData(v: string, fromReact = false, at = 0, count = this.data.length) {+ const old = this._d;+ this._d = String(v);if (!fromReact && this._wired && this.__wid !== undefined) wire.text(this.__wid, this.data);+ if (liveRanges()) rangesText(this, at, count, this.data.length - old.length + count);mutated(this, { type: "characterData", oldValue: old });}+ substringData(at: number, count: number) {+ this._at(at);+ return this.data.slice(at, at + count);+ }+ replaceData(at: number, count: number, v: string) {+ this._at(at);+ count = Math.min(count, this.data.length - at);+ this.setData(this.data.slice(0, at) + v + this.data.slice(at + count), false, at, count);+ }+ insertData(at: number, v: string) {+ this.replaceData(at, 0, v);+ }+ deleteData(at: number, count: number) {+ this.replaceData(at, count, "");+ }+ appendData(v: string) {+ this.replaceData(this.data.length, 0, v);+ }+ _at(at: number) {+ if (at < 0 || at > this.data.length) throw new Error(`IndexSizeError: offset ${at} is past the text's length ${this.data.length}`);+ }+ /** The text split at `at`: what's after goes to a new text node after this one (DOM's split a Text node). */+ splitText(at: number): Text_ {+ this._at(at);+ const next = new Text_(this.data.slice(at));+ const p = this.parentNode;+ if (p) p.insertBefore(next, this.nextSibling);+ if (liveRanges()) rangesSplit(this, at, next);+ this.replaceData(at, this.data.length - at, "");+ return next;+ }}export class Comment_ extends Node_ {diff --git a/sdk/ui/src/dom/parser.ts b/sdk/ui/src/dom/parser.tsnew file mode 100644index 00000000..39621da2--- /dev/null+++ b/sdk/ui/src/dom/parser.ts@@ -0,0 +1,100 @@+// Markup into nodes (docs/ts-native.feature P14a): innerHTML's setter and DOMParser, from the composition parser+// (src/html/parse.ts: not the HTML5 tree builder, but the tags, attributes, entities and implied end tags a page or an+// editor's content has). Tiptap parses its content with DOMParser; ProseMirror's clipboard reads pasted HTML through+// innerHTML.+import { parse, type HElement, type HNode } from "../html/parse";+import { DocumentFragment_, Element_, Node_, doc, makeElement, query } from "./all";++const SVG_NS = "http://www.w3.org/2000/svg";++function build(n: HNode, svg: boolean): Node_ {+ if (n.type === "text") return doc.createTextNode(n.text);+ const inSvg = svg || n.tag === "svg";+ const el = inSvg ? makeElement(n.tag, SVG_NS) : makeElement(n.tag);+ for (const [k, v] of n.attrs) el.setAttribute(k, v);+ for (const k of (n.content ?? n).kids) el.appendChild(build(k, inSvg && n.tag !== "foreignObject"));+ return el;+}++/** markup as a fragment of new nodes */+export function fragmentOf(html: string): DocumentFragment_ {+ const f = new DocumentFragment_();+ for (const k of parse(String(html)).kids) f.appendChild(build(k, false));+ return f;+}++/** an element's children replaced by the markup's (innerHTML's setter) */+export function setInnerHtml(el: Node_, html: string) {+ for (const k of el._kids.slice()) el.removeChild(k);+ el.appendChild(fragmentOf(html));+}++/** a parsed document: its own html, head and body, apart from the page's */+class ParsedDocument_ {+ documentElement: Element_;+ head: Element_;+ body: Element_;+ constructor(root: HElement) {+ const find = (tag: string, from: HElement): HElement | undefined => {+ for (const k of from.kids) {+ if (k.type !== "el") continue;+ if (k.tag === tag) return k;+ const f = find(tag, k);+ if (f) return f;+ }+ return undefined;+ };+ this.documentElement = makeElement("html");+ this.head = makeElement("head");+ this.body = makeElement("body");+ this.documentElement.appendChild(this.head);+ this.documentElement.appendChild(this.body);+ const h = find("head", root);+ const b = find("body", root);+ if (h) for (const k of h.kids) this.head.appendChild(build(k, false));+ // what isn't in head goes in body (a fragment's markup, as the HTML parser puts it)+ const kids = b ? b.kids : root.kids.filter((k) => !(k.type === "el" && (k.tag === "html" || k.tag === "head")));+ const htmlEl = find("html", root);+ const bodyKids = b ? kids : htmlEl ? htmlEl.kids.filter((k) => !(k.type === "el" && k.tag === "head")) : kids;+ for (const k of bodyKids) this.body.appendChild(build(k, false));+ }+ get nodeType() {+ return 9;+ }+ get firstChild() {+ return this.documentElement;+ }+ querySelector(s: string) {+ return query(this.documentElement, s, true)[0] ?? null;+ }+ querySelectorAll(s: string) {+ return query(this.documentElement, s, false);+ }+ getElementsByTagName(t: string) {+ return this.querySelectorAll(t);+ }+ createElement(t: string) {+ return doc.createElement(t);+ }+ createTextNode(t: string) {+ return doc.createTextNode(t);+ }+ createDocumentFragment() {+ return doc.createDocumentFragment();+ }+}++export class DOMParser_ {+ parseFromString(s: string, _type = "text/html") {+ return new ParsedDocument_(parse(String(s)));+ }+}++/** document.implementation: a detached document to parse into (ProseMirror's clipboard) */+export const implementation = {+ createHTMLDocument(title = "") {+ const d = new ParsedDocument_(parse(`<html><head><title>${title}</title></head><body></body></html>`));+ return d;+ },+ hasFeature: () => true,+};diff --git a/sdk/ui/src/dom/selection.ts b/sdk/ui/src/dom/selection.tsnew file mode 100644index 00000000..39398b1a--- /dev/null+++ b/sdk/ui/src/dom/selection.ts@@ -0,0 +1,482 @@+// Range and Selection as the DOM spec keeps them (docs/ts-native.feature P14a): boundary points in tree order, the+// selection's range live (moved by the tree's mutations as Chrome moves it), selectionchange queued as a task, and+// the selection mirrored to the host so it paints (with a caret in a focused editable).+import * as wire from "../wire";+import { Comment_, DOMRect_, DocumentFragment_, Element_, Event_, Node_, S, Text_, dispatch, doc, nodeList, rangeRects, run } from "./all";++// ---------------------------------------------------------------- boundary points++/** A node's length as boundary points count it: a text's or comment's characters (UTF-16), else its children. */+export function nodeLength(n: Node_): number {+ return n instanceof Text_ || n instanceof Comment_ ? n.data.length : n._kids.length;+}++export function indexOf(n: Node_): number {+ return n.parentNode ? n.parentNode._kids.indexOf(n) : 0;+}++/** Where (a, ao) is against (b, bo) in tree order: -1 before, 0 equal, 1 after (DOM's boundary point position). */+export function cmpPoint(a: Node_, ao: number, b: Node_, bo: number): number {+ if (a === b) return ao === bo ? 0 : ao < bo ? -1 : 1;+ const pos = a.compareDocumentPosition(b);+ // b precedes a: the answer the other way round+ if (pos & 2 && !(pos & 8)) return -cmpPoint(b, bo, a, ao);+ if (pos & 8) return -cmpPoint(b, bo, a, ao);+ // a is b's ancestor: b's ancestor that's a's child against ao+ if (pos & 16) {+ let c: Node_ = b;+ while (c.parentNode !== a) c = c.parentNode!;+ return indexOf(c) < ao ? 1 : -1;+ }+ return -1;+}++function check(n: Node_, o: number) {+ if (n.nodeType === 10) throw new Error("InvalidNodeTypeError: a doctype has no boundary points");+ if (o < 0 || o > nodeLength(n)) throw new Error(`IndexSizeError: offset ${o} is past the node's length ${nodeLength(n)}`);+}++// ---------------------------------------------------------------- Range++/** Ranges the tree's mutations move: the selection's (a range made by createRange keeps where it was set, which is+ * all ProseMirror needs of one: it sets both ends before each read). */+const live = new Set<Range_>();++export class Range_ {+ static START_TO_START = 0;+ static START_TO_END = 1;+ static END_TO_END = 2;+ static END_TO_START = 3;+ startContainer: Node_;+ startOffset = 0;+ endContainer: Node_;+ endOffset = 0;+ /** the selection this is the range of: its changes are the selection's */+ _sel: Selection_ | null = null;+ constructor() {+ this.startContainer = this.endContainer = doc;+ }+ get collapsed() {+ return this.startContainer === this.endContainer && this.startOffset === this.endOffset;+ }+ get commonAncestorContainer(): Node_ {+ for (let n: Node_ | null = this.startContainer; n; n = n.parentNode) if (n.contains(this.endContainer)) return n;+ return doc;+ }+ _set(start: boolean, n: Node_, o: number) {+ check(n, o);+ if (start) {+ this.startContainer = n;+ this.startOffset = o;+ if (this.endContainer.getRootNode() !== n.getRootNode() || cmpPoint(n, o, this.endContainer, this.endOffset) > 0) [this.endContainer, this.endOffset] = [n, o];+ } else {+ this.endContainer = n;+ this.endOffset = o;+ if (this.startContainer.getRootNode() !== n.getRootNode() || cmpPoint(n, o, this.startContainer, this.startOffset) < 0) [this.startContainer, this.startOffset] = [n, o];+ }+ this._sel?._changed(true);+ }+ setStart(n: Node_, o: number) {+ this._set(true, n, o);+ }+ setEnd(n: Node_, o: number) {+ this._set(false, n, o);+ }+ setStartBefore(n: Node_) {+ this._set(true, n.parentNode!, indexOf(n));+ }+ setStartAfter(n: Node_) {+ this._set(true, n.parentNode!, indexOf(n) + 1);+ }+ setEndBefore(n: Node_) {+ this._set(false, n.parentNode!, indexOf(n));+ }+ setEndAfter(n: Node_) {+ this._set(false, n.parentNode!, indexOf(n) + 1);+ }+ collapse(toStart = false) {+ if (toStart) [this.endContainer, this.endOffset] = [this.startContainer, this.startOffset];+ else [this.startContainer, this.startOffset] = [this.endContainer, this.endOffset];+ this._sel?._changed(true);+ }+ selectNode(n: Node_) {+ const p = n.parentNode;+ if (!p) throw new Error("InvalidNodeTypeError: the node has no parent");+ const i = indexOf(n);+ this._both(p, i, p, i + 1);+ }+ selectNodeContents(n: Node_) {+ this._both(n, 0, n, nodeLength(n));+ }+ _both(a: Node_, ao: number, b: Node_, bo: number) {+ this.startContainer = a;+ this.startOffset = ao;+ this.endContainer = b;+ this.endOffset = bo;+ this._sel?._changed(true);+ }+ cloneRange(): Range_ {+ const r = new Range_();+ r._both(this.startContainer, this.startOffset, this.endContainer, this.endOffset);+ return r;+ }+ detach() {}+ compareBoundaryPoints(how: number, other: Range_): number {+ const [a, ao] = how === 0 || how === 3 ? [this.startContainer, this.startOffset] : [this.endContainer, this.endOffset];+ const [b, bo] = how === 0 || how === 1 ? [other.startContainer, other.startOffset] : [other.endContainer, other.endOffset];+ return cmpPoint(a, ao, b, bo);+ }+ comparePoint(n: Node_, o: number): number {+ check(n, o);+ if (cmpPoint(n, o, this.startContainer, this.startOffset) < 0) return -1;+ if (cmpPoint(n, o, this.endContainer, this.endOffset) > 0) return 1;+ return 0;+ }+ isPointInRange(n: Node_, o: number): boolean {+ if (n.getRootNode() !== this.startContainer.getRootNode()) return false;+ return this.comparePoint(n, o) === 0;+ }+ intersectsNode(n: Node_): boolean {+ const p = n.parentNode;+ if (!p) return true;+ const i = indexOf(n);+ return cmpPoint(p, i, this.endContainer, this.endOffset) < 0 && cmpPoint(p, i + 1, this.startContainer, this.startOffset) > 0;+ }+ /** the text nodes the range covers, each with the part of it covered: [node, from, to] */+ _texts(): [Text_, number, number][] {+ const out: [Text_, number, number][] = [];+ const { startContainer: s, startOffset: so, endContainer: e, endOffset: eo } = this;+ if (s === e && s instanceof Text_) return [[s, so, eo]];+ const root = this.commonAncestorContainer;+ const walk = (n: Node_) => {+ for (const k of n._kids) {+ if (k instanceof Text_) {+ const from = k === s ? so : 0;+ const to = k === e ? eo : k.data.length;+ if (k === s || k === e || (cmpPoint(k, 0, s, so) >= 0 && cmpPoint(k, k.data.length, e, eo) <= 0)) {+ if (k === s || k === e || this.intersectsNode(k)) out.push([k, from, to]);+ }+ } else walk(k);+ }+ };+ if (root instanceof Text_) return [[root, so, eo]];+ walk(root);+ return out;+ }+ toString(): string {+ return this._texts()+ .map(([t, a, b]) => t.data.slice(a, b))+ .join("");+ }+ getClientRects(): DOMRect_[] {+ return nodeList(rangeRects(this));+ }+ getBoundingClientRect(): DOMRect_ {+ const rs = rangeRects(this);+ if (!rs.length) return new DOMRect_(0, 0, 0, 0);+ let [l, t, r, b] = [Infinity, Infinity, -Infinity, -Infinity];+ for (const x of rs) {+ l = Math.min(l, x.left);+ t = Math.min(t, x.top);+ r = Math.max(r, x.right);+ b = Math.max(b, x.bottom);+ }+ return new DOMRect_(l, t, r - l, b - t);+ }+ /** the range's contents removed: a text's covered part cut, the nodes wholly inside taken out, and the range+ * collapsed where they were (DOM's deleteContents, for one container or across siblings' subtrees) */+ deleteContents() {+ if (this.collapsed) return;+ const { startContainer: s, startOffset: so, endContainer: e, endOffset: eo } = this;+ if (s === e && s instanceof Text_) {+ s.deleteData(so, eo - so);+ return;+ }+ // where the range collapses: the start, or after the start's ancestor that's under the end's+ let [ns, no] = [s, so];+ if (!s.contains(e)) {+ let r: Node_ = s;+ while (r.parentNode && !r.parentNode.contains(e)) r = r.parentNode;+ [ns, no] = [r.parentNode!, indexOf(r) + 1];+ }+ // the nodes wholly inside whose parent isn't+ const inside = (k: Node_) => cmpPoint(k.parentNode!, indexOf(k), s, so) >= 0 && cmpPoint(k.parentNode!, indexOf(k) + 1, e, eo) <= 0;+ const whole: Node_[] = [];+ const walk = (n: Node_) => {+ for (const k of n._kids) {+ if (inside(k)) whole.push(k);+ else if (k.contains(s) || k.contains(e) || this.intersectsNode(k)) walk(k);+ }+ };+ walk(this.commonAncestorContainer);+ if (s instanceof Text_) s.deleteData(so, s.data.length - so);+ for (const n of whole) n.parentNode?.removeChild(n);+ if (e instanceof Text_) e.deleteData(0, eo);+ no = Math.min(no, nodeLength(ns));+ this._both(ns, no, ns, no);+ }+ insertNode(n: Node_) {+ const { startContainer: s, startOffset: so } = this;+ let parent: Node_;+ let before: Node_ | null;+ if (s instanceof Text_) {+ parent = s.parentNode!;+ before = so === 0 ? s : so === s.data.length ? s.nextSibling : s.splitText(so);+ } else {+ parent = s;+ before = s._kids[so] ?? null;+ }+ const grow = this.collapsed;+ parent.insertBefore(n, before);+ if (grow) this.setEnd(parent, indexOf(n) + (n instanceof DocumentFragment_ ? 0 : 1));+ }+ cloneContents(): DocumentFragment_ {+ const f = new DocumentFragment_();+ f.appendChild(doc.createTextNode(this.toString()));+ return f;+ }+ extractContents(): DocumentFragment_ {+ const f = this.cloneContents();+ this.deleteContents();+ return f;+ }+ surroundContents(n: Node_) {+ const f = this.extractContents();+ this.insertNode(n);+ n.appendChild(f);+ this.selectNode(n);+ }+}++// ---------------------------------------------------------------- the tree's mutations, on live ranges++/** A child list change (from nodes.ts's mutated): `added` put in at `at`, or `removed` taken out of `at`. */+export function rangesChildList(parent: Node_, at: number, added: number, removed: Node_ | null) {+ for (const r of live) {+ for (const start of [true, false]) {+ let n = start ? r.startContainer : r.endContainer;+ let o = start ? r.startOffset : r.endOffset;+ if (removed && removed.contains(n)) [n, o] = [parent, at];+ else if (n === parent && removed && o > at) o--;+ else if (n === parent && added && o > at) o += added;+ if (start) [r.startContainer, r.startOffset] = [n, o];+ else [r.endContainer, r.endOffset] = [n, o];+ }+ r._sel?._changed(false);+ }+}++/** A text's data replaced from `at`, `count` characters by `len` new ones (DOM's replace data). */+export function rangesText(t: Text_, at: number, count: number, len: number) {+ for (const r of live) {+ let moved = false;+ for (const start of [true, false]) {+ const n = start ? r.startContainer : r.endContainer;+ if (n !== t) continue;+ let o = start ? r.startOffset : r.endOffset;+ if (o > at && o <= at + count) o = at;+ else if (o > at + count) o += len - count;+ else continue;+ moved = true;+ if (start) r.startOffset = o;+ else r.endOffset = o;+ }+ if (moved) r._sel?._changed(false);+ }+}++/** A text split at `at` into it and `next` (DOM's split a Text node): points past the split go to the new node. */+export function rangesSplit(t: Text_, at: number, next: Text_) {+ for (const r of live) {+ if (r.startContainer === t && r.startOffset > at) [r.startContainer, r.startOffset] = [next, r.startOffset - at];+ if (r.endContainer === t && r.endOffset > at) [r.endContainer, r.endOffset] = [next, r.endOffset - at];+ }+}++export const liveRanges = () => live.size > 0;++// ---------------------------------------------------------------- Selection++export class Selection_ {+ _range: Range_ | null = null;+ /** anchor before focus */+ _forward = true;+ get rangeCount() {+ return this._range ? 1 : 0;+ }+ get anchorNode() {+ return this._range ? (this._forward ? this._range.startContainer : this._range.endContainer) : null;+ }+ get anchorOffset() {+ return this._range ? (this._forward ? this._range.startOffset : this._range.endOffset) : 0;+ }+ get focusNode() {+ return this._range ? (this._forward ? this._range.endContainer : this._range.startContainer) : null;+ }+ get focusOffset() {+ return this._range ? (this._forward ? this._range.endOffset : this._range.startOffset) : 0;+ }+ get baseNode() {+ return this.anchorNode;+ }+ get baseOffset() {+ return this.anchorOffset;+ }+ get extentNode() {+ return this.focusNode;+ }+ get extentOffset() {+ return this.focusOffset;+ }+ get isCollapsed() {+ return !this._range || this._range.collapsed;+ }+ get type() {+ return !this._range ? "None" : this._range.collapsed ? "Caret" : "Range";+ }+ get direction() {+ return !this._range || this._range.collapsed ? "none" : this._forward ? "forward" : "backward";+ }+ getRangeAt(i: number): Range_ {+ if (i !== 0 || !this._range) throw new Error(`IndexSizeError: no range at ${i}`);+ return this._range;+ }+ _adopt(r: Range_ | null, forward = true) {+ if (this._range && this._range !== r) {+ this._range._sel = null;+ live.delete(this._range);+ }+ this._range = r;+ this._forward = forward;+ if (r) {+ r._sel = this;+ live.add(r);+ }+ this._changed(true);+ }+ addRange(r: Range_) {+ if (this._range || !r.startContainer.isConnected) return;+ this._adopt(r);+ }+ removeRange(r: Range_) {+ if (r !== this._range) throw new Error("NotFoundError: not the selection's range");+ this._adopt(null);+ }+ removeAllRanges() {+ if (this._range) this._adopt(null);+ }+ empty() {+ this.removeAllRanges();+ }+ collapse(n: Node_ | null, o = 0) {+ if (!n) return this.removeAllRanges();+ check(n, o);+ if (!n.isConnected) return;+ const r = new Range_();+ r._both(n, o, n, o);+ this._adopt(r);+ }+ setPosition(n: Node_ | null, o = 0) {+ this.collapse(n, o);+ }+ collapseToStart() {+ if (!this._range) throw new Error("InvalidStateError: no selection");+ this.collapse(this._range.startContainer, this._range.startOffset);+ }+ collapseToEnd() {+ if (!this._range) throw new Error("InvalidStateError: no selection");+ this.collapse(this._range.endContainer, this._range.endOffset);+ }+ extend(n: Node_, o = 0) {+ if (!this._range) throw new Error("InvalidStateError: no selection to extend");+ check(n, o);+ this.setBaseAndExtent(this.anchorNode!, this.anchorOffset, n, o);+ }+ setBaseAndExtent(a: Node_, ao: number, f: Node_, fo: number) {+ check(a, ao);+ check(f, fo);+ if (!a.isConnected || !f.isConnected) return;+ const r = new Range_();+ const fwd = cmpPoint(a, ao, f, fo) <= 0;+ if (fwd) r._both(a, ao, f, fo);+ else r._both(f, fo, a, ao);+ this._adopt(r, fwd);+ }+ selectAllChildren(n: Node_) {+ this.setBaseAndExtent(n, 0, n, nodeLength(n));+ }+ containsNode(n: Node_, partly = false): boolean {+ const r = this._range;+ if (!r || !n.parentNode) return false;+ const p = n.parentNode;+ const i = indexOf(n);+ if (partly) return r.intersectsNode(n);+ return cmpPoint(p, i, r.startContainer, r.startOffset) >= 0 && cmpPoint(p, i + 1, r.endContainer, r.endOffset) <= 0;+ }+ deleteFromDocument() {+ this._range?.deleteContents();+ }+ /** Selection.modify: moved or extended by a character, word or line (editing.ts's moves) */+ modify(alter: string, direction: string, granularity: string) {+ (globalThis as { __raea_modify?: (s: Selection_, a: string, d: string, g: string) => void }).__raea_modify?.(this, alter, direction, granularity);+ }+ toString() {+ return this._range?.toString() ?? "";+ }+ /** The selection changed: selectionchange queued (one per task, as Chrome coalesces them), and the host told+ * what to paint. `now` is a change made through the API rather than a mutation's move. */+ _changed(_now: boolean) {+ scheduleChange();+ }+}++export const selection = new Selection_();++let queued = false;++let lastSent = "";++function scheduleChange() {+ if (queued) return;+ queued = true;+ setTimeout(() => {+ queued = false;+ mirror();+ run(() => dispatch(doc, new Event_("selectionchange", { bubbles: false, cancelable: false }), true));+ }, 0);+}++/** A boundary point as the host takes it: a text's wire id and UTF-16 offset, or an element's wire id and the wire id+ * of the child it's before (null: at its end). Unwired points have none. */+function hostPoint(n: Node_, o: number): { id: number; offset?: number; before?: number | null } | null {+ if (!n._wired || n.__wid === undefined) return null;+ if (n instanceof Text_) return { id: n.__wid, offset: o };+ if (!(n instanceof Element_)) return null;+ // the element's own string (React's text content) is one text: its offset is in it+ if (n._inline !== undefined) return { id: n.__wid, offset: o ? n._inline.length : 0 };+ for (let i = o; i < n._kids.length; i++) if (n._kids[i]._wired) return { id: n.__wid, before: n._kids[i].__wid };+ return { id: n.__wid, before: null };+}++/** What the host paints: the selection's two ends, and whether a caret shows (collapsed in a focused editable). */+export function mirror() {+ const s = selection;+ const a = s.anchorNode ? hostPoint(s.anchorNode, s.anchorOffset) : null;+ const f = s.focusNode ? hostPoint(s.focusNode, s.focusOffset) : null;+ const editable = !!S.active && (S.active as { isContentEditable?: boolean }).isContentEditable === true && !!s.focusNode && S.active.contains(s.focusNode);+ const msg = a && f ? { anchor: a, focus: f, caret: editable && s.isCollapsed } : null;+ const json = JSON.stringify(msg);+ if (json === lastSent) return;+ lastSent = json;+ try {+ wire.callSync("selection.set", msg);+ } catch {+ // a host without selection painting (the bevy_ui page)+ }+}++/** The host said the selection's endpoints moved off the tree (a fresh mount): forget it. */+export function resetSelection() {+ selection._adopt(null);+ lastSent = "";+}diff --git a/sdk/ui/src/elements.ts b/sdk/ui/src/elements.tsindex 6b4ea46c..1012d4fc 100644--- a/sdk/ui/src/elements.ts+++ b/sdk/ui/src/elements.ts@@ -1,8 +1,8 @@// Elements the page host draws that React's JSX doesn't type, typed as raea's own so `<view3d>` and its parts check// in a space's TSX (tools/sdk-coverage counts them as typed). Each prop is what runtime/js view3d.rs reads// (clear_color, projection, eye, spawn_part, mesh_of); the Blitz page's host builds its views with the same functions-// (engine/page view3d.rs, run from host.rs). A composition's render doesn't draw them: its 3D is <Canvas3D>-// (raea/3d), until M6 makes one tree. Vectors are [x, y, z]; angles are degrees; colours are CSS colours.+// (engine/page view3d.rs, run from host.rs). A composition's render doesn't draw them: its 3D is raea/3d's+// (a Camera3d and its parts). Vectors are [x, y, z]; angles are degrees; colours are CSS colours.import type { HTMLAttributes } from "react";type Vec3 = [number, number, number];diff --git a/sdk/ui/src/html/page/load.ts b/sdk/ui/src/html/page/load.tsindex dea76144..efe217bd 100644--- a/sdk/ui/src/html/page/load.ts+++ b/sdk/ui/src/html/page/load.ts@@ -58,6 +58,9 @@ async function load() {// (a host that never lays out, as the test host, is waited for a moment only)for (let i = 0; i < 3; i++) await new Promise((r) => (g.requestAnimationFrame(r), setTimeout(r, 200)));namedAccess();+ // the registry a page's scripts put their timelines in (window.__timelines["main"] = tl), made before they run as+ // The composition format's own runtime makes it: without it every such script threw at that line and the page never moved+ g.__timelines ??= {};for (let i = 0; i < compiled.scripts.length; i++) await runScript(compiled.scripts[i], i);try {document.dispatchEvent(new g.Event("DOMContentLoaded", { bubbles: true }));diff --git a/sdk/ui/src/react.ts b/sdk/ui/src/react.tsindex d16feee1..9846d472 100644--- a/sdk/ui/src/react.ts+++ b/sdk/ui/src/react.ts@@ -129,6 +129,9 @@ const config: Reconciler.HostConfig<string, Props, Container, Instance, { id: nuif (domMode) {const h = dom.hostElement(id, type, props, fiber, ctx === SVG_CTX);wire.create(id, h.kind, h.props, h.text);+ // dangerouslySetInnerHTML, as React DOM sets it: the markup parsed into this element's children (an inline SVG+ // icon, a sanitizer's HTML), each on the host now that the element is+ dom.innerHtmlProp(h.el, undefined, props);dom.listenFor(h.el);return h.el as unknown as Instance;}@@ -203,6 +206,9 @@ function unplace(p: any, c: any) {}const reconciler = Reconciler(config);+// in development, React Refresh's runtime (the window's dev runner, apps/app blitz/runner.ts) installs the devtools hook+// before React loads; registered with it, an edited component re-renders in place with its state kept+if ((globalThis as { __REACT_DEVTOOLS_GLOBAL_HOOK__?: unknown }).__REACT_DEVTOOLS_GLOBAL_HOOK__) reconciler.injectIntoDevTools();const ConcurrentRoot = 1;/** Runs `fn` and commits what it set synchronously (each host event is run this way). */diff --git a/sdk/ui/src/wire.ts b/sdk/ui/src/wire.tsindex c718a7c3..ebeaf9a1 100644--- a/sdk/ui/src/wire.ts+++ b/sdk/ui/src/wire.ts@@ -100,7 +100,11 @@ let nextId = 1; // 0 is the root// ops pushed outside a handler (a call's answer awaited, a timer) go out at the next microtasklet inDispatch = 0;let scheduled = false;+/** How many ops the JS has written, ever: geometry asks whether the page changed since it was last laid out. */+let written = 0;+export const writes = () => written;function pend(op: Op) {+ written++;pending.push(op);if (inDispatch || scheduled) return;scheduled = true;diff --git a/sdk/ui/test/dom.test.tsx b/sdk/ui/test/dom.test.tsxindex bd50812a..dfbf34d8 100644--- a/sdk/ui/test/dom.test.tsx+++ b/sdk/ui/test/dom.test.tsx@@ -99,6 +99,34 @@ describe("P18 DOM surface", () => {expect(ops.some((o: any) => o.op === "update" && o.set?.scrollTop === 400)).toBe(true);});+ test("a press goes where the host's cascade says: a child a stylesheet gives pointer events back, under a pointer-events-none layer", () => {+ const host = fresh();+ const log: string[] = [];+ function App() {+ return (+ <div data-testid="root" onClick={() => log.push("behind")}>+ <div data-testid="dock" className="pointer-events-none">+ <div data-testid="row" className="[&>*]:pointer-events-auto">+ <button data-testid="ok" onClick={() => log.push("allowed")}>Allow</button>+ </div>+ </div>+ </div>+ );+ }+ mount(<App />, 0, { dom: true });+ snap(host, { root: [0, 0, 800, 600], dock: [0, 400, 800, 200], row: [0, 400, 800, 100], ok: [10, 410, 40, 24] });+ // without the host's target, sdk/ui's own walk can't read the child variant and the press falls through+ host.send("root", "pointerdown", press(20, 420));+ host.send("root", "pointerup", press(20, 420));+ expect(log).toEqual(["behind"]);+ log.length = 0;+ // with it (Blitz's hit path, decided by Stylo as Chrome would), the button gets the click+ const target = host.tid("ok");+ host.send("root", "pointerdown", { ...press(20, 420), target });+ host.send("root", "pointerup", { ...press(20, 420), target });+ expect(log).toEqual(["allowed", "behind"]);+ });+test("a press: capture and bubble through native and React listeners in Chrome's order, then click", () => {const host = fresh();const log: string[] = [];@@ -264,3 +292,31 @@ describe("P18 DOM surface", () => {expect(seen).toEqual(["root", "root", "made"]);});});++describe("dangerouslySetInnerHTML", () => {+ test("its markup becomes the element's children on the host, an inline SVG in SVG's namespace, and follows a change", () => {+ const host = fresh();+ const icon = (fill: string) => `<svg viewBox="0 0 24 24" width="1em" height="1em"><title>Mark</title><path fill="${fill}" d="M0 0h24v24H0z"></path></svg>`;+ let set!: (s: string) => void;+ let ref: any;+ function App() {+ const [fill, setFill] = useState("#D97757");+ set = setFill;+ const r = useRef<any>(null);+ useEffect(() => void (ref = r.current), []);+ return <span ref={r} data-testid="mark" dangerouslySetInnerHTML={{ __html: icon(fill) }} />;+ }+ mount(<App />, 0, { dom: true });+ const span = host.nodes.get(host.tid("mark"))!;+ const svg = host.nodes.get(span.children[0])!;+ expect(svg.kind).toBe("svg");+ expect(svg.props.viewBox).toBe("0 0 24 24");+ const path = svg.children.map((c) => host.nodes.get(c)!).find((n) => n.kind === "path")!;+ expect(path.props.fill).toBe("#D97757");+ expect(ref.querySelector("path").namespaceURI).toBe("http://www.w3.org/2000/svg");+ flushSync(() => set("#1783FF"));+ const svg2 = host.nodes.get(host.nodes.get(host.tid("mark"))!.children[0])!;+ expect(svg2.children.map((c) => host.nodes.get(c)!).find((n) => n.kind === "path")!.props.fill).toBe("#1783FF");+ expect(host.nodes.get(host.tid("mark"))!.children.length).toBe(1);+ });+});diff --git a/sdk/ui/test/editing.test.ts b/sdk/ui/test/editing.test.tsnew file mode 100644index 00000000..75f6c61a--- /dev/null+++ b/sdk/ui/test/editing.test.ts@@ -0,0 +1,135 @@+// contenteditable and Selection (docs/ts-native.feature P14a) on the stand-in host: typing, Backspace, Delete and+// arrows edit the DOM in place with Chrome's events and mutation records, and the selection's range is live. The+// same is proved against Chrome by sdk/ui/parity/cases/p14-forms/contenteditable.tsx; this is the fast check.+import { beforeAll, describe, expect, test } from "bun:test";+import { install } from "../src/dom";+import { restart } from "../src/wire";+import { Host } from "./host";++beforeAll(() => install());+const g = globalThis as any;+const d = () => g.document;++function editor(html: (el: any) => void) {+ restart();+ new Host();+ const el = d().createElement("div");+ el.setAttribute("contenteditable", "true");+ html(el);+ d().body.appendChild(el);+ el.focus();+ return el;+}+const key = (k: string, mods: Record<string, boolean> = {}) => g.__ui_deliver(JSON.stringify({ t: "named", name: "keydown", value: { key: k, ...mods } }));+const type = (s: string) => [...s].forEach((c) => key(c));++describe("P14a contenteditable", () => {+ test("isContentEditable, contentEditable and focus", () => {+ const el = editor((e) => e.appendChild(d().createElement("p")));+ expect(el.isContentEditable).toBe(true);+ expect(el.contentEditable).toBe("true");+ expect(el.firstChild.isContentEditable).toBe(true);+ expect(d().activeElement).toBe(el);+ const off = d().createElement("span");+ off.contentEditable = "false";+ el.appendChild(off);+ expect(off.isContentEditable).toBe(false);+ });++ test("typing inserts at the caret, with beforeinput, input and characterData records", async () => {+ const el = editor((e) => e.appendChild(d().createTextNode("ac")));+ const t = el.firstChild;+ const events: string[] = [];+ for (const ty of ["keydown", "keypress", "beforeinput", "input"]) el.addEventListener(ty, (e: any) => events.push(`${ty}:${e.inputType ?? e.key}`));+ const records: any[] = [];+ const mo = new g.MutationObserver((rs: any[]) => records.push(...rs));+ mo.observe(el, { subtree: true, characterData: true, characterDataOldValue: true, childList: true });+ g.getSelection().collapse(t, 1);+ type("b");+ expect(el.textContent).toBe("abc");+ expect(events).toEqual(["keydown:b", "keypress:b", "beforeinput:insertText", "input:insertText"]);+ const s = g.getSelection();+ expect([s.focusNode, s.focusOffset, s.isCollapsed]).toEqual([t, 2, true]);+ await Promise.resolve();+ expect(records.map((r) => [r.type, r.oldValue])).toEqual([["characterData", "ac"]]);+ });++ test("a prevented beforeinput edits nothing", () => {+ const el = editor((e) => e.appendChild(d().createTextNode("x")));+ el.addEventListener("beforeinput", (e: any) => e.preventDefault());+ g.getSelection().collapse(el.firstChild, 1);+ type("y");+ expect(el.textContent).toBe("x");+ });++ test("Backspace, Delete and arrows across text nodes and a mark", () => {+ const el = editor((e) => {+ e.appendChild(d().createTextNode("ab"));+ const b = d().createElement("strong");+ b.appendChild(d().createTextNode("cd"));+ e.appendChild(b);+ e.appendChild(d().createTextNode("ef"));+ });+ const s = g.getSelection();+ s.collapse(el.lastChild, 2);+ key("Backspace");+ expect(el.textContent).toBe("abcde");+ key("ArrowLeft");+ // from the text after the mark, a step back is into the mark (between its c and d)+ key("ArrowLeft");+ expect([s.focusNode.data, s.focusOffset]).toEqual(["cd", 1]);+ key("Delete");+ expect(el.textContent).toBe("abce");+ key("ArrowRight", { shiftKey: true });+ key("ArrowRight", { shiftKey: true });+ expect(s.toString()).toBe("e");+ type("Z");+ expect(el.textContent).toBe("abcZ");+ });++ test("Enter splits the block; Backspace at its start joins it back", () => {+ const el = editor((e) => {+ const p = d().createElement("p");+ p.appendChild(d().createTextNode("hello"));+ e.appendChild(p);+ });+ const s = g.getSelection();+ s.collapse(el.firstChild.firstChild, 2);+ key("Enter");+ expect(el.children.length).toBe(2);+ expect([el.children[0].textContent, el.children[1].textContent]).toEqual(["he", "llo"]);+ key("Backspace");+ expect(el.children.length).toBe(1);+ expect(el.textContent).toBe("hello");+ });++ test("the selection's range is live: a removed node moves it to the parent", () => {+ const el = editor((e) => {+ e.appendChild(d().createTextNode("a"));+ e.appendChild(d().createTextNode("b"));+ });+ const s = g.getSelection();+ s.collapse(el.lastChild, 1);+ el.removeChild(el.lastChild);+ expect([s.focusNode, s.focusOffset]).toEqual([el, 1]);+ const r = d().createRange();+ r.setStart(el.firstChild, 0);+ r.setEnd(el, 1);+ expect(r.toString()).toBe("a");+ expect(r.collapsed).toBe(false);+ });++ test("selectionchange comes as a task, once for several changes", async () => {+ const el = editor((e) => e.appendChild(d().createTextNode("abc")));+ let n = 0;+ d().addEventListener("selectionchange", () => n++);+ await new Promise((r) => setTimeout(r, 1));+ n = 0;+ const s = g.getSelection();+ s.collapse(el.firstChild, 0);+ s.extend(el.firstChild, 2);+ expect(n).toBe(0);+ await new Promise((r) => setTimeout(r, 1));+ expect(n).toBe(1);+ });+});diff --git a/sdk/ui/test/nested-canvas.test.tsx b/sdk/ui/test/nested-canvas.test.tsxnew file mode 100644index 00000000..ee0b29ef--- /dev/null+++ b/sdk/ui/test/nested-canvas.test.tsx@@ -0,0 +1,28 @@+import { beforeAll, expect, test } from "bun:test";+import { install } from "../src/dom";++beforeAll(() => install());+const g = globalThis as any;++test("a canvas drawn on another goes as its list, copied, keyed by what it holds (systems/canvas replays it)", () => {+ const a = g.document.createElement("canvas");+ a.width = 20;+ a.height = 10;+ const ca = a.getContext("2d");+ ca.fillStyle = "red";+ ca.fillRect(0, 0, 5, 5);+ const b = g.document.createElement("canvas");+ const cb = b.getContext("2d");+ cb.drawImage(a, 3, 4, 10, 5);+ const op = (cb as any).list.at(-1);+ expect(op[0]).toBe("canvas");+ expect(op[1]).toMatchObject({ w: 20, h: 10 });+ expect(op[1].ops).toHaveLength(1);+ expect(op.slice(2, 10)).toEqual([null, null, null, null, 3, 4, 10, 5]);+ // drawn on after: the copy sent before is unchanged and the next draw has a new key+ const key = op[1].key;+ ca.fillRect(5, 5, 5, 5);+ expect(op[1].ops).toHaveLength(1);+ cb.drawImage(a, 0, 0);+ expect((cb as any).list.at(-1)[1].key).not.toBe(key);+});diff --git a/sdk/ui/test/tag-classes.test.tsx b/sdk/ui/test/tag-classes.test.tsxnew file mode 100644index 00000000..6e38d08b--- /dev/null+++ b/sdk/ui/test/tag-classes.test.tsx@@ -0,0 +1,15 @@+import { beforeAll, expect, test } from "bun:test";+import { install } from "../src/dom";++beforeAll(() => install());+const g = globalThis as any;++test("each tag makes its own class, a window global, as Chrome's (Excalidraw asks instanceof HTMLBRElement on every key)", () => {+ for (const [tag, name] of [["br", "HTMLBRElement"], ["p", "HTMLParagraphElement"], ["h2", "HTMLHeadingElement"], ["td", "HTMLTableCellElement"], ["div", "HTMLDivElement"]]) {+ const el = g.document.createElement(tag);+ expect(el instanceof g[name]).toBe(true);+ expect(el instanceof g.HTMLElement).toBe(true);+ expect(el.constructor.name).toBe(name);+ }+ expect(g.document.createElement("p") instanceof g.HTMLBRElement).toBe(false);+});diff --git a/sdk/video/src/media.tsx b/sdk/video/src/media.tsxindex d527fa94..cb285e87 100644--- a/sdk/video/src/media.tsx+++ b/sdk/video/src/media.tsx@@ -189,7 +189,7 @@ export function Audio(props: AudioProps) {attrs["data-generate"] = asset.kind;attrs["data-prompt"] = asset.prompt;attrs["data-seconds"] = asset.seconds;- // the generator's own settings (a TokenSynth note's midi, velocity, seed and precision; a Fish voice and speed),+ // the generator's own settings (a TokenSynth note's midi, velocity, seed and precision),// which the renderer passes to it with the prompt (sdk/react audio.rs `generated_params`)if (asset.options && Object.keys(asset.options).length) attrs["data-options"] = JSON.stringify(asset.options);}diff --git a/systems/canvas/Cargo.toml b/systems/canvas/Cargo.tomlindex f59e2c57..ee2ae711 100644--- a/systems/canvas/Cargo.toml+++ b/systems/canvas/Cargo.toml@@ -19,3 +19,5 @@ resvg = { version = "=0.48.1", default-features = false, features = ["text"] }tiny-skia = { version = "=0.12.0", default-features = false, features = ["std", "simd"] }# read's pixels across the wirebase64 = "0.22"+# which file of a family split by unicode-range has a glyph (subsets.rs)+ttf-parser = { version = "0.25", default-features = false, features = ["std"] }diff --git a/systems/canvas/src/draw.rs b/systems/canvas/src/draw.rsindex 7e739e29..34c0c938 100644--- a/systems/canvas/src/draw.rs+++ b/systems/canvas/src/draw.rs@@ -56,6 +56,12 @@ impl Ctx<'_> {let Some(img) = a.get(1).and_then(Value::as_str).and_then(|src| self.decode(src)) else { return };self.image(pm, a, &img)}+ // ["canvas", {key, w, h, ops}, sx, sy, sw, sh, dx, dy, dw, dh, state]: another canvas drawn on this one, its+ // list as it was then, replayed here (Excalidraw draws each element on a canvas of its own, then those)+ Some("canvas") => {+ let Some(img) = a.get(1).and_then(|l| self.nested(l)) else { return };+ self.image(pm, a, &img)+ }// ["video", src, sx, sy, sw, sh, dx, dy, dw, dh, state, t]: the frame showing at tSome("video") => {let Some(img) = a.get(1).and_then(Value::as_str).and_then(|src| video_frame(src, a.get(11).and_then(Value::as_f64).unwrap_or(0.0))) else { return };@@ -120,15 +126,27 @@ impl Ctx<'_> {Some("ideographic") => "ideographic",_ => "alphabetic",};- let mut esc = String::new();- for c in text.chars() {- match c {- '&' => esc.push_str("&"),- '<' => esc.push_str("<"),- _ => esc.push(c),+ let escape = |s: &str| {+ let mut e = String::new();+ for c in s.chars() {+ match c {+ '&' => e.push_str("&"),+ '<' => e.push_str("<"),+ _ => e.push(c),+ }}- }+ e+ };let fam = font["family"].as_str().unwrap_or("sans-serif").replace('"', "'");+ // a family split across files by unicode-range: each run names the file that has its glyphs (subsets.rs)+ let split = crate::split_families(&self.opt.fontdb).and_then(|s| crate::subsets::runs(&self.opt.fontdb, &s, &fam, text));+ let esc = match split {+ Some(runs) => runs.iter().map(|(f, s)| match f {+ Some(f) => format!("<tspan font-family=\"'{}', {fam}\">{}</tspan>", f.replace('\'', ""), escape(s)),+ None => format!("<tspan>{}</tspan>", escape(s)),+ }).collect(),+ None => escape(text),+ };let paint_attr = if kind == "fill" {"fill=\"#fff\"".to_string()} else {@@ -190,6 +208,32 @@ impl Ctx<'_> {Some(pm)}+ /// A canvas's list drawn on a bitmap of its own size: kept by its key (the page gives one per canvas, list+ /// generation and length), as the same element canvas is drawn on the board frame after frame.+ fn nested(&mut self, list: &Value) -> Option<sk::Pixmap> {+ static DRAWN: std::sync::Mutex<Vec<(String, sk::Pixmap)>> = std::sync::Mutex::new(Vec::new());+ let key = list["key"].as_str().map(str::to_string);+ if let Some(k) = &key+ && let Some((_, pm)) = DRAWN.lock().unwrap().iter().find(|(x, _)| x == k)+ {+ return Some(pm.clone());+ }+ let n = |k: &str| list[k].as_u64().filter(|v| *v > 0 && *v <= 16384).map(|v| v as u32);+ let mut out = sk::Pixmap::new(n("w")?, n("h")?)?;+ for op in list["ops"].as_array().into_iter().flatten() {+ self.op(&mut out, op);+ }+ if let Some(k) = key {+ let mut drawn = DRAWN.lock().unwrap();+ drawn.push((k, out.clone()));+ // the newest kept, up to 256 MB+ while drawn.iter().map(|(_, p)| p.data().len()).sum::<usize>() > 256 << 20 && drawn.len() > 1 {+ drawn.remove(0);+ }+ }+ Some(out)+ }+pub(crate) fn image(&mut self, pm: &mut sk::Pixmap, a: &[Value], img: &sk::Pixmap) {// ["image", src, sx, sy, sw, sh, dx, dy, dw, dh, state]let n = |i: usize| a.get(i).and_then(Value::as_f64).map(|v| v as f32);@@ -205,7 +249,17 @@ impl Ctx<'_> {let alpha = st["alpha"].as_f64().unwrap_or(1.0) as f32;let smooth = st["smooth"].as_bool().unwrap_or(true);// the source rect mapped onto the destination, in the call's space- let place = ts.pre_translate(dx, dy).pre_scale(dw / sw, dh / sh).pre_translate(-sx, -sy);+ // in the call's own space: fill_rect below applies `ts` to the shader too (placed with ts here as well, an+ // image under a scale drew from the wrong spot, its transparent padding, and Excalidraw's boards came out blank)+ // drawn under half size, smoothed: sampled from a mip level (halved), as Chrome does+ let shrink = ((ts.sx * ts.sx + ts.ky * ts.ky).sqrt() * dw / sw).abs().min(((ts.kx * ts.kx + ts.sy * ts.sy).sqrt() * dh / sh).abs());+ let levels = if smooth && shrink > 0.0 && shrink < 0.5 { ((1.0 / shrink).log2().floor() as u32).min(8) } else { 0 };+ let mip = (levels > 0).then(|| halved(img, levels)).flatten();+ let (img, k) = match &mip {+ Some(m) => (m, iw / m.width() as f32),+ None => (img, 1.0),+ };+ let place = sk::Transform::from_translate(dx, dy).pre_scale(dw / sw * k, dh / sh * k).pre_translate(-sx / k, -sy / k);let quality = if smooth { sk::FilterQuality::Bilinear } else { sk::FilterQuality::Nearest };let pattern = sk::Pattern::new(img.as_ref(), sk::SpreadMode::Pad, quality, alpha, place);let Some(inv) = ts.invert() else { return };@@ -219,3 +273,51 @@ impl Ctx<'_> {});}}++/// `img` halved `levels` times, each pixel the mean of the 2x2 block under it (premultiplied, so a mean is right): the+/// mip level Chrome samples an image drawn small from. Bilinear on the full image aliases, and a poster's stars+/// sparkled on a board at 50%.+fn halved(img: &sk::Pixmap, levels: u32) -> Option<sk::Pixmap> {+ let mut cur: std::borrow::Cow<sk::Pixmap> = std::borrow::Cow::Borrowed(img);+ for _ in 0..levels {+ let (w, h) = (cur.width(), cur.height());+ if w < 2 || h < 2 {+ break;+ }+ let (nw, nh) = (w / 2, h / 2);+ let mut out = sk::Pixmap::new(nw, nh)?;+ let src = cur.data();+ let dst = out.data_mut();+ for y in 0..nh as usize {+ for x in 0..nw as usize {+ for c in 0..4 {+ let at = |yy: usize, xx: usize| u16::from(src[(yy * w as usize + xx) * 4 + c]);+ let sum = at(2 * y, 2 * x) + at(2 * y, 2 * x + 1) + at(2 * y + 1, 2 * x) + at(2 * y + 1, 2 * x + 1);+ dst[(y * nw as usize + x) * 4 + c] = ((sum + 2) / 4) as u8;+ }+ }+ }+ cur = std::borrow::Cow::Owned(out);+ }+ match cur {+ std::borrow::Cow::Owned(p) => Some(p),+ std::borrow::Cow::Borrowed(_) => None,+ }+}+++#[cfg(test)]+mod tests {+ #[test]+ fn a_checkerboard_halved_is_its_mean() {+ let mut pm = tiny_skia::Pixmap::new(4, 4).unwrap();+ for (i, px) in pm.data_mut().chunks_mut(4).enumerate() {+ let on = (i % 4 + i / 4) % 2 == 0;+ px.copy_from_slice(if on { &[255, 255, 255, 255] } else { &[0, 0, 0, 255] });+ }+ let h = super::halved(&pm, 1).unwrap();+ assert_eq!((h.width(), h.height()), (2, 2));+ assert!(h.data().chunks(4).all(|p| p == [128, 128, 128, 255]), "{:?}", h.data());+ assert!(super::halved(&pm, 0).is_none());+ }+}diff --git a/systems/canvas/src/lib.rs b/systems/canvas/src/lib.rsindex 3c983881..cf1b13e8 100644--- a/systems/canvas/src/lib.rs+++ b/systems/canvas/src/lib.rs@@ -26,8 +26,11 @@ use serde_json::Value;use tiny_skia as sk;mod draw;+mod measure;+pub use measure::advances;mod filter;mod paint;+mod subsets;pub mod svg;use paint::*;@@ -79,13 +82,24 @@ pub fn videos(find: fn(&str) -> Option<std::path::PathBuf>) {/// The fonts a canvas was last drawn in (`canvas.read` has no World to ask).static FONTS: std::sync::Mutex<Option<std::sync::Arc<usvg::fontdb::Database>>> = std::sync::Mutex::new(None);+/// Where the page's fonts are now, for `canvas.read`, from a host that has them (raea-page's Blitz page: blitz-dom's+/// font database). Without it a read used the fonts the last shown canvas was drawn in, and a canvas read back just+/// after the page added a face (Excalidraw drawing each element onto a canvas of its own once Excalifont was in) came+/// back in the fallback, until some shown canvas was drawn again.+static FONT_SOURCE: std::sync::OnceLock<fn() -> std::sync::Arc<usvg::fontdb::Database>> = std::sync::OnceLock::new();++/// Gives `canvas.read` the page's fonts as they are when it's called. The first host's stands: there is one page font+/// database a process.+pub fn fonts(now: fn() -> std::sync::Arc<usvg::fontdb::Database>) {+ let _ = FONT_SOURCE.set(now);+}+/// `canvas.read` {width, height, __canvas2d, x, y, w, h} -> {data: base64 RGBA}: the canvas's list drawn on a bitmap of/// its own and the rectangle read off it, outside the bitmap transparent black (getImageData's answer).pub fn read(args: &Value) -> Result<Value, String> {use base64::Engine as _;let props = args.as_object().ok_or("no canvas")?;- let db = FONTS.lock().unwrap().clone();- let opt = db.map_or_else(usvg::Options::default, |db| page_fonts(&db));+ let opt = page_options();let (bw, bh, px) = Replay::update(None, props, &opt).rgba();let n = |k: &str| args[k].as_f64().unwrap_or(0.0) as i64;let (x, y, w, h) = (n("x"), n("y"), n("w").max(0), n("h").max(0));@@ -109,6 +123,12 @@ pub fn read(args: &Value) -> Result<Value, String> {Ok(serde_json::json!({ "data": base64::engine::general_purpose::STANDARD.encode(out) }))}+/// The text options a page's canvas draws with now: its fonts (`fonts`) as page_fonts makes them, else the defaults.+pub(crate) fn page_options() -> usvg::Options<'static> {+ let db = FONT_SOURCE.get().map(|now| now()).or_else(|| FONTS.lock().unwrap().clone());+ db.map_or_else(usvg::Options::default, |db| page_fonts(&db))+}+/// Where a video's src is as a file, for its frames drawn on a canvas (`videos`).static VIDEO_PATHS: std::sync::RwLock<Option<fn(&str) -> Option<std::path::PathBuf>>> = std::sync::RwLock::new(None);@@ -162,21 +182,63 @@ mod tests {assert_eq!(pm.pixel(5, 5).unwrap().alpha(), 0);assert_eq!(pm.pixel(15, 5).unwrap().alpha(), 255);}++ #[test]+ fn a_canvas_drawn_on_another_is_its_list_replayed() {+ let opt = usvg::Options::default();+ let mut pm = sk::Pixmap::new(8, 8).unwrap();+ let mut cx = Ctx { opt: &opt, images: HashMap::new() };+ let st = serde_json::json!({"ts": [1, 0, 0, 1, 0, 0], "alpha": 1, "comp": "source-over", "clip": []});+ // the source: a 2x2 canvas filled red; drawn at 4,4 scaled to 4x4+ let rect = serde_json::json!([0, 0, 0, 1, 2, 0, 1, 2, 2, 1, 0, 2, 4]);+ let src = serde_json::json!({"key": "test:1:1", "w": 2, "h": 2, "ops": [["fill", rect, "nonzero", [255, 0, 0, 1], st]]});+ cx.op(&mut pm, &serde_json::json!(["canvas", src, null, null, null, null, 4, 4, 4, 4, st]));+ let at = |x: u32, y: u32| pm.pixel(x, y).unwrap().demultiply();+ assert_eq!((at(5, 5).red(), at(5, 5).alpha()), (255, 255));+ assert_eq!(at(2, 2).alpha(), 0);+ }++ #[test]+ fn image_under_a_scale() {+ // Excalidraw's way: a 4x4 picture drawn at 2x size under a 0.5 transform covers 4x4 pixels at (2, 2)+ let mut pm = sk::Pixmap::new(12, 12).unwrap();+ let opt = usvg::Options::default();+ let mut img = sk::Pixmap::new(4, 4).unwrap();+ img.fill(sk::Color::from_rgba8(0, 200, 0, 255));+ let mut cx = Ctx { opt: &opt, images: HashMap::from([("pic".to_string(), img)]) };+ let st = serde_json::json!({"ts": [0.5, 0, 0, 0.5, 0, 0], "alpha": 1, "comp": "source-over", "clip": [], "shadow": null, "smooth": false});+ cx.op(&mut pm, &serde_json::json!(["image", "pic", null, null, null, null, 4, 4, 8, 8, st]));+ for (x, y) in [(2, 2), (5, 5), (3, 4)] {+ assert_eq!(pm.pixel(x, y).unwrap().green(), 200, "inside at {x},{y}");+ }+ for (x, y) in [(1, 1), (6, 6), (9, 3)] {+ assert_eq!(pm.pixel(x, y).unwrap().alpha(), 0, "outside at {x},{y}");+ }+ }}/// Text options for a canvas drawn without a Bevy world's fonts (raea-page's Blitz page): the faces in `db` (the/// system's and the page's own @font-face faces, blitz-dom's SVG faces), with Chrome's generic families on macOSpub fn page_fonts(db: &std::sync::Arc<usvg::fontdb::Database>) -> usvg::Options<'static> {- type Faces = std::sync::Arc<usvg::fontdb::Database>;- // the last `db` and its copy with the generic families set, made again when the page adds a face- static LAST: std::sync::Mutex<Option<(Faces, Faces)>> = std::sync::Mutex::new(None);- let mut last = LAST.lock().unwrap();- if !last.as_ref().is_some_and(|(from, _)| std::sync::Arc::ptr_eq(from, db)) {+ let mut last = PAGE_FONTS.lock().unwrap();+ if !last.as_ref().is_some_and(|(from, _, _)| std::sync::Arc::ptr_eq(from, db)) {let mut faces = (**db).clone();faces.set_sans_serif_family("Helvetica");faces.set_serif_family("Times");faces.set_monospace_family("Courier");- *last = Some((db.clone(), std::sync::Arc::new(faces)));+ // a family the page split by unicode-range, each file under an alias of its own (subsets.rs)+ let split = subsets::alias(&mut faces);+ *last = Some((db.clone(), std::sync::Arc::new(faces), std::sync::Arc::new(split)));}usvg::Options { fontdb: last.as_ref().unwrap().1.clone(), ..Default::default() }}++type Faces = std::sync::Arc<usvg::fontdb::Database>;+/// The last `db` page_fonts was given, its copy with the generic families set and the split families aliased, made+/// again when the page adds a face.+static PAGE_FONTS: std::sync::Mutex<Option<(Faces, Faces, std::sync::Arc<subsets::Subsets>)>> = std::sync::Mutex::new(None);++/// The split families of a database page_fonts made (none for any other: a Bevy world's fonts).+pub(crate) fn split_families(db: &Faces) -> Option<std::sync::Arc<subsets::Subsets>> {+ PAGE_FONTS.lock().unwrap().as_ref().filter(|(_, made, _)| std::sync::Arc::ptr_eq(made, db)).map(|(_, _, s)| s.clone())+}diff --git a/systems/canvas/src/measure.rs b/systems/canvas/src/measure.rsnew file mode 100644index 00000000..30beba8e--- /dev/null+++ b/systems/canvas/src/measure.rs@@ -0,0 +1,80 @@+//! A canvas's measureText: each character's advance in the face the canvas would draw it with (text in draw.rs).+//! The page asks for the characters it hasn't measured yet in a font, and keeps the ones its own family has; a+//! character another family stood in for is asked again, so a face the page loads later takes over.++use serde_json::{json, Value};+use usvg::fontdb::{Family, Query, Style, Weight, ID};++/// `canvas.advances`: {font: {family, weight, style}, chars} -> {adv: [em or null], own: [bool]}, one per character:+/// its advance as a fraction of the font size, and whether the font's first family has it.+pub fn advances(args: &Value) -> Result<Value, String> {+ Ok(advances_in(&crate::page_options(), args))+}++fn advances_in(opt: &usvg::Options, args: &Value) -> Value {+ let db = &opt.fontdb;+ let font = &args["font"];+ let weight = font["weight"].as_str().and_then(|w| w.parse().ok()).unwrap_or(400u16);+ let style = if font["style"].as_str() == Some("italic") { Style::Italic } else { Style::Normal };+ let names: Vec<String> = font["family"].as_str().unwrap_or("sans-serif").split(',').map(|s| s.trim().trim_matches(['\'', '"']).to_string()).filter(|s| !s.is_empty()).collect();+ let face_of = |name: &str| -> Option<ID> {+ let family = match name.to_lowercase().as_str() {+ "serif" => Family::Serif,+ "sans-serif" | "system-ui" => Family::SansSerif,+ "monospace" => Family::Monospace,+ "cursive" => Family::Cursive,+ "fantasy" => Family::Fantasy,+ _ => Family::Name(name),+ };+ db.query(&Query { families: &[family], weight: Weight(weight), style, ..Default::default() })+ };+ // the faces in the order a character is looked for: a split first family's subsets (subsets.rs), the families as+ // listed, then the default+ let mut faces: Vec<(ID, bool)> = Vec::new();+ if let (Some(split), Some(first)) = (crate::split_families(db), names.first()) {+ faces.extend(split.get(&first.to_lowercase()).into_iter().flatten().map(|(_, id)| (*id, true)));+ }+ faces.extend(names.iter().enumerate().filter_map(|(k, n)| face_of(n).map(|id| (id, k == 0))));+ faces.extend(face_of("sans-serif").map(|id| (id, false)));+ let chars: Vec<char> = args["chars"].as_str().unwrap_or("").chars().collect();+ let mut out: Vec<Option<(f64, bool)>> = vec![None; chars.len()];+ for (id, own) in faces {+ if out.iter().all(Option::is_some) {+ break;+ }+ db.with_face_data(id, |data, index| {+ let Ok(f) = ttf_parser::Face::parse(data, index) else { return };+ let em = f64::from(f.units_per_em());+ for (c, slot) in chars.iter().zip(out.iter_mut()).filter(|(_, s)| s.is_none()) {+ if let Some(a) = f.glyph_index(*c).and_then(|g| f.glyph_hor_advance(g)) {+ *slot = Some((f64::from(a) / em, own));+ }+ }+ });+ }+ json!({+ "adv": out.iter().map(|s| s.map(|(a, _)| a)).collect::<Vec<_>>(),+ "own": out.iter().map(|s| s.is_some_and(|(_, o)| o)).collect::<Vec<_>>(),+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn advances_are_the_faces_and_say_whose() {+ let mut db = usvg::fontdb::Database::new();+ db.load_font_data(std::fs::read("/System/Library/Fonts/Supplemental/Arial.ttf").unwrap());+ db.set_sans_serif_family("Arial");+ let opt = usvg::Options { fontdb: std::sync::Arc::new(db), ..Default::default() };+ let r = advances_in(&opt, &json!({"font": {"family": "Arial", "weight": "400", "style": "normal"}, "chars": "im"}));+ let (i, m) = (r["adv"][0].as_f64().unwrap(), r["adv"][1].as_f64().unwrap());+ assert!(i < 0.3 && m > 0.8, "{r}");+ assert_eq!(r["own"], json!([true, true]));+ // a family the page doesn't have: the default stands in, and says so+ let r = advances_in(&opt, &json!({"font": {"family": "Nope, sans-serif", "weight": "400", "style": "normal"}, "chars": "i"}));+ assert_eq!(r["own"], json!([false]));+ assert!((r["adv"][0].as_f64().unwrap() - i).abs() < 1e-9);+ }+}diff --git a/systems/canvas/src/subsets.rs b/systems/canvas/src/subsets.rsnew file mode 100644index 00000000..7315bc47--- /dev/null+++ b/systems/canvas/src/subsets.rs@@ -0,0 +1,108 @@+//! Canvas text in a family split across files by unicode-range, as the web ships big fonts (Excalidraw's Excalifont+//! is seven subsets, all of Latin in one). fontdb ignores unicode-range: a query for the family gives one of its faces,+//! and glyphs that face lacks fall back to other families, so whole lines of a board drew in Helvetica. Each face of+//! such a family is also kept under an alias family of its own, and a text op names, run by run, the subset that has+//! the glyphs, as Chrome picks a face by unicode-range.++use std::collections::HashMap;++use usvg::fontdb::{Database, ID, Language, Source};++/// A split family's faces under their alias families, by the family's name in lower case.+pub type Subsets = HashMap<String, Vec<(String, ID)>>;++/// Adds an alias face for each face of a family that has several of the same style, weight and stretch (its+/// unicode-range subsets), and says which they are.+pub(crate) fn alias(db: &mut Database) -> Subsets {+ let mut groups: HashMap<String, Vec<ID>> = HashMap::new();+ for f in db.faces() {+ // only faces a page added from bytes (its @font-face faces): a system font file is never a subset+ if !matches!(f.source, Source::Binary(_)) {+ continue;+ }+ let Some((name, _)) = f.families.first() else { continue };+ groups.entry(format!("{}\u{0}{:?}{:?}{:?}", name.to_lowercase(), f.style, f.weight, f.stretch)).or_default().push(f.id);+ }+ let mut out = Subsets::new();+ for (key, ids) in groups {+ if ids.len() < 2 {+ continue;+ }+ let family = key.split('\u{0}').next().unwrap_or_default().to_string();+ // the files with the most glyphs first: a page's own subsets before the cut-down copy of the same family an+ // SVG image embeds (Excalidraw's exportToSvg keeps only the glyphs its picture uses, and blitz-dom adds those+ // faces too), which runs would otherwise pick for every glyph it happens to have+ let mut ids = ids;+ let glyphs = |id: ID| db.with_face_data(id, |data, index| ttf_parser::Face::parse(data, index).map(|f| f.number_of_glyphs()).unwrap_or(0)).unwrap_or(0);+ ids.sort_by_key(|id| std::cmp::Reverse(glyphs(*id)));+ for (k, id) in ids.into_iter().enumerate() {+ let Some(mut info) = db.face(id).cloned() else { continue };+ let name = format!("{family} raea-subset-{k}");+ info.families = vec![(name.clone(), Language::English_UnitedStates)];+ info.post_script_name = format!("{}-raea-subset-{k}", info.post_script_name);+ out.entry(family.clone()).or_default().push((name, db.push_face_info(info)));+ }+ }+ out+}++/// The text split into runs by which subset of its first family has each character, each run with that subset's+/// alias family (None: no subset has it, so the family list as given decides). None when the family isn't split.+pub(crate) fn runs(db: &Database, subsets: &Subsets, families: &str, text: &str) -> Option<Vec<(Option<String>, String)>> {+ let first = families.split(',').next()?.trim().trim_matches(['\'', '"']).to_lowercase();+ let faces = subsets.get(&first)?;+ let chars: Vec<char> = text.chars().collect();+ // which characters each subset has, read from its cmap once for the op+ let cover: Vec<Vec<bool>> = faces+ .iter()+ .map(|(_, id)| {+ db.with_face_data(*id, |data, index| {+ let f = ttf_parser::Face::parse(data, index).ok()?;+ Some(chars.iter().map(|c| f.glyph_index(*c).is_some()).collect())+ })+ .flatten()+ .unwrap_or_else(|| vec![false; chars.len()])+ })+ .collect();+ let mut out: Vec<(Option<String>, String)> = Vec::new();+ for (i, c) in chars.iter().enumerate() {+ // a space goes with the run it's in, whichever subset has it+ let pick = if c.is_whitespace() && !out.is_empty() {+ out.last().unwrap().0.clone()+ } else {+ cover.iter().position(|has| has[i]).map(|k| faces[k].0.clone())+ };+ match out.last_mut() {+ Some((f, s)) if *f == pick => s.push(*c),+ _ => out.push((pick, c.to_string())),+ }+ }+ Some(out)+}++#[cfg(test)]+mod tests {+ use super::*;++ const FONT: &str = "/System/Library/Fonts/Supplemental/Arial.ttf";+ const OTHER: &str = "/System/Library/Fonts/Supplemental/Courier New.ttf";++ #[test]+ fn a_family_in_several_files_gets_an_alias_per_file_and_runs_name_the_one_with_the_glyphs() {+ let (Ok(bytes), Ok(other)) = (std::fs::read(FONT), std::fs::read(OTHER)) else { return };+ let mut db = Database::new();+ // two files of one family, as a page's unicode-range faces are, and a family in one file+ db.load_font_data(bytes.clone());+ db.load_font_data(bytes);+ db.load_font_data(other);+ let s = alias(&mut db);+ let faces = &s["arial"];+ assert_eq!(faces.len(), 2);+ assert_eq!(s.len(), 1);+ let r = runs(&db, &s, "Arial, sans-serif", "ab \u{4e2d}c").unwrap();+ let first = Some(faces[0].0.clone());+ // Arial has no CJK: that character is a run of its own that the family list decides+ assert_eq!(r, vec![(first.clone(), "ab ".to_string()), (None, "\u{4e2d}".to_string()), (first, "c".to_string())]);+ assert!(runs(&db, &s, "'No Such Family', sans-serif", "abc").is_none());+ }+}diff --git a/systems/material/src/maps.rs b/systems/material/src/maps.rsindex 72b3698d..116ea1a4 100644--- a/systems/material/src/maps.rs+++ b/systems/material/src/maps.rs@@ -224,6 +224,8 @@ pub fn material(world: &mut World, t: &Tup, inserted: &[Tup], dir: &Path) -> Res"add" => AlphaMode::Add,"multiply" => AlphaMode::Multiply,"premultiplied" => AlphaMode::Premultiplied,+ // soft cut-outs from the alpha over MSAA's samples (hair cards, foliage); without MSAA Bevy draws it solid+ "coverage" => AlphaMode::AlphaToCoverage,_ => AlphaMode::Opaque,};}diff --git a/systems/material/src/surface.rs b/systems/material/src/surface.rsindex bc8cfd8e..47fde899 100644--- a/systems/material/src/surface.rs+++ b/systems/material/src/surface.rs@@ -66,6 +66,10 @@ fn over(base: &StandardMaterial, s: &Surface) -> StandardMaterial {if has("normal_map") {m.normal_map_texture = s.made.normal_map_texture.clone();}+ // how its alpha draws (alphaMode): a glTF's MASK hair made "coverage", or a part made "blend"+ if has("alpha") {+ m.alpha_mode = s.made.alpha_mode;+ }if has("rough") {m.perceptual_roughness = s.made.perceptual_roughness;}diff --git a/systems/meshseq/src/cloth.rs b/systems/meshseq/src/cloth.rsnew file mode 100644index 00000000..0f223f1c--- /dev/null+++ b/systems/meshseq/src/cloth.rs@@ -0,0 +1,98 @@+//! A Character part's cloth (docs/cloth.md K2): a `model` row's `cloth` (a `.rseq` of the part's own vertices in its+//! bind pose, in the glTF's vertex order, baked by raea/body tools/cloth.ts `--bind`) and its `cloth_frame`, keyed per+//! frame. That frame's positions and normals go on the part's mesh (a copy, so another body wearing the same part is+//! untouched) and the skin poses them as it poses the part's own: its materials, its alpha cut-out, its morphs and its+//! bones stay as they are. The frame drawn is a function of the row at the frame, so `render --at` draws what a+//! straight render draws there.++use std::path::Path;+use std::sync::Arc;++use bevy::mesh::VertexAttributeValues;+use bevy::prelude::*;+use raea_core_program::eval::Tup;+use raea_core_program::ir::V;+use raea_sys_frame::*;+++#[derive(Component)]+pub struct ClothPlay {+ seq: Arc<raea_io_assets::meshseq::Seq>,+ /// the part's skinned meshes (entity, its copy), in the order the bake lays their vertices; empty until spawned+ parts: Vec<(Entity, Handle<Mesh>)>,+ last: Option<usize>,+}++/// A model row's cloth, opened beside its model (spawn.rs), when it has one.+pub fn spawn(world: &mut World, e: Entity, t: &Tup, inserted: &[Tup], dir: &Path) -> Result<(), String> {+ let Some(V::S(src)) = t.vals.get("cloth") else { return Ok(()) };+ let path = resolve_src(inserted, src, dir)?;+ let seq = Arc::new(raea_io_assets::meshseq::Seq::open(&path).map_err(|e| format!("model {}: cloth: {e}", t.id))?);+ world.entity_mut(e).insert(ClothPlay { seq, parts: Vec::new(), last: None });+ Ok(())+}++fn count(m: &Mesh) -> usize {+ match m.attribute(Mesh::ATTRIBUTE_POSITION) {+ Some(VertexAttributeValues::Float32x3(v)) => v.len(),+ _ => 0,+ }+}++/// Each cloth's frame for this frame's row, on its part's meshes.+#[allow(clippy::too_many_arguments)]+pub(crate) fn sync_cloth(+ mut commands: Commands,+ frame: Res<FrameRows>,+ mut meshes: ResMut<Assets<Mesh>>,+ mut q: Query<(Entity, &mut ClothPlay)>,+ kids: Query<&Children>,+ mut mesh3d: Query<&mut Mesh3d, With<bevy::mesh::skinning::SkinnedMesh>>,+ mut err: ResMut<Error>,+) {+ for (e, mut cp) in &mut q {+ let Some(v) = frame.vals(e) else { continue };+ let k = num(&v, "cloth_frame", 0.0).round().max(0.0) as usize;+ if cp.parts.is_empty() {+ // the model's scene spawned: its skinned meshes copied, each drawn from its copy from now on+ for x in descendants(e, &kids) {+ let Ok(mut m3) = mesh3d.get_mut(x) else { continue };+ let Some(src) = meshes.get(&m3.0).cloned() else { continue };+ let copy = meshes.add(src);+ m3.0 = copy.clone();+ commands.entity(x).insert(bevy::camera::visibility::NoFrustumCulling);+ cp.parts.push((x, copy));+ }+ if cp.parts.is_empty() {+ continue;+ }+ }+ if cp.last == Some(k) {+ continue;+ }+ let fr = match cp.seq.read(k.min(cp.seq.frames().saturating_sub(1))) {+ Ok(fr) => fr,+ Err(x) => {+ err.0 = Some(format!("cloth: {x}"));+ continue;+ }+ };+ let total: usize = cp.parts.iter().filter_map(|(_, h)| meshes.get(h)).map(count).sum();+ if total != fr.pos.len() {+ err.0 = Some(format!("cloth: the bake has {} vertices a frame, the part's meshes {total} (bake it from this part, with --bind)", fr.pos.len()));+ cp.last = Some(k);+ continue;+ }+ let mut at = 0;+ for (_, h) in &cp.parts {+ let Some(mut m) = meshes.get_mut(h) else { continue };+ let n = count(&m);+ m.insert_attribute(Mesh::ATTRIBUTE_POSITION, fr.pos[at..at + n].to_vec());+ if fr.nrm.len() == fr.pos.len() {+ m.insert_attribute(Mesh::ATTRIBUTE_NORMAL, fr.nrm[at..at + n].to_vec());+ }+ at += n;+ }+ cp.last = Some(k);+ }+}diff --git a/systems/meshseq/src/lib.rs b/systems/meshseq/src/lib.rsindex 6d113ca7..cabda487 100644--- a/systems/meshseq/src/lib.rs+++ b/systems/meshseq/src/lib.rs@@ -29,8 +29,10 @@ use bevy::mesh::{Indices, VertexAttributeValues};use bevy::render::render_resource::PrimitiveTopology;use std::sync::Arc;+pub mod cloth;+pub fn install(app: &mut App) {- app.add_systems(PostUpdate, (sync_meshseqs, sync_glitches).after(bevy::transform::TransformSystems::Propagate));+ app.add_systems(PostUpdate, (sync_meshseqs, sync_glitches, cloth::sync_cloth).after(bevy::transform::TransformSystems::Propagate));}#[derive(Component)]diff --git a/systems/ml/Cargo.toml b/systems/ml/Cargo.tomlindex 0dd43817..e5ecedd7 100644--- a/systems/ml/Cargo.toml+++ b/systems/ml/Cargo.toml@@ -11,6 +11,7 @@ license = "FSL-1.1-ALv2"coreml = ["ort/coreml"][dependencies]+raea-io-home = { path = "../../io/home" }# the same ort pin and prebuilt runtime as the legacy app's voice and raea's perceptionort = { version = "=2.0.0-rc.13", features = ["half"] }half = "2"diff --git a/systems/ml/src/models.rs b/systems/ml/src/models.rsindex 2693d38f..29afe2a1 100644--- a/systems/ml/src/models.rs+++ b/systems/ml/src/models.rs@@ -26,6 +26,7 @@ pub fn ensure(spec: &Spec, progress: &mut dyn FnMut(&str, u64)) -> anyhow::Resulcontinue;}let url = format!("https://huggingface.co/{repo}/resolve/main/{path}");+ raea_io_home::offline(&format!("the {} model's {local} from {url}", spec.name)).map_err(|e| anyhow::anyhow!(e))?;fetch(&url, &dest, &mut |n| progress(local, n))?;}Ok(dir)diff --git a/systems/page-net/src/host.rs b/systems/page-net/src/host.rsnew file mode 100644index 00000000..4e0928ed--- /dev/null+++ b/systems/page-net/src/host.rs@@ -0,0 +1,36 @@+//! raea's window on the feed (docs/app.feature AP5/AP6): with RAEA_PAGE_HOST (the feed's Node host, http://127.0.0.1:PORT),+//! the page's /host/* is that host's, and so is a /media/* that isn't on disk (a render the host made after the page+//! loaded); everything else is page_fetch's.++use base64::Engine as _;++use crate::page_fetch;++/// The page's fetch of its own origin: its host's for /host/* (and a /media/* the roots don't have), else page_fetch.+/// None, as page_fetch: not the page's origin, the network's.+pub fn fetch(args: &serde_json::Value) -> Option<serde_json::Value> {+ let u = args["url"].as_str().and_then(|u| url::Url::parse(u).ok())?;+ let own = u.scheme() == "http" && u.host_str() == Some("localhost") && u.port().is_none();+ if own && u.path().starts_with("/host/") {+ if let Some(r) = to_host(args, &u) {+ return Some(r);+ }+ }+ let r = page_fetch(args)?;+ if r["status"] == 404 && u.path().starts_with("/media/") {+ return Some(to_host(args, &u).unwrap_or(r));+ }+ Some(r)+}++/// The request sent on to RAEA_PAGE_HOST (method, headers and body as the page gave them), its answer as `fetch` gives+/// one; None when there's no host. A host that doesn't answer is a 502, so the page sees the failure, not a hang.+fn to_host(args: &serde_json::Value, u: &url::Url) -> Option<serde_json::Value> {+ let host = std::env::var("RAEA_PAGE_HOST").ok().filter(|h| !h.is_empty())?;+ let mut a = args.clone();+ a["url"] = serde_json::Value::String(format!("{}{}{}", host.trim_end_matches('/'), u.path(), u.query().map(|q| format!("?{q}")).unwrap_or_default()));+ Some(raea_io_net::http::fetch(&a).unwrap_or_else(|e| {+ let body = base64::engine::general_purpose::STANDARD.encode(e.as_bytes());+ serde_json::json!({ "status": 502, "statusText": "Bad Gateway", "url": args["url"], "redirected": false, "headers": [], "body": body })+ }))+}diff --git a/systems/page-net/src/lib.rs b/systems/page-net/src/lib.rsindex ddad1bc8..718f8453 100644--- a/systems/page-net/src/lib.rs+++ b/systems/page-net/src/lib.rs@@ -5,6 +5,9 @@use blitz_traits::net::{Bytes, NetHandler, NetProvider, Request};+mod host;+pub use host::fetch;+/// Files and data URLs; a path that isn't on disk is looked for under each of `roots` in turn (a server's root: WPT's/// `/css/...`).#[derive(Default)]@@ -28,6 +31,12 @@ impl NetProvider for FileNet {})}),"data" => raea_io_net::data_url(url.as_str()).map(|(_, b)| b),+ // the page's own origin (http://localhost/, as page_fetch has it): the file under the roots, confined, so an+ // @font-face, image or stylesheet the app names by its URL loads as in Chrome (Excalidraw's fonts did not)+ "http" if url.host_str() == Some("localhost") && url.port().is_none() && !self.roots.is_empty() => {+ let path = url::Url::parse(&format!("file://{}", url.path())).ok().and_then(|u| u.to_file_path().ok());+ path.and_then(|p| FrameNet { roots: self.roots.clone() }.confined(&p)).filter(|p| p.is_file()).and_then(|p| std::fs::read(p).ok())+ }"http" | "https" => match raea_io_net::cache::read(url.as_str()) {Ok(b) => Some(b),Err(e) => {@@ -38,7 +47,7 @@ impl NetProvider for FileNet {_ => None,};// a load that fails still answers (empty), so the document doesn't wait for it- if bytes.is_none() && !matches!(url.scheme(), "http" | "https") {+ if bytes.is_none() && (!matches!(url.scheme(), "http" | "https") || url.host_str() == Some("localhost")) {bevy::log::warn!("raea-page: {url} isn't a file, a data URL or a URL that reads");}handler.bytes(url.to_string(), Bytes::from(bytes.unwrap_or_default()));@@ -121,7 +130,14 @@ pub fn page_fetch(args: &serde_json::Value) -> Option<serde_json::Value> {}// its path decoded, as a file URL'slet path = url::Url::parse(&format!("file://{}", u.path())).ok()?.to_file_path().ok()?;- let found = if matches!(args["method"].as_str(), None | Some("GET" | "HEAD")) { FrameNet { roots }.confined(&path).filter(|p| p.is_file()) } else { None };+ // /media/x from the root's media/, then its assets/ (Bevy's assets folder: docs/sdk.feature S5a), confined either way+ let assets = path.strip_prefix("/media").ok().map(|rest| std::path::Path::new("/assets").join(rest));+ let net = FrameNet { roots };+ let found = if matches!(args["method"].as_str(), None | Some("GET" | "HEAD")) {+ net.confined(&path).filter(|p| p.is_file()).or_else(|| assets.and_then(|a| net.confined(&a)).filter(|p| p.is_file()))+ } else {+ None+ };Some(match found.and_then(|p| std::fs::read(&p).ok().map(|b| (p, b))) {Some((p, bytes)) => serde_json::json!({"status": 200, "statusText": "OK", "url": url, "redirected": false,diff --git a/systems/page-net/tests/own_origin.rs b/systems/page-net/tests/own_origin.rsnew file mode 100644index 00000000..58f79e3b--- /dev/null+++ b/systems/page-net/tests/own_origin.rs@@ -0,0 +1,36 @@+//! What Blitz loads from the page's own origin (an @font-face url, an image, a stylesheet named http://localhost/...)+//! is the file under the page's roots, as page_fetch answers the page's fetch; nothing outside a root.++use blitz_traits::net::{Bytes, NetHandler, NetProvider, Request};+use raea_sys_page_net::FileNet;+use std::sync::{Arc, Mutex};++struct Got(Arc<Mutex<Option<Bytes>>>);+impl NetHandler for Got {+ fn bytes(self: Box<Self>, _url: String, bytes: Bytes) {+ *self.0.lock().unwrap() = Some(bytes);+ }+}++fn load(net: &FileNet, url: &str) -> Vec<u8> {+ let got = Arc::new(Mutex::new(None));+ net.fetch(0, Request::get(url::Url::parse(url).unwrap()), Box::new(Got(got.clone())));+ got.lock().unwrap().take().expect("answered at once").to_vec()+}++#[test]+fn own_origin_reads_the_roots() {+ let base = std::env::temp_dir().join(format!("raea-own-origin-{}", std::process::id()));+ let root = base.join("public");+ std::fs::create_dir_all(root.join("fonts")).unwrap();+ std::fs::write(root.join("fonts/face.woff2"), "face").unwrap();+ std::fs::write(base.join("secret.txt"), "secret").unwrap();+ let net = FileNet { roots: vec![root] };++ assert_eq!(load(&net, "http://localhost/fonts/face.woff2"), b"face");+ // missing, or outside the root: empty, never a network request+ assert!(load(&net, "http://localhost/fonts/none.woff2").is_empty());+ assert!(load(&net, "http://localhost/../secret.txt").is_empty());++ std::fs::remove_dir_all(&base).unwrap();+}diff --git a/systems/page-net/tests/page_fetch.rs b/systems/page-net/tests/page_fetch.rsindex d2855b5a..e821b106 100644--- a/systems/page-net/tests/page_fetch.rs+++ b/systems/page-net/tests/page_fetch.rs@@ -33,6 +33,11 @@ fn the_page_fetches_only_inside_the_root() {assert_eq!(status(&format!("http://localhost{}", base.join("secret.txt").display())), Some(404));assert_eq!(status("http://localhost/link.txt"), Some(404));assert_eq!(status("http://localhost/media/none.wav"), Some(404));+ // /media/ falls back to the root's assets/ (S5a), confined the same way+ std::fs::create_dir_all(root.join("assets")).unwrap();+ std::fs::write(root.join("assets/kept.wav"), "RIFF").unwrap();+ assert_eq!(status("http://localhost/media/kept.wav"), Some(200));+ assert_eq!(status("http://localhost/media/..%2f..%2fsecret.txt"), Some(404));assert_eq!(page_fetch(&json!({ "url": "http://localhost/media/in.wav", "method": "POST" })).unwrap()["status"], 404);// other origins go to the networkassert_eq!(status("http://localhost:8080/media/in.wav"), None);diff --git a/systems/page-net/tests/page_host.rs b/systems/page-net/tests/page_host.rsnew file mode 100644index 00000000..bb732821--- /dev/null+++ b/systems/page-net/tests/page_host.rs@@ -0,0 +1,59 @@+//! raea's window on the feed (docs/app.feature AP5/AP6): with RAEA_PAGE_HOST set, the page's /host/* goes to that host+//! with its method, path and query, and so does a /media/* that isn't on disk; a file under the root is still the root's,+//! and a host that doesn't answer is a 502, not a hang.++use std::io::{Read, Write};+use std::net::TcpListener;++use raea_sys_page_net::fetch as page_fetch;+use serde_json::json;++/// A host that answers each request with its own request line as the body.+fn host() -> String {+ let l = TcpListener::bind("127.0.0.1:0").unwrap();+ let at = format!("http://{}", l.local_addr().unwrap());+ std::thread::spawn(move || {+ for s in l.incoming() {+ let mut s = s.unwrap();+ let mut buf = [0u8; 4096];+ let n = s.read(&mut buf).unwrap();+ let line = String::from_utf8_lossy(&buf[..n]).lines().next().unwrap_or("").to_string();+ let _ = write!(s, "HTTP/1.1 200 OK\r\ncontent-type: text/plain\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{line}", line.len());+ }+ });+ at+}++fn body(v: &serde_json::Value) -> String {+ use base64::Engine as _;+ String::from_utf8(base64::engine::general_purpose::STANDARD.decode(v["body"].as_str().unwrap()).unwrap()).unwrap()+}++#[test]+fn the_page_reaches_its_host() {+ let root = std::env::temp_dir().join(format!("raea-page-host-{}", std::process::id()));+ std::fs::create_dir_all(root.join("media")).unwrap();+ std::fs::write(root.join("media/on-disk.wav"), "RIFF").unwrap();+ unsafe { std::env::set_var("RAEA_PAGE_ROOT", &root) };+ let fetch = |url: &str, method: &str| page_fetch(&json!({ "url": url, "method": method })).unwrap();++ // no host: /host/* is a missing file, as before+ unsafe { std::env::remove_var("RAEA_PAGE_HOST") };+ assert_eq!(fetch("http://localhost/host/acp/events?after=3", "GET")["status"], 404);++ unsafe { std::env::set_var("RAEA_PAGE_HOST", host()) };+ let r = fetch("http://localhost/host/acp/events?after=3", "GET");+ assert_eq!(r["status"], 200);+ assert_eq!(body(&r), "GET /host/acp/events?after=3 HTTP/1.1");+ assert_eq!(body(&fetch("http://localhost/host/acp/act", "POST")), "POST /host/acp/act HTTP/1.1");+ // a render made after the page loaded is the host's; one on disk is the root's+ assert_eq!(body(&fetch("http://localhost/media/feed/new.mp4", "GET")), "GET /media/feed/new.mp4 HTTP/1.1");+ assert_eq!(body(&fetch("http://localhost/media/on-disk.wav", "GET")), "RIFF");++ // a host that's gone+ let gone = TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap();+ unsafe { std::env::set_var("RAEA_PAGE_HOST", format!("http://{gone}")) };+ assert_eq!(fetch("http://localhost/host/acp/act", "POST")["status"], 502);++ std::fs::remove_dir_all(&root).unwrap();+}diff --git a/systems/page/src/lib.rs b/systems/page/src/lib.rsindex 7bc3dad7..c22d831e 100644--- a/systems/page/src/lib.rs+++ b/systems/page/src/lib.rs@@ -145,10 +145,11 @@ pub fn resolve(mut docs: NonSendMut<Docs>, pages: Query<(Entity, &Page)>, time:for (e, page) in &pages {let Some(doc) = docs.0.get_mut(&e) else { continue };let at = clock.0.unwrap_or_else(|| time.elapsed_secs_f64());- // a page resized: its document's viewport follows (a window's page: the host sets the size)- if doc.viewport().window_size != (page.size.x, page.size.y) {+ // a page resized or rescaled (the iPad sets its scale late): its viewport follows, or text lays out off its box+ if doc.viewport().window_size != (page.size.x, page.size.y) || doc.viewport().hidpi_scale != page.scale {let mut v = doc.viewport().clone();v.window_size = (page.size.x, page.size.y);+ v.hidpi_scale = page.scale;doc.set_viewport(v);}let t0 = std::time::Instant::now();diff --git a/systems/page/src/ops.rs b/systems/page/src/ops.rsindex 03b39662..3a47d599 100644--- a/systems/page/src/ops.rs+++ b/systems/page/src/ops.rs@@ -230,13 +230,11 @@ pub fn apply(doc: &mut BaseDocument, nodes: &mut Nodes, ops: Vec<Op>) {}}let svg = in_svg(kind);+ // a textarea's value is its text too: Blitz makes its editor from its text (construct.rs)+ let area = (kind == "editableText" && m.element_name(n).is_some_and(|q| &*q.local == "textarea")).then(|| set.as_ref()?.get("value")?.as_str().map(str::to_string)).flatten();let kept = nodes.props.entry(id).or_default();- for key in unset.iter().flatten() {- kept.remove(key);- }- for (key, value) in set.iter().flatten() {- kept.insert(key.clone(), value.clone());- }+ for key in unset.iter().flatten() { kept.remove(key); }+ kept.extend(set.iter().flatten().map(|(k, v)| (k.clone(), v.clone())));if kind == "canvas" && set.iter().flatten().any(|(k, _)| matches!(k.as_str(), "__canvas2d" | "width" | "height")) {canvases.push(id);}@@ -255,6 +253,7 @@ pub fn apply(doc: &mut BaseDocument, nodes: &mut Nodes, ops: Vec<Op>) {None => m.clear_attribute(n, qual(&attr)),}}+ if let Some(t) = area.map(|v| m.create_text_node(&v)) { m.remove_and_drop_all_children(n); m.append_children(n, &[t]); }}// events go through the bridge (B3, H3: host.rs), not the documentOp::Listen { id, events } => {diff --git a/systems/perceive/Cargo.toml b/systems/perceive/Cargo.tomlindex bf9304af..24a22ee3 100644--- a/systems/perceive/Cargo.toml+++ b/systems/perceive/Cargo.toml@@ -17,6 +17,7 @@ face-portable = ["dep:rten", "dep:rten-tensor"]vision-portable = ["face-portable", "ocr-portable"][dependencies]+raea-io-home = { path = "../../io/home" }raea-sys-layout = { path = "../layout" }raea-sys-vision = { path = "../vision" }ocrs = { version = "0.13.1", optional = true }diff --git a/systems/perceive/src/face_portable.rs b/systems/perceive/src/face_portable.rsindex cf3dbe94..4b079de7 100644--- a/systems/perceive/src/face_portable.rs+++ b/systems/perceive/src/face_portable.rs@@ -19,6 +19,7 @@ fn model() -> Result<PathBuf, String> {if !p.exists() {std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;let tmp = p.with_extension("part");+ raea_io_home::offline("a text or face model download")?;let ok = std::process::Command::new("curl").args(["-fsSL", "-o"]).arg(&tmp).arg(MODEL.1).status().map(|s| s.success()).unwrap_or(false);if !ok {return Err(format!("couldn't fetch {}", MODEL.1));diff --git a/systems/perceive/src/ocr_portable.rs b/systems/perceive/src/ocr_portable.rsindex c58489b4..29cb6db8 100644--- a/systems/perceive/src/ocr_portable.rs+++ b/systems/perceive/src/ocr_portable.rs@@ -15,6 +15,7 @@ fn model(name: &str, url: &str) -> Result<PathBuf, String> {if !p.exists() {std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;let tmp = p.with_extension("part");+ raea_io_home::offline("a text or face model download")?;let ok = std::process::Command::new("curl").args(["-fsSL", "-o"]).arg(&tmp).arg(url).status().map(|s| s.success()).unwrap_or(false);if !ok {return Err(format!("couldn't fetch {url}"));diff --git a/systems/perceive/src/portable.rs b/systems/perceive/src/portable.rsindex 306ff356..da2c82da 100644--- a/systems/perceive/src/portable.rs+++ b/systems/perceive/src/portable.rs@@ -29,6 +29,7 @@ pub fn fetch((dir, name, url): (&str, &str, &str)) -> Result<PathBuf, String> {let p = dir.join(name);if !p.exists() {std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;+ raea_io_home::offline(&format!("the {name} model from {url}"))?;let tmp = p.with_extension("part");let ok = std::process::Command::new("curl").args(["-fsSL", "-o"]).arg(&tmp).arg(url).status().map(|s| s.success()).unwrap_or(false);if !ok {diff --git a/tools/release.sh b/tools/release.shindex e5ca516f..24da3458 100755--- a/tools/release.sh+++ b/tools/release.sh@@ -39,6 +39,27 @@ esacname=raea-$version-$platformstage=$(mktemp -d)/raeamkdir -p "$stage/bin" "$stage/share/raea" "$out"+# the skills gate (docs/skills.feature SK9): the committed tree at REF against this release's raea, so a stale reference,+# a retired word, a flag no verb takes or a dead link refuses the release+gate=$(mktemp -d)+git archive "$ref" | tar -x -C "$gate"+git -C "$gate" init -q && git -C "$gate" add -A && git -C "$gate" -c user.name=release -c [email protected] commit -qm "$ref" --no-verify+raea_bin=$bin/raea; [ -f "$raea_bin.exe" ] && raea_bin=$raea_bin.exe+if ! (cd "$gate" && SKILLS_STRICT=1 SKILLS_CHANGED= RAEA_BIN="$raea_bin" RAEA_APP="$root/apps/app" RAEA_APP_REV="$(git -C "$root" rev-parse "$ref:apps/app")" bash tools/skills.sh check); then+ echo "release.sh: tools/skills.sh check failed on $ref with $raea_bin; fix the skills (tools/skills.sh gen) before releasing" >&2+ rm -rf "$gate"+ exit 1+fi+rm -rf "$gate"+# the skills' changes since the last release, for its notes (SK9): RAEA_SINCE names where that was (a ref, or a date+# like 2026-10-31), else the last v* tag; written beside the archive as raea-VERSION-skills.md+since=${RAEA_SINCE:-$(git describe --tags --abbrev=0 --match 'v*' "$ref" 2>/dev/null || true)}+{+ echo "## The agent skills and guides, since ${since:-the start}"+ echo+ if [ -z "$since" ]; then range=("$ref"); elif git rev-parse -q --verify "$since^{commit}" >/dev/null; then range=("$since..$ref"); else range=(--since="$since" "$ref"); fi+ git log --no-merges --format='- %s' "${range[@]}" -- sdk/skills sdk/guides ':!sdk/skills/raea-work' | cut -c1-200+} > "$out/raea-$version-skills.md"case $platform inlinux-x86_64)cp "$bin/raea" "$bin/libraea_bundle.so" "$stage/bin/"@@ -69,7 +90,7 @@ done# (@raea/ui, the page's DOM every render goes through, isn't an @raea/<name> path, so it's named here)git archive "$ref" sdk/tsconfig.base.json sdk/ui/src sdk/ui/package.json sdk/ui/bevy sdk/raea/src sdk/raea/library sdk/raea/package.json sdk/react/js/src sdk/react/js/lite sdk/react/js/shims sdk/react/js/package.json sdk/react/js/tsconfig.json sdk/shell/src \"${pkgs[@]}" \- tools/tokensynth tools/sao tools/goo tools/splat tools/matchmove sdk/guides/craft docs/sdk-coverage.md engine/cli/template/theme.css ':(glob)engine/cli/src/*.ts' \+ tools/tokensynth tools/sao tools/goo tools/splat tools/matchmove tools/ensure.sh sdk/guides/craft docs/sdk-coverage.md engine/cli/template/theme.css ':(glob)engine/cli/src/*.ts' \| tar -x -C "$stage/share/raea"# a folder copied as it is here (links kept, as rsync -a; tar, since Git's bash on Windows has no rsync)copy() { mkdir -p "$2" && tar -C "$(dirname "$1")" --exclude .cache -cf - "$(basename "$1")" | tar -C "$2" -xf -; }@@ -91,6 +112,11 @@ cp -RL "$skills/sdk/skills" "$stage/share/raea/skills"copy sdk/react/js/node_modules "$stage/share/raea/sdk/react/js"rm -rf "$stage/share/raea/tools/tokensynth/__pycache__" "$skills"printf '%s\n' "$version" > "$stage/share/raea/VERSION"+# each skill's front matter names the raea it shipped with, so an agent holding an older or newer copy than its raea+# can tell, and reads `raea skill` instead (docs/skills.feature SK6; `raea skills install` stamps the same way)+for md in "$stage"/share/raea/skills/*/SKILL.md; do+ perl -0pi -e 's/\A---\n(.*?)\n---\n/"---\n" . join("\n", grep { !\/^version:\/ } split(\/\n\/, $1)) . "\nversion: '"$version"'\n---\n"/se' "$md"+doneif [ $platform = windows-x86_64 ]; thenarchive=$name.ziprm -f "$out/$archive"diff --git a/vendor/anyrender_svg/src/render.rs b/vendor/anyrender_svg/src/render.rsindex 631aa301..c5154f94 100644--- a/vendor/anyrender_svg/src/render.rs+++ b/vendor/anyrender_svg/src/render.rs@@ -170,12 +170,11 @@ fn render_children<S: PaintScene, F: FnMut(&mut S, &usvg::Node)>(| usvg::ImageKind::WEBP(_) => {#[cfg(feature = "image")]{- let Ok(decoded_image) = util::decode_raw_raster_image(img.kind())- else {+ // raea: decoded once per image, not on every paint (a feed card's posters kept a core busy)+ let Some(image) = util::cached_raster_image(img.kind(), img.rendering_mode()) else {error_handler(scene, node);continue;};- let image = util::into_image(decoded_image, img.rendering_mode());let image_ts = global_transform * util::to_affine(&img.abs_transform());scene.draw_image(image.as_ref(), image_ts);}diff --git a/vendor/anyrender_svg/src/util.rs b/vendor/anyrender_svg/src/util.rsindex a3501301..7d477fad 100644--- a/vendor/anyrender_svg/src/util.rs+++ b/vendor/anyrender_svg/src/util.rs@@ -255,6 +255,45 @@ pub(crate) fn default_error_handler<S: PaintScene>(scene: &mut S, node: &usvg::N);}+/// raea: an SVG's raster image decoded and made a brush once, found again by its bytes (Blitz parses an inline <svg>+/// again on each relayout, so the same image comes in a new tree each frame), so a page painting it every frame+/// neither decodes it again nor hands Vello a new image (a new blob is a new upload) each time. Bounded by the decoded+/// bytes it holds, the least recently used dropped first.+#[cfg(feature = "image")]+pub(crate) fn cached_raster_image(kind: &usvg::ImageKind, mode: usvg::ImageRendering) -> Option<ImageBrush> {+ use std::hash::{Hash, Hasher};+ use std::sync::Mutex;+ type Key = (usize, u64, u8);+ static CACHE: Mutex<Vec<(Key, usize, ImageBrush)>> = Mutex::new(Vec::new());+ const BUDGET: usize = 256 << 20;+ let data = match kind {+ usvg::ImageKind::JPEG(d) | usvg::ImageKind::PNG(d) | usvg::ImageKind::GIF(d) | usvg::ImageKind::WEBP(d) => d,+ usvg::ImageKind::SVG(_) => return None,+ };+ let mut h = std::collections::hash_map::DefaultHasher::new();+ data.as_slice().hash(&mut h);+ let key: Key = (data.len(), h.finish(), mode as u8);+ {+ let mut cache = CACHE.lock().unwrap();+ if let Some(i) = cache.iter().position(|(k, ..)| *k == key) {+ let hit = cache.remove(i);+ let brush = hit.2.clone();+ cache.push(hit);+ return Some(brush);+ }+ }+ let decoded = decode_raw_raster_image(kind).ok()?;+ let size = decoded.as_raw().len();+ let brush = into_image(decoded, mode);+ let mut cache = CACHE.lock().unwrap();+ cache.push((key, size, brush.clone()));+ let mut total: usize = cache.iter().map(|e| e.1).sum();+ while total > BUDGET && cache.len() > 1 {+ total -= cache.remove(0).1;+ }+ Some(brush)+}+#[cfg(feature = "image")]pub(crate) fn decode_raw_raster_image(img: &usvg::ImageKind,diff --git a/vendor/blitz-dom/src/document.rs b/vendor/blitz-dom/src/document.rsindex 78cfe6e9..99c2a177 100644--- a/vendor/blitz-dom/src/document.rs+++ b/vendor/blitz-dom/src/document.rs@@ -328,6 +328,9 @@ pub struct BaseDocument {/// Text selection state (for non-input text)pub(crate) text_selection: TextSelection,+ /// raea: a caret outside inputs: the inline root and byte offset it's drawn at (a focused contenteditable's+ /// collapsed selection, which raea's page sets; blitz-paint draws it as a text input's)+ pub caret: Option<(NodeId, usize)>,// TODO: collapse animating state into a bitflags/// Whether there are active CSS animations/transitions (so we should re-render every frame)@@ -567,6 +570,7 @@ impl BaseDocument {scrollbar_activity: HashMap::new(),scroll_animation: ScrollAnimationState::None,text_selection: TextSelection::default(),+ caret: None,};// Initialise document with root Document node@@ -2124,19 +2128,29 @@ impl BaseDocument {/// raea: a field's ::placeholder stylepub fn placeholder_style(&self, node_id: NodeId) -> Option<style::servo_arc::Arc<style::properties::ComputedValues>> {+ self.lazy_pseudo_style(node_id, &style::selector_parser::PseudoElement::Placeholder)+ }++ /// raea: a range input's thumb style (::-webkit-slider-thumb, ::-moz-range-thumb)+ pub fn slider_thumb_style(&self, node_id: NodeId) -> Option<style::servo_arc::Arc<style::properties::ComputedValues>> {+ self.lazy_pseudo_style(node_id, &style::selector_parser::PseudoElement::SliderThumb)+ }++ /// raea: a list item's ::marker style+ pub fn marker_style(&self, node_id: NodeId) -> Option<style::servo_arc::Arc<style::properties::ComputedValues>> {+ self.lazy_pseudo_style(node_id, &style::selector_parser::PseudoElement::Marker)+ }++ fn lazy_pseudo_style(+ &self,+ node_id: NodeId,+ pseudo: &style::selector_parser::PseudoElement,+ ) -> Option<style::servo_arc::Arc<style::properties::ComputedValues>> {let node = self.get_node(node_id)?;let parent = node.primary_styles()?;let read_guard = self.guard.read();let guards = StylesheetGuards::same(&read_guard);- self.stylist.lazily_compute_pseudo_element_style(- &guards,- node,- &style::selector_parser::PseudoElement::Placeholder,- style::stylist::RuleInclusion::All,- &parent,- false,- None,- )+ self.stylist.lazily_compute_pseudo_element_style(&guards, node, pseudo, style::stylist::RuleInclusion::All, &parent, false, None)}pub fn clear_hover(&mut self) -> bool {diff --git a/vendor/blitz-dom/src/layout/construct.rs b/vendor/blitz-dom/src/layout/construct.rsindex 4dc0c3b9..a83433c5 100644--- a/vendor/blitz-dom/src/layout/construct.rs+++ b/vendor/blitz-dom/src/layout/construct.rs@@ -1166,6 +1166,7 @@ pub(crate) fn build_inline_layout_into(builder.push_text(close);}text_layout.text = builder.build_into(&mut text_layout.layout);+ text_layout.text_nodes = std::mem::take(&mut text_transformer.texts);return;fn build_inline_layout_recursive(@@ -1394,7 +1395,9 @@ pub(crate) fn build_inline_layout_into(let bidi = if keeps_newlines { std::mem::take(&mut text_transformer.bidi) } else { Vec::new() };let text =text_transformer.transform(&data.content, parent_text_transform, builder);+ let start = builder.text().len();builder.push_text(&bidi_newlines(text, &bidi));+ text_transformer.texts.push((node_id, start, builder.text().len()));if keeps_newlines {text_transformer.bidi = bidi;}diff --git a/vendor/blitz-dom/src/layout/list.rs b/vendor/blitz-dom/src/layout/list.rsindex 0d4dbabf..c3996972 100644--- a/vendor/blitz-dom/src/layout/list.rs+++ b/vendor/blitz-dom/src/layout/list.rs@@ -78,9 +78,15 @@ fn node_list_item_child(let position = match list_style_position {ListStylePosition::Inside => ListItemLayoutPosition::Inside,ListStylePosition::Outside => {- let mut parley_style = stylo_to_parley::style(child_id, &styles);-- if let Some(font_family) = font_for_bullet_style(list_style_type) {+ // raea: in the item's ::marker style, its white space kept as Chrome's UA sheet has it (white-space: pre;+ // "1. " lost its space at the line's end and sat against the item's text)+ let marker_styles = doc.marker_style(child_id);+ let mut parley_style = stylo_to_parley::style(child_id, marker_styles.as_deref().unwrap_or(&**styles));+ parley_style.white_space_collapse = parley::WhiteSpaceCollapse::Preserve;++ // raea: a disc in the item's own font, as Chrome's "• " (in the Bullet font with an 8px pad it sat 3px above+ // Chrome's); the other bullets (◦ ▪ ▾ ▸) keep the Bullet font, which every text font may not have+ if !matches!(marker, Marker::Char('•')) && let Some(font_family) = font_for_bullet_style(list_style_type) {parley_style.font_family = font_family;}@@ -94,10 +100,7 @@ fn node_list_item_child();match &marker {- Marker::Char(char) => {- let mut buf = [0u8; 4];- builder.push_text(char.encode_utf8(&mut buf));- }+ Marker::Char(char) => builder.push_text(&format!("{char} ")),Marker::String(str) => builder.push_text(str),};diff --git a/vendor/blitz-dom/src/layout/text_transform.rs b/vendor/blitz-dom/src/layout/text_transform.rsindex 20348ac5..82ed9bbb 100644--- a/vendor/blitz-dom/src/layout/text_transform.rs+++ b/vendor/blitz-dom/src/layout/text_transform.rs@@ -115,6 +115,8 @@ pub(crate) struct TextTransformer {/// raea: the bidi controls open around the text being built (construct.rs), outermost first: each is closed/// before a preserved newline and opened again after it, as a paragraph ends every embedding (UAX #9 X8)pub(crate) bidi: Vec<(&'static str, &'static str)>,+ /// raea: each text node's bytes in the builder's text, as pushed (TextLayout::text_nodes)+ pub(crate) texts: Vec<(blitz_traits::node_id::NodeId, usize, usize)>,}impl TextTransformer {diff --git a/vendor/blitz-dom/src/node/text.rs b/vendor/blitz-dom/src/node/text.rsindex 865c9b5b..6467af52 100644--- a/vendor/blitz-dom/src/node/text.rs+++ b/vendor/blitz-dom/src/node/text.rs@@ -33,6 +33,10 @@ pub struct TextLayout {/// containing block (as `SPAN_*_CB` flags). The inline root claims those boxes in its place./// Set by each `RunMode::PerformLayout` run of inline layout.pub span_cb_flags: stylo_taffy::StyleFlags,+ /// raea: each text node's bytes in `text`, [start, end) as the builder had them after its white-space processing+ /// (a collapsed run's space may sit just before or after): what maps a DOM offset in it to the layout's and back+ /// (raea-runtime-dom's editing.rs: Range rects, caretPositionFromPoint, the selection's paint)+ pub text_nodes: Vec<(NodeId, usize, usize)>,}impl TextLayout {diff --git a/vendor/blitz-dom/src/util.rs b/vendor/blitz-dom/src/util.rsindex ad27ee61..dcb7135c 100644--- a/vendor/blitz-dom/src/util.rs+++ b/vendor/blitz-dom/src/util.rs@@ -176,9 +176,84 @@ pub fn svg_fonts() -> Arc<fontdb::Database> {Arc::clone(&FONT_DB.lock().unwrap())}+/// raea: an SVG image's own `@font-face` faces given as data: URLs (what Excalidraw's exportToSvg embeds), each as+/// (font-family, bytes). usvg skips `@font-face` ("not supported"), so its text fell back to the default face.+#[cfg(feature = "svg")]+fn svg_font_faces(source: &[u8]) -> Vec<(String, Vec<u8>)> {+ let Ok(text) = std::str::from_utf8(source) else { return Vec::new() };+ let mut out = Vec::new();+ let mut rest = text;+ while let Some(at) = rest.find("@font-face") {+ rest = &rest[at + 10..];+ let Some(open) = rest.find('{') else { break };+ let Some(close) = rest[open..].find('}') else { break };+ let body = &rest[open + 1..open + close];+ rest = &rest[open + close..];+ let family = body.split(';').find_map(|d| {+ let (k, v) = d.split_once(':')?;+ (k.trim().eq_ignore_ascii_case("font-family")).then(|| v.trim().trim_matches(|c| c == '"' || c == '\'').to_string())+ });+ let Some(family) = family.filter(|f| !f.is_empty()) else { continue };+ // each url(data:...;base64,...) in src: the first that decodes is the face+ let mut src = body;+ while let Some(u) = src.find("url(") {+ src = &src[u + 4..];+ let end = src.find(')').unwrap_or(src.len());+ let url = src[..end].trim().trim_matches(|c| c == '"' || c == '\'');+ src = &src[end..];+ let Some((meta, data)) = url.strip_prefix("data:").and_then(|u| u.split_once(',')) else { continue };+ if !meta.split(';').any(|p| p.trim().eq_ignore_ascii_case("base64")) {+ continue;+ }+ if let Some(bytes) = base64_decode(data) {+ out.push((family.clone(), decode_font_bytes(&bytes).into_owned()));+ break;+ }+ }+ }+ out+}++/// Base64 as a data: URL has it (either alphabet; whitespace and padding skipped). None on any other byte.+#[cfg(feature = "svg")]+fn base64_decode(s: &str) -> Option<Vec<u8>> {+ let mut out = Vec::with_capacity(s.len() * 3 / 4);+ let (mut acc, mut bits) = (0u32, 0u32);+ for c in s.bytes() {+ let v = match c {+ b'A'..=b'Z' => c - b'A',+ b'a'..=b'z' => c - b'a' + 26,+ b'0'..=b'9' => c - b'0' + 52,+ b'+' | b'-' => 62,+ b'/' | b'_' => 63,+ b'=' | b' ' | b'\n' | b'\r' | b'\t' => continue,+ _ => return None,+ } as u32;+ acc = (acc << 6) | v;+ bits += 6;+ if bits >= 8 {+ bits -= 8;+ out.push((acc >> bits) as u8);+ }+ }+ Some(out)+}+/// Parse an SVG image.#[cfg(feature = "svg")]pub(crate) fn parse_svg_image(source: &[u8]) -> Result<crate::node::SvgImageData, usvg::Error> {+ // raea: its own @font-face faces join the SVG faces first (once each), so its text is drawn in them+ {+ use std::hash::{Hash, Hasher};+ static SEEN: LazyLock<Mutex<std::collections::HashSet<u64>>> = LazyLock::new(Default::default);+ for (family, bytes) in svg_font_faces(source) {+ let mut h = std::collections::hash_map::DefaultHasher::new();+ (&family, &bytes).hash(&mut h);+ if SEEN.lock().unwrap().insert(h.finish()) {+ add_svg_font(bytes, Some(&family));+ }+ }+ }let options = usvg::Options {fontdb: Arc::clone(&FONT_DB.lock().unwrap()),..Default::default()diff --git a/vendor/blitz-paint/src/render.rs b/vendor/blitz-paint/src/render.rsindex a5612f8d..c591e58d 100644--- a/vendor/blitz-paint/src/render.rs+++ b/vendor/blitz-paint/src/render.rs@@ -20,7 +20,7 @@ use crate::text::DrawTextContext;use crate::{CustomWidgetSceneMap, SELECTION_COLOR};use anyrender::{PaintScene, Scene};use blitz_dom::node::{- ListItemLayout, ListItemLayoutPosition, Marker, NodeData, RasterImageData, TextInputData,+ ListItemLayout, ListItemLayoutPosition, NodeData, RasterImageData, TextInputData,TextNodeData,};use blitz_dom::{BaseDocument, ElementData, Node, NodeId, local_name};@@ -1641,15 +1641,12 @@ impl ElementCx<'_, '_> {);// Render text selection highlight (if any) using cached selection ranges- if let Some(&(sel_start, sel_end)) = self.context.selection_ranges.get(&self.node.id) {- crate::text::draw_text_selection(- scene,- &text_layout.layout,- transform,- sel_start,- sel_end,- );- }+ // raea: in the inline root's ::selection background, and its glyphs in the ::selection colour when that+ // isn't the text's own (as Chrome keeps the text's colours under its default highlight)+ let (sel_fill, sel_ink) = self.selection_colors();+ let selected = self.context.selection_ranges.get(&self.node.id).map(|&(sel_start, sel_end)| {+ crate::text::draw_text_selection(scene, &text_layout.layout, transform, sel_start, sel_end, sel_fill)+ });// Render textlet mut draw_text_context = self.context.draw_text_context.borrow_mut();@@ -1672,11 +1669,49 @@ impl ElementCx<'_, '_> {self.node.id,&mut draw_text_context,);+ if let (Some(path), Some(ink)) = (selected.filter(|p| !p.elements().is_empty()), sel_ink) {+ scene.push_clip_layer(Fill::NonZero, transform, &path);+ draw_text_context.color = Some(ink);+ let lines = text_layout.layout.lines().take(keep.unwrap_or(usize::MAX));+ crate::text::stroke_text(scene, lines, self.context.dom, transform, self.scale, self.node.id, &mut draw_text_context);+ draw_text_context.color = None;+ scene.pop_layer();+ }draw_text_context.ellipsis = None;draw_text_context.clamp = None;+ drop(draw_text_context);++ // raea: a contenteditable's caret (BaseDocument::caret), 1px wide in the caret colour, as a text input's+ if let Some((root, byte)) = self.context.dom.caret+ && root == self.node.id+ {+ let layout = &text_layout.layout;+ let cursor = parley::Cursor::from_byte_index(layout, byte.min(text_layout.text.len()), parley::Affinity::Downstream);+ let rect = cursor.geometry(layout, self.scale as f32);+ let color = self.style.get_inherited_text().color;+ let caret_color = match &self.style.get_inherited_ui().caret_color.0 {+ ColorOrAuto::Auto => color,+ ColorOrAuto::Color(c) => c.resolve_to_absolute(&color),+ };+ scene.fill(Fill::NonZero, transform, caret_color.as_srgb_color(), None, &convert_rect(&rect));+ }}}+ /// raea: the element's ::selection background (Blitz's default highlight while it's transparent) and its colour,+ /// None when that's the element's own colour (its text keeps its colours then, as under Chrome's default)+ fn selection_colors(&self) -> (Color, Option<Color>) {+ let data = self.node.try_stylo_element_data().and_then(|d| d.get());+ let Some(sel) = data.as_ref().and_then(|d| d.styles.pseudos.get(&style::selector_parser::PseudoElement::Selection)) else {+ return (SELECTION_COLOR, None);+ };+ let own = self.style.get_inherited_text().color;+ let ink = sel.get_inherited_text().color;+ let fill = sel.get_background().background_color.resolve_to_absolute(&ink);+ let fill = if fill.alpha == 0.0 { SELECTION_COLOR } else { fill.as_srgb_color() };+ (fill, (ink != own).then(|| ink.as_srgb_color()))+ }+fn draw_text_input_text(&self, scene: &mut impl PaintScene, pos: Point) {// Render the text in text inputsif let Some(input_data) = self.text_input {@@ -1801,20 +1836,16 @@ impl ElementCx<'_, '_> {fn draw_marker(&self, scene: &mut impl PaintScene, pos: Point) {if let Some(ListItemLayout {- marker,position: ListItemLayoutPosition::Outside(layout),+ ..}) = self.list_item{- // Right align and pad the bullet when rendering outside- let x_padding = match marker {- Marker::Char(_) => 8.0,- Marker::String(_) => 0.0,- };+ // Right align the bullet when rendering outside (raea: with no pad: a char marker carries its space, as a+ // string marker does, blitz-dom layout/list.rs)// Outside markers are placed outside the list item's border box// (`pos` is the origin of its content box)let item_layout = self.node.final_layout();let x_offset = -(layout.full_width() / layout.scale()- + x_padding+ item_layout.padding.left+ item_layout.border.left);@@ -1842,6 +1873,8 @@ impl ElementCx<'_, '_> {self.transform * Affine::translate((pos.x * self.scale, pos.y * self.scale));let mut draw_text_context = self.context.draw_text_context.borrow_mut();+ // raea: in the ::marker colour (the item's text colour when no rule sets one)+ draw_text_context.color = self.context.dom.marker_style(self.node.id).map(|m| m.get_inherited_text().color.as_srgb_color());crate::text::stroke_text(scene,layout.lines(),@@ -1851,6 +1884,7 @@ impl ElementCx<'_, '_> {self.node.id,&mut draw_text_context,);+ draw_text_context.color = None;}}@@ -1913,12 +1947,14 @@ impl ElementCx<'_, '_> {x: position.x as f64 * self.scale,y: position.y as f64 * self.scale,};+ let clips = self.hoisted_clips(scene, hoisted_child.node_id, parent_style_transform);self.render_node(scene,hoisted_child.node_id,parent_style_transform.pre_translate(pos),clip_rect,);+ (0..clips).for_each(|_| scene.pop_layer());}}@@ -1942,16 +1978,60 @@ impl ElementCx<'_, '_> {x: position.x as f64 * self.scale,y: position.y as f64 * self.scale,};+ let clips = self.hoisted_clips(scene, hoisted_child.node_id, parent_style_transform);self.render_node(scene,hoisted_child.node_id,parent_style_transform.pre_translate(pos),clip_rect,);+ (0..clips).for_each(|_| scene.pop_layer());}}}+ /// raea: a hoisted child (a z-index's, painted from its stacking-context root) under the overflow clips of the+ /// boxes between it and that root along its containing blocks, as Chrome clips it: each one's padding box, from+ /// the root, pushed as a clip layer. Returns how many were pushed. Drawn from the root alone it painted past them+ /// (Excalidraw's frame names, `z-index: 2` in its `overflow: hidden` editor, over the page around it).+ fn hoisted_clips(&self, scene: &mut impl PaintScene, child: NodeId, transform: Affine) -> usize {+ let tree = self.node.tree();+ let root = self.node.id;+ let mut pushed = 0;+ let mut current = tree[child].containing_block();+ while let Some(id) = current.filter(|id| *id != root) {+ let Some(node) = tree.get(id) else { break };+ current = node.containing_block();+ let Some(styles) = node.primary_styles() else { continue };+ let (x, y) = (styles.get_box().overflow_x, styles.get_box().overflow_y);+ let (cx, cy) = (!matches!(x, Overflow::Visible), !matches!(y, Overflow::Visible));+ if !cx && !cy {+ continue;+ }+ // its border box from the root: its place and those of the boxes it's in, less what they're scrolled by+ let layout = node.final_layout();+ let mut at = Vec2::new(layout.location.x as f64, layout.location.y as f64);+ let mut up = node.containing_block();+ while let Some(a) = up.filter(|a| *a != root) {+ let Some(an) = tree.get(a) else { break };+ let (l, sc) = (an.final_layout().location, *an.scroll_offset());+ at += Vec2::new(l.x as f64 - sc.x, l.y as f64 - sc.y);+ up = an.containing_block();+ }+ let b = layout.border;+ let far = 1e7;+ let pad = Rect::new(+ if cx { at.x + b.left as f64 } else { -far },+ if cy { at.y + b.top as f64 } else { -far },+ if cx { at.x + (layout.size.width - b.right) as f64 } else { far },+ if cy { at.y + (layout.size.height - b.bottom) as f64 } else { far },+ );+ scene.push_clip_layer(Fill::NonZero, transform, &pad.scale_from_origin(self.scale));+ pushed += 1;+ }+ pushed+ }+#[cfg(feature = "svg")]fn draw_svg(&self, scene: &mut impl PaintScene) {use style::properties::generated::longhands::object_fit::computed_value::T as ObjectFit;diff --git a/vendor/blitz-paint/src/render/form_controls.rs b/vendor/blitz-paint/src/render/form_controls.rsindex 6411a8cc..e2c96d8c 100644--- a/vendor/blitz-paint/src/render/form_controls.rs+++ b/vendor/blitz-paint/src/render/form_controls.rs@@ -1,5 +1,5 @@use super::ElementCx;-use crate::color::Color;+use crate::color::{Color, ToColorColor as _};use anyrender::PaintScene;use blitz_dom::local_name;use kurbo::{BezPath, Cap, Circle, Join, Point, Stroke};@@ -19,6 +19,9 @@ impl ElementCx<'_, '_> {if self.node.local_name() != "input" {return;}+ if self.node.attr(local_name!("type")) == Some("range") {+ return self.draw_range(scene);+ }let Some(on) = self.element.checkbox_input_checked() else {return;};@@ -69,3 +72,39 @@ impl ElementCx<'_, '_> {}}}++impl ElementCx<'_, '_> {+ /// raea: a range input's thumb at its value, as Chrome draws it: the page's own (::-webkit-slider-thumb with a+ /// width, its height, background and corner radius: Excalidraw's opacity slider) centred on the input, else+ /// Chrome's on macOS, a 4px track blue up to a 16px blue thumb. Blitz drew no thumb, only the input's own box.+ fn draw_range(&self, scene: &mut impl PaintScene) {+ let num = |v: Option<&str>| v.and_then(|v| v.trim().parse::<f64>().ok()).filter(|v| v.is_finite());+ let min = num(self.node.attr(local_name!("min"))).unwrap_or(0.0);+ let max = num(self.node.attr(local_name!("max"))).unwrap_or(100.0).max(min);+ let value = num(self.node.attr(local_name!("value"))).unwrap_or((min + max) / 2.0).clamp(min, max);+ let at = if max > min { (value - min) / (max - min) } else { 0.0 };+ let (px, b, t) = (self.scale, self.frame.border_box, self.transform);+ let thumb = self.context.dom.slider_thumb_style(self.node.id);+ let length = |s: &style::values::computed::Size| match s {+ style::values::generics::length::GenericSize::LengthPercentage(lp) => lp.0.to_length().map(|l| f64::from(l.px())),+ _ => None,+ };+ let own = thumb.as_ref().and_then(|th| length(&th.get_position().width).map(|w| (th, w)));+ if let Some((th, w)) = own {+ let h = length(&th.get_position().height).unwrap_or(w);+ let (w, h) = (w * px, h * px);+ let r = th.get_border().border_top_left_radius.0.width.0.resolve(style::values::computed::Length::new((w / px) as f32));+ let color = th.get_background().background_color.resolve_to_absolute(&th.clone_color()).as_srgb_color();+ let cx = b.x0 + w / 2.0 + at * (b.width() - w);+ let rect = kurbo::Rect::from_center_size((cx, b.center().y), (w, h));+ scene.fill(Fill::NonZero, t, color, None, &rect.to_rounded_rect(f64::from(r.px()) * px));+ return;+ }+ let d = 16.0 * px;+ let cx = b.x0 + d / 2.0 + at * (b.width() - d);+ let track = kurbo::Rect::new(b.x0, b.center().y - 2.0 * px, b.x1, b.center().y + 2.0 * px);+ scene.fill(Fill::NonZero, t, Color::from_rgba8(239, 239, 239, 255), None, &track.to_rounded_rect(2.0 * px));+ scene.fill(Fill::NonZero, t, ACCENT, None, &track.with_size((cx - b.x0, track.height())).to_rounded_rect(2.0 * px));+ scene.fill(Fill::NonZero, t, ACCENT, None, &Circle::new((cx, b.center().y), d / 2.0));+ }+}diff --git a/vendor/blitz-paint/src/text.rs b/vendor/blitz-paint/src/text.rsindex f655bfbe..912415f2 100644--- a/vendor/blitz-paint/src/text.rs+++ b/vendor/blitz-paint/src/text.rs@@ -12,7 +12,7 @@ use style::values::computed::{use style::values::generics::text::{GenericTextDecorationInset, GenericTextDecorationLength};use crate::color::{Color, ToColorColor as _};-use crate::{FONT_EMBOLDEN_ENABLED, SELECTION_COLOR};+use crate::FONT_EMBOLDEN_ENABLED;/// raea: how glyphs are drawn to match Chrome's text on macOS, as bevy-tsx's page fits it (its render/mod.rs/// `chrome_glyph_raster`): each outline grows by `per_size` of the font size up to `max` (CSS px), light text by@@ -1134,19 +1134,25 @@ pub(crate) fn stroke_text<'a>(/// Draw selection highlight rectangles for the given byte range in a layout./// Uses Parley's Selection type for accurate geometry calculation.+/// raea: in `color` (the ::selection background), returning the rects as one path (layout units) so the selected+/// glyphs can be drawn again inside them in the ::selection colourpub(crate) fn draw_text_selection(scene: &mut impl PaintScene,layout: &Layout<TextBrush>,transform: Affine,selection_start: usize,selection_end: usize,-) {+ color: Color,+) -> kurbo::BezPath {let anchor = Cursor::from_byte_index(layout, selection_start, Affinity::Downstream);let focus = Cursor::from_byte_index(layout, selection_end, Affinity::Downstream);let selection = Selection::new(anchor, focus);+ let mut path = kurbo::BezPath::new();selection.geometry_with(layout, |rect, _line_idx| {let rect = kurbo::Rect::new(rect.x0, rect.y0, rect.x1, rect.y1);- scene.fill(Fill::NonZero, transform, SELECTION_COLOR, None, &rect);+ scene.fill(Fill::NonZero, transform, color, None, &rect);+ kurbo::Shape::path_elements(&rect, 0.1).for_each(|e| path.push(e));});+ path}diff --git a/vendor/stylo/servo/selector_parser.rs b/vendor/stylo/servo/selector_parser.rsindex 8db71357..aedbca8d 100644--- a/vendor/stylo/servo/selector_parser.rs+++ b/vendor/stylo/servo/selector_parser.rs@@ -712,7 +712,8 @@ impl<'a, 'i> ::selectors::Parser<'i> for SelectorParser<'a> {ServoTextControlInnerEditor},"slider-fill" => SliderFill,- "slider-thumb" => SliderThumb,+ // raea: Chrome's and Firefox's names for it, as pages write them (Excalidraw's opacity slider)+ "slider-thumb" | "-webkit-slider-thumb" | "-moz-range-thumb" => SliderThumb,"slider-track" => SliderTrack,"-moz-progress-bar" => MozProgressBar,"-servo-anonymous-box" => {diff --git a/vendor/stylo/values/specified/ui.rs b/vendor/stylo/values/specified/ui.rsindex f614764b..bfbcb404 100644--- a/vendor/stylo/values/specified/ui.rs+++ b/vendor/stylo/values/specified/ui.rs@@ -274,21 +274,16 @@ pub enum MozTheme {pub enum PointerEvents {Auto,None,- #[cfg(feature = "gecko")]+ // raea: SVG's keywords for Servo too (Gecko-only upstream). Excalidraw's UI sets `pointer-events: all` on its+ // buttons under a `none` layer; unparsed, they inherited `none` and every click fell through to the canvas.+ // On HTML elements each acts as `auto`, as in Chrome.Visiblepainted,- #[cfg(feature = "gecko")]Visiblefill,- #[cfg(feature = "gecko")]Visiblestroke,- #[cfg(feature = "gecko")]Visible,- #[cfg(feature = "gecko")]Painted,- #[cfg(feature = "gecko")]Fill,- #[cfg(feature = "gecko")]Stroke,- #[cfg(feature = "gecko")]All,}diff --git a/vendor/vello_encoding/src/image_cache.rs b/vendor/vello_encoding/src/image_cache.rsindex 8b827d89..e5431031 100644--- a/vendor/vello_encoding/src/image_cache.rs+++ b/vendor/vello_encoding/src/image_cache.rs@@ -98,6 +98,12 @@ impl ImageCache {}}+ /// raea: the atlas at its size with nothing to upload, for a resolve that uses no images (it keeps the renderer's+ /// persistent atlas texture and what's resident in it)+ pub(crate) fn unchanged(&self) -> Images<'_> {+ Images { width: self.atlas.size().width as u32, height: self.atlas.size().height as u32, evicted: 0, images: &[] }+ }+pub(crate) fn bump_size(&mut self) -> bool {let mut new_size = self.atlas.size().width * 2;while new_size <= self.max_size {@@ -211,6 +217,17 @@ mod tests {use peniko::{Blob, ImageAlphaType, ImageFormat};use std::sync::Arc;+ /// raea: a resolve with no images reports the atlas as it is, not 0x0 (which made the renderer drop its atlas)+ #[test]+ fn unchanged_keeps_the_atlas_size() {+ let mut cache = ImageCache::new_with_sizes(64, 256);+ cache.begin_resolve();+ assert!(cache.get_or_insert(&image(1, 16, 16)).is_some());+ cache.finish_resolve();+ let i = cache.unchanged();+ assert_eq!((i.width, i.height, i.images.len()), (64, 64, 0));+ }+fn image(id_byte: u8, width: u32, height: u32) -> ImageData {let len = (width * height * 4) as usize;ImageData {diff --git a/vendor/vello_encoding/src/resolve.rs b/vendor/vello_encoding/src/resolve.rsindex 2513a216..a3a398ae 100644--- a/vendor/vello_encoding/src/resolve.rs+++ b/vendor/vello_encoding/src/resolve.rs@@ -188,7 +188,10 @@ impl Resolver {let resources = &encoding.resources;if resources.patches.is_empty() {let layout = resolve_solid_paths_only(encoding, packed);- return (layout, Ramps::default(), Images::default());+ // raea: the atlas as it is, nothing to upload. Images::default() said 0x0, and the renderer swapped its+ // persistent atlas for a 1x1 one, so the next scene with images found them "clean" in a new, empty atlas+ // and drew them blank (a page with an SVG mask: the mask's filtered layer is a solid-only scene)+ return (layout, Ramps::default(), self.image_cache.unchanged());}let patch_sizes = self.resolve_patches(encoding);self.resolve_pending_images();diff --git a/vendor/vendor.toml b/vendor/vendor.tomlindex a0849eb3..db09f769 100644--- a/vendor/vendor.toml+++ b/vendor/vendor.toml@@ -56,7 +56,7 @@ exit = "a bevy_ui_widgets release on parley 0.12"path = "vendor/blitz-paint"upstream = "crates.io:0.3.0-beta.4"kind = "patch"-reason = "angled tile gradients, many-tile gradient layers as one brush, text-shadow, ellipsis, inline-box opacity, box-shadow blur as Chrome's; filters by GPU passes (B4a/B4b)"+reason = "angled tile gradients, many-tile gradient layers as one brush, text-shadow, ellipsis, inline-box opacity, box-shadow blur as Chrome's; filters by GPU passes (B4a/B4b); z-index boxes clipped by the overflow between them and their stacking context; a range input's thumb"exit = "a Blitz release that draws these"[blitz-dom]@@ -84,7 +84,7 @@ exit = "parley carrying the fix"path = "vendor/stylo"upstream = "crates.io:0.22.0"kind = "patch"-reason = "line-clamp and text-wrap-style (with Chrome's pretty) for Servo too, Gecko-only upstream; url() filters"+reason = "line-clamp, text-wrap-style (with Chrome's pretty) and pointer-events' SVG keywords (all, visible, painted...) for Servo too, Gecko-only upstream; url() filters; ::-webkit-slider-thumb and ::-moz-range-thumb as the slider thumb"exit = "Servo's stylo enabling them"[anyrender]@@ -105,7 +105,7 @@ exit = "anyrender_svg drawing these"path = "vendor/vello_encoding"upstream = "crates.io:0.11.0"kind = "patch"-reason = "bump buffer sizes set by the embedder (vello#1861's BumpAllocationSizes), not 165 MiB of defaults, grown with the target past 1080p (bump_sizes_for: ptcl holds every tile's initial allocation, which alone filled 99% of a fixed 2M at 4K), and back at the defaults while set_bump_full is on (a frame that came out all black drawn again); glyph tops for the CoreGraphics y-map (RAEA_PAGE_CG_YMAP)"+reason = "bump buffer sizes set by the embedder (vello#1861's BumpAllocationSizes), not 165 MiB of defaults, grown with the target past 1080p (bump_sizes_for: ptcl holds every tile's initial allocation, which alone filled 99% of a fixed 2M at 4K), and back at the defaults while set_bump_full is on (a frame that came out all black drawn again); glyph tops for the CoreGraphics y-map (RAEA_PAGE_CG_YMAP); a resolve with no images keeps the image atlas (resolve.rs: a solid-only scene reported 0x0, the renderer swapped in a 1x1 atlas and every cached image then drew blank)"exit = "vello#1861 in a release; the y-map hook stays ours"# checked 2026-10-26 for firewheel and its graph, macros and nodes: crates.io 0.14.0 (latest) and Firewheel main 34b35cad stop at glam-32 and bevy_reflect 0.19; bevy_seedling 0.8.0 and its main ab4a88b4 need firewheel 0.12 and Bevy 0.19