Compare commits

..
Author SHA1 Message Date
shinyobjectz 05ada509e4 A .png with no --frame goes through the stills branch as frame 0: the export crate stays at its 1996 lines (with LX6 and LT1's planned four it is at the 2000 limit, and the tasks gate failed #268) 2026-11-29 11:38:02 -08:00
shinyobjectz 5922b25227 The emoji decoder widens a PNG's pixels in one loop: its three one-line closures matched closures elsewhere, and the duplicate gate failed #268 by two exact groups and one near 2026-11-29 11:24:56 -08:00
shinyobjectz 8a459acbe5 The export crate stays within its 2000 lines: the still's frame-0 branch in four lines (the size gate failed #268 at 2004) 2026-11-29 11:11:01 -08:00
shinyobjectz 8d60b97d16 Three paint fixes: a canvas draws a loaded Image, a boxed 3D view culls by its box, grey bitmap emoji draw (raea #260, #261, #262)
#260: drawImage of a loaded Image onto a canvas made in a composition drew nothing. The canvas is read back off the
page, where there is no project folder to find staticFile's /media/x in. A loaded Image now carries the file the host
found as currentSrc (sdk/raea frame-globals.ts), which drawImage already prefers, and the canvas host takes a src that
is a file as it stands whatever its roots make of it (systems/canvas media_file).

#261: two causes, neither the plane's turn. Bevy's update_frusta culls by the projection's whole view at the target's
shape, so a camera drawing a page box wider than the frame (an <R3F> in a 1080 x 389 box of a 1080 x 600 frame) had
meshes inside the box's view culled: the shelf's side cards, where the same cards turned the other way reached into
the frame's view and drew. raea-sys-viewbox's sub_view_frusta gives a camera with a sub view that view's frustum,
after Bevy's own and before visibility is checked. And `raea render X.tsx -o x.png` with no --frame took the frames
path, which draws 3D from rows under the whole frame and ignored the box; a 3D piece's bare .png is now drawn as
--frame 0 draws it.

#262: Apple Color Emoji keeps 52 glyphs (💬, 🗨) as grey + alpha PNGs. Vello's glyph run asks png for RGBA with a
transformation that leaves grey as it is, logs "Unsupported `output_color_type`" and skips the glyph. The page's
painter (raea-sys-filters) takes those glyphs out of the run and draws them as images placed as Vello places a
bitmap glyph (emoji.rs); skrifa and png at Vello's versions.
2026-11-29 11:00:11 -08:00
shinyobjectz 456fd1e153 An index job reserves 2 cores and 8 GB
It reserved 4 and 16, and from 11-17 to 11-29 raea-ingest's CPU and memory cost more than its GPU ($7.05 against
$5.97). A 52 s clip measured 1.9 cores busy and 4.9 GB across its processes. A job that takes more is billed for what
it takes. Deployed 11-29 and checked: /healthz on both servers, and the same clip indexed through the deployed job
(10 fragments, 9 posters, 23 s). The search server and the frame API keep their sizes, unmeasured.
2026-11-29 09:55:34 -08:00
shinyobjectz 3afc53d45b A raea render's GPU container reserves 2 cores and 8 GB, and each job says what it used
From 11-17 to 11-29 the farm's CPU and memory came to 65% on top of its GPUs: every GPU container reserved 4 cores
and 16 GiB. A 1080p cut measured 1.3 to 1.4 cores busy and 2.7 GB in its biggest process, so raea's containers now
reserve half (farm_plan.RESERVED); a run that takes more is billed for what it takes, as nothing here sets a limit.
The same cut rendered at the same speed after (262 to 268 ms a frame on a T4) for $0.013 against $0.017. Blender's
containers keep 4 and 16, unmeasured. Each job's last line now says the most cores busy and the biggest process of
its runs, so the next change is made from the jobs' own logs. Deployed 11-29.
2026-11-29 09:34:31 -08:00
shinyobjectz 7d79a24f33 Merge branch 'farm-version' 2026-11-29 09:27:03 -08:00
shaneandshinyobjectz 6af8bfa5bb Cut checks a box can fail on: raea sound check, text placement from the farm's scene read, and full render manifests (#267)
Shane on Dutch (11-29): words faded and cut in two, lines too quiet to hear, effects no one hears, and text laid
over the people and the dog the shot is about.

- raea sound check VIDEO (server/sound.ts): each voice clip's edit points against the take's words and its sound.
  A cut inside a word or on a word's sound is an error, and the message names the pause (or the boundary) to move
  it to. Lines more than 6 dB from the cut's median are an error, with the gainDb that evens them. An effect 10 dB
  or more under the voice is an error, since no one hears it. Buried or fighting music is a warning. offload.ts runs
  it after every render that has a manifest.
- The farm's POST /v1/scene (deploy/modal/farm_scene.py) reads a frame: people as a mask, faces, COCO's things,
  and words in the shot (four small OpenCV zoo models on the CPU, each pinned by its hash).
- server/place.ts turns a scene into costs. raea frames check now fails text over a face, a dog or a person when a
  clear place of its size exists, and names that place. raea frames place FILE lists the clear places in a take.
  Stacked lines move as one block, our own text isn't counted as the shot's words, and passers-by's small faces
  don't count.
- The farm wrote a split render's probe manifest (frame 0 only) as the render's. Each run now writes its own and
  the farm joins them, so the checks see every frame and every clip.

Tests: test/sound.ts (7), test/place.ts (4, on scene reads of three interview frames, boxes only),
test/farm_plan.py (the joined manifest).

Co-authored-by: shinyobjectz <[email protected]>
2026-11-29 09:20:52 -08:00
shinyobjectz 4b2225163e The farm renders with raea's newest release, and says which one it holds
farm.py took RAEA_VERSION or 0.1.6, and no deploy set the variable: on 11-29 the farm's health said 0.1.6 while the
boxes that send it their compositions ran 0.1.12. A container never had the variable either, so health said the
default whatever the image was built with. A deploy now takes the newest full release (GitHub's releases/latest, as
box.sh does) unless RAEA_VERSION pins one, with 0.1.12 when GitHub can't be asked, and the image carries the
version it was built with for its containers. Not deployed: the next modal deploy of raea-farm brings it.
2026-11-29 09:13:24 -08:00
shaneandshinyobjectz 57373a9901 skills: raea-skills main 8efd329 (#138: raea show --playable in cli.md) (#266)
tools/skills.sh check, strict, with a raea built at main 9ce8f53466: every reference and guide copy matches.

Co-authored-by: shinyobjectz <[email protected]>
2026-11-28 14:58:30 -08:00
shaneandshinyobjectz 9ce8f53466 raea show GAME.tsx --playable, and a playable's page shown as itself (PA16) (#265)
--playable exports the game's preview (native.ts: raea playable --networks preview, in a folder of its own) and shows
that page, titled from it; the raea app plays it in a phone, sandboxed (raea-feed #124). raea show takes a
NAME-preview.html as it is too. The help line, the manual and the conformance tests say so.

Co-authored-by: shinyobjectz <[email protected]>
2026-11-28 14:32:03 -08:00
shaneandshinyobjectz 28af820668 PA13, PA14: raea playable, and playables in the public engine (#264)
* PA13, PA14: raea playable, and playables in the public engine

Playables move from the private tree into the public engine (Shane 11-28: "public totally part of the engine"):
sdk/playable (raea/playable for authors, the browser host, check.ts, parity.ts, tony.ts), examples/playables and
docs/playables.feature, with raea/playable and @raea/playable back in sdk/tsconfig.base.json.

`raea playable GAME.tsx -o DIR` (apps/playable) replaces the Bun pipeline (playable.sh, bundle.ts, lint.ts, walk.ts,
alias.ts). It lints the source, renders each composition through `raea run` for its shapes and 3D kinds, bundles the
game and the host once with raea's own bundler, and writes each network's page or ZIP against its 5 MB cap.
engine/bundle gains `minify`, `inline` (inline.rs: pictures, sounds, fonts and .glb as data URLs, .bin as a
Uint8Array) and package-folder aliases (`three/=DIR`). brick-rush writes all nine targets in 7 s (1,384 KB a page);
mobile-ads' tiles and gates export; all play in WebKit, the Google and TikTok packages included.

check.ts lets a network's own page tags through; parity.ts draws in WebKit (chrome.ts is gone), 6.8/255 on
brick-rush frame 300. The craft guide motion/playable.md is `raea guide playable`. bench/live-3d skips brick-rush with
its real reason (PA18).

* tools/layers.toml: raea-app-playable in apps (PA13)

* Fonts travel with a playable, and an end card in a brand's type

An imported .ttf, .otf, .woff or .woff2 (and .jpeg) is its path in a native render (runtime/bundle rewrite.rs,
engine/bundle script.rs) and a data URL in a playable (inline.rs), so an @font-face names the same file either way.
<EndCard> takes font, color and button. Made for the real-brand playables in mobile-ads (ACANA, OLIPOP, HelloFresh),
which carry their brands' own type; the guide and docs/playables.feature say how.

* The preview page tells raea's review its ad events (PA16)

Inside a frame, the preview network posts {raeaPlayable: kind} to its parent on install and end, so the review can show
them beside the game.

* PA16 status: the review plays playables (raea-platform #99), on a host of their own

* The preview page tells the review when it's ready, seen or hidden, and the first touch (PA16)

Beside install and end, the preview build inside a frame posts ready (the game started), viewable and hidden (its page
shown or put away) and touch (the player took over from the game's own hand), so the review and the desktop show them.

* PA16 status: built in cloud (raea-platform #99, #101) and desktop (raea-feed #124), and raea show --playable

* raea playable says what the source can't have even when the game won't render for the lint

A fetch or a URL often stops the walk's render too, and the lint answered with the render's end ("lint.ts ended with
exit 1") and dropped the refusals it had found. Now the source's refusals are the answer, and a render that fails
for another reason is named by its error line.

* PA16 status: play.raea.io is live, checked with the ACANA export

* skills: raea-skills main ae81d0f (#135 notes hook, #136 and #137 the playable guide and raea playable in cli.md)

tools/skills.sh gen with a raea built at this branch and the feed app at main: every reference and guide copy matches it.

* raea-cli: export-game and playable dispatched in a line each, as the verbs around them, so the crate stays at the size gate's 2000 lines

* dupes: the playable's copies folded into what they copied

spec is raea-runtime-bundle's own (now pub), inline.rs's base64 is the base64 crate as raea's other crates use it,
the store and card JSON are json!, and the bundle FFI reads minify and inline as it reads z3 and stamps. tools/dupes.sh:
293 exact, 57 near, as allowed.

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-11-28 13:53:48 -08:00
shaneandshinyobjectz ea5640de8f raea show --fyi/--group; notes reach closed sessions through raea's hook (#263)
* raea show --fyi and --group; the inbox hook says seen

Shane 11-28: "some things I'm not approving, I'm just acknowledging"; "the agent can go 'let me add a label here'".
raea show --fyi sends a show only to be looked at (the person says Got it, never approves or sends notes); --group
"Title: what it is" FILE... lays the files out in groups, each titled and said in a plain line. Both go to the app's
host as ShowBody.intent and .groups (raea-feed host/show.ts), which hands them to the review (raea-platform
harness/board.ts). The inbox hook says a {kind: seen} line as "seen on item ...", and when every new line is one,
tells the agent there's nothing to do rather than to take it up.

* Notes reach closed sessions: raea's hook hands them over when the session starts again

Shane 11-28: "raea installs a hook in Claude Code and Codex so your notes are delivered when the session next starts".
What the person sends from raea to a session whose terminal has closed waits in its inbox (~/.raea/inbox); the hook
now reads it at SessionStart (a resumed session takes it up first, told it waited while the session was closed) and at
UserPromptSubmit, as well as after a tool and as a turn ends. raea skills install adds SessionStart and
UserPromptSubmit for Claude Code, and Stop, SessionStart and UserPromptSubmit for Codex.

Tested: raea-app-check-inbox (4, a SessionStart hand-over once) and the installer's test in a standalone crate. The
hook.rs change isn't compiled here: raea-app-check needs ~12 GB to build and the disk has 3.5 GB free.

* The inbox tests share one scratch folder helper (dupes: the new test copied the first one's setup)

* The inbox's all-seen check written so it isn't a copy of a closure in fingerprint-use (dupes)

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-11-28 11:29:49 -08:00
shaneandshinyobjectz 3ac738884c skills: 0.1.12's references (raea-skills #134) (#259)
The goal job kind, MakeGoal, a job's previews, and ~/.raea/machine-id and target, generated at main 096f87d1 with raea
built from it: tools/skills.sh check passes.

Co-authored-by: shinyobjectz <[email protected]>
2026-11-27 14:08:38 -08:00
shaneandshinyobjectz 096f87d153 A canvas draws a picture from its file: drawImage of a /media/ src (raea #253) (#258)
#255 gave new Image() in a composition its size, so the issue's 3D cards got a canvas the right size, but drawing the
screenshot on it painted nothing: the canvas host decoded only data: URLs (systems/canvas draw.rs decode). A picture
that isn't inline is now read from its file, found by the same roots a canvas's videos are (the page host's
page_path, so /media/x is the project's file; a plain or file:// path without one), its type by its name (png, jpeg,
webp, gif, bmp, svg). A src that isn't there, or isn't a picture, still draws nothing.

Co-authored-by: shinyobjectz <[email protected]>
2026-11-27 13:23:57 -08:00
shaneandshinyobjectz 845f7438d5 Small caps synthesised, flex lines with a 1/64 px tolerance, and a table's stray text in anonymous cells (#257)
Three layout misses 0.1.11 shipped, each from its issue's own repro.

Times, Helvetica: most system faces) the text drew in normal case. blitz-dom now checks the face a text's lower-case
letters are drawn in for an smcp GSUB feature (once per face, layout/small_caps.rs) and, where it has none, draws each
run of lower-case letters as their capitals at 70% of the font size, as Chrome synthesises them.

gaps come out a few ulps over 658.8 px, so the third item wrapped (rows of 2, 2, 1). Chrome lays out in 1/64 px units
and keeps them on one line. Taffy 0.15.0 is vendored with a line that overflows by less than 1/64 px still fitting,
greedy and balanced wrapping alike.

element around its text had no cells and drew nothing, not even its background. The table's runs of other children
(text, blocks, inline elements) are now wrapped in an anonymous block that the table lays out as an anonymous row
holding one anonymous cell, as css-tables-3 wraps them: the element is laid out shrink-to-fit around its text.

The regression tests (systems/page/tests/layout_0112.rs) lay out each repro; all four fail on main and pass here.

Co-authored-by: shinyobjectz <[email protected]>
2026-11-27 13:23:52 -08:00
shaneandshinyobjectz 6f96c78a8b Paint fixes for 0.1.11's reports: nested masks in a faded group, inline background images, empty clip-paths, svg overflow: visible (#256)
#247: two nested mask-image layers inside an opacity group refused the frame as past Vello's bump buffers. The scene
was small; its layers nested seven deep, and every layer past the fourth spills each tile's 16x16 pixels into Vello's
blend spill buffer, whose fixed size (1 << 20 pixels, raea-page's 1 << 18) holds 4096 spills, fewer than a 1080x1920
page's 8160 tiles. vello_encoding's resolve now measures how deep the scene's layers nest (layer_depth) and the
render's config sizes the blend spill for every tile to spill that deep (blend_spill_for), within the largest buffer
the device binds (set_max_buffer_size, given by raea-page).

#248: an inline element's background-image wasn't drawn (only its colour was). text.rs draw_inline_backgrounds now
draws its image layers on each line fragment, laid out over the fragments side by side as box-decoration-break: slice
does, so a background-size sweep crosses the lines in turn.

#250: clip-path: inset() that clips to no area (inset(0 0 0 100%)) returned no shape, which meant no clip-path, and
the element was drawn whole. It is now an empty clip, and an element whose clip-path has no area isn't drawn.

#251: an inline <svg> was always clipped to its viewport. The UA sheet now gives svg:not(:root) overflow: clip (as
Chrome's hidden, without making it a scroll container, so layout is unchanged), and draw_svg clips only when the
svg's overflow isn't visible.

Regression tests: vello_encoding's resolve and config tests for the blend spill; systems/page/tests/paint_repros.rs
paints each of #248, #250 and #251's repros into a recording scene and checks what is filled and under which clips.

Co-authored-by: shinyobjectz <[email protected]>
2026-11-27 12:29:15 -08:00
shaneandshinyobjectz e70d9c79c1 A loaded new Image() has the picture's size (#253) (#255)
A composition's Image (sdk/raea frame-globals.ts, installed where the runtime has none) fired load but kept width,
height, naturalWidth and naturalHeight at 0, so code sizing a canvas from it made a 0-high canvas, and a
CanvasTexture made from that was refused as an undetermined image format.

Now, when its load fires, naturalWidth and naturalHeight are the picture's size: a data: URL's from its header
(@raea/ui's sniffSize), any other src's from the host's asset.load, which finds staticFile's /media/ paths as <Img>
does (media/, assets/, public/) and fetches http URLs through raea's cache. width and height are the ones given (the
constructor's, or set) else the natural size, as in a browser. A file the host can't find fires error and onerror
instead of load, and only the last src set fires. The manual's web-components guide says so.

Co-authored-by: shinyobjectz <[email protected]>
2026-11-27 10:19:31 -08:00
shinyobjectz f4db12c1d0 CI's size and dupes gates on 0.1.11: the mixer's output device (the stream and following the system's output) in its own crate, raea-sys-mix-device, so raea-sys-mix is under 2000 lines and live.rs under 500; one make::Gate in raea-core-brief for a cut's and a goal's gates (cut-plan and goal-plan had the same struct, and status.rs the same closure twice); the CTA's best line found without a copy of hands-audit's fold 2026-11-26 17:26:59 -08:00
shinyobjectz cd159fe0be promoted-from: the layers gate's files (tools/layers.sh, layers.toml, layers.allow) may differ between an rc and its release, as no build reads them (0.1.11-rc2's one-line layers fix would otherwise force a rebuild) 2026-11-26 16:57:39 -08:00
shinyobjectz 316b612d70 layers: raea-runtime-goal-plan is in the runtime layer (MK28's crate had none, and main's CI gates failed on it from c41ec580 on) 2026-11-26 16:57:08 -08:00
shinyobjectz aa40a2fa86 #82: the ARM64 build (it compiles: raea.exe is AA64 and runs) is packed and checked without drawing (release-check.sh RAEA_CHECK_NO_GPU=1 keeps plugins, guides, song map and bin\'s files; the windows-11-arm runner has only WARP, which segfaults in Bevy as on x64, and lavapipe has no ARM64 build), and it uses the release's compile cache 2026-11-26 14:01:28 -08:00
shinyobjectz 48705982b6 windows-arm.yml runs on v* tags too, beside release.yml, and attaches raea-VERSION-windows-arm64.zip to that release (skills-passed from the tag, as release.yml reads it); an ARM64 failure never holds up the release 2026-11-26 14:01:28 -08:00
shinyobjectz 7580433cd2 windows-arm.yml: metis-sys alone on windows-latest's x64 MSVC too, which release.yml builds with 2026-11-26 14:01:28 -08:00
shinyobjectz 28f3fd814b #82: metis-sys vendored with GKlib's stdint.h/inttypes.h stand-ins only before Visual Studio 2013 (Visual Studio 18's stdint.h types int_fast16_t differently, and the windows-11-arm build failed on every GKlib file); its graphs, manual and programs left out 2026-11-26 14:01:28 -08:00
shinyobjectz 1905dc723c #82: a windows-arm64 zip: RAEA_WIN_ARCH=arm64 has onnxruntime.sh and win-bundle.sh take the ARM64 runtime, VC++ CRT, uv and DXC (FFmpeg stays x64, run emulated), release.sh names and packs raea-VERSION-windows-arm64.zip, and windows-arm.yml packs and checks it on WARP 2026-11-26 14:01:28 -08:00
shinyobjectz c41dd64516 #82: raea built natively for Windows on ARM in CI (windows-arm.yml on windows-11-arm: the release's four binaries, raea --version, a 2D still on WARP); rav1d's assembly off there, where MSVC skips its GNU .S files 2026-11-26 14:01:28 -08:00
shinyobjectz 1fc3a07655 Merge branch 'whats-new-0111' 2026-11-26 14:01:28 -08:00
shinyobjectz 986bd33463 whats-new 0.1.11: goals as make jobs, live sound following the output, tall pictures (#245), Windows on ARM (#82), and in the app typed Ideate on your own agent, one Settings, voice with Studio, Codex on Windows (#244) 2026-11-26 14:01:27 -08:00
shane c41ec580a9 Merge pull request #246 from shinyobjectz/skills-0111
skills: CLI reference for 0.1.11
2026-11-26 11:23:26 -08:00
shane 7e25dcc56e skills: the CLI reference as 0.1.11 prints it (raea-skills 98de983: make judge, make status's goal kind) 2026-11-26 11:23:10 -08:00
164 changed files with 34654 additions and 281 deletions

No files matched your search

Generated
+27 -2
View File
@@ -13956,6 +13956,18 @@ dependencies = [
"winit",
]
[[package]]
name = "raea-app-playable"
version = "0.1.0"
dependencies = [
"dunce",
"raea-io-home",
"raea-runtime-bundle",
"regex",
"serde_json",
"zip",
]
[[package]]
name = "raea-app-registry"
version = "0.1.0"
@@ -14240,6 +14252,7 @@ name = "raea-bundle"
version = "0.1.0"
dependencies = [
"anyhow",
"base64 0.22.1",
"dunce",
"lightningcss",
"oxc",
@@ -14292,6 +14305,7 @@ dependencies = [
"raea-app-media",
"raea-app-notes",
"raea-app-play",
"raea-app-playable",
"raea-app-scene",
"raea-app-solid",
"raea-app-sound",
@@ -16040,7 +16054,9 @@ dependencies = [
"anyrender",
"anyrender_vello",
"blitz-paint",
"png 0.18.1",
"rustc-hash 2.1.3",
"skrifa 0.44.0",
"vello",
"wgpu",
]
@@ -16436,11 +16452,22 @@ dependencies = [
"raea-io-home",
"raea-io-media",
"raea-io-trace",
"raea-sys-mix-device",
"raea-sys-mix-level",
"raea-sys-tone",
"serde_json",
]
[[package]]
name = "raea-sys-mix-device"
version = "0.1.0"
dependencies = [
"audioadapter-buffers",
"cpal 0.15.3",
"firewheel",
"raea-io-trace",
]
[[package]]
name = "raea-sys-mix-level"
version = "0.1.0"
@@ -20416,8 +20443,6 @@ dependencies = [
[[package]]
name = "taffy"
version = "0.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c8480887e8803986d96a7173729565520d4bbb721ad6b7ad6941a22897207aa"
dependencies = [
"serde",
"slotmap",
+6
View File
@@ -86,6 +86,7 @@ members = [
"systems/tone",
"systems/mix",
"systems/mix/level",
"systems/mix/device",
"systems/ml",
"systems/mlx",
"systems/kimodo",
@@ -238,6 +239,7 @@ members = [
"apps/capcut",
"apps/layers",
"apps/play",
"apps/playable",
"tools/sdk-props",
"tools/hands-audit",
]
@@ -406,6 +408,10 @@ vello_encoding = { path = "vendor/vello_encoding" }
# (changes marked "raea:"): raea-page blends a bevy_ui page as Bevy does (bevy_ui on Blitz). No upstream
# equivalent yet (linebender/vello blends the encoded values).
vello_shaders = { path = "vendor/vello_shaders" }
# taffy 0.15.0 (Blitz's, Bevy UI's, rune-taffy's) with a flex line whose items overflow its container by less than
# Chrome's layout unit, 1/64 px, kept on one line: f32 rounding wrapped items that add up to the container's width
# (changes marked "raea:", raea #252). Back to upstream once Taffy breaks flex lines with a tolerance.
taffy = { path = "vendor/taffy" }
# Firewheel 0.12 on Bevy 0.20: bevy_reflect 0.20 and a glam-33 feature (BillyDM/Firewheel#144; changes marked "raea:")
firewheel = { path = "vendor/firewheel" }
firewheel-core = { path = "vendor/firewheel-core" }
+44 -3
View File
@@ -55,6 +55,11 @@ fn said(l: &Value) -> String {
"result" => format!("a result{on}: {text}"),
"correction" => format!("a correction{on}: {text}"),
"sign" => format!("a sign-off{on} (ask {})", l["ask"]),
// a show only to be looked at (raea show --fyi), looked at: Got it, with a word or none
"seen" => {
let word = text.strip_prefix("Seen").unwrap_or(&text).trim_start_matches(':').trim();
if word.is_empty() { format!("seen{on}") } else { format!("seen{on}: {word}") }
}
k => format!("{}{on}: {text}", if k.is_empty() { "something" } else { k }),
};
format!("- {what}")
@@ -68,6 +73,17 @@ pub fn told(agent: &str, v: &Value) -> Option<String> {
return None;
}
let list = lines.iter().map(said).collect::<Vec<_>>().join("\n");
// only Got it on what was shown to look at: nothing to take up
if !lines.iter().any(|l| l["kind"] != "seen") {
return Some(format!("raea: the person has looked at what you showed them (your inbox, ~/.raea/inbox/{inbox}.jsonl):\n{list}\nNothing to do about it; carry on."));
}
// a session started again (resumed) after the person wrote to it while it was closed (Shane 11-28: "notes reach
// closed sessions"): what waited is handed over before anything else
if v["hook_event_name"].as_str() == Some("SessionStart") {
return Some(format!(
"raea: while this session was closed, the person sent this from the raea app (your inbox, ~/.raea/inbox/{inbox}.jsonl; marked read, so the app shows it as read):\n{list}\nTake it up first, before anything else. Answer an item with raea show --on ITEM --note LINE, or post the next version with raea show FILE --replaces ITEM."
));
}
Some(format!(
"raea: the person just sent this from the raea app (your inbox, ~/.raea/inbox/{inbox}.jsonl; marked read, so the app shows it as read):\n{list}\nTake it up now, before going on: it may change what you're doing. What you say next shows under your session in their feed; answer an item with raea show --on ITEM --note LINE, or post the next version with raea show FILE --replaces ITEM."
))
@@ -78,11 +94,17 @@ mod tests {
use super::*;
use serde_json::json;
#[test]
fn each_line_is_handed_over_once_and_a_half_written_one_waits() {
let d = std::env::temp_dir().join(format!("raea-inbox-{}", std::process::id()));
/// an empty inbox folder of the test's own
fn scratch(tag: &str) -> std::path::PathBuf {
let d = std::env::temp_dir().join(format!("raea-inbox-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
d
}
#[test]
fn each_line_is_handed_over_once_and_a_half_written_one_waits() {
let d = scratch("once");
let f = d.join("claude-code-abcd1234.jsonl");
std::fs::write(&f, "{\"kind\":\"message\",\"text\":\"more epic\"}\n{\"kind\":\"no").unwrap();
let first = unread(&d, "claude-code-abcd1234");
@@ -97,6 +119,25 @@ mod tests {
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn seen_is_said_as_seen_and_asks_nothing() {
assert_eq!(said(&json!({"kind": "seen", "item": "i-2", "title": "Lobby", "text": "Seen"})), "- seen on item i-2 \"Lobby\"");
assert_eq!(said(&json!({"kind": "seen", "item": "i-2", "title": "Lobby", "text": "Seen: lovely"})), "- seen on item i-2 \"Lobby\": lovely");
}
#[test]
fn what_waited_while_it_was_closed_is_handed_over_as_it_starts_again() {
let d = scratch("start");
std::fs::write(d.join("claude-code-5e55a0ff.jsonl"), "{\"kind\":\"edits\",\"item\":\"i-9\",\"title\":\"Cut\",\"text\":\"tighter open\"}\n").unwrap();
// SAFETY: tests in this crate don't read RAEA_INBOX_DIR concurrently
unsafe { std::env::set_var("RAEA_INBOX_DIR", &d) };
let start = told("claude", &json!({"hook_event_name": "SessionStart", "source": "resume", "session_id": "5e55a0ff-1"})).unwrap();
assert!(start.starts_with("raea: while this session was closed") && start.contains("- edits on item i-9 \"Cut\":\ntighter open"), "{start}");
assert_eq!(told("claude", &json!({"hook_event_name": "UserPromptSubmit", "session_id": "5e55a0ff-1"})), None, "handed over once");
unsafe { std::env::remove_var("RAEA_INBOX_DIR") };
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn the_inbox_is_named_as_raea_show_names_it() {
assert_eq!(name("claude", &json!({"session_id": "15cd6bb0-8829-466f-a28a-bbca3d35be92"})).as_deref(), Some("claude-code-15cd6bb0"));
+7 -1
View File
@@ -148,7 +148,13 @@ pub fn hook(args: &[String]) -> R<String> {
let event = v["hook_event_name"].as_str().unwrap_or("");
// what the person sent from the raea app since the last look (inbox.rs): handed over after any tool, and a turn about
// to end goes on to take it up
let sent = if matches!(event, "PostToolUse" | "AfterTool" | "Stop") { crate::inbox::told(agent, &v) } else { None };
let sent = if matches!(event, "PostToolUse" | "AfterTool" | "Stop" | "SessionStart" | "UserPromptSubmit") { crate::inbox::told(agent, &v) } else { None };
// a session starting again, or the person writing to it in its terminal: what they sent from raea while it was
// closed or idle goes in as context first (Claude Code's and Codex's SessionStart and UserPromptSubmit read
// hookSpecificOutput.additionalContext)
if matches!(event, "SessionStart" | "UserPromptSubmit") {
return Ok(sent.map(|t| json!({"hookSpecificOutput": {"hookEventName": event, "additionalContext": t}}).to_string()).unwrap_or_default());
}
if event == "Stop" {
// what the person sent, and a `make` job that isn't done (docs/make.feature MK2): either keeps the turn going
let reasons: Vec<String> = [sent, raea_app_check_make::stop(&v)].into_iter().flatten().collect();
+5 -5
View File
@@ -1,8 +1,7 @@
//! Whether a job is done (docs/make.feature MK1), from what's on disk and nothing the agent says: the deliverables, the
//! notes, the record of renders and checks, and the judge's rounds. Pure over a `Job` so it is tested on fixtures.
use std::path::{Path, PathBuf};
use std::time::SystemTime;
use std::{path::{Path, PathBuf}, time::SystemTime};
use raea_core_brief::make::{self, Make};
use raea_core_facts::{Level, record::Entry};
@@ -188,10 +187,11 @@ pub fn status(job: &Job) -> Value {
}
let mut gates = checks(job);
gates.extend(lods(job, &notes));
// a cut job: its brief's rules over every delivered file (MK25-MK27), and the person's review its critic; a goal's
let plan = |g: make::Gate| gate(g.name, g.of.as_deref(), g.clear, g.says);
match (&job.make.cut, job.make.kind) {
// a cut job: its brief's rules over every delivered file (MK25-MK27), and the person's review its critic
(Some(c), make::Kind::Cut) => gates.extend(raea_runtime_cut_plan::gates(c, job.dir).into_iter().map(|g| gate(g.name, g.of.as_deref(), g.clear, g.says))),
(_, make::Kind::Goal) => gates.extend(job.make.goal.iter().flat_map(|g| raea_runtime_goal_plan::gates(g, job.dir)).map(|g| gate(g.name, g.of.as_deref(), g.clear, g.says))),
(Some(c), make::Kind::Cut) => gates.extend(raea_runtime_cut_plan::gates(c, job.dir).into_iter().map(plan)),
(_, make::Kind::Goal) => gates.extend(job.make.goal.iter().flat_map(|g| raea_runtime_goal_plan::gates(g, job.dir)).map(plan)),
_ => gates.extend(critic(job, newest, &notes)),
}
let (asks, said) = crate::asked::gates(&sheets(job), job.ledger, &notes);
+17
View File
@@ -0,0 +1,17 @@
[package]
name = "raea-app-playable"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "`raea playable`: a raea game exported as a playable ad, one page or ZIP per ad network (docs/playables.feature)"
[dependencies]
dunce = "1"
# the game and sdk/playable's host bundled into one page by raea's own bundler (Rolldown, in process)
raea-runtime-bundle = { path = "../../runtime/bundle" }
# where raea's files are: an install's share/raea, else this checkout
raea-io-home = { path = "../../io/home" }
regex = "1"
serde_json = "1"
zip = { version = "9", default-features = false, features = ["deflate-flate2"] }
+102
View File
@@ -0,0 +1,102 @@
//! `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.
mod lint;
mod pages;
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 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
pub(crate) use raea_runtime_bundle::spec;
fn flag<'a>(args: &'a [String], name: &str) -> Option<&'a str> {
args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).map(String::as_str)
}
/// The folder whose node_modules holds the three.js a playable draws with: the project's own (`raea add [email protected]`),
/// else the copy beside sdk/playable or sdk/r3f in raea's own files
fn three_dir(game: &Path, home: &Path) -> R<PathBuf> {
let mut d = game.parent();
while let Some(dir) = d {
if dir.join("node_modules/three/package.json").is_file() {
return Ok(dir.to_path_buf());
}
d = dir.parent();
}
["sdk/playable", "sdk/r3f"]
.iter()
.map(|p| home.join(p))
.find(|d| d.join("node_modules/three/package.json").is_file())
.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 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() {
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 js = r.and_then(|_| std::fs::read_to_string(&out).map_err(|e| e.to_string()));
let _ = std::fs::remove_file(&out);
js
}
pub fn cli(args: &[String]) -> R<String> {
let game = args.get(1).filter(|a| !a.starts_with('-')).ok_or(USAGE)?;
let game = dunce::canonicalize(game).map_err(|e| format!("{game}: {e}"))?;
let out = PathBuf::from(flag(args, "-o").ok_or(format!("-o DIR is required: {USAGE}"))?);
let networks: Vec<&str> = flag(args, "--networks").map(|n| n.split(',').filter(|s| !s.is_empty()).collect()).unwrap_or_else(|| pages::NETWORKS.to_vec());
if let Some(bad) = networks.iter().find(|n| !pages::NETWORKS.contains(n)) {
return Err(format!("raea playable: no network {bad} (one of {})", pages::NETWORKS.join(", ")));
}
let orientation = flag(args, "--orientation").unwrap_or("both");
if !["portrait", "landscape", "both"].contains(&orientation) {
return Err("--orientation is portrait, landscape or both".into());
}
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();
let mut report = Vec::new();
let found = lint::lint(&game)?;
report.push(format!("3D kinds: {}", if found.kinds.is_empty() { "none".into() } else { found.kinds.join(", ") }));
for c in &found.comps {
let shape = if c.height > c.width { "portrait" } else { "landscape" };
report.push(format!("composition {}: {}x{} {shape}, {} fps, {:.0} s", c.id, c.width, c.height, c.fps, c.frames as f64 / c.fps.max(1.0)));
}
report.extend(found.notes.iter().map(|n| format!("note: {n}")));
if !found.refusals.is_empty() {
// the reasons first: the CLI marks an error's first line REFUSED
let mut why = found.refusals.clone();
why.extend(report);
return Err(why.join("\n"));
}
let js = bundle(&game, &raea_io_home::home())?;
std::fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?;
let mut over = false;
for net in networks {
let script = format!("{}\n{js}", pages::preamble(net, &store, &card));
let w = pages::write(net, &name, &script, &out, orientation)?;
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" }));
}
if over {
report.insert(0, format!("a page is over its network's {} KB cap", pages::CAP / 1024));
return Err(report.join("\n"));
}
report.push(format!("APPLIED {name} exported as a playable to {}", out.display()));
Ok(report.join("\n"))
}
+104
View File
@@ -0,0 +1,104 @@
//! What a playable can't have, refused before it is bundled (docs/playables.feature PA4): the source read for files
//! from disk, the network and the native engine's modules; the compositions rendered (sdk/playable/src/export/walk.ts,
//! through `raea run` in a process of its own) for their shapes and the 3D kinds the host doesn't draw.
use super::R;
use serde_json::Value;
use std::path::Path;
/// One composition the game registers
pub struct Comp {
pub id: String,
pub width: u32,
pub height: u32,
pub fps: f64,
pub frames: u64,
}
/// What the lint found: refusals stop the export, notes don't
pub struct Found {
pub comps: Vec<Comp>,
pub kinds: Vec<String>,
pub notes: Vec<String>,
pub refusals: Vec<String>,
}
const SOURCE_RULES: &[(&str, &str)] = &[
(r"\bstaticFile\s*\(", "staticFile() reads the edit's folder at render time; import the file instead (`import icon from \"./icon.png\"`), which the export carries in the page"),
(r"https?://", "a URL in the source: a playable makes no network requests (every network refuses one)"),
(r"\bfetch\s*\(|XMLHttpRequest|WebSocket", "fetch/XHR/WebSocket: a playable makes no network requests"),
(r#"from\s+["']raea/(native|ml|character|physics|media|matchmove|modelling)["']"#, "a module that needs the native engine (native calls, models, physics, footage)"),
(r"<(Video|Audio)\b", "<Video>/<Audio> play through the native media stack; a playable's sound is PA6 (not yet)"),
];
/// The game's source and its compositions, judged
pub fn lint(game: &Path) -> R<Found> {
let src = std::fs::read_to_string(game).map_err(|e| format!("{}: {e}", game.display()))?;
let mut refusals = Vec::new();
let mut notes = Vec::new();
// a URL the SVG namespace names is a name, not a request
let src_no_ns = src.replace("http://www.w3.org", "");
for (re, why) in SOURCE_RULES {
if regex::Regex::new(re).map_err(|e| e.to_string())?.is_match(&src_no_ns) {
refusals.push(why.to_string());
}
}
if !src.contains("raea/playable") {
notes.push("no raea/playable import: the game never opens the store itself (add an <EndCard> or <InstallButton>); the host's own end card shows at the last frame".into());
}
let walked = match walk(game) {
Ok(w) => w,
// what the source can't have (a fetch, a URL) often stops the render too: the refusal says why, the render's end doesn't
Err(_) if !refusals.is_empty() => return Ok(Found { comps: vec![], kinds: vec![], notes, refusals }),
Err(e) => return Err(e),
};
let comps: Vec<Comp> = walked["comps"]
.as_array()
.into_iter()
.flatten()
.map(|c| Comp {
id: c["id"].as_str().unwrap_or("").into(),
width: c["width"].as_u64().unwrap_or(0) as u32,
height: c["height"].as_u64().unwrap_or(0) as u32,
fps: c["fps"].as_f64().unwrap_or(30.0),
frames: c["frames"].as_u64().unwrap_or(0),
})
.collect();
let strings = |k: &str| walked[k].as_array().into_iter().flatten().filter_map(|v| v.as_str().map(String::from)).collect::<Vec<_>>();
if comps.is_empty() {
refusals.push("no composition registered (registerRoot)".into());
}
if comps.len() == 1 {
notes.push("one composition: the other orientation is letterboxed (Unity, AppLovin, Moloco and Mintegral want both; register a second one at the other shape)".into());
}
for k in strings("refused") {
refusals.push(format!("3D kind {k} isn't drawn in a playable"));
}
Ok(Found { comps, kinds: strings("kinds"), notes, refusals })
}
/// sdk/playable's walk run on the engine (`raea run`) after the game, in a process of its own so the game's React stays
/// out of this one; its answer is the JSON it prints
fn walk(game: &Path) -> R<Value> {
let walk = raea_io_home::home().join("sdk/playable/src/export/walk.ts");
if !walk.is_file() {
return Err(format!("{}: raea's playable SDK isn't there", walk.display()));
}
let work = std::env::temp_dir().join(format!("raea-playable-lint-{}", std::process::id()));
std::fs::create_dir_all(&work).map_err(|e| e.to_string())?;
let entry = work.join("lint.ts");
std::fs::write(&entry, format!("import {:?};\nexport {{ default }} from {:?};\n", super::spec(game), super::spec(&walk))).map_err(|e| e.to_string())?;
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
let run = std::process::Command::new(exe).arg("run").arg(&entry).output().map_err(|e| format!("raea run: {e}"));
let _ = std::fs::remove_dir_all(&work);
let run = run?;
let out = String::from_utf8_lossy(&run.stdout);
if !run.status.success() {
let err = String::from_utf8_lossy(&run.stderr);
let said: Vec<&str> = err.lines().chain(out.lines()).filter(|l| !l.trim().is_empty()).collect();
// the line that names the error, else the last one ("… ended with exit 1" says nothing)
let why = said.iter().find(|l| l.contains("Error") || l.contains("error:")).or(said.last()).unwrap_or(&"").trim().to_string();
return Err(format!("the game didn't render for the lint: {why}"));
}
let at = out.find('{').ok_or("the lint's walk printed no answer")?;
serde_json::from_str(&out[at..]).map_err(|e| format!("the lint's walk: {e}"))
}
+100
View File
@@ -0,0 +1,100 @@
//! Each network's package around the one script (docs/playables.feature, the Background's table): the page every
//! network gets, with that network's own tags, as one HTML file or a ZIP, checked against its cap.
use super::R;
use std::io::Write;
use std::path::{Path, PathBuf};
pub const NETWORKS: &[&str] = &["applovin", "unity", "google", "meta", "moloco", "mintegral", "tiktok", "liftoff", "preview"];
/// Every network's cap, 5 MB (TikTok's counted zipped, which is what's written)
pub const CAP: u64 = 5 * 1024 * 1024;
/// What one network got: the file and its size
pub struct Written {
pub network: String,
pub file: PathBuf,
pub bytes: u64,
}
/// The settings a page starts with, as the globals the host reads (sdk/playable network.ts, host/main.tsx): the network,
/// the store links, the end card's words
pub fn preamble(network: &str, store: &str, card: &str) -> String {
format!("var __RAEA_NETWORK__={},__RAEA_STORE__={store},__RAEA_PLAYABLE__={card};", serde_json::to_string(network).unwrap_or_default())
}
/// The page: the network's head and body tags, then the script (a page's inline script ends at the first "</script")
pub fn page(title: &str, head: &str, body: &str, script: &str) -> String {
let title = title.replace('&', "&amp;").replace('<', "&lt;");
format!(
"<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no,viewport-fit=cover\">\n<title>{title}</title>\n{head}\n</head>\n<body>\n{body}\n<script>\n{}\n</script>\n</body>\n</html>\n",
script.replace("</script", "<\\/script")
)
}
fn zip(file: &Path, entries: &[(String, String)]) -> R<()> {
let f = std::fs::File::create(file).map_err(|e| format!("{}: {e}", file.display()))?;
let mut w = zip::ZipWriter::new(f);
let o = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
for (name, text) in entries {
w.start_file(name.as_str(), o).map_err(|e| e.to_string())?;
w.write_all(text.as_bytes()).map_err(|e| e.to_string())?;
}
w.finish().map_err(|e| e.to_string())?;
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);
let file = match network {
// a ZIP with index.html; exitapi.js and the orientation tag in the head (Google Ads help 9981650)
"google" => {
let o = if orientation == "both" { "portrait,landscape" } else { orientation };
let head = format!("<meta name=\"ad.orientation\" content=\"{o}\">\n<script type=\"text/javascript\" src=\"https://tpc.googlesyndication.com/pagead/gadgets/html5/api/exitapi.js\"></script>");
let f = out.join(format!("{name}-google.zip"));
zip(&f, &[("index.html".into(), html(&head, ""))])?;
f
}
// a ZIP with index.html and config.json; TikTok's playable SDK before the game's script (TikTok Ads help)
"tiktok" => {
let o = match orientation {
"portrait" => 1,
"landscape" => 2,
_ => 0,
};
let body = "<script src=\"https://sf16-muse-va.ibytedtos.com/obj/union-fe-nc-i18n/playable/sdk/playable-sdk.js\"></script>";
let f = out.join(format!("{name}-tiktok.zip"));
zip(&f, &[("index.html".into(), html("", body)), ("config.json".into(), format!("{{\"playable_orientation\": {o}}}\n"))])?;
f
}
// a ZIP holding a folder and a page of the same name
"mintegral" => {
let f = out.join(format!("{name}-mintegral.zip"));
zip(&f, &[(format!("{name}/{name}.html"), html("", ""))])?;
f
}
// one HTML file, everything inlined; MRAID is injected by the network's webview (Meta: data URIs only)
"applovin" | "unity" | "meta" | "moloco" | "liftoff" | "preview" => {
let f = out.join(format!("{name}-{network}.html"));
std::fs::write(&f, html("", "")).map_err(|e| format!("{}: {e}", f.display()))?;
f
}
other => return Err(format!("raea playable: no network {other} (one of {})", NETWORKS.join(", "))),
};
let bytes = std::fs::metadata(&file).map(|m| m.len()).unwrap_or(0);
Ok(Written { network: network.into(), file, bytes })
}
#[cfg(test)]
mod tests {
#[test]
fn a_script_cannot_end_its_page_early() {
let p = super::page("t", "", "", "a('</script>')");
assert_eq!(p.matches("</script").count(), 1, "{p}");
}
#[test]
fn the_preamble_names_the_network_as_a_string() {
assert_eq!(super::preamble("applovin", "{}", "{}"), "var __RAEA_NETWORK__=\"applovin\",__RAEA_STORE__={},__RAEA_PLAYABLE__={};");
}
}
+9 -3
View File
@@ -21,8 +21,10 @@ struct Hook {
fn hooks(agent: &str) -> R<Vec<Hook>> {
let h = |event, matcher, secs| Hook { event, matcher, secs };
Ok(match agent {
"claude" => vec![h("PreToolUse", "Bash", 30), h("PostToolUse", "*", 60), h("Stop", "", 30)],
"codex" => vec![h("PreToolUse", "^(Bash|shell|shell_command|exec_command)$", 30), h("PostToolUse", "^(apply_patch|Edit|Write)$", 60)],
// SessionStart and UserPromptSubmit: notes sent from raea while the session was closed or idle reach it when it
// starts again or is next written to (Shane 11-28: "notes reach closed sessions")
"claude" => vec![h("PreToolUse", "Bash", 30), h("PostToolUse", "*", 60), h("Stop", "", 30), h("SessionStart", "", 10), h("UserPromptSubmit", "", 10)],
"codex" => vec![h("PreToolUse", "^(Bash|shell|shell_command|exec_command)$", 30), h("PostToolUse", "^(apply_patch|Edit|Write)$", 60), h("Stop", "", 30), h("SessionStart", "", 10), h("UserPromptSubmit", "", 10)],
"gemini" => vec![h("BeforeTool", "run_shell_command", 30), h("AfterTool", "write_file|replace", 60)],
"kimi" => vec![h("PreToolUse", "Bash|Shell", 30), h("PostToolUse", "Write|Edit|WriteFile|StrReplaceFile", 60)],
a => return Err(format!("no agent {a:?}: claude, codex, kimi or gemini")),
@@ -124,7 +126,8 @@ mod tests {
let c = d.join("claude/settings.json");
std::fs::create_dir_all(c.parent().unwrap()).unwrap();
std::fs::write(&c, r#"{"model":"x","hooks":{"PostToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"other"}]},{"matcher":"Write","hooks":[{"type":"command","command":"raea hook claude"}]}]}}"#).unwrap();
let [pre, post, stop] = <[Hook; 3]>::try_from(hooks("claude").unwrap()).ok().unwrap();
let [pre, post, stop, start, prompt] = <[Hook; 5]>::try_from(hooks("claude").unwrap()).ok().unwrap();
assert!(add_json(&c, "claude", &start).unwrap() && add_json(&c, "claude", &prompt).unwrap() && !add_json(&c, "claude", &start).unwrap());
assert!(add_json(&c, "claude", &pre).unwrap() && !add_json(&c, "claude", &pre).unwrap());
assert!(add_json(&c, "claude", &post).unwrap() && !add_json(&c, "claude", &post).unwrap(), "an older raea's after-save hook is widened to every tool, once");
assert!(add_json(&c, "claude", &stop).unwrap() && !add_json(&c, "claude", &stop).unwrap());
@@ -133,6 +136,9 @@ mod tests {
assert_eq!((v["hooks"]["PostToolUse"][0]["matcher"].as_str(), v["hooks"]["PostToolUse"][1]["matcher"].as_str()), (Some("Bash"), Some("*")));
assert_eq!(v["hooks"]["PreToolUse"][0]["hooks"][0]["command"], "raea hook claude");
assert_eq!(v["hooks"]["Stop"][0]["hooks"][0]["command"], "raea hook claude");
assert_eq!(v["hooks"]["SessionStart"][0]["hooks"][0]["command"], "raea hook claude");
assert_eq!(v["hooks"]["UserPromptSubmit"][0]["hooks"][0]["command"], "raea hook claude");
assert_eq!(hooks("codex").unwrap().iter().map(|h| h.event).collect::<Vec<_>>(), ["PreToolUse", "PostToolUse", "Stop", "SessionStart", "UserPromptSubmit"]);
let g = d.join("gemini/settings.json");
let [before, _] = <[Hook; 2]>::try_from(hooks("gemini").unwrap()).ok().unwrap();
assert!(add_json(&g, "gemini", &before).unwrap());
+1 -1
View File
@@ -16,7 +16,7 @@ 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 "a playable: it needs the playable host's raea_playable (sdk/playable)" ;;
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
+10
View File
@@ -318,3 +318,13 @@ pub fn doctor(m: &Make) -> Vec<String> {
}
out
}
/// One gate as `raea make status` lists it: its name, the file, item or rule it's about, whether it's clear, and what
/// it says. A cut's gates come from raea-runtime-cut-plan, a goal's from raea-runtime-goal-plan.
#[derive(Debug, Clone, PartialEq)]
pub struct Gate {
pub name: &'static str,
pub of: Option<String>,
pub clear: bool,
pub says: String,
}
+3 -2
View File
@@ -66,7 +66,9 @@ else throws a SyntaxError, as Chrome's does.
that doesn't load rejects, and the text falls back.
- `window` has `innerWidth`, `innerHeight` and `devicePixelRatio` for the composition's size, and `getComputedStyle`.
- `requestAnimationFrame` calls back once per frame drawn, given that frame's time, so a frame drawn again gets the
same calls. `new Image()` fires `load` when its `src` is set, with no pixel size.
same calls. `new Image()` fires `load` when its `src` is set (a `staticFile` path, a data: URL or an http URL), and
by then `naturalWidth` and `naturalHeight` are the picture's size; `width` and `height` are the ones you gave, else
the same. A file that isn't there fires `error` instead.
- `ResizeObserver` calls back once when it starts observing, then after any layout that changed an observed element's
size, with `contentRect`, `borderBoxSize` and `contentBoxSize`.
@@ -75,7 +77,6 @@ else throws a SyntaxError, as Chrome's does.
- `MutationObserver` and `IntersectionObserver` exist, so a component that makes one doesn't throw, but they never
call back.
- An `<img>`'s `onError` never fires: an image that doesn't load fails the render, naming its src.
- `new Image()` has no `naturalWidth` or `naturalHeight` (they stay 0).
- An element has no `innerHTML` or `outerHTML`: read `textContent`, or walk `children` and `childNodes`.
- A Range across wrapped lines is one rect, not one per line, and an inline element's `getClientRects()` is one rect
too.
+1 -1
View File
@@ -1,7 +1,7 @@
---
title: "raea app"
summary: "Run, check headless and package a desktop app written as one TSX file on @raea/ui."
order: 7
order: 8
sources: ["engine/cli/src/cli.rs", "engine/rune/src/main.rs"]
---
+1 -1
View File
@@ -1,7 +1,7 @@
---
title: "raea bundle"
summary: "Bundle a composition into one JavaScript file that render_bundle draws, on the Mac or the iPhone."
order: 6
order: 7
sources: ["engine/cli/src/cli.rs", "runtime/bundle/src/lib.rs"]
---
+1 -1
View File
@@ -1,7 +1,7 @@
---
title: "raea export"
summary: "The composition as a CapCut draft ready in its timeline: its footage and sounds as clips of their own files at their trims and gains, everything raea draws as transparent overlay clips above them."
order: 5
order: 6
sources: ["engine/cli/src/cli.rs"]
---
+1
View File
@@ -35,6 +35,7 @@ Render, play and package what you wrote.
| [`raea render`](render.md) | Render a composition to an MP4, a PNG or a folder of frames, on the GPU and headless. |
| [`raea play`](play.md) | Play a game live in a window, or headless with scripted keys, snapshots and a timing report. |
| [`raea export-game`](export-game.md) | Package a game as a program of its own: a Mac app or a command-line program. |
| [`raea playable`](playable.md) | Export a game as a playable ad: one page or ZIP for each ad network, under its size cap, from the same TSX that renders as the video ad. |
| [`raea export`](export.md) | The composition as a CapCut draft ready in its timeline: its footage and sounds as clips of their own files at their trims and gains, everything raea draws as transparent overlay clips above them. |
| [`raea bundle`](bundle.md) | Bundle a composition into one JavaScript file that render_bundle draws, on the Mac or the iPhone. |
| [`raea app`](app.md) | Run, check headless and package a desktop app written as one TSX file on @raea/ui. |
+48
View File
@@ -0,0 +1,48 @@
---
title: "raea playable"
summary: "Export a game as a playable ad: one page or ZIP for each ad network, under its size cap, from the same TSX that renders as the video ad."
order: 5
sources: ["apps/playable/src/lib.rs"]
---
`raea playable` turns a raea game into a playable ad: a short game served in place of a video ad inside other apps,
ending on a card that opens the store. The same file renders with `raea render` as the video ad, because a game that
nobody touches plays itself. Each network gets the page or ZIP it takes, with its own start, pause and store calls,
checked against its 5 MB cap. Nothing in the page loads anything: pictures, sounds and the 3D renderer travel inside it.
```sh
raea playable game.tsx -o out/playable --ios https://apps.apple.com/app/id123 --android https://play.google.com/store/apps/details?id=com.example
raea playable game.tsx -o out/playable --networks applovin,google,preview --cta "Play free"
```
Before it bundles, the export refuses what a playable can't have: files read from disk at render time (`staticFile`;
import the file instead), URLs and network calls, modules that need the native engine, `<Video>` and `<Audio>`, and 3D
kinds the playable's renderer doesn't draw. It notes a game with only one orientation, and one that never imports
`raea/playable` (`<EndCard>`, `<InstallButton>`, `install()`) to open the store itself.
The 3D is drawn by three.js on raea's scene contract, with Bevy's light units and tone mapping. It comes from the
project (`raea add [email protected]`).
<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->
## 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)
```
Headless: it needs nothing running and opens no window. Takes up to 1 argument besides its flags.
## Flags
| Flag | Takes | What it does |
| --- | --- | --- |
| `--android` | `URL` | The Google Play page the store tap opens on Android. |
| `--cta` | `TEXT` | The button's words on the host's own end card, `Play now` by default. A game's `<EndCard cta>` sets its own. |
| `--ios` | `URL` | The App Store page the store tap opens on iPhone and iPad. |
| `--networks` | `LIST` | The networks to write, split by commas: `applovin`, `unity`, `google`, `meta`, `moloco`, `mintegral`, `tiktok`, `liftoff`, `preview`. All of them by default. |
| `--orientation` | `portrait\|landscape\|both` | What Google's `ad.orientation` tag and TikTok's `config.json` are told; `both` by default. The game plays whichever of its compositions is nearest the screen's shape either way. |
| `--title` | `TEXT` | The title on the host's own end card, shown at the last frame when the game never shows an `<EndCard>`. |
| `-o` | `DIR` | The folder the pages and ZIPs go in, named GAME-NETWORK.html or .zip. |
<!-- generated:end -->
+1 -1
View File
@@ -1,7 +1,7 @@
---
title: "raea run"
summary: "Run a TypeScript program on the engine, headless, and print what it prints."
order: 8
order: 9
sources: ["engine/cli/src/cli.rs"]
---
+1 -1
View File
@@ -51,7 +51,7 @@ raea show out/cut-v2.mp4 --replaces i-show-2f9c --done c-3 --done c-4 --note "Wa
## Usage
```sh
raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] [--label LABEL] [--detail PARAGRAPH] [--labels FILE.json] [--despite CHECK WHY] | raea show --question Q --choice A --choice B [STILL...] | raea show [--title T] --question Q [--preview FILE] --choice A [--preview FILE] --choice B ... [--question Q2] ... | raea show --on ITEM [--working ID] [--ask TEXT] [--status S] [--states S1,S2] [--sign N --clip FILE --render HASH] [--done ID] [--note LINE] [--sub NAME] (shown in the raea app as an item the person can use and answer, posted quietly with a notice, the window left where they are unless --open: stills (several, a storyboard), a video, a sound, a NAME.script.ts or .md, a .tsx (an interactive artifact; a project's composition opens in its editor), or questions, all of them one item; --label "PLACE TAG" a label beside the picture, never on it, that points at PLACE (x0,y0,x1,y1 or x,y in its 0-1, then #N the Nth file, @T or @T-TO a film's seconds, or part=KEY a scene's part; the tag the rest), --detail the paragraph of the --label before it, --labels a JSON list of them as feed_post takes them, and a sheet raea media sheet made comes labelled; each question and choice with a --preview to play or read while answering (a still, a video, a sound, a script or .md; after a --choice that choice's, else the question's); what they send comes to ~/.raea/inbox/INBOX.jsonl; their edit comments are tasks: --working ID as you start one (each --ask with it one ask you read it as, for the person to correct; --status and --states where the note and each ask stand: to restate, to check, failing, to sign, passing, signed; --sign N --clip FILE --render HASH a clip under ask N for them to sign; a note closes when they retire it, never with --done), --done ID when it's settled, or with the version that settles it, FILE --replaces ITEM --done ID; never open media in Preview while the app is installed)
raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] [--playable] [--label LABEL] [--detail PARAGRAPH] [--labels FILE.json] [--despite CHECK WHY] | raea show --question Q --choice A --choice B [STILL...] | raea show [--title T] --question Q [--preview FILE] --choice A [--preview FILE] --choice B ... [--question Q2] ... | raea show --on ITEM [--working ID] [--ask TEXT] [--status S] [--states S1,S2] [--sign N --clip FILE --render HASH] [--done ID] [--note LINE] [--sub NAME] (shown in the raea app as an item the person can use and answer, posted quietly with a notice, the window left where they are unless --open: stills (several, a storyboard), a video, a sound, a NAME.script.ts or .md, a .tsx (an interactive artifact; a project's composition opens in its editor), a playable ad's NAME-preview.html (played in a phone, sandboxed; --playable exports a game's .tsx with raea playable and shows that), or questions, all of them one item; --label "PLACE TAG" a label beside the picture, never on it, that points at PLACE (x0,y0,x1,y1 or x,y in its 0-1, then #N the Nth file, @T or @T-TO a film's seconds, or part=KEY a scene's part; the tag the rest), --detail the paragraph of the --label before it, --labels a JSON list of them as feed_post takes them, and a sheet raea media sheet made comes labelled; each question and choice with a --preview to play or read while answering (a still, a video, a sound, a script or .md; after a --choice that choice's, else the question's); what they send comes to ~/.raea/inbox/INBOX.jsonl; their edit comments are tasks: --working ID as you start one (each --ask with it one ask you read it as, for the person to correct; --status and --states where the note and each ask stand: to restate, to check, failing, to sign, passing, signed; --sign N --clip FILE --render HASH a clip under ask N for them to sign; a note closes when they retire it, never with --done), --done ID when it's settled, or with the version that settles it, FILE --replaces ITEM --done ID; never open media in Preview while the app is installed)
```
Needs the raea app's host running on this machine; then waits for a person's click in the raea app (to answer). Takes any number of arguments besides its flags.
+81
View File
@@ -0,0 +1,81 @@
---
title: "raea 0.1.11"
version: "0.1.11"
date: "2026-11-26"
summary: "A goal is a make job, judged by its own commands and a fresh critic. Live sound follows your output device, a picture taller than the GPU's largest texture draws, and Windows on ARM gets raea's installer and its own build. In the app, typing to Ideate answers with your own agent, there is one Settings page, and voice comes with Studio."
sources: ["https://github.com/shinyobjectz/raea/releases/tag/v0.1.11"]
---
raea 0.1.11 makes a goal something `raea make` holds an agent to: the goal's own commands and a critic that only
reads decide when it's done, never the agent's word. Live sound now follows the output you're listening on, a very
tall picture draws instead of being refused, and Windows on ARM PCs get raea's installer and a build of their own. In
the app, typing to Ideate answers with the agent you connected, Settings are one page, and talking with Ideate comes
with Studio.
**Get the app at [raea.io](https://raea.io)** (a Mac with Apple silicon, Windows 10 or 11, or Linux on x86_64).
The engine alone:
```sh
curl -fsSL https://raea.io/install | sh
```
On Windows, in PowerShell: `irm https://raea.io/install.ps1 | iex`.
## What changed since 0.1.10
**A goal is a make job.** Besides scenes, kits, shots and cuts, `make: goal({...})` in `brief.ts` is a fifth kind of
job (MK28-MK29). Its rules are commands that must pass and things it must say, and `raea make judge` has a fresh
critic, which only reads, judge each `says` rule into `review/goal.judge.json`. `raea make status` is the one judge
of whether the goal is met.
**Cuts from a brief rotate their call to action.** A `cut` brief's `cta.also` lists the other lines a brief rotates,
and each cut ends on one of them within its last 8 seconds (MK25).
**Live sound follows your output.** When the system's output changes (headphones, AirPods, a display) or the stream
breaks, live sound reopens on the device in use instead of going quiet.
**A tall picture draws (#245).** A picture larger than the GPU's image atlas (a 1080 x 18000 site capture drawn 880
wide) was refused with a message about a filtered layer. It is now decoded at a size that fits the atlas, which is
16384 px a side even on a GPU that allows larger textures.
**Windows on ARM (#82).**
- `irm https://raea.io/install.ps1 | iex` installs on an ARM64 PC: raea's ARM64 build when the release has one, else
the x86_64 build, which Windows 11 on ARM runs emulated. Before, the installer refused ARM64 PCs.
- raea is built natively for Windows on ARM (`raea-0.1.11-windows-arm64.zip`) when its build passes, beside the
release's other archives.
- On a Snapdragon PC, raea picks DirectX 12 for its Adreno GPU, where Vulkan drew 2D pages striped and with grey boxes
behind fading text.
**In the app.**
- Typing to Ideate answers with your own agent (Claude, Codex, or whichever you connected), named on screen while it
thinks, and the conversation stays open instead of fading after a few seconds. raea's own voice model is only for
speaking.
- Talking with Ideate comes with Studio (300 minutes a month) and Enterprise (no limit). Free and Pro type.
- Settings are one page: your workspace's sections, then this computer's (account, plan, sharing, general, storage
and debugging), searched together.
- Signing out on the Mac's workspace signs raea's account out, and the menu names the account you're in.
- A review's player starts with sound, and remembers if you turn it off.
- Every project has a canvas: deliverables, previews and the brief's frames, marked with a region or a point and a
`#tag`, sent back as a note or as edits.
- On Windows, Codex's shell commands run (#244). Codex's elevated sandbox waited on a Windows prompt or failed every
call with "The tool call failed"; raea now starts it with Windows' unelevated sandbox, unless you set your own.
**raea cloud.**
- Boxes move onto each new release, and each box build is stamped with the commit and files it came from.
- An agent's errors go into its run's trace, a runaway render is stopped before it takes the box down, and an agent
waiting on a long render keeps its connection.
- A render sends a project's footage once, known by the file rather than its path.
- `raea words` on a box transcribes with Whisper large-v3, and `raea frames check` measures what a cut's pictures get
wrong (faces cut off, split frames that make no sense).
- Google's AI signs in on the box, in a browser you work from the dashboard.
**Known**
- The Windows on ARM build is checked in CI without drawing: GitHub's ARM64 runner has no GPU raea can draw on. A
Snapdragon PC is where its pictures are checked. If something looks wrong, the x86_64 build still runs there, and
`WGPU_BACKEND=vulkan` or `dx12` chooses the graphics API by hand.
- The Windows app is unsigned, as before: Windows asks once whether to run it (#221).
- On Linux, raea needs a processor with AVX (most from 2011 on) and glibc 2.39 or newer (Ubuntu 24.04, Debian 13,
Fedora 40 and later).
- A proxy set by an automatic configuration (PAC) file isn't read. If yours uses one, start raea with `HTTPS_PROXY`
set.
+244
View File
@@ -0,0 +1,244 @@
@spec
Feature: raea games as playable ads, exported for every ad network from the TSX that renders the video ad
Shane, 2026-10-29: "lets build a playables feature and explore how we can optimize or help raea agents build for
playables specifically as well as explore the export options included with it". A playable ad is a 15-60 second
mini-game served in place of a video ad, inside other apps' WebViews; it ends on a card that opens the store. Bevy
stays the engine for games (docs/web-export.md is raea's own web build); a playable is an export of a game, drawn by
a light web renderer on the same scene contract, because Bevy's renderer doesn't fit an ad (PA0b). The code is
sdk/playable (raea/playable for authors, the browser host, the export tools); the example is
examples/playables/brick-rush.tsx.
Background:
Given the networks that take advertiser playables in 2026, read from each network's own spec on 10-29
| network | package | cap | install call | also |
| AppLovin | one HTML, all inlined (base64/122) | 5 MB | mraid.open(url) | MRAID 2.0; timer starts at the first touch |
| Unity Ads | one index.html, inlined, minified | 5 MB | mraid.open(url) | MRAID 3.0 injected by the webview; start on ready + viewable, pause when not; both orientations |
| Google | ZIP, index.html, at most 512 files | 5 MB | ExitApi.exit() | exitapi.js and <meta name="ad.orientation"> in the head; billed per engagement |
| Meta | one HTML with data URIs, or ZIP | 5 MB | FbPlayableAd.onCTAClick() | no mraid.js; ZIP at most 100 files (blogs that say 2 MB are out of date) |
| Moloco | one HTML with data URIs, no ZIP | 5 MB | FbPlayableAd.onCTAClick() | mraid.js banned |
| Mintegral | ZIP: a folder and a page of one name | 5 MB | window.install() | gameReady() when loaded, gameStart from the network, gameEnd() when over |
| TikTok | ZIP, index.html + config.json | 5 MB zipped | window.openAppStore() | their playable-sdk.js before the game's script; {"playable_orientation": 0/1/2}; no mraid.js |
| Liftoff | one HTML, or ZIP with one folder | 5 MB | Liftoff.open() | relative paths only |
And every network refuses a network request, a redirect without a tap, and sound before the first touch
And ironSource's own network closed on 2026-04-30 (its traffic is Unity LevelPlay's)
Rule: Settled questions
Scenario: PA0a. What a raea playable is
Given a game written as any raea game is: React TSX, its state a pure fold of input (useGameState), its 3D the
SDK's components (which render data-3d elements, the contract the native engine reads)
Then the same file renders with `raea render` as the video ad (no one touches it, so it plays itself) and exports
with `raea playable` as a playable for each network
And it imports raea/playable for the store: <EndCard show={over}> when the game is over, <InstallButton> anywhere,
or install() from a tap; outside an export install() does nothing
And it registers a portrait and a landscape composition when it can (the host plays the one nearest the screen;
a single one is letterboxed, and Unity, AppLovin, Moloco and Mintegral want both)
Scenario: PA0b. Bevy's renderer stays out of ads; a light web renderer draws them (measured 10-29)
Given brick-rush's scene (24 cuboids, paddle, ball, a shadowed directional light) in plain Bevy 0.20 for
wasm32 (opt-level z, fat LTO, wasm-opt -Oz), next to the three.js export of the same game
| build | wasm | one HTML (base64) | zipped |
| Bevy, default features | 23.3 MB | 31.3 MB | 7.4 MB |
| Bevy, the features raea-render turns on | 21.5 MB | 28.7 MB | 6.9 MB |
| Bevy, only what the scene needs (WebGL2) | 12.3 MB | 16.5 MB | 3.7 MB |
| Bevy, only what the scene needs (WebGPU) | 10.8 MB | 14.6 MB | 3.1 MB |
| Bevy logic only (App, ECS, Transform; no renderer) | 0.55 MB | 0.74 MB | 0.2 MB |
| sdk/playable: React + three.js + the game | - | 0.79 MB | 0.22 MB |
And stored gzipped inside the page (DecompressionStream, in every WebView since 2023) the stripped WebGL2 build
is 4.99 MB as base64: under 5 MB with nothing left for raea's own crates, the game or its assets (brotli: 3.4 MB,
but older WebViews can't decompress brotli)
And first frame served from localhost: Bevy 1.9 s, three.js 0.66 s; at 4x CPU throttle 3.2 s and 1.5 s
Then the renderer (wgpu, naga, bevy_pbr) is about 95% of Bevy on the web: logic alone is small
And the industry does the same: Unity Playworks (ex-Luna) never ships Unity's WebGL build; it converts the game's
C# to JavaScript and runs it on its own ~650 KB playable engine; PlayCanvas's engine is ~1.2 MB
And so a playable is drawn by a light WebGL2 renderer on raea's scene contract, its look held to the native
engine's by a parity check (PA9), its shading moving toward Bevy's own (PA10, PA11); Bevy's logic may come along
as wasm (PA12); Bevy wasm stays the path for raea's uncapped web export (docs/web-export.md)
And WebGPU is on by default in iOS 26's WKWebView and reported in Android WebView, but a playable targets WebGL2
for reach
Rule: Built 10-29
@done
Scenario: PA1. The browser host
Then sdk/playable/src/host/main.tsx mounts the registered composition nearest the screen's shape on a stage
scaled uniformly into the screen, steps a Clock 1/fps at a time off requestAnimationFrame with the person's
input recorded per frame as live entries (input.ts: keys, the primary pointer, every finger, in composition
px), and draws the page's data-3d parts with three.js under the page (scene.ts), the page's background behind
the 3D becoming its clear colour
And it starts when the network says the ad is viewable, pauses while it isn't, stops stepping when the game's
EndCard shows, and at the composition's last frame shows its own EndCard
And the status: brick-rush plays in headless mobile Chrome in portrait and landscape; a drag moves the paddle; three
misses show "So close!"; a tap on the card fires end then install (tools/check.ts, PLAY_SECONDS=25)
@done
Scenario: PA2. Each network's start, pause, store and end calls
Then sdk/playable/src/network.ts is built with the network's name (__RAEA_NETWORK__) and the store links, and maps
whenReady, install and end onto the table in the Background (MRAID's ready/viewableChange; Mintegral's
gameReady, gameStart, gameEnd; the store call per network; preview does nothing)
@done
Scenario: PA3. raea/playable for authors
Then install(), end(), <EndCard> (the whole card opens the store; end() when it first shows) and <InstallButton>,
plain page elements, so a native render draws them as the playable does
@done
Scenario: PA4. The lint: what a playable can't have, refused before it is bundled
Then `raea playable` (apps/playable lint.rs, with sdk/playable/src/export/walk.ts run by `raea run`) renders each
composition at 12 frames through its length and refuses a 3D kind the host doesn't draw (PLAYABLE_KINDS in
host/kinds.ts), staticFile, URLs, fetch/XHR/WebSocket, modules that need
the native engine, and <Video>/<Audio> until PA6; it notes a missing raea/playable import and a single
orientation
@done
Scenario: PA5. One export, every network's package
Then `raea playable GAME.tsx -o DIR [--networks ...] [--ios URL] [--android URL] [--title T] [--cta T]
[--orientation O]` lints, bundles one minified script (PA13) and writes each network's page or ZIP, its settings
in a preamble before the script, checked against its cap
And the status: brick-rush exports for all nine targets (eight networks and preview) at 916 KB per HTML and 292 KB
per ZIP (786 and 218 before PA10's tone-mapping table)
@done
Scenario: PA7. A playable played as a phone shows it
Then sdk/playable/tools/check.ts PAGE.html OUT [WxH] opens it at a phone's size with touch (WebKit since PA7b),
drags across it, saves screenshots, reads the console and the ad events back, and fails on an exception or a
network request; CPU_THROTTLE=4 for a slow phone, PLAY_SECONDS to play to the end and tap the card
Rule: Made viable again 11-28
The 11-06 public-first squash took raea/playable and @raea/playable out of the public sdk/tsconfig.base.json (as it
did raea/body and raea/gen), so every export failed at the lint with "Cannot find module 'raea/playable'"
@done
Scenario: PA4b. The tools resolve the SDK's names themselves
Then sdk/playable/tools/alias.ts resolves raea, raea/<module> and @raea/<package> from sdk/tsconfig.base.json's
paths as engine/bundle's script.rs does, plus raea/playable and @raea/playable/*, as a Bun plugin for the bundle
And the lint's walk (tools/walk.ts) runs bundled after the game instead of imported by Bun's runtime, whose own
tsconfig paths ("raea/*") catch raea/playable before any plugin
And a game's own components in a project with no SDK tsconfig bundle as they render (mobile-ads' gates did not)
And the status 11-28: brick-rush exports for all nine targets (1,431 KB per HTML, 471 KB per ZIP); mobile-ads'
tiles (1,393 KB) and gates (1,395 KB) export for AppLovin, Google and preview
@done
Scenario: PA7b. The check plays in WebKit
Given iOS ad WebViews are WebKit, and raea doesn't test in Chrome (Shane 11-15)
Then tools/check.ts plays the page in Playwright's WebKit (playwright-core 1.64.1, the app's version) at a phone's
size with real pointer input held over frames, fails on an exception, a network request, an empty page, or an
end-card tap with no install event; parity.ts draws its still in WebKit too, and tools/chrome.ts is gone
And a network's own page tags (Google's exitapi.js, TikTok's playable-sdk.js) are stopped but not failed: the ad
view serves them
And the status 11-28: brick-rush, tiles and gates play to their end cards, events ["end","install"], no requests
Rule: Next
Scenario: PA6. Sound in a playable
Given networks keep sound off until the first touch and most players never turn it on
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
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
@done @needs:PA1
Scenario: PA9. The playable is held to the native render
Then a parity check renders the same composition frame with `raea render` and in the playable host (headless
Chrome, scripted input none, so both play themselves), and compares the 3D's colours where both drew a part
And it fails when they drift past a bar, so the light renderer can't quietly lose the look
And the status: sdk/playable/tools/parity.ts GAME.tsx COMPOSITION FRAME OUT [BAR] renders the frame with `raea render
--frame`, opens a preview build at the composition's size with #still=FRAME&comp=ID (the host draws that one frame
and stops), and compares the pixels the native frame drew over its background: coverage, mean colours, brightness
and mean difference (0-255), exiting 1 over BAR (default 16); native.png, playable.png and diff.png are kept
@done @needs:PA9
Scenario: PA10. The lighting conversion
Given the SDK's 3D layer hands lights to the renderer in its own units (r3f intensities converted from Bevy's lux,
lumens and cd/m²) and Bevy draws with its camera exposure and TonyMcMapface tone mapping
Then the host converts them so PA9's colours match
And the status: host/scene.ts turns the SDK's intensities back into Bevy's units (lux 8000, lumens 9e5 over 4π,
ambient 400 × π) times Bevy's camera exposure (1 / (1.2 · 2^9.7)); host/tonemap.ts draws the 3D into a half-float
target and maps it through TonyMcMapface, Bevy's own 48³ table (tools/tony.ts reads bevy_core_pipeline's ktx2)
resampled to 32³ sRGB bytes (98 KB; the 48³ table scored 5.3 for 311 KB more), sampled as tonemapping.wesl does;
where nothing was drawn it stays transparent over the page's own background
And the numbers on brick-rush (mean difference / 255, brightness): portrait frame 90 went from 50.2 and 0.688x
(three.js's units, no exposure) to 5.4 and 0.992x; landscape frame 300 is 9.1 and 0.971x. three.js's built-in
curves on the converted units scored Reinhard 14.5, Neutral 21.2, AgX 23.3, none 30.4, ACES 37.9; what is left is
the shading itself (the bricks' side faces a touch darker), PA11's job
@needs:PA9
Scenario: PA11. Bevy's own shading in the light renderer
Then Bevy's PBR shaders, composed for the pipelines a playable uses, are translated to GLSL ES 3.00 with naga at
export time, and the light renderer draws with them instead of three.js's own materials
And the 10-29 trial: Bevy 0.20's shaders are WESL, composed by bevy_shader with wesl 0.6 (defs as feature flags,
Int/UInt defs in a virtual `constants` package, `bevy_pbr/bevy_core_pipeline` folded to `bevy_core_pipeline`). A
standalone program doing the same over the registry sources, then naga 30 (validate, GLSL ES 3.00 for WebGL),
with WebGL2's defs (WEBGL2, NO_ARRAY_TEXTURES_SUPPORT, NO_CUBE_ARRAY_TEXTURES_SUPPORT, SIXTEEN_BYTE_ALIGNMENT,
AVAILABLE_STORAGE_BUFFER_BINDINGS=0, MAX_CASCADES_PER_LIGHT=1, PER_OBJECT_BUFFER_BATCH_SIZE=93 for the 176-byte
Mesh in 16 KB) and the mesh pipeline's for a plain forward StandardMaterial mesh with TonyMcMapface in the shader:
| shader | GLSL ES 3.00 | gzip | in Chrome's WebGL2 |
| bevy_pbr::render::pbr frag | 1,703 lines, 88 KB | 16 KB | compiles (29 ms) |
| bevy_pbr::render::mesh vert | 175 lines, 6.8 KB | 1.7 KB| compiles; the pair links (551 ms) |
| bevy_pbr::prepass (shadows) | 150 lines, 5.5 KB, vertex | | translated, not linked yet |
And what that leaves: nothing has been drawn with them. The program binds 7 textures (4 material maps, the point
and directional shadow maps, the Tony LUT) and 11 uniform blocks the host would fill as Bevy's render world does:
View (784 B), Lights (2,176 B), the cluster offsets, index lists and clustered lights (16 KB each, so the host
clusters lights on the CPU as Bevy does on WebGL2), the StandardMaterial (192 B), the Mesh batch and Globals.
That packing, and the shadow passes, are PA11's real work; the shaders themselves come over unchanged
Scenario: PA12. Bevy systems in a playable
Given Bevy's logic alone is 0.2 MB gzipped as wasm (PA0b)
Then a game whose rules are Rust (raea/ecs's world, behind the ecs.* native calls) runs them in wasm in the
playable, its world drawn by the light renderer
@done
Scenario: PA13. `raea playable`
Then the export is a raea CLI verb (apps/playable) on raea's own bundler, in process: engine/bundle gained
`minify` (Rolldown's minifier), `inline` (inline.rs: pictures, sounds, fonts and .glb as data URLs, a .bin as a
Uint8Array) and package-folder aliases (`--alias three/=DIR`, three.js from the project's node_modules, else
raea's own)
And the lint's walk runs as `raea run` in a process of its own; tools/playable.sh, bundle.ts, lint.ts, walk.ts,
alias.ts and chrome.ts are gone, and Bun is needed only for check.ts, parity.ts and tony.ts
And the status 11-28: brick-rush writes all nine targets in 7 s (1,384 KB per HTML, 464 KB per ZIP), mobile-ads'
tiles (1,345 KB) and gates (1,347 KB) export, and all play in WebKit, the Google and TikTok packages included;
a game with staticFile is refused with the reason first
And fonts travel as pictures do: an imported .ttf, .otf, .woff or .woff2 is its path in a native render and a data
URL in a playable, named in an @font-face; <EndCard> takes font, color and button for a brand's own card
Scenario: PA14. Agents writing playables
Then the raea skill says how a playable is shaped (hook, a hand until the first touch, a fail moment, the end card
within 30-60 s, both orientations), what the lint refuses, and how to check one (tools/check.ts)
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
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)
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
in raea cloud and in desktop v3, and a playable is one HTML page that loads nothing
Then a "playable" kind is drawn by that player: the preview page in a sandboxed iframe (allow-scripts only) inside
a phone frame, portrait and landscape, restarted from the stage's own button
And the host's ad events (ready, viewable, end, install) show beside it, so a reviewer sees the store tap fire
And each network's package, its size against the cap, is a download under it, and pins and notes work as on a video
And `raea show GAME.tsx --playable` exports the preview and shows it as that kind (`raea show PAGE.html` for a page
already exported); host/show.ts refuses .html today
# Status 11-28: built. Cloud: raea-platform #99 (merged into #97's oux-audit-1128) and #101: the playable kind
# (a delivered .html), its 9:16 card, the phone either way up with Restart, the events (ready, viewable,
# hidden, first touch, end card, store opened), and the network packages folded under it as downloads, red
# past 5 MB. Shane 11-28: the page plays on a domain of its own: play.raea.io, live 11-28 (#105, #106:
# PLAY_HOST, harness/play.ts: sandbox allow-scripts, 'wasm-unsafe-eval', network off, no-transform, framed by
# app.raea.cloud, api.raea.cloud and the desktop's local port). Checked live: the ACANA export uploaded, played
# from play.raea.io in a sandboxed frame in WebKit, ready and touch posted, the bytes as exported.
# Desktop: raea-feed #124: `raea show PAGE.html` posts a play item with a page, /host/playable serves it under
# the same policy, Playable.tsx draws it with pins. `raea show GAME.tsx --playable` exports the preview first
# (engine/cli show.ts, native.ts). Checked: the real ACANA export served under the policy runs clean in WebKit.
Scenario: PA17. Video ad and playable side by side
Then one shown game is both: its `raea render` (the video ad, played by its own hand) and its playable, one
project in the review, so a creative test brief gets both formats from one file
Scenario: PA18. brick-rush plays live in the native engine
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
+2
View File
@@ -20,6 +20,8 @@ rolldown = "=1.2.12"
# CSS imports and CSS modules (A2): @imports inlined, nesting and newer syntax lowered for Stylo
lightningcss = { version = "=1.0.0-alpha.72", features = ["bundler"] }
anyhow = "1"
# imported files carried in a playable's script as data (inline.rs)
base64 = "0.22"
# the Z3 compile (z3.rs, a live bundle's TSX): oxc as Rolldown 1.2.12 uses it
oxc = { version = "=0.152.0", features = ["transformer", "codegen", "semantic", "ast_visit"] }
tokio = { version = "1", features = ["rt-multi-thread"] }
+72
View File
@@ -0,0 +1,72 @@
//! A bundle that carries its files (docs/playables.feature PA13): a picture, sound or model a module imports becomes a
//! data URL in the script, and a `.bin` table its bytes, so the one page loads nothing (an ad network refuses a page
//! that makes a request). Ahead of the script resolver, which otherwise hands media back as their paths.
use rolldown_common::ModuleType;
use rolldown_plugin::{HookLoadArgs, HookLoadOutput, HookLoadReturn, HookUsage, Plugin, SharedLoadPluginContext};
use std::borrow::Cow;
use std::path::Path;
/// The files carried, by extension, with their media type
const TYPES: &[(&str, &str)] = &[
("png", "image/png"),
("jpg", "image/jpeg"),
("jpeg", "image/jpeg"),
("webp", "image/webp"),
("gif", "image/gif"),
("svg", "image/svg+xml"),
("mp3", "audio/mpeg"),
("m4a", "audio/mp4"),
("ogg", "audio/ogg"),
("wav", "audio/wav"),
("glb", "model/gltf-binary"),
("woff2", "font/woff2"),
("woff", "font/woff"),
("ttf", "font/ttf"),
("otf", "font/otf"),
];
#[derive(Debug)]
pub struct Inline;
/// Standard base64, padded (the base64 crate, as raea's other crates use it)
pub fn base64(bytes: &[u8]) -> String {
use base64::Engine;
base64::engine::general_purpose::STANDARD.encode(bytes)
}
impl Plugin for Inline {
fn name(&self) -> Cow<'static, str> {
Cow::Borrowed("raea:inline")
}
fn register_hook_usage(&self) -> HookUsage {
HookUsage::Load
}
async fn load(&self, _ctx: SharedLoadPluginContext, args: &HookLoadArgs<'_>) -> HookLoadReturn {
let path = args.id.split(['?', '#']).next().unwrap_or(args.id);
let Some(ext) = Path::new(path).extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase) else { return Ok(None) };
let code = if ext == "bin" {
let b = std::fs::read(path)?;
format!("export default Uint8Array.from(atob({:?}), (c) => c.charCodeAt(0));\n", base64(&b))
} else if let Some((_, mime)) = TYPES.iter().find(|(e, _)| *e == ext) {
let b = std::fs::read(path)?;
format!("export default {:?};\n", format!("data:{mime};base64,{}", base64(&b)))
} else {
return Ok(None);
};
Ok(Some(HookLoadOutput { code: code.into(), module_type: Some(ModuleType::Js), ..Default::default() }))
}
}
#[cfg(test)]
mod tests {
#[test]
fn base64_pads_as_the_standard_does() {
assert_eq!(super::base64(b""), "");
assert_eq!(super::base64(b"f"), "Zg==");
assert_eq!(super::base64(b"fo"), "Zm8=");
assert_eq!(super::base64(b"foo"), "Zm9v");
assert_eq!(super::base64(b"foobar"), "Zm9vYmFy");
}
}
+12 -2
View File
@@ -16,6 +16,7 @@ use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
pub mod edit;
pub mod inline;
pub mod script;
pub mod stamp;
pub mod z3;
@@ -41,6 +42,10 @@ pub struct Options {
pub edit: Option<edit::Edit>,
/// each element the edit's own files write stamped with its place in the code (stamp.rs; the app's editor asks)
pub stamps: bool,
/// minified (a playable's page, which ad networks cap at 5 MB)
pub minify: bool,
/// imported pictures, sounds, models and .bin tables carried in the script (inline.rs), not named by path
pub inline: bool,
}
/// `entry` bundled into one browser script and its CSS.
@@ -61,6 +66,7 @@ pub fn bundle_with(entry: &Path, o: Options) -> Result<Bundle, String> {
// no `//#region <path>` before each module: its path names the work folder (raea-motion-b<pid>), so every
// process's bundle differed and the incremental bake saw every function change (lightspeed T3)
experimental: Some(ExperimentalOptions { attach_debug_info: Some(AttachDebugInfo::None), ..Default::default() }),
minify: o.minify.then_some(rolldown_common::RawMinifyOptions::Bool(true)),
..Default::default()
};
let stamps = if o.stamps {
@@ -84,6 +90,9 @@ pub fn bundle_with(entry: &Path, o: Options) -> Result<Bundle, String> {
s.spawn(move || {
rt.block_on(async move {
let mut plugins = vec![Pluginable::new_shared(css)];
if o.inline {
plugins.push(Pluginable::new_shared(inline::Inline));
}
if let Some(s) = stamps {
plugins.push(Pluginable::new_shared(s));
}
@@ -320,7 +329,7 @@ pub mod ffi {
1
}
/// `entry` (a path, UTF-8) bundled with `opts` (JSON: {"z3": bool, "edit": {"dir", "js"}, "script": {..}, "defines", "stamps": bool}); returns JSON, {"js","css"} or {"error"}, to
/// `entry` (a path, UTF-8) bundled with `opts` (JSON: {"z3": bool, "edit": {"dir", "js"}, "script": {..}, "defines", "stamps": bool, "minify": bool, "inline": bool}); returns JSON, {"js","css"} or {"error"}, to
/// be freed with raea_bundle_free
///
/// # Safety
@@ -344,7 +353,8 @@ pub mod ffi {
js: path(&e["js"]),
work: std::path::absolute(&entry).ok().and_then(|p| p.parent().map(|d| d.to_path_buf())).unwrap_or_default(),
});
let o = super::Options { z3: opts["z3"].as_bool().unwrap_or(false), script, defines, edit, stamps: opts["stamps"].as_bool().unwrap_or(false) };
let (minify, inline) = (opts["minify"].as_bool().unwrap_or(false), opts["inline"].as_bool().unwrap_or(false));
let o = super::Options { z3: opts["z3"].as_bool().unwrap_or(false), script, defines, edit, stamps: opts["stamps"].as_bool().unwrap_or(false), minify, inline };
match super::bundle_with(std::path::Path::new(&entry), o) {
Ok(b) => serde_json::json!({"js": b.js, "css": b.css}),
Err(e) => serde_json::json!({"error": e}),
+14 -4
View File
@@ -23,7 +23,8 @@ pub struct Script {
pub motion: PathBuf,
/// sdk/shell/src/index.ts
pub shell: PathBuf,
/// `--alias SPEC=PATH`
/// `--alias SPEC=PATH`; a SPEC ending in `/` (`three/=DIR`) is a package and every subpath of it, resolved from DIR
/// (a folder whose node_modules holds it) wherever it's imported, so the bundle has one copy
pub aliases: HashMap<String, PathBuf>,
/// `--node-stub a,b`
pub stubs: Vec<String>,
@@ -36,8 +37,9 @@ const NODE: &[&str] = &[
];
const STUB: &str = "\0raea-node-stub:";
/// Files a script imports as their path (sdk/react's MEDIA_EXTS, as a composition imports them), plus models.
const MEDIA: &[&str] = &["mp4", "mov", "m4v", "mp3", "wav", "m4a", "png", "jpg", "webp", "gif", "glb", "gltf"];
/// Files a script imports as their path (sdk/react's MEDIA_EXTS, as a composition imports them), plus models and fonts
/// (an @font-face's url(), so a playable can carry the same font: inline.rs).
const MEDIA: &[&str] = &["mp4", "mov", "m4v", "mp3", "wav", "m4a", "png", "jpg", "jpeg", "webp", "gif", "glb", "gltf", "ttf", "otf", "woff", "woff2"];
#[derive(Debug)]
@@ -46,7 +48,12 @@ pub struct ScriptResolve(pub Script);
impl ScriptResolve {
/// `spec` as the engine's node_modules resolves it (Rolldown's resolver, from a file in sdk/react/js)
async fn from_engine(&self, ctx: &PluginContext, spec: &str) -> anyhow::Result<Option<HookResolveIdOutput>> {
let importer = self.0.js.join("_raea.js");
self.from_dir(ctx, spec, &self.0.js).await
}
/// `spec` as `dir`'s node_modules resolves it
async fn from_dir(&self, ctx: &PluginContext, spec: &str, dir: &Path) -> anyhow::Result<Option<HookResolveIdOutput>> {
let importer = dir.join("_raea.js");
let opts = rolldown_plugin::PluginContextResolveOptions { skip_self: true, ..Default::default() };
match ctx.resolve(spec, Some(&importer.to_string_lossy()), Some(opts)).await? {
Ok(r) => Ok(Some(HookResolveIdOutput::from_id(r.id.as_str()))),
@@ -84,6 +91,9 @@ impl Plugin for ScriptResolve {
if let Some(p) = s.aliases.get(spec) {
return Ok(path_id(p));
}
if let Some((_, dir)) = s.aliases.iter().find(|(k, _)| k.strip_suffix('/').is_some_and(|pkg| spec == pkg || spec.starts_with(k.as_str()))) {
return self.from_dir(ctx, spec, dir).await;
}
match spec {
"bun:test" | "vitest" | "@jest/globals" => return Ok(path_id(&s.js.join("shims/test.ts"))),
"@raea/shell" => return Ok(path_id(&s.shell)),
+2 -2
View File
@@ -133,7 +133,7 @@ import { version } from "react";
aliases: [("~lib".to_string(), d.join("lib/aliased.ts"))].into_iter().collect(),
stubs: vec!["fs".into()],
};
let o = raea_bundle::Options { z3: false, script: Some(script.clone()), defines: vec![("FLAG".into(), "\"ON\"".into())], edit: None, stamps: false };
let o = raea_bundle::Options { z3: false, script: Some(script.clone()), defines: vec![("FLAG".into(), "\"ON\"".into())], edit: None, stamps: false, ..Default::default() };
let b = raea_bundle::bundle_with(&d.join("work/entry.ts"), o).expect("bundles");
for want in ["MOTION_INDEX", "MOTION_ECS", "MOTION_PRELUDE", "TEST_SHIM:", "ZLIB_SHIM", "ALIASED", "ENGINE_REACT", "isn't available in raea's V8", "\"ON\""] {
assert!(b.js.contains(want), "{want} in the bundle: {}", b.js);
@@ -141,7 +141,7 @@ import { version } from "react";
assert!(!b.js.contains("OTHER_REACT"), "one React: the engine's");
// a Node built-in raea doesn't carry, not listed as a stub: the bundle fails, naming it
w("work/bad.ts", "import { createServer } from \"http\";\nconsole.log(createServer);\n");
let e = raea_bundle::bundle_with(&d.join("work/bad.ts"), raea_bundle::Options { z3: false, script: Some(script), defines: vec![], edit: None, stamps: false }).expect_err("http isn't carried");
let e = raea_bundle::bundle_with(&d.join("work/bad.ts"), raea_bundle::Options { z3: false, script: Some(script), defines: vec![], edit: None, stamps: false, ..Default::default() }).expect_err("http isn't carried");
assert!(e.contains("\"http\" is a Node built-in") && e.contains("--node-stub http"), "{e}");
let _ = std::fs::remove_dir_all(&d);
}
+2
View File
@@ -85,6 +85,8 @@ raea-app-media = { path = "../../apps/media" }
# `raea app run|check|bundle` and `raea rune` on either target (docs/targets.feature T0b)
raea-app-targets = { path = "../../apps/targets" }
raea-app-game = { path = "../../apps/game" }
# `raea playable`: a game as a playable ad for each network (docs/playables.feature PA13)
raea-app-playable = { path = "../../apps/playable" }
raea-app-capcut = { path = "../../apps/capcut" }
raea-app-layers = { path = "../../apps/layers" }
raea-app-play = { path = "../../apps/play", features = ["ml"] }
+72
View File
@@ -110,3 +110,75 @@ describe("labelsIn", () => {
expect(() => labelsIn('{"text":"a"}', "l.json")).toThrow(/--labels l.json is a list of labels/);
});
});
// Shane 11-28: "some things I'm not approving, I'm just acknowledging"; "the agent can go 'let me add a label here'".
// --fyi and --group go to the host (apps/app host/show.ts ShowBody.intent, .groups), which hands them to the review.
describe("raea show --fyi and --group", () => {
const run = (args: string[]) => {
const ops: [string, Record<string, unknown>][] = [];
const ask = (op: string, b: Record<string, unknown>) => {
ops.push([op, b]);
if (op === "harness") return { name: "Claude Code", pid: 7 };
return { kind: "item", id: "i-1", type: "look", title: "Lobby", project: "shop", workspace: "Work", inbox: "/inbox.jsonl" };
};
const out = showVerb(ask, args, "/work/shop", { CLAUDECODE: "1", CLAUDE_CODE_SESSION_ID: "abcdef123" });
return { out, body: ops.find(([op]) => op === "show")?.[1] };
};
test("--fyi sends a look-only show, and says nothing waits on it", () => {
const { out, body } = run(["lobby.png", "--fyi"]);
expect(body).toMatchObject({ intent: "fyi", files: ["/work/shop/lobby.png"] });
expect(out).toContain(`{"kind":"seen"}`);
expect(run(["lobby.png"]).body?.intent).toBeUndefined();
});
test("each --group holds the files after it, titled before the colon and said after it", () => {
const { body } = run(["--group", "Day: sun through the doors", "a.png", "b.png", "--group", "Night", "c.png", "--title", "Lobby"]);
expect(body?.files).toEqual(["/work/shop/a.png", "/work/shop/b.png", "/work/shop/c.png"]);
expect(body?.groups).toEqual([
{ title: "Day", says: "sun through the doors", files: ["/work/shop/a.png", "/work/shop/b.png"] },
{ title: "Night", files: ["/work/shop/c.png"] },
]);
expect(run(["a.png"]).body?.groups).toBeUndefined();
});
test("a group with no files, or --fyi on a question, is refused", () => {
expect(() => run(["a.png", "--group", "Empty"])).toThrow(/has no files/);
expect(() => run(["--group", ": no title", "a.png"])).toThrow(/is a title/);
expect(() => run(["--question", "Which?", "--choice", "A", "--choice", "B", "--fyi"])).toThrow(/--fyi/);
});
});
// --playable exports a game's preview (native.ts playable: raea playable --networks preview) and shows that page, which
// the app plays in a phone (apps/app host/playable.ts, docs/playables.feature PA16)
describe("raea show --playable", () => {
const run = (args: string[]) => {
const ops: [string, Record<string, unknown>][] = [];
const ask = (op: string, b: Record<string, unknown>) => {
ops.push([op, b]);
if (op === "harness") return { name: "Claude Code", pid: 7 };
if (op === "playable") return { page: "/tmp/raea-playable-x/acana-preview.html" };
return { kind: "item", id: "i-1", type: "play", title: "Acana", project: "ads", workspace: "Work", inbox: "/inbox.jsonl" };
};
showVerb(ask, args, "/work/ads", { CLAUDECODE: "1", CLAUDE_CODE_SESSION_ID: "abcdef123" });
return { exported: ops.find(([op]) => op === "playable")?.[1], body: ops.find(([op]) => op === "show")?.[1] };
};
test("the game is exported, and its preview page is what's shown, titled from it", () => {
const { exported, body } = run(["compositions/acana.tsx", "--playable"]);
expect(exported).toMatchObject({ file: "/work/ads/compositions/acana.tsx" });
expect(body).toMatchObject({ files: ["/tmp/raea-playable-x/acana-preview.html"], title: "Acana" });
expect(run(["acana.tsx", "--playable", "--title", "ACANA catch"]).body?.title).toBe("ACANA catch");
});
test("it takes one game's .tsx and nothing else", () => {
expect(() => run(["a.tsx", "b.tsx", "--playable"])).toThrow(/one game's \.tsx/);
expect(() => run(["cut.mp4", "--playable"])).toThrow(/one game's \.tsx/);
});
test("without it a .tsx is shown as it is", () => {
const { exported, body } = run(["picker.tsx"]);
expect(exported).toBeUndefined();
expect(body?.files).toEqual(["/work/ads/picker.tsx"]);
});
});
+5 -5
View File
@@ -134,7 +134,7 @@ pub fn run(args: &[String]) -> R<String> {
IN_HELP.set(was);
// `raea library` (engine/cli/src/library.ts) and `raea show` (show.ts: in the raea app, not Preview, Shane 11-09), under render's usage
let usage = format!("{usage}\n raea library [new NAME [--cloud] | add LIBRARY PATH | files LIBRARY | tag SHA TAGS | status | scan ...] | raea library search \"WORDS\" [--library LIBRARY] [--kind KIND] [--limit N] [--sound] (the person's libraries in the raea app: folders and drives indexed on this machine, searched by meaning; a folder an agent adds waits for the person's yes)");
let usage = format!("{usage}\n raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] [--label LABEL] [--detail PARAGRAPH] [--labels FILE.json] [--despite CHECK WHY] | raea show --question Q --choice A --choice B [STILL...] | raea show [--title T] --question Q [--preview FILE] --choice A [--preview FILE] --choice B ... [--question Q2] ... | raea show --on ITEM [--working ID] [--ask TEXT] [--status S] [--states S1,S2] [--sign N --clip FILE --render HASH] [--done ID] [--note LINE] [--sub NAME] (shown in the raea app as an item the person can use and answer, posted quietly with a notice, the window left where they are unless --open: stills (several, a storyboard), a video, a sound, a NAME.script.ts or .md, a .tsx (an interactive artifact; a project's composition opens in its editor), or questions, all of them one item; --label \"PLACE TAG\" a label beside the picture, never on it, that points at PLACE (x0,y0,x1,y1 or x,y in its 0-1, then #N the Nth file, @T or @T-TO a film's seconds, or part=KEY a scene's part; the tag the rest), --detail the paragraph of the --label before it, --labels a JSON list of them as feed_post takes them, and a sheet raea media sheet made comes labelled; each question and choice with a --preview to play or read while answering (a still, a video, a sound, a script or .md; after a --choice that choice's, else the question's); what they send comes to ~/.raea/inbox/INBOX.jsonl; their edit comments are tasks: --working ID as you start one (each --ask with it one ask you read it as, for the person to correct; --status and --states where the note and each ask stand: to restate, to check, failing, to sign, passing, signed; --sign N --clip FILE --render HASH a clip under ask N for them to sign; a note closes when they retire it, never with --done), --done ID when it's settled, or with the version that settles it, FILE --replaces ITEM --done ID; never open media in Preview while the app is installed)");
let usage = format!("{usage}\n raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] [--playable] [--label LABEL] [--detail PARAGRAPH] [--labels FILE.json] [--despite CHECK WHY] | raea show --question Q --choice A --choice B [STILL...] | raea show [--title T] --question Q [--preview FILE] --choice A [--preview FILE] --choice B ... [--question Q2] ... | raea show --on ITEM [--working ID] [--ask TEXT] [--status S] [--states S1,S2] [--sign N --clip FILE --render HASH] [--done ID] [--note LINE] [--sub NAME] (shown in the raea app as an item the person can use and answer, posted quietly with a notice, the window left where they are unless --open: stills (several, a storyboard), a video, a sound, a NAME.script.ts or .md, a .tsx (an interactive artifact; a project's composition opens in its editor), a playable ad's NAME-preview.html (played in a phone, sandboxed; --playable exports a game's .tsx with raea playable and shows that), or questions, all of them one item; --label \"PLACE TAG\" a label beside the picture, never on it, that points at PLACE (x0,y0,x1,y1 or x,y in its 0-1, then #N the Nth file, @T or @T-TO a film's seconds, or part=KEY a scene's part; the tag the rest), --detail the paragraph of the --label before it, --labels a JSON list of them as feed_post takes them, and a sheet raea media sheet made comes labelled; each question and choice with a --preview to play or read while answering (a still, a video, a sound, a script or .md; after a --choice that choice's, else the question's); what they send comes to ~/.raea/inbox/INBOX.jsonl; their edit comments are tasks: --working ID as you start one (each --ask with it one ask you read it as, for the person to correct; --status and --states where the note and each ask stand: to restate, to check, failing, to sign, passing, signed; --sign N --clip FILE --render HASH a clip under ask N for them to sign; a note closes when they retire it, never with --done), --done ID when it's settled, or with the version that settles it, FILE --replaces ITEM --done ID; never open media in Preview while the app is installed)");
// clothes for SOMA's body, sewn or laid on the skin (docs/character.feature CH45c): engine/cli/src/clothes.ts, wardrobe.ts and sewn.ts
let usage = format!("{usage}\n raea clothes [make NAME [\"WHAT IT IS\"] [--plain] [--set PATH=VALUE,...] [--colour #RRGGBB] | settings | cover NAME --parts PART[:SHARE],... --colour #RRGGBB [--stand MM] [--over UNDER] [--hard [--sole MM] [--sole-colour #RRGGBB] [--panels #RRGGBB,...]] | wear OUT_DIR GARMENT... [--body DIR] [--head HEAD_DIR]] (clothes for SOMA's body from words: make sews a garment: a sewing pattern (GarmentCode, MIT) from the words, or the plain base with --plain, its settings changed by --set PATH=VALUE (settings lists them and what each may be), cut to SOMA's measurements, draped by raea's own cloth and baked, as assets/clothes/NAME.json and its .glb, in --colour or the palette's next; the first make sets up GarmentCode and its Python in raea's models folder; cover makes one by procedure in the same file, no picture: the skin of the parts named (hips, waist, torso, chest, neck, head, upperArm, foreArm, hand, thigh, shin, foot, toes; a limb's SHARE is how far along it from its top), in one colour, MM off the skin (6 unless said), --over a garment already made as the one under it; wear puts garments on a body, innermost first (each GARMENT a name or its .json): OUT_DIR/NAME.glb each, with OUT_DIR/body.glb the body without the skin wholly under cloth; --body DIR another SOMA body folder (a headless one for a head part); --head HEAD_DIR the head that joins it (head.json), whose skin the body's is graded to at the collar; alone, the project's garments. The first use fetches SOMA's body (NVlabs/SOMA-X, Apache-2.0) into raea's models folder and needs Blender: raea setup blender)");
// body motion made by Kimodo, on MLX on a Mac and on PyTorch elsewhere (docs/character.feature CH15c):
@@ -147,7 +147,7 @@ pub fn run(args: &[String]) -> R<String> {
let usage = format!("{usage}\n raea spec FILE.ts [--as brief|script|taste|parts] (a spec's default export as JSON, checked against its schema: brief.ts, script.ts, taste.ts, NAME.parts.ts)\n raea workspace init [NAME] [--layout LAYOUT] | raea workspace adopt DIR [--name NAME] | raea workspace [--json] (a workspace: a git repo of projects under raea.root, ~/Documents/raea unless git config says)\n raea project new NAME [--storage inline|submodule] [--client NAME] | raea project tag [NAME] [--client NAME] [--no-client] | raea project split NAME [--remote URL] | raea project join NAME | raea project [--json] (a project in the workspace: its folder, brief.ts, media/, out/; its client, what raea.app files every card shown from it under (raea cloud's tags: projects don't nest); split and join keep its history)\n raea check EDIT.tsx --quick [--shape S] [--platform P] [--taste T] [-o check.json] (three stills of a composition checked for text: clipped, cramped, safe areas, sizes; about a second)\n raea hook [claude|codex|gemini|kimi] (every agent's tool hooks, which raea skills install adds: before a shell command, media opened in the Mac's viewer while the raea app is installed is stopped once for raea show (the same command again goes through); after a save, the quick check on a composition)\n raea next [DIR] (the two or three useful next steps for the project, from its brief, compositions, renders and checks)\n raea doctor [--fix] [DIR] (what doesn't match this raea: old brief files, an older workspace format, an agent's skill from another version)\n raea app run|check|bundle APP.tsx [--target web|native] [--size WxH] [--script steps.json] [--png DIR] [-o App.app] (a TSX app on @raea/ui: its window, the headless check, a Mac app; web is Blitz on Bevy, native is Rune; the app's `export const app` sets the target, web when it doesn't; raea rune ... is --target native)\n {}\n {}\n {} ({})\n {}\n {}\n {}", skill::USAGE, tools::blender::USAGE, tools::motion::SETUP_USAGE, tools::motion::SETUP_ABOUT, raea_app_engines::godot::USAGE, raea_app_engines::shot::USAGE, raea_app_engines::round::USAGE);
let (export_game, capcut, layers, xml, scene, physics, splat, wear, bake) = (raea_app_game::USAGE, raea_app_capcut::USAGE, raea_app_layers::USAGE, raea_app_layers::USAGE_XML, raea_app_scene::USAGE, motion::physics::USAGE, tools::splat::USAGE, raea_runtime_wear::USAGE, raea_app_lightbake::USAGE);
let apps = format!(" {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n", raea_app_direction::check::USAGE, raea_app_check::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, raea_app_ask::USAGE, raea_app_make::USAGE, raea_app_direction::USAGE, raea_app_direction::findings::USAGE, raea_app_notes::USAGE, raea_app_fingerprint::USAGE, raea_sys_index::cli::USAGE);
return Ok(format!("raea: renders, plays and checks raea compositions (React and TypeScript) on the GPU.\n\nusage: {usage}\n raea init (a project's files where they're missing: edit.tsx, cuts.ts, components/, AGENTS.md)\n raea cut TAKE \"line\" ... | --at A-B ... [--append] (cuts.ts and words.json: a take under media/ cut in the pauses around each line it says, transcribed first if it has no TAKE.words.json; or at those seconds)\n raea frame TAKE [--at S] (how a take fits the edit: a talking take for <FaceFrame>, a screen for <ScreenFit>, from where its face is)\n raea component list | raea component add NAME ... [--shared] [--force] | raea part list | raea part add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; raea part is its old name)\n raea brand DOMAIN|URL (the brand kit read from its website on this machine: brand/brand.css, brand/brand.json, BRAND.md, logos in media/brand; says when a plain fetch saw too little)\n raea guide [NAME] (craft, the floor read before any edit; the modes: pitch, explain, story, play, tool; motion, music, layout and the rest; bevy and bevy/NAME for 3D)\n raea context PROJECT (what to read before working on a project: taste, brief, look, the floor and its modes' guides)\n{apps} raea play EDIT.tsx [--input | --input-script KEYS.json] [--size WxH] [--seconds N|end] (a game, live; also: --input-log FILE --offscreen --snapshot T FILE --json FILE --seek F FILE --pick X,Y --view YAW,PITCH,DISTANCE --scrub N --baked --autoplay --no-vsync --master --3d)\n {export_game} (a game as a program of its own: a Mac app or a command)\n {capcut}\n {layers}\n {xml}\n {scene} (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)\n {physics} (the bakes <Physics> and <Goo> make)\n {bake}\n {wear} (a .glb's weathering causes for raea/wear: the model with a second UV set and its cause maps, made once in the asset store)\n {splat} (footage trained into a Gaussian splat for <Splat>; setup installs its tools)\n raea run SCRIPT.ts (a TypeScript program on the engine, headless: its default export is called, what it prints is the answer; a check like a room's checkLayout; also: --timeout S)\n raea gen image|video|music|sfx|speech|mesh|text \"PROMPT\" | gen plan|run FLOW.ts|FLOW.json | gen comfy import|export|run|schema FILE | gen models | gen balance (generated media through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI; ComfyUI workflows both ways: raea gen alone lists its flags)\n {neural_usage} (DLSS 5 neural rendering on a `render --aov` folder, with its motion and depth: your own MLX-DLSS build and weights, RAEA_MLXDLSS and RAEA_DLSS_MODEL)\n {light_usage} (each scene on each light path against its path-traced reference: distance in stops, the worst tile, a moving shot's flicker, a frame's cost; DIR/report.json)\n {} (each case on each denoiser against its converged truth: FLIP, RMSE, bias, flicker, blotches, lag after a disocclusion or a light going out, a frame's cost, and how many of MetalFX's numbers each meets; DIR/report.json)\n raea mezz [--check] PATH... (an intra-only ProRes copy of each long-GOP source over 1080p, for smooth scrubbing; --check says which would get one)\n raea traces [show [N|last|DIR]] (the sessions raea left, newest first: how each ended, its glitches; show tells one in full)", raea_denoise_bench::USAGE));
return Ok(format!("raea: renders, plays and checks raea compositions (React and TypeScript) on the GPU.\n\nusage: {usage}\n raea init (a project's files where they're missing: edit.tsx, cuts.ts, components/, AGENTS.md)\n raea cut TAKE \"line\" ... | --at A-B ... [--append] (cuts.ts and words.json: a take under media/ cut in the pauses around each line it says, transcribed first if it has no TAKE.words.json; or at those seconds)\n raea frame TAKE [--at S] (how a take fits the edit: a talking take for <FaceFrame>, a screen for <ScreenFit>, from where its face is)\n raea component list | raea component add NAME ... [--shared] [--force] | raea part list | raea part add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; raea part is its old name)\n raea brand DOMAIN|URL (the brand kit read from its website on this machine: brand/brand.css, brand/brand.json, BRAND.md, logos in media/brand; says when a plain fetch saw too little)\n raea guide [NAME] (craft, the floor read before any edit; the modes: pitch, explain, story, play, tool; motion, music, layout and the rest; bevy and bevy/NAME for 3D)\n raea context PROJECT (what to read before working on a project: taste, brief, look, the floor and its modes' guides)\n{apps} raea play EDIT.tsx [--input | --input-script KEYS.json] [--size WxH] [--seconds N|end] (a game, live; also: --input-log FILE --offscreen --snapshot T FILE --json FILE --seek F FILE --pick X,Y --view YAW,PITCH,DISTANCE --scrub N --baked --autoplay --no-vsync --master --3d)\n {export_game} (a game as a program of its own: a Mac app or a command)\n {} ({})\n {capcut}\n {layers}\n {xml}\n {scene} (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)\n {physics} (the bakes <Physics> and <Goo> make)\n {bake}\n {wear} (a .glb's weathering causes for raea/wear: the model with a second UV set and its cause maps, made once in the asset store)\n {splat} (footage trained into a Gaussian splat for <Splat>; setup installs its tools)\n raea run SCRIPT.ts (a TypeScript program on the engine, headless: its default export is called, what it prints is the answer; a check like a room's checkLayout; also: --timeout S)\n raea gen image|video|music|sfx|speech|mesh|text \"PROMPT\" | gen plan|run FLOW.ts|FLOW.json | gen comfy import|export|run|schema FILE | gen models | gen balance (generated media through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI; ComfyUI workflows both ways: raea gen alone lists its flags)\n {neural_usage} (DLSS 5 neural rendering on a `render --aov` folder, with its motion and depth: your own MLX-DLSS build and weights, RAEA_MLXDLSS and RAEA_DLSS_MODEL)\n {light_usage} (each scene on each light path against its path-traced reference: distance in stops, the worst tile, a moving shot's flicker, a frame's cost; DIR/report.json)\n {} (each case on each denoiser against its converged truth: FLIP, RMSE, bias, flicker, blotches, lag after a disocclusion or a light going out, a frame's cost, and how many of MetalFX's numbers each meets; DIR/report.json)\n raea mezz [--check] PATH... (an intra-only ProRes copy of each long-GOP source over 1080p, for smooth scrubbing; --check says which would get one)\n raea traces [show [N|last|DIR]] (the sessions raea left, newest first: how each ended, its glitches; show tells one in full)", raea_app_playable::USAGE, raea_app_playable::ABOUT, raea_denoise_bench::USAGE));
}
// `--version`: the release's version, which a skill's front matter names (docs/skills.feature SK6)
if args.len() == 1 && matches!(args[0].as_str(), "--version" | "-V") {
@@ -228,9 +228,9 @@ pub fn run(args: &[String]) -> R<String> {
// `export capcut EDIT.tsx` (a CapCut draft) and `render ... -o OUT.mov --alpha` (a transparent movie): apps/capcut
if let Some(done) = raea_app_capcut::cli(args, |a| raea_app_sound::render(a).unwrap_or_else(|| raea_runtime_export::render(a))) { return done; }
// `export-game EDIT.tsx -o OUT`: the game as a program of its own (game.rs, sdk/react/docs/game-export.md)
if args.first().map(String::as_str) == Some("export-game") {
return raea_app_game::export(args);
}
if args[0] == "export-game" { return raea_app_game::export(args); }
// `playable GAME.tsx -o DIR`: the game as a playable ad, a page or ZIP per network (apps/playable, docs/playables.feature)
if args[0] == "playable" { return raea_app_playable::cli(args); }
// `add PKG... [--dev] | remove NAME... | install [--offline] [--in DIR]`: npm packages for the project (its
// package.json and raea.lock, a pnpm-style node_modules from one verified store; install scripts never run), which
// a composition, an app screen or a legacy-app panel imports (io/npm)
+14
View File
@@ -416,6 +416,8 @@ const host: Host = (op, a) => {
return library(a);
case "show":
return show(a);
case "playable":
return playable(a as { file: string });
case "clothes":
return clothesHost(raea, cwd, process.env, a);
case "bug":
@@ -445,3 +447,15 @@ const r = await raeaHandler(host, engine)(args, { cwd, fs });
process.stdout.write(r.stdout);
process.stderr.write(r.stderr);
process.exitCode = r.exitCode;
/** `raea show GAME.tsx --playable` (show.ts): the game's preview page, exported by `raea playable` into a folder of its
* own (the show copies it into the app's media) */
function playable(a: { file: string }): { page: string } {
const out = mkdtempSync(`${tmpdir()}/raea-playable-`);
const r = spawnSync(raea, ["playable", a.file, "-o", out, "--networks", "preview"], { encoding: "utf8" });
if (r.status !== 0) throw new Error(`raea playable refused ${basename(a.file)}: ${`${r.stdout ?? ""}${r.stderr ?? ""}`.trim().slice(0, 1200)}`);
const page = readdirSync(out).find((f) => f.endsWith("-preview.html"));
if (!page) throw new Error(`raea playable made no preview page for ${basename(a.file)}`);
return { page: `${out}/${page}` };
}
+38 -7
View File
@@ -23,10 +23,18 @@ raea show [--title T] --question Q1 [--preview FILE] --choice A [--preview FILE]
It lands in the person's feed with a notice and the window stays where they are; --open brings the window up on it
(only when they're waiting on it).
FILE: stills (several make a storyboard), a video, a sound, a NAME.script.ts or .md, or a .tsx (an interactive
artifact; one of the project's compositions opens in its editor). P: Workspace/id (ids as raea workspace --json
artifact; one of the project's compositions opens in its editor), or a playable ad's .html (raea playable's
NAME-preview.html: it plays in a phone, sandboxed). --playable takes a game's .tsx, exports its preview with
\`raea playable\` and shows that page. P: Workspace/id (ids as raea workspace --json
lists them), a folder in the project, or a Copy reference from the app; a title only when it's the only one and
this folder isn't in another project. Else the one this folder is in. Who's showing it: --as NAME [--role ROLE]
[--inbox NAME], else your harness's.
raea show FILE... --fyi
Only for the person to look at, nothing to approve: they say Got it (you hear {"kind":"seen"}), and anything they
want to say back comes through the chat. Without it a show is a version for them to approve or send notes on.
raea show --group "Day: sun through the doors" A.png B.png --group "Night: practicals only" C.png [--title T]
Lay the files out in groups the person sees side by side, each titled before the colon and said after it in a plain
line (never shorthand); the files after a --group are its own. Keep it short: enough to know what each group is.
raea show FILE... --despite CHECK "why"
A render that still holds an error (raea findings --open lists them) isn't shown: fix it and render again, or say
why it goes anyway, once per check; the person reads the why on the item. One let through at the render (raea render
@@ -50,8 +58,8 @@ raea show FILE... --replaces ITEM --done ID...
closes when the person retires it, never with --done. raea notes post sends all of these from the notes.
`;
const WITH_VALUE = new Set(["--despite", "--label", "--detail", "--labels", "--title", "--ask", "--project", "--replaces", "--as", "--role", "--inbox", "--question", "--choice", "--preview", "--on", "--working", "--done", "--note", "--sub", "--status", "--states", "--sign", "--clip", "--render"]);
const FLAGS = new Set(["--open"]);
const WITH_VALUE = new Set(["--group", "--despite", "--label", "--detail", "--labels", "--title", "--ask", "--project", "--replaces", "--as", "--role", "--inbox", "--question", "--choice", "--preview", "--on", "--working", "--done", "--note", "--sub", "--status", "--states", "--sign", "--clip", "--render"]);
const FLAGS = new Set(["--open", "--fyi", "--playable"]);
/** The harness an agent runs in, named as the feed shows it, from the program that started this command (native.ts
* walks up its parents): any harness, not only the ones that mark their shells. */
@@ -84,6 +92,8 @@ const hash = (s: string) => {
return h.toString(36);
};
const marking = (args: string[]) => args.includes("--working") || args.includes("--done");
export function parseShow(args: string[], cwd: string) {
const one = (name: string) => {
const i = args.lastIndexOf(name);
@@ -95,7 +105,19 @@ export function parseShow(args: string[], cwd: string) {
if (unknown) throw new Error(`no ${unknown} here\n${SHOW_USAGE}`);
const abs = (f: string) => fromCwd(cwd, f);
// --despite takes two: the check, then why
const files = args.filter((a, i) => !a.startsWith("--") && !WITH_VALUE.has(args[i - 1] ?? "") && args[i - 2] !== "--despite").map(abs);
const isFile = (a: string, i: number) => !a.startsWith("--") && !WITH_VALUE.has(args[i - 1] ?? "") && args[i - 2] !== "--despite";
const files = args.filter(isFile).map(abs);
// the groups in order: each --group "Title: what it is" holds the files after it, up to the next --group
const groups: { title: string; says?: string; files: string[] }[] = [];
args.forEach((a, i) => {
if (a === "--group" && args[i + 1] !== undefined) {
const [title, ...rest] = args[i + 1].split(":");
if (!title.trim()) throw new Error(`--group "${args[i + 1]}" is a title, then what it is after a colon: --group "Night: practicals only"\n${SHOW_USAGE}`);
groups.push({ title: title.trim(), ...(rest.join(":").trim() ? { says: rest.join(":").trim() } : {}), files: [] });
} else if (groups.length && isFile(a, i)) groups.at(-1)!.files.push(abs(a));
});
const empty = groups.find((g) => !g.files.length);
if (empty) throw new Error(`the group "${empty.title}" has no files: put its files after its --group\n${SHOW_USAGE}`);
const despite = args.flatMap((a, i) => {
if (a !== "--despite") return [];
const [check, why] = [args[i + 1], args[i + 2]];
@@ -134,7 +156,8 @@ export function parseShow(args: string[], cwd: string) {
if ((labels.length || args.includes("--labels")) && (!files.length || questions || asked.length)) throw new Error(`labels go on the files you show: raea show FILE --label "PLACE TAG"\n${SHOW_USAGE}`);
if (labels.length && args.includes("--labels")) throw new Error(`--label or --labels, not both\n${SHOW_USAGE}`);
if (questions && files.length) throw new Error(`with several questions or previews, each file is a --preview of the question or choice it shows\n${SHOW_USAGE}`);
return { labels, labelsFile: one("--labels"), files, despite, choices, questions, open: args.includes("--open"), title: one("--title"), ask: one("--ask"), asks: many("--ask"), project: one("--project"), replaces: one("--replaces"), question: questions ? undefined : one("--question"), as: one("--as"), role: one("--role"), inbox: one("--inbox"), on: one("--on"), working: many("--working"), done: many("--done"), note: one("--note"), sub: one("--sub"), status: one("--status"), states: one("--states")?.split(",").map((s) => s.trim()).filter(Boolean), sign: one("--sign"), clip: one("--clip"), render: one("--render") };
if (args.includes("--fyi") && (asked.length || marking(args))) throw new Error(`--fyi shows files only to be looked at: a question, or marking comments, is answered\n${SHOW_USAGE}`);
return { groups, fyi: args.includes("--fyi"), labels, labelsFile: one("--labels"), files, despite, choices, questions, open: args.includes("--open"), playable: args.includes("--playable"), title: one("--title"), ask: one("--ask"), asks: many("--ask"), project: one("--project"), replaces: one("--replaces"), question: questions ? undefined : one("--question"), as: one("--as"), role: one("--role"), inbox: one("--inbox"), on: one("--on"), working: many("--working"), done: many("--done"), note: one("--note"), sub: one("--sub"), status: one("--status"), states: one("--states")?.split(",").map((s) => s.trim()).filter(Boolean), sign: one("--sign"), clip: one("--clip"), render: one("--render") };
}
/** A --labels file's labels, as feed_post takes them: a list, or { "labels": [...] } (raea media sheet's OUT.labels.json). */
@@ -189,7 +212,13 @@ export function showVerb(ask: Ask, args: string[], cwd: string, env: Record<stri
if (a.done.length && !a.replaces) throw new Error(`--done with files settles comments on the item they replace: add --replaces ITEM\n${SHOW_USAGE}`);
if (a.labelsFile !== undefined && !listed) throw new Error(`--labels ${a.labelsFile}: its labels weren't read (raea's own handler reads the file)`);
const labels = a.labels.length ? a.labels : listed;
const r = ask("show", { ...(labels?.length ? { labels } : {}), files: a.files, despite: a.despite, title: a.title, ask: askWith(a.ask, a.despite), question: a.question, choices: a.choices, questions: a.questions, open: a.open, project: a.project, replaces: a.replaces, cwd, by }) as
// --playable: the game's preview exported (raea playable --networks preview) and that page shown (docs/playables.feature PA16)
if (a.playable) {
if (a.files.length !== 1 || !/\.tsx$/.test(a.files[0]) || a.question || a.questions) throw new Error(`--playable shows one game's .tsx as its playable: raea show GAME.tsx --playable\n${SHOW_USAGE}`);
a.files = [(ask("playable", { file: a.files[0], cwd }) as { page: string }).page];
a.title ??= a.files[0].replace(/^.*[\\/]/, "").replace(/-preview\.html$/, "").replace(/[-_]+/g, " ").replace(/^\w/, (c) => c.toUpperCase());
}
const r = ask("show", { ...(labels?.length ? { labels } : {}), ...(a.fyi ? { intent: "fyi" } : {}), ...(a.groups.length ? { groups: a.groups } : {}), files: a.files, despite: a.despite, title: a.title, ask: askWith(a.ask, a.despite), question: a.question, choices: a.choices, questions: a.questions, open: a.open, project: a.project, replaces: a.replaces, cwd, by }) as
| { opened: string[] }
| { kind: "item" | "composition"; id: string; type: string; title: string; project: string; workspace: string; inbox: string; brought?: boolean };
if ("opened" in r) return `The raea app isn't on this Mac, so ${r.opened.length === 1 ? "it opened" : `${r.opened.length} files opened`} in the Mac's own viewer: nothing was posted and nothing comes back. Install raea (raea.io) to show work as items the person can answer.\n`;
@@ -213,7 +242,9 @@ export function showVerb(ask: Ask, args: string[], cwd: string, env: Record<stri
? `Shown in the raea app: "${r.title}" (${r.type}, item ${r.id}, project ${r.project} in ${r.workspace}); the window is on it.`
: `Posted in the raea app: "${r.title}" (${r.type}, item ${r.id}, project ${r.project} in ${r.workspace}), with a notice; the window stayed where the person is.`,
...settled,
`What the person sends on it (notes, edits, picks, answers, results) comes to ${inbox}, one JSON line each. Follow it (tail -n0 -F ${inbox}, or your harness's monitor) and answer each; a next version is raea show --replaces ${r.id} FILE.`,
a.fyi
? `Only to look at: when they've seen it, {"kind":"seen"} comes to ${inbox}; nothing to wait for.`
: `What the person sends on it (notes, edits, picks, answers, results) comes to ${inbox}, one JSON line each. Follow it (tail -n0 -F ${inbox}, or your harness's monitor) and answer each; a next version is raea show --replaces ${r.id} FILE.`,
"",
].join("\n");
}
+1 -1
View File
@@ -32,7 +32,7 @@ fn help_lists_every_verb() {
let listed = |v: &str| [format!("raea {v} "), format!("raea {v}\n"), format!("| {v} ")].iter().any(|l| help.contains(l.as_str()));
let missing: Vec<_> = verbs.iter().filter(|v| !listed(v) && !unlisted.contains(&v.as_str())).collect();
assert!(missing.is_empty(), "not in raea help: {missing:?}");
for usage in [raea_app_check::USAGE, raea_app_ask::USAGE, raea_app_direction::check::USAGE, raea_app_direction::USAGE, raea_app_notes::USAGE, raea_app_game::USAGE, raea_app_scene::USAGE, raea_app_voice::USAGE, motion::physics::USAGE, raea_runtime_wear::USAGE, tools::splat::USAGE, tools::sound::SAO_USAGE, tools::sound::TOKENSYNTH_USAGE, tools::song::USAGE, motion::track::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, raea_app_make::USAGE, tools::blender::USAGE, raea_app_lightbake::USAGE] {
for usage in [raea_app_check::USAGE, raea_app_ask::USAGE, raea_app_direction::check::USAGE, raea_app_direction::USAGE, raea_app_notes::USAGE, raea_app_game::USAGE, raea_app_playable::USAGE, raea_app_scene::USAGE, raea_app_voice::USAGE, motion::physics::USAGE, raea_runtime_wear::USAGE, tools::splat::USAGE, tools::sound::SAO_USAGE, tools::sound::TOKENSYNTH_USAGE, tools::song::USAGE, motion::track::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, raea_app_make::USAGE, tools::blender::USAGE, raea_app_lightbake::USAGE] {
assert!(help.contains(usage), "{usage}");
}
}
+2
View File
@@ -225,6 +225,8 @@ impl Engine {
image.texture_descriptor.view_formats = &[TextureFormat::Rgba8Unorm];
let target = app.world_mut().resource_mut::<Assets<Image>>().add(image);
app.insert_resource(TagRowTarget(target.clone())).init_resource::<ViewBox>().add_systems(PostUpdate, tag_row_view.before(bevy::camera::CameraUpdateSystems));
// a camera drawing a box's view culls by it (#261), once Bevy has made its own frusta
app.add_systems(PostUpdate, sub_view_frusta.after(bevy::camera::visibility::VisibilitySystems::UpdateFrusta).before(bevy::camera::visibility::VisibilitySystems::CheckVisibility));
// a free camera over the scene (docs/preview.feature PV1c): off until a preview asks for one
app.init_resource::<raea_sys_frame::view::FreeView>().add_systems(PostUpdate, raea_sys_frame::view::apply.before(bevy::transform::TransformSystems::Propagate));
// without native nothing ever comes back (frames are read back only to be encoded or analysed)
+1 -1
View File
@@ -2,7 +2,7 @@
//! raea-runtime-gpuframe), the render world's diagnostics forwarded.
use super::*;
pub(crate) use raea_sys_viewbox::{TagRowTarget, ViewBox, tag_row_view};
pub(crate) use raea_sys_viewbox::{TagRowTarget, ViewBox, sub_view_frusta, tag_row_view};
/// Bevy's render diagnostics (each pass's elapsed time, `render/...`): each new measurement into the run's totals (stats.read, the stats table: nobuild NB2a), the smoothed ones into its trace once a second.
#[cfg(feature = "native")]
+115
View File
@@ -0,0 +1,115 @@
// record: playable-brick-rush
// A playable ad's shape in raea (docs/playables.feature): a hand shows the move until the first touch, the player drags
// the paddle, three misses or a cleared wall ends it on an EndCard that opens the store. One game, two compositions
// (portrait and landscape) so each network's either orientation gets its own layout. Rendered with `raea render`, no
// one touches it: the paddle follows the ball, and the same file is the video ad.
import { AbsoluteFill, Composition, registerRoot, useCurrentFrame, useGameState, useVideoConfig, type FrameInput } from "raea";
import { Sphere } from "raea/3d";
import { LinearRgba, Srgba } from "raea/color";
import { StandardMaterial } from "raea/pbr";
import { Cuboid, Mesh3d } from "raea/mesh";
import { AmbientLight, DirectionalLight } from "raea/light";
import { Transform } from "raea/transform";
import { Camera3d } from "raea/camera";
import { EndCard } from "raea/playable";
const FPS = 30;
const COLS = 6, ROWS = 4, LIVES = 3;
const W = 6, TOP = 6; // field: x in [-W/2, W/2], y from 0 (paddle) to TOP
const FOV = 0.733; // radians, vertical
const COLORS = ["#ef476f", "#f78c6b", "#06d6a0", "#118ab2"];
interface Game { px: number; bx: number; by: number; vx: number; vy: number; alive: boolean[]; broke: number[]; hit: number; missed: number; lives: number; touched: boolean; over: "" | "won" | "lost" }
const INITIAL: Game = { px: 0, bx: 0, by: 0.6, vx: 0.06, vy: 0.1, alive: Array(COLS * ROWS).fill(true), broke: Array(COLS * ROWS).fill(-99), hit: -99, missed: -99, lives: LIVES, touched: false, over: "" };
const brickPos = (i: number): [number, number] => [(i % COLS - (COLS - 1) / 2) * (W / COLS), TOP - 0.5 - Math.floor(i / COLS) * 0.5];
/** The camera's distance that fits the whole field on a screen of this aspect */
const distance = (aspect: number) => Math.max((TOP + 1.5) / 2, (W + 1) / 2 / aspect) / Math.tan(FOV / 2);
/** A pointer's x on screen, in field units at the paddle's depth */
function fieldX(input: FrameInput, width: number, height: number): number | undefined {
if (!input.pointer) return undefined;
const d = distance(width / height);
const halfH = Math.tan(FOV / 2) * d;
return ((input.pointer.x / width) * 2 - 1) * halfH * (width / height);
}
const stepFor = (width: number, height: number) => (s: Game, input: FrameInput, frame: number): Game => {
if (s.over) return s;
const touched = s.touched || !!input.pointer?.down || !!input.touches?.length;
const want = touched ? fieldX(input, width, height) ?? s.px : s.bx; // before the first touch, the paddle plays itself
const px = Math.max(-W / 2 + 0.7, Math.min(W / 2 - 0.7, s.px + Math.max(-0.35, Math.min(0.35, want - s.px))));
let { bx, by, vx, vy, hit, missed, lives } = s;
bx += vx; by += vy;
if (bx < -W / 2 + 0.12 || bx > W / 2 - 0.12) vx = -vx;
if (by > TOP) vy = -Math.abs(vy);
if (by < 0.15 && by > -0.2 && vy < 0 && Math.abs(bx - px) < 0.8) { vy = Math.abs(vy); vx += (bx - px) * 0.05; hit = frame; }
if (by < -1.2) { lives -= 1; missed = frame; bx = px; by = 0.6; vx = 0.06; vy = 0.1; }
const alive = s.alive.slice(), broke = s.broke.slice();
for (let i = 0; i < alive.length; i++) {
if (!alive[i]) continue;
const [x, y] = brickPos(i);
if (Math.abs(bx - x) < W / COLS / 2 && Math.abs(by - y) < 0.22) { alive[i] = false; broke[i] = frame; vy = -vy; break; }
}
const over = !alive.some(Boolean) ? "won" : lives <= 0 ? "lost" : "";
return { px, bx, by, vx, vy, alive, broke, hit, missed, lives, touched, over };
};
const steps = new Map<string, ReturnType<typeof stepFor>>();
const stepOf = (w: number, h: number) => steps.get(`${w}x${h}`) ?? steps.set(`${w}x${h}`, stepFor(w, h)).get(`${w}x${h}`)!;
function BrickRush() {
const { width, height } = useVideoConfig();
const g = useGameState(INITIAL, stepOf(width, height));
const now = useCurrentFrame();
const last = g.broke.reduce((m, b) => Math.max(m, b), -99);
const kick = Math.max(0, 1 - (now - last) / 8);
const shake = kick * kick * 0.08 * Math.sin(now * 2.7);
const squash = Math.max(0, 1 - (now - g.hit) / 6);
const flash = Math.max(0, 1 - (now - g.missed) / 12);
const d = distance(width / height);
const s = width / 1080; // page sizes scale with the composition
return (
<AbsoluteFill style={{ background: `rgb(${16 + 90 * flash}, 20, 34)` }}>
<Camera3d transform={Transform.fromXyz(shake, TOP / 2 + shake, d).lookingAt([0, TOP / 2, 0])} projection={{ Perspective: { fov: FOV } }} />
<AmbientLight brightness={180} />
<DirectionalLight transform={Transform.fromXyz(2, 8, 6).lookingAt([0, 0, 0])} illuminance={9600} shadow_maps_enabled />
<Mesh3d transform={Transform.fromXyz(g.px, 0, 0).withScale([1 + 0.25 * squash, 1 - 0.35 * squash, 1])} name="paddle">
<Cuboid half_size={[0.7, 0.1, 0.2]} />
<StandardMaterial base_color="#f0ebd8" perceptual_roughness={0.4} />
</Mesh3d>
<Mesh3d transform={Transform.fromXyz(g.bx, g.by, 0)} name="ball">
<Sphere radius={0.14} />
<StandardMaterial base_color="#ffd166" emissive={LinearRgba.from(Srgba.hex("#ffd166")).mul(0.6)} />
</Mesh3d>
{g.alive.map((on, i) => {
const [x, y] = brickPos(i);
const t = (now - g.broke[i]) / 10;
if (!on && t > 1) return null;
const pop = on ? 1 : 1 + 0.6 * t;
return (
<Mesh3d key={i} transform={Transform.fromXyz(x, y, on ? 0 : t * 0.8).withScale([pop, on ? 1 : 1 - t, on ? 1 : 1 - t])} name={`brick-${i}`}>
<Cuboid half_size={[(W / COLS - 0.08) / 2, 0.2, 0.2]} />
<StandardMaterial base_color={on ? COLORS[Math.floor(i / COLS)] : "#ffffff"} perceptual_roughness={0.5} />
</Mesh3d>
);
})}
<div style={{ position: "absolute", left: 40 * s, top: 36 * s, fontFamily: "Inter, system-ui, sans-serif", fontWeight: 800, fontSize: 56 * s, color: "#f0ebd8" }}>
{"♥".repeat(Math.max(0, g.lives))}
</div>
{!g.touched ? (
<div style={{ position: "absolute", left: 0, right: 0, bottom: height * 0.12, textAlign: "center", fontFamily: "Inter, system-ui, sans-serif", fontWeight: 900, fontSize: 64 * s, color: "#ffffff", opacity: 0.6 + 0.4 * Math.sin(now / 5) ** 2 }}>
{`👆 Drag to play`}
</div>
) : null}
<EndCard show={!!g.over} title={g.over === "won" ? "Wall cleared!" : "So close!"} subtitle={g.over === "won" ? "300 more levels inside" : "Can you clear the wall?"} cta={g.over === "won" ? "Keep playing" : "Try again"} />
</AbsoluteFill>
);
}
registerRoot(() => (
<>
<Composition id="brick-rush-portrait" component={BrickRush} width={1080} height={1920} fps={FPS} durationInFrames={FPS * 45} />
<Composition id="brick-rush-landscape" component={BrickRush} width={1920} height={1080} fps={FPS} durationInFrames={FPS * 45} />
</>
));
+8 -2
View File
@@ -24,12 +24,13 @@ pub fn bundle_module(ts: &Path, out: &Path, body: &str) -> R<()> {
/// A path as an entry's import specifier. On Windows a canonical path is a verbatim one (\\?\C:\...), which Rolldown
/// can't resolve as an import (`raea run` on windows-latest, PT20); dunce drops the prefix where the plain path means the
/// same file, and changes nothing elsewhere.
fn spec(p: &Path) -> String {
pub fn spec(p: &Path) -> String {
dunce::simplified(p).display().to_string()
}
/// `entry` (TypeScript source) bundled into `out` by raea-bundle's library (engine/bundle/src/script.rs's resolution); `extra`
/// are bundle.ts's flags (--define K=V, --alias SPEC=PATH, --node-stub a,b).
/// are bundle.ts's flags (--define K=V, --alias SPEC=PATH, --node-stub a,b), and --minify 1 and --inline 1 (a page that
/// carries its files: engine/bundle inline.rs).
pub fn bundle_entry(entry: &str, out: &Path, extra: &[&str]) -> R<()> {
let out = &std::path::absolute(out).map_err(|e| format!("{}: {e}", out.display()))?;
let work = std::env::temp_dir().join(format!("raea-cli-e{}-{:?}", std::process::id(), std::thread::current().id()));
@@ -41,6 +42,7 @@ pub fn bundle_entry(entry: &str, out: &Path, extra: &[&str]) -> R<()> {
// in process by raea-bundle's library: the engine's resolution (engine/bundle/src/script.rs) and the flags
{
let (mut defines, mut aliases, mut stubs) = (serde_json::Map::new(), serde_json::Map::new(), Vec::new());
let (mut minify, mut inline) = (false, false);
let mut it = extra.iter();
while let Some(flag) = it.next() {
let Some(v) = it.next() else { break };
@@ -56,6 +58,8 @@ pub fn bundle_entry(entry: &str, out: &Path, extra: &[&str]) -> R<()> {
}
}
"--node-stub" => stubs.extend(v.split(',').filter(|s| !s.is_empty()).map(|s| Value::from(s))),
"--minify" => minify = *v != "0",
"--inline" => inline = *v != "0",
_ => {}
}
}
@@ -64,6 +68,8 @@ pub fn bundle_entry(entry: &str, out: &Path, extra: &[&str]) -> R<()> {
"script": {"js": js, "motion": root.join("sdk/raea/src"), "shell": root.join("sdk/shell/src/index.ts"),
"aliases": aliases, "stubs": stubs},
"defines": defines,
"minify": minify,
"inline": inline,
});
let r = inproc::bundle(&work.join("entry.ts"), opts);
let _ = std::fs::remove_dir_all(&work);
+3 -1
View File
@@ -35,7 +35,9 @@ pub fn drop_tsconfigs(dir: &Path, depth: usize) {
}
}
pub const MEDIA_EXTS: [&str; 12] = ["mp4", "mov", "m4v", "mp3", "wav", "m4a", "png", "jpg", "webp", "gif", "glb", "gltf"];
/// Files an edit imports as their path, as engine/bundle's script.rs MEDIA: media, models, and fonts (an @font-face's
/// url(), which a playable carries as a data URL)
pub const MEDIA_EXTS: &[&str] = &["mp4", "mov", "m4v", "mp3", "wav", "m4a", "png", "jpg", "jpeg", "webp", "gif", "glb", "gltf", "ttf", "otf", "woff", "woff2"];
/// The edit's source with its imports pointed at the bundle's copy of the SDK (its package name, a subpath such as /3d,
/// or a relative path into raea/motion/src), and media imported as modules turned into their paths (spec: "Media
+6 -9
View File
@@ -10,14 +10,8 @@ use std::path::Path;
use raea_core_brief::cut::{self, Cut, norm};
use serde_json::Value;
/// One gate as `raea make status` lists it: its name, the file or item it's about, whether it's clear, what it says.
#[derive(Debug, Clone, PartialEq)]
pub struct Gate {
pub name: &'static str,
pub of: Option<String>,
pub clear: bool,
pub says: String,
}
/// One gate as `raea make status` lists it (a goal's are the same kind)
pub use raea_core_brief::make::Gate;
fn gate(name: &'static str, of: Option<&str>, clear: bool, says: String) -> Gate {
Gate { name, of: of.map(str::to_string), clear, says }
@@ -192,7 +186,10 @@ fn file_gates(c: &Cut, plan: &cut::CutPlan, format: &str, f: &Path, rel: &str, s
in_order(&want, &j.iter().map(|(w, _)| w.as_str()).collect::<Vec<_>>())
};
let lines: Vec<&str> = std::iter::once(cta.text.as_str()).chain(cta.also.iter().map(String::as_str)).collect();
let (best, heard_share) = lines.iter().map(|l| (*l, share(l, &last))).fold(("", 0.0), |a, b| if b.1 > a.1 { b } else { a });
// the line heard most, the first of equals (none when no line's words were heard)
let heard: Vec<_> = lines.iter().map(|l| share(l, &last)).collect();
let heard_share = heard.iter().copied().fold(0.0, f64::max);
let best = lines.iter().zip(&heard).find(|(_, h)| heard_share > 0.0 && **h == heard_share).map_or("", |(l, _)| *l);
let on_screen = screen.iter().any(|(s, at)| *at >= end - within && lines.iter().any(|l| share(l, &s.split(' ').collect::<Vec<_>>()) >= CTA_SHARE));
let ok = heard_share >= CTA_SHARE || on_screen;
let says = match (ok, on_screen) {
+10 -10
View File
@@ -198,9 +198,9 @@ const LIVE_PAST: i64 = 3600;
/// raea-render program drawn by raea-render into `out` (.mp4, .png for one frame, a folder of PNGs). `dir` is where relative media resolves. `wanted`: the frames (all when None).
pub fn render_bundle(js: &Path, dir: &Path, out: &Path, wanted: Option<Vec<i64>>) -> R<String> {
// stills of a 3D scene: its engine opened live beside the page (as the fed path opens it), the page laid over each
// frame's 3D and each <Screen> painted from the page's own picture of it
// frame's 3D and each <Screen> painted from the page's own picture of it. A .png with no --frame is frame 0, drawn as --frame 0 draws it: the frames path gave a camera in a page element (an <R3F> in a box) the whole frame's view (#261)
let ext = out_ext(out);
let stills = (ext == "png" && wanted.as_ref().is_some_and(|w| w.len() == 1)) || ext.is_empty();
let stills = (ext == "png" && wanted.as_ref().is_none_or(|w| w.len() == 1)) || ext.is_empty();
let how = std::env::var_os("RAEA_3D").and_then(|v| v.into_string().ok()).unwrap_or_default();
// a game: its 3D made frame by frame as it's stepped (rows made beforehand hold every frame's scene: a 10-minute
// game took 24 GB before its first frame); RAEA_3D=live or =program chooses
@@ -210,16 +210,16 @@ pub fn render_bundle(js: &Path, dir: &Path, out: &Path, wanted: Option<Vec<i64>>
return render_bundle_with(js, dir, out, wanted, video, None, true);
}
if stills && how != "files" {
let upto = wanted.as_ref().and_then(|w| w.iter().max()).map_or(0, |f| f + 1);
// a still far into a 3D piece: its 3D made live at the still, as a game's is. The rows made beforehand hold a
// scene for every frame up to it: raea check --quick's three stills of a 13,175-frame film took 10.4 GB that
// way and 0.8 GB live, the same pixels as the film's (SG4a)
if how != "program" && upto > LIVE_PAST && raea_runtime_view::gpuview::paint_device().is_some() && wanted.as_deref().is_some_and(|w| crate::fed::stills_live(js, dir, w).unwrap_or(false)) {
let still = if ext == "png" && wanted.is_none() { Some(vec![0]) } else { wanted.clone() };
let upto = still.as_ref().and_then(|w| w.iter().max()).map_or(0, |f| f + 1);
// a still far into a 3D piece: its 3D made live at the still, as a game's is. The rows made beforehand hold a scene for every frame up to it:
// raea check --quick's three stills of a 13,175-frame film took 10.4 GB that way and 0.8 GB live, the same pixels as the film's (SG4a)
if how != "program" && upto > LIVE_PAST && raea_runtime_view::gpuview::paint_device().is_some() && still.as_deref().is_some_and(|w| crate::fed::stills_live(js, dir, w).unwrap_or(false)) {
raea_runtime_react::startup_mark("stills past the rows' reach: the 3D made live at each");
return render_bundle_with(js, dir, out, wanted, false, None, true);
return render_bundle_with(js, dir, out, still, false, None, true);
}
if let Some(scene) = scene_program_checked(js, dir, upto, wanted.as_deref())? {
return render_bundle_with(js, dir, out, wanted, false, Some(scene), false);
if let Some(scene) = scene_program_checked(js, dir, upto, still.as_deref())? {
return render_bundle_with(js, dir, out, still, false, Some(scene), false);
}
}
// a video: fed, its pages handed to the encoder on the GPU (B1d), until a frame holds 3D, which starts it again
+2 -8
View File
@@ -12,14 +12,8 @@ use std::time::{Duration, Instant, SystemTime};
use raea_core_brief::goal::Goal;
use serde_json::{Value, json};
/// One gate as `raea make status` lists it: its name, the rule it's about, whether it's clear, what it says.
#[derive(Debug, Clone, PartialEq)]
pub struct Gate {
pub name: &'static str,
pub of: Option<String>,
pub clear: bool,
pub says: String,
}
/// One gate as `raea make status` lists it (a cut's are the same kind): `of` is the rule it's about
pub use raea_core_brief::make::Gate;
fn gate(name: &'static str, of: &str, clear: bool, says: String) -> Gate {
Gate { name, of: Some(of.to_string()), clear, says }
+111 -10
View File
@@ -29,6 +29,7 @@ import contextlib
import json
import os
import re
import resource
import shutil
import subprocess
import time
@@ -38,7 +39,36 @@ import modal
HERE = os.path.dirname(os.path.abspath(__file__))
CLOUD = os.path.dirname(os.path.dirname(HERE))
RAEA = os.environ.get("RAEA_VERSION", "0.1.6")
def raea_version(env=os.environ, local=None, latest=None):
"""The raea the farm renders with: RAEA_VERSION when it's set (a deploy that pins one, and every container, whose
image carries the version it was built with), else, at a deploy, raea's newest release, as the boxes take
(deploy/sprites/box.sh). Until 11-29 this was "0.1.6" unless a deploy remembered the variable, and none did: the
farm drew 0.1.12 boxes' compositions with a raea six releases old, and a container, which never had the variable,
said 0.1.6 in /v1/health whatever its image held."""
if env.get("RAEA_VERSION"):
return env["RAEA_VERSION"]
if modal.is_local() if local is None else local:
try:
v = (latest or _latest_release)()
if re.fullmatch(r"\d+\.\d+\.\d+", v or ""):
return v
except Exception: # no network at a deploy: the fallback below, and the deploy's own log says which
pass
return RAEA_FALLBACK
def _latest_release():
import urllib.request
# releases/latest answers with a redirect to the newest full release's tag (never a pre-release)
with urllib.request.urlopen("https://github.com/shinyobjectz/raea/releases/latest", timeout=20) as r:
return r.geturl().rstrip("/").rsplit("/v", 1)[-1]
RAEA_FALLBACK = "0.1.12"
RAEA = raea_version()
BLENDER = os.environ.get("RAEA_FARM_BLENDER", "5.3.0")
# The GPUs each kind of job takes, the first Modal has free (bench/gpus.py, 11-17): raea's frames are bound by its CPU
# (React on QuickJS), so a T4 or an A10 draws them for the least a frame; Cycles gets the most samples a dollar on an
@@ -65,6 +95,8 @@ image = (
f"set -e; v={BLENDER}; curl -fsSL https://download.blender.org/release/Blender${{v%.*}}/blender-$v-linux-x64.tar.xz "
"| tar -xJ -C /opt && ln -s /opt/blender-$v-linux-x64/blender /usr/local/bin/blender && blender -b --version | head -1",
)
# what this image holds, for the containers: /v1/health says it, and the module agrees with the deploy that built it
.env({"RAEA_VERSION": RAEA})
.pip_install("fastapi[standard]==0.121.2")
# /v1/faces: OpenCV's YuNet face detector (232 KB, CPU), for the boxes' frames check (server/frames.ts): a box has
# no vision backend of its own (raea-perceive isn't in raea's Linux build), so a face cut by a 9:16 crop went unseen
@@ -74,6 +106,17 @@ image = (
"face_detection_yunet/face_detection_yunet_2023mar.onnx "
"&& echo '8f2383e4dd3cfbb4553ea8718107fc0423210dc964f9f4280604804ed2552fa4 /opt/yunet.onnx' | sha256sum -c"
)
# /v1/scene (11-29): what's in a frame, for the boxes' text placement (farm_scene.py, server/place.ts): people as a
# mask, COCO's things, words in the shot, beside YuNet's faces. Three more of OpenCV's zoo, Apache-2.0, on the CPU
.run_commands(
"set -e; z=https://media.githubusercontent.com/media/opencv/opencv_zoo/main/models; "
"curl -fsSL -o /opt/pphumanseg.onnx $z/human_segmentation_pphumanseg/human_segmentation_pphumanseg_2023mar.onnx; "
"curl -fsSL -o /opt/yolox_s.onnx $z/object_detection_yolox/object_detection_yolox_2022nov.onnx; "
"curl -fsSL -o /opt/ppocr_det.onnx $z/text_detection_ppocr/text_detection_en_ppocrv3_2023may.onnx; "
"printf '%s %s\\n' 552d8a984054e59b5d773d24b9b12022b22046ceb2bbc4c9aaeaceb36a9ddf24 /opt/pphumanseg.onnx "
"c5c2d13e59ae883e6af3b45daea64af4833a4951c92d116ec270d9ddbe998063 /opt/yolox_s.onnx "
"03f550c6b406fda8bf54bd8327815f6c7e2edd98cea02348c93d879254366587 /opt/ppocr_det.onnx | sha256sum -c"
)
.add_local_file(os.path.join(CLOUD, "image", "nvidia_icd.json"), "/usr/share/vulkan/icd.d/nvidia_icd.json", copy=True)
.env({"WGPU_BACKEND": "vulkan", "NVIDIA_DRIVER_CAPABILITIES": "all", "RAEA_CLIP_CHECK": "0", "RAEA_AUDIO_MUTE": "1",
"RAEA_MODELS": "/models/raea", "RAEA_FEED_MODELS": "/models/feed", "RAEA_LIBRARY_MODELS": "/models/library",
@@ -83,7 +126,7 @@ image = (
"RAEA_TOKENSYNTH": "/models/tokensynth", "RAEA_TOKENSYNTH_DEVICE": "cuda", "RAEA_AUDIO_AUTOSETUP": "0",
# Stable Audio Open small on ONNX Runtime with CUDA, as deploy/modal/sao.py installs it (CR25)
"RAEA_SAO": "/models/sao"})
.add_local_python_source("farm_plan", "farm_media", "prices")
.add_local_python_source("farm_plan", "farm_media", "prices", "farm_scene")
)
app = modal.App(os.environ.get("RAEA_FARM_APP", "raea-farm"), image=image)
@@ -104,20 +147,32 @@ CACHES = {"__GL_SHADER_DISK_CACHE": "1", "__GL_SHADER_DISK_CACHE_PATH": f"{ROOT}
"__GL_SHADER_DISK_CACHE_SIZE": str(4 << 30), "XDG_CACHE_HOME": f"{ROOT}/cache/xdg"}
# the scene reader's models, loaded once a container (/v1/scene)
SCENE = None
# when this container's Python started, for the job's bill (farm_plan.Bill)
BOOTED = time.time()
# what this container's last run used: cores busy on average (its processes' CPU time over the run's time) and the
# biggest of them at its peak, for the job's last line (farm_plan.Bill), so what a GPU container reserves
# (farm_plan.RESERVED) is held against what renders take (11-29: CPU and memory were 65% on top of the farm's GPU bill)
USED = {}
def life():
return {"task": os.environ.get("MODAL_TASK_ID", ""), "boot": BOOTED, "end": time.time()}
return {"task": os.environ.get("MODAL_TASK_ID", ""), "boot": BOOTED, "end": time.time(), **USED}
def run(cmd, cwd=None, env=None, timeout=6 * 3600):
t = time.time()
for d in (CACHES["__GL_SHADER_DISK_CACHE_PATH"], CACHES["XDG_CACHE_HOME"]):
os.makedirs(d, exist_ok=True)
u0 = resource.getrusage(resource.RUSAGE_CHILDREN)
r = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, env={**os.environ, "HOME": "/tmp/home", **CACHES, **(env or {})}, timeout=timeout)
return r.returncode, r.stdout + r.stderr, time.time() - t
u1, s = resource.getrusage(resource.RUSAGE_CHILDREN), time.time() - t
USED.update(cores=round((u1.ru_utime + u1.ru_stime - u0.ru_utime - u0.ru_stime) / max(s, 0.001), 2), peak_mb=round(u1.ru_maxrss / 1024))
return r.returncode, r.stdout + r.stderr, s
def snapshot(d):
@@ -152,8 +207,15 @@ class Log:
SCALEDOWN = 2
def on(gpus):
return dict(gpu=gpus, cpu=4, memory=16384, volumes={ROOT: vol, "/models": models}, timeout=6 * 3600, max_containers=GPUS, scaledown_window=SCALEDOWN)
def on(gpus, job):
import sys
if HERE not in sys.path: # at a deploy this file is loaded by path; in a container the image carries the module
sys.path.insert(0, HERE)
import farm_plan
cpu, gib = farm_plan.RESERVED[job]
return dict(gpu=gpus, cpu=cpu, memory=gib * 1024, volumes={ROOT: vol, "/models": models}, timeout=6 * 3600, max_containers=GPUS, scaledown_window=SCALEDOWN)
def kind():
@@ -164,7 +226,7 @@ def kind():
return prices.kind_of(name)
@app.function(**on(RAEA_GPUS))
@app.function(**on(RAEA_GPUS, "raea"))
def raea_run(id: str, args: list[str], frames: list[int] | None = None, first: int = 0, probe: bool = False, video: bool = False) -> dict:
"""raea ARGS in the job's folder. With `frames`: those frames to the job's frames/ folder, from frame `first` on,
as one H.264 run (frames/run-FIRST.mp4, joined by the coordinator without encoding again) when `video`, else PNGs.
@@ -185,12 +247,19 @@ def raea_run(id: str, args: list[str], frames: list[int] | None = None, first: i
os.makedirs(dest, exist_ok=True)
if video:
seg = f"/tmp/run-{first:05d}.mp4"
code, out, s = run(["raea", *args, "--at", ",".join(map(str, frames)), "-o", seg], cwd=work)
# the run's own manifest (its frames, each sound cut to them): the coordinator joins the runs' into the render's
# (farm_plan.joined), so a cut's whole edit comes back, not frame 0's alone (11-29, Dutch)
man = f"/tmp/run-{first:05d}.json"
code, out, s = run(["raea", *args, "--at", ",".join(map(str, frames)), "-o", seg, "--manifest", man], cwd=work)
if os.path.exists(seg):
shutil.move(seg, f"{dest}/run-{first:05d}.mp4")
vol.commit()
ms = re.search(r"([\d.]+) ms a frame", out)
return {"code": code, "out": out[-2000:], "s": s, "frames": len(frames), "ms": float(ms.group(1)) if ms else None, "kind": kind(), **life()}
try:
m = json.load(open(man))
except Exception:
m = None
return {"code": code, "out": out[-2000:], "s": s, "frames": len(frames), "ms": float(ms.group(1)) if ms else None, "kind": kind(), "manifest": m, **life()}
tmp = f"/tmp/{uuid.uuid4().hex}"
code, out, s = run(["raea", *args, "--at", ",".join(map(str, frames)), "-o", tmp], cwd=work)
# raea names --at's stills in order (frame-00000.png is the first frame asked for), beside its manifest
@@ -224,7 +293,7 @@ print("RAEA_INFO " + json.dumps({"start": s.frame_start, "end": s.frame_end, "fp
"""
@app.function(**on(BLENDER_GPUS))
@app.function(**on(BLENDER_GPUS, "blender"))
def blender_run(id: str, blend: str, start: int, end: int, opts: dict) -> dict:
vol.reload()
work = f"{JOBS}/{id}/work"
@@ -431,6 +500,38 @@ def api():
"seams": seams(cv2.cvtColor(im, cv2.COLOR_BGR2GRAY).astype(np.int16))})
return {"model": "yunet-2023mar", "frames": out}
@web.post("/v1/scene")
async def scene(req: Request):
"""what's in a video's frames, for the boxes' frames check and `raea frames place` (farm_scene.py): the body is
{"frames": [base64 JPEG, ...]} (at most 400), the answer each frame's size, its faces and split-screen seams
(as /v1/faces gives them, each face [x, y, w, h, "face", score]), a grid of where people are, and its things
(COCO's, and words in the shot as "text") as [x, y, w, h, label, score], in that frame's pixels"""
import base64
import cv2
import numpy as np
import farm_scene
check(req)
body = await req.json()
frames = body.get("frames") if isinstance(body, dict) else None
if not isinstance(frames, list) or not frames:
raise HTTPException(400, 'the body is {"frames": [base64 JPEG, ...]}')
if len(frames) > 400:
raise HTTPException(413, "at most 400 frames a call")
global SCENE
if SCENE is None:
SCENE = farm_scene.Scene()
out = []
for b64 in frames:
im = cv2.imdecode(np.frombuffer(base64.b64decode(b64), np.uint8), cv2.IMREAD_COLOR)
if im is None:
out.append(None)
continue
r = SCENE.read(im)
r["seams"] = seams(cv2.cvtColor(im, cv2.COLOR_BGR2GRAY).astype(np.int16))
out.append(r)
return {"model": "pphumanseg-2023mar+yolox-s-2022nov+ppocrv3-db-2023may+yunet-2023mar", "frames": out}
@web.post("/v1/words")
async def words(req: Request):
import base64
+67 -11
View File
@@ -87,7 +87,13 @@ def runs(first, last, k, warm=0):
return out
def price(kind, seconds, cpu=4, memory_gib=16):
# What a GPU container reserves beside its GPU, billed whether used or not; a run that takes more is billed for what
# it takes (Modal has no limit set here), so these are floors, not caps. raea's were 4 cores and 16 GiB until 11-29,
# when a 1080p cut measured 1.4 cores busy and 2.7 GB (the job's last line says each job's); Blender's is unmeasured.
RESERVED = {"raea": (2, 8), "blender": (4, 16)}
def price(kind, seconds, cpu=RESERVED["raea"][0], memory_gib=RESERVED["raea"][1]):
return prices.cost(kind, cpu=cpu, memory_gib=memory_gib, seconds=seconds)
@@ -97,21 +103,24 @@ BOOT = 3 # s a container is billed before its Python starts: the bench's cold s
class Bill:
"""What Modal bills for a job's GPU containers: each one's life from its boot (or the job's start, for one an
earlier job left up) to its last run's end, plus BOOT and SCALEDOWN, at its kind's price with 4 cores and 16 GiB."""
earlier job left up) to its last run's end, plus BOOT and SCALEDOWN, at its kind's price with what `job` ("raea", "blender") reserves."""
def __init__(self):
self.t0, self.tasks = time.time(), {}
def __init__(self, job="raea"):
self.t0, self.tasks, self.cores, self.peak_mb, self.cpu, self.gib = time.time(), {}, 0.0, 0, *RESERVED[job]
def add(self, r):
if isinstance(r, dict) and r.get("task"):
b, e = max(r["boot"], self.t0), r["end"]
k, b0, e0 = self.tasks.get(r["task"], (r.get("kind"), b, e))
self.tasks[r["task"]] = (k or r.get("kind"), min(b, b0), max(e, e0))
self.cores, self.peak_mb = max(self.cores, r.get("cores") or 0), max(self.peak_mb, r.get("peak_mb") or 0)
return r
def line(self):
up = [(k or "L4", e - b + BOOT + SCALEDOWN) for k, b, e in self.tasks.values()]
return f"raea farm: billed about ${sum(price(k, s) for k, s in up):.3f}: {len(up)} GPU containers up {sum(s for _, s in up):.0f} s in all"
# the busiest run's cores and biggest process, against what each container reserves (farm.py on())
used = f"; at most {self.cores:.1f} of {self.cpu} cores busy and {self.peak_mb / 1024:.1f} of {self.gib} GB in one process" if self.cores else ""
return f"raea farm: billed about ${sum(price(k, s, self.cpu, self.gib) for k, s in up):.3f}: {len(up)} GPU containers up {sum(s for _, s in up):.0f} s in all{used}"
def encode(frames_dir, out, fps, sound, run, start=0, frames=None):
@@ -145,9 +154,10 @@ def keep(frames_dir, out, start=0):
shutil.move(os.path.join(frames_dir, name), os.path.join(out, f"frame-{i:05d}.png"))
def spread(fn, kind, calls, log, what, bill=None, most=None):
def spread(fn, kind, calls, log, what, bill=None, most=None, got=None):
"""`calls` on `fn`, at most `most` GPUs at once when there are more calls than that (each GPU takes the next call
as it finishes one); each finished run said in the log as it lands. The first failure's code, else 0."""
as it finishes one); each finished run said in the log as it lands, and kept in `got` when given. The first
failure's code, else 0."""
code = 0
if most and len(calls) > most:
fn = fn.with_options(max_containers=most)
@@ -158,6 +168,8 @@ def spread(fn, kind, calls, log, what, bill=None, most=None):
continue
if bill:
bill.add(r)
if got is not None:
got.append(r)
log(f"raea farm: {r.get('frames')} {what} on a {r.get('kind') or kind} in {r['s']:.1f} s")
if r["code"]:
log(r["out"], err=True)
@@ -205,7 +217,8 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
return 3
# a video's runs can't drop warm-up frames without encoding again, so they have none
warm = 0 if video else opts.get("warm", 0)
code = spread(render, kind, [(id, rest, f, at, False, video) for f, at in runs(n0, length - 1, k * m, warm)], log, "frames", bill, k) if left else 0
got = [r0]
code = spread(render, kind, [(id, rest, f, at, False, video) for f, at in runs(n0, length - 1, k * m, warm)], log, "frames", bill, k, got) if left else 0
if code:
return code
# the sound's run finished first: its open files in the job's folder refuse the reload that brings the other
@@ -219,7 +232,7 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
path = os.path.join(work, manifest)
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
with open(path, "w") as f:
json.dump(p["manifest"], f, indent=2)
json.dump(joined(p["manifest"], [r.get("manifest") for r in got]), f, indent=2)
if video:
os.makedirs(os.path.dirname(dest) or ".", exist_ok=True)
c, o, s = join(frames, dest, sound, run)
@@ -229,6 +242,49 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
return 0
def joined(probe, parts):
"""The render's manifest from its runs' own (each holds its frames, and each sound cut to them, a clip's `at` its
source time at the run's first frame): every frame, and each clip made whole again where one run's piece ends on the
frame the next one's starts, at the source time it should. Frame 0's (the probe's) when no run brought one.
11-29 (Dutch): frame 0's alone was written, so a cut's edit was lost and nothing could check its edit points."""
parts = [m for m in parts if m]
if not parts:
return probe
out = {**probe, **{k: v for k, v in parts[0].items() if k not in ("frames", "sounds", "findings")}}
frames = {}
for m in parts:
for f in m.get("frames") or []:
frames.setdefault(f.get("frame"), f)
out["frames"] = [frames[k] for k in sorted(frames, key=lambda x: (x is None, x))]
seen, found = set(), []
for m in [probe, *parts]:
for x in m.get("findings") or []:
key = json.dumps(x, sort_keys=True)
if key not in seen:
seen.add(key)
found.append(x)
out["findings"] = found
snd = [m.get("sounds") for m in parts if isinstance(m.get("sounds"), dict)]
if snd:
fps = snd[0].get("fps") or out.get("fps") or 30
pieces = sorted((c for s in snd for c in s.get("clips") or []), key=lambda c: (c.get("from", 0), str(c.get("key"))))
clips = []
for c in pieces:
prev = next((p for p in reversed(clips) if p.get("key") == c.get("key") and p.get("src") == c.get("src") and p.get("to") == c.get("from")), None)
if prev is not None and abs(prev.get("at", 0) + (prev["to"] - prev["from"]) / fps - c.get("at", 0)) < 1.5 / fps:
prev["to"] = c["to"]
if "fadeOut" in c:
prev["fadeOut"] = c["fadeOut"]
continue
clips.append(dict(c))
notes, lines = [], []
for s in snd:
notes += [n for n in s.get("notes") or [] if n not in notes]
lines += [n for n in s.get("lines") or [] if n not in lines]
out["sounds"] = {**snd[0], "clips": clips, "notes": notes, "lines": lines}
return out
def blender_info(blend, work, run):
c, o, _ = run(["blender", "-b", blend, "--python-expr", BLENDER_INFO], cwd=work)
m = re.search(r"RAEA_INFO (\{.*\})", o)
@@ -275,7 +331,7 @@ def blender(args, opts, work, log, render, run, reload=lambda: None, bill=None):
left = last - first
k = gpus_for(left, frame_s, start_s, opts["gpus"])
m = parts_per_gpu(left, k, frame_s, start_s)
cost = price(kind, r0["s"] + k * m * start_s + left * frame_s)
cost = price(kind, r0["s"] + k * m * start_s + left * frame_s, *RESERVED["blender"])
parts = f" in {k * m} parts" if m > 1 else ""
log(f"raea farm: frame {first} on a {kind} in {r0['s']:.1f} s ({frame_s:.1f} s rendering); {left} left on {k} {kind}s{parts}, about ${cost:.3f} in all")
if opts.get("max_usd") is not None and cost > opts["max_usd"]:
@@ -302,7 +358,7 @@ def dispatch(args, opts, work, log, render, blender_render, cpu_env, run, reload
if opts.get("gpu"):
render, blender_render = (f.with_options(gpu=opts["gpu"]) for f in (render, blender_render))
if args and args[0] == "blender":
bill = Bill()
bill = Bill("blender")
code = blender(args, opts, work, log, blender_render, run, reload, bill)
log(bill.line())
return code
+143
View File
@@ -0,0 +1,143 @@
"""What's in a frame, for the boxes' text checks (server/frames.ts): where people are (a mask, hands and arms included),
their faces, and the things a person holds or a shot is about (a dog, a phone, a cup), so text isn't laid over them and
a clear place for it can be found (11-29, Shane on Dutch: "text being weirdly placed over footage where it blocks a
person or place, dont we have methods of correctly guessing where text needs to go based on the scene?").
Four small ONNX models from OpenCV's zoo, on the CPU through cv2.dnn, each pinned by its hash in farm.py's image:
PP-HumanSeg (2023mar, Apache-2.0): people, as a mask, at 192x192
YOLOX-S (2022nov, Apache-2.0): COCO's 80 things, as boxes, at 640x640
PP-OCRv3 DB (2023may, Apache-2.0): words in the shot (a sign someone holds, a shop's name), as boxes labelled "text"
YuNet (2023mar, MIT): faces, as boxes (the frames check's own)
A frame's answer: its size, a grid of how much of each cell is a person (0-9, a cell ~1/27 of the shorter side), the
faces and the things as [x, y, w, h, label, score] in the frame's pixels."""
import numpy as np
SEG = "/opt/pphumanseg.onnx"
DET = "/opt/yolox_s.onnx"
WORDS = "/opt/ppocr_det.onnx"
FACE = "/opt/yunet.onnx"
# COCO's classes, YOLOX's order
COCO = ("person bicycle car motorcycle airplane bus train truck boat traffic_light fire_hydrant stop_sign parking_meter "
"bench bird cat dog horse sheep cow elephant bear zebra giraffe backpack umbrella handbag tie suitcase frisbee skis "
"snowboard sports_ball kite baseball_bat baseball_glove skateboard surfboard tennis_racket bottle wine_glass cup "
"fork knife spoon bowl banana apple sandwich orange broccoli carrot hot_dog pizza donut cake chair couch "
"potted_plant bed dining_table toilet tv laptop mouse remote keyboard cell_phone microwave oven toaster sink "
"refrigerator book clock vase scissors teddy_bear hair_drier toothbrush").split()
# what a shot is about or a person holds: text over these hides them. Furniture, vehicles and the like are the place
KEEP = {"person", "bird", "cat", "dog", "horse", "backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee",
"sports_ball", "bottle", "wine_glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple", "sandwich",
"orange", "broccoli", "carrot", "hot_dog", "pizza", "donut", "cake", "laptop", "mouse", "remote", "keyboard",
"cell_phone", "book", "clock", "vase", "scissors", "teddy_bear", "hair_drier", "toothbrush"}
# grid cells along the frame's shorter side (40 px cells in a 1080-wide frame)
CELLS = 27
class Scene:
def __init__(self, seg=SEG, det=DET, face=FACE, words=WORDS):
import cv2
self.cv2 = cv2
self.seg = cv2.dnn.readNet(seg)
self.det = cv2.dnn.readNet(det)
self.words_model = cv2.dnn_TextDetectionModel_DB(words)
self.words_model.setBinaryThreshold(0.3)
self.words_model.setPolygonThreshold(0.5)
self.words_model.setMaxCandidates(200)
self.words_model.setUnclipRatio(2.0)
self.face_path = face
self.face, self.face_size = None, None
def people(self, im):
"""the share of each pixel that's a person, at the frame's size (PP-HumanSeg: RGB, 192x192, (x/255 - 0.5)/0.5)"""
cv2 = self.cv2
h, w = im.shape[:2]
x = cv2.resize(cv2.cvtColor(im, cv2.COLOR_BGR2RGB), (192, 192)).astype(np.float32) / 255.0
x = (x - 0.5) / 0.5
self.seg.setInput(x.transpose(2, 0, 1)[None])
out = self.seg.forward()[0] # [2, 192, 192], logits of background and person
e = np.exp(out - out.max(axis=0, keepdims=True))
p = e[1] / e.sum(axis=0)
return cv2.resize(p, (w, h), interpolation=cv2.INTER_LINEAR)
def things(self, im, least=0.35):
"""COCO things as [x, y, w, h, label, score] (YOLOX-S: BGR as is, letterboxed into 640x640 on grey 114)"""
cv2 = self.cv2
h, w = im.shape[:2]
r = min(640 / h, 640 / w)
pad = np.full((640, 640, 3), 114, np.uint8)
pad[: int(h * r), : int(w * r)] = cv2.resize(im, (int(w * r), int(h * r)))
self.det.setInput(pad.transpose(2, 0, 1)[None].astype(np.float32))
out = self.det.forward()[0] # [8400, 85]: x, y, w, h, objectness, 80 classes, on the strides' grids
grids, strides = [], []
for s in (8, 16, 32):
n = 640 // s
yv, xv = np.meshgrid(np.arange(n), np.arange(n), indexing="ij")
grids.append(np.stack((xv, yv), 2).reshape(-1, 2))
strides.append(np.full((n * n, 1), s))
grids, strides = np.concatenate(grids), np.concatenate(strides)
xy = (out[:, :2] + grids) * strides
wh = np.exp(out[:, 2:4]) * strides
scores = out[:, 4:5] * out[:, 5:]
cls = scores.argmax(1)
best = scores[np.arange(len(cls)), cls]
keep = best > least
boxes = np.concatenate([xy - wh / 2, wh], 1)[keep] / r
cls, best = cls[keep], best[keep]
idx = cv2.dnn.NMSBoxes(boxes.tolist(), best.tolist(), least, 0.45)
found = []
for i in np.array(idx).flatten() if len(idx) else []:
label = COCO[int(cls[i])]
if label not in KEEP:
continue
x, y, bw, bh = boxes[i]
x0, y0 = max(0.0, x), max(0.0, y)
found.append([round(float(x0), 1), round(float(y0), 1), round(float(min(w, x + bw) - x0), 1), round(float(min(h, y + bh) - y0), 1), label, round(float(best[i]), 3)])
return found
def words(self, im, least=0.6):
"""words in the shot as [x, y, w, h, "text", score] (PP-OCRv3 DB at the frame's size, rounded to 32s)"""
cv2 = self.cv2
h, w = im.shape[:2]
size = (max(32, round(w / 32) * 32), max(32, round(h / 32) * 32))
self.words_model.setInputParams(1.0 / 255.0, size, (122.67891434, 116.66876762, 104.00698793))
boxes, conf = self.words_model.detect(im)
out = []
for b, c in zip(boxes, conf):
if float(c) < least:
continue
x, y, bw, bh = cv2.boundingRect(np.array(b, np.int32))
out.append([float(max(0, x)), float(max(0, y)), float(bw), float(bh), "text", round(float(c), 3)])
return out
def faces(self, im):
cv2 = self.cv2
h, w = im.shape[:2]
if self.face is None or self.face_size != (w, h):
self.face, self.face_size = cv2.FaceDetectorYN.create(self.face_path, "", (w, h), 0.6, 0.3, 5000), (w, h)
_, found = self.face.detect(im)
return [[round(float(f[0]), 1), round(float(f[1]), 1), round(float(f[2]), 1), round(float(f[3]), 1), "face", round(float(f[14]), 3)] for f in (found if found is not None else [])]
def read(self, im):
h, w = im.shape[:2]
p = self.people(im)
return {"w": w, "h": h, "grid": grid(p, w, h), "things": self.things(im) + self.words(im), "faces": self.faces(im)}
def grid(p, w, h):
"""a person mask (0-1 a pixel) as a grid of digits, a row a string: how much of each cell is a person, 0-9"""
cell = min(w, h) / CELLS
cols, rows = max(1, round(w / cell)), max(1, round(h / cell))
out = []
for r in range(rows):
y0, y1 = int(r * h / rows), int((r + 1) * h / rows)
row = ""
for c in range(cols):
x0, x1 = int(c * w / cols), int((c + 1) * w / cols)
v = float(p[y0:y1, x0:x1].mean()) if y1 > y0 and x1 > x0 else 0.0
row += str(min(9, int(v * 10)))
out.append(row)
return {"cols": cols, "rows": rows, "people": out}
+4 -1
View File
@@ -187,7 +187,10 @@ server_image = indexer_image_for(None)
# one file indexed as a job (tools/library-index cloud-cli.ts), for a file of any length: raea cloud submits it through
# the API's POST /v1/index-jobs and collects it with GET /v1/index-jobs/ID on its next alarm (index-run.ts)
@app.function(image=indexer_image, gpu=GPU, cpu=4, memory=16384, secrets=[secret], timeout=3600, max_containers=12, scaledown_window=120)
# 2 cores and 8 GiB reserved (4 and 16 until 11-29): a 52 s clip measured 1.9 cores busy and 4.9 GB across its
# processes, and from 11-17 to 11-29 the app's CPU and memory cost more than its GPU. A job that takes more is billed
# for what it takes: these are floors, with no limit set
@app.function(image=indexer_image, gpu=GPU, cpu=2, memory=8192, secrets=[secret], timeout=3600, max_containers=12, scaledown_window=120)
def index_job(url: str, name: str, kind: str) -> dict:
import json
import subprocess as sp
+3
View File
@@ -13,5 +13,8 @@ case "${1:-}" in
words|transcribe) exec node /opt/raea-cloud/server/words.ts "$@" ;;
# faces cut by the frame or a seam, text too small (server/frames.ts, the farm's face detector)
frames) exec node /opt/raea-cloud/server/frames.ts "$@" ;;
# edit points inside words or on sound, lines too quiet to hear, effects no one hears (server/sound.ts, against each
# take's own words and sound); `raea sound` alone is raea's
sound) if [ "${2:-}" = check ]; then exec node /opt/raea-cloud/server/sound.ts "$@"; fi ;;
esac
exec /opt/raea/bin/raea "$@"
+105 -6
View File
@@ -9,6 +9,12 @@
// text: each text the render's manifest shows (raea render --manifest; a .tsx render through raea cloud writes
// VIDEO.render.json by itself), its font size in pixels of a 1080-wide frame: under 40 px is an error (no one
// reads it on a phone), under 48 px a warning (small for anything but a badge or small print).
// placement (11-29): each text against what's under it (the farm's POST /v1/scene: people, faces, the things a
// shot is about, words in the shot like a sign): text over a face, a thing or a person, where a clear place of
// its size exists, is said with that place (server/place.ts).
// raea frames place FILE [--at S[,S...]] [--box WxH] [-o REPORT.json]
// the clearest places in FILE (a take or an export, a picture or a video, at those seconds) for a box WxH in a
// 1080-wide frame (a caption, 840x110, by default): read the takes with it before laying text over them.
// Exit 1 on any error. A face at the edge that's meant (someone walking out of shot) is said, with its reason, in
// VIDEO.despite.txt beside the video: its findings are then warnings.
import { spawnSync } from "node:child_process"
@@ -16,6 +22,7 @@ import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSy
import os from "node:os"
import path from "node:path"
import { pathToFileURL } from "node:url"
import { placeReport, textOver, type Scene } from "./place.ts"
/** frames sampled a second, and the width they're read at (a face's place is in shares of the picture) */
const RATE = 2
@@ -27,7 +34,7 @@ export const FACE_MIN = 0.05
export const TEXT_ERROR = 40
export const TEXT_WARN = 48
export type Finding = { level: "error" | "warn"; kind: "face-cut" | "split" | "text-small"; at: number | null; until?: number; says: string }
export type Finding = { level: "error" | "warn"; kind: "face-cut" | "split" | "text-small" | "text-over"; at: number | null; until?: number; says: string }
/** a line where the picture jumps across nearly the whole frame (the farm's): its axis (h, a row), where, and its share */
export type Seam = [string, number, number]
export type Faces = { w: number; h: number; faces: number[][]; seams?: Seam[] } | null
@@ -149,6 +156,58 @@ function ffmpeg(args: string[]) {
if (r.status !== 0) throw new Error(`ffmpeg: ${(r.stderr ?? "").slice(-400)}`)
}
/** what the farm reads in a file's frames (`at`: those seconds, else RATE a second), from its POST /v1/scene, or from
* /v1/faces alone on a farm without it (then each scene is null) */
export async function scenes(file: string, at?: number[], f: typeof fetch = fetch): Promise<{ faces: Faces[]; scenes: Scene[] }> {
const url = process.env.RAEA_CLOUD_GPU_URL
const token = process.env.RAEA_CLOUD_GPU_TOKEN ?? ""
if (!url) throw new Error("the frames check needs the farm (RAEA_CLOUD_GPU_URL); this box has none set")
const dir = mkdtempSync(path.join(os.tmpdir(), "raea-frames-"))
try {
const scale = `scale='if(gt(iw,ih),-2,${SIDE})':'if(gt(iw,ih),${SIDE},-2)'`
if (/\.(png|jpe?g|webp)$/i.test(file)) ffmpeg(["-v", "error", "-y", "-i", file, "-vf", scale, "-q:v", "4", path.join(dir, "f00001.jpg")])
else if (at?.length) at.forEach((s, i) => ffmpeg(["-v", "error", "-y", "-ss", String(s), "-i", file, "-frames:v", "1", "-vf", scale, "-q:v", "4", path.join(dir, `f${String(i + 1).padStart(5, "0")}.jpg`)]))
else ffmpeg(["-v", "error", "-y", "-i", file, "-vf", `fps=${RATE},${scale}`, "-q:v", "4", path.join(dir, "f%05d.jpg")])
const jpgs = readdirSync(dir).filter((n) => n.endsWith(".jpg")).sort()
const outF: Faces[] = []
const outS: Scene[] = []
let scene = true
for (let i = 0; i < jpgs.length; i += 300) {
const body = JSON.stringify({ frames: jpgs.slice(i, i + 300).map((n) => readFileSync(path.join(dir, n)).toString("base64")) })
const call = async (route: string) => {
let r: Response | undefined
let why = ""
for (let k = 0; k < 4; k++) {
r = await f(`${url.replace(/\/$/, "")}${route}`, { method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, body, signal: AbortSignal.timeout(600_000) })
if (r.ok || r.status === 404) break
why = `${r.status} ${(await r.text()).slice(0, 300)}`
if (r.status < 500) break
await new Promise((ok) => setTimeout(ok, 1000 * 2 ** k))
}
return { r, why }
}
let { r, why } = scene ? await call("/v1/scene") : { r: undefined as Response | undefined, why: "" }
if (scene && r?.status === 404) scene = false
if (!scene) ({ r, why } = await call("/v1/faces"))
if (!r?.ok) throw new Error(`the farm couldn't look at ${path.basename(file)}: ${why || r?.status}`)
const got = ((await r.json()) as { frames: (Record<string, unknown> | null)[] }).frames
for (const g of got) {
if (!g) {
outF.push(null)
outS.push(null)
continue
}
const fs = (g.faces as unknown[][]) ?? []
outF.push({ w: g.w as number, h: g.h as number, faces: fs.map((x) => (typeof x[4] === "string" ? [x[0], x[1], x[2], x[3], x[5]] : x) as number[]), seams: g.seams as Seam[] | undefined })
outS.push(scene && g.grid ? ({ w: g.w, h: g.h, grid: g.grid, things: g.things ?? [], faces: fs.map((x) => (typeof x[4] === "string" ? x : [x[0], x[1], x[2], x[3], "face", x[4]])) } as Scene) : null)
}
}
return { faces: outF, scenes: outS }
} finally {
rmSync(dir, { recursive: true, force: true })
}
}
/** VIDEO's faces, two frames a second, by the farm */
export async function faces(file: string, f: typeof fetch = fetch): Promise<Faces[]> {
const url = process.env.RAEA_CLOUD_GPU_URL
@@ -187,7 +246,40 @@ function flag(args: string[], name: string): string | undefined {
/** the manifest a render of VIDEO wrote: --manifest, or VIDEO.render.json beside it */
export const manifestOf = (video: string) => `${video.slice(0, video.length - path.extname(video).length)}.render.json`
/** `raea frames place FILE [--at S,...] [--box WxH]` */
async function place(a: string[]): Promise<number> {
const file = a.find((x, i) => !x.startsWith("-") && !["--at", "--box", "-o"].includes(a[i - 1] ?? ""))
if (!file || !existsSync(file)) {
console.error("usage: raea frames place FILE [--at S[,S...]] [--box WxH] [-o REPORT.json] (the clearest places in a take or an export for a box WxH in a 1080-wide frame; a caption, 840x110, by default)")
return 2
}
const box = (flag(a, "--box") ?? "840x110").split("x").map(Number) as [number, number]
if (box.length !== 2 || !box.every((v) => v > 0)) {
console.error("raea frames place: --box is WxH in a 1080-wide frame's pixels, like 840x110")
return 2
}
let at = flag(a, "--at")?.split(",").map(Number).filter(Number.isFinite)
if (!at?.length && !/\.(png|jpe?g|webp)$/i.test(file)) {
const r = spawnSync("ffprobe", ["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", file], { encoding: "utf8" })
const len = Number.parseFloat(r.stdout) || 1
const n = Math.min(12, Math.max(1, Math.floor(len)))
at = Array.from({ length: n }, (_, i) => Math.round(((i + 0.5) * len * 100) / n) / 100)
}
const { scenes: ss } = await scenes(file, at)
if (!ss.some(Boolean)) {
console.error("raea frames place: the farm has no scene reader yet (POST /v1/scene): nothing to place by")
return 1
}
const rep = placeReport(file, ss, box)
console.log(`${path.basename(file)}${at?.length ? ` at ${at.join(", ")} s` : ""}: the clearest places for a ${box[0]}x${box[1]} box in a ${rep.frame?.join("x")} frame, best first`)
for (const p of rep.places) console.log(` left ${p.left} px, top ${p.top} px (${p.at}) cost ${p.cost}${p.covers.length ? ` covers ${p.covers.join(", ")}` : " clear"}`)
const o = flag(a, "-o")
if (o) writeFileSync(o, JSON.stringify(rep, null, 1))
return 0
}
export async function main(args: string[]): Promise<number> {
if (args[0] === "place") return place(args.slice(1))
const a = args[0] === "check" ? args.slice(1) : args
const video = a.find((x, i) => !x.startsWith("-") && !["--manifest", "-o"].includes(a[i - 1] ?? ""))
if (!video || !existsSync(video)) {
@@ -197,14 +289,21 @@ export async function main(args: string[]): Promise<number> {
const m = flag(a, "--manifest") ?? manifestOf(video)
const found: Finding[] = []
let looked = 0
const man = existsSync(m) ? JSON.parse(readFileSync(m, "utf8")) : null
let placed: number | null = null
try {
const fr = await faces(video)
looked = fr.length
found.push(...cutFaces(fr))
const got = await scenes(video)
looked = got.faces.length
found.push(...cutFaces(got.faces))
if (man && got.scenes.some(Boolean)) {
const over = textOver(man, got.scenes, RATE)
placed = over.length
found.push(...over)
}
} catch (e) {
console.log(`WARN the faces check couldn't run: ${(e as Error).message}`)
}
const texts = existsSync(m) ? smallText(JSON.parse(readFileSync(m, "utf8"))) : null
const texts = man ? smallText(man) : null
if (texts) found.push(...texts)
const despite = `${video.slice(0, video.length - path.extname(video).length)}.despite.txt`
const why = existsSync(despite) ? readFileSync(despite, "utf8").trim() : ""
@@ -212,7 +311,7 @@ export async function main(args: string[]): Promise<number> {
for (const x of out) console.log(`${x.level === "error" ? "ERROR" : "WARN "} ${x.at === null ? "" : `${x.at.toFixed(1)} s `}${x.says}`)
const errors = out.filter((x) => x.level === "error").length
const report = flag(a, "-o") ?? `${video.slice(0, video.length - path.extname(video).length)}.frames-check.json`
writeFileSync(report, JSON.stringify({ video, looked_at: looked, text_checked: texts !== null, findings: out }, null, 1))
writeFileSync(report, JSON.stringify({ video, looked_at: looked, text_checked: texts !== null, placement_checked: placed !== null, findings: out }, null, 1))
console.log(`${errors ? "FAILED" : "PASSED"} ${path.basename(video)}: ${looked} frames looked at for faces, ${texts === null ? "no manifest for its text" : `${new Set(texts.map((t) => t.says)).size} small texts`}, ${errors} errors, ${out.length - errors} warnings; ${path.basename(report)}`)
return errors ? 1 : 0
}
+16 -1
View File
@@ -192,6 +192,21 @@ async function main() {
const code = await afterRender(made, say)
if (code) process.exitCode = code
}
// what its sound gets wrong (sound.ts), from the render's manifest against each take's own words and sound: an edit
// point inside a word or on its sound, a line too quiet to hear, an effect no one hears (11-29, Shane on Dutch)
if (!exit && /\.(mp4|mov|m4v|webm)$/i.test(made) && existsSync(made) && process.env.RAEA_CLOUD_SOUND !== "0") {
const mi = args.indexOf("--manifest")
const man = mi >= 0 ? path.resolve(process.cwd(), args[mi + 1] ?? "") : ""
if (man && existsSync(man)) {
const { main: sound } = await import("./sound.ts")
say(`the sound check: ${path.basename(made)}'s edit points, line levels and effects`)
const code = await sound(["check", made, "--manifest", man]).catch((e) => (say(`the sound check couldn't run: ${(e as Error).message}`), 0))
if (code) {
say(`${path.basename(made)}'s sound has faults a listener hears: fix every ERROR above (move each cut to the pause or boundary it names, set the gainDb it gives), then render again`)
process.exitCode = code
}
}
}
// what its pictures get wrong (frames.ts): faces cut by the frame or a split screen's seam, text too small to read
// (11-25, Shane: "it cuts out faces all the time", "it makes text too small")
if (!exit && /\.(mp4|mov|m4v|webm)$/i.test(made) && existsSync(made) && process.env.RAEA_CLOUD_FRAMES !== "0") {
@@ -200,7 +215,7 @@ async function main() {
const mi = args.indexOf("--manifest")
const code = await frames(["check", made, ...(mi >= 0 ? ["--manifest", path.resolve(process.cwd(), args[mi + 1] ?? "")] : [])]).catch((e) => (say(`the frames check couldn't run: ${(e as Error).message}`), 0))
if (code) {
say(`${path.basename(made)} has a face cut or text too small: fix every ERROR above (reframe on the person, make the text bigger), then render again. A face at the edge that's meant goes in ${path.basename(made, path.extname(made))}.despite.txt with why`)
say(`${path.basename(made)} has a face cut, text too small, or text over what the shot shows: fix every ERROR above (reframe on the person, make the text bigger, move the text to the place it names; raea frames place TAKE shows a take's clear places), then render again. A face at the edge that's meant goes in ${path.basename(made, path.extname(made))}.despite.txt with why`)
process.exitCode = code
}
}
+284
View File
@@ -0,0 +1,284 @@
// Where text can go in a shot, and text laid where it hides what the shot is about (11-29, Shane on Dutch: "text being
// weirdly placed over footage where it blocks a person or place, dont we have methods of correctly guessing where text
// needs to go based on the scene? ... the rule of thirds, and placement of things over the scene").
//
// A frame's scene (the farm's POST /v1/scene: a person mask as a grid, faces, and the things a shot is about, a dog, a
// phone, a cup) becomes a cost for each grid cell: a face most, then a thing, then a person in the shot (the body
// itself, and the box around them a little), then the edges a phone's own buttons and captions cover; open ground is
// free. A text's cost is the mean of the cells it covers. A text is badly placed when it covers a face or a thing, or
// a person, and a place of the same size costs much less; that place is what's said.
//
// raea frames place FILE [--at S[,S...]] [--box WxH] [-o REPORT.json]
// FILE (a take or an export, a picture or a video) read at those seconds (a video: one a second, at most 12):
// the clearest places for a box WxH (in a 1080-wide frame; a caption, 840x110, by default), best first, as its
// top-left in pixels and in shares of the frame, and what each covers.
import path from "node:path"
/** a frame's scene, as the farm reads it (deploy/modal/farm_scene.py), in the pixels of the frame it was sent */
export type Scene = { w: number; h: number; grid: { cols: number; rows: number; people: string[] }; things: Thing[]; faces: Thing[] } | null
/** [x, y, w, h, label, score] */
export type Thing = [number, number, number, number, string, number]
/** a box in shares of the frame: x, y, w, h */
export type Box = [number, number, number, number]
/** what each covered cell costs */
const COST = { face: 10, thing: 6, body: 4, subject: 2, crowd: 0.5, edge: 5 }
/** a person whose box is this share of the frame's height or more is in the shot; smaller ones are passers-by */
const SUBJECT_MIN = 0.25
/** a face this share of the frame's height or more is someone in the shot (frames.ts FACE_MIN); smaller, a passer-by */
const FACE_IN_SHOT = 0.05
/** a thing this share of the frame's area or more is what the shot shows (a dog at someone's feet, a phone held up) */
const THING_MIN = 0.006
/** a text is badly placed when it costs this much or more, and a clear place costs this much less */
export const BAD = 1.6
export const BETTER = 1.2
/** the edges a phone's own interface covers on a tall frame (Reels and TikTok: the header, the buttons on the right,
* the caption and the bar at the bottom), in shares; a wide or square frame keeps a 5% margin all round */
export function safe(w: number, h: number): { top: number; bottom: number; left: number; right: number } {
return h / w > 1.5 ? { top: 0.07, bottom: 0.2, left: 0.04, right: 0.12 } : { top: 0.05, bottom: 0.05, left: 0.05, right: 0.05 }
}
export type Cost = { cols: number; rows: number; cost: Float32Array; why: Uint8Array }
/** why a cell costs what it does: 0 open, 1 crowd, 2 a person's box, 3 a body, 4 a thing, 5 a face, 6 the edge */
export const WHY = ["open ground", "passers-by", "a person in the shot", "a person in the shot", "", "a face", "the phone's own interface", "other text on screen"]
/** a box (shares) overlapping another by this share of the smaller one is the same place */
const overlaps = (a: Box, b: Box, share: number) => {
const ix = Math.max(0, Math.min(a[0] + a[2], b[0] + b[2]) - Math.max(a[0], b[0]))
const iy = Math.max(0, Math.min(a[1] + a[3], b[1] + b[3]) - Math.max(a[1], b[1]))
return ix * iy > share * Math.min(a[2] * a[3], b[2] * b[3])
}
const shareOf = (s: NonNullable<Scene>, t: Thing): Box => [t[0] / s.w, t[1] / s.h, t[2] / s.w, t[3] / s.h]
/** a scene as a cost per grid cell, and what each cell holds. `ours`: the render's own texts on this frame (the words
* the farm read there are ours, not the shot's); `others`: the ones a place must also stay off */
export function costs(s: NonNullable<Scene>, ours: Box[] = [], others: Box[] = []): Cost {
const { cols, rows, people } = s.grid
const cost = new Float32Array(cols * rows)
const why = new Uint8Array(cols * rows)
const set = (c: number, r: number, v: number, k: number) => {
if (c < 0 || r < 0 || c >= cols || r >= rows) return
const i = r * cols + c
if (v > cost[i]) {
cost[i] = v
why[i] = k
}
}
const cells = (t: Thing, pad = 0, inset = 0) => {
const [x, y, w, h] = t
const c0 = Math.floor(((x + w * inset) / s.w) * cols) - pad
const c1 = Math.ceil(((x + w * (1 - inset)) / s.w) * cols) - 1 + pad
const r0 = Math.floor((y / s.h) * rows) - pad
const r1 = Math.ceil(((y + h) / s.h) * rows) - 1 + pad
const out: [number, number][] = []
for (let r = r0; r <= r1; r++) for (let c = c0; c <= c1; c++) out.push([c, r])
return out
}
const persons = s.things.filter((t) => t[4] === "person")
for (const p of persons) {
const inShot = p[3] >= s.h * SUBJECT_MIN
// a person's box is loose around the body (the air between arms and legs): its middle costs more than its sides
for (const [c, r] of cells(p)) set(c, r, inShot ? COST.subject : COST.crowd, inShot ? 2 : 1)
if (inShot) for (const [c, r] of cells(p, 0, 0.15)) set(c, r, COST.subject + 1, 2)
}
// the body itself, where the mask sees it (a light coat it can miss; a card laid over it hides it, hence the box)
for (let r = 0; r < rows; r++) for (let c = 0; c < cols; c++) if (Number(people[r]?.[c] ?? 0) >= 4) set(c, r, COST.body, 3)
for (const t of s.things) {
if (t[4] === "person") continue
if (t[4] === "text" ? ours.some((o) => overlaps(o, shareOf(s, t), 0.4)) : (t[2] * t[3]) / (s.w * s.h) < THING_MIN) continue
for (const [c, r] of cells(t)) set(c, r, COST.thing, 4)
}
for (const o of others) for (const [c, r] of cells([o[0] * s.w, o[1] * s.h, o[2] * s.w, o[3] * s.h, "overlay", 1])) set(c, r, COST.thing, 7)
// a face and a cell around it: hair, chin, the mic at the mouth
for (const f of s.faces) {
if (f[3] >= s.h * FACE_IN_SHOT) for (const [c, r] of cells(f, 1)) set(c, r, COST.face, 5)
else for (const [c, r] of cells(f)) set(c, r, COST.crowd + 1, 1)
}
const sf = safe(s.w, s.h)
for (let r = 0; r < rows; r++)
for (let c = 0; c < cols; c++) {
const x = (c + 0.5) / cols
const y = (r + 0.5) / rows
if (y < sf.top || y > 1 - sf.bottom || x < sf.left || x > 1 - sf.right) set(c, r, COST.edge, 6)
}
return { cols, rows, cost, why }
}
/** labels of the things that make cells cost, for saying what a text covers */
function thingsUnder(s: NonNullable<Scene>, b: Box, ours: Box[] = []): string[] {
const out = new Set<string>()
for (const t of [...s.faces, ...s.things]) {
if (t[4] === "text" && ours.some((o) => overlaps(o, shareOf(s, t), 0.4))) continue
if (t[4] === "person" && t[3] < s.h * SUBJECT_MIN) continue
if (t[4] === "face" && t[3] < s.h * FACE_IN_SHOT) continue
if (t[4] !== "person" && t[4] !== "face" && (t[2] * t[3]) / (s.w * s.h) < THING_MIN) continue
const [x, y, w, h] = [t[0] / s.w, t[1] / s.h, t[2] / s.w, t[3] / s.h]
const ix = Math.max(0, Math.min(b[0] + b[2], x + w) - Math.max(b[0], x))
const iy = Math.max(0, Math.min(b[1] + b[3], y + h) - Math.max(b[1], y))
if (ix * iy > 0.12 * Math.min(w * h, b[2] * b[3])) out.add(t[4] === "person" ? "a person in the shot" : t[4] === "face" ? "a face" : t[4] === "text" ? "words in the shot (a sign)" : `a ${t[4].replace(/_/g, " ")}`)
}
return [...out]
}
/** the mean cost of the cells a box covers (each cell weighted by how much of it the box covers) */
export function boxCost(k: Cost, b: Box): number {
let sum = 0
let area = 0
const c0 = Math.max(0, Math.floor(b[0] * k.cols))
const c1 = Math.min(k.cols - 1, Math.ceil((b[0] + b[2]) * k.cols) - 1)
const r0 = Math.max(0, Math.floor(b[1] * k.rows))
const r1 = Math.min(k.rows - 1, Math.ceil((b[1] + b[3]) * k.rows) - 1)
for (let r = r0; r <= r1; r++)
for (let c = c0; c <= c1; c++) {
const ox = Math.min(b[0] + b[2], (c + 1) / k.cols) - Math.max(b[0], c / k.cols)
const oy = Math.min(b[1] + b[3], (r + 1) / k.rows) - Math.max(b[1], r / k.rows)
const a = Math.max(0, ox) * Math.max(0, oy)
sum += a * k.cost[r * k.cols + c]
area += a
}
return area ? sum / area : 0
}
/** where a box of this size costs least, over several frames together (a text's whole time on screen): candidates
* every 2% down and, for a box narrower than the frame's safe width, across too; a box on a third line (the rule of
* thirds) wins a tie */
export function places(ks: Cost[], w: number, h: number, size: [number, number], n = 3): { box: Box; cost: number }[] {
const sf = safe(w, h)
const out: { box: Box; cost: number }[] = []
const xs: number[] = []
const span = 1 - sf.left - sf.right - size[0]
if (span <= 0.02) xs.push(Math.max(0, (1 - size[0]) / 2))
else for (let x = sf.left; x <= sf.left + span + 1e-9; x += span / 4) xs.push(x)
for (let y = sf.top; y + size[1] <= 1 - sf.bottom + 1e-9; y += 0.02)
for (const x of xs) {
const b: Box = [x, y, size[0], size[1]]
const c = ks.reduce((s, k) => s + boxCost(k, b), 0) / ks.length
const mid = y + size[1] / 2
const third = Math.min(Math.abs(mid - 1 / 3), Math.abs(mid - 2 / 3))
// a wide box (a caption, a card) reads best centred; a narrow one may sit to a side
const centre = size[0] > 0.4 ? Math.abs(x + size[0] / 2 - (sf.left + (1 - sf.right)) / 2) * 1.5 : 0
out.push({ box: b, cost: c + third * 0.3 + centre })
}
out.sort((a, b) => a.cost - b.cost)
// the best few, apart from each other
const picked: { box: Box; cost: number }[] = []
for (const o of out) {
if (picked.some((p) => Math.abs(p.box[1] - o.box[1]) < size[1] && Math.abs(p.box[0] - o.box[0]) < size[0])) continue
picked.push(o)
if (picked.length >= n) break
}
return picked
}
export type Finding = { level: "error" | "warn"; kind: "text-over"; at: number | null; until?: number; says: string }
const px = (v: number, dim: number) => Math.round(v * dim)
/** each text the render's manifest shows, against the scenes of the frames it's on (sampled `rate` a second): one
* finding a text, when it covers a face, a thing or a person and a clearer place of its size exists */
export function textOver(manifest: any, scenes: Scene[], rate: number): Finding[] {
const W = Number(manifest?.width) || 1080
const H = Number(manifest?.height) || 1920
const fps = Number(manifest?.fps) || 30
// each text: its box (the ink with a margin, or the laid-out box when that's no bigger than twice the ink: a card's
// own box), and the sampled frames it's on
type On = { text: string; box: Box; from: number; to: number; frames: number[] }
// every text's box on each sampled frame
const onFrame = new Map<number, Box[]>()
const texts = new Map<string, On>()
for (const fr of (manifest?.frames ?? []) as any[]) {
const t0 = Number(fr?.frame ?? 0) / fps
const i = Math.round(t0 * rate)
if (Math.abs(i / rate - t0) > 0.5 / fps) continue
for (const t of (fr?.text ?? []) as any[]) {
const text = String(t?.text ?? "").trim()
if (!text || (t?.opacity ?? 1) <= 0.3) continue
const ink = (t?.ink ?? t?.box) as number[] | undefined
const lay = t?.box as number[] | undefined
if (!ink || ink.length < 4) continue
const useBox = lay && lay[2] * lay[3] <= 2 * ink[2] * ink[3]
const b = useBox ? lay! : [ink[0] - 12, ink[1] - 8, ink[2] + 24, ink[3] + 16]
const box: Box = [b[0] / W, b[1] / H, b[2] / W, b[3] / H]
const key = `${text}@${box.map((v) => v.toFixed(2)).join(",")}`
onFrame.set(i, [...(onFrame.get(i) ?? []), box])
const on = texts.get(key) ?? { text, box, from: t0, to: t0, frames: [] }
on.to = t0
if (!on.frames.includes(i)) on.frames.push(i)
texts.set(key, on)
}
}
// lines stacked into one block (a checklist, a two-line caption, a card's title and its line) move together: texts on
// the same frames whose boxes touch or nearly touch, one under the other
const all = [...texts.values()].sort((p, q) => p.box[1] - q.box[1])
const blocks: (On & { lines: number })[] = []
for (const t of all) {
const near = blocks.find((b) => {
const shared = t.frames.filter((f) => b.frames.includes(f)).length
const gap = t.box[1] - (b.box[1] + b.box[3])
const ox = Math.min(b.box[0] + b.box[2], t.box[0] + t.box[2]) - Math.max(b.box[0], t.box[0])
return shared * 2 >= Math.min(t.frames.length, b.frames.length) && gap < 0.02 && gap > -t.box[3] && ox > 0
})
if (!near) {
blocks.push({ ...t, frames: [...t.frames], lines: 1 })
continue
}
const x0 = Math.min(near.box[0], t.box[0])
const y0 = Math.min(near.box[1], t.box[1])
const x1 = Math.max(near.box[0] + near.box[2], t.box[0] + t.box[2])
const y1 = Math.max(near.box[1] + near.box[3], t.box[1] + t.box[3])
near.box = [x0, y0, x1 - x0, y1 - y0]
near.from = Math.min(near.from, t.from)
near.to = Math.max(near.to, t.to)
near.lines++
}
const out: Finding[] = []
for (const on of blocks) {
// the scene's cost on each of the block's frames: our own texts there aren't the shot's words, and the other texts
// on screen are places it can't go
const costAt = (i: number) => {
const s = scenes[i]
if (!s) return null
const ours = onFrame.get(i) ?? []
return costs(s, ours, ours.filter((b) => !overlaps(b, on.box, 0.5)))
}
const ks = on.frames.map(costAt).filter((k): k is Cost => !!k)
if (!ks.length) continue
const here = ks.reduce((s, k) => s + boxCost(k, on.box), 0) / ks.length
if (here < BAD) continue
const best = places(ks, W, H, [on.box[2], on.box[3]], 1)[0]
const under = [...new Set(on.frames.flatMap((i) => (scenes[i] ? thingsUnder(scenes[i]!, on.box, onFrame.get(i) ?? []) : [])))]
const what = under.length ? under.join(", ") : "what the shot shows"
const q = `${on.text.length > 40 ? `“${on.text.slice(0, 40)}...”` : `“${on.text}”`}${on.lines > 1 ? ` (and the ${on.lines - 1} line${on.lines > 2 ? "s" : ""} under it)` : ""}`
const when = on.to - on.from < 0.5 ? `at ${on.from.toFixed(1)} s` : `from ${on.from.toFixed(1)} s to ${on.to.toFixed(1)} s`
if (best && best.cost <= here - BETTER) {
const face = under.includes("a face")
out.push({ level: face || here >= BAD + 1.5 ? "error" : "warn", kind: "text-over", at: on.from, until: on.to, says: `${q} covers ${what} ${when}: move it to left ${px(best.box[0], W)} px, top ${px(best.box[1], H)} px (${Math.round(best.box[1] * 100)}% down), which is clear there. raea frames place shows the clear places in a shot` })
} else if (under.includes("a face")) {
out.push({ level: "error", kind: "text-over", at: on.from, until: on.to, says: `${q} covers a face ${when} and no place of its size is clear: make it smaller, put it on a shot with room, or cut to one` })
} else if (here >= BAD + 1.5) {
out.push({ level: "warn", kind: "text-over", at: on.from, until: on.to, says: `${q} covers ${what} ${when}, and no place of its size is clear in this shot: make it smaller, show it on a shot with room (a wider one, a cutaway), or as a card of its own` })
}
}
return out.sort((a, b) => (a.at ?? 0) - (b.at ?? 0))
}
/** `raea frames place`'s answer for a set of scenes and a box size (in a 1080-wide frame's pixels) */
export function placeReport(file: string, scenes: Scene[], size: [number, number]) {
const ss = scenes.filter((s): s is NonNullable<Scene> => !!s)
if (!ss.length) return { file, places: [] }
const w = ss[0].w
const h = ss[0].h
const scale = 1080 / Math.min(w, h)
const W = w * scale
const H = h * scale
const share: [number, number] = [size[0] / W, size[1] / H]
const ks = ss.map((s) => costs(s))
const ps = places(ks, w, h, share, 3)
return {
file: path.basename(file),
frame: [Math.round(W), Math.round(H)],
box: size,
places: ps.map((p) => ({ left: px(p.box[0], W), top: px(p.box[1], H), at: `${Math.round(p.box[1] * 100)}% down`, cost: Math.round(p.cost * 100) / 100, covers: [...new Set(ss.flatMap((s) => thingsUnder(s, p.box)))] })),
}
}
+298
View File
@@ -0,0 +1,298 @@
// `raea sound check` on a raea cloud box: what a cut's sound gets wrong that a listener hears at once, measured from the
// edit itself (its render manifest) against each source take's own words and sound, so it can't be passed by editing
// what the cut is "meant" to say (11-29, Shane on Dutch: "a lot of it is audio cuts, fading out words, putting in audio
// that is too low to hear but whisper picks up ... i dont really hear any sound effects being used").
//
// raea sound check VIDEO [--manifest RENDER.json] [-o REPORT.json]
// edit points: each voice clip's in and out against its take's words (TAKE.words.json beside the take; heard by
// the farm's Whisper when it has none) and its take's own level every 10 ms. A clip that starts or ends inside
// a word, or on sound (a word's tail, its first consonant), is an error, with the nearest gap to move it to.
// levels: each voice clip's speech level (its take's, plus its gainDb) against the cut's other lines: 6 dB or
// more apart is an error (a line too quiet to hear, that a transcriber still hears), 4 dB a warning; the
// gainDb that evens it is said.
// effects and music: an effect 10 dB or more under the voice is an error (no one hears it); music more than
// 26 dB under the voice, or within 6 dB of it, a warning.
// Exit 1 on any error. The report is VIDEO.sound-check.json beside it.
import { spawnSync } from "node:child_process"
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"
import os from "node:os"
import path from "node:path"
import { pathToFileURL } from "node:url"
import { hear, levels, type Word } from "./words.ts"
/** a voice clip's speech level is its take's loud 10 ms frames (the 90th percentile) inside the clip */
const SPEECH_Q = 0.9
/** at a cut point, sound this close to the speech level (dB) is speech still going: a word's tail or first consonant */
const ON_SOUND = 10
/** a gap to cut in: 40 ms at least this far under the speech level (dB), or, in a noisy take (a street), within
* GAP_FLOOR of its own quietest sound, but never closer than GAP_LEAST to the speech */
const GAP = 18
const GAP_FLOOR = 6
const GAP_LEAST = 8
/** a take's floor: its quietest 10 ms frames (the 10th percentile) around the clip */
const FLOOR_Q = 0.1
/** how far either side of a cut point a gap is looked for (s) */
const NEAR = 0.4
/** lines this far apart (dB) are an error, a warning */
const LEVEL_ERROR = 6
const LEVEL_WARN = 4
/** an effect this far under the voice (dB) isn't heard */
const SFX_UNDER = 10
/** music: further under than this isn't heard, closer than this fights the words */
const MUSIC_LOST = 26
const MUSIC_FIGHTS = 6
export type Finding = { level: "error" | "warn"; kind: "edit-in-word" | "edit-on-sound" | "level" | "effect-unheard" | "music" | "manifest"; at: number | null; says: string }
export type Clip = { key?: string; from: number; to: number; src: string; at: number; gainDb?: number; bus?: string; fadeIn?: number; fadeOut?: number }
export type Manifest = { fps?: number; length?: number; frames?: unknown[]; sounds?: { fps?: number; clips?: Clip[] } }
/** a take's level every 10 ms (dB) from `start` s on */
export type Levels = { start: number; db: number[] }
const MUSIC = /music|bed|score/i
const SFX = /sfx|fx|effect|foley|sting/i
export const busOf = (c: Clip): "voice" | "music" | "sfx" => (c.bus && MUSIC.test(c.bus) ? "music" : c.bus && SFX.test(c.bus) ? "sfx" : c.bus === "voice" || !c.bus ? (SFX.test(path.basename(c.src)) ? "sfx" : MUSIC.test(path.basename(c.src)) ? "music" : "voice") : "voice")
const pct = (xs: number[], q: number) => {
if (!xs.length) return -100
const s = [...xs].sort((a, b) => a - b)
return s[Math.min(s.length - 1, Math.floor(q * s.length))]
}
const at = (l: Levels, t: number) => l.db[Math.round((t - l.start) * 100)] ?? -100
/** the loudest 10 ms frame in [a, b] */
const peak = (l: Levels, a: number, b: number) => {
let m = -100
for (let t = a; t <= b + 1e-9; t += 0.01) m = Math.max(m, at(l, t))
return m
}
const secs = (t: number) => `${t.toFixed(2)} s`
/** the speech level of a clip's stretch of its take: its loud frames, inside its words when it has any */
export function speechLevel(l: Levels, a: number, b: number, words: Word[]): number {
const inWords = words.filter((w) => w.end > a && w.start < b)
const frames: number[] = []
for (let t = a; t < b; t += 0.01) if (!inWords.length || inWords.some((w) => t >= w.start && t <= w.end)) frames.push(at(l, t))
return pct(frames, SPEECH_Q)
}
/** the nearest time to `t` (within NEAR, never past `limit` on the clip's inside) that is a gap: 40 ms around it at
* least GAP dB under the speech level and inside no word */
/** the level under which a take is quiet enough to cut in: GAP under the speech, or near the take's own floor */
export const quietUnder = (l: Levels, ref: number) => Math.min(ref - GAP_LEAST, Math.max(ref - GAP, pct(l.db, FLOOR_Q) + GAP_FLOOR))
export function nearestGap(l: Levels, t: number, ref: number, words: Word[], inside: 1 | -1, limit: number): number | null {
const under = quietUnder(l, ref)
const quiet = (c: number) => (inside === 1 ? c <= limit : c >= limit) && peak(l, c - 0.02, c + 0.02) <= under && !words.some((w) => c > w.start - 0.01 && c < w.end + 0.01)
for (let d = 0; d <= NEAR + 1e-9; d += 0.01) {
for (const s of d ? [-1, 1] : [1]) {
const c = t + s * d
if (!quiet(c)) continue
// the middle of the gap it's in (a cut at a gap's edge takes a breath or a consonant with it), kept near t
let a = c
let b = c
while (a - 0.01 >= t - NEAR && quiet(a - 0.01)) a -= 0.01
while (b + 0.01 <= t + NEAR && quiet(b + 0.01)) b += 0.01
return Math.round(((a + b) / 2) * 100) / 100
}
}
return null
}
/** how close (s) a cut is to a boundary between two words that run together to count as on it (word timings are good
* to about 30 ms) */
const SEAM = 0.03
/** boundaries between words with no pause (under 80 ms) between them */
export function seams(words: Word[]): { at: number; before: string; after: string }[] {
const out: { at: number; before: string; after: string }[] = []
for (let i = 1; i < words.length; i++) {
const a = words[i - 1]
const b = words[i]
if (b.start - a.end < 0.08) out.push({ at: Math.round(((a.end + b.start) / 2) * 1000) / 1000, before: a.text, after: b.text })
}
return out
}
/** a voice clip's in and out: inside a word, or on sound */
export function editPoints(c: Clip, fps: number, words: Word[], l: Levels): Finding[] {
const out: Finding[] = []
const dur = (c.to - c.from) / fps
const tin = c.at
const tout = c.at + dur
const ref = speechLevel(l, tin, tout, words)
const name = path.basename(c.src)
for (const [edge, t, cutAt, inside] of [["in", tin, c.from / fps, 1], ["out", tout, c.to / fps, -1]] as const) {
const where = `the ${edge === "in" ? "start" : "end"} of the clip at ${secs(cutAt)} (${name} ${secs(t)})`
// speech that runs on with no pause still has its boundaries between words: a cut on one is tight, not a cut word
const seam = seams(words).find((x) => Math.abs(x.at - t) <= SEAM)
if (seam) {
const here = edge === "in" ? peak(l, t, t + 0.01) : peak(l, t - 0.01, t)
if (here >= ref - ON_SOUND)
out.push({ level: "warn", kind: "edit-on-sound", at: cutAt, says: `${where} is between “${seam.before}” and “${seam.after}” with no pause: a tight cut. Look at it on the waveform, or move it to a pause if one is near` })
continue
}
const word = words.find((w) => w.start + 0.02 < t && w.end - 0.02 > t)
const gap = nearestGap(l, t, ref, words, inside, inside === 1 ? tout - 0.1 : tin + 0.1)
const ms = (x: number) => `${x >= t ? "+" : ""}${Math.round((x - t) * 1000)} ms`
const bound = gap === null ? seams(words).filter((x) => Math.abs(x.at - t) <= NEAR && (inside === 1 ? x.at < tout - 0.1 : x.at > tin + 0.1)).sort((p, q) => Math.abs(p.at - t) - Math.abs(q.at - t))[0] : undefined
const move =
gap !== null
? `move it to ${secs(gap)} in ${name} (${ms(gap)}), the gap ${edge === "in" ? "before" : "after"} the words`
: bound
? `there's no pause within ${NEAR * 1000} ms; the nearest boundary between words is ${secs(bound.at)} in ${name} (${ms(bound.at)}, between “${bound.before}” and “${bound.after}”): cut there, or at another pause`
: `no pause or word boundary within ${NEAR * 1000} ms: cut at another pause, or take another line`
if (word) {
out.push({ level: "error", kind: "edit-in-word", at: cutAt, says: `${where} cuts “${word.text}” (${secs(word.start)}–${secs(word.end)}) in two: ${move}` })
continue
}
// the 10 ms just inside the cut: a word's onset a frame or two after an in point is a tight cut, not a cut one
const here = edge === "in" ? peak(l, t, t + 0.01) : peak(l, t - 0.01, t)
if (here >= Math.max(ref - ON_SOUND, pct(l.db, FLOOR_Q) + GAP_FLOOR + 2)) {
const near = words.reduce<Word | null>((b, w) => (Math.min(Math.abs(w.start - t), Math.abs(w.end - t)) < (b ? Math.min(Math.abs(b.start - t), Math.abs(b.end - t)) : 9) ? w : b), null)
out.push({ level: "error", kind: "edit-on-sound", at: cutAt, says: `${where} lands on sound ${Math.max(0, ref - here).toFixed(0)} dB under the speech${near ? `, ${Math.round(Math.min(Math.abs(near.start - t), Math.abs(near.end - t)) * 1000)} ms from “${near.text}”` : ""}: the word's ${edge === "in" ? "first sound" : "tail"} is cut. ${move[0].toUpperCase()}${move.slice(1)}` })
}
}
return out
}
export type Heard = { clip: Clip; kind: "voice" | "music" | "sfx"; level: number }
/** each voice line against the cut's others; effects and music against the voice */
export function balance(heard: Heard[], fps: number): Finding[] {
const out: Finding[] = []
const voice = heard.filter((h) => h.kind === "voice" && (h.clip.to - h.clip.from) / fps >= 0.4)
if (!voice.length) return out
const mid = pct(voice.map((h) => h.level), 0.5)
for (const h of voice) {
const d = h.level - mid
if (Math.abs(d) < LEVEL_WARN) continue
const g = (h.clip.gainDb ?? 0) - d
out.push({ level: Math.abs(d) >= LEVEL_ERROR ? "error" : "warn", kind: "level", at: h.clip.from / fps, says: `the line at ${secs(h.clip.from / fps)} (${path.basename(h.clip.src)} ${secs(h.clip.at)}) is ${Math.abs(d).toFixed(0)} dB ${d < 0 ? "under" : "over"} the cut's other lines${d < 0 ? ": too quiet to hear, though a transcriber still hears it" : ""}. Set its gainDb to ${g.toFixed(1)} (now ${(h.clip.gainDb ?? 0).toFixed(1)})` })
}
for (const h of heard.filter((x) => x.kind === "sfx")) {
const d = h.level - mid
if (d <= -SFX_UNDER)
out.push({ level: "error", kind: "effect-unheard", at: h.clip.from / fps, says: `the effect at ${secs(h.clip.from / fps)} (${path.basename(h.clip.src)}) peaks ${(-d).toFixed(0)} dB under the voice: no one hears it. Set its gainDb to about ${((h.clip.gainDb ?? 0) - d - 4).toFixed(1)} (4 dB under the voice), or cut it` })
}
for (const h of heard.filter((x) => x.kind === "music")) {
const d = h.level - mid
if (d < -MUSIC_LOST) out.push({ level: "warn", kind: "music", at: h.clip.from / fps, says: `the music (${path.basename(h.clip.src)}) sits ${(-d).toFixed(0)} dB under the voice: it's barely there. A bed under speech sits 12 to 20 dB under: gainDb about ${((h.clip.gainDb ?? 0) - d - 16).toFixed(1)}` })
else if (d > -MUSIC_FIGHTS) out.push({ level: "warn", kind: "music", at: h.clip.from / fps, says: `the music (${path.basename(h.clip.src)}) is within ${MUSIC_FIGHTS} dB of the voice: it fights the words. gainDb about ${((h.clip.gainDb ?? 0) - d - 16).toFixed(1)}` })
}
return out
}
/** the take a manifest names, on this box: its own path, or the part after a farm job's work/ under the project */
export function onBox(src: string, roots: string[]): string | null {
if (existsSync(src)) return src
const rel = src.includes("/work/") ? src.slice(src.lastIndexOf("/work/") + 6) : src.replace(/^\/+/, "")
for (const r of roots) {
const p = path.resolve(r, rel)
if (existsSync(p)) return p
}
return null
}
const wordsOf = (file: string) => `${file.slice(0, file.length - path.extname(file).length)}.words.json`
async function takeWords(file: string): Promise<Word[]> {
for (const p of [wordsOf(file), `${file}.words.json`]) {
if (existsSync(p)) {
const raw = JSON.parse(readFileSync(p, "utf8")) as ({ text: string; start_ms: number; end_ms: number } | Word)[] | { words: { text: string; start_ms: number; end_ms: number }[] }
const list = Array.isArray(raw) ? raw : raw.words
return list.map((w) => ("start_ms" in w ? { text: w.text, start: w.start_ms / 1000, end: w.end_ms / 1000 } : w))
}
}
const heard = await hear(file)
writeFileSync(wordsOf(file), `${JSON.stringify(heard.map((w) => ({ text: w.text, start_ms: Math.round(w.start * 1000), end_ms: Math.round(w.end * 1000) })))}\n`)
return heard
}
/** a take's level every 10 ms over [a, b] */
function takeLevels(file: string, a: number, b: number): Levels {
const start = Math.max(0, a)
const dir = mkdtempSync(path.join(os.tmpdir(), "raea-sound-"))
try {
const raw = path.join(dir, "a.raw")
const r = spawnSync("ffmpeg", ["-v", "error", "-y", "-ss", String(start), "-t", String(Math.max(0.05, b - start)), "-i", file, "-vn", "-ac", "1", "-ar", "16000", "-c:a", "pcm_s16le", "-f", "s16le", raw], { encoding: "utf8" })
if (r.status !== 0 || !existsSync(raw)) return { start, db: [] }
const buf = readFileSync(raw)
return { start, db: levels(new Int16Array(buf.buffer, buf.byteOffset, Math.floor(buf.length / 2))) }
} finally {
rmSync(dir, { recursive: true, force: true })
}
}
function flag(args: string[], name: string): string | undefined {
const i = args.indexOf(name)
return i >= 0 ? args[i + 1] : undefined
}
const stem = (v: string) => v.slice(0, v.length - path.extname(v).length)
/** the render's manifest: --manifest, else VIDEO.render.json (what raea cloud writes), else VIDEO.manifest.json */
export const manifestFor = (video: string, given?: string) => given ?? [`${stem(video)}.render.json`, `${stem(video)}.manifest.json`].find(existsSync) ?? `${stem(video)}.render.json`
export async function check(video: string, manifestPath: string, roots: string[]): Promise<{ findings: Finding[]; voice: number }> {
const m = JSON.parse(readFileSync(manifestPath, "utf8")) as Manifest
const fps = m.sounds?.fps ?? m.fps ?? 30
const found: Finding[] = []
const length = m.length ?? 0
const frames = m.frames?.length ?? 0
if (length > 1 && frames < length * 0.9)
found.push({ level: "error", kind: "manifest", at: null, says: `${path.basename(manifestPath)} holds ${frames} of the cut's ${length} frames, so its edit can't be checked: render the cut again (a render on raea cloud's GPUs before 11-29 kept frame 0's alone)` })
const clips = m.sounds?.clips ?? []
const heard: Heard[] = []
let voice = 0
for (const c of clips) {
const kind = busOf(c)
const file = onBox(c.src, roots)
if (!file) {
found.push({ level: "warn", kind: "manifest", at: c.from / fps, says: `${c.src} isn't on this box: its clip at ${secs(c.from / fps)} isn't checked` })
continue
}
const dur = (c.to - c.from) / fps
if (kind === "voice") {
voice++
const words = await takeWords(file)
const l = takeLevels(file, c.at - NEAR - 0.1, c.at + dur + NEAR + 0.1)
found.push(...editPoints(c, fps, words, l))
heard.push({ clip: c, kind, level: speechLevel(l, c.at, c.at + dur, words) + (c.gainDb ?? 0) })
} else {
const l = takeLevels(file, c.at, c.at + Math.min(dur, kind === "sfx" ? 2 : 20))
const level = kind === "sfx" ? pct(l.db, 0.98) : pct(l.db.filter((x) => x > -70), 0.5)
heard.push({ clip: c, kind, level: level + (c.gainDb ?? 0) })
}
}
found.push(...balance(heard, fps))
return { findings: found.sort((a, b) => (a.at ?? -1) - (b.at ?? -1)), voice }
}
export async function main(args: string[]): Promise<number> {
const a = args[0] === "check" ? args.slice(1) : args
const video = a.find((x, i) => !x.startsWith("-") && !["--manifest", "-o"].includes(a[i - 1] ?? ""))
if (!video || !existsSync(video)) {
console.error("usage: raea sound check VIDEO [--manifest RENDER.json] [-o REPORT.json] (edit points inside words or on sound, lines too quiet to hear, effects no one hears)")
return 2
}
const man = manifestFor(video, flag(a, "--manifest"))
if (!existsSync(man)) {
console.error(`raea sound check: no manifest for ${path.basename(video)} (${path.basename(man)}): render it with --manifest, or on raea cloud, which writes VIDEO.render.json`)
return 2
}
// the project the takes are under: here, and each folder above the video up to here
const roots = [process.cwd()]
for (let d = path.dirname(path.resolve(video)); d.startsWith(process.cwd()) && d !== process.cwd(); d = path.dirname(d)) roots.push(d)
const { findings, voice } = await check(video, man, roots)
for (const x of findings) console.log(`${x.level === "error" ? "ERROR" : "WARN "} ${x.at === null ? "" : `${x.at.toFixed(2)} s `}${x.says}`)
const errors = findings.filter((x) => x.level === "error").length
const report = flag(a, "-o") ?? `${stem(video)}.sound-check.json`
writeFileSync(report, `${JSON.stringify({ object: "sound.check", video, manifest: man, voice_clips: voice, passed: errors === 0, errors, warnings: findings.length - errors, findings }, null, 1)}\n`)
console.log(`${errors ? "FAILED" : "PASSED"} ${path.basename(video)}: ${voice} voice clips, ${errors} errors, ${findings.length - errors} warnings; ${path.basename(report)}`)
return errors ? 1 : 0
}
if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
const a = process.argv.slice(2)
main(a[0] === "sound" ? a.slice(1) : a).then(
(c) => process.exit(c),
(e) => (console.error(`raea sound: ${(e as Error).message}`), process.exit(1)),
)
}
+19 -1
View File
@@ -45,7 +45,17 @@ class FakeGpu:
if video:
# the run as one H.264 video, as raea render --at FRAMES -o run.mp4 writes it
run(["ffmpeg", "-y", "-loglevel", "error", "-f", "lavfi", "-i", "color=c=gray:s=16x16:r=30", "-frames:v", str(len(frames)), "-c:v", "libx264", "-pix_fmt", "yuv420p", f"{dest}/run-{first:05d}.mp4"])
return {"code": 0, "out": "", "s": 12 + 0.5 * len(frames), "frames": len(frames), "ms": 500.0}
# and its manifest, as raea writes one for --at's frames: those frames, and each sound cut to them (a clip's
# `at` is its source time at the run's first frame). One voice clip over frames 0-39, another from 40
a, z = frames[0], frames[-1] + 1
clips = []
if a < 40:
clips.append({"key": "n3", "from": a, "to": min(z, 40), "src": "/w/media/take.mov", "at": 1.0 + a / 30, "gainDb": 0.0, "bus": "voice", **({"fadeIn": 0.012} if a == 0 else {})})
if z > 40:
f = max(a, 40)
clips.append({"key": "n8", "from": f, "to": z, "src": "/w/media/take.mov", "at": 9.0 + (f - 40) / 30, "gainDb": -2.0, "bus": "voice", **({"fadeOut": 0.012} if z == self.length else {})})
man = {"width": 1920, "height": 1080, "fps": 30, "length": self.length, "frames": [{"frame": f, "videos": [], "text": [{"text": f"t{f}"}]} for f in frames], "findings": [], "sounds": {"fps": 30, "clips": clips, "notes": [], "lines": []}}
return {"code": 0, "out": "", "s": 12 + 0.5 * len(frames), "frames": len(frames), "ms": 500.0, "manifest": man}
for f in frames:
if f >= first:
self.png(f"{dest}/frame-{f:05d}.png")
@@ -104,6 +114,14 @@ assert code == 0, lines
assert all("--manifest" not in a and "--quality" in a for a in m.args), m.args
assert json.load(open(os.path.join(root, "jobs", "jm", "work", "out", "a.render.json")))["length"] == 60
ok("a render's own --manifest isn't passed to the GPUs (the probe would lose the length), and is written at the end")
# 11-29 (Dutch): the manifest written was frame 0's alone, so a cut's edit (every clip, where it starts in its source) was
# lost and nothing could check its edit points. It's the runs' own manifests joined: every frame, each clip whole
man = json.load(open(os.path.join(root, "jobs", "jm", "work", "out", "a.render.json")))
assert [f["frame"] for f in man["frames"]] == list(range(60)), [f["frame"] for f in man["frames"]][:12]
clips = sorted(man["sounds"]["clips"], key=lambda c: c["from"])
assert [(c["key"], c["from"], c["to"]) for c in clips] == [("n3", 0, 40), ("n8", 40, 60)], clips
assert abs(clips[0]["at"] - 1.0) < 1e-6 and abs(clips[1]["at"] - 9.0) < 1e-6 and clips[0].get("fadeIn") == 0.012 and clips[1].get("fadeOut") == 0.012, clips
ok("a split render's manifest is its runs' joined: all 60 frames, and each clip whole with its source time")
lines.clear()
long = FakeGpu(root, length=1000)
+1
View File
@@ -0,0 +1 @@
{"a": {"w": 540, "h": 960, "grid": {"cols": 27, "rows": 48, "people": ["222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222456542222222222222", "222222246777763222222222222", "222222267777776322222222222", "222222277777777522222222222", "222222267777777732222222222", "222222267777777752222222222", "222222267777777773222222222", "222222247777777775222222222", "222222224677777777322222222", "222222222677777777522222222", "222223322677777777632222222", "222323323777777777732222222", "225533324777777777752222222", "224653224777777777763222222", "222554325777777777774222222", "222454435777777777776222222", "222444334777777777776222222", "222433333567777777777322222", "222223323445677777777422222", "222222322333345666666422222", "222222322333345666666422222", "222222232344445666664222222", "222222233344545556663222222", "222222223344444555553222222", "222222223334444444443222222", "222222222223332323332222222", "222222222223332222232222222", "222222222333333222232222222", "222222222333333222332222222", "222222222223322222322222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222"]}, "things": [[26.2, 134.5, 409.7, 600.0, "person", 0.887], [422.1, 49.1, 117.8, 310.0, "person", 0.87], [96.8, 73.6, 26.0, 77.0, "person", 0.752], [318.6, 59.3, 34.7, 64.6, "person", 0.682], [0.2, 95.0, 29.7, 92.3, "person", 0.575], [384.2, 56.3, 49.6, 71.9, "person", 0.566], [148.7, 94.7, 25.4, 35.7, "person", 0.49], [202.9, 65.2, 35.5, 71.9, "person", 0.479], [421.5, 57.1, 55.3, 213.8, "person", 0.377], [1.3, 65.8, 24.1, 46.5, "person", 0.357], [176.0, 878.0, 165.0, 76.0, "text", 0.978], [362.0, 844.0, 149.0, 57.0, "text", 0.94], [179.0, 816.0, 182.0, 65.0, "text", 0.978], [366.0, 776.0, 171.0, 62.0, "text", 0.987], [183.0, 742.0, 191.0, 80.0, "text", 0.986], [180.0, 677.0, 180.0, 35.0, "text", 0.993], [181.0, 611.0, 182.0, 36.0, "text", 0.99], [154.0, 573.0, 238.0, 25.0, "text", 0.991], [146.0, 529.0, 258.0, 25.0, "text", 0.989]], "faces": [[131.1, 174.9, 82.5, 143.1, "face", 0.878], [332.9, 60.6, 12.0, 15.0, "face", 0.788], [435.5, 67.1, 20.6, 23.9, "face", 0.711], [421.1, 61.4, 11.2, 13.5, "face", 0.678]]}, "b": {"w": 540, "h": 960, "grid": {"cols": 27, "rows": 48, "people": ["222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222234332222222222", "222222222223677764222222222", "222222222225777777322222222", "222222222227777777622222222", "222222222237777777732222222", "222222222227777777752222222", "222222222226777777762222222", "222222222225777777773222222", "222222222225777777775222222", "222222222456777777776322222", "222222224777777777777622222", "222222236667777777777732222", "222222256667777777777752222", "222222366666677777777762222", "222222366666677777777762222", "222222456666777777777762222", "222222466666777777777762222", "222223566666777777777763222", "222223566667777777777653222", "222223466667777777777543222", "222223356667777777777432222", "222223335666777777776332222", "222222335666666666764222222", "222222356556556554543222222", "222222365555444333332222222", "222222354443333333222222222", "222222343333222222222222222", "222222343322222222222222222", "222222333222222222222222222", "222222232222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222"]}, "things": [[112.8, 117.2, 356.1, 835.9, "person", 0.867], [145.0, 677.0, 252.0, 37.0, "text", 0.994]], "faces": [[216.5, 193.3, 78.6, 128.6, "face", 0.902], [138.4, 362.6, 54.1, 79.0, "face", 0.739]]}, "c": {"w": 540, "h": 960, "grid": {"cols": 27, "rows": 48, "people": ["222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222332222222222", "222222222222225664222222222", "222222222222247777322222222", "222222222222257777522222222", "222222222222367777522222222", "222222222223677777522222222", "222222222236777777622222222", "222222222367777777622222222", "222222222577777777733Line truncated
+40
View File
@@ -0,0 +1,40 @@
// Text placement (server/place.ts) on three frames of street interviews, read by the farm's scene models
// (deploy/modal/farm_scene.py; the fixture holds only their boxes and grids): node test/place.ts
// 11-29 (Dutch): a caption laid over the dog the shot is about, a checklist on a woman's lap, beside a sign that is the
// ad's own hook
import assert from "node:assert/strict"
import { readFileSync } from "node:fs"
import { placeReport, textOver } from "../server/place.ts"
const ok = (m: string) => console.log(`ok ${m}`)
const sc = JSON.parse(readFileSync(new URL("./fixtures/scenes-interview.json", import.meta.url), "utf8"))
const t = (text: string, x: number, y: number, w: number, h: number) => ({ text, box: [x, y, w, h], ink: [x + 10, y + 6, w - 20, h - 12], opacity: 1, size: 48 })
const man = (texts: unknown[]) => ({ width: 1080, height: 1920, fps: 30, frames: [{ frame: 0, text: texts }] })
// c: a woman sitting with her dog; the caption on the dog, the hook over the crowd behind her
const c = textOver(man([t("$1,000 for one vet visit?", 116, 236, 848, 112), t("He hurt his little", 290, 1335, 630, 90)]), [sc.c], 1)
assert.equal(c.length, 1, JSON.stringify(c))
assert.equal(c[0].level, "error")
assert.match(c[0].says, /“He hurt his little” covers a dog/)
const top = Number(/top (\d+) px/.exec(c[0].says)?.[1])
assert.ok(top >= 1380, `moved below the dog, not ${top}`)
ok("a caption over the dog is an error, moved to the clear ground under it; the hook over passers-by is fine")
// a: a checklist on a woman's lap, a sign under her, a man standing behind: no clear place for a block that size
const a = textOver(man([t("✓ 24/7 virtual vet care", 256, 1044, 568, 80), t("✓ Price-matched Rx", 280, 1130, 520, 76), t("✓ Free delivery", 336, 1214, 410, 76)]), [sc.a], 1)
assert.equal(a.length, 1, "the checklist's three lines are one block")
assert.match(a[0].says, /and the 2 lines under it\) covers a person in the shot/)
assert.match(a[0].says, /no place of its size is clear/)
ok("a checklist on a person is said once for its block, and that no place its size is clear")
// the clearest places for a caption in a: never on the sign, which is the ad's hook
const pa = placeReport("a.jpg", [sc.a], [840, 110])
assert.ok(pa.places.length >= 2)
assert.ok(!pa.places[0].covers.includes("words in the shot (a sign)"), JSON.stringify(pa.places[0]))
assert.ok(pa.places[0].top < 400, JSON.stringify(pa.places[0]))
ok("raea frames place keeps a caption off the sign in the shot")
// b: a woman filling the frame; a caption over her coat is at most a warning
const b = textOver(man([t("Did you know you", 272, 1344, 536, 88)]), [sc.b], 1)
assert.ok(b.every((x) => x.level === "warn"), JSON.stringify(b))
ok("a caption over a person who fills the frame is at most a warning")
+80
View File
@@ -0,0 +1,80 @@
// `raea sound check`'s measures (server/sound.ts), on made-up takes: node test/sound.ts
// 11-29 (Dutch): words cut in two at a clip's edge, a guest's line 15 dB under the host's, effects 18 dB under the voice
import assert from "node:assert/strict"
import { balance, busOf, editPoints, nearestGap, type Clip, type Heard, type Levels } from "../server/sound.ts"
const ok = (m: string) => console.log(`ok ${m}`)
// a take: words at 1.00-1.40, 1.50-1.90 ("very" "loud") and 2.40-2.80 ("next"); speech at -20 dB, the street at -50
const words = [
{ text: "very", start: 1.0, end: 1.4 },
{ text: "loud", start: 1.5, end: 1.9 },
{ text: "next", start: 2.4, end: 2.8 },
]
const db: number[] = []
for (let t = 0; t < 4; t += 0.01) db.push(words.some((w) => t >= w.start - 0.005 && t <= w.end + 0.005) ? -20 : -50)
const take: Levels = { start: 0, db }
const fps = 30
const clip = (at: number, dur: number, extra: Partial<Clip> = {}): Clip => ({ key: "n1", from: 30, to: 30 + Math.round(dur * fps), src: "/w/work/media/raw/take.mov", at, gainDb: 0, bus: "voice", ...extra })
// cut in the gaps: 0.90 to 2.10 (both edges in silence)
assert.deepEqual(editPoints(clip(0.9, 1.2), fps, words, take), [])
ok("a clip cut in the gaps around its words passes")
// out at 1.70: inside "loud"
const inWord = editPoints(clip(0.9, 0.8), fps, words, take)
assert.equal(inWord.length, 1)
assert.equal(inWord[0].kind, "edit-in-word")
assert.match(inWord[0].says, /“loud”/)
assert.match(inWord[0].says, /move it to 1\.4\d s/)
ok("an out point inside a word is an error, with the gap before it to move to")
// in at 1.01: a hair past the start of "very" (inside the 20 ms grace), so it's on sound, not inside the word
const onSound = editPoints(clip(1.01, 1.0), fps, words, take)
assert.equal(onSound[0]?.kind, "edit-on-sound", JSON.stringify(onSound))
assert.match(onSound[0].says, /first sound/)
ok("an in point on a word's first sound is an error")
// "loud" and "next" run together with no pause: a cut on their boundary is tight (a warning), not a cut word
const run = [{ text: "say", start: 1.0, end: 1.4 }, { text: "so", start: 1.42, end: 1.7 }, { text: "then", start: 1.72, end: 2.0 }]
const runDb: number[] = []
for (let t = 0; t < 4; t += 0.01) runDb.push(t >= 0.995 && t <= 2.005 ? -20 : -50)
const tight = editPoints(clip(0.9, 0.81), fps, run, { start: 0, db: runDb })
assert.deepEqual(tight.map((x) => [x.level, x.kind]), [["warn", "edit-on-sound"]], JSON.stringify(tight))
assert.match(tight[0].says, /between “so” and “then”/)
const cutSo = editPoints(clip(0.9, 0.65), fps, run, { start: 0, db: runDb })
assert.equal(cutSo[0]?.level, "error")
assert.match(cutSo[0].says, /no pause within 400 ms; the nearest boundary between words is 1\.71 s/)
ok("a cut on the boundary of words that run together is a warning; inside one, the nearest boundary is said")
assert.equal(nearestGap(take, 1.7, -20, words, -1, 1.0), 1.45)
assert.equal(nearestGap({ start: 0, db: db.map(() => -20) }, 1.7, -20, [], -1, 0), null)
ok("the nearest gap is found, and a take with none says so")
// levels: three lines at -14, one guest at -29 (15 dB under: Gigi's hook B); an effect at -32; music at -50
const line = (from: number, level: number, extra: Partial<Clip> = {}): Heard => ({ clip: { ...clip(1, 2), from, to: from + 60, ...extra }, kind: "voice", level })
const heard: Heard[] = [
line(0, -14),
line(60, -29, { src: "/w/work/media/raw/guest.mov" }),
line(120, -15),
line(180, -13),
{ clip: { ...clip(0, 1), from: 90, to: 120, src: "/w/work/media/elevenlabs/sfx_pop.mp3", bus: "sfx", gainDb: -14 }, kind: "sfx", level: -32 },
{ clip: { ...clip(0, 20), from: 0, to: 600, src: "/w/work/media/elevenlabs/music.mp3", bus: "music", gainDb: -20 }, kind: "music", level: -50 },
]
const b = balance(heard, fps)
const quiet = b.find((x) => x.kind === "level")
assert.equal(quiet?.level, "error")
assert.match(quiet!.says, /guest\.mov/)
assert.match(quiet!.says, /15 dB under/)
assert.match(quiet!.says, /gainDb to 15\.0/)
assert.equal(b.filter((x) => x.kind === "level").length, 1, "the lines within 4 dB of each other pass")
const sfx = b.find((x) => x.kind === "effect-unheard")
assert.equal(sfx?.level, "error")
assert.match(sfx!.says, /18 dB under the voice/)
assert.equal(b.find((x) => x.kind === "music")?.level, "warn")
ok("a line 15 dB under the others is an error with the gain that evens it; an effect 18 dB under is unheard; buried music is said")
assert.equal(busOf({ ...clip(0, 1), bus: undefined, src: "/x/media/elevenlabs/sfx_tap.mp3" }), "sfx")
assert.equal(busOf({ ...clip(0, 1), bus: undefined, src: "/x/media/raw/Interview1.MOV" }), "voice")
assert.equal(busOf({ ...clip(0, 1), bus: "music", src: "/x/a.mp3" }), "music")
ok("a clip's kind from its bus, or its file's name when it has none")
+89
View File
@@ -0,0 +1,89 @@
# Playable ads: raea/playable and `raea playable`
A playable ad is a short game served in place of a video ad inside other apps (AppLovin, Unity, Google, Meta,
Moloco, Mintegral, TikTok, Liftoff). It ends on a card that opens the store. In raea it is a game written the usual
way (`games`), and the same file is both ads: `raea render` makes the video ad, because nobody touches it and it plays
itself, and `raea playable` makes the playable for each network.
## The shape
- **It plays itself until the first touch.** Before anyone touches it, the step plays (a hand, a ghost finger, the
computer making the best move each second). The first touch hands control over, and the hand goes. This is also
what the video ad shows.
- **The move is clear in two seconds.** One gesture: drag, tap a group, swipe a lane. Show it with the hand, not
words. A line of instructions is the rut.
- **A fail moment comes early.** Somewhere between 10 and 30 seconds the player nearly wins or just loses ("So
close!", a tower one short). That is what sends people to the store.
- **The card comes within 30 to 60 seconds.** End on `<EndCard>` when the game is over, won or lost, and never later
than the composition's last frame (the host shows its own card there).
- **Both orientations.** Register a portrait composition (1080x1920) and a landscape one (1920x1080) from the same
game. The host plays the one nearest the screen's shape; with one only, the other is letterboxed. Unity, AppLovin,
Moloco and Mintegral want both.
- **Words stay big.** A phone shows the composition scaled down: titles at 80 px and more, nothing under 36 px at
1080 wide.
## The store
```tsx
import { EndCard, InstallButton, install } from "raea/playable";
<EndCard show={g.over !== ""} title={g.over === "won" ? "Wall cleared!" : "So close!"} subtitle="Can you clear the wall?" cta="Try again" />
```
- `<EndCard show>` covers the game, and a tap anywhere on it opens the store (`end()` is called when it first shows).
`title`, `subtitle`, `icon` (an imported picture), `cta`, `background`, `font`, `color` and `button` set it; what
you put inside it (a logo, a product) goes between the words and the button.
- `<InstallButton>` is a button anywhere in the game; `install()` opens the store from your own tap handler.
- Outside an export (a render, a preview) they draw but do nothing. The store links come from the export's `--ios` and
`--android`.
## Input
- Read the pointer and touches from the frame's input as in any game: `input.pointer` (`x`, `y` in composition px,
`down`) and `input.touches`. Keys work too, for testing in a browser.
- The host samples input once a frame. A tap shorter than a frame can be missed, so act on the press (`down` becoming
true), not on a quick down-and-up within one frame.
## What a playable can't have
`raea playable` refuses these before it bundles:
- `staticFile()`. Import the file instead (`import icon from "./icon.png"`), and the export carries it in the page.
- Any URL, `fetch`, XHR or WebSocket. Networks refuse a page that makes a request.
- Modules that need the native engine: raea/native, raea/ml, raea/character, raea/physics, raea/media,
raea/matchmove and raea/modelling.
- `<Video>` and `<Audio>`, until sound comes to playables.
- 3D outside what the host draws: meshes (box, sphere, plane, cylinder, cone, torus, capsule, circle, ring), the
standard, physical and basic materials, perspective and orthographic cameras, the five light kinds, fog, tone
mapping, shadows and anti-aliasing. Models, splats and water stay in the video ad.
A font is carried the same way: import it (`import arvo from "./Arvo-Bold.ttf"`) and name it in an `@font-face` in a
`<style>`, ``src: url(${arvo})``. A font named but not imported isn't there on a phone, which draws its own sans-serif.
`<EndCard>` takes `font`, `color` and `button` (a style for its button), so a brand's card is in the brand's type.
## Export and check
```sh
raea add three@0.185.0 # once per project: the playable's 3D renderer
raea render game.tsx -o out/video-ad.mp4 # the video ad
raea playable game.tsx -o out/playable --ios https://apps.apple.com/app/id123 --android https://play.google.com/store/apps/details?id=com.example
```
It prints each network's file and its size against the 5 MB cap; a page is usually 1.3 to 1.5 MB, most of it
three.js. `--networks applovin,google,preview` makes fewer, `--title` and `--cta` set the host's own card, and
`--orientation` sets what Google and TikTok are told.
Play the `preview` page yourself before handing it over: open it at a phone's size, drag, lose, and tap the card. In
raea's own checkout, `bun sdk/playable/tools/check.ts PAGE.html OUT` plays it in WebKit, as an iPhone's ad view does,
and fails on an error, a request, or a card that opens nothing.
## How it fails
| What you see | Why | What to change |
|---|---|---|
| nothing moves until it's touched | the step only reads input | let the step play itself when nobody has touched it |
| the hand keeps playing after a touch | `touched` isn't kept in the state | set it in the step on the first press, and stop the hand from then |
| a tap does nothing | the press lasted less than a frame, or the step waits for the release | act on `down` |
| the page is refused for a request | a URL or `staticFile` in the source, or a font from the web | import the file; take the URL out |
| it's letterboxed on a phone | one orientation registered | register the other shape |
| the video ad shows the end card early | the self-play loses too fast | tune the self-play so it nearly wins |
+13
View File
@@ -0,0 +1,13 @@
src/host/tony.bin is the tone-mapping table Tony McMapface, resampled by tools/tony.ts from Bevy's copy of it.
Tony McMapface
Copyright (c) 2023 Tomasz Stachowiak
https://github.com/h3r2tic/tony-mc-mapface
Licensed under MIT.
Bevy's copy: bevy_core_pipeline's tonemapping/luts/tony_mc_mapface.ktx2
https://github.com/bevyengine/bevy
Licensed under MIT OR Apache-2.0.
host/tonemap.ts samples it as Bevy's tonemapping shader does. The rest of raea/playable is raea's own, under the
repository's licence.
+66
View File
@@ -0,0 +1,66 @@
{
"lockfileVersion": 2,
"configVersion": 1,
"workspaces": {
"": {
"name": "@raea/playable",
"dependencies": {
"react": "file:../raea/node_modules/react",
"react-dom": "file:../raea/node_modules/react-dom",
"scheduler": "file:../raea/node_modules/scheduler",
"three": "0.180.0",
},
"devDependencies": {
"@types/bun": "1.4.3",
"@types/react-dom": "19.2.0",
"@types/three": "0.180.0",
"playwright-core": "1.64.1",
},
},
},
"packages": {
"@dimforge/rapier3d-compat": ["@dimforge/[email protected]", "", {}, "sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow=="],
"@tweenjs/tween.js": ["@tweenjs/[email protected]", "", {}, "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA=="],
"@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.4.3" } }, "sha512-N67Pqy8JXbAY/j0tNraS3V5mubGvc6rrrNDmDCtZLlFzccbUJPDb0tvgUBC5q4m8ybkP93Jcn1QB+RYQ6PvBhw=="],
"@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog=="],
"@types/react": ["@types/[email protected]", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg=="],
"@types/react-dom": ["@types/[email protected]", "", { "peerDependencies": { "@types/react": "^19.2.0" } }, "sha512-brtBs0MnE9SMx7px208g39lRmC5uHZs96caOJfTjFcYSLHNamvaSMfJNagChVNkup2SdtOxKX1FDBkRSJe1ZAg=="],
"@types/stats.js": ["@types/[email protected]", "", {}, "sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA=="],
"@types/three": ["@types/[email protected]", "", { "dependencies": { "@dimforge/rapier3d-compat": "~0.12.0", "@tweenjs/tween.js": "~23.1.3", "@types/stats.js": "*", "@types/webxr": "*", "@webgpu/types": "*", "fflate": "~0.8.2", "meshoptimizer": "~0.22.0" } }, "sha512-ykFtgCqNnY0IPvDro7h+9ZeLY+qjgUWv+qEvUt84grhenO60Hqd4hScHE7VTB9nOQ/3QM8lkbNE+4vKjEpUxKg=="],
"@types/webxr": ["@types/[email protected]", "", {}, "sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg=="],
"@webgpu/types": ["@webgpu/[email protected]", "", {}, "sha512-lgiI4hbuLcI9unnm2cL/tvCaQU45dp0xcLWJh5uB/9MBGvIA4F8XIk7nSiBeg+K4xWGYwgZKn80LmERI5CxoTA=="],
"bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-tinRJNGOmUN+tEAsn2y2e942n9JHRHR42iUYzDH75NmhJqVBokGSQkkfSFdNWwsANIdrK6ACH9t01M452YyTwg=="],
"csstype": ["[email protected]", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="],
"fflate": ["[email protected]", "", {}, "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA=="],
"meshoptimizer": ["[email protected]", "", {}, "sha512-IebiK79sqIy+E4EgOr+CAw+Ke8hAspXKzBd0JdgEmPHiAwmvEj2S4h1rfvo+o/BnfEYd/jAOg5IeeIjzlzSnDg=="],
"playwright-core": ["[email protected]", "", { "bin": { "playwright-core": "cli.js" } }, "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ=="],
"react": ["react@file:../raea/node_modules/react", {}],
"react-dom": ["react-dom@file:../raea/node_modules/react-dom", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.0" } }],
"scheduler": ["scheduler@file:../raea/node_modules/scheduler", {}],
"three": ["[email protected]", "", {}, "sha512-o+qycAMZrh+TsE01GqWUxUIKR1AL0S8pq7zDkYOQw8GqfX8b8VoCKYUoHbhiX5j+7hr8XsuHDVU6+gkQJQKg9w=="],
"undici-types": ["[email protected]", "", {}, "sha512-EXE4ydL3S76dFb27UFjNVZHTyv/TLdATj/KUe29ptdcg6qXL48J2tZ3126E5kICj5jn781OR+XlVH1N6Mz8jbA=="],
"@types/node/undici-types": ["[email protected]", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="],
"react-dom/scheduler": ["[email protected]", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="],
}
}
+26
View File
@@ -0,0 +1,26 @@
{
"name": "@raea/playable",
"license": "FSL-1.1-ALv2",
"private": true,
"version": "0.1.0",
"description": "raea games as playable ads: the install call and end card authors use (raea/playable), and the browser host a playable export runs the game in (a fixed-step clock, touch input, the 3D drawn by three.js), docs/playables.feature.",
"type": "module",
"main": "src/index.ts",
"exports": {
".": "./src/index.ts",
"./host": "./src/host/main.tsx"
},
"//": "React is the SDK's own copy (sdk/raea), linked, so a game and the host share one React",
"dependencies": {
"react": "file:../raea/node_modules/react",
"react-dom": "file:../raea/node_modules/react-dom",
"scheduler": "file:../raea/node_modules/scheduler",
"three": "0.180.0"
},
"devDependencies": {
"@types/bun": "1.4.3",
"@types/react-dom": "19.2.0",
"@types/three": "0.180.0",
"playwright-core": "1.64.1"
}
}
+89
View File
@@ -0,0 +1,89 @@
// The two pieces of page every playable has: a button that opens the store, and the end card shown when the game is
// over. Plain page elements, so a raea render draws them as the playable does.
import { useEffect, type CSSProperties, type ReactNode } from "react";
import { end, install } from "./network";
export interface InstallButtonProps {
children?: ReactNode;
style?: CSSProperties;
}
const BUTTON: CSSProperties = {
border: "none",
borderRadius: 999,
padding: "0.7em 1.6em",
fontFamily: "Inter, system-ui, sans-serif",
fontWeight: 800,
fontSize: 40,
color: "#101422",
background: "#ffd166",
boxShadow: "0 6px 0 rgba(0,0,0,0.25)",
cursor: "pointer",
};
/** Opens the store when tapped (install()). */
export function InstallButton({ children = "Install", style }: InstallButtonProps) {
return (
<button
type="button"
onPointerUp={(e) => {
e.stopPropagation();
install();
}}
style={{ ...BUTTON, ...style }}
>
{children}
</button>
);
}
export interface EndCardProps {
/** shown once the game is over (a state the game's fold reaches); end() is called when it first shows */
show: boolean;
title?: string;
subtitle?: string;
/** the app's icon: an imported picture (`import icon from "./icon.png"`), which the export carries in the page */
icon?: string;
cta?: string;
background?: string;
/** the card's type (a brand's font, carried by importing it in an @font-face), Inter by default */
font?: string;
/** the text's colour, white by default */
color?: string;
/** the button's look over the default yellow pill: a brand's colours and type */
button?: CSSProperties;
children?: ReactNode;
}
/** The card the playable ends on: the whole card opens the store when tapped, as networks expect. */
export function EndCard({ show, title, subtitle, icon, cta = "Play now", background = "rgba(10, 12, 24, 0.82)", font = "Inter, system-ui, sans-serif", color = "#ffffff", button, children }: EndCardProps) {
useEffect(() => {
if (show) end();
}, [show]);
if (!show) return null;
return (
<div
onPointerUp={() => install()}
style={{
position: "absolute",
inset: 0,
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
gap: 28,
background,
color,
fontFamily: font,
textAlign: "center",
cursor: "pointer",
}}
>
{icon ? <img src={icon} alt="" style={{ width: 180, height: 180, borderRadius: 40 }} /> : null}
{title ? <div style={{ fontSize: 64, fontWeight: 900, lineHeight: 1.05, padding: "0 40px" }}>{title}</div> : null}
{subtitle ? <div style={{ fontSize: 34, opacity: 0.8, padding: "0 40px" }}>{subtitle}</div> : null}
{children}
<InstallButton style={button}>{cta}</InstallButton>
</div>
);
}
+22
View File
@@ -0,0 +1,22 @@
// `raea playable`'s lint, the part that renders (docs/playables.feature PA4): run by `raea run` on an entry that imports
// the game first, so its compositions are registered. Each composition is rendered at 12 frames through its length,
// and every 3D kind it draws is held to what the playable host draws (kinds.ts). Returns its shapes and the kinds.
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { Clock, getCompositions } from "raea";
import { PLAYABLE_KINDS } from "../host/kinds";
export default function walk() {
const kinds: Record<string, number> = {};
const comps = getCompositions().map((c) => {
const step = Math.max(1, Math.floor(c.durationInFrames / 12));
for (let f = 0; f < c.durationInFrames; f += step) {
const html = renderToStaticMarkup(
createElement(Clock, { frame: f, fps: c.fps, width: c.width, height: c.height, durationInFrames: c.durationInFrames }, createElement(c.component, c.defaultProps)),
);
for (const m of html.matchAll(/data-3d="([A-Za-z0-9]+)"/g)) kinds[m[1]] = (kinds[m[1]] ?? 0) + 1;
}
return { id: c.id, width: c.width, height: c.height, fps: c.fps, frames: c.durationInFrames };
});
return { comps, kinds: Object.keys(kinds), refused: Object.keys(kinds).filter((k) => !PLAYABLE_KINDS.has(k)) };
}
+5
View File
@@ -0,0 +1,5 @@
// raw tables, carried in the page by `raea playable` (engine/bundle inline.rs: a .bin import is a Uint8Array)
declare module "*.bin" {
const bytes: Uint8Array;
export default bytes;
}
+69
View File
@@ -0,0 +1,69 @@
// 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.
import type { FrameInput } from "raea";
/** window.addEventListener typed by the event's name (bun's globals type the bare addEventListener loosely) */
function on<K extends keyof WindowEventMap>(type: K, f: (e: WindowEventMap[K]) => void) {
window.addEventListener(type, f);
}
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 }>();
/** set on the first touch, click or key: networks keep sound off until then */
touched = false;
private firstTouch: (() => void)[] = [];
constructor(private stage: HTMLElement, private size: () => { width: number; height: number }) {
const at = (e: PointerEvent) => {
const r = this.stage.getBoundingClientRect();
const { width, height } = this.size();
return { x: ((e.clientX - r.left) / r.width) * width, y: ((e.clientY - r.top) / r.height) * height };
};
const first = () => {
if (this.touched) return;
this.touched = true;
for (const f of this.firstTouch) f();
};
on("pointerdown", (e) => {
first();
const p = at(e);
this.pointer = { ...p, down: true };
this.touches.set(e.pointerId, p);
});
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);
});
const up = (e: PointerEvent) => {
if (e.isPrimary && this.pointer) this.pointer = { ...this.pointer, down: false };
this.touches.delete(e.pointerId);
};
on("pointerup", up);
on("pointercancel", up);
on("keydown", (e) => {
first();
this.keys.add(e.key);
});
on("keyup", (e) => this.keys.delete(e.key));
on("blur", () => this.keys.clear());
}
/** Runs `f` on the first touch, click or key */
onFirstTouch(f: () => void) {
if (this.touched) f();
else this.firstTouch.push(f);
}
/** This frame's input, marked live (a person is playing: raea/games' fold reads it so) */
now(): FrameInput & { live: true } {
return {
keys: [...this.keys],
...(this.pointer ? { pointer: { ...this.pointer } } : {}),
...(this.touches.size ? { touches: [...this.touches].map(([id, p]) => ({ id, ...p })) } : {}),
live: true,
};
}
}
+12
View File
@@ -0,0 +1,12 @@
// The 3D kinds a playable's host draws (scene.ts, through sdk/r3f/src/three), apart from the renderer so the export's
// lint reads them without three.js (`raea playable`, docs/playables.feature PA4).
/** The kinds a playable draws; the export's lint refuses any other */
export const PLAYABLE_KINDS: ReadonlySet<string> = new Set([
"Canvas3D", "Group", "Mesh",
"Box", "Sphere", "Plane", "Cylinder", "Cone", "Torus", "Capsule", "Circle", "Ring",
"MeshStandardMaterial", "MeshPhysicalMaterial", "MeshBasicMaterial",
"PerspectiveCamera", "OrthographicCamera",
"AmbientLight", "DirectionalLight", "PointLight", "SpotLight", "HemisphereLight",
"Fog", "ToneMapping", "Shadows", "AntiAliasing",
]);
+168
View File
@@ -0,0 +1,168 @@
// 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.
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 { 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__ : {};
function pick(comps: RegisteredComposition[]): RegisteredComposition {
const screen = innerWidth / Math.max(1, innerHeight);
return comps.reduce((a, b) => (Math.abs(Math.log((b.width / b.height) / screen)) < Math.abs(Math.log((a.width / a.height) / screen)) ? b : a));
}
/** 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() {
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
const still = network === "preview" ? new URLSearchParams(location.hash.slice(1)) : undefined;
const fixed = still?.has("still") ? comps.find((c) => c.id === still.get("comp")) ?? comps[0] : undefined;
let comp = fixed ?? pick(comps);
document.head.insertAdjacentHTML("beforeend", `<style>html,body{margin:0;height:100%;overflow:hidden;background:#000;touch-action:none;user-select:none;-webkit-user-select:none}[${UNDER}]{background:transparent!important}#raea-stage{position:absolute;transform-origin:0 0;overflow:hidden}#raea-stage>canvas,#raea-page{position:absolute;inset:0;width:100%;height:100%}</style>`);
const stage = document.createElement("div");
stage.id = "raea-stage";
const canvas = document.createElement("canvas");
const page = document.createElement("div");
page.id = "raea-page";
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 layout = () => {
if (comps.length > 1 && !fixed) comp = pick(comps);
const s = Math.min(innerWidth / comp.width, innerHeight / comp.height);
Object.assign(stage.style, {
width: `${comp.width}px`,
height: `${comp.height}px`,
left: `${(innerWidth - comp.width * s) / 2}px`,
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);
};
layout();
addEventListener("resize", layout);
const input = new Input(stage, () => comp);
const root = createRoot(page);
const timeline: InputTimeline = {};
let frame = 0;
let timedOut = false;
let running = false;
let visible = true;
let last = 0;
let acc = 0;
let over = false;
let shown = false;
let firstDrawn = false;
// the ad events so far, for tools/check.ts to read back
const events: string[] = ((globalThis as { __raeaAdEvents?: string[] }).__raeaAdEvents = []);
// the preview page inside raea's review (a sandboxed frame) tells the review each event, which shows them beside it
const tell = (kind: string) => {
if (network === "preview" && window.parent !== window) window.parent.postMessage({ raeaPlayable: kind }, "*");
};
onAdEvent((e) => {
events.push(e.kind);
if (e.kind === "end") over = true;
tell(e.kind);
});
// the player took over from the game's own hand
input.onFirstTouch(() => tell("touch"));
const draw = () => {
const C = comp.component;
flushSync(() =>
root.render(
<Clock frame={frame} fps={comp.fps} width={comp.width} height={comp.height} durationInFrames={comp.durationInFrames} input={timeline} defaultProps={comp.defaultProps}>
<C {...comp.defaultProps} />
<EndCard show={timedOut} title={config.title} cta={config.cta} />
</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);
// 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;
};
const tick = (now: number) => {
requestAnimationFrame(tick);
if (!running || !visible) {
last = now;
return;
}
const step = 1000 / comp.fps;
acc += Math.min(250, now - last);
last = now;
let stepped = false;
// the game stops stepping once it is over (its EndCard showed, or time ran out): the card stays on the last frame
while (acc >= step && !over) {
acc -= step;
timeline[frame] = input.now();
if (frame + 1 >= comp.durationInFrames) {
timedOut = true;
break;
}
frame++;
stepped = true;
}
if (stepped || (timedOut && !shown)) {
shown = timedOut;
draw();
}
};
if (fixed) {
frame = Math.min(Number(still!.get("still")), comp.durationInFrames - 1);
draw();
(globalThis as { __raeaStill?: boolean }).__raeaStill = true;
return;
}
draw();
whenReady(
() => {
running = true;
last = performance.now();
tell("ready");
},
(on) => {
if (on !== visible) tell(on ? "viewable" : "hidden");
visible = on;
},
);
requestAnimationFrame(tick);
}
if (document.readyState === "loading") addEventListener("DOMContentLoaded", boot);
else boot();
+5
View File
@@ -0,0 +1,5 @@
// The page's 3D drawn by three.js: raea's three.js host (sdk/r3f/src/three, shared with <Raea> in React Three Fiber),
// held to what a playable may carry: a kind outside PLAYABLE_KINDS (kinds.ts) is refused by the export's lint
// (`raea playable`, docs/playables.feature PA4).
export { Scene3d } from "@raea/r3f/three/scene";
export { PLAYABLE_KINDS } from "./kinds";
+65
View File
@@ -0,0 +1,65 @@
// Bevy's tone mapping in the playable (docs/playables.feature PA10): the 3D drawn into a half-float target with no
// tone curve, then one full-screen pass maps it through TonyMcMapface (Bevy's default, tools/tony.ts's table) and
// encodes sRGB, as bevy_core_pipeline's tonemapping.wesl does. Where nothing was drawn it stays transparent, so the
// page's background shows through as it does under the native engine's 3D.
import * as THREE from "three";
import tony from "./tony.bin";
const N = Math.round(Math.cbrt(tony.length / 3));
const FRAG = /* glsl */ `
precision highp float;
precision highp sampler3D;
uniform sampler2D scene;
uniform sampler3D lut;
in vec2 vUv;
out vec4 color;
void main() {
vec4 c = texture(scene, vUv);
vec3 x = max(c.rgb / max(c.a, 1e-5), vec3(0.0));
vec3 uv = (x / (x + 1.0)) * (${N - 1}.0 / ${N}.0) + 0.5 / ${N}.0;
// the table holds sRGB-encoded bytes, already the screen's values
color = vec4(texture(lut, clamp(uv, 0.0, 1.0)).rgb * c.a, c.a);
}`;
const VERT = /* glsl */ `
in vec3 position;
in vec2 uv;
out vec2 vUv;
void main() { vUv = uv; gl_Position = vec4(position.xy, 0.0, 1.0); }`;
export class Tonemap {
private target: THREE.WebGLRenderTarget;
private quad: THREE.Mesh;
private camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
constructor(private renderer: THREE.WebGLRenderer) {
renderer.toneMapping = THREE.NoToneMapping;
renderer.outputColorSpace = THREE.LinearSRGBColorSpace;
this.target = new THREE.WebGLRenderTarget(1, 1, { type: THREE.HalfFloatType, samples: 4, colorSpace: THREE.LinearSRGBColorSpace });
const rgba = new Uint8Array(N * N * N * 4);
for (let i = 0; i < N * N * N; i++) rgba.set([tony[i * 3], tony[i * 3 + 1], tony[i * 3 + 2], 255], i * 4);
const lut = new THREE.Data3DTexture(rgba, N, N, N);
lut.minFilter = lut.magFilter = THREE.LinearFilter;
lut.unpackAlignment = 1;
lut.needsUpdate = true;
const material = new THREE.RawShaderMaterial({ glslVersion: THREE.GLSL3, vertexShader: VERT, fragmentShader: FRAG, uniforms: { scene: { value: this.target.texture }, lut: { value: lut } }, transparent: true, premultipliedAlpha: true, blending: THREE.NoBlending, depthTest: false, depthWrite: false });
this.quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), material);
}
/** The target sized to the canvas's drawing buffer */
resize() {
const s = this.renderer.getDrawingBufferSize(new THREE.Vector2());
this.target.setSize(s.x, s.y);
}
render(scene: THREE.Scene, camera: THREE.Camera) {
const r = this.renderer;
r.setRenderTarget(this.target);
r.setClearColor(0x000000, 0);
r.clear();
r.render(scene, camera);
r.setRenderTarget(null);
r.render(this.quad, this.camera);
}
}
Binary file not shown.
+4
View File
@@ -0,0 +1,4 @@
// raea/playable: what a game written for a playable ad uses (docs/playables.feature PA3). The same TSX renders as a
// video ad with `raea render` (where install() does nothing) and exports as a playable with `raea playable`.
export { install, end, isEnded, network, storeUrl, onAdEvent, type Network, type StoreLinks } from "./network";
export { EndCard, InstallButton, type EndCardProps, type InstallButtonProps } from "./cards";
+138
View File
@@ -0,0 +1,138 @@
// The ad network a playable export is built for, and the three things every network wants from it in its own words:
// when the ad may start (and must pause), how the store opens, and that the game ended (docs/playables.feature PA2).
// The export names the network at build time (__RAEA_NETWORK__); a game's own code only calls install() and end().
export type Network = "applovin" | "unity" | "google" | "meta" | "moloco" | "mintegral" | "tiktok" | "liftoff" | "preview";
export interface StoreLinks {
ios?: string;
android?: string;
}
declare const __RAEA_NETWORK__: Network | undefined;
declare const __RAEA_STORE__: StoreLinks | undefined;
interface Mraid {
getState(): string;
isViewable(): boolean;
addEventListener(event: string, f: (...a: unknown[]) => void): void;
open(url?: string): void;
}
type Win = typeof globalThis & {
mraid?: Mraid;
ExitApi?: { exit(): void };
FbPlayableAd?: { onCTAClick(): void };
Liftoff?: { open(): void };
install?: () => void;
openAppStore?: () => void;
gameReady?: () => void;
gameEnd?: () => void;
gameStart?: () => void;
gameClose?: () => void;
};
const w = globalThis as Win;
/** The network this build is for: "preview" outside an export (a raea render, a browser tab) */
export const network: Network = typeof __RAEA_NETWORK__ === "string" ? __RAEA_NETWORK__ : "preview";
const store: StoreLinks = typeof __RAEA_STORE__ === "object" && __RAEA_STORE__ ? __RAEA_STORE__ : {};
const MRAID: readonly Network[] = ["applovin", "unity", "liftoff"];
/** The store link for this device: iOS's on iPhone/iPad, Android's otherwise */
export function storeUrl(): string | undefined {
const ua = typeof navigator === "undefined" ? "" : navigator.userAgent;
const ios = /iPhone|iPad|iPod|Macintosh/.test(ua) && !/Android/.test(ua);
return (ios ? store.ios : store.android) ?? store.android ?? store.ios;
}
const listeners: ((e: { kind: "install" | "end" }) => void)[] = [];
/** Called on install() and end(), for the preview page's log and tests */
export function onAdEvent(f: (e: { kind: "install" | "end" }) => void): void {
listeners.push(f);
}
let ended = false;
/** Open the store, the network's way. Call it only from a player's tap (every network rejects an automatic redirect). */
export function install(): void {
for (const f of listeners) f({ kind: "install" });
if (!ended) end();
const url = storeUrl();
switch (network) {
case "applovin":
case "unity":
if (w.mraid) w.mraid.open(url);
return;
case "liftoff":
if (w.Liftoff) w.Liftoff.open();
else w.mraid?.open();
return;
case "google":
w.ExitApi?.exit();
return;
case "meta":
case "moloco":
w.FbPlayableAd?.onCTAClick();
return;
case "mintegral":
w.install?.();
return;
case "tiktok":
w.openAppStore?.();
return;
case "preview":
return;
}
}
/** The game is over (won, lost or out of time): Mintegral's gameEnd; the host shows the end card. Called once. */
export function end(): void {
if (ended) return;
ended = true;
for (const f of listeners) f({ kind: "end" });
if (network === "mintegral") w.gameEnd?.();
}
/** Whether end() was called */
export function isEnded(): boolean {
return ended;
}
/** Calls `start` once the ad may begin, then `visible(false|true)` as it is hidden and shown again (Unity, AppLovin:
* start only after MRAID's ready and while viewable, pause while not). Mintegral is told the game is ready and
* starts it with its own gameStart. */
export function whenReady(start: () => void, visible: (on: boolean) => void): void {
let started = false;
const go = () => {
if (started) return;
started = true;
start();
};
if (MRAID.includes(network) && w.mraid) {
const m = w.mraid;
const onReady = () => {
m.addEventListener("viewableChange", (on) => {
if (on) go();
visible(!!on);
});
if (m.isViewable()) go();
};
if (m.getState() === "loading") m.addEventListener("ready", onReady);
else onReady();
return;
}
if (network === "mintegral") {
w.gameStart = go;
w.gameClose = () => visible(false);
w.gameReady?.();
// Mintegral's preview tool calls gameStart; a page opened by hand starts on its own
if (!w.gameReady) go();
return;
}
if (typeof document !== "undefined") {
document.addEventListener("visibilitychange", () => visible(document.visibilityState === "visible"));
}
go();
}
+76
View File
@@ -0,0 +1,76 @@
// A playable played in headless WebKit, as an iPhone's ad WebView would show it (docs/playables.feature PA7): the page
// opened at a phone's size, a drag held long enough for the host's per-frame input to see it, its console,
// 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).
// 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";
import { webkit } from "playwright-core";
const [page, outDir, size = "390x844"] = process.argv.slice(2);
if (!page || !outDir) throw new Error("usage: bun tools/check.ts PAGE.html OUT_DIR [WxH]");
const [W, H] = size.split("x").map(Number);
mkdirSync(outDir, { recursive: true });
const browser = await webkit.launch();
const ctx = await browser.newContext({ viewport: { width: W, height: H }, deviceScaleFactor: 2, hasTouch: true, isMobile: true });
const p = await ctx.newPage();
const logs: string[] = [];
const problems: string[] = [];
p.on("console", (m) => logs.push(`${m.type()}: ${m.text()}`));
p.on("pageerror", (e) => problems.push(`exception: ${e.message}`));
// the scripts a network's own page tags load, which its ad view serves (apps/playable pages.rs): Google's exit API and
// TikTok's playable SDK. They're stopped here like any request, but they aren't the game's.
const NETWORK_TAGS = ["https://tpc.googlesyndication.com/pagead/gadgets/html5/api/exitapi.js", "https://sf16-muse-va.ibytedtos.com/obj/union-fe-nc-i18n/playable/sdk/playable-sdk.js"];
await ctx.route("**/*", (r) => {
const u = r.request().url();
if (u.startsWith("file:") || u.startsWith("data:") || u.startsWith("blob:")) return r.continue();
if (!NETWORK_TAGS.includes(u)) problems.push(`network request: ${u}`);
return r.abort();
});
await p.goto(page.startsWith("http") ? page : `file://${resolve(page)}`);
await p.waitForTimeout(1500);
const shot = (name: string) => p.screenshot({ path: resolve(outDir, `${name}.png`) });
// real input: WebKit makes the pointer events the host reads (host/input.ts), each press held over several frames
// (the host samples input once a frame, so a press shorter than a frame is lost)
const press = async (type: "down" | "move" | "up", x: number, y: number) => {
await p.mouse.move(x, y);
if (type === "down") await p.mouse.down();
if (type === "up") await p.mouse.up();
};
await shot("0-start");
await press("down", W * 0.3, H * 0.75);
for (let i = 0; i <= 10; i++) {
await press("move", W * (0.3 + 0.04 * i), H * 0.75);
await p.waitForTimeout(80);
}
await press("up", W * 0.7, H * 0.75);
await shot("1-played");
await p.waitForTimeout(2500);
await shot("2-later");
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 p.waitForTimeout(300);
}
const state = (await p.evaluate(() => ({
canvas: !!document.querySelector("#raea-stage canvas"),
parts: document.querySelectorAll("[data-3d]").length,
page: document.querySelector("#raea-page")?.childElementCount ?? 0,
events: (globalThis as { __raeaAdEvents?: unknown[] }).__raeaAdEvents ?? [],
}))) as { canvas: boolean; parts: number; page: number; events: unknown[] };
console.log(`page: ${JSON.stringify(state)}`);
if (!state.page && !state.parts) problems.push("nothing drew: the game's page is empty");
if (more > 0 && !JSON.stringify(state.events).includes("install")) problems.push("the end card was tapped but no install event came back");
for (const l of logs) console.log(l);
for (const pr of problems) console.log(`PROBLEM: ${pr}`);
await browser.close();
process.exit(problems.length ? 1 : 0);
+72
View File
@@ -0,0 +1,72 @@
// A playable held to the native render (docs/playables.feature PA9): one composition frame drawn by `raea render` and
// by the playable host (a preview build opened at the composition's size, no one playing, so both play themselves),
// compared where the native frame drew something over its background. The playable is drawn in WebKit, as an
// iPhone's ad view draws it (raea doesn't test in Chrome).
// `bun tools/parity.ts GAME.tsx COMPOSITION FRAME OUT_DIR [BAR]` prints the numbers, writes native.png, playable.png
// and diff.png, and exits 1 when the mean colour difference over the drawn pixels is over BAR (0-255, default 16).
import { mkdirSync } from "node:fs";
import { resolve } from "node:path";
import { webkit } from "playwright-core";
const [game, comp, at, outArg, barArg = "16"] = process.argv.slice(2);
if (!game || !comp || !at || !outArg) throw new Error("usage: bun tools/parity.ts GAME.tsx COMPOSITION FRAME OUT_DIR [BAR]");
const out = resolve(outArg);
mkdirSync(out, { recursive: true });
const name = game.split("/").pop()!.replace(/\.tsx$/, "");
const run = async (cmd: string[]) => {
const p = Bun.spawn(cmd, { stdout: "pipe", stderr: "pipe" });
const [o, e] = [await new Response(p.stdout).text(), await new Response(p.stderr).text()];
if ((await p.exited) !== 0) throw new Error(`${cmd.join(" ")} failed:\n${o}\n${e}`);
return o;
};
// the native frame, and the composition's size from the registry the playable reads
await run(["raea", "render", resolve(game), "-o", `${out}/native.png`, "--composition", comp, "--frame", at]);
await run(["raea", "playable", resolve(game), "-o", out, "--networks", "preview"]);
const size = (await run(["ffprobe", "-v", "error", "-select_streams", "v", "-show_entries", "stream=width,height", "-of", "csv=p=0", `${out}/native.png`])).trim();
const [W, H] = size.split(",").map(Number);
const browser = await webkit.launch();
const p = await browser.newPage({ viewport: { width: W, height: H }, deviceScaleFactor: 1 });
const problems: string[] = [];
p.on("pageerror", (e) => problems.push(`exception: ${e.message}`));
await p.route("**/*", (r) => {
const u = r.request().url();
if (/^(file|data|blob):/.test(u)) return r.continue();
problems.push(`network request: ${u}`);
return r.abort();
});
await p.goto(`file://${out}/${name}-preview.html#still=${at}&comp=${comp}`);
await p.waitForFunction(() => (globalThis as { __raeaStill?: unknown }).__raeaStill, null, { timeout: 10_000 }).catch(() => problems.push("the still never drew"));
await p.screenshot({ path: `${out}/playable.png` });
await browser.close();
const raw = async (png: string) => new Uint8Array(await new Response(Bun.spawn(["ffmpeg", "-v", "error", "-i", png, "-f", "rawvideo", "-pix_fmt", "rgb24", "-"], { stdout: "pipe" }).stdout).arrayBuffer());
const [a, b] = [await raw(`${out}/native.png`), await raw(`${out}/playable.png`)];
if (a.length !== b.length) throw new Error(`parity: sizes differ (${a.length} vs ${b.length} bytes)`);
await run(["ffmpeg", "-v", "error", "-y", "-i", `${out}/native.png`, "-i", `${out}/playable.png`, "-filter_complex", "blend=all_mode=difference", `${out}/diff.png`]);
// the drawn pixels: those of the native frame away from its background (the corner's colour)
const bg = [a[0], a[1], a[2]];
let n = 0, diff = 0, covered = 0;
const sumA = [0, 0, 0], sumB = [0, 0, 0];
for (let i = 0; i < a.length; i += 3) {
if (Math.abs(a[i] - bg[0]) + Math.abs(a[i + 1] - bg[1]) + Math.abs(a[i + 2] - bg[2]) < 24) continue;
n++;
for (let k = 0; k < 3; k++) {
diff += Math.abs(a[i + k] - b[i + k]) / 3;
sumA[k] += a[i + k];
sumB[k] += b[i + k];
}
if (Math.abs(b[i] - bg[0]) + Math.abs(b[i + 1] - bg[1]) + Math.abs(b[i + 2] - bg[2]) >= 24) covered++;
}
const hex = (s: number[]) => "#" + s.map((v) => Math.round(v / n).toString(16).padStart(2, "0")).join("");
const luma = (s: number[]) => 0.2126 * s[0] + 0.7152 * s[1] + 0.0722 * s[2];
const mean = diff / Math.max(1, n);
const bar = Number(barArg);
console.log(`${comp} frame ${at}: ${n} drawn pixels (${((100 * n) / (a.length / 3)).toFixed(1)}% of the frame), the playable covers ${((100 * covered) / Math.max(1, n)).toFixed(1)}% of them`);
console.log(`mean colour native ${hex(sumA)} playable ${hex(sumB)}, brightness ${(luma(sumB) / luma(sumA)).toFixed(3)}x`);
console.log(`mean difference ${mean.toFixed(1)} / 255 (bar ${bar}): ${mean <= bar ? "ok" : "OVER"}`);
for (const p of problems) console.log(`PROBLEM: ${p}`);
process.exit(mean <= bar && !problems.length ? 0 : 1);
+56
View File
@@ -0,0 +1,56 @@
// Bevy's TonyMcMapface tone-mapping table for the playable host (docs/playables.feature PA10): bevy_core_pipeline's
// tony_mc_mapface.ktx2 (48³, E5B9G9R9 floats, zstd; MIT, Tomasz Stachowiak) resampled to N³ and stored as sRGB-encoded
// RGB bytes, which host/tonemap.ts samples as Bevy's tonemapping.wesl does.
// `bun tools/tony.ts N OUT.bin` (N = 48 keeps Bevy's own size).
import { readdirSync } from "node:fs";
import { homedir } from "node:os";
const [nArg = "32", out = "src/host/tony.bin"] = process.argv.slice(2);
const N = Number(nArg);
const reg = `${homedir()}/.cargo/registry/src`;
const src = readdirSync(reg).map((d) => `${reg}/${d}/bevy_core_pipeline-0.20.0/src/tonemapping/luts/tony_mc_mapface.ktx2`).find((f) => Bun.file(f).size > 0);
if (!src) throw new Error("tony: bevy_core_pipeline 0.20.0 isn't in ~/.cargo/registry (build raea once)");
const ktx = new DataView(await Bun.file(src).arrayBuffer());
const u32 = (o: number) => ktx.getUint32(o, true);
const [format, D, superc] = [u32(12), u32(20), u32(44)];
if (format !== 123 || D !== 48 || superc !== 2) throw new Error(`tony: expected 48³ E5B9G9R9 with zstd, got format ${format}, ${D}³, supercompression ${superc}`);
// the one level's index: offset and length (u64s, small enough for a Number)
const off = Number(ktx.getBigUint64(80, true)), len = Number(ktx.getBigUint64(88, true));
const data = Bun.zstdDecompressSync(new Uint8Array(ktx.buffer, off, len));
const px = new DataView(data.buffer, data.byteOffset, data.byteLength);
/** E5B9G9R9: three 9-bit mantissas over one shared 5-bit exponent (bias 15) */
function texel(x: number, y: number, z: number): [number, number, number] {
const v = px.getUint32(((z * D + y) * D + x) * 4, true);
const s = 2 ** ((v >>> 27) - 15 - 9);
return [(v & 511) * s, ((v >>> 9) & 511) * s, ((v >>> 18) & 511) * s];
}
/** the table at p in [0, 1]³, trilinear as the GPU's sampler reads it (texel centres at (i + 0.5) / D) */
function sample(p: [number, number, number]): number[] {
const f = p.map((c) => Math.min(D - 1, Math.max(0, c * D - 0.5)));
const i0 = f.map(Math.floor), t = f.map((c, k) => c - i0[k]);
const i1 = i0.map((c) => Math.min(D - 1, c + 1));
const out = [0, 0, 0];
for (let corner = 0; corner < 8; corner++) {
const pick = [corner & 1, (corner >> 1) & 1, (corner >> 2) & 1];
const w = pick.reduce((m, b, k) => m * (b ? t[k] : 1 - t[k]), 1);
const c = texel(pick[0] ? i1[0] : i0[0], pick[1] ? i1[1] : i0[1], pick[2] ? i1[2] : i0[2]);
for (let k = 0; k < 3; k++) out[k] += w * c[k];
}
return out;
}
const srgb = (c: number) => (c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055);
// Bevy reads the table at uv = e * (D - 1) / D + 0.5 / D for e = x / (x + 1) in [0, 1]: texel i holds e = i / (D - 1).
// The new table keeps that layout at its own size, so the host samples it the same way with N for D.
const at = (e: number) => e * (D - 1) / D + 0.5 / D;
const bytes = new Uint8Array(N * N * N * 3);
for (let z = 0; z < N; z++)
for (let y = 0; y < N; y++)
for (let x = 0; x < N; x++) {
const c = sample([at(x / (N - 1)), at(y / (N - 1)), at(z / (N - 1))]);
const o = ((z * N + y) * N + x) * 3;
for (let k = 0; k < 3; k++) bytes[o + k] = Math.round(255 * srgb(Math.min(1, Math.max(0, c[k]))));
}
await Bun.write(out, bytes);
console.log(`tony: ${N}³ from ${D}³, ${bytes.length} bytes to ${out}`);
+1
View File
@@ -0,0 +1 @@
{ "extends": "../tsconfig.base.json", "compilerOptions": { "types": ["bun"] } }
@@ -41,3 +41,59 @@ test("an Image's load fires once its src is set", async () => {
await Promise.resolve();
expect([seen, img.complete, img.src]).toEqual([["onload", "listener"], true, "/media/x.png"]);
});
// #253: a loaded Image has the picture's size (a canvas sized from it was 0 high, and its CanvasTexture refused)
const host = globalThis as { __raea_call?: (n: string, j: string) => string | undefined };
const loaded = (img: any) => new Promise<string>((ok) => {
img.onload = () => ok("load");
img.onerror = () => ok("error");
});
test("a loaded Image's width, height and natural size are the picture's, from the host (asset.load)", async () => {
const calls: string[] = [];
host.__raea_call = (name, json) => {
calls.push(`${name} ${json}`);
return name === "asset.load" ? JSON.stringify({ path: "/edit/public/site.png", bytes: 999, width: 400, height: 300 }) : undefined;
};
try {
const img = new ours.Image();
const done = loaded(img);
img.src = "/media/site.png";
expect([img.naturalWidth, img.width]).toEqual([0, 0]);
expect(await done).toBe("load");
expect([img.width, img.height, img.naturalWidth, img.naturalHeight]).toEqual([400, 300, 400, 300]);
expect(calls).toEqual([`asset.load {"path":"/media/site.png"}`]);
// width and height given (the constructor's, or set) stay as given; the natural size is still the picture's
const sized = new ours.Image(50, 20);
const both = loaded(sized);
sized.src = "/media/site.png";
await both;
expect([sized.width, sized.height, sized.naturalWidth, sized.naturalHeight]).toEqual([50, 20, 400, 300]);
sized.height = 10;
expect([sized.width, sized.height]).toEqual([50, 10]);
} finally {
delete host.__raea_call;
}
});
test("a data: URL Image's size comes from its header; a file the host can't find fires error", async () => {
// a 3 x 2 PNG
const png = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAACCAYAAACddGYaAAAAEklEQVR4nGP4z8DwH4YZYBwAaG8H+VKwN2UAAAAASUVORK5CYII=";
const img = new ours.Image();
const done = loaded(img);
img.src = png;
expect(await done).toBe("load");
expect([img.width, img.height, img.naturalWidth, img.naturalHeight]).toEqual([3, 2, 3, 2]);
host.__raea_call = () => {
throw new Error("asset.load: asset /media/gone.png: No such file or directory");
};
try {
const gone = new ours.Image();
const failed = loaded(gone);
gone.src = "/media/gone.png";
expect(await failed).toBe("error");
expect([gone.complete, gone.naturalWidth, gone.width]).toEqual([true, 0, 0]);
} finally {
delete host.__raea_call;
}
});
+64 -11
View File
@@ -2,8 +2,14 @@
// for a web page call them. requestAnimationFrame's callbacks run once per frame the composition draws, given that frame's
// time (f * 1000 / fps ms), so a frame drawn again (a resumed render, `--at`) gets the same calls; one asked for while a
// frame draws runs at the next frame. `new Image()` loads: setting its src fires load (and onload) on the next microtask,
// so a preload resolves. It has no pixel size (naturalWidth and the rest stay 0): nothing reads a file's size
// synchronously here, and `<img>` draws the file itself.
// so a preload resolves, and by then naturalWidth and naturalHeight are the picture's size (#253): a data: URL's from its
// header, a file's or URL's from the host (native asset.load, which finds staticFile's /media/ paths as <Img> does).
// currentSrc is then the file the host found, which a canvas's drawImage draws from (#260).
// width and height are the ones given (the constructor's, or set) else the natural size, as a browser has them. A file
// the host can't find fires error (and onerror) instead. Under plain bun, with no host, a file's size stays 0.
import { hasNative, native } from "@raea/app/native";
import { sniffSize } from "@raea/ui/canvas";
type FrameCallback = (time: number) => void;
@@ -54,25 +60,56 @@ export function frameCallbacks(f: number, fps: number): void {
type Listener = (e: { type: string; target: unknown; currentTarget: unknown }) => void;
/** A preloadable image: its src set, load fires. */
/** A picture's size, and the file the host found for it: a data: URL's size from its header, anything else from the host
* (asset.load); no size when it has none (no host, or a format the header doesn't say). Throws the host's error for a
* file that isn't there. */
function picture(src: string): { size: [number, number] | null; file?: string } {
if (src.startsWith("data:")) return { size: sniffSize(src) };
if (src.startsWith("blob:") || !hasNative()) return { size: null };
const got = native("asset.load", { path: src });
return { size: got && typeof got.width === "number" && typeof got.height === "number" ? [got.width, got.height] : null, file: typeof got?.path === "string" ? got.path : undefined };
}
/** A preloadable image: its src set, load fires, with the picture's size. */
class FrameImage {
onload: Listener | null = null;
onerror: Listener | null = null;
complete = true;
width = 0;
height = 0;
naturalWidth = 0;
naturalHeight = 0;
/** the picture as it loaded: the file the host found for the src (staticFile's /media/x is the project's media/x),
* which is what a canvas's drawImage draws from (#260: read back off the page, a canvas has no project folder to
* find /media/ in, and the picture drew nothing); "" until it loads, as in a browser */
currentSrc = "";
alt = "";
crossOrigin: string | null = null;
decoding = "auto";
loading = "eager";
#src = "";
#width: number | null;
#height: number | null;
#loads = 0;
#listeners = new Map<string, Set<Listener>>();
constructor(width?: number, height?: number) {
this.width = width ?? 0;
this.height = height ?? 0;
this.#width = width ?? null;
this.#height = height ?? null;
}
get width(): number {
return this.#width ?? this.naturalWidth;
}
set width(v: number) {
this.#width = Number(v) || 0;
}
get height(): number {
return this.#height ?? this.naturalHeight;
}
set height(v: number) {
this.#height = Number(v) || 0;
}
get src(): string {
@@ -80,13 +117,29 @@ class FrameImage {
}
set src(v: string) {
this.#src = String(v);
const src = String(v);
this.#src = src;
this.complete = false;
this.naturalWidth = 0;
this.naturalHeight = 0;
this.currentSrc = "";
const load = ++this.#loads;
queueMicrotask(() => {
// a src set again before this one loaded: only the last one's load fires, as in a browser
if (load !== this.#loads) return;
let type = "load";
try {
const { size, file } = picture(src);
if (size) [this.naturalWidth, this.naturalHeight] = size;
this.currentSrc = file ?? src;
} catch (err) {
type = "error";
console.warn(`new Image(): ${src} didn't load: ${err instanceof Error ? err.message : String(err)}`);
}
this.complete = true;
const e = { type: "load", target: this, currentTarget: this };
this.onload?.call(this, e);
for (const l of this.#listeners.get("load") ?? []) l.call(this, e);
const e = { type, target: this, currentTarget: this };
(type === "load" ? this.onload : this.onerror)?.call(this, e);
for (const l of this.#listeners.get(type) ?? []) l.call(this, e);
});
}
+3
View File
@@ -51,6 +51,7 @@
"raea/blender/shot": ["./blender/src/shot.tsx"],
"raea/godot": ["./godot/src/index.ts"],
"raea/godot/shot": ["./godot/src/shot.tsx"],
"raea/playable": ["./playable/src/index.ts"],
"raea/pick": ["./render/src/pick.ts"],
"raea/playtest": ["./app/src/playtest.ts"],
"raea/ragdoll": ["./character/src/ragdoll.ts"],
@@ -112,6 +113,8 @@
"@raea/ui/canvas": ["./ui/src/canvas.ts"],
"@raea/physics": ["./physics/src/index.ts"],
"@raea/physics/*": ["./physics/src/*"],
"@raea/playable": ["./playable/src/index.ts"],
"@raea/playable/*": ["./playable/src/*"],
"@raea/web": ["./web/src/index.tsx"],
"@raea/web/*": ["./web/src/*"],
"@raea/room": ["./room/src/index.ts"],
+1 -1
Submodule skills updated: ae1c222713...8efd329239.
+2 -1
View File
@@ -165,7 +165,8 @@ impl Ctx<'_> {
if let Some(p) = self.images.get(src) {
return Some(p.clone());
}
let (mime, bytes) = raea_io_net::data_url(src)?;
// inline (data:), else the picture's file (a page's /media/: the host's roots, as its videos)
let (mime, bytes) = raea_io_net::data_url(src).or_else(|| crate::image_file(src))?;
let mime = mime.as_str();
let img = if mime == "image/svg+xml" {
let size = crate::svg::natural_size(&bytes, self.opt)?;
+54 -7
View File
@@ -84,8 +84,8 @@ impl Replay {
}
}
/// Where a canvas's videos' files are, for a host that draws canvases (raea-page's Blitz page: the page's roots); until
/// one is given a video's src is read as a file path.
/// Where a canvas's videos' and pictures' files are, for a host that draws canvases (raea-page's Blitz page: the page's
/// roots, so a /media/ src is the project's file); until one is given a src is read as a file path.
pub fn videos(find: fn(&str) -> Option<std::path::PathBuf>) {
*VIDEO_PATHS.write().unwrap() = Some(find);
}
@@ -140,9 +140,36 @@ pub(crate) fn page_options() -> usvg::Options<'static> {
db.map_or_else(usvg::Options::default, |db| page_fonts(&db))
}
/// Where a video's src is as a file, for its frames drawn on a canvas (`videos`).
/// Where a video's or a picture's src is as a file, for drawing it on a canvas (`videos`).
static VIDEO_PATHS: std::sync::RwLock<Option<fn(&str) -> Option<std::path::PathBuf>>> = std::sync::RwLock::new(None);
/// A src as a file: by the host's roots (`videos`), else as a path (a file:// URL's too); a src that is a file as it
/// stands (a loaded Image's currentSrc, the file its host found: #260) is that file whatever the roots make of it.
fn media_file(src: &str) -> Option<std::path::PathBuf> {
let plain = std::path::PathBuf::from(src.strip_prefix("file://").unwrap_or(src));
match *VIDEO_PATHS.read().unwrap() {
Some(f) => f(src).filter(|p| p.exists() || !(plain.is_absolute() && plain.is_file())).or(Some(plain)),
None => Some(plain),
}
}
/// A picture that isn't inline, read from its file, with its type by its name: drawImage of an <img> or new Image()
/// whose src is the project's /media/ file (raea #253: the card's screenshot drew nothing, as only data: URLs were
/// decoded).
pub(crate) fn image_file(src: &str) -> Option<(String, Vec<u8>)> {
let path = media_file(src)?;
let mime = match path.extension()?.to_str()?.to_ascii_lowercase().as_str() {
"png" => "image/png",
"jpg" | "jpeg" => "image/jpeg",
"webp" => "image/webp",
"gif" => "image/gif",
"bmp" => "image/bmp",
"svg" => "image/svg+xml",
_ => return None,
};
Some((mime.to_string(), std::fs::read(path).ok()?))
}
/// A video's frame at `t`, as a pixmap: opened and decoded on the CPU when it's asked for (a histogram reads one frame
/// per seek), the last few kept.
fn video_frame(src: &str, t: f64) -> Option<sk::Pixmap> {
@@ -150,10 +177,7 @@ fn video_frame(src: &str, t: f64) -> Option<sk::Pixmap> {
if let Some((.., pm)) = FRAMES.lock().unwrap().iter().find(|(s, b, _)| s == src && *b == t.to_bits()) {
return Some(pm.clone());
}
let path = match *VIDEO_PATHS.read().unwrap() {
Some(f) => f(src)?,
None => std::path::PathBuf::from(src.strip_prefix("file://").unwrap_or(src)),
};
let path = media_file(src)?;
let frame = raea_io_media::preferred().into_iter().find_map(|b| b.open_video(&path).ok()?.frame_at(t).ok())?;
let mut pm = sk::Pixmap::new(frame.width, frame.height)?;
for (i, px) in pm.pixels_mut().iter_mut().enumerate() {
@@ -209,6 +233,29 @@ mod tests {
assert_eq!(at(2, 2).alpha(), 0);
}
#[test]
fn a_picture_from_a_file_is_drawn() {
// raea #253: drawImage of a picture whose src is a file (a page's /media/, found by the host's roots) drew nothing
let dir = std::env::temp_dir().join(format!("raea-canvas-pic-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let mut pic = sk::Pixmap::new(3, 2).unwrap();
pic.fill(sk::Color::from_rgba8(0, 0, 210, 255));
let file = dir.join("shot.png");
pic.save_png(&file).unwrap();
let opt = usvg::Options::default();
let mut pm = sk::Pixmap::new(10, 10).unwrap();
let mut cx = Ctx { opt: &opt, images: HashMap::new() };
let st = serde_json::json!({"ts": [1, 0, 0, 1, 0, 0], "alpha": 1, "comp": "source-over", "clip": [], "shadow": null, "smooth": false});
let src = file.to_string_lossy().to_string();
cx.op(&mut pm, &serde_json::json!(["image", src, null, null, null, null, 2, 2, 6, 4, st]));
assert_eq!(pm.pixel(4, 4).unwrap().demultiply().blue(), 210, "the picture is drawn");
assert_eq!(pm.pixel(1, 1).unwrap().alpha(), 0, "only where it was asked to go");
// a file that isn't a picture, or isn't there, draws nothing and doesn't panic
cx.op(&mut pm, &serde_json::json!(["image", dir.join("none.png").to_string_lossy(), null, null, null, null, 0, 0, 10, 10, st]));
assert_eq!(pm.pixel(1, 1).unwrap().alpha(), 0);
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn image_under_a_scale() {
// Excalidraw's way: a 4x4 picture drawn at 2x size under a 0.5 transform covers 4x4 pixels at (2, 2)
+3
View File
@@ -14,4 +14,7 @@ blitz-paint = { version = "=0.3.0-beta.4", default-features = false }
# every call's arguments hashed, so the same print draws the same picture
rustc-hash = "2"
vello = { version = "=0.11.0", default-features = false, features = ["wgpu"] }
# a bitmap emoji's strike and its PNG, for the grey ones Vello's glyph run skips (emoji.rs, #262): Vello's own versions
skrifa = "0.44.0"
png = "0.18.1"
wgpu = "=30.0.1"
+136
View File
@@ -0,0 +1,136 @@
//! Bitmap emoji whose PNG Vello doesn't draw: grey ones. Apple Color Emoji keeps 52 of its glyphs as grey + alpha PNGs
//! (💬 and 🗨 among them), and Vello's glyph run asks png for RGBA with a transformation that adds alpha and leaves
//! grey as it is, logs "Unsupported `output_color_type`" and skips the glyph: its space was kept and nothing drawn
//! (#262). Those glyphs are taken out of the run and drawn here, as images placed the way Vello places a bitmap glyph.
use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::Arc;
use anyrender::Glyph;
use skrifa::bitmap::{BitmapData, BitmapFormat, Origin};
use skrifa::raw::TableProvider;
use skrifa::{GlyphId, MetadataProvider, instance::Size};
use vello::kurbo::{Affine, Vec2};
use vello::peniko::{Blob, FontData, ImageAlphaType, ImageData, ImageFormat};
thread_local! {
/// a font (its data's id and index) with bitmap strikes: its units per em, and whether it's Apple Color Emoji; None for a font with none
static FONTS: RefCell<HashMap<(u64, u32), Option<(f32, bool)>>> = RefCell::new(HashMap::new());
/// a glyph's picture once decoded (font, glyph, strike), so the same image is drawn each frame
static PICTURES: RefCell<HashMap<(u64, u32, u32, u32), Option<ImageData>>> = RefCell::new(HashMap::new());
}
/// A PNG's colour type Vello's glyph run draws: truecolour, with alpha or without (2 and 6); grey and palette ones it skips.
fn vello_draws(png: &[u8]) -> bool {
png.get(25).is_none_or(|t| matches!(t, 2 | 6))
}
/// A PNG as RGBA8, grey and palette ones expanded.
pub(crate) fn rgba(data: &[u8]) -> Option<(u32, u32, Vec<u8>)> {
let mut decoder = png::Decoder::new(std::io::Cursor::new(data));
decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16 | png::Transformations::ALPHA);
let mut reader = decoder.read_info().ok()?;
let mut buf = vec![0; reader.output_buffer_size()?];
let info = reader.next_frame(&mut buf).ok()?;
buf.truncate(info.buffer_size());
if info.color_type == png::ColorType::Indexed {
return None;
}
// each pixel's samples as four: grey (1 or 2 samples) spread over the three colours, and alpha the last sample
// of an even count, opaque otherwise
let n = info.color_type.samples();
let mut px = Vec::with_capacity(buf.len() / n * 4);
for p in buf.chunks_exact(n) {
let a = if n % 2 == 0 { p[n - 1] } else { 255 };
px.extend_from_slice(&if n < 3 { [p[0], p[0], p[0], a] } else { [p[0], p[1], p[2], a] });
}
(px.len() as u64 == u64::from(info.width) * u64::from(info.height) * 4).then_some((info.width, info.height, px))
}
/// The glyphs of a run Vello would skip, each as its picture and where it goes in the run's space, and the rest of the
/// run for Vello; None when the run has none (every font without bitmaps, nearly every emoji).
pub(crate) fn skipped(font: &FontData, font_size: f32, glyph_transform: Option<Affine>, glyphs: impl Iterator<Item = Glyph> + Clone) -> Option<(Vec<Glyph>, Vec<(ImageData, Affine)>)> {
let key = (font.data.id(), font.index);
let known = FONTS.with_borrow(|f| f.get(&key).copied());
if known == Some(None) {
return None;
}
let face = skrifa::FontRef::from_index(font.data.as_ref(), font.index).ok()?;
let strikes = face.bitmap_strikes();
let (upem, apple) = match known {
Some(Some(k)) => k,
_ => {
let k = strikes.format().and_then(|format| {
let upem = f32::from(face.head().ok()?.units_per_em());
let apple = format == BitmapFormat::Sbix && face.localized_strings(skrifa::string::StringId::POSTSCRIPT_NAME).any(|n| n.chars().eq("AppleColorEmoji".chars()));
Some((upem, apple))
});
FONTS.with(|f| f.borrow_mut().insert(key, k));
k?
}
};
let png_of = |g: &Glyph| match strikes.glyph_for_size(Size::new(font_size), GlyphId::new(g.id)) {
Some(b) => match b.data {
BitmapData::Png(d) if !vello_draws(d) => Some((b, d)),
_ => None,
},
None => None,
};
if !glyphs.clone().any(|g| png_of(&g).is_some()) {
return None;
}
let (mut rest, mut ours) = (Vec::new(), Vec::new());
for g in glyphs {
let Some((b, data)) = png_of(&g) else {
rest.push(g);
continue;
};
let pic = PICTURES.with(|p| {
p.borrow_mut()
.entry((key.0, key.1, g.id, b.ppem_y.to_bits()))
.or_insert_with(|| rgba(data).filter(|&(w, h, _)| w == b.width && h == b.height).map(|(width, height, px)| ImageData { data: Blob::new(Arc::new(px)), format: ImageFormat::Rgba8, alpha_type: ImageAlphaType::Alpha, width, height }))
.clone()
});
// one png can't read is left out, as Vello leaves it
let Some(pic) = pic else { continue };
// Vello's placement of a bitmap glyph (scene.rs, after Skia's): Apple Color Emoji an eighth of the size down
let outer = if apple { Vec2::new(0.0, f64::from(font_size) / 8.0) } else { Vec2::new(f64::from(b.bearing_x * font_size / upem), -f64::from(b.bearing_y * font_size / upem)) };
let mut at = Affine::translate((f64::from(g.x), f64::from(g.y))) * Affine::translate(outer) * Affine::scale(f64::from(font_size / b.ppem_y)) * Affine::translate((f64::from(b.inner_bearing_x), -f64::from(b.inner_bearing_y)));
if matches!(b.placement_origin, Origin::BottomLeft) {
at *= Affine::translate((0.0, -f64::from(pic.height)));
}
if let Some(t) = glyph_transform {
at *= t;
}
ours.push((pic, at));
}
Some((rest, ours))
}
#[cfg(test)]
mod tests {
use super::*;
/// a 2 x 1 PNG of colour type `kind`, 8 bits a channel, its rows given unfiltered
fn png_of(kind: png::ColorType, row: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
let mut e = png::Encoder::new(&mut out, 2, 1);
e.set_color(kind);
e.set_depth(png::BitDepth::Eight);
e.write_header().unwrap().write_image_data(row).unwrap();
out
}
#[test]
fn a_grey_png_is_the_one_vello_skips_and_reads_as_rgba() {
// #262: 💬 in Apple Color Emoji is grey + alpha
let grey = png_of(png::ColorType::GrayscaleAlpha, &[200, 255, 10, 128]);
assert!(!vello_draws(&grey));
assert_eq!(rgba(&grey), Some((2, 1, vec![200, 200, 200, 255, 10, 10, 10, 128])));
let colour = png_of(png::ColorType::Rgba, &[1, 2, 3, 4, 5, 6, 7, 8]);
assert!(vello_draws(&colour) && vello_draws(&png_of(png::ColorType::Rgb, &[1, 2, 3, 4, 5, 6])));
assert_eq!(rgba(&colour), Some((2, 1, vec![1, 2, 3, 4, 5, 6, 7, 8])));
assert_eq!(rgba(&png_of(png::ColorType::Grayscale, &[7, 9])), Some((2, 1, vec![7, 7, 7, 255, 9, 9, 9, 255])));
}
}
+1
View File
@@ -7,6 +7,7 @@
//! The passes work as Chrome's do: on premultiplied, sRGB-encoded values (no linearising), blur radii scaled by the
//! layer's transform; edges are transparent (CSS's `EdgeMode::None`).
mod emoji;
mod painter;
mod passes;
mod premul;
+8
View File
@@ -387,6 +387,14 @@ impl PaintScene for Painter<'_> {
self.hash.write_u32(g.y.to_bits());
}
let (scene, at) = self.top();
// the bitmap emoji Vello skips (grey PNGs: 💬, #262) drawn here, the rest of the run by Vello
if let Some((rest, ours)) = crate::emoji::skipped(font, font_size, glyph_transform, glyphs.clone()) {
VelloScenePainter::new(scene).draw_glyphs(font, font_size, hint, normalized_coords, embolden, style, brush, brush_alpha, at * transform, glyph_transform, rest.into_iter());
for (pic, place) in &ours {
scene.draw_image(pic, at * transform * *place);
}
return;
}
VelloScenePainter::new(scene).draw_glyphs(font, font_size, hint, normalized_coords, embolden, style, brush, brush_alpha, at * transform, glyph_transform, glyphs);
}
+2
View File
@@ -9,6 +9,8 @@ description = "raea's one mixer core: the same Firewheel graph plays live in the
[dependencies]
# the mix before the master: dialogue at one level, room tone at the joins
raea-sys-mix-level = { path = "level" }
# the system's output: the stream live play runs in, moved onto the device in use
raea-sys-mix-device = { path = "device" }
raea-io-trace = { path = "../../io/trace" }
# the bounce's scratch file, as the frames come (SG4a)
raea-io-home = { path = "../../io/home" }
+16
View File
@@ -0,0 +1,16 @@
[package]
name = "raea-sys-mix-device"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "raea's mixer on the system's output: Firewheel's processor driven from cpal's callback, and moved onto the device in use when the output changes or the stream breaks"
[dependencies]
raea-io-trace = { path = "../../../io/trace" }
# the mixer's graph, as raea-sys-mix pins it
firewheel = { version = "=0.12.1", default-features = false, features = ["std", "scheduled_events"] }
# the cpal react and the legacy app use (0.15): Firewheel's own CPAL backend needs 0.18, which can't link beside 0.15
cpal = "0.15"
# the processor's output, pulled into a stereo buffer
audioadapter-buffers = { version = "4.0.0", default-features = false, features = ["std"] }
+130
View File
@@ -0,0 +1,130 @@
//! The mixer's output: the system's default device, with Firewheel's processor pulled from cpal's callback, followed
//! when the system's output changes (headphones in, AirPods away, a display's speakers) or cpal says the stream broke
//! (11-26, Shane: "sometimes i dont hear any sound": the stream stayed on the device it opened on, gone or not the one
//! being listened to).
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use audioadapter_buffers::direct::InterleavedSlice;
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
pub use cpal::Stream;
use firewheel::backend::BackendProcessInfo;
use firewheel::node::StreamStatus;
use firewheel::{ActivateInfo, FirewheelContext};
/// The output a mixer plays on: the device's name (empty while there's none), the rate and block size it asks for,
/// and whether cpal said the stream broke.
pub struct Output {
pub name: String,
rate: u32,
block: u32,
lost: Arc<AtomicBool>,
looked: Instant,
}
impl Output {
/// The default device's stream, and the rate it runs at (`rate` when the device takes it).
pub fn open(cx: &mut FirewheelContext, rate: u32, block: u32) -> Result<(Output, Stream, u32), String> {
let lost = Arc::new(AtomicBool::new(false));
let (stream, got, name) = start(cx, rate, block, lost.clone())?;
Ok((Output { name, rate, block, lost, looked: Instant::now() }, stream, got))
}
/// Whether the stream should move: at once after cpal said it broke, else when the system's default output, looked
/// at once a second, is another device.
pub fn moved(&mut self) -> bool {
let lost = self.lost.load(Ordering::Relaxed);
if !lost && self.looked.elapsed() < Duration::from_secs(1) {
return false;
}
self.looked = Instant::now();
let now = cpal::default_host().default_output_device().and_then(|d| d.name().ok()).unwrap_or_default();
lost || (!now.is_empty() && now != self.name)
}
/// The stream started again on the default device: `old` is let go first, which hands the graph back (its
/// processor dropped). The new stream and its rate, or no device to play on (looked for again in a second).
pub fn reopen(&mut self, cx: &mut FirewheelContext, old: Option<Stream>) -> Result<(Stream, u32), String> {
drop(old);
let t0 = Instant::now();
while cx.is_active() && t0.elapsed() < Duration::from_millis(500) {
let _ = cx.update();
std::thread::sleep(Duration::from_millis(1));
}
self.lost.store(false, Ordering::Relaxed);
match start(cx, self.rate, self.block, self.lost.clone()) {
Ok((stream, rate, name)) => {
eprintln!("raea mixer: sound now on {name} (was {})", if self.name.is_empty() { "nothing" } else { &self.name });
self.name = name;
Ok((stream, rate))
}
Err(e) => {
if !self.name.is_empty() {
eprintln!("raea mixer: no sound: {e}");
}
self.name.clear();
Err(e)
}
}
}
}
/// The default output device, at `want` Hz when it takes it, `block` frames a callback when it takes that: Firewheel's
/// processor pulled from cpal's callback, as the bounce pulls it into a buffer (stereo, spread over the device's
/// channels).
fn start(cx: &mut FirewheelContext, want: u32, block: u32, lost: Arc<AtomicBool>) -> Result<(Stream, u32, String), String> {
let host = cpal::default_host();
let dev = host.default_output_device().ok_or("no audio output device")?;
let name = dev.name().unwrap_or_default();
let def = dev.default_output_config().map_err(|e| format!("audio output: {e}"))?;
let channels = def.channels();
let takes_48k = dev.supported_output_configs().map(|mut c| c.any(|r| r.channels() == channels && r.sample_format() == cpal::SampleFormat::F32 && r.min_sample_rate().0 <= want && r.max_sample_rate().0 >= want)).unwrap_or(false);
let rate = if takes_48k { want } else { def.sample_rate().0 };
let max_block = 8192usize;
let mut proc = cx
.activate(ActivateInfo { sample_rate: std::num::NonZeroU32::new(rate).unwrap(), max_block_frames: std::num::NonZeroU32::new(max_block as u32).unwrap(), num_stream_in_channels: 0, num_stream_out_channels: 2, input_to_output_latency_seconds: 0.0 })
.map_err(|e| format!("the mixer's graph: {e:?}"))?;
let ch = channels as usize;
let began = std::time::Instant::now();
let mut stereo = vec![0f32; max_block * 2];
let empty: [f32; 0] = [];
let mut callback = move |out: &mut [f32], info: &cpal::OutputCallbackInfo| {
let ts = info.timestamp();
let delay = ts.playback.duration_since(&ts.callback);
let frames = out.len() / ch.max(1);
let mut done = 0;
while done < frames {
let k = (frames - done).min(max_block);
let pi = BackendProcessInfo { frames: k, process_timestamp: Some(std::time::Instant::now()), duration_since_stream_start: began.elapsed(), input_stream_status: StreamStatus::empty(), output_stream_status: StreamStatus::empty(), dropped_frames: 0, process_to_playback_delay: delay };
if let (Ok(input), Ok(mut output)) = (InterleavedSlice::new(&empty[..], 0, 0), InterleavedSlice::new_mut(&mut stereo[..k * 2], 2, k)) {
proc.process(&input, &mut output, pi);
}
for i in 0..k {
let (l, r) = (stereo[2 * i], stereo[2 * i + 1]);
let o = &mut out[(done + i) * ch..(done + i + 1) * ch];
match ch {
1 => o[0] = 0.5 * (l + r),
_ => {
o[0] = l;
o[1] = r;
o[2..].fill(0.0);
}
}
}
done += k;
}
};
// the block size when the device's range takes it, else its own
let fits = dev.supported_output_configs().map(|mut c| c.any(|r| r.channels() == channels && matches!(r.buffer_size(), cpal::SupportedBufferSize::Range { min, max } if *min <= block && block <= *max))).unwrap_or(false);
let config = cpal::StreamConfig { channels, sample_rate: cpal::SampleRate(rate), buffer_size: if fits { cpal::BufferSize::Fixed(block) } else { cpal::BufferSize::Default } };
let mut said = raea_io_trace::once::said_once::<cpal::StreamError>("raea mixer");
let broke = move |e: cpal::StreamError| {
lost.store(true, Ordering::Relaxed);
said(e)
};
let stream = dev.build_output_stream(&config, move |o: &mut [f32], i: &cpal::OutputCallbackInfo| callback(o, i), broke, None).map_err(|e| format!("audio stream: {e}"))?;
stream.play().map_err(|e| format!("audio stream: {e}"))?;
Ok((stream, rate, name))
}
+22 -113
View File
@@ -7,16 +7,15 @@
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::atomic::Ordering;
use std::sync::mpsc::{Receiver, Sender, channel};
use std::sync::{Arc, Mutex};
use audioadapter_buffers::direct::InterleavedSlice;
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use firewheel::backend::BackendProcessInfo;
use cpal::traits::StreamTrait;
use firewheel::clock::{EventInstant, InstantSamples};
use firewheel::node::{NodeID, StreamStatus};
use firewheel::{ActivateInfo, FirewheelConfig, FirewheelContext};
use firewheel::node::NodeID;
use firewheel::{FirewheelConfig, FirewheelContext};
use raea_sys_mix_device::Output;
use crate::nodes::{Stats, event};
use raea_io_media::pcm::Pcm;
@@ -36,13 +35,8 @@ pub struct Live {
cx: FirewheelContext,
/// the device's stream: None for the moment it's reopened on another device (follow_device)
_stream: Option<cpal::Stream>,
/// the output it plays on (its name), the block size it was asked for, and whether cpal said the stream broke
/// (the device unplugged, its AirPods put away): the stage follows the system's output (11-26, Shane: "sometimes i
/// dont hear any sound": the stream stayed on the device it opened on, gone or not the one being listened to)
device: String,
block: u32,
lost: Arc<AtomicBool>,
looked: std::time::Instant,
/// the output it plays on, followed when the system's output changes (raea-sys-mix-device)
out: Output,
voices: NodeID,
master: NodeID,
score: Option<Score>,
@@ -93,8 +87,7 @@ impl Live {
let mut cx = FirewheelContext::new(FirewheelConfig::default());
let (voices, master) = crate::graph(&mut cx, stats.clone(), tap.as_ref().map(|t| t.1.clone()), mute)?;
let block = std::env::var("RAEA_AUDIO_BLOCK").ok().and_then(|v| v.parse().ok()).unwrap_or(256u32);
let lost = Arc::new(AtomicBool::new(false));
let (stream, rate, device) = start(&mut cx, block, lost.clone())?;
let (out, stream, rate) = Output::open(&mut cx, RATE, block)?;
if rate != RATE {
eprintln!("raea mixer: the device runs at {rate} Hz, not {RATE}: live play can't be the bounce sample for sample");
}
@@ -106,7 +99,7 @@ impl Live {
// a device opened beside the edit's open waits for nothing by then
Ok(Live {
opened: std::time::Instant::now(),
settled: false, cx, _stream: Some(stream), device, block, lost, looked: std::time::Instant::now(), voices, master, score: None, pcm: HashMap::new(), opening: HashMap::new(), loader: raea_io_media::pcm::loader(), rate, head, head_base: head, origin: None, drift_ms: Vec::new(), anchors: Vec::new(), slews: 0, load_ms: Vec::new(), load_wait: std::time::Duration::from_millis(std::env::var("RAEA_AUDIO_LOAD_WAIT_MS").ok().and_then(|v| v.parse().ok()).unwrap_or(80)), used: HashMap::new(), items: Vec::new(), keep: HashMap::new(), blocks: Vec::new(), master_set: (0.0, 20.0 * (crate::nodes::CEILING as f64).log10()), bypass: false, resting: false, built: Default::default(), stats, tap })
settled: false, cx, _stream: Some(stream), out, voices, master, score: None, pcm: HashMap::new(), opening: HashMap::new(), loader: raea_io_media::pcm::loader(), rate, head, head_base: head, origin: None, drift_ms: Vec::new(), anchors: Vec::new(), slews: 0, load_ms: Vec::new(), load_wait: std::time::Duration::from_millis(std::env::var("RAEA_AUDIO_LOAD_WAIT_MS").ok().and_then(|v| v.parse().ok()).unwrap_or(80)), used: HashMap::new(), items: Vec::new(), keep: HashMap::new(), blocks: Vec::new(), master_set: (0.0, 20.0 * (crate::nodes::CEILING as f64).log10()), bypass: false, resting: false, built: Default::default(), stats, tap })
}
/// The master: `gain_db` on the sum, then the limiter at `ceiling_db` (dBTP).
@@ -359,48 +352,22 @@ impl Live {
/// old one is let go, which hands the graph back (its processor dropped), and it starts again on the new device. The
/// timeline is placed again on the next frame, as after a rest.
fn follow_device(&mut self) {
let lost = self.lost.load(Ordering::Relaxed);
if !lost && self.looked.elapsed() < std::time::Duration::from_secs(1) {
if !self.out.moved() {
return;
}
self.looked = std::time::Instant::now();
let now = cpal::default_host().default_output_device().and_then(|d| d.name().ok()).unwrap_or_default();
if !lost && (now.is_empty() || now == self.device) {
return;
}
// the old stream and its callback go, and the processor in it: the context is free to start again
self._stream = None;
let t0 = std::time::Instant::now();
while self.cx.is_active() && t0.elapsed() < std::time::Duration::from_millis(500) {
let _ = self.cx.update();
std::thread::sleep(std::time::Duration::from_millis(1));
}
self.lost.store(false, Ordering::Relaxed);
match start(&mut self.cx, self.block, self.lost.clone()) {
Ok((stream, rate, device)) => {
eprintln!("raea mixer: sound now on {device} (was {})", if self.device.is_empty() { "nothing" } else { &self.device });
if rate != self.rate {
// the head and the score count samples: both at the new device's rate
self.head_base = (self.head_base as f64 * rate as f64 / self.rate as f64).round() as i64;
self.rate = rate;
self.score = None;
}
self._stream = Some(stream);
self.device = device;
self.resting = false;
self.origin = None;
self.settled = false;
self.opened = std::time::Instant::now();
let _ = self.cx.update();
}
// no device to play on (none plugged in): looked for again in a second
Err(e) => {
if !self.device.is_empty() {
eprintln!("raea mixer: no sound: {e}");
}
self.device.clear();
}
let Ok((stream, rate)) = self.out.reopen(&mut self.cx, self._stream.take()) else { return };
if rate != self.rate {
// the head and the score count samples: both at the new device's rate
self.head_base = (self.head_base as f64 * rate as f64 / self.rate as f64).round() as i64;
self.rate = rate;
self.score = None;
}
self._stream = Some(stream);
self.resting = false;
self.origin = None;
self.settled = false;
self.opened = std::time::Instant::now();
let _ = self.cx.update();
}
/// The device stream stopped (after stop_all and its fade-outs: nothing is heard): no callback runs, so neither the
@@ -465,64 +432,6 @@ impl Live {
}
}
/// The default output device, at 48 kHz when it takes it, `block` frames a callback when it takes that: Firewheel's
/// processor pulled from cpal's callback, as the bounce pulls it into a buffer (stereo, spread over the device's
/// channels).
fn start(cx: &mut FirewheelContext, block: u32, lost: Arc<AtomicBool>) -> Result<(cpal::Stream, u32, String), String> {
let host = cpal::default_host();
let dev = host.default_output_device().ok_or("no audio output device")?;
let name = dev.name().unwrap_or_default();
let def = dev.default_output_config().map_err(|e| format!("audio output: {e}"))?;
let channels = def.channels();
let takes_48k = dev.supported_output_configs().map(|mut c| c.any(|r| r.channels() == channels && r.sample_format() == cpal::SampleFormat::F32 && r.min_sample_rate().0 <= RATE && r.max_sample_rate().0 >= RATE)).unwrap_or(false);
let rate = if takes_48k { RATE } else { def.sample_rate().0 };
let max_block = 8192usize;
let mut proc = cx
.activate(ActivateInfo { sample_rate: std::num::NonZeroU32::new(rate).unwrap(), max_block_frames: std::num::NonZeroU32::new(max_block as u32).unwrap(), num_stream_in_channels: 0, num_stream_out_channels: 2, input_to_output_latency_seconds: 0.0 })
.map_err(|e| format!("the mixer's graph: {e:?}"))?;
let ch = channels as usize;
let began = std::time::Instant::now();
let mut stereo = vec![0f32; max_block * 2];
let empty: [f32; 0] = [];
let mut callback = move |out: &mut [f32], info: &cpal::OutputCallbackInfo| {
let ts = info.timestamp();
let delay = ts.playback.duration_since(&ts.callback);
let frames = out.len() / ch.max(1);
let mut done = 0;
while done < frames {
let k = (frames - done).min(max_block);
let pi = BackendProcessInfo { frames: k, process_timestamp: Some(std::time::Instant::now()), duration_since_stream_start: began.elapsed(), input_stream_status: StreamStatus::empty(), output_stream_status: StreamStatus::empty(), dropped_frames: 0, process_to_playback_delay: delay };
if let (Ok(input), Ok(mut output)) = (InterleavedSlice::new(&empty[..], 0, 0), InterleavedSlice::new_mut(&mut stereo[..k * 2], 2, k)) {
proc.process(&input, &mut output, pi);
}
for i in 0..k {
let (l, r) = (stereo[2 * i], stereo[2 * i + 1]);
let o = &mut out[(done + i) * ch..(done + i + 1) * ch];
match ch {
1 => o[0] = 0.5 * (l + r),
_ => {
o[0] = l;
o[1] = r;
o[2..].fill(0.0);
}
}
}
done += k;
}
};
// the block size when the device's range takes it, else its own
let fits = dev.supported_output_configs().map(|mut c| c.any(|r| r.channels() == channels && matches!(r.buffer_size(), cpal::SupportedBufferSize::Range { min, max } if *min <= block && block <= *max))).unwrap_or(false);
let config = cpal::StreamConfig { channels, sample_rate: cpal::SampleRate(rate), buffer_size: if fits { cpal::BufferSize::Fixed(block) } else { cpal::BufferSize::Default } };
let mut said = raea_io_trace::once::said_once::<cpal::StreamError>("raea mixer");
let broke = move |e: cpal::StreamError| {
lost.store(true, Ordering::Relaxed);
said(e)
};
let stream = dev.build_output_stream(&config, move |o: &mut [f32], i: &cpal::OutputCallbackInfo| callback(o, i), broke, None).map_err(|e| format!("audio stream: {e}"))?;
stream.play().map_err(|e| format!("audio stream: {e}"))?;
Ok((stream, rate, name))
}
impl Drop for Live {
fn drop(&mut self) {
let Some((path, buf)) = self.tap.take() else { return };
+3
View File
@@ -159,6 +159,9 @@ pub fn draw(mut scenes: ResMut<Scenes>, mut vello: ResMut<Vello>, device: Res<Re
}
// the image atlas (each filtered element is an image in it) as large as the device can make, not Vello's 8192
vello::low_level::vello_encoding::set_max_atlas_size(device.limits().max_texture_dimension_2d);
// and the blend spill, grown for a scene whose layers nest past four (raea #247), within what the device binds
let limits = device.limits();
vello::low_level::vello_encoding::set_max_buffer_size((limits.max_storage_buffer_binding_size as u64).min(limits.max_buffer_size));
// and an image larger than the atlas (16384 at most, whatever the device allows) decoded at a size that fits it
// (raea#245: an M5's GPU allows 32768, and a 1080x18000 picture was kept whole and refused)
blitz_dom::net::set_max_image_side(vello::low_level::vello_encoding::max_atlas_size());
+92
View File
@@ -0,0 +1,92 @@
//! Three of 0.1.11's layout misses, each laid out from its issue's own repro: `font-variant: small-caps` drew in normal
//! case (#249), a flex row whose items fit but for f32 rounding wrapped (#252), and a `display: table` element around
//! its text drew nothing at all (#254).
use bevy::math::UVec2;
use blitz_dom::BaseDocument;
use raea_sys_page::{Page, config};
fn laid_out(body: &str) -> BaseDocument {
let html = format!("<!doctype html><html><body style=\"margin:0\">{body}</body></html>");
let mut doc = blitz_html::HtmlDocument::from_html(&html, config(Page { size: UVec2::new(700, 400), scale: 1.0 })).into_inner();
doc.resolve(0.0);
doc
}
/// The border box of the element with `id`: x, y, width, height.
fn rect(doc: &BaseDocument, id: &str) -> (f64, f64, f64, f64) {
let node = doc.query_selector(&format!("#{id}")).unwrap().unwrap_or_else(|| panic!("no #{id}"));
let r = doc.get_client_bounding_rect(node).unwrap_or_else(|| panic!("#{id} has no box"));
(r.x, r.y, r.width, r.height)
}
/// #249: small capitals in a face without an `smcp` feature (Georgia) are synthesised as Chrome does: each lower-case
/// letter drawn as its capital at 70% of the font size. So the line is as wide as those capitals written out at 28 px,
/// and narrower than the text in full capitals.
#[test]
fn small_caps_are_synthesised_capitals_at_70_percent() {
let doc = laid_out(
r#"<div style="font-size: 40px; font-family: Georgia, serif">
<span id="caps" style="font-variant: small-caps">Compliance Audit</span><br>
<span id="spelled">C<span style="font-size: 28px">OMPLIANCE</span> A<span style="font-size: 28px">UDIT</span></span><br>
<span id="plain">Compliance Audit</span><br>
<span id="upper">COMPLIANCE AUDIT</span>
</div>"#,
);
let width = |id| rect(&doc, id).2;
let (caps, spelled, plain, upper) = (width("caps"), width("spelled"), width("plain"), width("upper"));
assert!((caps - spelled).abs() < 0.5, "small caps {caps} px wide, the capitals written out at 28 px {spelled}");
assert!(caps < upper - 20.0, "small caps {caps} px wide, full capitals {upper}");
assert!((caps - plain).abs() > 5.0, "small caps {caps} px wide, the text in normal case {plain}: drawn as it is");
}
/// #252: three 183.6 px items and two 54 px gaps add up to the 658.8 px container in exact arithmetic, a few ulps over
/// it in f32. Chrome lays out in 1/64 px units and keeps them on one line: rows of 3 and 2, not 2, 2 and 1.
#[test]
fn a_flex_row_that_fits_but_for_rounding_stays_one_row() {
let (w, size, cols) = (1080.0_f64, 0.17, 3.0);
let items: String = (0..5).map(|i| format!(r#"<div id="i{i}" style="width: {}px; height: 60px"></div>"#, size * w)).collect();
let doc = laid_out(&format!(
r#"<div style="display: flex; flex-wrap: wrap; justify-content: center; gap: {}px {}px; width: {}px">{items}</div>"#,
0.04 * w,
0.05 * w,
(cols * size + (cols - 1.0) * 0.05) * w
));
let y = |i: usize| rect(&doc, &format!("i{i}")).1;
assert_eq!((y(1), y(2)), (y(0), y(0)), "the first three items share a row");
assert!(y(3) > y(0) && y(4) == y(3), "the last two share the second row: {:?}", (0..5).map(y).collect::<Vec<_>>());
}
/// #254: a `display: table` element holding only text is laid out as Chrome lays it out, its text in an anonymous row
/// and cell: a block as wide as its text (shrink-to-fit), with the next block below it.
#[test]
fn a_table_around_its_text_is_as_wide_as_its_text() {
let doc = laid_out(
r#"<div style="font-size: 30px">
<div id="table" style="display: table; background: #FFD43B">Line one as a table</div>
<div id="next">Line two, block</div>
<span id="text">Line one as a table</span>
</div>"#,
);
let (tx, ty, tw, th) = rect(&doc, "table");
let text = rect(&doc, "text");
let next = rect(&doc, "next");
assert!(th > 30.0, "the table is a line tall: {th}");
assert!((tw - text.2).abs() < 0.5, "the table is {tw} px wide, its text {}", text.2);
assert_eq!((tx, ty), (0.0, 0.0));
assert!((next.1 - (ty + th)).abs() < 0.5, "the next block starts below the table: {} against {}", next.1, ty + th);
}
/// #254, the rest of css-tables-3's wrapping: a table's stray text beside a row of its own gets an anonymous row of its
/// own above it, and a table of rows alone builds no anonymous box (its cells as before).
#[test]
fn stray_text_beside_a_row_gets_a_row_of_its_own() {
let doc = laid_out(
r#"<div id="t" style="display: table; font-size: 20px">loose
<div style="display: table-row"><div id="cell" style="display: table-cell">in a cell</div></div></div>
<table id="plain"><tr><td id="td">a</td></tr></table>"#,
);
let cell = rect(&doc, "cell");
assert!(cell.1 >= 20.0, "the cell is in the second row, below the loose text: {cell:?}");
let td = rect(&doc, "td");
assert!(td.2 > 0.0 && td.3 > 0.0, "a plain table's cell keeps its box: {td:?}");
}
+124
View File
@@ -0,0 +1,124 @@
//! 0.1.11's paint reports, each the issue's own repro as HTML, painted by blitz-paint into a recording scene and read
//! back: what is filled, in what colour or brush, and under which clips (no GPU, so every runner checks them).
use anyrender::recording::RenderCommand;
use anyrender::{Paint, Scene};
use bevy::math::UVec2;
use vello::kurbo::{Point, Rect, Shape};
use raea_sys_page::{Page, config};
fn painted(html: &str, w: u32, h: u32) -> Scene {
let mut doc = blitz_html::HtmlDocument::from_html(html, config(Page { size: UVec2::new(w, h), scale: 1.0 })).into_inner();
doc.resolve(0.0);
let mut scene = Scene::new();
blitz_paint::paint_scene(&mut scene, &mut doc, 1.0, w, h, 0, 0);
scene
}
/// Each fill: its brush, its box on the page, and the boxes of the layers it's clipped by.
fn fills(scene: &Scene) -> Vec<(Paint, Rect, Vec<Rect>)> {
let (mut clips, mut out) = (Vec::new(), Vec::new());
for c in &scene.commands {
match c {
RenderCommand::PushLayer(l) => clips.push(l.transform.transform_rect_bbox(l.clip.bounding_box())),
RenderCommand::PushClipLayer(l) => clips.push(l.transform.transform_rect_bbox(l.clip.bounding_box())),
RenderCommand::PopLayer => drop(clips.pop()),
RenderCommand::Fill(f) => out.push((f.brush.clone(), f.transform.transform_rect_bbox(f.shape.bounding_box()), clips.clone())),
_ => {}
}
}
out
}
fn rgb(p: &Paint) -> Option<[u8; 3]> {
match p {
Paint::Solid(c) => {
let c = c.to_rgba8();
(c.a > 0).then_some([c.r, c.g, c.b])
}
_ => None,
}
}
/// What of `color` is drawn: the fills in it, each cut by its clips (None when a clip leaves none of it).
fn drawn(scene: &Scene, color: [u8; 3]) -> Vec<Rect> {
fills(scene)
.into_iter()
.filter(|(p, ..)| rgb(p) == Some(color))
.filter_map(|(_, r, clips)| {
let cut = clips.iter().fold(r, |a, c| a.intersect(*c));
(cut.width() > 0.0 && cut.height() > 0.0).then_some(cut)
})
.collect()
}
/// raea #250: `clip-path: inset(0 0 0 100%)` clips the element away (it drew whole); 99% leaves a sliver
#[test]
fn a_clip_path_inset_that_clips_everything_draws_nothing() {
let page = |inset: &str| {
format!(
r#"<body style="margin:0;background:#fff"><div style="padding:40px"><div style="position:relative;width:400px;height:300px;background:#0f0">
<div style="position:absolute;inset:0;background:#f00;clip-path:inset({inset})"></div></div></div></body>"#
)
};
for inset in ["0 0 0 100%", "100% 0 0 0", "0 60% 0 50%", "0 0 0 120%"] {
let s = painted(&page(inset), 700, 400);
assert_eq!(drawn(&s, [255, 0, 0]), vec![], "inset({inset}) drew red");
assert_eq!(drawn(&s, [0, 255, 0]).len(), 1, "inset({inset}) lost the green box");
}
let sliver = drawn(&painted(&page("0 0 0 99%"), 700, 400), [255, 0, 0]);
assert_eq!(sliver.len(), 1);
assert!((sliver[0].width() - 4.0).abs() < 0.01 && (sliver[0].height() - 300.0).abs() < 0.01, "{sliver:?}");
}
/// raea #251: an <svg> with `overflow: visible` draws past its viewport (a 1x1 svg drew nothing); without it, the
/// UA sheet still clips it to its box, as Chrome does
#[test]
fn an_svg_with_overflow_visible_draws_past_its_viewport() {
let page = |overflow: &str| {
format!(
r##"<body style="margin:0;background:#fff"><svg xmlns="http://www.w3.org/2000/svg" style="position:absolute;left:0;top:0;{overflow}" width="1" height="1">
<circle cx="200" cy="200" r="80" fill="#ff6600"/><polygon points="0,-40 32,24 -28,20" transform="translate(400 200) rotate(30)" fill="#3366ff"/></svg></body>"##
)
};
let s = painted(&page("overflow:visible"), 700, 400);
let circle = drawn(&s, [255, 102, 0]);
assert_eq!(circle.len(), 1, "the circle: {circle:?}");
assert!(circle[0].contains(Point::new(200.0, 200.0)) && circle[0].width() > 150.0, "{circle:?}");
let triangle = drawn(&s, [51, 102, 255]);
assert!(triangle.len() == 1 && triangle[0].contains(Point::new(400.0, 200.0)), "the triangle: {triangle:?}");
// the UA's clip, and an author's overflow: hidden, keep it in its 1x1 box
for overflow in ["", "overflow:hidden"] {
let s = painted(&page(overflow), 700, 400);
assert_eq!(drawn(&s, [255, 102, 0]), vec![], "{overflow:?} drew the circle past the box");
}
}
/// raea #248: a background-image on an inline element is drawn on each of its line fragments (it drew nothing, its
/// background-color did), laid out across the fragments side by side, so `background-size: 10% 100%` covers part of the
/// first line's fragment and nothing of the others'
#[test]
fn an_inline_elements_background_image_fills_its_line_fragments() {
let page = |size: &str| {
format!(
r#"<body style="margin:0;background:#fff"><div style="padding:40px;font-size:40px;line-height:50px"><div style="width:300px">Before <span id="m" style="background-image:linear-gradient(#FFD43B, #FFD43B);background-repeat:no-repeat;background-size:{size}">this marked phrase wraps over lines</span> after.</div></div></body>"#
)
};
let gradients = |s: &Scene| -> Vec<Rect> {
fills(s)
.into_iter()
.filter(|(p, ..)| matches!(p, Paint::Gradient(_)))
.filter_map(|(_, r, clips)| {
let cut = clips.iter().fold(r, |a, c| a.intersect(*c));
(cut.width() > 1.0 && cut.height() > 1.0).then_some(cut)
})
.collect()
};
let full = gradients(&painted(&page("100% 100%"), 700, 400));
assert!(full.len() >= 2, "a fill on each line's fragment: {full:?}");
let mut tops: Vec<i64> = full.iter().map(|r| r.y0.round() as i64).collect();
tops.dedup();
assert!(tops.len() >= 2, "on more than one line: {full:?}");
// 10% of the fragments side by side: on the first line alone
let half = gradients(&painted(&page("10% 100%"), 700, 400));
assert!(!half.is_empty() && half.iter().all(|r| r.y0 < full.iter().map(|f| f.y0).fold(f64::MAX, f64::min) + 1.0), "{half:?} vs {full:?}");
}
+47
View File
@@ -68,6 +68,29 @@ pub fn tag_row_view(t: Res<TagRowTarget>, images: Res<Assets<Image>>, view_box:
}
}
/// A camera with a sub view culls by that view. Bevy's update_frusta takes the projection's whole view at the target's
/// shape, so with a box wider than the frame (1080 x 389 in a 1080 x 600 frame, the same field of view up and down) a
/// mesh inside the box's view and outside the frame's was culled and never drawn: a curved shelf's side cards, where
/// the same cards turned the other way reached into the frame's view and drew (#261). After Bevy's own frusta, before
/// visibility is checked; a camera whose sub view went gets Bevy's frustum back.
pub fn sub_view_frusta(mut ours: Local<bevy::platform::collections::HashSet<Entity>>, mut q: Query<(Entity, &Camera, &GlobalTransform, &Projection, &mut bevy::camera::primitives::Frustum)>) {
for (e, c, at, p, mut f) in &mut q {
let next = match c.sub_camera_view.as_ref() {
Some(v) => {
ours.insert(e);
let clip_from_world = p.get_clip_from_view_for_sub(v) * at.affine().inverse();
bevy::camera::primitives::Frustum(bevy::shape::ViewFrustum::from_clip_from_world_custom_far(&clip_from_world, &at.translation(), &at.back(), p.far()))
}
None if ours.remove(&e) => p.compute_frustum(at),
None => continue,
};
// written only when it moves, so the frustum reads as changed when it is
if (0..6).any(|i| next.half_spaces[i].normal() != f.half_spaces[i].normal() || next.half_spaces[i].d() != f.half_spaces[i].d()) {
*f = next;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -126,6 +149,30 @@ mod tests {
assert!(app.world().get::<Camera>(cam).unwrap().sub_camera_view.is_none());
}
#[test]
fn a_wide_box_culls_by_its_own_view() {
use bevy::camera::primitives::{Frustum, Sphere};
// #261's shapes on this 600 x 600 target: fov 30 up and down, the frame 1.8 wide to 1 high and a box 600 x 216
// (1080 x 389's shape); a point 1.7 to the side, 3 ahead, is outside the frame's view (half of it is 1.45
// wide there) and inside the box's (2.23)
let (mut app, cam, _) = app();
app.add_systems(Update, sub_view_frusta.after(tag_row_view));
let p = PerspectiveProjection { fov: 30f32.to_radians(), aspect_ratio: 1080.0 / 600.0, ..default() };
let whole = Projection::Perspective(p.clone()).compute_frustum(&GlobalTransform::IDENTITY);
app.world_mut().entity_mut(cam).insert((Projection::Perspective(p), GlobalTransform::IDENTITY, whole));
let card = Sphere { center: bevy::math::Vec3A::new(1.7, 0.0, -3.0), radius: 0.05 };
let seen = |app: &App| app.world().get::<Frustum>(cam).unwrap().intersects_sphere(&card, true);
app.update();
assert!(!seen(&app), "outside the frame's view");
app.world_mut().resource_mut::<ViewBox>().0 = Some([0, 100, 600, 216]);
app.update();
assert!(seen(&app), "inside the box's view");
// the box goes: Bevy's frustum again
app.world_mut().resource_mut::<ViewBox>().0 = None;
app.update();
assert!(!seen(&app));
}
#[test]
fn a_cameras_own_viewport_is_left_as_it_is() {
let (mut app, _, h) = app();
+5
View File
@@ -55,6 +55,7 @@ raea-core-ask = "core"
raea-sys-k = "systems"
raea-sys-mix = "systems"
raea-sys-mix-level = "systems"
raea-sys-mix-device = "systems"
raea-sys-tone = "systems"
raea-seedling = "systems"
raea-sys-ml = "systems"
@@ -168,6 +169,7 @@ raea-runtime-twins = "runtime"
raea-runtime-dom = "runtime"
raea-runtime-dom-media = "runtime"
raea-runtime-edit = "runtime"
raea-runtime-goal-plan = "runtime"
raea-runtime-input = "runtime"
raea-runtime-bake = "runtime"
raea-runtime-bundle = "runtime"
@@ -229,6 +231,7 @@ raea-app-game = "apps"
raea-app-capcut = "apps"
raea-app-layers = "apps"
raea-app-play = "apps"
raea-app-playable = "apps"
raea-page-host = "runtime"
raea-rune-host = "runtime"
raea-rune-page = "runtime"
@@ -294,6 +297,8 @@ raea-sys-rt = true
raea-sys-mix = true
# the mix before the master: dialogue at one level, room tone at the joins (the mix masters what it gives)
raea-sys-mix-level = true
# the mixer's output: the device stream live play runs in, followed when the system's output changes
raea-sys-mix-device = true
raea-sys-tone = true
raea-sys-ml = true
raea-sys-mlx = true
+1 -1
View File
@@ -25,7 +25,7 @@ const verbs: Verb[] = JSON.parse(run(["help", "--json"])).verbs
// the index's groups, in the order a reader meets them; every verb is in one
const GROUPS: [string, string, string[]][] = [
["Make", "Render, play and package what you wrote.", ["render", "play", "export-game", "export", "bundle", "app", "run"]],
["Make", "Render, play and package what you wrote.", ["render", "play", "export-game", "playable", "export", "bundle", "app", "run"]],
["Projects", "The workspace, its projects and what a project holds.", ["init", "workspace", "project", "spec", "component", "part", "add", "brand", "library", "index"]],
["Check", "What's wrong before anyone watches it.", ["check", "judge", "make", "fingerprint", "findings", "scene", "light", "bench", "world", "solid", "next", "doctor", "hook", "traces"]],
["Footage", "Takes, cuts and the camera, from your own media.", ["media", "cut", "frame", "track", "splat", "mezz", "neural"]],
+5 -2
View File
@@ -18,9 +18,12 @@ die() { echo "promoted-from: $*" >&2; exit 1; }
# tests include tools/release.sh and an sdk/guides page, and tests aren't in a release build). The skills (skills/, the
# raea-skills pin) and docs/ are read by no build either (11-11, Shane: "promote skills to the latest possible"):
# release.sh packs the skills the release's commit pins, and the skills gate (its skills-passed line) and check-cli
# hold them to the candidate's binaries, so newer skills go out on a candidate's binaries
# hold them to the candidate's binaries, so newer skills go out on a candidate's binaries. The layers gate's files
# (tools/layers.sh and its layers.toml) are read by CI's check of the crate graph only (11-26: 0.1.11-rc2's commit failed
# CI on a crate with no layer, and the one-line fix would have forced a rebuild)
SAME=(':(exclude)README.md' ':(exclude).github' ':(exclude)tools/release.sh' ':(exclude)tools/release-check.sh' ':(exclude)tools/release-appimage.sh'
':(exclude)tools/release' ':(exclude)tools/agents' ':(exclude)tools/raea-app' ':(exclude)skills' ':(exclude)docs')
':(exclude)tools/release' ':(exclude)tools/agents' ':(exclude)tools/raea-app' ':(exclude)skills' ':(exclude)docs'
':(exclude)tools/layers.sh' ':(exclude)tools/layers.toml' ':(exclude)tools/layers.allow')
fetch_tag() { git cat-file -e "refs/tags/$1" 2>/dev/null || git fetch -q --depth=1 origin "refs/tags/$1:refs/tags/$1"; }
differ() { git diff --name-only "$1^{commit}" "$2^{commit}" -- . "${SAME[@]}"; }
+6
View File
@@ -11,6 +11,12 @@
svg|*:not(svg|svg), svg|*:not(svg|foreignObject) > svg|svg {
transform-origin: 0 0;
}
/* raea: Chrome's svg.css clips an inner <svg> to its viewport (`svg:not(:root) { overflow: hidden }`), which
* `overflow: visible` lifts (raea #251). `clip` rather than `hidden`, so an svg is no scroll container and lays out
* as it did (a flex item keeps its automatic minimum size); blitz-paint's draw_svg reads it */
svg|svg:not(:root) {
overflow: clip;
}
@font-face {
font-family: -moz-bullet-font;
+2 -1
View File
@@ -13,7 +13,8 @@ use style::{
};
/// Query fontique for the fonts matching `font_styles` (family list and attributes).
fn query_for_font_styles<'a>(
/// raea: small_caps.rs asks it for the face it checks for `smcp` (#249)
pub(crate) fn query_for_font_styles<'a>(
font_ctx: &'a mut FontContext,
font_styles: &'a FontStyles,
) -> parley::fontique::Query<'a> {
+60 -2
View File
@@ -573,7 +573,9 @@ fn collect_layout_children_with_wrap(
}
DisplayInside::Table => {
let (table_context, tlayout_children) = build_table_context(doc, container_node_id);
let wrapped = wrap_table_strays(doc, container_node_id, out);
let (table_context, tlayout_children) =
build_table_context(doc, container_node_id, wrapped);
#[allow(clippy::arc_with_non_send_sync)]
let data = SpecialElementData::TableRoot(Arc::new(table_context));
doc.nodes[container_node_id]
@@ -802,6 +804,49 @@ fn flush_pseudo_elements(doc: &mut BaseDocument, node_id: NodeId) {
}
}
/// raea: a table's children with each run of children that are no table box (text, a block or inline element, a
/// table inside it) wrapped in an anonymous block, which table.rs lays out as an anonymous row holding one anonymous
/// cell (css-tables-3 § 3.3, as Chrome does). Blitz dropped them, so a `display: table` element around its text (a
/// shrink-wrapped line) drew nothing, not even its background (#254). None when there is no such run (no text but
/// whitespace), so a table of rows builds no anonymous block. The blocks are `out`'s to free on reconstruction.
fn wrap_table_strays(
doc: &mut BaseDocument,
table_id: NodeId,
out: &mut LayoutChildren,
) -> Option<Vec<NodeId>> {
fn is_stray(node: &Node) -> bool {
match node.data.kind() {
NodeKind::Text => true,
NodeKind::Element => node.primary_styles().is_some_and(|style| {
let display = style.clone_display();
matches!(display.outside(), DisplayOutside::Block | DisplayOutside::Inline)
&& display.inside() != DisplayInside::Contents
&& !style.clone_position().is_absolutely_positioned()
}),
_ => false,
}
}
let children = doc.nodes[table_id].children.clone();
let any = children.iter().any(|&id| {
let node = &doc.nodes[id];
is_stray(node) && !node.is_whitespace_node()
});
if !any {
return None;
}
let mut runs = LayoutChildren::default();
for id in children {
match doc.nodes[id].data.kind() {
NodeKind::Comment => {}
_ if is_stray(&doc.nodes[id]) => runs.push_wrapped(table_id, id, doc),
_ => runs.push(id, doc),
}
}
runs.maybe_push_anon_block(doc);
out.anonymous_blocks.extend(runs.anonymous_blocks.iter().copied());
Some(runs.children.into_iter().collect())
}
/// Handles the cases where there are text nodes or inline nodes that need to be wrapped in an anonymous block node
fn collect_complex_layout_children(
doc: &mut BaseDocument,
@@ -1085,6 +1130,10 @@ pub(crate) fn build_inline_layout_into(
..Default::default()
});
// raea: which of its elements' text gets synthesised small capitals, asked of the fonts before the builder holds
// them (#249)
let small_caps = super::small_caps::synthesized(nodes, inline_context_root_node_id, font_ctx);
// Create a parley tree builder
let mut builder = layout_ctx.tree_builder(font_ctx, scale, true, &parley_style);
if let Some(style) = root_node_style.as_deref() {
@@ -1124,6 +1173,7 @@ pub(crate) fn build_inline_layout_into(
};
// The marker is a separate box, so words in the content don't continue from it.
let mut text_transformer = TextTransformer::default();
text_transformer.small_caps = small_caps;
text_transformer.word_break(&builder);
// raea: the root's bidi override around its content (stylo_to_parley::bidi_controls)
@@ -1395,10 +1445,18 @@ pub(crate) fn build_inline_layout_into(
s.clone_white_space_collapse() != stylo_to_parley::stylo::WhiteSpaceCollapse::Collapse
});
let bidi = if keeps_newlines { std::mem::take(&mut text_transformer.bidi) } else { Vec::new() };
// raea: the font size its synthesised small capitals scale, when they're its parent's (#249)
let small_caps = node
.parent
.filter(|p| text_transformer.small_caps.contains(p))
.and_then(|p| nodes[p].primary_styles().map(|s| s.get_font().font_size.used_size.0.px()));
let text =
text_transformer.transform(&data.content, parent_text_transform, builder);
let start = builder.text().len();
builder.push_text(&bidi_newlines(text, &bidi));
match small_caps {
Some(font_size) => super::small_caps::push(builder, &bidi_newlines(text, &bidi), font_size),
None => builder.push_text(&bidi_newlines(text, &bidi)),
}
text_transformer.texts.push((node_id, start, builder.text().len()));
if keeps_newlines {
text_transformer.bidi = bidi;
+2
View File
@@ -28,6 +28,8 @@ pub(crate) mod inline;
pub(crate) mod list;
pub(crate) mod paint_tree;
pub(crate) mod replaced;
// raea: synthesised small capitals (#249)
pub(crate) mod small_caps;
pub(crate) mod table;
pub(crate) mod text_transform;
#[cfg(feature = "writing-mode")]
+143
View File
@@ -0,0 +1,143 @@
//! raea: `font-variant: small-caps` as Chrome draws it (#249). A face with an `smcp` feature gets it
//! (stylo_to_parley::font_variant_caps); for a face without one (Georgia, Times, Helvetica: most system faces) Chrome
//! synthesises the small capitals, each lower-case letter drawn as its capital at 70% of the font size (Blink's
//! kSmallCapsFontSizeMultiplier). Blitz only asked for the feature, so such text drew in normal case, with no warning.
use std::cell::RefCell;
use std::collections::HashMap;
use blitz_traits::node_id::NodeId;
use parley::fontique::{QueryFont, QueryStatus};
use parley::{FontContext, StyleProperty, TreeBuilder};
use skrifa::MetadataProvider as _;
use skrifa::raw::TableProvider as _;
use style::properties::style_structs::Font as FontStyles;
use crate::font_metrics::query_for_font_styles;
use crate::node::TextBrush;
use crate::stylo_to_parley::stylo::FontVariantCaps;
/// The size of a synthesised small capital, as a fraction of the font size (Blink's)
pub(crate) const SCALE: f32 = 0.7;
thread_local! {
/// whether a face (its blob's id and index in it) has an `smcp` feature, read once
static SMCP: RefCell<HashMap<(u64, u32), bool>> = RefCell::new(HashMap::new());
}
/// The elements whose text under `root` (an inline layout's root) is drawn in synthesised small capitals: each text
/// node's parent (its DOM parent, which an anonymous block wrapping the text isn't) whose font-variant-caps is
/// small-caps, in a face whose lower-case letters have no `smcp` feature.
pub(crate) fn synthesized(nodes: &crate::NodeTree, root: NodeId, fcx: &mut FontContext) -> Vec<NodeId> {
let mut out = Vec::new();
let mut stack = vec![root];
while let Some(id) = stack.pop() {
let node = &nodes[id];
if node.is_text_node() {
let Some(parent) = node.parent.filter(|p| !out.contains(p)) else { continue };
let Some(style) = nodes[parent].primary_styles() else { continue };
let font = style.get_font();
if font.font_variant_caps == FontVariantCaps::SmallCaps && !has_smcp(fcx, font) {
out.push(parent);
}
continue;
}
stack.extend(node.children.iter().copied());
stack.extend(node.before());
stack.extend(node.after());
}
out
}
/// Whether the face `font` draws a lower-case `a` in has an `smcp` feature (true when no face has the letter: then
/// there is nothing to synthesise).
fn has_smcp(fcx: &mut FontContext, font: &FontStyles) -> bool {
let mut query = query_for_font_styles(fcx, font);
let mut face = None;
query.matches_with(|q: &QueryFont| {
let maps = skrifa::FontRef::from_index(q.blob.as_ref(), q.index).is_ok_and(|f| f.charmap().map('a').is_some());
if !maps {
return QueryStatus::Continue;
}
face = Some((q.blob.clone(), q.index));
QueryStatus::Stop
});
let Some((blob, index)) = face else { return true };
SMCP.with(|seen| *seen.borrow_mut().entry((blob.id(), index)).or_insert_with(|| has_feature(blob.as_ref(), index, b"smcp")))
}
/// Whether the face at `index` in `data` lists the GSUB feature `tag`.
pub(crate) fn has_feature(data: &[u8], index: u32, tag: &[u8; 4]) -> bool {
let tag = skrifa::Tag::new(tag);
let Ok(font) = skrifa::FontRef::from_index(data, index) else { return false };
let Ok(list) = font.gsub().and_then(|gsub| gsub.feature_list()) else { return false };
list.feature_records().iter().any(|record| record.feature_tag() == tag)
}
/// A lower-case letter a synthesised small capital replaces: one with a capital of its own.
fn is_small(c: char) -> bool {
c.is_lowercase() && !c.to_uppercase().eq(std::iter::once(c))
}
/// `text` pushed with each run of lower-case letters as their capitals at SCALE of `font_size` (px), the rest as it is.
pub(crate) fn push(builder: &mut TreeBuilder<TextBrush>, text: &str, font_size: f32) {
let mut rest = text;
while let Some(first) = rest.chars().next() {
let small = is_small(first);
let end = rest.char_indices().find(|&(_, c)| is_small(c) != small).map_or(rest.len(), |(i, _)| i);
let (run, tail) = rest.split_at(end);
if small {
builder.push_style_modification_span(&[StyleProperty::FontSize(font_size * SCALE)]);
builder.push_text(&run.to_uppercase());
builder.pop_style_span();
} else {
builder.push_text(run);
}
rest = tail;
}
}
#[cfg(test)]
mod tests {
use super::*;
use parley::{LayoutContext, TextStyle};
/// Each glyph run's text and font size, for `text` pushed as small capitals at 40 px.
fn runs(text: &str) -> Vec<(String, f32)> {
let mut font_ctx = FontContext::new();
let mut layout_ctx: LayoutContext<TextBrush> = LayoutContext::new();
let style = TextStyle { font_size: 40.0, ..TextStyle::default() };
let mut builder = layout_ctx.tree_builder(&mut font_ctx, 1.0, true, &style);
push(&mut builder, text, 40.0);
let mut layout = parley::Layout::new();
let built = builder.build_into(&mut layout);
layout.break_all_lines(None);
let mut out = Vec::new();
for line in layout.lines() {
for item in line.items() {
if let parley::PositionedLayoutItem::GlyphRun(run) = item {
out.push((built[run.run().text_range()].to_string(), run.run().font_size()));
}
}
}
out
}
#[test]
fn lower_case_letters_are_capitals_at_70_percent() {
let want = [("C", 40.0), ("OMPLIANCE", 28.0), (" A", 40.0), ("UDIT", 28.0)];
let want: Vec<(String, f32)> = want.iter().map(|(t, s)| (t.to_string(), *s)).collect();
assert_eq!(runs("Compliance Audit"), want);
}
#[test]
fn capitals_digits_and_spaces_keep_their_size() {
assert_eq!(runs("A1 B"), vec![("A1 B".to_string(), 40.0)]);
}
#[test]
fn a_letter_without_a_capital_of_its_own_keeps_its_size() {
// U+0138 kra is lower-case and has no capital
assert!(!is_small('ĸ') && is_small('a') && !is_small('A') && !is_small('1'));
}
}
+19 -4
View File
@@ -208,9 +208,12 @@ fn percent_plus_length(
dim.into()
}
/// raea: `wrapped` is the table's children with each run of children that are no table box (its text, a block or
/// an inline element) in an anonymous block (construct.rs `wrap_table_strays`, #254); None when it has no such run
pub(crate) fn build_table_context(
doc: &mut BaseDocument,
table_root_node_id: NodeId,
wrapped: Option<Vec<NodeId>>,
) -> (TableContext, Vec<NodeId>) {
let mut cells: Vec<TableCell> = Vec::new();
let mut oof_children: Vec<(NodeId, taffy::Position)> = Vec::new();
@@ -221,7 +224,8 @@ pub(crate) fn build_table_context(
let wm = table_wm(doc, table_root_node_id);
let root_node = &mut doc.nodes[table_root_node_id];
let children = std::mem::take(&mut root_node.children);
let dom_children = std::mem::take(&mut root_node.children);
let children = wrapped.unwrap_or_else(|| dom_children.to_vec());
let Some(stylo_styles) = root_node.primary_styles() else {
panic!("Ignoring table because it has no styles");
@@ -469,7 +473,7 @@ pub(crate) fn build_table_context(
.chain(oof_children.iter().map(|(node_id, _)| *node_id))
.collect();
let root_node = &mut doc.nodes[table_root_node_id];
root_node.children = children;
root_node.children = dom_children;
(
TableContext {
@@ -582,7 +586,9 @@ fn collect_table_cells(
) {
let node = &mut doc.nodes[node_id];
if !node.is_element() {
// raea: an anonymous block here is one construct.rs wrapped a run of the table's stray children in (#254)
let anonymous = node.is_anonymous();
if !node.is_element() && !anonymous {
return;
}
@@ -605,7 +611,16 @@ fn collect_table_cells(
return;
}
match display.inside() {
// raea: it is an anonymous row holding one anonymous cell, as css-tables-3 § 3.3 wraps such a run (#254)
let inside = if anonymous {
*row += 1;
cursor.start_row();
rows.push(TableRow { node_id, group: None, height: None, is_constrained: false });
DisplayInside::TableCell
} else {
display.inside()
};
match inside {
DisplayInside::TableRowGroup
| DisplayInside::TableHeaderGroup
| DisplayInside::TableFooterGroup
Loaded 100 of 164 files, more files were not shown because too many files have changed in this diff. Show more