mirror of
https://github.com/shinyobjectz/raea.git
synced 2026-12-06 08:46:06 -10:00
Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
034c3cff48 | ||
|
|
4044e442c2 | ||
|
|
788444e127 | ||
|
|
5b72d2e4dc | ||
|
|
33d34e51b5 | ||
|
|
7cd22cecfc | ||
|
|
76e6b00e04 | ||
|
|
88cacbe7f7 |
No files matched your search
Generated
+2
@@ -13978,7 +13978,9 @@ dependencies = [
|
||||
name = "raea-app-playable"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dunce",
|
||||
"raea-core-fonts",
|
||||
"raea-io-home",
|
||||
"raea-runtime-bundle",
|
||||
"regex",
|
||||
|
||||
@@ -142,7 +142,7 @@ fn critic(job: &Job, newest: Option<SystemTime>, notes: &str) -> Vec<Value> {
|
||||
let what = match job.make.kind {
|
||||
goal::Kind::Kit => "raea render shared/components/KIT/lineup.tsx --review review/r1",
|
||||
goal::Kind::Shot => "raea make framing --out review/r1",
|
||||
goal::Kind::Scene | goal::Kind::Cut | goal::Kind::Rules => "raea render EDIT.tsx --review review/r1",
|
||||
goal::Kind::Scene | goal::Kind::Cut | goal::Kind::Rules | goal::Kind::Playable => "raea render EDIT.tsx --review review/r1",
|
||||
};
|
||||
return vec![gate("critic", None, false, format!("no round yet: {what}, then raea judge review/r1 --kind {kind} --by claude --brief brief.ts"))];
|
||||
};
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use image::{Rgba, RgbaImage};
|
||||
use raea_core_brief::{make::Make, read};
|
||||
use raea_core_brief::{goal::Goal as Make, read};
|
||||
|
||||
use crate::sheet::{Tile, sheet};
|
||||
|
||||
@@ -148,7 +148,7 @@ fn a_shot_frames_its_start_middle_and_end() {
|
||||
// a shot with no composition can't be framed, and says what's needed
|
||||
let d = dir("framing");
|
||||
assert!(crate::shots::framing(&d, &m, &["hold".to_string()], &d).unwrap_err().contains("no composition"));
|
||||
assert!(raea_core_brief::make::doctor(&m).iter().any(|w| w.contains("shot `hold` has no composition")));
|
||||
assert!(raea_core_brief::goal::doctor(&m).iter().any(|w| w.contains("shot `hold` has no composition")));
|
||||
}
|
||||
|
||||
// MK18: the floor plan draws every placed footprint (invented ones dashed); the blockout boxes them from the entrance
|
||||
@@ -193,7 +193,7 @@ fn a_quote_reads_as_one_line() {
|
||||
|
||||
#[test]
|
||||
fn a_boxy_model_is_fitted_by_its_height_and_turned_to_lie_front_to_back() {
|
||||
use raea_core_brief::make::Object;
|
||||
use raea_core_brief::goal::Object;
|
||||
let stapler: Object = serde_json::from_value(serde_json::json!({"id": "stapler", "label": "Stapler", "dims": [0.05, 0.17, 0.07]})).unwrap();
|
||||
// long across (x) where the plan's is front to back (z): a quarter turn
|
||||
assert_eq!(crate::kit::fit_args(&stapler, Some([1.9, 0.72, 0.58])), ["--dims", "0.05,0.17,0.07", "--h", "0.07", "--turn", "90"]);
|
||||
|
||||
@@ -14,4 +14,7 @@ raea-runtime-bundle = { path = "../../runtime/bundle" }
|
||||
raea-io-home = { path = "../../io/home" }
|
||||
regex = "1"
|
||||
serde_json = "1"
|
||||
# the faces the native page draws with (core/fonts), inlined in the page under the families the game names (PA8)
|
||||
raea-core-fonts = { path = "../../core/fonts" }
|
||||
base64 = "0.22"
|
||||
zip = { version = "9", default-features = false, features = ["deflate-flate2"] }
|
||||
@@ -0,0 +1,127 @@
|
||||
//! The page's fonts as the native render draws them (docs/playables.feature PA8). A composition's page draws with
|
||||
//! raea's bundled faces (core/fonts: Fontsource latin subsets, a few weights a family), each family the page names
|
||||
//! aliased onto one (Helvetica, Arial and SF Pro draw as Inter, Times as EB Garamond, ...) and each weight drawn by the
|
||||
//! nearest face (core/fonts `face`). A phone has none of them, so brick-rush's Inter fell back to a serif. The export
|
||||
//! inlines, for every family the game's script names that raea aliases, its faces as @font-face data URLs under that
|
||||
//! name, each face's weight a range that makes the browser's choice the native one (Inter 400/700/900: 1-550, 551-800,
|
||||
//! 801-1000; a weight halfway between two faces takes the lighter, as `face`'s first-found minimum does). The page's
|
||||
//! own default family is Inter, the native page's.
|
||||
|
||||
use base64::Engine;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// The family a page with no family of its own draws in
|
||||
const DEFAULT: &str = "Inter";
|
||||
|
||||
/// Each family name the script writes (fontFamily values and CSS font-family declarations), as written, with the
|
||||
/// bundled family raea draws it as; the default first
|
||||
pub fn families(script: &str) -> Vec<(String, &'static str)> {
|
||||
let mut out: Vec<(String, &'static str)> = vec![(DEFAULT.into(), "inter")];
|
||||
let res = [
|
||||
r#"fontFamily["']?\s*:\s*["'`]([^"'`]+)["'`]"#,
|
||||
r#"font-family\s*:\s*([^;"'`}]+)"#,
|
||||
];
|
||||
for re in res {
|
||||
let re = regex::Regex::new(re).expect("a valid pattern");
|
||||
for cap in re.captures_iter(script) {
|
||||
for name in cap[1].split(',') {
|
||||
let name = name.trim().trim_matches(|c| c == '"' || c == '\'').trim();
|
||||
if let Some(c) = raea_core_fonts::canonical(name) {
|
||||
if !out.iter().any(|(n, _)| n.eq_ignore_ascii_case(name)) {
|
||||
out.push((name.to_string(), c));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A bundled family's faces as (weight range, style, woff2): each style's weights split halfway between neighbours,
|
||||
/// the halfway weight to the lighter face
|
||||
pub fn faces(canonical: &str) -> Vec<((u16, u16), &'static str, &'static [u8])> {
|
||||
let mut by_style: BTreeMap<&str, Vec<(u16, &'static [u8])>> = BTreeMap::new();
|
||||
for (f, w, st, bytes) in raea_core_fonts::BUNDLED {
|
||||
if *f == canonical {
|
||||
by_style
|
||||
.entry(st)
|
||||
.or_default()
|
||||
.push((w.parse().unwrap_or(400), bytes));
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for (st, mut ws) in by_style {
|
||||
ws.sort_by_key(|(w, _)| *w);
|
||||
let mut lo = 1u16;
|
||||
for (i, (w, bytes)) in ws.iter().enumerate() {
|
||||
let hi = ws.get(i + 1).map_or(1000, |(next, _)| (w + next) / 2);
|
||||
out.push(((lo, hi), st, *bytes));
|
||||
lo = hi + 1;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The page's <style>: each family the script names that raea aliases, its faces inlined under that name, and the
|
||||
/// page's default family
|
||||
pub fn style(script: &str) -> String {
|
||||
let b64 = base64::engine::general_purpose::STANDARD;
|
||||
let mut css = String::from("<style>\n");
|
||||
for (name, canonical) in families(script) {
|
||||
for ((lo, hi), st, bytes) in faces(canonical) {
|
||||
css.push_str(&format!(
|
||||
"@font-face{{font-family:\"{}\";font-style:{st};font-weight:{lo} {hi};src:url(data:font/woff2;base64,{}) format(\"woff2\")}}\n",
|
||||
name.replace('"', ""),
|
||||
b64.encode(bytes)
|
||||
));
|
||||
}
|
||||
}
|
||||
css.push_str(&format!("html,body{{font-family:\"{DEFAULT}\"}}\n</style>"));
|
||||
css
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn each_family_the_game_names_is_aliased_as_the_native_page_does() {
|
||||
let script = r#"h("div",{style:{fontFamily:"Inter, system-ui, sans-serif",fontWeight:900}});x={fontFamily:'Helvetica Neue'};y="b{font-family: Georgia, serif;}""#;
|
||||
let f = families(script);
|
||||
assert_eq!(
|
||||
f,
|
||||
[
|
||||
("Inter".to_string(), "inter"),
|
||||
("Helvetica Neue".into(), "inter"),
|
||||
("Georgia".into(), "eb-garamond")
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_weight_takes_the_face_the_native_page_takes() {
|
||||
let r: Vec<(u16, u16)> = faces("inter").iter().map(|(r, _, _)| *r).collect();
|
||||
assert_eq!(r, [(1, 550), (551, 800), (801, 1000)]);
|
||||
// the native pick for each weight is the face whose range holds it
|
||||
for w in [100u16, 400, 550, 551, 700, 800, 801, 900] {
|
||||
let native = raea_core_fonts::face("Inter", w, false).unwrap();
|
||||
let ours = faces("inter")
|
||||
.into_iter()
|
||||
.find(|((lo, hi), _, _)| (*lo..=*hi).contains(&w))
|
||||
.unwrap()
|
||||
.2;
|
||||
assert!(native == ours, "weight {w}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_style_holds_inter_and_sets_the_default() {
|
||||
let css = style("var x=1;");
|
||||
assert_eq!(css.matches("@font-face").count(), 3);
|
||||
assert!(
|
||||
css.contains("font-weight:801 1000")
|
||||
&& css.contains("html,body{font-family:\"Inter\"}")
|
||||
);
|
||||
assert!(css.len() < 110_000, "{} bytes", css.len());
|
||||
}
|
||||
}
|
||||
+64
-12
@@ -1,7 +1,9 @@
|
||||
//! `raea playable GAME.tsx -o DIR`: a raea game exported as a playable ad (docs/playables.feature PA13). The same TSX
|
||||
//! that renders with `raea render` as the video ad (it plays itself) is linted (lint.rs), bundled once with
|
||||
//! sdk/playable's browser host by raea's own bundler (Rolldown, in process: minified, its pictures and tables carried
|
||||
//! in the script, one three.js), and written as each network's page or ZIP (pages.rs), each checked against its cap.
|
||||
//! in the script; three.js only when the lint found a 3D kind, PA15), and written as each network's page or ZIP
|
||||
//! (pages.rs), each checked against its cap.
|
||||
mod fonts;
|
||||
mod lint;
|
||||
mod pages;
|
||||
|
||||
@@ -9,7 +11,7 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
type R<T> = Result<T, String>;
|
||||
|
||||
pub const USAGE: &str = "raea playable GAME.tsx -o DIR [--networks LIST] [--ios URL] [--android URL] [--title TEXT] [--cta TEXT] [--orientation portrait|landscape|both]";
|
||||
pub const USAGE: &str = "raea playable GAME.tsx -o DIR [--name NAME] [--networks LIST] [--ios URL] [--android URL] [--title TEXT] [--cta TEXT] [--orientation portrait|landscape|both]";
|
||||
pub const ABOUT: &str = "a game as a playable ad: one page or ZIP per network (applovin, unity, google, meta, moloco, mintegral, tiktok, liftoff, preview), each under its 5 MB cap, from the TSX that renders as the video ad";
|
||||
|
||||
/// A path as an import specifier (no Windows verbatim prefix, which Rolldown can't open): raea-bundle's own
|
||||
@@ -36,17 +38,31 @@ fn three_dir(game: &Path, home: &Path) -> R<PathBuf> {
|
||||
.ok_or_else(|| "a playable draws its 3D with three.js, which this project doesn't have: `raea add [email protected]` in it".into())
|
||||
}
|
||||
|
||||
/// The bundle's entry: 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)
|
||||
fn entry(game: &Path, host: &Path, with_3d: bool) -> String {
|
||||
let mut e = format!("import {:?};\nimport {{ start }} from {:?};\n", spec(game), spec(&host.join("main.tsx")));
|
||||
if with_3d {
|
||||
e.push_str(&format!("import {{ three3d }} from {:?};\nstart(three3d);\n", spec(&host.join("three.ts"))));
|
||||
} else {
|
||||
e.push_str("start();\n");
|
||||
}
|
||||
e
|
||||
}
|
||||
|
||||
/// The game and the host in one minified script that carries its files
|
||||
fn bundle(game: &Path, home: &Path) -> R<String> {
|
||||
let host = home.join("sdk/playable/src/host/main.tsx");
|
||||
if !host.is_file() {
|
||||
fn bundle(game: &Path, home: &Path, with_3d: bool) -> R<String> {
|
||||
let host = home.join("sdk/playable/src/host");
|
||||
if !host.join("main.tsx").is_file() {
|
||||
return Err(format!("{}: raea's playable host isn't there", host.display()));
|
||||
}
|
||||
let three = three_dir(game, home)?;
|
||||
let out = std::env::temp_dir().join(format!("raea-playable-{}.js", std::process::id()));
|
||||
let entry = format!("import {:?};\nimport {:?};\n", spec(game), spec(&host));
|
||||
let alias = format!("three/={}", three.display());
|
||||
let r = raea_runtime_bundle::bundle_entry(&entry, &out, &["--minify", "1", "--inline", "1", "--alias", &alias]);
|
||||
let mut flags = vec!["--minify".to_string(), "1".into(), "--inline".into(), "1".into()];
|
||||
if with_3d {
|
||||
flags.extend(["--alias".into(), format!("three/={}", three_dir(game, home)?.display())]);
|
||||
}
|
||||
let flags: Vec<&str> = flags.iter().map(String::as_str).collect();
|
||||
let r = raea_runtime_bundle::bundle_entry(&entry(game, &host, with_3d), &out, &flags);
|
||||
let js = r.and_then(|_| std::fs::read_to_string(&out).map_err(|e| e.to_string()));
|
||||
let _ = std::fs::remove_file(&out);
|
||||
js
|
||||
@@ -66,7 +82,12 @@ pub fn cli(args: &[String]) -> R<String> {
|
||||
}
|
||||
let store = serde_json::json!({"ios": flag(args, "--ios").unwrap_or(""), "android": flag(args, "--android").unwrap_or("")}).to_string();
|
||||
let card = serde_json::json!({"title": flag(args, "--title").unwrap_or(""), "cta": flag(args, "--cta").unwrap_or("Play now")}).to_string();
|
||||
let name = game.file_stem().and_then(|s| s.to_str()).unwrap_or("playable").to_string();
|
||||
// the files' name: the brief's (`playable({ playable: { name } })`), else the game's file name
|
||||
let stem = game.file_stem().map(|s| s.to_string_lossy().into_owned());
|
||||
let name = flag(args, "--name").map(str::to_string).or(stem).unwrap_or_else(|| "playable".into());
|
||||
if name.is_empty() || name.contains(['/', '\\']) {
|
||||
return Err(format!("--name {name:?}: a file name, no folders"));
|
||||
}
|
||||
|
||||
let mut report = Vec::new();
|
||||
let found = lint::lint(&game)?;
|
||||
@@ -83,16 +104,29 @@ pub fn cli(args: &[String]) -> R<String> {
|
||||
return Err(why.join("\n"));
|
||||
}
|
||||
|
||||
let js = bundle(&game, &raea_io_home::home())?;
|
||||
let js = bundle(&game, &raea_io_home::home(), !found.kinds.is_empty())?;
|
||||
// the faces the native page draws with, for the families the game names (PA8)
|
||||
let style = fonts::style(&js);
|
||||
std::fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?;
|
||||
let mut over = false;
|
||||
let mut written = Vec::new();
|
||||
for net in networks {
|
||||
let script = format!("{}\n{js}", pages::preamble(net, &store, &card));
|
||||
let w = pages::write(net, &name, &script, &out, orientation)?;
|
||||
let w = pages::write(net, &name, &script, &out, orientation, &style)?;
|
||||
let ok = w.bytes <= pages::CAP;
|
||||
over |= !ok;
|
||||
report.push(format!("{:<10} {:<40} {:>6} KB / {} KB {}", w.network, w.file.display(), w.bytes / 1024, pages::CAP / 1024, if ok { "ok" } else { "OVER" }));
|
||||
written.push(w);
|
||||
}
|
||||
// what was written, for raea goal's playable pack (sdk/goal packs/playable.ts) and raea cloud's review
|
||||
let manifest = serde_json::json!({
|
||||
"name": name, "game": game.display().to_string(), "orientation": orientation, "kinds": found.kinds,
|
||||
"compositions": found.comps.iter().map(|c| serde_json::json!({"id": c.id, "width": c.width, "height": c.height, "fps": c.fps, "frames": c.frames})).collect::<Vec<_>>(),
|
||||
"pages": written.iter().map(|w| serde_json::json!({"network": w.network, "file": w.file.file_name().map(|f| f.to_string_lossy().to_string()).unwrap_or_default(), "bytes": w.bytes})).collect::<Vec<_>>(),
|
||||
"cap": pages::CAP,
|
||||
});
|
||||
let mf = out.join(format!("{name}.playable.json"));
|
||||
std::fs::write(&mf, serde_json::to_string_pretty(&manifest).unwrap_or_default()).map_err(|e| format!("{}: {e}", mf.display()))?;
|
||||
if over {
|
||||
report.insert(0, format!("a page is over its network's {} KB cap", pages::CAP / 1024));
|
||||
return Err(report.join("\n"));
|
||||
@@ -100,3 +134,21 @@ pub fn cli(args: &[String]) -> R<String> {
|
||||
report.push(format!("APPLIED {name} exported as a playable to {}", out.display()));
|
||||
Ok(report.join("\n"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::entry;
|
||||
use std::path::Path;
|
||||
|
||||
#[test]
|
||||
fn a_2d_game_starts_with_no_drawer() {
|
||||
let e = entry(Path::new("/g/game.tsx"), Path::new("/h/host"), false);
|
||||
assert!(e.contains("start();") && !e.contains("three"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_3d_game_starts_with_three() {
|
||||
let e = entry(Path::new("/g/game.tsx"), Path::new("/h/host"), true);
|
||||
assert!(e.contains("three3d } from \"/h/host/three.ts\"") && e.contains("start(three3d);"), "{e}");
|
||||
}
|
||||
}
|
||||
@@ -43,9 +43,10 @@ fn zip(file: &Path, entries: &[(String, String)]) -> R<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `network`'s package of `script` (its preamble already first) written into `out` as NAME-NETWORK.html or .zip
|
||||
pub fn write(network: &str, name: &str, script: &str, out: &Path, orientation: &str) -> R<Written> {
|
||||
let html = |head: &str, body: &str| page(name, head, body, script);
|
||||
/// `network`'s package of `script` (its preamble already first) written into `out` as NAME-NETWORK.html or .zip, its
|
||||
/// `style` (the fonts, fonts.rs) first in the head
|
||||
pub fn write(network: &str, name: &str, script: &str, out: &Path, orientation: &str, style: &str) -> R<Written> {
|
||||
let html = |head: &str, body: &str| page(name, &format!("{style}\n{head}"), body, script);
|
||||
let file = match network {
|
||||
// a ZIP with index.html; exitapi.js and the orientation tag in the head (Google Ads help 9981650)
|
||||
"google" => {
|
||||
|
||||
@@ -16,7 +16,6 @@ mkdir -p "$OUT"
|
||||
export RAEA_SIGN=0 RAEA_MARK=0 RAEA_EXPORT_CACHE=0
|
||||
expected() { case $1 in
|
||||
examples/games/animated-character.tsx) echo "its media/RobotExpressive.glb was deleted" ;;
|
||||
examples/playables/brick-rush.tsx) echo "RAEA_LIVE3D_CHECK panics on frame 1: the fast rows carry the sun's rotation and the full rows don't (runtime/scene/src/live.rs; docs/playables.feature PA18)" ;;
|
||||
sdk/raea/bench/bevy-parity/3d/rotate_environment_map.tsx) echo "clearcoat textures need raea-sys-material's multi-layer feature, off by default (as bench/bevy-parity/runs.tsv leaves it out)" ;;
|
||||
esac; }
|
||||
SAME=0 DIFF=0 ERR=0 SKIP=0
|
||||
|
||||
+18
-5
@@ -1,8 +1,8 @@
|
||||
//! A goal (docs/goal.feature): one step of the work, on a project's brief.ts as `goal:` (one, or several in order: a
|
||||
//! workflow), written with `cut()`, `shot()`, `kit()`, `scene()` or `rules()` from "raea/brief" before anything is
|
||||
//! built, and read here. Each kind turns its packs on: a scene (a dressed, lit place), a kit (props that belong
|
||||
//! together), a shot (stills or camera moves of a built scene), a cut (ads from footage to a client's brief), and
|
||||
//! rules (any other work: only its own rules). Any goal can carry `rules` and an `aim`. Every object carries its real
|
||||
//! workflow), written with `cut()`, `shot()`, `kit()`, `scene()`, `playable()` or `rules()` from "raea/brief" before
|
||||
//! anything is built, and read here. Each kind turns its packs on: a scene (a dressed, lit place), a kit (props that
|
||||
//! belong together), a shot (stills or camera moves of a built scene), a cut (ads from footage to a client's brief), a
|
||||
//! playable (a game exported as a playable ad, playable.rs), and rules (any other work: only its own rules). Any goal can carry `rules` and an `aim`. Every object carries its real
|
||||
//! size and whether it came from the reference or was invented; every dial its value, where the value came from, and
|
||||
//! what it meant here. `raea goal check` (sdk/goal) holds each goal to it.
|
||||
|
||||
@@ -25,6 +25,9 @@ pub enum Kind {
|
||||
Cut,
|
||||
/// any other work, held only to its rules: commands that must pass, files that must exist, words a critic judges
|
||||
Rules,
|
||||
/// a game exported as a playable ad by `raea playable`: each network's page, the preview, both orientations unless
|
||||
/// the brief says one (playable.rs, docs/playables.feature PA19)
|
||||
Playable,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
|
||||
@@ -74,6 +77,8 @@ pub struct Goal {
|
||||
pub rounds: Option<u32>,
|
||||
/// a cut job's contract: the brief as rules (cut.rs)
|
||||
pub cut: Option<crate::cut::Cut>,
|
||||
/// a playable job's game, networks and orientation (playable.rs)
|
||||
pub playable: Option<crate::playable::Playable>,
|
||||
/// what the job shows but never delivers, relative to the brief (pictures, render tests, examples): each a file or a
|
||||
/// `dir/` (review/ and previews/ when left out). Deliverables are what it hands over; previews are how it got there
|
||||
#[serde(default)]
|
||||
@@ -227,7 +232,7 @@ impl Kind {
|
||||
/// as brief.ts writes it, and as raea judge's rubrics are named
|
||||
pub fn name(self) -> &'static str {
|
||||
// in the enum's order
|
||||
["scene", "kit", "shot", "cut", "rules"][self as usize]
|
||||
["scene", "kit", "shot", "cut", "rules", "playable"][self as usize]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -239,6 +244,7 @@ pub fn dials(kind: Kind) -> &'static [&'static str] {
|
||||
Kind::Shot => &["res", "seconds", "lens", "handheld", "look"],
|
||||
Kind::Cut => &["look"],
|
||||
Kind::Rules => &[],
|
||||
Kind::Playable => &["look"],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -276,6 +282,7 @@ fn by_kind(m: &Goal) -> Vec<String> {
|
||||
Kind::Cut => m.cut.as_ref().map(crate::cut::deliverables).unwrap_or_default(),
|
||||
// only its `file` rules, added above
|
||||
Kind::Rules => vec![],
|
||||
Kind::Playable => m.playable.as_ref().map(crate::playable::deliverables).unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -307,6 +314,12 @@ pub fn doctor(m: &Goal) -> Vec<String> {
|
||||
(Some(_), k) => out.push(format!("`cut` is for a cut job, not a {k:?}: drop it, or make this `cut({{...}})`")),
|
||||
_ => {}
|
||||
}
|
||||
match (&m.playable, m.kind) {
|
||||
(Some(p), Kind::Playable) => out.extend(crate::playable::doctor(p)),
|
||||
(None, Kind::Playable) => out.push("no `playable`: the game's TSX (`game`), and its networks and orientation when the brief names them".into()),
|
||||
(Some(_), k) => out.push(format!("`playable` is for a playable job, not a {k:?}: drop it, or make this `playable({{...}})`")),
|
||||
_ => {}
|
||||
}
|
||||
out.extend(crate::rules::doctor(&m.rules));
|
||||
if m.kind == Kind::Rules {
|
||||
if m.aim.as_deref().is_none_or(|a| a.trim().is_empty()) {
|
||||
|
||||
+21
-3
@@ -7,6 +7,7 @@ pub mod brief;
|
||||
pub mod cut;
|
||||
pub mod goal;
|
||||
pub mod parts;
|
||||
pub mod playable;
|
||||
pub mod rules;
|
||||
pub mod script;
|
||||
pub mod taste;
|
||||
@@ -30,18 +31,35 @@ macro_rules! decls {
|
||||
($cfg:ident; $($t:ty),* $(,)?) => { vec![$(format!("export {}", <$t as TS>::decl(&$cfg))),*] };
|
||||
}
|
||||
|
||||
/// The TypeScript declarations of every schema, one file's worth: sdk/raea/src/brief.gen.ts is this, checked by a test, and
|
||||
/// `raea/brief` (sdk/raea/src/brief.ts) types its builders with it, so the declarations ship with the SDK.
|
||||
/// The file the goal's declarations are written to, beside brief.gen.ts (which re-exports them)
|
||||
pub const GOAL_FILE: &str = "brief-goal.gen";
|
||||
|
||||
/// The TypeScript declarations of every schema, two files' worth (a file stays under 500 lines, tools/size.sh):
|
||||
/// sdk/raea/src/brief.gen.ts is this, the goal's (`goal_declarations`) re-exported from it, each checked by a test,
|
||||
/// and `raea/brief` (sdk/raea/src/brief.ts) types its builders with them, so the declarations ship with the SDK.
|
||||
pub fn declarations() -> String {
|
||||
let cfg = Config::new();
|
||||
let mut out = vec!["// Generated from raea-core-brief (core/brief) by its `declarations`; edit the Rust, not this.".to_string()];
|
||||
let mut out = vec![format!(
|
||||
"// Generated from raea-core-brief (core/brief) by its `declarations`; edit the Rust, not this.\nimport type {{ Goals }} from \"./{GOAL_FILE}\";\nexport type * from \"./{GOAL_FILE}\";"
|
||||
)];
|
||||
out.extend(decls!(cfg;
|
||||
brief::Brief, brief::Section, brief::Deliverable, brief::Reference, brief::Agent,
|
||||
script::Script, script::Scene, script::Beat, script::Line,
|
||||
taste::Taste, taste::TasteSection, taste::Rule, taste::RuleCheck, taste::RuleLevel, taste::Check,
|
||||
parts::Parts, parts::Concept, parts::Level, parts::Count, parts::Part,
|
||||
));
|
||||
out.join("\n\n") + "\n"
|
||||
}
|
||||
|
||||
/// 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 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::Phrase, cut::Cta, cut::Open,
|
||||
playable::Playable, playable::Orientation,
|
||||
rules::Rule,
|
||||
));
|
||||
out.join("\n\n") + "\n"
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
//! A playable goal (docs/playables.feature PA19): a raea game exported as a playable ad by `raea playable`, held to its
|
||||
//! pages. The game is one TSX that renders as the video ad and exports for each network; the goal names it, the
|
||||
//! networks it ships to and its orientation (both, unless the brief says one), and its deliverables are what the export
|
||||
//! writes into out/playable/: each network's page or ZIP, the preview, and the export's manifest, which raea goal's
|
||||
//! playable pack reads (sizes, compositions, when it was exported).
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use ts_rs::TS;
|
||||
|
||||
/// The networks `raea playable` writes for (apps/playable pages.rs NETWORKS, preview last)
|
||||
pub const NETWORKS: &[&str] = &[
|
||||
"applovin",
|
||||
"unity",
|
||||
"google",
|
||||
"meta",
|
||||
"moloco",
|
||||
"mintegral",
|
||||
"tiktok",
|
||||
"liftoff",
|
||||
];
|
||||
/// The networks whose package is a ZIP (the rest are one HTML page)
|
||||
const ZIPPED: &[&str] = &["google", "mintegral", "tiktok"];
|
||||
/// Where the export writes, relative to the brief
|
||||
pub const OUT: &str = "out/playable";
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
#[ts(rename = "PlayableOrientation")]
|
||||
pub enum Orientation {
|
||||
/// a portrait and a landscape composition, the host playing the one nearest the screen
|
||||
Both,
|
||||
Portrait,
|
||||
Landscape,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
#[ts(optional_fields, rename = "PlayableGoal")]
|
||||
pub struct Playable {
|
||||
/// the game's TSX, relative to the brief: it renders as the video ad and exports as the playable
|
||||
pub game: String,
|
||||
/// the files' name ([a-z0-9_], `NAME-NETWORK.html`); the game's file name when left out
|
||||
pub name: Option<String>,
|
||||
/// the networks it ships to (applovin, unity, google, meta, moloco, mintegral, tiktok, liftoff); all of them when
|
||||
/// left out. The preview page is always made: it's what the review plays
|
||||
#[serde(default)]
|
||||
#[ts(as = "Option<Vec<String>>", optional)]
|
||||
pub networks: Vec<String>,
|
||||
/// both unless the brief says one: Unity, AppLovin, Moloco and Mintegral want both
|
||||
pub orientation: Option<Orientation>,
|
||||
/// [least, most] seconds of play before the end card (15 to 60 by default)
|
||||
pub seconds: Option<[f64; 2]>,
|
||||
/// the same game rendered as the video ad too, as out/cuts/NAME_9x16.mp4 (PA17)
|
||||
pub video: Option<bool>,
|
||||
}
|
||||
|
||||
/// The name its files land as: its own, else the game's file name, as `raea playable` names them
|
||||
pub fn name(p: &Playable) -> String {
|
||||
p.name.clone().unwrap_or_else(|| {
|
||||
std::path::Path::new(&p.game)
|
||||
.file_stem()
|
||||
.and_then(|s| s.to_str())
|
||||
.unwrap_or("playable")
|
||||
.to_string()
|
||||
})
|
||||
}
|
||||
|
||||
/// The networks it ships to, in raea's order
|
||||
pub fn networks(p: &Playable) -> Vec<&'static str> {
|
||||
NETWORKS
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|n| p.networks.is_empty() || p.networks.iter().any(|m| m == n))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// What the export must have written: each network's page or ZIP, the preview and the manifest, and the video ad
|
||||
pub fn deliverables(p: &Playable) -> Vec<String> {
|
||||
let n = name(p);
|
||||
let mut out: Vec<String> = networks(p)
|
||||
.iter()
|
||||
.map(|net| {
|
||||
format!(
|
||||
"{OUT}/{n}-{net}.{}",
|
||||
if ZIPPED.contains(net) { "zip" } else { "html" }
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
out.push(format!("{OUT}/{n}-preview.html"));
|
||||
out.push(format!("{OUT}/{n}.playable.json"));
|
||||
if p.video == Some(true) {
|
||||
out.push(format!("out/cuts/{n}_9x16.mp4"));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// What the playable still lacks before it can be built against
|
||||
pub fn doctor(p: &Playable) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
if !p.game.ends_with(".tsx") {
|
||||
out.push(format!(
|
||||
"`game` {:?}: the game's TSX beside the brief (playable.tsx)",
|
||||
p.game
|
||||
));
|
||||
}
|
||||
if let Some(n) = p.name.as_deref().filter(|n| !crate::goal::is_name(n)) {
|
||||
out.push(format!("playable name `{n}`: names are [a-z0-9_]"));
|
||||
}
|
||||
for n in p
|
||||
.networks
|
||||
.iter()
|
||||
.filter(|n| !NETWORKS.contains(&n.as_str()))
|
||||
{
|
||||
out.push(format!(
|
||||
"network `{n}` isn't one raea exports to ({})",
|
||||
NETWORKS.join(", ")
|
||||
));
|
||||
}
|
||||
if let Some([a, b]) = p.seconds {
|
||||
if !(a > 0.0 && a <= b) {
|
||||
out.push(format!("seconds [{a}, {b}]: least then most, both over 0"));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
+45
-7
@@ -1,14 +1,18 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn declarations_match_the_committed_file() {
|
||||
let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../sdk/raea/src/brief.gen.ts");
|
||||
let now = declarations();
|
||||
if std::env::var_os("RAEA_WRITE").is_some() {
|
||||
std::fs::write(path, &now).unwrap();
|
||||
fn declarations_match_the_committed_files() {
|
||||
let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/../../sdk/raea/src");
|
||||
for (file, now) in [("brief.gen.ts".to_string(), declarations()), (format!("{GOAL_FILE}.ts"), goal_declarations())] {
|
||||
let path = format!("{dir}/{file}");
|
||||
if std::env::var_os("RAEA_WRITE").is_some() {
|
||||
std::fs::write(&path, &now).unwrap();
|
||||
}
|
||||
let committed = std::fs::read_to_string(&path).unwrap_or_default();
|
||||
assert!(committed == now, "sdk/raea/src/{file} is out of date: RAEA_WRITE=1 cargo test -p raea-core-brief");
|
||||
let lines = now.lines().count();
|
||||
assert!(lines <= 500, "sdk/raea/src/{file} is {lines} lines: split it (tools/size.sh)");
|
||||
}
|
||||
let committed = std::fs::read_to_string(path).unwrap_or_default();
|
||||
assert!(committed == now, "sdk/raea/src/brief.gen.ts is out of date: RAEA_WRITE=1 cargo test -p raea-core-brief");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -153,3 +157,37 @@ fn several_goals_are_a_workflow_and_each_is_held_to_its_rules() {
|
||||
let one: Brief = read("brief.ts", r#"{"title": "x", "goal": {"kind": "rules", "aim": "ship it", "rules": [{"id": "ok", "run": "true"}]}}"#).unwrap();
|
||||
assert!(goal::doctor_all(one.goal.as_ref().unwrap()).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_playable_goal_delivers_each_networks_page_the_preview_and_the_manifest() {
|
||||
let g: crate::goal::Goal = serde_json::from_str(r#"{"kind":"playable","aim":"a runner for a tea brand","playable":{"game":"playable.tsx","networks":["applovin","google"],"video":true}}"#).unwrap();
|
||||
assert_eq!(
|
||||
crate::goal::deliverables(&g),
|
||||
[
|
||||
"out/playable/playable-applovin.html",
|
||||
"out/playable/playable-google.zip",
|
||||
"out/playable/playable-preview.html",
|
||||
"out/playable/playable.playable.json",
|
||||
"out/cuts/playable_9x16.mp4"
|
||||
]
|
||||
);
|
||||
assert!(
|
||||
crate::goal::doctor(&g).is_empty(),
|
||||
"{:?}",
|
||||
crate::goal::doctor(&g)
|
||||
);
|
||||
// both orientations unless the brief names one: `raea playable`'s own default
|
||||
assert_eq!(g.playable.as_ref().unwrap().orientation, None);
|
||||
let bad: crate::goal::Goal = serde_json::from_str(
|
||||
r#"{"kind":"playable","aim":"x","playable":{"game":"game.ts","networks":["vungle"]}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let d = crate::goal::doctor(&bad).join("\n");
|
||||
assert!(d.contains("game.ts") && d.contains("vungle"), "{d}");
|
||||
let none: crate::goal::Goal = serde_json::from_str(r#"{"kind":"playable","aim":"x"}"#).unwrap();
|
||||
assert!(
|
||||
crate::goal::doctor(&none)
|
||||
.iter()
|
||||
.any(|l| l.starts_with("no `playable`"))
|
||||
);
|
||||
}
|
||||
@@ -99,3 +99,27 @@ Feature: raea cloud: a synced folder is pictured, understood, embedded and organ
|
||||
When StreetTalk's four Drive syncs run from empty
|
||||
Then every file has a picture, a description and tags; the three client folders are related to their client
|
||||
libraries; a search for a shot finds it by what's in it; and the run says its time and what it cost
|
||||
|
||||
Rule: every video has a light copy to watch and cut from
|
||||
Scenario: IG14. A video's proxy is made once, from the download its index already makes
|
||||
(built 12-02: raea-platform index-run.ts submitProxy/proxyDue, sdk/cloud/deploy/modal/proxy.py)
|
||||
Given a video in a library, uploaded or synced from Drive
|
||||
Then raea makes a 540p proxy of it on Modal (540 lines on the short side and never more than the original,
|
||||
H.264 CRF 28 with a keyframe every second, AAC 96 kbps, faststart) from the same address its index job
|
||||
fetches, so a synced file is downloaded through its tool once for both
|
||||
And the proxy is kept in R2 by the original's SHA-256, written through a ticket for the workspace's proxies
|
||||
alone (the job holds no raea credential), so footage kept twice is made once
|
||||
And an original already that light (H.264 in MP4, 540 lines or fewer, under 2.5 Mbps) is its own proxy
|
||||
And a library indexed before proxies gets them a few at a time, 8 running a workspace
|
||||
|
||||
Scenario: IG15. People watch the proxy
|
||||
When a person opens a video in the library
|
||||
Then it plays from its proxy: no copy of a Drive original through its tool, and no 4K HEVC in the browser
|
||||
And its original stays one click away (Open)
|
||||
|
||||
Scenario: IG16. Agents look and cut from proxies, and finish from originals
|
||||
When an agent searches its libraries for footage
|
||||
Then it finds videos by what's in them (what's seen, heard and said, with the seconds where) and by name
|
||||
And each video comes with its proxy, whose times are the original's, to fetch, watch, transcribe and rough-cut
|
||||
And the original (an upload's link, or a synced file through library_original) is fetched only for the master
|
||||
And drafts on the farm read clip copies at the size they're drawn (CR36); masters read the originals
|
||||
@@ -353,3 +353,14 @@ notes and is worth shipping without it: a person gets word scores, checks and bo
|
||||
5. **CLAP joins the stack** (Shane, 11-12: "include clap if we can if its not too much work"). It is about 300 lines
|
||||
of Rust on ort: the 48 kHz log-mel front end and the audio session (200), and the text tower with its tokenizer
|
||||
(100), run only when an axis's words change. Both are checked against the spike's vectors at cosine 0.999.
|
||||
6. **Pro and Studio include checks and content intelligence** (Shane, 11-20). Each month's pool (about 8,000 frames
|
||||
checked on Pro, ten times that on Studio) stops when it's spent and is never billed past. It pays for two things:
|
||||
- **clef-omni answering the fingerprint's questions** about a render's frames (`POST /v1/clef/ask`), so the agent
|
||||
reads answers in words and opens only the frames they flag. Its verdicts are another eye's (FP6d), and it serves
|
||||
the axes with no labels yet.
|
||||
- **content intelligence for references** (`GET /v1/intel/...`): public posts, videos, transcripts and ads, to find
|
||||
a videoform's references by what performs and keep them current (docs/videoform.md). A source's views and
|
||||
engagement are another eye's evidence too, never the person's taste. A reference found this way is still read
|
||||
once, as VF1 reads any link, and VF1's rights confirmation still applies.
|
||||
|
||||
Without a pool, everything here still works locally, and clef runs on the person's own Cloudflare account.
|
||||
@@ -28,7 +28,7 @@ project (`raea add [email protected]`).
|
||||
## Usage
|
||||
|
||||
```sh
|
||||
raea playable GAME.tsx -o DIR [--networks LIST] [--ios URL] [--android URL] [--title TEXT] [--cta TEXT] [--orientation portrait|landscape|both] (a game as a playable ad: one page or ZIP per network (applovin, unity, google, meta, moloco, mintegral, tiktok, liftoff, preview), each under its 5 MB cap, from the TSX that renders as the video ad)
|
||||
raea playable GAME.tsx -o DIR [--name NAME] [--networks LIST] [--ios URL] [--android URL] [--title TEXT] [--cta TEXT] [--orientation portrait|landscape|both] (a game as a playable ad: one page or ZIP per network (applovin, unity, google, meta, moloco, mintegral, tiktok, liftoff, preview), each under its 5 MB cap, from the TSX that renders as the video ad)
|
||||
```
|
||||
|
||||
Headless: it needs nothing running and opens no window. Takes up to 1 argument besides its flags.
|
||||
|
||||
@@ -135,9 +135,18 @@ Feature: raea games as playable ads, exported for every ad network from the TSX
|
||||
Then raea/tone's instruments and the export's generated foley (TokenSynth, SAO) play through Web Audio from data
|
||||
URLs after input.onFirstTouch, inside the size budget
|
||||
|
||||
@done
|
||||
Scenario: PA8. Fonts inlined
|
||||
Given brick-rush's page asks for Inter, which a phone doesn't have (it fell back to a serif in the first check)
|
||||
Then the export inlines the subset of each font the page uses, as the native render draws it
|
||||
# Status 12-03: built (apps/playable fonts.rs). The native page draws with core/fonts' faces (Fontsource latin
|
||||
# subsets, Inter 400/700/900), each family it names aliased (Helvetica, Arial, SF Pro as Inter, Times as EB
|
||||
# Garamond) and each weight drawn by the nearest face. The export inlines, for the page's default (Inter) and
|
||||
# every family the game's script names that raea aliases, those same faces under that name, each face's weight
|
||||
# a range (Inter 1-550, 551-800, 801-1000) so the browser picks the face core/fonts `face` picks; a test holds
|
||||
# the two picks equal at every weight. Inter adds about 95 KB a page. Checked: brick-rush's weight-900 "Drag to
|
||||
# play" draws the same face and weight in WebKit as in `raea render --frame` (it drew Inter SemiBold, then a
|
||||
# serif, before); parity at frame 90 went from 8.4 to 6.1/255.
|
||||
|
||||
@done @needs:PA1
|
||||
Scenario: PA9. The playable is held to the native render
|
||||
@@ -209,9 +218,16 @@ Feature: raea games as playable ads, exported for every ad network from the TSX
|
||||
And the guide is sdk/guides/craft/motion/playable.md (`raea guide playable`, copied into the skill's motion/), and
|
||||
SKILL.md routes "a playable ad" to it
|
||||
|
||||
@done
|
||||
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); 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.
|
||||
|
||||
Scenario: PA16. Playables in the review (raea cloud and the desktop)
|
||||
Given the review's own player (raea-platform board-simple review.js PLAYER_DRAWS) is the one view of a shown file
|
||||
@@ -241,4 +257,31 @@ Feature: raea games as playable ads, exported for every ad network from the TSX
|
||||
Given bench/live-3d/corpus.sh skips brick-rush: under RAEA_LIVE3D_CHECK it panics on frame 1, because the fast
|
||||
rows (runtime/scene/src/live.rs) carry the sun's rotation and the full rows don't
|
||||
Then the fast and full rows agree on a light's transform, and brick-rush plays live and leaves the corpus's skips
|
||||
# Status 12-03: the cause: the fast path (runtime/scene fast.rs `put`) rounded every column but a placement's
|
||||
# to 6 decimals, a light's rotation quaternion too, while the full rows (parts.rs) write it exact; a sun that
|
||||
# never moved differed on the first fast frame. A rotation and a colour column now go through exact on both.
|
||||
# runtime/scene/tests/live_light.rs panicked before the change and passes after; corpus.sh no longer skips
|
||||
# brick-rush.
|
||||
|
||||
@done
|
||||
Scenario: PA19. A brief that asks for a playable
|
||||
Given a brief's goal was a cut, a shot, a kit, a scene or rules, so a brief asking for a playable planned a cut
|
||||
Then core/brief has a playable goal (playable.rs: the game's TSX, its name, networks, orientation, seconds, and the
|
||||
video ad too when asked) whose deliverables are what `raea playable` writes into out/playable/: each network's
|
||||
page or ZIP, the preview and the export's manifest (NAME.playable.json)
|
||||
And raea goal's playable pack reads that manifest at publish and done: every page under the 5 MB cap, the
|
||||
compositions in the orientations asked for (both unless the brief names one), every network written, and the
|
||||
game unchanged since its export
|
||||
# Status 12-03: built (core/brief playable.rs, sdk/goal packs/playable.ts, `raea playable --name`, the manifest).
|
||||
# The generated declarations split in two to stay under 500 lines a file: brief.gen.ts re-exports
|
||||
# brief-goal.gen.ts. raea cloud's Ideate and brief form write `playable({ playable: {...} })` (raea-platform).
|
||||
|
||||
@done
|
||||
Scenario: PA20. A tap shorter than a frame still reaches the game
|
||||
Given the host handed the game only what was held when a step read the input, so a tap that went down and up
|
||||
between two steps never arrived (instant taps left the attract demo running)
|
||||
Then a press, a finger and a key count as held for the step after they went down, and the next step sees them
|
||||
let go
|
||||
# Status 12-03: #310 (host/input.ts). tools/check.ts plays with TAP_MS (0 is an instant tap, 150 by default);
|
||||
# every playable above was checked both ways.
|
||||
|
||||
+22
-6
@@ -12,8 +12,8 @@ Feature: Videoform: the kind of video a person makes again and again, read once
|
||||
references, its vocabulary, its template and its rules. It's found, inherited, taught and shared as a
|
||||
fingerprint is.
|
||||
2. Each part flows into the part of raea that does that job already: its ranges into its profile (FP6e), its rules
|
||||
into a controller's rule fields (DR4, DR8), its structure into a NAME.script.ts template, its references into
|
||||
brief.ts's `references` shape.
|
||||
into the section's `rules`, each in a taste line's shape (words, a check, its values, a level; DR4, DR8), its
|
||||
structure into a NAME.script.ts template, its references into brief.ts's `references` shape.
|
||||
3. A reference is read once, from the local drive or streamed from a URL, and never needed again: its per-shot rows,
|
||||
its vocabulary's vectors, its ranges, its structure and its rules are all that following and checking read.
|
||||
4. What stays the same across the references is the videoform; what varies is content. A rule's strength is its
|
||||
@@ -23,13 +23,26 @@ Feature: Videoform: the kind of video a person makes again and again, read once
|
||||
6. Checks start from the composition: a videoform's rules run in `raea check PROJECT` before any render, and
|
||||
embeddings only for shots that changed.
|
||||
|
||||
Start here (the order of work, and where it touches what exists):
|
||||
- The order: VF1 and VF2 (a reference in, a videoform made), VF3 (each reference read once into the kept rows), then
|
||||
VF4 with VF12 (the ranges, judged on the test bench). That pair is the gate: it passes on at least five of the
|
||||
person's sets before VF1b's platform pages or anything in VF9-VF11 is built.
|
||||
- New crates hold the work: raea-app-videoform (apps/videoform: ingest, rights, reading, the verbs, the bench),
|
||||
raea-sys-videoform (systems/videoform: the maths over kept rows) and raea-io-resolve (io/resolve, VF1b). The
|
||||
videoform section's types are core/brief's videoform.rs.
|
||||
- Three small hooks into what exists: fingerprint.ts's optional `videoform` field (systems/fingerprint taxonomy.rs,
|
||||
VF2), `raea context` printing a project's videoform (engine/cli guide.rs, VF2), and `raea check PROJECT` holding
|
||||
the rules of the fingerprint that judges the piece (apps/direction check.rs, VF8).
|
||||
- The bench (VF12) runs after every step, on every set, from the kept files alone; its numbers are the progress.
|
||||
|
||||
Background:
|
||||
Given the readers raea has: footage perception (systems/footage), Fingerprint's columns (systems/columns: SigLIP 2,
|
||||
CLAP, YAMNet, cached by content hash), Parakeet's words, Beat This!, HTDemucs and Silero VAD (systems/song), OCR,
|
||||
Depth Anything 3, and raea check's one decode of the picture (raea-app-check-read once.rs)
|
||||
And Fingerprint's fingerprint.ts (`about`, `extends`, `applies`, axes, encoder pins), its profiles (FP6e: ranges by
|
||||
measure name, critique, leave-one-out), `which` (FP14c) and evidence rows (FP2c)
|
||||
And controllers' `rule` fields and raea/check's `.ts` checks over the world (DR4), run by `raea check PROJECT`
|
||||
And taste lines' checks (raea's six forms, a check by name, a `.ts` check written with raea/check over the world;
|
||||
DR4), run by `raea check PROJECT`
|
||||
And the crate limits (a file at most 500 lines, a crate at most 2,000): raea-sys-fingerprint, -fingerprint-use and
|
||||
raea-app-fingerprint are each within 150 lines of theirs, so a videoform's code is its own crates, and the
|
||||
fingerprint crates grow only by a field and a map
|
||||
@@ -149,12 +162,15 @@ Feature: Videoform: the kind of video a person makes again and again, read once
|
||||
And the template is a NAME.script.ts a project made to the videoform starts from, checked by `raea spec`
|
||||
|
||||
@needs:VF6,VF7
|
||||
Scenario: VF8. Rules, with their strength, into a controller
|
||||
Scenario: VF8. Rules, with their strength, in the videoform's rules
|
||||
Given the plan
|
||||
| crate | file | lines | job |
|
||||
| raea-sys-videoform | systems/videoform/src/rules.rs | 240 | coverage, order and event rules from the kept rows, each with how strongly it holds; written as rule fields of the controller `videoform.rules` names |
|
||||
| raea-sys-videoform | systems/videoform/src/rules.rs | 240 | coverage, order and event rules from the kept rows, each with how strongly it holds; written into the section's `rules`, each a taste line with its check and values |
|
||||
| raea-app-direction | apps/direction/src/check.rs | 15 | tastes(): the rules of the fingerprint `which` names for the project, after the person's, the workspace's and the project's taste |
|
||||
Then a rule that holds in most references (a punch-in when a number is said; a close-up of the counters in every
|
||||
kitchen) is a rule field with its strength and its check
|
||||
kitchen) is a line in the section's `rules`, with its strength and its check
|
||||
And `raea check PROJECT` holds a piece to the rules of the fingerprint that judges it (raea-sys-fingerprint-use
|
||||
`which`), beside the person's, the workspace's and the project's taste
|
||||
And the person confirms the strongest rules once, on a contact sheet of shot-kind stills, and each answer is
|
||||
evidence in the videoform
|
||||
|
||||
|
||||
+7
-8
@@ -49,11 +49,10 @@ not only what was corrected. Notes still matter. They teach what the numbers can
|
||||
| Fingerprint: `fingerprint.ts` with `about`, `extends`, `applies` kinds and tags; `which` finds one by project, workspace and account; a child inherits its parent's evidence, its own counted more; notes teach the one that judged (FP14a-e) | the home: a videoform is one of these | the fields a kind of video needs |
|
||||
| Fingerprint's frozen encoders (SigLIP 2, CLAP, YAMNet, EmbeddingGemma 2, Depth Anything 3), columns cached by content hash, word and learned heads, evidence in f16 rows (FP1-FP4) | the per-shot vectors and measures, and where they're kept | no shot vocabulary, no structure |
|
||||
| Fingerprint profiles: ranges from admired work, critique against them, a leave-one-out test (FP6e, `raea fingerprint profile`) | a videoform's ranges, and its validation | few measures (loudness, tilt, cut rate, motion, light, colour, sharpness) |
|
||||
| Controllers' `rule` fields, a check by name or a `.ts` check on raea/check's world (DR4) | rules that `raea check PROJECT` and every agent hold work to | none written from references |
|
||||
| Notes become checks, and climb to project, workspace and taste (DR5-DR8, `raea notes keep`) | the path a correction takes to becoming a rule | a videoform's rules start from evidence, not notes |
|
||||
| `raea check`: findings and the record (DR3); who can fix what, carried findings, one decode (raea-app-check-cause, PR #205) | the check every pass runs | a videoform's rules join it as more rules |
|
||||
| `NAME.script.ts` (scenes, beats, lines, cut); `brief.ts` (`references`, `look`, `mode`, `deliver`) | a storyboard spec, and a brief that names references | no template made from references; references named, never read |
|
||||
| `taste.ts`, six checked forms | the person's standing lines | the forms are fixed: mined rules go to controllers, not here |
|
||||
| `taste.ts` lines: words, and a check that holds them (one of six forms, a check by name, or a `.ts` check on raea/check's world; DR4) | the person's, the workspace's and the project's standing lines, which `raea check PROJECT` and every agent hold work to | none written from references |
|
||||
| Footage perception (`systems/footage`: shots, cuts, camera, faces, words on screen, scene labels, performance, facts.json) | what each reference shot is | read for raw footage, not for references |
|
||||
| Transcription (Parakeet), beats, stems and voice activity (`raea song`, HTDemucs, Silero VAD), OCR | words, pauses, cuts against beats, music under voice, captions | not gathered into a videoform |
|
||||
| Index and libraries (SigLIP over a person's media; turbopuffer in the cloud) | finding footage by meaning; vector storage for teams | — |
|
||||
@@ -83,7 +82,7 @@ Each part of a videoform flows into the part of raea that already does that job:
|
||||
|---|---|---|
|
||||
| ranges (pace, pauses, shot lengths, loudness, colour, captions) | its own profile (FP6e) | `raea fingerprint score --profile` critiques a cut against them, and leave-one-out is already built |
|
||||
| the taste taught later | its own evidence and heads (FP2, FP14b-d) | a note on a piece it judged teaches it, never the person's general fingerprint unless they move it up |
|
||||
| rules (coverage, order, event rules, limits) | a controller's `rule` fields, which `videoform.rules` names | `raea check PROJECT` runs them, and they're edited in the app like any controller |
|
||||
| rules (coverage, order, event rules, limits) | the section's `rules`, each in a taste line's shape (words, check, values, level) | `raea check PROJECT` runs them for a piece the videoform judges (`which`), beside the taste |
|
||||
| structure (slots, their order and lengths) | a `NAME.script.ts` template, which `videoform.template` names | a project made to the videoform starts from it, and agents plan from it as from any storyboard |
|
||||
| references | `brief.ts`'s existing `references` shape, `{ target, note }`, with the source kept by content hash | a reference is named the way a brief already names one |
|
||||
|
||||
@@ -161,7 +160,7 @@ Following and checking need four kinds of thing from the references, and a video
|
||||
| per-shot rows | each reference shot's SigLIP 2 vector (one pooled vector, a few frames averaged), its CLAP vector over the shot's sound, and its measures (length, scale, camera move, caption boxes, light and colour, words, pauses at its edges, its place in the video) | the shot vocabulary; matching new footage to shot kinds; the embedding checks |
|
||||
| the vocabulary's vectors | each term's phrasings through the text towers, as word heads store them (FP2e) | naming shot kinds; finding domain things in new footage |
|
||||
| the profile | the ranges of every measure across the references (FP6e) | the critique, and composition-first range checks |
|
||||
| the structure and the rules | the slots with their lengths and shot kinds; the event and coverage rules with their strength | the template, and the controller rules `raea check` runs |
|
||||
| the structure and the rules | the slots with their lengths and shot kinds; the event and coverage rules with their strength | the template, and the rules `raea check` runs |
|
||||
|
||||
Also kept: one small still for each shot kind (a thumbnail, a few kilobytes), so the person can see what a kind is when
|
||||
confirming rules, and the evidence the person adds over time. The reference videos aren't kept.
|
||||
@@ -226,8 +225,8 @@ working as it was. This is the one time a reference is needed again, and it's th
|
||||
(open, sections, close), each with its length range, its shot kinds and what's on screen. This becomes the script
|
||||
template.
|
||||
5. **The event rules.** How often one thing comes with another across the references ("a punch-in when a number is
|
||||
said", "a close-up of the counters in every kitchen"). Those that hold in most references become controller rules,
|
||||
each stating how strongly it holds.
|
||||
said", "a close-up of the counters in every kitchen"). Those that hold in most references become the videoform's
|
||||
rules, each stating how strongly it holds.
|
||||
6. **The person confirms the strongest rules once,** on a contact sheet ("countertop close-up in every kitchen: 9 of
|
||||
10"). Each yes or no is evidence in the videoform, as any label is in a fingerprint.
|
||||
|
||||
@@ -247,7 +246,7 @@ working as it was. This is the one time a reference is needed again, and it's th
|
||||
- shot lengths and pauses (the voice's cut points are in the composition);
|
||||
- caption places and sizes.
|
||||
|
||||
These are the controller rules, run by `raea check PROJECT` as today.
|
||||
These are the videoform's rules, run by `raea check PROJECT` with the taste.
|
||||
2. **On the render manifest and measures, in seconds:** loudness, light and colour against the profile (`raea
|
||||
fingerprint score --profile`).
|
||||
3. **On embeddings, only for shots that changed:** each shot against its slot's shot kind (one SigLIP frame a shot);
|
||||
@@ -298,7 +297,7 @@ The sets, their answers and their verdicts are kept as fixtures, so each step of
|
||||
| | VF5 | the vocabulary loop with the person's AI, as word heads | medium-high | word heads already score from text; the report is new |
|
||||
| | VF6 | the shot vocabulary (clusters named from the vocabulary) | medium | clustering is plain; naming quality varies by domain |
|
||||
| | VF7 | the structure template | medium | alignment across varied videos is the hard part |
|
||||
| | VF8 | event rules into controller rules, with strength, confirmed by the person | medium | co-occurrence is plain; telling habit from style needs the person |
|
||||
| | VF8 | event rules into the videoform's rules, with strength, confirmed by the person; `raea check` holds them | medium | co-occurrence is plain; telling habit from style needs the person |
|
||||
| | VF8b | when it doesn't hold together: too few, mixed kinds (split into videoforms), traits that vary, outliers | medium-high | groups and spreads come from the kept rows |
|
||||
| | VF8c | adding and removing references from kept rows; encoder pins and `refresh` | high | Fingerprint keeps evidence across upgrades the same way (FP8c) |
|
||||
| 3, use | VF9 | following: context, coverage gaps, planning to the template | medium-high | context and scripts exist |
|
||||
|
||||
@@ -87,8 +87,10 @@ impl LiveScene {
|
||||
let mut want: [(&str, Option<f64>); WANT] = [("", None); WANT];
|
||||
let mut nw = 0usize;
|
||||
let mut put = |k: &'static str, v: f64| {
|
||||
// a Transform's columns as the World's f32 holds them (FC1d), the rest to 6 decimals
|
||||
want[nw] = (k, Some(if PLACE.contains(&k) || k.starts_with("col_") { v } else { r6(v) }));
|
||||
// a Transform's columns as the World's f32 holds them (FC1d), and a light's own rotation exact as parts.rs
|
||||
// writes it (rot_q*: rounded here, a still sun was sent again on the first fast frame, PA18); the rest
|
||||
// to 6 decimals
|
||||
want[nw] = (k, Some(if PLACE.contains(&k) || k.starts_with("col_") || k.starts_with("rot_q") { v } else { r6(v) }));
|
||||
nw += 1;
|
||||
};
|
||||
let mut color: Option<std::borrow::Cow<str>> = None;
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
//! A sun placed by its own rotation (a Bevy Transform's, as brick-rush's `Transform.fromXyz(2, 8, 6).lookingAt(...)`)
|
||||
//! keeps that rotation exact on live play's fast rows as on the full rows (docs/playables.feature PA18): the fast path
|
||||
//! rounded it to 6 decimals, so a sun that never moved was sent again on the first fast frame, and RAEA_LIVE3D_CHECK
|
||||
//! panicked there.
|
||||
use raea_core_scene::Node3;
|
||||
use raea_runtime_scene::{LiveScene, Shot};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// A part as a frame's scene hands it on: its kind, props, shape and children
|
||||
fn part(kind: &str, props: Value, shape: Option<&str>, kids: Vec<Node3>) -> Node3 {
|
||||
let props = std::sync::Arc::new(props.as_object().cloned().unwrap_or_default());
|
||||
Node3 {
|
||||
kind: kind.into(),
|
||||
props,
|
||||
shape: shape.map(Into::into),
|
||||
at: None,
|
||||
kids: kids.into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn scene(q: [f64; 4]) -> Vec<Node3> {
|
||||
let sun = json!({ "position": [2, 8, 6], "rotation": q, "illuminance": 9600, "shadow_maps_enabled": true });
|
||||
let paint = part(
|
||||
"MeshStandardMaterial",
|
||||
json!({ "color": "#ff6a3d" }),
|
||||
None,
|
||||
vec![],
|
||||
);
|
||||
vec![
|
||||
part("DirectionalLight", sun, None, vec![]),
|
||||
part(
|
||||
"Mesh",
|
||||
json!({ "name": "brick" }),
|
||||
Some("box(1,0.4,0.5)"),
|
||||
vec![paint],
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sun_placed_by_its_rotation_is_the_same_on_both_paths() {
|
||||
// SAFETY: the only test in this binary, set before anything reads the environment
|
||||
unsafe { std::env::set_var("RAEA_LIVE3D_CHECK", "1") };
|
||||
// looking from (2, 8, 6) at the origin: digits past the sixth decimal
|
||||
let q = [
|
||||
-0.42470818758010864,
|
||||
0.33985114097595215,
|
||||
0.17591990530490875,
|
||||
0.8204732537269592,
|
||||
];
|
||||
let mut ls = LiveScene::default();
|
||||
let s = scene(q);
|
||||
ls.open(
|
||||
Shot {
|
||||
scene: &s,
|
||||
clear: None,
|
||||
},
|
||||
64,
|
||||
64,
|
||||
30.0,
|
||||
);
|
||||
for f in 0..3 {
|
||||
let (set, gone) = ls.frame(Shot {
|
||||
scene: &s,
|
||||
clear: None,
|
||||
});
|
||||
assert!(gone.is_empty(), "frame {f}: nothing dropped: {gone:?}");
|
||||
assert!(
|
||||
set.iter()
|
||||
.all(|t| !t.vals.keys().any(|k| k.starts_with("rot_q"))),
|
||||
"frame {f}: a still sun is never sent again: {set:?}"
|
||||
);
|
||||
}
|
||||
// a sun that turns sends the part of its rotation that changed, exact
|
||||
let q2 = [
|
||||
-0.42470818758010864,
|
||||
0.3398512,
|
||||
0.17591990530490875,
|
||||
0.8204732537269592,
|
||||
];
|
||||
let s2 = scene(q2);
|
||||
let (set, _) = ls.frame(Shot {
|
||||
scene: &s2,
|
||||
clear: None,
|
||||
});
|
||||
let sun = set
|
||||
.iter()
|
||||
.find(|t| t.vals.contains_key("rot_qy"))
|
||||
.expect("the turned sun's rotation is sent");
|
||||
assert_eq!(
|
||||
sun.vals.get("rot_qy"),
|
||||
Some(&raea_core_program::ir::V::N(q2[1]))
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
# raea cloud's library proxies on Modal (index-run.ts, 12-02): a video's 540p copy, made once per version of the file and
|
||||
# kept in R2 by its source's SHA-256. Its own app, beside raea-ingest's indexer, so it deploys without the indexer's
|
||||
# bundle. From sdk/cloud:
|
||||
#
|
||||
# MODAL_PROFILE=raea modal deploy deploy/modal/proxy.py
|
||||
#
|
||||
# POST /v1/proxy-jobs {url, put, ticket} a job: the file fetched from url, its proxy written through the Worker's
|
||||
# put (/u/<prefix>/) with ticket (exp=&sig=) -> {id}
|
||||
# GET /v1/proxy-jobs/ID {state: running} | {state: done, sha256, proxy, bytes...} | {state: failed, error}
|
||||
# GET /healthz
|
||||
#
|
||||
# Every call but /healthz carries Authorization: Bearer RAEA_INGEST_TOKEN (Modal secret raea-ingest, as raea-ingest's).
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
import modal
|
||||
|
||||
app = modal.App("raea-proxy", image=modal.Image.debian_slim(python_version="3.12").apt_install("ffmpeg").pip_install("fastapi[standard]"))
|
||||
secret = modal.Secret.from_name("raea-ingest")
|
||||
|
||||
|
||||
@app.function(cpu=1, memory=1024, secrets=[secret], timeout=300, scaledown_window=120)
|
||||
@modal.concurrent(max_inputs=16)
|
||||
@modal.asgi_app()
|
||||
def api():
|
||||
from fastapi import FastAPI, HTTPException, Request
|
||||
from fastapi.responses import PlainTextResponse
|
||||
|
||||
web = FastAPI()
|
||||
token = os.environ["RAEA_INGEST_TOKEN"]
|
||||
|
||||
def check(req: Request):
|
||||
if req.headers.get("authorization", "").removeprefix("Bearer ") != token:
|
||||
raise HTTPException(401, "a raea ingest token is needed (Authorization: Bearer)")
|
||||
|
||||
@web.post("/v1/proxy-jobs")
|
||||
async def submit(req: Request):
|
||||
check(req)
|
||||
b = await req.json()
|
||||
if not isinstance(b.get("url"), str) or not b["url"].startswith("https://"):
|
||||
raise HTTPException(400, "url is the file's https address")
|
||||
if not isinstance(b.get("put"), str) or not b["put"].startswith("https://") or not b["put"].endswith("/") or not isinstance(b.get("ticket"), str):
|
||||
raise HTTPException(400, "put is the Worker's /u/<prefix>/ and ticket its exp=&sig=")
|
||||
call = await proxy_job.spawn.aio(b["url"], b["put"], b["ticket"])
|
||||
return {"id": call.object_id}
|
||||
|
||||
@web.get("/v1/proxy-jobs/{job}")
|
||||
async def collect(job: str, req: Request):
|
||||
check(req)
|
||||
try:
|
||||
out = await modal.FunctionCall.from_id(job).get.aio(timeout=0)
|
||||
except modal.exception.FunctionTimeoutError:
|
||||
return {"state": "failed", "error": "the file took over an hour"}
|
||||
except (TimeoutError, modal.exception.TimeoutError):
|
||||
return {"state": "running"}
|
||||
except Exception as e:
|
||||
return {"state": "failed", "error": str(e)[:300]}
|
||||
return {"state": "failed", **out} if out.get("error") else {"state": "done", **out}
|
||||
|
||||
@web.get("/healthz")
|
||||
def healthz():
|
||||
return PlainTextResponse("ok")
|
||||
|
||||
return web
|
||||
|
||||
|
||||
# ---- the proxy ----
|
||||
# What people watch and agents look, search and rough-cut from: 540 lines on the short side (never larger than the
|
||||
# original), H.264 CRF 28 veryfast, a keyframe every second so a seek lands anywhere, AAC 96 kbps stereo, faststart. On
|
||||
# one StreetTalk take (4K HEVC, 254 s, 726 MB) it was 45 MB. Written into R2 by its source's SHA-256 through the
|
||||
# Worker's /u/<prefix>/<file id> with a ticket (files.ts putTicket): the job holds no raea credential, and footage kept
|
||||
# twice is made once. A video already that light (H.264 in MP4, 540 lines or fewer, under 2.5 Mbps) is its own proxy.
|
||||
PROXY_SHORT = 540
|
||||
PROXY_LIGHT_BPS = 2_500_000
|
||||
PART = 64 << 20
|
||||
AGENT = {"user-agent": "raea-ingest/1"}
|
||||
|
||||
|
||||
def _probe(path: str) -> dict:
|
||||
import json
|
||||
|
||||
r = subprocess.run(["ffprobe", "-v", "error", "-show_streams", "-show_format", "-of", "json", path], capture_output=True, text=True, timeout=120)
|
||||
try:
|
||||
return json.loads(r.stdout or "{}")
|
||||
except ValueError:
|
||||
return {}
|
||||
|
||||
|
||||
def _picture(info: dict):
|
||||
"""(width, height as shown, codec) of its first video stream, or None"""
|
||||
v = next((s for s in info.get("streams", []) if s.get("codec_type") == "video" and s.get("disposition", {}).get("attached_pic") != 1), None)
|
||||
if not v:
|
||||
return None
|
||||
w, h = int(v.get("width") or 0), int(v.get("height") or 0)
|
||||
rot = 0
|
||||
for sd in v.get("side_data_list", []) or []:
|
||||
if "rotation" in sd:
|
||||
rot = int(float(sd["rotation"]))
|
||||
rot = rot or int(float((v.get("tags") or {}).get("rotate", 0) or 0))
|
||||
if abs(rot) % 180 == 90:
|
||||
w, h = h, w
|
||||
return w, h, v.get("codec_name", "")
|
||||
|
||||
|
||||
def _http(method: str, url: str, body=None, json_body=None, timeout=600) -> dict:
|
||||
import json
|
||||
import urllib.request
|
||||
|
||||
headers = dict(AGENT)
|
||||
data = body
|
||||
if json_body is not None:
|
||||
data = json.dumps(json_body).encode()
|
||||
headers["content-type"] = "application/json"
|
||||
if data is not None:
|
||||
headers["content-length"] = str(len(data))
|
||||
with urllib.request.urlopen(urllib.request.Request(url, data=data, method=method, headers=headers), timeout=timeout) as r:
|
||||
return json.loads(r.read() or b"{}")
|
||||
|
||||
|
||||
@app.function(cpu=8, memory=8192, secrets=[secret], timeout=3600, max_containers=12, scaledown_window=60)
|
||||
def proxy_job(url: str, put: str, ticket: str) -> dict:
|
||||
import hashlib
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
src, out = os.path.join(d, "in.media"), os.path.join(d, "proxy.mp4")
|
||||
h, got = hashlib.sha256(), 0
|
||||
try:
|
||||
with urllib.request.urlopen(urllib.request.Request(url, headers=AGENT), timeout=300) as r, open(src, "wb") as f:
|
||||
while chunk := r.read(8 << 20):
|
||||
h.update(chunk)
|
||||
got += len(chunk)
|
||||
f.write(chunk)
|
||||
except urllib.error.HTTPError as e:
|
||||
return {"error": f"couldn't fetch the file: {e.code}", "fetched": e.code}
|
||||
except Exception as e:
|
||||
return {"error": f"couldn't fetch the file: {e}"[:300]}
|
||||
sha = h.hexdigest()
|
||||
info = _probe(src)
|
||||
pic = _picture(info)
|
||||
fmt = info.get("format", {})
|
||||
bps = int(float(fmt.get("bit_rate") or 0)) or (int(got * 8 / float(fmt["duration"])) if float(fmt.get("duration") or 0) > 0 else 0)
|
||||
base = {"sha256": sha, "source_bytes": got, "seconds": round(float(fmt.get("duration") or 0), 2)}
|
||||
if not pic:
|
||||
return {**base, "proxy": None, "why": "no picture in it"}
|
||||
w, hgt, codec = pic
|
||||
if min(w, hgt) <= PROXY_SHORT and codec == "h264" and "mp4" in fmt.get("format_name", "") and 0 < bps <= PROXY_LIGHT_BPS:
|
||||
return {**base, "proxy": None, "why": "light enough to be its own", "width": w, "height": hgt}
|
||||
fid = f"file-{sha[:24]}"
|
||||
at = f"{put}{fid}?{ticket}"
|
||||
try:
|
||||
began = _http("POST", f"{at}&step=begin", json_body={})
|
||||
except urllib.error.HTTPError as e:
|
||||
return {"error": f"the Worker refused the proxy's upload: {e.code}"}
|
||||
if began.get("have"):
|
||||
return {**base, "proxy": fid, "kept": True}
|
||||
scale = f"scale='if(gt(iw,ih),-2,trunc(min({PROXY_SHORT},iw)/2)*2)':'if(gt(iw,ih),trunc(min({PROXY_SHORT},ih)/2)*2,-2)',format=yuv420p"
|
||||
r = subprocess.run(
|
||||
["ffmpeg", "-v", "error", "-y", "-i", src, "-map", "0:v:0", "-map", "0:a:0?", "-vf", scale, "-c:v", "libx264", "-preset", "veryfast", "-crf", "28",
|
||||
"-force_key_frames", "expr:gte(t,n_forced*1)", "-c:a", "aac", "-b:a", "96k", "-ac", "2", "-movflags", "+faststart", out],
|
||||
capture_output=True, text=True, timeout=3300,
|
||||
)
|
||||
if r.returncode != 0 or not os.path.exists(out):
|
||||
return {"error": f"ffmpeg stopped ({r.returncode}): {(r.stderr or '')[-300:]}"}
|
||||
size, parts = os.path.getsize(out), []
|
||||
with open(out, "rb") as f:
|
||||
n = 1
|
||||
while chunk := f.read(PART):
|
||||
parts.append(_http("PUT", f"{at}&upload={began['upload']}&part={n}", body=chunk))
|
||||
n += 1
|
||||
done = _http("POST", f"{at}&step=complete&upload={began['upload']}", json_body={"parts": parts})
|
||||
pw = _picture(_probe(out))
|
||||
return {**base, "proxy": done.get("id", fid), "bytes": size, "width": pw[0] if pw else None, "height": pw[1] if pw else None}
|
||||
|
||||
|
||||
@@ -21,6 +21,12 @@ say packages
|
||||
sudo -E apt-get update -qq
|
||||
sudo -E apt-get install -y -qq --no-install-recommends ca-certificates curl git git-lfs zstd xz-utils procps ripgrep \
|
||||
libasound2t64 libfontconfig1 libvulkan1 mesa-vulkan-drivers vulkan-tools > /dev/null
|
||||
# what every agent reached for and installed itself at each project's start (12-02: `which ffmpeg`, a search of the
|
||||
# disk, then apt, minutes in all): ffmpeg and ffprobe (the montage check reads frames with them too) and the PDF tools a
|
||||
# brief or brand guide is read with
|
||||
for f in ffmpeg poppler-utils; do
|
||||
dpkg -s "$f" > /dev/null 2>&1 || sudo -E apt-get install -y -qq --no-install-recommends "$f" > /dev/null 2>&1 || say "no $f here"
|
||||
done
|
||||
# faces an ad is set in (12-01: a box had Liberation and DejaVu alone, so every cut fell back to Liberation Sans): the
|
||||
# open families brands are closest to, each taken when this Ubuntu has it
|
||||
for f in fonts-inter fonts-roboto fonts-open-sans fonts-lato fonts-montserrat fonts-noto-core fonts-ibm-plex fonts-bebas-neue fonts-urw-base35 fonts-liberation2; do
|
||||
|
||||
+15
-10
@@ -35,7 +35,7 @@
|
||||
// can't set headers). The agent and raea get the container's environment without the token or the state keys.
|
||||
|
||||
import { claudeStopHook, jobsOf, markedEnd, sessionIn, watchEnd, watchTurnEnd } from "./turn-end.ts"
|
||||
import { execFileSync, spawn } from "node:child_process"
|
||||
import { execFile, spawn } from "node:child_process"
|
||||
import { timingSafeEqual } from "node:crypto"
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, symlinkSync, writeFileSync } from "node:fs"
|
||||
import { createServer, type IncomingMessage, type ServerResponse } from "node:http"
|
||||
@@ -144,14 +144,16 @@ const withoutKeys = (env: NodeJS.ProcessEnv) => {
|
||||
for (const k of [...AGENT_KEYS, "GOOGLE_API_KEY", "GOOGLE_APPLICATION_CREDENTIALS"]) delete out[k]
|
||||
return out
|
||||
}
|
||||
const raeaVersion = () => {
|
||||
try {
|
||||
version ??= execFileSync(RAEA, ["--version"], { encoding: "utf8", timeout: 20_000, env: childEnv() }).trim()
|
||||
} catch {
|
||||
version = "unknown"
|
||||
}
|
||||
return version
|
||||
}
|
||||
/** raea's version, asked once as the server starts and never on a request: asked synchronously, on a Sprite whose
|
||||
* disk was cold it held every request (health included) for 6 s, and up to its 20 s timeout after the restarts on
|
||||
* 12-02, which also left it "unknown" for good. "reading" until it answers */
|
||||
const raeaVersion = () => version ?? "reading"
|
||||
const versionKnown = new Promise<void>((resolve) =>
|
||||
execFile(RAEA, ["--version"], { encoding: "utf8", timeout: 120_000, env: childEnv() }, (e, out) => {
|
||||
version = e ? "unknown" : out.trim()
|
||||
resolve()
|
||||
}),
|
||||
)
|
||||
|
||||
function authorized(req: IncomingMessage, url: URL): boolean {
|
||||
const given = /^Bearer (.+)$/.exec(req.headers.authorization ?? "")?.[1] ?? url.searchParams.get("token") ?? ""
|
||||
@@ -252,6 +254,8 @@ const server = createServer(async (req, res) => {
|
||||
if (!authorized(req, url)) return json(res, { error: "unauthorized" }, 401)
|
||||
try {
|
||||
if (url.pathname === "/v1/health" && req.method === "GET") {
|
||||
// a moment for raea's version on a fresh start, without holding anything else up
|
||||
if (version === undefined) await Promise.race([versionKnown, new Promise((r) => setTimeout(r, 3000))])
|
||||
const def = (() => {
|
||||
try {
|
||||
return spawnFor().id
|
||||
@@ -467,7 +471,8 @@ if (existsSync("/proc/meminfo") && process.env.RAEA_CLOUD_MEMGUARD !== "0")
|
||||
process.stderr.write(line + "\n")
|
||||
for (const ws of agentSockets) if (ws.readyState === ws.OPEN) ws.send(JSON.stringify({ jsonrpc: "2.0", method: "_raea/stderr", params: { text: line + "\n" } }))
|
||||
})
|
||||
server.listen(PORT, () => {
|
||||
server.listen(PORT, async () => {
|
||||
await versionKnown
|
||||
const d = device(childEnv())
|
||||
const gpu = process.env.RAEA_CLOUD_GPU_URL
|
||||
console.log(
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// A goal (docs/goal.feature): one step of the work, `goal` on brief.ts, one or several in order (a workflow inline, or
|
||||
// a workflow() module the brief imports). cut, shot, kit, scene and rules are presets of it, each turning its kind's
|
||||
// a workflow() module the brief imports). cut, shot, kit, scene, playable and rules are presets of it, each turning its kind's
|
||||
// packs on; any goal carries `rules` (commands, files, words a critic judges) and an `aim`; `packs` switches any of
|
||||
// raea's by name and `checks` adds the project's own (raea/check `check()`s, imported into brief.ts). `name`, `step`
|
||||
// and `after` place it in a workflow. Pure: brief.ts imports this, and `raea spec` reads brief.ts with no Node.
|
||||
@@ -55,6 +55,7 @@ export const PACKS = {
|
||||
notes: "NOTES.md, with what the skill got wrong",
|
||||
floor: "no clipped text, low contrast, freeze, flash or loudness out of range",
|
||||
stills: "a composition's stills as it's saved: no clipped or cramped text, nothing out of the safe areas",
|
||||
playable: "each network's page under 5 MB, in the orientations asked for, exported since the game last changed",
|
||||
} as const
|
||||
export type PackName = keyof typeof PACKS
|
||||
|
||||
@@ -65,6 +66,7 @@ export const DEFAULTS: Record<GoalKind | "floor", PackName[]> = {
|
||||
scene: ["deliverables", "record", "critic", "notes", "stills"],
|
||||
kit: ["deliverables", "record", "critic", "notes", "stills"],
|
||||
shot: ["deliverables", "record", "critic", "notes", "stills"],
|
||||
playable: ["deliverables", "playable", "stills"],
|
||||
// a project with no `goal`: what any made video is held to, and any composition as it's saved
|
||||
floor: ["frames", "captions", "voice", "reading", "hook", "airgaps", "floor", "seen", "stills"],
|
||||
}
|
||||
@@ -119,6 +121,9 @@ export const kit = (m: Kindless): Contract => ({ kind: "kit", ...m })
|
||||
export const shot = (m: Kindless): Contract => ({ kind: "shot", ...m })
|
||||
/** cuts of footage from a client's brief: the brief as rules (`cut: {...}`) */
|
||||
export const cut = (m: Kindless): Contract => ({ kind: "cut", ...m })
|
||||
/** a game exported as a playable ad: `playable({ aim, playable: { game: "playable.tsx" } })`, both orientations and
|
||||
* every network unless it names them (docs/playables.feature PA19) */
|
||||
export const playable = (m: Kindless): Contract => ({ kind: "playable", ...m })
|
||||
/** any other work, held only to its rules: `rules({ aim: "the person's words", rules: [...] })` */
|
||||
export const rules = (m: Kindless): Contract => ({ kind: "rules", ...m })
|
||||
/** a shared workflow: its steps in order, each a goal (`after` orders them past it) */
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// raea/goal (@raea/goal): the loop's goals (docs/goal.feature): plan, run, check, done, for one goal or a workflow of
|
||||
// them. This entry is pure, as brief.ts imports it: the packs (./packs) and the runner (./run, `raea goal check`) read
|
||||
// files and run programs, and are loaded only by the runner.
|
||||
export { cut, DEFAULTS, goal, goalsOf, kit, momentsOf, nameOf, PACKS, packsOf, rules, scene, shot, unknownPacks, workflow } from "./contract.ts"
|
||||
export { cut, DEFAULTS, goal, goalsOf, kit, momentsOf, nameOf, PACKS, packsOf, playable, rules, scene, shot, unknownPacks, workflow } from "./contract.ts"
|
||||
export type { Contract, Goals, Moment, PackName, Workflow } from "./contract.ts"
|
||||
export { check, found } from "raea/check"
|
||||
export type { Check, Found } from "raea/check"
|
||||
@@ -11,6 +11,7 @@ import { criticPack, deliverablesPack, notesPack, recordPack } from "./job.ts"
|
||||
import { seenPack, surprisePack } from "./look.ts"
|
||||
import naming from "./naming.ts"
|
||||
import place from "./place.ts"
|
||||
import { playablePack } from "./playable.ts"
|
||||
import sizes, { allSizes } from "./sizes.ts"
|
||||
import sound from "./sound.ts"
|
||||
import reading from "./reading.ts"
|
||||
@@ -49,4 +50,5 @@ export const PACK_CHECKS: Record<PackName, Check[]> = {
|
||||
notes: [notesPack],
|
||||
floor: [floorPack],
|
||||
stills: [stillsPack],
|
||||
playable: [playablePack],
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import type { Contract } from "../contract.ts"
|
||||
import type { Job } from "../facts.ts"
|
||||
import { RAEA } from "../media.ts"
|
||||
import { deliverables as cutFiles } from "./cut.ts"
|
||||
import { deliverables as playableFiles } from "./playable.ts"
|
||||
import { unregistered } from "../project.ts"
|
||||
|
||||
export const SKILL_HEADING = "What the skill got wrong"
|
||||
@@ -36,6 +37,8 @@ function byKind(m: Contract): string[] {
|
||||
return (m.shots ?? []).map((s) => `out/shots/${s.name}.png|out/shots/${s.name}.mp4`)
|
||||
case "cut":
|
||||
return m.cut ? cutFiles(m.cut) : []
|
||||
case "playable":
|
||||
return m.playable ? playableFiles(m.playable) : []
|
||||
case "rules":
|
||||
return []
|
||||
}
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
// The playable pack (docs/playables.feature PA19): a playable goal's export, read from the manifest `raea playable`
|
||||
// writes beside its pages (out/playable/NAME.playable.json). Its pages each under the 5 MB cap, its compositions in the
|
||||
// orientations the goal asks for (both unless it says one), exported since the game last changed, and every network
|
||||
// it ships to written. The deliverables are the core/brief playable.rs list, mirrored here as cut.ts mirrors cut.rs.
|
||||
import { existsSync, readFileSync, statSync } from "node:fs"
|
||||
import path from "node:path"
|
||||
import { check, found } from "raea/check"
|
||||
import type { PlayableGoal } from "raea/brief.gen"
|
||||
import type { Contract } from "../contract.ts"
|
||||
import type { Job } from "../facts.ts"
|
||||
|
||||
export const NETWORKS = ["applovin", "unity", "google", "meta", "moloco", "mintegral", "tiktok", "liftoff"] as const
|
||||
const ZIPPED = new Set(["google", "mintegral", "tiktok"])
|
||||
export const OUT = "out/playable"
|
||||
/** every network's cap (apps/playable pages.rs CAP) */
|
||||
export const CAP = 5 * 1024 * 1024
|
||||
|
||||
/** what `raea playable` says it wrote (apps/playable lib.rs Manifest) */
|
||||
export interface PlayableManifest {
|
||||
name: string
|
||||
game: string
|
||||
orientation: "both" | "portrait" | "landscape"
|
||||
kinds: string[]
|
||||
compositions: { id: string; width: number; height: number; fps: number; frames: number }[]
|
||||
pages: { network: string; file: string; bytes: number }[]
|
||||
cap: number
|
||||
}
|
||||
|
||||
/** the name its files land as: its own (`raea playable --name`), else the game's file name */
|
||||
export const nameOf = (p: PlayableGoal) => p.name ?? path.basename(p.game, path.extname(p.game))
|
||||
export const networksOf = (p: PlayableGoal): string[] => NETWORKS.filter((n) => !p.networks?.length || p.networks.includes(n))
|
||||
|
||||
export function deliverables(p: PlayableGoal): string[] {
|
||||
const n = nameOf(p)
|
||||
const out = networksOf(p).map((net) => `${OUT}/${n}-${net}.${ZIPPED.has(net) ? "zip" : "html"}`)
|
||||
out.push(`${OUT}/${n}-preview.html`, `${OUT}/${n}.playable.json`)
|
||||
if (p.video === true) out.push(`out/cuts/${n}_9x16.mp4`)
|
||||
return out
|
||||
}
|
||||
|
||||
/** the playable goal of a job's contract, if it's one */
|
||||
export const playableOf = (c: Contract | null): PlayableGoal | null => (c?.kind === "playable" ? (c.playable ?? null) : null)
|
||||
|
||||
export function readManifest(root: string, p: PlayableGoal): PlayableManifest | string {
|
||||
const rel = `${OUT}/${nameOf(p)}.playable.json`
|
||||
const abs = path.join(root, rel)
|
||||
if (!existsSync(abs)) return `${rel} isn't there: export it with raea playable ${p.game} -o ${OUT}${p.name ? ` --name ${p.name}` : ""}${p.orientation && p.orientation !== "both" ? ` --orientation ${p.orientation}` : ""}`
|
||||
try {
|
||||
return JSON.parse(readFileSync(abs, "utf8")) as PlayableManifest
|
||||
} catch (e) {
|
||||
return `${rel} doesn't read: ${e instanceof Error ? e.message : e}`
|
||||
}
|
||||
}
|
||||
|
||||
export const playablePack = check<Job>({ id: "playable", text: "each network's page under 5 MB, in the orientations asked for, exported since the game last changed", over: "job", at: ["publish", "done"] }, async (j) => {
|
||||
const p = playableOf(j.contract)
|
||||
if (!p) return
|
||||
const m = readManifest(j.root, p)
|
||||
if (typeof m === "string") {
|
||||
found({ says: m, about: [p.game] })
|
||||
return
|
||||
}
|
||||
const want = p.orientation ?? "both"
|
||||
const shapes = new Set(m.compositions.map((c) => (c.height > c.width ? "portrait" : "landscape")))
|
||||
const asked: ("portrait" | "landscape")[] = want === "both" ? ["portrait", "landscape"] : [want]
|
||||
const missing = asked.filter((s) => !shapes.has(s))
|
||||
for (const s of missing)
|
||||
found({ says: `${p.game} registers no ${s} composition (it has ${m.compositions.map((c) => `${c.id} ${c.width}x${c.height}`).join(", ") || "none"})`, about: [p.game], fix: want === "both" ? "register a portrait and a landscape composition of the game, the host plays the one nearest the screen; or say orientation in the brief" : undefined })
|
||||
for (const pg of m.pages.filter((x) => x.bytes > CAP)) found({ says: `${pg.file} is ${Math.round(pg.bytes / 1024)} KB, over the ${CAP / 1024} KB cap`, about: [pg.file] })
|
||||
const written = new Set(m.pages.map((x) => x.network))
|
||||
for (const net of [...networksOf(p), "preview"].filter((n) => !written.has(n))) found({ says: `no ${net} page in the last export`, about: [`${OUT}/${nameOf(p)}-${net}`] })
|
||||
// exported since the game last changed: the manifest newer than the game's TSX
|
||||
const game = path.join(j.root, p.game)
|
||||
const manifest = path.join(j.root, OUT, `${nameOf(p)}.playable.json`)
|
||||
if (existsSync(game) && statSync(game).mtimeMs > statSync(manifest).mtimeMs) found({ says: `${p.game} changed after its last export: export it again`, about: [p.game] })
|
||||
})
|
||||
@@ -0,0 +1,43 @@
|
||||
// The playable goal (docs/playables.feature PA19): its deliverables are each network's page, the preview and the
|
||||
// export's manifest; the playable pack reads the manifest for both orientations, the 5 MB cap and a fresh export.
|
||||
import { expect, test } from "bun:test"
|
||||
import { goalCheck } from "../src/run.ts"
|
||||
import { deliverables } from "../src/packs/playable.ts"
|
||||
import { project, put, touch } from "./project.ts"
|
||||
|
||||
const goal = (playable: object) => ({ kind: "playable", aim: "a runner for a running brand", playable })
|
||||
const comp = (id: string, width: number, height: number) => ({ id, width, height, fps: 30, frames: 900 })
|
||||
const manifest = (compositions: object[], pages: { network: string; bytes: number }[]) =>
|
||||
JSON.stringify({ name: "runner", game: "runner.tsx", orientation: "both", kinds: [], compositions, pages: pages.map((p) => ({ ...p, file: `runner-${p.network}.html` })), cap: 5 * 1024 * 1024 })
|
||||
|
||||
test("its deliverables are each network's page, the preview and the manifest", () => {
|
||||
expect(deliverables({ game: "runner.tsx", networks: ["applovin", "tiktok"], video: true })).toEqual([
|
||||
"out/playable/runner-applovin.html", "out/playable/runner-tiktok.zip", "out/playable/runner-preview.html", "out/playable/runner.playable.json", "out/cuts/runner_9x16.mp4",
|
||||
])
|
||||
})
|
||||
|
||||
test("a game with one orientation, a page over the cap and a stale export are each found", async () => {
|
||||
const d = project(goal({ game: "runner.tsx", networks: ["applovin"] }))
|
||||
put(d, "out/playable/runner.playable.json", manifest([comp("portrait", 1080, 1920)], [{ network: "applovin", bytes: 6 * 1024 * 1024 }, { network: "preview", bytes: 1000 }]))
|
||||
touch(put(d, "runner.tsx", "export {}"), 60)
|
||||
const said = (await goalCheck({ cwd: d, at: "done" })).findings.filter((x) => x.check === "playable").map((x) => x.says)
|
||||
expect(said.some((s) => s.includes("no landscape composition"))).toBe(true)
|
||||
expect(said.some((s) => s.includes("over the 5120 KB cap"))).toBe(true)
|
||||
expect(said.some((s) => s.includes("changed after its last export"))).toBe(true)
|
||||
})
|
||||
|
||||
test("an export in both orientations under the cap passes", async () => {
|
||||
const d = project(goal({ game: "runner.tsx", networks: ["applovin"] }))
|
||||
touch(put(d, "runner.tsx", "export {}"), -60)
|
||||
put(d, "out/playable/runner.playable.json", manifest([comp("portrait", 1080, 1920), comp("landscape", 1920, 1080)], [{ network: "applovin", bytes: 1000 }, { network: "preview", bytes: 1000 }]))
|
||||
const f = (await goalCheck({ cwd: d, at: "done" })).findings
|
||||
expect(f.filter((x) => x.check === "playable")).toEqual([])
|
||||
// the pages themselves still have to be there
|
||||
expect(f.filter((x) => x.check === "deliverables").map((x) => x.says)).toContain("missing: out/playable/runner-applovin.html")
|
||||
})
|
||||
|
||||
test("no export yet says how to make one", async () => {
|
||||
const d = project(goal({ game: "runner.tsx", orientation: "portrait" }))
|
||||
const said = (await goalCheck({ cwd: d, at: "done" })).findings.filter((x) => x.check === "playable").map((x) => x.says)
|
||||
expect(said[0]).toContain("raea playable runner.tsx -o out/playable --orientation portrait")
|
||||
})
|
||||
@@ -0,0 +1,15 @@
|
||||
// What the host asks of whatever draws a playable's 3D (docs/playables.feature PA15): the export bundles a drawer
|
||||
// only when its lint found a 3D kind, so a 2D game's page carries no renderer at all.
|
||||
|
||||
/** One drawer on the stage's canvas, under the page */
|
||||
export interface Draw3d {
|
||||
/** The canvas sized to the composition, drawn at the screen's pixels (`scale` of the composition's) */
|
||||
fit(width: number, height: number, scale: number): void;
|
||||
/** The page's data-3d parts at this frame, read into the drawer's scene; true when there is any 3D to draw */
|
||||
sync(page: HTMLElement, seconds: number): boolean;
|
||||
/** Draws the scene synced last */
|
||||
draw(): void;
|
||||
}
|
||||
|
||||
/** Makes the drawer on the stage's canvas */
|
||||
export type MakeDraw3d = (canvas: HTMLCanvasElement) => Draw3d;
|
||||
@@ -1,5 +1,7 @@
|
||||
// A person's input as raea's FrameInput, in composition px: keys held, the primary pointer and every finger down.
|
||||
// The stage is the composition scaled uniformly into the screen, so each point is mapped back through its box.
|
||||
// A press is kept until a step has read it: the game steps at its fps (33 ms at 30), and a quick tap, or one on a phone
|
||||
// that drops frames, goes down and up between two steps, which a fold reading only what is held would never see.
|
||||
import type { FrameInput } from "raea";
|
||||
|
||||
/** window.addEventListener typed by the event's name (bun's globals type the bare addEventListener loosely) */
|
||||
@@ -11,6 +13,10 @@ export class Input {
|
||||
private keys = new Set<string>();
|
||||
private pointer?: { x: number; y: number; down: boolean };
|
||||
private touches = new Map<number, { x: number; y: number }>();
|
||||
/** pressed since the last step read the input: each finger where it last was, whether the pointer went down, keys */
|
||||
private unread = new Map<number, { x: number; y: number }>();
|
||||
private pressUnread = false;
|
||||
private keysUnread = new Set<string>();
|
||||
/** set on the first touch, click or key: networks keep sound off until then */
|
||||
touched = false;
|
||||
private firstTouch: (() => void)[] = [];
|
||||
@@ -31,11 +37,14 @@ export class Input {
|
||||
const p = at(e);
|
||||
this.pointer = { ...p, down: true };
|
||||
this.touches.set(e.pointerId, p);
|
||||
this.unread.set(e.pointerId, p);
|
||||
this.pressUnread = true;
|
||||
});
|
||||
on("pointermove", (e) => {
|
||||
const p = at(e);
|
||||
if (e.isPrimary) this.pointer = { ...p, down: this.pointer?.down ?? false };
|
||||
if (this.touches.has(e.pointerId)) this.touches.set(e.pointerId, p);
|
||||
if (this.unread.has(e.pointerId)) this.unread.set(e.pointerId, p);
|
||||
});
|
||||
const up = (e: PointerEvent) => {
|
||||
if (e.isPrimary && this.pointer) this.pointer = { ...this.pointer, down: false };
|
||||
@@ -46,6 +55,7 @@ export class Input {
|
||||
on("keydown", (e) => {
|
||||
first();
|
||||
this.keys.add(e.key);
|
||||
this.keysUnread.add(e.key);
|
||||
});
|
||||
on("keyup", (e) => this.keys.delete(e.key));
|
||||
on("blur", () => this.keys.clear());
|
||||
@@ -57,12 +67,19 @@ export class Input {
|
||||
else this.firstTouch.push(f);
|
||||
}
|
||||
|
||||
/** This frame's input, marked live (a person is playing: raea/games' fold reads it so) */
|
||||
/** This step's input, marked live (a person is playing: raea/games' fold reads it so). What went down since the last
|
||||
* step counts as held for this one, even if it is already up: the next step sees it let go. */
|
||||
now(): FrameInput & { live: true } {
|
||||
const keys = new Set([...this.keys, ...this.keysUnread]);
|
||||
const touches = new Map([...this.unread, ...this.touches]);
|
||||
const pointer = this.pointer && { ...this.pointer, down: this.pointer.down || this.pressUnread };
|
||||
this.unread.clear();
|
||||
this.pressUnread = false;
|
||||
this.keysUnread.clear();
|
||||
return {
|
||||
keys: [...this.keys],
|
||||
...(this.pointer ? { pointer: { ...this.pointer } } : {}),
|
||||
...(this.touches.size ? { touches: [...this.touches].map(([id, p]) => ({ id, ...p })) } : {}),
|
||||
keys: [...keys],
|
||||
...(pointer ? { pointer } : {}),
|
||||
...(touches.size ? { touches: [...touches].map(([id, p]) => ({ id, ...p })) } : {}),
|
||||
live: true,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,19 +1,18 @@
|
||||
// The browser host a playable export runs a raea game in (docs/playables.feature PA1): the game's registered
|
||||
// composition (the one nearest the screen's shape, so a portrait and a landscape one can both ship) put on a stage
|
||||
// scaled uniformly into the screen, a Clock stepped 1/fps at a time off requestAnimationFrame with the person's input
|
||||
// recorded per frame, and its 3D drawn by three.js under the page. It starts when the network says the ad is
|
||||
// viewable, pauses while it isn't, and ends on the game's own EndCard or, at the composition's last frame, on one of
|
||||
// its own.
|
||||
// recorded per frame, and its 3D, if it has any, drawn under the page by the drawer the export bundled with it
|
||||
// (draw3d.ts; none for a 2D game, PA15). It starts when the network says the ad is viewable, pauses while it isn't,
|
||||
// and ends on the game's own EndCard or, at the composition's last frame, on one of its own.
|
||||
// The export's entry calls start(): `raea playable` (apps/playable) writes it after the game's import.
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import * as THREE from "three";
|
||||
import { Clock, getCompositions, type InputTimeline, type RegisteredComposition } from "raea";
|
||||
import { EndCard } from "../cards";
|
||||
import { network, onAdEvent, whenReady } from "../network";
|
||||
import type { MakeDraw3d } from "./draw3d";
|
||||
import { Input } from "./input";
|
||||
import { Scene3d } from "./scene";
|
||||
import { UNDER, backgroundUnder3d } from "@raea/r3f/three/page";
|
||||
import { Tonemap } from "./tonemap";
|
||||
|
||||
declare const __RAEA_PLAYABLE__: { title?: string; cta?: string } | undefined;
|
||||
const config = typeof __RAEA_PLAYABLE__ === "object" && __RAEA_PLAYABLE__ ? __RAEA_PLAYABLE__ : {};
|
||||
@@ -26,7 +25,7 @@ function pick(comps: RegisteredComposition[]): RegisteredComposition {
|
||||
|
||||
/** The 3D is drawn under the page, so the page elements holding it are cleared and the innermost solid background
|
||||
* among them becomes the 3D's clear colour, as the native engine shows the page's background behind the 3D. */
|
||||
function boot() {
|
||||
function boot(make3d?: MakeDraw3d) {
|
||||
const comps = getCompositions();
|
||||
if (!comps.length) throw new Error("raea playable: the game registered no composition (registerRoot)");
|
||||
// a still (tools/parity.ts): one composition at one frame, no one playing, as `raea render --frame` draws it
|
||||
@@ -43,12 +42,8 @@ function boot() {
|
||||
stage.append(canvas, page);
|
||||
document.body.append(stage);
|
||||
|
||||
// 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();
|
||||
const d3 = make3d?.(canvas);
|
||||
if (!d3) canvas.style.visibility = "hidden";
|
||||
|
||||
const layout = () => {
|
||||
if (comps.length > 1 && !fixed) comp = pick(comps);
|
||||
@@ -60,11 +55,7 @@ function boot() {
|
||||
top: `${(innerHeight - comp.height * s) / 2}px`,
|
||||
transform: `scale(${s})`,
|
||||
});
|
||||
// the canvas is drawn at the screen's pixels, not the composition's
|
||||
renderer.setPixelRatio(Math.min(2, devicePixelRatio || 1) * s);
|
||||
renderer.setSize(comp.width, comp.height, false);
|
||||
tonemap.resize();
|
||||
scene.fit(comp.width, comp.height);
|
||||
d3?.fit(comp.width, comp.height, s);
|
||||
};
|
||||
layout();
|
||||
addEventListener("resize", layout);
|
||||
@@ -105,12 +96,13 @@ function boot() {
|
||||
</Clock>,
|
||||
),
|
||||
);
|
||||
scene.sync(page, frame / comp.fps);
|
||||
const clear = backgroundUnder3d(page);
|
||||
// the page's own background colour behind the 3D, untouched by the tone curve as natively
|
||||
stage.style.background = clear ?? "#000000";
|
||||
canvas.style.visibility = scene.any ? "visible" : "hidden";
|
||||
if (scene.any) tonemap.render(scene.scene, scene.camera);
|
||||
if (d3) {
|
||||
const any = d3.sync(page, frame / comp.fps);
|
||||
// the page's own background colour behind the 3D, untouched by the tone curve as natively
|
||||
stage.style.background = backgroundUnder3d(page) ?? "#000000";
|
||||
canvas.style.visibility = any ? "visible" : "hidden";
|
||||
if (any) d3.draw();
|
||||
}
|
||||
// a preview build says when its first frame was drawn (tools/check.ts reads it: startup on a slow phone)
|
||||
if (!firstDrawn && network === "preview") console.info(`raea playable: first frame at ${Math.round(performance.now())} ms`);
|
||||
firstDrawn = true;
|
||||
@@ -164,5 +156,8 @@ function boot() {
|
||||
requestAnimationFrame(tick);
|
||||
}
|
||||
|
||||
if (document.readyState === "loading") addEventListener("DOMContentLoaded", boot);
|
||||
else boot();
|
||||
/** Plays the registered game, its 3D drawn by `make3d` (none for a 2D game) */
|
||||
export function start(make3d?: MakeDraw3d) {
|
||||
if (document.readyState === "loading") addEventListener("DOMContentLoaded", () => boot(make3d));
|
||||
else boot(make3d);
|
||||
}
|
||||
@@ -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);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -3,6 +3,8 @@
|
||||
// exceptions and any network request it tried read back, and screenshots saved.
|
||||
// `bun tools/check.ts PAGE.html OUT_DIR [WxH]`; exits 1 on a page error, a request, or a page that never drew.
|
||||
// PLAY_SECONDS=N plays on, then taps the end card (and the check fails if no install event came back).
|
||||
// TAP_MS=N holds each tap N ms (150 by default); TAP_MS=0 presses and lets go at once, as a quick finger and
|
||||
// Playwright's own tap() do, which a host that samples input once a frame must still see (PA20, raea #310).
|
||||
// WebKit, not Chrome: iOS ad WebViews are WebKit, and raea doesn't test in Chrome.
|
||||
import { mkdirSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
@@ -51,13 +53,19 @@ await press("up", W * 0.7, H * 0.75);
|
||||
await shot("1-played");
|
||||
await p.waitForTimeout(2500);
|
||||
await shot("2-later");
|
||||
// a tap in play, then the end card's, each held TAP_MS
|
||||
const hold = Number(process.env.TAP_MS ?? 150);
|
||||
const tap = async (x: number, y: number) => {
|
||||
await press("down", x, y);
|
||||
if (hold > 0) await p.waitForTimeout(hold);
|
||||
await press("up", x, y);
|
||||
};
|
||||
await tap(W / 2, H * 0.6);
|
||||
const more = Number(process.env.PLAY_SECONDS ?? 0);
|
||||
if (more > 0) {
|
||||
await p.waitForTimeout(more * 1000);
|
||||
await shot("3-end");
|
||||
await press("down", W / 2, H / 2);
|
||||
await p.waitForTimeout(150);
|
||||
await press("up", W / 2, H / 2);
|
||||
await tap(W / 2, H / 2);
|
||||
await p.waitForTimeout(300);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,317 @@
|
||||
// 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,
|
||||
/**
|
||||
* how the plan, the report and other goals' `after` name it ([a-z0-9_]); the kind when left out
|
||||
*/
|
||||
name?: string,
|
||||
/**
|
||||
* the workflow step it serves, by the workflow's name for it (`edit`, `deliver`)
|
||||
*/
|
||||
step?: string,
|
||||
/**
|
||||
* the goals that must be done before this one starts, by name
|
||||
*/
|
||||
after?: Array<string>,
|
||||
/**
|
||||
* what the goal is, in the person's words
|
||||
*/
|
||||
aim?: string,
|
||||
/**
|
||||
* what must hold before the agent may stop, beside the kind's packs: each checked in code or by a fresh critic
|
||||
*/
|
||||
rules?: Array<GoalRule>,
|
||||
/**
|
||||
* the pictures the job answers to (paths beside the brief): what is in it and where for a scene, the style for a kit
|
||||
*/
|
||||
references?: Array<string>,
|
||||
/**
|
||||
* one paragraph every reference prompt carries: era, palette, materials, wear, and one fictional maker
|
||||
*/
|
||||
style?: string,
|
||||
/**
|
||||
* by name, from the kind's set (DIALS); one left out is read from the references
|
||||
*/
|
||||
dials?: { [key in string]: GoalDial }, objects?: Array<GoalObject>, shots?: Array<GoalShot>,
|
||||
/**
|
||||
* the compositions the job's checks hold (relative to the brief): each needs a clean render or check newer than it
|
||||
*/
|
||||
compositions?: Array<string>,
|
||||
/**
|
||||
* what must exist when it's done, relative to the brief; replaces the kind's own list (`deliverables`)
|
||||
*/
|
||||
deliverables?: Array<string>,
|
||||
/**
|
||||
* the most critic rounds the job gets; at the cap it is delivered with what's still missing (8 by default)
|
||||
*/
|
||||
rounds?: number,
|
||||
/**
|
||||
* a cut job's contract: the brief as rules (cut.rs)
|
||||
*/
|
||||
cut?: CutGoal,
|
||||
/**
|
||||
* a playable job's game, networks and orientation (playable.rs)
|
||||
*/
|
||||
playable?: PlayableGoal,
|
||||
/**
|
||||
* what the job shows but never delivers, relative to the brief (pictures, render tests, examples): each a file or a
|
||||
* `dir/` (review/ and previews/ when left out). Deliverables are what it hands over; previews are how it got there
|
||||
*/
|
||||
previews?: Array<string>,
|
||||
/**
|
||||
* raea's packs switched by name over the kind's defaults (`{ surprise: true, place: false }`): which of
|
||||
* raea/goal's rules hold this goal (docs/goal.feature)
|
||||
*/
|
||||
packs?: { [key in string]: boolean },
|
||||
/**
|
||||
* the project's own checks (raea/check `check()`, imported into brief.ts), run by `raea goal check`; as data, only
|
||||
* their declarations (id, text, over, at) reach Rust
|
||||
*/
|
||||
checks?: Array<unknown>, };
|
||||
|
||||
export type GoalKind = "scene" | "kit" | "shot" | "cut" | "rules" | "playable";
|
||||
|
||||
export type GoalSource = "customer" | "reference";
|
||||
|
||||
export type GoalDialValue = number | string;
|
||||
|
||||
export type GoalDial = GoalDialValue | { value: GoalDialValue, source?: GoalSource,
|
||||
/**
|
||||
* what the value meant for this job, in one line
|
||||
*/
|
||||
means?: string, };
|
||||
|
||||
export type GoalRoute = "solid" | "rule" | "gen" | "library" | "picture";
|
||||
|
||||
export type GoalOrigin = "reference" | "invented";
|
||||
|
||||
export type GoalPick = {
|
||||
/**
|
||||
* "tripo-h31", "meshy", ...
|
||||
*/
|
||||
generator: string,
|
||||
/**
|
||||
* one line: why this one ("sharper dial numerals; Tripo fused the handset to the cradle")
|
||||
*/
|
||||
why: string, };
|
||||
|
||||
export type GoalObject = {
|
||||
/**
|
||||
* snake_case, unique in the job
|
||||
*/
|
||||
id: string, label: string,
|
||||
/**
|
||||
* real height in metres
|
||||
*/
|
||||
h?: number,
|
||||
/**
|
||||
* [width, depth, height] in metres, for boxy things (generators invent depth)
|
||||
*/
|
||||
dims?: [number, number, number],
|
||||
/**
|
||||
* largest extent in metres, for things that lie flat (tools, papers)
|
||||
*/
|
||||
max?: number, route?: GoalRoute,
|
||||
/**
|
||||
* one object, its condition and its materials; never a real brand
|
||||
*/
|
||||
prompt?: string, source?: GoalOrigin,
|
||||
/**
|
||||
* where it is in reference 0: [x0, y0, x1, y1] in 0..1
|
||||
*/
|
||||
crop?: [number, number, number, number],
|
||||
/**
|
||||
* where it stands in a scene: metres, the floor's front-left corner at the origin, rot 0 = facing the entrance
|
||||
*/
|
||||
at?: [number, number, number], rot?: number, hero?: boolean,
|
||||
/**
|
||||
* how large it is planned to be seen, which is how much of it gets built: 0 the hero (half the frame or more),
|
||||
* 1 featured (under 50%), 2 dressing (under 20%), 3 background (under 8%: a grey box reads), 4 far (under 2%: a
|
||||
* silhouette). A render that shows it finer than this says so (`lod-closer`; `raea scene lod` lists every part)
|
||||
*/
|
||||
lod?: number, pick?: GoalPick,
|
||||
/**
|
||||
* what was fixed by script ("glass made transmissive, label kept opaque")
|
||||
*/
|
||||
fixes?: Array<string>, };
|
||||
|
||||
export type GoalShot = {
|
||||
/**
|
||||
* [a-z0-9_]: the file it lands as (out/shots/<name>.png or .mp4)
|
||||
*/
|
||||
name: string,
|
||||
/**
|
||||
* in a crew's words: "slow push along the counter, rack focus to the register"
|
||||
*/
|
||||
description?: string,
|
||||
/**
|
||||
* static, dolly, truck, pedestal, crane, pan, tilt, orbit, dollyZoom, path
|
||||
*/
|
||||
move?: string, seconds?: number, lens?: number,
|
||||
/**
|
||||
* none, subtle, walk
|
||||
*/
|
||||
handheld?: string,
|
||||
/**
|
||||
* a still rather than a move
|
||||
*/
|
||||
still?: boolean,
|
||||
/**
|
||||
* the composition that renders it (relative to the brief): `raea make shots` draws its framing sheet and lens chart
|
||||
*/
|
||||
composition?: string,
|
||||
/**
|
||||
* its frame rate, for the frames `seconds` spans (30 when left out)
|
||||
*/
|
||||
fps?: number, };
|
||||
|
||||
export type Goals = Goal | Array<Goal>;
|
||||
|
||||
export type CutGoal = {
|
||||
/**
|
||||
* the brief as text, relative to brief.ts (`pdftotext -layout brief.pdf media/brief.txt`): every `from` is found in it
|
||||
*/
|
||||
brief: string,
|
||||
/**
|
||||
* how many cuts the brief asks for; fewer planned is held open until an answered `open` item about "count" says why
|
||||
*/
|
||||
count?: Quoted<number>,
|
||||
/**
|
||||
* a cut's length when its own `seconds` says none: [least, most]
|
||||
*/
|
||||
seconds?: [number, number],
|
||||
/**
|
||||
* the formats every cut is delivered in when its own `formats` says none: "9:16", "16:9", "1:1", "4:5"
|
||||
*/
|
||||
formats?: Array<string>, cuts?: Array<CutPlan>,
|
||||
/**
|
||||
* what is said or shown: in every cut unless `every: false` (then in one or more)
|
||||
*/
|
||||
say?: Array<Phrase>,
|
||||
/**
|
||||
* what no cut says or shows: a banned claim, a word, a name
|
||||
*/
|
||||
never?: Array<Phrase>,
|
||||
/**
|
||||
* the line every cut ends on, heard or on screen in its last `within` seconds
|
||||
*/
|
||||
cta?: Cta,
|
||||
/**
|
||||
* the brief's open items ([TO CONFIRM]): each holds the job open until it has an answer
|
||||
*/
|
||||
open?: Array<CutOpen>,
|
||||
/**
|
||||
* every face whole and every text big enough, by the frames check of each file (true when left out)
|
||||
*/
|
||||
frames?: boolean, };
|
||||
|
||||
export type Quoted<T> = { value: T,
|
||||
/**
|
||||
* the brief's own words, as they are in its text
|
||||
*/
|
||||
from: string, };
|
||||
|
||||
export type CutPlan = {
|
||||
/**
|
||||
* [a-z0-9_], unique: each format lands as out/cuts/<id>_<W>x<H>.mp4 ("a1_s1_9x16.mp4")
|
||||
*/
|
||||
id: string, angle?: string,
|
||||
/**
|
||||
* solo or mashup
|
||||
*/
|
||||
kind?: string,
|
||||
/**
|
||||
* one of the brief's hook types ("Direct Problem", "Reaction")
|
||||
*/
|
||||
hook?: string,
|
||||
/**
|
||||
* captions, hook (a text hook) or none
|
||||
*/
|
||||
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<Beat>, };
|
||||
|
||||
export type Phrase = {
|
||||
/**
|
||||
* as it's said or shown; compared in lower case, by letters and digits ("24/7" and "24-7" are the same)
|
||||
*/
|
||||
text: string, from: string,
|
||||
/**
|
||||
* `say` only: false when one cut saying it is enough
|
||||
*/
|
||||
every?: boolean, };
|
||||
|
||||
export type Cta = { text: string, from: string,
|
||||
/**
|
||||
* the other lines a brief rotates (two host lines, a paid take's): any one lands it, each found in the brief
|
||||
*/
|
||||
also?: Array<string>,
|
||||
/**
|
||||
* how near the end it must land, in seconds (8 when left out)
|
||||
*/
|
||||
within?: number, };
|
||||
|
||||
export type CutOpen = { question: string, from: string,
|
||||
/**
|
||||
* what it decides: "count", "cta", "offer", a cut's id...
|
||||
*/
|
||||
about?: string,
|
||||
/**
|
||||
* the person's answer, as they gave it, and who gave it: until then the job can't be done
|
||||
*/
|
||||
answer?: string, by?: string, };
|
||||
|
||||
export type PlayableGoal = {
|
||||
/**
|
||||
* the game's TSX, relative to the brief: it renders as the video ad and exports as the playable
|
||||
*/
|
||||
game: string,
|
||||
/**
|
||||
* the files' name ([a-z0-9_], `NAME-NETWORK.html`); the game's file name when left out
|
||||
*/
|
||||
name?: string,
|
||||
/**
|
||||
* the networks it ships to (applovin, unity, google, meta, moloco, mintegral, tiktok, liftoff); all of them when
|
||||
* left out. The preview page is always made: it's what the review plays
|
||||
*/
|
||||
networks?: Array<string>,
|
||||
/**
|
||||
* both unless the brief says one: Unity, AppLovin, Moloco and Mintegral want both
|
||||
*/
|
||||
orientation?: PlayableOrientation,
|
||||
/**
|
||||
* [least, most] seconds of play before the end card (15 to 60 by default)
|
||||
*/
|
||||
seconds?: [number, number],
|
||||
/**
|
||||
* the same game rendered as the video ad too, as out/cuts/NAME_9x16.mp4 (PA17)
|
||||
*/
|
||||
video?: boolean, };
|
||||
|
||||
export type PlayableOrientation = "both" | "portrait" | "landscape";
|
||||
|
||||
export type GoalRule = {
|
||||
/**
|
||||
* a short name: [a-z0-9_], how status, the critic and NOTES.md name it
|
||||
*/
|
||||
id: string,
|
||||
/**
|
||||
* a command that must exit 0, run in the brief's folder (`bun test`, `raea check edit.tsx`)
|
||||
*/
|
||||
run?: string,
|
||||
/**
|
||||
* the seconds `run` gets before it counts as failed (300 when left out)
|
||||
*/
|
||||
timeout?: number,
|
||||
/**
|
||||
* a file that must exist, relative to the brief (`a|b`: either; `dir/`: three or more pictures in it)
|
||||
*/
|
||||
file?: string,
|
||||
/**
|
||||
* words that must be true of the work, judged by a fresh critic (`raea goal judge`), never by the agent that did it
|
||||
*/
|
||||
says?: string, };
|
||||
+2
-282
@@ -1,4 +1,6 @@
|
||||
// Generated from raea-core-brief (core/brief) by its `declarations`; edit the Rust, not this.
|
||||
import type { Goals } from "./brief-goal.gen";
|
||||
export type * from "./brief-goal.gen";
|
||||
|
||||
export type Brief = { title: string, logline?: string,
|
||||
/**
|
||||
@@ -203,285 +205,3 @@ material?: string, style?: string,
|
||||
* what a near crop of it must show
|
||||
*/
|
||||
near?: string, };
|
||||
|
||||
export type Goal = { kind: GoalKind,
|
||||
/**
|
||||
* how the plan, the report and other goals' `after` name it ([a-z0-9_]); the kind when left out
|
||||
*/
|
||||
name?: string,
|
||||
/**
|
||||
* the workflow step it serves, by the workflow's name for it (`edit`, `deliver`)
|
||||
*/
|
||||
step?: string,
|
||||
/**
|
||||
* the goals that must be done before this one starts, by name
|
||||
*/
|
||||
after?: Array<string>,
|
||||
/**
|
||||
* what the goal is, in the person's words
|
||||
*/
|
||||
aim?: string,
|
||||
/**
|
||||
* what must hold before the agent may stop, beside the kind's packs: each checked in code or by a fresh critic
|
||||
*/
|
||||
rules?: Array<GoalRule>,
|
||||
/**
|
||||
* the pictures the job answers to (paths beside the brief): what is in it and where for a scene, the style for a kit
|
||||
*/
|
||||
references?: Array<string>,
|
||||
/**
|
||||
* one paragraph every reference prompt carries: era, palette, materials, wear, and one fictional maker
|
||||
*/
|
||||
style?: string,
|
||||
/**
|
||||
* by name, from the kind's set (DIALS); one left out is read from the references
|
||||
*/
|
||||
dials?: { [key in string]: GoalDial }, objects?: Array<GoalObject>, shots?: Array<GoalShot>,
|
||||
/**
|
||||
* the compositions the job's checks hold (relative to the brief): each needs a clean render or check newer than it
|
||||
*/
|
||||
compositions?: Array<string>,
|
||||
/**
|
||||
* what must exist when it's done, relative to the brief; replaces the kind's own list (`deliverables`)
|
||||
*/
|
||||
deliverables?: Array<string>,
|
||||
/**
|
||||
* the most critic rounds the job gets; at the cap it is delivered with what's still missing (8 by default)
|
||||
*/
|
||||
rounds?: number,
|
||||
/**
|
||||
* a cut job's contract: the brief as rules (cut.rs)
|
||||
*/
|
||||
cut?: CutGoal,
|
||||
/**
|
||||
* what the job shows but never delivers, relative to the brief (pictures, render tests, examples): each a file or a
|
||||
* `dir/` (review/ and previews/ when left out). Deliverables are what it hands over; previews are how it got there
|
||||
*/
|
||||
previews?: Array<string>,
|
||||
/**
|
||||
* raea's packs switched by name over the kind's defaults (`{ surprise: true, place: false }`): which of
|
||||
* raea/goal's rules hold this goal (docs/goal.feature)
|
||||
*/
|
||||
packs?: { [key in string]: boolean },
|
||||
/**
|
||||
* the project's own checks (raea/check `check()`, imported into brief.ts), run by `raea goal check`; as data, only
|
||||
* their declarations (id, text, over, at) reach Rust
|
||||
*/
|
||||
checks?: Array<unknown>, };
|
||||
|
||||
export type GoalKind = "scene" | "kit" | "shot" | "cut" | "rules";
|
||||
|
||||
export type GoalSource = "customer" | "reference";
|
||||
|
||||
export type GoalDialValue = number | string;
|
||||
|
||||
export type GoalDial = GoalDialValue | { value: GoalDialValue, source?: GoalSource,
|
||||
/**
|
||||
* what the value meant for this job, in one line
|
||||
*/
|
||||
means?: string, };
|
||||
|
||||
export type GoalRoute = "solid" | "rule" | "gen" | "library" | "picture";
|
||||
|
||||
export type GoalOrigin = "reference" | "invented";
|
||||
|
||||
export type GoalPick = {
|
||||
/**
|
||||
* "tripo-h31", "meshy", ...
|
||||
*/
|
||||
generator: string,
|
||||
/**
|
||||
* one line: why this one ("sharper dial numerals; Tripo fused the handset to the cradle")
|
||||
*/
|
||||
why: string, };
|
||||
|
||||
export type GoalObject = {
|
||||
/**
|
||||
* snake_case, unique in the job
|
||||
*/
|
||||
id: string, label: string,
|
||||
/**
|
||||
* real height in metres
|
||||
*/
|
||||
h?: number,
|
||||
/**
|
||||
* [width, depth, height] in metres, for boxy things (generators invent depth)
|
||||
*/
|
||||
dims?: [number, number, number],
|
||||
/**
|
||||
* largest extent in metres, for things that lie flat (tools, papers)
|
||||
*/
|
||||
max?: number, route?: GoalRoute,
|
||||
/**
|
||||
* one object, its condition and its materials; never a real brand
|
||||
*/
|
||||
prompt?: string, source?: GoalOrigin,
|
||||
/**
|
||||
* where it is in reference 0: [x0, y0, x1, y1] in 0..1
|
||||
*/
|
||||
crop?: [number, number, number, number],
|
||||
/**
|
||||
* where it stands in a scene: metres, the floor's front-left corner at the origin, rot 0 = facing the entrance
|
||||
*/
|
||||
at?: [number, number, number], rot?: number, hero?: boolean,
|
||||
/**
|
||||
* how large it is planned to be seen, which is how much of it gets built: 0 the hero (half the frame or more),
|
||||
* 1 featured (under 50%), 2 dressing (under 20%), 3 background (under 8%: a grey box reads), 4 far (under 2%: a
|
||||
* silhouette). A render that shows it finer than this says so (`lod-closer`; `raea scene lod` lists every part)
|
||||
*/
|
||||
lod?: number, pick?: GoalPick,
|
||||
/**
|
||||
* what was fixed by script ("glass made transmissive, label kept opaque")
|
||||
*/
|
||||
fixes?: Array<string>, };
|
||||
|
||||
export type GoalShot = {
|
||||
/**
|
||||
* [a-z0-9_]: the file it lands as (out/shots/<name>.png or .mp4)
|
||||
*/
|
||||
name: string,
|
||||
/**
|
||||
* in a crew's words: "slow push along the counter, rack focus to the register"
|
||||
*/
|
||||
description?: string,
|
||||
/**
|
||||
* static, dolly, truck, pedestal, crane, pan, tilt, orbit, dollyZoom, path
|
||||
*/
|
||||
move?: string, seconds?: number, lens?: number,
|
||||
/**
|
||||
* none, subtle, walk
|
||||
*/
|
||||
handheld?: string,
|
||||
/**
|
||||
* a still rather than a move
|
||||
*/
|
||||
still?: boolean,
|
||||
/**
|
||||
* the composition that renders it (relative to the brief): `raea make shots` draws its framing sheet and lens chart
|
||||
*/
|
||||
composition?: string,
|
||||
/**
|
||||
* its frame rate, for the frames `seconds` spans (30 when left out)
|
||||
*/
|
||||
fps?: number, };
|
||||
|
||||
export type Goals = Goal | Array<Goal>;
|
||||
|
||||
export type CutGoal = {
|
||||
/**
|
||||
* the brief as text, relative to brief.ts (`pdftotext -layout brief.pdf media/brief.txt`): every `from` is found in it
|
||||
*/
|
||||
brief: string,
|
||||
/**
|
||||
* how many cuts the brief asks for; fewer planned is held open until an answered `open` item about "count" says why
|
||||
*/
|
||||
count?: Quoted<number>,
|
||||
/**
|
||||
* a cut's length when its own `seconds` says none: [least, most]
|
||||
*/
|
||||
seconds?: [number, number],
|
||||
/**
|
||||
* the formats every cut is delivered in when its own `formats` says none: "9:16", "16:9", "1:1", "4:5"
|
||||
*/
|
||||
formats?: Array<string>, cuts?: Array<CutPlan>,
|
||||
/**
|
||||
* what is said or shown: in every cut unless `every: false` (then in one or more)
|
||||
*/
|
||||
say?: Array<Phrase>,
|
||||
/**
|
||||
* what no cut says or shows: a banned claim, a word, a name
|
||||
*/
|
||||
never?: Array<Phrase>,
|
||||
/**
|
||||
* the line every cut ends on, heard or on screen in its last `within` seconds
|
||||
*/
|
||||
cta?: Cta,
|
||||
/**
|
||||
* the brief's open items ([TO CONFIRM]): each holds the job open until it has an answer
|
||||
*/
|
||||
open?: Array<CutOpen>,
|
||||
/**
|
||||
* every face whole and every text big enough, by the frames check of each file (true when left out)
|
||||
*/
|
||||
frames?: boolean, };
|
||||
|
||||
export type Quoted<T> = { value: T,
|
||||
/**
|
||||
* the brief's own words, as they are in its text
|
||||
*/
|
||||
from: string, };
|
||||
|
||||
export type CutPlan = {
|
||||
/**
|
||||
* [a-z0-9_], unique: each format lands as out/cuts/<id>_<W>x<H>.mp4 ("a1_s1_9x16.mp4")
|
||||
*/
|
||||
id: string, angle?: string,
|
||||
/**
|
||||
* solo or mashup
|
||||
*/
|
||||
kind?: string,
|
||||
/**
|
||||
* one of the brief's hook types ("Direct Problem", "Reaction")
|
||||
*/
|
||||
hook?: string,
|
||||
/**
|
||||
* captions, hook (a text hook) or none
|
||||
*/
|
||||
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<Beat>, };
|
||||
|
||||
export type Phrase = {
|
||||
/**
|
||||
* as it's said or shown; compared in lower case, by letters and digits ("24/7" and "24-7" are the same)
|
||||
*/
|
||||
text: string, from: string,
|
||||
/**
|
||||
* `say` only: false when one cut saying it is enough
|
||||
*/
|
||||
every?: boolean, };
|
||||
|
||||
export type Cta = { text: string, from: string,
|
||||
/**
|
||||
* the other lines a brief rotates (two host lines, a paid take's): any one lands it, each found in the brief
|
||||
*/
|
||||
also?: Array<string>,
|
||||
/**
|
||||
* how near the end it must land, in seconds (8 when left out)
|
||||
*/
|
||||
within?: number, };
|
||||
|
||||
export type CutOpen = { question: string, from: string,
|
||||
/**
|
||||
* what it decides: "count", "cta", "offer", a cut's id...
|
||||
*/
|
||||
about?: string,
|
||||
/**
|
||||
* the person's answer, as they gave it, and who gave it: until then the job can't be done
|
||||
*/
|
||||
answer?: string, by?: string, };
|
||||
|
||||
export type GoalRule = {
|
||||
/**
|
||||
* a short name: [a-z0-9_], how status, the critic and NOTES.md name it
|
||||
*/
|
||||
id: string,
|
||||
/**
|
||||
* a command that must exit 0, run in the brief's folder (`bun test`, `raea check edit.tsx`)
|
||||
*/
|
||||
run?: string,
|
||||
/**
|
||||
* the seconds `run` gets before it counts as failed (300 when left out)
|
||||
*/
|
||||
timeout?: number,
|
||||
/**
|
||||
* a file that must exist, relative to the brief (`a|b`: either; `dir/`: three or more pictures in it)
|
||||
*/
|
||||
file?: string,
|
||||
/**
|
||||
* words that must be true of the work, judged by a fresh critic (`raea goal judge`), never by the agent that did it
|
||||
*/
|
||||
says?: string, };
|
||||
@@ -31,5 +31,5 @@ export const parts = (p: Parts): Parts => p;
|
||||
* them in order (a workflow; `workflow()` shares one), each with its kind's packs and its own `rules`; `raea goal
|
||||
* check` holds each goal at every save, render, hand-over and stop. They're raea/goal's, here too so a brief imports
|
||||
* one module; `plan` is raea/task's. */
|
||||
export { cut, goal, kit, rules, scene, shot, workflow } from "raea/goal";
|
||||
export { cut, goal, kit, playable, rules, scene, shot, workflow } from "raea/goal";
|
||||
export { plan } from "raea/task";
|
||||
@@ -8,6 +8,7 @@ import { createRoot } from "react-dom/client";
|
||||
import { Clock, getCompositions, type InputTimeline, type RegisteredComposition } from "raea";
|
||||
import { Input } from "@raea/playable/host/input";
|
||||
import { Collector, UNDER3D_CSS, clearUnder3d } from "./collect";
|
||||
import { patchShaderModules } from "./wgsl";
|
||||
|
||||
/** raea-web's engine, as wasm-bindgen exports it (engine/web: `import init, { Raea } from "./raea_web.js"`). */
|
||||
export interface RaeaEngine {
|
||||
@@ -31,6 +32,8 @@ const loaded = new WeakMap<() => Promise<RaeaWebModule>, Promise<RaeaWebModule>>
|
||||
export function loadRaea(load: () => Promise<RaeaWebModule>): Promise<RaeaWebModule> {
|
||||
let p = loaded.get(load);
|
||||
if (!p) {
|
||||
// Safari reads WGSL to the letter: Bevy's shaders are made to its rules first (wgsl.ts)
|
||||
patchShaderModules();
|
||||
p = load().then(async (m) => (await m.default(), m));
|
||||
loaded.set(load, p);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
// Safari's WGSL (WebKit) holds to the spec: a `let` can't hold a texture or a sampler (they aren't constructible
|
||||
// types), while Chrome's Tint lets it through. Bevy's PBR shaders do it (bevy_pbr pbr_fragment.wesl,
|
||||
// `let texture = pbr_bindings::base_color_texture;`), in every mesh with UVs, so raea-web drew nothing in Safari
|
||||
// ("Fragment module is invalid", 12-02). Each such `let` is inlined here before the module is made: its name is replaced
|
||||
// by what it held (a global binding, or an index into a binding array) through the rest of its block.
|
||||
|
||||
/** the global bindings of handle types (textures, samplers, arrays of either) a shader declares */
|
||||
function handles(code: string): Set<string> {
|
||||
const out = new Set<string>();
|
||||
for (const m of code.matchAll(/\bvar\s+(\w+)\s*:\s*(?:texture_|sampler|binding_array\s*<\s*(?:texture_|sampler))/g)) out.add(m[1]);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** where the block holding `at` closes (the index of its `}`), or the end */
|
||||
function blockEnd(code: string, at: number): number {
|
||||
let depth = 0;
|
||||
for (let i = at; i < code.length; i++) {
|
||||
const c = code[i];
|
||||
if (c === "{") depth++;
|
||||
else if (c === "}") {
|
||||
if (depth === 0) return i;
|
||||
depth--;
|
||||
}
|
||||
}
|
||||
return code.length;
|
||||
}
|
||||
|
||||
/** The shader with every `let` that holds a texture or sampler inlined; the same text when there's none. */
|
||||
export function inlineHandleLets(code: string): string {
|
||||
const globals = handles(code);
|
||||
if (!globals.size) return code;
|
||||
const decl = /\blet\s+(\w+)\s*(?::\s*[^=]+)?=\s*([^;]+);/g;
|
||||
for (let guard = 0; guard < 10_000; guard++) {
|
||||
decl.lastIndex = 0;
|
||||
let m: RegExpExecArray | null, found: RegExpExecArray | null = null;
|
||||
while ((m = decl.exec(code))) {
|
||||
const root = /^\s*(?:\w+::)*(\w+)/.exec(m[2])?.[1];
|
||||
if (root && globals.has(root)) { found = m; break; }
|
||||
}
|
||||
if (!found) return code;
|
||||
const [whole, name, held] = found;
|
||||
const from = found.index + whole.length;
|
||||
const end = blockEnd(code, from);
|
||||
const value = held.trim().replace(/\s+/g, " ");
|
||||
const rest = code.slice(from, end).replace(new RegExp(`\\b${name}\\b`, "g"), () => value);
|
||||
code = code.slice(0, found.index) + rest + code.slice(end);
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
let patched = false;
|
||||
/** Makes every WebGPU shader module from its inlined text (once per page; nothing where there's no WebGPU). */
|
||||
export function patchShaderModules() {
|
||||
const G = (globalThis as { GPUDevice?: { prototype: { createShaderModule(d: { code: string }): unknown } } }).GPUDevice;
|
||||
if (patched || !G) return;
|
||||
patched = true;
|
||||
const make = G.prototype.createShaderModule;
|
||||
G.prototype.createShaderModule = function (d: { code: string }) {
|
||||
return make.call(this, typeof d?.code === "string" ? { ...d, code: inlineHandleLets(d.code) } : d);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
// wgsl.ts: a `let` holding a texture or sampler is inlined for Safari; everything else is left as it was
|
||||
import { expect, test } from "bun:test";
|
||||
import { inlineHandleLets } from "../../src/wgsl";
|
||||
|
||||
const head = `@group(2) @binding(1) var base_color_texture: texture_2d<f32>;
|
||||
@group(2) @binding(2) var base_color_sampler: sampler;
|
||||
@group(2) @binding(3) var bindless_textures_2d: binding_array<texture_2d<f32>, 16>;
|
||||
`;
|
||||
|
||||
test("a texture and a sampler held by lets are used directly, in their block only", () => {
|
||||
const code = `${head}fn f(uv: vec2<f32>) -> vec4<f32> {
|
||||
var c = vec4(1.0);
|
||||
if (true) {
|
||||
let texture = base_color_texture;
|
||||
let sampler_ = base_color_sampler;
|
||||
let coords = uv;
|
||||
c *= textureSampleBias(texture, sampler_, coords, 0.0);
|
||||
}
|
||||
let texture_scale = 2.0;
|
||||
return c * texture_scale;
|
||||
}`;
|
||||
const out = inlineHandleLets(code);
|
||||
expect(out).not.toContain("let texture =");
|
||||
expect(out).not.toContain("let sampler_ =");
|
||||
expect(out).toContain("textureSampleBias(base_color_texture, base_color_sampler, coords, 0.0)");
|
||||
expect(out).toContain("let coords = uv;");
|
||||
expect(out).toContain("let texture_scale = 2.0;");
|
||||
expect(out).toContain("return c * texture_scale;");
|
||||
});
|
||||
|
||||
test("a binding array's element, over lines, and the same name again in the next block", () => {
|
||||
const code = `${head}fn g(i: u32, uv: vec2<f32>) -> f32 {
|
||||
var a = 0.0;
|
||||
{
|
||||
let texture = bindless_textures_2d[
|
||||
i
|
||||
];
|
||||
a += textureSample(texture, base_color_sampler, uv).r;
|
||||
}
|
||||
{
|
||||
let texture = base_color_texture;
|
||||
a += textureSample(texture, base_color_sampler, uv).g;
|
||||
}
|
||||
return a;
|
||||
}`;
|
||||
const out = inlineHandleLets(code);
|
||||
expect(out).toContain("textureSample(bindless_textures_2d[ i ], base_color_sampler, uv).r");
|
||||
expect(out).toContain("textureSample(base_color_texture, base_color_sampler, uv).g");
|
||||
expect(out).not.toMatch(/let texture\b/);
|
||||
});
|
||||
|
||||
test("a module path (naga_oil's pbr_bindings::) is a binding all the same; a shader with no handles is untouched", () => {
|
||||
expect(inlineHandleLets(`${head}fn h() { let t = pbr_bindings::base_color_texture; textureDimensions(t); }`)).toContain("textureDimensions(pbr_bindings::base_color_texture)");
|
||||
const plain = "fn k() -> f32 { let x = 1.0; return x; }";
|
||||
expect(inlineHandleLets(plain)).toBe(plain);
|
||||
});
|
||||
+1
-1
@@ -216,7 +216,7 @@ gen_files() {
|
||||
echo "A field marked ? may be left out."
|
||||
echo
|
||||
echo '```ts'
|
||||
grep -v '^// Generated' "$ROOT/sdk/raea/src/brief.gen.ts" | sed '/^$/d'
|
||||
cat "$ROOT/sdk/raea/src/brief.gen.ts" "$ROOT/sdk/raea/src/brief-goal.gen.ts" | grep -vE '^(// Generated|import type|export type \* from)' | sed '/^$/d'
|
||||
echo '```'
|
||||
}
|
||||
rm -rf "$tmp"
|
||||
|
||||
Reference in new issue
Block a user