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
Layer pass, the page's half (docs/review.feature R2b, R2c, R2e; work in progress, parked with the source stamps): raea render --layers writes NAME.layers v1 (systems/layers, raea-sys-layers: gzip of RAEALAYR, the header's table of layers, each frame's quarter-size mask as runs) and render.json's "layers" names it. The page is painted a second time once the frame's update has laid it out: blitz-paint now names the node each paint call draws for (painting()), and an ID scene on vello_cpu draws that node's layer index as a flat colour with antialiasing off (edges counted above 12/255 coverage, glyphs emboldened as the page draws them). bench/layers/compare.sh scores each layer's mask (its own pixels plus those of the layers inside it) against oracle.sh's: all 12 page layers pass at IoU >= 0.977 at frames 10, 45 and 80. The 2 mesh layers come with the 3D half. key_of moved to raea-sys-layers (systems/frame re-exports it).
shinyobjectz7a3e87dddb59
diff --git a/Cargo.lock b/Cargo.lockindex 5dec7438..769d3ef0 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -14375,6 +14375,7 @@ dependencies = ["raea-runtime-plugins","raea-runtime-twins","raea-sys-fonts",+ "raea-sys-layers","raea-sys-page","serde_json","stylo",@@ -14778,6 +14779,7 @@ dependencies = ["raea-runtime-sound","raea-runtime-view","raea-sys-contact",+ "raea-sys-layers","raea-sys-light-meter","raea-sys-mix","raea-sys-page",@@ -15254,6 +15256,7 @@ dependencies = ["raea-core-program","raea-core-scene","raea-io-media",+ "raea-sys-layers","serde_json",]@@ -15308,6 +15311,19 @@ dependencies = ["wgpu",]+[[package]]+name = "raea-sys-layers"+version = "0.1.0"+dependencies = [+ "anyrender",+ "blitz-dom",+ "blitz-paint",+ "flate2",+ "glifo",+ "serde_json",+ "vello_cpu",+]+[[package]]name = "raea-sys-layout"version = "0.1.0"diff --git a/Cargo.toml b/Cargo.tomlindex 153e237c..714920fe 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -94,6 +94,7 @@ members = ["systems/page-net","systems/page-ops","systems/frame",+ "systems/layers","systems/splat","systems/sprite","systems/rt",diff --git a/bench/layers/compare.pl b/bench/layers/compare.plnew file mode 100644index 00000000..1e5d3c11--- /dev/null+++ b/bench/layers/compare.pl@@ -0,0 +1,46 @@+#!/usr/bin/perl+# bench/layers/compare.sh's comparison: NAME.layers on stdin, the oracle folder and the IoU floor as arguments.+use strict; my ($oracle, $min) = @ARGV; binmode STDIN; local $/; my $d = <STDIN>;+substr($d, 0, 8) eq "RAEALAYR" or die "not a layers file\n";+my $n = unpack("V", substr($d, 8, 4)); my $h = substr($d, 12, $n); my $o = 12 + $n;+# the header, read with no JSON module: the mask size, the moments, and each layer's key and parent+my ($mw, $mh) = $h =~ /"mask":\{"w":(\d+),"h":(\d+)/ or die "no mask size\n";+my @at = $h =~ /"at":\[([\d,]+)\]/ ? split(/,/, $1) : ();+my (@key, @parent);+while ($h =~ /\{"key":"((?:[^"\\]|\\.)*)","kind":"[a-z]+","name":"(?:[^"\\]|\\.)*","parent":(null|"(?:[^"\\]|\\.)*")/g) {+ push @key, $1; my $p = $2; $p =~ s/^"|"$//g; push @parent, $p eq "null" ? undef : $p;+}+my %index; $index{$key[$_]} = $_ + 1 for 0..$#key;+# each value's ancestors-or-self, as values+my @up = ([]); for my $v (1..@key) { my @c = ($v); my $p = $parent[$v - 1]; while (defined $p && $index{$p}) { push @c, $index{$p}; $p = $parent[$index{$p} - 1] } $up[$v] = \@c }+my (@frames, @prev);+my $count = $h =~ /"frames":(\d+),"width"/ ? $1 : die "no frame count\n";+for (1..$count) {+ my $runs = unpack("V", substr($d, $o, 4)); $o += 4; my @v;+ for (1..$runs) { my ($v, $c) = unpack("vv", substr($d, $o, 4)); $o += 4; push @v, ($v) x $c }+ @v = @prev unless $runs; @prev = @v; push @frames, [@v];+}+@at = (0..$count - 1) unless @at;+open my $k, "<", "$oracle/keys.txt" or die; my $fail = 0;+for (split /\n/, do { local $/; <$k> }) {+ my ($i, $want) = split / /, $_, 2; my $v = $index{$want};+ my @ious;+ for my $m (0..$#at) {+ my $pgm = "$oracle/$at[$m]/$i.pgm"; -f $pgm or next;+ open my $p, "<", $pgm or die; binmode $p; my $raw = do { local $/; <$p> };+ $raw =~ s/\AP5\s+(\d+)\s+(\d+)\s+(\d+)\s//s or die "$pgm: not a P5 PGM\n"; my $max = $3; ($1 == $mw && $2 == $mh) or die "$pgm: ${1}x$2, the layers are ${mw}x$mh\n";+ my @want = unpack("C*", $raw); my ($both, $either) = (0, 0);+ for my $px (0..$#want) {+ my $got = $v && grep { $_ == $v } @{$up[$frames[$m][$px]]};+ my $w = $want[$px] * 2 > $max;+ $both++ if $got && $w; $either++ if $got || $w;+ if ($ENV{LAYERS_WHY} && $ENV{LAYERS_WHY} eq "$i/$at[$m]" && ($got xor $w)) { printf " %s at %d,%d (value there %d)\n", $got ? "only the layers" : "only the oracle", $px % $mw, int($px / $mw), $frames[$m][$px] }+ }+ push @ious, $either ? $both / $either : 1;+ }+ my $worst = (sort { $a <=> $b } @ious)[0] // 0;+ my $ok = defined $v && $worst >= $min;+ $fail ||= !$ok;+ printf "%s layer %s (%s): IoU %s%s\n", $ok ? "ok " : "FAIL", $i, $want, join(" ", map { sprintf "%.3f", $_ } @ious), defined $v ? "" : ", not in the layers";+}+exit($fail ? 1 : 0);diff --git a/bench/layers/compare.sh b/bench/layers/compare.shnew file mode 100755index 00000000..1bd877ff--- /dev/null+++ b/bench/layers/compare.sh@@ -0,0 +1,11 @@+#!/bin/bash+# The layer pass against its oracle (docs/review.feature R2e): each layer's mask in NAME.layers (`raea render --layers`+# of bench/layers/conformance.tsx at the oracle's moments) against where hiding it changed the frame (oracle.sh), as+# IoU, at each moment. A layer's mask is its own pixels and those of every layer inside it (a hide hides those too).+# A layer passes at IoU >= MIN (0.95) at every moment where either mask has pixels; exits 1 when one fails.+# bench/layers/compare.sh ORACLE NAME.layers [MIN]+ORACLE=${1:?ORACLE: oracle.sh OUT folder}+LAYERS=${2:?NAME.layers}+MIN=${3:-0.95}+[ -f "$ORACLE/keys.txt" ] || { echo "no $ORACLE/keys.txt: run bench/layers/oracle.sh first"; exit 2; }+gunzip -c "$LAYERS" | perl "$(dirname "$0")/compare.pl" "$ORACLE" "$MIN"diff --git a/engine/cli/src/cli.rs b/engine/cli/src/cli.rsindex a1efce7b..5f4a497e 100644--- a/engine/cli/src/cli.rs+++ b/engine/cli/src/cli.rs@@ -345,7 +345,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] [--aov] [--alpha] [--kbps N | --quality draft|high|master|0..1] [--clay] (also: --lite --comps)\n raea render EDIT.tsx --review DIR [--frame N] (fixed cameras hero, front, right, top, iso, low in colour and clay: DIR/colour.png, clay.png, review.json)\n raea render PAGE.html -o OUT.mp4|OUT.png|DIR [--at A,B] [--alpha] (an HTML composition)\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] [--layers] [--stage WxH] [--10bit] [--aov] [--alpha] [--kbps N | --quality draft|high|master|0..1] [--clay] (also: --lite --comps)\n raea render EDIT.tsx --review DIR [--frame N] (fixed cameras hero, front, right, top, iso, low in colour and clay: DIR/colour.png, clay.png, review.json)\n raea render PAGE.html -o OUT.mp4|OUT.png|DIR [--at A,B] [--alpha] (an HTML composition)\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/page/Cargo.toml b/engine/page/Cargo.tomlindex de18e4ee..330aeb2e 100644--- a/engine/page/Cargo.toml+++ b/engine/page/Cargo.toml@@ -10,6 +10,8 @@ description = "HTML, CSS and React pages in Bevy (docs/blitz-bevy.feature): Blit# the layers under itraea-sys-page = { path = "../../systems/page" }raea-sys-fonts = { path = "../../systems/fonts" }+# the layer pass's page half (docs/review.feature R2b)+raea-sys-layers = { path = "../../systems/layers", features = ["page"] }raea-runtime-twins = { path = "../../runtime/twins" }raea-runtime-dom = { path = "../../runtime/dom" }raea-runtime-edit = { path = "../../runtime/edit" }diff --git a/engine/page/src/motion.rs b/engine/page/src/motion.rsindex a8bbb45a..53db16e4 100644--- a/engine/page/src/motion.rs+++ b/engine/page/src/motion.rs@@ -351,6 +351,7 @@ impl BlitzPage {}let labelled: Vec<_> = images.iter().enumerate().map(|(k, (i, w, h))| (i.clone(), *w, *h, if k == 0 { ENCODER_COPY } else { SCREEN_COPY })).collect();let mut got = self.read(&labelled)?.into_iter();+ self.layers();let page = got.next().ok_or("no page frame")?;let subs = keys.into_iter().zip(got).map(|(k, px)| (k.clone(), self.subs[&k].w, self.subs[&k].h, px)).collect();Ok((page, subs))diff --git a/engine/page/src/motion/read.rs b/engine/page/src/motion/read.rsindex 55064b95..21ee7c82 100644--- a/engine/page/src/motion/read.rs+++ b/engine/page/src/motion/read.rs@@ -14,6 +14,7 @@ impl BlitzPage {std::thread::yield_now();}self.dump();+ self.layers();}/// RAEA_PAGE_DUMP leaves this page out: a page beside the composition's (raea-render's image rows, rows2d.rs) wrote@@ -52,7 +53,9 @@ impl BlitzPage {}self.dump();let image = self.image();- Ok(self.read(&[(image, self.w, self.h, ENCODER_COPY)])?.remove(0))+ let px = self.read(&[(image, self.w, self.h, ENCODER_COPY)])?.remove(0);+ self.layers();+ Ok(px)}/// Each image drawn by one update and copied to the CPU once, in one submit, each into a buffer labelled `label`@@ -167,3 +170,18 @@ impl BlitzPage {out}}++impl BlitzPage {+ /// The composition's page as layer indices at a render's frame, recorded (`raea render --layers`); a page beside+ /// the composition's (`not_dumped`) or a page with no render clock records nothing. Called once the frame's update has laid+ /// the page out (after its read, for a read frame).+ pub(crate) fn layers(&mut self) {+ let (Some((now, _, fps)), true, true) = (self.clock, self.dumps, raea_sys_layers::on()) else { return };+ let (w, h, page) = (self.w, self.h, self.page);+ let scale = self.app.world().get::<Page>(page).map_or(1.0, |p| p.scale as f64);+ let mut docs = self.app.world_mut().non_send_mut::<Docs>();+ let Some(doc) = docs.0.get_mut(&page) else { return };+ let (px, layers) = raea_sys_layers::page_ids(doc, scale, w, h);+ raea_sys_layers::with(|r| r.frame((now * fps).round() as i64, w, h, &px, &layers));+ }+}diff --git a/runtime/export/Cargo.toml b/runtime/export/Cargo.tomlindex 35d2a02d..40aaf6be 100644--- a/runtime/export/Cargo.toml+++ b/runtime/export/Cargo.toml@@ -18,6 +18,7 @@ raea-render = { path = "../../engine/render", default-features = false, featuresraea-runtime-encode = { path = "../encode" }raea-page = { path = "../../engine/page" }raea-sys-page = { path = "../../systems/page" }+raea-sys-layers = { path = "../../systems/layers" }raea-gpu-device = { path = "../../gpu/device" }raea-io-net = { path = "../../io/net" }raea-io-media = { path = "../../io/media", default-features = false, features = ["soft-audio", "apple"] }diff --git a/runtime/export/src/fed.rs b/runtime/export/src/fed.rsindex 1ab59a67..97d31667 100644--- a/runtime/export/src/fed.rs+++ b/runtime/export/src/fed.rs@@ -41,13 +41,12 @@ pub(crate) fn frames_hold_3d(js: &Path, dir: &Path, frames: &[i64]) -> R<bool> {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) and-/// each frame's commit is applied on its own (OneBatch, PreUpdate only), its scene read after it; the frames split-/// across runtimes on threads, since frames are pure (each runtime's first frame is its whole tree). One event a frame,-/// each waited on the JS thread and back, took the Rome film's 8,064 frames 6 s on a quiet machine and 38 s at load-/// 50, before its engine could open. RAEA_BAKE_WORKERS sets how many runtimes (4; one for short timelines).+/// 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) and each frame's commit is+/// applied on its own (OneBatch, PreUpdate only), its scene read after it; the frames split across runtimes on threads,+/// since frames are pure (each runtime's first frame is its whole tree). One event a frame, each waited on the JS+/// thread and back, took the Rome film's 8,064 frames 6 s on a quiet machine and 38 s at load 50, before its engine+/// could open. RAEA_BAKE_WORKERS sets how many runtimes (4; one for short timelines).pub(crate) fn scene_frames_to(js: &Path, dir: &Path, upto: i64) -> R<Option<(Vec<(i64, Frame)>, u32, u32, f64)>> {scene_frames(js, dir, upto, true, &[])}diff --git a/runtime/export/src/lib.rs b/runtime/export/src/lib.rsindex df40af48..78e93d13 100644--- a/runtime/export/src/lib.rs+++ b/runtime/export/src/lib.rs@@ -70,7 +70,7 @@ static MANIFEST: std::sync::Mutex<Option<PathBuf>> = std::sync::Mutex::new(None)/// With --manifest, its file: the frames' boxes as drawn (Ctx.manifest), the 3D's clipping and the sounds heard.fn write_manifest(cx: &mut Ctx, (w, h, fps): (u32, u32, f64), clipping: Vec<Value>, heard: impl FnOnce(&Ctx) -> Value) -> R<()> {let (Some(path), Some(frames)) = (MANIFEST.lock().unwrap().clone(), cx.manifest.take()) else { return Ok(()) };- let m = json!({"width": w, "height": h, "fps": fps, "frames": frames, "clipping": clipping, "sounds": heard(cx), "not_applied": not_applied::seen()});+ let m = json!({"width": w, "height": h, "fps": fps, "frames": frames, "clipping": clipping, "sounds": heard(cx), "not_applied": not_applied::seen(), "layers": raea_sys_layers::finish(fps)});std::fs::write(&path, m.to_string()).map_err(|e| format!("{}: {e}", path.display()))}diff --git a/runtime/export/src/render.rs b/runtime/export/src/render.rsindex 667528aa..22f70ac7 100644--- a/runtime/export/src/render.rs+++ b/runtime/export/src/render.rs@@ -54,7 +54,8 @@ pub fn render(args: &[String]) -> R<String> {(_, Some(at)) => Some(at.split(',').map(|f| f.trim().parse::<i64>().map_err(|_| "--at takes frame numbers".to_string())).collect::<R<_>>()?),_ => None,};- *MANIFEST.lock().unwrap() = flag(args, "--manifest").map(PathBuf::from);+ let layers = raea_sys_layers::start(args.iter().any(|a| a == "--layers"), &out, &tsx);+ *MANIFEST.lock().unwrap() = flag(args, "--manifest").map(PathBuf::from).or(layers);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() {@@ -83,7 +84,7 @@ pub fn render(args: &[String]) -> R<String> {None => None,};// a whole video made from these same inputs before is the export: cloned from the cache, not rendered again- let cache = if wanted.is_none() { export_cache(&tsx, &js, &out, args) } else { None };+ let cache = if wanted.is_none() && !raea_sys_layers::on() { export_cache(&tsx, &js, &out, args) } else { None };let manifest = MANIFEST.lock().unwrap().clone();if let Some(c) = &cache {// with --manifest, the manifest kept beside the export comes back toodiff --git a/systems/frame/Cargo.toml b/systems/frame/Cargo.tomlindex 8f57b55a..8f985caf 100644--- a/systems/frame/Cargo.toml+++ b/systems/frame/Cargo.toml@@ -15,5 +15,7 @@ bevy = { version = "=0.20.0", default-features = false, features = ["std", "defaraea-core-program = { path = "../../core/program" }# a staticFile path (/media/x) as a file: the media folders it can be in (raea-core-scene media_path)raea-core-scene = { path = "../../core/scene" }+# the layer key (key_of), shared with the page's half of the layer pass+raea-sys-layers = { path = "../layers" }serde_json = "1"raea-io-media = { path = "../../io/media", default-features = false, optional = true }diff --git a/systems/frame/src/layer.rs b/systems/frame/src/layer.rsindex 2039eb79..94e5e09e 100644--- a/systems/frame/src/layer.rs+++ b/systems/frame/src/layer.rs@@ -9,30 +9,6 @@ use bevy::prelude::*;#[reflect(Component, Default)]pub struct LayerKey(pub String);-/// The key a stamped element or part's props give it: `data-raea-loc`, `#data-raea-idx` when it has one, then-/// `|data-raea-use` when it was drawn inside the edit's components. None for an unstamped one.-pub fn key_of(loc: Option<&str>, idx: Option<&str>, uses: Option<&str>) -> Option<String> {- let loc = loc.filter(|l| !l.is_empty())?;- let mut k = loc.to_string();- if let Some(i) = idx.filter(|i| !i.is_empty()) {- k.push('#');- k.push_str(i);- }- if let Some(u) = uses.filter(|u| !u.is_empty()) {- k.push('|');- k.push_str(u);- }- Some(k)-}+/// The key a stamped element or part's props give it (raea-sys-layers owns it: the page's half reads it too).+pub use raea_sys_layers::key_of;-#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn a_key_is_the_stamp_its_place_and_its_uses() {- assert_eq!(key_of(Some("a.tsx:3:5"), None, None).as_deref(), Some("a.tsx:3:5"));- assert_eq!(key_of(Some("card.tsx:2:10"), Some("2"), Some("comp.tsx:6:27#2")).as_deref(), Some("card.tsx:2:10#2|comp.tsx:6:27#2"));- assert_eq!(key_of(None, Some("2"), Some("x")), None);- }-}diff --git a/systems/layers/Cargo.toml b/systems/layers/Cargo.tomlnew file mode 100644index 00000000..240b0290--- /dev/null+++ b/systems/layers/Cargo.toml@@ -0,0 +1,23 @@+[package]+name = "raea-sys-layers"+version = "0.1.0"+edition = "2024"+license = "FSL-1.1-ALv2"+publish = false+description = "The layer pass (docs/review.feature R2b, R2c): which layer every pixel of a frame shows, as a quarter-size mask of layer indices and a table of the layers, written as NAME.layers"++[features]+# the page's half: a Blitz document painted as layer indices (without it: the keys, the table and the file)+page = ["dep:anyrender", "dep:blitz-dom", "dep:blitz-paint", "dep:vello_cpu", "dep:glifo"]++[dependencies]+anyrender = { version = "=0.14.0", optional = true }+blitz-dom = { version = "=0.3.0-beta.4", default-features = false, optional = true }+# the page painted again with each node's layer index for its colour (blitz_paint::painting names the node)+blitz-paint = { version = "=0.3.0-beta.4", default-features = false, optional = true }+# the ID picture: Vello's CPU rasterizer with antialiasing off (an edge pixel is one layer's, never a blend of two)+vello_cpu = { version = "=0.1.0", default-features = false, features = ["std", "text", "u8_pipeline"], optional = true }+# its glyph runs' synthetic bold (FontEmbolden), as blitz-paint asks for it+glifo = { version = "=0.2.0", default-features = false, optional = true }+flate2 = "1"+serde_json = "1"diff --git a/systems/layers/src/file.rs b/systems/layers/src/file.rsnew file mode 100644index 00000000..0cfde3dd--- /dev/null+++ b/systems/layers/src/file.rs@@ -0,0 +1,124 @@+//! NAME.layers (v1, agreed with apps/app's player): one gzip stream of "RAEALAYR", a u32 LE header length, the+//! header's JSON, then each frame as a u32 LE run count N and N (u16 value, u16 count) runs over its quarter-size mask,+//! row-major (N = 0: the frame before's mask). Value 0 is no layer, v is the header's layers[v - 1]. A run never+//! passes 65535. Mask px (x, y) is frame px (4x + 2, 4y + 2).++use std::collections::{BTreeMap, HashMap};+use std::io::Write;+use std::path::PathBuf;++use serde_json::json;++use crate::Layer;++pub const SCALE: u32 = 4;++pub struct Recorder {+ path: PathBuf,+ /// the export's file name+ video: String,+ /// the frame's size+ size: (u32, u32),+ layers: Vec<Layer>,+ /// each layer's first and last frame+ seen: Vec<[i64; 2]>,+ by_key: HashMap<String, u16>,+ /// each recorded frame's mask, as runs+ masks: BTreeMap<i64, Vec<(u16, u16)>>,+}++impl Recorder {+ pub fn new(path: PathBuf, video: String) -> Recorder {+ Recorder { path, video, size: (0, 0), layers: Vec::new(), seen: Vec::new(), by_key: HashMap::new(), masks: BTreeMap::new() }+ }++ /// Frame `f`'s layers: `px` (`w` x `h`, row-major) each pixel's index into `layers` plus one (0: none). A frame+ /// recorded again replaces what it had (a page drawn twice in a frame).+ pub fn frame(&mut self, f: i64, w: u32, h: u32, px: &[u16], layers: &[Layer]) {+ self.size = (w, h);+ let global: Vec<u16> = std::iter::once(0).chain(layers.iter().map(|l| self.index(l, f))).collect();+ let (mw, mh) = (w.div_ceil(SCALE), h.div_ceil(SCALE));+ let mut runs: Vec<(u16, u16)> = Vec::new();+ for y in 0..mh {+ let fy = (y * SCALE + SCALE / 2).min(h - 1);+ for x in 0..mw {+ let fx = (x * SCALE + SCALE / 2).min(w - 1);+ let v = px.get((fy * w + fx) as usize).and_then(|v| global.get(*v as usize)).copied().unwrap_or(0);+ match runs.last_mut() {+ Some((lv, n)) if *lv == v && *n < u16::MAX => *n += 1,+ _ => runs.push((v, 1)),+ }+ }+ }+ self.masks.insert(f, runs);+ }++ /// A layer's value in the file (its place in the table plus one), added at its first frame.+ fn index(&mut self, l: &Layer, f: i64) -> u16 {+ let i = match self.by_key.get(&l.key) {+ Some(i) => *i,+ None => {+ self.layers.push(l.clone());+ self.seen.push([f, f]);+ let i = self.layers.len() as u16;+ self.by_key.insert(l.key.clone(), i);+ i+ }+ };+ let s = &mut self.seen[i as usize - 1];+ *s = [s[0].min(f), s[1].max(f)];+ i+ }++ /// The header, as NAME.layers gives it.+ pub fn header(&self, fps: f64) -> serde_json::Value {+ let (w, h) = self.size;+ let layers: Vec<_> = self.layers.iter().zip(&self.seen).map(|(l, s)| {+ let mut v = json!({"key": l.key, "kind": l.kind, "name": l.name, "parent": l.parent, "loc": l.loc, "use": l.uses, "index": l.index, "frames": s});+ if let Some(src) = &l.src {+ v["src"] = json!(src);+ }+ v+ }).collect();+ let mut head = json!({"version": 1, "video": self.video, "fps": fps, "frames": self.masks.len(), "width": w, "height": h,+ "mask": {"w": w.div_ceil(SCALE), "h": h.div_ceil(SCALE), "scale": SCALE}, "layers": layers});+ // frames not from 0 on, one after another (a render's --at): which they are+ let at: Vec<i64> = self.masks.keys().copied().collect();+ if at.iter().enumerate().any(|(i, f)| *f != i as i64) {+ head["at"] = json!(at);+ }+ head+ }++ /// The file's bytes, before gzip.+ pub fn bytes(&self, fps: f64) -> Vec<u8> {+ let head = self.header(fps).to_string();+ let mut out = b"RAEALAYR".to_vec();+ out.extend((head.len() as u32).to_le_bytes());+ out.extend(head.as_bytes());+ let mut before: Option<&Vec<(u16, u16)>> = None;+ for runs in self.masks.values() {+ if before == Some(runs) {+ out.extend(0u32.to_le_bytes());+ continue;+ }+ out.extend((runs.len() as u32).to_le_bytes());+ for (v, n) in runs {+ out.extend(v.to_le_bytes());+ out.extend(n.to_le_bytes());+ }+ before = Some(runs);+ }+ out+ }++ /// Written to its path: the file's name. None when no frame was recorded.+ pub fn write(self, fps: f64) -> Result<Option<String>, String> {+ if self.masks.is_empty() {+ return Ok(None);+ }+ let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());+ gz.write_all(&self.bytes(fps)).and_then(|_| gz.finish().and_then(|b| std::fs::write(&self.path, b))).map_err(|e| format!("{}: {e}", self.path.display()))?;+ Ok(self.path.file_name().map(|n| n.to_string_lossy().into_owned()))+ }+}diff --git a/systems/layers/src/lib.rs b/systems/layers/src/lib.rsnew file mode 100644index 00000000..f003d4d7--- /dev/null+++ b/systems/layers/src/lib.rs@@ -0,0 +1,102 @@+//! The layer pass (docs/review.feature R2b, R2c): which layer each pixel of a frame shows, so raea's player can select+//! any layer (a 3D part, an element, a text, an image) by where it is clicked. A layer is a stamped thing (engine/bundle+//! stamp.rs): its key is where its JSX is written, its place in a list and the uses of the edit's components it was+//! drawn in (`key_of`). Each frame gives a quarter-size mask of layer indices (mask px (x, y) is frame px (4x+2,+//! 4y+2)); `Recorder` keeps them with the table of layers and writes NAME.layers (file.rs).++mod file;+#[cfg(feature = "page")]+mod page;+#[cfg(feature = "page")]+mod scene;++pub use file::Recorder;+#[cfg(feature = "page")]+pub use page::page_ids;++use std::cell::RefCell;+use std::path::PathBuf;++/// "file:line:col[#index]|use|use…": a stamped element or part's key from its props, `data-raea-loc`,+/// `#data-raea-idx` when it has one, then `|data-raea-use` when it was drawn inside the edit's components. None for an+/// unstamped one.+pub fn key_of(loc: Option<&str>, idx: Option<&str>, uses: Option<&str>) -> Option<String> {+ let loc = loc.filter(|l| !l.is_empty())?;+ let mut k = loc.to_string();+ if let Some(i) = idx.filter(|i| !i.is_empty()) {+ k.push('#');+ k.push_str(i);+ }+ if let Some(u) = uses.filter(|u| !u.is_empty()) {+ k.push('|');+ k.push_str(u);+ }+ Some(k)+}++/// One layer of the table: what NAME.layers' header lists for it.+#[derive(Clone, Debug, PartialEq)]+pub struct Layer {+ pub key: String,+ /// mesh | element | text | image | video | group+ pub kind: &'static str,+ pub name: String,+ /// the key of the nearest stamped thing it is inside+ pub parent: Option<String>,+ pub loc: String,+ pub uses: Vec<String>,+ /// its .map()'s key+ pub index: Option<String>,+ /// an image or video's source+ pub src: Option<String>,+}++thread_local! {+ /// `raea render --layers`: the render's recorder (one render per thread)+ static ON: RefCell<Option<Recorder>> = const { RefCell::new(None) };+}++/// With `on` (`raea render --layers`), layers recorded from now on for the export `out` of `tsx`, written by `finish`+/// (path_for); off otherwise. The render.json beside the layers that names them, when on.+pub fn start(on: bool, out: &std::path::Path, tsx: &std::path::Path) -> Option<PathBuf> {+ let path = on.then(|| path_for(out, tsx));+ // a folder of frames is no video: its name stands for it+ let video = out.file_name().unwrap_or_default().to_string_lossy().into_owned();+ ON.with(|r| *r.borrow_mut() = path.clone().map(|p| Recorder::new(p, video)));+ path.map(|p| p.with_extension("render.json"))+}++/// Whether this render records its layers.+pub fn on() -> bool {+ ON.with(|r| r.borrow().is_some())+}++/// The recorder, when on.+pub fn with<T>(f: impl FnOnce(&mut Recorder) -> T) -> Option<T> {+ ON.with(|r| r.borrow_mut().as_mut().map(f))+}++/// NAME.layers written at `fps`, the recorder stopped: the file's name, beside render.json, for its "layers". None when+/// off or nothing was recorded.+pub fn finish(fps: f64) -> Option<String> {+ let rec = ON.with(|r| r.borrow_mut().take())?;+ match rec.write(fps) {+ Ok(name) => name,+ Err(e) => {+ eprintln!("raea: the layers weren't written: {e}");+ None+ }+ }+}++/// The NAME.layers beside an export `out`: OUT.layers for a video or still, DIR/NAME.layers for a folder of frames+/// (NAME the composition's).+pub fn path_for(out: &std::path::Path, tsx: &std::path::Path) -> PathBuf {+ match out.extension() {+ Some(_) => out.with_extension("layers"),+ None => out.join(tsx.file_stem().unwrap_or_default()).with_extension("layers"),+ }+}++#[cfg(test)]+mod tests;diff --git a/systems/layers/src/page.rs b/systems/layers/src/page.rsnew file mode 100644index 00000000..b4908cbf--- /dev/null+++ b/systems/layers/src/page.rs@@ -0,0 +1,59 @@+//! The page's half of the layer pass: every node's layer (the nearest stamped element up from it, engine/bundle+//! stamp.rs), the page painted again with those as colours (scene.rs), and the layers it has this frame.++use std::collections::HashMap;++use blitz_dom::{BaseDocument, LocalName, NodeId};++use crate::{Layer, key_of};++/// The page as layer keys: each pixel's (row-major, `w` x `h`; None where no layer shows) by its index in `layers`,+/// and the layers shown or laid out this frame, in document order. `scale`: page px to frame px.+pub fn page_ids(doc: &mut BaseDocument, scale: f64, w: u32, h: u32) -> (Vec<u16>, Vec<Layer>) {+ let mut ids: HashMap<NodeId, u16> = HashMap::new();+ let mut layers: Vec<Layer> = Vec::new();+ // (node, the layer it's in, as an index into `layers` plus one)+ let mut stack = vec![(doc.root_node().id, 0u16)];+ while let Some((n, mut at)) = stack.pop() {+ let Some(node) = doc.get_node(n) else { continue };+ if node.is_element() && matches!(node.element_data().map(|e| &*e.name.local), Some("style" | "script" | "head")) {+ continue;+ }+ let attr = |a: &str| node.attr(LocalName::from(a));+ let key = node.is_element().then(|| key_of(attr("data-raea-loc"), attr("data-raea-idx"), attr("data-raea-use"))).flatten();+ if let (Some(key), true) = (key, node.has_boxes() && layers.len() < u16::MAX as usize - 1) {+ let tag = node.element_data().map(|e| e.name.local.to_string()).unwrap_or_default();+ let text = node.children.iter().all(|c| doc.get_node(*c).is_some_and(|c| c.is_text_node())) && !node.text_content().trim().is_empty();+ let (kind, src) = match (tag.as_str(), attr("data-raea-src")) {+ (_, Some(src)) => ("video", Some(src.to_string())),+ ("img", _) => ("image", attr("src").map(str::to_string)),+ _ if text => ("text", None),+ _ => ("element", None),+ };+ let name = match kind {+ "text" => node.text_content().trim().chars().take(40).collect(),+ _ => tag,+ };+ let (loc, rest) = key.split_once('|').map_or((key.as_str(), None), |(l, r)| (l, Some(r)));+ let (loc, index) = loc.split_once('#').map_or((loc, None), |(l, i)| (l, Some(i.to_string())));+ layers.push(Layer {+ kind,+ name,+ parent: at.checked_sub(1).map(|p| layers[p as usize].key.clone()),+ loc: loc.to_string(),+ uses: rest.map(|r| r.split('|').map(str::to_string).collect()).unwrap_or_default(),+ index,+ src,+ key,+ });+ at = layers.len() as u16;+ }+ if at > 0 {+ ids.insert(n, at);+ }+ stack.extend(node.children.iter().rev().map(|c| (*c, at)));+ }+ let mut scene = crate::scene::IdScene::new(w.min(u16::MAX as u32) as u16, h.min(u16::MAX as u32) as u16, &ids);+ blitz_paint::paint_scene(&mut scene, doc, scale, w, h, 0, 0);+ (scene.finish(), layers)+}diff --git a/systems/layers/src/scene.rs b/systems/layers/src/scene.rsnew file mode 100644index 00000000..f76f876c--- /dev/null+++ b/systems/layers/src/scene.rs@@ -0,0 +1,130 @@+//! The ID scene: blitz-paint's calls drawn with the layer index of the node each draws for (blitz_paint::painting) as+//! a flat colour, antialiasing off, so each pixel holds exactly one layer's index: low byte red, high byte green,+//! alpha 255 where something was drawn. Brushes, opacity, blends and filters are not drawn; clips are. A node in no+//! layer draws index 0, so it still covers the layers under it.++use std::collections::HashMap;+use std::sync::Arc;++use anyrender::{Glyph, NormalizedCoord, PaintRef, PaintScene, RenderContext};+use blitz_dom::NodeId;+use vello_cpu::kurbo::{Affine, BezPath, Rect, Shape, Stroke};+use vello_cpu::peniko::{BlendMode, Color, Fill, FontData, StyleRef};+use vello_cpu::{PaintType, Pixmap, Resources};++/// a pixel more than this covered (of 255) is drawn whole, a less covered one not at all: about where an edge changes+/// the picture visibly (bench/layers/oracle.sh counts a change past 10 of 255)+const COVERED: u8 = 12;+const TOLERANCE: f64 = 0.1;++pub(crate) struct IdScene<'a> {+ ctx: vello_cpu::RenderContext,+ resources: Resources,+ /// each node's layer index (nodes not here: 0)+ ids: &'a HashMap<NodeId, u16>,+}++impl<'a> IdScene<'a> {+ pub(crate) fn new(w: u16, h: u16, ids: &'a HashMap<NodeId, u16>) -> Self {+ let mut ctx = vello_cpu::RenderContext::new(w, h);+ ctx.set_aliasing_threshold(Some(COVERED));+ IdScene { ctx, resources: Resources::new(), ids }+ }++ /// Each pixel's layer index, row-major.+ pub(crate) fn finish(mut self) -> Vec<u16> {+ self.ctx.flush();+ let mut px = Pixmap::new(self.ctx.width(), self.ctx.height());+ self.ctx.render(&mut px, &mut self.resources);+ px.data().iter().map(|p| if p.a == 0 { 0 } else { p.r as u16 | (p.g as u16) << 8 }).collect()+ }++ /// Ready to draw for the node being painted, at `transform`: false when its brush draws nothing.+ fn brush(&mut self, paint: PaintRef<'_>, transform: Affine) -> bool {+ if let PaintRef::Solid(c) = paint {+ if c.components[3] <= 0.0 {+ return false;+ }+ }+ let id = blitz_paint::painting().and_then(|n| self.ids.get(&n)).copied().unwrap_or(0);+ self.ctx.set_transform(transform);+ self.ctx.reset_paint_transform();+ self.ctx.set_paint(PaintType::Solid(Color::from_rgba8((id & 0xff) as u8, (id >> 8) as u8, 0, 255)));+ true+ }+}++impl RenderContext for IdScene<'_> {}++impl PaintScene for IdScene<'_> {+ fn reset(&mut self) {+ self.ctx.reset();+ }++ fn push_layer(&mut self, fill: Fill, _blend: impl Into<BlendMode>, alpha: f32, transform: Affine, clip: &impl Shape, _filter: Option<Arc<anyrender::Filter>>, _backdrop: Option<Arc<anyrender::Filter>>) {+ // a layer drawn at no opacity shows nothing of its content+ if alpha <= 0.0 {+ return self.push_clip_layer(Fill::NonZero, Affine::IDENTITY, &Rect::ZERO);+ }+ self.push_clip_layer(fill, transform, clip);+ }++ fn push_clip_layer(&mut self, fill: Fill, transform: Affine, clip: &impl Shape) {+ self.ctx.set_transform(transform);+ self.ctx.set_fill_rule(fill);+ self.ctx.push_clip_layer(&clip.into_path(TOLERANCE));+ }++ fn pop_layer(&mut self) {+ self.ctx.pop_layer();+ }++ fn stroke<'b>(&mut self, style: &Stroke, transform: Affine, brush: impl Into<PaintRef<'b>>, _bt: Option<Affine>, shape: &impl Shape) {+ if self.brush(brush.into(), transform) {+ self.ctx.set_stroke(style.clone());+ self.ctx.stroke_path(&shape.into_path(TOLERANCE));+ }+ }++ fn fill<'b>(&mut self, style: Fill, transform: Affine, brush: impl Into<PaintRef<'b>>, _bt: Option<Affine>, shape: &impl Shape) {+ if self.brush(brush.into(), transform) {+ self.ctx.set_fill_rule(style);+ let path: BezPath = shape.into_path(TOLERANCE);+ self.ctx.fill_path(&path);+ }+ }++ fn draw_glyphs<'b, 's: 'b>(+ &'s mut self,+ font: &'b FontData,+ font_size: f32,+ hint: bool,+ coords: &'b [NormalizedCoord],+ embolden: vello_cpu::kurbo::Vec2,+ style: impl Into<StyleRef<'b>>,+ brush: impl Into<PaintRef<'b>>,+ brush_alpha: f32,+ transform: Affine,+ glyph_transform: Option<Affine>,+ glyphs: impl Iterator<Item = Glyph> + Clone,+ ) {+ if brush_alpha <= 0.0 || !self.brush(brush.into(), transform) {+ return;+ }+ let glyphs = glyphs.map(|g| vello_cpu::Glyph { id: g.id, x: g.x, y: g.y });+ let run = |ctx: &'s mut vello_cpu::RenderContext, res: &'s mut Resources| ctx.glyph_run(res, font).font_size(font_size).hint(hint).normalized_coords(coords).glyph_transform(glyph_transform.unwrap_or_default()).font_embolden(glifo::FontEmbolden::new(vello_cpu::kurbo::Diagonal2::new(embolden.x, embolden.y)));+ match style.into() {+ StyleRef::Fill(fill) => {+ self.ctx.set_fill_rule(fill);+ run(&mut self.ctx, &mut self.resources).fill_glyphs(glyphs);+ }+ StyleRef::Stroke(stroke) => {+ self.ctx.set_stroke(stroke.clone());+ run(&mut self.ctx, &mut self.resources).stroke_glyphs(glyphs);+ }+ }+ }++ /// a shadow is not its element's: the layer under it shows there+ fn draw_box_shadow(&mut self, _transform: Affine, _rect: Rect, _brush: Color, _radius: f64, _std_dev: f64) {}+}diff --git a/systems/layers/src/tests.rs b/systems/layers/src/tests.rsnew file mode 100644index 00000000..80898a0a--- /dev/null+++ b/systems/layers/src/tests.rs@@ -0,0 +1,41 @@+use super::*;++fn layer(key: &str, kind: &'static str) -> Layer {+ Layer { key: key.into(), kind, name: kind.into(), parent: None, loc: key.into(), uses: vec![], index: None, src: None }+}++#[test]+fn a_key_is_the_stamp_its_place_and_its_uses() {+ assert_eq!(key_of(Some("a.tsx:3:5"), None, None).as_deref(), Some("a.tsx:3:5"));+ assert_eq!(key_of(Some("card.tsx:2:10"), Some("2"), Some("comp.tsx:6:27#2")).as_deref(), Some("card.tsx:2:10#2|comp.tsx:6:27#2"));+ assert_eq!(key_of(None, Some("2"), Some("x")), None);+}++#[test]+fn masks_sample_each_fourth_pixel_and_keys_keep_their_index_across_frames() {+ let mut r = Recorder::new("x.layers".into(), "x.mp4".into());+ // 8x4: left half layer a, right half b; the mask is 2x1, sampled at x = 2 and 6+ let px: Vec<u16> = (0..32).map(|i| if i % 8 < 4 { 1 } else { 2 }).collect();+ r.frame(0, 8, 4, &px, &[layer("a", "element"), layer("b", "text")]);+ // next frame b comes first in the list and a is gone: b keeps value 2+ let px2: Vec<u16> = (0..32).map(|i| if i % 8 < 4 { 0 } else { 1 }).collect();+ r.frame(1, 8, 4, &px2, &[layer("b", "text")]);+ r.frame(2, 8, 4, &px2, &[layer("b", "text")]);+ let b = r.bytes(30.0);+ assert_eq!(&b[..8], b"RAEALAYR");+ let n = u32::from_le_bytes(b[8..12].try_into().unwrap()) as usize;+ let head: serde_json::Value = serde_json::from_slice(&b[12..12 + n]).unwrap();+ assert_eq!(head["mask"], serde_json::json!({"w": 2, "h": 1, "scale": 4}));+ assert_eq!(head["layers"][1]["frames"], serde_json::json!([0, 2]));+ assert_eq!(head["layers"][0]["frames"], serde_json::json!([0, 0]));+ assert!(head.get("at").is_none());+ let words: Vec<u16> = b[12 + n..].chunks(2).map(|c| u16::from_le_bytes([c[0], c[1]])).collect();+ // frame 0: 2 runs (1,1),(2,1); frame 1: (0,1),(2,1); frame 2: the same as frame 1+ assert_eq!(words, vec![2, 0, 1, 1, 2, 1, 2, 0, 0, 1, 2, 1, 0, 0]);+}++#[test]+fn a_folder_of_frames_gets_the_compositions_name() {+ assert_eq!(path_for(std::path::Path::new("o/film.mp4"), std::path::Path::new("src/promo.tsx")), PathBuf::from("o/film.layers"));+ assert_eq!(path_for(std::path::Path::new("o/frames"), std::path::Path::new("src/promo.tsx")), PathBuf::from("o/frames/promo.layers"));+}diff --git a/vendor/blitz-paint/src/lib.rs b/vendor/blitz-paint/src/lib.rsindex 5a91135a..952b58cf 100644--- a/vendor/blitz-paint/src/lib.rs+++ b/vendor/blitz-paint/src/lib.rs@@ -36,6 +36,32 @@ pub struct TilePattern {pub tile: kurbo::Size,}+/// raea: the node whose box or text the paint calls going out now draw (a glyph run, the element its text is in), for+/// a painter that tells nodes apart: the layer pass's ID scene (raea-sys-layers, docs/review.feature R2b). None outside+/// paint_scene.+pub fn painting() -> Option<NodeId> {+ PAINTING.with(|p| Some(p.get()).filter(|n| *n != 0).map(NodeId::from_u64))+}++thread_local! {+ static PAINTING: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };+}++/// raea: `painting` is `node` until this is dropped, then what it was.+pub(crate) struct Painting(u64);++impl Painting {+ pub(crate) fn enter(node: NodeId) -> Painting {+ Painting(PAINTING.with(|p| p.replace(node.as_u64())))+ }+}++impl Drop for Painting {+ fn drop(&mut self) {+ PAINTING.with(|p| p.set(self.0));+ }+}+/// The default color for text selection highlightsconst SELECTION_COLOR: Color = Color::from_rgb8(180, 213, 255);diff --git a/vendor/blitz-paint/src/render.rs b/vendor/blitz-paint/src/render.rsindex 350a5f9b..5a7d211c 100644--- a/vendor/blitz-paint/src/render.rs+++ b/vendor/blitz-paint/src/render.rs@@ -730,6 +730,7 @@ impl<'dom, 'a> BlitzDomPainter<'dom, 'a> {clip_rect: Rect,) {let node = &self.dom.as_ref().tree()[node_id];+ let _painting = crate::Painting::enter(node_id);// raea: a plane of a 3D rendering context is drawn by its root, sorted by depth, not in paint order (and a// projective one again, inside its warp layer)diff --git a/vendor/blitz-paint/src/text.rs b/vendor/blitz-paint/src/text.rsindex 98efdba3..75d46f2c 100644--- a/vendor/blitz-paint/src/text.rs+++ b/vendor/blitz-paint/src/text.rs@@ -889,6 +889,7 @@ pub(crate) fn stroke_text<'a>(let font_size = run.font_size();let metrics = run.font_metrics();let style = glyph_run.style();+ let _painting = crate::Painting::enter(style.brush.id);let synthesis = run.synthesis();// raea: a bevy_ui <Text> draws its glyphs upright, as bevy_text does: it takes no synthetic italic's// skew from parley (an Italic or Oblique run of a face with no slant drawn as its upright face)