Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

raea render --props and --scale, getInputProps() and a composition's calculateMetadata: input props over defaultProps, a size or length worked out from them, and a render at S times the composition's size (#176, #175)

shinyobjectzc0417d91abf0
diff --git a/apps/direction/src/pure.rs b/apps/direction/src/pure.rs
index 14d1d71a..02514b89 100644
--- a/apps/direction/src/pure.rs
+++ b/apps/direction/src/pure.rs
@@ -28,7 +28,7 @@ const LEVELS: f32 = 96.0;
const SHARE: f64 = 1e-4;
const LEAST: usize = 64;
/// The flags of the render the stills repeat (each takes a value, then the bare ones): what it draws and at what size
-const KEEP: [&str; 9] = ["--composition", "--w", "--h", "--fps", "--frames", "--words", "--perception", "--input", "--stage"];
+const KEEP: [&str; 11] = ["--composition", "--w", "--h", "--fps", "--frames", "--words", "--perception", "--input", "--stage", "--props", "--scale"];
const KEEP_BARE: [&str; 2] = ["--clay", "--lite"];
const BY: &str = "raea render (frame-pure)";
diff --git a/docs/manual/reference/cli/render.md b/docs/manual/reference/cli/render.md
index 94ca1d8b..b743630e 100644
--- a/docs/manual/reference/cli/render.md
+++ b/docs/manual/reference/cli/render.md
@@ -60,7 +60,7 @@ the reason in the manifest. A render of a file in a raea project also keeps its
## Usage
```sh
-raea render EDIT.tsx -o OUT.mp4|OUT.png|OUT.wav|DIR [--audio OUT.wav] [--frame N | --at A,B] [--composition ID] [--w W] [--h H] [--fps FPS] [--frames N] [--words W.json] [--perception P.json] [--input I.json|inputs.rrl] [--manifest render.json] [--layers] [--stage WxH] [--10bit] [--aov] [--alpha [--alpha-codec prores|hevc|rle|png]] [--kbps N | --quality draft|high|master|0..1] [--clay] [--despite CHECK WHY] (also: --lite --comps)
+raea render EDIT.tsx -o OUT.mp4|OUT.png|OUT.wav|DIR [--audio OUT.wav] [--frame N | --at A,B] [--composition ID] [--w W] [--h H] [--fps FPS] [--frames N] [--words W.json] [--perception P.json] [--input I.json|inputs.rrl] [--props JSON|P.json] [--scale S] [--manifest render.json] [--layers] [--stage WxH] [--10bit] [--aov] [--alpha [--alpha-codec prores|hevc|rle|png]] [--kbps N | --quality draft|high|master|0..1] [--clay] [--despite CHECK WHY] (also: --lite --comps)
raea render EDIT.tsx --review DIR [--frame N] (fixed cameras hero, front, right, top, iso, low in colour and clay: DIR/colour.png, clay.png, review.json)
raea render PAGE.html -o OUT.mp4|OUT.png|DIR [--at A,B] [--alpha] (an HTML composition)
raea render --bundle NAME.comp.js -o OUT.png|DIR [--dir DIR] [--frame N] (a bundle from raea bundle, as render_bundle draws it)
@@ -94,8 +94,10 @@ Headless: it needs nothing running and opens no window. Takes up to 1 argument b
| `--lite` | – | Draw with raea's live view runtime instead of React, as a live game does. Used by the app when it opens a game. |
| `--manifest` | `render.json` | Write the render's manifest to this file instead of beside the output: the composition's length in frames (`length`, whichever frames were rendered), every frame's element boxes as drawn, what the render found and the sounds heard, which `raea check` and `raea world` read. |
| `--perception` | `P.json` | The perception the composition's Clock reads (faces, boxes, one for every frame or by frame), when it isn't the `perception.json` beside it. |
+| `--props` | `JSON\|P.json` | Input props, as a JSON object or a file holding one. `getInputProps()` returns them, and they go over the composition's `defaultProps` before `calculateMetadata` runs. |
| `--quality` | `draft\|high\|master\|0..1` | Constant-quality encoding: `draft` for previews, `high` for most deliveries, `master` for type and hard edges, or a number from 0 to 1. On Windows and Linux (OpenH264) it scales the bitrate instead, and once a frame fits at OpenH264's finest quantiser (12), a higher setting writes the same file. |
| `--review` | `DIR` | Render a 3D scene from six fixed cameras (hero, front, right, top, iso, low), in colour and in clay, to `DIR/colour.png`, `DIR/clay.png` and `DIR/review.json`. |
+| `--scale` | `S` | Draws the composition at S times its size: `0.5` is a half-size draft, `2` a 1080p composition at 4K. Layout stays in the composition's own pixels. Above 0, 8 at most. |
| `--stage` | `WxH` | Render a responsive composition, one that lays out from `useVideoConfig()`, at this size. A fixed-size composition ignores it and says so. |
| `--w` | `W` | Width in pixels for a file with no `<Composition>` or `config` (1080 by default). |
| `--words` | `W.json` | A transcript for the Clock's words (captions and cuts read them), when it isn't the `words.json` beside the composition. |
diff --git a/docs/manual/reference/sdk/app.md b/docs/manual/reference/sdk/app.md
index f3715788..97ed0325 100644
--- a/docs/manual/reference/sdk/app.md
+++ b/docs/manual/reference/sdk/app.md
@@ -32,7 +32,7 @@ app.step(10);
import { App, BevyApp, clearRegistry, Composition } from "raea/app"
```
-`raea/app` exports 1 component, 1 hook, 4 functions, 3 classes, 17 values, 17 types. Bevy's counterpart: `bevy_app`. Source: [sdk/raea/src/app.ts](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/src/app.ts).
+`raea/app` exports 1 component, 1 hook, 5 functions, 3 classes, 17 values, 18 types. Bevy's counterpart: `bevy_app`. Source: [sdk/raea/src/app.ts](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/src/app.ts).
## Components
@@ -49,6 +49,7 @@ Declares a composition inside the root. It draws nothing itself; a renderer find
| `fps` (required) | `number` | frames a second |
| `durationInFrames` (required) | `number` | its length in frames |
| `defaultProps` | `P` | the props it's rendered with (JSON-like values only) |
+| `calculateMetadata` | `CalculateMetadata<P>` | its size, rate, length or props worked out from the props it's rendered with (`defaultProps` under the command line's `--props`): what it returns replaces the values above, so one composition renders a video per props file. It returns its values directly, not a promise |
| `controls` | `Controls<P>` | the composition's controls: which of its defaultProps a person may tune, and how. Each names a defaultProps key, whose value is the control's; the feed's Controls panel shows them on the timeline and a change reaches the live picture as that prop |
| `edit` | `Edit` | a hand edit laid over the composition (docs/craft-system.md, L): written back by the app's timeline |
@@ -90,6 +91,15 @@ The compositions the registered root declares, in order.
function getCompositions(): RegisteredComposition[]
```
+### `getInputProps`
+
+The props given on the command line (`raea render --props '{"n": 2}'` or `--props props.json`), anywhere in a
+program; `{}` when none were. A composition's component gets them over its `defaultProps`.
+
+```ts
+function getInputProps<T extends Record<string, unknown> = Record<string, unknown>>(): T
+```
+
### `registerRoot`
Names the root component the renderer starts from, and records its compositions. Call it once.
@@ -240,6 +250,14 @@ The frame's main schedules: Update for game logic, then SpawnScene, PostUpdate a
## Types
+### `CalculateMetadata`
+
+What `calculateMetadata` is given and may return.
+
+```ts
+type CalculateMetadata = (given: { defaultProps: P; props: P; compositionId: string }) => { durationInFrames?: number; width?: number; height?: number; fps?: number; props?: P; } | void
+```
+
### `ChoiceControl`
One of a list: a string or a number from `options`.
diff --git a/docs/manual/reference/sdk/index.md b/docs/manual/reference/sdk/index.md
index 83b74d91..ca89b1b6 100644
--- a/docs/manual/reference/sdk/index.md
+++ b/docs/manual/reference/sdk/index.md
@@ -31,8 +31,8 @@ The composition, the app, and the specs and notes an agent writes.
| Import | What it's for | Exports |
| --- | --- | --- |
-| [`raea`](raea.md) | The main entry: compositions, sequences, time, interpolation, springs, footage, sound and words. | 21 components, 9 hooks, 64 functions, 11 values, 108 types |
-| [`raea/app`](app.md) | The App, its plugins and schedules, and the registry a video's compositions are kept in. | 1 component, 1 hook, 4 functions, 3 classes, 17 values, 17 types |
+| [`raea`](raea.md) | The main entry: compositions, sequences, time, interpolation, springs, footage, sound and words. | 21 components, 9 hooks, 65 functions, 11 values, 109 types |
+| [`raea/app`](app.md) | The App, its plugins and schedules, and the registry a video's compositions are kept in. | 1 component, 1 hook, 5 functions, 3 classes, 17 values, 18 types |
| [`raea/brief`](brief.md) | The specs an agent writes as data: brief, script, taste and an object's parts, checked against raea's schemas. | 8 functions, 34 types |
| [`raea/note`](note.md) | A person's note as a file in the project: their words kept as written, and the asks the agent restates it as. | 1 function, 4 types |
diff --git a/docs/manual/reference/sdk/raea.md b/docs/manual/reference/sdk/raea.md
index 48ed5f13..873e3888 100644
--- a/docs/manual/reference/sdk/raea.md
+++ b/docs/manual/reference/sdk/raea.md
@@ -38,7 +38,7 @@ See [Your first video](../../start/first-video.md) for the whole loop, and
import { AbsoluteFill, ACTION_KEY, actionsIn, Animate } from "raea"
```
-`raea` exports 21 components, 9 hooks, 64 functions, 11 values, 108 types. Source: [sdk/raea/src/index.tsx](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/src/index.tsx).
+`raea` exports 21 components, 9 hooks, 65 functions, 11 values, 109 types. Source: [sdk/raea/src/index.tsx](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/src/index.tsx).
## Components
@@ -106,6 +106,7 @@ Declares a composition inside the root. It draws nothing itself; a renderer find
| `fps` (required) | `number` | frames a second |
| `durationInFrames` (required) | `number` | its length in frames |
| `defaultProps` | `P` | the props it's rendered with (JSON-like values only) |
+| `calculateMetadata` | `CalculateMetadata<P>` | its size, rate, length or props worked out from the props it's rendered with (`defaultProps` under the command line's `--props`): what it returns replaces the values above, so one composition renders a video per props file. It returns its values directly, not a promise |
| `controls` | `Controls<P>` | the composition's controls: which of its defaultProps a person may tune, and how. Each names a defaultProps key, whose value is the control's; the feed's Controls panel shows them on the timeline and a change reaches the live picture as that prop |
| `edit` | `Edit` | a hand edit laid over the composition (docs/craft-system.md, L): written back by the app's timeline |
@@ -525,6 +526,15 @@ The compositions the registered root declares, in order.
function getCompositions(): RegisteredComposition[]
```
+### `getInputProps`
+
+The props given on the command line (`raea render --props '{"n": 2}'` or `--props props.json`), anywhere in a
+program; `{}` when none were. A composition's component gets them over its `defaultProps`.
+
+```ts
+function getInputProps<T extends Record<string, unknown> = Record<string, unknown>>(): T
+```
+
### `gridDelay`
A grid item's distance from an origin, in steps (raea-animate's StaggerPattern::Grid, the same rule).
@@ -1113,6 +1123,14 @@ type AssetKind = "lyria" | "sao" | "tokensynth"
The props of [`Audio`](#audio), tabled there.
+### `CalculateMetadata`
+
+What `calculateMetadata` is given and may return.
+
+```ts
+type CalculateMetadata = (given: { defaultProps: P; props: P; compositionId: string }) => { durationInFrames?: number; width?: number; height?: number; fps?: number; props?: P; } | void
+```
+
### `ChoiceControl`
One of a list: a string or a number from `options`.
diff --git a/engine/cli/src/cli.rs b/engine/cli/src/cli.rs
index a05d2503..8869d71c 100644
--- a/engine/cli/src/cli.rs
+++ b/engine/cli/src/cli.rs
@@ -376,8 +376,8 @@ pub fn run(args: &[String]) -> R<String> {
}
if args.first().map(String::as_str) != Some("render") || args.len() < 2 {
return Err(format!(
- "raea render EDIT.tsx -o OUT.mp4|OUT.png|OUT.wav|DIR [--audio OUT.wav] [--frame N | --at A,B] [--composition ID] [--w W] [--h H] [--fps FPS] [--frames N] [--words W.json] [--perception P.json] [--input I.json|inputs.rrl] [--manifest render.json] [--layers] [--stage WxH] [--10bit] [--aov] [--alpha [--alpha-codec prores|hevc|rle|png]] [--kbps N | --quality draft|high|master|0..1] [--clay] [--despite CHECK WHY] (also: --lite --comps)\n raea render EDIT.tsx --review DIR [--frame N] (fixed cameras hero, front, right, top, iso, low in colour and clay: DIR/colour.png, clay.png, review.json)\n raea render PAGE.html -o OUT.mp4|OUT.png|DIR [--at A,B] [--alpha] (an HTML composition)\n raea render --bundle NAME.comp.js -o OUT.png|DIR [--dir DIR] [--frame N] (a bundle from raea bundle, as render_bundle draws it)
- raea media probe|still|sheet|audio|loudness|motion|cuts|freezes|proxy|lod|trim|concat FILE ... | ffmpeg ARGS | ffprobe ARGS (media work, native: media help)
+ "raea render EDIT.tsx -o OUT.mp4|OUT.png|OUT.wav|DIR [--audio OUT.wav] [--frame N | --at A,B] [--composition ID] [--w W] [--h H] [--fps FPS] [--frames N] [--words W.json] [--perception P.json] [--input I.json|inputs.rrl] [--props JSON|P.json] [--scale S] [--manifest render.json] [--layers] [--stage WxH] [--10bit] [--aov] [--alpha [--alpha-codec prores|hevc|rle|png]] [--kbps N | --quality draft|high|master|0..1] [--clay] [--despite CHECK WHY] (also: --lite --comps)\n raea render EDIT.tsx --review DIR [--frame N] (fixed cameras hero, front, right, top, iso, low in colour and clay: DIR/colour.png, clay.png, review.json)\n raea render PAGE.html -o OUT.mp4|OUT.png|DIR [--at A,B] [--alpha] (an HTML composition)\n raea render --bundle NAME.comp.js -o OUT.png|DIR [--dir DIR] [--frame N] (a bundle from raea bundle, as render_bundle draws it)
+ raea media probe|still|sheet|audio|loudness|motion|cuts|freezes|proxy|share|lod|trim|concat FILE ... | ffmpeg ARGS | ffprobe ARGS (media work, native: media help)
raea bundle EDIT.tsx --composition-bundle -o OUT.js [--portable DIR] (a composition for render_bundle, on the Mac or the iPhone)\n raea add PKG[@RANGE]... [--dev] | remove NAME... | install [--offline] [--in DIR] (npm packages for the project: raea.lock, node_modules)\n {} (foley, local)\n {} (an instrument's notes, local)\n raea setup-audio [--check] [sao|tokensynth] (install or check the local audio models)\n {} (the song's energy map: beats, sections, builds, drops, stops, hits, cuts per bar; also: --backend NAME)\n raea sounds [WORDS] | sounds get PACK/INSTRUMENT [--notes ..|--all] [-o DIR] (open sample libraries for a Sampler)\n {} (the clip's camera solved, for <Matchmove>)",
tools::sound::SAO_USAGE, tools::sound::TOKENSYNTH_USAGE, tools::song::USAGE, motion::track::USAGE
));
diff --git a/runtime/bundle/src/entry.rs b/runtime/bundle/src/entry.rs
index cd96982f..3cff6554 100644
--- a/runtime/bundle/src/entry.rs
+++ b/runtime/bundle/src/entry.rs
@@ -5,13 +5,15 @@ pub fn entry(file: &str, o: &CompOpts) -> String {
let js = |v: &Option<Value>| v.as_ref().map(Value::to_string).unwrap_or("null".into());
let (words, perception, input) = (js(&o.words), js(&o.perception), js(&o.input));
let given = serde_json::to_string(&o.given).unwrap_or("[]".into());
+ let props = format!("{} x{}", js(&o.props), o.scale.unwrap_or(1.0));
// the composition's element made once, so a frame re-renders only what reads the frame (its clock, through
// useCurrentFrame), not every part (docs/control.feature FC1b). A frame is already pure (a still renders any
// frame alone), so a part drawing Math.random or Date in render without reading the frame breaks either way.
// RAEA_STILL_TREE=0 makes it each frame, as before. In the entry's text, so the bundle cache tells the two apart
let still = std::env::var("RAEA_STILL_TREE").map_or(true, |v| v != "0");
format!(
- r#"import {{ frameCallbacks, pureAgain, pureFrame, pureSession, seedOf }} from "./motion/pure";
+ r#"import "./props"; // --props, set before the edit's modules run: {props}
+import {{ frameCallbacks, pureAgain, pureFrame, pureSession, seedOf }} from "./motion/pure";
import {{ canvas2d }} from "./motion/canvas2d";
import * as BevyReact from "bevy-react";
import {{ mount, addEventListener, BevyCanvasElement }} from "bevy-react";
@@ -33,7 +35,8 @@ if (!C) throw new Error("{file} exports no component and registers no compositio
// durationInFrames}}` (score's SDK backend writes it); its positive numbers win over the CLI's settings
const MC: any = (M as any).config ?? {{}};
const pos = (v: any, d: number) => (typeof v === "number" && v > 0 ? v : d);
-const cfg = reg ?? {{ id: "main", width: pos(MC.width, {w}), height: pos(MC.height, {h}), fps: pos(MC.fps, {fps}), durationInFrames: pos(MC.durationInFrames, {frames}), defaultProps: {{}} }};
+const cfg = reg ?? {{ id: "main", width: pos(MC.width, {w}), height: pos(MC.height, {h}), fps: pos(MC.fps, {fps}), durationInFrames: pos(MC.durationInFrames, {frames}), defaultProps: (globalThis as any).__raea_input_props ?? {{}} }};
+if (!reg && (globalThis as any).__raea_scale !== undefined) console.warn("NOT APPLIED --scale: it draws a <Composition> at a fraction of its size; this file registers none (--w and --h size it)");
for (const [k, key, v] of {given} as [string, string, number][]) if ((cfg as any)[key] !== v) console.warn(`NOT APPLIED ${{k}} ${{v}}: the composition says its ${{key}} is ${{(cfg as any)[key]}}; ${{k}} only sizes a file with no <Composition> or config`);
// the Clock's words (frames {{text, from, to}}, or seconds {{text, start, end}} / {{text, start_ms, end_ms}}), perception
// (one for every frame, or by frame: the latest at or before it) and input (a timeline, or inputs.rrl's step keys)
diff --git a/runtime/bundle/src/fresh.rs b/runtime/bundle/src/fresh.rs
index 7a621fba..b24cb5cf 100644
--- a/runtime/bundle/src/fresh.rs
+++ b/runtime/bundle/src/fresh.rs
@@ -167,6 +167,9 @@ pub fn bundle_fresh(tsx: &Path, out_js: &Path, o: &CompOpts, portable: Option<&P
}
let js = raea_io_home::home().join("sdk/react/js");
link_node_modules(&js, &work)?;
+ // the command line's props, where getInputProps() and a Composition read them (the entry imports it first)
+ let global = |v: Option<String>| v.unwrap_or("undefined".into());
+ std::fs::write(work.join("props.ts"), format!("(globalThis as any).__raea_input_props = {};\n(globalThis as any).__raea_scale = {};\n", global(o.props.as_ref().map(Value::to_string)), global(o.scale.map(|s| s.to_string())))).map_err(|e| e.to_string())?;
if o.lite {
// the game's code and the SDK's resolve "react" to the live view runtime (tsconfig paths cover the files under
// the work folder; packages in node_modules keep their own React)
diff --git a/runtime/bundle/src/lib.rs b/runtime/bundle/src/lib.rs
index ad5ebf96..2eeba25c 100644
--- a/runtime/bundle/src/lib.rs
+++ b/runtime/bundle/src/lib.rs
@@ -133,6 +133,11 @@ pub struct CompOpts {
pub words: Option<Value>,
pub perception: Option<Value>,
pub input: Option<Value>,
+ /// `--props`: the composition's props from the command line, a JSON object or a file of one (over its
+ /// defaultProps, and what getInputProps() returns; docs/move-in.feature MV4, #176)
+ pub props: Option<Value>,
+ /// `--scale S`: a `<Composition>` laid out at its own size and drawn at S times it (MV5, #175)
+ pub scale: Option<f64>,
/// live play's runtime instead of React (sdk/react/js/lite: each frame rendered and only what changed sent, no
/// reconciler): what a game plays on; renders keep React
pub lite: bool,
@@ -184,9 +189,22 @@ pub fn input_file(path: &str) -> R<Value> {
Ok(json!({ "steps": steps }))
}
+/// `--props`: a JSON object written out, or a file holding one.
+pub fn props_arg(given: &str) -> R<Value> {
+ let v = if given.trim_start().starts_with('{') { serde_json::from_str(given).map_err(|e| format!("--props {given}: {e}"))? } else { json_file(given)? };
+ if v.is_object() { Ok(v) } else { Err(format!("--props takes a JSON object ({{\"n\": 2}}) or a file of one, not {v}")) }
+}
+
+/// What the command line gave this run's composition (`--props`, `--scale`), for the render's manifest: a check of
+/// the file knows what it was rendered with.
+pub fn given() -> Option<Value> {
+ GIVEN.lock().unwrap().clone()
+}
+static GIVEN: std::sync::Mutex<Option<Value>> = std::sync::Mutex::new(None);
+
pub fn comp_opts(args: &[String]) -> R<CompOpts> {
let n = |k: &str| -> R<Option<f64>> { flag(args, k).map(|v| v.parse::<f64>().map_err(|_| format!("{k} takes a number"))).transpose() };
- Ok(CompOpts {
+ let o = CompOpts {
composition: flag(args, "--composition"),
w: n("--w")?.unwrap_or(1080.0) as u32,
h: n("--h")?.unwrap_or(1920.0) as u32,
@@ -196,9 +214,15 @@ pub fn comp_opts(args: &[String]) -> R<CompOpts> {
words: flag(args, "--words").map(|p| json_file(&p).and_then(|v| words_shape(&v).map(|_| v).map_err(|e| format!("--words {p}: {e}")))).transpose()?,
perception: flag(args, "--perception").map(|p| json_file(&p)).transpose()?,
input: flag(args, "--input").map(|p| input_file(&p)).transpose()?,
+ props: flag(args, "--props").map(|p| props_arg(&p)).transpose()?,
+ scale: n("--scale")?.map(|s| if s > 0.0 && s <= 8.0 { Ok(s) } else { Err(format!("--scale takes a number above 0, 8 at most (0.5 draws a half-size draft), not {s}")) }).transpose()?,
lite: args.iter().any(|a| a == "--lite"),
comps: args.iter().any(|a| a == "--comps"),
- })
+ };
+ if o.props.is_some() || o.scale.is_some() {
+ *GIVEN.lock().unwrap() = Some(json!({"props": o.props, "scale": o.scale}));
+ }
+ Ok(o)
}
/// A composition bundled for the engine (raea-bundle's library: Rolldown, on the Mac): the edit's folder and the SDK beside the engine's
diff --git a/runtime/export/src/lib.rs b/runtime/export/src/lib.rs
index a573582c..b412e8ff 100644
--- a/runtime/export/src/lib.rs
+++ b/runtime/export/src/lib.rs
@@ -74,9 +74,9 @@ fn write_manifest(cx: &mut Ctx, (w, h, fps, length): (u32, u32, f64, i64), found
let (Some(path), Some(frames)) = (MANIFEST.lock().unwrap().clone(), cx.manifest.take()) else { return Ok(()) };
path.parent().map_or(Ok(()), std::fs::create_dir_all).map_err(|e| format!("{}: {e}", path.display()))?;
let mut v = json!({"width": w, "height": h, "fps": fps, "length": length, "frames": frames, "findings": raea_core_facts::finding::ranked(found), "sounds": heard(cx), "not_applied": not_applied::seen(), "layers": raea_sys_layers::finish(fps), "has3d": cx.scene3d.is_some() || cx.live3d.is_some()});
- // the parts SG9 needs (scene.rs's SEEN): stills' parts on screen, a longer render's remounts
- if let (Some(m), Some(Value::Object(seen))) = (v.as_object_mut(), scene::SEEN.lock().unwrap().take()) {
- m.extend(seen);
+ // the parts SG9 needs (scene.rs's SEEN: stills' parts on screen, a longer render's remounts), and --props and --scale
+ for more in [scene::SEEN.lock().unwrap().take(), given()] {
+ v.as_object_mut().into_iter().zip(more.and_then(|m| m.as_object().cloned())).for_each(|(m, more)| m.extend(more));
}
std::fs::write(&path, v.to_string()).map_err(|e| format!("{}: {e}", path.display()))
}
diff --git a/sdk/raea/src/index.tsx b/sdk/raea/src/index.tsx
index 64ee407c..6b327ab7 100644
--- a/sdk/raea/src/index.tsx
+++ b/sdk/raea/src/index.tsx
@@ -53,6 +53,8 @@ export {
getCompositions,
registerRoot,
useControl,
+ getInputProps,
+ type CalculateMetadata,
type CompositionProps,
type Edit,
type RegisteredComposition,
diff --git a/sdk/video/src/registry.tsx b/sdk/video/src/registry.tsx
index ac642e0f..037c4611 100644
--- a/sdk/video/src/registry.tsx
+++ b/sdk/video/src/registry.tsx
@@ -23,6 +23,10 @@ export interface CompositionProps<P extends Record<string, unknown> = Record<str
durationInFrames: number;
/** the props it's rendered with (JSON-like values only) */
defaultProps?: P;
+ /** its size, rate, length or props worked out from the props it's rendered with (`defaultProps` under the command
+ * line's `--props`): what it returns replaces the values above, so one composition renders a video per props file.
+ * It returns its values directly, not a promise */
+ calculateMetadata?: CalculateMetadata<P>;
/** the composition's controls: which of its defaultProps a person may tune, and how (docs/realtime.feature RT4).
* Each names a defaultProps key, whose value is the control's; the feed's Controls panel shows them on the
* timeline and a change reaches the live picture as that prop */
@@ -31,6 +35,21 @@ export interface CompositionProps<P extends Record<string, unknown> = Record<str
edit?: Edit;
}
+/** What `calculateMetadata` is given and may return. */
+export type CalculateMetadata<P extends Record<string, unknown> = Record<string, unknown>> = (given: { defaultProps: P; props: P; compositionId: string }) => {
+ durationInFrames?: number;
+ width?: number;
+ height?: number;
+ fps?: number;
+ props?: P;
+} | void;
+
+/** The props given on the command line (`raea render --props '{"n": 2}'` or `--props props.json`), anywhere in a
+ * program; `{}` when none were. A composition's component gets them over its `defaultProps`. */
+export function getInputProps<T extends Record<string, unknown> = Record<string, unknown>>(): T {
+ return ((globalThis as { __raea_input_props?: unknown }).__raea_input_props ?? {}) as T;
+}
+
/** A hand edit: `segments` are the composition's own frame ranges, [from, to), played one after another, so a trim,
* a split, a cut word or a moved span is a change to this list; the length becomes their sum. */
export interface Edit {
@@ -89,6 +108,28 @@ function validate(props: CompositionProps<any>, taken: readonly RegisteredCompos
if (typeof props.component !== "function" && (typeof props.component !== "object" || props.component === null)) {
fail("component", "must be a React component");
}
+ const jsonObject = (field: string, v: unknown) => {
+ if (!isJsonLike(v, new Set()) || Array.isArray(v)) fail(field, "must be an object of JSON-like values (no functions, class instances or cycles)");
+ };
+ const declared = props.defaultProps ?? {};
+ jsonObject("defaultProps", declared);
+ // the command line's props over its own (--props, MV4), then what calculateMetadata makes of them
+ const input = getInputProps();
+ let defaultProps: Record<string, unknown> = Object.keys(input).length ? { ...declared, ...input } : declared;
+ if (props.calculateMetadata !== undefined) {
+ if (typeof props.calculateMetadata !== "function") fail("calculateMetadata", "must be a function");
+ const meta = props.calculateMetadata({ defaultProps: declared, props: defaultProps, compositionId: props.id });
+ if (meta && typeof (meta as { then?: unknown }).then === "function") fail("calculateMetadata", "returned a promise: it returns its values directly (pass data it would load with --props)");
+ if (meta) {
+ const { props: made, ...size } = meta;
+ // (a copy: an element's props are frozen)
+ props = { ...props, ...Object.fromEntries(Object.entries(size).filter(([, v]) => v !== undefined)) };
+ if (made !== undefined) {
+ jsonObject("calculateMetadata's props", made);
+ defaultProps = made;
+ }
+ }
+ }
for (const field of ["width", "height", "durationInFrames"] as const) {
const v = props[field];
if (!Number.isInteger(v) || v <= 0) fail(field, `must be a positive integer, got ${v}`);
@@ -96,10 +137,6 @@ function validate(props: CompositionProps<any>, taken: readonly RegisteredCompos
if (typeof props.fps !== "number" || !(props.fps > 0) || !Number.isFinite(props.fps)) {
fail("fps", `must be a positive number, got ${props.fps}`);
}
- const defaultProps = props.defaultProps ?? {};
- if (!isJsonLike(defaultProps, new Set()) || Array.isArray(defaultProps)) {
- fail("defaultProps", "must be an object of JSON-like values (no functions, class instances or cycles)");
- }
const segments = props.edit?.segments;
if (segments !== undefined) {
if (!Array.isArray(segments) || segments.length === 0) fail("edit.segments", "must be a non-empty list of [from, to] frame ranges");
@@ -108,9 +145,11 @@ function validate(props: CompositionProps<any>, taken: readonly RegisteredCompos
if (!ok) fail("edit.segments", `has ${JSON.stringify(seg)}: each is [from, to) with 0 <= from < to <= ${props.durationInFrames}`);
}
}
- const scale = props.edit?.scale;
- if (scale !== undefined && !(typeof scale === "number" && scale > 0 && scale <= 1)) fail("edit.scale", `must be a number above 0 and at most 1, got ${scale}`);
- const [w, h] = scale === undefined || scale === 1 ? [props.width, props.height] : [Math.max(1, Math.round(props.width * scale)), Math.max(1, Math.round(props.height * scale))];
+ const draft = props.edit?.scale;
+ if (draft !== undefined && !(typeof draft === "number" && draft > 0 && draft <= 1)) fail("edit.scale", `must be a number above 0 and at most 1, got ${draft}`);
+ // with the command line's --scale (MV5): laid out at its own size, drawn at that many times it
+ const scale = (draft ?? 1) * ((globalThis as { __raea_scale?: number }).__raea_scale ?? 1);
+ const [w, h] = scale === 1 ? [props.width, props.height] : [Math.max(1, Math.round(props.width * scale)), Math.max(1, Math.round(props.height * scale))];
const controls = validControls(props.controls, defaultProps as Record<string, unknown>, fail);
const cut = segments ? edited(props.component, segments) : props.component;
return {
@@ -435,7 +474,7 @@ export function registerRoot(given: ComponentType | ReactElement): void {
...IMPLICIT,
durationInFrames: walk.latestEnd > 0 ? Math.ceil(walk.latestEnd) : IMPLICIT.durationInFrames,
component: Root,
- defaultProps: {},
+ defaultProps: getInputProps(),
controls: {},
});
}