Compare commits

..
Author SHA1 Message Date
shinyobjectz 8ecf1b8b1e A playable carries Bevy's world as wasm for a game whose rules are raea/ecs systems
PA12: runtime/ecs builds as a cdylib for wasm32 (src/wasm.rs; sdk/playable/ecs/build.sh: 253 KB, 105 KB gzipped,
no imports) into sdk/playable/src/host/ecs.wasm, with the hash of what it was built from beside it, which apps/playable's
test checks. The lint's walk sees a World made; the export carries the module and its entry loads host/ecs.ts before
the game, so raea/ecs's calls (native.ts ecsCall: the engine's bridge, else the page's) reach Bevy's tables in the page
as they do in the engine. A page that can't make the module keeps raea/ecs's TypeScript tables.

World.copy() is a game's next state (copied with its systems, stepped on its own), and a native store nothing holds
frees its world, so a game's let-go states don't keep theirs. examples/playables/star-catch.tsx is a game whose rules
are three systems on a World; conformance/ecs-wasm.test.ts runs one world's life on the wasm and on the TypeScript
tables and finds them equal. The playable guide shows the pattern.
2026-12-03 11:39:23 -08:00
47 changed files with 791 additions and 31545 deletions

No files matched your search

+1 -2
View File
@@ -213,8 +213,7 @@ pub(crate) fn contrast(video: &str, runs: &[Run], w: f64, h: f64, probe: &Probe,
continue;
}
// the same measure `raea world` joins to a text from its render (raea-sys-measure, DR2)
let color = r.middle_color();
let ratio = if crate::read::native() { crate::read::contrast(video, t, crop, color) } else { raea_sys_measure::contrast(std::path::Path::new(video), t, crop, color) };
let ratio = if crate::read::native() { crate::read::contrast(video, t, crop, &r.color) } else { raea_sys_measure::contrast(std::path::Path::new(video), t, crop, &r.color) };
let Some(ratio) = ratio else { continue };
measured += 1;
if ratio < 3.0 {
+5 -6
View File
@@ -67,8 +67,8 @@ fn taste_checks_hold_text_to_the_persons_line() {
Taste { form: "text-above", value: 62.0, line: "Captions sit clear of the bottom.".into() },
Taste { form: "text-hold", value: 2.0, line: "Text holds two seconds".into() },
]);
let low = Run { text: "Render anything.".into(), from: 1.0, to: 4.0, box_: [800.0, 800.0, 300.0, 60.0], boxes: vec![[800.0, 800.0, 300.0, 60.0]], colors: vec![], 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]], colors: vec![], color: String::new(), size: 48.0 };
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![]);
taste_text(&rules, &[low, high], 1920.0, 1080.0, &mut issues, &mut passed);
let says: Vec<_> = issues.iter().map(|i| (i.rule, i.p, i.at)).collect();
@@ -267,7 +267,7 @@ fn typing_is_one_run_and_cues_find_their_word() {
#[test]
fn a_caption_is_timed_from_the_first_word_it_shows() {
let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 1.0, box_: [0.0; 4], boxes: vec![], colors: vec![], color: String::new(), size: 48.0 };
let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 1.0, box_: [0.0; 4], boxes: vec![], color: String::new(), size: 48.0 };
let words: Vec<Word> = [("half", 12.2), ("of", 12.66), ("the", 12.8), ("spend", 12.96)].iter().map(|(t, s)| Word { text: (*t).into(), start: *s, end: *s }).collect();
let (mut issues, mut passed) = (vec![], vec![]);
// on with "of": on time, though "spend" (its first word of weight) is said 0.3 s later
@@ -335,7 +335,7 @@ fn safe_area_tests_the_letters_not_the_box() {
#[test]
fn a_card_sharing_one_word_with_another_line_isnt_held_to_it() {
let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 2.0, box_: [0.0; 4], boxes: vec![], colors: vec![], color: String::new(), size: 48.0 };
let run = |text: &str, from: f64| Run { text: text.into(), from, to: from + 2.0, box_: [0.0; 4], boxes: vec![], color: String::new(), size: 48.0 };
let said = |ws: &[(&str, f64)]| ws.iter().map(|(t, s)| Word { text: (*t).into(), start: *s, end: *s }).collect::<Vec<Word>>();
let words = said(&[("at", 37.9), ("wirestock", 38.2), ("i", 38.9), ("worked", 39.0), ("on", 39.2), ("a", 39.3), ("sora", 39.5), ("campaign", 40.2)]);
let (mut issues, mut passed) = (vec![], vec![]);
@@ -425,11 +425,10 @@ fn things_found_are_findings_and_an_unknown_rule_is_not() {
#[test]
fn a_moving_text_is_read_where_it_is() {
let ink = |f: usize| [56.7 + 4.0 * f as f64, 1000.0, 26.7, 40.0];
let run = Run { text: "E".into(), from: 0.0, to: 8.0, box_: [996.0, 1000.0, 60.0, 40.0], boxes: (0..240).map(ink).collect(), colors: vec![], color: String::new(), size: 40.0 };
let run = Run { text: "E".into(), from: 0.0, to: 8.0, box_: [996.0, 1000.0, 60.0, 40.0], boxes: (0..240).map(ink).collect(), color: String::new(), size: 40.0 };
let (t, b) = run.middle(30.0);
assert_eq!(t, 4.0);
assert!((b[0] - 520.0).abs() < 1e-9 && b[1..] == [1000.0, 60.0, 40.0], "{b:?}");
let still = Run { boxes: vec![ink(0); 240], box_: [40.0, 1000.0, 60.0, 40.0], ..run };
assert_eq!(still.middle(30.0), (4.0, [40.0, 1000.0, 60.0, 40.0]));
}
+2 -36
View File
@@ -43,10 +43,6 @@ pub struct Run {
/// a full-width box is nowhere near x = 0, #89): a text the camera carries (a sign on a panning street) moves
/// through the frame's edges and zones, which only counts against it when no frame shows it clear
pub boxes: Vec<[f64; 4]>,
/// its colour on each of those frames, beside `boxes`: a text can change colour while it reads the same (a step
/// chip lighting up, grey on dark to dark on yellow), and its contrast is its colour on the frame it's measured at
pub colors: Vec<String>,
/// its colour on its last frame
pub color: String,
pub size: f64,
}
@@ -61,15 +57,6 @@ impl Run {
let (at, [x, y, w, h]) = (self.boxes[n / 2], self.box_);
(self.to - (n - n / 2) as f64 / fps, [x + at[0] - last[0], y + at[1] - last[1], w, h])
}
/// Its colour on the frame `middle` measures: the one it had there, not the one it ended with.
pub fn middle_color(&self) -> &str {
let n = self.boxes.len();
match self.colors.get(n / 2) {
Some(c) if n > 1 && self.colors.len() == n => c,
_ => &self.color,
}
}
}
/// The brand kit the cut was styled from (brand/ at or above the manifest's or the video's folder, as render finds
@@ -127,21 +114,18 @@ pub fn text_runs(manifest: &Value) -> Vec<Run> {
});
let mut r = match found {
Some(i) => open.remove(i),
None => Run { text: text.clone(), from: t, to: t, box_: b, boxes: Vec::new(), colors: Vec::new(), color: String::new(), size: 0.0 },
None => Run { text: text.clone(), from: t, to: t, box_: b, boxes: Vec::new(), color: String::new(), size: 0.0 },
};
let color = x["color"].as_str().unwrap_or("rgb(255, 255, 255)").to_string();
if text.len() > r.text.len() {
r.boxes.clear();
r.colors.clear();
}
if text.len() >= r.text.len() {
r.text = text;
r.box_ = b;
r.boxes.push(ink.unwrap_or(b));
r.colors.push(color.clone());
}
r.to = t + 1.0 / fps;
r.color = color;
r.color = x["color"].as_str().unwrap_or("rgb(255, 255, 255)").to_string();
r.size = x["size"].as_f64().unwrap_or(0.0);
next.push(r);
}
@@ -310,21 +294,3 @@ pub fn cues(runs: &[Run], words: &[Word], issues: &mut Vec<Issue>, passed: &mut
passed.push(format!("cues: {checked} texts land on their words"));
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn a_text_that_lights_up_is_measured_in_its_colour_at_the_middle() {
// a step chip: grey on dark for six frames, then dark on yellow for four (the same words)
let m = json!({"fps": 10.0, "frames": (0..10).map(|f| json!({"frame": f, "text": [
{"text": "03 MAP", "box": [500, 120, 130, 52], "size": 23, "color": if f < 6 { "rgb(169, 169, 174)" } else { "rgb(10, 10, 11)" }}
]})).collect::<Vec<_>>()});
let runs = text_runs(&m);
assert_eq!(runs.len(), 1);
assert_eq!(runs[0].color, "rgb(10, 10, 11)", "its last colour");
assert_eq!(runs[0].middle_color(), "rgb(169, 169, 174)", "the frame contrast measures is still grey");
}
}
+8 -17
View File
@@ -60,7 +60,7 @@ enum Sounds {
/// What a page carries beside the game and the host, as the lint found the game needs it
#[derive(Clone, Copy, PartialEq, Debug)]
struct Carry {
/// a 3D drawer (Bevy's programs, its scene read by three.js), for a game with a 3D kind (PA11, PA15)
/// three.js, for a game with a 3D kind (PA15)
with_3d: bool,
sounds: Sounds,
/// Bevy's world as wasm, for a game that makes a raea/ecs World (PA12)
@@ -68,15 +68,15 @@ struct Carry {
}
/// The bundle's entry: Bevy's world first for a game on raea/ecs (PA12: a World made as the game's module loads is
/// already Bevy's), the game, then the host started with Bevy's PBR programs as its 3D drawer (PA11) only for a game
/// with 3D (PA15: a 2D game's page carries no renderer) and a sound player only for a game with sound, Tone.js in it only for a
/// already Bevy's), the game, then the host started with three.js as its 3D drawer only for a game with 3D (PA15: a
/// 2D game's page carries no renderer) and a sound player only for a game with sound, Tone.js in it only for a
/// raea/tone graph (PA6)
fn entry(game: &Path, host: &Path, carry: Carry) -> String {
let Carry { with_3d, sounds, ecs } = carry;
let first = if ecs { format!("import {:?};\n", spec(&host.join("ecs.ts"))) } else { String::new() };
let mut e = format!("{first}import {:?};\nimport {{ start }} from {:?};\n", spec(game), spec(&host.join("main.tsx")));
if with_3d {
e.push_str(&format!("import {{ bevy3d }} from {:?};\n", spec(&host.join("bevy.ts"))));
e.push_str(&format!("import {{ three3d }} from {:?};\n", spec(&host.join("three.ts"))));
}
if sounds != Sounds::None {
e.push_str(&format!("import {{ sound }} from {:?};\n", spec(&host.join("sound.ts"))));
@@ -84,9 +84,9 @@ fn entry(game: &Path, host: &Path, carry: Carry) -> String {
if sounds == Sounds::Tone {
e.push_str(&format!("import {{ tone }} from {:?};\n", spec(&host.join("tone.ts"))));
}
let d3 = if with_3d { "bevy3d" } else { "undefined" };
let d3 = if with_3d { "three3d" } else { "undefined" };
e.push_str(&match sounds {
Sounds::None if with_3d => "start(bevy3d);\n".into(),
Sounds::None if with_3d => "start(three3d);\n".into(),
Sounds::None => "start();\n".into(),
Sounds::Media => format!("start({d3}, sound());\n"),
Sounds::Tone => format!("start({d3}, sound(tone));\n"),
@@ -217,7 +217,7 @@ mod tests {
#[test]
fn a_3d_game_starts_with_three() {
let e = e(true, Sounds::None, false);
assert!(e.contains("bevy3d } from \"/h/host/bevy.ts\"") && e.contains("start(bevy3d);"), "{e}");
assert!(e.contains("three3d } from \"/h/host/three.ts\"") && e.contains("start(three3d);"), "{e}");
}
#[test]
@@ -225,7 +225,7 @@ mod tests {
let media = e(false, Sounds::Media, false);
assert!(media.contains("start(undefined, sound());") && !media.contains("tone"), "{media}");
let tone = e(true, Sounds::Tone, false);
assert!(tone.contains("tone } from \"/h/host/tone.ts\"") && tone.contains("start(bevy3d, sound(tone));"), "{tone}");
assert!(tone.contains("tone } from \"/h/host/tone.ts\"") && tone.contains("start(three3d, sound(tone));"), "{tone}");
}
#[test]
@@ -242,13 +242,4 @@ mod tests {
let built = std::fs::read_to_string(root.join("sdk/playable/src/host/ecs.wasm.from")).unwrap_or_default();
assert_eq!(built.trim(), now, "runtime/ecs changed since ecs.wasm was built: bash sdk/playable/ecs/build.sh");
}
#[test]
fn the_carried_bevy_programs_are_made_from_bevys_shaders_as_they_are() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
let out = std::process::Command::new("bash").arg(root.join("sdk/playable/bevy/from.sh")).output().expect("bash");
let now = String::from_utf8_lossy(&out.stdout).trim().to_string();
let built = std::fs::read_to_string(root.join("sdk/playable/src/host/bevy/programs.from")).unwrap_or_default();
assert_eq!(built.trim(), now, "Bevy's shaders or tools/bevy-glsl changed since programs.ts was made: bash sdk/playable/bevy/build.sh");
}
}
+1 -1
View File
@@ -83,7 +83,7 @@ pub struct CutPlan {
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(optional_fields)]
#[ts(rename = "CutBeat")]
#[ts(rename = "Beat")]
pub struct Beat {
/// where it starts, in seconds from the cut's start (0 for the first)
pub at: f64,
+3 -3
View File
@@ -54,11 +54,11 @@ pub fn declarations() -> String {
/// The goal's declarations (what the work is held to: goal.rs, cut.rs, playable.rs, rules.rs): sdk/raea/src/brief-goal.gen.ts
pub fn goal_declarations() -> String {
let cfg = Config::new();
// a cut's beats are its own (cut.rs Beat, CutBeat in TypeScript: feel, story, asl, tempo), not a script's
let mut out = vec!["// Generated from raea-core-brief (core/brief) by its `goal_declarations`; edit the Rust, not this.".to_string()];
// a cut's beats are a script's (script.rs Beat)
let mut out = vec!["// Generated from raea-core-brief (core/brief) by its `goal_declarations`; edit the Rust, not this.\nimport type { Beat } from \"./brief.gen\";".to_string()];
out.extend(decls!(cfg;
goal::Goal, goal::Kind, goal::Source, goal::DialValue, goal::Dial, goal::Route, goal::Origin, goal::Pick, goal::Object, goal::Shot, goal::Goals,
cut::Cut, cut::Quoted<u32>, cut::CutPlan, cut::Beat, cut::Phrase, cut::Cta, cut::Open,
cut::Cut, cut::Quoted<u32>, cut::CutPlan, cut::Phrase, cut::Cta, cut::Open,
playable::Playable, playable::Orientation,
rules::Rule,
));
+4 -10
View File
@@ -13,12 +13,9 @@ every project to import as `@shared/components/NAME`. `raea part` is the old nam
Beside raea's own sets is the library: several hundred open-source components (text reveals, counters, charts,
transitions, product-screen demos, game HUDs and more), sorted by what they're for rather than who made them.
`raea make component list` ends with its categories; `list WORDS` searches it by a category (`text`), a category and
type (`text/reveal`), a name or the name it had upstream, the phrases people ask for it with (`"chat input"`,
`composer`, `"lower third"`, `template`), or words in what it does (`"count up"`). `show NAME` tells one in full: what
it draws and how it moves, when to use it and when not, the size and length it was designed at, and each prop with its
type, default and what it does; `--json` gives the same as JSON, for every hit of a `list`. `add NAME` copies the
component into `components/CATEGORY/NAME/`, with the shared helpers it needs under `components/_lib/`. Each file's
first line names the library it came from, and `CREDITS.md` in sdk/raea/library/components holds their licences.
type (`text/reveal`), or words in a name or description (`"count up"`). `add NAME` copies the component into
`components/CATEGORY/NAME/`, with the shared helpers it needs under `components/_lib/`. Each file's first line names
the library it came from, and `CREDITS.md` in sdk/raea/library/components holds their licences.
```sh
raea make component list
@@ -26,8 +23,6 @@ raea make component add captions end-card
raea make component add reel --shared
raea make component list text/reveal
raea make component list count up
raea make component list chat input
raea make component show prompt-send
raea make component add soft-blur-in
```
@@ -36,7 +31,7 @@ raea make component add soft-blur-in
## Usage
```sh
raea make component list [WORDS] [--json] | raea make component show NAME [--json] | raea make component add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; WORDS search the library by use and by how people ask: text/reveal, "count up", "chat input", template; show tells one in full: what it draws, when to use it and when not, its props)
raea make component list [WORDS] | raea make component add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; WORDS search the library by use: text/reveal, "count up")
```
Headless: it needs nothing running and opens no window. Takes any number of arguments besides its flags.
@@ -46,7 +41,6 @@ Headless: it needs nothing running and opens no window. Takes any number of argu
| Flag | Takes | What it does |
| --- | --- | --- |
| `--force` | – | Replace a component's files that are already there. Without it, an existing component is left alone and the command stops. |
| `--json` | – | The library's items as JSON (`list`: every hit, best first; `show`: the one), each with its props, when to use it and when not, and the phrases it's asked for with. |
| `--shared` | – | Copy into the workspace's `shared/components/` instead, where every project in the workspace imports it as `/components/NAME`. |
<!-- generated:end -->
+2 -3
View File
@@ -20,9 +20,8 @@ import the file instead), URLs and network calls, modules that need the native e
kinds the playable's renderer doesn't draw. It notes a game with only one orientation, and one that never imports
`raea/playable` (`<EndCard>`, `<InstallButton>`, `install()`) to open the store itself.
The 3D is drawn by Bevy's own PBR shaders, translated to WebGL2 when raea is built, with Bevy's light units,
shadows, fog and TonyMcMapface tone mapping. three.js reads the page's 3D parts into a scene for them, so it comes from
the project (`raea add [email protected]`). A game with no 3D ships without either.
The 3D is drawn by three.js on raea's scene contract, with Bevy's light units and tone mapping. It comes from the
project (`raea add [email protected]`).
<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->
+1 -4
View File
@@ -38,7 +38,6 @@ comment read as asks is a note: it closes when the person retires it, and the ap
raea show out/look-1.png out/look-2.png out/look-3.png --ask "Which of these three?"
raea show out/cut.mp4 --replaces i-show-2f9c
raea show --question "Warmer or cooler grade?" --choice Warmer --choice Cooler
raea show --choose "Warm grade" out/warm-1.png out/warm-2.png --choose "Cool grade" out/cool-1.png --recommend 2
raea show --question "Which opening?" --choice Slam --preview out/slam.mp4 --choice Drift --preview out/drift.mp4 \
--question "Narrator speed?" --preview voice/take.mp3 --choice "As is" --choice Faster
raea show --on i-show-2f9c --working c-3 --sub "grade pass"
@@ -52,7 +51,7 @@ raea show out/cut-v2.mp4 --replaces i-show-2f9c --done c-3 --done c-4 --note "Wa
## Usage
```sh
raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] [--playable] [--label LABEL] [--detail PARAGRAPH] [--labels FILE.json] [--despite CHECK WHY] | raea show --choose LABEL FILE... --choose LABEL FILE... [--recommend N] | raea show --question Q --choice A --choice B [STILL...] | raea show [--title T] --question Q [--preview FILE] --choice A [--preview FILE] --choice B ... [--question Q2] ... | raea show --on ITEM [--working ID] [--ask TEXT] [--status S] [--states S1,S2] [--sign N --clip FILE --render HASH] [--done ID] [--note LINE] [--sub NAME] (shown in the raea app as an item the person can use and answer, posted quietly with a notice, the window left where they are unless --open: stills (several, a storyboard), a video, a sound, a NAME.script.ts or .md, a .tsx (an interactive artifact; a project's composition opens in its editor), a playable ad's NAME-preview.html (played in a phone, sandboxed; --playable exports a game's .tsx with raea playable and shows that), or questions, all of them one item; --choose LABEL FILE... once per option (2 to 6) for the person to pick one, --recommend N the one you would (nothing is picked for them), their pick back as {"kind":"answer","choice":LABEL}; --label "PLACE TAG" a label beside the picture, never on it, that points at PLACE (x0,y0,x1,y1 or x,y in its 0-1, then #N the Nth file, @T or @T-TO a film's seconds, or part=KEY a scene's part; the tag the rest), --detail the paragraph of the --label before it, --labels a JSON list of them as feed_post takes them, and a sheet raea media sheet made comes labelled; each question and choice with a --preview to play or read while answering (a still, a video, a sound, a script or .md; after a --choice that choice's, else the question's); what they send comes to ~/.raea/inbox/INBOX.jsonl; their edit comments are tasks: --working ID as you start one (each --ask with it one ask you read it as, for the person to correct; --status and --states where the note and each ask stand: to restate, to check, failing, to sign, passing, signed; --sign N --clip FILE --render HASH a clip under ask N for them to sign; a note closes when they retire it, never with --done), --done ID when it's settled, or with the version that settles it, FILE --replaces ITEM --done ID; never open media in Preview while the app is installed)
raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] [--playable] [--label LABEL] [--detail PARAGRAPH] [--labels FILE.json] [--despite CHECK WHY] | raea show --question Q --choice A --choice B [STILL...] | raea show [--title T] --question Q [--preview FILE] --choice A [--preview FILE] --choice B ... [--question Q2] ... | raea show --on ITEM [--working ID] [--ask TEXT] [--status S] [--states S1,S2] [--sign N --clip FILE --render HASH] [--done ID] [--note LINE] [--sub NAME] (shown in the raea app as an item the person can use and answer, posted quietly with a notice, the window left where they are unless --open: stills (several, a storyboard), a video, a sound, a NAME.script.ts or .md, a .tsx (an interactive artifact; a project's composition opens in its editor), a playable ad's NAME-preview.html (played in a phone, sandboxed; --playable exports a game's .tsx with raea playable and shows that), or questions, all of them one item; --label "PLACE TAG" a label beside the picture, never on it, that points at PLACE (x0,y0,x1,y1 or x,y in its 0-1, then #N the Nth file, @T or @T-TO a film's seconds, or part=KEY a scene's part; the tag the rest), --detail the paragraph of the --label before it, --labels a JSON list of them as feed_post takes them, and a sheet raea media sheet made comes labelled; each question and choice with a --preview to play or read while answering (a still, a video, a sound, a script or .md; after a --choice that choice's, else the question's); what they send comes to ~/.raea/inbox/INBOX.jsonl; their edit comments are tasks: --working ID as you start one (each --ask with it one ask you read it as, for the person to correct; --status and --states where the note and each ask stand: to restate, to check, failing, to sign, passing, signed; --sign N --clip FILE --render HASH a clip under ask N for them to sign; a note closes when they retire it, never with --done), --done ID when it's settled, or with the version that settles it, FILE --replaces ITEM --done ID; never open media in Preview while the app is installed)
```
Needs the raea app's host running on this machine; then waits for a person's click in the raea app (to answer). Takes any number of arguments besides its flags.
@@ -64,7 +63,6 @@ Needs the raea app's host running on this machine; then waits for a person's cli
| `--as` | `NAME` | Who's showing it, as the feed names them (your harness's name when left out: Claude Code, Codex, Gemini). |
| `--ask` | `LINE` | What you want from the person, shown with the item. With `--on` and `--working`: one ask you read the comment as (give it once per ask), shown on the comment for the person to correct. |
| `--choice` | `A` | With `--question`: one answer to pick; give it once per answer. Stills given instead are the choices. |
| `--choose` | `LABEL FILE...` | One option for the person to pick, named, its files after it; give it once per option, 2 to 6. Their pick comes back as `{"kind":"answer","choice":LABEL}`. |
| `--clip` | `FILE` | With `--sign`: the clip the person is to sign, cut from the render (`raea notes check` cuts it). |
| `--despite` | `CHECK WHY` | A check the render still fails, and why it goes to the person anyway; give it once per check. `raea show` refuses a render whose record still holds an error, naming each, and the why is shown on the item. |
| `--detail` | `PARAGRAPH` | The paragraph the viewer opens from the `--label` before it. |
@@ -78,7 +76,6 @@ Needs the raea app's host running on this machine; then waits for a person's cli
| `--preview` | `FILE` | A still, video, sound, script or `.md` the person can play or read while answering. After a `--choice` it is that choice's preview, otherwise the question's. |
| `--project` | `P` | The project to post to: its id, title or `Workspace/project`. The project this folder is in when left out. |
| `--question` | `Q` | Ask the person this, with `--choice` answers or stills to pick from. |
| `--recommend` | `N` | With `--choose`: the option you'd pick, from 1, marked on it. Nothing is picked for the person. |
| `--render` | `HASH` | With `--sign`: the sha256 of the render the clip was cut from, which the person's sign names. |
| `--replaces` | `ITEM` | The item this is the next version of, so the feed shows it as that item's new version. |
| `--role` | `ROLE` | With `--as`: the role shown beside the name. |
+4 -33
View File
@@ -185,7 +185,7 @@ Feature: raea games as playable ads, exported for every ad network from the TSX
curves on the converted units scored Reinhard 14.5, Neutral 21.2, AgX 23.3, none 30.4, ACES 37.9; what is left is
the shading itself (the bricks' side faces a touch darker), PA11's job
@done @needs:PA9
@needs:PA9
Scenario: PA11. Bevy's own shading in the light renderer
Then Bevy's PBR shaders, composed for the pipelines a playable uses, are translated to GLSL ES 3.00 with naga at
export time, and the light renderer draws with them instead of three.js's own materials
@@ -204,35 +204,6 @@ Feature: raea games as playable ads, exported for every ad network from the TSX
View (784 B), Lights (2,176 B), the cluster offsets, index lists and clustered lights (16 KB each, so the host
clusters lights on the CPU as Bevy does on WebGL2), the StandardMaterial (192 B), the Mesh batch and Globals.
That packing, and the shadow passes, are PA11's real work; the shaders themselves come over unchanged
# Status 12-03: built. tools/bevy-glsl composes the three programs with Bevy's own ShaderCache (raea's vendored
# bevy_pbr, bevy_render and bevy_core_pipeline 0.20.0, WebGL2's defs, 10 directional lights, Gaussian shadow
# filtering, MSAA, distance fog, the projection's kind read from the view) and naga 30 translates them;
# sdk/playable/bevy/build.sh writes them into host/bevy/programs.ts (105 KB, 21 KB gzipped) with each block's field offsets and which of Bevy's bindings each
# block and sampler is, and apps/playable's test fails when Bevy's shaders or the translator change and it isn't
# rebuilt. host/bevy.ts replaces three.js's renderer (three.ts and tonemap.ts are gone): it reads raea's three.js
# scene graph (scene.ts) for the parts, geometry and transforms, and fills Bevy's blocks as Bevy's render world
# does (bevy/fill.ts: prepare_view_uniforms, prepare_lights, MeshUniform::new, StandardMaterial's uniform; the
# lights back in Bevy's units through units.ts): reverse Z, one 1x1x1 light cluster packed as Bevy packs it for
# WebGL2, one directional shadow cascade (as Bevy on WebGL2 has) fitted to what the camera sees of the scene,
# point and spot lights, distance fog (Bevy's GpuFog from the scene's Fog: linear from near to far, or
# exponential for a density, as the native engine makes it), a forward pass into half float with 4x MSAA, then
# TonyMcMapface through Bevy's table. A Plane3d is drawn as its one face (Bevy's PlaneMeshBuilder), not as the
# flat Box three.js was given, whose top face three points down. Not drawn yet, each warned once in the
# console: an environment's light, a camera's own <Fog> (Bevy's DistanceFog component), normal maps, transmission, vertex colours, point and
# spot shadows, rect lights, a shadow catcher, a paint look
# Measured on brick-rush against `raea render --frame` (mean difference over the drawn pixels / 255, both pages
# against the same native frames; landscape frame 300 rendered with --despite type-over-part): portrait frame 90
# three.js 6.1 -> Bevy 4.3 (PA10 recorded 5.4), landscape frame 300 9.8 -> 7.7, what is left in landscape mostly
# the page's pulsing hint text. star-catch portrait frame 150: 17.0 -> 15.6 over the frame, 6.7 -> 5.0 over the
# 3D above the hint text. A scene of a floor, six boxes, a ball, a sun with shadows, a point light and a spot
# light (frame 10): perspective portrait 1.3, orthographic landscape 0.8, with linear fog 0.7, with exponential
# fog 0.7. The page: brick-rush 1,889 -> 1,794 KB (three's renderer out, the programs in).
# First frame in a fresh WebKit (served from localhost, to the GPU finishing it, 25 interleaved runs): three.js
# median 131 ms, mean 129.8; Bevy median 131 ms, mean 131.8. The GL work is about 5 ms on both pages; the rest
# is script and the page. Chrome's 4x CPU throttle isn't used (raea doesn't test in Chrome); with every WebKit
# process clamped to the efficiency cores at background priority (taskpolicy -b), 142 and 145 ms over 11 runs.
# brick-rush and star-catch play to their end cards and store taps in WebKit (tools/check.ts) in portrait and
# landscape, with instant and 150 ms taps
@done
Scenario: PA12. Bevy systems in a playable
@@ -274,9 +245,9 @@ Feature: raea games as playable ads, exported for every ad network from the TSX
Scenario: PA15. A 2D playable carries no three.js
Given 11-28's tiles bundle: three.js 924 KB of 1,393 KB, react-dom 178 KB, for a game that draws no 3D
Then the export builds the host without the three.js scene when the lint finds no 3D kind (about 470 KB a page)
# Status 12-03: built. The host asks for its 3D through one interface (host/draw3d.ts); a drawer (three.ts then,
# Bevy's programs in bevy.ts since PA11) draws it, and the export's entry passes it to start() only when the lint
# found a 3D kind, so a 2D game's bundle never imports three.js. Measured (preview page, before -> after, the after with PA8's ~95 KB of Inter):
# Status 12-03: built. The host asks for its 3D through one interface (host/draw3d.ts); three.ts draws it with
# three.js, and the export's entry passes it to start() only when the lint found a 3D kind, so a 2D game's
# bundle never imports three.js. Measured (preview page, before -> after, the after with PA8's ~95 KB of Inter):
# tiles 1,345 -> 378 KB, gates 1,347 -> 380 KB, three 2D brand playables 2,752 -> 1,782, 3,409 -> 2,440 and
# 2,693 -> 1,724 KB; brick-rush (3D, keeps three.js) 1,384 -> 1,478 KB. Each of the six played to its end card
# and its store tap in WebKit (tools/check.ts), with instant taps (TAP_MS=0) and 150 ms taps.
+2 -36
View File
@@ -1,10 +1,9 @@
// The component library (sdk/raea/library/components, catalog.ts): every listed file is there, every relative import
// in it lands on a file of the library, nothing imports another video framework, the search finds by use and by the
// words people ask with, and each item carries what an agent picks by (tools/library-meta.sh writes it).
// in it lands on a file of the library, nothing imports another video framework, and the search finds by use.
import { describe, expect, test } from "bun:test";
import { existsSync, readFileSync } from "node:fs";
import { dirname, join, normalize } from "node:path";
import { listed, searched, shown, terms, type Item } from "../src/catalog";
import { listed, type Item } from "../src/catalog";
const lib = join(import.meta.dir, "../../../sdk/raea/library/components");
const cat = JSON.parse(readFileSync(join(lib, "catalog.json"), "utf8")) as { sources: Record<string, { licence: string }>; items: Item[] };
@@ -46,37 +45,4 @@ describe("the component library", () => {
expect(listed(cat.items, ["count", "up"]).split("\n")[0]).toContain("count");
expect(listed(cat.items, ["zzqx"])).toContain("no component in the library");
});
test("each item says what it draws, when to use it and not, how it's asked for, and its props", () => {
const thin = cat.items.filter((i) => !i.what || !i.use_when?.length || !i.avoid_when?.length || !i.asked_as?.length || !Array.isArray(i.props) || !i.aspect);
expect(thin.map((i) => i.name)).toEqual([]);
// its props are the ones its file declares
const flash = cat.items.find((i) => i.name === "flash-count")!;
expect(flash.props!.find((p) => p.name === "value")).toMatchObject({ type: "number", default: "3600" });
});
test("its words name no other library or its tooling: the components are raea's", () => {
const named = cat.items.flatMap((i) => [i.what ?? "", ...(i.use_when ?? []), ...(i.avoid_when ?? [])].filter((s) => /\b(remotion|remocn|snapcn|snap-cn|shadcn)\b/i.test(s)).map((s) => `${i.name}: ${s}`));
expect(named).toEqual([]);
});
test("search by the words people use: a product's UI, a composer, a chat input, a template, an AI prompt", () => {
const top = (q: string, n = 3) => searched(cat.items, terms([q])).slice(0, n).map((i) => `${i.category}/${i.name}`);
expect(top("claude code").every((n) => /terminal|agent/.test(n))).toBe(true);
expect(top("composer")).toEqual(expect.arrayContaining(["ui/prompt-send"]));
expect(top("chat input", 5)).toEqual(expect.arrayContaining(["ui/input", "ui/prompt-send"]));
expect(top("AI prompt").every((n) => n.startsWith("ui/prompt-"))).toBe(true);
expect(top("composer animations with claude")).toEqual(expect.arrayContaining(["ui/prompt-send"]));
// the upstream name is a search alias: snapcn's terminal-simulator is ui/terminal-session here
expect(top("terminal simulator", 2).sort()).toEqual(["ui/terminal-session", "ui/terminal-simulator"]);
// "template" alone: the items that are one, and how to narrow it
expect(listed(cat.items, ["template"])).toContain("say what it shows to narrow it");
expect(listed(cat.items, ["cli"])).not.toContain("click-type");
});
test("show: one item in full, with its props and when to use it", () => {
const i = cat.items.find((i) => i.name === "prompt-send")!;
const s = shown(i);
for (const want of ["ui/prompt-send", "use it when:", "not when:", "props:", "text?: string", "raea make component add prompt-send", 'import { PromptSend } from "./components/ui/prompt-send"']) expect(s).toContain(want);
});
});
+24 -88
View File
@@ -6,15 +6,7 @@
import { existsSync, readFileSync, realpathSync } from "node:fs";
import { dirname, join } from "node:path";
/** One of a component's props, read from its Props type: its type as written, its default, a line on what it does */
export type Prop = { name: string; type: string; default?: string; says?: string; required?: boolean };
/** An item; the fields after `from` are tools/library-meta.sh's: the upstream component it was matched to by content
* (a search alias, never its name here), what it draws and how it moves, when to use it and when not, the phrases
* people ask for it with, its props, and the length, frame rate, size, aspect and feel it was designed at */
export type Item = {
name: string; category: string; type: string; says: string; component: string; default?: boolean; files: string[]; needs: string[]; fonts: string[]; packages?: string[]; from: string;
upstream?: string; what?: string; use_when?: string[]; avoid_when?: string[]; asked_as?: string[]; props?: Prop[]; length?: number; fps?: number; size?: string; aspect?: string; vibe?: string;
};
export type Item = { name: string; category: string; type: string; says: string; component: string; default?: boolean; files: string[]; needs: string[]; fonts: string[]; packages?: string[]; from: string };
type Catalog = { sources: Record<string, { url: string; licence: string }>; items: Item[] };
export type Got = { item: Item; licence: string; files: Record<string, string> };
@@ -25,9 +17,6 @@ function home(raea: string, env: Record<string, string | undefined>): string | u
return [env.RAEA_HOME && join(env.RAEA_HOME, rel), join(bin, "../share/raea", rel), join(bin, "../..", rel)].find((p) => p && existsSync(join(p, "catalog.json")));
}
/** An item by its name, category/name or category/type/name */
export const found = (items: Item[], want: string) => items.find((i) => i.name === want || `${i.category}/${i.name}` === want || `${i.category}/${i.type}/${i.name}` === want);
/** Host op "components": {op: "list"} is every item, {op: "get", name} one item with its files' text (by its path in
* the library, which is its path under components/). No library beside this raea: an empty list, and no item. */
export function componentsHost(raea: string, env: Record<string, string | undefined>, a: Record<string, unknown>): Item[] | Got | null {
@@ -36,99 +25,46 @@ export function componentsHost(raea: string, env: Record<string, string | undefi
const cat = JSON.parse(readFileSync(join(dir, "catalog.json"), "utf8")) as Catalog;
if (a.op !== "get") return cat.items;
const want = String(a.name).replace(/^\/+|\/+$/g, "");
const item = found(cat.items, want);
const item = cat.items.find((i) => i.name === want || `${i.category}/${i.name}` === want || `${i.category}/${i.type}/${i.name}` === want);
if (!item) return null;
const files = Object.fromEntries([...item.files, ...item.needs].map((f) => [f, readFileSync(join(dir, f), "utf8")]));
return { item, licence: cat.sources[item.from]?.licence ?? "", files };
}
// what a row says: the item's own line, or what it draws when that line is a few words
const line = (i: Item) => (i.says.length >= 40 || !i.what ? i.says : i.what).split(". ")[0];
const row = (i: Item) => `${`${i.category}/${i.name}`.padEnd(34)} ${i.type.padEnd(13)} ${line(i).slice(0, 110)}`;
// words that say nothing about which one ("a", "animation", "component") are skipped; "template", "effect" and
// "preset" narrow to the items that are one when they're all a search says, and only rank otherwise
const FILLER = new Set(["a", "an", "the", "with", "for", "of", "and", "in", "on", "to", "my", "our", "some", "please", "use", "using", "raea", "component", "components", "animation", "animations", "animated", "thing", "something", "from", "like", "one"]);
const SOFT = new Set(["template", "templates", "effect", "effects", "preset", "presets"]);
const esc = (w: string) => w.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
// a word at a word's start ("count" finds "counter"); a short one only whole ("cli" isn't "click", "ai" isn't "aim")
const finds = (w: string) => (w.length <= 3 ? new RegExp(`(^|[^a-z0-9])${esc(w)}(s|es)?($|[^a-z0-9])`, "i") : new RegExp(`(^|[^a-z0-9])${esc(w.replace(/s$/, ""))}`, "i"));
/** How well an item answers the words: 0 when a word that matters isn't anywhere in it. The name, the upstream name
* and the phrases people ask for it with count most; what it does and when to use it count once */
export function scored(i: Item, ws: string[]): number {
const asked = (i.asked_as ?? []).join(" | ");
const told = [i.says, i.what ?? "", ...(i.use_when ?? [])].join(" ");
const named = (n: string | undefined, w: string) => (!n ? 0 : n.split("-").includes(w) ? 3 : w.length > 3 && n.includes(w) ? 2 : 0);
const key = ws.filter((w) => !SOFT.has(w));
let s = 0;
// the words together, as written: a phrase people ask with, a name, or a sentence of what it does
const phrase = key.join(" ");
if (key.length > 1) s += (i.asked_as ?? []).some((a) => a.toLowerCase().includes(phrase)) ? 6 : [i.name, i.upstream ?? ""].includes(key.join("-")) ? 6 : told.toLowerCase().includes(phrase) ? 3 : 0;
for (const w of ws) {
const [c, t] = w.split("/");
const re = finds(w);
let got = 0;
if (w.includes("/")) got = i.category === c && (!t || i.type === t) ? 4 : 0;
else if (i.category === w || i.type === w) got = 4;
// its name (or upstream's), the phrases it's asked for with, and its own words each add
else got = Math.max(named(i.name, w), named(i.upstream, w)) + (re.test(asked) ? 3 : 0) + (re.test(told) || i.from === w ? 1 : 0);
if (!got && !SOFT.has(w)) return 0;
s += got;
}
return s;
}
const row = (i: Item) => `${`${i.category}/${i.name}`.padEnd(34)} ${i.type.padEnd(13)} ${i.says.split(". ")[0].slice(0, 110)}`;
/** `raea make component list`'s lines for the library: with no words, each category and its types; with words, the
* items they name. A word is a category ("text"), a category/type ("text/reveal"), a name or upstream name, or
* anything in the phrases people ask with, what it does or when to use it; every word that matters must be found */
* items they name. A word is a category ("text"), a category/type ("text/reveal"), or anything in a name or in what
* an item does; every word must be found, and a name's own words count first. */
export function listed(items: Item[], words: string[]): string {
if (!items.length) return "";
const ws = terms(words);
if (!ws.length) {
if (!words.length) {
const cats = [...new Set(items.map((i) => i.category))].sort();
const line = (c: string) => {
const of = items.filter((i) => i.category === c);
const types = [...new Set(of.map((i) => i.type))].sort().map((t) => `${t} ${of.filter((i) => i.type === t).length}`);
return `${c.padEnd(14)} ${String(of.length).padStart(3)} ${types.join(", ")}`;
};
return `\nThe library, by what a component is for (raea make component list text, list text/reveal, list "chat input", list "count up"; show NAME tells one in full; add NAME copies one):\n${cats.map(line).join("\n")}\n`;
return `\nThe library, by what a component is for (raea make component list text, list text/reveal, list "count up"; add NAME copies one):\n${cats.map(line).join("\n")}\n`;
}
const found = searched(items, ws);
const ws = words.join(" ").toLowerCase().split(/\s+/).filter(Boolean);
const phrase = ws.join(" ");
const score = (i: Item) => {
// the words together, as written, in what it does: ahead of the same words scattered
let s = ws.length > 1 && i.says.toLowerCase().includes(phrase) ? 3 : 0;
for (const w of ws) {
const [c, t] = w.split("/");
if (w.includes("/") ? i.category === c && (!t || i.type === t) : i.category === w || i.type === w) s += 4;
else if (i.name.split("-").includes(w)) s += 3;
else if (i.name.includes(w)) s += 2;
else if (i.says.toLowerCase().includes(w)) s += 1;
else return 0;
}
return s;
};
const found = items.map((i) => [score(i), i] as const).filter(([s]) => s > 0).sort((a, b) => b[0] - a[0] || a[1].name.localeCompare(b[1].name));
if (!found.length) return `no component in the library for "${words.join(" ")}" (raea make component list shows the categories)\n`;
// "template" or "effect" alone: the items that are one, a page of them, and how to narrow it
if (ws.every((w) => SOFT.has(w))) {
const top = found.slice(0, 30);
return `${found.length} components are a ${ws[0].replace(/s$/, "")}; say what it shows to narrow it (list ${ws[0]} chat, list ${ws[0]} logo, list "${ws[0]} product demo"):\n${top.map(row).join("\n")}\n${found.length > top.length ? `... and ${found.length - top.length} more\n` : ""}`;
}
return found.map(row).join("\n") + "\n";
}
/** A search's words that matter, in lower case */
export const terms = (words: string[]) => words.join(" ").toLowerCase().split(/\s+/).filter((w) => w && !FILLER.has(w));
/** The items the words find, best first */
export function searched(items: Item[], ws: string[]): Item[] {
// equal scores: the one more of whose asked-for phrases the words are in is more about them
const res = ws.filter((w) => !w.includes("/")).map(finds);
const fit = (i: Item) => (i.asked_as ?? []).filter((a) => res.some((re) => re.test(a))).length;
return items
.map((i) => [scored(i, ws), fit(i), i] as const)
.filter(([s]) => s > 0)
.sort((a, b) => b[0] - a[0] || b[1] - a[1] || a[2].name.localeCompare(b[2].name))
.map(([, , i]) => i);
}
/** `raea make component show NAME`: everything an agent picks by, without opening the file */
export function shown(i: Item, from = "./components"): string {
const list = (head: string, xs?: string[]) => (xs?.length ? `${head}\n${xs.map((x) => ` - ${x}`).join("\n")}\n` : "");
const made = [i.size && `${i.size} (${i.aspect})`, !i.size && i.aspect, i.length && `${i.length} frames at ${i.fps ?? 30} fps`, i.vibe && `feels ${i.vibe}`].filter(Boolean).join(", ");
const props = (i.props ?? []).map((p) => ` ${p.name}${p.required ? "" : "?"}: ${p.type}${p.default !== undefined ? ` = ${p.default}` : ""}${p.says ? `\n ${p.says}` : ""}`);
return `${i.category}/${i.name} (${i.type}; from ${i.from}${i.upstream ? `, ${i.upstream} there` : ""})
${i.what ?? i.says}
${list("use it when:", i.use_when)}${list("not when:", i.avoid_when)}${i.asked_as?.length ? `asked for as: ${i.asked_as.join("; ")}\n` : ""}${made ? `designed at: ${made}\n` : ""}${props.length ? `props:\n${props.join("\n")}\n` : "props: none (its words and colours are written in the file)\n"}add it: raea make component add ${i.name}
import ${i.default ? i.component : `{ ${i.component} }`} from "${from}/${i.category}/${i.name}";
`;
return found.map(([, i]) => row(i)).join("\n") + "\n";
}
/** What `add` says of a copied item: where it is, how to import it, the fonts it loads, whose it was */
+2 -2
View File
@@ -136,7 +136,7 @@ pub fn run(args: &[String]) -> R<String> {
IN_HELP.set(was);
// `raea library` (engine/cli/src/library.ts) and `raea show` (show.ts: in the raea app, not Preview, Shane 11-09), 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)");
let usage = format!("{usage}\n raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] [--playable] [--label LABEL] [--detail PARAGRAPH] [--labels FILE.json] [--despite CHECK WHY] | raea show --choose LABEL FILE... --choose LABEL FILE... [--recommend N] | raea show --question Q --choice A --choice B [STILL...] | raea show [--title T] --question Q [--preview FILE] --choice A [--preview FILE] --choice B ... [--question Q2] ... | raea show --on ITEM [--working ID] [--ask TEXT] [--status S] [--states S1,S2] [--sign N --clip FILE --render HASH] [--done ID] [--note LINE] [--sub NAME] (shown in the raea app as an item the person can use and answer, posted quietly with a notice, the window left where they are unless --open: stills (several, a storyboard), a video, a sound, a NAME.script.ts or .md, a .tsx (an interactive artifact; a project's composition opens in its editor), a playable ad's NAME-preview.html (played in a phone, sandboxed; --playable exports a game's .tsx with raea playable and shows that), or questions, all of them one item; --choose LABEL FILE... once per option (2 to 6) for the person to pick one, --recommend N the one you would (nothing is picked for them), their pick back as {{\"kind\":\"answer\",\"choice\":LABEL}}; --label \"PLACE TAG\" a label beside the picture, never on it, that points at PLACE (x0,y0,x1,y1 or x,y in its 0-1, then #N the Nth file, @T or @T-TO a film's seconds, or part=KEY a scene's part; the tag the rest), --detail the paragraph of the --label before it, --labels a JSON list of them as feed_post takes them, and a sheet raea media sheet made comes labelled; each question and choice with a --preview to play or read while answering (a still, a video, a sound, a script or .md; after a --choice that choice's, else the question's); what they send comes to ~/.raea/inbox/INBOX.jsonl; their edit comments are tasks: --working ID as you start one (each --ask with it one ask you read it as, for the person to correct; --status and --states where the note and each ask stand: to restate, to check, failing, to sign, passing, signed; --sign N --clip FILE --render HASH a clip under ask N for them to sign; a note closes when they retire it, never with --done), --done ID when it's settled, or with the version that settles it, FILE --replaces ITEM --done ID; never open media in Preview while the app is installed)");
let usage = format!("{usage}\n raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] [--playable] [--label LABEL] [--detail PARAGRAPH] [--labels FILE.json] [--despite CHECK WHY] | raea show --question Q --choice A --choice B [STILL...] | raea show [--title T] --question Q [--preview FILE] --choice A [--preview FILE] --choice B ... [--question Q2] ... | raea show --on ITEM [--working ID] [--ask TEXT] [--status S] [--states S1,S2] [--sign N --clip FILE --render HASH] [--done ID] [--note LINE] [--sub NAME] (shown in the raea app as an item the person can use and answer, posted quietly with a notice, the window left where they are unless --open: stills (several, a storyboard), a video, a sound, a NAME.script.ts or .md, a .tsx (an interactive artifact; a project's composition opens in its editor), a playable ad's NAME-preview.html (played in a phone, sandboxed; --playable exports a game's .tsx with raea playable and shows that), or questions, all of them one item; --label \"PLACE TAG\" a label beside the picture, never on it, that points at PLACE (x0,y0,x1,y1 or x,y in its 0-1, then #N the Nth file, @T or @T-TO a film's seconds, or part=KEY a scene's part; the tag the rest), --detail the paragraph of the --label before it, --labels a JSON list of them as feed_post takes them, and a sheet raea media sheet made comes labelled; each question and choice with a --preview to play or read while answering (a still, a video, a sound, a script or .md; after a --choice that choice's, else the question's); what they send comes to ~/.raea/inbox/INBOX.jsonl; their edit comments are tasks: --working ID as you start one (each --ask with it one ask you read it as, for the person to correct; --status and --states where the note and each ask stand: to restate, to check, failing, to sign, passing, signed; --sign N --clip FILE --render HASH a clip under ask N for them to sign; a note closes when they retire it, never with --done), --done ID when it's settled, or with the version that settles it, FILE --replaces ITEM --done ID; never open media in Preview while the app is installed)");
// clothes for SOMA's body, sewn or laid on the skin (docs/character.feature CH45c): engine/cli/src/clothes.ts, wardrobe.ts and sewn.ts
let usage = format!("{usage}\n raea make clothes [make NAME [\"WHAT IT IS\"] [--plain] [--set PATH=VALUE,...] [--colour #RRGGBB] | settings | cover NAME --parts PART[:SHARE],... --colour #RRGGBB [--stand MM] [--over UNDER] [--hard [--sole MM] [--sole-colour #RRGGBB] [--panels #RRGGBB,...]] | wear OUT_DIR GARMENT... [--body DIR] [--head HEAD_DIR]] (clothes for SOMA's body from words: make sews a garment: a sewing pattern (GarmentCode, MIT) from the words, or the plain base with --plain, its settings changed by --set PATH=VALUE (settings lists them and what each may be), cut to SOMA's measurements, draped by raea's own cloth and baked, as assets/clothes/NAME.json and its .glb, in --colour or the palette's next; the first make sets up GarmentCode and its Python in raea's models folder; cover makes one by procedure in the same file, no picture: the skin of the parts named (hips, waist, torso, chest, neck, head, upperArm, foreArm, hand, thigh, shin, foot, toes; a limb's SHARE is how far along it from its top), in one colour, MM off the skin (6 unless said), --over a garment already made as the one under it; wear puts garments on a body, innermost first (each GARMENT a name or its .json): OUT_DIR/NAME.glb each, with OUT_DIR/body.glb the body without the skin wholly under cloth; --body DIR another SOMA body folder (a headless one for a head part); --head HEAD_DIR the head that joins it (head.json), whose skin the body's is graded to at the collar; alone, the project's garments. The first use fetches SOMA's body (NVlabs/SOMA-X, Apache-2.0) into raea's models folder, and the first use of any step makes the Python environment the clothes run in there (by uv); no step needs Blender)");
// body motion made by Kimodo, on MLX on a Mac and on PyTorch elsewhere (docs/character.feature CH15c):
@@ -149,7 +149,7 @@ pub fn run(args: &[String]) -> R<String> {
let usage = format!("{usage}\n raea spec FILE.ts [--as brief|script|taste|parts] (a spec's default export as JSON, checked against its schema: brief.ts, script.ts, taste.ts, NAME.parts.ts)\n raea workspace init [NAME] [--layout LAYOUT] | raea workspace adopt DIR [--name NAME] | raea workspace [--json] (a workspace: a git repo of projects under raea.root, ~/Documents/raea unless git config says)\n raea project new NAME [--storage inline|submodule] [--client NAME] | raea project tag [NAME] [--client NAME] [--no-client] | raea project split NAME [--remote URL] | raea project join NAME | raea project [--json] (a project in the workspace: its folder, brief.ts, media/, out/; its client, what raea.app files every card shown from it under (raea cloud's tags: projects don't nest); split and join keep its history)\n raea check EDIT.tsx --quick [--shape S] [--platform P] [--taste T] [-o check.json] (three stills of a composition checked for text: clipped, cramped, safe areas, sizes; about a second)\n raea hook [claude|codex|gemini|kimi] (every agent's tool hooks, which raea skills install adds: before a shell command, media opened in the Mac's viewer while the raea app is installed is stopped once for raea show (the same command again goes through); after a save, the quick check on a composition)\n raea doctor [--fix] [DIR] (what doesn't match this raea: old brief files, an older workspace format, an agent's skill from another version)\n raea app run|check|bundle APP.tsx [--target web|native] [--size WxH] [--script steps.json] [--png DIR] [-o App.app] (a TSX app on @raea/ui: its window, the headless check, a Mac app; web is Blitz on Bevy, native is Rune; the app's `export const app` sets the target, web when it doesn't; raea rune ... is --target native)\n {}\n {}\n {} ({})\n {}\n {}\n {}", skill::USAGE, tools::blender::USAGE, tools::motion::SETUP_USAGE, tools::motion::SETUP_ABOUT, raea_app_engines::godot::USAGE, raea_app_engines::shot::USAGE, raea_app_engines::round::USAGE);
let (export_game, capcut, layers, xml, scene, physics, splat, wear, bake) = (raea_app_game::USAGE, raea_app_capcut::USAGE, raea_app_layers::USAGE, raea_app_layers::USAGE_XML, raea_app_scene::USAGE, motion::physics::USAGE, tools::splat::USAGE, raea_runtime_wear::USAGE, raea_app_lightbake::USAGE);
let apps = format!(" {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n", raea_app_direction::check::USAGE, raea_app_check::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, raea_app_ask::USAGE, format!("{GOAL_USAGE}\n {}", raea_app_make::USAGE), raea_app_direction::USAGE, raea_app_direction::findings::USAGE, raea_app_notes::USAGE, raea_app_fingerprint::USAGE, raea_sys_index::cli::USAGE);
return Ok(usage::under_make(&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 words FILE [-o OUT.words.json] (what FILE says, word by word, into its words.json beside it: parakeet-mlx on a Mac, the farm's Whisper on a raea cloud box)\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 make component list [WORDS] [--json] | raea make component show NAME [--json] | raea make component add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; WORDS search the library by use and by how people ask: text/reveal, \"count up\", \"chat input\", template; show tells one in full: what it draws, when to use it and when not, its props)\n raea brand DOMAIN|URL (the brand kit read from its website on this machine: brand/brand.css, brand/brand.json, BRAND.md, logos in media/brand; says when a plain fetch saw too little)\n raea guide [NAME] (craft, the floor read before any edit; the modes: pitch, explain, story, play, tool; motion, music, layout and the rest; bevy and bevy/NAME for 3D)\n raea context PROJECT (what to read before working on a project: taste, brief, look, the floor and its modes' guides)\n{apps} raea play EDIT.tsx [--input | --input-script KEYS.json] [--size WxH] [--seconds N|end] (a game, live; also: --input-log FILE --offscreen --snapshot T FILE --json FILE --seek F FILE --pick X,Y --view YAW,PITCH,DISTANCE --scrub N --baked --autoplay --no-vsync --master --3d)\n {export_game} (a game as a program of its own: a Mac app or a command)\n {} ({})\n {capcut}\n {layers}\n {xml}\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 {bake}\n {wear} (a .glb's weathering causes for raea/wear: the model with a second UV set and its cause maps, made once in the asset store)\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 {light_usage} (each scene on each light path against its path-traced reference: distance in stops, the worst tile, a moving shot's flicker, a frame's cost; DIR/report.json)\n {} (each case on each denoiser against its converged truth: FLIP, RMSE, bias, flicker, blotches, lag after a disocclusion or a light going out, a frame's cost, and how many of MetalFX's numbers each meets; DIR/report.json)\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)", raea_app_playable::USAGE, raea_app_playable::ABOUT, raea_denoise_bench::USAGE)));
return Ok(usage::under_make(&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 words FILE [-o OUT.words.json] (what FILE says, word by word, into its words.json beside it: parakeet-mlx on a Mac, the farm's Whisper on a raea cloud box)\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 make component list [WORDS] | raea make component add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; WORDS search the library by use: text/reveal, \"count up\")\n raea brand DOMAIN|URL (the brand kit read from its website on this machine: brand/brand.css, brand/brand.json, BRAND.md, logos in media/brand; says when a plain fetch saw too little)\n raea guide [NAME] (craft, the floor read before any edit; the modes: pitch, explain, story, play, tool; motion, music, layout and the rest; bevy and bevy/NAME for 3D)\n raea context PROJECT (what to read before working on a project: taste, brief, look, the floor and its modes' guides)\n{apps} raea play EDIT.tsx [--input | --input-script KEYS.json] [--size WxH] [--seconds N|end] (a game, live; also: --input-log FILE --offscreen --snapshot T FILE --json FILE --seek F FILE --pick X,Y --view YAW,PITCH,DISTANCE --scrub N --baked --autoplay --no-vsync --master --3d)\n {export_game} (a game as a program of its own: a Mac app or a command)\n {} ({})\n {capcut}\n {layers}\n {xml}\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 {bake}\n {wear} (a .glb's weathering causes for raea/wear: the model with a second UV set and its cause maps, made once in the asset store)\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 {light_usage} (each scene on each light path against its path-traced reference: distance in stops, the worst tile, a moving shot's flicker, a frame's cost; DIR/report.json)\n {} (each case on each denoiser against its converged truth: FLIP, RMSE, bias, flicker, blotches, lag after a disocclusion or a light going out, a frame's cost, and how many of MetalFX's numbers each meets; DIR/report.json)\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)", raea_app_playable::USAGE, raea_app_playable::ABOUT, raea_denoise_bench::USAGE)));
}
// `--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") {
+3 -13
View File
@@ -28,7 +28,7 @@ import { absolute, fromCwd, labelsIn, showVerb } from "./show";
// `raea make clothes` (clothes.ts): garments for SOMA's body from words
import { clothesVerb } from "./clothes";
// the component library (catalog.ts): open components sorted by use, listed and copied by `raea make component`
import { added, found, listed, searched, shown as inFull, terms, type Got, type Item } from "./catalog";
import { added, listed, type Got, type Item } from "./catalog";
// `raea bug` (bug.ts): an agent's report of a bug in raea, to raea's server
import { bugVerb } from "./bug";
@@ -199,18 +199,8 @@ export function raeaHandler(host?: Host, engine?: Engine) {
// the library beside this raea (none in a shell with no host: raea's own sets are all it lists)
const shelf = (): Item[] => (host ? (host("components", { op: "list" }) as Item[]) : []);
if (args[1] === undefined) return out(parts() + listed(shelf(), []), 0, was);
const ws = clean(args.slice(2));
// --json: the items found (each with its props, when to use it and when not) for an agent to pick from
if (args[1] === "list" && args.includes("--json")) return out(`${JSON.stringify(ws.length ? searched(shelf(), terms(ws)) : shelf(), null, 1)}\n`, 0, was);
if (args[1] === "list") return out(ws.length ? listed(shelf(), ws) : parts() + listed(shelf(), []), 0, was);
// show: one item in full, so it can be picked without opening its file
if (args[1] === "show") {
const item = ws[0] ? found(shelf(), ws[0]) : undefined;
if (!item) return out("", 1, `${was}raea make component show: no "${ws[0] ?? ""}" in the library (raea make component list WORDS finds one)\n`);
const at = (await c.fs.exists(p("compositions"))) ? "../components" : "./components";
return out(args.includes("--json") ? `${JSON.stringify(item, null, 1)}\n` : inFull(item, at), 0, was);
}
if (args[1] !== "add") return out("", 2, `${was}raea make component list [WORDS] [--json] | show NAME [--json] | add NAME ... [--shared] [--force]\n`);
if (args[1] === "list") return out(clean(args.slice(2)).length ? listed(shelf(), clean(args.slice(2))) : parts() + listed(shelf(), []), 0, was);
if (args[1] !== "add") return out("", 2, `${was}raea make component list [WORDS] | raea make component add NAME ... [--shared] [--force]\n`);
const names = clean(args.slice(2));
if (!names.length) return out("", 2, `${was}raea make component add NAME ... (raea make component list shows them)\n`);
const force = args.includes("--force");
+4 -29
View File
@@ -32,9 +32,6 @@ raea show [--title T] --question Q1 [--preview FILE] --choice A [--preview FILE]
raea show FILE... --fyi
Only for the person to look at, nothing to approve: they say Got it (you hear {"kind":"seen"}), and anything they
want to say back comes through the chat. Without it a show is a version for them to approve or send notes on.
raea show --choose "Warm grade" A.png B.png --choose "Cool grade" C.png [--recommend 2] [--title T] [--ask TEXT]
The person picks one: 2 to 6 options, each named, its files after it. --recommend N marks the one you'd pick (from
1); nothing is picked for them. Their pick comes back as {"kind":"answer","choice":"Cool grade"}.
raea show --group "Day: sun through the doors" A.png B.png --group "Night: practicals only" C.png [--title T]
Lay the files out in groups the person sees side by side, each titled before the colon and said after it in a plain
line (never shorthand); the files after a --group are its own. Keep it short: enough to know what each group is.
@@ -61,7 +58,7 @@ raea show FILE... --replaces ITEM --done ID...
closes when the person retires it, never with --done. raea notes post sends all of these from the notes.
`;
const WITH_VALUE = new Set(["--group", "--choose", "--recommend", "--despite", "--label", "--detail", "--labels", "--title", "--ask", "--project", "--replaces", "--as", "--role", "--inbox", "--question", "--choice", "--preview", "--on", "--working", "--done", "--note", "--sub", "--status", "--states", "--sign", "--clip", "--render"]);
const WITH_VALUE = new Set(["--group", "--despite", "--label", "--detail", "--labels", "--title", "--ask", "--project", "--replaces", "--as", "--role", "--inbox", "--question", "--choice", "--preview", "--on", "--working", "--done", "--note", "--sub", "--status", "--states", "--sign", "--clip", "--render"]);
const FLAGS = new Set(["--open", "--fyi", "--playable"]);
/** The harness an agent runs in, named as the feed shows it, from the program that started this command (native.ts
@@ -121,26 +118,6 @@ export function parseShow(args: string[], cwd: string) {
});
const empty = groups.find((g) => !g.files.length);
if (empty) throw new Error(`the group "${empty.title}" has no files: put its files after its --group\n${SHOW_USAGE}`);
// the options to choose from (raea-platform home.feature HM5): each --choose "Label" holds the files after it
const options: { label: string; files: string[]; recommended?: true }[] = [];
args.forEach((a, i) => {
if (a === "--choose" && args[i + 1] !== undefined) options.push({ label: args[i + 1].trim(), files: [] });
else if (a === "--group" && options.length) throw new Error(`--choose and --group don't mix: each option is its own group\n${SHOW_USAGE}`);
else if (options.length && isFile(a, i)) options.at(-1)!.files.push(abs(a));
});
if (options.length) {
if (options.length < 2 || options.length > 6) throw new Error(`--choose gives 2 to 6 options, each with its files\n${SHOW_USAGE}`);
const bare = options.find((o) => !o.label || !o.files.length);
if (bare) throw new Error(`the option "${bare.label}" ${bare.label ? "has no files: put its files after its --choose" : "needs a name"}\n${SHOW_USAGE}`);
if (files.length !== options.flatMap((o) => o.files).length) throw new Error(`with --choose, every file goes after the option it's in\n${SHOW_USAGE}`);
if (args.includes("--question") || args.includes("--fyi")) throw new Error(`--choose is its own question: no --question or --fyi with it\n${SHOW_USAGE}`);
}
const recommend = one("--recommend");
if (recommend !== undefined) {
const n = Number(recommend);
if (!options.length || !Number.isInteger(n) || n < 1 || n > options.length) throw new Error(`--recommend N names one of the --choose options, from 1${options.length ? ` to ${options.length}` : ""}\n${SHOW_USAGE}`);
options[n - 1].recommended = true;
}
const despite = args.flatMap((a, i) => {
if (a !== "--despite") return [];
const [check, why] = [args[i + 1], args[i + 2]];
@@ -180,7 +157,7 @@ export function parseShow(args: string[], cwd: string) {
if (labels.length && args.includes("--labels")) throw new Error(`--label or --labels, not both\n${SHOW_USAGE}`);
if (questions && files.length) throw new Error(`with several questions or previews, each file is a --preview of the question or choice it shows\n${SHOW_USAGE}`);
if (args.includes("--fyi") && (asked.length || marking(args))) throw new Error(`--fyi shows files only to be looked at: a question, or marking comments, is answered\n${SHOW_USAGE}`);
return { groups, options, fyi: args.includes("--fyi"), labels, labelsFile: one("--labels"), files, despite, choices, questions, open: args.includes("--open"), playable: args.includes("--playable"), title: one("--title"), ask: one("--ask"), asks: many("--ask"), project: one("--project"), replaces: one("--replaces"), question: questions ? undefined : one("--question"), as: one("--as"), role: one("--role"), inbox: one("--inbox"), on: one("--on"), working: many("--working"), done: many("--done"), note: one("--note"), sub: one("--sub"), status: one("--status"), states: one("--states")?.split(",").map((s) => s.trim()).filter(Boolean), sign: one("--sign"), clip: one("--clip"), render: one("--render") };
return { groups, fyi: args.includes("--fyi"), labels, labelsFile: one("--labels"), files, despite, choices, questions, open: args.includes("--open"), playable: args.includes("--playable"), title: one("--title"), ask: one("--ask"), asks: many("--ask"), project: one("--project"), replaces: one("--replaces"), question: questions ? undefined : one("--question"), as: one("--as"), role: one("--role"), inbox: one("--inbox"), on: one("--on"), working: many("--working"), done: many("--done"), note: one("--note"), sub: one("--sub"), status: one("--status"), states: one("--states")?.split(",").map((s) => s.trim()).filter(Boolean), sign: one("--sign"), clip: one("--clip"), render: one("--render") };
}
/** A --labels file's labels, as feed_post takes them: a list, or { "labels": [...] } (raea media sheet's OUT.labels.json). */
@@ -241,7 +218,7 @@ export function showVerb(ask: Ask, args: string[], cwd: string, env: Record<stri
a.files = [(ask("playable", { file: a.files[0], cwd }) as { page: string }).page];
a.title ??= a.files[0].replace(/^.*[\\/]/, "").replace(/-preview\.html$/, "").replace(/[-_]+/g, " ").replace(/^\w/, (c) => c.toUpperCase());
}
const r = ask("show", { ...(labels?.length ? { labels } : {}), ...(a.fyi ? { intent: "fyi" } : a.options.length ? { intent: "choose", options: a.options } : {}), ...(a.groups.length ? { groups: a.groups } : {}), files: a.files, despite: a.despite, title: a.title, ask: askWith(a.ask, a.despite), question: a.question, choices: a.choices, questions: a.questions, open: a.open, project: a.project, replaces: a.replaces, cwd, by }) as
const r = ask("show", { ...(labels?.length ? { labels } : {}), ...(a.fyi ? { intent: "fyi" } : {}), ...(a.groups.length ? { groups: a.groups } : {}), files: a.files, despite: a.despite, title: a.title, ask: askWith(a.ask, a.despite), question: a.question, choices: a.choices, questions: a.questions, open: a.open, project: a.project, replaces: a.replaces, cwd, by }) as
| { opened: string[] }
| { kind: "item" | "composition"; id: string; type: string; title: string; project: string; workspace: string; inbox: string; brought?: boolean };
if ("opened" in r) return `The raea app isn't on this Mac, so ${r.opened.length === 1 ? "it opened" : `${r.opened.length} files opened`} in the Mac's own viewer: nothing was posted and nothing comes back. Install raea (raea.io) to show work as items the person can answer.\n`;
@@ -265,9 +242,7 @@ export function showVerb(ask: Ask, args: string[], cwd: string, env: Record<stri
? `Shown in the raea app: "${r.title}" (${r.type}, item ${r.id}, project ${r.project} in ${r.workspace}); the window is on it.`
: `Posted in the raea app: "${r.title}" (${r.type}, item ${r.id}, project ${r.project} in ${r.workspace}), with a notice; the window stayed where the person is.`,
...settled,
a.options.length
? `They pick one of ${a.options.length}: {"kind":"answer","choice":"<the option's name>"} comes to ${inbox}. Follow it (tail -n0 -F ${inbox}, or your harness's monitor) and carry on with their pick.`
: a.fyi
a.fyi
? `Only to look at: when they've seen it, {"kind":"seen"} comes to ${inbox}; nothing to wait for.`
: `What the person sends on it (notes, edits, picks, answers, results) comes to ${inbox}, one JSON line each. Follow it (tail -n0 -F ${inbox}, or your harness's monitor) and answer each; a next version is raea show --replaces ${r.id} FILE.`,
"",
+1 -1
View File
@@ -17,7 +17,7 @@ import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node
import { tmpdir } from "node:os"
import path from "node:path"
import { check, found } from "raea/check"
import type { CutBeat as Beat } from "raea/brief.gen"
import type { Beat } from "raea/brief.gen"
import type { FileFacts } from "../facts.ts"
import { type Faces, Unmet } from "../media.ts"
import { cutOf } from "./cut.ts"
+1 -2
View File
@@ -20,8 +20,7 @@ Run `raea context PROJECT` before anything else and read all of it. It prints, i
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 (`NAME.script.ts`) and a direction. To write one,
`raea guide brief` has its types, a cut goal's contract and an example.
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.
+2 -23
View File
@@ -12,9 +12,8 @@ docs/components.md in the raea repository.
every thing the piece needs as a component: `Kitchen`, `Kettle`, `Steam`, `BrushedSteel`, `MorningLook`,
`PriceCard`. One component is one concern: one object, one surface, one effect, one card.
2. **Look before making.** `raea make component list` shows raea's own and the library's categories; `raea make
component list WORDS` searches the library by what a piece is for and how people ask for it (`text/reveal`,
`numbers/counter`, `"count up"`, `"chat input"`, `template`): several hundred open-source text reveals, counters,
charts, logo stings, HUDs and screen demos, and `raea make component show NAME` says when to use one and its props. A
component list WORDS` searches the library by what a piece is for (`text/reveal`, `numbers/counter`, `transitions`,
`"count up"`): several hundred open-source text reveals, counters, charts, logo stings, HUDs and screen demos. A
project's `components/` and the workspace's `shared/components/` hold what this person already has; `raea library
search "WORDS"` finds their assets. Interface pieces (forms, tables, dashboards) come from shadcn, never rebuilt:
see "shadcn" below. A library piece arrives with its source's sample words, colours and fonts: pass the brief's.
@@ -29,26 +28,6 @@ docs/components.md in the raea repository.
A piece written as one long file of meshes and numbers can't be reused, checked part by part, tuned by a person or
fixed by a note that names a thing. Write components even for a one-off: the next note will name one of them.
## A template, an effect, a branded screen: the library first
When the person asks for a template, an effect, a preset, "something from remocn" (or snapcn), or a known kind of app
screen moving (a chat box or composer, an AI prompt, a terminal, an agent at work, a phone or laptop showing an app),
the library has it more often than not, already made and timed. Look there before drawing anything:
1. `raea make component list WORDS`, with the person's own words: `list composer`, `list "chat input"`, `list "AI
prompt"`, `list "claude code"`, `list terminal`, `list template product`, `list "lower third"`. It searches each
component's name, the name it had upstream, the phrases people ask for it with, and what it does; `list template`
or `list effect` alone lists the ones that are and says how to narrow it.
2. `raea make component show NAME` for the best hits: what it draws and how it moves, when to use it and when not
(naming the better pick for the other case), the size, length and frame rate it was designed at, and every prop
with its type, default and what it does. `list WORDS --json` gives the same for every hit. Pick from these;
there's no need to open the files, and never fetch the upstream sources by hand.
3. `raea make component add NAME`, then pass the brief's words, colours, fonts and logo through its props. A
component with no props (some templates) has them written in its file: change them there.
Only when nothing fits is it written new, as a component (step 4). A brand's own product UI that isn't in the library
(a particular app's chat window, say) is built from the nearest one: `add` it and restyle it.
## What a component is
A component is a React function component that draws one thing from its props and the frame:
-126
View File
@@ -1,126 +0,0 @@
# brief.ts: the brief as code
A project's brief.ts is a module whose default export is `brief({...})` from `raea/brief`. raea runs it, `raea goal
check` holds the work to its `goal`, and tsc checks it against the same types raea reads. Everything you need to write
one is on this page, so you don't need to open the SDK.
## The shape
```ts
import { brief, cut, rules } from "raea/brief"
export default brief({
title: string, // the project as people name it
for?: string, // the client or person it's for
audience?: string, // who watches, and where
believe?: string, // the one thing they should think afterwards
voice?: string, look?: string, sound?: string,
notDoing?: string[], // the anti-goals
assumed?: string[], // facts you wrote that the person hasn't confirmed, by key ("audience")
sections?: { heading: string, text: string }[],
goal?: Goal | Goal[], // what the work is held to: cut(), rules(), scene(), kit(), shot(), playable()
plan?: PlanFile, // tasks (raea/task plan()), inline or imported
})
```
A goal made with `cut({...})` or `rules({...})` takes these fields:
| Field | What it is |
| --- | --- |
| `aim` | what the goal is, in the person's words |
| `rules` | `{ id, run? , timeout?, file?, says? }[]`: what must hold before you stop (below) |
| `cut` | a cut job's contract, the brief as rules (below) |
| `deliverables` | files that must exist when it's done, relative to brief.ts (a cut goal lists its own) |
| `previews` | what it shows but never delivers (`review/` and `previews/` when left out) |
| `checks` | the project's own `check()`s from raea/check, imported into brief.ts |
| `name`, `after`, `step` | for several goals in order: a goal's name, the goals before it, its workflow step |
## A cut job's contract (`cut: {...}`)
Every `from` is the brief's own words, copied from its text file as they are, so a person can find the line the
rule came from. raea refuses a `from` it can't find.
| Field | Type | What it holds |
| --- | --- | --- |
| `brief` | `string` | the brief as text, relative to brief.ts (`pdftotext -layout brief.pdf brief_docs/brief.txt`) |
| `count` | `{ value: number, from }` | how many cuts the brief asks for. Fewer planned stays open until a person answers an `open` item about `"count"` |
| `seconds` | `[least, most]` | a cut's length when the cut doesn't give its own |
| `formats` | `string[]` | `"9:16"`, `"16:9"`, `"1:1"`, `"4:5"`: every cut's formats when the cut doesn't give its own |
| `cuts` | `CutPlan[]` | one per cut: `{ id, angle?, kind?, hook?, text?, formats?, seconds?, beats? }` |
| `say` | `{ text, from, every? }[]` | what is said or shown in every cut (`every: false`: one cut is enough) |
| `never` | `{ text, from }[]` | what no cut says or shows: a banned claim, a word, a name |
| `cta` | `{ text, from, also?, within? }` | the line every cut ends on, heard or shown in its last `within` seconds (8 by default); `also` lists other lines the brief rotates |
| `open` | `{ question, from, about?, answer?, by? }[]` | the brief's open items (TBD, to confirm). Each holds the job open until a person's answer is written in, with who gave it |
| `frames` | `boolean` | every face whole and every text big enough, in every frame (true by default) |
A cut's `id` is `[a-z0-9_]` and unique. Each format lands as `out/cuts/<id>_<format with x>.mp4`, for example
`out/cuts/a1_s1_9x16.mp4`. `text` is `"captions"`, `"hook"` or `"none"`. `kind` is `"solo"` or `"mashup"`. `hook` is
one of the brief's hook types, as the brief names it.
A cut's `beats` are decided before it's cut, in order: `{ at, feel, story?, asl?, tempo? }[]`. `at` is where the beat
starts, in seconds from the cut's start (0 for the first). `feel` is what the viewer feels there, in the person's
words, and `story` is what they understand by its end. A fresh critic watches each beat for both. `asl` is the beat's
average shot length in seconds, and `tempo` is how its shot lengths move: `"build"` (shorter as it goes), `"release"`
(longer) or `"hold"` (even). The montage check holds the cut to them.
## Rules
| Kind | Example | How it's checked |
| --- | --- | --- |
| `run` | `{ id: "tests", run: "bun test" }` | the command must exit 0 in brief.ts's folder (300 s unless `timeout` says otherwise) |
| `file` | `{ id: "sheet", file: "review/sheet.png" }` | the file must exist (`a\|b`: either one; `dir/`: three or more pictures in it) |
| `says` | `{ id: "logo_end", says: "The wordmark is on screen in each cut's last 3 seconds" }` | words that must be true of the work, judged by a fresh critic, never by you |
You don't run the critic yourself or choose it: `raea goal check` asks for a verdict when one is missing or older than
the work. A `says` rule about a video ("in each cut's last 3 seconds") is watched and heard. One about files or text
is read.
## An example
```ts
// brief.ts
import { brief, cut } from "raea/brief"
export default brief({
title: "Juniper Tea · street interviews, round 1",
for: "Juniper Tea",
audience: "TikTok and Reels, 25-40, already buying loose-leaf",
believe: "Juniper tastes like the tea shop, at home",
goal: cut({
aim: "Ten 9:16 cuts from the street interviews, each ending on the free-trial line",
cut: {
brief: "brief_docs/brief.txt",
count: { value: 10, from: "10 unique cuts total" },
seconds: [20, 40],
formats: ["9:16"],
cuts: [
{
id: "a1_s1", angle: "Angle 1", kind: "solo", hook: "Direct Problem", text: "captions",
beats: [
{ at: 0, feel: "caught off guard, curious", story: "she's a real tea drinker, not an actor", asl: 1.5, tempo: "build" },
{ at: 4, feel: "the small sadness of bad tea at home", story: "bagged tea tastes like paper to her", asl: 3, tempo: "hold" },
{ at: 14, feel: "the surprise of a good first sip", story: "Juniper is the shop's taste at home", asl: 2, tempo: "release" },
],
},
{ id: "a1_s2", angle: "Angle 1", kind: "mashup", hook: "Reaction", text: "captions" },
],
say: [{ text: "free shipping over $35", from: "Mention: free shipping over $35", every: false }],
never: [{ text: "cures", from: "Never claim the tea cures or treats anything" }],
cta: { text: "Try Juniper free for 30 days", from: "CTA: \"Try Juniper free for 30 days\"" },
open: [
{
question: "The footage holds 4 usable interviews, not 10: deliver 4 this round?",
from: "10 unique cuts total", about: "count",
// left out until the person answers; then their words and who gave them
answer: "Yes, 4 now and the rest after the reshoot", by: "the client's producer",
},
],
},
rules: [
{ id: "wordmark_end", says: "The Juniper wordmark is on screen in each cut's last 3 seconds" },
],
}),
})
```
Write it, then run `raea goal check`. It names each rule that doesn't hold and the line of the brief it came from.
+3 -9
View File
@@ -57,12 +57,6 @@ import { EndCard, InstallButton, install } from "raea/playable";
standard, physical and basic materials, perspective and orthographic cameras, the five light kinds, fog, tone
mapping, shadows and anti-aliasing. Models, splats and water stay in the video ad.
The host draws that 3D with Bevy's own PBR shaders, so a frame of the playable matches `raea render --frame` closely.
It has the sun's shadow, point and spot lights, fog from `<Fog>` and Bevy's tone mapping. Some things are left out,
and the page's console names each one once: normal maps, transmission, vertex colours, point and spot shadows, rect
lights, an environment's light, a camera's own `<Fog>` child, a shadow catcher and a paint look. Check how the 3D looks
in the `preview` page, not only in the video ad.
## Rules on raea/ecs
A game whose rules are systems on a raea/ecs `World` keeps Bevy's world in the playable: the export sees a World made
@@ -101,14 +95,14 @@ carried for you, as the video ad draws them. Any other family named but not impo
## Export and check
```sh
raea add [email protected] # once per project with 3D: it reads the scene for the playable
raea add [email protected] # once per project: the playable's 3D renderer
raea add [email protected] # once per project, if it uses raea/tone
raea render game.tsx -o out/video-ad.mp4 # the video ad
raea playable game.tsx -o out/playable --ios https://apps.apple.com/app/id123 --android https://play.google.com/store/apps/details?id=com.example
```
It prints each network's file and its size against the 5 MB cap. A 2D game's page is about 400 KB; 3D adds about
1 MB (three.js's scene graph and Bevy's shaders) and Tone.js about 360 KB for raea/tone, and the rest is the game's own pictures and sounds. `--networks applovin,google,preview` makes fewer, `--title` and `--cta` set the host's own card, and
It prints each network's file and its size against the 5 MB cap. A 2D game's page is about 400 KB; three.js adds about
1 MB for 3D and Tone.js about 360 KB for raea/tone, and the rest is the game's own pictures and sounds. `--networks applovin,google,preview` makes fewer, `--title` and `--cta` set the host's own card, and
`--orientation` sets what Google and TikTok are told.
Play the `preview` page yourself before handing it over: open it at a phone's size, drag, lose, and tap the card. In
+2 -12
View File
@@ -9,15 +9,5 @@ src/host/tony.bin is the tone-mapping table Tony McMapface, resampled by tools/t
https://github.com/bevyengine/bevy
Licensed under MIT OR Apache-2.0.
host/bevy.ts samples it as Bevy's tonemapping shader does.
src/host/bevy/programs.ts holds Bevy's PBR shaders (bevy_pbr's mesh, pbr and prepass programs, with bevy_render's
and bevy_core_pipeline's shader imports), composed by Bevy's shader cache and translated to GLSL ES by naga
(tools/bevy-glsl).
Bevy
By the Bevy contributors
https://github.com/bevyengine/bevy
Licensed under MIT OR Apache-2.0.
The rest of raea/playable is raea's own, under the repository's licence.
host/tonemap.ts samples it as Bevy's tonemapping shader does. The rest of raea/playable is raea's own, under the
repository's licence.
-16
View File
@@ -1,16 +0,0 @@
#!/usr/bin/env bash
# Bevy's PBR programs for a playable (docs/playables.feature PA11): tools/bevy-glsl composes Bevy's mesh, pbr and
# prepass shaders with WebGL2's defs and translates them to GLSL ES 3.00, into sdk/playable/src/host/bevy/programs.ts,
# with the hash of what they were made from beside it (programs.from). apps/playable's test fails when Bevy's shaders
# or the translator change and this isn't run.
# usage: bash sdk/playable/bevy/build.sh [TARGET_DIR]
set -euo pipefail
root=$(cd "$(dirname "$0")/../../.." && pwd)
target=${1:-$root/target/bevy-glsl}
out=$root/sdk/playable/src/host/bevy
work=$(mktemp -d)
trap 'rm -r "$work"' EXIT
cargo run -q --release --manifest-path "$root/tools/bevy-glsl/Cargo.toml" --target-dir "$target" -- "$root" "$work"
cp "$work/programs.ts" "$out/programs.ts"
bash "$root/sdk/playable/bevy/from.sh" > "$out/programs.from"
echo "programs.ts: $(wc -c < "$out/programs.ts" | tr -d ' ') bytes, $(gzip -9c "$out/programs.ts" | wc -c | tr -d ' ') gzipped"
-10
View File
@@ -1,10 +0,0 @@
#!/usr/bin/env bash
# what programs.ts is made from (build.sh): the translator, raea's vendored bevy_pbr shaders, and the Bevy and naga it
# composes them with (Cargo.lock's lines)
set -euo pipefail
root=$(cd "$(dirname "$0")/../../.." && pwd)
{
cat "$root"/tools/bevy-glsl/Cargo.toml "$root"/tools/bevy-glsl/src/*.rs
find "$root/vendor/bevy_pbr/src" \( -name '*.wesl' -o -name '*.wgsl' \) | LC_ALL=C sort | xargs cat
grep -A1 -E '^name = "(bevy_render|bevy_core_pipeline|bevy_shader)"$' "$root/Cargo.lock"
} | shasum -a 256 | cut -c1-64
-415
View File
@@ -1,415 +0,0 @@
// A playable's 3D drawn by Bevy's own PBR programs (docs/playables.feature PA11): Bevy's mesh, pbr and prepass shaders
// as Bevy composes them for a WebGL2 device, translated to GLSL ES by naga (tools/bevy-glsl, bevy/programs.ts), fed the
// uniform blocks Bevy's render world fills (bevy/fill.ts). The page's parts are read by raea's three.js host into a
// scene graph (scene.ts), which this reads back without three's renderer: each mesh's geometry and world transform,
// each material's values, each light in Bevy's units. As Bevy on WebGL2 draws: one directional shadow cascade, a
// forward pass into half float with 4x MSAA and reverse Z, the point and spot lights in one cluster, distance fog; then
// Bevy's TonyMcMapface through its own table, as the native engine's frame pass does. The export bundles it only for a
// game whose lint found a 3D kind (PA15).
import * as THREE from "three";
import type { Draw3d } from "./draw3d";
import { Scene3d } from "./scene";
import tony from "./tony.bin";
import { Block } from "./bevy/block";
import { Meshes, POINTS, Program, Textures, UNITS, programs } from "./bevy/gl";
import { PBR_FRAG, PBR_VERT, SHADOW_VERT } from "./bevy/programs";
import { ambientOf, cascade, fillFog, fillLights, fillMaterial, fillMesh, fillView, toLight, type Cascade, type Lights, type Surface } from "./bevy/fill";
const BATCH = 93; // PER_OBJECT_BUFFER_BATCH_SIZE: the meshes one uniform block holds
const N = Math.round(Math.cbrt(tony.length / 3));
const EMPTY_FS = "#version 300 es\nprecision highp float;\nvoid main() {}\n";
const TONE_VS = `#version 300 es
out vec2 uv;
void main() { vec2 p = vec2((gl_VertexID << 1) & 2, gl_VertexID & 2); uv = p; gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0); }`;
// the HDR target is drawn upside down (naga's coordinate flip): its first row is the picture's top
const TONE_FS = `#version 300 es
precision highp float;
precision highp sampler3D;
uniform sampler2D scene;
uniform sampler3D lut;
uniform float exposure;
in vec2 uv;
out vec4 color;
void main() {
vec4 c = texture(scene, vec2(uv.x, 1.0 - uv.y));
vec3 x = max(c.rgb / max(c.a, 1e-5), vec3(0.0)) * exposure;
vec3 t = (x / (x + 1.0)) * (${N - 1}.0 / ${N}.0) + 0.5 / ${N}.0;
color = vec4(texture(lut, clamp(t, 0.0, 1.0)).rgb * c.a, c.a);
}`;
/** One draw: a mesh (or one of an instanced mesh's copies), its geometry's range and its material's slot */
type Draw = {
geometry: THREE.BufferGeometry;
world: THREE.Matrix4;
material: number;
surface: Surface;
start: number;
count: number;
casts: boolean;
receives: boolean;
depth: number;
};
const ALIGN = (n: number, a: number) => Math.ceil(n / a) * a;
export function bevy3d(canvas: HTMLCanvasElement): Draw3d {
const gl = canvas.getContext("webgl2", { alpha: true, premultipliedAlpha: true, antialias: false, depth: false, stencil: false, powerPreference: "high-performance" });
if (!gl) throw new Error("raea playable: this browser has no WebGL2");
const hdr = !!gl.getExtension("EXT_color_buffer_float") || !!gl.getExtension("EXT_color_buffer_half_float");
const warned = new Set<string>();
const warn = (why: string) => {
if (warned.has(why)) return;
warned.add(why);
console.warn(`raea playable: ${why}`);
};
if (!hdr) warn("this browser can't draw into half float: the 3D's highlights clip before the tone curve");
// linked while the page's first frame is built; bound at the first draw
const [pbr, shadowProgram, tone] = programs(gl, [[PBR_VERT, PBR_FRAG], [SHADOW_VERT, EMPTY_FS], [TONE_VS, TONE_FS]]) as [Program, Program, Program];
let exposureAt: WebGLUniformLocation | null = null;
const align = gl.getParameter(gl.UNIFORM_BUFFER_OFFSET_ALIGNMENT) as number;
const blocks = {
view: new Block("view"),
lightView: new Block("view"),
lights: new Block("lights"),
clustered: new Block("clustered_lights"),
offsets: new Block("cluster_offsets_and_counts"),
lists: new Block("clusterable_object_index_lists"),
globals: new Block("globals"),
fog: new Block("fog"),
metadata: new Block("metadata"),
mesh: new Block("mesh", 1, ALIGN(new Block("mesh").size, align)),
material: new Block("material", 1, ALIGN(new Block("material").size, align)),
};
const buffers = new Map<Block, { b: WebGLBuffer; bytes: number }>();
const upload = (block: Block) => {
let k = buffers.get(block);
if (!k) buffers.set(block, (k = { b: gl.createBuffer()!, bytes: 0 }));
gl.bindBuffer(gl.UNIFORM_BUFFER, k.b);
if (k.bytes !== block.bytes.byteLength) {
gl.bufferData(gl.UNIFORM_BUFFER, block.bytes, gl.DYNAMIC_DRAW);
k.bytes = block.bytes.byteLength;
} else gl.bufferSubData(gl.UNIFORM_BUFFER, 0, block.bytes);
return k.b;
};
const bind = (name: string, block: Block, copy = 0) => {
const k = buffers.get(block)!;
gl.bindBufferRange(gl.UNIFORM_BUFFER, POINTS[name], k.b, copy * block.stride, block.size);
};
const textures = new Textures(gl);
const meshes = new Meshes(gl);
// Bevy's table for TonyMcMapface (tools/tony.ts), sRGB bytes already
const lut = gl.createTexture()!;
gl.bindTexture(gl.TEXTURE_3D, lut);
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
gl.texImage3D(gl.TEXTURE_3D, 0, gl.RGB8, N, N, N, 0, gl.RGB, gl.UNSIGNED_BYTE, tony);
for (const [k, v] of [[gl.TEXTURE_MIN_FILTER, gl.LINEAR], [gl.TEXTURE_MAG_FILTER, gl.LINEAR], [gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE], [gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE], [gl.TEXTURE_WRAP_R, gl.CLAMP_TO_EDGE]]) gl.texParameteri(gl.TEXTURE_3D, k, v);
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
// a depth texture sampled with comparison, as Bevy's shadow samplers are (reverse Z: greater-or-equal is lit)
const depthTexture = (target: number, size: number) => {
const t = gl.createTexture()!;
gl.bindTexture(target, t);
if (target === gl.TEXTURE_CUBE_MAP) for (let f = 0; f < 6; f++) gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, 0, gl.DEPTH_COMPONENT32F, size, size, 0, gl.DEPTH_COMPONENT, gl.FLOAT, null);
else gl.texImage2D(target, 0, gl.DEPTH_COMPONENT32F, size, size, 0, gl.DEPTH_COMPONENT, gl.FLOAT, null);
gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, gl.GEQUAL);
gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
return t;
};
// point lights' shadows aren't drawn: their cube is one texel, never sampled
const pointShadows = depthTexture(gl.TEXTURE_CUBE_MAP, 1);
let shadowSize = 0;
let shadowMap: WebGLTexture | null = null;
const shadowFbo = gl.createFramebuffer()!;
const shadowTarget = (size: number) => {
if (size === shadowSize && shadowMap) return;
if (shadowMap) gl.deleteTexture(shadowMap);
shadowSize = size;
shadowMap = depthTexture(gl.TEXTURE_2D, size);
gl.bindFramebuffer(gl.FRAMEBUFFER, shadowFbo);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, shadowMap, 0);
gl.drawBuffers([gl.NONE]);
gl.readBuffer(gl.NONE);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
};
shadowTarget(2048);
// the forward pass's targets: multisampled colour and depth, resolved into a texture the tone pass reads
const samples = Math.min(4, gl.getParameter(gl.MAX_SAMPLES) as number);
const msaaFbo = gl.createFramebuffer()!;
const resolveFbo = gl.createFramebuffer()!;
let color: WebGLRenderbuffer | null = null;
let depth: WebGLRenderbuffer | null = null;
let resolved: WebGLTexture | null = null;
let width = 1;
let height = 1;
const targets = () => {
if (color) gl.deleteRenderbuffer(color);
if (depth) gl.deleteRenderbuffer(depth);
if (resolved) gl.deleteTexture(resolved);
const format = hdr ? gl.RGBA16F : gl.RGBA8;
color = gl.createRenderbuffer()!;
gl.bindRenderbuffer(gl.RENDERBUFFER, color);
gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, format, width, height);
depth = gl.createRenderbuffer()!;
gl.bindRenderbuffer(gl.RENDERBUFFER, depth);
gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT32F, width, height);
gl.bindFramebuffer(gl.FRAMEBUFFER, msaaFbo);
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, color);
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depth);
resolved = gl.createTexture()!;
gl.bindTexture(gl.TEXTURE_2D, resolved);
gl.texStorage2D(gl.TEXTURE_2D, 1, format, width, height);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.bindFramebuffer(gl.FRAMEBUFFER, resolveFbo);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, resolved, 0);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
};
const scene = new Scene3d();
let frame = 0;
let seconds = 0;
/** The scene's meshes and lights, as Bevy's extraction would find them */
const gather = () => {
const draws: Draw[] = [];
const lights: Lights = { ambient: null, directional: [], points: [], spots: [] };
const materials = new Map<string, { slot: number; surface: Surface }>();
const ids = new WeakMap<THREE.Material, number>();
let nextId = 0;
const order: { m: THREE.Material; tint: THREE.Color | null; surface: Surface }[] = [];
const slotOf = (m: THREE.Material, tint: THREE.Color | null) => {
let id = ids.get(m);
if (id === undefined) ids.set(m, (id = nextId++));
const key = tint ? `${id}:${tint.getHexString()}` : `${id}`;
let k = materials.get(key);
if (!k) {
k = { slot: order.length, surface: { blend: false, doubleSided: false } };
materials.set(key, k);
order.push({ m, tint, surface: k.surface });
}
return k;
};
const camInv = scene.camera.matrixWorldInverse;
const p = new THREE.Vector3();
const add = (mesh: THREE.Mesh, world: THREE.Matrix4, tint: THREE.Color | null) => {
const g = mesh.geometry;
const mats = Array.isArray(mesh.material) ? mesh.material : [mesh.material];
const groups = Array.isArray(mesh.material) && g.groups.length ? g.groups : [{ start: 0, count: Infinity, materialIndex: 0 }];
for (const gr of groups) {
const m = mats[gr.materialIndex ?? 0];
if (!m || !m.visible) continue;
if (m instanceof THREE.ShadowMaterial) {
warn("a shadow catcher isn't drawn in a playable yet");
continue;
}
const k = slotOf(m, tint);
p.setFromMatrixPosition(world).applyMatrix4(camInv);
draws.push({ geometry: g, world, material: k.slot, surface: k.surface, start: gr.start, count: gr.count, casts: mesh.castShadow, receives: mesh.receiveShadow, depth: p.z });
}
};
scene.scene.updateMatrixWorld();
scene.scene.traverseVisible((o) => {
if (o instanceof THREE.InstancedMesh) {
const one = new THREE.Matrix4();
for (let i = 0; i < o.count; i++) {
o.getMatrixAt(i, one);
const tint = o.instanceColor ? new THREE.Color().fromArray(o.instanceColor.array, i * 3) : null;
add(o, o.matrixWorld.clone().multiply(one), tint);
}
} else if (o instanceof THREE.Mesh) add(o, o.matrixWorld, null);
else if (o instanceof THREE.AmbientLight || o instanceof THREE.HemisphereLight) lights.ambient = ambientOf(o, lights.ambient);
else if (o instanceof THREE.DirectionalLight) lights.directional.push(o);
else if (o instanceof THREE.SpotLight) {
lights.spots.push(o);
if (o.castShadow) warn("a spot light's shadow isn't drawn in a playable yet");
} else if (o instanceof THREE.PointLight) {
lights.points.push(o);
if (o.castShadow) warn("a point light's shadow isn't drawn in a playable yet");
} else if (o instanceof THREE.RectAreaLight) warn("a rect light isn't drawn in a playable yet");
else if (o instanceof THREE.Points || o instanceof THREE.Line || o instanceof THREE.Sprite) warn(`a ${o.type} isn't drawn in a playable yet`);
});
if (scene.scene.userData.raeaEnvironment) warn("an environment's light isn't drawn in a playable yet");
if (scene.effects.some((e) => e.kind === "Look")) warn("a paint look isn't drawn in a playable yet");
blocks.material.resize(order.length);
order.forEach(({ m, tint, surface }, slot) => Object.assign(surface, fillMaterial(blocks.material, slot, m, tint, warn)));
return { draws, lights, materials: order.length };
};
const drawAll = (list: Draw[], program: Program, main: boolean) => {
let batch = -1;
let cull: boolean | null = null;
for (let i = 0; i < list.length; i++) {
const d = list[i];
const m = meshes.get(d.geometry);
if (!m) continue;
const at = (d as Draw & { at: number }).at;
const b = Math.floor(at / BATCH);
if (b !== batch) {
bind("mesh", blocks.mesh, b);
batch = b;
}
gl.uniform1ui(program.first, at % BATCH);
const two = d.surface.doubleSided;
if (cull !== !two) {
if (two) gl.disable(gl.CULL_FACE);
else gl.enable(gl.CULL_FACE);
cull = !two;
}
if (main) {
bind("material", blocks.material, d.material);
const s = d.surface;
const tex = (unit: number, t: THREE.Texture | null | undefined) => {
gl.activeTexture(gl.TEXTURE0 + unit);
gl.bindTexture(gl.TEXTURE_2D, textures.get(t) ?? textures.white);
};
tex(UNITS.base_color_texture, s.map);
tex(UNITS.emissive_texture, s.emissiveMap);
tex(UNITS.metallic_roughness_texture, s.mrMap);
tex(UNITS.occlusion_texture, s.aoMap);
}
gl.bindVertexArray(m.vao);
const start = d.start;
const count = Math.min(d.count, m.count - start);
if (m.index) gl.drawElements(gl.TRIANGLES, count, m.index, start * (m.index === gl.UNSIGNED_INT ? 4 : 2));
else gl.drawArrays(gl.TRIANGLES, start, count);
}
gl.bindVertexArray(null);
};
return {
fit(w, h, scale) {
// the canvas is drawn at the screen's pixels, not the composition's
const ratio = Math.min(2, devicePixelRatio || 1) * scale;
const cw = Math.max(1, Math.floor(w * ratio));
const ch = Math.max(1, Math.floor(h * ratio));
if (cw !== width || ch !== height || !color) {
width = canvas.width = cw;
height = canvas.height = ch;
targets();
}
scene.fit(w, h);
},
sync(page, s) {
seconds = s;
scene.sync(page, s);
return scene.any;
},
draw() {
frame++;
const { draws, lights } = gather();
draws.forEach((d, i) => ((d as Draw & { at: number }).at = i));
blocks.mesh.resize(Math.ceil(draws.length / BATCH));
draws.forEach((d, i) => fillMesh(blocks.mesh, Math.floor(i / BATCH), i % BATCH, d.world, d.receives));
// the shadow: the first directional light that casts one, its cascade over what casts and catches
const sun = scene.settings.shadows ? lights.directional.find((l) => l.castShadow) : undefined;
let shadow: { light: THREE.DirectionalLight; cascade: Cascade } | null = null;
if (sun) {
shadowTarget(Math.min(scene.settings.shadowMap || 2048, gl.getParameter(gl.MAX_TEXTURE_SIZE) as number));
const bounds = new THREE.Box3();
const box = new THREE.Box3();
for (const d of draws) {
if (!d.geometry.boundingBox) d.geometry.computeBoundingBox();
bounds.union(box.copy(d.geometry.boundingBox!).applyMatrix4(d.world));
}
const c = cascade(toLight(sun), bounds, scene.camera, shadowSize);
if (c) shadow = { light: sun, cascade: c };
}
for (const b of [blocks.view, blocks.lightView, blocks.lights, blocks.clustered, blocks.offsets, blocks.lists, blocks.globals, blocks.fog]) b.resize(1);
fillFog(blocks.fog, scene.scene.fog as THREE.Fog | THREE.FogExp2 | null);
fillView(blocks.view, scene.camera, width, height, frame);
fillLights(blocks.lights, blocks.clustered, blocks.offsets, blocks.lists, lights, shadow, width, height);
blocks.globals.f("time", seconds);
blocks.globals.u("frame_count", frame);
for (const b of Object.values(blocks)) upload(b);
for (const [name, b] of [["lights", blocks.lights], ["clustered_lights", blocks.clustered], ["cluster_offsets_and_counts", blocks.offsets], ["clusterable_object_index_lists", blocks.lists], ["globals", blocks.globals], ["metadata", blocks.metadata], ["fog", blocks.fog]] as [string, Block][]) bind(name, b);
// Bevy's clip space flipped in y by naga: front faces wind clockwise in GL's
gl.frontFace(gl.CW);
gl.cullFace(gl.BACK);
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.GEQUAL);
gl.clearDepth(0);
// the shadow pass, from the light, as Bevy's prepass draws it
if (shadow) {
fillView(blocks.lightView, scene.camera, shadowSize, shadowSize, frame, undefined);
blocks.lightView.f("clip_from_world", shadow.cascade.clipFromWorld.elements);
upload(blocks.lightView);
bind("view", blocks.lightView);
// not sampled while it's drawn into
gl.activeTexture(gl.TEXTURE0 + UNITS.directional_shadow_textures);
gl.bindTexture(gl.TEXTURE_2D, null);
gl.bindFramebuffer(gl.FRAMEBUFFER, shadowFbo);
gl.viewport(0, 0, shadowSize, shadowSize);
gl.depthMask(true);
gl.disable(gl.BLEND);
gl.clear(gl.DEPTH_BUFFER_BIT);
shadowProgram.use();
drawAll(draws.filter((d) => d.casts && !d.surface.blend), shadowProgram, false);
}
// the forward pass: opaque, then blended back to front without writing depth
bind("view", blocks.view);
gl.bindFramebuffer(gl.FRAMEBUFFER, msaaFbo);
gl.viewport(0, 0, width, height);
gl.clearColor(0, 0, 0, 0);
gl.depthMask(true);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
pbr.use();
gl.activeTexture(gl.TEXTURE0 + UNITS.directional_shadow_textures);
gl.bindTexture(gl.TEXTURE_2D, shadowMap);
gl.activeTexture(gl.TEXTURE0 + UNITS.point_shadow_textures);
gl.bindTexture(gl.TEXTURE_CUBE_MAP, pointShadows);
gl.activeTexture(gl.TEXTURE0 + UNITS.raea_gi);
gl.bindTexture(gl.TEXTURE_2D, textures.none);
gl.disable(gl.BLEND);
drawAll(draws.filter((d) => !d.surface.blend), pbr, true);
const blended = draws.filter((d) => d.surface.blend).sort((a, b) => a.depth - b.depth);
if (blended.length) {
gl.enable(gl.BLEND);
// BlendState::ALPHA_BLENDING
gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
gl.depthMask(false);
drawAll(blended, pbr, true);
gl.depthMask(true);
gl.disable(gl.BLEND);
}
// resolved, then tone-mapped onto the canvas
gl.bindFramebuffer(gl.READ_FRAMEBUFFER, msaaFbo);
gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, resolveFbo);
gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.viewport(0, 0, width, height);
gl.disable(gl.DEPTH_TEST);
gl.disable(gl.CULL_FACE);
if (!exposureAt) {
tone.use();
gl.uniform1i(gl.getUniformLocation(tone.p, "scene"), 0);
gl.uniform1i(gl.getUniformLocation(tone.p, "lut"), 1);
exposureAt = gl.getUniformLocation(tone.p, "exposure");
}
tone.use();
gl.uniform1f(exposureAt, scene.settings.exposure * scene.settings.grade);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, resolved);
gl.activeTexture(gl.TEXTURE1);
gl.bindTexture(gl.TEXTURE_3D, lut);
gl.drawArrays(gl.TRIANGLES, 0, 3);
textures.done();
meshes.done();
},
};
}
-82
View File
@@ -1,82 +0,0 @@
// One of Bevy's uniform blocks as bytes (docs/playables.feature PA11): its fields written by their names in Bevy's
// shader structs, at the offsets naga laid them out (programs.ts LAYOUT), so the host fills a block as Bevy's render
// world fills its buffer. A path names nested fields with dots; each array on the way takes the next index.
import { LAYOUT } from "./programs";
type Plan = { at: number; strides: number[] };
export class Block {
readonly size: number;
bytes: ArrayBuffer;
f32: Float32Array;
u32: Uint32Array;
i32: Int32Array;
private readonly layout: Record<string, number>;
private readonly plans = new Map<string, Plan>();
/** `name` is the binding's name in Bevy's files (view, lights, mesh, material ...); `count` copies of it, each
* `stride` bytes apart (a buffer of many materials, or of batches of meshes) */
constructor(readonly name: string, count = 1, readonly stride = 0) {
const layout = LAYOUT[name];
if (!layout) throw new Error(`raea playable: Bevy's programs have no ${name} block`);
this.layout = layout;
this.size = layout.$size;
this.bytes = new ArrayBuffer(0);
this.f32 = new Float32Array(0);
this.u32 = new Uint32Array(0);
this.i32 = new Int32Array(0);
this.resize(count);
}
/** Room for `count` copies, cleared */
resize(count: number) {
const bytes = Math.max(1, count) * Math.max(this.stride, this.size);
if (bytes !== this.bytes.byteLength) {
this.bytes = new ArrayBuffer(bytes);
this.f32 = new Float32Array(this.bytes);
this.u32 = new Uint32Array(this.bytes);
this.i32 = new Int32Array(this.bytes);
} else new Uint8Array(this.bytes).fill(0);
}
private plan(path: string): Plan {
let p = this.plans.get(path);
if (p) return p;
p = { at: 0, strides: [] };
const top = this.layout["[]"];
if (top !== undefined) p.strides.push(top);
let pre = "";
for (const seg of path.split(".")) {
pre = pre ? `${pre}.${seg}` : seg;
const at = this.layout[pre];
if (at === undefined) throw new Error(`raea playable: Bevy's ${this.name} has no ${pre}`);
p.at += at;
const s = this.layout[`${pre}[]`];
if (s !== undefined) p.strides.push(s);
}
this.plans.set(path, p);
return p;
}
/** A field's byte offset in copy `copy`, each array on its path at the index given in turn */
at(path: string, copy = 0, ...index: number[]): number {
const p = this.plan(path);
let at = copy * this.stride + p.at;
for (let k = 0; k < p.strides.length; k++) at += (index[k] ?? 0) * p.strides[k];
return at;
}
f(path: string, v: number | ArrayLike<number>, copy = 0, ...index: number[]) {
const at = this.at(path, copy, ...index) >> 2;
if (typeof v === "number") this.f32[at] = v;
else this.f32.set(v, at);
}
u(path: string, v: number, copy = 0, ...index: number[]) {
this.u32[this.at(path, copy, ...index) >> 2] = v >>> 0;
}
i(path: string, v: number, copy = 0, ...index: number[]) {
this.i32[this.at(path, copy, ...index) >> 2] = v | 0;
}
}
-319
View File
@@ -1,319 +0,0 @@
// Bevy's uniform blocks filled from the scene (docs/playables.feature PA11), as Bevy's render world fills them:
// bevy_render's prepare_view_uniforms (the view), bevy_pbr's prepare_lights (lights, clustered lights, the light
// cluster's lists), MeshUniform::new (each mesh) and StandardMaterial's as_bind_group_shader_type (each material).
// The scene is raea's three.js scene graph (scene.ts); its lights are back in Bevy's units through units.ts, and its
// colours are linear already (three's working space is linear sRGB, Bevy's LinearRgba).
import * as THREE from "three";
import { AMBIENT, LUMENS, LUX, toRaea } from "@raea/r3f/units";
import type { Block } from "./block";
/** Bevy's default camera exposure, EV100 9.7 (Exposure::default) */
export const EXPOSURE = 1 / (1.2 * 2 ** 9.7);
const MAX_DIRECTIONAL = 10; // the programs' MAX_DIRECTIONAL_LIGHTS
const MAX_CLUSTERED = 204; // the clustered lights' array in a uniform block
const SQRT_2 = Math.SQRT2;
/** Bevy's matrices for a three.js camera: clip_from_view as Bevy makes it (reverse Z; a perspective one with no far
* plane), from three's projection's own terms so its zoom and view offset carry */
export function clipFromView(cam: THREE.Camera): THREE.Matrix4 {
const p = cam.projectionMatrix.elements;
const m = new THREE.Matrix4();
if (cam instanceof THREE.OrthographicCamera) {
const r = 1 / (cam.far - cam.near);
// glam's orthographic_rh(left, right, bottom, top, far, near): Bevy swaps near and far for reverse Z
m.set(p[0], 0, 0, p[12], 0, p[5], 0, p[13], 0, 0, r, cam.far * r, 0, 0, 0, 1);
} else {
const near = (cam as THREE.PerspectiveCamera).near ?? 0.1;
// perspective_infinite_reverse_rh, with three's x and y terms
m.set(p[0], 0, p[8], 0, 0, p[5], p[9], 0, 0, 0, 0, near, 0, 0, -1, 0);
}
return m;
}
/** The View block for a camera on a viewport of `width` x `height` pixels */
export function fillView(b: Block, cam: THREE.Camera, width: number, height: number, frame: number, clip?: THREE.Matrix4) {
const clipFromViewM = clip ?? clipFromView(cam);
const worldFromView = cam.matrixWorld.clone();
const viewFromWorld = worldFromView.clone().invert();
const viewFromClip = clipFromViewM.clone().invert();
const clipFromWorld = clipFromViewM.clone().multiply(viewFromWorld);
b.f("clip_from_world", clipFromWorld.elements);
b.f("unjittered_clip_from_world", clipFromWorld.elements);
b.f("world_from_clip", worldFromView.clone().multiply(viewFromClip).elements);
b.f("world_from_view", worldFromView.elements);
b.f("view_from_world", viewFromWorld.elements);
b.f("clip_from_view", clipFromViewM.elements);
b.f("view_from_clip", viewFromClip.elements);
const at = new THREE.Vector3().setFromMatrixPosition(worldFromView);
b.f("world_position", [at.x, at.y, at.z]);
b.f("lod_view_world_position", [at.x, at.y, at.z]);
b.f("exposure", EXPOSURE);
b.f("viewport", [0, 0, width, height]);
b.f("main_pass_viewport", [0, 0, width, height]);
// ColorGrading::default (it acts only where the tone curve is in this pass; the tone curve is the frame pass's)
b.f("color_grading.balance", [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0]);
for (const k of ["saturation", "contrast", "gamma", "gain"]) b.f(`color_grading.${k}`, [1, 1, 1]);
b.f("color_grading.midtone_range", [0.2, 0.7]);
b.f("color_grading.post_saturation", 1);
b.u("frame_count", frame);
}
/** A three.js light's colour in Bevy's LinearRgba */
const rgb = (c: THREE.Color, k: number) => [c.r * k, c.g * k, c.b * k, 1];
/** The scene's lights, found by walking it */
export type Lights = {
ambient: THREE.Color | null;
directional: THREE.DirectionalLight[];
points: THREE.PointLight[];
spots: THREE.SpotLight[];
};
/** The one shadow cascade (WebGL2 has room for one, as Bevy on WebGL2 does) */
export type Cascade = { clipFromWorld: THREE.Matrix4; texel: number };
/** The light's world rotation as Bevy's looking_to gives it: -Z along the light, +Z back toward it */
function worldFromLight(toLight: THREE.Vector3): THREE.Matrix4 {
const z = toLight.clone().normalize();
const up = Math.abs(z.y) > 0.9999 ? new THREE.Vector3(0, 0, 1) : new THREE.Vector3(0, 1, 0);
const x = new THREE.Vector3().crossVectors(up, z).normalize();
const y = new THREE.Vector3().crossVectors(z, x);
return new THREE.Matrix4().makeBasis(x, y, z);
}
/** Where a directional light shines from: its position less its target's */
export function toLight(l: THREE.DirectionalLight | THREE.SpotLight): THREE.Vector3 {
const from = new THREE.Vector3().setFromMatrixPosition(l.matrixWorld);
const to = new THREE.Vector3().setFromMatrixPosition(l.target.matrixWorld);
const d = from.sub(to);
return d.lengthSq() > 0 ? d.normalize() : new THREE.Vector3(0, 1, 0);
}
/** One cascade as bevy_light's calculate_cascade makes it, fitted to what casts and catches shadow: the scene's
* bounds, narrowed (across the light) to what the camera sees of them, as Bevy's cascades cover the view */
export function cascade(toward: THREE.Vector3, bounds: THREE.Box3, cam: THREE.Camera, size: number): Cascade | null {
if (bounds.isEmpty()) return null;
const wfl = worldFromLight(toward);
const lfw = wfl.clone().transpose();
const box = new THREE.Box3();
const p = new THREE.Vector3();
for (let i = 0; i < 8; i++) {
p.set(i & 1 ? bounds.max.x : bounds.min.x, i & 2 ? bounds.max.y : bounds.min.y, i & 4 ? bounds.max.z : bounds.min.z);
box.expandByPoint(p.applyMatrix4(lfw));
}
// what the camera sees, as far as the scene reaches from it: its frustum's corners in the light's space
const eye = new THREE.Vector3().setFromMatrixPosition(cam.matrixWorld);
const reach = Math.max(1, Math.sqrt(Math.max(bounds.distanceToPoint(eye) ** 2, ...[0, 1, 2, 3, 4, 5, 6, 7].map((i) => eye.distanceToSquared(new THREE.Vector3(i & 1 ? bounds.max.x : bounds.min.x, i & 2 ? bounds.max.y : bounds.min.y, i & 4 ? bounds.max.z : bounds.min.z))))));
const seen = new THREE.Box3();
const lfc = lfw.clone().multiply(cam.matrixWorld);
const inv = cam.projectionMatrixInverse;
for (let i = 0; i < 8; i++) {
// three's NDC corner, at the near plane or at `reach` along the view
p.set(i & 1 ? 1 : -1, i & 2 ? 1 : -1, -1).applyMatrix4(inv);
if (i & 4) {
if (cam instanceof THREE.OrthographicCamera) p.z = -reach;
else p.multiplyScalar(reach / Math.max(1e-6, -p.z));
}
seen.expandByPoint(p.applyMatrix4(lfc));
}
const min = new THREE.Vector2(Math.max(box.min.x, seen.min.x), Math.max(box.min.y, seen.min.y));
const max = new THREE.Vector2(Math.min(box.max.x, seen.max.x), Math.min(box.max.y, seen.max.y));
if (min.x >= max.x || min.y >= max.y) return null;
const margin = 0.02 * Math.max(max.x - min.x, max.y - min.y) + 0.05;
const diameter = Math.max(max.x - min.x, max.y - min.y) + 2 * margin;
const texel = diameter / size;
const near = new THREE.Vector3(
Math.floor((0.5 * (min.x + max.x)) / texel) * texel,
Math.floor((0.5 * (min.y + max.y)) / texel) * texel,
box.max.z + margin,
);
const cascadeFromWorld = lfw.clone().setPosition(-near.x, -near.y, -near.z);
const r = 1 / (near.z - (box.min.z - margin));
const clipFromCascade = new THREE.Matrix4().set(2 / diameter, 0, 0, 0, 0, 2 / diameter, 0, 0, 0, 0, r, 1, 0, 0, 0, 1);
return { clipFromWorld: clipFromCascade.multiply(cascadeFromWorld), texel };
}
/** The Lights block, the clustered lights and the one cluster's lists, as prepare_lights fills them for a 1x1x1
* cluster grid: every point and spot light in the one cluster */
export function fillLights(lights: Block, clustered: Block, offsets: Block, lists: Block, l: Lights, shadow: { light: THREE.DirectionalLight; cascade: Cascade } | null, width: number, height: number) {
const ambient = l.ambient ?? new THREE.Color(1, 1, 1).multiplyScalar(80);
lights.f("ambient_color", [ambient.r, ambient.g, ambient.b, 1]);
const dirs = l.directional.slice(0, MAX_DIRECTIONAL);
dirs.forEach((d, i) => {
const lux = toRaea("DirectionalLight", d.intensity) * LUX;
lights.f("directional_lights.color", rgb(d.color, lux), 0, i);
const t = toLight(d);
lights.f("directional_lights.direction_to_light", [t.x, t.y, t.z], 0, i);
const casts = shadow?.light === d;
lights.u("directional_lights.flags", casts ? 1 : 0, 0, i); // SHADOW_MAPS_ENABLED
lights.f("directional_lights.shadow_depth_bias", 0.02, 0, i);
lights.f("directional_lights.shadow_normal_bias", 1.8 * SQRT_2, 0, i);
lights.u("directional_lights.num_cascades", casts ? 1 : 0, 0, i);
lights.f("directional_lights.cascades_overlap_proportion", 0.3, 0, i);
lights.u("directional_lights.depth_texture_base_index", 0, 0, i);
lights.u("directional_lights.decal_index", 0xffffffff, 0, i);
lights.f("directional_lights.sun_disk_angular_size", 0.00930842, 0, i);
lights.f("directional_lights.sun_disk_intensity", 1, 0, i);
if (casts && shadow) {
lights.f("directional_lights.cascades.clip_from_world", shadow.cascade.clipFromWorld.elements, 0, i, 0);
lights.f("directional_lights.cascades.texel_size", shadow.cascade.texel, 0, i, 0);
lights.f("directional_lights.cascades.far_bound", 1e9, 0, i, 0);
}
});
const points = l.points.slice(0, MAX_CLUSTERED);
const spots = l.spots.slice(0, MAX_CLUSTERED - points.length);
const p = new THREE.Vector3();
const put = (k: number, light: THREE.PointLight | THREE.SpotLight, lumens: number) => {
const range = light.distance > 0 ? light.distance : 1000;
const c = rgb(light.color, lumens / (4 * Math.PI));
clustered.f("data.color_inverse_square_range", [c[0], c[1], c[2], 1 / (range * range)], 0, k);
p.setFromMatrixPosition(light.matrixWorld);
clustered.f("data.position_radius", [p.x, p.y, p.z, 0], 0, k);
clustered.f("data.shadow_depth_bias", 0.08, 0, k);
clustered.f("data.shadow_normal_bias", 0.6, 0, k);
clustered.f("data.shadow_map_near_z", 0.1, 0, k);
clustered.u("data.decal_index", 0xffffffff, 0, k);
clustered.f("data.range", range, 0, k);
};
points.forEach((pl, k) => put(k, pl, toRaea("PointLight", pl.intensity) * LUMENS));
spots.forEach((s, j) => {
const k = points.length + j;
put(k, s, toRaea("SpotLight", s.intensity) * LUMENS);
const dir = toLight(s).negate();
const outer = s.angle;
const inner = outer * (1 - s.penumbra);
const scale = 1 / Math.max(Math.cos(inner) - Math.cos(outer), 1e-4);
clustered.f("data.light_custom_data", [dir.x, dir.z, scale, -Math.cos(outer) * scale], 0, k);
clustered.u("data.flags", (1 << 5) | (dir.y < 0 ? 1 << 1 : 0), 0, k); // SPOT_LIGHT, SPOT_LIGHT_Y_NEGATIVE
clustered.f("data.spot_light_tan_angle", Math.tan(outer), 0, k);
});
// the one cluster: its lights from offset 0, its point lights then its spot lights (9 bits a count), and their
// indices four to a u32 (clustered_forward.wesl's WebGL2 unpacking)
offsets.u32[offsets.at("data") >> 2] = (points.length << 9) | spots.length;
for (let k = 0; k < points.length + spots.length; k++) lists.u32[(lists.at("data", 0, k >> 4) >> 2) + ((k >> 2) & 3)] |= k << (8 * (k & 3));
lights.u("cluster_dimensions", 1);
lights.u32[(lights.at("cluster_dimensions") >> 2) + 1] = 1;
lights.u32[(lights.at("cluster_dimensions") >> 2) + 2] = 1;
lights.u32[(lights.at("cluster_dimensions") >> 2) + 3] = 1;
lights.f("cluster_factors", [1 / width, 1 / height, 0, 0]);
lights.u("n_directional_lights", dirs.length);
lights.i("spot_light_shadowmap_offset", (shadow ? 1 : 0) - points.length);
lights.u("ambient_light_flags", 1); // AFFECTS_LIGHTMAPPED_MESHES
lights.u("n_rect_lights", 0);
}
/** One mesh's MeshUniform in its batch's slot */
export function fillMesh(b: Block, copy: number, slot: number, world: THREE.Matrix4, receives: boolean) {
const e = world.elements;
// world_from_local as Affine3::to_transpose: the affine's three rows, its translation in each w
const rows = [e[0], e[4], e[8], e[12], e[1], e[5], e[9], e[13], e[2], e[6], e[10], e[14]];
b.f("world_from_local", rows, copy, slot);
b.f("previous_world_from_local", rows, copy, slot);
// inverse_transpose_3x3, packed into a mat2x4 and an f32
const n = new THREE.Matrix3().getNormalMatrix(world).elements;
b.f("local_from_world_transpose_a", [n[0], n[1], n[2], n[3], n[4], n[5], n[6], n[7]], copy, slot);
b.f("local_from_world_transpose_b", n[8], copy, slot);
// no LOD (u16::MAX), SHADOW_RECEIVER, SIGN_DETERMINANT_MODEL_3X3
b.u("flags", 0xffff | (receives ? 1 << 29 : 0) | (world.determinant() > 0 ? 1 << 31 : 0), copy, slot);
b.u("current_skin_index", 0xffffffff, copy, slot);
b.u("material_and_lightmap_bind_group_slot", 0xffff << 16, copy, slot);
b.u("morph_descriptor_index", 0xffffffff, copy, slot);
}
/** What a material draws with: its block's flags say which pictures it samples */
export type Surface = {
map?: THREE.Texture | null;
emissiveMap?: THREE.Texture | null;
mrMap?: THREE.Texture | null;
aoMap?: THREE.Texture | null;
blend: boolean;
doubleSided: boolean;
};
type AnyMaterial = THREE.Material & Partial<THREE.MeshPhysicalMaterial> & { color?: THREE.Color; map?: THREE.Texture | null };
/** One material's StandardMaterialUniform, from a three.js material raea's host made (materials.ts), times an
* instance's colour */
export function fillMaterial(b: Block, copy: number, material: THREE.Material, tint: THREE.Color | null, warn: (why: string) => void): Surface {
const m = material as AnyMaterial;
const c = m.color ?? new THREE.Color(1, 1, 1);
const t = tint ?? { r: 1, g: 1, b: 1 };
b.f("base_color", [c.r * t.r, c.g * t.g, c.b * t.b, m.opacity], copy);
const unlit = m instanceof THREE.MeshBasicMaterial;
const e = m.emissive;
const k = m.emissiveIntensity ?? 1;
// a StandardMaterial's emissive in nits, its exposure weight 0 (it skips the camera's exposure, as natively)
if (e) b.f("emissive", [e.r * k, e.g * k, e.b * k, 0], copy);
b.f("attenuation_color", [1, 1, 1, 1], copy);
const map = m.map ?? null;
const uv = map ? (map.matrixAutoUpdate && map.updateMatrix(), map.matrix.elements) : [1, 0, 0, 0, 1, 0, 0, 0, 1];
b.f("uv_transform", [uv[0], uv[1], uv[2], 0, uv[3], uv[4], uv[5], 0, uv[6], uv[7], uv[8], 0], copy);
// Bevy's reflectance 0.5 is three's specularIntensity 1 (materials.ts), tinted by the specular colour
const r = 0.5 * (m.specularIntensity ?? 1);
const st = m.specularColor ?? { r: 1, g: 1, b: 1 };
b.f("reflectance", [st.r * r, st.g * r, st.b * r], copy);
b.f("perceptual_roughness", m.roughness ?? 0.5, copy);
b.f("metallic", m.metalness ?? 0, copy);
b.f("ior", m.ior ?? 1.5, copy);
b.f("attenuation_distance", Infinity, copy);
b.f("clearcoat", m.clearcoat ?? 0, copy);
b.f("clearcoat_perceptual_roughness", m.clearcoatRoughness ?? 0.5, copy);
b.f("anisotropy_rotation", [1, 0], copy);
b.f("parallax_depth_scale", 0.1, copy);
b.f("max_parallax_layer_count", 16, copy);
b.f("lightmap_exposure", 1, copy);
b.u("max_relief_mapping_search_steps", 5, copy);
b.u("deferred_lighting_pass_id", 1, copy);
if ((m.transmission ?? 0) > 0) warn("transmission isn't drawn in a playable yet");
if (m.normalMap) warn("a normal map isn't drawn in a playable yet");
if ((m as { vertexColors?: boolean }).vertexColors) warn("vertex colours aren't drawn in a playable yet");
const s: Surface = { map, emissiveMap: m.emissiveMap, aoMap: m.aoMap, blend: false, doubleSided: m.side === THREE.DoubleSide };
if (m.roughnessMap || m.metalnessMap) {
if (!m.roughnessMap || m.roughnessMap === m.metalnessMap) s.mrMap = m.roughnessMap ?? m.metalnessMap;
else warn("separate roughness and metalness maps aren't drawn in a playable yet (one metallic-roughness map is)");
}
let flags = 1 << 8; // FOG_ENABLED
if (s.map) flags |= 1 << 0;
if (s.emissiveMap) flags |= 1 << 1;
if (s.mrMap) flags |= 1 << 2;
if (s.aoMap) flags |= 1 << 3;
if (s.doubleSided) flags |= 1 << 4;
if (unlit) flags |= 1 << 5;
let cutoff = 0.5;
if (m.alphaTest > 0) {
flags |= 1 << 29; // ALPHA_MODE_MASK
cutoff = m.alphaTest;
} else if (m.transparent && (m.opacity < 1 || !!map)) {
flags |= 2 << 29; // ALPHA_MODE_BLEND
s.blend = true;
}
b.u("flags", flags, copy);
b.f("alpha_cutoff", cutoff, copy);
return s;
}
/** The ambient light's colour times its brightness in cd/m² (a hemisphere light is drawn as the ambient between its
* two colours) */
export function ambientOf(l: THREE.AmbientLight | THREE.HemisphereLight, had: THREE.Color | null): THREE.Color {
const nits = toRaea("AmbientLight", l.intensity) * AMBIENT;
const c = l instanceof THREE.HemisphereLight ? l.color.clone().lerp(l.groundColor, 0.5) : l.color.clone();
return (had ?? new THREE.Color(0, 0, 0)).add(c.multiplyScalar(nits));
}
/** Bevy's distance fog (prepare_fog's GpuFog) from the scene's, as the native engine makes it from a Fog part: a
* density makes it exponential, else linear from near to far; none is mode 0, which the shader passes over */
export function fillFog(b: Block, fog: THREE.Fog | THREE.FogExp2 | null) {
if (!fog) return;
const c = fog.color;
b.f("base_color", [c.r, c.g, c.b, 1]);
b.f("directional_light_color", [0, 0, 0, 0]);
b.f("directional_light_exponent", 8);
if (fog instanceof THREE.FogExp2) {
b.f("be", [fog.density, 0, 0]);
b.u("mode", 2);
} else {
b.f("be", [fog.near, fog.far, 0]);
b.u("mode", 1);
}
}
-214
View File
@@ -1,214 +0,0 @@
// WebGL2 plumbing for Bevy's programs in a playable (docs/playables.feature PA11): programs linked with each uniform
// block on its binding's point and each sampler on its unit, by the names Bevy's files give them (programs.ts), and
// the scene's geometry and pictures as GL buffers and textures, kept while the scene holds them.
import * as THREE from "three";
import { BLOCKS, SAMPLERS } from "./programs";
/** Each of Bevy's uniform bindings on its own binding point */
export const POINTS: Record<string, number> = {
view: 0, lights: 1, cluster_offsets_and_counts: 2, clusterable_object_index_lists: 3, clustered_lights: 4,
globals: 5, mesh: 6, material: 7, metadata: 8, fog: 9,
};
/** Each of Bevy's textures on its own unit */
export const UNITS: Record<string, number> = {
base_color_texture: 0, emissive_texture: 1, metallic_roughness_texture: 2, occlusion_texture: 3,
directional_shadow_textures: 4, point_shadow_textures: 5, raea_gi: 6,
};
/** A program linking: compiled and linked as soon as it's asked for, its blocks and samplers bound (which waits for
* the link) only when it's first drawn with, so the driver compiles it while the page's first frame is being built */
export class Program {
private done = false;
first: WebGLUniformLocation | null = null;
constructor(private gl: WebGL2RenderingContext, readonly p: WebGLProgram, private shaders: WebGLShader[]) {}
/** Linked and bound; throws when it didn't link */
use() {
const gl = this.gl;
gl.useProgram(this.p);
if (this.done) return;
this.done = true;
const p = this.p;
if (!gl.getProgramParameter(p, gl.LINK_STATUS)) {
const why = this.shaders.map((s) => gl.getShaderInfoLog(s)).find(Boolean) || gl.getProgramInfoLog(p);
throw new Error(`raea playable: Bevy's programs didn't link: ${why}`);
}
for (const s of this.shaders) gl.deleteShader(s);
const blocks = gl.getProgramParameter(p, gl.ACTIVE_UNIFORM_BLOCKS) as number;
for (let i = 0; i < blocks; i++) {
const name = gl.getActiveUniformBlockName(p, i) ?? "";
const point = POINTS[BLOCKS[name] ?? ""];
if (point === undefined) throw new Error(`raea playable: Bevy's uniform block ${name} has no binding`);
gl.uniformBlockBinding(p, i, point);
}
for (const [name, texture] of Object.entries(SAMPLERS)) {
const at = gl.getUniformLocation(p, name);
if (at) gl.uniform1i(at, UNITS[texture]);
}
this.first = gl.getUniformLocation(p, "naga_vs_first_instance");
}
}
function shader(gl: WebGL2RenderingContext, type: number, src: string): WebGLShader {
const s = gl.createShader(type)!;
gl.shaderSource(s, src);
gl.compileShader(s);
return s;
}
/** Programs compiled and linked, without waiting for either */
export function programs(gl: WebGL2RenderingContext, pairs: [string, string][]): Program[] {
return pairs.map(([vs, fs]) => {
const p = gl.createProgram()!;
const v = shader(gl, gl.VERTEX_SHADER, vs);
const f = shader(gl, gl.FRAGMENT_SHADER, fs);
gl.attachShader(p, v);
gl.attachShader(p, f);
gl.linkProgram(p);
return new Program(gl, p, [v, f]);
});
}
/** One picture's texture, made again when three.js marks it changed */
type Kept = { tex: WebGLTexture; version: number; seen: number };
const WRAP: Record<number, number> = { [THREE.RepeatWrapping]: 0x2901, [THREE.ClampToEdgeWrapping]: 0x812f, [THREE.MirroredRepeatWrapping]: 0x8370 };
/** The scene's pictures as textures: a colour picture in sRGB (sampled as linear, as Bevy's Rgba8UnormSrgb is) */
export class Textures {
private kept = new Map<THREE.Texture, Kept>();
private frame = 0;
/** Bevy's fallback for a texture a material doesn't have: white */
readonly white: WebGLTexture;
/** raea GI's screen with nothing in it: every pixel's light comes from the ambient light, as natively without GI */
readonly none: WebGLTexture;
constructor(private gl: WebGL2RenderingContext) {
this.white = this.pixel([255, 255, 255, 255]);
this.none = this.pixel([0, 0, 0, 0]);
}
private pixel(rgba: number[]): WebGLTexture {
const gl = this.gl;
const t = gl.createTexture()!;
gl.bindTexture(gl.TEXTURE_2D, t);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(rgba));
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
return t;
}
/** A three.js texture's GL texture, or undefined until its picture has loaded */
get(t: THREE.Texture | null | undefined): WebGLTexture | undefined {
if (!t) return undefined;
const img = t.image as (TexImageSource & { width?: number; height?: number; complete?: boolean; data?: ArrayBufferView }) | undefined;
if (!img || img.complete === false || !(img.width ?? 0)) return undefined;
const gl = this.gl;
let k = this.kept.get(t);
if (k && k.version === t.version) {
k.seen = this.frame;
return k.tex;
}
const tex = k?.tex ?? gl.createTexture()!;
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, t.flipY);
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, t.premultiplyAlpha);
gl.pixelStorei(gl.UNPACK_ALIGNMENT, t.unpackAlignment);
const srgb = t.colorSpace === THREE.SRGBColorSpace;
const internal = srgb ? gl.SRGB8_ALPHA8 : gl.RGBA8;
if (img.data) gl.texImage2D(gl.TEXTURE_2D, 0, internal, img.width!, img.height!, 0, gl.RGBA, gl.UNSIGNED_BYTE, img.data);
else gl.texImage2D(gl.TEXTURE_2D, 0, internal, gl.RGBA, gl.UNSIGNED_BYTE, img);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
gl.generateMipmap(gl.TEXTURE_2D);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, WRAP[t.wrapS] ?? gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, WRAP[t.wrapT] ?? gl.CLAMP_TO_EDGE);
this.kept.set(t, { tex, version: t.version, seen: this.frame });
return tex;
}
/** The end of a frame: a texture the scene no longer draws is let go */
done() {
for (const [t, k] of this.kept)
if (k.seen < this.frame - 1) {
this.gl.deleteTexture(k.tex);
this.kept.delete(t);
}
this.frame++;
}
}
/** One geometry's vertex array: positions, normals and UVs at Bevy's locations 0, 1 and 2, and its indices */
export type Mesh = { vao: WebGLVertexArrayObject; count: number; index: number; buffers: WebGLBuffer[]; version: string; seen: number };
export class Meshes {
private kept = new Map<THREE.BufferGeometry, Mesh>();
private frame = 0;
constructor(private gl: WebGL2RenderingContext) {}
get(g: THREE.BufferGeometry): Mesh | undefined {
const pos = g.attributes.position as THREE.BufferAttribute | undefined;
if (!pos) return undefined;
const nor = g.attributes.normal as THREE.BufferAttribute | undefined;
const uv = g.attributes.uv as THREE.BufferAttribute | undefined;
const version = `${pos.version}.${nor?.version ?? -1}.${uv?.version ?? -1}.${g.index?.version ?? -1}`;
let m = this.kept.get(g);
if (m && m.version === version) {
m.seen = this.frame;
return m;
}
const gl = this.gl;
if (m) this.free(m);
const vao = gl.createVertexArray()!;
gl.bindVertexArray(vao);
const buffers: WebGLBuffer[] = [];
const attr = (loc: number, a: THREE.BufferAttribute | undefined, size: number) => {
if (!a) {
gl.disableVertexAttribArray(loc);
gl.vertexAttrib4f(loc, 0, 0, 0, 0);
return;
}
const b = gl.createBuffer()!;
buffers.push(b);
gl.bindBuffer(gl.ARRAY_BUFFER, b);
gl.bufferData(gl.ARRAY_BUFFER, a.array as Float32Array, gl.STATIC_DRAW);
gl.enableVertexAttribArray(loc);
gl.vertexAttribPointer(loc, size, gl.FLOAT, false, 0, 0);
};
attr(0, pos, 3);
attr(1, nor, 3);
attr(2, uv, 2);
let index = 0;
if (g.index) {
const b = gl.createBuffer()!;
buffers.push(b);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, b);
const arr = g.index.array;
const wide = arr instanceof Uint32Array || (!(arr instanceof Uint16Array) && pos.count > 65535);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, wide ? Uint32Array.from(arr) : Uint16Array.from(arr), gl.STATIC_DRAW);
index = wide ? gl.UNSIGNED_INT : gl.UNSIGNED_SHORT;
}
gl.bindVertexArray(null);
m = { vao, count: g.index ? g.index.count : pos.count, index, buffers, version, seen: this.frame };
this.kept.set(g, m);
return m;
}
private free(m: Mesh) {
this.gl.deleteVertexArray(m.vao);
for (const b of m.buffers) this.gl.deleteBuffer(b);
}
done() {
for (const [g, m] of this.kept)
if (m.seen < this.frame - 1) {
this.free(m);
this.kept.delete(g);
}
this.frame++;
}
}
-1
View File
@@ -1 +0,0 @@
e79d0a380e1b6a00a0c7a9f21f1d6aa19fa1ec3673f1aea423c4ba4f087b9a65
-10
View File
@@ -1,10 +0,0 @@
// Bevy's PBR programs for a playable, as tools/bevy-glsl makes them (docs/playables.feature PA11): generated by
// sdk/playable/bevy/build.sh, not edited. Each program's GLSL ES 3.00; which of Bevy's bindings each uniform block
// and sampler is; each binding's fields at their byte offsets (nested fields from their struct's start, an array's
// stride under `name[]`).
export const PBR_VERT = "#version 300 es\nprecision highp float;\nprecision highp int;\nuniform uint naga_vs_first_instance;\nstruct _1bevy_pbr_render_1forward_io_Vertex {\nuint instance_index;\nvec3 position;\nvec3 normal;\nvec2 uv;\n};\nstruct _1bevy_pbr_render_1forward_io_VertexOutput {\nvec4 position;\nvec4 world_position;\nvec3 world_normal;\nvec2 uv;\nuint instance_index;\n};\nstruct _1bevy_pbr_render_1forward_io_UncompressedVertex {\nuint instance_index;\nvec3 position;\nvec3 normal;\nvec2 uv;\n};\nstruct _1bevy_render_mesh_1metadata_types_MeshMetadata {\nvec3 aabb_center;\nuint pad_a;\nvec3 aabb_half_extents;\nuint pad_b;\nvec4 uv_channels_min_and_extents[2];\n};\nstruct _1bevy_pbr_render_1mesh_types_Mesh {\nmat3x4 world_from_local;\nmat3x4 previous_world_from_local;\nmat2x4 local_from_world_transpose_a;\nfloat local_from_world_transpose_b;\nuint flags;\nuvec2 lightmap_uv_rect;\nuint first_vertex_index;\nuint current_skin_index;\nuint material_and_lightmap_bind_group_slot;\nuint tag;\nuint morph_descriptor_index;\nuint metadata_index;\n};\nstruct _1bevy_render_view_ColorGrading {\nmat3x3 balance;\nvec3 saturation;\nvec3 contrast;\nvec3 gamma;\nvec3 gain;\nvec3 lift;\nvec2 midtone_range;\nfloat exposure;\nfloat hue;\nfloat post_saturation;\n};\nstruct _1bevy_render_view_View {\nmat4x4 clip_from_world;\nmat4x4 unjittered_clip_from_world;\nmat4x4 world_from_clip;\nmat4x4 world_from_view;\nmat4x4 view_from_world;\nmat4x4 clip_from_view;\nmat4x4 view_from_clip;\nvec3 world_position;\nfloat exposure;\nvec4 viewport;\nvec4 main_pass_viewport;\nvec4 frustum[6];\nvec3 lod_view_world_position;\n_1bevy_render_view_ColorGrading color_grading;\nfloat mip_bias;\nuint frame_count;\n};\nlayout(std140) uniform _1bevy_render_mesh_1metadata_types_MeshMetadata_block_0Vertex { _1bevy_render_mesh_1metadata_types_MeshMetadata _group_2_binding_9_vs; };\nlayout(std140) uniform type_10_block_1Vertex { _1bevy_pbr_render_1mesh_types_Mesh _group_2_binding_0_vs[93]; };\nlayout(std140) uniform _1bevy_render_view_View_block_2Vertex { _1bevy_render_view_View _group_0_binding_0_vs; };\nlayout(location = 0) in vec3 _p2vs_location0;\nlayout(location = 1) in vec3 _p2vs_location1;\nlayout(location = 2) in vec2 _p2vs_location2;\nsmooth out vec4 _vs2fs_location0;\nsmooth out vec3 _vs2fs_location1;\nsmooth out vec2 _vs2fs_location2;\nflat out uint _vs2fs_location6;\n_1bevy_render_mesh_1metadata_types_MeshMetadata _1bevy_pbr_render_1mesh_functions_1get_metadata(uint instance_index) {\n_1bevy_render_mesh_1metadata_types_MeshMetadata _e2 = _group_2_binding_9_vs;\nreturn _e2;\n}\n_1bevy_pbr_render_1forward_io_UncompressedVertex _1bevy_pbr_render_1forward_io_1decompress_vertex(_1bevy_pbr_render_1forward_io_Vertex vertex_in, uint instance_index_1) {\n_1bevy_pbr_render_1forward_io_UncompressedVertex uncompressed_vertex = _1bevy_pbr_render_1forward_io_UncompressedVertex(0u, vec3(0.0), vec3(0.0), vec2(0.0));\n_1bevy_render_mesh_1metadata_types_MeshMetadata _e2 = _1bevy_pbr_render_1mesh_functions_1get_metadata(instance_index_1);\nuncompressed_vertex.instance_index = instance_index_1;\nuncompressed_vertex.position = vertex_in.position;\nuncompressed_vertex.normal = vertex_in.normal;\nuncompressed_vertex.uv = vertex_in.uv;\n_1bevy_pbr_render_1forward_io_UncompressedVertex _e11 = uncompressed_vertex;\nreturn _e11;\n}\nmat4x4 _1bevy_render_maths_2affine3_to_square(mat3x4 affine) {\nreturn transpose(mat4x4(affine[0], affine[1], affine[2], vec4(0.0, 0.0, 0.0, 1.0)));\n}\nmat4x4 _1bevy_pbr_render_1mesh_functions_3get_world_from_local(uint instance_index_2) {\nmat3x4 _e4 = _group_2_binding_0_vs[instance_index_2].world_from_local;\nmat4x4 _e5 = _1bevy_render_maths_2affine3_to_square(_e4);\nreturn _e5;\n}\nmat3x3 _1bevy_render_maths_4mat2x4_f32_to_mat3x3_unpack(mat2x4 a, float b) {\nreturn mat3x3(a[0].xyz, vec3(a[0].w, a[1].xy), vec3(a[1].zw, b));\n}\nvec3 _1bevy_pbr_render_1mesh_functions_4mesh_normal_local_to_world(vec3 vertex_normal, uint instance_index_3) {\nif (any(notEqual(vertex_normal, vec3(0.0)))) {\nmat2x4 _e9 = _group_2_binding_0_vs[instance_index_3].local_from_world_transpose_a;\nfloat _e13 = _group_2_binding_0_vs[instance_index_3].local_from_world_transpose_b;\nmat3x3 _e14 = _1bevy_render_maths_4mat2x4_f32_to_mat3x3_unpack(_e9, _e13);\nreturn normalize((_e14 * vertex_normal));\n} else {\nreturn vertex_normal;\n}\n}\nvec4 _1bevy_pbr_render_1mesh_functions_4mesh_position_local_to_world(mat4x4 world_from_local_1, vec4 vertex_position) {\nreturn (world_from_local_1 * vertex_position);\n}\nvec4 _1bevy_pbr_render_1view_transformations_3position_world_to_clip(vec3 world_pos) {\nmat4x4 _e3 = _group_0_binding_0_vs.clip_from_world;\nvec4 clip_pos = (_e3 * vec4(world_pos, 1.0));\nreturn clip_pos;\n}\nvoid main() {\n_1bevy_pbr_render_1forward_io_Vertex vertex_no_morph = _1bevy_pbr_render_1forward_io_Vertex((uint(gl_InstanceID) + naga_vs_first_instance), _p2vs_location0, _p2vs_location1, _p2vs_location2);\n_1bevy_pbr_render_1forward_io_VertexOutput out_ = _1Line truncated
export const PBR_FRAG = "#version 300 es\nprecision highp float;\nprecision highp int;\nstruct _1bevy_pbr_render_1forward_io_VertexOutput {\nvec4 position;\nvec4 world_position;\nvec3 world_normal;\nvec2 uv;\nuint instance_index;\n};\nstruct _1bevy_pbr_render_1forward_io_FragmentOutput {\nvec4 color;\n};\nstruct _1bevy_pbr_render_1pbr_types_StandardMaterial {\nvec4 base_color;\nvec4 emissive;\nvec4 attenuation_color;\nmat3x3 uv_transform;\nvec3 reflectance;\nfloat perceptual_roughness;\nfloat metallic;\nfloat diffuse_transmission;\nfloat specular_transmission;\nfloat thickness;\nfloat ior;\nfloat attenuation_distance;\nfloat clearcoat;\nfloat clearcoat_perceptual_roughness;\nfloat anisotropy_strength;\nvec2 anisotropy_rotation;\nuint flags;\nfloat alpha_cutoff;\nfloat parallax_depth_scale;\nfloat max_parallax_layer_count;\nfloat lightmap_exposure;\nuint max_relief_mapping_search_steps;\nuint deferred_lighting_pass_id;\n};\nstruct _1bevy_pbr_render_1pbr_types_PbrInput {\n_1bevy_pbr_render_1pbr_types_StandardMaterial material;\nvec3 diffuse_occlusion;\nfloat specular_occlusion;\nvec4 frag_coord;\nvec4 world_position;\nvec3 world_normal;\nvec3 N;\nvec3 V;\nvec3 lightmap_light;\nvec3 clearcoat_N;\nfloat anisotropy_strength;\nvec3 anisotropy_T;\nvec3 anisotropy_B;\nbool is_orthographic;\nuint flags;\nfloat directional_shadow_factor;\n};\nstruct _1bevy_pbr_render_1mesh_types_Mesh {\nmat3x4 world_from_local;\nmat3x4 previous_world_from_local;\nmat2x4 local_from_world_transpose_a;\nfloat local_from_world_transpose_b;\nuint flags;\nuvec2 lightmap_uv_rect;\nuint first_vertex_index;\nuint current_skin_index;\nuint material_and_lightmap_bind_group_slot;\nuint tag;\nuint morph_descriptor_index;\nuint metadata_index;\n};\nstruct _1bevy_render_view_ColorGrading {\nmat3x3 balance;\nvec3 saturation;\nvec3 contrast;\nvec3 gamma;\nvec3 gain;\nvec3 lift;\nvec2 midtone_range;\nfloat exposure;\nfloat hue;\nfloat post_saturation;\n};\nstruct _1bevy_render_view_View {\nmat4x4 clip_from_world;\nmat4x4 unjittered_clip_from_world;\nmat4x4 world_from_clip;\nmat4x4 world_from_view;\nmat4x4 view_from_world;\nmat4x4 clip_from_view;\nmat4x4 view_from_clip;\nvec3 world_position;\nfloat exposure;\nvec4 viewport;\nvec4 main_pass_viewport;\nvec4 frustum[6];\nvec3 lod_view_world_position;\n_1bevy_render_view_ColorGrading color_grading;\nfloat mip_bias;\nuint frame_count;\n};\nstruct _1bevy_pbr_render_1pbr_functions_SampleBias {\nfloat mip_bias;\n};\nstruct _1bevy_pbr_render_1pbr_lighting_LayerLightingInput {\nvec3 N;\nvec3 R;\nfloat NdotV;\nfloat perceptual_roughness;\nfloat roughness;\n};\nstruct _1bevy_pbr_render_1pbr_lighting_LightingInput {\n_1bevy_pbr_render_1pbr_lighting_LayerLightingInput layers[1];\nvec3 P;\nvec3 V;\nvec3 diffuse_color;\nfloat metallic;\nvec3 F0_dielectric;\nvec3 F0_metallic;\nvec2 F_ab;\n};\nstruct _1bevy_pbr_render_2mesh_view_types_DirectionalCascade {\nmat4x4 clip_from_world;\nfloat texel_size;\nfloat far_bound;\n};\nstruct _1bevy_pbr_render_2mesh_view_types_DirectionalLight {\n_1bevy_pbr_render_2mesh_view_types_DirectionalCascade cascades[1];\nvec4 color;\nvec3 direction_to_light;\nuint flags;\nfloat soft_shadow_size;\nfloat shadow_depth_bias;\nfloat shadow_normal_bias;\nuint num_cascades;\nfloat cascades_overlap_proportion;\nuint depth_texture_base_index;\nuint decal_index;\nfloat sun_disk_angular_size;\nfloat sun_disk_intensity;\n};\nstruct _1bevy_pbr_render_2mesh_view_types_RectLight {\nvec4 color;\nvec3 position;\nfloat width;\nvec3 right;\nfloat height;\nvec3 up;\nfloat range;\n};\nstruct _1bevy_pbr_render_2mesh_view_types_Lights {\n_1bevy_pbr_render_2mesh_view_types_DirectionalLight directional_lights[10];\nvec4 ambient_color;\nuvec4 cluster_dimensions;\nvec4 cluster_factors;\nuint n_directional_lights;\nint spot_light_shadowmap_offset;\nuint ambient_light_flags;\nuint n_rect_lights;\n_1bevy_pbr_render_2mesh_view_types_RectLight rect_lights[8];\n};\nstruct _1bevy_pbr_render_1clustered_forward_ClusterableObjectIndexRanges {\nuint first_point_light_index_offset;\nuint first_spot_light_index_offset;\nuint first_rect_light_index_offset;\nuint first_reflection_probe_index_offset;\nuint first_irradiance_volume_index_offset;\nuint first_decal_offset;\nuint last_clusterable_object_index_offset;\n};\nstruct _1bevy_pbr_render_2mesh_view_types_ClusterOffsetsAndCounts {\nuvec4 data[1024];\n};\nstruct _1bevy_pbr_render_2mesh_view_types_ClusterableObjectIndexLists {\nuvec4 data[1024];\n};\nstruct _1bevy_pbr_render_2mesh_view_types_ClusteredLight {\nvec4 light_custom_data;\nvec4 color_inverse_square_range;\nvec4 position_radius;\nuint flags;\nfloat shadow_depth_bias;\nfloat shadow_normal_bias;\nfloat spot_light_tan_angle;\nfloat soft_shadow_size;\nfloat shadow_map_near_z;\nuint decal_index;\nfloat range;\n};\nstruct _1bevy_pbr_render_2mesh_view_types_ClusteredLights {\n_1bevy_pbr_render_2mesh_view_types_ClusteredLight data[204];\n};\nstruct _1bevy_render_globals_Globals {\nfloat time;\nfloat delta_time;\nuint frame_count;\Line truncated
export const SHADOW_VERT = "#version 300 es\nprecision highp float;\nprecision highp int;\nuniform uint naga_vs_first_instance;\nstruct _1bevy_pbr_prepass_io_Vertex {\nuint instance_index;\nvec3 position;\n};\nstruct _1bevy_pbr_prepass_io_VertexOutput {\nvec4 position;\nvec4 world_position;\nfloat unclipped_depth;\nuint instance_index;\n};\nstruct _1bevy_pbr_prepass_io_UncompressedVertex {\nuint instance_index;\nvec3 position;\n};\nstruct _1bevy_render_mesh_1metadata_types_MeshMetadata {\nvec3 aabb_center;\nuint pad_a;\nvec3 aabb_half_extents;\nuint pad_b;\nvec4 uv_channels_min_and_extents[2];\n};\nstruct _1bevy_pbr_render_1mesh_types_Mesh {\nmat3x4 world_from_local;\nmat3x4 previous_world_from_local;\nmat2x4 local_from_world_transpose_a;\nfloat local_from_world_transpose_b;\nuint flags;\nuvec2 lightmap_uv_rect;\nuint first_vertex_index;\nuint current_skin_index;\nuint material_and_lightmap_bind_group_slot;\nuint tag;\nuint morph_descriptor_index;\nuint metadata_index;\n};\nstruct _1bevy_render_view_ColorGrading {\nmat3x3 balance;\nvec3 saturation;\nvec3 contrast;\nvec3 gamma;\nvec3 gain;\nvec3 lift;\nvec2 midtone_range;\nfloat exposure;\nfloat hue;\nfloat post_saturation;\n};\nstruct _1bevy_render_view_View {\nmat4x4 clip_from_world;\nmat4x4 unjittered_clip_from_world;\nmat4x4 world_from_clip;\nmat4x4 world_from_view;\nmat4x4 view_from_world;\nmat4x4 clip_from_view;\nmat4x4 view_from_clip;\nvec3 world_position;\nfloat exposure;\nvec4 viewport;\nvec4 main_pass_viewport;\nvec4 frustum[6];\nvec3 lod_view_world_position;\n_1bevy_render_view_ColorGrading color_grading;\nfloat mip_bias;\nuint frame_count;\n};\nlayout(std140) uniform _1bevy_render_mesh_1metadata_types_MeshMetadata_block_0Vertex { _1bevy_render_mesh_1metadata_types_MeshMetadata _group_2_binding_9_vs; };\nlayout(std140) uniform type_9_block_1Vertex { _1bevy_pbr_render_1mesh_types_Mesh _group_2_binding_0_vs[93]; };\nlayout(std140) uniform _1bevy_render_view_View_block_2Vertex { _1bevy_render_view_View _group_0_binding_0_vs; };\nlayout(location = 0) in vec3 _p2vs_location0;\nsmooth out vec4 _vs2fs_location4;\nsmooth out float _vs2fs_location6;\nflat out uint _vs2fs_location7;\n_1bevy_render_mesh_1metadata_types_MeshMetadata _1bevy_pbr_render_1mesh_functions_1get_metadata(uint instance_index) {\n_1bevy_render_mesh_1metadata_types_MeshMetadata _e2 = _group_2_binding_9_vs;\nreturn _e2;\n}\n_1bevy_pbr_prepass_io_UncompressedVertex _1bevy_pbr_prepass_io_1decompress_vertex(_1bevy_pbr_prepass_io_Vertex vertex_in, uint instance_index_1) {\n_1bevy_pbr_prepass_io_UncompressedVertex uncompressed_vertex = _1bevy_pbr_prepass_io_UncompressedVertex(0u, vec3(0.0));\n_1bevy_render_mesh_1metadata_types_MeshMetadata _e2 = _1bevy_pbr_render_1mesh_functions_1get_metadata(instance_index_1);\nuncompressed_vertex.instance_index = instance_index_1;\nuncompressed_vertex.position = vertex_in.position;\n_1bevy_pbr_prepass_io_UncompressedVertex _e7 = uncompressed_vertex;\nreturn _e7;\n}\nmat4x4 _1bevy_render_maths_2affine3_to_square(mat3x4 affine) {\nreturn transpose(mat4x4(affine[0], affine[1], affine[2], vec4(0.0, 0.0, 0.0, 1.0)));\n}\nmat4x4 _1bevy_pbr_render_1mesh_functions_3get_world_from_local(uint instance_index_2) {\nmat3x4 _e4 = _group_2_binding_0_vs[instance_index_2].world_from_local;\nmat4x4 _e5 = _1bevy_render_maths_2affine3_to_square(_e4);\nreturn _e5;\n}\nvec4 _1bevy_pbr_render_1mesh_functions_4mesh_position_local_to_world(mat4x4 world_from_local_1, vec4 vertex_position) {\nreturn (world_from_local_1 * vertex_position);\n}\nvec4 _1bevy_pbr_render_1view_transformations_3position_world_to_clip(vec3 world_pos) {\nmat4x4 _e3 = _group_0_binding_0_vs.clip_from_world;\nvec4 clip_pos = (_e3 * vec4(world_pos, 1.0));\nreturn clip_pos;\n}\nvoid main() {\n_1bevy_pbr_prepass_io_Vertex vertex_no_morph = _1bevy_pbr_prepass_io_Vertex((uint(gl_InstanceID) + naga_vs_first_instance), _p2vs_location0);\n_1bevy_pbr_prepass_io_VertexOutput out_ = _1bevy_pbr_prepass_io_VertexOutput(vec4(0.0), vec4(0.0), 0.0, 0u);\n_1bevy_pbr_prepass_io_UncompressedVertex vertex_1 = _1bevy_pbr_prepass_io_UncompressedVertex(0u, vec3(0.0));\nmat4x4 world_from_local = mat4x4(0.0);\n_1bevy_pbr_prepass_io_UncompressedVertex _e3 = _1bevy_pbr_prepass_io_1decompress_vertex(vertex_no_morph, vertex_no_morph.instance_index);\nvertex_1 = _e3;\nmat4x4 _e6 = _1bevy_pbr_render_1mesh_functions_3get_world_from_local(vertex_no_morph.instance_index);\nworld_from_local = _e6;\nmat4x4 _e9 = world_from_local;\nvec3 _e11 = vertex_1.position;\nvec4 _e14 = _1bevy_pbr_render_1mesh_functions_4mesh_position_local_to_world(_e9, vec4(_e11, 1.0));\nout_.world_position = _e14;\nvec4 _e17 = out_.world_position;\nvec4 _e19 = _1bevy_pbr_render_1view_transformations_3position_world_to_clip(_e17.xyz);\nout_.position = _e19;\nfloat _e23 = out_.position.z;\nout_.unclipped_depth = _e23;\nfloat _e28 = out_.position.z;\nout_.position.z = min(_e28, 1.0);\nout_.instance_index = vertex_no_morph.instance_index;\n_1bevy_pbr_prepass_io_VertexOutput _eLine truncated
export const BLOCKS: Record<string, string> = {"_1bevy_pbr_render_1pbr_types_StandardMaterial_block_1Fragment":"material","_1bevy_pbr_render_2mesh_view_types_ClusterOffsetsAndCounts_block_4Fragment":"cluster_offsets_and_counts","_1bevy_pbr_render_2mesh_view_types_ClusterableObjectIndexLists_block_5Fragment":"clusterable_object_index_lists","_1bevy_pbr_render_2mesh_view_types_ClusteredLights_block_6Fragment":"clustered_lights","_1bevy_pbr_render_2mesh_view_types_Fog_block_8Fragment":"fog","_1bevy_pbr_render_2mesh_view_types_Lights_block_3Fragment":"lights","_1bevy_render_globals_Globals_block_7Fragment":"globals","_1bevy_render_mesh_1metadata_types_MeshMetadata_block_0Vertex":"metadata","_1bevy_render_view_View_block_2Fragment":"view","_1bevy_render_view_View_block_2Vertex":"view","type_10_block_0Fragment":"mesh","type_10_block_1Vertex":"mesh","type_9_block_1Vertex":"mesh"};
export const SAMPLERS: Record<string, string> = {"_group_0_binding_2_fs":"point_shadow_textures","_group_0_binding_41_fs":"raea_gi","_group_0_binding_5_fs":"directional_shadow_textures","_group_3_binding_1_fs":"base_color_texture","_group_3_binding_3_fs":"emissive_texture","_group_3_binding_5_fs":"metallic_roughness_texture","_group_3_binding_7_fs":"occlusion_texture"};
export const LAYOUT: Record<string, Record<string, number>> = {"cluster_offsets_and_counts":{"$size":16384,"data":0,"data[]":16},"clusterable_object_index_lists":{"$size":16384,"data":0,"data[]":16},"clustered_lights":{"$size":16320,"data":0,"data.color_inverse_square_range":16,"data.decal_index":72,"data.flags":48,"data.light_custom_data":0,"data.position_radius":32,"data.range":76,"data.shadow_depth_bias":52,"data.shadow_map_near_z":68,"data.shadow_normal_bias":56,"data.soft_shadow_size":64,"data.spot_light_tan_angle":60,"data[]":80},"fog":{"$size":64,"base_color":0,"be":32,"bi":48,"directional_light_color":16,"directional_light_exponent":44,"mode":60},"globals":{"$size":16,"_webgl2_padding":12,"delta_time":4,"frame_count":8,"time":0},"lights":{"$size":2176,"ambient_color":1600,"ambient_light_flags":1656,"cluster_dimensions":1616,"cluster_factors":1632,"directional_lights":0,"directional_lights.cascades":0,"directional_lights.cascades.clip_from_world":0,"directional_lights.cascades.far_bound":68,"directional_lights.cascades.texel_size":64,"directional_lights.cascades[]":80,"directional_lights.cascades_overlap_proportion":128,"directional_lights.color":80,"directional_lights.decal_index":136,"directional_lights.depth_texture_base_index":132,"directional_lights.direction_to_light":96,"directional_lights.flags":108,"directional_lights.num_cascades":124,"directional_lights.shadow_depth_bias":116,"directional_lights.shadow_normal_bias":120,"directional_lights.soft_shadow_size":112,"directional_lights.sun_disk_angular_size":140,"directional_lights.sun_disk_intensity":144,"directional_lights[]":160,"n_directional_lights":1648,"n_rect_lights":1660,"rect_lights":1664,"rect_lights.color":0,"rect_lights.height":44,"rect_lights.position":16,"rect_lights.range":60,"rect_lights.right":32,"rect_lights.up":48,"rect_lights.width":28,"rect_lights[]":64,"spot_light_shadowmap_offset":1652},"material":{"$size":192,"alpha_cutoff":164,"anisotropy_rotation":152,"anisotropy_strength":144,"attenuation_color":32,"attenuation_distance":132,"base_color":0,"clearcoat":136,"clearcoat_perceptual_roughness":140,"deferred_lighting_pass_id":184,"diffuse_transmission":116,"emissive":16,"flags":160,"ior":128,"lightmap_exposure":176,"max_parallax_layer_count":172,"max_relief_mapping_search_steps":180,"metallic":112,"parallax_depth_scale":168,"perceptual_roughness":108,"reflectance":96,"specular_transmission":120,"thickness":124,"uv_transform":48},"mesh":{"$size":16368,"[]":176,"current_skin_index":148,"first_vertex_index":144,"flags":132,"lightmap_uv_rect":136,"local_from_world_transpose_a":96,"local_from_world_transpose_b":128,"material_and_lightmap_bind_group_slot":152,"metadata_index":164,"morph_descriptor_index":160,"previous_world_from_local":48,"tag":156,"world_from_local":0},"metadata":{"$size":64,"aabb_center":0,"aabb_half_extents":16,"pad_a":12,"pad_b":28,"uv_channels_min_and_extents":32,"uv_channels_min_and_extents[]":16},"view":{"$size":784,"clip_from_view":320,"clip_from_world":0,"color_grading":608,"color_grading.balance":0,"color_grading.contrast":64,"color_grading.exposure":136,"color_grading.gain":96,"color_grading.gamma":80,"color_grading.hue":140,"color_grading.lift":112,"color_grading.midtone_range":128,"color_grading.post_saturation":144,"color_grading.saturation":48,"exposure":460,"frame_count":772,"frustum":496,"frustum[]":16,"lod_view_world_position":592,"main_pass_viewport":480,"mip_bias":768,"unjittered_clip_from_world":64,"view_from_clip":384,"view_from_world":256,"viewport":464,"world_from_clip":128,"world_from_view":192,"world_position":448}};
+31
View File
@@ -0,0 +1,31 @@
// A playable's 3D drawn by three.js (raea's three.js host, sdk/r3f/src/three, through scene.ts), tone-mapped by
// Bevy's own curve (tonemap.ts). The export bundles it only for a game whose lint found a 3D kind (PA15).
import * as THREE from "three";
import type { Draw3d } from "./draw3d";
import { Scene3d } from "./scene";
import { Tonemap } from "./tonemap";
export function three3d(canvas: HTMLCanvasElement): Draw3d {
// the 3D is tone-mapped by its own pass (antialiased in its target) and left transparent where nothing was drawn
const renderer = new THREE.WebGLRenderer({ canvas, antialias: false, alpha: true, premultipliedAlpha: true, powerPreference: "high-performance" });
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const tonemap = new Tonemap(renderer);
const scene = new Scene3d();
return {
fit(width, height, scale) {
// the canvas is drawn at the screen's pixels, not the composition's
renderer.setPixelRatio(Math.min(2, devicePixelRatio || 1) * scale);
renderer.setSize(width, height, false);
tonemap.resize();
scene.fit(width, height);
},
sync(page, seconds) {
scene.sync(page, seconds);
return scene.any;
},
draw() {
tonemap.render(scene.scene, scene.camera);
},
};
}
+65
View File
@@ -0,0 +1,65 @@
// Bevy's tone mapping in the playable (docs/playables.feature PA10): the 3D drawn into a half-float target with no
// tone curve, then one full-screen pass maps it through TonyMcMapface (Bevy's default, tools/tony.ts's table) and
// encodes sRGB, as bevy_core_pipeline's tonemapping.wesl does. Where nothing was drawn it stays transparent, so the
// page's background shows through as it does under the native engine's 3D.
import * as THREE from "three";
import tony from "./tony.bin";
const N = Math.round(Math.cbrt(tony.length / 3));
const FRAG = /* glsl */ `
precision highp float;
precision highp sampler3D;
uniform sampler2D scene;
uniform sampler3D lut;
in vec2 vUv;
out vec4 color;
void main() {
vec4 c = texture(scene, vUv);
vec3 x = max(c.rgb / max(c.a, 1e-5), vec3(0.0));
vec3 uv = (x / (x + 1.0)) * (${N - 1}.0 / ${N}.0) + 0.5 / ${N}.0;
// the table holds sRGB-encoded bytes, already the screen's values
color = vec4(texture(lut, clamp(uv, 0.0, 1.0)).rgb * c.a, c.a);
}`;
const VERT = /* glsl */ `
in vec3 position;
in vec2 uv;
out vec2 vUv;
void main() { vUv = uv; gl_Position = vec4(position.xy, 0.0, 1.0); }`;
export class Tonemap {
private target: THREE.WebGLRenderTarget;
private quad: THREE.Mesh;
private camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
constructor(private renderer: THREE.WebGLRenderer) {
renderer.toneMapping = THREE.NoToneMapping;
renderer.outputColorSpace = THREE.LinearSRGBColorSpace;
this.target = new THREE.WebGLRenderTarget(1, 1, { type: THREE.HalfFloatType, samples: 4, colorSpace: THREE.LinearSRGBColorSpace });
const rgba = new Uint8Array(N * N * N * 4);
for (let i = 0; i < N * N * N; i++) rgba.set([tony[i * 3], tony[i * 3 + 1], tony[i * 3 + 2], 255], i * 4);
const lut = new THREE.Data3DTexture(rgba, N, N, N);
lut.minFilter = lut.magFilter = THREE.LinearFilter;
lut.unpackAlignment = 1;
lut.needsUpdate = true;
const material = new THREE.RawShaderMaterial({ glslVersion: THREE.GLSL3, vertexShader: VERT, fragmentShader: FRAG, uniforms: { scene: { value: this.target.texture }, lut: { value: lut } }, transparent: true, premultipliedAlpha: true, blending: THREE.NoBlending, depthTest: false, depthWrite: false });
this.quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), material);
}
/** The target sized to the canvas's drawing buffer */
resize() {
const s = this.renderer.getDrawingBufferSize(new THREE.Vector2());
this.target.setSize(s.x, s.y);
}
render(scene: THREE.Scene, camera: THREE.Camera) {
const r = this.renderer;
r.setRenderTarget(this.target);
r.setClearColor(0x000000, 0);
r.clear();
r.render(scene, camera);
r.setRenderTarget(null);
r.render(this.quad, this.camera);
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
// Bevy's TonyMcMapface tone-mapping table for the playable host (docs/playables.feature PA10): bevy_core_pipeline's
// tony_mc_mapface.ktx2 (48³, E5B9G9R9 floats, zstd; MIT, Tomasz Stachowiak) resampled to N³ and stored as sRGB-encoded
// RGB bytes, which host/bevy.ts's tone pass samples as Bevy's tonemapping.wesl does.
// RGB bytes, which host/tonemap.ts samples as Bevy's tonemapping.wesl does.
// `bun tools/tony.ts N OUT.bin` (N = 48 keeps Bevy's own size).
import { readdirSync } from "node:fs";
import { homedir } from "node:os";
-12
View File
@@ -16,18 +16,6 @@ export const GEOMETRY: Record<string, (a: number[]) => THREE.BufferGeometry> = {
Ring: (a) => new THREE.RingGeometry(a[0] ?? 0.5, a[1] ?? 1, 48),
};
/** A Plane3d's one face (its Mesh's data-shape "plane(nx, ny, nz, w, h)"), as Bevy's PlaneMeshBuilder makes it: the +Y
* plane, w along x and h along -z, turned to its normal by the shortest arc. Its Box child (a box with no depth, for
* three's sake) would face both ways, and three's BoxGeometry points a flat side's normal down */
export function planeOf(kind: string, el: Element): THREE.BufferGeometry | undefined {
const m = kind === "Box" ? /^plane\(([^)]*)\)$/.exec(el.parentElement?.getAttribute("data-shape") ?? "") : null;
if (!m) return undefined;
const [nx, ny, nz, w, h] = m[1].split(",").map(Number);
const g = new THREE.PlaneGeometry(w, h).rotateX(-Math.PI / 2);
const n = new THREE.Vector3(nx, ny, nz).normalize();
return g.applyQuaternion(new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(0, 1, 0), n));
}
interface BufferSpec {
positions: number[];
indices?: number[];
+2 -2
View File
@@ -8,7 +8,7 @@ import { HDRLoader } from "three/examples/jsm/loaders/HDRLoader.js";
import type { Sky } from "three/examples/jsm/objects/Sky.js";
import { paintLook, paintTone } from "./paint";
import { fire, flat, grass, placeFlat, plateTexture, richText, screenCard, sky, splatPoints } from "./extras";
import { GEOMETRY, geometryOfShape, planeOf, shapesReady } from "./geometry";
import { GEOMETRY, geometryOfShape, shapesReady } from "./geometry";
import { KINDS, PRIMITIVES } from "./kinds";
import { TONE, fitCamera, makeLight, setCamera, setLight, vec } from "./lights";
import { MATERIAL, paint, texture, vertexColoured } from "./materials";
@@ -390,7 +390,7 @@ export class Scene3d {
const mesh = owner?.obj instanceof THREE.Mesh ? owner.obj : undefined;
if (mesh) {
k.geometry?.dispose();
k.geometry = planeOf(kind, el) ?? GEOMETRY[kind](Array.isArray(p.args) ? (p.args as number[]) : []);
k.geometry = GEOMETRY[kind](Array.isArray(p.args) ? (p.args as number[]) : []);
mesh.geometry = k.geometry;
}
return k;
File diff suppressed because it is too large. Load diff
+2 -23
View File
@@ -1,4 +1,5 @@
// Generated from raea-core-brief (core/brief) by its `goal_declarations`; edit the Rust, not this.
import type { Beat } from "./brief.gen";
export type Goal = { kind: GoalKind,
/**
@@ -232,29 +233,7 @@ text?: string, formats?: Array<string>, seconds?: [number, number],
* the cut's beats in order (docs/goal.feature MK48): what each must make the viewer feel and understand, decided
* before the cut (Murch: emotion and story weigh most), and its pace
*/
beats?: Array<CutBeat>, };
export type CutBeat = {
/**
* where it starts, in seconds from the cut's start (0 for the first)
*/
at: number,
/**
* what the viewer feels here, in the person's words ("the itch of a chore left undone")
*/
feel: string,
/**
* what the viewer understands by its end ("the app does the reminding")
*/
story?: string,
/**
* its average shot length in seconds: the shots inside it average within a third of this
*/
asl?: number,
/**
* how its shot lengths move: "build" (shorter as it goes), "release" (longer) or "hold" (even)
*/
tempo?: string, };
beats?: Array<Beat>, };
export type Phrase = {
/**
+1 -1
Submodule skills updated: fb72c5e256...a2481c23ef.
-2221
View File
File diff suppressed because it is too large. Load diff
-17
View File
@@ -1,17 +0,0 @@
[package]
name = "bevy-glsl"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "Bevy's PBR programs for a playable (docs/playables.feature PA11): composed by Bevy's own ShaderCache with WebGL2's defs, translated to GLSL ES 3.00 by naga, with each uniform block's layout"
# its own workspace: run on demand (sdk/playable/bevy/build.sh), not part of raea's build
[workspace]
[dependencies]
bevy_shader = "=0.20.0"
bevy_asset = "=0.20.0"
naga = { version = "=30.0.1", features = ["wgsl-in", "glsl-out"] }
serde_json = "1"
uuid = { version = "1", features = ["v4"] }
-283
View File
@@ -1,283 +0,0 @@
//! Bevy's PBR programs for a playable (docs/playables.feature PA11). Bevy's own ShaderCache composes them, from Bevy's
//! shader files (raea's vendored bevy_pbr, and bevy_render and bevy_core_pipeline at the version raea builds), with the
//! defs Bevy's mesh and prepass pipelines give a WebGL2 device; naga translates each entry point to GLSL ES 3.00 for
//! WebGL. Beside the sources, bevy.json says for each program which uniform block and sampler is which binding and
//! lays out each block's struct (offsets, sizes, strides), so the host fills them as Bevy's render world does.
//!
//! cargo run --release --manifest-path tools/bevy-glsl/Cargo.toml -- RAEA_ROOT OUT_DIR
use bevy_asset::AssetId;
use bevy_shader::{Shader, ShaderCache, ShaderCacheError, ShaderCacheSource, ShaderDefVal, ValidateShader};
use naga::back::glsl;
use naga::proc::{BoundsCheckPolicies, Layouter};
use naga::{AddressSpace, ShaderStage, TypeInner};
use serde_json::{Map, Value, json};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
fn keep(_: &(), source: ShaderCacheSource, _: &ValidateShader) -> Result<String, ShaderCacheError> {
match source {
ShaderCacheSource::Wgsl(s) => Ok(s),
ShaderCacheSource::SpirV(_) => panic!("a SPIR-V shader in the pbr program"),
}
}
fn def(name: &str) -> ShaderDefVal {
ShaderDefVal::Bool(name.to_string().into(), true)
}
fn uint(name: &str, v: u32) -> ShaderDefVal {
ShaderDefVal::UInt(name.to_string().into(), v)
}
/// WebGL2's limits as Bevy reads them (render/light.rs under `webgl`, gpu_array_buffer.rs's batch size: a 16 KB
/// uniform binding over the 176-byte MeshUniform)
fn per_file_defs(path: &str) -> Vec<ShaderDefVal> {
match path {
"bevy_pbr/render/mesh_view_types.wesl" => vec![uint("MAX_DIRECTIONAL_LIGHTS", 10), uint("MAX_CASCADES_PER_LIGHT", 1), uint("MAX_RECT_LIGHTS", 8)],
"bevy_pbr/render/mesh_bindings.wesl" => vec![uint("PER_OBJECT_BUFFER_BATCH_SIZE", 93)],
_ => vec![],
}
}
/// What every program on a WebGL2 device gets (mesh.rs specialize, view and device parts)
fn webgl_defs() -> Vec<ShaderDefVal> {
vec![
def("WEBGL2"),
def("NO_ARRAY_TEXTURES_SUPPORT"),
def("NO_CUBE_ARRAY_TEXTURES_SUPPORT"),
def("SIXTEEN_BYTE_ALIGNMENT"),
uint("AVAILABLE_STORAGE_BUFFER_BINDINGS", 0),
uint("MAX_DIRECTIONAL_LIGHTS", 10),
uint("MAX_CASCADES_PER_LIGHT", 1),
uint("PER_OBJECT_BUFFER_BATCH_SIZE", 93),
def("MESH_PIPELINE"),
def("VERTEX_OUTPUT_INSTANCE_INDEX"),
def("VERTEX_POSITIONS"),
def("VERTEX_NORMALS"),
def("VERTEX_UVS"),
def("VERTEX_UVS_A"),
def("METADATA_USE_UNIFORM_BUFFERS"),
// no VIEW_PROJECTION_PERSPECTIVE: the shader reads the projection's kind from the view, so an orthographic
// camera shades as it does natively
// material.rs: the material's bind group
uint("MATERIAL_BIND_GROUP", 3),
]
}
/// The forward pass of a lit StandardMaterial mesh into an HDR target: Bevy tone-maps after it (the host's tone pass,
/// with Bevy's TonyMcMapface table), as it does natively with an HDR camera. Distance fog is in, off (its mode 0) where
/// the scene has none
fn forward_defs() -> Vec<ShaderDefVal> {
let mut d = webgl_defs();
d.extend([
def("MULTISAMPLED"),
def("SHADOW_FILTER_METHOD_GAUSSIAN"),
def("DISTANCE_FOG"),
ShaderDefVal::Int("SCREEN_SPACE_SPECULAR_TRANSMISSION_BLUR_TAPS".into(), 4),
uint("RENDER_PHASE_TYPE", 1),
]);
d
}
/// A directional light's shadow pass (prepass/mod.rs for a shadow view: depth only, positions, and on WebGL2 the
/// orthographic depth clamp emulated, as it has no unclipped depth)
fn shadow_defs() -> Vec<ShaderDefVal> {
let mut d = webgl_defs();
d.retain(|v| !matches!(v, ShaderDefVal::Bool(n, _) if n == "VERTEX_NORMALS" || n == "VERTEX_UVS" || n == "VERTEX_UVS_A" || n == "VIEW_PROJECTION_PERSPECTIVE"));
d.extend([def("PREPASS_PIPELINE"), def("DEPTH_PREPASS"), def("UNCLIPPED_DEPTH_ORTHO_EMULATION"), def("VIEW_PROJECTION_ORTHOGRAPHIC")]);
d
}
fn files(root: &Path, under: &Path, out: &mut Vec<(String, PathBuf)>) {
let Ok(rd) = std::fs::read_dir(under) else { return };
for e in rd.flatten() {
let p = e.path();
if p.is_dir() {
files(root, &p, out);
} else if p.extension().is_some_and(|x| x == "wesl" || x == "wgsl") {
out.push((p.strip_prefix(root).unwrap().to_string_lossy().replace('\\', "/"), p));
}
}
}
/// A type's layout in a uniform block, as naga lays it out (WGSL's uniform rules, std140's)
fn layout(m: &naga::Module, l: &Layouter, ty: naga::Handle<naga::Type>) -> Value {
let t = &m.types[ty];
let size = l[ty].size;
let scalar = |s: naga::Scalar| match s.kind {
naga::ScalarKind::Float => "f32",
naga::ScalarKind::Uint => "u32",
naga::ScalarKind::Sint => "i32",
naga::ScalarKind::Bool => "bool",
_ => "?",
};
match &t.inner {
TypeInner::Scalar(s) => json!({ "k": scalar(*s), "size": size }),
TypeInner::Atomic(s) => json!({ "k": scalar(*s), "size": size }),
TypeInner::Vector { size: n, scalar: s } => json!({ "k": "vec", "n": *n as u32, "s": scalar(*s), "size": size }),
TypeInner::Matrix { columns, rows, .. } => {
let col = if *rows as u32 == 2 { 8 } else { 16 };
json!({ "k": "mat", "c": *columns as u32, "r": *rows as u32, "stride": col, "size": size })
}
TypeInner::Array { base, size: n, stride } => {
let count = match n {
naga::ArraySize::Constant(c) => c.get(),
_ => 0,
};
json!({ "k": "array", "of": layout(m, l, *base), "count": count, "stride": stride, "size": size })
}
TypeInner::Struct { members, span } => {
let fields: Vec<Value> = members
.iter()
.map(|f| json!({ "name": f.name.clone().unwrap_or_default(), "offset": f.offset, "type": layout(m, l, f.ty) }))
.collect();
json!({ "k": "struct", "name": t.name.clone().unwrap_or_default(), "fields": fields, "size": span })
}
other => json!({ "k": format!("{other:?}").split([' ', '{', '(']).next().unwrap_or("?"), "size": size }),
}
}
/// One entry point in GLSL ES 3.00 for WebGL, and what its names bind to
fn translate(wgsl: &str, stage: ShaderStage, entry: &str) -> Result<(String, Value), String> {
let module = naga::front::wgsl::parse_str(wgsl).map_err(|e| e.emit_to_string(wgsl))?;
let info = naga::valid::Validator::new(naga::valid::ValidationFlags::all(), naga::valid::Capabilities::all())
.validate(&module)
.map_err(|e| e.emit_to_string(wgsl))?;
let options = glsl::Options {
version: glsl::Version::Embedded { version: 300, is_webgl: true },
writer_flags: glsl::WriterFlags::ADJUST_COORDINATE_SPACE | glsl::WriterFlags::FORCE_POINT_SIZE,
binding_map: Default::default(),
zero_initialize_workgroup_memory: false,
};
let pipeline = glsl::PipelineOptions { shader_stage: stage, entry_point: entry.to_string(), multiview: None };
let mut out = String::new();
let mut w = glsl::Writer::new(&mut out, &module, &info, &options, &pipeline, BoundsCheckPolicies::default()).map_err(|e| format!("{e:?}"))?;
let reflection = w.write().map_err(|e| format!("{e:?}"))?;
let mut lay = Layouter::default();
lay.update(module.to_ctx()).map_err(|e| format!("{e:?}"))?;
let mut uniforms = Map::new();
for (h, name) in &reflection.uniforms {
let g = &module.global_variables[*h];
let b = g.binding.as_ref().map(|b| json!({ "group": b.group, "binding": b.binding })).unwrap_or(Value::Null);
let kind = match g.space {
AddressSpace::Uniform => "uniform",
AddressSpace::Storage { .. } => "storage",
_ => "other",
};
uniforms.insert(name.clone(), json!({ "var": g.name, "space": kind, "at": b, "type": layout(&module, &lay, g.ty) }));
}
let mut textures = Map::new();
for (name, m) in &reflection.texture_mapping {
let t = &module.global_variables[m.texture];
let s = m.sampler.map(|s| &module.global_variables[s]);
let at = |g: &naga::GlobalVariable| g.binding.as_ref().map(|b| json!({ "group": b.group, "binding": b.binding }));
textures.insert(name.clone(), json!({ "texture": t.name, "at": at(t), "sampler": s.map(|s| s.name.clone()), "sampler_at": s.and_then(at), "kind": format!("{:?}", module.types[t.ty].inner).split([' ', '{', '(']).next().unwrap_or("?").to_string(), "dim": dim(&module.types[t.ty].inner) }));
}
let varyings: Vec<String> = reflection.varying.keys().cloned().collect();
Ok((out, json!({ "uniforms": uniforms, "textures": textures, "varyings": varyings })))
}
/// A binding's name as Bevy's files give it (`..._bindings__1clustered_lights` -> clustered_lights)
fn short(var: &str) -> String {
var.rsplit("bindings_").next().unwrap_or(var).trim_start_matches('_').trim_start_matches(|c: char| c.is_ascii_digit()).to_string()
}
/// A block's fields at their offsets by dotted path, each from its own struct's start; an array's stride as `path[]`
fn flatten(t: &Value, prefix: &str, out: &mut Map<String, Value>) {
match t["k"].as_str() {
Some("struct") => {
for f in t["fields"].as_array().into_iter().flatten() {
let name = f["name"].as_str().unwrap_or_default();
let path = if prefix.is_empty() { name.to_string() } else { format!("{prefix}.{name}") };
out.insert(path.clone(), f["offset"].clone());
flatten(&f["type"], &path, out);
}
}
Some("array") => {
out.insert(format!("{prefix}[]"), t["stride"].clone());
flatten(&t["of"], prefix, out);
}
_ => {}
}
}
fn dim(t: &TypeInner) -> Value {
match t {
TypeInner::Image { dim, arrayed, class } => json!({ "dim": format!("{dim:?}"), "arrayed": arrayed, "class": format!("{class:?}") }),
_ => Value::Null,
}
}
fn main() -> Result<(), String> {
let args: Vec<String> = std::env::args().collect();
let (Some(root), Some(out)) = (args.get(1), args.get(2)) else {
return Err("usage: bevy-glsl RAEA_ROOT OUT_DIR".into());
};
let root = PathBuf::from(root);
let reg = std::env::var("CARGO_HOME").map(PathBuf::from).unwrap_or_else(|_| PathBuf::from(std::env::var("HOME").unwrap_or_default()).join(".cargo"));
let registry = std::fs::read_dir(reg.join("registry/src"))
.map_err(|e| format!("cargo's registry: {e}"))?
.flatten()
.map(|e| e.path())
.find(|p| p.join("bevy_render-0.20.0").is_dir())
.ok_or("bevy_render 0.20.0 isn't in cargo's registry: build raea first")?;
let crates: Vec<(&str, PathBuf)> = vec![
("bevy_pbr", root.join("vendor/bevy_pbr/src")),
("bevy_render", registry.join("bevy_render-0.20.0/src")),
("bevy_core_pipeline", registry.join("bevy_core_pipeline-0.20.0/src")),
];
let mut cache: ShaderCache<String, ()> = ShaderCache::new((), keep);
let mut ids: BTreeMap<String, AssetId<Shader>> = BTreeMap::new();
for (name, src) in &crates {
let mut fs = Vec::new();
files(src, src, &mut fs);
for (rel, p) in fs {
let path = format!("{name}/{rel}");
let text = std::fs::read_to_string(&p).map_err(|e| format!("{}: {e}", p.display()))?;
let mut shader = if rel.ends_with(".wesl") { Shader::from_wesl(text, format!("embedded://{path}")) } else { Shader::from_wgsl(text, format!("embedded://{path}")) };
shader.shader_defs = per_file_defs(&path);
let id = AssetId::Uuid { uuid: uuid::Uuid::new_v4() };
cache.set_shader(id, shader);
ids.insert(path, id);
}
}
let id = |p: &str| ids.get(p).copied().ok_or(format!("{p} isn't among Bevy's shaders"));
let out = PathBuf::from(out);
std::fs::create_dir_all(&out).map_err(|e| e.to_string())?;
let programs: [(&str, &str, ShaderStage, &str, Vec<ShaderDefVal>); 3] = [
("pbr.vert", "bevy_pbr/render/mesh.wesl", ShaderStage::Vertex, "vertex", forward_defs()),
("pbr.frag", "bevy_pbr/render/pbr.wesl", ShaderStage::Fragment, "fragment", forward_defs()),
("shadow.vert", "bevy_pbr/prepass/prepass.wesl", ShaderStage::Vertex, "vertex", shadow_defs()),
];
let mut meta = Map::new();
let mut ts = String::from("// Bevy's PBR programs for a playable, as tools/bevy-glsl makes them (docs/playables.feature PA11): generated by\n// sdk/playable/bevy/build.sh, not edited. Each program's GLSL ES 3.00; which of Bevy's bindings each uniform block\n// and sampler is; each binding's fields at their byte offsets (nested fields from their struct's start, an array's\n// stride under `name[]`).\n");
let (mut blocks, mut samplers, mut layouts) = (Map::new(), Map::new(), Map::new());
for (name, file, stage, entry, defs) in programs {
let wgsl = cache.get(0, id(file)?, &defs).map_err(|e| format!("{file}: {e}"))?;
std::fs::write(out.join(format!("{name}.wgsl")), wgsl.as_str()).map_err(|e| e.to_string())?;
let (glsl, info) = translate(&wgsl, stage, entry).map_err(|e| format!("{file} ({name}): {e}"))?;
std::fs::write(out.join(format!("{name}.glsl")), &glsl).map_err(|e| e.to_string())?;
eprintln!("{name}: {} lines, {} bytes", glsl.lines().count(), glsl.len());
// leading spaces and blank lines carry nothing in GLSL
let tight: String = glsl.lines().map(str::trim_start).filter(|l| !l.is_empty()).collect::<Vec<_>>().join("\n");
ts.push_str(&format!("export const {} = {};\n", name.replace('.', "_").to_uppercase(), Value::from(tight)));
for (block, u) in info["uniforms"].as_object().into_iter().flatten() {
let short = short(u["var"].as_str().unwrap_or_default());
blocks.insert(block.clone(), Value::from(short.clone()));
let mut flat = Map::new();
flat.insert("$size".into(), u["type"]["size"].clone());
flatten(&u["type"], "", &mut flat);
layouts.insert(short, Value::Object(flat));
}
for (sampler, t) in info["textures"].as_object().into_iter().flatten() {
samplers.insert(sampler.clone(), Value::from(short(t["texture"].as_str().unwrap_or_default())));
}
meta.insert(name.into(), info);
}
ts.push_str(&format!("export const BLOCKS: Record<string, string> = {};\n", Value::Object(blocks)));
ts.push_str(&format!("export const SAMPLERS: Record<string, string> = {};\n", Value::Object(samplers)));
ts.push_str(&format!("export const LAYOUT: Record<string, Record<string, number>> = {};\n", Value::Object(layouts)));
std::fs::write(out.join("programs.ts"), ts).map_err(|e| e.to_string())?;
std::fs::write(out.join("bevy.json"), serde_json::to_string_pretty(&Value::Object(meta)).unwrap()).map_err(|e| e.to_string())?;
Ok(())
}
-1
View File
@@ -274,7 +274,6 @@ rtools = "tools"
skillcheck = "tools"
seetool = "tools"
raea-hands-audit = "tools"
bevy-glsl = "tools" # Bevy's PBR shaders as WebGL2 GLSL for a playable's light host (docs/playables.feature PA11)
# systems that hold only a facility another system may build on (docs/overhaul.md: the mixer graph, ONNX sessions,
# Vision requests, K kernels on the GPU)
-24
View File
@@ -1,24 +0,0 @@
#!/bin/bash
# The component library's catalog, given what an agent picks a component by (tools/library-meta/enrich.ts): each item
# matched by content to the upstream component it came from, with what it draws, when to use it and when not, the
# phrases people ask for it with, its props, and the length and size it was designed at. `raea make component list
# WORDS` searches these and `raea make component show NAME` prints them.
# tools/library-meta.sh [UPSTREAM] UPSTREAM holds a checkout of each source catalog.json names, in a folder named as
# the catalog names it (remocn, snapcn, rve-templates); with none given they're
# cloned (shallow) from the catalog's urls into a scratch folder, removed after
# REPORT=1 tools/library-meta.sh also lists the upstream components the library didn't take
# Run it after adding to the library or after upstream's docs change, then read the diff: hand.json beside enrich.ts
# holds the words written by hand (snapcn's and React Video Editor's components have no when-to-use docs upstream).
set -euo pipefail
ROOT=$(cd "$(dirname "$0")/.." && pwd)
cat=$ROOT/sdk/raea/library/components/catalog.json
up=${1:-}
if [ -z "$up" ]; then
up=$(mktemp -d "${TMPDIR:-/tmp}/library-meta.XXXXXX")
trap 'rm -rf "$up"' EXIT
jq -r '.sources | to_entries[] | "\(.key) \(.value.url)"' "$cat" | while read -r key url; do
GIT_LFS_SKIP_SMUDGE=1 git clone -q --depth 1 "$url.git" "$up/$key"
done
fi
for d in $(jq -r '.sources | keys[]' "$cat"); do [ -d "$up/$d" ] || { echo "library-meta: no $up/$d" >&2; exit 2; }; done
bun "$ROOT/tools/library-meta/enrich.ts" "$up" ${REPORT:+--report}
-129
View File
@@ -1,129 +0,0 @@
// The component library's catalog (sdk/raea/library/components/catalog.json), given what an agent picks a component
// by: each item matched by content to the upstream component it was taken from (its name there kept as `upstream`, a
// search alias, never its name here), then what it draws and how it moves, when to use it and when not, the phrases
// people ask for it with, its props (name, type, default, one line) read from its own source, and the length, frame
// rate, size and feel it was designed at. Hand-written words in hand.json beside this win over upstream's.
//
// bun tools/library-meta/enrich.ts UPSTREAM [--report] UPSTREAM holds checkouts of remocn, snapcn, rve-templates
// (tools/library-meta.sh clones them and runs this). Run again after the library changes: it only rewrites these fields.
import { readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { type Prop, readProps } from "./props";
import { documented, similarity, tokens, type Up, upstream } from "./upstream";
import { phrases, relink, veil } from "./words";
type Hand = { what?: string; use_when?: string[]; avoid_when?: string[]; asked_as?: string[]; vibe?: string };
type Item = Record<string, unknown> & { name: string; category: string; type: string; says: string; component: string; files: string[]; from: string };
const [up, ...flags] = process.argv.slice(2);
if (!up) throw new Error("usage: bun tools/library-meta/enrich.ts UPSTREAM [--report]");
const lib = join(import.meta.dir, "../../sdk/raea/library/components");
const catPath = join(lib, "catalog.json");
const cat = JSON.parse(readFileSync(catPath, "utf8")) as { sources: unknown; items: Item[] };
const hand = JSON.parse(readFileSync(join(import.meta.dir, "hand.json"), "utf8")) as Record<string, Hand>;
const ups = upstream(up);
// each item's upstream original: the same source's component whose identifiers and strings it shares most
const match = new Map<string, { u: Up; score: number }>();
for (const i of cat.items) {
const t = tokens(i.files.map((f) => readFileSync(join(lib, f), "utf8")).join("\n"));
let best: { u: Up; score: number } | undefined;
for (const u of ups) if (u.source === i.from) {
const score = similarity(t, u.tokens);
if (!best || score > best.score) best = { u, score };
}
if (best && best.score >= 0.3) match.set(i.name, best);
}
const ours = new Map([...cat.items].flatMap((i) => (match.has(i.name) ? [[match.get(i.name)!.u.name, `${i.category}/${i.name}`] as const] : [])));
const known = new Set([...ups.map((u) => u.name), ...documented(up).map((d) => d.name)]);
const sentences = (s: string) => s.split(/(?<=[.!?])\s+(?=[A-Z`"'(])/).filter(Boolean);
// upstream's words in ours: names out, pointers at our names, markdown's emphasis and links as plain words
const said = (s: string) => relink(veil(s.replace(/\*\*([^*]+)\*\*/g, "$1").replace(/\[([^\]]+)\]\([^)]*\)/g, "$1")), ours, known);
const stop = (s: string) => (s && !/[.!?:]$/.test(s) ? `${s}.` : s);
/** what it draws and how it moves: the first sentences that describe, not the ones that list props or themes */
function what(i: Item, u?: Up): string {
const pick = (s?: string) =>
sentences(said(s ?? ""))
.filter((x) => !/^(Pass|It ships|Ships|Install|Standalone|Use it|Import|Wrap|Set |Every |All )/.test(x) && !/`raea make component add`/.test(x))
.slice(0, 2)
.join(" ");
if (i.from === "rve-templates") return [i.says.split(". ")[0].replace(/\.?$/, "."), u?.description && `(${u.description}.)`].filter(Boolean).join(" ") + " No props: its words and colours are written in the file.";
// snapcn's description says what it draws and its Usage how it's built; remocn's Usage says how it moves
const d = stop(pick(u?.description));
let w = i.from === "snapcn" ? d : pick(u?.usage);
if (!w || w.length < 100) w = [d, stop(pick(i.from === "snapcn" ? u?.usage : ""))].filter((x, k, a) => x && a.indexOf(x) === k).join(" ");
if (!w) w = i.says;
return w.length > 420 ? `${sentences(w)[0]}` : w;
}
function props(i: Item, u?: Up): Prop[] {
const file = i.files.find((f) => f.endsWith("/index.tsx")) ?? i.files.find((f) => f.endsWith(".tsx")) ?? i.files[0];
const rows = new Map((u?.rows ?? []).map((r) => [r.name, r]));
return readProps(readFileSync(join(lib, file), "utf8"), i.component).map((p) => {
const r = rows.get(p.name);
const says = p.says ?? (r?.description ? said(r.description) : undefined);
const dflt = p.default ?? r?.default;
return { name: p.name, type: p.type, ...(dflt !== undefined ? { default: dflt } : {}), ...(says ? { says: veil(says) } : {}), ...(p.required ? { required: true } : {}) };
});
}
const gcd = (a: number, b: number): number => (b ? gcd(b, a % b) : a);
const uniq = (xs: string[]) => {
const seen = new Set<string>();
return xs.filter((x) => x && !seen.has(x.toLowerCase()) && seen.add(x.toLowerCase()));
};
const missing: string[] = [];
cat.items = cat.items.map((i) => {
const m = match.get(i.name);
const u = m?.u;
const h = hand[i.name] ?? {};
const base: Item = { ...i };
for (const k of ["upstream", "what", "use_when", "avoid_when", "asked_as", "props", "length", "fps", "size", "aspect", "vibe"]) delete base[k];
const use = h.use_when ?? (u?.useWhen ?? []).map(said);
const avoid = h.avoid_when ?? (u?.avoidWhen ?? []).map(said);
if (!use.length) missing.push(`${i.category}/${i.name}`);
const g = u?.width && u.height ? gcd(u.width, u.height) : 0;
return {
...base,
...(u ? { upstream: u.name } : {}),
what: h.what ?? what(i, u),
use_when: use,
avoid_when: avoid,
asked_as: uniq([...(h.asked_as ?? []), ...(u?.askedAs ?? []).map(veil), ...phrases({ ...i, section: u?.section, upstream: u?.name })]),
props: props(i, u),
...(u?.frames ? { length: u.frames, fps: u.fps ?? 30 } : {}),
...(g ? { size: `${u!.width}x${u!.height}`, aspect: `${u!.width! / g}:${u!.height! / g}` } : { aspect: "any: it fills the frame it's given" }),
...((h.vibe ?? u?.vibe) ? { vibe: h.vibe ?? u?.vibe } : {}),
};
});
// hand.json's names, and the components (or category/type) its words point at, must be the library's
const names = new Set(cat.items.flatMap((i) => [`${i.category}/${i.name}`, `${i.category}/${i.type}`]));
const bad = Object.entries(hand).flatMap(([n, h]) => [
...(cat.items.some((i) => i.name === n) ? [] : [`hand.json: no item ${n}`]),
...[...JSON.stringify(h).matchAll(/`([a-z]+\/[a-z0-9-]+)`/g)].filter(([, r]) => !names.has(r)).map(([, r]) => `hand.json ${n}: no item ${r}`),
]);
if (bad.length) throw new Error(bad.join("\n"));
// one prop to a line, so the file reads (and diffs) by item
const lines: string[] = [];
const text = JSON.stringify(cat, (k, v) => (k === "props" && Array.isArray(v) ? v.map((p) => `\u0001${lines.push(JSON.stringify(p)) - 1}`) : v), 1);
writeFileSync(catPath, `${text.replace(/"\\u0001(\d+)"/g, (_, n) => lines[Number(n)])}\n`);
const mapped = cat.items.filter((i) => i.upstream).length;
console.log(`${cat.items.length} items enriched, ${mapped} matched to an upstream component (${cat.items.filter((i) => i.upstream && i.upstream !== i.name).length} under another name there)`);
const unmatched = cat.items.filter((i) => !i.upstream).map((i) => `${i.category}/${i.name}`);
if (unmatched.length) console.log(`no upstream match (check by hand): ${unmatched.join(", ")}`);
if (missing.length) console.log(`no use_when (add it to hand.json): ${missing.length}: ${missing.join(", ")}`);
if (flags.includes("--report")) {
// upstream components the library didn't take, by docs section
const took = new Set(cat.items.filter((i) => i.upstream).map((i) => `${i.from}/${i.upstream}`));
const left = new Map<string, string[]>();
const regs = new Set(ups.map((u) => `${u.source}/${u.name}`));
for (const d of documented(up))
if (regs.has(`${d.source}/${d.name}`) && !took.has(`${d.source}/${d.name}`)) left.set(`${d.source} ${d.section}`, [...(left.get(`${d.source} ${d.section}`) ?? []), d.name]);
for (const u of ups) if (u.source !== "rve-templates" && !u.section && !took.has(`${u.source}/${u.name}`)) left.set(`${u.source} (no docs page)`, [...(left.get(`${u.source} (no docs page)`) ?? []), u.name]);
for (const u of ups) if (u.source === "rve-templates" && !took.has(`${u.source}/${u.name}`)) left.set("rve-templates", [...(left.get("rve-templates") ?? []), u.name]);
console.log("\nnot vendored:");
for (const [k, v] of [...left].sort()) console.log(`${k} (${v.length}): ${v.sort().join(", ")}`);
}
-137
View File
@@ -1,137 +0,0 @@
{
"agent-steps": {"use_when": ["Showing an AI agent at work: a prompt in a pill, then a log of steps that each run and flip to done, ending on one answer chip.", "A product demo beat where the point is 'it does the steps for you': research, build, render."], "avoid_when": ["You want the answer text itself to stream in: use `ui/answer-stream`.", "You want a terminal with commands and output: use `ui/terminal-simulator` or `ui/terminal-session`."], "asked_as": ["agent working", "AI agent steps", "agent log", "thinking steps", "tool calls", "Claude working on a task", "agent narrating its work"]},
"answer-stream": {"use_when": ["The beat after a prompt is sent: a close shot on the send button that cuts to an AI answer writing itself while the camera pulls back.", "Following `ui/prompt-zoom` or `ui/prompt-send` in an AI product demo."], "avoid_when": ["You only need the prompt being typed: use `ui/prompt-send`.", "You want one sentence of the answer picked out: use `text/answer-highlight`."], "asked_as": ["AI answer streaming", "chat response typing", "streaming reply", "LLM response", "answer writes itself", "send then answer"]},
"button-press": {"use_when": ["A call to action being clicked: a cursor walks onto a split button, hovers, presses, a spinner runs, a tick draws.", "Any 'one click and it's done' beat in an app demo."], "avoid_when": ["You need a cursor moving over your own screen: use `ui/cursor-track`.", "You want a switch flipping on: use `ui/toggle-on`."], "asked_as": ["button click", "click the button", "CTA click", "press button", "loading spinner then check", "submit button"]},
"capture-reveal": {"use_when": ["A screenshot or copy-to-clipboard moment: a toast counts up over a browser window, which drops away while a headline rises from behind it.", "Introducing a capture, clip or export feature."], "avoid_when": ["You want a camera tour of a still screenshot: use `ui/screenshot-tour`."], "asked_as": ["screenshot capture", "copied to clipboard", "toast notification", "browser window", "capture tool"]},
"caret": {"use_when": ["You are building your own typing scene and need a blinking text caret that blinks on the frame clock.", "Adding a caret to a title or field you made yourself."], "avoid_when": ["You want a whole field that types: use `ui/input`, `ui/prompt-send` or `ui/click-type`."], "asked_as": ["blinking cursor", "text caret", "typing cursor", "insertion point"]},
"click-type": {"use_when": ["Opening an AI or search demo: a composer writes its own placeholder, a cursor flies in and clicks, then a hard cut to the field typing the prompt at the caret.", "A short 'type your idea here' beat for any app with a prompt box."], "avoid_when": ["You want the prompt to be sent and the camera to ride the caret: use `ui/prompt-send`.", "You want a plain form field with states: use `ui/input`."], "asked_as": ["click and type", "type into the box", "prompt composer typing", "cursor clicks the input", "typing a prompt"]},
"cursor-track": {"use_when": ["Walking a cursor over your own screen, screenshot or UI along waypoints, with a ring pulse on each click.", "Turning a static app screen into a guided click-through."], "avoid_when": ["You want a cursor clicking one button with a spinner and tick: use `ui/button-press`.", "You want several collaborators' cursors: use `ui/multiplayer-cursors`."], "asked_as": ["cursor over screen", "mouse moves and clicks", "click-through demo", "guided tour cursor", "walkthrough"]},
"input": {"use_when": ["A single text field that moves through idle, hover, focus, typing, blur and invalid on the timeline: sign-up forms, email capture, a search box.", "Building your own form or chat scene from parts."], "avoid_when": ["You want a full AI prompt composer with send: use `ui/prompt-send` or `ui/click-type`."], "asked_as": ["text field", "form field", "email input", "input box", "focus ring", "typing in a field", "validation error"]},
"phone-frame": {"use_when": ["Showing an app, screen recording or screenshot inside a phone that rises in and floats, flat, tilted or with a 3D crane move.", "Mobile app launches and app-store style promos."], "avoid_when": ["You want several phones playing clips: use `ui/phone-stack`.", "You need a laptop: use `overlays/laptop-frame`."], "asked_as": ["iPhone mockup", "phone mockup", "device frame", "app on a phone", "mobile screen recording"]},
"phone-stack": {"use_when": ["Several vertical clips or app screens, each in its own phone, rising out of a blur and pushing the older ones back.", "Showing a run of short-form videos or app screens one after another."], "avoid_when": ["One phone is enough: use `ui/phone-frame`.", "You want a turning wall of clips: use `gallery/reel-wall`."], "asked_as": ["stacked phones", "multiple phone screens", "phone clips", "vertical videos in phones"]},
"prompt-mark": {"use_when": ["A brand intro for an AI product: a short prompt types into a pill, the camera pans to send, and the send arrow becomes your logo lockup.", "Ending an AI demo on the logo."], "avoid_when": ["The prompt is longer than about 11 characters: the pan was measured for a short one; use `ui/prompt-send`.", "You don't need a logo at the end: use `ui/prompt-zoom`."], "asked_as": ["prompt to logo", "AI logo reveal", "send button becomes logo", "prompt box logo intro"]},
"prompt-send": {"use_when": ["An AI chat composer that unrolls from a hairline, writes a brief while the camera rides the caret, then a pointer sends it.", "The opening of any 'tell the AI what you want' demo; pair with `ui/answer-stream` for the reply."], "avoid_when": ["You want the zoom into the caret mid-sentence: use `ui/prompt-zoom`.", "You want the send to end on a logo: use `ui/prompt-mark`."], "asked_as": ["AI prompt typing", "chat composer", "composer", "prompt box", "chat input", "send a prompt", "type a message and send", "Claude chat input", "ChatGPT-style prompt"]},
"prompt-zoom": {"use_when": ["A prompt field types a sentence and, partway through, cuts in one frame to a close-up of the caret while the typing carries on.", "A punchy AI-input beat inside a fast edit."], "avoid_when": ["You want the send and a pointer: use `ui/prompt-send`.", "You want the answer after it: follow it with `ui/answer-stream`."], "asked_as": ["prompt zoom", "zoom into the prompt", "caret close-up", "AI prompt typing", "composer close-up"]},
"roster-grant": {"use_when": ["Access, invites or seats being granted: rows of people cards stream past a button, a pointer clicks it, and the avatars turn to the accent colour one by one.", "Team, waitlist or early-access announcements."], "avoid_when": ["You want a social follower count rushing up: use `social/upvote-burst` or a number counter."], "asked_as": ["access granted", "invite team", "waitlist approved", "user avatars", "team members", "early access"]},
"terminal-session": {"use_when": ["A developer tool or CLI launch: one camera flies from a headline to an install command panel to a green terminal typing its output.", "Showing a command, its install and its result in one continuous move."], "avoid_when": ["You want a plain terminal window that types and scrolls: use `ui/terminal-simulator`.", "You want the camera locked to the typing cursor: use `ui/terminal-cursor-zoom`."], "asked_as": ["terminal", "terminal session", "install command", "npm install", "CLI demo", "command line", "Claude Code", "coding agent terminal", "dev tool launch"]},
"karaoke-captions": {"use_when": ["Whole-line captions where a colour fill sweeps across the words as they are spoken, with keywords in the accent colour.", "Talking-head and podcast clips that need readable, paced captions."], "avoid_when": ["You want one word at a time popping: use `captions/word-captions`."], "asked_as": ["karaoke captions", "highlighted captions", "subtitle fill", "spoken words highlight"]},
"word-captions": {"use_when": ["Burned-in word-by-word captions from a timed transcript, in a pill inside the safe area, each word popping as it is spoken.", "Short-form vertical clips (reels, shorts) of someone talking."], "avoid_when": ["You want the whole line visible with a fill sweep: use `captions/karaoke-captions`."], "asked_as": ["TikTok captions", "word by word captions", "burned in subtitles", "short-form captions", "auto captions"]},
"card-rail": {"use_when": ["A row of cards (screens, products, posts) flicked sideways across a tilted plane that slows and rests one card along.", "Showing breadth: many examples passing in one move."], "avoid_when": ["You want a 3D turning wall: use `gallery/reel-wall`."], "asked_as": ["card carousel", "sliding cards", "flick cards", "product cards row"]},
"moodboard-reveal": {"use_when": ["A four-beat montage: a kinetic headline, a scattered photo gallery, a camera push from dark to light, landing on a hero image.", "Brand or campaign openers built from photos."], "avoid_when": ["You want a simple grid of photos: use `gallery/gallery-grid`."], "asked_as": ["moodboard", "photo montage", "image collage intro", "brand photos"]},
"orbit-gallery": {"use_when": ["A hero where a stream of photos spirals in from the edges toward a title held in the middle; works in any aspect.", "Showing a large library of images or user work at once."], "avoid_when": ["You want photos landing on a pile: use `gallery/photo-stack`."], "asked_as": ["spiral gallery", "image vortex", "photos orbit", "image universe"]},
"reel-collage": {"use_when": ["A photo reel between two captions shuts like an eyelid, the words swap, and a collage blooms in around them: a short three-beat scene.", "A 'before you were here / now you are' style reveal with pictures."], "avoid_when": ["You want a calm grid: use `gallery/gallery-grid`."], "asked_as": ["photo collage", "reel collage", "eyelid transition", "photo reveal"]},
"reel-wall": {"use_when": ["A curved wall of vertical clips turning in the dark, for as long as the composition runs.", "Showing many short videos or creators at once."], "avoid_when": ["You want flat cards sliding sideways: use `gallery/card-rail`."], "asked_as": ["video wall", "3D carousel of clips", "reels wall", "rotating wall of videos"]},
"bloom-lockup": {"use_when": ["A logo reveal where a wall of finished work blooms out from your logo, cuts in tight, then bends away through a lens and flash as the wordmark arrives.", "Closing a portfolio, agency or product film on the brand."], "avoid_when": ["You want a quick, plain logo fade: use `logo/logo-fade-reveal`."], "asked_as": ["logo reveal", "logo with work behind it", "brand lockup", "portfolio logo outro"]},
"cut-lockup": {"use_when": ["A logo reveal in hard cuts: huge on grid paper, three cuts down, a night push where its construction lines draw, then paper wipes to the lockup.", "Design-led brands that want the logo's construction shown."], "avoid_when": ["You want a soft single-move reveal: use `logo/logo-blur-reveal`."], "asked_as": ["logo construction", "logo grid reveal", "hard cut logo", "brand lockup"]},
"gather-lockup": {"use_when": ["A line of type over a wall of your work falls apart word by word, the wall cuts to four slots, and the last hands over to your mark and wordmark.", "Agency or creator brand outros at 24 fps."], "avoid_when": ["Your edit runs at 30 or 60 and you can't keep this at 24: it cuts between held poses; use `logo/bloom-lockup`."], "asked_as": ["logo outro", "work wall to logo", "brand lockup", "agency sting"]},
"hero-launch": {"use_when": ["A product launch hero: two cards slide into formation as the headline reveals above them.", "Opening a launch or announcement film with the product shots."], "avoid_when": ["You want a whole launch story: use `text/announce-title` or a `logo/` launch item."], "asked_as": ["launch hero", "product launch", "hero section video", "announcement opener"]},
"logo-assemble": {"use_when": ["A scatter of cards collapses into one brand card that lands tilted and settles, showing the logo and name.", "A brand reveal after a montage of features."], "avoid_when": ["You want the logo drawn as a line: use `logo/logo-stroke-draw`."], "asked_as": ["logo assemble", "cards into logo", "brand card reveal"]},
"logo-drift": {"use_when": ["A field of tiles (integrations, partners, tools) drifts past a headline while the camera pulls back.", "'Works with everything you use' scenes."], "avoid_when": ["You want a fixed logo wall: use `logo/ecosystem-constellation`."], "asked_as": ["integrations wall", "partner logos", "logo cloud", "works with", "tool logos drifting"]},
"logo-flicker": {"use_when": ["Images flip past very fast, slow down and fade, and the logo and name resolve: a studio-ident style reveal.", "Opening a film with a burst of its own footage."], "avoid_when": ["You don't have a stack of images: use `logo/logo-glitch-reveal` or `logo/logo-blur-reveal`."], "asked_as": ["flicker logo reveal", "studio intro", "images flip into logo", "film ident"]},
"sky-lockup": {"use_when": ["A one-line promise comes apart word by word, the page washes to a soft sky, and the mark inside the sentence slides over and becomes the logo, in under two seconds.", "A short brand outro that doesn't slow the end of a video."], "avoid_when": ["You want a long, dramatic reveal: use `logo/bloom-lockup`."], "asked_as": ["logo outro", "sky reveal", "short brand ending", "tagline to logo"]},
"wordmark-cut": {"use_when": ["A wordmark twice the frame's width cooling from a lit gradient to ink, then a cut closer onto its last letters.", "Typographic brands whose name is the logo."], "avoid_when": ["You have an icon mark rather than a wordmark: use `logo/logo-assemble`."], "asked_as": ["wordmark reveal", "big logo type", "brand name reveal"]},
"count-grid": {"use_when": ["A grid of cards rushes in and settles on five, then every empty cell fills from the middle out as the count jumps to five hundred: scale in one beat.", "A 1.5-second beat inside a longer edit."], "avoid_when": ["You need a standalone stat with its own hold: use `numbers/compact-stat` or `numbers/flash-count`."], "asked_as": ["grid count", "from 5 to 500", "scale up count", "number of users grid"]},
"laptop-frame": {"use_when": ["A laptop opens, shows a notch notification, then the camera dives into the screen until your screenshot or recording fills the frame.", "Moving from a device shot into a full-screen product demo."], "avoid_when": ["A phone: use `ui/phone-frame`.", "A plain browser window: use a `ui/` browser item."], "asked_as": ["MacBook mockup", "laptop mockup", "device mockup", "screen recording in a laptop", "zoom into the screen"]},
"brand-wheel": {"use_when": ["A lead word and a wheel of platform or brand pills rolling through until a cursor clicks the last one: 'ship to X, Y and Z'.", "Listing the places a product publishes to."], "avoid_when": ["You want a drifting logo wall: use `logo/logo-drift`."], "asked_as": ["platform wheel", "brand pills", "publish everywhere", "rolling brands"]},
"announce-title": {"use_when": ["A four-shot announcement title: an eyebrow rushes past on a receding type plane, the name builds on paper, and the tagline writes itself last word first.", "Launch films that need a title with real camera moves from three strings."], "avoid_when": ["A single-move title is enough: use `text/feature-headline` or `text/crash-zoom`."], "asked_as": ["launch title", "announcement", "product name reveal", "introducing title"]},
"answer-highlight": {"use_when": ["An AI chat answer writes itself under a question, then a selection is dragged across the one sentence that matters and settles on one word.", "Pointing at the key line of a chatbot reply."], "avoid_when": ["You want the answer to stream after a send: use `ui/answer-stream`."], "asked_as": ["AI answer highlight", "ChatGPT-style answer", "chat response highlight", "select the answer"]},
"check-cycle": {"use_when": ["A sentence that keeps finishing itself: the word beside a ticked checkbox rolls through a list (Intros, Demos, Launches...) and rests.", "Listing what a product makes or does in one line."], "avoid_when": ["You want words flipping in 3D: use `text/word-flip`."], "asked_as": ["checkbox list", "rolling words", "use cases cycle", "it does X Y Z"]},
"drop-line": {"use_when": ["Words cut past one card at a time, then the last word sinks out from under the dot of its own i: a 38-frame title beat.", "Fast, punchy openers."], "avoid_when": ["You want a slower statement: use `text/punch-lines`."], "asked_as": ["fast words", "word by word cut", "punchy title"]},
"font-shuffle": {"use_when": ["A launch title decodes out of scrambled glyphs, flashes the accent, then the product name tries on eleven typefaces.", "Type, design and font tools; playful launches."], "avoid_when": ["You want a clean decode only: use `text/matrix-decode`."], "asked_as": ["font shuffle", "typeface cycle", "scrambled text", "font change animation"]},
"hello-zoom": {"use_when": ["Words flicker in place, one line types on, then the camera dives through its own letters into the next card.", "A greeting or opener that leads into the next scene."], "avoid_when": ["You want a camera push without the dive: use `text/crash-zoom`."], "asked_as": ["hello", "zoom through text", "dive into letters", "typing intro"]},
"highlight-sweep": {"use_when": ["Emphasising a span of text that is visible from frame one: a mark wipes open, with five emphasis presets for the highlighted words.", "Pointing at the key words of a headline."], "avoid_when": ["You want the words themselves to arrive: use a `text/reveal` item."], "asked_as": ["text highlight", "highlighter", "emphasis", "marker sweep", "underline words"]},
"portal-intro": {"use_when": ["A sentence with a picture chip in it leans in until the chip takes the frame, then a title types over the picture and the mark arrives.", "Intros that move from words into footage."], "avoid_when": ["You want words only: use `text/hello-zoom`."], "asked_as": ["portal intro", "zoom into image in text", "picture in sentence", "intro"]},
"punch-lines": {"use_when": ["Full-frame title cards cutting hard between beats: a statement flicked in line by line, then a hero line whose words punch up and push forward.", "Hook openers and manifesto-style ads."], "avoid_when": ["You want one quiet line: use `text/cool-down`."], "asked_as": ["punchy text", "hook", "title cards", "statement lines", "kinetic typography ad"]},
"spec-sweep": {"use_when": ["A one-line spec slides in word by word while a highlight runs along it and an icon charges up.", "Product specs and feature claims (battery, speed, size)."], "avoid_when": ["A spec with a big number: use a `numbers/` stat."], "asked_as": ["spec line", "feature claim", "product spec", "charging icon"]},
"status-cycle": {"use_when": ["A status pill whose label rolls through states while its width springs, then a column of chips steps up.", "Showing an app's states (Queued, Rendering, Done) or a list of options."], "avoid_when": ["You want an agent log: use `ui/agent-steps`."], "asked_as": ["status pill", "status changes", "loading states", "chips"]},
"text-rewrite": {"use_when": ["A line writes itself, is selected, has its opening cut away, and gets a new ending: rewriting, editing or AI writing tools.", "'Change one word and it all changes' beats."], "avoid_when": ["You want one line replaced by another whole: use `text/text-swap`."], "asked_as": ["rewrite text", "edit sentence", "AI rewriting", "text replaced"]},
"text-select": {"use_when": ["A line writes itself a word at a time, pushes forward, and is selected under a gradient with a glint: the beat before copying.", "Calling out a quote or a key sentence."], "avoid_when": ["The copy should be visible from frame one: use `text/highlight-sweep`."], "asked_as": ["text selection", "select text", "copy text", "highlighted line"]},
"text-swap": {"use_when": ["Replacing one line with another: the old line rushes the camera and flies past, revealing the new one behind it.", "'Not this, but this' beats."], "avoid_when": ["Only one word changes: use `text/word-flip`."], "asked_as": ["swap text", "replace line", "text change", "before after text"]},
"text-swell": {"use_when": ["The lead word rises and floats toward you, then the rest of the sentence pushes in from the right, bouncing, and shoves it aside.", "Playful, bouncy statements."], "avoid_when": ["A calm, steady line: use `text/cool-down`."], "asked_as": ["bouncy text", "swelling word", "playful title"]},
"title-sweep": {"use_when": ["An end title lit by a gradient travelling through its letters, a cut to dark, and a second title taking over.", "Endings and chapter closers."], "avoid_when": ["You want rolling credits: use `text/credits-roll`."], "asked_as": ["end title", "gradient title", "closing title", "outro title"]},
"type-morph": {"use_when": ["A headline types under a glowing caret, sheds its lead, morphs letter by letter and ends under a colour flood.", "AI and writing products' titles."], "avoid_when": ["You only need typing: use `text/typewriter-subtitle`."], "asked_as": ["typing headline", "morphing text", "caret title", "AI typing"]},
"word-flip": {"use_when": ["A headline types out, then one word cycles on a 3D flip: 'Make [videos / ads / games]'.", "One sentence that covers many uses."], "avoid_when": ["A reel that stops on one word: use `text/word-wheel`."], "asked_as": ["rotating word", "word cycle", "changing word in headline", "flip text"]},
"word-gather": {"use_when": ["A sentence arrives one word at a time, out of order, and gathers into place in the accent colour, turning to ink as it settles.", "Short statements that should feel composed."], "avoid_when": ["Words in reading order: use a `text/reveal` item."], "asked_as": ["words gather", "words fly in", "sentence assembles"]},
"word-wheel": {"use_when": ["A column of words spins like a slot reel and stops on one beside a fixed lead-in.", "Picking one answer from many: 'Made for [designers]'."], "avoid_when": ["You want it to keep cycling: use `text/word-flip`."], "asked_as": ["slot machine words", "word reel", "spinning words", "word roulette"]},
"dot-bloom": {"use_when": ["A halftone transition: the outgoing shot washes to cream, breaks into drifting dots, and they thin onto the next shot.", "Soft, printed-looking scene changes."], "avoid_when": ["A plain dissolve: use `transitions/cross-dissolve`."], "asked_as": ["halftone transition", "dot transition", "dissolve to dots"]},
"sound-wave": {"use_when": ["A quick audio visual: bars moving like a waveform, for music, podcasts or voice.", "A placeholder audio meter you'll restyle in the file."], "avoid_when": ["You want it driven by the real sound or set by props: edit the file, it's a loop of sine waves."], "asked_as": ["audio visualizer", "waveform", "sound bars", "equalizer", "podcast audio"]},
"bokeh-circles": {"use_when": ["A soft, out-of-focus moving background behind titles."], "avoid_when": ["You want props for colours and count: it's written in the file; for a designed backdrop use `backgrounds/synthwave` or `backgrounds/phyllotaxis`."], "asked_as": ["bokeh", "soft lights background", "blurry circles"]},
"geometric-patterns": {"use_when": ["A slowly turning line-pattern background behind text."], "avoid_when": ["You want a designed pattern with props: use `backgrounds/pattern-tile` or `backgrounds/truchet-flip`."], "asked_as": ["geometric background", "shapes pattern", "abstract background"]},
"gradient-shift": {"use_when": ["A calm moving colour gradient behind titles or a lower third."], "avoid_when": ["You want brand colours from props: edit the file's colours."], "asked_as": ["gradient background", "moving gradient", "ambient background"]},
"grid-pulse": {"use_when": ["A tech-feeling dot grid that pulses in waves behind content."], "avoid_when": ["You want a pattern with props: use `backgrounds/pattern-tile`."], "asked_as": ["dot grid", "pulse grid", "tech background"]},
"liquid-wave": {"use_when": ["A rolling wave across the bottom of the frame, for water, calm or fill themes."], "avoid_when": ["You want a liquid filling a shape: use `depth/liquid-fill`."], "asked_as": ["wave", "water wave", "liquid background"]},
"matrix-rain": {"use_when": ["Falling green code for hacker, AI or data themes."], "avoid_when": ["You want text decoding from code: use `text/matrix-decode`."], "asked_as": ["matrix", "code rain", "hacker background", "falling code"]},
"particle-explosion": {"use_when": ["A burst of particles from the centre for a reveal or celebration."], "avoid_when": ["You want confetti: use `marks/confetti`.", "A burst of strokes: use `marks/radial-burst`."], "asked_as": ["particle burst", "explosion", "particles"]},
"starfield": {"use_when": ["Flying through stars for space, speed or launch moments."], "avoid_when": ["You want a retro horizon: use `backgrounds/synthwave`."], "asked_as": ["starfield", "space", "warp speed", "stars"]},
"area-chart": {"use_when": ["A simple area chart revealing left to right, data written in the file."], "avoid_when": ["You want data from props and a designed look: use `charts/growth-line` or `charts/area-compare`."], "asked_as": ["area chart", "growth chart"]},
"chart-animation": {"use_when": ["A basic bar chart growing in turn, data written in the file."], "avoid_when": ["You want bars set by props: use `charts/animated-bar-chart` or `charts/spring-bars`."], "asked_as": ["bar chart", "bars growing", "column chart"]},
"comparison-chart": {"use_when": ["Two bars comparing a before and after."], "avoid_when": ["You want a designed versus scene: use `charts/versus-split` or `charts/dumbbell-shift`."], "asked_as": ["before after chart", "comparison", "vs chart"]},
"donut-chart": {"use_when": ["A donut showing a share with a centre number."], "avoid_when": ["You want it from props: use `charts/share-donut`."], "asked_as": ["donut chart", "ring chart", "percentage ring"]},
"line-chart": {"use_when": ["A line with points drawing left to right, data in the file."], "avoid_when": ["You want props and labels: use `charts/animated-line-chart`."], "asked_as": ["line chart", "line graph", "trend"]},
"pie-chart": {"use_when": ["A pie chart sweeping in slice by slice."], "avoid_when": ["A donut from props: use `charts/share-donut`."], "asked_as": ["pie chart", "slices", "share chart"]},
"progress-bars": {"use_when": ["Labelled horizontal bars filling to their values in turn."], "avoid_when": ["Ranked bars that race: use `charts/benchmark-race`."], "asked_as": ["progress bars", "skill bars", "horizontal bars"]},
"card-flip": {"use_when": ["A card flipping in 3D from front to back: before/after, question/answer."], "avoid_when": ["A fan of cards: use `depth/card-fan`."], "asked_as": ["card flip", "flip card", "3D card"]},
"gallery-grid": {"use_when": ["A 2x3 grid of photos filling in tile by tile."], "avoid_when": ["A designed montage: use `gallery/moodboard-reveal`."], "asked_as": ["photo grid", "image grid", "gallery"]},
"image-carousel": {"use_when": ["Photos sliding past with the centre one in focus."], "avoid_when": ["Cards flicked on a tilted plane: use `gallery/card-rail`."], "asked_as": ["carousel", "image slider", "slideshow"]},
"image-comparison-slider": {"use_when": ["A divider sliding across a before and after image."], "avoid_when": ["A scan that reveals a fixed build: use `ui/scan-fix`."], "asked_as": ["before after slider", "image comparison", "compare photos"]},
"image-zoom-reveal": {"use_when": ["A photo revealed through a growing window as it zooms out."], "avoid_when": ["A slow pan over a still: use `looks/ken-burns`."], "asked_as": ["image reveal", "zoom out reveal", "photo reveal"]},
"masonry-gallery": {"use_when": ["Photos dropping into a masonry wall of mixed sizes."], "avoid_when": ["A plain grid: use `gallery/gallery-grid`."], "asked_as": ["masonry", "pinterest grid", "photo wall"]},
"photo-stack": {"use_when": ["Photos landing on a pile, each slightly turned: memories, recaps."], "avoid_when": ["A spiral of many photos: use `gallery/orbit-gallery`."], "asked_as": ["photo pile", "stack of photos", "polaroids"]},
"rotating-carousel": {"use_when": ["Cards turning round a 3D carousel."], "avoid_when": ["A turning wall of video: use `gallery/reel-wall`."], "asked_as": ["3D carousel", "rotating cards"]},
"spotlight-reveal": {"use_when": ["A spotlight sweeping the dark to reveal a word or image."], "avoid_when": ["A designed light sting: use `logo/spotlight`."], "asked_as": ["spotlight", "reveal in the dark", "circle reveal"]},
"end-card": {"use_when": ["A plain closing card with a thank-you and subscribe button for a channel video."], "avoid_when": ["A brand outro: use a `logo/lockup` item like `logo/sky-lockup`."], "asked_as": ["end card", "outro", "subscribe end screen", "thanks for watching"]},
"logo-blur-reveal": {"use_when": ["A logo pulling focus from a heavy blur, quick and plain."], "avoid_when": ["A designed reveal: use `logo/first-light` or `logo/sky-lockup`."], "asked_as": ["logo blur", "logo focus pull"]},
"logo-bounce-drop": {"use_when": ["A logo dropping in and bouncing to rest: playful brands."], "avoid_when": ["A designed bounce: use `logo/snap-click`."], "asked_as": ["logo bounce", "logo drop"]},
"logo-fade-reveal": {"use_when": ["The simplest logo reveal: logo and name fading up together."], "avoid_when": ["You want a moment: use a `logo/sting` item."], "asked_as": ["logo fade in", "simple logo reveal"]},
"logo-glitch-reveal": {"use_when": ["A logo appearing through RGB glitch: tech, gaming, music."], "avoid_when": ["You want a whole glitch transition: use a `transitions/` item."], "asked_as": ["glitch logo", "RGB split logo"]},
"logo-scale-rotate": {"use_when": ["A logo scaling up while turning into place."], "avoid_when": ["A 3D spin: use `logo/logo-spin-reveal`."], "asked_as": ["logo spin scale", "logo rotate in"]},
"logo-spin-reveal": {"use_when": ["A logo spinning on its vertical axis and settling."], "avoid_when": ["A turntable of a product: use `depth/turntable`."], "asked_as": ["logo spin", "3D logo spin"]},
"logo-split-reveal": {"use_when": ["Two halves of a logo sliding together."], "avoid_when": ["A designed split: use `logo/split-match`."], "asked_as": ["logo split", "halves join"]},
"logo-stroke-draw": {"use_when": ["An outline logo drawn as a line, then filled: hand-made, architectural or line-art marks."], "avoid_when": ["Your logo isn't an SVG path: use `logo/logo-fade-reveal`."], "asked_as": ["logo draw", "line drawing logo", "stroke animation", "signature"]},
"logo-typewriter": {"use_when": ["An icon with the company name typed beside it."], "avoid_when": ["A typed headline: use `text/typewriter-subtitle`."], "asked_as": ["logo typewriter", "typed company name"]},
"camera-shake": {"use_when": ["A decaying shake on impact moments, around anything it wraps."], "avoid_when": ["A designed impact frame: use `marks/impact-shake`."], "asked_as": ["camera shake", "screen shake", "impact"]},
"ken-burns": {"use_when": ["A slow pan and zoom over a still photo: documentaries, memorials, recaps."], "avoid_when": ["Depth from a flat photo: use `depth/parallax-depth`."], "asked_as": ["ken burns", "pan and zoom", "photo motion"]},
"noise-grain": {"use_when": ["A light film grain over the whole frame for texture."], "avoid_when": ["A whole print look: use `looks/riso-print`."], "asked_as": ["film grain", "noise overlay", "texture"]},
"vignette-pulse": {"use_when": ["Dark edges breathing in and out: tension, heartbeat, focus."], "avoid_when": ["You want a static vignette: edit the file's pulse."], "asked_as": ["vignette", "dark edges", "pulse"]},
"circular-progress": {"use_when": ["A ring filling to a percentage with the number counting in its centre."], "avoid_when": ["Rings like a fitness app: use `numbers/activity-rings`."], "asked_as": ["progress ring", "percentage circle", "loading ring"]},
"countdown-intro": {"use_when": ["A 3, 2, 1, GO ring countdown into an opening card."], "avoid_when": ["A designed countdown: use `numbers/countdown` or `numbers/t-minus`."], "asked_as": ["countdown", "3 2 1", "intro countdown"]},
"countdown-timer": {"use_when": ["Large digits ticking down 5 to GO with a spring."], "avoid_when": ["A real clock or timer: use `numbers/drop-timer` or `hud/shot-clock`."], "asked_as": ["countdown timer", "timer"]},
"progress-steps": {"use_when": ["Numbered steps lighting along a line: onboarding, how it works."], "avoid_when": ["An agent working through steps: use `ui/agent-steps`."], "asked_as": ["steps", "progress steps", "how it works", "stepper"]},
"stat-counter": {"use_when": ["A plain big number counting up with commas and a label."], "avoid_when": ["You want props and a designed stat: use `numbers/compact-stat` or `numbers/flash-count`."], "asked_as": ["stat counter", "count up", "big number"]},
"lower-third": {"use_when": ["A news-style name and title bar for an interview or talking head."], "avoid_when": ["You want words from props: edit the file's name and title."], "asked_as": ["lower third", "name tag", "name and title", "chyron"]},
"notification-pop": {"use_when": ["Phone-style notifications stacking in: messages, sales, alerts."], "avoid_when": ["A pile of notifications as a full scene: use a `ui/` phone item."], "asked_as": ["notifications", "push notification", "toast stack"]},
"picture-in-picture": {"use_when": ["A small inset window over the main shot: a face cam over a screen."], "avoid_when": ["Two shots side by side: use `overlays/split-screen`."], "asked_as": ["picture in picture", "PiP", "face cam", "inset video"]},
"polaroid-frame": {"use_when": ["A photo dropping in as a polaroid with a white border."], "avoid_when": ["Many photos on a pile: use `gallery/photo-stack`."], "asked_as": ["polaroid", "instant photo frame"]},
"split-screen": {"use_when": ["Two panels sliding to meet: comparisons, two people, before and after."], "avoid_when": ["A small inset: use `overlays/picture-in-picture`."], "asked_as": ["split screen", "side by side", "two videos"]},
"subscribe-reminder": {"use_when": ["A floating subscribe button with a cursor click and bell for channel videos."], "avoid_when": ["A brand CTA: use `ui/button-press`."], "asked_as": ["subscribe button", "like and subscribe", "bell"]},
"animated-list": {"use_when": ["A bulleted list with rows sliding in one after another."], "avoid_when": ["A designed feature list: use `text/index-list` or `text/feature-trio`."], "asked_as": ["bullet list", "list animation", "agenda"]},
"animated-text": {"use_when": ["A headline whose letters spring in one by one, quick and plain."], "avoid_when": ["A designed reveal with props: use a `text/reveal` item like `text/per-character-rise`."], "asked_as": ["letter animation", "text reveal", "headline animation"]},
"bounce-text": {"use_when": ["Words dropping in and bouncing: playful titles."], "avoid_when": ["A designed bounce: use `text/text-swell`."], "asked_as": ["bouncy text", "bounce in"]},
"bubble-pop-text": {"use_when": ["Letters popping in as bubbles: kids, games, playful brands."], "avoid_when": ["A sober title: use `text/cool-down`."], "asked_as": ["bubble text", "pop letters"]},
"chapter-title": {"use_when": ["A chapter number and title card to split a long video into parts."], "avoid_when": ["An end title: use `text/title-sweep`."], "asked_as": ["chapter title", "section card", "part 1"]},
"cinematic-title-intro": {"use_when": ["A wide-spaced title fading up between letterbox bars: trailers, film openers."], "avoid_when": ["A designed film title: use `text/announce-title`."], "asked_as": ["cinematic title", "movie title", "trailer title"]},
"credits-roll": {"use_when": ["End credits scrolling up the frame."], "avoid_when": ["One end title: use `text/title-sweep`."], "asked_as": ["credits", "end credits", "rolling credits"]},
"floating-bubble-text": {"use_when": ["A word floating in a bobbing bubble: labels, tags."], "avoid_when": ["A pill that takes over the line: use `text/inline-pill-takeover`."], "asked_as": ["floating label", "text chip", "bubble label"]},
"glitch-text": {"use_when": ["A word glitching with RGB splits: tech, gaming, music."], "avoid_when": ["A chromatic wave over a line: use `text/chromatic-wave`."], "asked_as": ["glitch text", "RGB split", "distorted text"]},
"popping-text": {"use_when": ["Words popping in with a scale punch."], "avoid_when": ["A designed punch: use `text/hook-punch`."], "asked_as": ["pop text", "scale pop"]},
"pulsing-text": {"use_when": ["A word pulsing gently for emphasis on a hold."], "avoid_when": ["A one-time emphasis: use `text/highlight-sweep`."], "asked_as": ["pulsing text", "heartbeat text"]},
"quote-card": {"use_when": ["A pull quote with attribution on a card."], "avoid_when": ["A designed quote: use `social/quote-hero` or `social/said-who`."], "asked_as": ["quote", "quote card", "testimonial"]},
"slide-text": {"use_when": ["A line of text sliding in from the side, plain."], "avoid_when": ["Lines sliding in one by one with props: use `text/line-by-line-slide`."], "asked_as": ["slide in text", "text slide"]},
"text-highlight": {"use_when": ["A marker highlight sweeping behind words of a line in turn."], "avoid_when": ["A designed highlight with props: use `text/highlight-sweep` or `marks/marker-highlight`."], "asked_as": ["highlight words", "marker", "highlighter"]},
"title-split": {"use_when": ["A title splitting apart to reveal a second line."], "avoid_when": ["A designed split: use `text/beam-split`."], "asked_as": ["split title", "title reveal"]},
"typewriter-subtitle": {"use_when": ["A subtitle typed letter by letter with a cursor."], "avoid_when": ["A typing AI prompt: use `ui/prompt-send`.", "Handwriting: use `text/handwrite`."], "asked_as": ["typewriter", "typing text", "typed subtitle"]},
"blinds-transition": {"use_when": ["Blinds closing over one scene and opening on the next."], "avoid_when": ["A designed split: use `transitions/mondrian-split`."], "asked_as": ["blinds", "venetian blinds transition"]},
"clock-wipe": {"use_when": ["A radial wipe sweeping round like a clock hand."], "avoid_when": ["A slash: use `transitions/slash-wipe`."], "asked_as": ["clock wipe", "radial wipe"]},
"cross-dissolve": {"use_when": ["The classic dissolve between two scenes."], "avoid_when": ["You want a styled dissolve: use `transitions/dot-bloom`."], "asked_as": ["cross dissolve", "crossfade", "fade between"]},
"fade-through-black": {"use_when": ["A dip to black between scenes: time passing, chapter changes."], "avoid_when": ["A dip through a colour: use `transitions/fade-through`."], "asked_as": ["fade to black", "dip to black"]},
"film-burn": {"use_when": ["A warm film-burn flare washing across the frame: vintage, nostalgia."], "avoid_when": ["An anamorphic lens flare: use `transitions/anamorphic-flare`."], "asked_as": ["film burn", "light leak", "flare"]},
"iris-transition": {"use_when": ["A circle closing on one scene and opening on the next: silent-film or cartoon style."], "avoid_when": ["A designed reveal: use `transitions/torn-edge`."], "asked_as": ["iris", "circle wipe"]},
"letterbox-reveal": {"use_when": ["Letterbox bars opening to reveal the scene: cinematic openers."], "avoid_when": ["A whole title: use `text/cinematic-title-intro`."], "asked_as": ["letterbox", "cinema bars", "black bars"]},
"morph-transition": {"use_when": ["One shape morphing into another to carry a cut."], "avoid_when": ["A shared-axis move: use `transitions/shared-axis-z`."], "asked_as": ["morph", "shape morph transition"]},
"pixel-transition": {"use_when": ["The frame breaking into pixels and rebuilding as the next scene: games, retro."], "avoid_when": ["A pixel look on a whole shot: use `looks/brick-mosaic`."], "asked_as": ["pixel transition", "pixelate", "8-bit transition"]},
"push-transition": {"use_when": ["The next scene pushing the old one out of frame."], "avoid_when": ["Doors sliding apart: use `transitions/slide-doors`."], "asked_as": ["push", "slide transition"]},
"slide-wipe": {"use_when": ["A coloured panel wiping across to the next scene."], "avoid_when": ["A slashed wipe: use `transitions/slash-wipe`."], "asked_as": ["wipe", "panel wipe", "colour wipe"]},
"whip-pan": {"use_when": ["A fast blurred whip pan between two scenes: energy, travel, comedy."], "avoid_when": ["A camera crash zoom on text: use `text/crash-zoom`."], "asked_as": ["whip pan", "swish pan", "fast pan"]},
"zoom-through": {"use_when": ["Zooming through the frame into the next scene."], "avoid_when": ["A dolly zoom: use `depth/dolly-zoom`."], "asked_as": ["zoom transition", "zoom through"]}
}
-101
View File
@@ -1,101 +0,0 @@
// A library component's props, read from its own source with the TypeScript parser: each member of its Props type
// (the type of its first parameter, or COMPONENTProps), its type as written, the default its destructuring gives it,
// and the doc comment above it. Members of an interface it extends, or of a type it intersects, count when they're
// in the same file. A default that's a constant of the file (`slant = SLANT`) is shown as that constant's value.
import ts from "../../sdk/shell/node_modules/typescript/lib/typescript.js";
export type Prop = { name: string; type: string; default?: string; says?: string; required?: boolean };
const flat = (s: string) => s.replace(/\s+/g, " ").trim();
export function readProps(src: string, component: string): Prop[] {
const sf = ts.createSourceFile("index.tsx", src, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
const types = new Map<string, ts.InterfaceDeclaration | ts.TypeAliasDeclaration>();
const consts = new Map<string, string>();
let fn: ts.FunctionLikeDeclaration | undefined;
// `const X: React.FC<XProps> = (...)`: the props' type is the annotation's argument
let annotated: ts.TypeNode | undefined;
for (const st of sf.statements) {
if (ts.isInterfaceDeclaration(st) || ts.isTypeAliasDeclaration(st)) types.set(st.name.text, st);
if (ts.isFunctionDeclaration(st) && st.name?.text === component) fn = st;
if (ts.isVariableStatement(st))
for (const d of st.declarationList.declarations) {
if (!ts.isIdentifier(d.name) || !d.initializer) continue;
const init = d.initializer;
if (d.name.text === component && (ts.isArrowFunction(init) || ts.isFunctionExpression(init))) {
fn = init;
if (d.type && ts.isTypeReferenceNode(d.type)) annotated = d.type.typeArguments?.[0];
}
else if (ts.isStringLiteral(init) || ts.isNumericLiteral(init) || init.kind === ts.SyntaxKind.TrueKeyword || init.kind === ts.SyntaxKind.FalseKeyword || ts.isNoSubstitutionTemplateLiteral(init) || ts.isPrefixUnaryExpression(init))
consts.set(d.name.text, init.getText(sf));
}
}
// its props' type: the first parameter's, else COMPONENTProps
const param = fn?.parameters[0];
const typeNode: ts.TypeNode | undefined = param?.type ?? annotated;
const props = new Map<string, Prop>();
const seen = new Set<string>();
const doc = (m: ts.Node) =>
flat(
ts
.getJSDocCommentsAndTags(m)
.map((j) => (typeof j.comment === "string" ? j.comment : (j.comment ?? []).map((c) => c.text).join("")))
.join(" "),
) ||
flat(
(ts.getLeadingCommentRanges(sf.text, m.getFullStart()) ?? [])
.map((r) => sf.text.slice(r.pos, r.end))
.filter((c) => c.startsWith("//"))
.map((c) => c.replace(/^\/\/\s?/, ""))
.join(" "),
);
const members = (ms: readonly ts.TypeElement[]) => {
for (const m of ms) {
if (!ts.isPropertySignature(m) || !m.name) continue;
const name = m.name.getText(sf).replace(/^["']|["']$/g, "");
if (props.has(name)) continue;
const says = doc(m);
props.set(name, { name, type: m.type ? flat(m.type.getText(sf)) : "unknown", ...(says ? { says } : {}), ...(m.questionToken ? {} : { required: true }) });
}
};
const walk = (t: ts.TypeNode | undefined) => {
if (!t) return;
if (ts.isTypeLiteralNode(t)) members(t.members);
else if (ts.isIntersectionTypeNode(t)) t.types.forEach(walk);
else if (ts.isParenthesizedTypeNode(t)) walk(t.type);
else if (ts.isTypeReferenceNode(t)) {
const name = t.typeName.getText(sf);
// Partial<X>, Readonly<X> and the like: X's members
if (t.typeArguments?.length && !types.has(name)) t.typeArguments.forEach(walk);
else named(name);
}
};
const named = (name: string) => {
const d = types.get(name);
if (!d || seen.has(name)) return;
seen.add(name);
if (ts.isInterfaceDeclaration(d)) {
members(d.members);
for (const h of d.heritageClauses ?? []) for (const e of h.types) named(e.expression.getText(sf));
} else walk(d.type);
};
if (typeNode) walk(typeNode);
else named(`${component}Props`);
// defaults: the first parameter's destructuring, else `const { ... } = props` in the body
let pattern = param && ts.isObjectBindingPattern(param.name) ? param.name : undefined;
if (!pattern && param && ts.isIdentifier(param.name) && fn?.body) {
const id = param.name.text;
const find = (n: ts.Node): ts.ObjectBindingPattern | undefined =>
ts.isVariableDeclaration(n) && ts.isObjectBindingPattern(n.name) && n.initializer && ts.isIdentifier(n.initializer) && n.initializer.text === id ? n.name : ts.forEachChild(n, find);
pattern = find(fn.body);
}
for (const el of pattern?.elements ?? []) {
const name = (el.propertyName ?? el.name).getText(sf);
if (!el.initializer || !props.has(name)) continue;
let d = flat(el.initializer.getText(sf));
if (consts.has(d)) d = consts.get(d) as string;
if (d.length > 160) d = `${d.slice(0, 157)}...`;
props.get(name)!.default = d;
}
return [...props.values()];
}
-191
View File
@@ -1,191 +0,0 @@
// The upstream libraries the component library was taken from, read from plain checkouts of them (tools/library-meta.sh
// clones them): each upstream component's source (for matching by content), its docs page (what it is, when to use
// it and when not, how people ask for it, its props table, the motion described under Usage) and its preview's size
// and length. Nothing here runs upstream code: the files are read as text.
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
import { basename, join, relative } from "node:path";
export type Row = { name: string; type?: string; default?: string; description?: string };
export type Up = {
source: string; // the catalog's `from`
name: string; // upstream's own name for it
section?: string; // its docs section (ai, numbers, product-scenes, ...)
tokens: Set<string>;
description?: string;
useWhen: string[];
avoidWhen: string[];
askedAs: string[];
vibe?: string;
usage?: string; // the first paragraph of prose under Usage
rows: Row[]; // its docs' props table
frames?: number;
fps?: number;
width?: number;
height?: number;
};
const read = (p: string) => (existsSync(p) ? readFileSync(p, "utf8") : "");
const dirs = (p: string) => (existsSync(p) ? readdirSync(p).filter((d) => !d.startsWith("_") && statSync(join(p, d)).isDirectory()) : []);
const walk = (p: string): string[] => (existsSync(p) ? readdirSync(p).flatMap((f) => (statSync(join(p, f)).isDirectory() ? walk(join(p, f)) : [join(p, f)])) : []);
/** What a source file is made of, for matching: its identifiers and its strings, without comments or imports */
export function tokens(src: string): Set<string> {
const body = src
.replace(/\/\*[\s\S]*?\*\//g, " ")
.replace(/(^|[^:"'`])\/\/.*$/gm, "$1")
.replace(/^\s*import[\s\S]*?from\s+["'][^"']+["'];?/gm, " ");
const out = new Set<string>();
for (const [, s] of body.matchAll(/"([^"\n]{3,80})"|'([^'\n]{3,80})'/g)) if (s) out.add(`"${s}`);
for (const [w] of body.matchAll(/[A-Za-z_$][\w$]{2,}/g)) out.add(w);
return out;
}
export function similarity(a: Set<string>, b: Set<string>): number {
let both = 0;
for (const t of a) if (b.has(t)) both++;
return both / (a.size + b.size - both || 1);
}
/** A docs page's frontmatter: scalars and lists of strings, the only YAML these pages use */
function frontmatter(text: string): Record<string, string | string[]> {
const m = text.match(/^---\n([\s\S]*?)\n---/);
const out: Record<string, string | string[]> = {};
let key = "";
const unq = (v: string) => {
v = v.trim();
if (v.startsWith('"')) {
try {
return JSON.parse(v) as string;
} catch {
return v.slice(1, -1);
}
}
return v.startsWith("'") ? v.slice(1, -1).replace(/''/g, "'") : v;
};
for (const line of (m?.[1] ?? "").split("\n")) {
const kv = line.match(/^(\w+):\s*(.*)$/);
if (kv) {
key = kv[1];
out[key] = kv[2].trim() ? unq(kv[2]) : [];
} else if (/^\s+-\s/.test(line) && Array.isArray(out[key])) (out[key] as string[]).push(unq(line.replace(/^\s+-\s/, "")));
}
return out;
}
/** A docs page's <PropsTable rows={[...]}>: each row's string fields */
function propsTable(text: string): Row[] {
const at = text.indexOf("<PropsTable");
if (at < 0) return [];
const end = text.indexOf("/>", at);
const block = text.slice(at, end < 0 ? undefined : end);
const rows: Row[] = [];
for (const [obj] of block.matchAll(/\{[^{}]*\}/g)) {
const row: Record<string, string> = {};
for (const [, k, v] of obj.matchAll(/(\w+):\s*("(?:[^"\\]|\\.)*")/g)) {
try {
row[k] = JSON.parse(v);
} catch {
row[k] = v.slice(1, -1);
}
}
if (row.name) rows.push(row as Row);
}
return rows;
}
/** The first paragraph of prose under ## Usage, after its code block */
function usage(text: string): string | undefined {
const at = text.search(/^## Usage/m);
if (at < 0) return undefined;
const rest = text.slice(at).replace(/^## Usage\n/, "").replace(/```[\s\S]*?```/g, "\n\n");
const para = rest
.split(/\n\s*\n/)
.map((p) => p.trim())
.find((p) => p && !p.startsWith("<") && !p.startsWith("#") && !p.startsWith("|") && !p.startsWith("import "));
return para?.replace(/\s+/g, " ");
}
/** A preview config's length and size (W, H and FPS are the libraries' shared 1280x720 at 30) */
function config(text: string): Pick<Up, "frames" | "fps" | "width" | "height"> {
const num = (k: string, named: Record<string, number>) => {
const v = text.match(new RegExp(`\\b${k}:\\s*([\\w.]+)`))?.[1];
return v === undefined ? undefined : /^\d/.test(v) ? Number(v) : named[v];
};
return { frames: num("durationInFrames", {}), fps: num("fps", { FPS: 30 }), width: num("compositionWidth", { W: 1280 }), height: num("compositionHeight", { H: 720 }) };
}
function page(docs: string, name: string, byComponent: Map<string, string>): Partial<Up> {
const file = byComponent.get(name);
if (!file) return {};
const text = read(file);
const fm = frontmatter(text);
const list = (k: string) => (Array.isArray(fm[k]) ? (fm[k] as string[]) : []);
return {
section: relative(docs, file).split("/")[0],
description: typeof fm.description === "string" ? fm.description : undefined,
useWhen: list("useWhen"),
avoidWhen: list("avoidWhen"),
askedAs: list("askedAs"),
vibe: typeof fm.vibe === "string" ? fm.vibe : undefined,
usage: usage(text),
rows: propsTable(text),
};
}
/** Each docs page by the component it documents (its frontmatter's `component`, else its file name) */
function docsIndex(docs: string): Map<string, string> {
const by = new Map<string, string>();
for (const f of walk(docs).filter((f) => f.endsWith(".mdx") && !f.endsWith("/index.mdx"))) {
const c = read(f).match(/^component:\s*"?([\w-]+)"?/m)?.[1] ?? basename(f, ".mdx");
if (!by.has(c)) by.set(c, f);
}
return by;
}
function registry(source: string, root: string, regs: string[], docs: string): Up[] {
const byComponent = docsIndex(docs);
return regs.flatMap((reg) =>
dirs(join(root, reg)).map((name) => {
const dir = join(root, reg, name);
const src = readdirSync(dir)
.filter((f) => /\.tsx?$/.test(f) && f !== "config.ts")
.map((f) => read(join(dir, f)))
.join("\n");
return { source, name, tokens: tokens(src), useWhen: [], avoidWhen: [], askedAs: [], rows: [], ...config(read(join(dir, "config.ts"))), ...page(docs, name, byComponent) };
}),
);
}
/** Every upstream component, from checkouts at UP/remocn, UP/snapcn and UP/rve-templates (React Video Editor's) */
export function upstream(up: string): Up[] {
const rve = join(up, "rve-templates");
const table = new Map<string, string>();
for (const [, file, said] of read(join(rve, "README.md")).matchAll(/^\|[^|]+\|\s*`([\w-]+)\.tsx`\s*\|\s*([^|]+?)\s*\|/gm)) table.set(file, said);
const templates = walk(join(rve, "templates"))
.filter((f) => f.endsWith(".tsx"))
.map((f) => {
const name = basename(f, ".tsx");
return { source: "rve-templates", name, tokens: tokens(read(f)), description: table.get(name), useWhen: [], avoidWhen: [], askedAs: [], rows: [] } as Up;
});
return [
...registry("remocn", join(up, "remocn"), ["registry/remocn"], join(up, "remocn/content/docs")),
...registry("snapcn", join(up, "snapcn"), ["registry/snap-cn", "registry/snap-cn-ui"], join(up, "snapcn/content/docs")),
...templates,
];
}
/** Docs pages with no registry folder behind them (a section's overview, a guide) aren't components; these are */
export function documented(up: string): { source: string; name: string; section: string; description?: string }[] {
const out: { source: string; name: string; section: string; description?: string }[] = [];
for (const [source, docs, skip] of [
["remocn", join(up, "remocn/content/docs"), /^(guides|getting-started|craft|icons)$/],
["snapcn", join(up, "snapcn/content/docs"), /^(getting-started|collections)$/],
] as const)
for (const [name, file] of docsIndex(docs)) {
const section = relative(docs, file).split("/")[0];
if (skip.test(section) || !file.includes("/", docs.length + 1)) continue;
const fm = frontmatter(read(file));
out.push({ source, name, section, description: typeof fm.description === "string" ? fm.description : undefined });
}
return out;
}
-85
View File
@@ -1,85 +0,0 @@
// The words the catalog gives each component: upstream's own (what it is, when to use it, how people ask for it) put
// in raea's plain voice with the other libraries' names taken out, and the phrases a person says for a kind of thing
// ("chat input", "terminal", "lower third") added by what the component is.
/** Upstream's text with the libraries' and their tooling's names out: the component is raea's now */
export function veil(s: string): string {
return s
.replace(/\s*(for|in) Remotion\b/g, "")
.replace(/\bRemotion `?<Composition>`?/g, "raea composition")
.replace(/`?@[a-z-]+\/captions`?/g, "raea's captions")
.replace(/`@[a-z-]+\/[\w-]+`/g, "raea")
.replace(/`?npx shadcn@latest add [^`\s]+`?/g, "`raea make component add`")
.replace(/\b(the|a) (Remocn|remocn|snapcn) (repo|registry|site|docs)\b/gi, "the original library")
.replace(/\bthe word Remocn\b/g, "a sample wordmark")
.replace(/\b(Remocn|remocn|snapcn|snap-cn)[- ]ui\b/gi, "the shared UI kit")
.replace(/\b(the|its|a) (Remocn|remocn|snapcn|snap-cn)('s)? (mark|logo|lime|brand|wordmark)\b/gi, "$1 sample $4")
.replace(/remocn-only/gi, "not shipped")
.replace(/\bRemotion\b/g, "raea")
.replace(/\bshadcn\b/gi, "UI-kit")
.replace(/\b(the|a|an) (Remocn|remocn|snapcn|snap-cn)\b/gi, "the brand")
.replace(/\b(Remocn|remocn|snapcn|snap-cn)\b/g, "the brand")
.replace(/(^|[.!?:]\s+)the brand/g, "$1The brand")
.replace(/\bthe customi[sz]er\b/gi, "a form")
.replace(/\s+—\s+/g, ": ")
.replace(/\s{2,}/g, " ")
.trim();
}
/** Other components named in `backticks` by their upstream name: ours (category/name) where we have it; where we
* don't, the pointer goes and the reason stays ("You need X: use `y`" becomes "You need X") */
export function relink(s: string, ours: Map<string, string>, known: Set<string>): string {
const M = "\u0000";
const swapped = s.replace(/`([a-z0-9]+(?:-[a-z0-9]+)*)`/g, (m, n) => (ours.has(n) ? `\`${ours.get(n)}\`` : known.has(n) ? M : m));
if (!swapped.includes(M)) return swapped;
return swapped
.replace(new RegExp(`\\s*\\((${M}[,\\s]*(or\\s+|and\\s+)?)+\\)`, "g"), "")
.replace(new RegExp(`${M}(\\s*(,|or|and)\\s*${M})+`, "g"), M)
.replace(new RegExp(`\\s*(,|or|and)\\s*${M}`, "g"), "")
.replace(new RegExp(`${M}\\s*(,|or|and)\\s*`, "g"), "")
.replace(new RegExp(`[:;,.]?\\s*(then |instead )?(use|try|reach for|pair (it )?with|see|choose|pick)\\s+(the\\s+)?${M}[^.;]*`, "gi"), "")
.replace(new RegExp(M, "g"), "another component")
.replace(/\s+[-:;,]?\s*\.$/, ".")
.replace(/\s+([.,;:])/g, "$1")
.replace(/[:;,]\s*$/, "")
.trim();
}
export type Shape = { name: string; category: string; type: string; section?: string; upstream?: string };
/** The phrases people say for what a component is, beyond its own docs' (a person asking for "a terminal", "a
* composer" or "a template" means one of these) */
export function phrases(i: Shape): string[] {
const n = `${i.name} ${i.upstream ?? ""}`;
const out: string[] = [];
const add = (...p: string[]) => out.push(...p);
// a whole scene to fill with your words (a product demo, a launch, a testimonial): what people mean by "a template"
const scene = /^(product-scenes|compositions|ui-blocks|scenes|templates)$/.test(i.section ?? "") || /^(end-card|launch)$/.test(i.type) || i.category === "social";
if (scene) add("template", "scene template", "preset");
if (/^(looks|transitions|marks|backgrounds|depth)$/.test(i.category) || /^(effects|graphic-looks|camera|motion-graphics|filters|shaders)$/.test(i.section ?? "")) add("effect", "preset");
// a box a person types a prompt or message into (the "composer" of a chat app)
if (i.type === "prompt" || /^(prompt-|click-type$|input$|caret-dolly$|card-push-line$|ghost-complete$|chat-to-preview)/.test(i.name))
add("AI prompt", "prompt box", "chat input", "composer", "chat composer", "message box", "Claude composer", "branded UI animation");
// an AI assistant's side of it: answers, agents, voice
if (i.type === "ai" || /^(answer-|agent-|voice-agent)/.test(i.name)) add("AI chat", "chat UI", "AI assistant", "chatbot", "LLM", "AI product demo");
if (/^(agent-steps|terminal-)/.test(i.name)) add("Claude Code", "coding agent", "agent working");
if (/terminal/.test(n)) add("terminal", "command line", "CLI", "shell", "console", "Claude Code terminal", "dev tool");
if (i.type === "code") add("developer", "dev tool", "code");
if (/cursor|click|button-press/.test(n)) add("mouse cursor", "click", "pointer");
if (i.category === "ui") add("UI animation", "app demo", "product UI", "screen recording look");
if (i.type === "phone" || /phone/.test(n)) add("phone mockup", "mobile app", "iPhone");
if (/laptop|browser/.test(n) || i.type === "browser") add("laptop mockup", "browser window", "website");
if (i.category === "text") add("text animation", "kinetic type", "kinetic typography", "title");
if (i.category === "numbers") add("stat", "number", "counter", "big number");
if (i.category === "charts") add("chart", "graph", "data viz");
if (i.category === "captions") add("captions", "subtitles");
if (i.category === "logo") add("logo reveal", "logo animation", "intro", "outro", "sting");
if (i.type === "lower-third") add("lower third", "name title", "name tag");
if (i.category === "transitions") add("transition", "scene change", "wipe");
if (i.category === "backgrounds") add("background", "backdrop", "loop");
if (i.category === "social" || i.type === "social") add("social post", "social media");
if (i.category === "hud") add("HUD", "game overlay", "scoreboard");
if (i.category === "gallery") add("photo gallery", "image grid", "photos");
if (i.category === "looks") add("look", "filter", "grade");
return out;
}